text:
import numpy as np
import seqlib
import random
import argparse
import sys

"""
parser = argparse.ArgumentParser(description="Virterbi gene finder")
parser.add_argument("--file", required=True, type=str, metavar='<path>')
arg = parser.parse_args()

myfasta = seqlib.read_fasta(arg.file)

seq=myfasta[1]
"""

seq = " GGGGGGAAAAAAAA"

# probabilities
intron_prob = {"A": 0.3, "T": 0.3, "C": 0.2, "G": 0.2}
exon_prob = {"G": 0.3, "C": 0.3, "A": 0.2, "T": 0.2}
transition_prob = {"EE": 0.6, "EI": 0.4, "II": 0.7, "IE": 0.3}

length = len(seq)

row1 = [None] * length
row2 = [None] * length
matrix = [row1, row2]
matrix[0][0] = ("N", 0.5)
matrix[1][0] = ("N", 0.5)

def exon_score(nt, m, i):
    # pass in transition prob? dont make it global
    L = exon_prob[nt] * m[0][i - 1][1] * transition_prob["EE"]
    D = exon_prob[nt] * m[1][i - 1][1] * transition_prob["EI"]
    if L > D:
        return ("L", L)
    elif D > L:
        return ("D", L)
    elif D == L:
        print("coin toss")
        if random.randint(0, 1) == 0:
            return ("L", L)
        elif random.randint(0, 1) == 1:
            return ("D", D)

def intron_score(nt, m, i):
    L = intron_prob[nt] * m[1][i - 1][1] * transition_prob["II"]
    D = intron_prob[nt] * m[0][i - 1][1] * transition_prob["IE"]
    if L > D:
        return ("L", L)
    elif D > L:
        return ("D", L)
    elif D == L:
        if random.randint(0, 1) == 0:
            return ("L", L)
        elif random.randint(0, 1) == 1:
            return ("D", D)

for i in range(1, length):
    nt = seq[i]
    matrix[0][i] = exon_score(nt, matrix, i)
    matrix[1][i] = intron_score(nt, matrix, i)

for i in matrix:
    print(i)


text:
import numpy as np

from bbdob import ObjectiveBase
from bbdob.utils import packbits

class NKLandscape(ObjectiveBase):
    """
    A class of NK-landscape.
    The NK-landscape has a parameter k which specifies that how many bits each bit depends on.
    The evaluation value of a bit is obtained from a lookup table by using a
    combination of values of k+1 bits and the evaluation value of an individual
    is calculated by averaging the evaluation values of all bits.
    Here, the k bits and the lookup table are randomly generated in advance.

    Reference:
    http://ncra.ucd.ie/wp-content/uploads/2020/08/SocialLearning_GECCO2019.pdf
    """
    def __init__(self, dim, k=2, seed=1, minimize=True):
        """
        Parameters
        ----------
        k : int, default 2
            A user parameter which determines the ruggedness of the problem.
            How many bits each bit depends on.
        seed : int, default 1
            A random number seed.
            The seed is required to determine the k bits and
            to generate the lookup table.
        """
        super(NKLandscape, self).__init__(dim, minimize=minimize)
        assert 0 < k < dim
        self.k = k
        if seed is not None:
            next_seed = np.random.randint(0, 2**31)
            np.random.seed(seed)
        self.eval_table = self.get_evaluation_table()
        self.neighbor = self.get_neighbor()
        if seed is not None:
            np.random.seed(next_seed)

    def evaluate(self, c):
        c = self._check_shape(c)
        evals = np.zeros(c.shape[0])
        for d in range(self.dim):
            bits = np.concatenate([c[:, d][:, np.newaxis], c[:, self.neighbor[d]]], axis=1)
            evals += self.eval_table[d][packbits(bits)]
        evals /= self.dim
        evals = -evals if self.minimize else evals
        info = {}
        return evals, info

    def get_evaluation_table(self):
        """
        Generate a lookup table.

        Returns
        -------
        numpy.ndarray
            Lookup table to calculate the evaluation value.
        """
        return np.array([
                np.random.choice(np.arange(2**(self.k+1)), 2**(self.k+1), replace=False) / (2**(self.k+1) - 1)
                for _ in range(self.dim)
            ])

    def get_neighbor(self):
        """
        Determine the k bits for each bit.

        Returns
        -------
        numpy.ndarray
            List of each bit that depends on which bits.
        """
        neighbor = np.zeros((self.dim, self.dim), dtype=np.bool)
        for i in range(self.dim):
            k = 0
            while k < self.k:
                n = np.random.choice(self.dim)
                if i == n or neighbor[i, n]:
                    continue
                neighbor[i, n] = True
                k += 1
        return neighbor

    def __str__(self):
        sup_str = "    " + super(NKLandscape, self).__str__().replace("\n", "\n    ")
        return 'NK-landscape(\n' \
               '{}\n' \
               '    k: {}\n' \
               ')\n'.format(sup_str, self.k)

ext: py

reason: import numpy


text:
"""Module for linear autonomous pool models."""
from __future__ import division

from sympy import symbols, Matrix, exp, ones, diag, simplify, eye, log
from math import factorial, sqrt
import numpy as np
from scipy.linalg import expm
from scipy.optimize import brentq

from . import phase_type
from .dtmc import DTMC
from .helpers import entropy

#############################################
# Linear autonomous compartment model class #
# d/dt x(t) = Bx(t) + u                     #
#############################################

def _age_vector_dens(u, B, Qt):
    """Return the (symbolic) probability density vector of the compartment ages.

    Args:
        u (SymPy dx1-matrix): external input vector
        B (SymPy dxd-matrix): compartment matrix
        Qt (SymPy dxd-matrix): Qt = :math:`e^{t\\,B}`

    Returns:
        SymPy dx1-matrix: probability density vector of the compartment ages
        :math:`f_a(y) = (X^\\ast)^{-1}\\,e^{y\\,B}\\,u`
    """
    xss = -B.inv()*u
    X = diag(*xss)

    return X.inv()*Qt*u

def _age_vector_cum_dist(u, B, Qt):
    """Return the (symbolic) cumulative distribution function vector of the
    compartment ages.

    Args:
        u (SymPy dx1-matrix): external input vector
        B (SymPy dxd-matrix): compartment matrix
        Qt (SymPy dxd-matrix): Qt = :math:`e^{t\\,B}`

    Returns:
        SymPy dx1-matrix: cumulative distribution function vector of the
        compartment ages

        :math:`f_a(y)=(X^\\ast)^{-1}\\,B^{-1}\\,(e^{y\\,B}-I)\\,u`
    """
    d = B.rows
    xss = -B.inv()*u
    X = diag(*xss)

    return X.inv()*B.inv()*(Qt-eye(d))*u

def _age_vector_nth_moment(u, B, n):
    """Return the (symbolic) vector of nth moments of the compartment ages.

    Args:
        u (SymPy dx1-matrix): external input vector
        B (SymPy dxd-matrix): compartment matrix
        n (positive int): order of the moment

    Returns:
        SymPy dx1-matrix: vector of nth moments of the compartment ages
        :math:`\\mathbb{E}[a^n]=(-1)^n\\,n!\\,X^\\ast)^{-1}\\,B^{-n}\\,x^\\ast`

    See Also:
        :func:`_age_vector_exp`: Return the (symbolic) vector of expected values
        of the compartment ages.
    """
    xss = -B.inv()*u
    X = diag(*xss)

    return (-1)**n*factorial(n)*X.inv()*(B.inv()**n)*xss

def _age_vector_exp(u, B):
    """Return the (symbolic) vector of expected values of the compartment ages.

    Args:
        u (SymPy dx1-matrix): external input vector
        B (SymPy dxd-matrix): compartment matrix

    Returns:
        SymPy dx1-matrix: vector of expected values of the compartment ages
        :math:`\\mathbb{E}[a] = -(X^\\ast)^{-1}\\,B^{-1}\\,x^\\ast`

    See Also:
        :func:`_age_vector_nth_moment`: Return the (symbolic) vector of
        ``n`` th moments of the compartment ages.
    """
    return _age_vector_nth_moment(u, B, 1)

def _age_vector_variance(u, B):
    """Return the (symbolic) vector of variances of the compartment ages.

    Args:
        u (SymPy dx1-matrix): external input vector
        B (SymPy dxd-matrix): compartment matrix

    Returns:
        SymPy dx1-matrix: vector of variances of the compartment ages
        :math:`\\sigma^2(a) = \\mathbb{E}[a^2] - (\\mathbb{E}[a])^2`
        component-wise

    See Also:
        | :func:`_age_vector_exp`: Return the (symbolic) vector of expected
            values of the compartment ages.
        | :func:`_age_vector_nth_moment`: Return the (symbolic) vector of
            ``n`` th moments of the compartment ages.
    """
    sv = _age_vector_nth_moment(u, B, 2)
    ev = _age_vector_exp(u, B)
    vl = [sv[i] - ev[i]**2 for i in range(sv.rows)]

    return Matrix(sv.rows, 1, vl)

def _age_vector_sd(u, B):
    """Return the (symbolic) vector of standard deviations of the
    compartment ages.

    Args:
        u (SymPy dx1-matrix): external input vector
        B (SymPy dxd-matrix): compartment matrix

    Returns:
        SymPy dx1-matrix: vector of standard deviations of the compartment ages
        :math:`\\sigma(a) = \\sqrt{\\sigma^2(a)}` component-wise

    See Also:
        :func:`_age_vector_variance`: Return the (symbolic) vector of variances
        of the compartment ages.
    """
    sdl = [sqrt(e) for e in _age_vector_variance(u, B)]

    return Matrix(len(sdl), 1, sdl)

def _generalized_inverse_CDF(CDF, u, start_dist=1e-4, tol=1e-8):
    """Compute generalized inverse of a cumulative distribution function.

    Can be used for quantile computation or generation of random variables

    Args:
        CDF (Python function): cumulative distribution function
        start_dist (float): how far right from 0 to start looking for the
            bisection interval,
            defaults to 1e-4
        tol (float): tolerance for brentq algorithm of numerical root search,
            defaults to 1e-8

    Returns:
        int: smallest :math:`y` such that :math:`\\operatorname{CDF}(y)\\geq u`
    """
    def f(a):
        res = u-CDF(a)
        return res

    x1 = start_dist

    # go so far to the right such that CDF(x1)>u, the bisect in interval [0, x1]
    y1 = f(x1)
    while y1 >= 0:
        x1 = x1*2 + 0.1
        y1 = f(x1)

    if np.isnan(y1):
        res = np.nan
    else:
        res = brentq(f, 0, x1, xtol=tol)

    return res

def create_random_probability_vector(d: int, p: float) -> np.ndarray:
    """Create a random probability vector.

    Args:
        d: dimension of the random vector
        p: probability of setting elements to nonzero value

    Returns:
        random probability vector `v` s.t.
        - :math:`v_i \geq 0`
        - :math:`\mathbb{P}(v_i>0) = p`
        - :math:`\sum_i v_i=1`
    """
    v = np.random.binomial(1, p, d)
    v = v * np.random.uniform(0, 1, d)
    if v.sum():
        v = v / v.sum()
        return np.random.permutation(v)
    else:
        # ensure that at least one entry is greater than 0
        c = np.random.choice(np.arange(d))
        v[c] = 1.0
        return v

def create_random_compartmental_matrix(d: int, p: float) -> np.ndarray:
    r"""Create a random invertible compartmental matrix.

    Args:
        d: dimension of the matrix (number of pools)
        p: probability of existence of non-necessary connections

    Returns:
        random invertible compartmental matrix `B` s.t.

        - all diagonal entries are nonpositive
        - all off-diagonal entries are nonnegative
        - all column sums are nonpositive
        - :math:`B` is invertible
        - :math:`-B_{ii} <= 1`
        - :math:`\mathbb{P}(B_{ij}>0) = p` for :math:`i \neq j`
        - :math:`\mathbb{P}(z_j)>0) = p`, where :math:`z_j = -\sum_i B_{ij}`
    """
    V = np.zeros((d+1, d+1))

    # add pools step by step, always keep the new pools connected to the
    # previous smaller system
    # pool 0 is the output pool

    # build adjacency matrix
    for n in range(1, d+1):
        # random connections to smaller output-connected system
        V[:n, n] = np.random.binomial(1, p, n)

        # random connections from smaller output-connected system
        V[n, :n] = np.random.binomial(1, p, n)

        # ensure connection to smaller output-connected system
        c = np.random.choice(np.arange(n))
        V[c, n] = 1

    # create B from adjacency matrix,
    # repeat until det(B) is significantly different from 0
    x = 0
    while x < 1e-08:
        # make random speeds from adjacencies
        # (1 - uniform) to make sure the value will not be 0
        # with a 0 value an essential connection could get lost
        B = V * (1 - np.random.uniform(0, 1, (d+1)**2).reshape((d+1, d+1)))

        # build diagonals
        for j in range(B.shape[1]):
            B[j, j] = -B[:, j].sum()

        # ignore output pool 0
        B = B[1:, 1:]

        x = np.abs(np.linalg.det(B))
    return B

############################################################################

class Error(Exception):
    """Generic error occuring in this module."""
    pass

class NonInvertibleCompartmentalMatrix(Exception):
    pass

class LinearAutonomousPoolModel(object):
    """General class of linear autonomous compartment models.

    :math:`\\frac{d}{dt} x(t) = B\\,x(t) + u`

    Notes:
        - symbolic matrix exponential Qt = :math:`e^{t\\,B}`
            cannot be computed automatically
        - for symbolic computations it has to be given manually: model.Qt = ...
        - otherwise only numerical computations possible
        - symbolical computations can take very long, in particular
          for complicated systems. An enforced purely numerical
          treatment could then be the right choice; choose
          ``force_numerical=True``
        - number of pools denoted by :math:`d`
        - steady state vector denoted by
          :math:`x^\\ast=-B^{-1}\\,u`
        - normalized steady state vector denoted by
          :math:`\\eta=\\frac{x^\\ast}{\\|x^\\ast\\|}`
        - norm of a vector :math:`v` given by
          :math:`\\|\\mathbf{v}\\| = \\sum\\limits_{i=1}^d |v_i|`

    Attributes:
        u (SymPy dx1-matrix): The model's external input vector.
        B (SymPy dxd-matrix): The model's compartment matrix.
        Qt (SymPy dxd-matrix): Qt = :math:`e^{t\\,B}`
    """

    def __init__(self, u, B, force_numerical=False):
        """Return a linear autonomous compartment model with external
        inputs u and (invertible) compartment matrix B.

        Symbolical computations can take very long, in particular
        for complicated systems. An enforced purely numerical
        treatment could then be the right choice.

        Args:
            u (SymPy dx1-matrix): external input vector
            B (SymPy dxd-matrix): invertible compartment matrix
            force_numerical (boolean, optional):
                if True do not try symbolical computations,
                defaults to False

        Remark:
            While there are compartmental
            systems that have singular matrices (systems with traps), most of the
            methods of this class are only correct for invertible B.
            We therefore reject singular matrices alltogether.
        """
        # cover one-dimensional input
        if (not hasattr(u, 'is_Matrix')) or (not u.is_Matrix):
            u = Matrix(1, 1, [u])
        if (not hasattr(B, 'is_Matrix')) or (not B.is_Matrix):
            B = Matrix(1, 1, [B])

        try:
            B.inv()
        except ValueError as e:
            print(B)
            raise NonInvertibleCompartmentalMatrix("""
            The matrix B is not invertible.
            While there are compartmental systems that have singular matrices
            (systems with traps), most of the methods of this class are only
            correct for invertible B.
            We therefore reject singular matrices alltogether.
            """)

        self.B = B
        self.u = u
        # compute matrix exponential if no symbols are involved
        if (not force_numerical) and ((B.is_Matrix) and (len(B.free_symbols) == 0)):
            t = symbols('t')
            self.Qt = exp(t*B)

    @classmethod
    def from_random(cls, d: int, p: float):
        """Create a random compartmental system.

        Args:
            d: dimension of the matrix (number of pools)
            p: probability of having a connection between two pools
                and of nonzero value in input vector

        Returns:
            randomly generated compartmental system

            - `beta`: from :func:`create_random_probability_vector`
            - `B: from :func:`~create_random_compartmental_matrix`
        """
        beta = Matrix(create_random_probability_vector(d, p))
        B = Matrix(create_random_compartmental_matrix(d, p))

        return cls(beta, B, force_numerical=True)

    # private methods

    def _get_Qt(self, x):
        """Return matrix exponential of :math:`B` symbolically
        if possible, or numerically.

        Args:
            x (nonnegative):
            time at which the matrix exponential is to be evaluated
            None: purely symbolic treatment
            nonnegative value: symbolic treatment at time x if possible,
                otherwise purely numeric treatment

        Returns:
            Sympy or NumPy dxd-matrix: :math:`e^{x\\,B}

        Raises:
            Error: If purely symbolic treatment is intended by no symbolic
                matrix exponential is available.
        """
        if x is None:
            # purely symbolic case
            if not hasattr(self, 'Qt'):
                raise(Error(
                    'No matrix exponential given for symbolic calculations'))

            Qt = self.Qt
        else:
            # numerical case
            if hasattr(self, 'Qt'):
                # if self.Qt exists, calculate symbolically and substitute t by
                # time
                t = symbols('t')
                Qt = self.Qt.subs({t: x})
            else:
                # purely numerical calculation
                B = self.B
                D = np.array([[B[i,j] for j in range(B.cols)]
                        for i in range(B.rows)], dtype='float64') * float(x)
                Qt = expm(D)

        return Qt

    # public methods

    @property
    def beta(self):
        """Return the initial distribution of the according Markov chain.

        Returns:
            SymPy or numerical dx1-matrix:
                :math:`\\beta = \\frac{u}{\\|u\\|}`
        """
        return self.u/sum([e for e in self.u])

    @property
    def xss(self):
        """Return the (symbolic) steady state vector.

        Returns:
            SymPy or numerical dx1-matrix:
                :math:`x^\\ast = -B^{-1}\\,u`
        """
        return -self.B.inv()*self.u

    @property
    def eta(self):
        """Return the initial distribution of the Markov chain according to
        system age.

        Returns:
            SymPy or numerical dx1-matrix:
                :math:`\\eta = \\frac{x^\\ast}{\\|x^\\ast\\|}`
        """
        return self.xss/sum([e for e in self.xss])

    # transit time

    def T_cum_dist_func(self, time=None):
        """Return the cumulative distribution function of the transit time.

        Args:
            time (nonnegative, optional):
                time at which :math:`F_T` is to be evaluated,
                defaults to None: purely symbolic treatment

        Returns:
            SymPy expression or numerical value: cumulative distribution
            function of the transit time (evaluated at time)

        See Also:
            :func:`.phase_type.cum_dist_func`: Return the (symbolic) cumulative
            distribution function of phase-type.
        """
        Qt = self._get_Qt(time)

        return phase_type.cum_dist_func(self.beta, self.B, Qt)

    def T_density(self, time=None):
        """Return the probability density function of the transit time.

        Args:
            time (nonnegative, optional):
                time at which :math:`f_T` is to be evaluated,
                defaults to None: purely symbolic treatment

        Returns:
            SymPy expression or numerical value: probability density
            function of the transit time (evaluated at time)

        See Also:
            :func:`.phase_type.density`: Return the (symbolic) probability
            density function of the phase-type distribution.
        """
        Qt = self._get_Qt(time)

        return phase_type.density(self.beta, self.B, Qt)

    @property
    def T_expected_value(self):
        """Return the (symbolic) expected value of the transit time.

        See Also:
            :func:`.phase_type.expected_value`: Return the (symbolic) expected
            value of the phase-type distribution.
        """
        return phase_type.expected_value(self.beta, self.B)

    @property
    def T_standard_deviation(self):
        """Return the (symbolic) standard deviation of the transit time.

        See Also:
            :func:`.phase_type.standard_deviation`: Return the (symbolic)
            standard deviation of the phase-type distribution.
        """
        return phase_type.standard_deviation(self.beta, self.B)

    @property
    def T_variance(self):
        """Return the (symbolic) variance of the transit time.

        See Also:
            :func:`.phase_type.variance`: Return the (symbolic) variance of
            the phase-type distribution.
        """
        return phase_type.variance(self.beta, self.B)

    def T_nth_moment(self, n):
        """Return the (symbolic) ``n`` th moment of the transit time.

        Args:
            n (positive int): order of the moment

        Returns:
            SymPy expression or numerical value: :math:`\mathbb{E}[T^n]`

        See Also:
            :func:`.phase_type.nth_moment`: Return the (symbolic) ``n`` th
            moment of the phase-type distribution.
        """
        return phase_type.nth_moment(self.beta, self.B, n)

    def T_quantile(self, q, tol=1e-8):
        """Return a numerical quantile of the transit time distribution.

        The quantile is computed by a numerical inversion of the
        cumulative distribution function.

        Args:
            q (between 0 and 1): probability mass to be left to the quantile
                q = 1/2 computes the median
            tol (float): tolerance for brentq algorithm of numerical
                root search, defaults to 1e-8

        Returns:
            float: The smallest :math:`y` such that :math:`F_T(y)\\geq q`

        See Also:
            :func:`T_cum_dist_func`: Return the cumulative distribution
            function of the transit time.
        """
        CDF = lambda t: float(self.T_cum_dist_func(t))
        try:
            res = _generalized_inverse_CDF(CDF, q, tol=tol)
        except TypeError as err:
            raise Error("Quantiles cannot be computed symbolically.") from err

        return res

    # system age

    def A_cum_dist_func(self, age=None):
        """Return the cumulative distribution function of the system age.

        Args:
            age (nonnegative, optional):
                age at which :math:`F_A` is to be evaluated,
                defaults to None: purely symbolic treatment

        Returns:
            SymPy expression or numerical value: cumulative distribution
            function of PH(:math:`\\eta`, :math:`B`)
            (evaluated at age)

        See Also:
            :func:`.phase_type.cum_dist_func`: Return the (symbolic) cumulative
            distribution function of phase-type.
        """
        Qt = self._get_Qt(age)
        t, y = symbols('t y')
        return phase_type.cum_dist_func(self.eta, self.B, Qt).subs({t:y})

    def A_density(self, age=None):
        """Return the probability density function of the system age.

        Args:
            age (nonnegative, optional):
                age at which :math:`f_A` is to be evaluated,
                defaults to None: purely symbolic treatment

        Returns:
            SymPy expression or numerical value: probability density function
            of PH(:math:`\\eta`, :math:`B`) (evaluated at age)

        See Also:
            :func:`.phase_type.density`: Return the (symbolic) probability
            density function of the phase-type distribution.
        """
        Qt = self._get_Qt(age)
        t, y = symbols('t y')
        return phase_type.density(self.eta, self.B, Qt).subs({t:y})

    @property
    def A_expected_value(self):
        """Return the (symbolic) expected value of the system age.

        Returns:
            SymPy expression or numerical value: expected value of
            PH(:math:`\\eta`, :math:`B`)

        See Also:
            :obj:`.phase_type.expected_value`: Return the (symbolic) expected
            value of the phase-type distribution.
        """
        t, y = symbols('t y')
        return phase_type.expected_value(self.eta, self.B).subs({t:y})

    @property
    def A_standard_deviation(self):
        """Return the (symbolic) standard deviation of the system age.

        Returns:
            SymPy expression or numerical value: standard deviation of
            PH(:math:`\\eta`, :math:`B`)

        See Also:
            :func:`.phase_type.standard_deviation`: Return the (symbolic)
            standard deviation of the phase-type distribution.
        """
        return phase_type.standard_deviation(self.eta, self.B)

    @property
    def A_variance(self):
        """Return the (symbolic) variance of the system age.

        Returns:
            SymPy expression or numerical value: variance of
            PH(:math:`\\eta`, :math:`B`)

        See Also:
            func:`.phase_type.variance`: Return the (symbolic) variance of the
            phase-type distribution.
        """
        return phase_type.variance(self.eta, self.B)

    def A_nth_moment(self, n):
        """Return the (symbolic) ``n`` th moment of the system age.

        Args:
            n (positive int): order of the moment

        Returns:
            SymPy expression or numerical value: ``n`` th moment of
            PH(:math:`\\eta`, :math:`B`)

        See Also:
            :func:`.phase_type.nth_moment`: Return the (symbolic) ``n`` th
            moment of the phase-type distribution.
        """
        return phase_type.nth_moment(self.eeta, self.B, n)

    def A_quantile(self, q, tol=1e-8):
        """Return a numerical quantile of the system age distribution.

        The quantile is computed by a numerical inversion of the
        cumulative distribution function.

        Args:
            q (between 0 and 1): probability mass to be left to the quantile
                q = 1/2 computes the median
            tol (float): tolerance for brentq algorithm of numerical
                root search, defaults to 1e-8

        Raises:
            Error: if attempt is made to compute quantiles symbolically

        Returns:
            float: smallest :math:`y` such that :math:`F_A(y)\\geq q`

        See Also:
            :func:`A_cum_dist_func`: Return the cumulative distribution
            function of the system age.
        """
        CDF = lambda t: float(self.A_cum_dist_func(t))
        try:
            res = _generalized_inverse_CDF(CDF, q, tol=tol)
        except TypeError as err:
            raise Error("Quantiles cannot be computed symbolically.") from err

        return res

    # compartment age

    def a_cum_dist_func(self, age=None):
        """Return the cumulative distribution function vector of the
        compartment ages.

        Args:
            age (nonnegative, optional):
                age at which :math:`F_a` is to be evaluated,
                defaults to None: purely symbolic treatment

        Returns:
            SymPy or numerical dx1-matrix: :math:`F_a` (evaluated at age)
                :math:`F_a(y) = (X^\\ast)^{-1}\\,B^{-1}\\,`
                :math:`(e^{y\\,B}-I)\\,u`
        """
        Qt = self._get_Qt(age)
        t, y = symbols('t y')
        return _age_vector_cum_dist(self.u, self.B, Qt).subs({t:y})

    def a_density(self, age=None):
        """Return the probability density function vector of the
        compartment ages.

        Args:
            age (nonnegative, optional):
                age at which :math:`f_a` is to be evaluated,
                defaults to None: purely symbolic treatment

        Returns:
            SymPy or numerical dx1-matrix: :math:`f_a` (evaluated at age)
                :math:`f_a(y) = (X^\\ast)^{-1}\\,`
                :math:`e^{y\\,B}\\,u`
        """
        Qt = self._get_Qt(age)
        t, y = symbols('t y')
        return _age_vector_dens(self.u, self.B, Qt).subs({t:y})

    @property
    def a_expected_value(self):
        """Return the (symbolic) vector of expected values of the
        compartment ages.

        Returns:
            SymPy dx1-matrix:
            :math:`\\mathbb{E}[a] = -(X^\\ast)^{-1}\\,`
            :math:`B^{-1}\\,x^\\ast`
        """
        t, y = symbols('t y')
        return _age_vector_exp(self.u, self.B)

    @property
    def a_standard_deviation(self):
        """Return the (symbolic) vector of standard deviations of the
        compartment ages.

        Returns:
            SymPy dx1-matrix:
            :math:`\\sigma(a) = \\sqrt{\\sigma^2(a)}` component-wise
        """
        return _age_vector_sd(self.u, self.B)

    @property
    def a_variance(self):
        """Return the (symbolic) vector of variances of the compartment ages.

        Returns:
            SymPy dx1-matrix:
            :math:`\\sigma^2(a) = \\mathbb{E}[a^2]`
            :math:`- (\\mathbb{E}[a])^2` component-wise
        """
        return _age_vector_variance(self.u, self.B)

    def a_nth_moment(self, n):
        """Return the (symbolic) vector of the ``n`` th moments of the
        compartment ages.

        Args:
            n (positive int): order of the moment

        Returns:
            SymPy or numerical dx1-matrix:
            :math:`\\mathbb{E}[a^n] = (-1)^n\\,n!\\,(X^\\ast)^{-1}`
            :math:`\\ ,B^{-n}\\,x^\\ast`
        """
        return _age_vector_nth_moment(self.beta, self.B, n)

    def a_quantile(self, q, tol=1e-8):
        """Return a vector of numerical quantiles of the pool age distributions.

        The quantiles is computed by a numerical inversion of the
        cumulative distribution functions.

        Args:
            q (between 0 and 1): probability mass to be left to the quantile
                q = 1/2 computes the median
            tol (float): tolerance for brentq algorithm of numerical
                root search, defaults to 1e-8

        Returns:
            numpy.array: vector :math:`y=(y_1,\\ldots,y_d)` with
            :math:`y_i` smallest value such that :math:`F_{a_i}(y_i)\\geq q`

        See Also:
            :func:`a_cum_dist_func`: Return the cumulative distribution function
            vector of the compartment ages.
        """
        d = self.B.rows
        res = np.nan * np.zeros(d)
        try:
            for pool in range(d):
                CDF = lambda t: float(self.a_cum_dist_func(t)[pool])
                res[pool] = _generalized_inverse_CDF(CDF, q, tol=tol)
        except TypeError as err:
            raise Error("Quantiles cannot be computed symbolically.") from err

        return res

    # Laplacians for T and A

    @property
    def T_laplace(self):
        """Return the symbolic Laplacian of the transit time.

        Returns:
            SymPy expression: Laplace transform of the probability density of
            PH(:math:`\\beta`, :math:`B`)

        See Also:
            :obj:`.phase_type.laplace`: Return the symbolic Laplacian of the
            phase-type distribtion.
        """
        return simplify(phase_type.laplace(self.beta, self.B))

    @property
    def A_laplace(self):
        """Return the symbolic Laplacian of the system age.

        Returns:
            SymPy expression: Laplace transform of the probability density of
            PH(:math:`\\eta`, :math:`B`)

        See Also:
            :obj:`.phase_type.laplace`: Return the symbolic Laplacian of the
            phase-type distribtion.
        """
        return simplify(phase_type.laplace(self.eta, self.B))

    # release

    @property
    def r_compartments(self):
        """Return the (symbolic) release vector of the system in steady state.

        Returns:
            SymPy or numerical dx1-matrix: :math:`r_j = z_j \\, x^\\ast_j`

        See Also:
            | :func:`.phase_type.z`: Return the (symbolic) vector of rates
                toward absorbing state.
            | :obj:`xss`: Return the (symbolic) steady state vector.
        """
        r = phase_type.z(self.B)
        return Matrix(self.xss.rows, 1, [phase_type.z(self.B)[i]*self.xss[i]
                                            for i in range(self.xss.rows)])

    @property
    def r_total(self):
        """Return the (symbolic) total system release in steady state.

        Returns:
            SymPy expression or numerical value:
            :math:`r = \\sum\\limits_{j=1}^d r_j`

        See Also:
            :obj:`r_compartments`: Return the (symbolic) release vector of the
            system in steady state.
        """
        return sum(self.r_compartments)

    @property
    def absorbing_jump_chain(self):
        """Return the absorbing jump chain as a discrete-time Markov chain.

        The generator of the absorbing chain is just given by :math:`B`, which
        allows the computation of the transition probability matrix :math:`P`
        from :math:`B=(P-I)\\,D` with :math:`D` being the diagonal matrix with
        diagonal entries taken from :math:`-B`.

        Returns:
            :class:`~.DTMC.DTMC`: :class:`DTMC` (beta, P)
        """
        # B = (P - I) * D
        d = self.B.rows
        D = diag(*[-self.B[j,j] for j in range(d)])
        P = self.B * D**(-1) + eye(d)

        return DTMC(self.beta, P)

    @property
    def ergodic_jump_chain(self):
        """Return the ergodic jump chain as a discrete-time Markov chain.

        The generator is given by

        .. math::
            Q = \\begin{pmatrix}
                    B & \\beta \\\\
                    z^T & -1
                \\end{pmatrix}

        and the corresponding transition probability matrix :math:`P_Q` can
        then be obtained from :math:`Q=(P_Q-I)\\,D_Q`, where :math:`D_Q` is the
        diagonal matrix with entries from the diagonal of :math:`-Q`.

        Returns:
           :class:`~.DTMC.DTMC`: :class:`DTMC` (beta_ext, Q) with
           beta_ext = (beta, 0)
        """
        B = self.B
        d = B.rows

        lor = []
        for i in range(d):
            row = list(B[i,:]) + [self.beta[i]]
            lor.append(row)

        row = list(phase_type.z(B)) + [-1]
        lor.append(row)

        # (d+1)x(d+1) matrix
        # B     beta
        # z^T     -1
        Q = lor

        P = Matrix(Q)
        for j in range(d+1):
            for i in range(d+1):
                if Q[j][j] != 0:
                    if i != j:
                        P[i,j] = -Q[i][j]/Q[j][j]
                    else:
                        P[i,j] = 0
                else:
                    if i != j:
                        P[i,j] = 0
                    else:
                        P[i,j] = 1

        beta = Matrix(d+1, 1, list(self.beta) + [0])
        return DTMC(beta, P)

    #fixme: to be tested
    @property
    def entropy_per_jump(self):
        """Return the entropy per jump.

        Returns:
            SymPy expression or float: :math:`\\theta_J=`
            :math:`\\sum\\limits_{j=1}^{d+1} \\pi_j`
            :math:`\\sum\\limits_{i=1}^{d+1}-p_{ij}\\,\\log p_{ij}`
            :math:`+\\sum\\limits_{j=1}^d \\pi_j\\,(1-\\log -b_{jj})`
            :math:`+\\pi_{d+1}\\,\\sum\\limits_{i=1}^d`
            :math:`-\\beta_i\\,\\log\\beta_i`

        Notes:
            - :math:`\\pi` is the stationary distribution of the ergodic
              jump chain.
            - :math:`\\theta_J=` entropy of ergodic jump chain +
              entropy of sojourn times (no stay in environmental
              compartment :math:`d+1`)

        See Also:
            :obj:`~.DTMC.DTMC.stationary_distribution`:
            Return the (symbolic) stationary distribution.
        """
        d = self.B.rows
        P = self.ergodic_jump_chain.P
        pi = self.ergodic_jump_chain.stationary_distribution

        theta_jumps = self.ergodic_jump_chain.ergodic_entropy

        theta_stays = 0
        for j in range(d+1):
            x = 0

            if j == d:
                # no entropy for stay in environment
                x += 0
            else:
                # differential entropy of exponential distribution
                x += (1-log(-self.B[j,j]))
            x *= pi[j]
            theta_stays += x

        return theta_jumps + theta_stays

    #fixme: to be tested
    @property
    def entropy_per_cycle(self):
        """Return the entropy per cycle.

        Returns:
            SymPy expression or float: entropy per jump
            :math:`\\times` expected number of jumps per cycle

        See Also:
            | :obj:`entropy_per_jump`: Return the entropy per jump.
            | :obj:`~.DTMC.DTMC.expected_number_of_jumps`:
              Return the (symbolic) expected number of jumps before absorption.
        """
        theta_per_jump = self.entropy_per_jump
        jumps = self.absorbing_jump_chain.expected_number_of_jumps
        # add one jump from the environment into the system
        return theta_per_jump * (jumps+1)

    #fixme: to be tested
    @property
    def entropy_rate(self):
        """Return the entropy rate (entropy per unit time).

        Returns:
            SymPy expression or float: entropy per cycle
            :math:`\\cdot\\frac{1}{\\mathbb{E}T}`

        See Also:
            | :obj:`entropy_per_cycle`: Return the entropy per cylce.
            | :obj:`T_expected_value`: Return the (symbolic) expected
              value of the transit time.
        """
        # the entropy rate is the entropy per unit time
        # thus the entropy per cycle over cycle length
        theta_cycle = self.entropy_per_cycle
        return theta_cycle/self.T_expected_value

max_stars_repo_name: goujou/LAPM

max_issues_repo_name: goujou/LAPM

max_forks_repo_name: goujou/LAPM

reason: import numpy,from scipy,from sympy


text:
""" Average Cost Functions for Horton to determine Charges for Molecular Dynamics.
Copyright 2019 Simulation Lab
University of Freiburg
Author: Lukas Elflein <elfleinl@cs.uni-freiburg.de>
"""

import numpy as np
import h5py
import shutil

# We want to average over cost functions.
# These cost functions contain the three objects of the cost function: A, B, C
# A is a quadratic matrix (97x97), B a vector of the same dimension, and C is a constant.
# In the end, we are interested in the best-fit charges Q which are the solution to
# Q = A^-1 B
# We have multiple snapshots of a molecule, with corresponding As and Bs.
# This script averages over A and B, and outputs a HDF5 file containing these averaged objects.
# Later, these files will be used to obtain corresponding charges.

def read_h5(work_dir, timesteps):
	"""
	Import cost functions.

	Arguments:
	work_dir: the top-level directory the data is located in.
	timesteps: timestep labels of the snapshot subfolders in the work_dir.

	Returns:
	A_matrices: a dictionary of matrices, indexed by their timestep.
	B_vectors: a dictionary of vectors, indexed by their timestep.
	"""

	# Define the names and places of the HDF5 files that HORTON outputs.
	files = ['system300.cost.lnrhoref.-9.h5', 'system600.cost.lnrhoref.-9.h5']

	# The 97x97 matrices corresponding to each timestep
	A_matrices = dict()
	# The corresponding B vectors
	B_vectors = dict()

	# keep one HDF5 file as a template for writing into later
	template = False

	# Extract the values for each timestep
	print('loading data:')
	for timestep in timesteps:
		# build the path to the raw data
		sys_path = work_dir + '/' + timestep + 'ps'
		# go down into the subdir
		sys_path += '/smampppp_' + timestep + 'ps_new_constrains'
		# build the filename
		filename = 'system' + timestep + '.cost.lnrhoref.-9.h5'

		# special case:	1000ps are saved as 1ns
		if timestep == '1000':
			sys_path = work_dir + '/' + timestep + 'ps'
			# go down into the subdir
			sys_path += '/smampppp_' + timestep + 'ps_new_constrains'
			# build the filename
			filename = 'system' + timestep + '.cost.lnrhoref.-9.h5'

		path = sys_path + '/' + filename
		print(path, '... Done')

		# load the objects (read-only) from HDF5 file
		f = h5py.File(path, 'r')
		# Extract the A matrix
		A = np.array(f['cost']['A'])
		A_matrices[timestep] = A
		# Extract the B vector
		B = np.array(f['cost']['B'])
		B_vectors[timestep] = B

		if not template:
			shutil.copyfile(path, './average_cost.h5')
			template = True

	return A_matrices, B_vectors

def average(A_matrices, B_vectors, timesteps):
	"""
	Average over matrices.

	Arguments:
	A_matrices: a dictionary of NxN matrices, indexed with their timestep.
	B_vectors: a dictionary of vectors with len N, indexed with their timestep.
	timesteps: a list or tuple of timesteps.

	Returns:
	A: the average of all A_matrices.
	B: the average of all B_matrices.
	"""

	# Initialize empty
	time = list(B_vectors.keys())[0]
	A = A_matrices[time] * 0
	B = B_vectors[time] * 0

	# Average by adding all objects and dividing by their number
	for timestep in timesteps:
		A += A_matrices[timestep]
		B += B_vectors[timestep]

	# Divide
	number_snapshots = len(timesteps)
	A /= number_snapshots
	B /= number_snapshots

	return A, B

def export(A, B, template_path='./average_cost.h5'):
	"""
	Export&save numpy-matrices to HDF5 objects.

	Arguments:
	A: Averaged A-matrix.
	B: Averaged B-vector.

	Keyword Arguments:
	template_path: the path to the template file A and B are written into.
	"""
	# Open the template file
	f = h5py.File(template_path, 'r+')
	# Load the template A matrix
	A_old = f['cost/A']
	# Assign the averaged A
	A_old[...] = A
	# Do the same for the B-vectors
	B_old = f['cost/B']
	B_old[...] = B
	# Save changes
	f.close()

	# Make sure that the changes were written into the template
	f = h5py.File(template_path, 'r')
	assert np.allclose(f['cost/A'][()], A)
	assert np.allclose(f['cost/B'][()], B)

	print('\nData has been written to {}:'.format(template_path))

def main():
	"""
	Run the script.
	"""
	# Uncomment to define an absolute working dir path
	# WORK_DIR = '/work/ws/nemo/fr_jh1130-smamp_shared-0/for_lukas'
	# The WORK_DIR is the top-level directory, all timesteps are subfolders here
	WORK_DIR = '.'
	TIMESTEPS = [str(time) for time in range(100, 1100, 100)]
	A_matrices, B_vectors = read_h5(work_dir=WORK_DIR, timesteps=TIMESTEPS)

	print('Calculating averages')
	A, B = average(A_matrices, B_vectors, timesteps=TIMESTEPS)

	export(A, B)
	print('Done.')

if __name__ == '__main__':
	main()


text:
#!/usr/bin/env python

import argparse

parser = argparse.ArgumentParser(description="Use plot.ly to visualize walkers.")
parser.add_argument("--burn", type=int, default=0, help="How many samples to discard from the beginning of the chain for burn in.")
parser.add_argument("--chain", default="chain.npy", help="The name of the file storing the walker positions.")
parser.add_argument("--name", default="hist", help="The name of the object that we are fitting. The plot.ly plots will show up under this label.")

args = parser.parse_args()

import numpy as np

chain = np.load(args.chain)

# Convention within the Julia EnsembleSampler is
# ndim, niter, nwalkers = chain.shape
# However, when written to disk, we should have been following the emcee convention
nwalkers, niter, ndim = chain.shape

# nsamples = nwalkers * niter
# Flatchain is made after the walkers have been burned
# flatchain = np.reshape(chain, (nsamples, ndim))

from plotly import tools
import plotly.plotly as py
import plotly.graph_objs as go

# First, let's try to make a single 2D contour and a single histogram

fig = tools.make_subplots(rows=ndim, cols=1, shared_xaxes=True, vertical_spacing=0.005)

x = np.arange(niter)

# Label the axes appropriately based upon how many parameters we have
if ndim == 10:
    labels = [r"$M_\ast\quad [M_\odot]$", r"$r_c$ [AU]", r"$T_{10}$ [K]", r"$q$", r"$\log M_\mathrm{gas} \quad \log [M_\odot]$",  r"$\xi$ [km/s]", r"$i_d \quad [{}^\circ]$", r"PA $[{}^\circ]$", r"$v_r$ [km/s]", r"$\mu_\alpha$ ['']", r"$\mu_\delta$ ['']"]
elif ndim == 11:
    labels = [r"$M_\ast\quad [M_\odot]$", r"$r_c$ [AU]", r"$T_{10}$ [K]", r"$q$", r"$\log M_\mathrm{gas} \quad \log [M_\odot]$",  r"$\xi$ [km/s]", r"$d$ [pc]", r"$i_d \quad [{}^\circ]$", r"PA $[{}^\circ]$", r"$v_r$ [km/s]", r"$\mu_\alpha$ ['']", r"$\mu_\delta$ ['']"]
else:
    labels = None

max_stars_repo_name: elnjensen/DiskJockey

max_issues_repo_name: elnjensen/DiskJockey

max_forks_repo_name: elnjensen/DiskJockey


text:
import torch
from conllu import parse_incr
from tqdm import tqdm
from ete3 import Tree as EteTree
from tree import tokentree_to_ete
from scipy.sparse.csgraph import minimum_spanning_tree
from senreps import fetch_sen_reps, fetch_pos_tags

def parse_corpus(filename):

    data_file = open(filename, encoding="utf-8")

    ud_parses = list(parse_incr(data_file))

    return ud_parses

def create_gold_distances(corpus):
    '''
    create gold distances from the corpus for every sentence
    gold distances are stored as 2D Tensors
    '''

    all_distances = []

    for item in tqdm(corpus):
        tokentree = item.to_tree()
        ete_tree = tokentree_to_ete(tokentree)

        nodes = ete_tree.search_nodes()
        sen_len = len(nodes)
        distances = torch.zeros((sen_len, sen_len))

        for i in range(sen_len):
            node1 = nodes[i]
            for j in range(i, sen_len):
                node2 = nodes[j]
                distance = node1.get_distance(node2)
                distances[int(node1.name)-1][int(node2.name)-1] = distance
                distances[int(node2.name)-1][int(node1.name)-1] = distance

        all_distances.append(distances)

    return all_distances

def create_mst(distances):
    '''
    create minimum spanning trees from distances
    '''
    distances = torch.triu(distances).detach().cpu().numpy()

    mst = minimum_spanning_tree(distances).toarray()
    mst[mst>0] = 1.

    return mst

def edges(mst):
    '''
    creates edges stored as tuples from minimum spanning trees
    '''
    edges = []
    for i in range(len(mst)):
        for j in (mst[i]==1).nonzero()[0]:
            edges.extend([(i, j), (j, i)])

    return set(edges)

def calc_uuas(pred_distances, gold_distances):
    '''
    calculating uuas scores for normal struc. dependency task
    '''
    pred_mst = create_mst(pred_distances)
    gold_mst = create_mst(gold_distances)

    pred_edges = edges(pred_mst)
    gold_edges = edges(gold_mst)

    correct = sum(edge in pred_edges for edge in gold_edges)
    total_gold = len(gold_edges)
    if total_gold!=0:
        uuas = correct/total_gold
    elif len(pred_edges)==0:
        uuas = 1
    else:
        uuas=0

    return uuas

def calc_fake_uuas(pred_edges, fake_edges):
    '''
    calculating uuas scores based only on edges for control task
    '''
    correct = sum(pred_edges.max(dim=0)[1]==fake_edges).item()
    if len(fake_edges)!=0:
        uuas = correct/len(fake_edges)
    elif len(pred_edges)==0:
        uuas = 1
    else:
        uuas=0

    return uuas

def create_data(filename: str, model, tokenizer, model_type, device, vocab=None):
    '''
    create data for the POS-tagging task
    '''
    ud_parses = parse_corpus(filename)

    sen_reps = fetch_sen_reps(ud_parses, model, tokenizer, model_type, concat=True, device=device)

    pos_tags, pos_vocab = fetch_pos_tags(ud_parses, vocab=vocab)

    return sen_reps, pos_tags, pos_vocab

def init_corpus(path, model, tokenizer, model_type, device, concat=False, cutoff=None):
    """ Initialises the data of a corpus.

    Parameters
    ----------
    path : str
        Path to corpus location
    concat : bool, optional
        Optional toggle to concatenate all the tensors
        returned by `fetch_sen_reps`.
    cutoff : int, optional
        Optional integer to "cutoff" the data in the corpus.
        This allows only a subset to be used, alleviating
        memory usage.
    """
    corpus = parse_corpus(path)[:cutoff]

    embs, sen_len = fetch_sen_reps(corpus, model, tokenizer, model_type, concat=concat, device=device)
    #gold_distances = create_gold_distances(corpus)

    return embs, sen_len

reason: from scipy


text:
import pathlib
import subprocess
from setuptools import find_packages
from distutils.core import setup
from Cython.Build import cythonize
import numpy as np

def load_req():
    with open('requirements.txt') as req:
        return [str(l) for l in req.readlines()]

# The directory containing this file
HERE = pathlib.Path(__file__).parent

# The text of the README file
README = (HERE / "README.md").read_text()

# This call to setup() does all the work
setup(
    name="ctpn-text-detector",
    version="3.0.0",
    install_requires=load_req(),
    ext_modules=cythonize(["src/utils/bbox/*.pyx"]),
    include_package_data=True,
    description="encapsulating CTPN text detector in python package",
    long_description=README,
    long_description_content_type='text/markdown',
    url="https://github.com/Mohamed209/CTPN-text-detector",
    author="Mohamed Mossad",
    author_email="mohamedmosad209@gmail.com",
    license="MIT",
    classifiers=[
            "License :: OSI Approved :: MIT License",
            'Programming Language :: Python :: 3',
    ],
    packages=find_packages()
)


text:
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""preprocess."""

import os
import argparse
import numpy as np

from src.datasets import makeup_dataset

parser = argparse.ArgumentParser(description="preprocess")
parser.add_argument("--data_dir", type=str, default="", help="dataset path")
parser.add_argument("--classes", type=int, default=10, help='class number')
parser.add_argument("--pre_result_dir", type=str, default="./preprocess_Result",
                    help="preprocess data path")
args_opt = parser.parse_args()

if __name__ == '__main__':
    batch_size = 1
    data_dir = args_opt.data_dir

    test_dataset = makeup_dataset(data_dir=data_dir, mode='test', batch_size=1, bag_size=20, classes=args_opt.classes,
                                  num_parallel_workers=8)
    test_dataset.__loop_size__ = 1

    image_path = os.path.join(args_opt.pre_result_dir, "00_data")
    label_path = os.path.join(args_opt.pre_result_dir, "label.npy")
    nslice_path = os.path.join(args_opt.pre_result_dir, "nslice.npy")
    os.makedirs(image_path, exist_ok=True)
    label_list = []
    nslice_list = []
    for i, data in enumerate(test_dataset.create_dict_iterator(output_numpy=True)):
        file_name = "ava_bs" + str(batch_size) + "_" + str(i) + ".bin"
        file_path = os.path.join(image_path, file_name)
        data["imgs"].tofile(file_path)
        label_list.append(data["labels"])
        nslice_list.append(data["nslice"])
    np.save(os.path.join(label_path), label_list)
    np.save(os.path.join(nslice_path), nslice_list)
    print("=" * 20, "export bin files finished", "=" * 20)

max_stars_repo_name: leelige/mindspore

max_issues_repo_name: leelige/mindspore

max_forks_repo_name: leelige/mindspore


text:
import sys
sys.path.append('..')
from common.core import *
from common.gfxutil import *
from common.audio import *
from common.mixer import *
from common.note import *
from common.wavegen import *
from common.wavesrc import *
from common.writer import *

from kivy.core.window import Window
from kivy.clock import Clock as kivyClock
from kivy.uix.label import Label
from kivy.uix.image import Image
from kivy.graphics.instructions import InstructionGroup
from kivy.graphics import Color, Ellipse, Rectangle, Bezier
from kivy.graphics import PushMatrix, PopMatrix, Translate, Scale, Rotate
from kivy.graphics.texture import Texture
from kivy.config import Config

from MusicHelper import Note, Notes

from random import random, randint, choice
import numpy as np

class Wall(InstructionGroup):
	def __init__(self):
		super(Wall, self).__init__()

		self.texture = Image(source='../data/stonewall2_edited.png').texture
		self.rect = Rectangle( texture=self.texture, pos=(0,0), size=(Subwindow.width(),Window.height*0.2) )
		self.add(Color(0.2,0.15,0.15))
		self.add(self.rect)

	def on_update(self, dt):
		pass

class Button(InstructionGroup):
    def __init__(self, y, h, color, note = Notes.B, get_current_notes=None):
        super(Button, self).__init__()

        self.color = color

        # Set alpha
        alpha_lvl = 0.5
        self.enabled_color = Color(rgba=(color.rgb[0], color.rgb[1], color.rgb[2], alpha_lvl))
        self.disabled_color = Color(rgba=(0.5, 0.5, 0.5, alpha_lvl))

        self.add(self.color)

        self.crrect = CRRectangle( crpos=(Window.width, y), crsize=(100, h) )
        self.add(self.crrect)

        self.note = note
        self.is_enabled = True

        self.refresh = 2.0
        self.refresh_time = self.refresh

        self.note_texture = self.get_note_texture(note)
        self.text_crrect = CRRectangle( texture=self.note_texture, crpos=(Window.width-25, y), crsize=(50, 50) )
        self.add(Color(1,1,1))
        self.add(self.text_crrect)

        self.get_current_notes = get_current_notes

    def get_boundaries(self):
        lowerX, lowerY = self.crrect.pos
        upperX = lowerX + self.crrect.get_crsize()[0]
        upperY = lowerY + self.crrect.get_crsize()[1]

        return lowerX, lowerY, upperX, upperY

    def get_note(self):
        return self.note

    def new_note(self):
        current_notes, all_notes = self.get_current_notes()
        for note in current_notes:
            if note in all_notes:
                all_notes.remove(note)
        self.note = choice(all_notes)
        self.note_texture = self.get_note_texture(self.note)
        self.text_crrect.texture = self.note_texture

        # while True:
        #     note = choice(notes)
        #     if note not in existing_notes:
        #         existing_notes.append(note)
        #         b = Button(button_y_positions[i], h-5, Color(*colors[i]), note=note, get_current_notes=self.get_current_notes)
        #         self.buttons.append(b)
        #         self.add(b)
        #         break

    def get_note_texture(self, note):
        name = note.get_name()
        return Image(source='../data/'+name+'.png').texture

    def enable(self):
        self.is_enabled = True
        n = self.enabled_color.rgba
        self.color.rgba = (n[0],n[1],n[2],n[3])
        # TODO: get new note, make note text visible

    def disable(self):
        self.is_enabled = False
        n = self.disabled_color.rgba
        self.color.rgba = (n[0],n[1],n[2],n[3])
        # TODO: make note text invisible, set note to None

    def on_update(self, dt):
        if not self.is_enabled:
            self.refresh_time -= dt
            if self.refresh_time <= 0:
                self.refresh_time = self.refresh
                self.is_enabled = True
                self.enable()
                self.new_note()
        return True

class Foreground(InstructionGroup):
    def __init__(self, key):
        super(Foreground, self).__init__()

        w = Subwindow.width()
        h = Window.height

        # Draw Wall
        self.wall = Wall()
        self.add(self.wall)

        # key of game
        self.key = key

        # Draw Buttons
        self.buttons = []
        num_buttons = 4
        height = Window.height*0.6
        h = height/num_buttons

        button_y_positions = np.linspace(Window.height-height -  h/2, Window.height-h/2  , num_buttons)

        # rygb from top to bottom (so, ordered bgyr here)
        colors = [(.22, .22, 1.), (.22, 1., .22), (1., 1., .22), (1., .22, .22)]

        existing_notes = []
        for i in xrange(num_buttons):
            notes = Note.get_notes_in_key(self.key)
            while True:
                note = choice(notes)
                if note not in existing_notes:
                    existing_notes.append(note)
                    b = Button(button_y_positions[i], h-5, Color(*colors[i]), note=note, get_current_notes=self.get_current_notes)
                    self.buttons.append(b)
                    self.add(b)
                    break
                else:
                    pass

    def get_current_notes(self):
        notes = []
        for btn in self.buttons:
            notes.append(btn.get_note())
        return (notes, Note.get_notes_in_key(self.key))

    def on_update(self, dt):
        # As of now, should never be removed
        return True

max_stars_repo_name: osmidy/Dischord

max_issues_repo_name: osmidy/Dischord

max_forks_repo_name: osmidy/Dischord


text:
import os
import pickle
import numpy as np
from .process_utils import DrawGaussian

# COCO typical constants
MIN_KEYPOINTS = 5
MIN_AREA = 32 * 32

#Key points in body
# POINTS = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17] # without head
POINTS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]

# Non traditional body parts
BODY_PARTS_INDEX = [
    (0,1),   # nose - left eye
    (0,2),   # nose - right eye
    (1,3),   # left eye - left ear
    (2,4),   # right eye - right ear
    (17,5),  # neck - left shoulder
    (17,6),  # neck - right shoulder
    (5,7),   # left shoulder - left elbow
    (6,8),   # right shoulder - right elbow
    (7,9),   # left elbow - left hand
    (8,10),  # right elbow - right hand
    (17,11), # neck - left waist
    (17,12), # neck - right waist
    (11,13), # left waist - left knee
    (12,14), # right waise - right knee
    (13,15), # left knee - left foot
    (14,16), # right knee - right foot
    (0,17)   # nose - neck
]

BODY_PARTS = [(POINTS.index(x), POINTS.index(y)) for x, y in BODY_PARTS_INDEX if (x in POINTS) and (y in POINTS)]

#BODY_PARTS = [
#    (0,1),   # nose - left eye
#    (0,2),   # nose - right eye
#    (1,3),   # left eye - left ear
#    (2,4),   # right eye - right ear
#    (17,5),  # neck - left shoulder
#    (17,6),  # neck - right shoulder
#    (5,7),   # left shoulder - left elbow
#    (6,8),   # right shoulder - right elbow
#    (7,9),   # left elbow - left hand
#    (8,10),  # right elbow - right hand
#    (17,11), # neck - left waist
#    (17,12), # neck - right waist
#    (11,13), # left waist - left knee
#    (12,14), # right waise - right knee
#    (13,15), # left knee - left foot
#    (14,16), # right knee - right foot
#    (0,17)   # nose - neck
#]

FLIP = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12), (13,14), (15,16)]
#FLIP_INDICES = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12), (13,14), (15,16)]
FLIP_INDICES = [(POINTS.index(x), POINTS.index(y)) for x, y in FLIP if (x in POINTS) and (y in POINTS)]

FLIP_PAF = [(0,1), (2,3), (4,5), (6,7), (8,9), (10,11), (12,13), (14,15)]
#FLIP_INDICES_PAF = [(0,1), (2,3), (4,5), (6,7), (8,9), (10,11), (12,13), (14,15)]
BODY_INDICES_PAF = [(POINTS.index(x), POINTS.index(y)) for x, y in FLIP_PAF if (x in POINTS) and (y in POINTS)]

def check_annot(annot):
    return annot['num_keypoints'] >= MIN_KEYPOINTS and annot['area'] > MIN_AREA and not annot['iscrowd'] == 1

def get_heatmap(coco, img, keypoints, sigma):
    n_joints = keypoints.shape[1]
    out_map = np.zeros((n_joints + 1, img.shape[0], img.shape[1]))
    for person_id in range(keypoints.shape[0]):
        keypoints_person = keypoints[person_id]
        for i in range(keypoints.shape[1]):
            keypoint = keypoints_person[i]
            # Ignore unannotated keypoints
            if keypoint[2] > 0:
                out_map[i] = np.maximum(out_map[i], DrawGaussian(out_map[i], keypoint[0:2], sigma=sigma))
    out_map[n_joints] = 1 - np.sum(out_map[0:n_joints], axis=0) # Last heatmap is background
    return out_map

def get_paf(coco, img, keypoints, sigma_paf, variable_width):
    out_pafs = np.zeros((len(BODY_PARTS), 2, img.shape[0], img.shape[1]))
    n_person_part = np.zeros((len(BODY_PARTS),img.shape[0],img.shape[1]))
    for person_id in range(keypoints.shape[0]):
        keypoints_person = keypoints[person_id]
        for i in range(len(BODY_PARTS)):
            part = BODY_PARTS[i]
            keypoint_1 = keypoints_person[part[0], :2]
            keypoint_2 = keypoints_person[part[1], :2]
            if keypoints_person[part[0], 2] > 0 and keypoints_person[part[1], 2] > 0:
                part_line_segment = keypoint_2 - keypoint_1
                # Notation from paper
                l = np.linalg.norm(part_line_segment)
                if l>1e-2:
                    sigma = sigma_paf
                    if variable_width:
                        sigma = sigma_paf *  l * 0.025
                    v = part_line_segment/l
                    v_per = v[1], -v[0]
                    x, y = np.meshgrid(np.arange(img.shape[1]), np.arange(img.shape[0]))
                    dist_along_part = v[0] * (x - keypoint_1[0]) + v[1] * (y - keypoint_1[1])
                    dist_per_part = np.abs(v_per[0] * (x - keypoint_1[0]) + v_per[1] * (y - keypoint_1[1]))
                    mask1 = dist_along_part >= 0
                    mask2 = dist_along_part <= l
                    mask3 = dist_per_part <= sigma
                    mask = mask1 & mask2 & mask3
                    out_pafs[i, 0] = out_pafs[i, 0] + mask.astype('float32') * v[0]
                    out_pafs[i, 1] = out_pafs[i, 1] + mask.astype('float32') * v[1]
                    n_person_part[i] += mask.astype('float32')
    n_person_part = n_person_part.reshape(out_pafs.shape[0], 1, img.shape[0], img.shape[1])
    out_pafs = out_pafs/(n_person_part + 1e-8)
    return out_pafs

def add_neck(keypoints):
    right_shoulder = keypoints[6, :]
    left_shoulder = keypoints[5, :]
    neck = np.zeros(3)
    if right_shoulder[2] > 0 and left_shoulder[2] > 0:
        neck = (right_shoulder + left_shoulder) / 2
        neck[2] = 2

    neck = neck.reshape(1, len(neck))
    neck = np.round(neck)
    keypoints = np.vstack((keypoints,neck))

    return keypoints

def get_keypoints(coco, img, annots):
    keypoints = []
    for annot in annots:
        person_keypoints = np.array(annot['keypoints']).reshape(-1, 3)
#        person_keypoints = add_neck(person_keypoints)
        person_keypoints = add_neck(person_keypoints)[POINTS,:]
        keypoints.append(person_keypoints)
    return np.array(keypoints)

def get_ignore_mask(coco, img, annots):
    mask_union = np.zeros((img.shape[0], img.shape[1]), 'bool')
    masks = []
    for annot in annots:
        mask = coco.annToMask(annot).astype('bool')
        masks.append(mask)
        if check_annot(annot):
            mask_union = mask_union | mask
    ignore_mask = np.zeros((img.shape[0], img.shape[1]), 'bool')
    for i in range(len(annots)):
        annot = annots[i]
        mask = masks[i]
        if not check_annot(annot):
            ignore_mask = ignore_mask | (mask & ~mask_union)

    return ignore_mask.astype('uint8')

def clean_annot(coco, data_path, split):
    ids_path = os.path.join(data_path, split + '_ids.pkl')
    if os.path.exists(ids_path):
        print('Loading filtered annotations for {} from {}'.format(split,ids_path))
        with open(ids_path, 'rb') as f:
            return pickle.load(f)
    else:
        print('Filtering annotations for {}'.format(split))
#        person_ids = coco.getCatIds(catNms=['person'])
        indices_tmp = sorted(coco.imgs.keys())
        indices = np.zeros(len(indices_tmp))
        valid_count = 0
        for i in range(len(indices_tmp)):
            anno_ids = coco.getAnnIds(indices_tmp[i])
            annots = coco.loadAnns(anno_ids)
            # Coco standard constants
            annots = list(filter(lambda annot: check_annot(annot), annots))
            if len(annots) > 0:
                indices[valid_count] = indices_tmp[i]
                valid_count += 1
            if i%100==0:
                print(i)
        indices = indices[:valid_count]
        print('Saving filtered annotations for {} to {}'.format(split, ids_path))
        with open(ids_path, 'wb') as f:
            pickle.dump(indices, f)
        return indices


text:
# Updated Animation Starter Code
from tkinter import *
import random
import pyaudio
import sys
import numpy as np
import aubio
import threading
import copy
import PIL

#sourced and modified from the Aubio Demos in GitHub
#https://github.com/aubio/aubio/blob/master/python/demos/demo_pitch.py
def getPitch() :
    p = pyaudio.PyAudio()

    # open stream
    buffer_size = 1024
    pyaudio_format = pyaudio.paFloat32
    n_channels = 1
    samplerate = 44100
    stream = p.open(format=pyaudio_format,
                    channels=n_channels,
                    rate=samplerate,
                    input=True,
                    frames_per_buffer=buffer_size)

    if len(sys.argv) > 1:
        # record 5 seconds
        output_filename = sys.argv[1]
        record_duration = 5 # exit 1
        outputsink = aubio.sink(sys.argv[1], samplerate)
        total_frames = 0
    else:
        # run forever
        outputsink = None
        record_duration = None
    tolerance = 0.8
    win_s = 4096 # fft size
    hop_s = buffer_size # hop size
    pitch_o = aubio.pitch("default", win_s, hop_s, samplerate)
    pitch_o.set_unit("midi")
    pitch_o.set_tolerance(tolerance)

    print("*** starting recording")

    audiobuffer = stream.read(buffer_size)
    signal = np.fromstring(audiobuffer, dtype=np.float32)

    pitch = pitch_o(signal)[0]
    confidence = pitch_o.get_confidence()

    #print(pitch)

    #print("{}".format(pitch))

    if outputsink:
        outputsink(signal, len(signal))

    print("*** done recording")
    stream.stop_stream()
    stream.close()
    p.terminate()

    return pitch

#animation shell code from 15-112 Website
####################################
# customize these functions
####################################

def init(data):
    # load data.xyz as appropriate
    data.mapWidth = data.width*70
    data.radius = 20
    data.cx = data.radius
    data.groundY = int(data.height * 2/3 + 70)
    data.cy = data.groundY - data.radius
    data.timerDelay = 10
    data.speed = 5
    data.scroll = 0
    data.timer = 0
    data.isDead = False
    data.mode = "screen"
    data.desert = PhotoImage(file = "desert.gif")

    #data.bird = PhotoImage(file="normal bird.png")
    #data.drawBird = False

    #cactus data
    data.cacti = []
    data.cactusThickness = 10
    data.cactusPosition = 0

    for cactusX in range(data.width,data.mapWidth,data.width) :
        y = int(random.randint((data.groundY-data.height//6),data.groundY-20))
        data.cacti.append([cactusX+random.randint(0,data.width//2), y])

    #mountain data
    data.mountains = []

    #jump data
    data.pitchList = []
    data.isJumping = False
    data.isFalling = False

    #Score Data
    data.hiScore = 0
    data.currentScore = 0

    #Gold Coin Data
    data.coins = []
    data.coinRadius = 10
    for coinPositions in range(data.width+20,data.mapWidth+20,data.width) :
        y = int(random.randint(20,data.groundY-data.height//2))
        data.coins.append([coinPositions,y])

    #Deadly Coin Data
    data.deadlyCoins = []
    data.deadlyCoinRadius = 10
    for coinPositions in range(data.width*3//2, data.mapWidth*3//2,data.width*2) :
        y = int(random.randint(40,data.groundY-data.height//2))
        data.deadlyCoins.append([coinPositions,y])

    #Night Mode Data
    #data.color = 99
    data.red = 255
    data.blue = 255
    data.green = 255
    data.isNight = False
    data.scoreTextColor = "black"

    #Character Data
    data.firstBoxColor = "black"
    data.secondBoxColor = "black"
    data.thirdBoxColor = "black"
    data.fourthBoxColor = "black"
    data.characterName = "Facebook"
    data.displayInstruction = False
    data.flashingInstruction = False
    data.characterInstruction = True
    data.facebook = PhotoImage(file="facebook.gif")
    data.comcast = PhotoImage(file="comcast.gif")
    data.att = PhotoImage(file = "att.gif")
    data.verizon = PhotoImage(file = "verizon.gif")
    data.characterScreen = PhotoImage(file = "desert screen.gif")

    #Bird Data
    data.normalBird = PhotoImage(file = "normal bird.gif")
    data.screamingBird = PhotoImage(file = "screaming bird.gif")
    data.fallingBird = PhotoImage(file = "falling bird.gif")
    data.deadBird = PhotoImage(file = "dead bird.gif")

    #Start Screen Data
    data.screenJumping = True
    data.screenFalling = False

    #Character List Data
    data.characterList = []
    data.newList =[]
    data.coinsCollected = 0
    data.coinNewList = copy.copy(data.coins)
    data.facebookList = ["The telecom operators do not block the access to any number\nand there will be no deliberate delay connection\nto a particular number,\nunless the law specifies","Free Basics is an open platform(?)\nlaunched by Facebook\nthat provides free access to selected websites\n and internet services","Free Basics is not an open platform\nas Facebook defines its technical guidelines & reserves\nthe right to change the rules.","It's an app that offers users in\ndeveloping markets a 'free'\nFacebook-centric version of\n\the internet","Since Facebook rolled out Free Basics\nin a lot of developing nations\nit has become THE Internet itself for\na lot of people","In Myanmar,FB launched with the\ngovt's support. Later, during the Rohingya\ncrisis, it was\naccused of supporting ethnic cleansing."]

####################################
# mode dispatcher
####################################

def mousePressed(event, data):
    if (data.mode == "screen"): screenMousePressed(event, data)
    elif (data.mode == "playGame"):   gameMousePressed(event, data)
    elif (data.mode == "character"):       characterMousePressed(event, data)

def keyPressed(event, data):
    if (data.mode == "screen"): screenKeyPressed(event, data)
    elif (data.mode == "playGame"):   gameKeyPressed(event, data)
    elif (data.mode == "character"): characterKeyPressed(event,data)

def timerFired(data):
    if (data.mode == "screen"): screenTimerFired(data)
    elif (data.mode == "playGame"):   gameTimerFired(data)
    elif (data.mode == "character"):       characterTimerFired(data)

def redrawAll(canvas, data):
    if (data.mode == "screen"): screenRedrawAll(canvas, data)
    elif (data.mode == "playGame"):   gameRedrawAll(canvas, data)
    elif (data.mode == "character"):       characterRedrawAll(canvas, data)

# Screen mode
####################################

def screenMousePressed(event, data):
    pass

def screenKeyPressed(event, data):
    data.mode = "character"
    data.cy = data.groundY - data.radius

def screenTimerFired(data):
    if data.timer%5000 == 0:
        if data.screenJumping :
            data.cy -= data.speed
            if data.cy - data.radius <= data.width//2 :
                data.screenJumping = False
                data.screenFalling = True

        if data.screenFalling :
            data.cy += data.speed

            if data.cy + data.radius >= data.groundY - data.radius :
                #print("um wtf")
                data.cy = data.groundY - data.radius
                data.screenJumping = True
                data.screenFalling = False

def screenRedrawAll(canvas, data):
    canvas.create_image(data.width//2,data.height//2,image = data.desert)
    canvas.create_text(data.width//2, data.height//4,
                       text="The No Internet Game", font="Arial 20")
    canvas.create_text(data.width//4 + 30,data.height//4 + 20,text="Try:",font = "Arial 15",anchor = "w")
    canvas.create_text(data.width//4+40,data.height//4 + 45, text = "Checking the network cable, modem, and router\nReconnecting to WiFi", font = "Arial 10",anchor = "w")
    canvas.create_text(data.width//4 + 32, data.height//4 + 65, text = "ERR_INTERNET_DISCONNECTED", font = "Arial 10", anchor = "w")
    canvas.create_text(data.width//4 + 15,data.height//4 + 85,text = "Press any key to choose a character!", font = "Arial 15", anchor = "w")
    #canvas.create_text(data.width//2+30,data.height//4 + 60, text = "Reconnecting to Wi-Fi", font = "Arial 10", anchor = "e")
    #canvas.create_rectangle(0-data.scroll,data.groundY,data.width,data.height,fill="black")
    canvas.create_image(data.cx-data.scroll,data.cy,image = data.normalBird)

#Mode Template code from Animation Demos in 15-112 Website
####################################
# character mode
####################################

def characterMousePressed(event, data):
    if ((event.x > data.width//8) and (event.x < data.width//2 - 40) and \
    (event.y > data.height//4 - 60) and (event.y < data.height//2 - 80)) :
        data.characterName = "Facebook"
        data.firstBoxColor = "red"
        data.displayInstruction = True
        data.characterInstruction = False

    elif ((event.x > data.width//8) and (event.x<data.width//2 - 40) and \
    (event.y > data.height*3//4 - 100) and (event.y < data.height - 120)) :
        #print("I clicked")
        data.characterName = "AT&T"
        data.secondBoxColor = "red"
        data.displayInstruction = True
        data.characterInstruction = False

    elif ((event.x > data.width//2 + 40) and (event.x < data.width*7//8) and \
    (event.y > data.height//4 - 60) and (event.y < data.height//2 - 80)) :

        data.characterName = "Comcast"
        data.thirdBoxColor = "red"
        data.displayInstruction = True
        data.characterInstruction = False
        #print(data.characterName)

    elif ((event.x > data.width//2 + 40) and (event.x < data.width*7//8) and \
    (event.y > data.height*3//4-100) and (event.y < data.height - 120)) :
        data.characterName = "Verizon"
        data.fourthBoxColor = "red"
        data.displayInstruction = True
        data.characterInstruction = False

def characterKeyPressed(event, data):
    data.mode = "playGame"

def characterTimerFired(data):
    data.timer += 1
    if data.timer%50 == 0 :
        data.flashingInstruction = False
    else :
        data.flashingInstruction = True

def drawClickToPlay(canvas,data) :
    canvas.create_text(data.width//2,data.height//2,
    text = "Press any key to start playing!"
    ,fill = "red",font = "Arial 15 bold")

def characterRedrawAll(canvas, data):
    canvas.create_image(data.width//2,data.height//2,image = data.characterScreen)
    if data.characterInstruction :
        canvas.create_text(data.width//2,50,
        text = "CLICK ON THE OPTIONS BELOW TO CHOOSE A CHARACTER!",
        fill = "red", font = "Courier 15 bold")
    if data.displayInstruction :
        canvas.create_text(data.width//2,data.height//2-55,
        text = "Raise your voice pitch to make the bird fly")
        canvas.create_text(data.width//2,data.height//2-40,
        text = "Collect the gold coins to increase your points")
        canvas.create_text(data.width//2,data.height//2-25,
        text="Don't hit the green coins or the cacti else you're ded lolol")
        if data.flashingInstruction :
            drawClickToPlay(canvas,data)

    #first character name
    canvas.create_rectangle(data.width//8,data.height//4-60,data.width//2 \
    - 40,data.height//2-80, fill = data.firstBoxColor)
    canvas.create_image(data.width//8 + 3*data.width//16 - 20, data.height//4 - \
    60 + data.height//8 - 10,image = data.facebook)

    #second character name
    canvas.create_rectangle(data.width//8, data.height*3//4 - 100, \
    data.width//2 - 40, data.height-120,fill=data.secondBoxColor)
    canvas.create_image(data.width//8 + 3*data.width//16 - 20, \
    data.height*5//8 + 15,image = data.att)

    #third character name
    canvas.create_rectangle(data.width//2 + 40, data.height//4-60,\
    data.width*7//8, data.height//2 - 80, fill = data.thirdBoxColor)
    canvas.create_image(data.width*3//16 - 20 + data.width//2 + 40, \
    data.height//4 - 60 + data.height//8 - 10, image = data.comcast)

    #fourth character name
    canvas.create_rectangle(data.width//2 + 40, data.height*3//4 - 100, \
    data.width*7//8, data.height - 120, fill = data.fourthBoxColor)
    canvas.create_image(data.width//2 + 40 + 3*data.width//16 - 20, \
    data.height//8 - 10 + data.height*3//4 - 100, image = data.verizon)

#Game mode
####################################

def gameMousePressed(event, data):
    # use event.x and event.y
    if data.isDead :
        if ((event.x > data.width//2 - 20) and (event.x < data.width//2 + 20) \
        and (event.y > data.height//2 -10) and (event.y < data.height//2 + 10)) :
            init(data)

def gameKeyPressed(event, data):
    # use event.char and event.keysym
   pass

def circleMovement(data) :
    data.cx += data.speed
    xLeft = data.cx - data.radius
    xRight = data.cx + data.radius
    yTop = data.cy - data.radius
    yBottom = data.cy + data.radius
    #put a buffer
    buffer = data.width * 2/3
    #Check whether we're scrolling out of the buffer distance
    if (data.cx + data.radius + buffer) >= (data.scroll + data.width) :
        data.scroll += data.speed

#this function is only to draw two clouds that remain stationary on the canvas
def drawClouds(data,canvas) :
    pass

def deadlyCoinsDraw(data,canvas) :
    for coins in data.deadlyCoins :
        x = coins[0]
        y = coins[1]
        canvas.create_oval(x-data.deadlyCoinRadius-data.scroll,
        y-data.deadlyCoinRadius,x+data.deadlyCoinRadius-data.scroll,
        y+data.deadlyCoinRadius,fill = "green")

def drawCacti(data,canvas) :
    #print(data.cacti)
    shift = random.randint(-20,20)
    for cactus in data.cacti :
        #print(cactus)
        height = cactus[1]
        cactusPosition = cactus[0]
        canvas.create_rectangle(cactusPosition-data.scroll,data.groundY,
        data.cactusThickness+cactusPosition-data.scroll,height,
        fill = "green",width = 0)

        #top circle
        left = cactusPosition - data.scroll
        top = height - data.cactusThickness//2
        right = cactusPosition + data.cactusThickness - data.scroll
        bottom = height + data.cactusThickness//2
        canvas.create_oval(left,top,right,bottom,fill="green",width=0)

        #left cactus branch
        xRightTop = cactusPosition - data.scroll
        yRightTop = height + 0.3*(data.groundY - height)
        xRightBottom = cactusPosition - data.scroll
        yRightBottom = yRightTop + data.cactusThickness
        yLeftTop = yRightTop - 3
        xLeftTop = cactusPosition - 10 - data.scroll
        xLeftBottom = cactusPosition - 10 - data.scroll
        yLeftBottom = yLeftTop + data.cactusThickness
        #print(xRightTop,yRightTop,xRightBottom,yRightBottom,xLeftBottom,
        #yLeftBottom,xLeftTop,yLeftTop)
        canvas.create_polygon(xRightTop,yRightTop,xRightBottom,yRightBottom,
        xLeftBottom,yLeftBottom,xLeftTop,yLeftTop,fill = "green")

        # first circle
        left1 = xLeftTop - data.cactusThickness//2
        top1 = yLeftTop
        right1 = xLeftTop + data.cactusThickness/2
        bottom1 = yLeftBottom
        canvas.create_oval(left1,top1,right1,bottom1,fill = "green",width=0)

        #left cactus branch's top rectangle
        xTop = left1
        yTop = top1 - 0.3*(data.groundY-height)
        xBottom = right1
        yBottom = bottom1 - data.cactusThickness//2 - 1
        canvas.create_rectangle(xTop,yTop,xBottom,yBottom,fill="green",width=0)

        # second circle
        left2 = left1
        top2 = yTop - data.cactusThickness//2
        right2 = right1
        bottom2 = yTop + data.cactusThickness//2
        canvas.create_oval(left2,top2,right2,bottom2,fill="green",width=0)

        """Right Cactus Branch"""
        xLTop = cactusPosition + data.cactusThickness - data.scroll
        yLTop = height + 0.2*(data.groundY - height)
        xLBottom = cactusPosition + data.cactusThickness - data.scroll
        yLBottom = yLTop + data.cactusThickness
        xRTop = cactusPosition + data.cactusThickness + 10 - data.scroll
        yRTop = yLTop - 3
        xRBottom = cactusPosition + data.cactusThickness + 10 - data.scroll
        yRBottom = yRTop + data.cactusThickness
        canvas.create_polygon(xLTop,yLTop,xLBottom,yLBottom,xRBottom,yRBottom,\
        xRTop,yRTop,fill="green")

        #third circle
        left3 = xRTop - data.cactusThickness//2
        top3 = yRTop
        right3 = xRTop + data.cactusThickness//2
        bottom3 = yRBottom
        canvas.create_oval(left3,top3,right3,bottom3,fill="green",width=0)

        #right cactus's top rectangle
        topX = left3
        topY = top3 - 0.4*(data.groundY - height)
        bottomX = right3
        bottomY = bottom3 - data.cactusThickness//2 - 1
        canvas.create_rectangle(topX,topY,bottomX,bottomY,fill="green",width=0)

        #fourth circle
        left4 = left3
        top4 = topY - data.cactusThickness//2
        right4 = topX + data.cactusThickness
        bottom4 = top4 + data.cactusThickness
        canvas.create_oval(left4,top4,right4,bottom4,fill="green",width=0)

#function to find distance between two points
def distance(x1,y1,x2,y2) :
    x = (x2 - x1)**2
    y = (y1 - y2)**2
    return (x+y)**0.5

#to find whether the ball is being collided by the cactus
def cactusCollision(data) :
    index = 0
    while index < len(data.cacti) :
        cactus = data.cacti[index]
        cactusPosition = cactus[0]
        height = cactus[1]
        #check whether the cactus's left branch area is being hit
        if ((data.cx + data.radius >= cactusPosition -10) and \
        (data.cx + data.radius <= cactusPosition + data.cactusThickness + 10) \
        and (data.cy + data.radius >= height - 3 - 0.2*(data.groundY - height) \
        - data.cactusThickness//2)) or ((data.cx - data.radius <= cactusPosition\
         + data.cactusThickness + 10) and \
         (data.cx -data.radius >= cactusPosition - 10) and \
         (data.cy + data.radius >= height-3 - 0.2*(data.groundY-height) - \
         data.cactusThickness//2)) :
            print("collide with cactus")
            data.isDead = True
            return
        index += 1

def drawCharacterList(data,canvas) :
    if data.characterName == "Facebook" :
        data.characterList = data.facebookList
    elif data.characterName == "Comcast" :
        data.characterList = data.comcastList
    elif data.characterName == "Verizon" :
        data.characterList = data.verizonList
    elif data.characterName == "AT&T" :
        data.characterList = data.attList
    if len(data.newList) > 0 :
        for coins in data.newList :
            x = coins[0]
            y = coins[1]
            if len(data.characterList) >= data.coinsCollected and data.coinsCollected > 0:
                line = data.characterList[data.coinsCollected - 1]
                canvas.create_text(x-data.scroll,y,text = line, font = "Arial 5 bold")
                data.newList = data.newList[1:]

#to check if dino is colliding with coins and also to make then disappear
#if they do
def coinCollision(data) :
    index = 0
    while index < len(data.coins) :
        coins = data.coins[index]
        x = coins[0]
        y = coins[1]
        print(data.cx,x)
        #check if the upper part of ball hits the coin
        #print(x,y)
        #print(data.scroll)
        if distance(data.cx,data.cy,x+data.coinRadius,y) <= data.radius + \
        data.coinRadius :   ### should this be data.cx or data.cx + data.radius
            #print("if coin part")
            data.coinsCollected += 1
            data.newList.append(coins)
            data.coins.pop(index)
            data.currentScore += 10

            return
        index += 1

def deadlyCoinCollision(data) :
    index = 0
    while index < len(data.deadlyCoins):
        coins = data.deadlyCoins[index]
        x = coins[0]
        y = coins[1]
        #print(data.cx,x)
        #check if the upper part of ball hits the coin
        #print(x,y)
        #print(data.scroll)
        if distance(data.cx,data.cy,x+data.deadlyCoinRadius,y) <= data.radius + \
        data.deadlyCoinRadius :   ### should this be data.cx or data.cx + data.radius
            print("coin death lolololol")
            data.isDead = True
            return
        index += 1

def drawCoins(data,canvas) :
    for coins in data.coins :
        height = coins[1]
        coinPosition = coins[0]
        canvas.create_oval(coinPosition-data.coinRadius-data.scroll,
        height-data.coinRadius,coinPosition+data.coinRadius-data.scroll,
        height+data.coinRadius,fill="gold")
        canvas.create_text(coinPosition-data.scroll,height,text = "+10",
        font = "Ariel 5")

# from 112 Website on Strings
def readFile(path,data):
    with open(path, "rt") as f:
        return f.read()

def writeFile(path, contents,data):
    with open(path, "wt") as f:
        f.write(str(data.currentScore) + " " + data.characterName + "\n")

def getScores(path,data) :
    scores = []
    for line in readFile("score.txt",data).splitlines() :
        words = line.split(" ")
        if words == [""]: continue
        scores += [(int(words[0]),words[1])]
    return ((sorted(scores))[::-1])

def gameTimerFired(data):
    cactusCollision(data)
    deadlyCoinCollision(data)
    if data.isDead == False :

        data.timer += 1
        circleMovement(data)

        x = getPitch()
        coinCollision(data)
        cactusCollision(data)
        #print(x)

        #night mode
        if (data.currentScore%50 > 30 and data.currentScore%50 < 49) :
            print("night",data.currentScore%50)
            data.isNight = True
        else :
            data.isNight = False

        if data.isNight :
            if data.red > 0 and data.blue > 0 and data.green > 0 :
                if data.timer%2 == 0 :
                    data.red -= 5
                    data.green -= 5
                    data.blue -= 5
            else :
                data.red = 0
                data.blue = 0
                data.green = 0

        elif not(data.isNight) :
            if data.red < 255 and data.blue < 255 and data.green < 255 :
                data.red += 5
                data.blue += 5
                data.green += 5

        #score modification
        if data.timer%5 == 0 :
            data.currentScore += 1

        contentsToWrite = str(data.currentScore) + " " + str(data.characterName) + "\n"

        if len(getScores("score.txt",data)) == 0 :
            data.hiScore = data.currentScore
        #contentsRead = readFile("score.txt", data)
        if len(getScores("score.txt",data)) > 0:
            data.hiScore = getScores("score.txt",data)[0][0]
            if data.currentScore > data.hiScore :
                data.hiScore = data.currentScore

        #the ball should jump only when it's on the ground
        if x > 65 and data.cy >= data.groundY - data.radius:
            data.isJumping = True
            #print("adding")
            data.pitchList.append(x)

        if data.isJumping == True :
            data.cy -= x//7
            if (x == 0 and data.cy < data.groundY - data.radius) or (data.cy-data.radius < 0):
                #print("going into if")
                data.isFalling = True
                data.isJumping = False
                #print("falling",data.isFalling)
                #print("jumping",data.isJumping)
        if data.isFalling == True :
            #print("I'm falling")
            if data.cy + data.pitchList[len(data.pitchList)-1]//7 >= data.groundY - data.radius:
                data.cy = data.groundY - data.radius
            else :
                data.cy += data.pitchList[len(data.pitchList)-1]//7
            #print(data.pitchList[len(data.pitchList)-1]//7)

            data.pitchList[len(data.pitchList)-1] = data.pitchList[len(data.pitchList)-1] + 1

        if data.cy >= data.groundY - data.radius :
            data.isFalling = False
            data.isJumping = False

    else :
        writeFile("score.txt",str(data.currentScore) + " " + data.characterName + "\n",data)

#from Spring 2016 Notes
def rgbString(red, green, blue):
    return "#%02x%02x%02x" % (red, green, blue)

def gameRedrawAll(canvas, data):
    canvas.create_image(data.width//2,data.height//2,image = data.desert)
    #canvas.create_image(0-data.scroll,0,data.width-data.scroll,data.height,image = data.desert)

    if data.isNight :
        canvas.create_rectangle(0,0,data.width,data.height,
        fill=rgbString(data.red,data.green,data.blue),width=0)
        canvas.create_oval(data.width*3//4, data.height//4 - 30, \
        data.width*3//4 + 60, data.height//4 + 30,fill="white",width = 0)
        canvas.create_oval(data.width*3//4-5, data.height//4 - 25, \
        data.width*3//4 + 45, data.height//4 + 25,fill=rgbString(data.red,data.green,data.blue),width = 0)
        data.scoreTextColor = "white"
    elif data.isNight == False :
        data.scoreTextColor = "black"
    # draw in canvas

    #canvas.create_rectangle(0-data.scroll,data.groundY,data.width,\
    #data.height,fill="tan4")

    drawCacti(data,canvas)
    drawCoins(data,canvas)
    deadlyCoinsDraw(data,canvas)

    canvas.create_text(data.width//8,data.height//10 - 10, text = "Character :" + data.characterName, font = "Arial 10 bold", fill = data.scoreTextColor)

    canvas.create_text(data.width*1/8,data.height//10,text = "Hi-Score: " + \
    str(data.hiScore) + " Score: " + str(data.currentScore),
    font = "Arial 10 bold",fill=data.scoreTextColor)
    if data.isJumping :
        canvas.create_image(data.cx - data.scroll,
        data.cy,image = data.screamingBird)
    elif data.isFalling :
        canvas.create_image(data.cx-data.scroll,
        data.cy,image = data.fallingBird)
    else :
        canvas.create_image(data.cx-data.scroll,
        data.cy,image = data.normalBird)

    if data.isDead :
        print("DED lolol")
        canvas.create_text(data.width//2,data.height//2-60,text="GAMEOVER!")
        canvas.create_text(data.width//2,data.height//2 -40,
        text = "YOU HIT NET NEUTRALITY")
        canvas.create_image(data.cx-data.scroll,data.cy,
        image = data.deadBird)
        canvas.create_rectangle(data.width//2 - 20,\
        data.height//2-10,data.width//2 + 20,data.height//2+10,fill = "blue")

####################################
# use the run function as-is
####################################

def run(width=300, height=300):
    def redrawAllWrapper(canvas, data):
        canvas.delete(ALL)
        canvas.create_rectangle(0, 0, data.width, data.height,
                                fill='white', width=0)
        redrawAll(canvas, data)
        canvas.update()

    def mousePressedWrapper(event, canvas, data):
        mousePressed(event, data)
        redrawAllWrapper(canvas, data)

    def keyPressedWrapper(event, canvas, data):
        keyPressed(event, data)
        redrawAllWrapper(canvas, data)

    def timerFiredWrapper(canvas, data):
        timerFired(data)
        redrawAllWrapper(canvas, data)
        # pause, then call timerFired again
        canvas.after(data.timerDelay, timerFiredWrapper, canvas, data)
    # Set up data and call init
    class Struct(object): pass
    data = Struct()
    data.width = width
    data.height = height
    data.timerDelay = 25 # milliseconds
    root = Tk()
    root.resizable(width=False, height=False) # prevents resizing window
    init(data)
    # create the root and the canvas
    canvas = Canvas(root, width=data.width, height=data.height)
    canvas.configure(bd=0, highlightthickness=0)
    canvas.pack()
    # set up events
    root.bind("<Button-1>", lambda event:
                            mousePressedWrapper(event, canvas, data))
    root.bind("<Key>", lambda event:
                            keyPressedWrapper(event, canvas, data))
    timerFiredWrapper(canvas, data)
    # and launch the app
    root.mainloop()  # blocks until window is closed
    print("bye!")

run(500, 500)

# if __name__ == "__main__":
#     # creating thread
#     t1 = threading.Thread(target=run, args=())
#     t2 = threading.Thread(target=getPitch, args=())
#
#     # starting thread 1
#     t1.start()
#     # starting thread 2
#     t2.start()
#
#     # wait until thread 1 is completely executed
#     t1.join()
#     # wait until thread 2 is completely executed
#     t2.join()
#
#     # both threads completely executed
#     print("Done!")

max_stars_repo_name: santacalculus/screaming-angry-bird

max_issues_repo_name: santacalculus/screaming-angry-bird

max_forks_repo_name: santacalculus/screaming-angry-bird


text:
from __future__ import print_function, division

import numpy as np
from numpy import log, arctan2
import matplotlib.pyplot as plt

R = 6
rmax = 8.5

fig = plt.figure(figsize=(6, 3), frameon=False)

ax = plt.gca()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

plt.xlim((0, rmax))
plt.xlabel('radius')

r = np.linspace(0, rmax, int(rmax * 20 + 1))
r[0] = np.finfo(float).eps  # (to avoid division by 0)

def sqrtp(x):
    return np.sqrt(x, where=x > 0, out=np.zeros_like(x))
zRm1 = sqrtp((R - 1)**2 - r**2)
zR   = sqrtp( R**2      - r**2)
zRp1 = sqrtp((R + 1)**2 - r**2)

rhoRm1 = np.maximum(r, R - 1)
rhoR   = np.maximum(r, R    )
rhoRp1 = np.maximum(r, R + 1)

def F_1(z, rho):
    return 1/2 * z * rho / r + 1/2 * r * log(z + rho)

def F0(z, rho):
    return z

def F1(z, rho):
    return r * log(z + rho)

def F2(z, rho):
    return r * arctan2(z, r)

F = {-1: F_1, 0: F0, 1: F1, 2: F2}

def p(n):
    return 4 * (r * F[n - 1](zR, rhoR) - R * F[n](zR, rhoR)) - \
           2 * (r * F[n - 1](zRm1, rhoRm1) - (R - 1) * F[n](zRm1, rhoRm1)) - \
           2 * (r * F[n - 1](zRp1, rhoRp1) - (R + 1) * F[n](zRp1, rhoRp1))

plt.plot([0, R - 1, R, R + 1, rmax],
         [0,     0, 1,     0,    0],
         'k--', label='$b_{}$'.format(R))
lpR = '$p_{' + str(R) + ';'
plt.plot(r, p(0), 'b', label=lpR+'0}$')
plt.plot(r, p(1), 'g', label=lpR+'1}$')
plt.plot(r, p(2), 'r', label=lpR+'2}$')

plt.ylim(bottom=0)

plt.legend()
plt.tight_layout()

# plt.savefig('rbasex-pRn.svg')
# plt.show()

max_stars_repo_name: MikhailRyazanov/PyAbel

max_issues_repo_name: MikhailRyazanov/PyAbel

max_forks_repo_name: MikhailRyazanov/PyAbel

reason: import numpy,from numpy


text:
import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches
from matplotlib.collections import PatchCollection
import numpy as np

from .utils import rotmat

def droplet(xy=(0.0, 0.0), width=0.4, height=1.0, rot=0.0):

    # convert to x,y being in the middle of the droplet
    x = xy[0] - width / 2.0
    y = xy[1] - height / 2.0

    verts = [
        (x + 0.5 * width, y + height),
        (x + 0.375 * width, y + 0.8 * height),
        (x, y + 0.5 * height),
        (x, y + 0.35 * height),
        (x, y),
        (x + width, y),
        (x + width, y + 0.35 * height),
        (x + width, y + 0.5 * height),
        (x + 0.625 * width, y + 0.8 * height),
        (x + 0.5 * width, y + height),
        (x + 0.5 * width, y + height),
    ]

    # perform rotation
    if rot != 0:
        R = rotmat(rot)
        # subtract xy to rotate around the droplets centre
        # and move it back to xy
        verts = R.dot(np.array(verts - np.array(xy)).T).T + np.array(xy)

    codes = [
        Path.MOVETO,
        Path.CURVE4,
        Path.CURVE4,
        Path.CURVE4,
        Path.CURVE4,
        Path.CURVE4,
        Path.CURVE4,
        Path.CURVE4,
        Path.CURVE4,
        Path.LINETO,
        Path.CLOSEPOLY,
    ]

    return Path(verts, codes)

if __name__ == "__main__":
    fig, ax = plt.subplots()
    patch = patches.PathPatch(droplet(), facecolor="aqua", lw=1)
    ax.add_patch(patch)

    ax.set_xlim(-1, 1)
    ax.set_ylim(-1, 1)

    plt.show()
    # plt.savefig("droplet.png", dpi=300)
    # plt.close(fig)