예제 #1
0
def plot_ibd_total(c):
    '''Plot Oren's total genomic IBD % vs. kinship, displaying the trend of IBD.'''     
    i = np.where(c[:, 4] > 0)[0]
    t, ibd = c[i, 3], (1.0 * c[i, 4]) / sum(ChromDao.TOTAL_BP_TYPED)
    # Fix HBD probabilities to account for the probability that one can choose the same haplotype twice.
    # (We only account for the probability of the two different haps being equal in c[i,4].)
    hbd = np.where(c[:, 0] == c[:, 1])[0]
    ibd[hbd] = 0.5 * (1 + ibd[hbd])
    
    j = i[np.where(c[:, 0] != c[:, 1])[0]]
    a, b, r, _, stderr = stats.linregress(t[j], ibd[j])
    xr = polyval([a, b], t[j])
    
    P.figure(1)
    P.clf()
    P.hold(True)
    P.scatter(t, ibd, s=2, lw=0, color='b')
    P.plot(t[j], xr, 'r-')
    T = np.arange(0, 1, 0.01)
    P.plot(T, T, 'g-')
    P.xlim([-0.01, 1.01])
    P.ylim([-0.01, 1.01])
    P.title(' %% IBD of Whole Genome vs. Expected %%\nslope = %.2f, intercept = %.2f, r = %.2f, std error = %.2e' % (a, b, r, stderr))
    P.xlabel('$\gamma := \Delta_1+\Delta_3+\Delta_5+\Delta_7+\Delta_8$: Empirical ID Coefficients')
    P.ylabel('$i = $ % IBD in Oren''s Code')
    P.show()
    return t, ibd
예제 #2
0
def seprate(numberator, roots):
    # seprates a fraction
    tempRes = []
    for i in roots:
        temp = P.poly1d([complex(1, 0)])
        for j in roots:
            if not i == j:
                temp = temp * P.poly1d([complex(1, 0), -j])
        tempRes += [P.polyval(numberator, i) / P.polyval(temp, i)]
    res = []
    for i in range(0, len(tempRes)):
        s = tempRes[i]
        m = P.poly1d([complex(1, 0), -roots[i]])
        k = [s, roots[i]]
        res += [k]
    return res
예제 #3
0
def plot_ibd_total(c):
    '''Plot Oren's total genomic IBD % vs. kinship, displaying the trend of IBD.'''
    i = np.where(c[:, 4] > 0)[0]
    t, ibd = c[i, 3], (1.0 * c[i, 4]) / sum(ChromDao.TOTAL_BP_TYPED)
    # Fix HBD probabilities to account for the probability that one can choose the same haplotype twice.
    # (We only account for the probability of the two different haps being equal in c[i,4].)
    hbd = np.where(c[:, 0] == c[:, 1])[0]
    ibd[hbd] = 0.5 * (1 + ibd[hbd])

    j = i[np.where(c[:, 0] != c[:, 1])[0]]
    a, b, r, _, stderr = stats.linregress(t[j], ibd[j])
    xr = polyval([a, b], t[j])

    P.figure(1)
    P.clf()
    P.hold(True)
    P.scatter(t, ibd, s=2, lw=0, color='b')
    P.plot(t[j], xr, 'r-')
    T = np.arange(0, 1, 0.01)
    P.plot(T, T, 'g-')
    P.xlim([-0.01, 1.01])
    P.ylim([-0.01, 1.01])
    P.title(
        ' %% IBD of Whole Genome vs. Expected %%\nslope = %.2f, intercept = %.2f, r = %.2f, std error = %.2e'
        % (a, b, r, stderr))
    P.xlabel(
        '$\gamma := \Delta_1+\Delta_3+\Delta_5+\Delta_7+\Delta_8$: Empirical ID Coefficients'
    )
    P.ylabel('$i = $ % IBD in Oren' 's Code')
    P.show()
    return t, ibd
예제 #4
0
def simplize(numberator, denominator, roots):
    # simplizes the numberator and Denominator
    counter = 0
    for i in roots:
        if P.polyval(numberator, i) == 0:
            numberator = P.polydiv(numberator, polyFromRoot([i]))
            numberator = numberator[0]
            denominator = P.polydiv(denominator, polyFromRoot([i]))
            denominator = denominator[0]
            roots = roots[:counter] + roots[counter + 1:]
        counter += 1
    return [numberator, denominator, roots]
예제 #5
0
    def get_level_parameters(cls, level):
        """

        :param int level: Liczba całkowita większa od jendości.
        :return: Zwraca listę współczynników dla poszczególnych puktów
                 w metodzie NC. Na przykład metoda NC stopnia 2 używa punktów
                 na początku i końcu przedziału i każdy ma współczynnik 1,
                 więc metoda ta zwraca [1, 1]. Dla NC 3 stopnia będzie to
                 [1, 3, 1] itp.
        :rtype: List of integers
        """
        paramList = []
        for elem in range(level):
            param = 1
            for i in range(level):
                if elem != i:
                    param = param*poly1d([1, -i])
            param = polyint(param)
            param = polyval(param,level-1)-polyval(param,0)
            a = math.pow(-1,level-elem-1)/math.factorial(elem)/math.factorial(level-elem-1)
            paramList.append(param*a)
        return paramList            
예제 #6
0
파일: 2d.py 프로젝트: Cadair/kPyWavelet
    def psi(self, t):
        """DOG wavelet as described in Torrence and Compo (1998)

        The derivative of a Gaussian of order n can be determined using
        the probabilistic Hermite polynomials. They are explicitly
        written as:
            Hn(x) = 2 ** (-n / s) * n! * sum ((-1) ** m) * (2 ** 0.5 *
                x) ** (n - 2 * m) / (m! * (n - 2*m)!)
        or in the recursive form:
            Hn(x) = x * Hn(x) - nHn-1(x)

        Source: http://www.ask.com/wiki/Hermite_polynomials

        """
        p = hermitenorm(self.m)
        return (-1) ** (self.m + 1) * polyval(p, t) * np.exp(-t ** 2 / 2) / np.sqrt(gamma(self.m + 0.5))
예제 #7
0
    def psi(self, t):
        """DOG wavelet as described in Torrence and Compo (1998)

        The derivative of a Gaussian of order n can be determined using
        the probabilistic Hermite polynomials. They are explicitly
        written as:
            Hn(x) = 2 ** (-n / s) * n! * sum ((-1) ** m) * (2 ** 0.5 *
                x) ** (n - 2 * m) / (m! * (n - 2*m)!)
        or in the recursive form:
            Hn(x) = x * Hn(x) - nHn-1(x)

        Source: http://www.ask.com/wiki/Hermite_polynomials

        """
        p = hermitenorm(self.m)
        return ((-1)**(self.m + 1) * polyval(p, t) * np.exp(-t**2 / 2) /
                np.sqrt(gamma(self.m + 0.5)))
예제 #8
0
def list_derivative(f, x, n, o=3, p=5):
    """
    Returns the nth derivative of f with respect to x, where zip(x,f) are 
    datapoints, using curve-fit polynomials of order o to p points.
    """
    assert p % 2 == 1  # should be odd imo
    assert len(f) >= p  # won't work otherwise
    derivative = []
    for i in xrange(len(f)):
        start = i - (p - 1) / 2
        if start < 0:
            start = 0
        end = start + p
        if end >= len(f):
            start = -1 - p
            end = -1
        spline = polyfit(x[start:end], f[start:end], o)
        derivative.append(polyval(polyder(spline, n), x[i]))
    print("diff in list lengths: " + str(len(f) - len(derivative)))
    return array(derivative)
예제 #9
0
    def __iadd__(self, other):
        if not (self.flag and other.flag):
            raise Exception('bad arguments')

        self.scatter_list.extend(other.scatter_list)

        slope, intercept, r_value, p_value, std_err = stats.linregress(
            self.scatter_list)
        self.slope = slope
        self.intercept = intercept
        self.r_val = r_value
        self.p_val = p_value
        self.std_err = std_err

        self.max = max(self.scatter_list, key=itemgetter(1))
        self.min = min(self.scatter_list, key=itemgetter(1))

        self.x_grid = [x for x, y in self.scatter_list]
        self.line = polyval([self.slope, self.intercept], self.x_grid)

        return self
예제 #10
0
    def __init__(self, dStream_obj):
        self.scatter_list = self.scatter_plot(dStream_obj)
        self.scatter_list = [point for point in self.scatter_list if point]

        if self.scatter_list:
            self.flag = True
            slope, intercept, r_value, p_value, std_err = stats.linregress(
                self.scatter_list)
            self.slope = slope
            self.intercept = intercept
            self.r_val = r_value
            self.p_val = p_value
            self.std_err = std_err

            self.max = max(self.scatter_list, key=itemgetter(1))
            self.min = min(self.scatter_list, key=itemgetter(1))

            self.x_grid = [x for x, y in self.scatter_list]

            self.line = polyval([self.slope, self.intercept], self.x_grid)
        else:
            self.flag = False
def wavelet_inverse(wave, scale, dt, dj=0.25, mother="MORLET", param=-1):
    """Inverse continuous wavelet transform
    Torrence and Compo (1998), eq. (11)

    INPUTS
        waves (array like):
          WAVE is the WAVELET transform. This is a complex array.
          
        scale (array like):
           the vector of scale indices 
        dt (float) :
            amount of time between each original value, i.e. the sampling time.
        dj (float, optional) :
            the spacing between discrete scales. Default is 0.25.
           A smaller # will give better scale resolution, but be slower to plot.
        mother (string, optional) :
            the mother wavelet function.
             The choices are 'MORLET', 'PAUL', or 'DOG'
         PARAM = the mother wavelet parameter.
            For 'MORLET' this is k0 (wavenumber), default is 6.
            For 'PAUL' this is m (order), default is 4.
            For 'DOG' this is m (m-th derivative), default is 2.    

    OUTPUTS
        iwave (array like) :
            Inverse wavelet transform.
    """
    import numpy as np

    j1, n = wave.shape
    J1 = len(scale)
    if not j1 == J1:
        print j1, n, J1
        raise Exception("Input array are inconsistent")
    sj = np.dot(scale.reshape(len(scale), 1), np.ones((1, n)))
    #
    mother = mother.upper()

    # psi0 comes from Table 1,2 Torrence and Compo (1998)
    # Cdelta comes from Table 2 Torrence and Compo (1998)
    if mother == 'MORLET':  #-----------------------------------  Morlet
        if (param == -1): param = 6.
        psi0 = np.pi**(-0.25)
        if param == 6.:
            Cdelta = 0.776
    elif mother == 'PAUL':  #--------------------------------  Paul
        if (param == -1): param = 4.
        m = param
        psi0 = np.real(2.**m * 1j**m * np.prod(np.arange(2, m + 1)) /
                       np.sqrt(np.pi * np.prod(np.arange(2, 2 * m + 1))) *
                       (1**(-(m + 1))))
        if m == 4.:
            Cdelta = 1.132
    elif mother == 'DOG':  #--------------------------------  DOG
        if (param == -1): param = 2.
        m = param
        from scipy.special import gamma
        from numpy.lib.polynomial import polyval
        from scipy.special.orthogonal import hermitenorm
        p = hermitenorm(m)
        psi0 = (-1)**(m + 1) / np.sqrt(gamma(m + 0.5)) * polyval(p, 0)
        print psi0
        if m == 2.:
            Cdelta = 3.541
        if m == 6.:
            Cdelta = 1.966
    else:
        raise Exception("Mother must be one of MORLET,PAUL,DOG")

    #eq. (11) in Torrence and Compo (1998)
    iwave = dj * np.sqrt(dt) / Cdelta / psi0 * (np.real(wave) /
                                                sj**0.5).sum(axis=0)
    return iwave
예제 #12
0
x= [2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015]
y = [485709,486722,475887,469311,453618,447977,436867,426885,392470,370021,351340,335504,306387,273781,238761]

p1= np.polyfit(x,y,1)
p2= np.polyfit(x,y,2)
p3= np.polyfit(x,y,3)
from scipy.interpolate import *



import matplotlib.pyplot as plt
xp = linspace(2000,2020,100)

fig,ax = plt.subplots()

plt.plot(xp,polyval(p1,xp),'r-')
plt.plot(xp,polyval(p2,xp),'m:')
plt.plot(xp,polyval(p3,xp),'b--')
ax.set_title("Prediction of Crime Data in Chicago")
ax.set_ylabel('Count')
ax.set_xlabel('Year')
plt.plot(x,y,'o')

#yfit = p1[0] * x + p1[1]
#yresid = y - yfit
#SSresid = sum(pow(yresid,2))
#SStotal = len(y) * np.var(y)

#rsq = 1- SSresid / SStotal

from scipy.stats import *
예제 #13
0
# Programa de Franco Benassi
# Proyecto #3 Interfaces Graficas 2020
# Ejercicio 3
from matplotlib.pyplot import figure
import numpy as np
from numpy.lib.polynomial import polyval
from pylab import *

recorrido = np.load(
    "/home/franco-os/Documentos/Informática/Interfaces de Grafica de Usuario/Proyecto 3/datas/f1.npy"
)
recorrido2 = np.load(
    "/home/franco-os/Documentos/Informática/Interfaces de Grafica de Usuario/Proyecto 3/datas/f2.npy"
)
x = np.arange(start=1, stop=50, step=1)
z = np.polyfit(x, recorrido, 1)
z_2 = np.polyfit(x, recorrido2, 2)

figure()
plot(x, recorrido, 'o')
plot(x, recorrido2, 'o')
plot(x, polyval(z, x), '-')
plot(x, polyval(z_2, x), '-')
show()
예제 #14
0
def analyze_olfaction_covariance(covariance, receptors):
    ''' Covariance: n x n covariance matrix.
        Positions:  list of n  positions '''
    
    positions = [pose.get_2d_position() for pose, sens in receptors] #@UnusedVariable
    positions = array(positions).transpose().squeeze()
    
    require_shape(square_shape(), covariance)
    n = covariance.shape[0]
    require_shape((2, n), positions)
    
    distances = create_distance_matrix(positions)
    correlation = cov2corr(covariance)
    flat_distances = distances.reshape(n * n) 
    flat_correlation = correlation.reshape(n * n)
    
    # let's fit a polynomial
    deg = 4
    poly = polyfit(flat_distances, flat_correlation, deg=deg)  
    
    knots = linspace(min(flat_distances), max(flat_distances), 2000)
    poly_int = polyval(poly, knots)
    
    poly_fder = polyder(poly)
    
    fder = polyval(poly_fder, distances)
    
    Ttheta = create_olfaction_Ttheta(positions, fder)
    Tx, Ty = create_olfaction_Txy(positions, fder, distances)
    
    
    report = Node('olfaction-theory')
    report.data('flat_distances', flat_distances)
    report.data('flat_correlation', flat_correlation)
    
    
    with report.data_file('dist_vs_corr', 'image/png') as filename:
        pylab.figure()
        pylab.plot(flat_distances, flat_correlation, '.')
        pylab.plot(knots, poly_int, 'r-')
        pylab.xlabel('distance')
        pylab.ylabel('correlation')
        pylab.title('Correlation vs distance')
        pylab.legend(['data', 'interpolation deg = %s' % deg]) 
        pylab.savefig(filename)
        pylab.close()
    
    with report.data('fder', fder).data_file('fder', 'image/png') as filename:
        pylab.figure()
        pylab.plot(knots, polyval(poly_fder, knots), 'r-')
        pylab.title('f der')
        pylab.savefig(filename)
        pylab.close() 
    
    report.data('distances', distances)
    report.data('correlation', correlation)
    report.data('covariance', covariance)
    report.data('f', polyval(poly, distances))   
    
    
    
    f = report.figure(id='cor-vs-distnace', caption='Estimated kernels',
                       shape=(3, 3))
    f.sub('dist_vs_corr')
    f.sub('fder')
    f.sub('f', display='scale')
    f.sub('distances', display='scale')
    f.sub('correlation', display='posneg')
    f.sub('covariance', display='posneg')
    
    T = numpy.zeros(shape=(3, Tx.shape[0], Tx.shape[1]))
    T[0, :, :] = Tx
    T[1, :, :] = Ty
    T[2, :, :] = Ttheta
    
    T_report = create_report_figure_tensors(T, report_id='tensors',
        caption="Predicted learned tensors")
    
    report.add_child(T_report)

    return report
예제 #15
0
def wavelet_inverse(wave, scale, dt, dj=0.25, mother="MORLET",param=-1):
    """Inverse continuous wavelet transform
    Torrence and Compo (1998), eq. (11)

    INPUTS
        waves (array like):
          WAVE is the WAVELET transform. This is a complex array.
          
        scale (array like):
           the vector of scale indices 
        dt (float) :
            amount of time between each original value, i.e. the sampling time.
        dj (float, optional) :
            the spacing between discrete scales. Default is 0.25.
           A smaller # will give better scale resolution, but be slower to plot.
        mother (string, optional) :
            the mother wavelet function.
             The choices are 'MORLET', 'PAUL', or 'DOG'
         PARAM = the mother wavelet parameter.
            For 'MORLET' this is k0 (wavenumber), default is 6.
            For 'PAUL' this is m (order), default is 4.
            For 'DOG' this is m (m-th derivative), default is 2.    

    OUTPUTS
        iwave (array like) :
            Inverse wavelet transform.
    """
    import numpy as np
    
    j1, n = wave.shape
    J1 = len(scale)
    if not j1 == J1:
        print j1,n,J1
        raise Exception("Input array are inconsistent")
    sj = np.dot(scale.reshape(len(scale),1),np.ones((1,n)))
    #
    mother = mother.upper()
    
    # psi0 comes from Table 1,2 Torrence and Compo (1998)
    # Cdelta comes from Table 2 Torrence and Compo (1998)
    if mother=='MORLET':  #-----------------------------------  Morlet
        if (param == -1): param = 6.
        psi0=np.pi**(-0.25)
        if param==6.:
            Cdelta = 0.776
    elif mother=='PAUL': #--------------------------------  Paul
        if (param == -1): param = 4.
        m = param   
        psi0=np.real(2.**m*1j**m*np.prod(np.arange(2, m + 1))/np.sqrt(np.pi*np.prod(np.arange(2,2*m+1)))*(1**(-(m+1))))
        if m==4.:
           Cdelta = 1.132 
    elif mother=='DOG':  #--------------------------------  DOG
        if (param == -1): param = 2.
        m = param
        from scipy.special import gamma 
        from numpy.lib.polynomial import polyval
        from scipy.special.orthogonal import hermitenorm
        p = hermitenorm(m)
        psi0=(-1)**(m+1)/np.sqrt(gamma(m+0.5))*polyval(p, 0)
        print psi0
        if m==2.:
            Cdelta=3.541
        if m==6.:
            Cdelta=1.966
    else:
        raise Exception("Mother must be one of MORLET,PAUL,DOG")
    
    #eq. (11) in Torrence and Compo (1998)
    iwave = dj * np.sqrt(dt) / Cdelta /psi0 * (np.real(wave) / sj**0.5).sum(axis=0) 
    return iwave