Ejemplo n.º 1
0
def fit_fmpe(x, y, y_err, init_params, limit_params):

    chi2 = Chi2Regression(fmpe_pdf_10, x=x, y=y, error=y_err)

    bin_width = np.diff(x)
    bin_width = np.mean(bin_width)
    params = describe(fmpe_pdf_10, verbose=False)[1:]
    fixed_params = {}

    for param in params:

        if param not in init_params.keys():

            fixed_params['fix_{}'.format(param)] = True

    m = Minuit(
        chi2,
        **init_params,
        **limit_params,
        **fixed_params,
        bin_width=bin_width,
        print_level=0,
        pedantic=False,
    )
    m.migrad()

    return m
Ejemplo n.º 2
0
def fit_spe(x, y, y_err, sigma_e, snr=4, debug=False):

    params_init = compute_fit_init_param(x,
                                         y,
                                         snr=snr,
                                         sigma_e=sigma_e,
                                         debug=debug)

    mask = x > (params_init['baseline'] + params_init['gain'] / 2)
    mask *= y > 0

    x = x[mask]
    y = y[mask]
    y_err = y_err[mask]

    keys = [
        'limit_baseline', 'limit_gain', 'limit_sigma_e', 'limit_sigma_s',
        'limit_a_1', 'limit_a_2', 'limit_a_3', 'limit_a_4'
    ]

    values = [
        (-0.5 * params_init['gain'], 1.5 * params_init['gain']),
        (0.5 * params_init['gain'], 1.5 * params_init['gain']),
        (0.5 * params_init['sigma_e'], 1.5 * params_init['sigma_e']),
        (0.5 * params_init['sigma_s'], 1.5 * params_init['sigma_s']),
        (0.5 * params_init['a_1'], 1.5 * params_init['a_1']),
        (0.5 * params_init['a_2'], 1.5 * params_init['a_2']),
        (0, params_init['a_2']),
        (0, params_init['a_2']),
    ]

    param_bounds = dict(zip(keys, values))

    chi2 = Chi2Regression(single_photoelectron_pdf, x, y, y_err)
    # chi2 = Chi2Regression(log_spe, x, np.log(y), np.log(y_err))
    m = Minuit(
        chi2,
        **params_init,
        **param_bounds,
        print_level=0,
        pedantic=False,
    )
    m.migrad(nsplit=5, ncall=30000)
    '''
    try:
        m.minos()
    except RuntimeError:
        pass

    '''

    if debug:
        plt.figure()
        plt.plot(x, y)
        plt.plot(x, single_photoelectron_pdf(x, **m.values))
        print(m.values, m.errors, m.fval)
        plt.show()

    return m.values, m.errors, params_init, param_bounds
Ejemplo n.º 3
0
def fit_template(events, pulse_width=(4, 5), rise_time=12):

    for event in events:

        adc_samples = event.data.adc_samples.copy()
        time = np.arange(adc_samples.shape[-1]) * 4
        pulse_indices = event.data.pulse_mask
        pulse_indices = np.argwhere(pulse_indices)
        pulse_indices = [tuple(arr) for arr in pulse_indices]
        amplitudes = np.zeros(adc_samples.shape) * np.nan
        times = np.zeros(adc_samples.shape) * np.nan

        plt.figure()

        for pulse_index in pulse_indices:

            left = pulse_index[-1] - int(pulse_width[0])
            left = max(0, left)
            right = pulse_index[-1] + int(pulse_width[1]) + 1
            right = min(adc_samples.shape[-1] - 1, right)

            y = adc_samples[pulse_index[0], left:right]
            t = time[left:right]

            where_baseline = np.arange(adc_samples.shape[-1])
            where_baseline = (where_baseline < left) + \
                             (where_baseline >= right)
            where_baseline = adc_samples[pulse_index[0]][where_baseline]

            baseline_0 = np.mean(where_baseline)
            baseline_std = np.std(where_baseline)
            limit_baseline = (baseline_0 - baseline_std,
                              baseline_0 + baseline_std)

            t_0 = time[pulse_index[-1]] - rise_time
            limit_t = (t_0 - 2 * 4, t_0 + 2 * 4)

            amplitude_0 = np.max(y)
            limit_amplitude = (max(np.min(y), 0), amplitude_0 * 1.2)

            chi2 = Chi2Regression(get_pulse_shape, t, y)
            m = Minuit(chi2, t=t_0,
                       amplitude=amplitude_0,
                       limit_t=limit_t,
                       limit_amplitude=limit_amplitude,
                       baseline=baseline_0,
                       limit_baseline=limit_baseline,
                       print_level=0, pedantic=False)
            m.migrad()

            adc_samples[pulse_index[0]] -= get_pulse_shape(time, **m.values)
            amplitudes[pulse_index] = m.values['amplitude']
            times[pulse_index] = m.values['t']

        event.data.reconstructed_amplitude = amplitudes
        event.data.reconstructed_time = times

        yield event
Ejemplo n.º 4
0
def triple_GaussianFit(Nbins, xmin, xmax, data):
    """Given inputs of data and corresponding histogram
    returns Chi2 regression Gaussian fit from Minuit"""
    fig, ax = plt.subplots()
    hist, bins, _ = ax.hist(data, bins=Nbins, range=(xmin, xmax))
    plt.close(fig)

    # Defining variables
    dis_bins = bins[1] - bins[0]
    x_hist = np.arange(xmin + dis_bins / 2, (xmax), dis_bins)
    x_var = np.linspace(xmin - dis_bins / 2, (xmax), 1000)

    # Only inputs from bins >0
    histcor = hist[hist > 0]
    x_hist = x_hist[hist > 0]
    error = np.array([1 / i for i in histcor])
    N_scale = max(hist) / max(gauss_pdf(x_var, np.mean(data), np.std(data)))

    # Fit
    chi2_object = Chi2Regression(triple_gauss, x_hist, histcor, weights=error)
    minuit = Minuit(chi2_object,
                    pedantic=False,
                    N1=N_scale,
                    N2=N_scale / 2,
                    N3=N_scale / 3,
                    mu1=15,
                    mu2=20,
                    mu3=35,
                    sigma1=10,
                    sigma2=5,
                    sigma3=5,
                    print_level=0)

    minuit.migrad()
    NDOF = len(histcor) - 9
    Chi2_fit = minuit.fval
    Prob_fit = stats.chi2.sf(Chi2_fit, NDOF)

    #Parameters of fit
    (N1_fit, N2_fit, N3_fit, mean1_fit, mean2_fit, mean3_fit, sigma1_fit,
     sigma2_fit, sigma3_fit) = minuit.args
    (N1_fite, N2_fite, N3_fite, mean1_fite, mean2_fite, mean3_fite,
     sigma1_fite, sigma2_fite, sigma3_fite) = minuit.errors.values()

    # Significant decimals
    decmu1, decstd1 = decimals(mean1_fite), decimals(sigma1_fite)

    # Text string to use as a label or info box later
    text_string = (r"Gaussian $\chi^2$ in numbers:" + "\n" + r"$\mu$ = " +
                   str(round(mean1_fit, decmu1)) + r"$\pm$" +
                   str(round(mean1_fite, decmu1)) + "\n" + r"$\sigma$ = " +
                   str(round(sigma1_fit, decstd1)) + r"$\pm$" +
                   str(round(sigma1_fite, decstd1)) + "\n" + r"$\chi^2$ = " +
                   str(round(Chi2_fit, 2)) + "\n" + "NDOF = " + str(NDOF) +
                   "\n" + "Prob = " + str(round(Prob_fit * 100, 3)) + "%")

    return minuit, x_var, triple_gauss(x_var, *minuit.args), text_string
Ejemplo n.º 5
0
def fit_power_lawab(x, y, ey, **kwargs):
    '''
    Use chisq regression to fit for y = b * x^a
    Return two dictionaries: one for the values of a and b.
    and the second for the errors.
    '''
    x2reg = Chi2Regression(powerlaw, x, y, ey)
    m = Minuit(x2reg, print_level=0, a=-0.5, error_a=0.1, b=10, error_b=1)
    m.migrad()
    m.hesse()
    return m.values, m.errors
Ejemplo n.º 6
0
def fit_power_law(x, y, ey):
    '''
    Use chisq regression to fit for y = exp(b) * x^a
    Return two dictionaries: one for the values of a and b.
    and the second for the errors.
    '''
    x2reg = Chi2Regression(poly1, np.log(x), np.log(y), error=ey / y)
    m = Minuit(x2reg, print_level=0, a=-0.5, error_a=1, b=1, error_b=1)
    m.migrad()
    m.hesse()
    return m.values, m.errors
Ejemplo n.º 7
0
def chi2_fit(function, x_values, y_values, unc_y, **start_parameters):
    """Chi2 Minuit fit with arbitrary function. Returns dict(values), dict(errors), chi2-value, prob(chi2)-value"""
    chi2_object = Chi2Regression(function, x_values, y_values, unc_y)
    minuit = Minuit(chi2_object, pedantic=False, print_level=0, **start_parameters)
    minuit.migrad()  # perform the actual fit
    if (not minuit.get_fmin().is_valid):
        print("  WARNING: The ChiSquare fit DID NOT converge!!!")
        conv = "No"
    else:
        conv = "Yes"
    minuit_output = [minuit.get_fmin(), minuit.get_param_states()]
    Ndof_fit = len(y_values) - len(start_parameters)
    prop_chi2 = stats.chi2.sf(minuit.fval, Ndof_fit)
    return minuit.values, minuit.errors, minuit.fval, Ndof_fit, prop_chi2, conv
def constant_check(top, t_top):
    """ Reduced chi-square of top being constant """
    def constant_func(x, a):
        return a

    top, t_top = np.array(top), np.array(t_top)

    error = np.array([np.sqrt((i - np.mean(top))**2) for i in top])
    chi2_object = Chi2Regression(constant_func, t_top, top, weights=error)
    minuit = iminuit.Minuit(chi2_object, pedantic=False, a=0, print_level=0)
    minuit.migrad()
    NDOF = len(top) - 1
    Chi2_fit = minuit.fval

    if NDOF == 0:
        NDOF = 1

    return Chi2_fit / NDOF
Ejemplo n.º 9
0
def interpo_poly3(y, xi, yi, xref):
    '''
    Given an array *xi* and an array *yi*, fit a 3rd-order polynomial.
    Then solve x for a given y.
    '''
    x2reg = Chi2Regression(poly3, xi, yi)
    m = Minuit(x2reg, print_level=0, pedantic=False)
    m.migrad()
    # Solve x for a given y
    coefs = [m.values[k] for k in ['a3', 'a2', 'a1', 'a0']]
    coefs[-1] -= y
    roots = np.roots(coefs)
    # get the one that is closest to xref
    dist = 1e9
    rt = None
    for r in roots:
        if np.abs(xref - r) < dist:
            dist = np.abs(xref - r)
            rt = r
    if r is None:
        raise ValueError('Cannot find the proper root')
    return r
Ejemplo n.º 10
0
def malinger(values,variances):
    """script that takes indepentent values, variances and spits out mean and
    variance...
    INCLUDE chi2, Ndf, p-value"""
    #Add values, get mean and variances based on multiple independent measure-
    #ments of same thing
    #make chi-square fit based on real mean (fit straight line)

    Nvar = 1
    Ndof_calc = len(values) - Nvar

    def fit_function(x, alpha0):
        return alpha0

    chi2_object = Chi2Regression(fit_function, np.array(range(len(values))), np.array(values), np.array(variances))

    minuit = Minuit(chi2_object, pedantic=False, alpha0=np.mean(values), print_level=0)
    minuit.migrad();  # perform the actual fit
    minuit_output = [minuit.get_fmin(), minuit.get_param_states()] # save the output parameters in case needed

    alpha0_fit = minuit.values['alpha0']
    sigma_alpha0_fit = minuit.errors['alpha0']
    Chi2_fit = minuit.fval # the chi2 value
    Prob_fit =  stats.chi2.sf(Chi2_fit, Ndof_calc) # The chi2 probability given N degrees of freedom (Ndof)


    print ("alpha0 = " + str(alpha0_fit) + ", sigma_alpha0_fit= " + str(sigma_alpha0_fit) + ", Chi2 = "
           + str(Chi2_fit) + ", P-val = " + str(Prob_fit))

    table1 = []
    table1.append(["mean","variance"])
    for i in range(len(values)):
        table1.append([round(values[i],3),round(variances[i],3)])

    table(table1)

    return alpha0_fit, sigma_alpha0_fit, Chi2_fit, Prob_fit
Ejemplo n.º 11
0
var = np.var(A_sick)
sigma = (np.sqrt(var))
x = np.linspace(min(A_sick), max(A_sick), 200)
bins = np.linspace(0, 30, 30)

hist, edges = np.histogram(A_sick, 30)
fig, ax1 = plt.subplots(figsize=(5, 5))

ax1.hist(A_sick, edges, histtype='step', normed=True)
ax1.plot(x, mlab.normpdf(x, mean, sigma), "-r")

ax1.set_title("A_sick")
ax1.set_xlabel("Value")
ax1.set_ylabel('Frequency')

asd = Chi2Regression(gaussian_f, bins, hist)

minuit = Minuit(asd, height=mean, width=sigma)
minuit.migrad()
minuit_output = [minuit.get_fmin(), minuit.get_param_states()]
ch2 = minuit.fval
prob = str(stats.chi2.sf(minuit.fval, len(A_sick) - 3))
ax1.legend(["Fit", "Measurement"], loc='upper right')
ax1.text(0.02,
         0.95, ("Chi 2: 2005.6" + "\nProbability: 0.4417"),
         family='monospace',
         transform=ax1.transAxes,
         fontsize=9,
         verticalalignment='top')
#print(ch2,prob,mean,sigma,"<------")
Ejemplo n.º 12
0
             ecolor='k',
             elinewidth=1,
             capsize=2,
             capthick=1)
ax1.set_title('Assignemnt 5.2 - Histogram of residuals with a Gaussian fit')
ax1.set_xlabel('Residual')
ax1.set_ylabel('Frequency / binwidth = 0.01')


# Draw Gaussian:
# -------------
def func_Gaussian(x, N, mu, sigma):
    return N * stats.norm.pdf(x, mu, sigma)


Chi2_Gaussian = Chi2Regression(func_Gaussian, x, y, sy)
minuit_Gaussian = Minuit(Chi2_Gaussian,
                         pedantic=False,
                         N=len(y),
                         mu=mu,
                         sigma=std)
minuit_Gaussian.migrad()  # perform the actual fit

chi2_gaussian = minuit_Gaussian.fval
ndof_gaussian = len(x) - len(minuit_Gaussian.args)
prob_gaussian = stats.chi2.sf(chi2_gaussian, ndof_gaussian)

xaxis = np.linspace(xmin, xmax, 1000)
yaxis = func_Gaussian(xaxis, *minuit_Gaussian.args)
ax1.plot(xaxis, yaxis, '-', label='Gaussian distribution fit')
Ejemplo n.º 13
0
                                                bins=Nbins,
                                                range=(xmin, xmax))
Hist_HitMiss_centers = 0.5 * (Hist_HitMiss_edges[1:] + Hist_HitMiss_edges[:-1])
Hist_HitMiss_error = np.sqrt(Hist_HitMiss)
Hist_HitMiss_indexes = Hist_HitMiss > 0  # Produce a new histogram, using only bins with non-zero entries

#----------------------------------------------------------------------------------
# Plot histograms on screen:
#----------------------------------------------------------------------------------

fig, ax = plt.subplots(figsize=(10, 5))
ax.set_xlabel("Random number")
ax.set_ylabel("Frequency")

chi2_object_hitmiss = Chi2Regression(
    fit_function, Hist_HitMiss_centers[Hist_HitMiss_indexes],
    Hist_HitMiss[Hist_HitMiss_indexes],
    Hist_HitMiss_error[Hist_HitMiss_indexes])
minuit_hitmiss = Minuit(chi2_object_hitmiss, p0=20.0, pedantic=False)

minuit_hitmiss.migrad()
chi2_hitmiss = minuit_hitmiss.fval
ndof_hitmiss = chi2_object_hitmiss.ndof
prob_hitmiss = stats.chi2.sf(chi2_hitmiss, ndof_hitmiss)

p0 = minuit_hitmiss.args
x_fit = np.linspace(xmin, xmax, 1000)

y_fit_simple = fit_function(x_fit, p0)
#ax.plot(x_fit, y_fit_simple, 'b-')

names = ['Hit & Miss:', 'Entries', 'Mean', 'RMS']
Ejemplo n.º 14
0
A_ill_mean, A_ill_sigma, A_ill_error_mean = mu_RMS(A_ill)


def gauss_pdf(x, mu, sigma):
    """Normalized Gaussian"""
    return 1 / np.sqrt(2 * np.pi) / sigma * np.exp(
        -(x - mu)**2 / 2. / sigma**2)


def gauss_extended(x, N, mu, sigma):
    """Non-normalized Gaussian"""
    return N * gauss_pdf(x, mu, sigma)


chi_A_ill = Chi2Regression(gauss_extended, x, y, sy)
minuit_ill = Minuit(chi_A_ill,
                    pedantic=False,
                    N=len(A_ill),
                    mu=A_ill_mean,
                    sigma=A_ill_sigma)
minuit_ill.migrad()
print(minuit_ill.fval)
#Ndof = 120-*minuit_ill.args
prob = stats.chi2.sf(minuit_ill.fval, (65 - len(minuit_ill.args)))
print(prob)

xaxis = np.linspace(0.0, 30, 1000)
yaxis = gauss_extended(xaxis, *minuit_ill.args)
names = [
    'Distribution of A ill:', 'Entries', 'Mean', 'RMS', "Chi2/Ndof", "Prob"
Ejemplo n.º 15
0
def compute_gaussian_parameters_first_peak(bins, count, snr=4, debug=False):

    temp = count.copy()
    mask = ((count / np.sqrt(count)) > snr) * (count > 0)
    temp[~mask] = 0
    peak_indices = scipy.signal.argrelmax(temp, order=4)[0]

    if not len(peak_indices) > 1:

        raise PeakNotFound('Could not detect enough peaks in the histogram\n'
                           'N_peaks found : {} \n '
                           'SNR : {} \n'.format(len(peak_indices), snr))

    x_peaks = np.array(bins[peak_indices])

    peak_distance = np.diff(x_peaks)
    peak_distance = np.mean(peak_distance) // 2
    peak_distance = peak_distance.astype(np.int)

    highest_peak_index = peak_indices[0]

    highest_peak_range = np.arange(-peak_distance, peak_distance + 1)
    highest_peak_range += highest_peak_index
    highest_peak_range[highest_peak_range < 0] = 0
    highest_peak_range[highest_peak_range >= len(count)] = len(count) + 1
    highest_peak_range = np.unique(highest_peak_range)

    bins = bins[highest_peak_range]
    count = count[highest_peak_range]

    mask = count > 0
    bins = bins[mask]
    count = count[mask]

    parameter_names = describe(gaussian)
    del parameter_names[0]

    mean = np.average(bins, weights=count)
    std = np.average((bins - mean)**2, weights=count)
    std = np.sqrt(std)
    amplitude = np.sum(count)
    parameter_init = [mean, std, amplitude]
    parameter_init = dict(zip(parameter_names, parameter_init))

    bound_names = []

    for name in parameter_names:

        bound_names.append('limit_' + name)

    bounds = [(np.min(bins), np.max(bins)), (0.5 * std, 1.5 * std),
              (0.5 * amplitude, 1.5 * amplitude)]

    bounds = dict(zip(bound_names, bounds))

    gaussian_minimizer = Chi2Regression(gaussian,
                                        bins,
                                        count,
                                        error=np.sqrt(count))

    minuit = Minuit(gaussian_minimizer,
                    **parameter_init,
                    **bounds,
                    print_level=0,
                    pedantic=False)
    minuit.migrad()

    if debug:

        plt.figure()
        plt.plot(bins, count)
        plt.plot(bins, gaussian(bins, **minuit.values))
        plt.show()

    return minuit.values, minuit.errors
Ejemplo n.º 16
0
def fit_gexp(x, y, err=None, **kwargs):
    x2reg = Chi2Regression(GExp2, x, y, err)
    m = Minuit(x2reg, **kwargs)
    m.migrad()
    #m.hesse()
    return x2reg, m
Ejemplo n.º 17
0
            ecolor='r',
            elinewidth=1,
            capsize=1,
            capthick=1)
ax.set_xlim(xmin, xmax)
ax.set_title('Assignemnt 4.1 - A for ill people')
ax.set_xlabel('Value of A for ill people')
ax.set_ylabel('Frequency / binwidth = 0.1')


#The fit:
def func_Gaussian(x, N, mu, sigma):
    return N * stats.norm.pdf(x, mu, sigma)


Chi2_object_Gaussian = Chi2Regression(func_Gaussian, x, y, sy)
minuit_Gaussian = Minuit(Chi2_object_Gaussian,
                         pedantic=False,
                         N=len(A_ill),
                         mu=A_ill_mean,
                         sigma=np.std(A_ill, ddof=1))  #
minuit_Gaussian.migrad()  # perform the actual fit

xaxis = np.linspace(xmin, xmax, 1000)
yaxis = func_Gaussian(xaxis, *minuit_Gaussian.args)
ax.plot(xaxis, yaxis, '-', label='Gaussian distribution fit')

chi2_Gaussian = minuit_Gaussian.fval
ndof_Gaussian = len(x) - len(minuit_Gaussian.args)
prob_Gaussian = stats.chi2.sf(chi2_Gaussian, ndof_Gaussian)
Ejemplo n.º 18
0
# <codecell>

def poly1(x, a0, a1):
    return a0+x*a1
def poly2(x, a0, a1, a2):
    return a0+x*(a1+x*a2)
def poly3(x, a0, a1, a2, a3):
    return a0+x*(a1+x*(a2+x*a3))
def poly4(x, a0, a1, a2, a3, a4):
    return a0+x*(a1+x*(a2+x*(a3+x*a4)))
def poly5(x, a0, a1, a2, a3, a4, a5):
    return a0+x*(a1+x*(a2+x*(a3+x*(a4+x*a5))))

# <codecell>

x2reg= Chi2Regression(poly3, tpr[j1:j2], prise[j1:j2])#, error=np.sqrt(np.abs(prise[j1:j2])))
m= Minuit(x2reg, print_level=0, pedantic=False)

# <codecell>

m.migrad()

# <codecell>

x2reg.draw(m);

# <codecell>

print m.values
c = [m.values['a3'],m.values['a2'],m.values['a1'], m.values['a0']]
c[-1]-= threshold
Ejemplo n.º 19
0
from iminuit import Minuit
from probfit import Chi2Regression

# <codecell>

def logit(x, x0, norm, tau, y0):
    return norm/(1+np.exp(-(x-x0)/tau)) + y0

# <codecell>

x= np.arange(12, 18, 0.05)
sel= (tevent.t>12)&(tevent.t<18)&(tevent.p<0.5*np.max(tevent.p))&(tevent.p>0.01*np.max(tevent.p))
plt.plot(tevent.t[sel], tevent.p[sel], 'bo-')
plt.plot(x, logit(x, 14.9, 7000, 0.49, 0), 'g-')

# <codecell>

x2reg= Chi2Regression(logit, tevent.t[sel], tevent.p[sel])
m = Minuit(x2reg, print_level=0, x0= 14.0, norm=8000, tau= 0.5, pedantic=False)
m.migrad();
print m.values

# <codecell>

x2reg.draw();

# <codecell>

x2reg.draw_residual();

x= np.array(result['npelist'])
y= result['BaF2:SL-APD9mm']
ey= result['BaF2:SL-APD9mm_err']

# <codecell>

def poly1(x, a, b):
    return a*x + b

# <codecell>

print np.log(x)

# <codecell>

x2reg = Chi2Regression(poly1, np.log(x), np.log(y), error= ey/y)

# <codecell>

mnt = Minuit(x2reg, print_level=1, a=-0.5, b=1.0, error_a=1, error_b=1)
mnt.migrad()
mnt.hesse()

# <codecell>

a= mnt.values['a']
b= mnt.values['b']
print mnt.values

# <codecell>
acc_array_b = []
error_array_a = []
error_array_b = []

#Declaring Fitting function (const. acceleration)
def fit_func(t,a,v0,s0):
    return 0.5 * a * t**2 + v0*t+s0

#Computes acceleration on 'A' side of every run
for i in range(5):

    d_a = d[0:5,0] #CHANGE THIS FOR EVERY PERSON!!!!!!!!!!
    print(d_a)
    t_a = tA[i,0:5]

    chi2_object = Chi2Regression(fit_func, t_a, d_a,error = sigma_d)
    minuit = Minuit(chi2_object, pedantic=False, a = 9.8, v0 = 16, s0 = 2)
    minuit.migrad();
    chi2_trans = minuit.fval

    acc_a = minuit.values['a']
    acc_array_a.append(acc_a)

    error_acc_a = minuit.errors['a']
    error_array_a.append(error_acc_a) #error on every full run

#PLOTTING A
#OBS - REMEMBER TITLE AND AXIS AND LIMITS
x = np.linspace(0,2,100)
fig1, ax = plt.subplots(figsize=(10,6))
ax.errorbar(t_a,d_a,sigma_d,fmt='ro',ecolor ='k',elinewidth=1,capsize=2,capthick=1)
tmp_timer_dat = []
infiles = ["data/Timer_Dat/timer_R1.dat"]
for infile in infiles:
    n, tmp_timer_dat = np.loadtxt(infile, skiprows=0, unpack=True)
    timer_C1 = np.append(timer_dat, tmp_timer_dat)
timer_dat = timer_C1

# Set data and plot
y = timer_dat
y = [x - y[0] for x in y]
y = np.array(y[1:len(y)])
n = np.linspace(1, len(y), len(y))
x = n

# Perform liner fit of measurements
chi2_object = Chi2Regression(linear, x, y)
minuit = Minuit(chi2_object, pedantic=False, a=0, b=0)  #
minuit.migrad()  # perform the actual fit

# Compute residuals
res = []
for i in range(len(y)):
    res.append(y[i] - y[i - 1])
res[0] = y[0]
res = [x - minuit.values["a"] for x in res]

#Fit residuals to gauss
minL = min(res) - 0.1
maxL = max(res) + 0.1
bins = 10
Ejemplo n.º 23
0
x = linspace(-10,10,30)
y = 3*x**2 +2*x + 1
#add some noise
y = y+randn(30)*10
errorbar(x,y,10, fmt='b.')

# <codecell>

#there is a poly2 builtin but just to remind you that you can do this
def my_poly(x, a, b, c):
    return a*x**2+ b*x+ c

# <codecell>

err = np.array([10]*30)
x2reg= Chi2Regression(my_poly, x, y, error=err)
x2reg.draw(args={'a':1,'b':2,'c':3})

# <codecell>

m = Minuit(x2reg, a=1, b=2, c=3)
m.migrad()
x2reg.show(m)

# <markdowncell>

# ###Let's do some physics
# Remeber the D mass?? Let's try to fit relativistic Breit-Wigner to it.

# <codecell>
Ejemplo n.º 24
0
                                                range=(xmin, xmax))
Hist_HitMiss_centers = 0.5 * (Hist_HitMiss_edges[1:] + Hist_HitMiss_edges[:-1])
Hist_HitMiss_error = np.sqrt(Hist_HitMiss)
Hist_HitMiss_indexes = Hist_HitMiss > 0  # Produce a new histogram, using only bins with non-zero entries

#----------------------------------------------------------------------------------
# Plot histograms on screen:
#----------------------------------------------------------------------------------

fig, ax = plt.subplots(figsize=(14, 8))
ax.set_title("Random numbers produced by a PDF")
ax.set_xlabel("Random number")
ax.set_ylabel("Frequency / binwidth = 0.01")

chi2_object_hitmiss = Chi2Regression(
    fit_func, Hist_HitMiss_centers[Hist_HitMiss_indexes],
    Hist_HitMiss[Hist_HitMiss_indexes],
    Hist_HitMiss_error[Hist_HitMiss_indexes])
minuit_hitmiss = Minuit(chi2_object_hitmiss, pedantic=False, p3=100, p4=0.24)
minuit_hitmiss.migrad()

chi2_hitmiss = minuit_hitmiss.fval
#ndof_hitmiss = chi2_object_hitmiss.ndof
ndof_hitmiss = len(Hist_HitMiss_centers[Hist_HitMiss_indexes]) - len(
    minuit_hitmiss.args)
prob_hitmiss = stats.chi2.sf(chi2_hitmiss, ndof_hitmiss)

p3, p4 = minuit_hitmiss.args
x_fit = np.linspace(xmin, xmax, 1000)
y_fit_simple = fit_func(x_fit, p3, p4)
ax.plot(x_fit, y_fit_simple, 'r-')
Ejemplo n.º 25
0
x = np.loadtxt("dage.txt", delimiter=",")

if ~np.isin(newy, y):
    y = np.append(y, newy)
    x = np.append(x, newx)

np.savetxt("dage.txt", x, delimiter=",")
np.savetxt("smittede.txt", y, delimiter=",")


def exp(x, a, b, c):
    return a * np.exp(b * x) + c


# %%
chi2_object = Chi2Regression(exp, x, y, error=None)
minuit = Minuit(chi2_object, pedantic=False, a=2, b=1, c=1, print_level=0)
minuit.migrad()  # perform the actual fit
chi2 = sum((exp(x, *minuit.args) - y)**2)

NDOF = len(x) - len(minuit.args)
chi2_prob = stats.chi2.sf(chi2, NDOF)

print(minuit.args)
print("chi2 = ", chi2)
print("chi2_prob = ", chi2_prob)
print(y)
# %%

max(x)
lin = np.linspace(0, max(x) + 2, 200)
Ejemplo n.º 26
0
def fit_pulse_simple(x, y, ey, **kwargs):
    x2reg = Chi2Regression(pulse_shape_simple, x, y, ey)
    m = Minuit(x2reg, **kwargs)
    m.migrad()
    m.hesse()
    return x2reg, m
        jd = np.asarray(jd) - tmax
    except ValueError:
        continue

    jd_valid = jd

    flux_valid = flux
    flux_err_valid = flux_err

    # Require at least 10 points with S/N over 5 for good fit
    # We want more data points than number of parameters for a valid fit

    if np.sum(flux_valid / flux_err_valid > 10) < 5:
        continue

    chi2 = Chi2Regression(zheng, jd_valid, flux_valid, error=flux_err_valid)
    m = iminuit.Minuit(chi2, A=1, error_A=0.1,
                       t0=-20, error_t0=1, limit_t0=(-30, -5),
                       tb=20.4, fix_tb=True, error_tb=1,
                       alpha_r=2.1, limit_alpha_r=(1, 3),
                       fix_alpha_r=True,
                       alpha_d=-2.52, error_alpha_d=0.15,
                       limit_alpha_d=(-4., -1.),
                       s=1.3, error_s=0.15, limit_s=(0.3, 3),
                       pedantic=True, print_level=0, errordef=1.0)
    m.set_strategy(2)
    m.migrad()
    chi2_ = chi2

    print name
    print 'Migrad ok: ', m.migrad_ok()
Ejemplo n.º 28
0

#lets define our line
#first argument has to be independent variable
#arguments after that are shape parameters
def line(x, m, c):  #define it to be parabolic or whatever you like
    return m * x + c


#We can make it faster but for this example this is plentily fast.
#We will talk about speeding things up later(you will need cython)

describe(line)

#cost function
chi2 = Chi2Regression(line, x, y, err)
#Chi^2 regression is just a callable object nothing special about it
describe(chi2)

#minimize it
#yes it gives you a heads up that you didn't give it initial value
#we can ignore it for now
minimizer = iminuit.Minuit(
    chi2)  #see iminuit tutorial on how to give initial value/range/error
minimizer.migrad()
#very stable robust minimizer
#you can look at your terminal to see what it is doing;

#lets see our results
print minimizer.values
print minimizer.errors
Ejemplo n.º 29
0
# -*- coding: utf-8 -*-
import numpy as np
from iminuit import Minuit
from matplotlib import pyplot as plt
from numpy.random import randn, seed

from probfit import Chi2Regression, linear

seed(0)
ndata = 30
x = np.linspace(-10, 10, ndata)
y = 2 * x + 5
y += randn(ndata)

x2r = Chi2Regression(linear, x, y, np.array([1.0] * ndata))

m = Minuit(x2r, m=1, c=2)

plt.figure(figsize=(8, 3))
plt.subplot(121)
x2r.draw(m)
plt.title("Before")

m.migrad()  # fit

plt.subplot(122)
x2r.draw(m)
plt.title("After")
Ejemplo n.º 30
0
            label='Income for 12 months',
            fmt='.r',
            ecolor='r',
            elinewidth=1,
            capsize=1,
            capthick=1)
ax.set_title('Assignemnt 5.1 - Monthly income for 12 months')
ax.set_xlabel('Months')
ax.set_ylabel('Income in million dollars')


def fit_function(x, alpha0, alpha1):  #So alpha0 + alpha1*x = y
    return alpha0 + alpha1 * x


chi2_object = Chi2Regression(fit_function, x_12, y_12, ey_12)
minuit = Minuit(chi2_object,
                pedantic=False,
                alpha0=-0.3,
                fix_alpha1=True,
                print_level=0)
minuit.migrad()
# perform the actual fit

Chi2_fit = minuit.fval  #The chi2 value
#Ndof_calc = chi2_object.ndof                   #The degree of freedom
Ndof_calc = len(x_12) - len(minuit.args)
Prob_fit = stats.chi2.sf(
    Chi2_fit,
    Ndof_calc)  # The chi2 probability given N degrees of freedom (Ndof)