Пример #1
0
def fitear(funcion_aux, x_data, y_data, params_opt=None):

    if params_opt:
        fit_params, fit_covar = fit(funcion_aux, x_data, y_data, p0=params_opt)
    else:
        fit_params, fit_covar = fit(funcion_aux, x_data, y_data)

    cant_param = len(fit_params)
    params = np.array([])

    for ind_param in range(cant_param):
        params = np.append(params, fit_params[ind_param])

    return funcion_aux(x_data, *params)
Пример #2
0
    def fit(self, func, p0, freq_range=(0, 1.5), bounds=(-np.inf, np.inf)):
        self._func = func

        T = self.T.loc[self.T.freq.between(*freq_range)]

        real_func = lambda *args: np.real(func(*args))
        imag_func = lambda *args: np.imag(func(*args))

        ropt, rcov = fit(real_func, T.freq, T.real, p0=p0, bounds=bounds)
        iopt, icov = fit(imag_func, T.freq, T.imag, p0=p0, bounds=bounds)
        rerr = np.sqrt(np.diag(rcov))
        ierr = np.sqrt(np.diag(icov))

        return pd.DataFrame({'r': ropt, 'rerr': rerr, 'i': iopt, 'ierr': ierr})
Пример #3
0
def fit_data(data, ini, t=None):
    if t:
        func = lambda B, Hf, Hso: wl.delta_sigma(B, Hf, Hso, t)
        ini = ini[:2]
    else:
        func = wl.delta_sigma
    
    try: 
        popt, pcov = fit(func, data.B, data.s, p0=ini)
        perr = np.sqrt(np.diag(pcov))
        
        if t:
            popt.append(t)
            perr.append(0)
            
        out = dict(zip(['Hf', 'Hso', 't', 'Hf_err', 'Hso_err', 't_err'], 
                       np.concatenate((popt, perr))))
        
    except:
        print('Could not find the optimal parameters for ', data.attrs)
        out = dict(zip(['Hf', 'Hso', 't', 'Hf_err', 'Hso_err', 't_err'],
                       np.full(6, None)))
        
    finally:
        return out
Пример #4
0
    def run(self, cxn, context):
        self.pulser.line_trigger_state(False)
        self.setup_datavault(
            'frequency', 'photons')  # gives the x and y names to Data Vault
        self.setup_grapher('Interleaved Linescan')
        self.detunings = self.get_scan_list(
            self.p.InterleavedLinescan.line_scan, 'MHz')
        return_detuning, return_counts = [], []
        for i, detuning in enumerate(self.detunings):
            if context == (0, 2):
                should_break = self.update_progress(i /
                                                    float(len(self.detunings)))
                if should_break:
                    return should_break
            # self.p.Transitions.main_cooling_369 divide by 2 for the double pass
            freq = U(detuning, 'MHz') / 2.0 + self.p.ddsDefaults.DP369_freq
            track_detuning, track_counts = self.program_pulser(freq, detuning)
            return_detuning.append(track_detuning)
            return_counts.append(track_counts)

        # skip first couple points of data since they occasionally come in at random values
        # after performing a Shelving experiment, should not affect fit. Then set the parameter
        # in parametervault to the fitted center
        popt, pcov = fit(self.lorentzian_fit,
                         return_detuning[2:],
                         return_counts[2:],
                         p0=self.fit_guess)
        self.pv.set_parameter(
            ('Transitions', 'main_cooling_369', U(popt[0], 'MHz')))
Пример #5
0
    def run(self, cxn, context):

        self.set_default_parameters()
        self.setup_datavault('time', 'probability')
        self.setup_grapher('Rabi Flopping qubit_0')

        self.times = np.arange(0.1, 6.1 * self.pi_time, 3.2)
        probs, times = [], []
        for i, duration in enumerate(self.times):
            should_break = self.update_progress(i/float(len(self.times)))
            if should_break:
                self.pulser.line_trigger_state(False)
                break
            self.p['MicrowaveInterrogation.duration'] = U(duration, 'us')
            self.program_pulser(sequence)
            [counts] = self.run_sequence()


            if i % self.p.StandardStateDetection.points_per_histogram == 0:
                hist = self.process_data(counts)
                self.plot_hist(hist)

            pop = self.get_pop(counts)
            self.dv.add(duration, pop)
            probs.append(pop)
            times.append(duration)

        popt, pcov = fit(self.rabi, times, probs, p0=[1.0, self.pi_time, 0.0, 0.0],
                         bounds=(0.0, [1.0, 200.0, 3.14, 1.0]))
        self.pv.set_parameter(('Pi_times', 'qubit_0', U(popt[1], 'us')))
        print('Updated qubit_0 pi_time to ' + str(popt[1])[:8] + ' microseconds')

        return popt[1]
Пример #6
0
def get_fit_inrange(binc, y, inf, sup, plot=False):
    entries = np.sum(y)
    x = binc[np.where((binc > inf) & (binc < sup))]
    y = y[np.where((binc > inf) & (binc < sup))]
    s = np.sqrt(y * (1 - y / entries))
    mean = np.dot(y, x) / np.sum(y)
    std = 20  # np.std(data)
    A = np.max(y)
    par, cov = fit(gaus,
                   x,
                   y,
                   p0=[A, mean, std, 0, 0],
                   sigma=s,
                   absolute_sigma=True)
    if plot:
        xfit = np.linspace(np.min(x), np.max(x), 500)
        ax.plot(x, y, '.b', label='Data')
        ax.plot(xfit, gaus(xfit, *par), 'r', label='Fit')
        ax.set_xlabel('ADC')
        ax.set_ylabel('Entries')
        ax.legend(loc=1,
                  frameon=True,
                  fancybox=False,
                  framealpha=1,
                  edgecolor='k')
        plt.draw()
        plt.pause(0.5)
        plt.cla()
    N = x.size
    return par, cov, N
Пример #7
0
def modelfit(N, bins, count, params):


    burst=PulseModel(N, bins, counts)
    
    final_param=fit(burst, bins, count, p0=param)
    
    return final_param
Пример #8
0
    def runFit(self , simulated , experimental , a0 , d0 , shift0 , key):
        popt , pcov = fit(self.convolveWithGaussian , simulated, experimental, p0 = (a0 , d0 , shift0), bounds = ((0 , 0 , 0) , (10 , 10 ,1) ))
        broadened = self.convolveWithGaussian(simulated , *popt)

        print(key + ":  fwhm= " , popt[0]  , "+/- " , pcov[0][0] ," ",
              ", vertical shift= " , popt[1]  , "+/- " , pcov[1][1] ," ",
              ", horizontal shift= " , popt[2]  , "+/- " , pcov[2][2] ," ")

        return(broadened , popt , pcov)
Пример #9
0
def gauss(model, x, y, p0):
    popt, pcov = fit(
        model, x, y,
        p0)  #popt son los parametros del fit, pcov es la curva del fit
    maxg = popt[0]
    meang = popt[1]
    sigmag = popt[2]

    return [maxg, meang, sigmag]
Пример #10
0
def shockley_fit(I, V):
    params = fit(
        shockley,
        V,
        I,
    )
    n = params[0][0]
    Is = params[0][1]
    return [n, Is]
Пример #11
0
def Gaussfit(
    space,
    Array,
    init_width=30
):  # Fit Gaussian to magnitude of Amplitude array. Return fit parameters.
    init_params = [
        0.1, 1, init_width
    ]  # Use initial width parameter smaller than expected width for beam profile. Otherwise, use initial width parameter larger than expected width - avoids bad fit in k-space.
    est_params, est_err = fit(Gaussian, space, Array, p0=init_params)
    return est_params  # [offset, amplitude, width]
Пример #12
0
def MC_Amer_call(S0, K, mu, r, d, sigma, t, T, delta_t, N):
    '''
    Parameters
    ==========
    S0: float
        Initial value of stock process
    mu: float
        Drift of stock process
    r: float
        Risk Free rate
    delta: float
        Continuous dividend yield
    sigma: float
        Volatility of stock process
    T: float
        Time horizon
    delta_t: float
        Time step size
    N: integer
        Number of paths to generate
    
    Returns
    =======
    C: Float
        Value of American call option
    '''

    M = int((T - t) / delta_t)  # number of steps. Must be an integer.

    S = generate_paths(S0, mu, d, sigma, delta_t, N, M)

    h = np.maximum(S - K, 0)  #compute exercise values
    g = h[M]  #set up excercised value vector
    tau = np.repeat(T, N)  #set up stopping time vector

    for j in range(M - 1, 0, -1):
        k = S[j] > K  #in the money boolean vector
        x = S[j, k]  # in the money points
        y = g[k] * np.exp(-(r - d) * (tau[k] - t * delta_t))

        a, __ = fit(func, x, y)  #regression step
        C_hat = func(S[j, k], a[0], a[1], a[2],
                     a[3])  #find estimated continuation value

        g[k][C_hat >= h[j, k]] = h[j, k][
            C_hat >= h[j, k]]  #update g where excercise more than continuation
        tau[k][C_hat >= h[j, k]] = j / f8(M) * (
            T - t)  #update optimal excercise time

    C_0 = np.sum(np.exp(-(r - d) * delta_t * tau).T * g) / N
    V_0 = np.maximum(C_0, h[0, 0])

    return V_0
Пример #13
0
def von_mises_fit(stimulusAng,avgSur=180):
    """The von Mises fit function:
        This function creates the best von Mises fit on the neuronal population activity by using Levenberg-Marquardt algorithm. The fit
        is done by using the fit_func(ang,amp,kappa,avg) outputs. scipy.optimize.curve_fit() is used for Levenberg-Marquardt algorithm.
        The decoded center hue angle is the angle (x value) of the von Mises fit with global maximum (maximal y-value).
        
        Paramters
        ---------
        stimulusAng: float. The hue angle of the center stimulus in degrees.
        avgSur: float, optional. The hue angle of the surround stimulus in degrees.
        
        Returns
        -------
        popt[2]-stimulusAng: float. The angle difference between the decoded and real center stimulus hues
        stimulusAng-avgSur: float. The angle difference between the center and surround stimuli hues
        popFit: list. All x-values of the von Mises fit to the population activity for different center stimulus conditions.
        surDecoder: list. The ensemble of the population activity for different center stimulus conditions.
        popt: list. The von Mises fit parameter values. These values are amplitude,kappa and global maximum, respectively.
    """
    #stimulusAng=180
    surDecoder=[]#Population activity for a given center-surround stimulus
    for i in range(0,len(colMod.resulty)):
        surDecoder.append(colMod.resulty[i][np.where(colMod.x==stimulusAng)[0][0]])
    x=colMod.x[np.where(colMod.x==0)[0][0]:np.where(colMod.x==360)[0][0]]#angles are restricted to a single cycle for the fit   
    popt, pcov = fit(fit_func, colMod.unitTracker, surDecoder,method='lm')#Levenberg-Marquardt algorithm, popt is the fit parameters, pcov gives the covariance matrix.
    popFit=fit_func(x,*popt)#The fit values to the population activity
    
    """
    Transform the negative angular values to the positive matching angle.
    """
    if popt[2]>360:
        popt[2]=popt[2]-360    
    if popt[2]<-360:
        popt[2]=popt[2]+360
    """
    If the kappa is fit as a negative value, it can be changed to the positive by adding 180° to the maximum value of the fit.
    """
    if popt[1]<0:
        popt[1]=abs(popt[1])
        popt[2]=popt[2]+180
    if popt[2]<-0.1 and popt[1]>0:
        popt[2]=360+popt[2]
#THESE IF STATEMENTS are to solve the irregular parameters problem: due to the fact: cos(x)=cos(-x) and -a*cos(x)=acos(x+180), if kappa is negative it is changed
#to its positive value before adding +180 to the readout angle. Similarly, if kappa is positive but angle is negative, 360 degrees are added (in that part threshold
#is given as -0.1 because in the beginning (stimulus angle=0) there is small error that decoded angle is in -0.000001 range.)
    return popt[2]-stimulusAng, stimulusAng-avgSur, popFit,surDecoder, popt 
Пример #14
0
    def run(self, cxn, context):

        self.setup_datavault(
            'frequency',
            'probability')  # gives the x and y names to Data Vault
        self.setup_grapher('Microwave Linescan qubit_minus')
        self.detunings = self.get_scan_list(self.p.MicrowaveLinescan.scan,
                                            'kHz')

        self.set_default_parameters()

        deltas, probs = [], []
        for i, detuning in enumerate(self.detunings):
            should_break = self.update_progress(i / float(len(self.detunings)))
            if should_break:
                break

            self.p['MicrowaveInterrogation.detuning'] = U(detuning, 'kHz')
            self.program_pulser(sequence)

            [counts] = self.run_sequence()

            if i % self.p.StandardStateDetection.points_per_histogram == 0:
                hist = self.process_data(counts)
                self.plot_hist(hist)

            pop = self.get_pop(counts)
            self.dv.add(detuning + self.p.Transitions.qubit_minus['kHz'], pop)
            deltas.append(detuning + self.p.Transitions.qubit_minus['kHz'])
            probs.append(pop)

        param_guess = [
            20.0, deltas[np.argmax(probs)],
            np.min(probs),
            np.max(probs) - np.min(probs)
        ]
        popt, pcov = fit(self.sinc_fit, deltas, probs, p0=param_guess)
        self.pv.set_parameter(('Transitions', 'qubit_minus', U(popt[1],
                                                               'kHz')))
        print('Updated qubit_minus frequency to ' + str(popt[1]) + ' kHz')

        return should_break
Пример #15
0
    def run_interleaved_linescan(self):
        self.pulser.line_trigger_state(False)

        linescan_context = self.sc.context()

        self.line_tracker = self.make_experiment(interleaved_linescan)
        self.line_tracker.initialize(self.cxn, linescan_context, self.ident)
        try:
            detunings, counts = self.line_tracker.run(self.cxn,
                                                      linescan_context)
        except TypeError:
            return TypeError

        if max(counts) < 100:
            print("Lorentzian is weak or missing")
            return RuntimeError

        if self.p.MicrowaveInterrogation.AC_line_trigger == 'On':
            self.pulser.line_trigger_state(True)
            self.pulser.line_trigger_duration(
                self.p.MicrowaveInterrogation.delay_from_line_trigger)

        fit_guess = [5.0, 30.0, 4000.0, 1.0]
        try:
            popt, pcov = fit(self.lorentzian_fit,
                             detunings[2:],
                             counts[2:],
                             p0=fit_guess)
        except RuntimeError:
            print(
                'Fit did not work, returning RuntimeError from scipy.curve_fit'
            )
            return RuntimeError

        center = popt[0]
        return center
Пример #16
0
    phi = -data[3]*f * 360 # phase = deltaT/T * 360
    fig = bodeplot(f, Amp=Vout/Vin, Phase=phi, deg=True)

    # Model
    fline = np.logspace(0, log10(2000), 1000)
    Hline = H_teo(2*np.pi*fline)
    Hline_abs = np.absolute(Hline)
    Hline_phase = np.angle(Hline) * 180/np.pi
    fig = bodeplot(fline, Amp=Hline_abs, Phase=Hline_phase, figure=fig, asline=True)

    # Slope estimation
    x = f[-3:]
    y = 20*np.log10(Vout[-3:]/Vin[-3:])
    M = np.ones((y.size, 2))
    M[:,1] = y
    params = fit(lambda x,p1,p2: p1+np.log10(x)*p2, x, y)
    print("Slope [dB/decade]", params[0][0])
    xline = np.linspace(6e1, max(x), 1000)
    
    # plot stile
    ax = fig.axes[0]
    handles,_ = ax.get_legend_handles_labels()
    fig.legend(handles, labels=["Data", "Model"], loc ='lower center', ncol=2)
    fig.subplots_adjust(hspace=0.4, left=0.1)
    ax.plot(xline, params[0][0] + params[0][1]*np.log10(xline), '--')
    plt.plot()
    plt.tight_layout()
    plt.show()

    # Output impedance
    fig = bodeplot(fline, Amp=np.absolute(Z_osc(2*np.pi*fline)), Phase=np.angle(Z_osc(2*np.pi*fline)), asline=True)
Пример #17
0
import numpy as np
from scipy.optimize import curve_fit as fit

z = [
    0.07, 0.11, 0.14, 0.18, 0.22, 0.27, 0.31, 0.36, 0.4, 0.45, 0.5, 0.55, 0.61,
    0.66, 0.72, 0.82, 0.98, 1.15, 1.33, 1.53, 1.75, 1.98, 2.24, 2.52, 2.82,
    3.15
]
a = []
for i in z:
    a.append(1.0 / i)

te = [
    2.51, 1.47, 1.52, 1.93, 2.07, 0.69, 1.4, 0.79, 1.92, 1.33, 1.15, 1.56,
    0.77, 1.16, 1.26, 0.91, 0.31, 1.55, 0.61, 0.37, 0.42, 0.54, 0.17, 0.18,
    0.27, 0.32
]
t = []
for tmp in te:
    t.append(tmp * 10**6)

#plt.scatter(a,t)


def func(x, a, b, k):
    return a * np.log10(b * x) + k


popt, pcov = fit(func, a, t)

plt.plot(a, func(a, *popt))
Пример #18
0
with open("C1t2mgh2ogood00000.txt", 'r') as file:
	for line in file.readlines()[23000::10]: #Drop data points before waveform begins. Downsample by 10.
		time, amplitude = line.split(',')

		times.append(float(time))
		amplitudes.append(float(amplitude))

	times = np.asarray(times)
	amplitudes = np.asarray(amplitudes)

peaks, properties = find_peaks(amplitudes, height=exponential(times, 5.65, 1/0.04, 0.5), distance=1000)


#Fit data. Write data and fit to a file.

fit_params, fit_error = fit(exponential, times[peaks], amplitudes[peaks], p0=(6.5, 20, 1))
errors = np.divide(np.sqrt(np.diag(fit_error))*100, fit_params)

print("Model: " + str(fit_params[0]) + '*E^(-x/' + str(1/fit_params[1]) + ") + " + str(fit_params[2]))

plt.title("MG spin-echo measurement for heavy mineral oil")
plt.xlabel("Time (s)")
plt.ylabel("Amplitude (V)")

plt.plot(times, amplitudes)
plt.scatter(times[peaks], amplitudes[peaks], s=20, marker="x", c="r")
plt.plot(np.arange(0, 0.2, 0.001), exponential(np.arange(0, 0.2, 0.001), *fit_params))
plt.legend(["Raw data", 
			"Fit: " + "y={0:.2f}".format(fit_params[0]) + '*E^(-x/' + "{0:.2f}".format(1/fit_params[1]) + ") + " + "{0:.2f}".format(fit_params[2]),  
			"Filtered peaks"])
Пример #19
0
def main():
    if len(sys.argv) != 2:
        print('.')
        print('.')
        print('.')
        print(
            'Number of parameters does not add up. Please enter command e.g. like this:'
        )
        print('python transform_h5_to_csv.py test')
        print(' ')
        print('Nothing was done')
        return -1

    filename = sys.argv[1]
    if filename[-3:] == '.h5':
        filename = filename[:-3]

    import os.path

    if not os.path.isfile(filename + '.h5'):
        print('.')
        print('.')
        print('.')
        print("The following file did not exist:")
        print(filename + '.h5')
        print(' ')
        print('Nothing was done')
        return -2

    f = h5py.File(filename + '.h5', 'r')

    t_data = np.array(f['t'])
    t_0 = np.array(f['t_0'])
    x_data = np.array(f['x_data'])
    x_data[0, :10]

    y_data = np.array(f['y_data'])

    samples = y_data.shape[1]
    datapoints = y_data.shape[0]

    assert np.max(np.std(x_data, 0)) < 1e-10
    # If this assertion catches, your x-axis changes during the experiment!

    # Gaussian blur in order to find potential approximate minima
    gauss_data = np.zeros_like(y_data)
    sigma = 10
    print("Standard deviation for gaussian bluring: " +
          str(np.round(sigma * (x_data[0, 1] - x_data[0, 0]), 3)) + " MHz")
    for i in range(y_data.shape[0]):
        gauss_data[i, :] = gauss(y_data[i, :], sigma)

    # Get all minima. Do so by looking at the change in sign of the derivative.
    # A minima needs to be below -0.2 to be relevant!
    diff_data = gauss_data[:, 1:] - gauss_data[:, :-1]
    minima = np.zeros_like(y_data)
    minima[:, 1:-1] = ((diff_data[:, :-1] < 0) * 1.) * (
        (diff_data[:, 1:] > 0) * 1.) * ((y_data[:, 1:-1] < -0.2) * 1.)

    # Calculate here the approximal values based on the minima approach
    approx_minima = np.ones_like(y_data[:, 0]) * -1.
    for i in range(0, y_data.shape[0], 1):
        # Get index of all the minima in ith trial
        temp_minima = np.argwhere(minima[i, :])
        temp_minima = np.array(
            [temp_minima[index][0] for index in range(temp_minima.shape[0])])

        if temp_minima.shape[0] > 0:
            # Get the blurred values of these minima
            values_minima = gauss_data[i, temp_minima]

            # Get the smallest minimum in case of multiple minima
            arg_smallest = np.argmin(values_minima)

            # Get the index of the smallest minimum
            smallest_min = temp_minima[arg_smallest]

            approx_minima[i] = smallest_min

    # Define the pdf of a Polynomial
    def poly_pdf(x, a, b, c, d, e, f):
        return a + b * x + c * (x**2) + d * (x**3) + e * (x**4) + f * (x**5)

    # Calculate now the minima based on fit around the data points from the approximal values
    slength = 10  # Defines the region where to search for lowest point first (2*slength+1)
    dlength = 6  # Defines how many data points to consider left and right to the minimum (2*dlength+1)

    fit_minima = np.copy(approx_minima)

    for i in range(fit_minima.shape[0]):
        approx_i = approx_minima[i]
        if approx_i >= 0:  # This means the minimum is relevant
            # Find first actual minima in data, since blurring shifts that peak
            lower_bound = max(approx_i - slength, 0)
            upper_bound = min(approx_i + slength + 1, x_data.shape[1])

            x_data_i = np.arange(int(lower_bound), int(upper_bound))
            y_data_i = y_data[i, int(lower_bound):int(upper_bound)]

            approx_i = np.argmin(y_data_i) + lower_bound
            approx_minima[i] = approx_i  # Update minimum to actual minimum

            lower_bound = max(approx_i - dlength, 0)
            upper_bound = min(approx_i + dlength + 1, x_data.shape[1])

            x_data_i = np.arange(int(lower_bound), int(upper_bound))
            y_data_i = y_data[i, int(lower_bound):int(upper_bound)]

            p, _ = fit(poly_pdf, x_data_i - approx_i,
                       y_data_i)  #,p0=[1,1,1,approx_i,1])

            def current_polynomial(x):
                return p[0] + p[1] * x + p[2] * (x**2) + p[3] * (
                    x**3) + p[4] * (x**4) + p[5] * (x**5)

            #assert i!=2260

            f = minimize(current_polynomial, x0=0)
            fit_minima[i] = f.x + approx_i

        if temp_minima.shape[0] > 0:
            # Get the blurred values of these minima
            values_minima = gauss_data[i, temp_minima]

            # Get the smallest minimum in case of multiple minima
            arg_smallest = np.argmin(values_minima)

            # Get the index of the smallest minimum
            smallest_min = temp_minima[arg_smallest]

            approx_minima[i] = smallest_min

    # Transform the fitted positions to actual frequencies
    resonant_freq = np.zeros_like(fit_minima)
    for i in range(resonant_freq.shape[0]):
        if fit_minima[i] > 0:
            min_full = int(fit_minima[i] // 1 + 0.5)
            min_diff = fit_minima[i] - min_full
            resonant_freq[i] = x_data[i, min_full] + min_diff * (
                x_data[i, min_full + 1] - x_data[i, min_full])

    # Write data into file
    with open(filename + '.csv', 'w') as f:
        # Write header
        s = str(t_0)
        for i in range(samples):
            s += ',' + str(x_data[0, i])
        s += ',f0'
        f.write(s)
        f.write('\n')

        for j in range(datapoints):
            s = str(t_data[j])
            for i in range(samples):
                s += ',' + str(y_data[j, i])
            s += ',' + str(resonant_freq[j])
            f.write(s)
            f.write('\n')
Пример #20
0
	4.27,
	3,
	1.8,
	1.48,
	1.23,
	1.03,
	0.867,
	0.746,
	0.63]
'''
#Distilled water data
x = [0.002, 0.006, 0.01, 0.02, 0.04, 0.06, 0.07, 0.1, 0.12, 0.14, 0.16]

y = [7.84, 7.73, 7.46, 7.27, 6.15, 4.71, 3.76, 1.66, 0.98, 0.56, 0.35]

fit_params, fit_error = fit(exponential, x, y, p0=(6.5, 20, 1))
errors = np.divide(np.sqrt(np.diag(fit_error)) * 100, fit_params)

plt.title("Spin-echo T2 measurement for distilled water")
plt.xlabel("$2 \\tau$ (s)")
plt.ylabel("Amplitude (V)")

plt.scatter(x, y, marker="x", c="r", s=20.)
plt.plot(np.arange(0, 0.16, 0.0001),
         exponential(np.arange(0, 0.16, 0.0001), *fit_params))
plt.legend([
    "Fit: " + "y={0:.2f}".format(fit_params[0]) + '*E^(-x/' +
    "{0:.2f}".format(1 / fit_params[1]) + ") + " +
    "{0:.2f}".format(fit_params[2]), "Raw data"
])
Пример #21
0
NN = np.array( [50,100,150,200,250] ) #Values of N to time
TT = np.zeros(len(NN))

for i in range(len(NN)):
#Redifine uvvis_cropped with the number of antennae desired for timing
#This change is then reflected in uvvis_cropped within part_two()
#This way, finding uvvis_cropped is not included in the timing of part_two()
    rows,antennae = get_selection(pos,vis,NN[i],order) 
    uvvis_cropped = np.zeros( (len(rows),vis.shape[1]) )
    for j in range(len(rows)): uvvis_cropped[j] = uvvis[rows[j]]
#Time the FFT routine
    TT[i]=timeit.timeit('part_two()',setup='from proj import part_two',number=1)
    print NN[i],TT[i]

#Fit an NlogN trend to the timings
a,c = fit( nlogn, NN, TT )[0]
#Plot the results 
NN_sm = np.linspace(0,300,100) 
mpl.figure()
mpl.plot(NN,TT,'ko')
mpl.plot(NN_sm,nlogn(NN_sm,a,c),'r-',label=r"$%.2en\log n + %.2f$" % (a,c))
mpl.ylabel("$t$",fontsize=20)
mpl.xlabel("$N$",fontsize=20)
mpl.xlim(0,300)
mpl.ylim(14.5,16)
mpl.legend()
mpl.savefig("FFT_image_timing.pdf")
mpl.show()


Пример #22
0
    3.43, 4.94, 6.45, 9.22, 6.32, 6.11, 4.63, 8.95, 7.8, 8.35, 11.45, 14.71,
    11.97, 12.46, 17.42, 17.0, 15.45, 19.15, 20.86
]
"""Linera regression"""
slope, intercept, r_value, p_value, std_err = lin(x, y)
"""apparently a float conversion is needed to avoid numpy errors"""
x = np.float64(x)
LinFit = x * slope + intercept
"""Cube fitting"""


def CubeFun(x, a, b, c, d):
    return a * (x**3) + b * (x**2) + c * x + d


params, params_covariance = fit(CubeFun, x, y)
CubeFit = CubeFun(x, *params)
"""integration"""
A = quad(lambda x: CubeFun(x, *params), min(x), max(x))
"""BIC calculation"""


def BIC(y, yhat, k, weight=1):
    err = y - yhat
    sigma = np.std(np.real(err))
    n = len(y)
    B = n * np.log(sigma**2) + weight * k * np.log(n)
    return B


LineError = BIC(y, LinFit, 2)
        starting_values1 = [420, 10, 30, -0.0005, 0.26]  #large Peak
        starting_values2 = [550, 10, 30, -0.0005, 0.26]  #medium peak
        starting_values3 = [585, 10, 30, -0.0005, 0.26]  #small peak
        x_fit2 = [x if x >= 490 and x <= 620 else 0
                  for x in dset['x']]  # Medium Peak
        x_fit1 = [x if x >= 350 and x <= 490 else 0
                  for x in dset['x']]  # Large Peak
        x_fit3 = [x if x >= 570 and x <= 650 else 0
                  for x in dset['x']]  # Small Peak
        y_fit1 = np.array(dset['y'])[np.nonzero(x_fit1)]
        y_fit2 = np.array(dset['y'])[np.nonzero(x_fit2)]
        y_fit3 = np.array(dset['y'])[np.nonzero(x_fit3)]
        x_fit1 = np.array(x_fit1)[np.nonzero(x_fit1)]
        x_fit2 = np.array(x_fit2)[np.nonzero(x_fit2)]
        x_fit3 = np.array(x_fit3)[np.nonzero(x_fit3)]
        fit_result1 = fit(fitfunc, x_fit1, y_fit1, starting_values1)
        fit_result2 = fit(fitfunc, x_fit2, y_fit2, starting_values2)
        fit_result3 = fit(fitfunc, x_fit3, y_fit3, starting_values3)
        outp.write('Fläche Gauss LPeak: {}\n'.format(fit_result1[0][2]))
        outp.write('Fläche Gauss MPeak: {}\n'.format(fit_result2[0][2]))
        outp.write('Fläche Gauss SPeak: {}\n'.format(fit_result3[0][2]))
        #print('Fläche Gauss: {}'.format(fit_result[0][2]))
        plt.plot(x_fit1, fitfunc(x_fit1, *fit_result1[0]))
        plt.plot(x_fit2, fitfunc(x_fit2, *fit_result2[0]))
        plt.plot(x_fit3, fitfunc(x_fit3, *fit_result3[0]))
        #plt.plot(x_fit, fitfunc(x_fit, *starting_values))
        if mode == 'v':
            #plt.savefig('outp.png')
            plt.show()

    outp.close()
Пример #24
0
pressure = []

counter = 0
for i in range(len(p_all)):
    pressure.append(
        Bin(p_all[i], weight=w_all[i], bins=pres_bin, bounds=pres_range))
    pdf = Density(p_all[i], weight=w_all[i], bounds=pres_range)
    guess = [
        max(pdf.get_norm_y()), pres_mid, (pres_range[1] - pres_range[0]) / 16
    ]
    popt, pcov = fit(
        model_func,
        pdf.get_x(),
        pdf.get_y(),
        p0=guess,
        bounds=[[.1 * max(pdf.get_norm_y()), .5 * pres_range[0], 0],
                [
                    1.2 * max(pdf.get_norm_y()), pres_range[1],
                    pres_range[1] / 4
                ]],
        method='trf')
    A_fit, B_fit, C_fit = popt
    param.append(popt)
    gaussian = []

    for i in pdf.get_x():
        gaussian.append(model_func(i, A_fit, B_fit, C_fit))

    NKDE_P.append([pdf.get_x(), pdf.get_norm_y(), gaussian, None])
    counter += 1
Пример #25
0
def __main__():
    # least squares algorithm
    N_ls = 100
    M_ls = sample_complexity(least_squares, N_ls, 0.1)

    # perceptron algorithm
    N_p = 100
    M_p = sample_complexity(perceptron, N_p, 0.1)

    # Winnow algorithm
    N_w = 150
    M_w = sample_complexity(winnow, N_w, 0.1)

    # 1-NN algorithm
    N_nn = 15
    M_nn = sample_complexity(one_nearest_neighbors, N_nn, 0.1)

    ########## plot all algorithms in 2,2 matrix plot #######
    M = [M_ls, M_p, M_w, M_nn]
    N = [N_ls, N_p, N_w, N_nn]
    name = ['Least squares', 'Perceptron', 'Winnow', '1-NN']

    fig, ax = plt.subplots(2, 2, figsize=(14, 14))

    i = 0
    for row in range(ax.shape[0]):
        for col in range(ax.shape[1]):
            ax[row, col] = plot_sample_complexity_ax(ax[row, col], N[i], M[i],
                                                     name[i])
            ax[1, col].set_xlabel('Dimension n', fontsize=18)
            i += 1

        ax[row, 0].set_ylabel('Sample complexity m', fontsize=18)

    ######### Fit linear, log and exp functions ##########
    M = [M_ls, M_p, M_w, M_nn]
    N = [N_ls, N_p, N_w, N_nn]

    lin_fits = []
    log_fits = []
    exp_fits = []

    lin_popts = []
    log_popts = []
    exp_popts = []

    log_start = 1

    for i, m in enumerate(M):
        n = np.arange(1, N[i] + 1)
        popt_lin, pcov_lin = fit(lin_func, n, m, bounds=([0, -5], [2, 5]))
        popt_log, pcov_log = fit(log_func,
                                 n,
                                 m,
                                 bounds=([-np.inf, 0,
                                          -np.inf], [np.inf, np.inf, np.inf]))
        popt_exp, pcov_exp = fit(exp_func, n, m)

        lin_popts.append(popt_lin)
        log_popts.append(popt_log)
        exp_popts.append(popt_exp)

        lin_fits.append(lin_func(n, *popt_lin))
        log_fits.append(log_func(n, *popt_log))
        exp_fits.append(exp_func(n, *popt_exp))

    ############# plot all fits in 2,2 matrix plot #########
    fig, ax = plt.subplots(2, 2, figsize=(14, 14))

    i = 0
    for row in range(ax.shape[0]):
        for col in range(ax.shape[1]):
            n = np.arange(1, N[i] + 1)
            ax[row, col] = plot_sample_complexity_ax(ax[row, col], N[i], M[i],
                                                     name[i])
            ax[row, col].plot(n,
                              lin_fits[i],
                              linestyle='--',
                              label=(r'$f(n) = %.1f n + %.1f$' %
                                     (lin_popts[i][0], lin_popts[i][1])))
            ax[row,
               col].plot(n,
                         log_fits[i],
                         linestyle='dotted',
                         label=r'$f(n) = %.1f\cdot log(%.1f n) + %.1f$' %
                         (log_popts[i][0], log_popts[i][1], log_popts[i][2]))
            ax[row, col].plot(n,
                              exp_fits[i],
                              linestyle='dashdot',
                              label=r'$f(n) = %.1f\cdot exp(%.1f n)$' %
                              (exp_popts[i][0], exp_popts[i][1]))
            ax[row, col].set_ylim([0, max(M[i]) + 3])
            ax[row, col].legend()
            ax[1, col].set_xlabel('Dimension n', fontsize=18)
            i += 1

        ax[row, 0].set_ylabel('Sample complexity m', fontsize=18)
Пример #26
0
def trace(line_data, center, check=False):

    xx = np.array([i / 100000 for i in range(len(line_data))])

    # def fun(x,a,b,c,d,e,f,g,h,i):
    #     return i*x**8+h*x**7+g*x**6+f*x**5+a*x**4+b*x**3+c*x**2+d*x**1+e

    def fun(x, c, d, e):
        return c * x**2 + d * x**1 + e

    #32 c r ти«

    base = 20
    d = 1

    #fitting right hand========================================
    end = center + base + d + 1
    aa = fit(fun, xx[center:end], np.array(line_data[center:end]))[0]

    while fun(xx[end - 1], aa[0], aa[1], aa[2]) > fun(xx[end - 2], aa[0],
                                                      aa[1], aa[2]):
        #while fun(xx[end-1],aa[0],aa[1],aa[2],aa[3],aa[4],aa[5],aa[6],aa[7],aa[8])>fun(xx[end-2],aa[0],aa[1],aa[2],aa[3],aa[4],aa[5],aa[6],aa[7],aa[8]):
        end += d
        aa = fit(fun, xx[center:end], np.array(line_data[center:end]))[0]
        #plt.plot(xx[center:center+int(len(line_data)*(base+n*rate))],fun(xx[center:center+int(len(line_data)*(base+n*rate))],aa[0],aa[1],aa[2],aa[3],aa[4],aa[5],aa[6],aa[7],aa[8]))

    r = end - 1
    tem = r
    big = line_data[r]
    for i in range(center, r):
        if line_data[i] > big:
            big = line_data[i]
            tem = i

    r = tem
    #fitting left hand===========================================
    start = center - (base + d)
    aa = fit(fun, xx[start:center + 1],
             np.array(line_data[start:center + 1]))[0]

    while fun(xx[start], aa[0], aa[1], aa[2]) > fun(xx[start + 1], aa[0],
                                                    aa[1], aa[2]):
        #while fun(xx[start],aa[0],aa[1],aa[2],aa[3],aa[4],aa[5],aa[6],aa[7],aa[8])>fun(xx[start+1],aa[0],aa[1],aa[2],aa[3],aa[4],aa[5],aa[6],aa[7],aa[8]):
        start -= d
        aa = fit(fun, xx[start:center + 1],
                 np.array(line_data[start:center + 1]))[0]
        #plt.plot(xx[center-int(len(line_data)*(base+n*rate)):center],fun(xx[center-int(len(line_data)*(base+n*rate)):center],aa[0],aa[1],aa[2],aa[3],aa[4],aa[5],aa[6],aa[7],aa[8]))
        #plt.show()

    l = start
    tem = l
    big = line_data[l]

    for i in range(l + 1, center + 1):
        if line_data[i] > big:
            big = line_data[i]
            tem = i
    l = tem

    if check:
        plt.plot(xx, line_data)
        plt.scatter(xx[center], line_data[center])
        plt.scatter(xx[l], line_data[l])
        plt.scatter(xx[r], line_data[r])
        plt.show()
    return l, center, r
Пример #27
0
def D(x):
    return (Dm - D0) * 10**3


def F(x):
    return (3 * L**2 * x - 4 * x**3)


# np.savetxt('test3.txt', np.column_stack([x, D0, Dm, D(x), F(x)]), fmt="%2.2f", header="x D0 Dm D F")


def g(a, m):
    return m * a


param, cov = fit(g, F(x), D(x))
x_plot = np.linspace(0, 165, 1000)
plt.plot(F(x), D(x), 'b.', label='Messwerte')

plt.plot(x_plot, g(x_plot, *param), 'r-', label='lineare Regression')

plt.xlabel(r'$\left(3 L^2 x - 4 x^3\right) \,/\, \mathrm{m^3}$')
plt.ylabel(r'$D(x) \,/\, 10^{-3} \, \mathrm{m}$')

plt.xlim(0, 0.175)
plt.ylim(0, 1.2)

plt.legend(loc='best')
plt.grid()
# plt.show()
# plt.savefig('rundbeid1.pdf')
Пример #28
0
def getupdown(*args, **kwargs):
    filename, title, Sd, Sm, Sy, sh, sm, fh, fm, p, t = args
    ss = kwargs.pop('ss', 0)
    fs = kwargs.pop('fs', 0)
    Fd = kwargs.pop('Fd', None)
    Fm = kwargs.pop('Fm', None)
    Fy = kwargs.pop('Fy', None)
    preview = kwargs.pop('preview', False)
    bounds = kwargs.pop('bounds', [1, 1, 1, 1])
    up = kwargs.pop('up', True)
    datetimeaxis = kwargs.pop('datetimeaxis', False)
    df = file_fetcher(filename, t)

    trimmed = df_trimmer(df,
                         Sd,
                         Sm,
                         Sy,
                         sh,
                         sm,
                         fh,
                         fm,
                         t,
                         ss=ss,
                         fs=fs,
                         Fd=Fd,
                         Fm=Fm,
                         Fy=Fy)

    xforfit = get_x_for_fit(trimmed, Sd, Sm, Sy, t)
    yforfit = trimmed[p].to_list()
    xforplot = trimmed[t]

    fig, ax = plt.subplots(nrows=2,
                           ncols=1,
                           figsize=(8.5, 11),
                           constrained_layout=True)

    ax[0].set_title(title)

    ax[0].set_xlabel("Datetime")
    ax[0].plot(df[t], df[p], c='b', label=title)
    ax[0].plot(trimmed[t], trimmed[p], c='red')
    ax[0].grid(True)

    if up:
        fitvars, _ = fit(
            spin_up, xforfit,
            yforfit)  #, bounds=[(0, 83500, 0),(numpy.inf, 100000, numpy.inf)])
        print("\n\nSpin up:", "pmax*(1-numpy.exp(-(t-t0)/tau))+shift\n")
        print(title)
        print("pmax", "t0", "tau", 'shift')
        for i, val in enumerate(["pmax:", "t0:", "tau:", "shift:"]):
            print(fitvars[i], end='\t')
        print('')
        fy = spin_up(xforfit, fitvars[0], fitvars[1], fitvars[2], fitvars[3])
        if datetimeaxis:
            ax[1].plot(xforplot, fy, c='green', label="Spin Up")
        else:
            ax[1].plot(xforfit, fy, c='green', label="Spin Up")

    else:
        fitvars, _ = fit(
            spin_down, xforfit,
            yforfit)  #, bounds=[(0, 83500, 0),(numpy.inf, 100000, numpy.inf)])
        print("\n\nSpin down:", "p0*numpy.exp(-(t-t0)/tau)+shift\n")
        print(title)
        print(["p0", "t0", "tau", "shift"])
        for i, val in enumerate(["p0:", "t0:", "tau:", "shift:"]):
            print(fitvars[i], end='\t')

        fy = spin_up(xforfit, fitvars[0], fitvars[1], fitvars[2], fitvars[3])

        if datetimeaxis:
            ax[1].plot(xforplot, fy, c='green', label="Spin Down")
        else:
            ax[1].plot(xforfit, fy, c='green', label="Spin Down")

    if datetimeaxis:
        ax[1].set_xlabel("Datetime")
        ax[1].scatter(trimmed[t], trimmed[p], c='red')

    else:
        ax[1].set_xlabel("Seconds since Midnight")
        ax[1].scatter(xforfit, trimmed[p], c='red')
        ax[1].plot(xforfit,
                   fy,
                   c='green',
                   label=("Spin " + ("Up" if up else "Down")))

    ax[1].grid(True)
    ax[1].legend(loc='best')
    ax[0].legend(loc='best')

    return fig
Пример #29
0
# data[1] is sigma



rtwolog = sqrt(2*log(2))

# Load in the datafile that has the angular error as a function of particle energy 
angdata = np.transpose(np.loadtxt(os.path.join(os.path.dirname(__file__),"angerror.txt"), delimiter=","))

# the fit is best when done in log-space of energy 
# so we do a little fitty-fit
logged = np.log10(angdata[0])
from scipy.optimize import curve_fit as fit
def func(x, c1,c2,c3):
    return( c1 + c2*x + c3*(x**2) )
popt, pcov = fit(func, logged, angdata[1])


def get_ang_error(energy):
    """
    Returns a best-guess for the angular error - the FIFTYth percentile

    Energy should be a float and in GeV
    """
    if not isinstance(energy, (int,float)):
        raise TypeError("Expected {}, got {}".format(float, type(energy)))
    
    try:
        # we really want to just use the data, so let's try interpolating first 
        error = get_closest( energy, angdata[0], angdata[1] )
    except ValueError: # failing that we use the fit (which isn't as good)
Пример #30
0
# define the model of post-burnout flight we'll use to fit the data and
# pull out the drag coefficient
def amodel(v, C_d):
    rho = 2.3 * 10**-3
    A = 4 * sp.pi / 144
    M = 7.75 / 32.2
    return (rho * v**2 * C_d * A) / (2 * M)

# apply a non-linear least squares fit to our post burnout, pre data-gap
# (possibly caused by brake deployment) a2x data using the velocities (found by
# integrating a2x) as the independent variable in the model defined above, then
# extract the drag coefficient
# JOHN: the (1.5 < data.time) business is to specify that the regression should
# apply only to our post-burn pre-gap data
nlregress = fit(amodel, # the model defined above
                data.v2x[(1.5 < data.time) & (data.time < 3)], # indep. data
                data.a2x[(1.5 < data.time) & (data.time < 3)]) # dep. data
# get value we want (C_d) from returned data structure and print it
dragcoeff = nlregress[0][0]
print dragcoeff # result is -0.244946411454

# plot a2x with integrated vel and accel along with model fit.
plt.plot(data.time, data.a2x, '.-',
         data.time, data.v2x, '.-',
         data.time, data.x2x, '.-',
         data.time, amodel(data.v2x, dragcoeff))
plt.show()
#plt.savefig('plots/test4ints.png', bbox_inches=None, dpi=160)

Пример #31
0
def fit_line(starting_values, xval, yval):
    fitfunc = lambda x, m: line(x, m, 0)
    fit_result = fit(fitfunc, xval, yval, starting_values)
    print(fit_result)
    return fit_result
Пример #32
0
R = 102.8e3
ws = 1 / (R * C)  # omega
Rd_arr, deltat_arr, Vpp_arr, dt_arr, dV_arr = readCSV('data1.csv', skiprows=1)
for i in range(4):
    filename = base_filename + str(i) + '.csv'
    t, V = readCSV(filename, skiprows=2)
    t -= t[0]
    N = len(V)  # number of points

    print("Measured frequency =", 1 / deltat_arr[i],
          "(expected %1f)" % (ws / (2 * np.pi)))

    # I use lambdas to change fit parameters (in this case I decided to set w and fit phi)
    params = fit(
        lambda t, A, phi1, B, phi2, C: func(t, ws, A, phi1, B, phi2, C),
        t,
        V,
        p0=[1, 3 * np.pi / 4, 1, 3 * np.pi / 4, 0])
    A, phi1, B, phi2, C = params[0]

    print("A = %.2f \t phi1 = %.2f \t B = %.2f \t phi2 = %.2f \t C = %.2f" %
          (A, phi1 % (2 * np.pi), B / ws, phi2 % (2 * np.pi), C))
    print("Coefficient ratio (x100) %.2f" % (100 * B / ws * A))

    plt.subplot(121)
    plt.plot(t * 1000,
             V,
             color='royalblue',
             linewidth=2.0,
             label='Experimental data')
    plt.plot(t * 1000,