How to use iminuit - 10 common examples

To help you get started, we’ve selected a few iminuit examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github gammapy / gammapy / gammapy / detect / test_statistic.py View on Github external
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
github JeffersonLab / PyPWA / test / walkingRun.py View on Github external
#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"
github cta-observatory / ctapipe / ctapipe / reco / ImPACT.py View on Github external
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],
github JeffersonLab / PyPWA / PyPWA / libs / fit / minuit.py View on Github external
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
github gammapy / gammapy / gammapy / modeling / iminuit.py View on Github external
"""
    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
github dsavoiu / kafe / kafe / iminuit_wrapper.py View on Github external
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
github cta-observatory / ctapipe / ctapipe / image / muon / intensity_fitter.py View on Github external
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
github zfit / zfit / zfit / minimizers / minimizer_minuit.py View on Github external
nan_counter += 1
                info_values = {}
                info_values['loss'] = loss_value
                info_values['old_loss'] = current_loss
                info_values['nan_counter'] = nan_counter
                # but loss value not needed here
                _ = self.strategy.minimize_nan(loss=loss, params=params, minimizer=minimizer,
                                               values=info_values)
            else:
                nan_counter = 0
                current_loss = loss_value
            return gradients_values

        grad_func = grad_func if self._use_tfgrad else None

        minimizer = iminuit.Minuit.from_array_func(fcn=func, start=start_values,
                                                   error=errors, limit=limits, name=params_name,
                                                   grad=grad_func,
                                                   # use_array_call=True,
                                                   print_level=minuit_verbosity,
                                                   # forced_parameters=[f"param_{i}" for i in range(len(start_values))],
                                                   **minimizer_init)

        strategy = minimizer_setter.pop('strategy')
        minimizer.set_strategy(strategy)
        minimizer.tol = self.tolerance / 1e-3  # iminuit 1e-3 and tolerance 0.1
        assert not minimizer_setter, "minimizer_setter is not empty, bug. Please report. minimizer_setter: {}".format(
            minimizer_setter)
        self._minuit_minimizer = minimizer
        result = minimizer.migrad(**minimize_options)
        fitresult = FitResult.from_minuit(loss=loss, params=params, result=result, minimizer=self.copy())
        return fitresult
github flav-io / flavio / flavio / math / optimize.py View on Github external
def minimize_migrad(fun, x0, args=(), dx0=None, **kwargs):
    """Minimization function using MINUIT's MIGRAD minimizer."""
    import iminuit
    mfun = MinuitFunction(f=fun, dim=len(x0), args=args)
    # bring the parameters in a suitable form
    par = iminuit.util.describe(mfun)
    x0_dict = {par[i]: x0i for i, x0i in enumerate(x0)}
    if dx0 is None:
        dx0 = np.ones(len(x0))
    dx0_dict = {'error_' + par[i]: dx0i for i, dx0i in enumerate(dx0)}
    # run
    minuit_args={'errordef': 1}
    minuit_args.update(kwargs)
    minuit = iminuit.Minuit(mfun, **x0_dict, **dx0_dict, **minuit_args)
    fmin, param = minuit.migrad()
    # cast migrad result in terms of scipy-like result object
    res = scipy.optimize.OptimizeResult()
    res.success = fmin['is_valid']
    res.fun = fmin['fval']
    res.x = np.array([p['value'] for p in param])
    res.nfev = fmin['nfcn']
    return res
github marinang / lauztat / statnight / model.py View on Github external
def describe(function):
    return iminuit.describe(function)

iminuit

Jupyter-friendly Python frontend for MINUIT2 in C++

MIT
Latest version published 3 months ago

Package Health Score

81 / 100
Full package analysis

Similar packages