Beispiel #1
0
    def __init__(self, parent=None, size=(-1, -1)):
        wx.Frame.__init__(self,
                          parent,
                          -1,
                          'Parameter Panel Test',
                          size=size,
                          style=wx.DEFAULT_FRAME_STYLE)
        panel = GridPanel(self)

        param1 = Parameter(value=99.0,
                           vary=True,
                           min=0,
                           name='peak1_amplitude')
        param2 = Parameter(value=110.2,
                           vary=True,
                           min=100,
                           max=120,
                           name='peak1_center')
        param3 = Parameter(value=1.23,
                           vary=True,
                           min=0.5,
                           max=2.0,
                           name='peak1_sigma')

        panel.Add(ParameterPanel(panel, param1, show_name=True), style=LEFT)
        # panel.NewRow()
        panel.Add(ParameterPanel(panel, param2, show_name=True), style=LEFT)
        panel.Add(ParameterPanel(panel, param3, show_name=True), style=LEFT)
        panel.pack()
        self.createMenus()

        self.SetSize((700, 200))
        self.Show()
        self.Raise()
Beispiel #2
0
def approximate_angles(goal,
                       side_lengths,
                       angle_guesses=(90, 90, 90),
                       report=True,
                       iter_cb=None):
    """Given the desired end effector location (goal), the lengths of the arm segments, and the initial guesses of the
    angles, approximate the angles the servos must be set to."""

    # The base servo angle can be calculated and fixed.
    base = np.rad2deg(np.arctan(goal[0] / goal[2]))

    # define the starting values of the parameters of the minimized function
    base = Parameter('base', base, vary=False)  # base is exact
    shoulder = Parameter('shoulder', angle_guesses[0], min=0, max=180)
    elbow = Parameter('elbow', angle_guesses[1], min=0, max=180)
    wrist = Parameter('wrist', angle_guesses[2], min=0, max=180)
    params = Parameters()
    params.add_many(base, shoulder, elbow, wrist)

    result = minimize(end_effector,
                      params,
                      args=(goal, side_lengths),
                      method="leastsq",
                      iter_cb=iter_cb)

    if report:
        print(fit_report(result.params))

    return result
Beispiel #3
0
def gaussians_to_population(y_array, x_array, xl, xr):
    """
    Fit y_array with two Gaussian distributions with the initial guess of their center
    coordinates xl and xr.
    Returns a Parameter object representing the ratio of the left population.

    Example:
        left_populations = data.new_data('Left_populations', -1)
        for idx in np.ndindex(left_populations.shape):
            left_populations[idx] = gaussian_to_population(data['Digitizer_count'][idx], data['Volt'], 0.12, 0.16).value
    """
    def dual_gaussian(x, ratio, sigma, center_left, sep):
        gauss = lambda m, s, x: 1.0/(s*sqrt(2*pi)) * np.exp(-(x-m)**2/(2*s**2))
        return ratio * gauss(center_left, sigma, x) + (1.0-ratio) * gauss(center_left + sep, sigma, x)

    # Normalize distribution so that the integration by x gives one
    norm = y_array.sum() * (x_array[1] - x_array[0])

    model = lmfit.Model(dual_gaussian, independent_vars=['x'])
    result = model.fit(y_array / norm, x=x_array,
                    ratio=Parameter(value=0.5, min=0.0, max=1.0),
                    sigma=Parameter(value=(xr-xl)/2, max=(xr-xl)),
                    center_left=xl,
                    sep=Parameter(value=xr-xl, min=(xr-xl)/2))
    return result.params['ratio']
Beispiel #4
0
    def _setup_params_from(self, initial_guess, data):  # 5 ms
        params = Parameters()
        x, y, z = self._make_center_priors(data, initial_guess)  # 4.47 ms
        min_index = data.medium_index * 1.001
        n = Parameter(name='n',
                      value=initial_guess['n'],
                      min=min_index,
                      max=2.33)
        r = Parameter(name='r', value=initial_guess['r'], min=0.05, max=5)
        params.add_many(x, y, z, n, r)
        if self.theory == 'mieonly':
            alpha_val = self._alpha_guess(initial_guess)
            params.add(name='alpha', value=alpha_val, min=0.05, max=1.0)
        elif self.theory == 'mielens':
            angle_val = self._lens_guess(initial_guess)
            params.add(name='lens_angle', value=angle_val, min=0.05, max=1.1)
        if self.theory == 'mielensalpha':
            alpha_val = self._alpha_guess(initial_guess)
            angle_val = self._lens_guess(initial_guess)
            params.add(name='alpha', value=alpha_val, min=0.05, max=1.0)
            params.add(name='lens_angle', value=angle_val, min=0.05, max=1.1)

        if 'illum_wavelen' in initial_guess:
            wavelength = initial_guess['illum_wavelen']
            params.add(name='illum_wavelen',
                       value=wavelength,
                       min=.1,
                       max=2.000)
        return params
Beispiel #5
0
def epw_single_species_settings_params():
    """
    Standard input for the spectral_density_model function

    Includes both settings and params: separated by the function

    spectral_density_model_settings_params

    """
    probe_wavelength = 532 * u.nm
    scattering_angle = np.deg2rad(63)
    scatter_vec = np.array(
        [np.cos(scattering_angle),
         np.sin(scattering_angle), 0])

    kwargs = {}
    kwargs["probe_wavelength"] = probe_wavelength.to(u.m).value
    kwargs["probe_vec"] = np.array([1, 0, 0])
    kwargs["scatter_vec"] = scatter_vec
    kwargs["ions"] = ["H+"]

    kwargs["n"] = Parameter("n",
                            value=2e17 * 1e6,
                            vary=True,
                            min=8e16 * 1e6,
                            max=6e17 * 1e6)
    kwargs["T_e_0"] = Parameter("T_e_0", value=10, vary=True, min=5, max=20)
    kwargs["T_i_0"] = Parameter("T_i_0", value=20, vary=False, min=5, max=70)

    w0 = probe_wavelength.value
    kwargs["wavelengths"] = ((np.linspace(w0 - 40, w0 + 40, num=512) *
                              u.nm).to(u.m).value)

    return kwargs
Beispiel #6
0
    def assess(self):
        # TODO: mutually exclusive args
        # TODO: check for when best and worst are not extrema

        if self.optimal_fit:
            points_params = Parameters()
            worst = Parameter("worst", value=self.worst, vary=False)
            lower_middle = Parameter("lower_middle")
            middle = Parameter("middle")
            upper_middle = Parameter("upper_middle")
            best = Parameter("best", value=self.best, vary=False)
            for param in [lower_middle, middle, upper_middle]:
                param.set(min=self.data.min(), max=self.data.max())
            points_params.add_many(worst, lower_middle, middle, upper_middle,
                                   best)

            def objective(params):
                v = params.valuesdict()
                u = Utility(name="u", points=list(v.values()))
                u.fit()
                chisqr = u.result.chisqr
                return chisqr

            self.optimal_points = minimize(objective,
                                           points_params,
                                           method=self.method)
            v = self.optimal_points.params.valuesdict()
            self.points = np.array(list(v.values()))
        return self.points
Beispiel #7
0
 def factory(Flux_Density=1, Spectral_Index=2, Pivot_Energy=1):
     from lmfit import Parameter
     pars = [
         Parameter(name='Flux_Density', value=Flux_Density),
         Parameter(name='Spectral_Index', value=Spectral_Index),
         Parameter(name='Pivot_Energy', value=Pivot_Energy)
     ]
     return PowerLaw(*pars)
Beispiel #8
0
    def test_add_many_params(self):
        # test that we can add many parameters, but only parameters are added.
        a = Parameter('a', 1)
        b = Parameter('b', 2)

        p = Parameters()
        p.add_many(a, b)

        assert_(list(p.keys()) == ['a', 'b'])
Beispiel #9
0
def fit(fun, x0=None, args=None, check_fun=None, debug=False,
        cons_meth=methods_cons_good, uncons_meth=methods_uncons_good):
    from lmfit import Parameter, Parameters, minimize
    best_result = None
    best_coeffs = None
    best_err = 1e300

    N = len(x0)

    for restart in (False, True):
        if restart:
            if debug:
                print('-'*10 + 'RESTARTING WITH BEST SOLUTION' + '-'*10)
            best_coeffs_restart = best_coeffs
        for method_list, bounded in zip([uncons_meth, cons_meth], [False, True]):
            for method in method_list:
                fit_params = Parameters() # Ordered dict
                for i in range(N):
                    if restart:
                        v = best_coeffs_restart[i]
                    else:
                        try:
                            v = x0[-i]
                        except:
                            v = 1e-20
                    if bounded:
                        if restart:
                            l, h = -abs(best_coeffs_restart[i])*1e3, abs(best_coeffs_restart[i])*1e3
                        else:
                            l, h = -1e5, 1e5
                        fit_params['c' + str(i)] = Parameter(value=v, min=l, max=h, vary=True)
                    else:
                        fit_params['c' + str(i)] = Parameter(value=v, vary=True)

                try:
                    print('starting', [i.value for i in fit_params.values()])
                    result = minimize(fun, fit_params, args=args, method=method)
                except Exception as e:
                    if debug:
                        print(e)
                    continue
                result = postproc_lmfit(result)
                fit = [i.value for i in result.params.values()]

                if result.aard < best_err and (check_fun is None or check_fun(fit)):
                    best_err = result.aard
                    best_coeffs = fit
                    best_result = result

                if debug:
                    if check_fun is None:
                        print(result.aard, method)
                    else:
                        print(result.aard, check_fun(fit), method)
    return best_coeffs, best_result
Beispiel #10
0
def line(data_obj, opt_kwargs={}):
    d, f, t = data_obj.dft

    _line = Model(linear)

    params = Parameters()
    params['m'] = Parameter(name='m', value=np.median(f))
    params['c'] = Parameter(name='c', value=0, min=-10 * np.median(f))

    fitted = _line.fit(f, params, x=d)

    return fitted, (d, f, fitted.best_fit)
Beispiel #11
0
    def run_kropff_low_lambda(self, update_table_ui=False):
        gmodel = Model(kropff_low_lambda,
                       missing='drop',
                       independent_vars=['lda'])

        lda = self.xaxis_to_fit
        o_gui = GuiUtility(parent=self.parent)

        ahkl_init = np.float(str(self.parent.kropff_low_lda_ahkl_init.text()))
        bhkl_init = np.float(str(self.parent.kropff_low_lda_bhkl_init.text()))

        for _row, yaxis in enumerate(self.list_yaxis_to_fit):

            _entry = self.parent.fitting_input_dictionary['rois'][_row][
                'fitting']['kropff']['high']
            a0 = np.float(_entry['a0'])
            b0 = np.float(_entry['b0'])

            yaxis = -np.log(yaxis)
            _result = gmodel.fit(yaxis,
                                 lda=lda,
                                 a0=Parameter('a0', value=a0, vary=False),
                                 b0=Parameter('b0', value=b0, vary=False),
                                 ahkl=ahkl_init,
                                 bhkl=bhkl_init)

            ahkl = _result.params['ahkl'].value
            ahkl_error = _result.params['ahkl'].stderr
            bhkl = _result.params['bhkl'].value
            bhkl_error = _result.params['bhkl'].stderr

            yaxis_fitted = kropff_low_lambda(lda, a0, b0, ahkl, bhkl)

            result_dict = {
                'ahkl': ahkl,
                'bhkl': bhkl,
                'ahkl_error': ahkl_error,
                'bhkl_error': bhkl_error,
                'xaxis_to_fit': lda,
                'yaxis_fitted': yaxis_fitted
            }

            self.parent.fitting_input_dictionary['rois'][_row]['fitting'][
                'kropff']['low'] = deepcopy(result_dict)

            if update_table_ui:
                o_gui.update_kropff_low_lambda_table_ui(row=_row,
                                                        ahkl=ahkl,
                                                        bhkl=bhkl,
                                                        ahkl_error=ahkl_error,
                                                        bhkl_error=bhkl_error)
    def __init__(self, config):

        defaultRkpVary = True
        defaultRkpMin = float("-inf")
        defaultRkpMax = float("inf")

        params = Parameters()

        params['s1'] = Parameter('s1',
                                 value=config['compounds'][0]['solubility'],
                                 vary=False)
        params['s2'] = Parameter('s2',
                                 value=config['compounds'][1]['solubility'],
                                 vary=False)

        rkp12Conf = config['binary']['rkp']['x1-x2']

        params['rkp12_1'] = \
                Parameter('rkp12_1', \
                        value=rkp12Conf[0]['value'],
                        vary=(rkp12Conf[0]['vary'] if 'vary' in rkp12Conf[0] else defaultRkpVary), \
                        min=(rkp12Conf[0]['min'] if 'min' in rkp12Conf[0] else defaultRkpMin), \
                        max=(rkp12Conf[0]['max'] if 'max' in rkp12Conf[0] else defaultRkpMax))
        params['rkp12_2'] = \
                Parameter('rkp12_2', \
                        value=rkp12Conf[1]['value'],
                        vary=(rkp12Conf[1]['vary'] if 'vary' in rkp12Conf[1] else defaultRkpVary), \
                        min=(rkp12Conf[1]['min'] if 'min' in rkp12Conf[1] else defaultRkpMin), \
                        max=(rkp12Conf[1]['max'] if 'max' in rkp12Conf[1] else defaultRkpMax))
        params['rkp12_3'] = \
                Parameter('rkp12_3', \
                        value=rkp12Conf[2]['value'],
                        vary=(rkp12Conf[2]['vary'] if 'vary' in rkp12Conf[2] else defaultRkpVary), \
                        min=(rkp12Conf[2]['min'] if 'min' in rkp12Conf[2] else defaultRkpMin), \
                        max=(rkp12Conf[2]['max'] if 'max' in rkp12Conf[2] else defaultRkpMax))

        # data

        rawdata = np.array(config['data'])

        rawdataLength = len(rawdata)

        data = np.delete(rawdata, 4, 1)

        soly = np.delete(rawdata, [0, 1, 2, 3], 1).reshape((rawdataLength, ))

        self.params = params
        self.data = data
        self.soly = soly
Beispiel #13
0
    def dofit(self):
        minVidx = find_nearest(self.d[:,0],float(self.entryminV.get()))
        maxVidx = find_nearest(self.d[:,0],float(self.entrymaxV.get()))
        self.vdata = self.d[minVidx:maxVidx,0]
        idata = self.d[minVidx:maxVidx,1]
        

            
        self.popt['i0'] = Parameter(value=float(self.entryi0.get()),vary=self.usei0.get())
        self.popt['nvt'] = Parameter(value=float(self.entrynvt.get()), vary =self.usenvt.get() )
        self.popt['R'] = Parameter(value=float(self.entryR.get()), vary = self.useR.get())
        
        minimize(fnc2min, self.popt, args=(self.vdata,idata))
        self.newfit=1
        self.refreshFigure()
Beispiel #14
0
def fit_g_smd(ser_smd, ser_gs, wp_smd):
    from lmfit import Model, Parameter, Parameters

    model_g_smd = Model(
        cal_g_smd,
        independent_vars=["smd"],
        param_names=["g_smd", "wp_smd"],
    )
    prms = Parameters()
    prm_g_smd = Parameter("g_smd", 0.02, vary=True, min=1e-4, max=0.5)
    prm_wp_smd = Parameter("wp_smd", wp_smd, vary=False)
    prms.add_many(prm_g_smd, prm_wp_smd)

    res_fit = model_g_smd.fit(ser_gs / ser_gs.max(), smd=ser_smd, params=prms)
    return res_fit
Beispiel #15
0
    def fit_polynomial(self, max_degree: int = 7) -> List[float]:
        """
        Fit the highest degree polynomial possible with the available energy data. (0 degree is actually 1st degree with 0 shift)

        Parameters:
            max_degree (int): Max degree of polynomial to try and fit. (Max possible: 7)

        Returns:
            (List[Float]): The polynomial coefficients from highest degree to the constant term 
        """
        energies = self.refined_energies if self.refined_energies else self.energies
        if not energies:
            raise ValueError("No known energies found for strip {}".format(
                self.number))

        degree = min(
            len(energies) -
            1, max_degree) if max_degree is not None else len(energies) - 1

        model = PolynomialModel(max(degree, 1))
        x, y = [*zip(*energies)]
        pars = model.guess(y, x=x)
        if degree == 0:
            pars["c0"] = Parameter("c0", value=0, vary=False)

        out = model.fit(y, pars, x=x)
        self.polynomial_coefficients = list(
            reversed([p[1].value for p in out.params.items()]))
        return self.polynomial_coefficients
Beispiel #16
0
 def test_vary_false(self):
     guess = self.guess()
     guess['center'] = Parameter(value=1.3, vary=False)
     true_values = self.true_values()
     true_values['center'] = 1.3
     result = self.model.fit(self.data, x=self.x, **guess)
     assert_results_close(result.values, true_values, rtol=0.05)
Beispiel #17
0
 def parameters(self):
     """List of parameters defining the function."""
     if self._parameters is None:
         self._parameters = [
             Parameter(name) for name in self.module.parameters
         ]
     return self._parameters
Beispiel #18
0
    def fit(self):

        if not self.params:
            self.params = Parameters()
            a = Parameter(name="a", value=1)
            b = Parameter(name="b", value=1)
            c = Parameter(name="c", value=1)
            self.params.add_many(a, b, c)

        self.result = minimize(
            self.residuals,
            self.params,
            args=(self.points, np.linspace(0, 1, 5)),
            nan_policy="propagate",
        )
        return self.result
Beispiel #19
0
 def test_bounding(self):
     guess = self.guess()
     guess['center'] = Parameter(value=2, min=1.3)
     true_values = self.true_values()
     true_values['center'] = 1.3  # as close as it's allowed to get
     result = self.model.fit(self.data, x=self.x, **guess)
     assert_results_close(result.values, true_values, rtol=0.05)
Beispiel #20
0
    def test_pickle_parameter(self):
        # test that we can pickle a Parameter
        p = Parameter('a', 10, True, 0, 1)
        pkl = pickle.dumps(p)

        q = pickle.loads(pkl)

        assert_(p == q)
Beispiel #21
0
def hertz_model(data_obj, opt_kwargs={}):
    d, f, t = data_obj.dft

    _hertz = Model(hertz)

    params = Parameters()
    params['a1'] = Parameter(name='a1', value=np.median(f))
    params['b1'] = Parameter(name='b1', value=0, min=-10 * np.median(f))
    params['cp'] = Parameter(name='cp', value=d.max() * 0.7)
    params['k'] = Parameter(name='k', value=20)
    params['bead_radius'] = Parameter(name='bead_radius',
                                      value=data_obj.bead_radius,
                                      vary=False)

    fitted = _hertz.fit(f, params, x=d)

    return fitted, (d, f, fitted.best_fit)
Beispiel #22
0
def fit_g_ta(ser_ta, ser_gs):
    from lmfit import Model, Parameter, Parameters

    model_g_ta = Model(
        cal_g_ta,
        independent_vars=["ta_c"],
        param_names=["g_ta", "tl", "th"],
    )
    prms = Parameters()
    prm_g_ta = Parameter(
        "g_ta", ser_ta.median(), vary=True, min=ser_ta.min(), max=ser_ta.max()
    )
    prm_tl = Parameter("tl", min=ser_ta.min(), vary=False)
    prm_th = Parameter("th", ser_ta.max(), vary=False)
    prms.add_many(prm_g_ta, prm_tl, prm_th)

    res_fit = model_g_ta.fit(ser_gs / ser_gs.max(), ta_c=ser_ta, params=prms)
    return res_fit
Beispiel #23
0
def fit_g_dq(ser_dq, ser_gs):
    from lmfit import Model, Parameter, Parameters

    model_g_dq = Model(
        cal_g_dq,
        independent_vars=["dq"],
        param_names=["g_dq_base", "g_dq_shape"],
    )
    prms = Parameters()
    prm_g_dq_base = Parameter(
        "g_dq_base",
        ser_gs.min() / ser_gs.max(),
        vary=False,
    )
    prm_g_dq_shape = Parameter("g_dq_shape", 0.1, vary=True, min=0.01, max=0.95)
    prms.add_many(prm_g_dq_base, prm_g_dq_shape)
    res_fit = model_g_dq.fit(ser_gs / ser_gs.max(), dq=ser_dq, params=prms)
    return res_fit
Beispiel #24
0
def convert_to_parameter(obj, name):
    """
    Converts a numeric parameter to an lmfit Parameter
    """
    return Parameter(name = name,
                     value = obj.value,
                     vary = obj.vary,
                     min = obj.minimum,
                     max = obj.maximum,
                     expr = obj.expr)
def fit_Ecal_onedip(xdata, ydata, c1, guessed_sigma=.01):
    '''
        This just fits one dip, a PseudoVoigt with inverse amplitude.
            Useful for getting peak COM.
    '''
    # just fit the first
    # theta-tth factor
    factor = 1

    # TODO : a1, a2 the number of peaks (this makes 2*2 = 4)
    # TODO : Make a Model
    #def dips(x, c0, wavelength, a1, a2, sigma):
    def dips(x, c1, a1, sigma):
        sign = -1
        result = voigt(x=x, amplitude=sign * a1, center=c1, sigma=sigma)
        return result

    model = Model(dips) + LinearModel()

    guessed_average = np.mean(ydata)
    guessed_amplitude = np.abs(np.min(ydata) - guessed_average)
    # Fill out initial guess.
    init_guess = {
        'c1': Parameter('intercept', value=c1),
        'sigma': Parameter('sigma', value=guessed_sigma),
        'a1': Parameter('a1', guessed_amplitude, min=0),
        'intercept': Parameter("intercept", 0),
        'slope': Parameter("slope", guessed_average),
    }
    params = Parameters(init_guess)

    # fit_kwargs = dict(ftol=1)
    fit_kwargs = dict()
    result = model.fit(ydata, x=xdata, params=params, fit_kwargs=fit_kwargs)
    print("Found center to be at theta : {}".format(result.best_values['c1']))

    plt.figure(2)
    plt.clf()
    plt.plot(xdata, ydata, linewidth=0, marker='o', color='b', label="data")
    plt.plot(xdata, result.best_fit, color='r', label="best fit")
    plt.legend()
    return result
Beispiel #26
0
    def test_expr_and_constraints_GH265(self):
        # test that parameters are reevaluated if they have bounds and expr
        # see GH265
        p = Parameters()

        p['a'] = Parameter('a', 10, True)
        p['b'] = Parameter('b', 10, True, 0, 20)

        assert_equal(p['b'].min, 0)
        assert_equal(p['b'].max, 20)

        p['a'].expr = '2 * b'
        assert_almost_equal(p['a'].value, 20)

        p['b'].value = 15
        assert_almost_equal(p['b'].value, 15)
        assert_almost_equal(p['a'].value, 30)

        p['b'].value = 30
        assert_almost_equal(p['b'].value, 20)
        assert_almost_equal(p['a'].value, 40)
Beispiel #27
0
def fit_g_kd(ser_kd, ser_gs):
    from lmfit import Model, Parameter, Parameters

    model_g_kd = Model(
        cal_g_kd,
        independent_vars=["kd"],
        param_names=["g_kd"],
    )
    prms = Parameters()
    prm_g_kd = Parameter("g_kd", 100, vary=True, min=10, max=300)
    prms.add(prm_g_kd)
    res_fit = model_g_kd.fit(ser_gs / ser_gs.max(), kd=ser_kd, params=prms)
    return res_fit
Beispiel #28
0
 def __init__(self,
              name=None,
              value=None,
              vary=True,
              min=-np.inf,
              max=np.inf,
              expr=None,
              brute_step=None,
              user_data=None):
     if name is None:
         name = randstr(8)
     self.name = name
     self.user_data = user_data
     self.init_value = value
     self.min = min
     self.max = max
     self.brute_step = brute_step
     self.vary = vary
     self._expr = expr
     self._expr_ast = None
     self._expr_eval = None
     self._expr_deps = []
     self._delay_asteval = False
     self.stderr = None
     self.correl = None
     self.from_internal = lambda val: val
     self._val = value
     self._init_bounds()
     lmfitParameter.__init__(self,
                             name,
                             value=value,
                             vary=vary,
                             min=min,
                             max=max,
                             expr=expr,
                             brute_step=brute_step,
                             user_data=user_data)
Beispiel #29
0
def singlet_probabilities(dist_arrays, x_array, sep, x_pos=None):
    """
    Fit n-dimensional array of the double Gaussian distribution dist_arrays
    and returns (n-1)-dimensional singlet-return probabilities by thresholding.
    The probability of the peak positioned at x_pos is returned.
    If x_pos is None (default), the initial guess is given by np.argmax of the first histogram.

    Example:
        ps = data.new_data('Singlet_probabilities', -1)
        ps[:] = singlet_probabilities(data['Digitizer_count'], data['Volt'], 0.010)
    """
    integral_dist = np.sum(dist_arrays, axis=tuple(range(len(dist_arrays.shape)-1)), dtype=np.float64)
    out_shape = dist_arrays.shape[:-1]

    def dual_gaussian(x, ratio, sigma, x_pos, sep):
        gauss = lambda m, s, x: 1.0/(s*sqrt(2*pi)) * np.exp(-(x-m)**2/(2*s**2))
        return ratio * gauss(x_pos, sigma, x) + (1.0-ratio) * gauss(x_pos + sep, sigma, x)

    # Normalize distribution so that the integration by x gives one
    full_count = integral_dist.sum()
    integral_dist = integral_dist / (full_count * (x_array[1] - x_array[0]))

    model = lmfit.Model(dual_gaussian, independent_vars=['x'])
    result = model.fit(integral_dist, x=x_array,
                    ratio=Parameter(value=0.5, min=0.0, max=1.0),
                    sigma=Parameter(value=abs(sep)/2, max=abs(sep)),
                    x_pos=x_pos,
                    sep=Parameter(value=sep, min=sep*(2**copysign(1, -sep)), max=sep*(2**copysign(1, sep))))

    threshold = result.params['x_pos'].value + result.params['sep'].value / 2
    singlet_slice = slice_for_range(x_array, x_array[0], threshold)

    count = full_count / np.product(out_shape)
    ps = np.empty(out_shape, dtype=np.float64)
    for idx in np.ndindex(out_shape):
        ps[idx] = np.sum(dist_arrays[idx][singlet_slice], dtype=np.float64) / count
    return ps
def param(*args, **kws):
    "create a fitting Parameter as a Variable"
    if len(args) > 0:
        a0 = args[0]
        if isinstance(a0, six.string_types):
            kws.update({'expr': a0})
        elif isinstance(a0, (int, float)):
            kws.update({'value': a0})
        else:
            raise ValueError(
                "first argument to param() must be string or number")
        args = args[1:]
    if '_larch' in kws:
        kws.pop('_larch')
    return Parameter(*args, **kws)
Beispiel #31
0
def guess(xdata, ydata, sigma=None):
    '''
        sigma is often hard to guess, allow it to be externally guessed
    '''
    g_average = np.average(ydata)

    # choose between a peak or dip
    dip_amp = np.min(ydata) - g_average
    peak_amp = np.max(ydata) - g_average
    if np.abs(dip_amp) > peak_amp:
        print("found a dip")
        g_amp = dip_amp
    else:
        print("found a peak")
        g_amp = peak_amp

    if sigma is None:
        # guess fwhm
        w, = np.where(np.abs(ydata - g_average) < np.abs(g_amp / 2.))
        g_fwhm = np.abs(xdata[w[-1]] - xdata[w[0]])
        # guess...
        g_sigma = g_fwhm / 2.
    else:
        g_sigma = sigma

    x0 = xdata[np.argmax(np.abs(ydata - g_average))]

    init_guess = {
        'amplitude': Parameter('amplitude', value=g_amp, vary=True),
        'sigma': Parameter('sigma', min=0, value=g_sigma, vary=True),
        'x0': Parameter('x0', value=x0, vary=True),
        'intercept': Parameter('intercept', value=g_average, vary=True),
        'slope': Parameter('slope', value=0, vary=True),
    }
    params = Parameters(init_guess)
    return params
 def __init__(self, glbl = False, *args, **kwargs):
     Parameter.__init__(self, *args, **kwargs)
     #super().__init__(self, *args, **kwargs)
     self.glbl = glbl
Beispiel #33
0
    def addModel(self, event=None, model=None, prefix=None, isbkg=False):
        if model is None and event is not None:
            model = event.GetString()
        if model is None or model.startswith('<'):
            return

        self.models_peaks.SetSelection(0)
        self.models_other.SetSelection(0)

        if prefix is None:
            p = model[:5].lower()
            curmodels = ["%s%i_" % (p, i+1) for i in range(1+len(self.fit_components))]
            for comp in self.fit_components:
                if comp in curmodels:
                    curmodels.remove(comp)

            prefix = curmodels[0]

        label = "%s(prefix='%s')" % (model, prefix)
        title = "%s: %s " % (prefix[:-1], model)
        title = prefix[:-1]
        mclass_kws = {'prefix': prefix}
        if 'step' in model.lower():
            form = model.lower().replace('step', '').strip()

            if form.startswith('err'): form = 'erf'
            label = "Step(form='%s', prefix='%s')" % (form, prefix)
            title = "%s: Step %s" % (prefix[:-1], form[:3])
            mclass = lm_models.StepModel
            mclass_kws['form'] = form
            minst = mclass(form=form, prefix=prefix)
        else:
            if model in ModelFuncs:
                mclass = getattr(lm_models, ModelFuncs[model])
            else:
                mclass = getattr(lm_models, model+'Model')

            minst = mclass(prefix=prefix)

        panel = GridPanel(self.mod_nb, ncols=2, nrows=5, pad=2, itemstyle=CEN)

        def SLabel(label, size=(80, -1), **kws):
            return  SimpleText(panel, label,
                               size=size, style=wx.ALIGN_LEFT, **kws)
        usebox = Check(panel, default=True, label='Use in Fit?', size=(100, -1))
        bkgbox = Check(panel, default=False, label='Is Baseline?', size=(125, -1))
        if isbkg:
            bkgbox.SetValue(1)

        delbtn = Button(panel, 'Delete Component', size=(125, -1),
                        action=partial(self.onDeleteComponent, prefix=prefix))

        pick2msg = SimpleText(panel, "    ", size=(125, -1))
        pick2btn = Button(panel, 'Pick Values from Data', size=(150, -1),
                          action=partial(self.onPick2Points, prefix=prefix))

        # SetTip(mname,  'Label for the model component')
        SetTip(usebox,   'Use this component in fit?')
        SetTip(bkgbox,   'Label this component as "background" when plotting?')
        SetTip(delbtn,   'Delete this model component')
        SetTip(pick2btn, 'Select X range on Plot to Guess Initial Values')

        panel.Add(SLabel(label, size=(275, -1), colour='#0000AA'),
                  dcol=3,  style=wx.ALIGN_LEFT, newrow=True)
        panel.Add(usebox, dcol=1)
        panel.Add(bkgbox, dcol=2, style=LCEN)
        panel.Add(delbtn, dcol=1, style=wx.ALIGN_LEFT)

        panel.Add(pick2btn, dcol=2, style=wx.ALIGN_LEFT, newrow=True)
        panel.Add(pick2msg, dcol=2, style=wx.ALIGN_RIGHT)

        # panel.Add((10, 10), newrow=True)
        # panel.Add(HLine(panel, size=(150,  3)), dcol=4, style=wx.ALIGN_CENTER)

        panel.Add(SLabel("Parameter "), style=wx.ALIGN_LEFT,  newrow=True)
        panel.AddMany((SLabel(" Value"), SLabel(" Type"), SLabel(' Bounds'),
                       SLabel("  Min", size=(60, -1)),
                       SLabel("  Max", size=(60, -1)),  SLabel(" Expression")))

        parwids = OrderedDict()
        parnames = sorted(minst.param_names)

        for a in minst._func_allargs:
            pname = "%s%s" % (prefix, a)
            if (pname not in parnames and
                a in minst.param_hints and
                a not in minst.independent_vars):
                parnames.append(pname)

        for pname in parnames:
            sname = pname[len(prefix):]
            hints = minst.param_hints.get(sname, {})

            par = Parameter(name=pname, value=0, vary=True)
            if 'min' in hints:
                par.min = hints['min']
            if 'max' in hints:
                par.max = hints['max']
            if 'value' in hints:
                par.value = hints['value']
            if 'expr' in hints:
                par.expr = hints['expr']

            pwids = ParameterWidgets(panel, par, name_size=100, expr_size=125,
                                     float_size=80, prefix=prefix,
                                     widgets=('name', 'value',  'minval',
                                              'maxval', 'vary', 'expr'))
            parwids[par.name] = pwids
            panel.Add(pwids.name, newrow=True)

            panel.AddMany((pwids.value, pwids.vary, pwids.bounds,
                           pwids.minval, pwids.maxval, pwids.expr))

        for sname, hint in minst.param_hints.items():
            pname = "%s%s" % (prefix, sname)
            if 'expr' in hint and pname not in parnames:
                par = Parameter(name=pname, value=0, expr=hint['expr'])
                pwids = ParameterWidgets(panel, par, name_size=100, expr_size=225,
                                         float_size=80, prefix=prefix,
                                         widgets=('name', 'value', 'expr'))
                parwids[par.name] = pwids
                panel.Add(pwids.name, newrow=True)
                panel.Add(pwids.value)
                panel.Add(pwids.expr, dcol=4, style=wx.ALIGN_RIGHT)
                pwids.value.Disable()

        fgroup = Group(prefix=prefix, title=title, mclass=mclass,
                       mclass_kws=mclass_kws, usebox=usebox, panel=panel,
                       parwids=parwids, float_size=65, expr_size=150,
                       pick2_msg=pick2msg, bkgbox=bkgbox)


        self.fit_components[prefix] = fgroup
        panel.pack()

        self.mod_nb.AddPage(panel, title, True)
        sx,sy = self.GetSize()
        self.SetSize((sx, sy+1))
        self.SetSize((sx, sy))
Beispiel #34
0
    def addModel(self, event=None, model=None, is_step=False):
        if model is None and event is not None:
            model = event.GetString()
        if model is None or model.startswith("<"):
            return

        curmodels = ["p%i_" % (i + 1) for i in range(1 + len(self.fit_components))]
        for comp in self.fit_components:
            if comp in curmodels:
                curmodels.remove(comp)

        prefix = curmodels[0]

        label = "%s(prefix='%s')" % (model, prefix)
        title = "%s: %s" % (prefix[:-1], (model + " " * 4)[:5])
        mclass_kws = {"prefix": prefix}
        if is_step:
            form = model.lower()
            if form.startswith("err"):
                form = "erf"
            label = "Step(form='%s', prefix='%s')" % (form, prefix)
            title = "%s: Step %s" % (prefix[:-1], form[:3])
            mclass = lm_models.StepModel
            mclass_kws["form"] = form
            minst = mclass(form=form, prefix=prefix)
        else:
            mclass = getattr(lm_models, model + "Model")
            minst = mclass(prefix=prefix)

        panel = GridPanel(self.mod_nb, ncols=1, nrows=1, pad=1, itemstyle=CEN)

        def SLabel(label, size=(75, -1), **kws):
            return SimpleText(panel, label, size=size, style=wx.ALIGN_LEFT, **kws)

        usebox = Check(panel, default=True, label="Use?", size=(75, -1))
        delbtn = Button(panel, "Delete Model", size=(120, -1), action=partial(self.onDeleteComponent, prefix=prefix))
        pick2msg = SimpleText(panel, "    ", size=(75, -1))
        pick2btn = Button(panel, "Pick Data Range", size=(125, -1), action=partial(self.onPick2Points, prefix=prefix))

        # SetTip(mname,  'Label for the model component')
        SetTip(usebox, "Use this component in fit?")
        SetTip(delbtn, "Delete this model component")
        SetTip(pick2btn, "Select X range on Plot to Guess Initial Values")

        panel.Add(HLine(panel, size=(520, 3)), style=wx.ALIGN_CENTER, dcol=6)

        panel.Add(SLabel(label, size=(200, -1), colour="#0000AA"), dcol=3, newrow=True)
        panel.AddMany((usebox, pick2msg, pick2btn))

        panel.Add(SLabel("Parameter"), newrow=True)
        panel.AddMany((SLabel("Value"), SLabel("Type"), SLabel("Min"), SLabel("Max"), SLabel("Expression")))

        parwids = OrderedDict()

        parnames = sorted(minst.param_names)

        for a in minst._func_allargs:
            pname = "%s%s" % (prefix, a)
            if pname not in parnames and a in minst.param_hints and a not in minst.independent_vars:
                parnames.append(pname)

        for pname in parnames:
            sname = pname[len(prefix) :]
            hints = minst.param_hints.get(sname, {})

            par = Parameter(name=pname, value=0, vary=True)
            if "min" in hints:
                par.min = hints["min"]
            if "max" in hints:
                par.max = hints["max"]
            if "value" in hints:
                par.value = hints["value"]
            if "expr" in hints:
                par.expr = hints["expr"]

            pwids = ParameterWidgets(
                panel,
                par,
                name_size=80,
                expr_size=150,
                float_size=70,
                prefix=prefix,
                widgets=("name", "value", "minval", "maxval", "vary", "expr"),
            )
            parwids[par.name] = pwids
            panel.Add(pwids.name, newrow=True)
            panel.AddMany((pwids.value, pwids.vary, pwids.minval, pwids.maxval, pwids.expr))

        for sname, hint in minst.param_hints.items():
            pname = "%s%s" % (prefix, sname)
            if "expr" in hint and pname not in parnames:
                par = Parameter(name=pname, value=0, expr=hint["expr"])

                pwids = ParameterWidgets(
                    panel,
                    par,
                    name_size=80,
                    expr_size=275,
                    float_size=70,
                    prefix=prefix,
                    widgets=("name", "value", "vary", "expr"),
                )
                parwids[par.name] = pwids
                panel.Add(pwids.name, newrow=True)
                panel.AddMany((pwids.value, pwids.vary))
                panel.Add(pwids.expr, dcol=3, style=wx.ALIGN_RIGHT)
                pwids.value.Disable()
                pwids.vary.Disable()

        panel.Add(HLine(panel, size=(90, 3)), style=wx.ALIGN_CENTER, newrow=True)
        panel.Add(delbtn, dcol=2)
        panel.Add(HLine(panel, size=(250, 3)), dcol=3, style=wx.ALIGN_CENTER)

        fgroup = Group(
            prefix=prefix,
            title=title,
            mclass=mclass,
            mclass_kws=mclass_kws,
            usebox=usebox,
            panel=panel,
            parwids=parwids,
            float_size=65,
            expr_size=150,
            pick2_msg=pick2msg,
        )

        self.fit_components[prefix] = fgroup
        panel.pack()

        self.mod_nb.AddPage(panel, title, True)
        sx, sy = self.GetSize()
        self.SetSize((sx, sy + 1))
        self.SetSize((sx, sy))