예제 #1
0
def get_db_pixel(tths, xs, ys):
    """Get direct beam pixel at TTH = 0 degrees. This is done by taking a 
    total of 40 images around TTH = 0, finding the direct beam pixel for each of them
    and fitting these positions to a line to get the direct beam pixel position at TTH = 0

    Arguments:
        tths {[float]} -- array of 2th values
        xs {[float]} -- array of the x positions of the direct beam pixel
        ys {[float]} -- array of the y positions of the direct beam pixel

    Returns:
        tuple -- x0, y0 (direct beam pixel position at 2th = 0)
    """

    n0 = len(tths)//2
    s_ = np.s_[n0-20:n0+20]

    xs, ys, tths = xs[s_], ys[s_], tths[s_]

    mod_xs = LinearModel()
    params_xs = mod_xs.guess(xs, x=tths)
    fit_xs = mod_xs.fit(xs, params=params_xs, x=tths)
    fit_xs = mod_xs.fit(xs, params=fit_xs.params, x=tths)

    mod_ys = LinearModel()
    params_ys = mod_ys.guess(ys, x=tths)
    fit_ys = mod_ys.fit(ys, params=params_ys, x=tths)
    fit_ys = mod_ys.fit(ys, params=fit_ys.params, x=tths)
    
    x0 = fit_xs.eval(params=fit_xs.params, x=0.0)
    y0 = fit_ys.eval(params=fit_ys.params, x=0.0)

    return x0, y0
예제 #2
0
def poly_gaussian():
    gauss1 = Model(gaussian, independent_vars=['x'], prefix='gauss1_')
    gauss2 = Model(gaussian, independent_vars=['x'], prefix='gauss2_')
    gauss3 = Model(gaussian, independent_vars=['x'], prefix='gauss3_')
    gauss4 = Model(gaussian, independent_vars=['x'], prefix='gauss4_')
    linear1 = LinearModel(independent_vars=['x'], prefix='linear1_')
    linear2 = LinearModel(independent_vars=['x'], prefix='linear2_')
    model = gauss1 + gauss2 + linear1 + gauss3 + linear2 + gauss4
    return model
예제 #3
0
파일: models.py 프로젝트: rhroberts/kfit
def line_mod(N):
    '''
        Returns a model consisting of N lines
    '''
    # initialize model
    model = LinearModel(prefix='lin1_')
    # Add N-1 lines
    for i in range(N - 1):
        model += LinearModel(prefix='lin' + str(i + 2) + '_')
    return model
예제 #4
0
    def pulse_areas(self):
        """
        Obtains the area of a pulse by fitting an ExponentialGaussian
        and with a linear background to the data.
        """
        shape = ExponentialGaussianModel()
        line = LinearModel()
        model = shape + line

        result = []

        for index, pulse in enumerate(self.pulses):
            if len(pulse[0]) < 10:
                pass
            else:
                x = self.pulse_headers[index]['offset']
                pars = model.make_params(gamma=0.02,
                                         sigma=5,
                                         center=15,
                                         amplitude=max(pulse[0]) * 1000,
                                         intercept=pulse[0][0],
                                         slope=1e-12)
                out = model.fit(pulse[0], pars, x=x)
                comps = out.eval_components()
                result.append(simps(comps['expgaussian'], x))

        return result
예제 #5
0
def find_peaks(filename,
               show_plots=False):  #subtract background and find peaks
    num_samp_left = 200
    num_samp_right = 200

    data = np.genfromtxt(filename)
    x = data[:, 0]
    y = data[:, 1]
    x_bg = np.hstack([x[:num_samp_left], x[-num_samp_right:]])
    y_bg = np.hstack([y[:num_samp_left], y[-num_samp_right:]])
    model = LinearModel()
    params = model.guess(y_bg, x=x_bg)
    out = model.fit(y_bg, x=x_bg, params=params)
    if show_plots:
        plt.plot(x, y)
        plt.plot(x_bg, y_bg, '.')
    y_fit = out.model.func(x, **out.best_values)
    data = y - y_fit
    if show_plots:
        plt.plot(x, data)
        plt.show()
    indexes = peakutils.indexes(-data, thres=0.25, min_dist=65)
    print(indexes)
    pplot(x, data, indexes)
    peaks_x = peakutils.interpolate(x, data, ind=indexes)
    print(peaks_x)
예제 #6
0
def correct_data(xData, yData, startIdx=0, endIdx=-1):
    y = yData
    # start x at zero
    x = xData - xData[0]

    # linear model
    lr = LinearModel()
    params = lr.make_params()

    # fit model
    xSelection = x[startIdx:endIdx]
    ySelection = y[startIdx:endIdx]
    outParams = lr.fit(ySelection, params, x=xSelection)

    # construct corrected data
    linear_trend = x * outParams.best_values['slope'] + outParams.best_values[
        'intercept']
    yCorrected = y - linear_trend + y[0]

    result = {
        "correctedData":
        json.loads(
            pd.DataFrame({
                "x": xData.tolist(),
                "y": yCorrected.tolist()
            }).to_json(orient='records'))
    }
    return result
예제 #7
0
    def fit(self, xx, yy, fitType):
        xx = np.asarray(xx)
        yy = np.asarray(yy)
        print("XX", xx)
        print("YY", yy)
        print(len(xx))
        print(len(yy))
        print("XX", xx)
        x1 = xx[0]
        x2 = xx[-1]
        y1 = yy[0]
        y2 = yy[-1]
        m = (y2 - y1) / (x2 - x1)
        b = y2 - m * x2

        if fitType == "Gaussian":
            mod = GaussianModel()
        elif fitType == "Lorentzian":
            mod = LorentzianModel()
        else:
            mod = VoigtModel()

        pars = mod.guess(yy, x=xx, slope=m)
        print(pars)
        mod = mod + LinearModel()
        pars.add('intercept', value=b, vary=True)
        pars.add('slope', value=m, vary=True)
        out = mod.fit(yy, pars, x=xx)

        return out.best_fit
예제 #8
0
def find_fit_sigmoid(x, y):
    model_gompertz = lm.models.Model(gompertz)
    params_gompertz = lm.Parameters()
    params_gompertz.add('asymptote', value=1E-3, min=1E-8)
    params_gompertz.add('displacement', value=1E-3, min=1E-8)
    params_gompertz.add('step_center', value=1E-3, min=1E-8)

    result_gompertz = model_gompertz.fit(y, params_gompertz, x=x)

    step_mod = StepModel(form='erf', prefix='step_')
    line_mod = LinearModel(prefix='line_')

    params_stln = line_mod.make_params(intercept=y.min(), slope=0)
    params_stln += step_mod.guess(y, x=x, center=90)

    model_stln = step_mod + line_mod
    result_stln = model_stln.fit(y, params_stln, x=x)

    ret_result = None
    ret_model = None

    if result_stln.chisqr < result_gompertz.chisqr:
        ret_result = result_stln
        ret_model = model_stln
    else:
        ret_result = result_gompertz
        ret_model = model_gompertz

    return ret_result, ret_model
예제 #9
0
    def guess(self, data, x=None, **kwargs):
        lm = LinearModel()
        y_slope = lm.eval(x=x, params=lm.guess(np.abs(data), x=x))
        center, hwhm, height = guess_peak(np.abs(np.abs(data) - y_slope), x=x)

        pars = self.make_params(Ms=height, B_res=center, dB=hwhm)
        return pars
예제 #10
0
def MTF(Y, X):
    """
    Fit a polynomial to the MTF curve
    """
    pow_mod = PowerLawModel(prefix='pow_')
    lin_mod = LinearModel(prefix="lin_")
    const_mod = Model(sigmoid)
    poly_mod = PolynomialModel(3)
     
    #X = list(reversed(X))
     
    pars = poly_mod.guess(Y, x=X) + lin_mod.guess(Y, x=X)
    model = poly_mod + lin_mod
     
    result = model.fit(Y, pars, x=X)
    # write error report
    print result.fit_report()
     
    c0 = result.best_values['c0']
    c1 = result.best_values['c1']
    c2 = result.best_values['c2']
    slop = result.best_values['lin_slope']
    inter = result.best_values['lin_intercept']
#     c3 = result.best_values['c3']
#     c4 = result.best_values['c4']
#     c5 = result.best_values['c5']
#     c6 = result.best_values['c6']
#     A = result.best_values["amplitude"]
#     k = result.best_values["exponent"]
        
    limit = polynomial(c0,c1,c2,inter,slop,10.)
#     limit = A*9**k
    return result.best_fit, limit
예제 #11
0
def rotational_temperature_analysis(L, E_upper):
    """
    Function that will perform a rotational temperature analysis. This will perform a least-squares fit of log(L),
    which is related to the theoretical line strength and integrated flux, and the upper state energy for the same
    transition.

    Parameters
    ----------
    L - 1D array
        Value L related to the line and theoretical line strength
    E_upper - 1D array
        The upper state energy in wavenumbers.

    Returns
    -------
    ModelResult - object
        Result of the least-squares fit
    """
    # Convert the upper state energy
    E_upper *= units.kbcm
    logL = np.log(L)
    model = LinearModel()
    params = model.make_params()
    result = model.fit(x=E_upper, y=logL, params=params)
    return result
예제 #12
0
def line_fit(x, y, errors=True):
    """
    Simple helper function that speeds up line fitting. Uses lmfit
    
    Parameters
    ----------
    x, y (float)
        Sample length x, y arrays of data to be fitted

    Returns
    -------
    Returns slope and intercept, with uncertainties (use uncertainties package if availabe)
    Also returns fit object out, can be dropped
    """
    from lmfit.models import LinearModel

    mod = LinearModel()
    par = mod.guess(y, x=x)
    out = mod.fit(y, par, x=x)

    s = out.params["slope"]
    i = out.params["intercept"]

    if errors:
        try:
            from uncertainties import ufloat

            return ufloat(s.value, s.stderr), ufloat(i.value, i.stderr), out
        except:
            return s.value, s.stderr, i.value, i.stderr, out
    else:
        return s.value, i.value, out
    def twoPeakLorentzianFit(self):
        try:
            nRow, nCol = self.dockedOpt.fileInfo()

            self.gausFit.binFitData = zeros((nRow, 0))
            self.gausFit.TwoPkGausFitData = zeros((nCol, 12))  # Creates the empty 2D List
            for j in range(nCol):
                yy1 = []
                yy2 = []
                yy = self.dockedOpt.TT[:, j]
                i = 0
                for y in yy:
                    if i < len(yy)/2:
                        yy1.append(y)
                    else:
                        yy2.append(y)
                    i += 1

                xx = arange(0, len(yy))
                xx1 = arange(0, len(yy)/2)
                xx2 = arange(len(yy)/2, len(yy))

                x1 = xx[0]
                x2 = xx[-1]
                y1 = yy[0]
                y2 = yy[-1]
                m = (y2 - y1) / (x2 - x1)
                b = y2 - m * x2

                mod1 = LorentzianModel(prefix='p1_')
                mod2 = LorentzianModel(prefix='p2_')

                pars1 = mod1.guess(yy1, x=xx1)
                pars2 = mod2.guess(yy2, x=xx2)
                mod = mod1 + mod2 + LinearModel()
                pars = pars1 + pars2

                pars.add('intercept', value=b, vary=True)
                pars.add('slope', value=m, vary=True)
                out = mod.fit(yy, pars, x=xx, slope=m)



                self.gausFit.TwoPkGausFitData[j, :] = (out.best_values['p1_amplitude'], 0, out.best_values['p1_center'],
                                                       0, out.best_values['p1_sigma'], 0,
                                                       out.best_values['p2_amplitude'], 0, out.best_values['p2_center'],
                                                       0, out.best_values['p2_sigma'], 0)

                # Saves fitted data of each fit
                fitData = out.best_fit
                binFit = np.reshape(fitData, (len(fitData), 1))
                self.gausFit.binFitData = np.concatenate((self.gausFit.binFitData, binFit), axis=1)

                if self.gausFit.continueGraphingEachFit == True:
                    self.gausFit.graphEachFitRawData(xx, yy, out.best_fit, 'L')

            return False
        except Exception as e:
            QMessageBox.warning(self.myMainWindow, "Error", "There was an error \n\n Exception: " + str(e))
            return True
예제 #14
0
def init_dr_model(baseline=False, guess=None):
    """ Function to serialize a Model object for DR fits.
        Defaults to a Gaussian line shape, but the option to include
        a linear offset is available.

        Additionally, if a guess is provided in the
        lmfit convention then it will be incorporated.

        args:
        -----------------
        baseline - boolean indicating if linear offset is included
        guess - nested dict with keys corresponding to parameter name
                and values corresponding to dicts with key/value
                indicating the parameter value, range, and constraints
    """
    model = GaussianModel()
    if baseline:
        model += LinearModel()
    params = model.make_params()
    if guess:
        params.update(guess)
    # Constrain amplitude to always be negative
    # since we're measuring depletion.
    params["amplitude"].set(max=0.0)
    return model, params
예제 #15
0
def calibrate_pitch(mono='111'):
    BMMuser = user_ns['BMMuser']
    # read content from INI file
    datafile = os.path.join(BMMuser.DATA, 'edges%s.ini' % mono)
    print(f'reading {datafile}')
    config.read_file(open(datafile))

    edges = dict()
    for i in config.items('edges'):
        el = i[0]
        vals = [float(j) for j in i[1].split(',')
                ]  # convert CSV string -> list of strings -> list of floats
        edges[el] = vals

    # organize the data from the INI file
    ordered = [y[1] for y in sorted([(edges[x][1], x) for x in edges.keys()])]
    ee = list()
    tt = list()
    for el in ordered:
        ee.append(edges[el][1])
        tt.append(edges[el][3])

    mod = LinearModel()
    pars = mod.guess(tt, x=ee)
    out = mod.fit(tt, pars, x=ee)
    print(whisper(out.fit_report(min_correl=0)))
    out.plot()
예제 #16
0
def make_model(peak_positions,
               fwhm=0.05,
               max_fwhm=0.5,
               pos_range=0.5,
               amplitude=1000.):
    n_peaks = len(peak_positions)
    pars = Parameters()

    bg = LinearModel(prefix='bg_')
    pars.update(bg.make_params(slope=0, intercept=0))

    mod = bg
    #pars['bg_intercept'].set(vary=True)
    #pars['bg_slope'].set(vary=True)

    for i in range(n_peaks):
        prefix = 'pk{}_'.format(i)
        peak = PseudoVoigtModel(prefix=prefix)
        # Set this zero
        pars.update(peak.make_params())
        pars[prefix + 'center'].set(peak_positions[i],
                                    min=peak_positions[i] - pos_range,
                                    max=peak_positions[i] + pos_range,
                                    vary=True)
        pars[prefix + 'sigma'].set(fwhm, min=0., max=max_fwhm, vary=True)
        pars[prefix + 'amplitude'].set(amplitude, min=0., vary=True)
        pars[prefix + 'fraction'].set(0.0, min=0., max=1., vary=True)
        mod += peak
    return mod, pars
def phaser(x, y, fc, y0):
    def phaseFit(x, Qt, fr):
        return y0 - 180 * np.arctan(2 * Qt * (x - fr) / fr) / np.pi

    gmodel = Model(phaseFit)
    gmodel = gmodel + LinearModel()

    # print(gmodel.param_names)
    # print(gmodel.independent_vars)

    df = 0.002
    dy = 50
    Qt = 30000
    dQt = Qt

    params = gmodel.make_params()

    params.add('y0', value=y0, min=y0 - dy, max=y0 + dy)
    params.add('Qt', value=Qt, min=Qt - dQt, max=Qt + dQt)
    params.add('fr', value=fc, min=fc - df, max=fc + df)
    params.add('intercept', value=1, vary=True)
    params.add('slope', value=0, vary=True)

    result = gmodel.fit(y, params, x=x)

    return result
예제 #18
0
def basic_fit_FanoResonance(freq,
                            trace,
                            filename='untitled',
                            plot=True,
                            save=True):
    start, stop = None, None  #np.argmax(trace)-500,np.argmax(trace)+500# 27900,28200  #Specifies the window within the data to analyse. Set to None,None if you want the whole window
    Lin_mod = LinearModel(
    )  #Linear lmfit model for background offset and slope
    BW_mod = BreitWignerModel()  #Breit-Wigner-Fano model
    mod = BW_mod + Lin_mod
    x = freq[start:stop] / 1E6  #Convert frequencies to MHz
    trace = (10**(trace / 10))  #Convert decibel data to linear
    y = trace[start:stop]
    pars = BW_mod.guess(y, x=x)  #Initialize fit params
    pars += Lin_mod.guess(y, x=x, slope=0, vary=False)
    pars['center'].set(
        value=x[np.argmax(y)], vary=True, expr=''
    )  #Use numpy to find the highest transmission value. Corresponding frequency is used as a guess for the centre frequency
    pars['sigma'].set(value=0.1, vary=True, expr='')  #Linewidth
    pars['q'].set(
        value=1, vary=True,
        expr='')  #Fano factor (asymmetry term). q=infinite gives a Lorentzian
    pars['amplitude'].set(value=-0.03, vary=True, expr='')  #Amplitude
    out = mod.fit(y, pars, x=x)
    sigma = out.params['sigma']
    centre = out.params['center']
    return (x, y, out.best_fit, sigma.value, centre.value,
            centre.value / sigma.value
            )  #Returns linewidth in GHz, centre in GHz and Q factor
예제 #19
0
def fit_voigt_over_linear(q,
                          I,
                          cen=1,
                          sig=0.002,
                          sigmin=1e-4,
                          sigmax=0.01,
                          amplmin=0,
                          amplmax=500,
                          trim=0.06,
                          plot=False):

    trim = logical_and(q < cen + trim, q > cen - trim)
    q = q[trim]
    I = I[trim]

    mod = LinearModel()
    mod.set_param_hint('slope', value=-20)
    mod.set_param_hint('intercept', value=10)
    lineout = mod.fit(I, x=q)
    pars = lineout.params

    mod += VoigtModel()
    pars.add('center', value=cen)
    pars.add('sigma', value=sig, max=sigmax, min=sigmin)
    pars.add('amplitude',
             value=amplmin / 2 + amplmax / 2,
             min=amplmin,
             max=amplmax)
    out = mod.fit(I, pars, x=q)

    return out
예제 #20
0
def lmDDOFit(xdata,
             ydata,
             params,
             ctr_range=1.2,
             amp_range=3,
             sig_range=6,
             weightexponential=0):

    x = xdata
    y = ydata
    #Define a linear model and a Damped Oscillator Model
    line_mod = LinearModel(prefix='line_')
    ddo_mod = DampedOscillatorModel(prefix='ddo_')
    #Initial Pars for Linear Model
    pars = line_mod.make_params(intercept=0, slope=0)
    pars['line_intercept'].set(0, vary=True)
    pars['line_slope'].set(0, vary=True)
    #Extend param list to use multiple peaks. Currently unused.
    peaks = []
    #Add fit parameters, Center, Amplitude, and Sigma
    for i in range(0, len(params) / 3):
        peaks.append(DampedOscillatorModel(prefix='ddo' + str(i) + '_'))
        pars.update(peaks[i].make_params())
        ctr = params[3 * i]
        amp = params[3 * i + 1]
        sig = params[3 * i + 2]
        pars['ddo' + str(i) + '_center'].set(ctr,
                                             min=ctr / ctr_range,
                                             max=ctr * ctr_range)
        pars['ddo' + str(i) + '_amplitude'].set(amp,
                                                min=amp / amp_range,
                                                max=amp * amp_range)
        pars['ddo' + str(i) + '_sigma'].set(sig,
                                            min=sig / sig_range,
                                            max=sig * sig_range)
#Create full model. Add linear model and all peaks
    mod = line_mod
    for i in xrange(len(peaks)):
        mod = mod + peaks[i]


#Initialize fit
    init = mod.eval(pars, x=x)
    #Do the fit. The weight exponential can weight the points porportional to the
    #amplitude of y point. In this way, points on peak can be given more weight.
    out = mod.fit(y, pars, x=x, weights=y**weightexponential)
    #Get the fit parameters
    fittedsigma = out.params['ddo0_sigma'].value
    fittedAmp = out.params['ddo0_amplitude'].value
    fittedCenter = out.params['ddo0_center'].value
    fittedIntercept = out.params['line_intercept'].value
    fittedSlope = out.params['line_slope'].value
    fittedQ = 1 / (2 * fittedsigma)
    #Returns the output fit as well as an array of the fit parameters
    """Returns output fit as will as list of important fitting parameters"""
    return out, [
        fittedCenter, fittedAmp, fittedsigma, fittedQ, fittedIntercept,
        fittedSlope
    ]
예제 #21
0
    def fitting_math(
        self,
        xfile: List[str],
        yfile: List[str],
        flag: int = 1,
    ) -> Any:
        """PeakLogic.fitting_math() fits the data to a cosh and a
        gaussian, then subtracts the cosh to find peak current.."""

        try:
            center: float = self.app.peak_center_.get()
            x: "np.ndarray[Any, np.dtype[np.float64]]" = np.array(
                xfile, dtype=np.float64)
            y: "np.ndarray[Any, np.dtype[np.float64]]" = np.array(
                yfile, dtype=np.float64)

            # cut out outliers
            passingx: "np.ndarray[Any, np.dtype[np.float64]]"
            passingy: "np.ndarray[Any, np.dtype[np.float64]]"
            passingx, passingy = self.trunc_edges(xfile, yfile)

            rough_peak_positions = [min(passingx), center]

            min_y = float(min(passingy))
            model = LinearModel(prefix="Background")
            params = model.make_params()  # a=0, b=0, c=0
            params.add("slope", 0, min=0)
            # params.add("b", 0, min=0)
            params.add("intercept", 0, min=min_y)

            for i, cen in enumerate(rough_peak_positions):
                peak, pars = self.add_lz_peak(f"Peak_{i+1}", cen)
                model = model + peak
                params.update(pars)

            _ = model.eval(params, x=passingx)
            result = model.fit(passingy, params, x=passingx)
            comps = result.eval_components()

            ip = float(max(comps["Peak_2"]))

            if flag == 1:
                return ip
            if flag == 0:
                return (
                    x,
                    y,
                    result.best_fit,
                    comps["Background"],
                    comps["Peak_1"],
                    comps["Peak_2"],
                    ip,
                    passingx,
                )

        except Exception:  # pragma: no cover
            print("Error Fitting")
            print(sys.exc_info())
            return -1
예제 #22
0
def gauss_peak_fit(energy_data, cnts_data, energy_spectrum, channel_width):
    '''
    spectrum_gauss_fit takes an input spectrum and finds the peaks of the
    spectrum and fits a gaussian curve to the photopeaks and returns the
    amplitude and sigma of the gaussian peak.
    Make sure the spectrum is calibrated first.

    sigma_list, amplitude_list = spectrum_gauss_fit(energy_data, cnts_data, energy_spectrum, channel_width)

    energy_data: .energies_kev that has been calibrated from becquerel
    cnts_data: .cps_vals from becquerel spectrum
    energy_spectrum: an array of gamma energies generated from gamma_energies
    channel_width: width of the peak for analysis purposes
    '''
    sigma_list = []
    amplitude_list = []
    for erg in energy_spectrum:
        x_loc = list(
            filter(lambda x: (erg - 3) < energy_data[x] < (erg + 3),
                   range(len(energy_data))))
        x_loc_pk = range(int(x_loc[0] - 5), int(x_loc[0] + 5))
        pk_cnt = np.argmax(cnts_data[x_loc_pk])
        ch_width = range(int(x_loc_pk[pk_cnt] - channel_width),
                         int(x_loc_pk[pk_cnt] + channel_width))

        calibration = energy_data[ch_width]
        real_y_gauss = cnts_data[ch_width]
        x = np.asarray(calibration)
        real_y = np.asarray(real_y_gauss)

        mod_gauss = GaussianModel(prefix='g1_')
        line_mod = LinearModel(prefix='line')
        pars = mod_gauss.guess(real_y, x=x)
        pars.update(line_mod.make_params(intercept=real_y.min(), slope=0))
        pars.update(mod_gauss.make_params())
        pars['g1_center'].set(x[np.argmax(real_y)], min=x[np.argmax(real_y)]\
        - 3)
        pars['g1_sigma'].set(3, min=0.25)
        pars['g1_amplitude'].set(max(real_y), min=max(real_y) - 10)
        mod = mod_gauss + line_mod
        out = mod.fit(real_y, pars, x=x)

        #print("The amplitude sum is %0.2f" % sum(real_y))
        gauss_x = []
        gauss_y = []
        parameter_list_1 = []
        real_y_gauss = []
        #print(out.fit_report(min_correl=10))
        sigma = out.params['g1_sigma'].value
        amplitude = out.params['g1_amplitude'].value
        sigma_list.append(sigma)
        amplitude_list.append(amplitude)
        fit_params = {}

        #gauss_fit_parameters = [out.params[key].value for k in out.params]
        #print(key, "=", out.params[key].value, "+/-", out.params[key].stderr)
        gauss_fit_parameters = []

    return sigma_list, amplitude_list
예제 #23
0
def lenar_calc(x,y):
    mod = LinearModel()
    pars = mod.guess(y, x=x)
    out  = mod.fit(y, pars, x=x)
    calc= out.best_values['slope']
    stress=calc*multi()
    stress=round(stress,3)
    #plt.plot(x,out.bes_fit)
    return stress, x , out.best_fit,out
    def LorentzianFit(self, freq, trace, plot=True):

        if np.any(np.iscomplex(trace)):
            trace = trace.real

        #print (len(trace))
        start, stop = None, None  #Specifies the window within the data to analyse.
        Lin_mod = LinearModel(
        )  #Linear lmfit model for background offset and slope
        BW_mod = BreitWignerModel()  #Breit-Wigner-Fano model
        mod = BW_mod + Lin_mod

        x = freq[start:stop] / 1E6  #Convert frequencies to MHz
        trace = (10**(trace / 10))  #Convert decibel data to linear
        y = trace[start:stop]

        pars = BW_mod.guess(y, x=x)  #Initialize fit params
        pars += Lin_mod.guess(y, x=x, slope=0, vary=False)
        pars['center'].set(
            value=x[np.argmax(y)], vary=True, expr=''
        )  #Find the highest transmission value. Corresponding frequency is used as a guess for the centre frequency
        pars['sigma'].set(value=0.05, vary=True, expr='')  #Linewidth
        pars['q'].set(
            value=0, vary=True,
            expr='')  #Fano factor (asymmetry term). q=0 gives a Lorentzian
        pars['amplitude'].set(value=-0.03, vary=True, expr='')  #Amplitude

        out = mod.fit(y, pars, x=x)
        #         print (out.fit_report())
        #print (out.params['amplitude'],out.params['q'],out.params['sigma'])
        sigma = out.params['sigma']
        centre = out.params['center']

        dic = {
            'x': x,
            'y': y,
            'fit': out.best_fit,
            'out': out,
            'sigma': sigma.value,
            'centre': centre.value,
            'Q': centre.value / sigma.value
        }

        df = pd.DataFrame(data=dic)

        if plot == True:
            print(out.params['amplitude'], out.params['q'],
                  out.params['sigma'])
            plt.plot(x, y, color='orange', label='Data')
            plt.plot(x,
                     out.best_fit,
                     color='darkslateblue',
                     label='Fano resonance fit')

#         return(sigma.value,centre.value,centre.value/sigma.value)       #Returns linewidth in GHz, centre in GHz and Q factor
        return df
예제 #25
0
def poly_lorentzian(number_unique_lorentzians=None):
    model = Model(lorentzian, independent_vars=['x'], prefix='lorentzian1_')
    model += LinearModel(independent_vars=['x'], prefix='linear1_')
    if number_unique_lorentzians is None:
        raise UserWarning('number_unique_lorentzians need to be given')
    for i in range(2, number_unique_lorentzians + 1):
        model += Model(lorentzian,
                       independent_vars=['x'],
                       prefix='lorentzian{}_'.format(i))
    return model
예제 #26
0
    def lin_and_multi_gaussian(self, numOfComponents, cList, sList, aList, lS, lI, limits):
        """All lists should be the same length"""
        gList = []

        if self.xAxis == 'wave' and self.initVals == 'vel':
            cList = vel_to_wave(self.restWave, vel=np.array(cList), flux=0)[0]
            sList = vel_to_wave(self.restWave, vel=np.array(sList), flux=0, delta=True)[0]
            aList = vel_to_wave(self.restWave, vel=0, flux=np.array(aList))[1]
        elif self.xAxis == 'vel' and self.initVals == 'wave':
            cList = wave_to_vel(self.restWave, wave=np.array(cList), flux=0)[0]
            sList = wave_to_vel(self.restWave, wave=np.array(sList), flux=0, delta=True)[0]
            aList = wave_to_vel(self.restWave, wave=0, flux=np.array(aList))[1]

        lin = LinearModel(prefix='lin_')
        self.linGaussParams = lin.guess(self.flux, x=self.x)
        self.linGaussParams.update(lin.make_params())
        self.linGaussParams['lin_slope'].set(lS, vary=True)
        self.linGaussParams['lin_intercept'].set(lI, vary=True)

        for i in range(numOfComponents):
            if type(limits['c']) is list:
                cLimit = limits['c'][i]
            else:
                cLimit = limits['c']
            if type(limits['s']) is list:
                sLimit = limits['s'][i]
            else:
                sLimit = limits['s']
            if type(limits['a']) is list:
                aLimit = limits['a'][i]
            else:
                aLimit = limits['a']
            lims = {'c': cLimit, 's': sLimit, 'a': aLimit}
            prefix = 'g{0}_'.format(i+1)
            gList.append(self._gaussian_component(self.linGaussParams, prefix, cList[i], sList[i], aList[i], lims))
        gList = np.array(gList)
        mod = lin + gList.sum()

        init = mod.eval(self.linGaussParams, x=self.x)
        out = mod.fit(self.flux, self.linGaussParams, x=self.x, weights=self.weights)
        f = open(os.path.join(constants.OUTPUT_DIR, self.rp.regionName, "{0}_Log.txt".format(self.rp.regionName)), "a")
        print("######## %s %s Linear and Multi-gaussian Model ##########\n" % (self.rp.regionName, self.lineName))
        print(out.fit_report())
        f.write("######## %s %s Linear and Multi-gaussian Model ##########\n" % (self.rp.regionName, self.lineName))
        f.write(out.fit_report())
        f.close()
        components = out.eval_components()

        if not hasattr(self.rp, 'plotResiduals'):
            self.rp.plotResiduals = True
        self.plot_emission_line(numOfComponents, components, out, self.rp.plotResiduals, init=init, scaleFlux=self.rp.scaleFlux)

        self._get_amplitude(numOfComponents, out)

        return out, components
예제 #27
0
def get_linearmodel(slope=0.8, intercept=0.5, noise=1.5):
    # create data to be fitted
    np.random.seed(88)
    x = np.linspace(0, 10, 101)
    y = intercept + x * slope
    y = y + np.random.normal(size=len(x), scale=noise)

    model = LinearModel()
    params = model.make_params(intercept=intercept, slope=slope)

    return x, y, model, params
예제 #28
0
    def __init__(self, ModelString):

        self.NumModels = {}
        self.NumModels['Total'] = len(ModelString)
        self.NumModels['Linear'] = len(re.findall('L', ModelString))
        self.NumModels['Gaussian'] = len(re.findall('G', ModelString))
        self.NumModels['Voigt'] = len(re.findall('V', ModelString))
        if self.NumModels['Total'] != self.NumModels['Linear'] + self.NumModels[
                'Gaussian'] + self.NumModels['Voigt']:
            print(
                'Warning: Number of total functions does not equal number of summed functions'
            )
        ModelCounter = 0
        i = 0
        while i < self.NumModels['Linear']:
            if ModelCounter == 0:
                self.Model = LinearModel(prefix='L' + str(i + 1) + '_')
            else:
                self.Model = self.Model + LinearModel(prefix='L' + str(i + 1) +
                                                      '_')
            ModelCounter = ModelCounter + 1
            i += 1
        i = 0
        while i < self.NumModels['Gaussian']:
            if ModelCounter == 0:
                self.Model = GaussianModel(prefix='G' + str(i + 1) + '_')
            else:
                self.Model = self.Model + GaussianModel(prefix='G' +
                                                        str(i + 1) + '_')
            ModelCounter = ModelCounter + 1
            i += 1
        i = 0
        while i < self.NumModels['Voigt']:
            if ModelCounter == 0:
                self.Model = VoigtModel(prefix='V' + str(i + 1) + '_')
            else:
                self.Model = self.Model + VoigtModel(prefix='V' + str(i + 1) +
                                                     '_')
            ModelCounter = ModelCounter + 1
            i += 1
예제 #29
0
def lenar_calc(x, y):
    global dados
    mod = LinearModel()
    pars = mod.guess(y, x=x)
    out = mod.fit(y, pars, x=x)

    ##    print out.best_values
    plt.plot(x, out.best_fit)
    calc = out.best_values['slope']
    ##    print calc,multi()
    stresslocal = calc * multi()
    globalstress.append(stresslocal)
    print 'Value:', dados, round(stresslocal, 3)
예제 #30
0
def fF_plot(pressures, volumes, out_params):
    p = pressures[:, 0]
    sigP = pressures[:, 1]
    V = volumes[:, 0]
    sigV = volumes[:, 1]

    results = out_params.params.valuesdict()

    Vo = results['vo']
    ko = results['ko']
    kpo = results['kp']

    sigVo = out_params.params['vo'].stderr

    #ignore the divide by zero error if the first piece of data is at 0 GPa
    np.seterr(divide='ignore', invalid='ignore')

    #f = (1.0/2.0)*(((V/Vo)**(-2.0/3.0))-1.0)
    f = (((Vo / V)**(2. / 3.)) - 1.) / 2.
    F = p / (3. * f * (1. + (2. * f))**(5. / 2.))
    eta = V / Vo
    sigeta = np.abs(eta) * ((((sigV / V)**2.0) +
                             ((sigVo / Vo)**2))**(1.0 / 2.0))
    sigprime = ((7.0 * (eta**(-2.0 / 3.0)) - 5.0) *
                sigeta) / (2.0 * (1.0 - (eta**-2.0 / 3.0)) * eta)
    sigF = F * np.sqrt(((sigP / p)**2.0) + (sigprime**2))

    line_mod = LinearModel()
    pars = line_mod.guess(f)
    out = line_mod.fit(F, pars, x=f)

    plt.figure(4)
    plt.plot(f, out.best_fit, '-', color='black')

    plt.errorbar(f, F, fmt='ko', xerr=0, yerr=sigF, alpha=1.0, capsize=3.)

    plt.xlabel('Eulerian strain $\mathit{f_E}$', fontweight='bold')
    plt.ylabel('Normalized pressure $\mathbf{F_E}$ (GPa)', fontweight='bold')
    plt.tick_params(direction='in', bottom=1, top=1, left=1, right=1)
    plt.title("$\mathit{f_E}$-F", fontweight='bold')

    #plt.savefig('Ff-plot.png',dpi=600,bbox_inches='tight')

    print(out.fit_report())

    slope = uct.ufloat(out.params['slope'], out.params['slope'].stderr)
    inter = uct.ufloat(out.params['intercept'], out.params['intercept'].stderr)

    k_p = ((2.0 * slope) / (3 * inter)) + 4

    return k_p, f, F, sigF, out.best_fit