def split_peak_params(self, peak_result): amplitude = peak_result.params['amplitude'].value decay = peak_result.params['decay'].value skew = peak_result.params['skew'].value decay_right = 2**(-skew) * decay decay_left = 2**skew * decay baseline = peak_result.params['baseline'].value floor = peak_result.params['floor'].value ceiling = peak_result.params['ceiling'].value peak_params_left = lmfit.Parameters() peak_params_left['amplitude'] = lmfit.Parameter(value=amplitude, vary=False) peak_params_left['decay'] = lmfit.Parameter(value=decay_left, vary=False) peak_params_left['baseline'] = lmfit.Parameter(value=baseline, vary=False) peak_params_left['floor'] = lmfit.Parameter(value=floor, vary=False) peak_params_left['ceiling'] = lmfit.Parameter(value=ceiling, vary=False) peak_params_right = lmfit.Parameters() peak_params_right['amplitude'] = lmfit.Parameter(value=amplitude, vary=False) peak_params_right['decay'] = lmfit.Parameter(value=decay_right, vary=False) peak_params_right['baseline'] = lmfit.Parameter(value=baseline, vary=False) peak_params_right['floor'] = lmfit.Parameter(value=floor, vary=False) peak_params_right['ceiling'] = lmfit.Parameter(value=ceiling, vary=False) return peak_params_left, peak_params_right
def __init__(self, data_modelers): self.parameters = [] for i_shot in data_modelers: Mod = data_modelers[i_shot] for i_N in range(3): p = Mod.PAR.Nabc[i_N] lmfit_p = lmfit.Parameter("rank%d_shot%d_Nabc%d" % (COMM.rank, i_shot, i_N), min=p.minval, max=p.maxval, vary=True, value=p.init, user_data=[p.center, p.beta]) self.parameters.append(lmfit_p) for i_rot in range(3): p = Mod.PAR.RotXYZ_params[i_rot] lmfit_p = lmfit.Parameter("rank%d_shot%d_RotXYZ%d" % (COMM.rank, i_shot, i_rot), min=p.minval, max=p.maxval, vary=True, value=p.init, user_data=[p.center, p.beta]) self.parameters.append(lmfit_p) p = Mod.PAR.Scale lmfit_p = lmfit.Parameter("rank%d_shot%d_Scale" % (COMM.rank, i_shot), min=p.minval, max=p.maxval, vary=True, value=p.init, user_data=[p.center, p.beta]) self.parameters.append(lmfit_p) for i_uc in range(len(Mod.PAR.ucell)): p = Mod.PAR.ucell[i_uc] lmfit_p = lmfit.Parameter("rank%d_shot%d_Ucell%d" % (COMM.rank, i_shot, i_uc), min=p.minval, max=p.maxval, vary=True, value=p.init, user_data=[p.center, p.beta]) self.parameters.append(lmfit_p)
def parameters(): """Initialize a Parameters class for tests.""" pars = lmfit.Parameters() pars.add( lmfit.Parameter(name='a', value=10.0, vary=True, min=-100.0, max=100.0, expr=None, brute_step=5.0, user_data=1)) pars.add( lmfit.Parameter(name='b', value=0.0, vary=True, min=-250.0, max=250.0, expr="2.0*a", brute_step=25.0, user_data=2.5)) exp_attr_values_A = ('a', 10.0, True, -100.0, 100.0, None, 5.0, 1) exp_attr_values_B = ('b', 20.0, False, -250.0, 250.0, "2.0*a", 25.0, 2.5) assert_parameter_attributes(pars['a'], exp_attr_values_A) assert_parameter_attributes(pars['b'], exp_attr_values_B) return pars, exp_attr_values_A, exp_attr_values_B
def tip_line_fit(point1, point2, image, length_spacing, line_thickness, width_spacing): """Fit the tip of a line to a complementary error function, 1 - erf(x). Args: point1: 1D array or float. point2: 1D array or float. image: 2D array. length_spacing: float, `get_thick_line()`. line_thickness: float, `get_thick_line()`. width_spacing: float, `get_thick_line()`. """ profile_parameters = {} profile_parameters["length_spacing"] = length_spacing # pixel profile_parameters["line_thickness"] = line_thickness # pixel profile_parameters["width_spacing"] = width_spacing # pixel profile_parameters["normalized_intensities"] = True x_profile, y_profile = line_profile(image, point1, point2, **profile_parameters) def errorfunction(x, mu, sigma, mt, bg): # pylint: disable=no-member return bg + (0.5 * mt * special.erfc((x - mu) / (np.sqrt(2) * sigma))) model = lmfit.Model(errorfunction) fit_params = {} fit_params["mu"] = lmfit.Parameter("mu", value=x_profile[-1] / 2, min=0, max=x_profile[-1]) fit_params["sigma"] = lmfit.Parameter("sigma", value=1, vary=True, min=0, max=x_profile[-1]) fit_params["mt"] = lmfit.Parameter("mt", value=1, vary=True, min=0) fit_params["bg"] = lmfit.Parameter("bg", value=1, vary=True, min=0) fit_result = model.fit(y_profile.copy(), x=x_profile.copy(), **fit_params) return x_profile, y_profile, fit_result, errorfunction
def test_dumps_loads_parameters_usersyms(): """Test for dumps/loads methods for a Parameters class with usersyms.""" def half(x): return 0.5 * x pars = lmfit.Parameters(usersyms={"half": half, 'my_func': np.sqrt}) pars.add(lmfit.Parameter(name='a', value=9.0, min=-100.0, max=100.0)) pars.add(lmfit.Parameter(name='b', value=100.0, min=-250.0, max=250.0)) pars.add("c", expr="half(b) + my_func(a)") dumps = pars.dumps() assert isinstance(dumps, str) assert '"half": {' in dumps assert '"my_func": {' in dumps newpars = lmfit.Parameters().loads(dumps) assert 'half' in newpars._asteval.symtable assert 'my_func' in newpars._asteval.symtable assert_allclose(newpars['a'].value, 9.0) assert_allclose(newpars['b'].value, 100.0) # within the py.test environment the encoding of the function 'half' does # not work correctly as it is changed from <function half at 0x?????????>" # to "<function test_dumps_loads_parameters_usersyms.<locals>.half at 0x?????????> # This result in the "importer" to be set to None and the final "decode4js" # does not do the correct thing. # # Of note, this is only an issue within the py.test framework and it DOES # work correctly in a normal Python interpreter. Also, it isn't an issue # when DILL is used, so in that case the two asserts below will pass. if lmfit.jsonutils.HAS_DILL: assert newpars == pars assert_allclose(newpars['c'].value, 53.0)
def setup(): fig, ax = plt.subplots() self.ax = ax fig.canvas.set_window_title('Peakup') self.ax.clear() # Setup LiveCallbacks self.live_plot = LivePlot(scaler, dcm_c2_pitch_name, linestyle='', marker='*', color='C0', label='raw', ax=self.ax, use_teleporter=False) # Setup LiveFit # f_gauss(x, A, sigma, x0, y0, m) model = lmfit.Model(f_gauss, ['x']) init_guess = { 'A': lmfit.Parameter('A', 100000, min=0), 'sigma': lmfit.Parameter('sigma', 0.001, min=0), 'x0': lmfit.Parameter('x0', pitch_guess), 'y0': lmfit.Parameter('y0', 0, min=0), 'm': lmfit.Parameter('m', 0, vary=False) } self.lf = LiveFit(model, scaler, {'x': dcm_c2_pitch_name}, init_guess) self.lpf = LiveFitPlot(self.lf, ax=self.ax, color='r', use_teleporter=False, label='Gaussian fit')
def test_init_bounds(): """Tests to make sure that initial bounds are consistent. Only for specific cases not tested above with the initializations of the Parameter class. """ # test 1: min > max; should swap min and max par = lmfit.Parameter(name='a', value=0.0, min=10.0, max=-10.0) assert par.min == -10.0 assert par.max == 10.0 # test 2: min == max; should raise a ValueError msg = r"Parameter 'a' has min == max" with pytest.raises(ValueError, match=msg): par = lmfit.Parameter(name='a', value=0.0, min=10.0, max=10.0) # FIXME: ideally this should be impossible to happen ever.... # perhaps we should add a setter method for MIN and MAX as well? # test 3: max or min is equal to None par.min = None par._init_bounds() assert par.min == -np.inf par.max = None par._init_bounds() assert par.max == np.inf
def test_Parameter_no_name(): """Test for Parameter name, now required positional argument.""" msg = r"missing 1 required positional argument: 'name'" msg_PY2 = r"__init__()" if six.PY2: with pytest.raises(TypeError, match=msg_PY2): lmfit.Parameter() else: with pytest.raises(TypeError, match=msg): lmfit.Parameter()
def find_max_like(data, sample, seed=None): ''' Uses lmfit to approximate the highest likelihood parameter values. We use likelihood instead of posterior because lmfit requires an array of residuals. Prameters --------- data: Spectrum object experimental dataset sample: Sample object information about the sample that produced data_spectrum phi_guess: float user's best guess of the expected volume fraction seed: int (optional) if specified, passes the seed through to the MC multiple scatterin calculation Returns ------- theta: 3 or 5 -tuple best fit (phi, l0, l1) or (phi, l0, l1, l0, l1) as floats ''' def resid(params): if 'reflectance' in data.keys() and 'transmittance' in data.keys(): theta = (params['phi'], params['l0_r'], params['l1_r'], params['l0_t'], params['l1_t']) elif 'reflectance' in data.keys(): theta = (params['phi'], params['l0_r'], params['l1_r']) else: theta = (params['phi'], params['l0_t'], params['l1_t']) theory_spect = calc_model_spect(sample, theta, seed) resid_spect = calc_resid_spect(data, theory_spect) resid = np.concatenate([ resid_spect.reflectance / resid_spect.sigma_r, resid_spect.transmittance / resid_spect.sigma_t ]) return resid[np.isfinite(resid)] fit_params = lmfit.Parameters() fit_params['phi'] = lmfit.Parameter(value=.55, min=min_phi, max=max_phi) if 'reflectance' in data.keys(): fit_params['l0_r'] = lmfit.Parameter(value=0, min=min_l0, max=max_l0) fit_params['l1_r'] = lmfit.Parameter(value=0, min=min_l1, max=max_l1) if 'transmittance' in data.keys(): fit_params['l0_t'] = lmfit.Parameter(value=0, min=min_l0, max=max_l0) fit_params['l1_t'] = lmfit.Parameter(value=0, min=min_l1, max=max_l1) fit_params = lmfit.minimize(resid, fit_params).params return tuple(fit_params.valuesdict().values())
def split_peak_params(self, peak_result): amplitude = peak_result.params['amplitude'].value decay = peak_result.params['decay'].value baseline = peak_result.params['baseline'].value floor = peak_result.params['floor'].value ceiling = peak_result.params['ceiling'].value half_peak_params = lmfit.Parameters() half_peak_params['amplitude'] = lmfit.Parameter(value=amplitude, vary=False) half_peak_params['decay'] = lmfit.Parameter(value=decay, vary=False) half_peak_params['baseline'] = lmfit.Parameter(value=baseline, vary=False) half_peak_params['floor'] = lmfit.Parameter(value=floor, vary=False) half_peak_params['ceiling'] = lmfit.Parameter(value=ceiling, vary=False) return half_peak_params, half_peak_params
def test_parameters_add_many(): """Tests for add_many method.""" a = lmfit.Parameter('a', 1) b = lmfit.Parameter('b', 2) par = lmfit.Parameters() par.add_many(a, b) par_with_tuples = lmfit.Parameters() par_with_tuples.add_many(('a', 1), ('b', 2)) assert list(par.keys()) == ['a', 'b'] assert par == par_with_tuples
def fit_g2(tau, g2, g2_error, bgfactor=0.1, tau0=0, t_antibunch=1e-9, a_bunch=[], t_bunch=[], sigma=None, tau0_fixed=False): # create fit parameters params = _lmfit.Parameters() params.add('tau0', value=tau0) if tau0_fixed: params['tau0'].set(vary=False) params.add('bgfactor', value=bgfactor, min=0) params.add('t_antibunch', value=t_antibunch) a_params = [ _lmfit.Parameter('A_' + str(i), value=a, min=0) for i, a in enumerate(a_bunch) ] t_params = [ _lmfit.Parameter('t_' + str(i), value=t) for i, t in enumerate(t_bunch) ] for p in (a_params + t_params): params.add(p) params.add('g2_0', expr='( bgfactor**2 + 2*bgfactor ) / ( 1 + bgfactor )**2') # wrap g2_normalized in order to make it compatible to lmfit.Model def g2_wrapped(tau, **kwargs): tau0 = kwargs['tau0'] bgfactor = kwargs['bgfactor'] t_antibunch = kwargs['t_antibunch'] a_bunch = [kwargs[a.name] for a in a_params] t_bunch = [kwargs[t.name] for t in t_params] if sigma is None: return g2_bgfactor(tau, tau0, bgfactor, t_antibunch, a_bunch, t_bunch) else: return g2_bgfactor_gauss(tau, tau0, bgfactor, sigma, t_antibunch, a_bunch, t_bunch) model = _lmfit.Model(g2_wrapped, independent_vars=['tau']) result = model.fit( tau=tau, data=g2, params=params, weights=1 / g2_error, ) return result
def parameter_df_to_lmfit(df): """ Converts a dataframe of model parameters to an LMFit 'Parameters' object. All parameters are initialised with 'parameter_type=model_parameter' and 'vary=True'. The provided dataframe should be (a subset of) the dataframe returned by get_double_parameters_as_dataframe(). NOTE: At present, you need to manually add a column named 'short_name' to this dataframe, to succinctly identify each parameter (this is not currently defined in the 'dataset' object itself). """ params = lmfit.Parameters() for idx, row in df.iterrows(): param = lmfit.Parameter(row['short_name'], value=row['initial_value'], min=row['min_value'], max=row['max_value'], vary=True, user_data={ 'index': row['index'], 'name': row['name'], 'parameter_type': 'model_parameter', }) params.add(param) return params
def __init__(self, label, x, y, x0=None, value=None, fix=False, mini=None, maxi=None, expr=None, auto=False): self.label = label self.param = lmfit.Parameter(self.label, value=value, vary=not (fix), expr=expr, min=mini, max=maxi) self.x = x self.y = y self.x0 = x0 self.auto = value if x0 is None: pass elif np.array_equal(self.x, x0): self.y0 = self.y else: self.spline = interpolate.splrep(x, y, s=0) self.y0 = interpolate.splev(self.x0, self.spline, der=0, ext=2)
def test_parameters_update(parameters): """Tests for updating a Parameters class.""" pars, exp_attr_values_A, exp_attr_values_B = parameters msg = r"'test' is not a Parameters object" with pytest.raises(ValueError, match=msg): pars.update('test') pars2 = lmfit.Parameters() pars2.add( lmfit.Parameter(name='c', value=7.0, vary=True, min=-70.0, max=70.0, expr=None, brute_step=0.7, user_data=7)) exp_attr_values_C = ('c', 7.0, True, -70.0, 70.0, None, 0.7, 7) pars_updated = pars.update(pars2) assert_parameter_attributes(pars_updated['a'], exp_attr_values_A) assert_parameter_attributes(pars_updated['b'], exp_attr_values_B) assert_parameter_attributes(pars_updated['c'], exp_attr_values_C)
def estimate_parameters(self) -> np.array: """Estimate values of unknown parameters by setting up and solving a LS optimization. Returns: np.array: Distance residuals. The distances are signed point-to-plane distances. """ # Define rigid body parameters for lmfit params = lmfit.Parameters() for parameter in fields(self._rbp): initial_value = getattr(self._rbp, parameter.name).initial_value observed_value = getattr(self._rbp, parameter.name).observed_value observation_weight = getattr(self._rbp, parameter.name).observation_weight vary = np.isfinite(observation_weight) params[parameter.name] = lmfit.Parameter( name=parameter.name, value=initial_value, vary=vary, user_data={ "observed_value": observed_value, "observation_weight": observation_weight, "is_observed": observation_weight > 0 and np.isfinite(observation_weight), }, ) # Optimize with lmfit self._optim_results = lmfit.minimize( SimpleICPOptimization.__residuals, params, method="least_squares", args=( self._cp, self._distance_weights, ), ) # Save estimated values estimated_values = [ self._optim_results.params["alpha1"].value, self._optim_results.params["alpha2"].value, self._optim_results.params["alpha3"].value, self._optim_results.params["tx"].value, self._optim_results.params["ty"].value, self._optim_results.params["tz"].value, ] self._rbp.set_parameter_attributes_from_list("estimated_value", estimated_values) # Compute unweighted distance residuals weighted_distance_residuals = self._optim_results.residual[ 0:self._cp.num_corr_pts - 1] unweighted_distance_residuals = (weighted_distance_residuals / self._distance_weights) return unweighted_distance_residuals
def __deepcopy__(self, memo): """Parameters deepcopy needs to make sure that asteval is available and that all individula parameter objects are copied""" _pars = SATLASParameters(asteval=None) # find the symbols that were added by users, not during construction sym_unique = self._asteval.user_defined_symbols() unique_symbols = { key: deepcopy(self._asteval.symtable[key], memo) for key in sym_unique } _pars._asteval.symtable.update(unique_symbols) # we're just about to add a lot of Parameter objects to the newly parameter_list = [] for key, par in self.items(): if isinstance(par, lm.Parameter): param = lm.Parameter(name=par.name, value=par.value, min=par.min, max=par.max) param.vary = par.vary param.stderr = par.stderr param.correl = par.correl param.init_value = par.init_value param.expr = par.expr parameter_list.append(param) _pars.add_many(*parameter_list) _pars._prefix = self._prefix return _pars
def plot_train_fits(self, plot_grid): train_responses = self.train_responses pulse_offsets = self.pulse_offsets results = self.train_fit_results train_plots = plot_grid #dyn_plots = PlotGrid() #dyn_plots.set_shape(len(results), 1) models = {4: PspTrain(4), 8: PspTrain(8)} for i, stim_params in enumerate(results.keys()): fits = results[stim_params] amps = [] for j, fit in enumerate(fits): fit, n_psp = fit print "-----------" print stim_params print fit import lmfit params = { k: lmfit.Parameter(name=k, value=v) for k, v in fit.items() } tvals = train_responses[stim_params][j].responses[ 0].time_values model = models[n_psp] train_plots[i, j].plot(tvals, model.eval(x=tvals, params=params), pen='b', antialias=True)
def _mkParameterDct(self, parameterCollection): """ The dictionary that relates parameter names to models. Where there are multiple occurrences of the same parameter, the min, max, and value of the parameter are adjusted. Returns ------- dict key: str (parameter name) value: list-modelName """ parameterDct = {} countDct = {} for parameters in parameterCollection: for parameterName, parameter in parameters.items(): if not parameterName in parameterDct.keys(): newParameter = lmfit.Parameter(name=parameter.name, min=parameter.min, max=parameter.max, value=parameter.value) parameterDct[parameterName] = newParameter countDct[parameterName] = 1 else: # Adjust parameter values curParameter = parameterDct[parameterName] curParameter.set(min=min(curParameter.min, parameter.min)) curParameter.set(max=max(curParameter.max, parameter.max)) curParameter.set(value=curParameter.value + parameter.value) countDct[parameterName] += 1 for parameterName, parameter in parameterDct.items(): parameter.set(value=parameter.value / countDct[parameterName]) return parameterDct
def parameter(): """Initialize parameter for tests.""" param = lmfit.Parameter(name='a', value=10.0, vary=True, min=-100.0, max=100.0, expr=None, brute_step=5.0, user_data=1) expected_attribute_values = ('a', 10.0, True, -100.0, 100.0, None, 5.0, 1) assert_parameter_attributes(param, expected_attribute_values) return param, expected_attribute_values
def __init__(self, amplitude, sigma, skew, baseline, floor, ceiling, null, peak_limit_frc=.2): # initialise null model null_model = lmfit.models.ConstantModel() null_params = lmfit.Parameters() null_params['c'] = null # initialise peak model peak_model = lmfit.Model(skewed_gaussian) peak_params = lmfit.Parameters() peak_params['center'] = lmfit.Parameter(value=0, vary=False) peak_params['amplitude'] = amplitude peak_params['sigma'] = sigma peak_params['skew'] = skew peak_params['baseline'] = baseline peak_params['ceiling'] = ceiling peak_params['floor'] = floor # initialise flank model half_peak_model = lmfit.Model(gaussian) super(SkewedGaussianPeakFitter, self).__init__( null_model=null_model, null_params=null_params, peak_model=peak_model, peak_params=peak_params, half_peak_model=half_peak_model, peak_limit_frc=peak_limit_frc )
def test_live_fit_plot(fresh_RE): RE = fresh_RE try: import lmfit except ImportError: raise pytest.skip('requires lmfit') def gaussian(x, A, sigma, x0): return A * np.exp(-(x - x0)**2 / (2 * sigma**2)) model = lmfit.Model(gaussian) init_guess = { 'A': 2, 'sigma': lmfit.Parameter('sigma', 3, min=0), 'x0': -0.2 } livefit = LiveFit(model, 'det', {'x': 'motor'}, init_guess, update_every=50) lfplot = LiveFitPlot(livefit, color='r') lplot = LivePlot('det', 'motor', ax=plt.gca(), marker='o', ls='none') RE(scan([det], motor, -1, 1, 50), [lplot, lfplot]) expected = {'A': 1, 'sigma': 1, 'x0': 0} for k, v in expected.items(): assert np.allclose(livefit.result.values[k], v, atol=1e-6)
def create_params(basis, model, nuclei=None, conditions=None, constraints=None): """TODO""" fnames_k, params_k = create_params_k(model=model, conditions=conditions) fnames_lr, params_lr = create_params_lr(basis, conditions, nuclei) params_lr = set_thermal_factors(fnames_lr, params_lr, nuclei) if constraints == "hn_ap": fnames_lr, params_lr = set_hn_ap_constraints(fnames_lr, params_lr, nuclei=nuclei, conditions=conditions) if constraints == "nh": fnames_lr, params_lr = set_nh_constraints(fnames_lr, params_lr) fnames = dict(**fnames_k, **fnames_lr) # hack to add parameters depending on parameters not added yet params = lf.Parameters() params.add_many(*(lf.Parameter(fname) for fname in fnames.values())) params.update(params_lr) params.update(params_k) return fnames, params
def test_live_fit_multidim(fresh_RE): RE = fresh_RE try: import lmfit except ImportError: raise pytest.skip('requires lmfit') motor1._fake_sleep = 0 motor2._fake_sleep = 0 det4.exposure_time = 0 def gaussian(x, y, A, sigma, x0, y0): return A * np.exp(-((x - x0)**2 + (y - y0)**2) / (2 * sigma**2)) model = lmfit.Model(gaussian, ['x', 'y']) init_guess = { 'A': 2, 'sigma': lmfit.Parameter('sigma', 3, min=0), 'x0': -0.2, 'y0': 0.3 } cb = LiveFit(model, 'det4', { 'x': 'motor1', 'y': 'motor2' }, init_guess, update_every=50) RE(outer_product_scan([det4], motor1, -1, 1, 10, motor2, -1, 1, 10, False), cb) expected = {'A': 1, 'sigma': 1, 'x0': 0, 'y0': 0} for k, v in expected.items(): assert np.allclose(cb.result.values[k], v, atol=1e-6)
def test_live_fit_plot(RE, hw): try: import lmfit except ImportError: raise pytest.skip("requires lmfit") def gaussian(x, A, sigma, x0): return A * np.exp(-(x - x0)**2 / (2 * sigma**2)) model = lmfit.Model(gaussian) init_guess = { "A": 2, "sigma": lmfit.Parameter("sigma", 3, min=0), "x0": -0.2, } livefit = LiveFit(model, "det", {"x": "motor"}, init_guess, update_every=50) lfplot = LiveFitPlot(livefit, color="r") lplot = LivePlot("det", "motor", ax=plt.gca(), marker="o", ls="none") RE(scan([hw.det], hw.motor, -1, 1, 50), [lplot, lfplot]) expected = {"A": 1, "sigma": 1, "x0": 0} for k, v in expected.items(): assert np.allclose(livefit.result.values[k], v, atol=1e-6)
def test_repr(): """Tests for the __repr__ method.""" par = lmfit.Parameter(name='test', value=10.0, min=0.0, max=20.0) assert par.__repr__() == "<Parameter 'test', value=10.0, bounds=[0.0:20.0]>" par = lmfit.Parameter(name='test', value=10.0, vary=False) assert par.__repr__() == "<Parameter 'test', value=10.0 (fixed), bounds=[-inf:inf]>" par.set(vary=True) par.stderr = 0.1 assert par.__repr__() == "<Parameter 'test', value=10.0 +/- 0.1, bounds=[-inf:inf]>" par = lmfit.Parameter(name='test', expr='10.0*2.5') assert par.__repr__() == "<Parameter 'test', value=-inf, bounds=[-inf:inf], expr='10.0*2.5'>" par = lmfit.Parameter(name='test', brute_step=0.1) assert par.__repr__() == "<Parameter 'test', value=-inf, bounds=[-inf:inf], brute_step=0.1>"
def __init__(self, tguess=20, bguess=1.75, nguess=1e22, trange=[2.73, 50], brange=[1, 3], nrange=[1e20, 1e25], tfixed=False, bfixed=False, nfixed=False): """ Initialize an SED fitter instance with a set of guesses. The input parameters follow a template that is the same for each of temperature, beta, and column. Once initialized, `PixelFitter` can be called as a function of frequency (Hz), flux (MJy), and error (MJy) Parameters ---------- guess : float The guessed value for T,N, or beta. Temperature in Kelvin, column in :math:`cm^{-2}` range : tuple or list of length 2 The minimum/maximum values of each parameter fixed : bool Is the parameter fixed at the guessed value? """ import lmfit from collections import OrderedDict parlist = [ (n, lmfit.Parameter(name=n, value=x)) for n, x in zip(('T', 'beta', 'N'), (tguess, bguess, nguess)) ] parameters = lmfit.Parameters() parameters.update(OrderedDict(parlist)) assert parameters.keys()[0] == 'T' assert parameters.keys()[1] == 'beta' assert parameters.keys()[2] == 'N' parameters['beta'].vary = not bfixed parameters['beta'].min = brange[0] parameters['beta'].max = brange[1] parameters['T'].vary = not tfixed parameters['T'].min = trange[0] parameters['T'].max = trange[1] parameters['N'].vary = not nfixed parameters['N'].min = nrange[0] parameters['N'].max = nrange[1] self.parameters = parameters
def _real_params(self, params): """ Generate a Parameters object for each curve """ real = copy(params) tied = self._all_tied() for param, global_param in self._all_tied().items(): real[param] = lmfit.Parameter(expr=global_param) return real
def test_setup_bounds_and_scale_gradient_methods(): """Tests for the setup_bounds and scale_gradient methods. Make use of the MINUIT-style transformation to obtain the the Parameter values and scaling factor for the gradient. See: https://lmfit.github.io/lmfit-py/bounds.html """ # situation 1: no bounds par_no_bounds = lmfit.Parameter('no_bounds', value=10.0) assert_allclose(par_no_bounds.setup_bounds(), 10.0) assert_allclose(par_no_bounds.scale_gradient(par_no_bounds.value), 1.0) # situation 2: no bounds, min/max set to None after creating the parameter # TODO: ideally this should never happen; perhaps use a setter here par_no_bounds = lmfit.Parameter('no_bounds', value=10.0) par_no_bounds.min = None par_no_bounds.max = None assert_allclose(par_no_bounds.setup_bounds(), 10.0) assert_allclose(par_no_bounds.scale_gradient(par_no_bounds.value), 1.0) # situation 3: upper bound par_upper_bound = lmfit.Parameter('upper_bound', value=10.0, max=25.0) assert_allclose(par_upper_bound.setup_bounds(), 15.968719422671311) assert_allclose(par_upper_bound.scale_gradient(par_upper_bound.value), -0.99503719, rtol=1.e-6) # situation 4: lower bound par_lower_bound = lmfit.Parameter('upper_bound', value=10.0, min=-25.0) assert_allclose(par_lower_bound.setup_bounds(), 35.98610843) assert_allclose(par_lower_bound.scale_gradient(par_lower_bound.value), 0.995037, rtol=1.e-6) # situation 5: both lower and upper bounds par_both_bounds = lmfit.Parameter('both_bounds', value=10.0, min=-25.0, max=25.0) assert_allclose(par_both_bounds.setup_bounds(), 0.4115168460674879) assert_allclose(par_both_bounds.scale_gradient(par_both_bounds.value), -20.976788, rtol=1.e-6)
def fitAndPlotBumplessData(y, x, x0, width, fudge = 0.5, ax = [], color = 'r', linestyle = '-'): """ fitAndPlotBumplessData: -reduces x-scan data to eliminate bump -fits reduced data -plots (if axes supplied) fit line -returns center of fit's transition Parameters ---------- y : y data from scan x : x data from scan x0 : estimated half-max from scan width : estimated width of transition from scan fudge : Fudge factor for x-scan data reduction to remove bump from post-scan fit (in mm). Defaults to def_fudge ax : axis object for plotting fit, Default value is None which suppresses plot color : color of fit line. Defaults to red. linestyle : string descriptor of linetype for fit line, Default value is solid line """ x_reduced_max = x0 + fudge + 0.5*width xdata = np.asarray(x) ydata = np.asarray(y) ix = np.where(xdata < x_reduced_max) x_reduced = xdata[ix] y_reduced = ydata[ix] red_model = lmfit.Model(erfx, missing = 'drop') red_guess = {'low': min(y_reduced), 'high': max(y_reduced), 'wid': lmfit.Parameter('wid', value = width, min=0), 'x0': x0} params = red_model.make_params(low = min(y_reduced), high = max(y_reduced), wid = width, x0 = x0) redFit = red_model.fit(y_reduced, params, x = x_reduced) redFit_x0 = redFit.result.params['x0'].value redFit_width = redFit.result.params['wid'].value #plot new fit if ax is not None: redFit.plot_fit(ax = ax, data_kws = {'visible':False}, fit_kws={'color': color, 'linestyle' : linestyle}, init_kws={'visible':False}, xlabel = 'motorX', ylabel = 'detX') ax.set_title(' ') return redFit_x0