Esempio n. 1
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
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. 3
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 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()
    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. 6
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
Esempio n. 7
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