CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-iminuit

Jupyter-friendly Python frontend for MINUIT2 C++ library for function minimization and error analysis

Pending
Overview
Eval results
Files

core-minimization.mddocs/

Core Minimization

The Minuit class provides the primary interface for function minimization and parameter estimation using the MINUIT2 C++ library. It supports multiple minimization algorithms, parameter management, and comprehensive error analysis.

Capabilities

Minuit Class

Function minimizer and error computer with comprehensive parameter management and algorithm selection.

class Minuit:
    """Function minimizer and error computer."""
    
    # Class constants for errordef values
    LEAST_SQUARES: float = 1.0    # For least-squares cost functions
    LIKELIHOOD: float = 0.5       # For log-likelihood cost functions
    
    def __init__(self, fcn, *args, grad=None, name=None, **kwds):
        """
        Initialize Minuit minimizer.
        
        Args:
            fcn: Cost function to minimize  
            *args: Initial parameter values (positional)
            grad: Gradient function (optional, bool, or callable)
            name: Parameter names (optional)
            **kwds: Initial parameter values (keyword)
        """

Parameter Access Properties

Access and modify parameter values, errors, limits, and fixed status through array-like views.

# Parameter information (read-only)
@property
def parameters(self) -> Tuple[str, ...]:
    """Get tuple of parameter names."""

@property  
def pos2var(self) -> Tuple[str, ...]:
    """Map variable index to name."""
    
@property
def var2pos(self) -> Dict[str, int]:
    """Map variable name to index."""

@property
def npar(self) -> int:
    """Get number of parameters."""

@property
def nfit(self) -> int:
    """Get number of fitted parameters (fixed parameters not counted)."""

# Parameter values and errors (read/write)
@property
def values(self):
    """Access parameter values via an array-like view."""

@property  
def errors(self):
    """Access parameter parabolic errors via an array-like view."""
    
@property
def fixed(self):
    """Access whether parameters are fixed via an array-like view."""
    
@property
def limits(self):
    """Access parameter limits via a array-like view."""

Minimization Algorithms

Multiple algorithms for finding function minima with different performance characteristics.

def migrad(self, ncall=None, iterate=5, use_simplex=True):
    """
    Run Migrad minimization algorithm.
    
    Args:
        ncall: Maximum function calls (optional)
        iterate: Number of iterations if convergence fails
        use_simplex: Whether to use Simplex if Migrad fails
        
    Returns:
        Self for method chaining
    """

def simplex(self, ncall=None):
    """
    Run Simplex minimization algorithm.
    
    Args:
        ncall: Maximum function calls (optional)
        
    Returns:
        Self for method chaining
    """

def scan(self, ncall=None):
    """
    Brute-force minimization by scanning parameter space.
    
    Args:
        ncall: Maximum function calls (optional)
        
    Returns:
        Self for method chaining
    """

def scipy(self, method=None, ncall=None, hess=None, hessp=None, 
          constraints=None, options=None):
    """
    Minimize with SciPy algorithms.
    
    Args:
        method: SciPy method name or callable
        ncall: Maximum function calls (optional)
        hess: Hessian function (optional)
        hessp: Hessian-vector product (optional)
        constraints: Constraint specifications (optional)
        options: Algorithm-specific options (optional)
        
    Returns:
        Self for method chaining
    """

Error Analysis

Asymptotic and profile-based uncertainty estimation methods for parameter errors.

def hesse(self, ncall=None):
    """
    Run Hesse algorithm to compute asymptotic errors.
    
    Args:
        ncall: Maximum function calls (optional)
        
    Returns:
        Self for method chaining
    """

def minos(self, *parameters, cl=None, ncall=None):
    """
    Run Minos algorithm to compute confidence intervals.
    
    Args:
        *parameters: Parameter names/indices for Minos analysis
        cl: Confidence level (optional, uses errordef if None)
        ncall: Maximum function calls (optional)
        
    Returns:
        Self for method chaining
    """

Function and Gradient Access

Access to the cost function and its gradient for advanced usage.

@property
def fcn(self):
    """Get cost function (usually a least-squares or likelihood function)."""

@property
def grad(self):
    """Get gradient function of the cost function."""

Minimization Settings

Control minimization strategy, precision, tolerance, and output behavior.

@property
def errordef(self) -> float:
    """Access FCN increment above minimum that corresponds to one standard deviation."""

@errordef.setter  
def errordef(self, value: float):
    """Set errordef value."""

@property
def precision(self) -> Optional[float]:
    """Access estimated precision of the cost function."""

@precision.setter
def precision(self, value: Optional[float]):
    """Set precision value."""

@property
def tol(self) -> float:
    """Access tolerance for convergence with the EDM criterion."""

@tol.setter
def tol(self, value: float):
    """Set tolerance value."""

@property
def strategy(self):
    """Access current minimization strategy."""

@strategy.setter
def strategy(self, value):
    """Set minimization strategy (0: fast, 1: balanced, 2: accurate)."""

@property
def print_level(self) -> int:
    """Access current print level."""

@print_level.setter
def print_level(self, value: int):
    """Set print level (0: quiet, 1: normal, 2: verbose)."""

@property
def throw_nan(self) -> bool:
    """Access whether to raise runtime error if function evaluates to NaN."""

@throw_nan.setter
def throw_nan(self, value: bool):
    """Set NaN handling behavior."""

Fit Results

Access to minimization results, covariance information, and parameter status.

@property
def fmin(self):
    """Get function minimum data object."""

@property
def fval(self) -> Optional[float]:
    """Get function value at minimum."""

@property
def valid(self) -> bool:
    """Return True if the function minimum is valid."""

@property
def accurate(self) -> bool:
    """Return True if the covariance matrix is accurate."""

@property
def covariance(self):
    """Return covariance matrix."""

@property
def params(self):
    """Get list of current parameter data objects."""

@property
def init_params(self):
    """Get list of current parameter data objects set to the initial fit state."""

@property
def merrors(self):
    """Return a dict-like with Minos data objects."""

@property
def ndof(self) -> int:
    """Get number of degrees of freedom if cost function supports this."""

@property
def nfcn(self) -> int:
    """Get total number of function calls."""

@property
def ngrad(self) -> int:
    """Get total number of gradient calls."""

Parameter Management

Methods for fixing parameters and resetting minimization state.

def fixto(self, key, value):
    """
    Fix parameter and set it to value.
    
    Args:
        key: Parameter name or index
        value: Value to fix parameter to
        
    Returns:
        Self for method chaining
    """

def reset(self):
    """
    Reset minimization state to initial state.
    
    Returns:
        Self for method chaining
    """

Usage Examples

Basic Minimization

from iminuit import Minuit

# Simple quadratic function
def cost(x, y):
    return (x - 1)**2 + (y - 2)**2

# Initialize and minimize  
m = Minuit(cost, x=0, y=0)
m.migrad()

print(f"Minimum at: x={m.values['x']:.3f}, y={m.values['y']:.3f}")
print(f"Function value: {m.fval:.6f}")

Parameter Management

# Set parameter limits
m.limits['x'] = (0, 10)
m.limits['y'] = (-5, 5)

# Fix a parameter
m.fixed['x'] = True

# Or fix to specific value
m.fixto('y', 2.5)

# Check parameter status
print(f"Fixed parameters: {[p for p in m.parameters if m.fixed[p]]}")

Error Analysis

# Compute asymptotic errors
m.hesse()
print(f"Asymptotic errors: {dict(m.errors)}")

# Compute profile-based errors for specific parameters
m.minos('x', 'y')
print(f"Minos errors: {dict(m.merrors)}")

# Access correlation matrix
if m.covariance is not None:
    corr = m.covariance.correlation()
    print(f"Correlation matrix:\n{corr}")

Advanced Settings

# Set minimization strategy (0=fast, 1=default, 2=accurate)
m.strategy = 2

# Set tolerance for convergence
m.tol = 0.001

# Enable verbose output
m.print_level = 1

# Set errordef for chi-square fitting
m.errordef = Minuit.LEAST_SQUARES

Install with Tessl CLI

npx tessl i tessl/pypi-iminuit

docs

core-minimization.md

cost-functions.md

index.md

scipy-interface.md

testing.md

utilities.md

visualization.md

tile.json