text:
import numpy as np
import scipy as sp
import scipy.optimize as opt
import scipy.stats as stats
import math
from Utils import logsumexp,inv_chol,logdet_chol,solve_chol
from copy import deepcopy

def gaussian_kl(mu1,Sigma1,mu2,Sigma2,cholSigma1 = None,cholSigma2 = None):
    if cholSigma1 == None:
        cholSigma1 = np.linalg.cholesky(Sigma1)
    if cholSigma2 == None:
        cholSigma2 = np.linalg.cholesky(Sigma2)
    d = len(mu1)

    dmu = np.linalg.solve(cholSigma1,mu1 - mu2)
    Lhat = np.linalg.solve(cholSigma2,cholSigma1)

#    dmu = sp.linalg.solve_triangular(cholSigma1,mu1 - mu2,lower=True)
#    Lhat = sp.linalg.solve_triangular(cholSigma2,cholSigma1,lower=True)

    logDetSigmaRatio = 2.0*(np.sum(np.log(np.diag(cholSigma2))) - np.sum(np.log(np.diag(cholSigma1))))
    trSigmaInvSigma = np.sum(np.power(Lhat,2)) - float(d)
    dmuTerm = np.sum(np.power(dmu,2),0)
    kl = 0.5*(logDetSigmaRatio + trSigmaInvSigma + dmuTerm)
    if kl <= -1e-10:
        print kl, logDetSigmaRatio, trSigmaInvSigma, dmuTerm
        assert(kl >= -1e-10)
    elif kl < 0:
        kl = 0
    return kl

def gaussian_kl_vec(mu1,Sigma1,mu2,Sigma2,cholSigma1 = None,cholSigma2 = None):
    d = mu1.shape[0]
    N = mu1.shape[1]

    if cholSigma1 == None:
        cholSigma1 = np.empty_like(Sigma1)
        for i in range(N):
            cholSigma1[:,:,i] = np.linalg.cholesky(Sigma1[:,:,i])
    if cholSigma2 == None:
        cholSigma2 = np.linalg.cholesky(Sigma2)

    SigmaInvSigma = solve_chol(cholSigma2,Sigma1.reshape((d,-1))).reshape((d,d,N))
    trSigmaInvSigma = np.trace(SigmaInvSigma) - float(d)

    muDiff = mu1 - mu2
    dmuDiff = np.copy(muDiff)
    for i in range(N):
        dmuDiff[:,i] = solve_chol(cholSigma1[:,:,i], muDiff[:,i])
    dmuTerm = np.sum(np.multiply(muDiff,dmuDiff),0)

    logDetSigmaRatio = 2.0*(np.sum(np.log(np.diagonal(cholSigma2)).reshape((1,d)),1) - np.sum(np.log(np.diagonal(cholSigma1)).reshape((N,d)),1))

    kl = np.maximum(0,0.5*(logDetSigmaRatio + trSigmaInvSigma + dmuTerm))

    return kl

def gaussian_logprob(x,mu,Sigma,cholSigma = None,normalized = True):
    if cholSigma == None:
        cholSigma = np.linalg.cholesky(Sigma)

    if mu == None:
        dx = np.linalg.solve(cholSigma,x)
    else:
        dx = np.linalg.solve(cholSigma,x - mu)

    quadForm = np.sum(np.power(dx,2),0)
#    quadForm = np.dot(dx.T,dx)

    if normalized:
        return -0.5*(np.sum(math.log(2.0*math.pi) + 2*np.log(np.diag(cholSigma))) + quadForm)
    else:
        return -0.5*quadForm

def gaussian_logprob_grad(x,mu,Sigma,cholSigma = None):
    if cholSigma == None:
        cholSigma = np.linalg.cholesky(Sigma)

    if mu == None:
        return -0.5*solve_chol(cholSigma,x).T
    else:
        return -0.5*solve_chol(cholSigma,x-mu).T

def gaussian_prec_logprob(x,mu,InvSigma,cholInvSigma = None,normalized = True):
    if mu == None:
        dx = x
    else:
        dx = x - mu

    quadForm = np.sum(np.multiply(dx,np.dot(InvSigma,dx)))
#    quadForm = np.dot(dx.T,np.dot(InvSigma,dx))

    if normalized:
        if cholInvSigma == None:
            cholInvSigma = np.linalg.cholesky(InvSigma)

        return -0.5*(np.sum(math.log(2.0*math.pi) - 2*np.log(np.diag(cholInvSigma))) + quadForm)
    else:
        return -0.5*quadForm

def gaussian_dist_xmu1xmu2_product_x(mu1,Sigma1,mu2,Sigma2):
    """Compute distribution of N(x|mu1,Sigma1)N(x|mu2,Sigma2)"""
    InvSigmaHat = np.linalg.inv(Sigma1) + np.linalg.inv(Sigma2)
    SigmaHat = np.linalg.inv(InvSigmaHat)
    muHat = np.dot(SigmaHat,np.linalg.solve(Sigma1, mu1) + np.linalg.solve(Sigma2,mu2))
    logC = gaussian_logprob(mu1,mu2,Sigma1 + Sigma2)
    return (logC,muHat,SigmaHat)

def gaussian_dist_yxxmu_product_x(y,Ay,by,Sigmay,mu,Sigma,cholSigmay = None,cholSigma = None,InvSigma = None):
    """Compute distribution p(x) \propto N(y|Ay*x+by,Sigmay)N(x|mu,Sigma)"""
    if cholSigma == None:
        cholSigma = np.linalg.cholesky(Sigma)
#    if InvSigma == None:
#        InvSigma = inv_chol(cholSigma)
    if cholSigmay == None:
        cholSigmay = np.linalg.cholesky(Sigmay)
    InvSigmayAy = solve_chol(cholSigmay, Ay)

    yDim = len(y)
    xDim = len(mu)

    SigmaBar = Sigmay + np.dot(Ay,np.dot(Sigma,Ay.T))
    # SigmaHat = (Ay.T * Sigma_y^-1 * Ay + Sigma^-1)^-1
    #          = Sigma - Sigma * Ay.T * inv(Sigma_y + A*Sigma*A.T) * A * Sigma (woodbury)
    tmpSigmaHat = np.identity(Sigma.shape[0]) - np.dot(Sigma, np.dot(Ay.T,np.linalg.solve(SigmaBar,Ay)))
    SigmaHat = np.dot(tmpSigmaHat,Sigma)

    muHat = np.dot(SigmaHat, np.dot(InvSigmayAy.T, y - by)) + np.dot(tmpSigmaHat,mu)
    logC = gaussian_logprob(y,np.dot(Ay,mu)+by,SigmaBar,normalized = False) \
            + np.sum(np.log(np.diag(np.linalg.cholesky(SigmaHat)))) \
            - np.sum(np.log(np.diag(cholSigma))) \
            - 0.5*yDim*np.log(2.0*math.pi) - np.sum(np.log(np.diag(cholSigmay)))

    return (logC,muHat,SigmaHat)

def gaussian_dist_yxxz_intxproduct_z(y,Ay,by,Sigmay,Ax,bx,Sigmax,mu,Sigma):
    """
    Compute distribution of p(z) = C * N(z|mu,Sigma) \int N(y|Ay*x + by,Sigmay)N(x|Ax*z + bx,Sigmax) dx
                                 = N(m,S)

    Returns (logC,muBar,SigmaBar).
    """
    cholSigmax = np.linalg.cholesky(Sigmax)
    cholSigmay = np.linalg.cholesky(Sigmay)
    cholSigma = np.linalg.cholesky(Sigma)
    InvSigmax = inv_chol(cholSigmax)
    InvSigmay = inv_chol(cholSigmay)
    InvSigma = inv_chol(cholSigma)
    InvSigmayAy = np.dot(InvSigmay,Ay)

    mhatxy = np.dot(Ay.T,np.dot(InvSigmay,y - by)) - np.dot(InvSigmax,bx)
    Pxy = np.dot(Ay.T, InvSigmayAy) + InvSigmax
    cholPxy = np.linalg.cholesky(Pxy)
#    Pzy = np.dot(Ax.T,np.dot(InvSigmax - np.dot(InvSigmax,solve_chol(cholPxy,InvSigmax)),Ax)) + InvSigma
    Pzy = np.dot(Ax.T,np.dot(InvSigmax,Ax)) - np.dot(Ax.T,np.dot(InvSigmax,solve_chol(cholPxy,InvSigmax)),Ax) + InvSigma
    Pzym = np.dot(Ax.T,solve_chol(cholSigmax,solve_chol(cholPxy, (np.dot(Ay.T,solve_chol(cholSigmay,y)) - solve_chol(cholSigmax,bx)) ))) + solve_chol(cholSigma,mu)
    cholPzy = np.linalg.cholesky(Pzy)
    m = solve_chol(cholPzy,Pzym)
    S = inv_chol(cholPzy)
    rt2pi = math.sqrt(2.0*math.pi)
    logC = gaussian_logprob(bx,0,Sigmax) + gaussian_logprob(mu,0,Sigma) + gaussian_logprob(y,by,Sigmay) - 0.5*(logdet_chol(rt2pi*cholPxy) + logdet_chol(rt2pi*cholPzy))\
           + 0.5*(np.dot(mhatxy.T,solve_chol(cholPxy,mhatxy)) + np.dot(m.T,Pzym))
#    print y - by,bx
#    print mhatxy
#    print Pxy
#    print Pzy
#    print m
#    print 'quadBits = ',0.5*(np.dot(mhatxy.T,solve_chol(cholPxy,mhatxy))), 0.5*np.dot(m.T,Pzym)
    return (logC,m,S)

#class GaussianDistribution:
#    __mu = None
#    __Sigma = None
#    __CholSigma = None

def klDiv_var(Phi,logPhi,logPsi,KLdivs):
    finitePhiInds = np.nonzero(np.isfinite(logPhi))
    D_upper = np.sum(np.multiply(Phi[finitePhiInds],logPhi[finitePhiInds] - logPsi[finitePhiInds])) + np.sum(np.multiply(Phi[finitePhiInds],KLdivs[finitePhiInds]))
    return D_upper

def klDiv_varit(Phi,logPhi,logPsi,logweights_ref,logweights_other,KLdivs,upd_other_logweights = False):
    tmp = logPsi - KLdivs
    lsetmp = logsumexp(tmp,0)
    lsetmp[np.logical_not(np.isfinite(lsetmp))] = 0
    logPhi = logweights_ref.reshape((1,-1)) + (tmp - lsetmp)
    Phi = np.exp(logPhi)
    if upd_other_logweights:
        logweights_other = logsumexp(logPhi,1)
    logPsi = logweights_other.reshape((-1,1)) + logPhi - logsumexp(logPhi,1).reshape((-1,1))

    D_upper = klDiv_var(Phi,logPhi,logPsi,KLdivs)

    if upd_other_logweights:
        return (D_upper,Phi,logPhi,logPsi,logweights_other)
    else:
        return (D_upper,Phi,logPhi,logPsi)

class GaussianMixtureModel:
    logweights = None
    mus = None
    Sigmas = None
    dim = 0

    def __init__(self,dim,nComps = 0):
        self.logweights = np.empty((nComps))
        self.mus = np.asarray(np.empty((dim,nComps)))
        self.Sigmas = np.asarray(np.empty((dim,dim,nComps)))
        self.dim = dim

    def klDivergence_varupper(self,other):
        """ Returns an (upper bound) approximation to KL(self||other). """
        D = self.dim
        Nref = self.numComps()
        Nother = other.numComps()

        if KLdivs == None:
            cholSigmaSelf = np.empty((D,D,Nref))
            for b in range(Nref):
                cholSigmaSelf[:,:,b] = np.linalg.cholesky(self.getSigma(b))

            KLdivs = np.empty((Nother,Nref))
            for b in range(Nother):
                mub = other.getMu(b)
                Sigmab = other.getSigma(b)
                cholSigmab = np.linalg.cholesky(other.getSigma(b))

                KLdivs[b,:] = gaussian_kl_vec(self.mus,self.Sigmas,mub,Sigmab,cholSigma1 = cholSigmaSelf,cholSigma2 = cholSigmab)

        logPhi = other.logweights.reshape(Nother,1) + self.logweights.reshape(1,Nref)
        logPsi = self.logweights.reshape(Nother,1) + logPhi - logsumexp(logPhi,1).reshape((Nother,1))
        Phi = np.exp(logPhi)

        done = False
        itNum = 0
        D_upper = np.inf
        while not done:
            itNum += 1
            last_D_upper = D_upper

            (D_upper,Phi,logPhi,logPsi) = klDiv_varit(Phi,logPhi,logPsi,self.logweights,other.logweights,KLdivs)

            assert(np.isfinite(D_upper))
            print '{0}: D_upper = {2}'.format(itNum,D_upper)
            if D_upper - last_D_upper > 1e-6:
                break

        return D_upper

    def simplify(self,ref = None,natThresh = None,minNumComps = 1):
        """ Remove components and adjust the mixture until just before the KL divergence exceeds natThresh """
        maxNumSubVarIts = 5
        maxNumVarIts = 20
        maxNumDelPerIt = 1

        D = self.dim
        Nself = self.numComps()
        Nnew = Nself

        # Compute Cholesky decompositions
        cholSigmaSelf = np.empty((D,D,Nself))
        for b in range(Nself):
            cholSigmaSelf[:,:,b] = np.linalg.cholesky(self.getSigma(b))

        if ref == None:
            ref = deepcopy(self)
            cholSigmaRef = deepcopy(cholSigmaSelf)
            Nref = Nself
            # Initialize the variational parameters
            Phi = np.diag(np.exp(self.logweights.reshape(Nnew)))
#            logPhi = np.log(Phi)
            logPhi = np.empty_like(Phi)
            logPhi[Phi > 0] = np.log(Phi[Phi > 0])
            logPhi[Phi <= 0] = -np.inf
#            logPsi = np.log(Phi)
            logPsi = np.copy(logPhi)
        else:
            Nref = ref.numComps()
            cholSigmaRef = np.empty((D,D,Nref))
            for a in range(Nref):
                cholSigmaRef[:,:,a] = np.linalg.cholesky(ref.getSigma(a))
            # Initialize the variational parameters
            logPhi = self.logweights.reshape(Nnew,1) + ref.logweights.reshape(1,Nref)
            logPsi = self.logweights.reshape(Nnew,1) + logPhi - logsumexp(logPhi,1).reshape((Nnew,1))
            Phi = np.exp(logPhi)

        # Compute KL divergence between components
        KLdivs = np.empty((Nself,Nref))
        for b in range(Nself):
            mub = self.getMu(b)
            Sigmab = self.getSigma(b)
            cholSigmab = cholSigmaSelf[:,:,b]

            KLdivs[b,:] = gaussian_kl_vec(ref.mus,ref.Sigmas,mub,Sigmab,cholSigma1 = cholSigmaRef,cholSigma2 = cholSigmab)
        del cholSigmaSelf

        new_D_upper = klDiv_var(Phi,logPhi,logPsi,KLdivs)

        newActiveComps = [i for i in range(0,Nself)]
        newActiveComps.sort(key=lambda x: self.logweights[x])

        globalVarItCnt = 0
        itNum = 0
        while Nnew-maxNumDelPerIt >= minNumComps:
            itNum += 1

            currNumDel = 1
#            delLogW = logsumexp(self.logweights[newActiveComps[0:2]])
#            while delLogW < np.log(1e-4) and currNumDel < maxNumDelPerIt:
#                currNumDel += 1
#                delLogW = logsumexp(self.logweights[newActiveComps[0:(currNumDel+1)]])
#            print '{0}: numDel = {1}'.format(itNum,currNumDel)
            delCompI = newActiveComps[0:currNumDel]
            propComps = newActiveComps[currNumDel:]
            numDel = len(delCompI)
            Nprop = Nnew-numDel

            propLogWeights = np.logaddexp(self.logweights[propComps], logsumexp(self.logweights[delCompI]) - np.log(Nprop))
            propMus = self.mus[:,propComps].reshape((D,Nprop))
            propSigmas = self.Sigmas[:,:,propComps].reshape((D,D,Nprop))

            propLogPhi = np.logaddexp(logPhi[propComps,:],logsumexp(logsumexp(logPhi[delCompI,:],1),0) - np.log(Nprop))
            propPhi = np.exp(propLogPhi)
            prevNormPropPhi = None
            propKLdivs = KLdivs[propComps,:]
            propLogPsi = propLogWeights.reshape(Nprop,1) + propLogPhi - logsumexp(propLogPhi,1).reshape((Nprop,1))

            D_upper = klDiv_var(propPhi,propLogPhi,propLogPsi,propKLdivs)

            varItNum = 0
#            while varItNum < maxNumVarIts and (itNum == 0 or D_upper >= natThresh):
            while varItNum < maxNumVarIts and (varItNum == 0 or D_upper >= natThresh):
                varItNum += 1
                globalVarItCnt += 1

                last_propLogWeights = propLogWeights
                lastVarIt_D_upper = D_upper

                # Minimize the upper bound wrt the variational parameters and log weights
                subVarItNum = 0
                while subVarItNum < maxNumSubVarIts and D_upper >= natThresh:
                    lastsub_propLogWeights = propLogWeights
                    lastSubVarIt_D_upper = D_upper
                    (D_upper,propPhi,propLogPhi,propLogPsi,propLogWeights) = klDiv_varit(propPhi,propLogPhi,propLogPsi,ref.logweights,propLogWeights,propKLdivs,True)
                    if np.abs(D_upper - lastSubVarIt_D_upper) < 1e-6:
                        break

                if D_upper >= natThresh:
                    normPropPhi = np.exp(propLogPhi - logsumexp(propLogPhi,1).reshape(Nprop,1))
                    if prevNormPropPhi != None:
#                        updPropComps = np.nonzero(np.sum(np.abs(normPropPhi - prevNormPropPhi),1).ravel() > 1e-2)
#                        updPropComps = updPropComps[0]
                        updPropComps = np.array([np.argmax(np.sum(np.abs(normPropPhi - prevNormPropPhi),1).ravel())])
                    else:
                        updPropComps = range(Nprop)
#                    updPropComps = range(Nprop)
#                    updPropComps = np.array([np.argmax(logsumexp(propLogPhi,1).ravel())])
                else:
                    updPropComps = []

                if len(updPropComps) > 0:
                    if prevNormPropPhi == None:
                        prevNormPropPhi = normPropPhi
                    else:
                        prevNormPropPhi[updPropComps,:] = normPropPhi[updPropComps,:]
                    propMus[:,updPropComps] = np.dot(ref.mus,normPropPhi[updPropComps,:].T)
                    dmus = propMus[:,updPropComps].reshape(D,-1,1) - ref.mus.reshape(D,1,Nref)
                    dmuCovs = np.multiply(dmus.reshape(D,1,-1,Nref),dmus.reshape(1,D,-1,Nref))
                    #updPropSigmas = np.sum(np.multiply((ref.Sigmas.reshape(D,D,1,Nref) + dmuCovs).reshape((D,D,-1,Nref)),normPropPhi[updPropComps,:].reshape((1,1,-1,Nref))),3)
                    updPropSigmas = np.sum(np.multiply(ref.Sigmas.reshape(D,D,1,Nref),normPropPhi[updPropComps,:].reshape((1,1,-1,Nref))),3) + np.sum(np.multiply(dmuCovs.reshape((D,D,-1,Nref)),normPropPhi[updPropComps,:].reshape((1,1,-1,Nref))),3)
                    propSigmas[:,:,updPropComps] = updPropSigmas

                    prev___D_upper = D_upper
                    prev___KLDivs = propKLdivs[updPropComps,:]
                    for (tInd,propInd) in enumerate(updPropComps):
                        mub = propMus[:,propInd].reshape((D,1))
                        Sigmab = propSigmas[:,:,propInd]
                        propKLdivs[propInd,:] = gaussian_kl_vec(ref.mus,ref.Sigmas,mub,Sigmab,cholSigma1 = cholSigmaRef)

#                    (D_upper,propPhi,propLogPhi,propLogPsi,propLogWeights) = klDiv_varit(propPhi,propLogPhi,propLogPsi,ref.logweights,propLogWeights,propKLdivs,True)
                    D_upper = klDiv_var(propPhi,propLogPhi,propLogPsi,propKLdivs)
                    if False and D_upper - prev___D_upper >= 1e-6:
                        print '{0} -> {1}'.format(prev___D_upper,D_upper)
                        print 'prevKLDivs = {0}'.format(prev___KLDivs)
                        print 'currKLDivs = {0}'.format(propKLdivs[updPropComps,:])
                        assert(D_upper - prev___D_upper < 1e-6)
#                    print '{0} -> {1}'.format(prev___D_upper,D_upper)
                    if prev___D_upper >= D_upper + 1e-8:
                        break

#                (D_upper,propPhi,propLogPhi,propLogPsi,propLogWeights) = klDiv_varit(propPhi,propLogPhi,propLogPsi,ref.logweights,propLogWeights,propKLdivs,True)
#                print '  {1}: D_upper = {0}, subVarItNums = {2}'.format(D_upper,varItNum,subVarItNum)

                if np.abs(D_upper - lastVarIt_D_upper) < 1e-6 and np.all(np.abs(last_propLogWeights - propLogWeights) < 1e-6):
                    break

#            print '{2}: D_upper = {0}, varItNums = {1}'.format(D_upper,varItNum,itNum)

            if D_upper > natThresh:
                break
            else:
                Nnew = Nprop
                new_D_upper = D_upper

                KLdivs[propComps,:] = propKLdivs
                logPhi[propComps,:] = propLogPhi
                Phi[propComps,:] = propPhi
                logPsi[propComps,:] = propLogPsi

                self.logweights[delCompI] = -np.inf
                self.logweights[propComps] = propLogWeights
                self.mus[:,propComps] = propMus
                self.Sigmas[:,:,propComps] = propSigmas

                while numDel > 0:
                    newActiveComps.pop(0)
                    numDel += -1
                newActiveComps.sort(key=lambda x: self.logweights[x])

        if Nnew < Nself:
            self.logweights = self.logweights[newActiveComps]
            self.mus = self.mus[:,newActiveComps].reshape(D,Nnew)
            self.Sigmas = self.Sigmas[:,:,newActiveComps].reshape(D,D,Nnew)

        return new_D_upper

    def getLogW(self,compI):
        return self.logweights[compI]

    def getMu(self,compI):
        if isinstance(compI,(int, long)):
            return np.reshape(self.mus[:,compI],(self.dim,1))
        else:
            return np.reshape(self.mus[:,compI],(self.dim,compI.size))

    def getSigma(self,compI):
        if isinstance(compI,(int, long)):
            return np.reshape(self.Sigmas[:,:,compI],(self.dim,self.dim))
        else:
            return np.reshape(self.Sigmas[:,:,compI],(self.dim,self.dim,compI.size))

    def drawSamples(self,N):
        Ws = np.exp(self.logweights - logsumexp(self.logweights))
        sampleComps = np.random.multinomial(N,Ws)
        samples = np.empty((self.dim,N))
        startInd = 0
        for i in range(len(sampleComps)):
            cN = sampleComps[i]
            if cN < 0:
                print cN
                print sampleComps
                print Ws
                print self.logweights
            assert(cN >= 0)
            assert(startInd >= 0)
            samples[:,startInd:(startInd+cN)] = self.getMu(i) + np.dot(np.linalg.cholesky(self.Sigmas[:,:,i]),np.random.randn(self.dim,cN))
            startInd += cN
        return samples

    def logProb(self,x):
        N = self.numComps()
        if len(x.shape) == 1:
            x = x.reshape((self.dim,-1))
        lps = np.empty((N,x.shape[1]))
        for i in range(N):
            lps[i,:] = gaussian_logprob(x,self.getMu(i),self.Sigmas[:,:,i]) + self.logweights[i]
        return logsumexp(lps,0)

    def dlogProb(self,x):
        N = self.numComps()
        origxshape = x.shape
        if len(x.shape) == 1:
            x = x.reshape((self.dim,1))
        lps = np.empty((N,1))
        grads = np.empty((N,self.dim))
        for i in range(N):
            cmu = self.getMu(i)
            cSigma = self.Sigmas[:,:,i]
            cholSigma = np.linalg.cholesky(cSigma)
            lps[i,0] = gaussian_logprob(x,cmu,cSigma,cholSigma) + self.logweights[i]
            grads[i,:] = gaussian_logprob_grad(x,cmu,cSigma,cholSigma)
        return np.sum(np.multiply(np.exp(lps-logsumexp(lps,0)),grads),0).reshape(origxshape)

    def findMaximum(self,x0 = None):
        if x0 == None:
            lp = self.logProb(self.mus)
            minI = np.argmax(lp.reshape(-1))
            x0 = self.getMu(minI)
#        optRes = opt.fmin(lambda x: -self.logProb(x), x0, disp=False)
        optRes = opt.fmin_bfgs(lambda x: -self.logProb(x), x0, disp=False, fprime = lambda x: -self.dlogProb(x))
        return optRes

    def productGaussianDist(self,mu,Sigma):
        newDist = self
        for i in range(self.numComps()):
            (clogC, cmu, cSigma) = gaussian_dist_xmu1xmu2_product_x(mu,Sigma,self.getMu(i),self.Sigmas[:,:,i])
            newDist.mus[:,[i]] = cmu
            newDist.Sigmas[:,:,i] = cSigma
            newDist.logweights[i] += clogC
        logC = newDist.normalizeWeights()
        return (logC,newDist)

    def numComps(self):
        return len(self.logweights)

    def addMixture(self,w,mixDist):
        self.logweights = np.hstack((self.logweights,mixDist.logweights + np.log(w)))
        self.mus = np.hstack((self.mus,mixDist.mus))
        self.Sigmas = np.dstack((self.Sigmas,mixDist.Sigmas))

    def addMixtureLogW(self,logw,mixDist):
        self.logweights = np.hstack((self.logweights,mixDist.logweights + logw))
        self.mus = np.hstack((self.mus,mixDist.mus))
        self.Sigmas = np.dstack((self.Sigmas,mixDist.Sigmas))

    def addComponent(self,w,mu,Sigma):
        self.logweights = np.hstack((self.logweights,np.log(w)))
        self.mus = np.hstack((self.mus,mu))
        self.Sigmas = np.dstack((self.Sigmas,Sigma))

    def addComponentLogW(self,logw,mu,Sigma):
        logw = np.asarray(logw)
        self.logweights = np.hstack((self.logweights,logw))
        self.mus = np.hstack((self.mus,mu))
        self.Sigmas = np.dstack((self.Sigmas,np.asarray(Sigma)))

    def setComponentLogW(self,compI,logw,mu,Sigma):
        logw = np.asarray(logw)
        compI = np.asarray(compI).ravel()
        self.logweights[compI] = logw
        self.mus[:,compI] = mu.reshape((self.dim,compI.size))
        self.Sigmas[:,:,compI] = Sigma.reshape((self.dim,self.dim,compI.size))

    def normalizeWeights(self):
        N = self.numComps()
        if N == 0:
            return -np.inf
        elif N == 1:
            normFactor = self.logweights[0]
            self.logweights[0] = 0
#            print 'Normalizing single component mixture, normFactor = {0}, lw = {1}'.format(normFactor,self.logweights[0,0])
            return normFactor
        else:
            normFactor = logsumexp(self.logweights)
            assert(np.isfinite(normFactor))
            self.logweights -= normFactor
            normFactor2 = logsumexp(self.logweights)
            if np.abs(normFactor2) > 1e-8:
                normFactor += normFactor2
                self.logweights -= normFactor2
            return normFactor

    def transform(self,A,b):
        newDim = A.shape[0]
        transMM = GaussianMixtureModel(newDim,self.numComps())
        transMM.logweights = deepcopy(self.logweights)
        transMM.mus = np.dot(A,self.mus) + b
        for compI in range(self.numComps()):
            transMM.Sigmas[:,:,compI] = np.dot(np.dot(A,self.Sigmas[:,:,compI]),A.T)
        return transMM

#    def cdf(self,ub):
#        assert(self.dim == 1) # Unimplmemented for multivariate gaussians
#        return np.exp(self.logcdf(ub))
#
#    def logcdf(self,ub):
#        assert(self.dim == 1) # Unimplmemented for multivariate gaussians
#        logcdfs = deepcopy(self.logweights)
#        for compI in range(self.numComps()):
#            logcdfs[compI] += stats.norm.logcdf(ub,self.mus[0,compI],np.sqrt(self.Sigmas[0,0,compI]))
#        return logsumexp(logcdfs)
    def logcdf(self,ub):
        assert(self.dim == 1) # Unimplmemented for multivariate gaussians
        return np.log(self.cdf(ub))

    def cdf(self,ub):
        assert(self.dim == 1) # Unimplmemented for multivariate gaussians
        ret = np.zeros_like(ub)
        for compI in range(self.numComps()):
            ccdf = stats.norm.cdf(ub,self.mus[0,compI],np.sqrt(self.Sigmas[0,0,compI]))
            ret[ccdf > 0] += np.exp(self.logweights[compI] + np.log(ccdf[ccdf > 0]))
        return ret

    def removeUnusedComponents(self):
        goodComps = np.flatnonzero(np.isfinite(self.logweights))
        self.logweights = self.logweights[goodComps]
        self.mus = np.reshape(self.mus[:,goodComps],(self.dim,len(goodComps)))
        self.Sigmas = np.reshape(self.Sigmas[:,:,goodComps],(self.dim,self.dim,len(goodComps)))

    def computeMeanCovar(self):
        weights = np.exp(self.logweights - logsumexp(self.logweights))
        mu = np.dot(self.mus,weights).reshape((self.dim,1))
        Ex2 = np.reshape(np.dot(self.Sigmas,weights),(self.dim,self.dim)) + np.asarray(np.dot(np.multiply(self.mus,weights),self.mus.T))
        Sigma = Ex2 - np.dot(mu, mu.T)
        return (mu,Sigma)

    def computeMean(self):
        weights = np.exp(self.logweights - logsumexp(self.logweights))
        mu = np.dot(self.mus,weights).reshape((self.dim,1))
        return mu

    def printDist(self):
        for i in range(len(self.logweights)):
            print 'Component {0}: log(w) = {1}'.format(i,self.logweights[i])
            print '  mu       sigma'
            for d in range(self.dim):
                print '  {0} {1}'.format(self.mus[d,i],self.Sigmas[d,:,i])

reason: import numpy,import scipy


text:
from abc import ABCMeta, abstractmethod
import numpy as np
from deeppavlov.core.commands.utils import expand_path
from keras.preprocessing.sequence import pad_sequences
from deeppavlov.core.common.log import get_logger

log = get_logger(__name__)

class RankingDict(metaclass=ABCMeta):
    """Class to encode characters, tokens, whole contexts and responses with vocabularies, to pad and truncate.

    Args:
        save_path: A path including filename to store the instance of
            :class:`deeppavlov.models.ranking.ranking_network.RankingNetwork`.
        load_path: A path including filename to load the instance of
            :class:`deeppavlov.models.ranking.ranking_network.RankingNetwork`.
        max_sequence_length: A maximum length of a sequence in tokens.
            Longer sequences will be truncated and shorter ones will be padded.
        tok_dynamic_batch:  Whether to use dynamic batching. If ``True``, a maximum length of a sequence for a batch
            will be equal to the maximum of all sequences lengths from this batch,
            but not higher than ``max_sequence_length``.
        padding: Padding. Possible values are ``pre`` and ``post``.
            If set to ``pre`` a sequence will be padded at the beginning.
            If set to ``post`` it will padded at the end.
        truncating: Truncating. Possible values are ``pre`` and ``post``.
            If set to ``pre`` a sequence will be truncated at the beginning.
            If set to ``post`` it will truncated at the end.
        max_token_length: A maximum length of a token for representing it by a character-level embedding.
        char_dynamic_batch: Whether to use dynamic batching for character-level embeddings.
            If ``True``, a maximum length of a token for a batch
            will be equal to the maximum of all tokens lengths from this batch,
            but not higher than ``max_token_length``.
        char_pad: Character-level padding. Possible values are ``pre`` and ``post``.
            If set to ``pre`` a token will be padded at the beginning.
            If set to ``post`` it will padded at the end.
        char_trunc: Character-level truncating. Possible values are ``pre`` and ``post``.
            If set to ``pre`` a token will be truncated at the beginning.
            If set to ``post`` it will truncated at the end.
        update_embeddings: Whether to store and update context and response embeddings or not.
    """

    def __init__(self,
                 save_path: str,
                 load_path: str,
                 max_sequence_length: int,
                 max_token_length: int,
                 padding: str = 'post',
                 truncating: str = 'post',
                 token_embeddings: bool = True,
                 char_embeddings: bool = False,
                 char_pad: str = 'post',
                 char_trunc: str = 'post',
                 tok_dynamic_batch: bool = False,
                 char_dynamic_batch: bool = False,
                 update_embeddings: bool = False):

        self.max_sequence_length = max_sequence_length
        self.token_embeddings = token_embeddings
        self.char_embeddings = char_embeddings
        self.max_token_length = max_token_length
        self.padding = padding
        self.truncating = truncating
        self.char_pad = char_pad
        self.char_trunc = char_trunc
        self.tok_dynamic_batch = tok_dynamic_batch
        self.char_dynamic_batch = char_dynamic_batch
        self.upd_embs = update_embeddings

        save_path = expand_path(save_path).resolve().parent
        load_path = expand_path(load_path).resolve().parent

        self.char_save_path = save_path / "char2int.dict"
        self.char_load_path = load_path / "char2int.dict"
        self.tok_save_path = save_path / "tok2int.dict"
        self.tok_load_path = load_path / "tok2int.dict"
        self.cont_save_path = save_path / "cont2toks.dict"
        self.cont_load_path = load_path / "cont2toks.dict"
        self.resp_save_path = save_path / "resp2toks.dict"
        self.resp_load_path = load_path / "resp2toks.dict"
        self.cemb_save_path = str(save_path / "context_embs.npy")
        self.cemb_load_path = str(load_path / "context_embs.npy")
        self.remb_save_path = str(save_path / "response_embs.npy")
        self.remb_load_path = str(load_path / "response_embs.npy")

        self.int2tok_vocab = {}
        self.tok2int_vocab = {}
        self.response2toks_vocab = {}
        self.response2emb_vocab = {}
        self.context2toks_vocab = {}
        self.context2emb_vocab = {}

    def init_from_scratch(self):
        log.info("[initializing new `{}`]".format(self.__class__.__name__))
        if self.char_embeddings:
            self.build_int2char_vocab()
            self.build_char2int_vocab()
        self.build_int2tok_vocab()
        self.build_tok2int_vocab()
        self.build_context2toks_vocabulary()
        self.build_response2toks_vocabulary()
        if self.upd_embs:
            self.build_context2emb_vocabulary()
            self.build_response2emb_vocabulary()

    def load(self):
        log.info("[initializing `{}` from saved]".format(self.__class__.__name__))
        if self.char_embeddings:
            self.load_int2char()
            self.build_char2int_vocab()
        self.load_int2tok()
        self.build_tok2int_vocab()
        self.load_context2toks()
        self.load_response2toks()
        if self.upd_embs:
            self.load_cont()
            self.load_resp()

    def save(self):
        log.info("[saving `{}`]".format(self.__class__.__name__))
        if self.char_embeddings:
            self.save_int2char()
        self.save_int2tok()
        self.save_context2toks()
        self.save_response2toks()
        if self.upd_embs:
            self.save_cont()
            self.save_resp()

    @abstractmethod
    def build_int2char_vocab(self):
        pass

    @abstractmethod
    def build_int2tok_vocab(self):
        pass

    @abstractmethod
    def build_response2toks_vocabulary(self):
        pass

    @abstractmethod
    def build_context2toks_vocabulary(self):
        pass

    def build_char2int_vocab(self):
        self.char2int_vocab = {el[1]: el[0] for el in self.int2char_vocab.items()}

    def build_tok2int_vocab(self):
        self.tok2int_vocab = {el[1]: el[0] for el in self.int2tok_vocab.items()}

    def build_response2emb_vocabulary(self):
        for i in range(len(self.response2toks_vocab)):
            self.response2emb_vocab[i] = None

    def build_context2emb_vocabulary(self):
        for i in range(len(self.context2toks_vocab)):
            self.context2emb_vocab[i] = None

    def conts2toks(self, conts_li):
        toks_li = [self.context2toks_vocab[cont] for cont in conts_li]
        return toks_li

    def resps2toks(self, resps_li):
        toks_li = [self.response2toks_vocab[resp] for resp in resps_li]
        return toks_li

    def make_toks(self, items_li, type):
        if type == "context":
            toks_li = self.conts2toks(items_li)
        elif type == "response":
            toks_li = self.resps2toks(items_li)
        return toks_li

    def make_ints(self, toks_li):
        if self.tok_dynamic_batch:
            msl = min(max([len(el) for el in toks_li]), self.max_sequence_length)
        else:
            msl = self.max_sequence_length
        if self.char_dynamic_batch:
            mtl = min(max(len(x) for el in toks_li for x in el), self.max_token_length)
        else:
            mtl = self.max_token_length

        if self.token_embeddings and not self.char_embeddings:
            return self.make_tok_ints(toks_li, msl)
        elif not self.token_embeddings and self.char_embeddings:
            return self.make_char_ints(toks_li, msl, mtl)
        elif self.token_embeddings and self.char_embeddings:
            tok_ints = self.make_tok_ints(toks_li, msl)
            char_ints = self.make_char_ints(toks_li, msl, mtl)
            return np.concatenate([np.expand_dims(tok_ints, axis=2), char_ints], axis=2)

    def make_tok_ints(self, toks_li, msl):
        ints_li = []
        for toks in toks_li:
            ints = []
            for tok in toks:
                index = self.tok2int_vocab.get(tok)
                if self.tok2int_vocab.get(tok) is not None:
                    ints.append(index)
                else:
                    ints.append(0)
            ints_li.append(ints)
        ints_li = pad_sequences(ints_li,
                                maxlen=msl,
                                padding=self.padding,
                                truncating=self.truncating)
        return ints_li

    def make_char_ints(self, toks_li, msl, mtl):
        ints_li = np.zeros((len(toks_li), msl, mtl))

        for i, toks in enumerate(toks_li):
            if self.truncating == 'post':
                toks = toks[:msl]
            else:
                toks = toks[-msl:]
            for j, tok in enumerate(toks):
                if self.padding == 'post':
                    k = j
                else:
                    k = j + msl - len(toks)
                ints = []
                for char in tok:
                    index = self.char2int_vocab.get(char)
                    if index is not None:
                        ints.append(index)
                    else:
                        ints.append(0)
                if self.char_trunc == 'post':
                    ints = ints[:mtl]
                else:
                    ints = ints[-mtl:]
                if self.char_pad == 'post':
                    ints_li[i, k, :len(ints)] = ints
                else:
                    ints_li[i, k, -len(ints):] = ints
        return ints_li

    def save_int2char(self):
        with self.char_save_path.open('w') as f:
            f.write('\n'.join(['\t'.join([str(el[0]), el[1]]) for el in self.int2char_vocab.items()]))

    def load_int2char(self):
        with self.char_load_path.open('r') as f:
            data = f.readlines()
        self.int2char_vocab = {int(el.split('\t')[0]): el.split('\t')[1][:-1] for el in data}

    def save_int2tok(self):
        with self.tok_save_path.open('w') as f:
            f.write('\n'.join(['\t'.join([str(el[0]), el[1]]) for el in self.int2tok_vocab.items()]))

    def load_int2tok(self):
        with self.tok_load_path.open('r') as f:
            data = f.readlines()
        self.int2tok_vocab = {int(el.split('\t')[0]): el.split('\t')[1][:-1] for el in data}

    def save_context2toks(self):
        with self.cont_save_path.open('w') as f:
            f.write('\n'.join(['\t'.join([str(el[0]), ' '.join(el[1])]) for el in self.context2toks_vocab.items()]))

    def load_context2toks(self):
        with self.cont_load_path.open('r') as f:
            data = f.readlines()
        self.context2toks_vocab = {int(el.split('\t')[0]): el.split('\t')[1][:-1].split(' ') for el in data}

    def save_response2toks(self):
        with self.resp_save_path.open('w') as f:
            f.write(
                '\n'.join(['\t'.join([str(el[0]), ' '.join(el[1])]) for el in self.response2toks_vocab.items()]))

    def load_response2toks(self):
        with self.resp_load_path.open('r') as f:
            data = f.readlines()
        self.response2toks_vocab = {int(el.split('\t')[0]): el.split('\t')[1][:-1].split(' ') for el in data}

    def save_cont(self):
        context_embeddings = []
        for i in range(len(self.context2emb_vocab)):
            context_embeddings.append(self.context2emb_vocab[i])
        context_embeddings = np.vstack(context_embeddings)
        np.save(self.cemb_save_path, context_embeddings)

    def load_cont(self):
        context_embeddings_arr = np.load(self.cemb_load_path)
        for i in range(context_embeddings_arr.shape[0]):
            self.context2emb_vocab[i] = context_embeddings_arr[i]

    def save_resp(self):
        response_embeddings = []
        for i in range(len(self.response2emb_vocab)):
            response_embeddings.append(self.response2emb_vocab[i])
        response_embeddings = np.vstack(response_embeddings)
        np.save(self.remb_save_path, response_embeddings)

    def load_resp(self):
        response_embeddings_arr = np.load(self.remb_load_path)
        for i in range(response_embeddings_arr.shape[0]):
            self.response2emb_vocab[i] = response_embeddings_arr[i]

ext: py

max_stars_repo_name: amithfernando/DeepPavlov

max_issues_repo_name: amithfernando/DeepPavlov

max_forks_repo_name: amithfernando/DeepPavlov

reason: import numpy


text:
from collections import namedtuple
import functools
import itertools
from multiprocessing import Pool as ProcessPool
from multiprocessing.pool import ThreadPool
import os
import re
import warnings

import numpy as np
from scipy import stats

__all__ = ['distribution_fit', 'DistributionFit']

DistributionFit = namedtuple('DistributionFit', ['name', 'args', 'fit'])

_distributions = ('alpha', 'anglit', 'arcsine', 'argus', 'beta', 'betaprime', 'bradford', 'burr', 'burr12', 'cauchy', 'chi', 'chi2', 'cosine', 'crystalball', 'dgamma', 'dweibull', 'erlang', 'expon', 'exponnorm', 'exponweib', 'exponpow', 'f', 'fatiguelife', 'fisk', 'foldcauchy', 'foldnorm', 'frechet_r', 'frechet_l', 'genlogistic', 'gennorm', 'genpareto', 'genexpon', 'genextreme', 'gausshyper', 'gamma', 'gengamma', 'genhalflogistic', 'gilbrat', 'gompertz', 'gumbel_r', 'gumbel_l', 'halfcauchy', 'halflogistic', 'halfnorm', 'halfgennorm', 'hypsecant', 'invgamma', 'invgauss', 'invweibull', 'johnsonsb', 'johnsonsu', 'kappa4', 'kappa3', 'ksone', 'kstwobign', 'laplace', 'levy', 'levy_l', 'levy_stable', 'logistic', 'loggamma', 'loglaplace', 'lognorm', 'lomax', 'maxwell', 'mielke', 'moyal', 'nakagami', 'ncx2', 'ncf', 'nct', 'norm', 'norminvgauss', 'pareto', 'pearson3', 'powerlaw', 'powerlognorm', 'powernorm', 'rdist', 'reciprocal', 'rayleigh', 'rice', 'recipinvgauss', 'semicircular', 'skewnorm', 't', 'trapz', 'triang', 'truncexpon', 'truncnorm', 'tukeylambda', 'uniform', 'vonmises', 'vonmises_line', 'wald', 'weibull_min', 'weibull_max', 'wrapcauchy')

def np_cache(**kwargs):
    def decorator(function):
        @functools.lru_cache(**kwargs)
        def cached_wrapper(hashable_array):
            array = np.array(hashable_array)
            return function(array)

        @functools.wraps(function)
        def wrapper(array):
            return cached_wrapper(tuple(array))

        # copy lru_cache attributes over too
        wrapper.cache_info = cached_wrapper.cache_info
        wrapper.cache_clear = cached_wrapper.cache_clear

        return wrapper
    return decorator

@np_cache(maxsize=16)
def distribution_fit(data):
    results = []
    with ThreadPool(processes=int(0.25*os.cpu_count()),
                    initializer=_warning_disabler) as p:
        results.extend(p.map(functools.partial(_distribution_fit, data), _distributions))
    return tuple(sorted((result for result in results if result is not None),
                        key=lambda dist: dist.fit))

def _warning_disabler():
    warnings.simplefilter("ignore")

def _kstest(data, distribution, arg):
    return (stats.kstest(data, distribution, args=arg), arg)

def _distribution_fit(data, distribution):
    fit = args = ()
    try:
        fit = stats.kstest(data, distribution)
    except TypeError as e:
        missing_arguments = int(re.search('\d+', str(e)).group(0))
        if 1 <= missing_arguments <= 2:
            available_args = (range(1,11),)*missing_arguments

            with ProcessPool(processes=int(0.5*os.cpu_count()),
                             initializer=_warning_disabler) as p:
                (fit, args) = min(p.map(functools.partial(_kstest, data, distribution), itertools.product(*available_args)))

    return DistributionFit(distribution, args, fit) if fit else None

reason: import numpy,from scipy


text:
import numpy as np
import pytest

from probnum import diffeq

@pytest.fixture
def rng():
    return np.random.default_rng(seed=1)

@pytest.fixture
def step():
    return 0.2

@pytest.fixture
def solver_order():
    return 4

@pytest.fixture
def noise_scale():
    return 1

@pytest.fixture
def num_samples():
    return 100

@pytest.mark.parametrize(
    "perturb_fct",
    [
        diffeq.perturbed.step.perturb_uniform,
        diffeq.perturbed.step.perturb_lognormal,
    ],
)
def test_mean(perturb_fct, step, solver_order, noise_scale, num_samples, rng):
    suggested_steps = perturb_fct(
        rng, step, solver_order, noise_scale, size=num_samples
    )
    mean_suggested_step = np.sum(suggested_steps) / num_samples
    np.testing.assert_allclose(mean_suggested_step, step, atol=1e-4, rtol=1e-4)

@pytest.mark.parametrize(
    "perturb_fct",
    [
        diffeq.perturbed.step.perturb_uniform,
        diffeq.perturbed.step.perturb_lognormal,
    ],
)
def test_var(perturb_fct, step, solver_order, noise_scale, num_samples, rng):
    expected_var = step ** (2 * solver_order + 1)
    suggested_steps = perturb_fct(
        rng, step, solver_order, noise_scale, size=num_samples
    )
    var = ((suggested_steps - step) ** 2) / num_samples
    np.testing.assert_allclose(expected_var, var, atol=1e-4, rtol=1e-4)

max_stars_repo_name: christopheroates/probnum

max_issues_repo_name: christopheroates/probnum

max_forks_repo_name: christopheroates/probnum


text:
# -*- coding: utf-8 -*-
from dewloosh.geom.polyhedron import TetraHedron
from dewloosh.math.array import repeat
from numba import njit, prange
import numpy as np
from numpy import ndarray
__cache = True

@njit(nogil=True, cache=__cache)
def monoms_TET4(pcoord: ndarray):
    r, s, t = pcoord
    return np.array([1, r, s, t])

@njit(nogil=True, cache=__cache)
def shp_TET4(pcoord: ndarray):
    r, s, t = pcoord
    return np.array([1 - r - s - t, r, s, t])

@njit(nogil=True, parallel=True, cache=__cache)
def shape_function_matrix_TET4(pcoord: np.ndarray):
    eye = np.eye(3, dtype=pcoord.dtype)
    shp = shp_TET4(pcoord)
    res = np.zeros((3, 12), dtype=pcoord.dtype)
    for i in prange(4):
        res[:, i * 3: (i+1) * 3] = eye*shp[i]
    return res

@njit(nogil=True, cache=__cache)
def dshp_TET4():
    return np.array([[-1., -1., -1.], [1., 0., 0.],
                     [0., 1., 0.], [0., 0., 1.]])

class TET4(TetraHedron):

    @classmethod
    def lcoords(cls, *args, **kwargs):
        return np.array([
            [0., 0., 0.],
            [1., 0., 0.],
            [0., 1., 0.],
            [0., 0., 1.]])

    @classmethod
    def lcenter(cls, *args, **kwargs):
        return np.array([[1/3, 1/3, 1/3]])

    def shape_function_derivatives(self, coords=None, *args, **kwargs):
        coords = self.pointdata.x.to_numpy() if coords is None else coords
        if len(coords.shape) == 2:
            return repeat(dshp_TET4(), coords.shape[0])
        else:
            return dshp_TET4()

max_stars_repo_name: dewloosh/dewloosh-geom

max_issues_repo_name: dewloosh/dewloosh-geom

max_forks_repo_name: dewloosh/dewloosh-geom

reason: import numpy,from numpy,from numba


text:
# %matplotlib inline
# %load_ext autoreload
# %autoreload 2

import keras
import keras.preprocessing.image
from keras_retinanet.models.resnet import custom_objects
from keras_retinanet.preprocessing.coco import CocoGenerator

import matplotlib.pyplot as plt
import cv2
import os
import numpy as np
import time
import argparse
import tensorflow as tf

def get_session():
    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True
    return tf.Session(config=config)

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
	help="path to input image")
ap.add_argument("-m", "--model", required=True, help="path to output model")
# ap.add_argument("-p", "--plot", type=str, default="plot.png",
	# help="path to output loss/accuracy plot")
args = vars(ap.parse_args())

# os.environ["CUDA_VISIBLE_DEVICES"] = "0"
keras.backend.tensorflow_backend.set_session(get_session())

#model = keras.models.load_model('/home/fiuna/Documentos/notebook/snapshots/resnet50_pascal_50.h5', custom_objects=custom_objects)
model = keras.models.load_model(args["model"], custom_objects=custom_objects)

# image = cv2.imread("D:\\Luis\\codigos\\deep learning\\basketball\\JPEGImages\\n02802426_9097.jpeg")
image = cv2.imread(args["image"])

#dst = cv2.resize(src, (2*width, 2*height), interpolation = cv2.INTER_CUBIC)

#draw = cv2.resize(image, (300,300), interpolation = cv2.INTER_CUBIC)
draw = image.copy()
#draw = cv2.cvtColor(draw, cv2.COLOR_BGR2RGB)

_, _, detections = model.predict_on_batch(np.expand_dims(image, axis=0))

detections2 = detections
#detections = detections[0,1:,4:]

print("Detections shape ", detections.shape)
#print(detections[:, :3, 4:])
print(detections)

predicted_labels = np.argmax(detections[0, :, 4:], axis=1)#orig
#predicted_labels = detections[0, 1, 4:]
#print("Predicted Labels > ", predicted_labels)

scores = detections[0, np.arange(detections.shape[1]), 4 + predicted_labels]
print("Scores shape > ", scores.shape)
idx=0
while scores[idx]>0.5:
#for idx in range(0, 10):
#idx=3
# if score < 0.5:
#     continue
	b = detections[0, idx, :4].astype(int)
#print("b values> ", b)

	cv2.rectangle(draw, (b[0], b[1]), (b[2], b[3]), (255, 0, 0), 3)
# caption = "{} {:.3f}".format(val_generator.label_to_name(label), score)
	caption = "Tomate"
	cv2.putText(draw, caption, (b[0], b[1] - 10), cv2.FONT_HERSHEY_PLAIN, 1.5, (0, 0, 0), 3)
	cv2.putText(draw, caption, (b[0], b[1] - 10), cv2.FONT_HERSHEY_PLAIN, 1.5, (255, 255, 255), 2)

	#draw = cv2.cvtColor(draw, cv2.COLOR_RGB2BGR)
	print("Scores > ", scores[idx])
	idx = idx+1

#draw = cv2.cvtColor(draw, cv2.COLOR_BGR2RGB)
cv2.imwrite("xxpruebas.jpg",draw)
cv2.imshow("prueba", draw)
cv2.waitKey()
cv2.destroyAllWindows()


text:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import normalize,scale
from sklearn.cross_validation import cross_val_score
from sklearn import metrics

def count(predicts):
	c = 0
	for pre in predicts:
		if pre == True:
			c+=1
	return c

#importing dataset and converting to datasframe
data = pd.read_csv('heart.csv', header=None)
df = pd.DataFrame(data) #data frame

#extracting columns x and y
x = df.iloc[:, 0:5]
x = x.drop(x.columns[1:3], axis=1)
x = pd.DataFrame(scale(x))

y = df.iloc[:, 13]
y = y-1

# x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.4)

#plotting the data
fig = plt.figure()

ax1 = fig.add_subplot(1,2,1)
ax1.scatter(x[1],x[2], c=y)
ax1.set_title("Original Data")

clusters = 2

model = KMeans(init='k-means++', n_clusters=clusters, n_init=10,random_state=100)

scores = cross_val_score(model, x, y, scoring='accuracy', cv=10)
print ("10-Fold Accuracy : ", scores.mean()*100)

model.fit(x)

predicts = model.predict(x)
print ("Accuracy(Total) = ", count(predicts == np.array(y))/(len(y)*1.0) *100)
centroids = model.cluster_centers_

# print centroids

ax1.scatter(centroids[:, 1], centroids[:, 2],
            marker='x', s=169, linewidths=3,
            color='b', zorder=10)

ax2 = fig.add_subplot(1,2,2)
ax2.set_title("KMeans Clustering")
ax2.scatter(x[1],x[2], c=predicts)
ax2.scatter(centroids[:, 1], centroids[:, 2],
            marker='x', s=169, linewidths=3,
            color='b', zorder=10)

#metrics
cm = metrics.confusion_matrix(y, predicts)
print (cm/len(y))
print (metrics.classification_report(y, predicts))

plt.show()


text:
import numpy as np
import matplotlib as mpl

from numpy.testing import assert_array_equal

from ..core import (
    _VectorPlotter,
    unique_dashes,
    unique_markers,
)

class TestVectorPlotter:

    def test_flat_variables(self, flat_data):

        p = _VectorPlotter()
        p.establish_variables(data=flat_data)
        assert p.input_format == "wide"
        assert list(p.variables) == ["x", "y"]
        assert len(p.plot_data) == len(flat_data)

        try:
            expected_x = flat_data.index
            expected_x_name = flat_data.index.name
        except AttributeError:
            expected_x = np.arange(len(flat_data))
            expected_x_name = None

        x = p.plot_data["x"]
        assert_array_equal(x, expected_x)

        expected_y = flat_data
        expected_y_name = getattr(flat_data, "name", None)

        y = p.plot_data["y"]
        assert_array_equal(y, expected_y)

        assert p.variables["x"] == expected_x_name
        assert p.variables["y"] == expected_y_name

class TestCoreFunc:

    def test_unique_dashes(self):

        n = 24
        dashes = unique_dashes(n)

        assert len(dashes) == n
        assert len(set(dashes)) == n
        assert dashes[0] == ""
        for spec in dashes[1:]:
            assert isinstance(spec, tuple)
            assert not len(spec) % 2

    def test_unique_markers(self):

        n = 24
        markers = unique_markers(n)

        assert len(markers) == n
        assert len(set(markers)) == n
        for m in markers:
            assert mpl.markers.MarkerStyle(m).is_filled()

max_stars_repo_name: empyrals/seaborn

max_issues_repo_name: empyrals/seaborn

max_forks_repo_name: empyrals/seaborn

reason: import numpy,from numpy


text:
#!/usr/bin/env python
# coding: utf-8

DESCRIPTION="This script unifies the data format from different datasets."

import numpy as np
import argparse
import glob2
import gzip
import logging
import os.path
import json
import random
import csv

try:
   import cPickle as pickle
except:
   import pickle
PROTOCOL = pickle.HIGHEST_PROTOCOL

def get_dest_files(dest_dir,i):
    dest_X_file = "%s/X_%03d.csv"%(dest_dir,i)
    dest_y_file = "%s/y_%03d.dat"%(dest_dir,i)
    return dest_X_file,dest_y_file

def check_dest_files(dest_dir,i):
    dest_X_file,dest_y_file = get_dest_files(dest_dir,i)
    if os.path.exists(dest_X_file) and os.path.exists(dest_y_file):
        return None,None
    return dest_X_file,dest_y_file

def save_data(X,y,dest_X_file,dest_y_file):
    np.savetxt(dest_X_file,X,fmt="%.18e",delimiter=',')
    np.savetxt(dest_y_file,y,fmt="%d",delimiter=',')

def make_test_db(src_dir,dest_dir):
    files = glob2.glob("%s/*pickle.gz"%src_dir)
    for i,file in enumerate(files):
        dest_X_file,dest_y_file = check_dest_files(dest_dir,i)
        if None == dest_X_file:
            continue
        with open(file,"rb") as fin:
            data = pickle.loads(gzip.decompress(fin.read()))
        X = data['samples']
        y = data['labels']
        save_data(X,y,dest_X_file,dest_y_file)

def make_face_db(src_dir,dest_dir,n_clusters):
    files = sorted(glob2.glob("%s/num%02d/test*_sample_feature.csv"%(src_dir,n_clusters)))
    #print(files)
    for i,file in enumerate(files):
        dest_X_file,dest_y_file = check_dest_files(dest_dir,i)
        if None == dest_X_file:
            continue
        X = np.loadtxt(file,delimiter=',')
        src_y_file = "%s/num%02d/test%02d_groundtruth.txt"%(src_dir,n_clusters,i)
        data = csv.reader(open(src_y_file,'r'))
        y = [int(r[2]) for r in data]
        save_data(X,y,dest_X_file,dest_y_file)

def make_preid_db(src_dir,dest_dir,n_clusters):
    flatten = lambda l: [item for sublist in l for item in sublist]

    Xs = sorted(glob2.glob("%s/X_*.npy"%src_dir))
    ys = sorted(glob2.glob("%s/y_*.npy"%src_dir))
    Xys = [[np.load(X),np.load(y)] for X,y in zip(Xs,ys)]
    for t in range(0,100):
        dest_X_file,dest_y_file = get_dest_files(dest_dir,t)
        if None == dest_X_file:
            continue
        random.shuffle(Xys)
        # inliers
        X_ = []
        y_ = []
        meta = {'inliers':[],'outliers':[]}
        for i,(X,y) in enumerate(Xys[:n_clusters]):
            random.shuffle(X)
            #print("X:",X)
            #print("y:",y)

            sample_num = max(1,int(np.random.normal(8,1)))
            X_.append(np.array(X[0:max(1,min(sample_num,len(X)))]))
            y_ += [i+1]*sample_num
            meta['inliers'].append({'person_id':int(y[0]),'sample_num':sample_num})
        # outliers
        Xys_t_out = Xys[n_clusters:]
        outlier_person_num = len(Xys_t_out)
        # 0 < outlier_num <= 2*outlier_person_num
        outlier_num = min(max(1,int(np.random.normal(8,1))),2*outlier_person_num)
        #print("outlier_person_num=",outlier_person_num)
        #print("outlier_num       =",outlier_num)
        for i,(X,y) in enumerate(Xys_t_out):
            if i >= outlier_num:
                break
            #print("i,outlier_num",i,outlier_num)
            #print("outlier_person_num:",outlier_person_num)
            #print("outlier_num%outlier_person_num",outlier_num%outlier_person_num)
            #print("(i<outlier_num%outlier_person_num))",(i<outlier_num%outlier_person_num))
            sample_num = 1
            if outlier_num>outlier_person_num:
                sample_num += (i<outlier_num%outlier_person_num)
            #print("n_samples:", sample_num)
            random.shuffle(X)
            X_.append(np.mat(X[0:sample_num]))
            y_ += [0]*sample_num
            meta['outliers'].append({'person_id':int(y[0]),'sample_num':sample_num})
        #for X in X_:
        #    print("X.shape",X.shape)
        X__ = np.vstack(X_)
        #print("X__.shape",X__.shape)
        save_data(X__,np.array(y_),dest_X_file,dest_y_file)
        with open("%s/meta_%03d.json"%(dest_dir,t), 'w') as outfile:
            #print(meta)
            json.dump(meta, outfile)

def make_preid_mo_db(src_dir,dest_dir,n_clusters,rate_outliers):
    flatten = lambda l: [item for sublist in l for item in sublist]

    Xs = sorted(glob2.glob("%s/X_*.npy"%src_dir))
    ys = sorted(glob2.glob("%s/y_*.npy"%src_dir))
    Xys = [[np.load(X),np.load(y)] for X,y in zip(Xs,ys)]

    OutlierFiles = sorted(glob2.glob("%s/X_outliers*.npy"%src_dir))
    Outliers_temp = [np.load(f) for f in OutlierFiles]
    X_outliers = np.vstack(Outliers_temp)

    outlier_num = int(8*n_clusters*rate_outliers)
    for t in range(0,5):
        dest_X_file,dest_y_file = get_dest_files(dest_dir,t)
        if None == dest_X_file:
            continue
        random.shuffle(Xys)
        # inliers
        X_ = []
        y_ = []
        meta = {'inliers':[],'outliers':[]}
        for i,(X,y) in enumerate(Xys[:n_clusters]):
            random.shuffle(X)
            #print("X:",X)
            #print("y:",y)

            sample_num = max(1,int(np.random.normal(8,1)))
            X_.append(np.array(X[0:max(1,min(sample_num,len(X)))]))
            y_ += [i+1]*sample_num
            meta['inliers'].append({'person_id':int(y[0]),'sample_num':sample_num})
        X__ = np.vstack(X_)

        np.random.shuffle(X_outliers)
        #for X in X_:
        #    print("X.shape",X.shape)
        X_ = np.r_[X__, X_outliers[:outlier_num]]
        y_+= [0]*outlier_num
        #print("X__.shape",X__.shape)
        save_data(X_,np.array(y_),dest_X_file,dest_y_file)

def main(args,logger):
    src_dir=args.src_dir
    dest_dir=args.dest_dir

    if args.type=='test':
        make_test_db(src_dir,dest_dir)
    elif args.type=='face_feature':
        make_face_db(src_dir,dest_dir,args.n_clusters)
    elif args.type=='preid':
        make_preid_db(src_dir,dest_dir,args.n_clusters)
    elif args.type=='preid_mo':
        make_preid_mo_db(src_dir,dest_dir,args.n_clusters,args.rate_outliers)
    else:
        logger.warn("Unknown dataset type: '%s'."%args.type)

parser = argparse.ArgumentParser(description=DESCRIPTION)
parser.add_argument('type', \
        action='store', \
        nargs=None, \
        const=None, \
        default='test', \
        type=str, \
        choices=None, \
        help='Dataset name. It must be test|face|preid|.', \
        metavar=None)

parser.add_argument('src_dir', \
        action='store', \
        nargs=None, \
        const=None, \
        default=None, \
        type=str, \
        choices=None, \
        help='Directory path where the source data are located.', \
        metavar=None)

parser.add_argument('dest_dir', \
        action='store', \
        nargs=None, \
        const=None, \
        default=None, \
        type=str, \
        choices=None, \
        help='Directory path where the formatted data will be located.', \
        metavar=None)

parser.add_argument('-n','--n_clusters', \
        action='store', \
        nargs='?', \
        const=None, \
        default=None, \
        type=int, \
        choices=None, \
        help='Number of clusters',
        metavar=None)

parser.add_argument('-o','--rate_outliers', \
        action='store', \
        nargs='?', \
        const=None, \
        default=None, \
        type=float, \
        choices=None, \
        help='Rate of outliers',
        metavar=None)

if __name__ == '__main__':
    args = parser.parse_args()
    logger = logging.getLogger(__file__)
    logger.setLevel(logging.DEBUG)
    sh = logging.StreamHandler()
    logger.addHandler(sh)

    main(args,logger)


text:
import json
import asyncio
from abc import ABC, abstractmethod
from threading import Lock, Thread
import time
from functools import partial
import numpy as np
from concurrent.futures import ThreadPoolExecutor

speedup_factor = 50

def load_netlist(filename):
    with open(filename) as f:
        netlist = json.load(f)
    tasks = netlist["tasks"]
    samples = netlist["samples"]
    return samples, tasks

class WorkerTemplate(ABC):
    def __init__(self, maestro, n_workers=1):
        self.maestro = maestro
        self.gantry = maestro.gantry
        self.gripper = maestro.gripper
        self.spincoater = maestro.spincoater
        self.characterization = maestro.characterization
        self.liquidhandler = maestro.liquidhandler
        self.hotplates = maestro.hotplates
        self.storage = maestro.storage

        self.working = False
        self.POLLINGRATE = 0.0001  # seconds
        self.n_workers = n_workers

    # def main(self, workers):
    #     self.working = True
    #     asyncio.set_event_loop(self.loop)
    #     if not self.loop.is_running():
    #         self.loop.run_until_complete(asyncio.wait(workers))
    # else:
    #     self.loop.call_soon_threadsafe(asyncio.wait(workers))

    def prime(self, loop):
        asyncio.set_event_loop(loop)
        self.loop = loop
        self.queue = asyncio.PriorityQueue()

    def start(self):
        self.working = True
        for _ in range(self.n_workers):
            asyncio.run_coroutine_threadsafe(self.worker(), self.loop)

    def stop_workers(self):
        self.working = False
        # self.thread.join()

    def add_task(self, task):
        # if not self.working:
        #     raise RuntimeError("Cannot add to queue, workers not running!")
        payload = (task["start"], task)
        self.loop.call_soon_threadsafe(self.queue.put_nowait, payload)

    async def worker(self):
        """process items from the queue + keep the maestro lists updated"""
        while self.working:
            _, task = await self.queue.get()  # blocking wait for next task
            task_description = f'{task["task"]}, {task["sample"]}'
            sample = self.maestro.samples[task["sample"]]
            sample_task = [t for t in sample["tasks"] if t["task"] == task["task"]][0]
            # print(f"starting {task_description}")
            if task is None:  # finished flag
                break

            # wait for all previous tasks to complete

            with self.maestro.lock_pendingtasks:
                self.maestro.pending_tasks.append(task["id"])
            for precedent in task["precedents"]:
                found = False
                first = True
                while not found:
                    with self.maestro.lock_completedtasks:
                        found = precedent in self.maestro.completed_tasks
                    if found:
                        break
                    else:
                        if first:
                            print(f"waiting for precedents of {task_description}")
                        await asyncio.sleep(self.POLLINGRATE)
                        first = False

            # wait for this task's target start time
            wait_for = task["start"] - (self.maestro.nist_time() - self.maestro.t0)
            if wait_for > 0:
                print(f"\twaiting {wait_for} seconds for {task_description} start time")
                await asyncio.sleep(wait_for)

            # execute this task
            # function = partial(
            #     self.functions[task["function"]],
            #     args=task["args"],
            #     kwargs=task["kwargs"],
            # )

            sample_task["start_actual"] = self.maestro.nist_time() - self.maestro.t0
            function = self.functions[task["task"]]
            if asyncio.iscoroutinefunction(function):
                print(f"\t\texecuting {task_description} as coro")
                await function(task)
            else:
                print(f"\t\texecuting {task_description} as thread")
                await self.loop.run_in_executor(
                    self.maestro.threadpool, partial(function, task)
                )

            # update task lists
            sample_task["finish_actual"] = self.maestro.nist_time() - self.maestro.t0
            print(f"\t\t\tfinished {task_description}")
            with self.maestro.lock_completedtasks:
                self.maestro.completed_tasks[task["id"]] = (
                    self.maestro.nist_time() - self.maestro.t0
                )
            with self.maestro.lock_pendingtasks:
                self.maestro.pending_tasks.remove(task["id"])
            self.queue.task_done()

class Worker_GantryGripper(WorkerTemplate):
    def __init__(self, maestro):
        super().__init__(maestro=maestro, n_workers=1)
        self.functions = {
            "moveto": partial(self.pause, 12 / speedup_factor),
            "moverel": partial(self.pause, 12 / speedup_factor),
            "open": partial(self.pause, 1 / speedup_factor),
            "close": partial(self.pause, 1 / speedup_factor),
            "transfer": partial(self.pause, 30 / speedup_factor),
            "idle_gantry": partial(self.pause, 30 / speedup_factor),
            "storage_to_spincoater": partial(self.pause, 30 / speedup_factor),
            "spincoater_to_hotplate": partial(self.pause, 30 / speedup_factor),
            "hotplate_to_storage": partial(self.pause, 30 / speedup_factor),
            "storage_to_characterization": partial(self.pause, 30 / speedup_factor),
            "characterization_to_storage": partial(self.pause, 30 / speedup_factor),
        }

    def pause(self, t, task):
        # t -= np.random.random() * 5 / speedup_factor
        time.sleep(min(t, 0))

class Worker_Hotplate(WorkerTemplate):
    def __init__(self, maestro, n_workers):
        super().__init__(maestro=maestro, n_workers=n_workers)
        self.functions = {
            "anneal": self.anneal,
        }

    async def anneal(self, task):
        sample = self.maestro.samples[task["sample"]]
        await asyncio.sleep(sample["anneal_recipe"]["duration"] / speedup_factor)

    # def anneal(self, task):
    #     sample = self.maestro.samples[task["sample"]]
    #     time.sleep(sample["anneal_recipe"]["duration"] / speedup_factor)

class Worker_Storage(WorkerTemplate):
    def __init__(self, maestro, n_workers):
        super().__init__(maestro=maestro, n_workers=n_workers)
        self.functions = {
            "cooldown": self.cooldown,
        }

    async def cooldown(self, task):
        sample = self.maestro.samples[task["sample"]]
        await asyncio.sleep(180 / speedup_factor)

    # def cooldown(self, task):
    #     sample = self.maestro.samples[task["sample"]]
    #     time.sleep(180 / speedup_factor)

class Worker_SpincoaterLiquidHandler(WorkerTemplate):
    def __init__(self, maestro):
        super().__init__(maestro=maestro, n_workers=1)
        self.functions = {
            "spincoat": self.spincoat,
        }

    async def spincoat(self, task):
        """executes a series of spin coating steps. A final "stop" step is inserted
        at the end to bring the rotor to a halt.

        Args:
            recipe (SpincoatRecipe): recipe of spincoating steps + drop times

        Returns:
            record: dictionary of recorded spincoating process.
        """

        sample = self.maestro.samples[task["sample"]]
        recipe = sample["spincoat_recipe"]
        # time.sleep(recipe["duration"] / speedup_factor)
        await asyncio.sleep(recipe["duration"] / speedup_factor)
        # solution_dropped = False
        # antisolvent_dropped = False
        # record = {}

        # self.spincoater.start_logging()
        # spincoating_in_progress = True
        # t0 = self.nist_time()
        # tnext = 0
        # for start_time, (rpm, acceleration, duration) in zip(
        #     recipe.start_times, recipe.steps
        # ):
        #     tnext += start_time
        #     tnow = self.nist_time() - t0  # time relative to recipe start
        #     while (
        #         tnow <= tnext
        #     ):  # loop and check for drop times until next spin step is reached
        #         if not solution_dropped and tnow >= recipe.solution_droptime:
        #             self.liquidhandler.drop_perovskite()
        #             solution_dropped = True
        #             record["solution_drop"] = tnow
        #         if not antisolvent_dropped and tnow >= recipe.antisolvent_droptime:
        #             self.liquidhandler.drop_antisolvent()
        #             antisolvent_dropped = True
        #             record["antisolvent_drop"] = tnow
        #         time.sleep(0.1)

        #     self.spincoater.set_rpm(rpm=rpm, acceleration=acceleration)

        # self.spincoater.stop()
        # record.update(self.spincoater.finish_logging())

        # sample["spincoat_recipe"]["record"] = record

class Worker_Characterization(WorkerTemplate):
    def __init__(self, maestro):
        super().__init__(maestro=maestro)
        self.functions = {
            "characterize": partial(self.pause, 60 * 2.5 / speedup_factor),
        }

    def pause(self, t, task):
        time.sleep(t)

class Maestro:
    def __init__(self):
        self.gantry = None
        self.gripper = None
        self.spincoater = None
        self.characterization = None
        self.liquidhandler = None

        # Labware
        self.hotplates = {"HotPlate1": None}
        self.storage = {"SampleTray1": None}

        # Status
        self.samples = {}

        # worker thread coordination
        self.threadpool = ThreadPoolExecutor(max_workers=40)
        self.pending_tasks = []
        self.completed_tasks = {}
        self.lock_pendingtasks = Lock()
        self.lock_completedtasks = Lock()

        self.workers = {
            "gantry_gripper": Worker_GantryGripper(self),
            "spincoater_lh": Worker_SpincoaterLiquidHandler(self),
            "characterization": Worker_Characterization(self),
            "hotplates": Worker_Hotplate(self, n_workers=25),
            "storage": Worker_Storage(self, n_workers=45),
        }

    def load_netlist(self, filepath):
        self.samples, self.tasks = load_netlist(filepath)

    def make_background_event_loop(self):
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.loop)
        self.loop.run_until_complete(self._keep_loop_running())

    async def _keep_loop_running(self):
        while self.working:
            await asyncio.sleep(1)

    def run(self):
        self.working = True
        self.thread = Thread(target=self.make_background_event_loop)
        self.thread.start()  # generates asyncio event loop in background thread (self.loop)
        time.sleep(0.5)
        # self.loop = asyncio.new_event_loop()
        self.loop.set_debug(True)
        self.t0 = self.nist_time()

        for worker in self.workers.values():
            worker.prime(loop=self.loop)
        for t in self.tasks:
            assigned = False
            t["start"] /= speedup_factor
            for workername, worker in self.workers.items():
                if t["task"] in worker.functions:
                    worker.add_task(t)
                    assigned = True
                    continue
            if not assigned:
                raise Exception(f"No worker assigned to task {t['task']}")

        for worker in self.workers.values():
            worker.start()
        # self.loop.run_forever()

    def nist_time(self):
        return time.time()

def main():
    maestro = Maestro()
    maestro.load_netlist("maestronetlist.json")
    maestro.run()

max_stars_repo_name: fenning-research-group/PASCAL

max_issues_repo_name: fenning-research-group/PASCAL

max_forks_repo_name: fenning-research-group/PASCAL