Ejemplo n.º 1
0
def Rectangle(signal, guess):
    
    if guess == False:
        return [0, 0, 0]
    else:
        amp, centre, stdev, offset = guess
        
        data = np.array([range(len(signal)), signal]).T
        X = data[:,0]
        Y = data[:,1]

        step_mod = Rectangle()
        const_mod = ConstantModel()
        
        pars = step_mod.guess(Y, x=X, center=centre)
        pars += const_mod.guess(Y, x=X)

        mod = step_mod + const_mod
        result = mod.fit(Y, pars, x=X)
        # write error report
        #print result.fit_report()
        fwhm = result.best_values['sigma'] * 2.3548
        print fwhm
        
    return X, result.best_fit, result.redchi, 0
Ejemplo n.º 2
0
def GaussConst(signal, guess):
    
    if guess == False:
        return [0, 0, 0]
    else:
        amp, centre, stdev, offset = guess
        
        data = np.array([range(len(signal)), signal]).T
        X = data[:,0]
        Y = data[:,1]

        gauss_mod = GaussianModel(prefix='gauss_')
        const_mod = ConstantModel(prefix='const_')
        
        #pars = lorentz_mod.make_params(amplitude=amp, center=centre, sigma=stdev / 3.)
        #lorentz_mod.set_param_hint('sigma', value = stdev / 3., min=0., max=stdev)
        
        pars = gauss_mod.guess(Y, x=X, center=centre, sigma=stdev / 3., amplitude=amp)
        #pars += step_mod.guess(Y, x=X, center=centre)
        pars += const_mod.guess(Y, x=X)
        
        pars['gauss_sigma'].vary = False
        mod = gauss_mod + const_mod
        result = mod.fit(Y, pars, x=X)
        # write error report
        #print result.fit_report()
        fwhm = result.best_values['gauss_sigma'] * 2.3548

        
    return X, result.best_fit, result.redchi, fwhm
def GaussConst(signal, guess):
    
    amp, centre, stdev, offset = guess
    
    data = np.array([range(len(signal)), signal]).T
    X = data[:,0]
    Y = data[:,1]

    gauss_mod = GaussianModel(prefix='gauss_')
    const_mod = ConstantModel(prefix='const_')
    
    pars = gauss_mod.make_params(center=centre, sigma=stdev, amplitude=amp)
    pars += const_mod.guess(Y, x=X)
    pars['gauss_center'].min = centre - 5.
    pars['gauss_center'].max = centre + 5.
    pars['gauss_sigma'].max = stdev + 5.
    
    mod = gauss_mod + const_mod
    result = mod.fit(Y, pars, x=X)
    
    fwhm = result.best_values['gauss_sigma'] #* 2.3548
    centr = result.best_values['gauss_center']
    
    # Values within two stdevs i.e. 95%
    pl.plot(np.repeat(centr - fwhm * 2, len(Y)),
            np.arange(len(Y)), 'b-')
    pl.plot(np.repeat(centr + fwhm * 2, len(Y)),
            np.arange(len(Y)), 'b-')
    
    return X, result.best_fit, result.best_values['gauss_sigma'] * 4
def Box(signal, guess):
    
    amp, centre, stdev, offset = guess
    
    data = np.array([range(len(signal)), signal]).T
    X = data[:,0]
    Y = data[:,1]

    gauss_mod = RectangleModel(prefix='gauss_', mode='logistic')
    const_mod = ConstantModel(prefix='const_')
    
    pars = gauss_mod.make_params( center1=centre-stdev*3, center2=centre+stdev*3, sigma1=0, sigma2=0, amplitude=amp)
    pars += const_mod.guess(Y, x=X)
    pars['gauss_center1'].min = centre-stdev*3 - 3
    pars['gauss_center2'].max = centre-stdev*3 + 3
    pars['gauss_center2'].min = centre+stdev*3 - 3
    pars['gauss_center2'].max = centre+stdev*3 + 3
    
    mod = gauss_mod + const_mod
    result = mod.fit(Y, pars, x=X)
    
    c1 = result.best_values['gauss_center1']
    c2 = result.best_values['gauss_center2']
    
    pl.legend()
    
    return X, result.best_fit, c2-c1
def Box(signal, guess):

    amp, centre, stdev, offset = guess

    data = np.array([range(len(signal)), signal]).T
    X = data[:, 0]
    Y = data[:, 1]

    gauss_mod = RectangleModel(prefix='gauss_', mode='logistic')
    const_mod = ConstantModel(prefix='const_')

    pars = gauss_mod.make_params(center1=centre - stdev * 3,
                                 center2=centre + stdev * 3,
                                 sigma1=0,
                                 sigma2=0,
                                 amplitude=amp)
    pars += const_mod.guess(Y, x=X)
    pars['gauss_center1'].min = centre - stdev * 3 - 3
    pars['gauss_center2'].max = centre - stdev * 3 + 3
    pars['gauss_center2'].min = centre + stdev * 3 - 3
    pars['gauss_center2'].max = centre + stdev * 3 + 3

    mod = gauss_mod + const_mod
    result = mod.fit(Y, pars, x=X)

    c1 = result.best_values['gauss_center1']
    c2 = result.best_values['gauss_center2']

    pl.legend()

    return X, result.best_fit, c2 - c1
Ejemplo n.º 6
0
def gauss_step_const(signal, guess):
    """
    Fits high contrast data very well
    """
    if guess == False:
        return [0, 0]
    else:
        amp, centre, stdev, offset = guess
        
        data = np.array([range(len(signal)), signal]).T
        X = data[:,0]
        Y = data[:,1]

#         gauss_mod = Model(gaussian)
        gauss_mod = Model(gaussian)
        const_mod = ConstantModel()
        step_mod = StepModel(prefix='step')
        
        pars = gauss_mod.make_params(height=amp, center=centre, width=stdev / 3., offset=offset)
#         pars = gauss_mod.make_params(amplitude=amp, center=centre, sigma=stdev / 3.)
        gauss_mod.set_param_hint('sigma', value = stdev / 3., min=stdev / 2., max=stdev)
        pars += step_mod.guess(Y, x=X, center=centre)

        pars += const_mod.guess(Y, x=X)
    
        
        mod = const_mod + gauss_mod + step_mod
        result = mod.fit(Y, pars, x=X)
        # write error report
        #print result.fit_report()
        print "contrast fit", result.redchi
    
    return X, result.best_fit, result.redchi
def GaussConst(signal, guess):

    amp, centre, stdev, offset = guess

    data = np.array([range(len(signal)), signal]).T
    X = data[:, 0]
    Y = data[:, 1]

    gauss_mod = GaussianModel(prefix='gauss_')
    const_mod = ConstantModel(prefix='const_')

    pars = gauss_mod.make_params(center=centre, sigma=stdev, amplitude=amp)
    pars += const_mod.guess(Y, x=X)
    pars['gauss_center'].min = centre - 5.
    pars['gauss_center'].max = centre + 5.
    pars['gauss_sigma'].max = stdev + 5.

    mod = gauss_mod + const_mod
    result = mod.fit(Y, pars, x=X)

    fwhm = result.best_values['gauss_sigma']  #* 2.3548
    centr = result.best_values['gauss_center']

    # Values within two stdevs i.e. 95%
    pl.plot(np.repeat(centr - fwhm * 2, len(Y)), np.arange(len(Y)), 'b-')
    pl.plot(np.repeat(centr + fwhm * 2, len(Y)), np.arange(len(Y)), 'b-')

    return X, result.best_fit, result.best_values['gauss_sigma'] * 4
def GaussConst(signal, guess):
    """
    Fits a Gaussian function
    Plots fwhm and 2*sigma gap widths for comparison
    with the analytically calculated one
    """
    amp, centre, stdev, offset = guess
    
    data = np.array([range(len(signal)), signal]).T
    X = data[:,0]
    Y = data[:,1]

    gauss_mod = GaussianModel(prefix='gauss_')
    const_mod = ConstantModel(prefix='const_')
    
    pars = gauss_mod.make_params(center=centre, sigma=stdev, amplitude=amp)
    pars += const_mod.guess(Y, x=X)
    pars['gauss_center'].min = centre - 5.
    pars['gauss_center'].max = centre + 5.
    pars['gauss_sigma'].max = stdev + 5.
    
    mod = gauss_mod + const_mod
    result = mod.fit(Y, pars, x=X)
    
    fwhm = result.best_values['gauss_sigma'] #* 2.3548
    centr = result.best_values['gauss_center']
    
    # Values within two stdevs i.e. 95%
    pl.plot(np.repeat(centr - fwhm * 2, len(Y)),
            np.arange(len(Y)), 'b-')
    pl.plot(np.repeat(centr + fwhm * 2, len(Y)),
            np.arange(len(Y)), 'b-', label="Sigma * 2")
    
    pl.plot(np.repeat(centr - fwhm * 2.3548 / 2., len(Y)),
            np.arange(len(Y)), 'y--')
    pl.plot(np.repeat(centr + fwhm * 2.3548 / 2., len(Y)),
            np.arange(len(Y)), 'y--', label="FWHM")
    
    return X, result.best_fit, result.best_values['gauss_sigma'] * 4, centr
Ejemplo n.º 9
0
def Step(signal, guess):
    
    if guess == False:
        return [0, 0, 0]
    else:
        amp, centre, stdev, offset = guess
        
        data = np.array([range(len(signal)), signal]).T
        X = data[:,0]
        Y = data[:,1]

        step_mod = StepModel(prefix='step')
        const_mod = ConstantModel(prefix='const_')
        
        pars = step_mod.guess(Y, x=X, center=centre)
        pars += const_mod.guess(Y, x=X)

        mod = step_mod + const_mod
        result = mod.fit(Y, pars, x=X)
        # write error report
        #print result.fit_report()
        
    return X, result.best_fit, result.redchi, 0
Ejemplo n.º 10
0
def GaussStepConst(signal, guess):
    """
    Fits high contrast data very well
    """
    if guess == False:
        return [0, 0, 0]
    else:
        amp, centre, stdev, offset = guess
        
        data = np.array([range(len(signal)), signal]).T
        X = data[:,0]
        Y = data[:,1]

#         gauss_mod = Model(gaussian)
        gauss_mod = Model(gaussian)
        const_mod = ConstantModel()
        step_mod = StepModel(prefix='step')
        
        gauss_mod.set_param_hint('width', value = stdev / 2., min=stdev / 3., max=stdev)
        gauss_mod.set_param_hint('fwhm', expr='2.3548*width')
        pars = gauss_mod.make_params(height=amp, center=centre, width=stdev / 2., offset=offset)
        
        pars += step_mod.guess(Y, x=X, center=centre)

        pars += const_mod.guess(Y, x=X)
        
        pars['width'].vary = False
        
        mod = const_mod + gauss_mod + step_mod
        result = mod.fit(Y, pars, x=X)
        # write error report
        #print result.fit_report()
        
        fwhm = result.best_values['width'] * 2.3548
        
    return X, result.best_fit, result.redchi, fwhm
 def CurveFitting(self, frec, Pxx, iaf, ax):
     'Non-Linear Least-Squares Minimization and Curve-Fitting for Python'
     
     # ----- adjusting a model to the obtained PSD -----               
     # model 1: constante
     g1 = ConstantModel(prefix = 'g1_')
     pars = g1.guess(Pxx, x = frec)    
     pars['g1_c'].set(0)
     # model 2: k2/f^-1
     g2 = PowerLawModel(prefix = 'g2_')
     pars += g2.guess(Pxx, x = frec)
     pars['g2_exponent'].set(-1)
     #model 3: probability density function
     g3 = GaussianModel(prefix = 'g3_')
     pars += g3.guess(Pxx, x = frec)
     pars['g3_center'].set(iaf, min = iaf-2, max = iaf+2)
     # model 4: probability density function
     g4 = GaussianModel(prefix = 'g4_')
     pars += g4.guess(Pxx, x = frec)
     pars['g4_center'].set(20, min = 16, max = 25)
     # final model
     gA = g1 + g2 + g3 + g4
     outA = gA.fit(Pxx, pars, x = frec) 
     diffA= np.sum(Pxx - outA.best_fit)        
     gB = g1 + g2 + g3 
     outB = gB.fit(Pxx, pars, x = frec) 
     diffB= np.sum(Pxx - outB.best_fit)
     gC = g1 + g2 
     outC = gC.fit(Pxx, pars, x = frec) 
     diffC= np.sum(Pxx - outC.best_fit)
     diffs= np.abs([diffA, diffB, diffC])
     idx  = np.where(diffs == np.min(diffs))[0][0]
     out  = [outA, outB, outC][idx]
     # ----- plotting the desire PSD -----   
     # original and fitted curves
     ax.plot(frec, Pxx, 'k', linewidth = 2, label = 'PSD')
     ax.plot(frec, out.best_fit, 'b.-', linewidth = 2, markersize = 9, label ='BestModel')
     ax.set_xlim(frec[0], 32)
     ax.set_ylim(ymin = 0)
     ax.tick_params(axis = 'both', labelsize = 16)
     ax.set_xlabel('Frequency [Hz]', fontsize = 'x-large')
     ax.grid()
     # components of the fitted curved
     comps = out.eval_components(x = frec)
     g12 = comps['g1_'] + comps['g2_']
     ax.plot(frec, g12, 'g--', linewidth = 2, label = 'PowerLawModel')      
     idx1, idx2 = np.where(frec >= 5)[0][0], np.where(frec <= 15)[0][-1]
     # final value on the subplot
     if out != outC:
         diffs = out.best_fit[idx1:idx2] - g12[idx1:idx2]
         peak1 = np.amax(diffs)
         idx = np.where(diffs == peak1)[0]
         idx+= len(out.best_fit[:idx1])
         ax.plot((frec[idx],frec[idx]), (g12[idx],out.best_fit[idx]), 'r-o', linewidth = 3, markersize = 9) 
         ax.text(frec[idx], g12[idx], str(np.around(peak1, decimals=2)), horizontalalignment='right', verticalalignment='top', color='r', fontsize='xx-large')
     else:
         peak1 = 0
     # optional valued on the subplot        
     diffs = Pxx[idx1:idx2] - g12[idx1:idx2]
     peak2 = np.amax(diffs)        
     idx = np.where(peak2 == diffs)[0]
     idx+= len(Pxx[:idx1])
     ax.plot((frec[idx],frec[idx]), (g12[idx], Pxx[idx]), 'r-*', linewidth = 3, markersize = 11) 
     ax.text(frec[idx], Pxx[idx], str(np.around(peak2, decimals=2)), horizontalalignment='left', verticalalignment='top', color='r', fontsize='xx-large')
     ax.legend(loc='upper right', shadow=True)
     
     return peak1, peak2
Ejemplo n.º 12
0
def call_constant(x, y, ylock):
	const = ConstantModel(prefix='constant_')
	pars = const.guess(np.array(y), x=np.array(x))
	pars['constant_c'].set(ylock, min=ylock-ylock*0.001, max=ylock+ylock*0.001)
	return const, pars
Ejemplo n.º 13
0
def call_constant(x, y, ylock):
	const = ConstantModel(prefix='constant_')
	pars = const.guess(y, x=x)
	pars['constant_c'].set(ylock, min=ylock-0.01, max=ylock+0.0001)
	return const, pars
Ejemplo n.º 14
0
now = datetime.datetime.now()
data_energy.write(
    "\n\nAt: %i/%i/%i, %i:%i:%i \n" %
    (now.day, now.month, now.year, now.hour, now.minute, now.second))
data_energy.write(
    "Archivo \t  Curva \t \t  Centro \t err \t \t \t\t  Fwhm \t err \t\t\t\t Area \t Err\n"
)

L_mod = LorentzianModel(prefix='L0')
c_mod = ConstantModel()

for filename in files:
    x, y = np.loadtxt(direction + filename, unpack=True)

    pars = L_mod.guess(y, x=x)
    pars += c_mod.guess(y, x=x)

    mod = L_mod + c_mod
    out = mod.fit(y, pars, x=x)

    #	fit_log.write("\n\n\n\n\n\n Fitted from: %s%s \n" %(direction, filename))
    #	now= datetime.datetime.now()
    #	fit_log.write("At: %i/%i/%i, %i:%i:%i \n" %(now.day,now.month,now.year,now.hour,now.minute,now.second))
    #	fit_log.write(out.fit_report(min_correl=0.2))

    print_to_fit_log(filename, data_energy, out, 0)

    plt.plot(x, y, 'b')
    plt.plot(x, out.init_fit, 'g--')
    plt.plot(x, out.best_fit, 'r')
    plt.show()
    def CurveFitting(self, frec, Pxx, iaf, ax):
        'Non-Linear Least-Squares Minimization and Curve-Fitting for Python'

        # ----- adjusting a model to the obtained PSD -----
        # model 1: constante
        g1 = ConstantModel(prefix='g1_')
        pars = g1.guess(Pxx, x=frec)
        pars['g1_c'].set(0)
        # model 2: k2/f^-1
        g2 = PowerLawModel(prefix='g2_')
        pars += g2.guess(Pxx, x=frec)
        pars['g2_exponent'].set(-1)
        #model 3: probability density function
        g3 = GaussianModel(prefix='g3_')
        pars += g3.guess(Pxx, x=frec)
        pars['g3_center'].set(iaf, min=iaf - 2, max=iaf + 2)
        # model 4: probability density function
        g4 = GaussianModel(prefix='g4_')
        pars += g4.guess(Pxx, x=frec)
        pars['g4_center'].set(20, min=16, max=25)
        # final model
        gA = g1 + g2 + g3 + g4
        outA = gA.fit(Pxx, pars, x=frec)
        diffA = np.sum(Pxx - outA.best_fit)
        gB = g1 + g2 + g3
        outB = gB.fit(Pxx, pars, x=frec)
        diffB = np.sum(Pxx - outB.best_fit)
        gC = g1 + g2
        outC = gC.fit(Pxx, pars, x=frec)
        diffC = np.sum(Pxx - outC.best_fit)
        diffs = np.abs([diffA, diffB, diffC])
        idx = np.where(diffs == np.min(diffs))[0][0]
        out = [outA, outB, outC][idx]
        # ----- plotting the desire PSD -----
        # original and fitted curves
        ax.plot(frec, Pxx, 'k', linewidth=2, label='PSD')
        ax.plot(frec,
                out.best_fit,
                'b.-',
                linewidth=2,
                markersize=9,
                label='BestModel')
        ax.set_xlim(frec[0], 32)
        ax.set_ylim(ymin=0)
        ax.tick_params(axis='both', labelsize=16)
        ax.set_xlabel('Frequency [Hz]', fontsize='x-large')
        ax.grid()
        # components of the fitted curved
        comps = out.eval_components(x=frec)
        g12 = comps['g1_'] + comps['g2_']
        ax.plot(frec, g12, 'g--', linewidth=2, label='PowerLawModel')
        idx1, idx2 = np.where(frec >= 5)[0][0], np.where(frec <= 15)[0][-1]
        # final value on the subplot
        if out != outC:
            diffs = out.best_fit[idx1:idx2] - g12[idx1:idx2]
            peak1 = np.amax(diffs)
            idx = np.where(diffs == peak1)[0]
            idx += len(out.best_fit[:idx1])
            ax.plot((frec[idx], frec[idx]), (g12[idx], out.best_fit[idx]),
                    'r-o',
                    linewidth=3,
                    markersize=9)
            ax.text(frec[idx],
                    g12[idx],
                    str(np.around(peak1, decimals=2)),
                    horizontalalignment='right',
                    verticalalignment='top',
                    color='r',
                    fontsize='xx-large')
        else:
            peak1 = 0
        # optional valued on the subplot
        diffs = Pxx[idx1:idx2] - g12[idx1:idx2]
        peak2 = np.amax(diffs)
        idx = np.where(peak2 == diffs)[0]
        idx += len(Pxx[:idx1])
        ax.plot((frec[idx], frec[idx]), (g12[idx], Pxx[idx]),
                'r-*',
                linewidth=3,
                markersize=11)
        ax.text(frec[idx],
                Pxx[idx],
                str(np.around(peak2, decimals=2)),
                horizontalalignment='left',
                verticalalignment='top',
                color='r',
                fontsize='xx-large')
        ax.legend(loc='upper right', shadow=True)

        return peak1, peak2
Ejemplo n.º 16
0
cont = 3.0   # continuum level
randamp = 3. # amplitude of gaussian noise

x   = np.arange(0,xmax)
y   = randamp * np.random.randn(xmax) + jrr.spec.onegaus(x, aa, bb, cc, cont)
err = randamp * np.random.randn(xmax)
plt.plot(x, y, color='black')

# Let's try fitting that gaussian w the python version of MPFIT
p0 = (50., xmax/2, 5, 2)
fa = {'x':x, 'y':y, 'err':err}
m = mpfit.mpfit(myfunct, p0, functkw=fa)
# There has got to be a less kludgy way to do line below
bestfit = jrr.spec.onegaus(x, m.params[0], m.params[1], m.params[2], m.params[3])
plt.plot(x, bestfit, color='blue')


# The same, but with LMFIT
mod1 = GaussianModel()
mod2 = ConstantModel()  # The continuum level
mod = mod1 + mod2
pars = mod1.guess(y, x=x) + mod2.guess(y, x=x)  # This is cool.  It made rough guesses for us.
pars['c'].min = 0  # Set bounds on continuum
pars['c'].max = 10 # Set bounds on continuum
#pars['amplitude'].vary = False  # Fix a parameter
out = mod.fit(y, pars, x=x, weights=1/err**2)  # Fitting is done here.
plt.plot(x, out.best_fit, color='orange')
print(out.fit_report(min_correl=0.25))
plt.show()
# This is actually more elegant.  I think I should learn LMFIT and use it...
Ejemplo n.º 17
0
matrices = np.zeros((1024, 256))

index = 0

L_mod = GaussianModel()
c_mod = ConstantModel()

pixel_x = np.arange(1024)

for filename in files:
    data = np.loadtxt("./matrices/" + filename)
    pixel_y = data[:, 0]
    data = np.delete(data, 0, 1)
    maxima = []
    data = np.log(data)

    for linea in range(len(data)):
        #print(data)
        #print(pixel_x)
        pars = L_mod.guess(data[linea], x=pixel_x)
        pars += c_mod.guess(data[linea], x=pixel_x)

        mod = L_mod + c_mod
        out = mod.fit(data[linea], pars, x=pixel_x)

        print(out.fit_report(min_correl=0.2))

#plt.imshow(np.log(matrices), cmap=cmap)

plt.show()