Exemplo n.º 1
0
def plot_fmpe_fit(x, y, y_err, fitter, pixel_id=None):

    if pixel_id is None:

        pixel_id = ''

    else:

        pixel_id = str(pixel_id)

    m = fitter
    n_free_parameters = len(m.list_of_vary_param())
    n_dof = len(x) - n_free_parameters

    n_events = int(np.sum(y))
    # m.draw_contour('sigma_e', 'sigma_s', show_sigma=True, bound=5)

    x_fit = np.linspace(np.min(x), np.max(x), num=len(x) * 10)
    y_fit = fmpe_pdf_10(x_fit, **m.values)

    text = '$\chi^2 / ndof : $ {:.01f} / {}\n'.format(m.fval, n_dof)
    text += 'Baseline : {:.02f} $\pm$ {:.02f} [LSB]\n'.format(
        m.values['baseline'], m.errors['baseline'])
    text += 'Gain : {:.02f} $\pm$ {:.02f} [LSB]\n'.format(m.values['gain'],
                                                          m.errors['gain'])
    text += '$\sigma_e$ : {:.02f} $\pm$ {:.02f} [LSB]\n'.format(
        m.values['sigma_e'], m.errors['sigma_e'])
    text += '$\sigma_s$ : {:.02f} $\pm$ {:.02f} [LSB]'.format(
        m.values['sigma_s'], m.errors['sigma_s'])

    data_text = r'$N_{events}$' + ' : {}\nPixel : {}'.format(n_events,
                                                             pixel_id)

    fig = plt.figure()
    axes = fig.add_axes([0.1, 0.3, 0.8, 0.6])
    axes_residual = fig.add_axes([0.1, 0.1, 0.8, 0.2])
    axes.step(x, y, where='mid', color='k', label=data_text)
    axes.errorbar(x, y, y_err, linestyle='None', color='k')
    axes.plot(x_fit, y_fit, label=text, color='r')

    y_fit = fmpe_pdf_10(x, **m.values)
    axes_residual.errorbar(x, ((y - y_fit) / y_err), marker='o', ls='None',
                           color='k')
    axes_residual.set_xlabel('[LSB]')
    axes.set_ylabel('count')
    axes_residual.set_ylabel('pull')
    # axes_residual.set_yscale('log')
    axes.legend(loc='best')

    return fig
Exemplo n.º 2
0
    def pdf(self, x, baseline, gain, sigma_e, sigma_s, a_0, a_1):
        params = {
            'baseline': baseline,
            'gain': gain,
            'sigma_e': sigma_e,
            'sigma_s': sigma_s,
            'a_0': a_0,
            'a_1': a_1,
            'bin_width': 0
        }

        return fmpe_pdf_10(x, **params)
Exemplo n.º 3
0
    def pdf(self, x, baseline, gain, sigma_e, sigma_s, a_0, a_1, a_2, a_3, a_4,
            a_5, a_6, a_7, a_8, a_9):

        params = {
            'baseline': baseline,
            'gain': gain,
            'sigma_e': sigma_e,
            'sigma_s': sigma_s,
            'a_0': a_0,
            'a_1': a_1,
            'a_2': a_2,
            'a_3': a_3,
            'a_4': a_4,
            'a_5': a_5,
            'a_6': a_6,
            'a_7': a_7,
            'a_8': a_8,
            'a_9': a_9,
            'bin_width': 0
        }

        return fmpe_pdf_10(x, **params)
Exemplo n.º 4
0
def compute_init_fmpe(x, y, y_err, n_pe_peaks, snr=3, min_dist=5, debug=False):

    y = y.astype(np.float)
    cleaned_y = np.convolve(y, np.ones(min_dist), mode='same')
    cleaned_y_err = np.convolve(y_err, np.ones(min_dist), mode='same')
    bin_width = np.diff(x)
    bin_width = np.mean(bin_width)

    if (x != np.sort(x)).any():

        raise ValueError('x must be sorted !')

    d_y = np.diff(cleaned_y)
    indices = np.arange(len(y))
    peak_mask = np.zeros(y.shape, dtype=bool)
    peak_mask[1:-1] = (d_y[:-1] > 0) * (d_y[1:] < 0)
    peak_mask[1:-1] *= (cleaned_y[1:-1] / cleaned_y_err[1:-1]) > snr
    peak_indices = indices[peak_mask]
    peak_indices = peak_indices[:min(len(peak_indices), n_pe_peaks)]

    if len(peak_indices) <= 1:

        raise PeakNotFound('Not enough peak found for : \n'
                           'SNR : {} \t '
                           'Min distance : {} \n '
                           'Need a least 2 peaks, found {}!!'.
                           format(snr, min_dist, len(peak_indices)))

    x_peak = x[peak_indices]
    y_peak = y[peak_indices]
    gain = np.diff(x_peak)
    gain = np.average(gain, weights=y_peak[:-1])

    sigma = np.zeros(len(peak_indices))
    mean_peak_x = np.zeros(len(peak_indices))
    amplitudes = np.zeros(len(peak_indices))

    distance = int(gain / 2)

    if distance < bin_width:

        raise ValueError('Distance between peaks must be >= {} the bin width'
                         ''.format(bin_width))

    n_x = len(x)

    for i, peak_index in enumerate(peak_indices):

        left = x[peak_index] - distance
        left = np.searchsorted(x, left)
        left = max(0, left)
        right = x[peak_index] + distance + 1
        right = np.searchsorted(x, right)
        right = min(n_x - 1, right)

        amplitudes[i] = np.sum(y[left:right]) * bin_width
        mean_peak_x[i] = np.average(x[left:right], weights=y[left:right])

        sigma[i] = np.average((x[left:right] - mean_peak_x[i])**2,
                              weights=y[left:right])
        sigma[i] = np.sqrt(sigma[i] - bin_width**2 / 12)

    gain = np.diff(mean_peak_x)
    gain = np.average(gain)
    sigma_e = np.sqrt(sigma[0]**2)
    sigma_s = (sigma[1:] ** 2 - sigma_e**2) / np.arange(1, len(sigma), 1)
    sigma_s = np.mean(sigma_s)
    sigma_s = np.sqrt(sigma_s)

    params = {'baseline': mean_peak_x[0], 'sigma_e': sigma_e,
              'sigma_s': sigma_s, 'gain': gain}

    for i, amplitude in enumerate(amplitudes):

        params['a_{}'.format(i)] = amplitude

    if debug:

        x_fit = np.linspace(np.min(x), np.max(x), num=len(x)*10)

        plt.figure()
        plt.step(x, y, where='mid', color='k', label='data')
        plt.errorbar(x, y, y_err, linestyle='None', color='k')
        plt.plot(x[peak_indices], y[peak_indices], linestyle='None',
                 marker='o', color='r', label='Peak positions')
        plt.plot(x_fit, fmpe_pdf_10(x_fit, bin_width=bin_width, **params),
                 label='init', color='g')
        plt.legend(loc='best')
        plt.show()

    return params