or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-minimization.mdcost-functions.mdindex.mdscipy-interface.mdtesting.mdutilities.mdvisualization.md

utilities.mddocs/

0

# Utilities

1

2

Utility classes and functions for accessing fit results, parameter information, warnings, and performing common operations. These provide structured access to minimization results and helper functions.

3

4

## Capabilities

5

6

### Result Data Classes

7

8

Data classes that store and provide access to minimization results.

9

10

```python { .api }

11

class FMin:

12

"""Function minimum information object."""

13

14

fval: float # Function value at minimum

15

edm: float # Estimated distance to minimum

16

tolerance: float # Convergence tolerance used

17

nfcn: int # Number of function calls

18

ncalls: int # Total number of calls (alias for nfcn)

19

errordef: float # Error definition used

20

is_valid: bool # Whether minimum is valid

21

has_valid_parameters: bool # Whether parameters are valid

22

has_accurate_covar: bool # Whether covariance is accurate

23

has_posdef_covar: bool # Whether covariance is positive definite

24

has_made_posdef_covar: bool # Whether covariance was forced positive definite

25

hesse_failed: bool # Whether HESSE failed

26

has_covariance: bool # Whether covariance matrix exists

27

is_above_max_edm: bool # Whether EDM is above maximum

28

has_reached_call_limit: bool # Whether call limit was reached

29

algorithm: str # Algorithm used for minimization

30

31

def __str__(self) -> str:

32

"""String representation of fit results."""

33

34

def __repr__(self) -> str:

35

"""Detailed representation for debugging."""

36

```

37

38

### Parameter Information

39

40

Classes for accessing individual parameter data and collections.

41

42

```python { .api }

43

class Param:

44

"""Single parameter information object."""

45

46

number: int # Parameter index

47

name: str # Parameter name

48

value: float # Parameter value

49

error: float # Parabolic error

50

is_const: bool # Whether parameter is constant

51

is_fixed: bool # Whether parameter is fixed

52

has_limits: bool # Whether parameter has limits

53

has_lower_limit: bool # Whether parameter has lower limit

54

has_upper_limit: bool # Whether parameter has upper limit

55

lower_limit: float # Lower limit value

56

upper_limit: float # Upper limit value

57

merror: Optional[MError] # Minos error information (if available)

58

59

def __str__(self) -> str:

60

"""String representation of parameter."""

61

62

class Params:

63

"""Collection of parameter objects with dict-like and list-like access."""

64

65

def __len__(self) -> int:

66

"""Number of parameters."""

67

68

def __getitem__(self, key) -> Param:

69

"""Access parameter by name or index."""

70

71

def __iter__(self):

72

"""Iterate over parameters."""

73

74

def __str__(self) -> str:

75

"""Tabular string representation."""

76

```

77

78

### Minos Error Information

79

80

Classes for asymmetric error information from MINOS algorithm.

81

82

```python { .api }

83

class MError:

84

"""Minos error information object."""

85

86

name: str # Parameter name

87

number: int # Parameter index

88

lower: float # Lower error (negative)

89

upper: float # Upper error (positive)

90

is_valid: bool # Whether Minos succeeded

91

lower_valid: bool # Whether lower error is valid

92

upper_valid: bool # Whether upper error is valid

93

at_lower_limit: bool # Whether lower error hit parameter limit

94

at_upper_limit: bool # Whether upper error hit parameter limit

95

at_lower_max_fcn: bool # Whether lower error hit function call limit

96

at_upper_max_fcn: bool # Whether upper error hit function call limit

97

lower_new_min: bool # Whether new minimum found during lower scan

98

upper_new_min: bool # Whether new minimum found during upper scan

99

nfcn: int # Number of function calls used

100

min: float # Parameter value at minimum

101

102

def __str__(self) -> str:

103

"""String representation of Minos errors."""

104

105

class MErrors:

106

"""Collection of Minos error objects with dict-like access."""

107

108

def __len__(self) -> int:

109

"""Number of parameters with Minos errors."""

110

111

def __getitem__(self, key) -> MError:

112

"""Access Minos error by parameter name or index."""

113

114

def __iter__(self):

115

"""Iterate over Minos errors."""

116

117

def __contains__(self, key) -> bool:

118

"""Check if parameter has Minos error."""

119

```

120

121

### Matrix Classes

122

123

Classes for covariance and correlation matrices with convenient access methods.

124

125

```python { .api }

126

class Matrix:

127

"""Matrix representation for covariance and correlation matrices."""

128

129

def __init__(self, data):

130

"""

131

Initialize matrix.

132

133

Args:

134

data: Matrix data (2D array-like)

135

"""

136

137

def __getitem__(self, key):

138

"""Access matrix elements by parameter name or index."""

139

140

def __array__(self) -> np.ndarray:

141

"""Convert to numpy array."""

142

143

def correlation(self):

144

"""

145

Convert covariance matrix to correlation matrix.

146

147

Returns:

148

Matrix: Correlation matrix

149

"""

150

151

def __str__(self) -> str:

152

"""Formatted string representation."""

153

```

154

155

### Array-like Views

156

157

Views that provide array-like access to parameter properties.

158

159

```python { .api }

160

class ValueView:

161

"""Array-like view of parameter values."""

162

163

def __getitem__(self, key):

164

"""Get parameter value by name or index."""

165

166

def __setitem__(self, key, value):

167

"""Set parameter value by name or index."""

168

169

def __len__(self) -> int:

170

"""Number of parameters."""

171

172

class ErrorView:

173

"""Array-like view of parameter errors."""

174

175

def __getitem__(self, key):

176

"""Get parameter error by name or index."""

177

178

def __setitem__(self, key, value):

179

"""Set parameter error by name or index."""

180

181

class FixedView:

182

"""Array-like view of parameter fixed status."""

183

184

def __getitem__(self, key) -> bool:

185

"""Get parameter fixed status by name or index."""

186

187

def __setitem__(self, key, value):

188

"""Set parameter fixed status by name or index."""

189

190

class LimitView:

191

"""Array-like view of parameter limits."""

192

193

def __getitem__(self, key):

194

"""Get parameter limits by name or index."""

195

196

def __setitem__(self, key, value):

197

"""Set parameter limits by name or index."""

198

```

199

200

### Utility Functions

201

202

Helper functions for common operations and function introspection.

203

204

```python { .api }

205

def describe(func, annotations=None):

206

"""

207

Describe function signature and parameter information.

208

209

Args:

210

func: Function to describe

211

annotations: Optional type annotations dictionary

212

213

Returns:

214

Namespace: Object with parameter information including:

215

- name: function name

216

- var: list of parameter names

217

- pos: positional parameter names

218

- varargs: varargs parameter name (if any)

219

- varkw: varkw parameter name (if any)

220

- annotations: type annotations

221

"""

222

223

def make_func_code(names, varargs=None, varkw=None):

224

"""

225

Create function code object with specified parameter names.

226

227

Args:

228

names: Parameter names (list of strings)

229

varargs: Variable args parameter name (optional)

230

varkw: Variable keyword args parameter name (optional)

231

232

Returns:

233

types.CodeType: Function code object

234

"""

235

236

def make_with_signature(func, names, annotations=None):

237

"""

238

Create function with specific signature from existing function.

239

240

Args:

241

func: Original function

242

names: Parameter names for new signature

243

annotations: Type annotations (optional)

244

245

Returns:

246

callable: Function with modified signature

247

"""

248

249

def merge_signatures(callables):

250

"""

251

Merge signatures of multiple callables.

252

253

Args:

254

callables: Sequence of callable objects

255

256

Returns:

257

Tuple: (merged_parameter_names, parameter_mappings)

258

"""

259

260

def gradient(func, x, eps=None):

261

"""

262

Numerical gradient computation.

263

264

Args:

265

func: Function to differentiate

266

x: Point at which to compute gradient

267

eps: Step size (optional, auto-selected if None)

268

269

Returns:

270

np.ndarray: Gradient vector

271

"""

272

273

def is_positive_definite(matrix):

274

"""

275

Check if matrix is positive definite.

276

277

Args:

278

matrix: Matrix to check (2D array-like)

279

280

Returns:

281

bool: True if matrix is positive definite

282

"""

283

```

284

285

### Warning Classes

286

287

Warning classes used throughout iminuit for different types of issues.

288

289

```python { .api }

290

class IMinuitWarning(RuntimeWarning):

291

"""Generic iminuit warning."""

292

293

class HesseFailedWarning(IMinuitWarning):

294

"""HESSE algorithm failure warning."""

295

296

class PerformanceWarning(UserWarning):

297

"""Warning about performance issues."""

298

```

299

300

## Usage Examples

301

302

### Accessing Fit Results

303

304

```python

305

from iminuit import Minuit

306

307

# After fitting

308

m = Minuit(cost_function, x=1, y=2)

309

m.migrad()

310

m.hesse()

311

312

# Access function minimum information

313

fmin = m.fmin

314

print(f"Function value: {fmin.fval}")

315

print(f"Is valid: {fmin.is_valid}")

316

print(f"Has accurate covariance: {fmin.has_accurate_covar}")

317

print(f"Function calls: {fmin.nfcn}")

318

319

# Print formatted summary

320

print(fmin)

321

```

322

323

### Working with Parameters

324

325

```python

326

# Access individual parameters

327

params = m.params

328

for param in params:

329

print(f"{param.name}: {param.value} ± {param.error}")

330

if param.has_limits:

331

print(f" Limits: [{param.lower_limit}, {param.upper_limit}]")

332

333

# Access specific parameter

334

x_param = params['x']

335

print(f"Parameter x: value={x_param.value}, error={x_param.error}")

336

337

# Check parameter status

338

if x_param.is_fixed:

339

print("Parameter x is fixed")

340

```

341

342

### Minos Errors

343

344

```python

345

# Run Minos to get asymmetric errors

346

m.minos()

347

348

# Access Minos errors

349

merrors = m.merrors

350

for name, merror in merrors.items():

351

print(f"{name}: {merror.lower:+.3f} / {merror.upper:+.3f}")

352

if not merror.is_valid:

353

print(f" Warning: Minos failed for {name}")

354

355

# Check specific parameter

356

if 'x' in merrors:

357

x_merror = merrors['x']

358

print(f"x Minos errors: {x_merror.lower} / +{x_merror.upper}")

359

```

360

361

### Covariance Matrix

362

363

```python

364

# Access covariance matrix

365

if m.covariance is not None:

366

cov = m.covariance

367

print("Covariance matrix:")

368

print(cov)

369

370

# Convert to correlation matrix

371

corr = cov.correlation()

372

print("Correlation matrix:")

373

print(corr)

374

375

# Access specific elements

376

print(f"Cov(x,y) = {cov['x', 'y']}")

377

print(f"Corr(x,y) = {corr['x', 'y']}")

378

```

379

380

### Parameter Views

381

382

```python

383

# Array-like access to parameter properties

384

print(f"Parameter values: {dict(m.values)}")

385

print(f"Parameter errors: {dict(m.errors)}")

386

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

387

388

# Modify parameters through views

389

m.values['x'] = 1.5 # Set parameter value

390

m.errors['x'] = 0.1 # Set parameter error

391

m.fixed['y'] = True # Fix parameter

392

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

393

```

394

395

### Function Description

396

397

```python

398

from iminuit.util import describe

399

400

def my_function(x, y, z=1, *args, **kwargs):

401

return x + y + z

402

403

# Describe function signature

404

desc = describe(my_function)

405

print(f"Function name: {desc.name}")

406

print(f"Parameters: {desc.var}")

407

print(f"Positional: {desc.pos}")

408

print(f"Varargs: {desc.varargs}")

409

print(f"Varkw: {desc.varkw}")

410

```

411

412

### Numerical Gradient

413

414

```python

415

from iminuit.util import gradient

416

import numpy as np

417

418

def quadratic(x):

419

return x[0]**2 + 2*x[1]**2

420

421

# Compute numerical gradient

422

x = np.array([1.0, 2.0])

423

grad = gradient(quadratic, x)

424

print(f"Gradient at {x}: {grad}")

425

426

# Custom step size

427

grad_custom = gradient(quadratic, x, eps=1e-6)

428

print(f"Gradient with custom eps: {grad_custom}")

429

```

430

431

### Matrix Operations

432

433

```python

434

from iminuit.util import is_positive_definite

435

import numpy as np

436

437

# Check if covariance matrix is positive definite

438

if m.covariance is not None:

439

is_valid = is_positive_definite(m.covariance)

440

print(f"Covariance is positive definite: {is_valid}")

441

442

# Check custom matrix

443

test_matrix = np.array([[2, 1], [1, 2]])

444

print(f"Test matrix is positive definite: {is_positive_definite(test_matrix)}")

445

```

446

447

### Working with Warnings

448

449

```python

450

import warnings

451

from iminuit.util import HesseFailedWarning, PerformanceWarning

452

453

# Catch iminuit-specific warnings

454

with warnings.catch_warnings():

455

warnings.simplefilter("error", HesseFailedWarning)

456

try:

457

m.hesse()

458

except HesseFailedWarning:

459

print("HESSE algorithm failed!")

460

461

# Filter performance warnings

462

warnings.filterwarnings("ignore", category=PerformanceWarning)

463

```

464

465

### Custom Function Signatures

466

467

```python

468

from iminuit.util import make_with_signature

469

470

def generic_function(*args):

471

return sum(x**2 for x in args)

472

473

# Create function with specific parameter names

474

named_function = make_with_signature(generic_function, ['a', 'b', 'c'])

475

476

# Now can use with parameter names

477

m = Minuit(named_function, a=1, b=2, c=3)

478

```