def pyfxcor(inspec, template, vmin=-200., vmax=200., res=3, rej=1000):
    rv, cc = pyasl.crosscorrRV(inspec[0],
                               inspec[1],
                               template[0],
                               template[1],
                               vmin,
                               vmax,
                               res,
                               skipedge=rej)

    cen_gs = np.argmax(cc)
    perfx, perfy = rv[cen_gs - 5:cen_gs + 6], cc[cen_gs - 5:cen_gs + 6]

    try:
        gauss = ConstantModel() + GaussianModel()
        pars = gauss.make_params()
        pars['center'].set(value=rv[np.argmax(cc)], vary=True)
        pars['amplitude'].set(value=max(cc), vary=True)
        pars['sigma'].set(vary=True)
        pars['c'].set(value=0, vary=True)
        out = gauss.fit(perfy, pars, x=perfx)
        ct = out.best_values['center']
        cterr = out.params['center'].stderr
    except:
        return 'error', ''

    return ct, cterr
Esempio n. 2
0
def fit_peaks(
    x,
    y,
    peak_pos,
    bg="constant",
    sigma_guess=2,
    center_pm=20,
    sigma_min=0.5,
    amplitude_max_m=3.0,
    bg_pm=100,
):
    mod = ConstantModel()

    for i, p in enumerate(peak_pos):
        mod += LorentzianModel(prefix="p%s_" % i)

    pars = mod.make_params()

    for i, p in enumerate(peak_pos):
        pars["p%s_center" % i].set(p, min=p - center_pm, max=p + center_pm)
        pars["p%s_sigma" % i].set(sigma_guess, min=sigma_min)
        # pars['p%s_amplitude' % i].set(10**2, min=0.0)
        pars["p%s_amplitude" % i].set(
            amplitude_max_m * y[find_nearest_index(x, p)], min=0.0
        )

    pars["c"].set(0, min=-1 * bg_pm, max=bg_pm)

    out = mod.fit(y, pars, x=x, method="leastsq")
    out.peak_pos = peak_pos
    return out
Esempio n. 3
0
def fitgaussian_sample(sample, components, svg, verbose, center, cmin, cmax,
                       amp, amin, sigma, smin):
    '''Fits gaussian curve to dyad coverage for a single sample.'''
    print('Fits gaussian curve to dyad coverage of sample {}'.format(sample))
    input = sample + '-dyad.txt'
    dyads = pd.read_csv(input, sep='\t', index_col=0, comment='#')
    x = dyads.index.values
    y = dyads['Relative Frequency'].values
    if not amp:
        amp = dyads['Relative Frequency'].max() * 100
    if not center:
        center = 0.0
    if not sigma:
        sigma = dyads.index.max() / 2
    plt.figure()
    plt.title(sample)
    plt.xlabel('Position relative to dyad (bp)')
    plt.ylabel('Relative Frequency')
    plt.xlim(x[0], x[len(x) - 1])
    plt.xticks(list(range(x[0], x[len(x) - 1] + 1, 25)))
    plt.plot(dyads.index.values,
             dyads['Relative Frequency'].values,
             color='red')
    plot_output = sample + '-dyad-gaussian.png'
    try:
        constant = ConstantModel(prefix='c_')
        pars = constant.make_params()
        pars['c_c'].set(value=dyads['Relative Frequency'].min(),
                        min=0.0,
                        max=dyads['Relative Frequency'].max())
        gauss = GaussianModel(prefix='g_')
        pars.update(gauss.make_params())
        pars['g_center'].set(value=center, min=cmin, max=cmax)
        pars['g_sigma'].set(value=sigma, min=smin)
        pars['g_amplitude'].set(value=amp, min=amin)
        mod = constant + gauss
        init = mod.eval(pars, x=x)
        out = mod.fit(y, pars, x=x)
        if components:
            plt.plot(x, init, 'b--', label='Initial fit')
        if verbose:
            print(out.fit_report(min_correl=0.5))
        plt.plot(x, out.best_fit, 'b-', label='Best fit')
        if components:
            comps = out.eval_components(x=x)
            plt.plot(x,
                     np.repeat(comps['c_'], len(x)),
                     'g--',
                     label='Constant component')
            plt.plot(x, comps['g_'], 'm--', label='Gaussian component')
    except Exception as e:
        logging.warning(
            'could not fit gaussian curve to sample {}'.format(sample), e)
    if components:
        plt.legend(loc='lower right')
    plt.savefig(plot_output)
    if svg:
        plot_svg_output = sample + '-dyad-gaussian.svg'
        plt.savefig(plot_svg_output, transparent=True)
    plt.close()
def fit_s21mag(x_val, y_val):
    peak = GaussianModel()
    offset = ConstantModel()
    model = peak + offset
    pars = offset.make_params(c=np.median(y_val))
    pars += peak.guess(y_val, x=x_val, amplitude=-0.5)
    result = model.fit(y_val, pars, x=x_val)
    return result
Esempio n. 5
0
    def model(self):
        """Returns the sum of all peak models."""
        model = ConstantModel(prefix="BASE_")
        model.set_param_hint("c", vary=False, value=0)
        self.params += model.make_params()

        for peak in self._peaks:
            model += peak.model
        return model
Esempio n. 6
0
def fit_s21mag(x_val, y_val):
    x_val_midpoint = int(np.round(len(x_val) / 2))
    peak = GaussianModel()
    offset = ConstantModel()
    model = peak + offset
    pars = offset.make_params(c=np.median(y_val))
    pars += peak.guess(y_val,
                       x=x_val,
                       amplitude=-0.05,
                       center=x_val[x_val_midpoint])
    result = model.fit(y_val, pars, x=x_val)
    return result
    def FitSpectrumInit(self, label):
        """
        Fit the spectrum with the fit params of another spectrum (given by label) as initial values. Useful when you fit big number of similar spectra.
        """

        borders = np.genfromtxt(label + '/spectrumborders_' + label + '.txt',
                                unpack=True)
        np.savetxt(self.label + '/spectrumborders_' + self.label + '.txt',
                   borders)
        self.y = self.y[(self.x > borders[0]) & (self.x < borders[-1])]
        self.x = self.x[(self.x > borders[0]) & (self.x < borders[-1])]
        FitData = np.load(label + '/fitparams_' + label + '.npz')
        baseline = FitData['c'] / self.maxyvalue
        ctr = FitData['x0']
        sigma = FitData['sigma']
        gamma = FitData['gamma']
        ramanmodel = ConstantModel()
        ramanmodel.set_param_hint('c', value=baseline[0], min=0)

        for i in range(len(sigma)):
            prefix = 'p' + str(i + 1)
            tempvoigt = Model(func=voigt, prefix=prefix)
            tempvoigt.set_param_hint(prefix + 'x0', value=ctr[i], min=0)
            tempvoigt.set_param_hint(prefix + 'sigma', value=sigma[i], min=0)
            tempvoigt.set_param_hint(prefix + 'gamma', value=gamma[i], min=0)
            tempvoigt.set_param_hint(prefix + 'height',
                                     expr='wofz(((0) + 1j*' + prefix +
                                     'gamma) / ' + prefix +
                                     'sigma / sqrt(2)).real')
            tempvoigt.set_param_hint(prefix + 'fwhm',
                                     expr='0.5346 * 2 *' + prefix +
                                     'gamma + sqrt(0.2166 * (2*' + prefix +
                                     'gamma)**2 + (2 * ' + prefix +
                                     'sigma * sqrt(2 * log(2) ) )**2  )')
            ramanmodel += tempvoigt

        pars = ramanmodel.make_params()
        fitresult = ramanmodel.fit(self.y, pars, x=self.x, scale_covar=True)

        plt.clf()
        comps = fitresult.eval_components()
        xplot = np.linspace(self.x[0], self.x[-1], 1000)
        plt.plot(self.x, self.y * self.maxyvalue, 'r-')
        plt.plot(self.x, fitresult.best_fit * self.maxyvalue)
        for i in range(0, len(sigma)):
            plt.plot(
                self.x, comps['p' + str(i + 1)] * self.maxyvalue +
                comps['constant'] * self.maxyvalue, 'k-')
        plt.savefig(self.label + '/rawplot_' + self.label + '.pdf')
        save_modelresult(fitresult,
                         self.label + '/modelresult_' + self.label + '.sav')
        plt.clf()
Esempio n. 8
0
class CModel(Model):
    """docstring for CModel"""
    def __init__(self, nexp=0, moddef=" "):
        self.definition = moddef
        self.model = ConstantModel()
        self.nexp = 0
        self.errors = None
        self.params = None
        self.res = None
        for _ in range(nexp):
            self.add_exp()

    def add_exp(self):
        self.nexp += 1
        self.model += ExponentialModel(prefix=Prefixes[self.nexp])

    def prep_params(self):
        amp = '{}amplitude'
        dec = '{}decay'
        cntrl_expr = 'c'
        self.model.set_param_hint('c', value=1.0, min=0)
        for i in range(1, self.nexp + 1):
            currA = amp.format(Prefixes[i])
            currT = dec.format(Prefixes[i])
            self.model.set_param_hint(currA, value=1.0, min=0)
            self.model.set_param_hint(currT, value=1.0, min=0)
            cntrl_expr += ' + ' + currA

        self.params = self.model.make_params()
        self.params.add('cntrl', value=1, min=1 - 1e-5, max=1 + 1e-5)
        self.params['cntrl'].vary = True
        self.params['cntrl'].expr = cntrl_expr

    def fit(self, *args, **kwargs):
        try:
            self.prep_params()
            self.res = self.model.fit(params=self.params, *args, **kwargs)
        except Exception as e:
            print("Undefined exception while fit: {} {}".format(type(e), e),
                  file=sys.stderr)
            raise
        return self.res

    def has_covar(self):
        covar = self.res.covar
        if covar is None or np.isnan(np.sum(covar)):
            return False
        else:
            return True

    def report(self):
        return self.res.fit_report(), self.res.covar
    def FitSpectrum(self):
        """
        Fit Spectrum with initial values provided by SelectBaseline() and SelectPeaks()
        """

        polyparams = self.Fitbaseline(self)
        base = polyparams[0].n
        ramanmodel = ConstantModel()
        ramanmodel.set_param_hint('c', value=base, min=0)
        globwidth = 1

        xpeak, ypeak = np.genfromtxt(self.peakfile, unpack=True)
        if type(xpeak) == np.float64:
            xpeak = [xpeak]
            ypeak = [ypeak]

        for i in range(0, len(xpeak)):
            prefix = 'p' + str(i + 1)

            tempvoigt = Model(func=voigt, prefix=prefix)
            tempvoigt.set_param_hint(prefix + 'x0', value=xpeak[i], min=0)
            tempvoigt.set_param_hint(prefix + 'sigma', value=globwidth, min=0)
            tempvoigt.set_param_hint(prefix + 'gamma', value=globwidth, min=0)
            tempvoigt.set_param_hint(prefix + 'height',
                                     value=ypeak[i],
                                     expr='wofz(((0) + 1j*' + prefix +
                                     'gamma) / ' + prefix +
                                     'sigma / sqrt(2)).real')
            tempvoigt.set_param_hint(prefix + 'fwhm',
                                     expr='0.5346 * 2 *' + prefix +
                                     'gamma + sqrt(0.2166 * (2*' + prefix +
                                     'gamma)**2 + (2 * ' + prefix +
                                     'sigma * sqrt(2 * log(2) ) )**2  )')
            ramanmodel += tempvoigt

        pars = ramanmodel.make_params()
        fitresult = ramanmodel.fit(self.y, pars, x=self.x, scale_covar=True)

        print(fitresult.fit_report(min_correl=0.5))
        comps = fitresult.eval_components()
        xplot = np.linspace(self.x[0], self.x[-1], 1000)
        plt.plot(self.x, self.y * self.maxyvalue, 'rx')
        plt.plot(self.x, fitresult.best_fit * self.maxyvalue)
        for i in range(0, len(xpeak)):
            plt.plot(
                self.x, comps['p' + str(i + 1)] * self.maxyvalue +
                comps['constant'] * self.maxyvalue, 'k-')
        plt.show()
        plt.savefig(self.label + '/rawplot_' + self.label + '.pdf')
        save_modelresult(fitresult,
                         self.label + '/modelresult_' + self.label + '.sav')
Esempio n. 10
0
File: fit.py Progetto: 9dogs/edp
def fit_peak_df(df, model=GaussianModel, params=None, fit_range=(-np.inf, np.inf), x_field=None, fit_field='nphe2_mean', out_field='peak_fit'):
    """
    Fits DataFrame with selected peak model. Appends residuals column to DataFrame.
    """
    # Data
    fit_min, fit_max = fit_range

    df_ranged = df[(df.index > fit_min) & (df.index < fit_max)]

    if x_field:
        x = np.array(df_ranged[x_field])
        full_x = np.array(df[x_field])
    else:
        x = np.array(df_ranged.index.get_values())
        full_x = np.array(df.index.get_values())

    y = np.array(df_ranged[fit_field].values)
    full_y = np.array(df[fit_field].values)

    # Models
    if isinstance(model, str):
        try:
            model = PEAK_MODELS[model]
        except KeyError:
            print("Undefined model: {}, using default".format(model))

    peak_mod = model(prefix='peak_')
    const_mod = ConstantModel(prefix='const_')
    result_model = const_mod + peak_mod

    # Parameters
    if not params:
        pars = const_mod.make_params(c=y.min())
        pars += peak_mod.guess(y, x=x, center=0)
    else:
        pars = params

    # Fitting
    result = result_model.fit(y, params=pars, x=x)

    peak_eval = result.eval(x=full_x)
    y_res = full_y - peak_eval
    df[out_field] = pd.Series(peak_eval, index=df.index)
    df[out_field + '_res'] = pd.Series(y_res, index=df.index)

    return df, result
Esempio n. 11
0
    def gaussian_fit(self, x, y, paras=None, method=None):
        g1model = GaussianModel(prefix='g1_')
        g2model = GaussianModel(prefix='g2_')
        g3model = GaussianModel(prefix='g3_')
        cmodel = ConstantModel()

        paras_fit = g1model.guess(data=y, x=x)
        paras_fit.update(g2model.make_params())
        paras_fit.update(g3model.make_params())

        paras_fit['g1_amplitude'].set(min=0.)
        paras_fit['g2_amplitude'].set(min=0.)
        paras_fit['g3_amplitude'].set(min=0.)

        paras_fit['g1_center'].set(min=paras['g1_center'] - 300.,
                                   value=paras['g1_center'],
                                   max=paras['g1_center'] + 300.)
        paras_fit['g2_center'].set(min=paras['g2_center'] - 300.,
                                   value=paras['g2_center'],
                                   max=paras['g2_center'] + 300.)
        paras_fit['g3_center'].set(min=paras['g3_center'] - 300.,
                                   value=paras['g3_center'],
                                   max=paras['g3_center'] + 300.)

        paras_fit['g1_sigma'].set(min=100,
                                  value=paras['g1_sigma'],
                                  max=paras['g1_sigma'] + 50.)
        paras_fit['g2_sigma'].set(min=100,
                                  value=paras['g2_sigma'],
                                  max=paras['g2_sigma'] + 50.)
        paras_fit['g3_sigma'].set(min=100,
                                  value=paras['g3_sigma'],
                                  max=paras['g3_sigma'] + 50.)

        paras_fit.update(cmodel.make_params())

        model = g1model + g2model + g3model + cmodel
        result = model.fit(y, x=x, params=paras_fit, mothod=method)

        yfit = result.best_fit
        y_para = result.best_values

        residual = y - yfit

        return yfit, y_para, result, residual
Esempio n. 12
0
def test_stepmodel_erf():
    x, y = get_data()
    stepmod = StepModel(form='linear')
    const = ConstantModel()
    pars = stepmod.guess(y, x)
    pars = pars + const.make_params(c=3 * y.min())
    mod = stepmod + const

    out = mod.fit(y, pars, x=x)

    assert (out.nfev > 5)
    assert (out.nvarys == 4)
    assert (out.chisqr > 1)
    assert (out.params['c'].value > 3)
    assert (out.params['center'].value > 1)
    assert (out.params['center'].value < 4)
    assert (out.params['amplitude'].value > 50)
    assert (out.params['sigma'].value > 0.2)
    assert (out.params['sigma'].value < 1.5)
Esempio n. 13
0
def test_stepmodel_erf():
    x, y = get_data()
    stepmod = StepModel(form='linear')
    const = ConstantModel()
    pars = stepmod.guess(y, x)
    pars = pars + const.make_params(c=3*y.min())
    mod = stepmod + const

    out = mod.fit(y, pars, x=x)

    assert(out.nfev > 5)
    assert(out.nvarys == 4)
    assert(out.chisqr > 1)
    assert(out.params['c'].value > 3)
    assert(out.params['center'].value > 1)
    assert(out.params['center'].value < 4)
    assert(out.params['amplitude'].value > 50)
    assert(out.params['sigma'].value > 0.2)
    assert(out.params['sigma'].value < 1.5)
Esempio n. 14
0
def make_multiplegaussian_model(self, no_of_gauss=None):
    """ This method creates a model of multiple gaussians with an offset. The
    parameters are: 'amplitude', 'center', 'sigma', 'fwhm' and offset
    'c'. For function see:
    http://cars9.uchicago.edu/software/python/lmfit/builtin_models.html#models.LorentzianModel

    @return lmfit.model.CompositeModel model: Returns an object of the
                                              class CompositeModel
    @return lmfit.parameter.Parameters params: Returns an object of the
                                               class Parameters with all
                                               parameters for the
                                               lorentzian model.
    """

    model = ConstantModel()
    for ii in range(no_of_gauss):
        model += GaussianModel(prefix='gaussian{0}_'.format(ii))

    params = model.make_params()

    return model, params
Esempio n. 15
0
def pyfxcor(inspec, template, obj, vmin=-400., vmax=400., res=3, rej=200):
    
    rv, cc = pyasl.crosscorrRV(inspec[0], inspec[1], template[0], template[1],
                               vmin, vmax, res, skipedge=rej)
    
    cen_gs = np.argmax(cc)
    perfx, perfy = rv[cen_gs-5:cen_gs+6], cc[cen_gs-5:cen_gs+6]
    
    try:
        gauss = ConstantModel() + GaussianModel()
        pars = gauss.make_params()
        pars['center'].set(value=rv[np.argmax(cc)], vary=True)
        pars['amplitude'].set(value=max(cc), vary=True)
        pars['sigma'].set(vary=True)
        pars['c'].set(value=0, vary=True)
        out = gauss.fit(perfy, pars, x=perfx)
        ct = out.best_values['center']
        cterr = out.params['center'].stderr
    except:
        plt.plot(inspec[0], inspec[1])
        plt.savefig(obj+'.png', dpi=300)
        pl.clf()
        return 'error', ''
    
    plt.subplot(311)
    plt.plot(rv, cc)
    curraxlim = plt.axis()
    out.plot_fit(numpoints=100)
    plt.axis(curraxlim)
    plt.subplot(312)
    plt.plot(obj[1][0], obj[1][1], 'r-', linewidth=0.5)
    plt.subplot(313)
    plt.plot(inspec[0], inspec[1], 'b-', linewidth=0.5)
    plt.savefig(obj[0]+'.png', dpi=300)
    plt.clf()
    
    return ct, cterr
 def BuiltInModels(self) :
     
     FitInfo = self.FitInfo
     
     ModelString = list()
     for key in FitInfo['Models'] :
         ModelString.append((key,FitInfo['Models'][key]['model']))
     
     for Model in ModelString :
         try :
             FitModel
         except :
             if Model[1] == 'Constant' :
                 FitModel = ConstantModel(prefix=Model[0]+'_')
             if Model[1] == 'Linear' :
                 FitModel = LinearModel(prefix=Model[0]+'_')
             if Model[1] == 'Gaussian' :
                 FitModel = GaussianModel(prefix=Model[0]+'_')
             if Model[1] == 'SkewedGaussian' :
                 FitModel = SkewedGaussianModel(prefix=Model[0]+'_')
             if Model[1] == 'Voigt' :
                 FitModel = VoigtModel(prefix=Model[0]+'_')
         else :
             if Model[1] == 'Constant' :
                 FitModel = FitModel + ConstantModel(prefix=Model[0]+'_')
             if Model[1] == 'Linear' :
                 FitModel = FitModel + LinearModel(prefix=Model[0]+'_')
             if Model[1] == 'Gaussian' :
                 FitModel = FitModel + GaussianModel(prefix=Model[0]+'_')
             if Model[1] == 'SkewedGaussian' :
                 FitModel = FitModel + SkewedGaussianModel(prefix=Model[0]+'_')
             if Model[1] == 'Voigt' :
                 FitModel = FitModel + VoigtModel(prefix=Model[0]+'_')
     
     self.FitModel = FitModel
     self.ModelParameters = FitModel.make_params()
def fit_double_gaussian_sample(sample,
                               absolute=False,
                               components=False,
                               gaussian=False,
                               svg=False,
                               verbose=False,
                               center1=None,
                               cmin1=None,
                               cmax1=None,
                               amp1=None,
                               amin1=None,
                               sigma1=None,
                               smin1=None,
                               center2=None,
                               cmin2=None,
                               cmax2=None,
                               amp2=None,
                               amin2=None,
                               sigma2=None,
                               smin2=None,
                               suffix=None):
    '''Fits double gaussian curve to dyad coverage for a single sample.'''
    print('Fits double gaussian curve to dyad coverage of sample {}'.format(
        sample))
    input = sample + (suffix if suffix else '') + '-dyad.txt'
    dyads = pd.read_csv(input, sep='\t', index_col=0, comment='#')
    x = dyads.index.values
    yheader = 'Frequency' if absolute else 'Relative Frequency'
    y = dyads[yheader].values
    if not amp1:
        amp1 = dyads[yheader].max() * 50
    if not center1:
        center1 = -dyads.index.max() / 4
    if not sigma1:
        sigma1 = dyads.index.max() / 5
    if not amp2:
        amp2 = dyads[yheader].max() * 50
    if not center2:
        center2 = dyads.index.max() / 4
    if not sigma2:
        sigma2 = dyads.index.max() / 5
    plt.figure()
    plt.title(sample)
    plt.xlabel('Position relative to dyad (bp)')
    plt.ylabel('Frequency' if absolute else 'Relative Frequency')
    plt.xlim(x[0], x[len(x) - 1])
    plt.xticks(list(range(x[0], x[len(x) - 1] + 1, 25)))
    plt.plot(x, y, color='red')
    plot_output = sample + (suffix
                            if suffix else '') + '-dyad-double-gaussian.png'
    try:
        constant = ConstantModel(prefix='c_')
        pars = constant.make_params()
        pars['c_c'].set(value=dyads[yheader].min(),
                        min=0.0,
                        max=dyads[yheader].max())
        gauss1 = GaussianModel(prefix='g1_')
        pars.update(gauss1.make_params())
        pars['g1_center'].set(value=center1, min=cmin1, max=cmax1)
        pars['g1_sigma'].set(value=sigma1, min=smin1)
        pars['g1_amplitude'].set(value=amp1, min=amin1)
        gauss2 = GaussianModel(prefix='g2_')
        pars.update(gauss2.make_params())
        pars['g2_center'].set(value=center2, min=cmin2, max=cmax2)
        pars['g2_sigma'].set(value=sigma2, min=smin2)
        pars['g2_amplitude'].set(value=amp2, min=amin2)
        mod = constant + gauss1 + gauss2
        init = mod.eval(pars, x=x)
        out = mod.fit(y, pars, x=x)
        if components:
            plt.plot(x, init, 'b--', label='Initial fit')
        if verbose:
            print(out.fit_report(min_correl=0.5))
        plt.plot(x, out.best_fit, 'b-', label='Best fit')
        if gaussian:
            comps = out.eval_components(x=x)
            constant_y = comps['c_']
            plt.plot(x, [yv + constant_y for yv in comps['g1_']],
                     'm--',
                     label='Gaussian 1')
            plt.plot(x, [yv + constant_y for yv in comps['g2_']],
                     'y--',
                     label='Gaussian 2')
        if components:
            comps = out.eval_components(x=x)
            plt.plot(x,
                     np.repeat(comps['c_'], len(x)),
                     'g--',
                     label='Constant component')
            plt.plot(x, comps['g1_'], 'm--', label='Gaussian component 1')
            plt.plot(x, comps['g2_'], 'k--', label='Gaussian component 2')
    except Exception as e:
        logging.warning(
            'could not fit double gaussian curve to sample {}'.format(sample),
            e)
    if components:
        plt.legend(loc='lower right')
    plt.savefig(plot_output)
    if svg:
        plot_svg_output = sample + (suffix if suffix else
                                    '') + '-dyad-double-gaussian.svg'
        plt.savefig(plot_svg_output, transparent=True)
    plt.close()
Esempio n. 18
0
for j, d in enumerate(data):
    sigma = d[2] / 2
    if sigma == np.nan:
        continue
    y = d[3:]
    x = arange(len(y))
    y0 = np.mean([y[:200], y[-200:]])
    x0 = ((y - y0) * x).sum() / (y - y0).sum()
    mod = GaussianModel()

    pars = mod.guess(y, x=x)
    pars['sigma'].set(sigma, min=5, max=4000)
    pars['center'].set(x0, min=200, max=6500)
    #pars['amplitude'].set(y.max()/sigma,min=1,max=60536)
    bg = ConstantModel()
    pars.update(bg.make_params())
    pars['c'].set(y.min())

    model = mod + bg
    try:
        out = model.fit(y, pars, x=x)
    except:
        continue
    print(out.fit_report(min_correl=0.25))
    ax = subplot(n, m, j + 1)
    ax.tick_params(labelbottom='off')
    ax.tick_params(labelleft='off')
    plot(x, y, 'ob')
    plot(x, out.best_fit, '-r')
    res.append(out.params)
def lmfit_mngauss(x,y, *params):
    """
    Fit multiple gaussians from two spectra that are multiplied together

    INPUT:
    x - is the wavelength array
    y - is the normalized flux
    params - is a tuple of 2 list/arrays of initial guess values for the each spectras parameters
             (this controls the number of gaussians to be fitted
                 number of gaussians: len(params)/3 - 3 parameters per Gaussian)
    OUTPUT:
    mod - the lmfit model object used for the fit
    out - the lmfit fit object that contains all the results of the fit
    init- array with the initial guess model (usefull to see the initial guess when plotting)
    """
    
    m_params = params[0]
    
    m_mods = []
    prefixes = []
    for i in range(0, len(m_params), 3):
        pref = "gm%02i_" % (i/3)
        gauss_i = GaussianModel(prefix=pref)

        if i == 0:
            pars = gauss_i.guess(y, x=x)
        else:
            pars.update(gauss_i.make_params())
    
        A = m_params[i]
        l_cen = m_params[i+1]
        sigma = m_params[i+2]

        pars[pref+'amplitude'].set(A)
        pars[pref+'center'].set(l_cen)
        pars[pref+'sigma'].set(sigma)

        m_mods.append(gauss_i)
        prefixes.append(pref)
    
    m_mod = m_mods[0]
    if len(m_mods) > 1:
      for m in m_mods[1:]:
            m_mod += m

    m_one = ConstantModel(prefix="m_one_")
    prefixes.append("m_one_")
    pars.update(m_one.make_params())
    pars['m_one_c'].set(value=1, vary=False)

    try: 
        n_params = params[1]
        n_mods = []
        #prefixes = []
        for j in range(0, len(n_params), 3):
            pref = "gn%02i_" % (j/3)
            gauss_j = GaussianModel(prefix=pref)
            pars.update(gauss_j.make_params())
        
            A = n_params[j]
            l_cen = n_params[j+1]
            sigma = n_params[j+2]

            pars[pref+'amplitude'].set(A)
            pars[pref+'center'].set(l_cen)
            pars[pref+'sigma'].set(sigma)

            n_mods.append(gauss_j)
            prefixes.append(pref)
        
        n_mod = n_mods[0]
        if len(n_mods) > 1:
            for n in n_mods[1:]:
                n_mod += n
        
        n_one = ConstantModel(prefix="n_one_")
        prefixes.append("n_one_")
        pars.update(n_one.make_params())
        pars['n_one_c'].set(value=1, vary=False)

        mod = (m_one + m_mod) * (n_one + n_mod)
    except:
    	print("Error with second spectra, only fitting first")
        mod = m_one + m_mod
    
    

    init = mod.eval(pars, x=x)
    out = mod.fit(y, pars, x=x)
    
    print("Printed prefixes", prefixes)
    #print(init)
    return mod, out, init
Esempio n. 20
0
from qcodes.plots.qcmatplotlib import MatPlot
from qcodes.plots.pyqtgraph import QtPlot
from scipy.optimize import curve_fit
import scipy.integrate as integrate
import pandas as pd
import matplotlib.pyplot as plt
from lmfit.models import LorentzianModel, ConstantModel, GaussianModel

pd_dat = pd.read_csv(
    'Scripts and PPT Summary/CryoRX/2020-06-22/18-15-29_qtt_scan1D/RP1.dat',
    skiprows=[0, 2],
    delimiter='\t')

xval = pd_dat['# "RP1"']
yval = pd_dat['S21mag']

peak = GaussianModel()
offset = ConstantModel()
model = peak + offset

pars = offset.make_params(c=np.median(yval))
pars += peak.guess(yval, x=xval, amplitude=-0.5)
result = model.fit(yval, pars, x=xval)

x = [[1 + 1.j * 1], [1 + 1.j * 100]]
print(np.mean(x))
print(abs(result.values['height']))

plt.plot(xval, yval)
plt.plot(xval, result.best_fit, 'b--')
plt.show()
Esempio n. 21
0
amplitude1= 300
amplitude2= 300

sigma=0.4
sigma1=0.15
sigma2= 0.4

c=856.0

for filename in files:
	x,y = np.loadtxt(direction + filename, unpack=True)
	
	pars= L0_mod.make_params(center=center+1.0, amplitude=amplitude, sigma=sigma) 
	pars+=L1_mod.make_params(center=center1, amplitude= amplitude1, sigma=sigma1)
	pars+=L2_mod.make_params(center=center2, amplitude= amplitude2, sigma=sigma2, max=2*sigma2 )
	pars+=c_mod.make_params(c=c)

	mod =L0_mod + c_mod + L1_mod + L2_mod

	#Aparecen picos extra a partir de estos archivos
	if float(filename)>=20.50:
		if float(filename)==20.50:
			pars+=L3_mod.make_params(center= center1-0.5, amplitude= amplitude1, sigma=sigma1)
			pars+=L4_mod.make_params(center=center2-1.5, amplitude= amplitude2, sigma=sigma2)
		else:
			pars+=L3_mod.make_params(center= center3, amplitude= amplitude3, sigma=sigma3)
			pars+=L4_mod.make_params(center=center4, amplitude= amplitude4, sigma=sigma4)

		mod +=L3_mod + L4_mod
		pass
Esempio n. 22
0
    inicio = ind = list(abs(x - 805)).index(np.nanmin(abs(x - 805)))
    ind = list(abs(x - 815)).index(np.nanmin(abs(x - 815)))
    cavity_y = y[ind:]
    cavity_x = x[ind:]

    y = y[inicio:ind]
    x = x[inicio:ind]

    #Semillas que se dan iterativamente
    pars = L0_mod.make_params(center=center, amplitude=amplitude, sigma=sigma)
    pars += L1_mod.make_params(center=center1,
                               amplitude=amplitude1,
                               sigma=sigma1)

    pars2 = L2_mod.guess(cavity_y, x=cavity_x)
    pars += c_mod.make_params(c=c)
    pars2 += c2_mod.make_params(c=c)

    #bound_parameters_sigma(pars,2,5)

    #Defino funcion
    mod = L0_mod + c_mod + L1_mod  #+  L2_mod
    mod2 = L2_mod + c2_mod
    #Fiteo
    out = mod.fit(y, pars, x=x)
    out_cavity = mod2.fit(cavity_y, pars2, x=cavity_x)

    #Imprimo el archivo fit log
    fit_log.write("\n\n\n\n\n\n Fitted from: %s%s \n" % (direction, filename))
    now = datetime.datetime.now()
    fit_log.write(
Esempio n. 23
0
class CModel(Model):
    """docstring for CModel"""
    def __init__(self, nexp=0, sum_one=False):
        self.sum_one_flag = sum_one
        self.model = ConstantModel()
        self.nexp = 0
        self.errors = None
        self.params = None
        self.res = None
        for _ in range(nexp):
            self.add_exp()

    def add_exp(self):
        self.nexp += 1
        self.model += ExponentialModel(prefix=Prefixes[self.nexp])


    def prep_params(self, tcf_type):
        if tcf_type == 'acf':
            self.prep_acfParams()
        elif tcf_type == 'ccf':
            self.prep_ccfParams()

    def prep_ccfParams(self):
        amp = '{}amplitude'
        dec = '{}decay'
        self.model.set_param_hint('c', value=1.0)
        for i in range(1, self.nexp + 1):
            currA = amp.format(Prefixes[i])
            currT = dec.format(Prefixes[i])
            self.model.set_param_hint(currA, value=1, min=-1.5, max=1.5)
            self.model.set_param_hint(currT, value=1, min=0)

        self.params = self.model.make_params()

    def prep_acfParams(self):
        amp = '{}amplitude'
        dec = '{}decay'
        cntrl_expr = ' '
        if self.sum_one_flag:
            cntrl_expr = 'c'
        self.model.set_param_hint('c', value=1.0, min=0)
        for i in range(1, self.nexp + 1):
            currA = amp.format(Prefixes[i])
            currT = dec.format(Prefixes[i])
            self.model.set_param_hint(currA, value=1.0, min=0.0)
            self.model.set_param_hint(currT, value=1.0, min=0.0)
            if self.sum_one_flag:
                cntrl_expr += ' + ' + currA

        self.params = self.model.make_params()
        if self.sum_one_flag:
            self.params.add('cntrl', value= 1, max= 1+1e-5, min= 1-1e-5)
            self.params['cntrl'].vary = True
            self.params['cntrl'].expr = cntrl_expr


    def fit(self, tcf_type='acf', *args, **kwargs):
        try:
            self.prep_params(tcf_type)
            self.res = self.model.fit(params=self.params, *args, **kwargs)
        except Exception as e:
            print("Undefined exception while fit: {} {}".format(type(e), e), file=sys.stderr)
            raise
        return self.res

    def has_covar(self):
        covar = self.res.covar
        if covar is None or np.isnan(np.sum(covar)):
            return False
        else:
            return True

    def check_errors(self):
        for ivar, name in enumerate(self.res.var_names):
            par = self.res.params[name]
            if par.stderr / par.value > 1:
                return False
        return True

    def report(self):
        return self.res.fit_report(), self.res.covar