text:
import pandas as pd
import networkx as nx
import json

def read_graph(input_path):
    """
    The function reads the graph from input path.
    :param input_path: Graph read into memory.
    :return G: Networkx graph.
    """
    edges = pd.read_csv(input_path)
    edge_list=edges.values.tolist()

    """
    remove self loops
    """
    for e in edge_list:
        if len(set(e))==len(e):
            continue
        else:
            edge_list.remove(e)

    G = nx.from_edgelist(edge_list)
    return G

def json_read(path):
    """
    Function to read json file of seed and activation sequences.

    :param path: Path for dumping the JSON.
    """
    with open(path, 'r') as myfile:
          data=myfile.read()
    obj = json.loads(data)
    return obj

def json_dumper(data, path):
    """
    Function to save a JSON to disk.
    :param data: Dictionary of seed set and corresponding activations.
    :param path: Path for dumping the JSON.
    """
    with open(path, 'a') as outfile:
        json.dump(data, outfile)
        outfile.write(',')
        outfile.write('\n')

reason: import networkx


text:
# -*- coding: utf-8 -*-
"""
    utils
    ~~~~~
    `utils` module of the `mrtool` package.
"""
from typing import Union, List, Any, Tuple
import numpy as np
import pandas as pd
try:
    from cdd import Matrix, RepType, Polyhedron
except:
    Warning("no cdd module installed, create fake classes.")
    class Matrix:
        pass
    class RepType:
        INEQUALITY = None
    class Polyhedron:
        def get_generators(self):
            pass

def get_cols(df, cols):
    """Return the columns of the given data frame.
    Args:
        df (pandas.DataFrame):
            Given data frame.
        cols (str | list{str} | None):
            Given column name(s), if is `None`, will return a empty data frame.
    Returns:
        pandas.DataFrame | pandas.Series:
            The data frame contains the columns.
    """
    assert isinstance(df, pd.DataFrame)
    if isinstance(cols, list):
        assert all([isinstance(col, str) and col in df
                    for col in cols])
    else:
        assert (cols is None) or (isinstance(cols, str) and cols in df)

    if cols is None:
        return df[[]]
    else:
        return df[cols]

def is_cols(cols):
    """Check variable type fall into the column name category.
    Args:
        cols (str | list{str} | None):
            Column names candidate.
    Returns:
        bool:
            if `col` is either str, list{str} or None
    """
    ok = isinstance(cols, (str, list)) or cols is None
    if isinstance(cols, list):
        ok = ok and all([isinstance(col, str)
                         for col in cols])
    return ok

def input_cols(cols, append_to=None, default=None):
    """Process the input column name.
    Args:
        cols (str | list{str} | None):
            The input column name(s).
        append_to (list{str} | None, optional):
            A list keep track of all the column names.
        default (str | list{str} | None, optional):
            Default value when `cols` is `None`.
    Returns:
        str | list{str}:
            The name of the column(s)
    """
    assert is_cols(cols)
    assert is_cols(append_to)
    assert is_cols(default)
    default = [] if default is None else default
    cols = default if cols is None else cols

    if isinstance(cols, list):
        cols = cols.copy()

    if cols is not None and append_to is not None:
        if isinstance(cols, str):
            append_to.append(cols)
        else:
            append_to += cols
    return cols

def combine_cols(cols):
    """Combine column names into one list of names.

    Args:
        cols (list{str | list{str}}):
            A list of names of columns or list of column names.

    Return:
        list{str}:
            Combined names of columns.
    """
    combined_cols = []
    for col in cols:
        if isinstance(col, str):
            combined_cols.append(col)
        else:
            combined_cols += col

    return combined_cols

def sizes_to_indices(sizes):
    """Converting sizes to corresponding indices.
    Args:
        sizes (numpy.dnarray):
            An array consist of non-negative number.
    Returns:
        list{range}:
            List the indices.
    """
    indices = []
    a = 0
    b = 0
    for i, size in enumerate(sizes):
        b += size
        indices.append(np.arange(a, b))
        a += size

    return indices

def is_gaussian_prior(prior, size=None):
    """Check if variable satisfy Gaussian prior format

    Args:
        prior (numpy.ndarray):
            Either one or two dimensional array, with first group refer to mean
            and second group refer to standard deviation.

    Keyword Args:
        size (int | None, optional):
            Size the variable, prior related to.

    Returns:
        bool:
            True if satisfy condition.
    """
    # check type
    ok = isinstance(prior, np.ndarray) or prior is None
    if prior is not None:
        # check dimension
        ok = ok and (prior.ndim == 1 or prior.ndim == 2) and len(prior) == 2
        if size is not None and prior.ndim == 2:
            ok = ok and (prior.shape[1] == size)
        # check value
        ok = ok and np.all(prior[1] > 0.0)
    return ok

is_laplace_prior = is_gaussian_prior

def is_uniform_prior(prior, size=None):
    """Check if variable satisfy uniform prior format

    Args:
        prior (numpy.ndarray):
            Either one or two dimensional array, with first group refer to lower
            bound and second group refer to upper bound.

    Keyword Args:
        size (int | None, optional):
            Size the variable, prior related to.

    Returns:
        bool:
            True if satisfy condition.
    """
    # check type
    ok = isinstance(prior, np.ndarray) or prior is None
    if prior is not None:
        # check dimension
        ok = ok and (prior.ndim == 1 or prior.ndim == 2) and len(prior) == 2
        if size is not None and prior.ndim == 2:
            ok = ok and (prior.shape[1] == size)
        # check value
        ok = ok and np.all(prior[0] <= prior[1])
    return ok

def input_gaussian_prior(prior, size):
    """Process the input Gaussian prior

    Args:
        prior (numpy.ndarray):
            Either one or two dimensional array, with first group refer to mean
            and second group refer to standard deviation.
        size (int, optional):
            Size the variable, prior related to.

    Returns:
        numpy.ndarray:
            Prior after processing, with shape (2, size), with the first row
            store the mean and second row store the standard deviation.
    """
    assert is_gaussian_prior(prior)
    if prior is None:
        return np.array([[0.0]*size, [np.inf]*size])
    elif prior.ndim == 1:
        return np.repeat(prior[:, None], size, axis=1)
    else:
        assert prior.shape[1] == size
        return prior

input_laplace_prior = input_gaussian_prior

def input_uniform_prior(prior, size):
    """Process the input Gaussian prior

    Args:
        prior (numpy.ndarray):
            Either one or two dimensional array, with first group refer to mean
            and second group refer to standard deviation.
        size (int, optional):
            Size the variable, prior related to.

    Returns:
        numpy.ndarray:
            Prior after processing, with shape (2, size), with the first row
            store the mean and second row store the standard deviation.
    """
    assert is_uniform_prior(prior)
    if prior is None:
        return np.array([[-np.inf]*size, [np.inf]*size])
    elif prior.ndim == 1:
        return np.repeat(prior[:, None], size, axis=1)
    else:
        assert prior.shape[1] == size
        return prior

def avg_integral(mat, spline=None):
    """Compute average integral.

    Args:
        mat (numpy.ndarray):
            Matrix that contains the starting and ending points of the integral
            or a single column represents the mid-points.
        spline (xspline.XSpline | None, optional):
            Spline integrate over with, when `None` treat the function as
            linear.

    Returns:
        numpy.ndarray:
            Design matrix when spline is not `None`, otherwise the mid-points.
    """
    assert mat.ndim == 2
    if mat.size == 0:
        return mat.reshape(mat.shape[0], 0)

    if mat.shape[1] == 1:
        return mat if spline is None else spline.design_mat(
            mat.ravel(), l_extra=True, r_extra=True)[:, 1:]
    else:
        if spline is None:
            return mat.mean(axis=1)[:, None]
        else:
            x0 = mat[:, 0]
            x1 = mat[:, 1]
            dx = x1 - x0
            val_idx = (dx == 0.0)
            int_idx = (dx != 0.0)

            mat = np.zeros((dx.size, spline.num_spline_bases))

            if np.any(val_idx):
                mat[val_idx, :] = spline.design_mat(x0[val_idx],
                                                    l_extra=True,
                                                    r_extra=True)
            if np.any(int_idx):
                mat[int_idx, :] = spline.design_imat(
                    x0[int_idx], x1[int_idx], 1,
                    l_extra=True,
                    r_extra=True)/(dx[int_idx][:, None])

            return mat[:, 1:]

# random knots
def sample_knots(num_intervals: int,
                 knot_bounds: Union[np.ndarray, None] = None,
                 interval_sizes: Union[np.ndarray, None] = None,
                 num_samples: int = 1) -> Union[np.ndarray, None]:
    """Sample knots given a set of rules.

    Args:
        num_intervals
            Number of intervals (number of knots minus 1).
        knot_bounds
            Bounds for the interior knots. Here we assume the domain span 0 to 1,
            bound for a knot should be between 0 and 1, e.g. ``[0.1, 0.2]``.
            ``knot_bounds`` should have number of interior knots of rows, and each row
            is a bound for corresponding knot, e.g.
            ``knot_bounds=np.array([[0.0, 0.2], [0.3, 0.4], [0.3, 1.0]])``,
            for when we have three interior knots.
        interval_sizes
            Bounds for the distances between knots. For the same reason, we assume
            elements in `interval_sizes` to be between 0 and 1. For example,
            ``interval_distances=np.array([[0.1, 0.2], [0.1, 0.3], [0.1, 0.5], [0.1, 0.5]])``
            means that the distance between first (0) and second knot has to be between 0.1 and 0.2, etc.
            And the number of rows for ``interval_sizes`` has to be same with ``num_intervals``.
        num_samples
            Number of knots samples.

    Returns:
        np.ndarray: Return knots sample as array, with `num_samples` rows and number of knots columns.
    """
    # rename variables
    k = num_intervals
    b = knot_bounds
    d = interval_sizes
    N = num_samples

    t0 = 0.0
    tk = 1.0
    # check input
    assert t0 <= tk
    assert k >= 2

    if d is not None:
        assert d.shape == (k, 2) and sum(d[:, 0]) <= 1.0 and\
            np.all(d >= 0.0) and np.all(d <= 1.0)
    else:
        d = np.repeat(np.array([[0.0, 1.0]]), k, axis=0)

    if b is not None:
        assert b.shape == (k - 1, 2) and\
            np.all(b[:, 0] <= b[:, 1]) and\
            np.all(b[:-1, 1] <= b[1:, 1]) and\
            np.all(b >= 0.0) and np.all(b <= 1.0)
    else:
        b = np.repeat(np.array([[0.0, 1.0]]), k - 1, axis=0)

    d = d*(tk - t0)
    b = b*(tk - t0) + t0
    d[0] += t0
    d[-1] -= tk

    # find vertices of the polyhedron
    D = -col_diff_mat(k - 1)
    I = np.identity(k - 1)

    A1 = np.vstack((-D, D))
    A2 = np.vstack((-I, I))

    b1 = np.hstack((-d[:, 0], d[:, 1]))
    b2 = np.hstack((-b[:, 0], b[:, 1]))

    A = np.vstack((A1, A2))
    b = np.hstack((b1, b2))

    mat = np.insert(-A, 0, b, axis=1)
    mat = Matrix(mat)
    mat.rep_type = RepType.INEQUALITY
    poly = Polyhedron(mat)
    ext = poly.get_generators()
    vertices_and_rays = np.array(ext)

    if vertices_and_rays.size == 0:
        print('there is no feasible knots')
        return None

    if np.any(vertices_and_rays[:, 0] == 0.0):
        print('polyhedron is not closed, something is wrong.')
        return None
    else:
        vertices = vertices_and_rays[:, 1:]

    # sample from the convex combination of the vertices
    n = vertices.shape[0]
    s_simplex = sample_simplex(n, N=N)
    s = s_simplex.dot(vertices)

    s = np.insert(s, 0, t0, axis=1)
    s = np.insert(s, k, tk, axis=1)

    return s

def sample_simplex(n, N=1):
    """sample from n dimensional simplex"""
    assert n >= 1

    # special case when n == 1
    if n == 1:
        return np.ones((N, n))

    # other cases
    s = np.random.rand(N, n - 1)
    s.sort(axis=1)
    s = np.insert(s, 0, 0.0, axis=1)
    s = np.insert(s, n, 1.0, axis=1)

    w = np.zeros((n + 1, n))
    id_d0 = np.diag_indices(n)
    id_d1 = (id_d0[0] + 1, id_d0[1])
    w[id_d0] = -1.0
    w[id_d1] = 1.0

    return s.dot(w)

def col_diff_mat(n):
    """column difference matrix"""
    D = np.zeros((n + 1, n))
    id_d0 = np.diag_indices(n)
    id_d1 = (id_d0[0] + 1, id_d0[1])
    D[id_d0] = -1.0
    D[id_d1] = 1.0

    return D

def nonlinear_trans(score, slope=6.0, quantile=0.7):
    score_min = np.min(score)
    score_max = np.max(score)
    weight = (score - score_min)/(score_max - score_min)

    sorted_weight = np.sort(weight)
    x = sorted_weight[int(0.8*weight.size)]
    y = 1.0 - x

    # calculate the transformation coefficient
    c = np.zeros(4)
    c[1] = slope*x**2/quantile
    c[0] = quantile*np.exp(c[1]/x)
    c[3] = slope*y**2/(1.0 - quantile)
    c[2] = (1.0 - quantile)*np.exp(c[3]/y)

    weight_trans = np.zeros(weight.size)

    for i in range(weight.size):
        w = weight[i]
        if w == 0.0:
            weight_trans[i] = 0.0
        elif w < x:
            weight_trans[i] = c[0]*np.exp(-c[1]/w)
        elif w < 1.0:
            weight_trans[i] = 1.0 - c[2]*np.exp(-c[3]/(1.0 - w))
        else:
            weight_trans[i] = 1.0

    weight_trans = (weight_trans - np.min(weight_trans))/\
        (np.max(weight_trans) - np.min(weight_trans))

    return weight_trans

def mat_to_fun(alt_mat, ref_mat=None):
    alt_mat = np.array(alt_mat)
    assert alt_mat.ndim == 2
    if ref_mat is not None:
        ref_mat = np.array(ref_mat)
        assert ref_mat.ndim == 2

    if alt_mat.size == 0:
        fun = None
        jac_fun = None
    else:
        if ref_mat is None or ref_mat.size == 0:
            mat = alt_mat
        else:
            mat = alt_mat - ref_mat
        def fun(x, mat=mat):
            return mat.dot(x)

        def jac_fun(x, mat=mat):
            return mat

    return fun, jac_fun

def mat_to_log_fun(alt_mat, ref_mat=None):
    alt_mat = np.array(alt_mat)
    assert alt_mat.ndim == 2
    if ref_mat is not None:
        ref_mat = np.array(ref_mat)
        assert ref_mat.ndim == 2

    if alt_mat.size == 0:
        fun = None
        jac_fun = None
    else:
        if ref_mat is None or ref_mat.size == 0:
            def fun(beta):
                return np.log(1.0 + alt_mat.dot(beta))

            def jac_fun(beta):
                return alt_mat/(1.0 + alt_mat.dot(beta)[:, None])
        else:
            def fun(beta):
                return np.log(1.0 + alt_mat.dot(beta)) - \
                       np.log(1.0 + ref_mat.dot(beta))

            def jac_fun(beta):
                return alt_mat/(1.0 + alt_mat.dot(beta)[:, None]) - \
                       ref_mat/(1.0 + ref_mat.dot(beta)[:, None])

    return fun, jac_fun

def empty_array():
    return np.array(list())

def to_list(obj: Any) -> List[Any]:
    """Convert objective to list of object.

    Args:
        obj (Any): Object need to be convert.

    Returns:
        List[Any]:
            If `obj` already is a list object, return `obj` itself,
            otherwise wrap `obj` with a list and return it.
    """
    if isinstance(obj, list):
        return obj
    else:
        return [obj]

def is_numeric_array(array: np.ndarray) -> bool:
    """Check if an array is numeric.

    Args:
        array (np.ndarray): Array need to be checked.

    Returns:
        bool: True if the array is numeric.
    """
    numerical_dtype_kinds = {'b',  # boolean
                             'u',  # unsigned integer
                             'i',  # signed integer
                             'f',  # floats
                             'c'}  # complex
    try:
        return array.dtype.kind in numerical_dtype_kinds
    except AttributeError:
        # in case it's not a numpy array it will probably have no dtype.
        return np.asarray(array).dtype.kind in numerical_dtype_kinds

def expand_array(array: np.ndarray,
                 shape: Tuple[int],
                 value: Any,
                 name: str) -> np.ndarray:
    """Expand array when it is empty.

    Args:
        array (np.ndarray):
            Target array. If array is empty, fill in the ``value``. And
            When it is not empty assert the ``shape`` agrees and return the original array.
        shape (Tuple[int]): The expected shape of the array.
        value (Any): The expected value in final array.
        name (str): Variable name of the array (for error message).

    Returns:
        np.ndarray: Expanded array.
    """
    array = np.array(array)
    if len(array) == 0:
        array = np.full(shape, value)
    else:
        assert array.shape == shape, f"{name}, inconsistent shape."
    return array

ext: py

max_stars_repo_name: jiaweih/MRTool

max_issues_repo_name: jiaweih/MRTool

max_forks_repo_name: jiaweih/MRTool

reason: import numpy


text:
import json
import subprocess
import numpy.random as nprd

from n0test.tdt_generator import Generation

ENV_KEY = "N0TEST_JSON_CreateVirtualMachine_REQUESTS"
# JSON_FILEPATH = "n0test.CreateVirtualMachine.json"
JSON_FILEPATH = "/tmp/n0test.selected.json"
JSON_SEED_FILEPATH = "n0test.CreateVirtualMachine.seed.json"
GENERATION_CASES = 512

class CreateVirtualMachineGeneration(Generation):
    def run_get_proc(self, request_list):
        p = subprocess.Popen([
            "virtualmachine.test",
            "-test.coverprofile=/dev/stderr"
        ], env={
            ENV_KEY: json.dumps(request_list),
        }, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

        return p

    def run_get_score(self, out, err, chosen):
        if "PASS" in out:
            lines = err.split('\n')
            coverage = 0

            for l in lines:
                if len(l) == 0:
                    continue

                if l[-1] == '1':
                    coverage += 1

            return coverage

        elif "N0TEST_OMIT" in out:
            return -1

        print("out={}\nerr={}\nrequest={}".format(out.decode('utf-8'), err.decode('utf-8'), json.dumps(request, indent=2)))

        # TODO: crash report, 保存したい
        return -1

    def select(self, select_num=256):
        filtered = filter(lambda x: x["score"] != -1, self._result)
        # selected = sorted(filtered, key=lambda x: x["distance"], reverse=True)[:select_num]
        # self._selected = list(map(lambda x: x["case"], selected)) + self._persistence
        self._selected = list(map(lambda x: x["case"], filtered)) + self._persistence
        # self._selected = list(map(lambda x: x["case"], selected))

        return self._selected

if __name__ == "__main__":
    # with open(JSON_FILEPATH) as f:
    #     prev = json.load(f)
    prev = None

    with open(JSON_SEED_FILEPATH) as f:
        seed = json.load(f)

    if prev:
        gen = CreateVirtualMachineGeneration(seed=seed, list_operate_distance=3, previous=prev)
    else:
        gen = CreateVirtualMachineGeneration(seed=seed, list_operate_distance=3)

    for i in range(500):
        while gen.len < GENERATION_CASES:
            if nprd.rand() < 0.75:
                gen.mutate(nprd.randint(1, 10) * (1 if nprd.rand() < 0.5 else -1))
                gen.mutate(nprd.randint(1, 10) * (1 if nprd.rand() < 0.5 else -1))
            else:
                gen.cross()

        gen.run()
        gen.persistent()
        gen.select(int(GENERATION_CASES * 0.75))

        print(json.dumps({
            "score(coverage)": gen.max_score,
            "persistenced": len(gen.persistence),
            "average_distance": gen.average_distance,
        }))

        with open(JSON_FILEPATH, mode='w') as f:
            json.dump(gen.persistence, f, indent=2)

        gen = CreateVirtualMachineGeneration(previous_generation=gen)

max_stars_repo_name: cordiers/multi-comp-go-py

max_issues_repo_name: cordiers/multi-comp-go-py

max_forks_repo_name: cordiers/multi-comp-go-py


text:
from meta_mb.baselines.linear_baseline import LinearFeatureBaseline
from meta_mb.meta_algos.ppo_maml import PPOMAML
from meta_mb.samplers.meta_samplers import MAMLSampler
from meta_mb.samplers.maml_sample_processor import MAMLSampleProcessor
from meta_mb.policies.meta_gaussian_mlp_policy import MetaGaussianMLPPolicy

import tensorflow as tf
import numpy as np
import unittest

from gym.spaces import Box

class MetaPointEnv():

    def step(self, action):
        """
        Run one timestep of the environment's dynamics. When end of episode
        is reached, reset() should be called to reset the environment's internal state.

        Args:
            action : an action provided by the environment
        Returns:
            (observation, reward, done, info)
            observation : agent's observation of the current environment
            reward [Float] : amount of reward due to the previous action
            done : a boolean, indicating whether the episode has ended
            info : a dictionary containing other diagnostic information from the previous action
        """
        prev_state = self._state
        self._state = prev_state + np.clip(action, -0.1, 0.1)
        reward = self.reward(prev_state, action, self._state)
        done = self.done(self._state)
        next_observation = np.copy(self._state)
        return next_observation, reward, done, {}

    def reset(self):
        """
        Resets the state of the environment, returning an initial observation.
        Outputs
        -------
        observation : the initial observation of the space. (Initial reward is assumed to be 0.)
        """
        self._state = np.random.uniform(-2, 2, size=(2,))
        observation = np.copy(self._state)
        return observation

    @property
    def observation_space(self):
        return Box(low=-np.inf, high=np.inf, shape=(2,))

    @property
    def action_space(self):
        return Box(low=-0.1, high=0.1, shape=(2,))

    def done(self, obs):
        if obs.ndim == 1:
            return abs(obs[0]) < 0.01 and abs(obs[1]) < 0.01
        elif obs.ndim == 2:
            return np.logical_and(np.abs(obs[:, 0]) < 0.01, np.abs(obs[:, 1]) < 0.01)

    def reward(self, obs, act, obs_next):
        if obs_next.ndim == 1:
            return - np.sqrt(obs_next[0]**2 + obs_next[1]**2)
        elif obs_next.ndim == 2:
            return - np.sqrt(obs_next[:, 0] ** 2 + obs_next[:, 1] ** 2)

    def log_diagnostics(self, paths):
        pass

    def sample_tasks(self, n_tasks):
        return [{}] * n_tasks

    def set_task(self, task):
        pass

class TestLikelihoodRation(unittest.TestCase):
    """
    Assure that likelihhood ratio at first gradient step is approx. one since pi_old = pi_new
    """

    def setUp(self):
        self.env = env = MetaPointEnv()

        self.baseline = baseline = LinearFeatureBaseline()

        self.policy = policy = MetaGaussianMLPPolicy(
            name="meta-policy",
            obs_dim=np.prod(env.observation_space.shape),
            action_dim=np.prod(env.action_space.shape),
            meta_batch_size=10,
            hidden_sizes=(16, 16),
            learn_std=True,
            hidden_nonlinearity=tf.tanh,
            output_nonlinearity=None,
        )

        self.sampler = MAMLSampler(
            env=env,
            policy=policy,
            rollouts_per_meta_task=2,
            meta_batch_size=10,
            max_path_length=50,
            parallel=False,
        )

        self.sample_processor = MAMLSampleProcessor(
            baseline=baseline,
            discount=0.99,
            gae_lambda=1.0,
            normalize_adv=True,
            positive_adv=False,
        )

        self.algo = PPOMAML(
            policy=policy,
            inner_lr=0.1,
            meta_batch_size=10,
            num_inner_grad_steps=2,
            learning_rate=1e-3,
            num_ppo_steps=5,
            num_minibatches=1,
            clip_eps=0.5,
            clip_outer=True,
            target_outer_step=0,
            target_inner_step=2e-2,
            init_outer_kl_penalty=0,
            init_inner_kl_penalty=1e-3,
            adaptive_outer_kl_penalty=False,
            adaptive_inner_kl_penalty=True,
            anneal_factor=1.0,
        )

    def test_likelihood_ratio(self):
        with tf.Session() as sess:

            # initialize uninitialized vars  (only initialize vars that were not loaded)
            uninit_vars = [var for var in tf.global_variables() if not sess.run(tf.is_variable_initialized(var))]
            sess.run(tf.variables_initializer(uninit_vars))

            self.sampler.update_tasks()
            self.policy.switch_to_pre_update()  # Switch to pre-update policy

            all_samples_data, all_paths = [], []
            for step in range(1):

                """ -------------------- Sampling --------------------------"""
                paths = self.sampler.obtain_samples(log_prefix=str(step))
                all_paths.append(paths)

                """ ----------------- Processing Samples ---------------------"""
                samples_data = self.sample_processor.process_samples(paths, log=False)
                all_samples_data.append(samples_data)

                """ ------------------- Inner Policy Update --------------------"""
                obs_phs, action_phs, adv_phs, dist_info_phs, all_phs = self.algo._make_input_placeholders('')

                for i in range(self.algo.meta_batch_size):
                    obs = samples_data[i]['observations']
                    actions = samples_data[i]['actions']
                    agent_infos = samples_data[i]['agent_infos']
                    param_vals = self.policy.get_param_values()

                    likelihood_ratio_sym = self.policy.likelihood_ratio_sym(obs_phs[i], action_phs[i],
                                                                          dist_info_phs[i],
                                                                          self.policy.policies_params_phs[i])

                    feed_dict_params = dict(zip(self.policy.policies_params_phs[i].values(), param_vals.values()))

                    feed_dict_dist_infos = dict(zip(dist_info_phs[i].values(), agent_infos.values()))

                    feed_dict = {obs_phs[i]: obs,
                                 action_phs[i]: actions
                                 }

                    feed_dict.update(feed_dict_params)
                    feed_dict.update(feed_dict_dist_infos)

                    lr = sess.run(likelihood_ratio_sym, feed_dict=feed_dict)

                    self.assertTrue(np.allclose(lr, 1))

max_stars_repo_name: iclavera/meta-mb

max_issues_repo_name: iclavera/meta-mb

max_forks_repo_name: iclavera/meta-mb


text:
from __future__ import absolute_import, print_function
from numba import cuda
from numba.cuda.testing import unittest, SerialMixin
from numba.tests.support import captured_stdout

class TestCudaDetect(SerialMixin, unittest.TestCase):
    def test_cuda_detect(self):
        # exercise the code path
        with captured_stdout() as out:
            cuda.detect()
        output = out.getvalue()
        self.assertIn('Found', output)
        self.assertIn('CUDA devices', output)

if __name__ == '__main__':
    unittest.main()

max_stars_repo_name: uw-ipd/numba

max_issues_repo_name: uw-ipd/numba

max_forks_repo_name: uw-ipd/numba

reason: from numba


text:
from settings import Settings
from exceptions import NoBridgeException, SaveMyLaptopException
from random import randint
from copy import deepcopy
import os
import pickle

from dna import DNA
from mutation import Mutation
from cross_over import Cross_Over
from nn import NN
from utils import reshape_mnist_images, clean_folder, copy_files_from_to

import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

class GeneticAlgorithm(object):

    def __init__(self, population_size):

        self.generation = 0
        self.population_size = population_size
        self.mutations_per_breeding = Settings.MUTATIONS_PER_BREEDING

        self.mnist = input_data.read_data_sets("MNIST_data", one_hot=True)

        self.population = []
        self.fitness = []

        self.best_ever_fitness = 1
        self.best_generations_fitness = []

        # if there is a check point, load it, otherwise start with an initial population
        if not os.path.exists(Settings.CHECKPOINT_PATH):
            os.mkdir(Settings.CHECKPOINT_PATH)

        self.start_generation = len(os.listdir(Settings.CHECKPOINT_PATH))

        if(self.start_generation):
            self.load_last_saved_generation()
        else:
            self.create_initial_population()

    def evolve(self, num_generations):

        """
        Evolve the population for a fixed number of generations
        """

        for gen in range(self.start_generation, num_generations):

            self.generation += 1
            print("Evolving generation " + str(self.generation))

            self.next_generation_dna = []
            self.next_generation_fitness = []

            # save the three best individuals that go through the next generation unchanged
            # (produces N_BEST_CANDIDATES offsprings)
            for best_i in range(Settings.N_BEST_CANDIDATES):

                self.next_generation_dna.append(self.population[best_i])
                self.next_generation_fitness.append(self.fitness[best_i])

            # breed the three best individuals together
            for best_i in range(Settings.N_BEST_CANDIDATES):
                for best_j in range(best_i + 1, Settings.N_BEST_CANDIDATES):
                    self.attempt_breeding(best_i, best_j)

            # breed each best individual with a random individual from the population
            # including itself because, well.. parthenogenesis and all..
            for best_i in range(Settings.N_BEST_CANDIDATES):
                other_i = randint(0, self.population_size - 1)
                self.attempt_breeding(best_i, other_i)

            # breed two different random individuals together until the number of offsprings
            # reaches the maximum population size
            while(len(self.next_generation_dna) < self.population_size):
                other_i = randint(0, self.population_size - 1)
                other_j = randint(0, self.population_size - 1)
                self.attempt_breeding(other_i, other_j)

            # sort the next generation individuals by fitness
            self.next_generation_fitness, self.next_generation_dna = (list(t) for t in zip(*sorted(zip(self.next_generation_fitness, self.next_generation_dna))))

            # update the population for the next generation
            self.population = self.next_generation_dna
            self.fitness = self.next_generation_fitness

            # update the best_generations_fitness list
            self.best_generations_fitness.append(self.fitness[0])

            # update the number of mutations per breeding if necessary
            # the number of mutations can be increased temporarily to get out of a local optimum
            gen_i = len(self.best_generations_fitness) - 1
            previous_gen_i = gen_i - 1

            if(self.best_generations_fitness[previous_gen_i] <= self.best_generations_fitness[gen_i]):
                self.mutations_per_breeding += 1
            else:
                self.mutations_per_breeding = 1

            # save generation checkpoint
            self.save_generation_checkpoint()

            print("\n ===============================================")
            print("\n ============== End of generation ==============")
            print("\nFitness history through generations :", self.best_generations_fitness)
            best_so_far = max(self.best_generations_fitness)
            print("The best individual so far is from generation", self.best_generations_fitness.index(best_so_far),
                  "with a fitness of ", best_so_far)
            print("\n ===============================================")

    def attempt_breeding(self, individual_i, individual_j):

        """
        Attempt to breed the two individuals (several times if necessary)
        If the breeding is successful and the Neural Networks can be built,
        the two offsprings are added into the next generation.

        The breeding process is the following:
            - cross-over between the two lovers
            - mutate the offsprings with probability p
            - create the offsprings neural networks

        """

        successful_breedings = 0
        breeding_attempts = 0

        while(successful_breedings < 2 and breeding_attempts < Settings.MAX_BREEDING_ATTEMPTS):

            try:
                # cross over the two individuals
                offspring_1, offspring_2 = Cross_Over(self.population[individual_i], self.population[individual_j]).breed()

            except NoBridgeException as e:
                print(e)
                print("Failed to cross-over the individuals")
                return (False)
            except Exception as e:
                print("Failed to cross-over the individuals")
                return (False)

            for offspring in [offspring_1, offspring_2]:

                # apply (several if we are stuck in a local optimum) mutations to the offspring
                for _ in range(self.mutations_per_breeding):
                    offspring = Mutation(offspring).mutate()

                mutated_offspring = offspring

                # build and train the crossed-mutated graphs on the spot
                if(successful_breedings < 2):

                    try:
                        mutated_offspring_fitness = self.build_and_train_network(mutated_offspring)

                        self.next_generation_dna.append(mutated_offspring)
                        self.next_generation_fitness.append(mutated_offspring_fitness)
                        successful_breedings += 1

                    except Exception as e:
                        print("Failed to build the NN \n\n" + str(e))

        return(successful_breedings)

    def build_and_train_network(self, individual_dna):

        """
        Train the Neural Network for a fixed number of steps and regularly evaluate
        its performances
        """

        best_validation_error = 1

        graph = tf.Graph()
        with graph.as_default():

            # build the Neural Network using the mutated dna instance
            nn = NN(individual_dna)

            # and train the resulting model
            num_trainable_variables = np.sum([np.prod(v.shape) for v in tf.trainable_variables()])
            print("==========================================")
            print("Number of trainable variables :", num_trainable_variables)
            print("Training the following DNA: \n")
            print(nn.dna)

            if(num_trainable_variables > Settings.MAX_TRAINABLE_PARAMETERS):
                raise SaveMyLaptopException()

            with tf.Session(graph=graph) as sess:

                # merge the summaries and create a file writer in the tmp folder
                clean_folder(Settings.TMP_FOLDER_PATH)
                merged_summaries = tf.summary.merge_all()
                writer = tf.summary.FileWriter(Settings.TMP_FOLDER_PATH, sess.graph)

                # initialize variables and finalize the graph
                sess.run(tf.global_variables_initializer())
                sess.graph.finalize()

                for training_step in range(Settings.TRAINING_STEPS):

                    # training step
                    images, labels = self.mnist.train.next_batch(Settings.MINIBATCH_SIZE)
                    images = reshape_mnist_images(images)

                    sess.run(nn.optimize, {nn.input: images, nn.labels: labels, nn.is_training: True})

                    # performance evaluation every few training steps
                    if not training_step % Settings.EVALUATION_RATE:

                        test_images, test_labels = self.mnist.test.next_batch(Settings.TEST_BATCH_SIZE)
                        test_images = reshape_mnist_images(test_images)

                        summary, validation_error = sess.run([merged_summaries, nn.prediction_error], {nn.input: test_images, nn.labels: test_labels, nn.is_training: False})
                        writer.add_summary(summary, training_step)
                        print('Test error {:6.2f}%'.format(100 * validation_error))
                        best_validation_error = min(best_validation_error, validation_error)

                # close the writer
                writer.close()

                # save graph logs and dna string into the right models folder
                model_path = Settings.MODELS_FOLDER_PATH + str(self.generation) + "/" + "{:f}".format(best_validation_error)

                copy_files_from_to(Settings.TMP_FOLDER_PATH, model_path)

                file_path = model_path + "/topology.txt"
                with open(file_path, 'a') as topo_file:
                    topo_file.write(nn.dna.__str__())

        print("Training and Saving complete !\n\n")

        return(best_validation_error)

    def create_initial_population(self):

        """
        Create an initial population consisting of *population_size*
        primitive neural networks with an input-output structure
        """

        for individual_i in range(self.population_size):

            individual_dna = DNA(Settings.INPUT_SHAPE, Settings.OUTPUT_SHAPE)
            individual_dna.create_primitive_structure()

            individual_fitness = self.build_and_train_network(individual_dna)

            self.population.append(individual_dna)
            self.fitness.append(individual_fitness)

        self.best_generations_fitness.append(min(self.fitness))

    def load_last_saved_generation(self):

        print("Loading generation", self.start_generation, "from checkpoint..  ", end='')

        last_checkpoint_path = Settings.CHECKPOINT_PATH + str(self.start_generation) + "/"

        # load the population list
        population_file = open(last_checkpoint_path + "population.pickle", "rb")
        self.population = pickle.load(population_file)
        population_file.close()

        # load the fitness list
        fitness_file = open(last_checkpoint_path + "fitness.pickle", "rb")
        self.fitness = pickle.load(fitness_file)
        fitness_file.close()

        # load the best generations fitness list
        best_fitness_file = open(last_checkpoint_path + "best_fitness.pickle", "rb")
        self.best_generations_fitness = pickle.load(best_fitness_file)
        best_fitness_file.close()

        # restore generation number
        self.generation = self.start_generation

        print("done.")

    def save_generation_checkpoint(self):

        save_path = Settings.CHECKPOINT_PATH + str(self.generation) + "/"
        os.mkdir(save_path)

        print("Saving generation", self.generation, "in the checkpoint folder..  ", end='')

        # save the population list
        population_file = open(save_path + "population.pickle", "wb")
        pickle.dump(self.population, population_file)
        population_file.close()

        # save the fitness list
        fitness_file = open(save_path + "fitness.pickle", "wb")
        pickle.dump(self.fitness, fitness_file)
        fitness_file.close()

        # save the best generations fitness list
        best_fitness_file = open(save_path + "best_fitness.pickle", "wb")
        pickle.dump(self.best_generations_fitness, best_fitness_file)
        best_fitness_file.close()

        print("done.")

max_stars_repo_name: cedricsimar/ANNT

max_issues_repo_name: cedricsimar/ANNT

max_forks_repo_name: cedricsimar/ANNT


text:
from collections import defaultdict
import numpy as np

class Graph():
    def __init__(self, vertices=None):
        ##We'll assume for now a staggered array.
        self.adj=[]
        self.vertices=vertices

    def init_from_edge_list(self,num_verts,edges):
        self.vertices = [Node(i) for i in range(num_verts)]
        self.adj = defaultdict(list)
        for ed in edges:
            vert_0 = self.vertices[ed[0]]
            vert_1 = self.vertices[ed[1]]
            self.adj[vert_0].append(vert_1)
        return self

class Node():
    def __init__(self,val,next=None,color="white",
                pi=None,d=np.inf,key=None):
        self.next=next
        self.val=val
        self.color=color
        self.pi=pi
        self.d=d
        if key is None:
            self.key=val
        else:
            self.key=key

def remove_zeros(res):
    """
    res is expected to be a dictionary of dictionaries
    representing a flow graph.
    """
    res1 = {}
    for k in res.keys():
        res2 = {}
        for kk in res[k].keys():
            if res[k][kk] > 0:
                res2[kk] = res[k][kk]
        if len(res2) > 0:
            res1[k] = res2
    return res1


text:
#!/usr/bin/env python
"""Contains classes that represent biological sequence data. These
provide generic biological sequence manipulation functions, plus functions
that are critical for the EVOLVE calculations.

WARNING: Do not import sequence classes directly! It is expected that you will
access them through the moltype module. Sequence classes depend on information
from the MolType that is _only_ available after MolType has been imported.

Sequences are intended to be immutable. This is not enforced by the code for
performance reasons, but don't alter the MolType or the sequence data after
creation.
"""
from __future__ import division
from annotation import Map, Feature, _Annotatable
from cogent.util.transform import keep_chars, for_seq, per_shortest, \
    per_longest
from cogent.util.misc import DistanceFromMatrix
from cogent.core.genetic_code import DEFAULT as DEFAULT_GENETIC_CODE, \
    GeneticCodes
from cogent.parse import gff
from cogent.format.fasta import fasta_from_sequences
from cogent.core.info import Info as InfoClass
from numpy import array, zeros, put, nonzero, take, ravel, compress, \
    logical_or, logical_not, arange
from numpy.random import permutation
from operator import eq, ne
from random import shuffle
import re
import warnings

__author__ = "Rob Knight, Gavin Huttley, and Peter Maxwell"
__copyright__ = "Copyright 2007-2012, The Cogent Project"
__credits__ = ["Rob Knight", "Peter Maxwell", "Gavin Huttley",
                    "Matthew Wakefield", "Daniel McDonald"]
__license__ = "GPL"
__version__ = "1.5.3"
__maintainer__ = "Rob Knight"
__email__ = "rob@spot.colorado.edu"
__status__ = "Production"

ARRAY_TYPE = type(array(1))

#standard distance functions: left  because generally useful
frac_same = for_seq(f=eq, aggregator=sum, normalizer=per_shortest)
frac_diff = for_seq(f=ne, aggregator=sum, normalizer=per_shortest)

class SequenceI(object):
    """Abstract class containing Sequence interface.

    Specifies methods that Sequence delegates to its MolType, and methods for
    detecting gaps.
    """
    #String methods delegated to self._seq -- remember to override if self._seq
    #isn't a string in your base class, but it's probably better to make
    #self._seq a property that contains the string.
    LineWrap = None #used for formatting FASTA strings
    def __str__(self):
        """__str__ returns self._seq unmodified."""
        return self._seq

    def toFasta(self, make_seqlabel=None):
        """Return string of self in FASTA format, no trailing newline

        Arguments:
            - make_seqlabel: callback function that takes the seq object and
              returns a label str
        """
        return fasta_from_sequences([self], make_seqlabel = make_seqlabel,
                        line_wrap=self.LineWrap)

    def translate(self, *args, **kwargs):
        """translate() delegates to self._seq."""
        return self._seq.translate(*args, **kwargs)

    def count(self, item):
        """count() delegates to self._seq."""
        return self._seq.count(item)

    def __cmp__(self, other):
        """__cmp__ compares based on the sequence string."""
        return cmp(self._seq, other)

    def __hash__(self):
        """__hash__ behaves like the sequence string for dict lookup."""
        return hash(self._seq)

    def __contains__(self, other):
        """__contains__ checks whether other is in the sequence string."""
        return other in self._seq

    def shuffle(self):
        """returns a randomized copy of the Sequence object"""
        randomized_copy_list = list(self)
        shuffle(randomized_copy_list)
        return self.__class__(''.join(randomized_copy_list), Info=self.Info)

    def complement(self):
        """Returns complement of self, using data from MolType.

        Always tries to return same type as item: if item looks like a dict,
        will return list of keys.
        """
        return self.__class__(self.MolType.complement(self), Info=self.Info)

    def stripDegenerate(self):
        """Removes degenerate bases by stripping them out of the sequence."""
        return self.__class__(self.MolType.stripDegenerate(self), Info=self.Info)

    def stripBad(self):
        """Removes any symbols not in the alphabet."""
        return self.__class__(self.MolType.stripBad(self), Info=self.Info)

    def stripBadAndGaps(self):
        """Removes any symbols not in the alphabet, and any gaps."""
        return self.__class__(self.MolType.stripBadAndGaps(self), Info=self.Info)

    def rc(self):
        """Returns reverse complement of self w/ data from MolType.

        Always returns same type self.
        """
        return self.__class__(self.MolType.rc(self), Info=self.Info)

    def isGapped(self):
        """Returns True if sequence contains gaps."""
        return self.MolType.isGapped(self)

    def isGap(self, char=None):
        """Returns True if char is a gap.

        If char is not supplied, tests whether self is gaps only.
        """
        if char is None:    #no char - so test if self is all gaps
            return len(self) == self.countGaps()
        else:
            return self.MolType.isGap(char)

    def isDegenerate(self):
        """Returns True if sequence contains degenerate characters."""
        return self.MolType.isDegenerate(self)

    def isValid(self):
        """Returns True if sequence contains no items absent from alphabet."""
        return self.MolType.isValid(self)

    def isStrict(self):
        """Returns True if sequence contains only monomers."""
        return self.MolType.isStrict(self)

    def firstGap(self):
        """Returns the index of the first gap in the sequence, or None."""
        return self.MolType.firstGap(self)

    def firstDegenerate(self):
        """Returns the index of first degenerate symbol in sequence, or None."""
        return self.MolType.firstDegenerate(self)

    def firstInvalid(self):
        """Returns the index of first invalid symbol in sequence, or None."""
        return self.MolType.firstInvalid(self)

    def firstNonStrict(self):
        """Returns the index of first non-strict symbol in sequence, or None."""
        return self.MolType.firstNonStrict(self)

    def disambiguate(self, method='strip'):
        """Returns a non-degenerate sequence from a degenerate one.

        method can be 'strip' (deletes any characters not in monomers or gaps)
        or 'random'(assigns the possibilities at random, using equal
        frequencies).
        """
        return self.__class__(self.MolType.disambiguate(self, method), \
            Info=self.Info)

    def degap(self):
        """Deletes all gap characters from sequence."""
        return self.__class__(self.MolType.degap(self), Info=self.Info)

    def gapList(self):
        """Returns list of indices of all gaps in the sequence, or []."""
        return self.MolType.gapList(self)

    def gapVector(self):
        """Returns vector of True or False according to which pos are gaps."""
        return self.MolType.gapVector(self)

    def gapMaps(self):
        """Returns dicts mapping between gapped and ungapped positions."""
        return self.MolType.gapMaps(self)

    def countGaps(self):
        """Counts the gaps in the specified sequence."""
        return self.MolType.countGaps(self)

    def countDegenerate(self):
        """Counts the degenerate bases in the specified sequence."""
        return self.MolType.countDegenerate(self)

    def possibilities(self):
        """Counts number of possible sequences matching the sequence.

        Uses self.Degenerates to decide how many possibilites there are at
        each position in the sequence.
        """
        return self.MolType.possibilities(self)

    def MW(self, method='random', delta=None):
        """Returns the molecular weight of (one strand of) the sequence.

        If the sequence is ambiguous, uses method (random or strip) to
        disambiguate the sequence.

        If delta is passed in, adds delta per strand (default is None, which
        uses the alphabet default. Typically, this adds 18 Da for terminal
        water. However, note that the default nucleic acid weight assumes
        5' monophosphate and 3' OH: pass in delta=18.0 if you want 5' OH as
        well.

        Note that this method only calculates the MW of the coding strand. If
        you want the MW of the reverse strand, add self.rc().MW(). DO NOT
        just multiply the MW by 2: the results may not be accurate due to
        strand bias, e.g. in mitochondrial genomes.
        """
        return self.MolType.MW(self, method, delta)

    def canMatch(self, other):
        """Returns True if every pos in self could match same pos in other.

        Truncates at length of shorter sequence.
        Gaps are only allowed to match other gaps.
        """
        return self.MolType.canMatch(self, other)

    def canMismatch(self, other):
        """Returns True if any position in self could mismatch with other.

        Truncates at length of shorter sequence.
        Gaps are always counted as matches.
        """
        return self.MolType.canMismatch(self, other)

    def mustMatch(self, other):
        """Returns True if all positions in self must match positions in other."""
        return self.MolType.mustMatch(self, other)

    def canPair(self, other):
        """Returns True if self and other could pair.

        Pairing occurs in reverse order, i.e. last position of other with
        first position of self, etc.

        Truncates at length of shorter sequence.
        Gaps are only allowed to pair with other gaps, and are counted as 'weak'
        (same category as GU and degenerate pairs).

        NOTE: second must be able to be reverse
        """
        return self.MolType.canPair(self, other)

    def canMispair(self, other):
        """Returns True if any position in self could mispair with other.

        Pairing occurs in reverse order, i.e. last position of other with
        first position of self, etc.

        Truncates at length of shorter sequence.
        Gaps are always counted as possible mispairs, as are weak pairs like GU.
        """
        return self.MolType.canMispair(self, other)

    def mustPair(self, other):
        """Returns True if all positions in self must pair with other.

        Pairing occurs in reverse order, i.e. last position of other with
        first position of self, etc.
        """
        return not self.MolType.canMispair(self, other)

    def diff(self, other):
        """Returns number of differences between self and other.

        NOTE: truncates at the length of the shorter sequence. Case-sensitive.
        """
        return self.distance(other)

    def distance(self, other, function=None):
        """Returns distance between self and other using function(i,j).

        other must be a sequence.

        function should be a function that takes two items and returns a
        number. To turn a 2D matrix into a function, use
        cogent.util.miscs.DistanceFromMatrix(matrix).

        NOTE: Truncates at the length of the shorter sequence.

        Note that the function acts on two _elements_ of the sequences, not
        the two sequences themselves (i.e. the behavior will be the same for
        every position in the sequences, such as identity scoring or a function
        derived from a distance matrix as suggested above). One limitation of
        this approach is that the distance function cannot use properties of
        the sequences themselves: for example, it cannot use the lengths of the
        sequences to normalize the scores as percent similarities or percent
        differences.

        If you want functions that act on the two sequences themselves, there
        is no particular advantage in making these functions methods of the
        first sequences by passing them in as parameters like the function
        in this method. It makes more sense to use them as standalone functions.
        The factory function cogent.util.transform.for_seq is useful for
        converting per-element functions into per-sequence functions, since it
        takes as parameters a per-element scoring function, a score aggregation
        function, and a normalization function (which itself takes the two
        sequences as parameters), returning a single function that combines
        these functions and that acts on two complete sequences.
        """
        if function is None:
            #use identity scoring function
            function = lambda a, b : a != b
        distance = 0
        for first, second in zip(self, other):
            distance += function(first, second)
        return distance

    def matrixDistance(self, other, matrix):
        """Returns distance between self and other using a score matrix.

        WARNING: the matrix must explicitly contain scores for the case where
        a position is the same in self and other (e.g. for a distance matrix,
        an identity between U and U might have a score of 0). The reason the
        scores for the 'diagonals' need to be passed explicitly is that for
        some kinds of distance matrices, e.g. log-odds matrices, the 'diagonal'
        scores differ from each other. If these elements are missing, this
        function will raise a KeyError at the first position that the two
        sequences are identical.
        """
        return self.distance(other, DistanceFromMatrix(matrix))

    def fracSame(self, other):
        """Returns fraction of positions where self and other are the same.

        Truncates at length of shorter sequence.
        Note that fracSame and fracDiff are both 0 if one sequence is empty.
        """
        return frac_same(self, other)

    def fracDiff(self, other):
        """Returns fraction of positions where self and other differ.

        Truncates at length of shorter sequence.
        Note that fracSame and fracDiff are both 0 if one sequence is empty.
        """
        return frac_diff(self, other)

    def fracSameGaps(self, other):
        """Returns fraction of positions where self and other share gap states.

        In other words, if self and other are both all gaps, or both all
        non-gaps, or both have gaps in the same places, fracSameGaps will
        return 1.0. If self is all gaps and other has no gaps, fracSameGaps
        will return 0.0. Returns 0 if one sequence is empty.

        Uses self's gap characters for both sequences.
        """
        if not self or not other:
            return 0.0

        is_gap = self.MolType.Gaps.__contains__
        return sum([is_gap(i) == is_gap(j) for i,j in zip(self, other)]) \
            /min(len(self),len(other))

    def fracDiffGaps(self, other):
        """Returns frac. of positions where self and other's gap states differ.

        In other words, if self and other are both all gaps, or both all
        non-gaps, or both have gaps in the same places, fracDiffGaps will
        return 0.0. If self is all gaps and other has no gaps, fracDiffGaps
        will return 1.0.

        Returns 0 if one sequence is empty.

        Uses self's gap characters for both sequences.
        """
        if not self or not other:
            return 0.0
        return 1.0 - self.fracSameGaps(other)

    def fracSameNonGaps(self, other):
        """Returns fraction of non-gap positions where self matches other.

        Doesn't count any position where self or other has a gap.
        Truncates at the length of the shorter sequence.

        Returns 0 if one sequence is empty.
        """
        if not self or not other:
            return 0.0

        is_gap = self.MolType.Gaps.__contains__
        count = 0
        identities = 0
        for i, j in zip(self, other):
            if is_gap(i) or is_gap(j):
                continue
            count += 1
            if i == j:
                identities += 1

        if count:
            return identities/count
        else:   #there were no positions that weren't gaps
            return 0

    def fracDiffNonGaps(self, other):
        """Returns fraction of non-gap positions where self differs from other.

        Doesn't count any position where self or other has a gap.
        Truncates at the length of the shorter sequence.

        Returns 0 if one sequence is empty. Note that this means that
        fracDiffNonGaps is _not_ the same as 1 - fracSameNonGaps, since both
        return 0 if one sequence is empty.
        """
        if not self or not other:
            return 0.0

        is_gap = self.MolType.Gaps.__contains__
        count = 0
        diffs = 0
        for i, j in zip(self, other):
            if is_gap(i) or is_gap(j):
                continue
            count += 1
            if i != j:
                diffs += 1

        if count:
            return diffs/count
        else:   #there were no positions that weren't gaps
            return 0

    def fracSimilar(self, other, similar_pairs):
        """Returns fraction of positions where self[i] is similar to other[i].

        similar_pairs must be a dict such that d[(i,j)] exists if i and j are
        to be counted as similar. Use PairsFromGroups in cogent.util.misc to
        construct such a dict from a list of lists of similar residues.

        Truncates at the length of the shorter sequence.

        Note: current implementation re-creates the distance function each
        time, so may be expensive compared to creating the distance function
        using for_seq separately.

        Returns 0 if one sequence is empty.
        """
        if not self or not other:
            return 0.0

        return for_seq(f = lambda x, y: (x,y) in similar_pairs, \
            normalizer=per_shortest)(self, other)

    def withTerminiUnknown(self):
        """Returns copy of sequence with terminal gaps remapped as missing."""
        gaps = self.gapVector()
        first_nongap = last_nongap = None
        for i, state in enumerate(gaps):
            if not state:
                if first_nongap is None:
                    first_nongap = i
                last_nongap = i
        missing = self.MolType.Missing
        if first_nongap is None:    #sequence was all gaps
            result = self.__class__([missing for i in len(self)],Info=self.Info)
        else:
            prefix = missing*first_nongap
            mid = str(self[first_nongap:last_nongap+1])
            suffix = missing*(len(self)-last_nongap-1)
            result = self.__class__(prefix + mid + suffix, Info=self.Info)
        return result

class Sequence(_Annotatable, SequenceI):
    """Holds the standard Sequence object. Immutable."""
    MolType = None      #connected to ACSII when moltype is imported

    def __init__(self, Seq='',Name=None, Info=None, check=True, \
            preserve_case=False, gaps_allowed=True, wildcards_allowed=True):
        """Initialize a sequence.

        Arguments:
            Seq: the raw sequence string, default is ''

            Name: the sequence name

            check: if True (the default), validates against the MolType
        """
        if Name is None and hasattr(Seq, 'Name'):
            Name = Seq.Name
        self.Name = Name
        orig_seq = Seq
        if isinstance(Seq, Sequence):
            Seq = Seq._seq
        elif isinstance(Seq, ModelSequence):
            Seq = str(Seq)
        elif type(Seq) is not str:
            try:
                Seq = ''.join(Seq)
            except TypeError:
                Seq = ''.join(map(str, Seq))
        Seq = self._seq_filter(Seq)
        if not preserve_case and not Seq.isupper():
            Seq = Seq.upper()
        self._seq = Seq

        if check:
            self.MolType.verifySequence(self._seq, gaps_allowed, \
                wildcards_allowed)

        if not isinstance(Info, InfoClass):
            try:
                Info = InfoClass(Info)
            except TypeError:
                Info = InfoClass()
        if hasattr(orig_seq, 'Info'):
            try:
                Info.update(orig_seq.Info)
            except:
                pass
        self.Info = Info

        if isinstance(orig_seq, _Annotatable):
            self.copyAnnotations(orig_seq)

    def _seq_filter(self, seq):
        """Returns filtered seq; used to do DNA/RNA conversions."""
        return seq

    def getColourScheme(self, colours):
        return {}
        #dict([(motif,colours.black) for motif in self.MolType])

    def getColorScheme(self, colors):   #alias to support US spelling
        return self.getColourScheme(colours=colors)

    def copyAnnotations(self, other):
        self.annotations = other.annotations[:]

    def annotateFromGff(self, f):
        first_seqname = None
        for (seqname, source, feature, start, end, score, strand,
                frame, attributes, comments) in gff.GffParser(f):
            if first_seqname is None:
                first_seqname = seqname
            else:
                assert seqname == first_seqname, (seqname, first_seqname)
            feat_label = gff.parse_attributes(attributes)
            self.addFeature(feature, feat_label, [(start, end)])

    def withMaskedAnnotations(self, annot_types, mask_char=None, shadow=False):
        """returns a sequence with annot_types regions replaced by mask_char
        if shadow is False, otherwise all other regions are masked.

        Arguments:
            - annot_types: annotation type(s)
            - mask_char: must be a character valid for the seq MolType. The
              default value is the most ambiguous character, eg. '?' for DNA
            - shadow: whether to mask the annotated regions, or everything but
              the annotated regions"""
        if mask_char is None:
            ambigs = [(len(v), c) for c,v in self.MolType.Ambiguities.items()]
            ambigs.sort()
            mask_char = ambigs[-1][1]
        assert mask_char in self.MolType, 'Invalid mask_char %s' % mask_char

        annotations = []
        annot_types = [annot_types, [annot_types]][isinstance(annot_types, str)]
        for annot_type in annot_types:
            annotations += self.getAnnotationsMatching(annot_type)

        region = self.getRegionCoveringAll(annotations)
        if shadow:
            region = region.getShadow()

        i = 0
        segments = []
        for b, e in region.getCoordinates():
            segments.append(self._seq[i:b])
            segments.append(mask_char * (e-b))
            i = e
        segments.append(self._seq[i:])

        new = self.__class__(''.join(segments), Name=self.Name, check=False,
                            Info=self.Info)
        new.annotations = self.annotations[:]
        return new

    def gappedByMapSegmentIter(self, map, allow_gaps=True, recode_gaps=False):
        for span in map.spans:
            if span.lost:
                if allow_gaps:
                    unknown = span.terminal or recode_gaps
                    seg = "-?"[unknown] * span.length
                else:
                    raise ValueError('Gap(s) in map %s' % map)
            else:
                seg = self._seq[span.Start:span.End]
                if span.Reverse:
                    complement = self.MolType.complement
                    seg = [complement(base) for base in seg[::-1]]
                    seg = ''.join(seg)
            yield seg

    def gappedByMapMotifIter(self, map):
        for segment in self.gappedByMapSegmentIter(map):
            for motif in segment:
                yield motif

    def gappedByMap(self, map, recode_gaps=False):
        segments = self.gappedByMapSegmentIter(map, True, recode_gaps)
        new = self.__class__(''.join(segments),
            Name=self.Name, check=False, Info=self.Info)
        annots = self._slicedAnnotations(new, map)
        new.annotations = annots
        return new

    def _mapped(self, map):
        # Called by generic __getitem__
        segments = self.gappedByMapSegmentIter(map, allow_gaps=False)
        new = self.__class__(''.join(segments), self.Name, Info=self.Info)
        return new

    def __add__(self, other):
        """Adds two sequences (other can be a string as well)."""
        if hasattr(other, 'MolType'):
            if self.MolType != other.MolType:
                raise ValueError, "MolTypes don't match: (%s,%s)" % \
                    (self.MolType, other.MolType)
            other_seq = other._seq
        else:
            other_seq = other
        new_seq = self.__class__(self._seq + other_seq)
        # Annotations which extend past the right end of the left sequence
        # or past the left end of the right sequence are dropped because
        # otherwise they will annotate the wrong part of the constructed
        # sequence.
        left = [a for a in self._shiftedAnnotations(new_seq, 0)
                if a.map.End <= len(self)]
        if hasattr(other, '_shiftedAnnotations'):
            right = [a for a in other._shiftedAnnotations(new_seq, len(self))
                if a.map.Start >= len(self)]
            new_seq.annotations = left + right
        else:
            new_seq.annotations = left
        return new_seq

    def __repr__(self):
        myclass = '%s' % self.__class__.__name__
        myclass = myclass.split('.')[-1]
        if len(self) > 10:
            seq = str(self._seq[:7]) + '... %s' % len(self)
        else:
            seq = str(self._seq)
        return "%s(%s)" % (myclass, seq)

    def getTracks(self, policy):
        return policy.tracksForSequence(self)

    def getName(self):
        """Return the sequence name -- should just use Name instead."""

        return self.Name

    def __len__(self):
        return len(self._seq)

    def __iter__(self):
        return iter(self._seq)

    def gettype(self):
        """Return the sequence type."""

        return self.MolType.label

    def resolveambiguities(self):
        """Returns a list of tuples of strings."""
        ambigs = self.MolType.resolveAmbiguity
        return [ambigs(motif) for motif in self._seq]

    def slidingWindows(self, window, step, start=None, end=None):
        """Generator function that yield new sequence objects
        of a given length at a given interval.
        Arguments:
            - window: The length of the returned sequence
            - step: The interval between the start of the returned
              sequence objects
            - start: first window start position
            - end: last window start position
        """
        start = [start, 0][start is None]
        end = [end, len(self)-window+1][end is None]
        end = min(len(self)-window+1, end)
        if start < end and len(self)-end >= window-1:
            for pos in xrange(start, end, step):
                yield self[pos:pos+window]

    def getInMotifSize(self, motif_length=1, log_warnings=True):
        """returns sequence as list of non-overlapping motifs

        Arguments:
            - motif_length: length of the motifs
            - log_warnings: whether to notify of an incomplete terminal motif"""
        seq = self._seq
        if motif_length == 1:
            return seq
        else:
            length = len(seq)
            remainder = length % motif_length
            if remainder and log_warnings:
                warnings.warn('Dropped remainder "%s" from end of sequence' %
                        seq[-remainder:])
            return [seq[i:i+motif_length]
                    for i in range(0, length-remainder, motif_length)]

    def parseOutGaps(self):
        gapless = []
        segments = []
        nongap = re.compile('([^%s]+)' % re.escape("-"))
        for match in nongap.finditer(self._seq):
            segments.append(match.span())
            gapless.append(match.group())
        map = Map(segments, parent_length=len(self)).inverse()
        seq = self.__class__(
            ''.join(gapless),
            Name = self.getName(), Info=self.Info)
        if self.annotations:
            seq.annotations = [a.remappedTo(seq, map) for a in self.annotations]
        return (map, seq)

class ProteinSequence(Sequence):
    """Holds the standard Protein sequence. MolType set in moltype module."""
    pass

class ProteinWithStopSequence(Sequence):
    """Holds the standard Protein sequence, allows for stop codon

    MolType set in moltype module
    """
    pass

class NucleicAcidSequence(Sequence):
    """Base class for DNA and RNA sequences. Abstract."""
    PROTEIN = None #will set in moltype
    CodonAlphabet = None   #will set in moltype
    def reversecomplement(self):
        """Converts a nucleic acid sequence to its reverse complement.
        Synonymn for rc."""
        return self.rc()

    def rc(self):
        """Converts a nucleic acid sequence to its reverse complement."""
        complement = self.MolType.rc(self)
        rc = self.__class__(complement, Name=self.Name, Info=self.Info)
        self._annotations_nucleic_reversed_on(rc)
        return rc

    def _gc_from_arg(self, gc):
        # codon_alphabet is being deprecated in favor of genetic codes.
        if gc is None:
            gc = DEFAULT_GENETIC_CODE
        elif isinstance(gc, (int, basestring)):
            gc = GeneticCodes[gc]
        return gc

    def hasTerminalStop(self, gc=None):
        """Return True if the sequence has a terminal stop codon.

        Arguments:
            - gc: a genetic code"""
        gc = self._gc_from_arg(gc)
        codons = self._seq
        assert len(codons) % 3 == 0
        return codons and gc.isStop(codons[-3:])

    def withoutTerminalStopCodon(self, gc=None):
        gc = self._gc_from_arg(gc)
        codons = self._seq
        assert len(codons) % 3 == 0, "seq length not divisible by 3"
        if codons and gc.isStop(codons[-3:]):
            codons = codons[:-3]
        return self.__class__(codons, Name=self.Name, Info=self.Info)

    def getTranslation(self, gc=None):
        gc = self._gc_from_arg(gc)
        codon_alphabet = self.CodonAlphabet(gc).withGapMotif()
        # translate the codons
        translation = []
        for posn in range(0, len(self._seq)-2, 3):
            orig_codon = self._seq[posn:posn+3]
            resolved = codon_alphabet.resolveAmbiguity(orig_codon)
            trans = []
            for codon in resolved:
                if codon == '---':
                    aa = '-'
                else:
                    assert '-' not in codon
                    aa = gc[codon]
                    if aa == '*':
                        continue
                trans.append(aa)
            if not trans:
                raise ValueError(orig_codon)
            aa = self.PROTEIN.whatAmbiguity(trans)
            translation.append(aa)

        translation = self.PROTEIN.makeSequence(
                Seq=''.join(translation), Name=self.Name)

        return translation

    def getOrfPositions(self, gc=None, atg=False):
        gc = self._gc_from_arg(gc)
        orfs = []
        start = None
        protein = self.getTranslation(gc=gc)
        for (posn, aa) in enumerate(protein):
            posn *= 3
            if aa == '*':
                if start is not None:
                    orfs.append((start,posn))
                start = None
            else:
                if start is None:
                    if (not atg) or gc.isStart(self[posn:posn+3]):
                        start = posn
        if start is not None:
            orfs.append((start, posn+3))
        return orfs

    def toRna(self):
        """Returns copy of self as RNA."""
        return RnaSequence(self)

    def toDna(self):
        """Returns copy of self as DNA."""
        return DnaSequence(self)

class DnaSequence(NucleicAcidSequence):

    def getColourScheme(self, colours):
        return {
                'A': colours.black,
                'T': colours.red,
                'C': colours.blue,
                'G': colours.green,
                }

    def _seq_filter(self, seq):
        """Converts U to T."""
        return seq.replace('u','t').replace('U','T')

class RnaSequence(NucleicAcidSequence):

    def getColourScheme(self, colours):
        return {
                'A': colours.black,
                'U': colours.red,
                'C': colours.blue,
                'G': colours.green,
                }

    def _seq_filter(self, seq):
        """Converts T to U."""
        return seq.replace('t','u').replace('T','U')

class ABSequence(Sequence):
    """Used for two-state modeling; MolType set in moltypes."""
    pass

class ByteSequence(Sequence):
    """Used for storing arbitrary bytes."""
    def __init__(self, Seq='', Name=None, Info=None, check=False, \
            preserve_case=True):
        return super(ByteSequence, self).__init__(Seq, Name=Name, Info=Info, \
                check=check, preserve_case=preserve_case)

class ModelSequenceBase(object):
    """Holds the information for a non-degenerate sequence. Mutable.

    A ModelSequence is an array of indices of symbols, where those symbols are
    defined by an Alphabet. This representation of Sequence is convenient for
    counting symbol frequencies or tuple frequencies, remapping data (e.g. for
    reverse-complement), looking up model parameters, etc. Its main drawback is
    that the sequences can no longer be treated as strings, and conversion
    to/from strings can be fairly time-consuming. Also, any symbol not in the
    Alphabet cannot be represented at all.

    A sequence can have a Name, which will be used for output in formats
    such as FASTA.

    A sequence Class has an alphabet (which can be overridden in instances
    where necessary), a delimiter used for string conversions, a LineWrap
    for wrapping characters into lines for e.g. FASTA output.

    Note that a ModelSequence _must_ have an Alphabet, not a MolType,
    because it is often important to store just a subset of the possible
    characters (e.g. the non-degenerate bases) for modeling purposes.
    """
    Alphabet = None     #REPLACE IN SUBCLASSES
    MolType = None      #REPLACE IN SUBCLASSES
    Delimiter = ''      #Used for string conversions
    LineWrap = 80       #Wrap sequences at 80 characters by default.

    def __init__(self, data='', Alphabet=None, Name=None, Info=None, \
        check='ignored'):
        """Initializes sequence from data and alphabet.

        WARNING: Does not validate the data or alphabet for compatibility.
        This is for speed. Use isValid() to check whether the data
        is consistent with the alphabet.

        WARNING: If data has name and/or Info, gets ref to same object rather
        than copying in each case.
        """
        if Name is None and hasattr(data, 'Name'):
            Name = data.Name
        if Info is None and hasattr(data, 'Info'):
            Info = data.Info
        #set the label
        self.Name = Name
        #override the class alphabet if supplied
        if Alphabet is not None:
            self.Alphabet = Alphabet
        #if we haven't already set self._data (e.g. in a subclass __init__),
        #guess the data type and set it here
        if not hasattr(self, '_data'):
            #if data is a sequence, copy its data and alphabet
            if isinstance(data, ModelSequence):
                self._data = data._data
                self.Alphabet = data.Alphabet
            #if it's an array
            elif type(data) == ARRAY_TYPE:
                self._data = data
            else:    #may be set in subclass init
                self._from_sequence(data)

        self.MolType = self.Alphabet.MolType
        self.Info = Info

    def __getitem__(self, *args):
        """__getitem__ returns char or slice, as same class."""
        if len(args) == 1 and not isinstance(args[0], slice):
            result = array([self._data[args[0]]])
        else:
            result = self._data.__getitem__(*args)
        return self.__class__(result)

    def __cmp__(self, other):
        """__cmp__ compares based on string"""
        return cmp(str(self), other)

    def _from_sequence(self, data):
        """Fills self using the values in data, via the Alphabet."""
        if self.Alphabet:
            self._data = array(self.Alphabet.toIndices(data), \
                self.Alphabet.ArrayType)
        else:
            self._data = array(data)

    def __str__(self):
        """Uses alphabet to convert self to string, using delimiter."""
        if hasattr(self.Alphabet, 'toString'):
            return self.Alphabet.toString(self._data)
        else:
            return self.Delimiter.join(map(str, \
                self.Alphabet.fromIndices(self._data)))

    def __len__(self):
        """Returns length of data."""
        return len(self._data)

    def toFasta(self, make_seqlabel=None):
        """Return string of self in FASTA format, no trailing newline

        Arguments:
            - make_seqlabel: callback function that takes the seq object and
              returns a label str
        """
        return fasta_from_sequences([self], make_seqlabel = make_seqlabel,
                        line_wrap=self.LineWrap)

    def toPhylip(self, name_len=28, label_len=30):
        """Return string of self in one line for PHYLIP, no newline.

        Default: max name length is 28, label length is 30.
        """
        return str(self.Name)[:name_len].ljust(label_len) + str(self)

    def isValid(self):
        """Checks that no items in self are out of the Alphabet range."""
        return self._data == self._data.clip(m, 0, len(self.Alphabet)-1)

    def toKwords(self, k, overlapping=True):
        """Turns sequence into sequence of its k-words.

        Just returns array, not Sequence object."""
        alpha_len = len(self.Alphabet)
        seq = self._data
        seq_len = len(seq)
        if overlapping:
            num_words = seq_len - k + 1
        else:
            num_words, remainder = divmod(seq_len, k)
            last_index = num_words * k
        result = zeros(num_words)
        for i in range(k):
            if overlapping:
                curr_slice = seq[i:i+num_words]
            else:
                curr_slice = seq[i:last_index+i:k]
            result *= alpha_len
            result += curr_slice
        return result

    def __iter__(self):
        """iter returns characters of self, rather than slices."""
        if hasattr(self.Alphabet, 'toString'):
            return iter(self.Alphabet.toString(self._data))
        else:
            return iter(self.Alpabet.fromIndices(self._data))

    def tostring(self):
        """tostring delegates to self._data."""
        return self._data.tostring()

    def gaps(self):
        """Returns array containing 1 where self has gaps, 0 elsewhere.

        WARNING: Only checks for standard gap character (for speed), and
        does not check for ambiguous gaps, etc.
        """
        return self._data == self.Alphabet.GapIndex

    def nongaps(self):
        """Returns array contining 0 where self has gaps, 1 elsewhere.

        WARNING: Only checks for standard gap character (for speed), and
        does not check for ambiguous gaps, etc.
        """
        return self._data != self.Alphabet.GapIndex

    def regap(self, other, strip_existing_gaps=False):
        """Inserts elements of self into gaps specified by other.

        WARNING: Only checks for standard gap character (for speed), and
        does not check for ambiguous gaps, etc.
        """
        if strip_existing_gaps:
            s = self.degap()
        else:
            s = self
        c = self.__class__
        a = self.Alphabet.Gapped
        result = zeros(len(other),a.ArrayType)+a.GapIndex
        put(result, nonzero(other.nongaps()), s._data)
        return c(result)

    def degap(self):
        """Returns ungapped copy of self, not changing alphabet."""
        if not hasattr(self.Alphabet, 'Gap') or self.Alphabet.Gap is None:
            return self.copy()
        d = take(self._data, nonzero(logical_not(self.gapArray()))[0])
        return self.__class__(d, Alphabet=self.Alphabet, Name=self.Name, \
            Info=self.Info)

    def copy(self):
        """Returns copy of self, always separate object."""
        return self.__class__(self._data.copy(), Alphabet=self.Alphabet, \
            Name=self.Name, Info=self.Info)

    def __contains__(self, item):
        """Returns true if item in self (converts to strings)."""
        return item in str(self)

    def disambiguate(self, *args, **kwargs):
        """Disambiguates self using strings/moltype. Should recode if demand."""
        return self.__class__(self.MolType.disambiguate(str(self), \
            *args,**kwargs))

    def distance(self, other, function=None, use_indices=False):
        """Returns distance between self and other using function(i,j).

        other must be a sequence.

        function should be a function that takes two items and returns a
        number. To turn a 2D matrix into a function, use
        cogent.util.miscs.DistanceFromMatrix(matrix).

        use_indices: if False, maps the indices onto items (e.g. assumes
        function relates the characters). If True, uses the indices directly.

        NOTE: Truncates at the length of the shorter sequence.

        Note that the function acts on two _elements_ of the sequences, not
        the two sequences themselves (i.e. the behavior will be the same for
        every position in the sequences, such as identity scoring or a function
        derived from a distance matrix as suggested above). One limitation of
        this approach is that the distance function cannot use properties of
        the sequences themselves: for example, it cannot use the lengths of the
        sequences to normalize the scores as percent similarities or percent
        differences.

        If you want functions that act on the two sequences themselves, there
        is no particular advantage in making these functions methods of the
        first sequences by passing them in as parameters like the function
        in this method. It makes more sense to use them as standalone functions.
        The factory function cogent.util.transform.for_seq is useful for
        converting per-element functions into per-sequence functions, since it
        takes as parameters a per-element scoring function, a score aggregation
        function, and a normalization function (which itself takes the two
        sequences as parameters), returning a single function that combines
        these functions and that acts on two complete sequences.
        """
        if function is None:
            #use identity scoring
            shortest = min(len(self), len(other))
            if not hasattr(other, '_data'):
                other = self.__class__(other)
            distance = (self._data[:shortest] != other._data[:shortest]).sum()
        else:
            distance = 0
            if use_indices:
                self_seq = self._data
                if hasattr(other, '_data'):
                    other_seq = other._data
            else:
                self_seq = self.Alphabet.fromIndices(self._data)
                if hasattr(other, '_data'):
                    other_seq = other.Alphabet.fromIndices(other._data)
                else:
                    other_seq = other
            for first, second in zip(self_seq, other_seq):
                distance += function(first, second)
        return distance

    def matrixDistance(self, other, matrix, use_indices=False):
        """Returns distance between self and other using a score matrix.

        if use_indices is True (default is False), assumes that matrix is
        an array using the same indices that self uses.

        WARNING: the matrix must explicitly contain scores for the case where
        a position is the same in self and other (e.g. for a distance matrix,
        an identity between U and U might have a score of 0). The reason the
        scores for the 'diagonals' need to be passed explicitly is that for
        some kinds of distance matrices, e.g. log-odds matrices, the 'diagonal'
        scores differ from each other. If these elements are missing, this
        function will raise a KeyError at the first position that the two
        sequences are identical.
        """
        return self.distance(other, DistanceFromMatrix(matrix))

    def shuffle(self):
        """Returns shuffled copy of self"""
        return self.__class__(permutation(self._data), Info=self.Info)

    def gapArray(self):
        """Returns array of 0/1 indicating whether each position is a gap."""
        gap_indices = []
        a = self.Alphabet
        for c in self.MolType.Gaps:
            if c in a:
                gap_indices.append(a.index(c))
        gap_vector = None
        for i in gap_indices:
            if gap_vector is None:
                gap_vector = self._data == i
            else:
                gap_vector = logical_or(gap_vector, self._data == i)
        return gap_vector

    def gapIndices(self):
        """Returns array of indices of gapped positions in self."""
        return self.gapArray().nonzero()[0]

    def fracSameGaps(self, other):
        """Returns fraction of positions where gaps match other's gaps.
        """
        if not other:
            return 0
        self_gaps = self.gapArray()
        if hasattr(other, 'gapArray'):
            other_gaps = other.gapArray()
        elif hasattr(other, 'gapVector'):
            other_gaps = array(other.gapVector())
        else:
            other_gaps = array(self.MolType.gapVector(other))
        min_len = min(len(self), len(other))
        self_gaps, other_gaps = self_gaps[:min_len], other_gaps[:min_len]
        return (self_gaps == other_gaps).sum()/float(min_len)

class ModelSequence(ModelSequenceBase, SequenceI):
    """ModelSequence provides an array-based implementation of Sequence.

    Use ModelSequenceBase if you need a stripped-down, fast implementation.
    ModelSequence implements everything that SequenceI implements.

    See docstrings for ModelSequenceBase and SequenceI for information about
    these respective classes.
    """
    def stripBad(self):
        """Returns copy of self with bad chars excised"""
        valid_indices = self._data < len(self.Alphabet)
        result = compress(valid_indices, self._data)
        return self.__class__(result, Info=self.Info)

    def stripBadAndGaps(self):
        """Returns copy of self with bad chars and gaps excised."""
        gap_indices = map(self.Alphabet.index, self.MolType.Gaps)
        valid_indices = self._data < len(self.Alphabet)
        for i in gap_indices:
            valid_indices -= self._data == i
        result = compress(valid_indices, self._data)
        return self.__class__(result, Info=self.Info)

    def stripDegenerate(self):
        """Returns copy of self without degenerate symbols.

        NOTE: goes via string intermediate because some of the algorithms
        for resolving degenerates are complex. This could be optimized if
        speed becomes critical.
        """
        return self.__class__(self.MolType.stripDegenerate(str(self)), \
            Info=self.Info)

    def countGaps(self):
        """Returns count of gaps in self."""
        return self.gapArray().sum()

    def gapVector(self):
        """Returns list of bool containing whether each pos is a gap."""
        return map(bool, self.gapArray())

    def gapList(self):
        """Returns list of gap indices."""
        return list(self.gapIndices())

    def gapMaps(self):
        """Returns dicts mapping gapped/ungapped positions."""
        nongaps = logical_not(self.gapArray())
        indices = arange(len(self)).compress(nongaps)
        new_indices = arange(len(indices))
        return dict(zip(new_indices, indices)), dict(zip(indices, new_indices))

    def firstGap(self):
        """Returns position of first gap, or None."""
        a = self.gapIndices()
        try:
            return a[0]
        except IndexError:
            return None

    def isGapped(self):
        """Returns True of sequence contains gaps."""
        return len(self.gapIndices())

    def MW(self, *args, **kwargs):
        """Returns molecular weight.

        Works via string intermediate: could optimize using array of MW if
        speed becomes important.
        """
        return self.MolType.MW(str(self), *args, **kwargs)

    def fracSimilar(self, other, similar_pairs):
        """Returns fraction of positions where self[i] is similar to other[i].

        similar_pairs must be a dict such that d[(i,j)] exists if i and j are
        to be counted as similar. Use PairsFromGroups in cogent.util.misc to
        construct such a dict from a list of lists of similar residues.

        Truncates at the length of the shorter sequence.

        Note: current implementation re-creates the distance function each
        time, so may be expensive compared to creating the distance function
        using for_seq separately.

        Returns 0 if one sequence is empty.

        NOTE: goes via string intermediate, could optimize using array if
        speed becomes important. Note that form of similar_pairs input would
        also have to change.
        """
        if not self or not other:
            return 0.0

        return for_seq(f = lambda x, y: (x,y) in similar_pairs, \
            normalizer=per_shortest)(str(self), str(other))

class ModelNucleicAcidSequence(ModelSequence):
    """Abstract class defining ops for codons, translation, etc."""

    def toCodons(self):
        """Returns copy of self in codon alphabet. Assumes ungapped."""
        alpha_len = len(self.Alphabet)
        return ModelCodonSequence(alpha_len*(\
            alpha_len*self._data[::3] + self._data[1::3]) + self._data[2::3], \
            Name=self.Name, Alphabet=self.Alphabet.Triples)

    def complement(self):
        """Returns complement of sequence"""
        return self.__class__(self.Alphabet._complement_array.take(self._data),\
            Info=self.Info)

    def rc(self):
        """Returns reverse-complement of sequence"""
        comp = self.Alphabet._complement_array.take(self._data)
        return self.__class__(comp[::-1], Info=self.Info)

    def toRna(self):
        """Returns self as RNA"""
        return ModelRnaSequence(self._data)

    def toDna(self):
        """Returns self as DNA"""
        return ModelDnaSequence(self._data)

class ModelRnaSequence(ModelNucleicAcidSequence):
    MolType = None  #set to RNA in moltype.py
    Alphabet = None #set to RNA.Alphabets.DegenGapped in moltype.py

    def __init__(self, data='', *args, **kwargs):
        """Returns new ModelRnaSequence, converting T -> U"""
        if hasattr(data, 'upper'):
            data = data.upper().replace('T','U')
        return super(ModelNucleicAcidSequence, self).__init__(data, \
            *args, **kwargs)

class ModelDnaSequence(ModelNucleicAcidSequence):
    MolType = None  #set to DNA in moltype.py
    Alphabet = None #set to DNA.Alphabets.DegenGapped in moltype.py

    def __init__(self, data='', *args, **kwargs):
        """Returns new ModelRnaSequence, converting U -> T"""
        if hasattr(data, 'upper'):
            data = data.upper().replace('U','T')
        return super(ModelNucleicAcidSequence, self).__init__(data, \
            *args, **kwargs)

class ModelCodonSequence(ModelSequence):
    """Abstract base class for codon sequences, incl. string conversion."""
    SequenceClass = ModelNucleicAcidSequence
    def __str__(self):
        """Joins triplets together as string."""
        return self.Delimiter.join(map(''.join, \
            self.Alphabet.fromIndices(self._data)))

    def _from_string(self, s):
        """Reads from a raw string, rather than a DnaSequence."""
        s = s.upper().replace('U','T')    #convert to uppercase DNA
        d = self.SequenceClass(s, \
            Alphabet=self.Alphabet.SubEnumerations[0])
        self._data = d.toCodons()._data

    def __init__(self, data='', Alphabet=None, Name=None, Info=None):
        """Override __init__ to handle init from string."""
        if isinstance(data, str):
            self._from_string(data)
        ModelSequence.__init__(self, data, Alphabet, Name, Info=Info)

    def toCodons(self):
        """Converts self to codons -- in practice, just returns self.

        Supports interface of other NucleicAcidSequences."""
        return self

    def toDna(self):
        """Returns a ModelDnaSequence from the data in self"""
        unpacked = self.Alphabet.unpackArrays(self._data)
        result = zeros((len(self._data),3))
        for i, v in enumerate(unpacked):
            result[:,i] = v
        return ModelDnaSequence(ravel(result), Name=self.Name)

    def toRna(self):
        """Returns a ModelDnaSequence from the data in self."""
        unpacked = self.Alphabet.unpackArrays(self._data)
        result = zeros((len(self._data),3))
        for i, v in enumerate(unpacked):
            result[:,i] = v
        return ModelRnaSequence(ravel(result), Name=self.Name)

class ModelDnaCodonSequence(ModelCodonSequence):
    """Holds non-degenerate DNA codon sequence."""
    Alphabet = None #set to DNA.Alphabets.Base.Triples in moltype.py
    SequenceClass = ModelDnaSequence

class ModelRnaCodonSequence(ModelCodonSequence):
    """Holds non-degenerate DNA codon sequence."""
    Alphabet = None #set to RNA.Alphabets.Base.Triples in motype.py
    SequenceClass = ModelRnaSequence

    def _from_string(self, s):
        """Reads from a raw string, rather than a DnaSequence."""
        s = s.upper().replace('T','U')    #convert to uppercase DNA
        d = self.SequenceClass(s, \
            Alphabet=self.Alphabet.SubEnumerations[0])
        self._data = d.toCodons()._data

class ModelProteinSequence(ModelSequence):
    MolType = None  #set to PROTEIN in moltype.py
    Alphabet = None #set to PROTEIN.Alphabets.DegenGapped in moltype.py

class ModelProteinWithStopSequence(ModelSequence):
    MolType = None #set to PROTEIN_WITH_STOP in moltype.py
    Alphabet= None #set to PROTEIN_WITH_STOP.Alphabets.DegenGapped in moltype.py

max_stars_repo_name: sauloal/cnidaria

max_issues_repo_name: sauloal/cnidaria

max_forks_repo_name: sauloal/cnidaria

reason: from numpy