Python scipy.array() Examples

The following are 30 code examples of scipy.array(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module scipy , or try the search function .
Example #1
Source File: instrument_model.py    From isofit with Apache License 2.0 6 votes vote down vote up
def _flat_field(X, uniformity_thresh):
    """."""

    Xhoriz = _low_frequency_horiz(X, sigma=4.0)
    Xhorizp = _low_frequency_horiz(X, sigma=3.0)
    nl, nb, nc = X.shape
    FF = s.zeros((nb, nc))
    use_ff = s.ones((X.shape[0], X.shape[2])) > 0
    for b in range(nb):
        xsub = Xhoriz[:, b, :]
        xsubp = Xhorizp[:, b, :]
        mu = xsub.mean(axis=0)
        dists = abs(xsub - mu)
        distsp = abs(xsubp - mu)
        thresh = _percentile(dists.flatten(), 90.0)
        uthresh = dists * uniformity_thresh
        #use       = s.logical_and(dists<thresh, abs(dists-distsp) < uthresh)
        use = dists < thresh
        FF[b, :] = ((xsub*use).sum(axis=0)/use.sum(axis=0)) / \
            ((X[:, b, :]*use).sum(axis=0)/use.sum(axis=0))
        use_ff = s.logical_and(use_ff, use)
    return FF, Xhoriz, Xhorizp, s.array(use_ff) 
Example #2
Source File: first_peaks_method.py    From Automated_Music_Transcription with MIT License 6 votes vote down vote up
def readWav():
    """
        Reads a sound wave from a standard input and finds its parameters.
    """

    # Read the sound wave from the input.
    sound_wave = wave.open(sys.argv[1], "r")

    # Get parameters of the sound wave.
    nframes = sound_wave.getnframes()
    framerate = sound_wave.getframerate()
    params = sound_wave.getparams()
    duration = nframes / float(framerate)

    print "frame rate: %d " % (framerate,)
    print "nframes: %d" % (nframes,)
    print "duration: %f seconds" % (duration,)
    print scipy.array(sound_wave)

    return (sound_wave, nframes, framerate, duration, params) 
Example #3
Source File: old2cpDetect.py    From cpdetect with GNU General Public License v3.0 6 votes vote down vote up
def calc_twostate_weights( data ):
	weights=[0,0,0] # the change cannot have occurred in the last 3 points
	means_mss=calc_mean_mss( data )

	i=0
	try:
		for nA, mean2A, varA, nB, mean2B, varB in means_mss :
			#print "computing for data", nA, mean2A, varA, nB, mean2B, varB
			numf1 = calc_alpha( nA, mean2A, varA )
			numf2 = calc_alpha( nB, mean2B, varB )
			denom = (varA + varB) * (mean2A*mean2B)
			weights.append( (numf1*numf2)/denom) 
			i += 1
	except:
		print "failed at data", i # means_mss[i]
		print "---"
		#print means_mss
		print "---"
		raise

	weights.extend( [0,0] ) # the change cannot have occurred at the last 2 points
	return array( weights ) 
Example #4
Source File: test_mldata.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def test_fetch_one_column(tmpdata):
    _urlopen_ref = datasets.mldata.urlopen
    try:
        dataname = 'onecol'
        # create fake data set in cache
        x = sp.arange(6).reshape(2, 3)
        datasets.mldata.urlopen = mock_mldata_urlopen({dataname: {'x': x}})

        dset = fetch_mldata(dataname, data_home=tmpdata)
        for n in ["COL_NAMES", "DESCR", "data"]:
            assert_in(n, dset)
        assert_not_in("target", dset)

        assert_equal(dset.data.shape, (2, 3))
        assert_array_equal(dset.data, x)

        # transposing the data array
        dset = fetch_mldata(dataname, transpose_data=False, data_home=tmpdata)
        assert_equal(dset.data.shape, (3, 2))
    finally:
        datasets.mldata.urlopen = _urlopen_ref 
Example #5
Source File: least_squares_first_peaks_2.py    From Automated_Music_Transcription with MIT License 6 votes vote down vote up
def readWav():
    """
        Reads a sound wave from a standard input and finds its parameters.
    """

    # Read the sound wave from the input.
    sound_wave = wave.open(sys.argv[1], "r")
  
    # Get parameters of the sound wave.
    nframes = sound_wave.getnframes()
    framerate = sound_wave.getframerate()
    params = sound_wave.getparams()
    duration = nframes / float(framerate)

    print "frame rate: %d " % (framerate,)
    print "nframes: %d" % (nframes,)
    print "duration: %f seconds" % (duration,)
    print scipy.array(sound_wave)

    return (sound_wave, nframes, framerate, duration, params) 
Example #6
Source File: rlocus.py    From python-control with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _break_points(num, den):
    """Extract break points over real axis and gains given these locations"""
    # type: (np.poly1d, np.poly1d) -> (np.array, np.array)
    dnum = num.deriv(m=1)
    dden = den.deriv(m=1)
    polynom = den * dnum - num * dden
    real_break_pts = polynom.r
    # don't care about infinite break points
    real_break_pts = real_break_pts[num(real_break_pts) != 0]
    k_break = -den(real_break_pts) / num(real_break_pts)
    idx = k_break >= 0   # only positives gains
    k_break = k_break[idx]
    real_break_pts = real_break_pts[idx]
    if len(k_break) == 0:
        k_break = [0]
        real_break_pts = den.roots
    return k_break, real_break_pts 
Example #7
Source File: add_HRRR_profiles_to_modtran_config.py    From isofit with Apache License 2.0 6 votes vote down vote up
def get_HRRR_data(filename):
    grbs = pygrib.open(filename)

    msgs = [str(grb) for grb in grbs]

    string = 'Geopotential Height:gpm'
    temp = [msg for msg in msgs if msg.find(string) > -1 and msg.find('isobaricInhPa') > -1]
    pressure_levels_Pa = s.array([int(s.split(' ')[3]) for s in temp])

    geo_pot_height_grbs = grbs.select(name = 'Geopotential Height', \
                                      typeOfLevel='isobaricInhPa', level=lambda l: l > 0)
    temperature_grbs = grbs.select(name = 'Temperature', \
                                   typeOfLevel='isobaricInhPa', level=lambda l: l > 0)
    rh_grbs = grbs.select(name = 'Relative humidity', \
                          typeOfLevel='isobaricInhPa', level=lambda l: l > 0)

    lat, lon = geo_pot_height_grbs[0].latlons()

    geo_pot_height = s.stack([grb.values for grb in geo_pot_height_grbs])
    temperature = s.stack([grb.values for grb in temperature_grbs])
    rh = s.stack([grb.values for grb in rh_grbs])

    return lat, lon, geo_pot_height, temperature, rh, pressure_levels_Pa 
Example #8
Source File: fig4p5.py    From Mathematics-of-Epidemics-on-Networks with MIT License 6 votes vote down vote up
def complete_graph_dX(X, t, tau, gamma, N):
    r'''This system is given in Proposition 2.3, taking Q=S, T=I
    f_{SI}(k) = f_{QT}= k*\tau 
    f_{IS}(k) = f_{TQ} = \gamma
    
    \dot{Y}^0 = \gamma Y^1 - 0\\
    \dot{Y}^1 = 2\gamma Y^2  + 0Y^0 - (\gamma + (N-1)\tau)Y^1
    \dot{Y}^2 = 3\gamma Y^3 + (N-1)\tau Y^1 - (2\gamma+2(N-2))Y^2
    ...
    \dot{Y}^N = (N-1)\tau Y^{N-1} - N\gamma Y^N
    Note that X has length N+1
    '''
    #X[k] is probability of k infections.  
    dX = []
    dX.append(gamma*X[1])
    for k in range(1,N):
        dX.append((k+1)*gamma*X[k+1]+ (N-k+1)*(k-1)*tau*X[k-1]
                    - ((N-k)*k*tau + k*gamma)*X[k])
    dX.append((N-1)*tau*X[N-1] - N*gamma*X[N])
    
    return scipy.array(dX) 
Example #9
Source File: fig3p2.py    From Mathematics-of-Epidemics-on-Networks with MIT License 6 votes vote down vote up
def star_graph_lumped(N, tau, gamma, I0, tmin, tmax, tcount):
    times = scipy.linspace(tmin, tmax, tcount)
    #    [[central node infected] + [central node susceptible]]
    #X = [Y_1^1, Y_1^2, ..., Y_1^{N}, Y_2^0, Y_2^1, ..., Y_2^{N-1}]
    X0 = scipy.zeros(2*N)  #length 2*N of just 0 entries
    #X0[I0]=I0*1./N #central infected, + I0-1 periph infected prob
    X0[N+I0] = 1#-I0*1./N #central suscept + I0 periph infected
    X = EoN.my_odeint(star_graph_dX, X0, times, args = (tau, gamma, N))
    #X looks like [[central susceptible,k periph] [ central inf, k-1 periph]] x T

    central_susc = X[:,N:]
    central_inf = X[:,:N]
    print(central_susc[-1][:])
    print(central_inf[-1][:])
    I = scipy.array([ sum(k*central_susc[t][k] for k in range(N))
              + sum((k+1)*central_inf[t][k] for k in range(N))
              for t in range(len(X))])
    S = N-I
    return times, S, I 
Example #10
Source File: checkdam.py    From hydrology with GNU General Public License v3.0 6 votes vote down vote up
def find_range(array, x):
    """
    Function to calculate bounding intervals from array to do piecewise linear interpolation.

    :param array: list of values
    :param x: interpolation value
    :return: boundary interval

    Examples:
        >>> array = [0, 1, 2, 3, 4]
        >>>find_range(array, 1.5)
        1, 2
    """
    if x < max(array):
        start = bisect_left(array, x)
        return array[start-1], array[start]
    else:
        return min(array), max(array) 
Example #11
Source File: fig3p2.py    From Mathematics-of-Epidemics-on-Networks with MIT License 6 votes vote down vote up
def complete_graph_dX(X, t, tau, gamma, N):
    r'''This system is given in Proposition 2.3, taking Q=S, T=I
    f_{SI}(k) = f_{QT}= k*\tau 
    f_{IS}(k) = f_{TQ} = \gamma
    
    \dot{Y}^0 = \gamma Y^1 - 0\\
    \dot{Y}^1 = 2\gamma Y^2  + 0Y^0 - (\gamma + (N-1)\tau)Y^1
    \dot{Y}^2 = 3\gamma Y^3 + (N-1)\tau Y^1 - (2\gamma+2(N-2))Y^2
    ...
    \dot{Y}^N = (N-1)\tau Y^{N-1} - N\gamma Y^N
    Note that X has length N+1
    '''
    #X[k] is probability of k infections.  
    dX = []
    dX.append(gamma*X[1])
    for k in range(1,N):
        dX.append((k+1)*gamma*X[k+1]+ (N-k+1)*(k-1)*tau*X[k-1]
                    - ((N-k)*k*tau + k*gamma)*X[k])
    dX.append((N-1)*tau*X[N-1] - N*gamma*X[N])
    
    return scipy.array(dX) 
Example #12
Source File: fig2p11.py    From Mathematics-of-Epidemics-on-Networks with MIT License 6 votes vote down vote up
def star_graph_lumped(N, tau, gamma, I0, tmin, tmax, tcount):
    times = scipy.linspace(tmin, tmax, tcount)
    #    [[central node infected] + [central node susceptible]]
    #X = [Y_1^1, Y_1^2, ..., Y_1^{N}, Y_2^0, Y_2^1, ..., Y_2^{N-1}]
    X0 = scipy.zeros(2*N)  #length 2*N of just 0 entries
    X0[I0]=I0*1./N #central infected, + I0-1 periph infected prob
    X0[N+I0] = 1-I0*1./N #central suscept + I0 periph infected
    X = EoN.my_odeint(star_graph_dX, X0, times, args = (tau, gamma, N))
    #X looks like [[central susceptible,k periph] [ central inf, k-1 periph]] x T

    central_inf = X[:,:N]
    central_susc = X[:,N:]

    I = scipy.array([ sum(k*central_susc[t][k] for k in range(N))
            + sum((k+1)*central_inf[t][k] for k in range(N))
            for t in range(len(X))])
    S = N-I
    return times, S, I 
Example #13
Source File: fig2p11.py    From Mathematics-of-Epidemics-on-Networks with MIT License 6 votes vote down vote up
def complete_graph_dX(X, t, tau, gamma, N):
    r'''This system is given in Proposition 2.3, taking Q=S, T=I
    f_{SI}(k) = f_{QT}= k*\tau
    f_{IS}(k) = f_{TQ} = \gamma

    \dot{Y}^0 = \gamma Y^1 - 0\\
    \dot{Y}^1 = 2\gamma Y^2  + 0Y^0 - (\gamma + (N-1)\tau)Y^1
    \dot{Y}^2 = 3\gamma Y^3 + (N-1)\tau Y^1 - (2\gamma+2(N-2))Y^2
    ...
    \dot{Y}^N = (N-1)\tau Y^{N-1} - N\gamma Y^N
    Note that X has length N+1
    '''
    #X[k] is probability of k infections.
    dX = []
    dX.append(gamma*X[1])
    for k in range(1,N):
        dX.append((k+1)*gamma*X[k+1]+ (N-k+1)*(k-1)*tau*X[k-1]
                    - ((N-k)*k*tau + k*gamma)*X[k])
    dX.append((N-1)*tau*X[N-1] - N*gamma*X[N])

    return scipy.array(dX) 
Example #14
Source File: UI_reactor.py    From pychemqt with GNU General Public License v3.0 6 votes vote down vote up
def Regresion(self):
        t=array(self.KEq_Tab.getColumn(0)[:-1])
        k=array(self.KEq_Tab.getColumn(1)[:-1])
        if len(t)>=4:
            if 4<=len(t)<8:
                inicio=r_[0, 0, 0, 0]
                f=lambda par, T: exp(par[0]+par[1]/T+par[2]*log(T)+par[3]*T)
                resto=lambda par, T, k: k-f(par, T)
            else:
                inicio=r_[0, 0, 0, 0, 0, 0, 0, 0]
                f=lambda par, T: exp(par[0]+par[1]/T+par[2]*log(T)+par[3]*T+par[4]*T**2+par[5]*T**3+par[6]*T**4+par[7]*T**5)
                resto=lambda par, T, k: k-f(par, T)

            ajuste=leastsq(resto,inicio,args=(t, k))
            kcalc=f(ajuste[0], t)
            error=(k-kcalc)/k*100
            self.KEq_Dat.setColumn(0, ajuste[0])
            self.KEq_Tab.setColumn(2, kcalc)
            self.KEq_Tab.setColumn(3, error)

            if ajuste[1] in [1, 2, 3, 4]:
                self.ajuste=ajuste[0] 
Example #15
Source File: viewComponents.py    From pychemqt with GNU General Public License v3.0 6 votes vote down vote up
def fill(self, array):
        """Populate the widgets with the DIPPR coefficient in array in format
        [eq, A, B, C, D, E, Tmin, Tmax]"""
        if array[0] != 0:
            for valor, entrada in zip(array[1:6], self.coeff):
                entrada.setValue(valor)
            self.tmin.setValue(array[6])
            self.tmax.setValue(array[7])
            self.eq.setValue(array[0])
            latex = self.latex[array[0]]
            tex = "$%s = %s$" % (self.proptex, latex)
            self.eqformula.setTex(tex)
            self.eq.setVisible(False)
            self.eqformula.setVisible(True)
            self.btnPlot.setEnabled(True)
            self.equation = array[0] 
Example #16
Source File: c9_23_efficient_based_on_sortino_ratio.py    From Python-for-Finance-Second-Edition with MIT License 5 votes vote down vote up
def sortino(R,w):
    mean_return=sp.mean(R,axis=0)
    ret = sp.array(mean_return)
    LPSD=LPSD_f(R,rf)
    return (sp.dot(w,ret) - rf)/LPSD

# function 4: for given n-1 weights, return a negative sharpe ratio 
Example #17
Source File: surface_glint.py    From isofit with Apache License 2.0 5 votes vote down vote up
def Sa(self, x_surface, geom):
        """Covariance of prior distribution, calculated at state x.  We find
        the covariance in a normalized space (normalizing by z) and then un-
        normalize the result for the calling function."""

        Cov = ThermalSurface.Sa(self, x_surface, geom)
        f = s.array([[(10.0 * self.scale[self.glint_ind])**2]])
        Cov[self.glint_ind, self.glint_ind] = f
        return Cov 
Example #18
Source File: c9_44_equal_weighted_vs_value_weighted.py    From Python-for-Finance-Second-Edition with MIT License 5 votes vote down vote up
def ret_f(ticker):
    a=x[x.index==ticker]
    p=sp.array(a['VALUE'])
    ddate=a['DATE'][1:]
    ret=p[1:]/p[:-1]-1
    out1=pd.DataFrame(p[1:],index=ddate)
    out2=pd.DataFrame(ret,index=ddate)
    output=pd.merge(out1,out2,left_index=True, right_index=True)
    output.columns=['Price_'+ticker,'Ret_'+ticker]
    return output 
Example #19
Source File: c9_14_get_IBM_ret_from_yanMonthly.py    From Python-for-Finance-Second-Edition with MIT License 5 votes vote down vote up
def ret_f(ticker):
    a=x[x.index==ticker]
    p=sp.array(a['VALUE'])
    ddate=a['DATE']
    ret=p[1:]/p[:-1]-1
    output=pd.DataFrame(ret,index=ddate[1:])
    output.columns=[ticker]
    return output 
Example #20
Source File: fig2p11.py    From Mathematics-of-Epidemics-on-Networks with MIT License 5 votes vote down vote up
def star_graph_dX(X, t, tau, gamma, N):
    '''this system is given in Proposition 2.4, taking Q=S, T=I
    so f_{SI}(k) = f_{QT}(k) = k*tau
    f_{IS}(k) = f_{TQ}(k) = gamma
    X has length 2*(N-1)+2 = 2N'''

    #    [[central node infected] + [central node susceptible]]
    #X = [Y_1^1, Y_1^2, ..., Y_1^{N}, Y_2^0, Y_2^1, ..., Y_2^{N-1}]

    #Note that in proposition Y^0 is same as Y_2^0
    #and Y^N is same as Y_1^N

    #Y1[k]: central node infected, & k-1 peripheral nodes infected
    Y1vec = [0]+list(X[0:N])      #for Y_1^k, use Y1vec[k]
    #pad with 0 to make easier calculations Y_1^0=0
    #the probability of -1 nodes infected is 0

    #Y2[k]: central node susceptible & k peripheral nodes infected
    Y2vec = list(X[N:])+[0]   #for Y_2^k use Y2vec[k]
    #padded with 0 to make easier calculations. Y_2^N=0
    #the probability of N (of N-1) peripheral nodes infected is 0
    dY1vec = []
    dY2vec = []
    for k in range(1, N):
        #k-1 peripheral nodes infected, central infected
        dY1vec.append((N-k+1)*tau*Y1vec[k-1] + (k-1)*tau*Y2vec[k-1]
                    +k*gamma*Y1vec[k+1]
                    - ((N-k)*tau + (k-1)*gamma+gamma)*Y1vec[k])
    #now the Y^N equation
    dY1vec.append(tau*Y1vec[N-1] + (N-1)*tau*Y2vec[N-1] - N*gamma*Y1vec[N])

    #now the Y^0 equation
    dY2vec.append(gamma*(N-1)*Y1vec[1] + gamma*Y2vec[1]-0)

    for k in range(1,N):
        #k peripheral nodes infected, central susceptible
        dY2vec.append(0 + gamma*Y1vec[k+1] + gamma*(k+1)*Y2vec[k+1]
                    - (k*tau + 0 + k*gamma)*Y2vec[k])

    return scipy.array(dY1vec + dY2vec) 
Example #21
Source File: fig2p11.py    From Mathematics-of-Epidemics-on-Networks with MIT License 5 votes vote down vote up
def complete_graph_lumped(N, tau, gamma, I0, tmin, tmax, tcount):
    times = scipy.linspace(tmin, tmax, tcount)
    X0 = scipy.zeros(N+1)  #length N+1 of just 0 entries
    X0[I0]=1. #start with 100 infected.
    X = integrate.odeint(complete_graph_dX, X0, times, args = (tau, gamma, N))
    #X[t] is array whose kth entry is p(k infected| time=t).
    I = scipy.array([sum(k*Pkt[k] for k in range(len(Pkt))) for Pkt in X])
    S = N-I
    return times, S, I 
Example #22
Source File: optics.py    From REDPy with GNU General Public License v3.0 5 votes vote down vote up
def set_reach_dist(SetOfObjects, point_index, epsilon):

    """
    Sets reachability distance and ordering. This function is the primary workhorse of
    the OPTICS algorithm.
    
    SetofObjects: Instantiated and prepped instance of 'setOfObjects' class
    epsilon: Determines maximum object size that can be extracted. Smaller epsilons
        reduce run time. (float)

    """
    
    row = [SetOfObjects.data[point_index,:]]
    indices = np.argsort(row)
    distances = np.sort(row)

    if scipy.iterable(distances):

        unprocessed = indices[(SetOfObjects._processed[indices] < 1)[0].T]
        rdistances = scipy.maximum(distances[(SetOfObjects._processed[indices] < 1)[0].T],
            SetOfObjects._core_dist[point_index])
        SetOfObjects._reachability[unprocessed] = scipy.minimum(
            SetOfObjects._reachability[unprocessed], rdistances)

        if unprocessed.size > 0:
            return unprocessed[np.argsort(np.array(SetOfObjects._reachability[
                unprocessed]))[0]]
        else:
            return point_index
    else:
        return point_index 
Example #23
Source File: optics.py    From REDPy with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, distance_pairs):

        self.data = distance_pairs
        self._n = len(self.data)
        self._processed = scipy.zeros((self._n, 1), dtype=bool)
        self._reachability = scipy.ones(self._n) * scipy.inf
        self._core_dist = scipy.ones(self._n) * scipy.nan
        self._index = scipy.array(range(self._n))
        self._nneighbors = scipy.ones(self._n, dtype=int)*self._n
        self._cluster_id = -scipy.ones(self._n, dtype=int)
        self._is_core = scipy.ones(self._n, dtype=bool)
        self._ordered_list = [] 
Example #24
Source File: count_expression.py    From pancanatlas_code_public with MIT License 5 votes vote down vote up
def compress_g(g, idx2gene):
    """Find reduced g"""

    g = sorted(g, key = lambda x: len(idx2gene[x]))[::-1]
    g_ = [g[0]]
    seen = idx2gene[g[0]]

    for gg in g[1:]:
        if not all([i in seen for i in idx2gene[gg]]):
            g_.append(gg)
            seen += idx2gene[gg]
    
    return sp.array(g_) 
Example #25
Source File: recipe-576547.py    From code with MIT License 5 votes vote down vote up
def total_mass_conservation(number_mat, vol_grid,box_volume):
	ini_mass=s.dot(number_mat[0,:],vol_grid)*box_volume
	fin_mass=s.dot(number_mat[-1,:],vol_grid)*box_volume
	mass_conservation=(ini_mass-fin_mass)/ini_mass

	results=s.array([ini_mass,fin_mass,mass_conservation])
	return results 
Example #26
Source File: signal_processing.py    From bird-species-classification with MIT License 5 votes vote down vote up
def stft(x, fs, framesz, hop):
    framesamp = int(framesz*fs)
    hopsamp = int(hop*fs)
    w = scipy.hanning(framesamp)
    X = scipy.array([scipy.fft(w*x[i:i+framesamp])
                     for i in range(0, len(x)-framesamp, hopsamp)])
    return X 
Example #27
Source File: old2cpDetect.py    From cpdetect with GNU General Public License v3.0 5 votes vote down vote up
def largest_logodds( self ):
		return array( self.logodds.values() ).max() 
Example #28
Source File: viewComponents.py    From pychemqt with GNU General Public License v3.0 5 votes vote down vote up
def fit(self):
        """Fit experimental data to a DIPPR equation"""
        uniT = unidades.Temperature.text()
        hHeader = ["T, %s" % uniT, "%s, %s" % (self.title(), self.unit.text())]
        dlg = InputTableDialog(
                title=self.title(), DIPPR=True, horizontalHeader=hHeader,
                hasTc=True, Tc=self.parent.Tc.value, t=self.t,
                property=self.data, eq=self.eq.value())

        if dlg.exec_():
            t = array(dlg.widget.column(0, unidades.Temperature))
            p = array(dlg.widget.column(1, self.unit))
            eq = dlg.widget.eqDIPPR.value()

            def errf(parametros, eq, t, f):
                var = array([eq]+list(parametros))
                return f-array([DIPPR(self.prop, ti, var) for ti in t])

            # Do the least square fitting
            p0 = [1, 1, 1, 1, 1]
            coeff, cov, info, mesg, ier = optimize.leastsq(
                    errf, p0, args=(eq, t, p), full_output=True)

            ss_err = (info['fvec']**2).sum()
            ss_tot = ((p-p.mean())**2).sum()
            r = 1-(ss_err/ss_tot)

            if ier in range(1, 5):
                self.fill([eq]+list(coeff)+[min(t), max(t)])
                self.t = list(t)
                self.data = list(p)
                self.plot(r)
                self.valueChanged.emit()
            else:
                title = QtWidgets.QApplication.translate("pychemqt", "Warning")
                msg = QtWidgets.QApplication.translate(
                        "pychemqt", "Fit unsuccessfully")
                QtWidgets.QMessageBox.warning(self, title, msg) 
Example #29
Source File: tdft.py    From Shazam with MIT License 5 votes vote down vote up
def tdft(audio, srate, windowsize, windowshift,fftsize):

    """Calculate the real valued fast Fourier transform of a segment of audio multiplied by a 
    a Hamming window.  Then, convert to decibels by multiplying by 20*log10.  Repeat for all
    segments of the audio."""
    
    windowsamp = int(windowsize*srate)
    shift = int(windowshift*srate)
    window = scipy.hamming(windowsamp)
    spectrogram = scipy.array([20*scipy.log10(abs(np.fft.rfft(window*audio[i:i+windowsamp],fftsize))) 
                     for i in range(0, len(audio)-windowsamp, shift)])
    return spectrogram 
Example #30
Source File: fig3p2.py    From Mathematics-of-Epidemics-on-Networks with MIT License 5 votes vote down vote up
def star_graph_dX(X, t, tau, gamma, N):
    '''this system is given in Proposition 2.4, taking Q=S, T=I
    so f_{SI}(k) = f_{QT}(k) = k*tau
       f_{IS}(k) = f_{TQ}(k) = gamma
    X has length 2*(N-1)+2 = 2N'''

    #    [[central node infected] + [central node susceptible]]
    #X = [Y_1^1, Y_1^2, ..., Y_1^{N}, Y_2^0, Y_2^1, ..., Y_2^{N-1}]

    #Note that in proposition Y^0 is same as Y_2^0 
    #and Y^N is same as Y_1^N
    
    #Y1[k]: central node infected, & k-1 peripheral nodes infected
    Y1vec = [0]+list(X[0:N])      #for Y_1^k, use Y1vec[k]
    #pad with 0 to make easier calculations Y_1^0=0
    #the probability of -1 nodes infected is 0

    #Y2[k]: central node susceptible & k peripheral nodes infected
    Y2vec = list(X[N:])+[0]   #for Y_2^k use Y2vec[k]
    #padded with 0 to make easier calculations. Y_2^N=0
    #the probability of N (of N-1) peripheral nodes infected is 0
    dY1vec = []
    dY2vec = []
    for k in range(1, N):
        #k-1 peripheral nodes infected, central infected
        dY1vec.append((N-k+1)*tau*Y1vec[k-1] + (k-1)*tau*Y2vec[k-1] 
                      +k*gamma*Y1vec[k+1] 
                      - ((N-k)*tau + (k-1)*gamma+gamma)*Y1vec[k])
    #now the Y^N equation
    dY1vec.append(tau*Y1vec[N-1] + (N-1)*tau*Y2vec[N-1] - N*gamma*Y1vec[N])
    
    #now the Y^0 equation
    dY2vec.append(gamma*(N-1)*Y1vec[1] + gamma*Y2vec[1]-0)

    for k in range(1,N):
        #k peripheral nodes infected, central susceptible
        dY2vec.append(0 + gamma*Y1vec[k+1] + gamma*(k+1)*Y2vec[k+1]
                      - (k*tau + 0 + k*gamma)*Y2vec[k])

    return scipy.array(dY1vec + dY2vec)