Beispiel #1
0
def latex_table(directory,
                file_,
                data,
                data_err,
                tab,
                out=False,
                data_ol=[],
                data_err_ol=[]):
    """
        Parameters
        ----------    

        Returns
        -------

    """

    with open(directory + "tabelle/tab_" + file_ + ".txt", "w") as text_file:
        text_file.write("\\begin{tabular}{c")
        for z in range(1, len(data)):
            text_file.write("|c")
        text_file.write("} \n")
        text_file.write("%s" % tab[0])
        for z in range(1, len(data)):
            text_file.write(" & %s" % tab[z])
        text_file.write("\\\\\n\hline\n")
        for i in range(len(data[0])):
            text_file.write("%s" % xe(data[0][i], data_err[0][i], "$\pm$"))
            for j in range(1, len(data)):
                text_file.write(" & %s" %
                                xe(data[j][i], data_err[j][i], "$\pm$"))
            text_file.write("\\\\\n")
        if out == True:
            for i in range(len(data_ol[0])):
                text_file.write("%s" %
                                xe(data_ol[0][i], data_err_ol[0][i], "$\pm$"))
                for j in range(1, len(data_ol)):
                    text_file.write(
                        " & %s" %
                        xe(data_ol[j][i], data_err_ol[j][i], "$\pm$"))
                text_file.write("\\\\\n")
        text_file.write("\\end{tabular}")
        text_file.close()
def mc_integrator(f_over_dist,
                  dist_sampler,
                  epsrel=1e-4,
                  epsabs=1e-4,
                  start_n=10000,
                  max_bunch=10000000,
                  print_info=True):
    summ = 0.0
    sum2 = 0.0
    i = 0
    n = 0
    while True:
        if i == 0:
            dn = start_n
            if print_info:
                print('################ mc_integrator ################')
                print()
                print('epsrel = %.2g' % epsrel)
                print('epsabs = %.2g' % epsabs)
                print()
                print('***** Cycle %d *****' % i)
                print('Generating start_n = %d samples' % start_n)
        else:
            target_error = epsabs + I * epsrel
            target_n = int((DI / target_error)**2 * n)
            dn = min(target_n - n, max_bunch)
            if print_info:
                print()
                print('***** Cycle %d *****' % i)
                print('Estimated necessary samples = %d' % target_n)
                print('Generating %d more samples (max = %d)' %
                      (dn, max_bunch))
        sample = dist_sampler(dn)
        n += dn
        y = f_over_dist(sample)
        summ += np.sum(y, axis=0)
        sum2 += np.sum(y**2, axis=0)
        I = summ / n
        DI = np.sqrt((sum2 - summ**2 / n) / (n * (n - 1)))
        if print_info:
            print('Result with %d samples:' % n)
            print('I = %s  (I = %g, DI = %g)' % (lab.xe(I, DI), I, DI))
        if all(DI < epsrel * I + epsabs):
            if print_info:
                print(
                    'Termination condition DI < epsrel * I + epsabs satisfied.'
                )
                print()
                print('############## END mc_integrator ##############')
            break
        i += 1
    return I, DI
Beispiel #3
0
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]')
py.xlabel('T [°C]')
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])
par2 = out.par
cov2 = out.cov
err2 = sqrt(diag(cov2))
chi2norm2 = out.chisq / out.chisq_dof
print('chi2norm = ', chi2norm2)
print('p-value = ', out.chisq_pvalue)
print('parameters = ', par2)
print('errors     = ', err2)

#plot(angolo, cos4(angolo, *par0), '-k')
plot(angolo, cos4(angolo, *par1), '-g', label='$y = a \cdot \cos^4(x-b)$\n$\\frac{\chi^2}{dof} = %.2f$\n$b_{fit} = %s °$' %(chi2norm1,xe(par1[1],err1[1])))
#plot(angolo, cos4(angolo, *par2), '-g', label='$y = a \cdot \cos^4(x-b)$\n$\\frac{\chi^2}{dof} = %.2f$\n$b_{fit} = %s$' %(chi2norm2,xe(par2[1],err2[1])))
legend(fontsize='x-large')
xlabel('$\\varphi$ [°]', fontsize='large')
ylabel('intensità della seconda armonica [u.a.]', fontsize='large')
    ##funzione di fit
    def retta(x, a, b):
        return a*x + b
    
    par, cov = curve_fit(retta, n, l, sigma = dl, 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]
    dm_fit = py.sqrt(dm_fit**2+(0.01*m_fit)**2)
    m.append(m_fit)
    q.append(q_fit)
    dm.append(dm_fit)
    dq.append(dq_fit)
    print('m = %s  q = %s' %(xe(m_fit, dm_fit), xe(q_fit, dq_fit)))
    x = py.linspace(0, len(n)+1, 100)
    py.plot(x, retta(x, *par), linewidth=1, color ='tab:green' ,label='{} = {} [mm]'.format('$m_{fit}$', xe(m_fit, dm_fit)))
    py.legend(fontsize='large')
    py.ylabel('l [mm]')
    py.xlabel('N')

    
    
    
    
    

clf()
errorbar(primi, Vpp, yerr=dy, xerr=dx, fmt='.k')
xx = linspace(min(primi), max(primi), 2000)
plot(xx, PM(xx, *par), label='fit con tutte le misure', color='tab:orange')
#$y = \\alpha \\frac{\sin^2(\\beta (\\theta - \\theta_m))}{[\\beta (\\theta - \\theta_m)]^2}$
xxx = linspace(min(primi[cutindex1:cutindex2]),
               max(primi[cutindex1:cutindex2]), 2000)
plot(xxx, PM(xxx, *parc), label='fit senza le code', color='tab:green')
plot(xx, PM(xx, *parc), '--', color='tab:green', label='estrapolazione')
#plot(xxx, gaussiana(xxx, *parg))
bbox_props = dict(boxstyle="round", fc="w", ec="0.5", alpha=0.5)
text(
    313,
    505,
    '$y = \\alpha \\frac{\sin^2(\\beta (\\theta - \\theta_m))}{[\\beta (\\theta - \\theta_m)]^2}$ \n $\\beta_{fit} = 1.377(2)\;gradi^{-1}$'
    % xe(parc[1] * 60, errc[1] * 60),
    fontsize='large',
    verticalalignment='top',
    horizontalalignment='right',
    bbox=bbox_props)
xlabel('angolo [\']')
ylabel('intensità seconda armonica [mV]')
legend(fontsize='large', loc=2)

figure('sinc_gaussiana').set_tight_layout(True)
clf()
errorbar(primi, Vpp, yerr=dy, xerr=dx, fmt='.k')
xx = linspace(min(primi), max(primi), 2000)
xxx = linspace(min(primi[cutindex1:cutindex2]),
               max(primi[cutindex1:cutindex2]), 2000)
plot(
Beispiel #7
0
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])
errorbar(power, Vpp, fmt='.k', yerr=dy, xerr=dx, markersize=4)
xx = linspace(min(power), max(power), 2000)
plot(
    xx,
    parabola(xx, *par),
    color='tab:green',
    label=
Beispiel #8
0
                 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)

        if i % larghezza == 0:
            ylabel('t [ms]')
        if i >= len(files) - larghezza:
            xlabel('ordini')
        #xlabel('numero ordine interferenza')
        #ylabel('t [ms]')
        xticks(arange(1, n_ordini + 1, 1))
        ylim(ylim(min(t) - 0.2 * (max(t) - min(t)), max(t)))
        xlim(0.5, n_ordini + 0.5)
    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 #10
0
                    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(
        (out.chisq, out.chisq_dof, out.chisq / out.chisq_dof)))
    print('p_value = %.3f\n' % out.chisq_pvalue)

    figure('potenza_alla2')
    subplot(altezza, larghezza, j)
    errorbar(power[indici_bassi],
             Vpp[indici_bassi],
             fmt='.k',
             yerr=dy[indici_bassi],
             xerr=dx[indici_bassi],
             markersize=4)
    xx = linspace(
        min(power[indici_bassi]) - 6,
        max(power[indici_bassi]) + 6, 2000)
l633_2 = ufloat(289.2, 0.5)
l532_1 = ufloat(291.3, 0.5)
l532_2 = ufloat(287.1, 0.5)

lamb = [633, 532]
lamb_n = [850, 1300]
atten_n = [ufloat(4, 0.1), ufloat(1.5, 0.1)]
atten_1 = array([
    um.log10(pin633_1 / pout633_1) / l633_1,
    um.log10(pin532_1 / pout532_1) / l532_1
]) * 10000
atten_2 = array([
    um.log10(pin633_2 / pout633_2) / l633_2,
    um.log10(pin532_2 / pout532_2) / l532_2
]) * 10000
print('attenuazione1 532 = %s' % xe(atten_1[1].n, atten_1[1].s))
print('attenuazione2 532 = %s' % xe(atten_2[1].n, atten_2[1].s))
print('attenuazione1 633 = %s' % xe(atten_1[0].n, atten_1[0].s))
print('attenuazione2 633 = %s' % xe(atten_2[0].n, atten_2[0].s))

sigma633 = std(array([
    atten_1[0].n,
    atten_2[0].n,
]), ddof=1)
sigma532 = std(array([
    atten_1[1].n,
    atten_2[1].n,
]), ddof=1)
print('sigma 532  = %.2f' % sigma532)
print('sigma 633  = %.2f' % sigma633)
print('mean sigma = %.2f' % qmean([sigma532, sigma633]))
Beispiel #12
0
 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)
 x = py.linspace(I[j] - 2, I[0] + 1, 100)
 py.plot(x,
         retta(x, *par),
         linewidth=1,
         color=c_fit[i],
         label='{} = {} mA, T = {} °C'.format('$I_{th}$', xe(I_th, dI),
                                              T[i]))
 py.legend(fontsize='large')
 py.ylabel('P [$\mu$W]')
 py.xlabel('I [mA]')
def fit_bayes(f,
              x,
              y,
              dx,
              dy,
              par0,
              cov0,
              relax='x',
              std_dig=1.5,
              cor_err=0.01,
              prob_err=0.05,
              gamma=1,
              print_info=False,
              plot_figure=None):
    """
	if dx is None, par0-cov0 is the estimate of parameters
	if dx is not None, par0-cov0 is the estimate of [parameters, xs]
	f must be fully vectorized
	"""
    if print_info:
        print('################# fit_bayes #################')
        print()
        print('f = {}'.format(f))
        print('x.shape = {}'.format(x.shape))
        print('y.shape = {}'.format(y.shape))
        print('dy.shape = {}'.format(dy.shape))
        print('dx = None' if dx is None else 'dx.shape = {}'.format(dx.shape))
        print()
        print('Starting estimate of parameters:')
        print(lab.format_par_cov(par0, cov0))
        print()

    # TARGET ERRORS FOR RESULTS

    # target relative error on computed standard deviations
    # 1/2.1 to round correctly
    std_relerr = 10**(-std_dig) * 1 / 2.1

    # target relative error on (1 - correlation)
    # 1/2.1 to round correctly
    onemcor_relerr = cor_err * 1 / 2.1

    # target absolute error on computed averages
    # align with error on standard deviations, based on initial estimate
    dp0 = np.sqrt(np.diag(cov0))
    avg_abserr = std_relerr * dp0

    # target relative error on computed variances
    # 2 because variance = std ** 2
    var_relerr = std_relerr * 2

    # sigma factor for statistical errors
    sigma = abs(stats.norm.ppf(prob_err / 2))

    if print_info:
        print('Target relative error on standard deviations = %.3g' %
              std_relerr)
        print('Target absolute error on averages:\n{}'.format(avg_abserr))
        print()

    # VARIABLE TRANSFORM AND LIKELIHOOD

    # diagonalize starting estimate of covariance
    w, V = linalg.eigh(cov0)
    dp0 = np.sqrt(w)
    p0 = V.T.dot(par0)

    if print_info:
        print('Diagonalized starting estimate of parameters:')
        print(lab.xe(p0, dp0))
        print()

    # change variable: p0 -> C, dp0 -> 1
    # (!) M and Q will be changed by functions, so do not reassign them!
    C = 10
    M = np.copy(dp0)
    Q = p0 - C * M
    dp0 /= M
    p0 = (p0 - Q) / M

    # likelihood (not normalized)
    idy2 = 1 / dy**2
    vx = x.reshape((1, ) + x.shape)
    vy = y.reshape((1, ) + y.shape)
    if dx is None:
        chi20 = np.sum((y - f(x, *par0))**2 *
                       idy2)  # initial normalization with L(C) == 1

        def L(p):
            return np.exp((-np.sum((vy - f(
                vx,
                *np.einsum(
                    'ik,jk', V,
                    M.reshape((1, ) + M.shape) * p + Q.reshape(
                        (1, ) + Q.shape)).reshape(p.shape[::-1] +
                                                  (1, ))))**2 * idy2,
                                   axis=1) + chi20) / 2)
    else:
        vdx = dx.reshape((1, ) + dx.shape)
        chi20 = np.sum((y - f(par0[-len(x):], *par0[:-len(x)]))**2 *
                       idy2)  # initial normalization with L(C) == 1

        def L(px):
            tpx = np.einsum(
                'ik,jk', V,
                M.reshape((1, ) + M.shape) * px + Q.reshape((1, ) + Q.shape))
            p = tpx[:-len(x)]
            p = p.reshape(p.shape + (1, ))
            txstar = tpx[-len(x):].T
            return np.exp((-np.sum(
                (vy - f(txstar, *p))**2 * idy2, axis=1) - np.sum(
                    ((txstar - vx) / vdx)**2, axis=1) + chi20) / 2)

    # INTEGRAND

    # integrand: [L, p0 * L, ..., pd * L, p0 * p0 * L, p0 * p1 * L, ..., p0 * pd * L, p1 * p1 * L, ..., pd * pd * L]
    # change of variable: p = C + k * tan(theta), theta in (-pi/2, pi/2)
    idxs = np.triu_indices(len(p0))
    bounds = [(-np.pi / 2, np.pi / 2)] * len(p0)
    k = 1 / 2

    @vegas.batchintegrand
    def integrand(theta):
        t = np.tan(theta)
        p = C + k * t
        l = np.prod(k * (1 + t**2), axis=1) * L(p)
        return np.concatenate(
            (np.ones(l.shape +
                     (1, )), p, np.einsum('ij,il->ijl', p, p)[(..., ) + idxs]),
            axis=1) * l.reshape(l.shape + (1, ))

    # figure showing sections of the integrand
    if not (plot_figure is None):
        length = len(p0) if dx is None else len(p0) - len(x)
        plot_figure.clf()
        plot_figure.set_tight_layout(True)
        G = gridspec.GridSpec(length, length + 2)
        subplots = np.empty((length, length + 2), dtype=object)
        eps = 1e-4
        xs = np.linspace(-np.pi / 2 + eps, np.pi / 2 - eps, 256)

        for i in range(length):
            axes = plot_figure.add_subplot(G[i, 0])
            subplots[i, 0] = axes
            theta = np.zeros((len(xs), len(p0)))

            def fplot(theta_i):
                theta[:, i] = theta_i
                return integrand(theta)[:, 0]

            axes.plot(xs, fplot(xs), '-k', label=R'$L$ along $p_{%d}$' % (i))
            axes.legend(loc=1)

        for i in range(length):
            axes = plot_figure.add_subplot(G[i, 1])
            subplots[i, 1] = axes
            theta = np.zeros((len(xs), len(p0)))

            def fplot(theta_i):
                theta[:, i] = theta_i
                return integrand(theta)[:, 1 + i]

            axes.plot(xs,
                      fplot(xs),
                      '-k',
                      label=R'$p_{%d}\cdot L$ along $p_{%d}$' % (i, i))
            axes.legend(loc=1, fontsize='small')

        mat = np.empty(cov0.shape, dtype='uint32')
        mat[idxs] = np.arange(len(idxs[0]))
        for i in range(length):
            for j in range(i, length):
                theta = np.zeros((len(xs), len(p0)))
                if i == j:
                    axes = plot_figure.add_subplot(G[i, i + 2])
                    subplots[i, i + 2] = axes

                    def fplot(theta_i):
                        theta[:, i] = theta_i
                        return integrand(theta)[:, 1 + len(p0) + mat[i, i]]

                    axes.plot(xs,
                              fplot(xs),
                              '-k',
                              label=R'$p_{%d}^2\cdot L$ along $p_{%d}$' %
                              (i, i))
                    axes.legend(loc=1, fontsize='small')
                else:  # i != j

                    def fplot_p(theta_ij):
                        theta[:, i] = theta_ij
                        theta[:, j] = theta_ij
                        return integrand(theta)[:, 1 + len(p0) + mat[i, j]]

                    def fplot_m(theta_ij):
                        theta[:, i] = theta_ij
                        theta[:, j] = -theta_ij
                        return integrand(theta)[:, 1 + len(p0) + mat[i, j]]

                    axes = plot_figure.add_subplot(G[i, j + 2])
                    subplots[i, j + 2] = axes
                    axes.plot(
                        xs,
                        fplot_p(xs),
                        '-k',
                        label=
                        R'$p_{%d}\cdot p_{%d}\cdot L$ along $p_{%d}=p_{%d}$' %
                        (i, j, i, j))
                    axes.legend(loc=1, fontsize='small')
                    axes = plot_figure.add_subplot(G[j, i + 2])
                    subplots[j, i + 2] = axes
                    axes.plot(
                        xs,
                        fplot_m(xs),
                        '-k',
                        label=
                        R'$p_{%d}\cdot p_{%d}\cdot L$ along $p_{%d}=-p_{%d}$' %
                        (i, j, i, j))
                    axes.legend(loc=1, fontsize='small')

    # INTEGRAL

    func_mean = np.vectorize(lambda x: x.mean, otypes=['float64'])
    func_sdev = np.vectorize(lambda x: x.sdev, otypes=['float64'])

    def matrify(I):
        par = np.asarray(I[:len(p0)])
        cov = np.empty(cov0.shape, dtype=gvar.GVar)
        cov[idxs] = I[len(p0):]
        cov.T[idxs] = cov[idxs]
        return par, cov

    # takes the integration result and computes average and covariance dividing by normalization
    def normalize(I):
        par = [I[j] / I[0] for j in range(1, len(p0) + 1)]
        cov_u = [
            I[j + len(par) + 1] / I[0] - par[idxs[0][j]] * par[idxs[1][j]]
            for j in range(len(idxs[0]))
        ]
        return matrify(par + cov_u)

    # do inverse variable transform
    def target_result(I):
        par, cov = normalize(I)
        par = V.dot(M * par + Q)
        cov = V.dot(np.outer(M, M) * cov).dot(V.T)
        return np.concatenate((par, cov[idxs]))

    if isinstance(relax, str):
        relax = [relax]
    if 'x' in relax:
        if dx is None:
            nrelax = np.ones(len(p0), dtype=bool)
        else:
            nrelax = np.arange(len(p0)) < len(p0) - len(x)
    ignore_corr = 'corr' in relax
    if hasattr(relax, '__iter__') and all([isinstance(a, bool)
                                           for a in relax]):
        nrelax = ~np.asarray(relax)
    if hasattr(relax, '__getitem__') and 'indexes' in relax:
        nrelax = ~np.asarray(relax['indexes'])

    # compute objects on which errors are defined: avg, var, (1-corr)**2
    gamma = 1
    err_np0 = np.sum(nrelax)
    err_idxs = np.diag_indices(
        err_np0) if 'corr' in relax else np.triu_indices(err_np0)
    nrelax2 = np.outer(nrelax, nrelax)

    def target_error(I):
        par, cov = matrify(I)
        par = par[nrelax]
        cov = cov[nrelax2].reshape(2 * [err_np0])
        sigma = np.sqrt(np.diag(cov))
        var_onemcor2 = (1 - cov / np.outer(sigma, sigma))**2
        np.fill_diagonal(var_onemcor2, np.diag(cov))

        if gamma != 1:
            Q[:] = gamma * Q + (1 - gamma) * (V.T.dot(func_mean(par)) - C * M)
            M[:] = gamma * M + (1 - gamma) * np.sqrt(
                np.diag(V.T.dot(func_mean(cov)).dot(V)))

        return np.concatenate((par, var_onemcor2[err_idxs]))

    epsrel = np.ones([err_np0] * 2) * onemcor_relerr / sigma * 2
    np.fill_diagonal(epsrel, var_relerr / sigma)
    epsrel = np.concatenate((np.zeros(err_np0), epsrel[err_idxs]))

    epsabs = np.zeros(epsrel.shape)
    epsabs[:err_np0] = avg_abserr[nrelax] / sigma

    I = mc_integrator_2(integrand,
                        bounds,
                        target_result=target_result,
                        target_error=target_error,
                        epsrel=epsrel,
                        epsabs=epsabs,
                        print_info=print_info)

    # FINALLY, RESULT!

    par, cov = matrify(I)

    if print_info:
        print()
        # print('Normalized result:')
        # print(lab.format_par_cov(func_mean((V.T.dot(par) - Q) / M), func_mean(V.T.dot(cov).dot(V) / np.outer(M, M))))
        # print('Diagonalized result:')
        # print(lab.format_par_cov(func_mean(V.T.dot(par)), func_mean(V.T.dot(cov).dot(V))))

    # plot final variable transform
    if not (plot_figure is None) and gamma != 1:
        for i in range(length):
            axes = subplots[i, 0]
            theta = np.zeros((len(xs), len(p0)))

            def fplot(theta_i):
                theta[:, i] = theta_i
                return integrand(theta)[:, 0]

            axes.plot(xs, fplot(xs), '-r')
            axes.legend(loc=1)

        for i in range(length):
            axes = subplots[i, 1]
            theta = np.zeros((len(xs), len(p0)))

            def fplot(theta_i):
                theta[:, i] = theta_i
                return integrand(theta)[:, 1 + i]

            axes.plot(xs, fplot(xs), '-r')
            axes.legend(loc=1, fontsize='small')

        for i in range(length):
            for j in range(i, length):
                theta = np.zeros((len(xs), len(p0)))
                if i == j:
                    axes = subplots[i, i + 2]

                    def fplot(theta_i):
                        theta[:, i] = theta_i
                        return integrand(theta)[:, 1 + len(p0) + mat[i, i]]

                    axes.plot(xs, fplot(xs), '-r')
                else:  # i != j

                    def fplot_p(theta_ij):
                        theta[:, i] = theta_ij
                        theta[:, j] = theta_ij
                        return integrand(theta)[:, 1 + len(p0) + mat[i, j]]

                    def fplot_m(theta_ij):
                        theta[:, i] = theta_ij
                        theta[:, j] = -theta_ij
                        return integrand(theta)[:, 1 + len(p0) + mat[i, j]]

                    axes = subplots[i, j + 2]
                    axes.plot(xs, fplot_p(xs), '-r')
                    axes = subplots[j, i + 2]
                    axes.plot(xs, fplot_m(xs), '-r')

    dpar = func_sdev(par)
    dcov = func_sdev(cov)

    mpar = func_mean(par)
    mcov = func_mean(cov)

    if print_info:
        print('Starting estimate was:')
        print(lab.format_par_cov(par0, cov0))
        print('Result:')
        print(lab.format_par_cov(mpar, mcov))
        print('Averages with computing errors:')
        print(par)
        print('Standard deviations with computing errors:')
        sigma = np.sqrt(np.diag(cov))
        print(sigma)
        print('Correlations with computing errors:')
        print(cov / np.outer(sigma, sigma))
        print()
        print('############### END fit_bayes ###############')

    return mpar, mcov, dpar, dcov
    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:
            yticks(array([]))
        else:
            ylabel('segn. [mV]')
        n_subplot += 1
        plot(t,
             volt,
             '.k',
             markersize=1,
             label='file: %s\n$F$ = %.0f' % tuple((numbers[i], par[4])))
Beispiel #15
0
                    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))
    m.append(m_fit)
    q.append(q_fit)
    dm.append(dm_fit)
    dq.append(dq_fit)
    print('picco %s: m = %s  q = %s' %
          (nomipicchi[k], xe(m_fit, dm_fit), xe(q_fit, dq_fit)))
    plot(ordini, retta(ordini_fit, *par))

xticks(arange(0, n_ordini, 1))
xlim(-0.3, n_ordini - 1 + 0.3)
ylim(min(t), max(t))
ylabel('t [ms]')
xlabel('ordine')

m = array(m)
dm = array(dm)
q = array(q)
dq = array(dq)
uFSR = gvar(m.mean(), dm.mean() / sqrt(3))
diffq = diff(q)
udeltaq_sinistra = gvar(diffq[0], dq.mean() * sqrt(2))
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(
    angolo,
    cos2(angolo, *par),
    '-',
    color='tab:orange',
    label=
    '$y = a \cdot \cos^2(x-b)$\n$\\frac{\chi^2}{dof} = %.2f \qquad b_{fit} = %s$\n'
    % (chi2norm, xe(par[1], err[1])))
plot(
    angolo,
    cos2o(angolo, *paro),
    '-',
    color='tab:green',
    label=
    '$y = a \cdot \cos^2(x-b) + c$\n$\\frac{\chi^2}{dof} = %.2f \qquad b_{fit} = %s$'
    % (chi2normo, xe(paro[1], erro[1])))
legend(fontsize='x-large', loc=0)
xlabel('$\\varphi$ [°]', fontsize='large')
ylabel('$V_{pp}$ [mV]', fontsize='large')