Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def fit_amplitude(counts, background, kernel, start_value):
"""Fit amplitude.
TODO: document.
"""
out = dict()
def stat(amplitude):
return stats.cash(counts, background + amplitude * kernel)
from iminuit import Minuit
minuit = Minuit(stat, pedantic=False, print_level=0,
amplitude=start_value)
minuit.migrad()
# import IPython; IPython.embed(); 1/0
out['amplitude'] = minuit.values['amplitude']
out['ncalls'] = minuit.ncalls
return out
#minuitLn=minuitLikelihood(resonances=resonances,waves=waves,normint=normint,alphaList=alphaList,acceptedPath=acceptedPath,generatedPath=generatedPath)
minuitLn=minuitLikelihood(waves=waves,normint=normint,alphaList=alphaList,acceptedPath=acceptedPath,generatedPath=generatedPath,accNormInt=accNormInt)
#CHANGE THESE VALUES IN ORDER TO TEST THE RESULTS OF THE CALCNEGLNL FUNCTION
#wave1Re=.1
#wave1Im=.1
#wave2Re=.1
#wave2Im=.1
#print minuitLn.calcneglnL(wave1Re,wave1Im,wave2Re,wave2Im)
#UNCOMMENT THE LINES BELOW TO TEST THE MINUIT MINIMIZATION OF THE CALCNEGLNL FUNCTION
m=Minuit(minuitLn.calcneglnL,wave1Re=0.01,wave2Re=0.01,wave1Im=-0.01,wave2Im=-0.01)#,fix_wave1Im=True,fix_wave2Im=True)
m.set_strategy(1)
m.set_up(0.5)
m.migrad(ncall=1000)
Vvalues = m.values
print Vvalues
numpy.save(os.path.join(dataDir,"Vvalues.npy"),Vvalues)
#m.draw_profile('wave1Re')
#m.draw_profile('wave2Re')
covariance=numpy.array(m.matrix())
#covariance=numpy.array(m.covariance())
numpy.save(os.path.join(dataDir,"minuitCovar3.npy"),covariance)
print covariance
print"done"
step: ndarray
Initial step size in the fit
limits: ndarray
Fit bounds
minimiser_name: str
Name of minimisation method
max_calls: int
Maximum number of calls to minimiser
Returns
-------
tuple: best fit parameters and errors
"""
limits = np.asarray(limits)
if minimiser_name == "minuit":
self.min = Minuit(
self.get_likelihood,
print_level=1,
source_x=params[0],
error_source_x=step[0],
limit_source_x=limits[0],
fix_source_x=False,
source_y=params[1],
error_source_y=step[1],
limit_source_y=limits[1],
fix_source_y=False,
core_x=params[2],
error_core_x=step[2],
limit_core_x=limits[2],
fix_core_x=False,
core_y=params[3],
error_core_y=step[3],
def minimize(
parameters: _Dict[str, _Any], settings: _Dict[str, _Any],
likelihood: _likelihoods.ChiSquared, set_up: int, strategy=1,
num_of_calls=1000
):
settings["forced_parameters"] = parameters
settings["errordef"] = set_up
optimizer = _iminuit.Minuit(likelihood, **settings)
optimizer.set_strategy(strategy)
optimizer.set_up(set_up)
optimizer.migrad(num_of_calls)
return optimizer
"""
from iminuit import Minuit
# In Gammapy, we have the factor 2 in the likelihood function
# This means `errordef=1` in the Minuit interface is correct
kwargs.setdefault("errordef", 1)
kwargs.setdefault("print_level", 0)
kwargs.update(make_minuit_par_kwargs(parameters))
minuit_func = MinuitLikelihood(function, parameters)
kwargs = kwargs.copy()
migrad_opts = kwargs.pop("migrad_opts", {})
strategy = kwargs.pop("strategy", 1)
tol = kwargs.pop("tol", 0.1)
minuit = Minuit(minuit_func.fcn, **kwargs)
minuit.tol = tol
minuit.strategy = strategy
minuit.migrad(**migrad_opts)
factors = minuit.args
info = {
"success": minuit.migrad_ok(),
"nfev": minuit.get_num_call_fcn(),
"message": _get_message(minuit, parameters),
}
optimizer = minuit
return factors, info, optimizer
def update_parameter_data(self, show_warnings=False):
"""
(Re-)Sets the parameter names, values and step size in iminuit.
"""
fitparam = self.__iminuit.fitarg.copy() # copy minimizer arguments
for parameter, value, err in zip(
self.parameter_names,
self.current_parameters,
self.parameter_errors):
fitparam[parameter] = value
fitparam["error_"+parameter] = err
# replace minimizer
##del self.__iminuit
self.__iminuit = iminuit.Minuit(
self.function_to_minimize,
print_level=self.print_level,
forced_parameters=self.parameter_names,
errordef=self.errordef,
**fitparam)
return 0
step_sizes["error_ring_width"] = 0.001 * radius.to_value(u.rad)
step_sizes["error_optical_efficiency_muon"] = 0.05
constraints = {}
constraints["limit_impact_parameter"] = (0, None)
constraints["limit_phi"] = (-np.pi, np.pi)
constraints["fix_radius"] = True
constraints["fix_center_x"] = True
constraints["fix_center_y"] = True
constraints["limit_ring_width"] = (0.0, None)
constraints["limit_optical_efficiency_muon"] = (0.0, None)
# Create Minuit object with first guesses at parameters
# strip away the units as Minuit doesnt like them
minuit = Minuit(
negative_log_likelihood,
# forced_parameters=parameter_names,
**initial_guess,
**step_sizes,
**constraints,
errordef=0.5,
print_level=0,
pedantic=True,
)
# Perform minimisation
minuit.migrad()
# Get fitted values
result = minuit.values