Ejemplo n.º 1
0
def get_amp_first_harmonic(a, tes, freq_mod):
    """
    This function takes the signal of a given TES, makes its spectrum
    and get the amplitude of the first harmonic that should be around
    the modulation frequency of the source.

    Parameters
    ----------
    a : qubicpack object
    tes : int
        tes number
    freq_mod : float
        modulation frequency of the external source

    Returns
    -------

    """
    data = a.timeline(TES=tes)
    t_data = a.timeline_timeaxis(axistype='pps')
    FREQ_SAMPLING = 1. / (t_data[1] - t_data[0])
    spectrum_f, freq_f = mlab.psd(data,
                                  Fs=FREQ_SAMPLING,
                                  NFFT=len(data),
                                  window=mlab.window_hanning)
    amp_peak = np.interp(freq_mod, freq_f, spectrum_f)
    okfit = np.abs(freq_f - freq_mod) < 0.1

    guess = np.array([
        freq_mod, 0.01,
        np.max(spectrum_f[okfit]),
        np.median(spectrum_f[okfit])
    ])

    res = ft.do_minuit(freq_f[okfit],
                       spectrum_f[okfit],
                       np.ones(np.sum(okfit)),
                       guess,
                       functname=dl.gauss,
                       fixpars=[1, 0, 0, 0, 0],
                       nohesse=True,
                       force_chi2_ndf=True)

    return t_data, data, FREQ_SAMPLING, freq_f, spectrum_f, amp_peak, okfit, res
Ejemplo n.º 2
0
 def minuit(self,
            p0=None,
            chi2=None,
            verbose=True,
            print_level=0,
            ncallmax=10000,
            extra_args=None,
            nsplit=1,
            return_chi2fct=False):
     if p0 is None:
         p0 = self.p0
     if verbose & (print_level > 1):
         print('About to call Minuit with chi2:')
         print(chi2)
         print('Initial parameters, fixed and bounds:')
         for i in range(len(p0)):
             print(
                 'Param {0:}: init={1:6.2f} Fixed={2:} Range=[{3:6.3f}, {4:6.3f}]'
                 .format(i, p0[i], self.fixedpars[i], self.flatprior[i][0],
                         self.flatprior[i][1]))
     self.fitresult_minuit = ft.do_minuit(self.xvals,
                                          self.yvals,
                                          self.covar,
                                          p0,
                                          functname=self.model,
                                          fixpars=self.fixedpars,
                                          rangepars=self.flatprior,
                                          verbose=verbose,
                                          chi2=self.chi2,
                                          print_level=print_level,
                                          ncallmax=ncallmax,
                                          extra_args=extra_args,
                                          nsplit=nsplit)
     if len(self.fitresult_minuit[3]) == 0:
         cov = np.diag(self.fitresult_minuit[2])
     else:
         cov = self.fitresult_minuit[3]
     if return_chi2fct:
         return self.fitresult_minuit[1], cov, self.fitresult_minuit[6]
     else:
         return self.fitresult_minuit[1], cov
Ejemplo n.º 3
0
def fit_sb(flatmap_init,
           az_init,
           el_init,
           model,
           newsize=70,
           dmax=5.,
           az_center=0.,
           el_center=50.,
           doplot=False,
           resample=False,
           verbose=False,
           extra_title='',
           return_fitted=False,
           precision=None,
           nsiglo=1.,
           nsighi=3.,
           figsave=None):
    #### If requested, resample the iage in order to speedup the fitting
    if resample:
        ### Resample input map to have less pixels to deal with for fitting
        flatmap = scsig.resample(scsig.resample(flatmap_init, newsize, axis=0),
                                 newsize,
                                 axis=1)
        az = np.linspace(np.min(az_init), np.max(az_init), newsize)
        el = np.linspace(np.min(el_init), np.max(el_init), newsize)
    else:
        flatmap = flatmap_init
        az = np.array(az_init)
        el = np.array(el_init)
    az2d, el2d = np.meshgrid(az * np.cos(np.radians(el_center)), np.flip(el))

    # if verbose:
    # 	print('fit_sb: Model Name = ',model.name)
    # 	print('Initial Parameters:')
    # 	model.print_start()

    ### First find the location of the maximum closest to the center
    distance_max = dmax
    mask = np.array(
        np.sqrt((az2d - az_center)**2 +
                (el2d - el_center)**2) < distance_max).astype(int)
    ### We use a smoothed version of the map in order to avoid glitches
    smoothed_flatmap = f.gaussian_filter(flatmap, 2.)
    wmax = np.where((smoothed_flatmap * mask) == np.max(smoothed_flatmap *
                                                        mask))
    maxval = flatmap[wmax][0]
    # print('Maximum of map is {0:5.2g} and was found at: az={1:5.2f}, el={2:5.2f}'.format(maxval,az2d[wmax][0], el2d[wmax][0]))

    ### Get the fixed parameters
    fixpars = model.fixpars

    ### Create range for the fitting around the initial values
    ranges = model.ranges.T

    ### Update initial parameters with the values found on the map
    parsinit = model.startpars
    parsinit[0] = az2d[wmax][0]
    parsinit[1] = el2d[wmax][0]
    parsinit[9] = maxval
    if model.name == 'SbModelIndepPeaksAmp':
        parsinit[9:] = maxval
        ranges[9:, 1] = maxval * 2
    elif model.name == 'SbModelIndepPeaksAmpFWHM':
        for i in range(model.npeaks):
            parsinit[9 + 2 * i] = maxval
            ranges[9 + 2 * i, 1] = maxval * 2
    elif model.name == 'SbModelIndepPeaks':
        for i in range(model.npeaks):
            parsinit[9 + 4 * i] = maxval
            ranges[9 + 4 * i, 1] = np.abs(maxval) * 2

    ### Run the fitting
    x = [az2d, el2d]
    mm, ss = ft.meancut(flatmap, 3)
    if verbose:
        print('Running Minuit with model: {}'.format(model.name))
        model.print_start()
    mychi2 = ft.MyChi2_nocov(x, np.ravel(flatmap),
                             np.zeros_like(np.ravel(flatmap)) + ss, model)
    fit = ft.do_minuit(x,
                       np.ravel(flatmap),
                       np.zeros_like(np.ravel(flatmap)) + ss,
                       parsinit,
                       functname=model,
                       chi2=mychi2,
                       rangepars=ranges,
                       fixpars=fixpars,
                       force_chi2_ndf=False,
                       verbose=False,
                       nohesse=True,
                       precision=precision)
    fitpars = fit[1]
    fiterrs = fit[2]

    ### Get the peaks positions and amplitudes
    themap, newxxyy = model(x, fitpars, return_peaks=True)
    ### Put the fitted amplitude values to zero when needed (when peak ouside the input image)
    if model.name == 'SbModelIndepPeaksAmp':
        xmin = np.min(az2d)
        xmax = np.max(az2d)
        ymin = np.min(el2d)
        ymax = np.max(el2d)
        for i in range(model.npeaks):
            if (((newxxyy[0, i] < xmin) or (newxxyy[0, i] > xmax))
                    or ((newxxyy[1, i] < ymin) or (newxxyy[1, i] > ymax))):
                fitpars[9 + i] = 0
                fiterrs[9 + i] = 0
        ### Now get the map again with updated parameters
        themap, newxxyy = model(x, fitpars, return_peaks=True)
    elif model.name == 'SbModelIndepPeaksAmpFWHM':
        xmin = np.min(az2d)
        xmax = np.max(az2d)
        ymin = np.min(el2d)
        ymax = np.max(el2d)
        for i in range(model.npeaks):
            if (((newxxyy[0, i] < xmin) or (newxxyy[0, i] > xmax))
                    or ((newxxyy[1, i] < ymin) or (newxxyy[1, i] > ymax))):
                fitpars[9 + 2 * i] = 0
                fiterrs[9 + 2 * i] = 0
        ### Now get the map again with updated parameters
        themap, newxxyy = model(x, fitpars, return_peaks=True)
    elif model.name == 'SbModelIndepPeaks':
        xmin = np.min(az2d)
        xmax = np.max(az2d)
        ymin = np.min(el2d)
        ymax = np.max(el2d)
        for i in range(model.npeaks):
            if (((newxxyy[0, i] < xmin) or (newxxyy[0, i] > xmax))
                    or ((newxxyy[1, i] < ymin) or (newxxyy[1, i] > ymax))):
                fitpars[9 + 4 * i] = 0
                fiterrs[9 + 4 * i] = 0

    if verbose:
        print('===========================================================')
        print('Fitted values:')
        print('-----------------------------------------------------------')
        for i in range(len(parsinit)):
            print('{0:<20}: {1:>12.6f} +/- {2:>12.6f}'.format(
                model.parnames[i], fitpars[i], fiterrs[i]))
        print('-----------------------------------------------------------')
        print('Residuals**2/pix : {0:^8.5g}'.format(
            np.sum((flatmap - themap)**2) / np.size(flatmap)))
        print('===========================================================')

    if doplot:
        rc('figure', figsize=(18, 4))
        sh = np.shape(newxxyy)
        mm, ss = ft.meancut(flatmap, 3)

        subplot(1, 4, 1)
        imshow(themap,
               extent=[
                   np.min(az) * np.cos(np.radians(50)),
                   np.max(az) * np.cos(np.radians(50)),
                   np.min(el),
                   np.max(el)
               ],
               vmin=mm - ss,
               vmax=mm + 10 * ss)
        colorbar()
        title('Fitted Map ' + extra_title)
        xlabel('Angle in Az direction [deg.]')
        ylabel('Elevation [deg.]')

        mm, ss = ft.meancut(flatmap - themap, 3)
        subplot(1, 4, 2)
        imshow(flatmap,
               extent=[
                   np.min(az) * np.cos(np.radians(50)),
                   np.max(az) * np.cos(np.radians(50)),
                   np.min(el),
                   np.max(el)
               ],
               vmin=mm - nsiglo * ss,
               vmax=mm + nsighi * ss)
        xlim(
            np.min(az) * np.cos(np.radians(50)),
            np.max(az) * np.cos(np.radians(50)))
        ylim(np.min(el), np.max(el))
        colorbar()

        for i in range(sh[1]):
            ax = plot(newxxyy[0, i], newxxyy[1, i], 'r.')
        title('Input Map ' + extra_title)
        xlabel('Angle in Az direction [deg.]')
        ylabel('Elevation [deg.]')

        subplot(1, 4, 3)
        imshow(themap,
               extent=[
                   np.min(az) * np.cos(np.radians(50)),
                   np.max(az) * np.cos(np.radians(50)),
                   np.min(el),
                   np.max(el)
               ],
               vmin=mm - nsiglo * ss,
               vmax=mm + nsighi * ss)
        colorbar()
        title('Fitted Map ' + extra_title)
        xlabel('Angle in Az direction [deg.]')
        ylabel('Elevation [deg.]')

        subplot(1, 4, 4)
        imshow(flatmap - themap,
               extent=[
                   np.min(az) * np.cos(np.radians(50)),
                   np.max(az) * np.cos(np.radians(50)),
                   np.min(el),
                   np.max(el)
               ],
               vmin=mm - nsiglo * ss,
               vmax=mm + nsighi * ss)
        colorbar()
        title('Residual Map ' + extra_title)
        xlabel('Angle in Az direction [deg.]')
        ylabel('Elevation [deg.]')
        tight_layout()

        if figsave:
            savefig(figsave)
        show()

    if return_fitted:
        return fit, newxxyy, themap
    else:
        return fit, newxxyy
Ejemplo n.º 4
0
# set values for fold plot
pars = [dc, 0.05, 0., 1.2]
# theTES=45
# plot folded TES data
FoldedFiltTES(tt, pars, theTES, folded, folded_notch)

### Plot it along with a guess for fiber signal
#### Now fit the fiber signal
#### NB errors come from renormalizing chi2/ndf to 1
guess = [dc, 0.06, 0., 1.2]
fit_info = ft.do_minuit(tt,
                        folded[theTES, :],
                        np.ones(len(tt)),
                        guess,
                        functname=ft.simsig,
                        rangepars=[[0., 1.], [0., 1], [0., 1], [0., 1]],
                        fixpars=[0, 0, 0, 0],
                        force_chi2_ndf=True,
                        verbose=False,
                        nohesse=True)
# plot the free fit
FoldedTESFreeFit(tt, fit_info, theTES, folded)

##################################################
# ## Now do a kind a multipass analysis where
# ## TES exhibiting nice signal are manually picked
# ## I tried an automated algorithm but it was not
# ## very satisfying...
# ## Running the following with the keyword
# ## reselect_ok = True
# ## will go through all TES and ask for a [y] if it