def test_line_defaults(self):
        # Perform the fit of a straight line with fit_linear and with
        # all the methods of fit_curve, with default options. Check
        # that results are identical.

        # Config parameters
        x = np.linspace(0, 1, 10)
        m = 2
        q = 3
        dy = 0.1 * np.ones(x.shape)  # uniform errors because of leastsq
        methods = [
            'wleastsq', 'leastsq', 'odrpack', 'linodr', 'ev'
            # omit pymc3 because result is different
            # omit ml because it requires errors on x
        ]

        # Reference fit
        y = m * x + q + dy * np.random.randn(*x.shape)
        par, cov = lab.fit_linear(x, y, dy=dy)
        chisq = np.sum((y - (par[0] * x + par[1]))**2 / dy**2)

        # fits
        for method in methods:
            out = lab.fit_curve(lambda x, m, q: m * x + q,
                                x,
                                y,
                                dy=dy,
                                p0=[1, 1],
                                method=method)
            assertions = []
            assertions.append(np.allclose(par, out.par))
            if method == 'leastsq':
                ratio = out.cov / cov
                assertions.append(np.allclose(0, ratio - np.mean(ratio)))
            else:
                assertions.append(np.allclose(cov, out.cov))
            assertions.append(np.allclose(chisq, out.chisq, atol=0.1))
            assertion = all(assertions)
            if not assertion:
                print('Fit different from reference fit.')
                print('Reference result:')
                print('chisq = {:.2f}'.format(chisq))
                print(lab.format_par_cov(par, cov))
                print('Method `{}` result:'.format(method))
                print('chisq = {:.2f}'.format(out.chisq))
                print(lab.format_par_cov(out.par, out.cov))
            self.assertTrue(assertion)
Beispiel #2
0
##faccio il grafico
py.figure(1)
py.errorbar(T, L, dL, dT, '.', markersize='3')


##funzione di fit
def retta(x, a, b):
    return a * x + b


##trovo I_th con un fit
m = []
dm = []
q = []
dq = []
out = fit_curve(retta, T, L, dy=1, p0=[1, 1], absolute_sigma=True)
par = out.par
cov = out.cov
err = py.sqrt(py.diag(cov))
m_fit = par[0]
q_fit = par[1]
dm_fit = err[0]
dq_fit = err[1]
print('m = %s  q = %s' % (xe(m_fit, dm_fit), xe(q_fit, dq_fit)))
x = py.linspace(T[0] - 1, T[len(T) - 1] + 1, 100)
py.plot(x,
        retta(x, *par),
        linewidth=1,
        label='m = 0.22(2) nm/°C \n q = 775.4(5) nm')
py.legend(fontsize='large')
py.ylabel('$\lambda$ [nm]')
dV = dVpp / ((cos((angolo + angolo0)*pi/180)**2 + ratio*sin((angolo + angolo0)*pi/180)**2)**2)
dy = 1.5*ones(len(angolo)) / ((cos((angolo + angolo0)*pi/180)**2 + ratio*sin((angolo + angolo0)*pi/180)**2)**2)
dx = ones(len(angolo))

errorbar(angolo, V, yerr=dy, xerr=dx, fmt='.k')

V2 = Vpp*(cos((angolo + angolo0)*pi/180)**2 + b2sua2*sin((angolo + angolo0)*pi/180)**2)
dV2 = dVpp*(cos((angolo + angolo0)*pi/180)**2 + b2sua2*sin((angolo + angolo0)*pi/180)**2)
dy2 = 1.5*ones(len(angolo))*(cos((angolo + angolo0)*pi/180)**2 + b2sua2*sin((angolo + angolo0)*pi/180)**2)

#errorbar(angolo, V2, yerr=dV2, xerr=dx, fmt='.k')

def cos4(x, a, b):
    return a*(cos((x-b)*pi/180))**4

out = fit_curve(cos4, angolo, Vpp, dy=dVpp, dx=dx, p0=[60, -10])
par0 = out.par
cov0 = out.cov

out = fit_curve(cos4, angolo, V, dy=dy, dx=dx, p0=[120, -10])
par1 = out.par
cov1 = out.cov
err1 = sqrt(diag(cov1))
chi2norm1 = out.chisq / out.chisq_dof
print('chi2norm = ', chi2norm1)
print('p-value = ', out.chisq_pvalue)
print('parameters = ', par1)
print('errors     = ', err1)


out = fit_curve(cos4, angolo, V2, dy=dy2, dx=dx, p0=[80, -10])
def gaussiana(theta, a, b, theta_m):
    return a * exp(-1 / 2 * ((theta - theta_m) / b)**2)


primi, Vpp, dVpp = loadtxt('borcapDVTvsPM01.txt', unpack=True)  #primi, mV, mV

minerr = 0.8
dV = dVpp
for i in range(len(dVpp)):
    dV[i] = max(dVpp[i], minerr)

#fit onesto
dy = 0.68 * 0.5 * dVpp
dx = 0.68 * 0.5 * ones(len(primi))
out = fit_curve(PM, primi, Vpp, dy=dy, dx=dx, p0=[500, 0.02, 150])
par = out.par
cov = out.cov

#fit senza code
cutlevel = 100  #mV
cutindex1 = 0
cutindex2 = len(Vpp)
for i in range(len(Vpp) - 1):
    if (cutlevel < Vpp[i + 1]) & (cutlevel >= Vpp[i]):
        cutindex1 = i
    if (cutlevel < Vpp[i]) & (cutlevel >= Vpp[i + 1]):
        cutindex2 = i + 1
out = fit_curve(PM,
                primi[cutindex1:cutindex2],
                Vpp[cutindex1:cutindex2],
     else:
         zona = 'dopo'
     if (zona == 'prima') & (I[k] > HM - level) & (I[k] < HM + level):
         indici_prima.append(k)
     if (zona == 'dopo') & (I[k] > HM - level) & (I[k] < HM + level):
         indici_dopo.append(k)
         
 if min(len(indici_prima), len(indici_dopo)) < 10:
     print('ATTENZIONE: pochi punti per interpolare')
 
 
 
 def parabola(y, a, b, c):
     return a*(y**2) + b*y + c
 #uso una parabola per interpolare (attenzione uso x = ay^2 + by + c)
 out = fit_curve(parabola, I[indici_prima], ang[indici_prima], p0=[1,1,1], absolute_sigma=False)
 par1 = out.par
 ang_prima = parabola(HM, *par1)
 out = fit_curve(parabola, I[indici_dopo], ang[indici_dopo], p0=[1,1,1], absolute_sigma=False)
 par2 = out.par
 ang_dopo = parabola(HM, *par2)
 FWHM[i] = ang_dopo - ang_prima
 
 py.ylabel('segnale [$\mu$A]', fontsize='large')
 py.xlabel('θ [deg]', fontsize='large')
 py.plot(parabola(py.sort(I[indici_prima]), *par1), py.sort(I[indici_prima]), '-c', linewidth=2)
 py.plot(parabola(py.sort(I[indici_dopo]), *par2), py.sort(I[indici_dopo]), '-c', linewidth=2)
 
 py.plot([ang_prima, ang_dopo], [HM, HM], '-', linewidth=2, color='tab:red', label='{} = {}°$\pm$0.5°'.format(ang_p[i], round(FWHM[i],1)))
 py.legend(fontsize='large')
 
Beispiel #6
0
        dpower[i] = 0.1

dpower = 0.01 * power

dy = 0.68 * 0.5 * dV
dx = dpower


def parabola(x, a):
    return a * x**2


out = fit_curve(parabola,
                power,
                Vpp,
                dy=dy,
                dx=dx,
                p0=[1],
                absolute_sigma=True)
par = out.par
cov = out.cov
err = sqrt(diag(cov))
print('a = %s' % xe(par, err))
print('chisq/dof = %d/%d = %.2f' % tuple(
    (out.chisq, out.chisq_dof, out.chisq / out.chisq_dof)))
print('p_value = %.3f\n' % out.chisq_pvalue)

figure('potenza_alla2').set_tight_layout(True)
clf()
#griglia = GridSpec(2, 1, height_ratios=[2,1])
#subplot(griglia[0])
Beispiel #7
0
        dm = []
        q = []
        dq = []
        nomipicchi = ['sinistra', 'centro  ', 'destra  ']
        for k in range(3):
            piccoinquestione = picchi[k::3]
            plot(ordini,
                 t[piccoinquestione],
                 'o',
                 color='tab:red',
                 markersize='4')
            """come errore metto (1/2)*sensibilità*0.68,
            scelta discutibile ma giustificata a spanne dal confidence level"""
            out = fit_curve(retta,
                            ordini_fit,
                            t[piccoinquestione],
                            dy=0.5 * 0.68 * (t[1] - t[0]),
                            p0=[1, 1],
                            absolute_sigma=True)
            par = out.par
            cov = out.cov
            m_fit = par[0]
            q_fit = par[1]
            dm_fit, dq_fit = sqrt(diag(cov))
            print('picco %s: m = %s  q = %s' %
                  (nomipicchi[k], xe(m_fit, dm_fit), xe(q_fit, dq_fit)))
            m.append(m_fit)
            q.append(q_fit)
            dm.append(dm_fit)
            dq.append(dq_fit)
            plot(ordini, retta(ordini_fit, *par), linewidth=1)
    figure('isteresi_30-70')
    errorbar(V, d, yerr=dd, xerr=dV, fmt='.')

    cut1 = 0
    j = 0
    while abs(V[0] - V[j]) < 20:
        cut2 = j
        j += 1

    m = []
    for k in range(2):
        out = fit_curve(retta,
                        V[cut1:cut2],
                        d[cut1:cut2],
                        dy=dd[cut1:cut2],
                        dx=dV[cut1:cut2],
                        p0=[1, 1],
                        absolute_sigma=True)
        par = out.par
        cov = out.cov
        dpar = sqrt(diag(cov))
        plot(V[cut1:cut2],
             retta(V[cut1:cut2], *par),
             label='coeff. angolare = {} $\mu$m/V'.format(xe(par[0], dpar[0])))
        m.append(par[0])
        cut1 = cut2
        cut2 = len(V)
    print('differenza relativa = ', abs(m[0] - m[1]) / ((m[0] + m[1]) / 2))

legend(fontsize='large')
Beispiel #9
0
for pmax in range(p_i, p_f, step):
    indici_bassi = []
    for i in range(len(power)):
        if power[i] < pmax:
            indici_bassi.append(i)
    indici_bassi = array(indici_bassi)
    p_max.append(max(power[indici_bassi]))

    ##fit bassa potenza
    def parabola(x, a):
        return a * x**2

    out = fit_curve(parabola,
                    power[indici_bassi],
                    Vpp[indici_bassi],
                    dy=dy[indici_bassi],
                    dx=dx[indici_bassi],
                    p0=[1],
                    absolute_sigma=True)
    par = out.par
    cov = out.cov
    err = sqrt(diag(cov))
    a1_fit.append(par[0])
    da1_fit.append(err[0])
    chisq = out.chisq
    chisq1 = '{0:.2f}'.format(out.chisq)
    p_value = '{0:.1f}'.format(out.chisq_pvalue * 100)
    dof = out.chisq_dof
    chidof = '{0:.2f}'.format(chisq / dof)
    print('a = %s' % xe(par, err))
    print('chisq/dof = %d/%d = %.3f' % tuple(
mieiatten = array(list(atten_1) + list(atten_2))
mieiatten = unumpy.nominal_values(mieiatten)
dy = [0.93, 0.45, 0.93, 0.45]


def xalla4(x, a):
    return a * x**(-4)


def xallab(x, a, b):
    return a * x**b


out = fit_curve(xalla4,
                mieilamb.astype(float),
                mieiatten,
                dy=dy,
                p0=[2e13],
                absolute_sigma=True)
par4 = out.par
cov4 = out.cov
chi2norm = out.chisq / out.chisq_dof
print('punti misurati: chi2/dof = %.2f/%d = %.2f' %
      (out.chisq, out.chisq_dof, chi2norm))
std4 = sqrt(diag(cov4))
out = fit_curve(xallab,
                mieilamb.astype(float),
                mieiatten,
                dy=dy,
                p0=[2e12, -4],
                absolute_sigma=True)
parb = out.par
    j = len(P) - 1
    while P[j] < P5:
        j = j - 1

    k = j + level
    while k > j - level:
        indici_dopo.append(k)
        k = k - 1

    #uso una parabola per interpolare (attenzione uso x = ay^2 + by + c)
    def parabola(y, a, b, c):
        return a * (y**2) + b * y + c

    out = fit_curve(parabola,
                    P[indici_prima],
                    ang[indici_prima],
                    p0=[1, 3.6, 0],
                    method='odrpack')
    par1 = out.par
    ang_prima = parabola(P5, *par1)
    out = fit_curve(parabola,
                    P[indici_dopo],
                    ang[indici_dopo],
                    p0=[-1, 1, 0],
                    method='odrpack')
    par2 = out.par
    print(par1)
    print(par2)
    ang_dopo = parabola(P5, *par2)
    ang_m = (ang_dopo - ang_prima) / 2
    ang_prima = ang_prima * py.pi / 180
Beispiel #12
0
    j = 0
    while P[j] > 300:
        j = j + 1

    ##funzione di fit
    def retta(x, a, b):
        return a * x + b

    ##trovo I_th con un fit
    m = []
    dm = []
    q = []
    dq = []
    out = fit_curve(retta,
                    I[0:j - 1],
                    P[0:j - 1],
                    dy=dP[0:j - 1],
                    p0=[1, 1],
                    absolute_sigma=True)
    par = out.par
    cov = out.cov
    m_fit = par[0]
    q_fit = par[1]
    dm_fit, dq_fit = py.sqrt(py.diag(cov))
    I_th = -q_fit / m_fit
    dI = I_th * (dm_fit / m_fit + dq_fit / q_fit)
    print('m = %s  q = %s' % (xe(m_fit, dm_fit), xe(q_fit, dq_fit)))
    print('I_th = %s' % (xe(I_th, dI)))
    m.append(m_fit)
    q.append(q_fit)
    dm.append(dm_fit)
    dq.append(dq_fit)
    dt = 0.68 * 0.5 * (t[1] - t[0])
    dt = 10e-6
    dV = 10

    volt = (volt1 + volt2) / 2

    D = t[argmin(volt)]
    A = volt[argmin(volt)]
    B = -24
    p0 = [A, B, 36, D, 200]
    curva = CurveModel(trasmittivita, symb=True)
    out = fit_curve(curva,
                    t,
                    volt,
                    dy=dV,
                    dx=dt,
                    p0=p0,
                    pfix=[False, True, True, False, False],
                    absolute_sigma=False,
                    method='odrpack')
    par = out.par
    cov = out.cov
    err = sqrt(diag(cov))

    print(numbers[i], 'F = %s' % xe(par[4], err[4]), std(diff(volt)))
    if numbers[i] != '06c':
        subplot(altez, largh, n_subplot)
        ylim(-550, 0)
        if len(files) - n_subplot <= largh:
            xlabel('t [ms]')
        if (n_subplot - 1) % largh != 0:
errorbar(xdata, tem00, yerr=yerr, xerr=xerr, fmt='.')


def gauss(x, mu, sigma, norma):
    return norma * exp(-(x - mu)**2 / (2 * sigma**2))


xlabel('$\\theta$ [°]')
ylabel('P [$\mu$W]')

par0 = [194, 3, 50]
#out = fit_curve(gauss, xdata, tem00, dx=xerr/4, dy=yerr, p0=par0, method='leastsq')
out = fit_curve(gauss,
                xdata,
                tem00,
                dy=yerr,
                dx=xerr,
                p0=par0,
                method='odrpack')
par = out.par
cov = out.cov
err = sqrt(cov)
chi2 = out.chisq
dof = out.chisq_dof
chi2norm = chi2 / dof
pvalue = out.chisq_pvalue
print('chi2 = ', chi2)
print('dof = ', dof)
print('chi2norm = ', chi2norm)
print('pvalue = ', pvalue)
xx = py.linspace(min(xdata) - 1, max(xdata) + 1, 1000)
dx = 0.68 * 0.5 * ones(len(dVpp))

figure('2polarizzatori').set_tight_layout(True)
clf()
errorbar(angolo, Vpp, yerr=dy, fmt='.k')


def cos2(x, a, b):
    return a * (cos((x - b) * pi / 180))**2


def cos2o(x, a, b, c):
    return a * (cos((x - b) * pi / 180))**2 + c


out = fit_curve(cos2, angolo, Vpp, dy=dy, p0=[60, -90])
par = out.par
cov = out.cov
err = sqrt(diag(cov))
chi2norm = out.chisq / out.chisq_dof
pvalue = out.chisq_pvalue

out = fit_curve(cos2o, angolo, Vpp, dy=dy, p0=[60, -90, 1])
paro = out.par
covo = out.cov
erro = sqrt(diag(covo))
print(paro, erro)
chi2normo = out.chisq / out.chisq_dof
pvalueo = out.chisq_pvalue

plot(