Calibration API¶
Fits a model to observations. Guide: Model Calibration.
Calibrator ¶
Calibrate the parameters of a simulation against observed data.
The calibration problem is built in Rust once, when the calibrator is created, and every optimization, prediction and uncertainty method reads that one problem.
Source code in commol/api/calibrator.py
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 | |
Attributes¶
rust_problem
property
¶
The calibration problem built in Rust, for the runners of methods.
Returns:
| Type | Description |
|---|---|
CalibrationProblemProtocol
|
The problem every optimization, prediction and method reads. |
rust_optimizer
property
¶
The optimizer built in Rust, for the runners of methods.
Returns:
| Type | Description |
|---|---|
OptimizationConfigProtocol
|
The optimizer of |
seed
property
¶
The seed of the calibration's random numbers.
Returns:
| Type | Description |
|---|---|
int
|
|
Methods:¶
__init__ ¶
__init__(simulation: Simulation, problem: CalibrationProblem) -> None
Initializes the calibration from a Simulation and CalibrationProblem.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
simulation
|
Simulation
|
A fully initialized Simulation object with the model to calibrate. |
required |
problem
|
CalibrationProblem
|
A fully constructed and validated calibration problem definition. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a parameter, observation, position or constraint does not fit the model. |
Source code in commol/api/calibrator.py
rust_predictive ¶
rust_predictive(sample: ParameterSample, positions: list[float]) -> PredictiveProtocol
The run of every draw of sample at positions, for a Predictive:
each replicate of a stochastic engine has a seed of its own, derived
from the calibrator's seed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sample
|
ParameterSample
|
The draws, in the problem's order. |
required |
positions
|
list[float]
|
Positions to report at, sorted and unique. |
required |
Returns:
| Type | Description |
|---|---|
PredictiveProtocol
|
The runs, computed in Rust. |
Source code in commol/api/calibrator.py
with_model ¶
with_model(model: Model) -> Calibrator
The same calibration problem on another model, with the same seed.
The draws of a predictive of the copy take the seeds they take here,
so Scenarios runs every scenario on common random numbers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Model
|
The model, such as a copy of this one with other parameter values. |
required |
Returns:
| Type | Description |
|---|---|
Calibrator
|
A calibrator of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a parameter, observation, position or constraint of the problem
does not fit |
Source code in commol/api/calibrator.py
point_sample ¶
point_sample(result: CalibrationResult) -> ParameterSample
The point estimate of a fit as a sample of one draw.
A Predictive or Scenarios of it runs the model at the fit, so a
fit is read as any sample is.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
CalibrationResult
|
A fit of this calibration problem. |
required |
Returns:
| Type | Description |
|---|---|
ParameterSample
|
One draw at |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the names of |
Source code in commol/api/calibrator.py
delta_band ¶
delta_band(result: LocalResult, positions: Sequence[float], confidence_level: float) -> DeltaBand
The band of every output of a local approximation by the delta method.
The model is linearized at the fit of result: the variance of an
output is J Σ Jᵀ, with J its derivatives on the unbounded
scale and Σ the covariance of result. The band is the
prediction at the fit plus and minus the quantile of a normal, or of
the Student t of a SandwichResult, times its standard deviation. It
runs the model a few times per parameter, not once per draw, and reads
only the fields of result, so a result read back from JSON works.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
LaplaceResult | SandwichResult
|
A local approximation of this calibration problem. |
required |
positions
|
Sequence[float]
|
Positions to report at. |
required |
confidence_level
|
float
|
Strictly between 0 and 1. |
required |
Returns:
| Type | Description |
|---|---|
DeltaBand
|
The prediction at the fit and the ends of the interval of each output at each position. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the result's parameters are not the problem's, the level is not strictly between 0 and 1, the engine is stochastic, or the engine rejects a position. |
RuntimeError
|
If the derivatives fail at the fit. |
Source code in commol/api/calibrator.py
rust_observation_draws ¶
rust_observation_draws(sample: ParameterSample, observed_data: list[ObservedDataPoint], noise: ObservationNoise) -> ObservationDrawsProtocol
Every draw's value of observed_data with noise, for a Predictive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sample
|
ParameterSample
|
The draws, in the problem's order. |
required |
observed_data
|
list[ObservedDataPoint]
|
The observations. |
required |
noise
|
NoNoise | ResidualNoise | DistributionNoise
|
The observation noise, drawn from the calibrator's seed. |
required |
Returns:
| Type | Description |
|---|---|
ObservationDrawsProtocol
|
The draws, computed in Rust. |
Source code in commol/api/calibrator.py
rust_log_score ¶
rust_log_score(sample: ParameterSample, observed_data: list[ObservedDataPoint]) -> list[float]
The log score of each observation under the predictive of sample,
for commol.scores.log_score.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sample
|
ParameterSample
|
The draws, in the problem's order. |
required |
observed_data
|
list[ObservedDataPoint]
|
The observations. |
required |
Returns:
| Type | Description |
|---|---|
list[float]
|
One log score per observation, computed in Rust. |
Source code in commol/api/calibrator.py
run ¶
run(starts: int = 1) -> CalibrationResult
Runs the calibration optimization from one or more starts.
Start 0 is the initial guess of each parameter. Each further start is a
row of a Latin hypercube over the bounds, drawn from seed, so the
starts cover the parameter space; a particle swarm takes a seed of
its own at each start, also from seed. They run in parallel, on the
threads of commol.threads; the result is the best of them, the
first start of lowest loss, and lists every start. Distinct ends with
equal losses are a sign that the data do not identify the
parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
starts
|
int
|
Number of starts, at least 1 (default 1). A verbose optimizer
shows one start, so it needs |
1
|
Returns:
| Type | Description |
|---|---|
CalibrationResult
|
The best start: the optimized parameter values, in the order of
the problem's parameters, its final loss and convergence, every
start ( |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
RuntimeError
|
If every start fails. |
Source code in commol/api/calibrator.py
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 | |
run_with_history ¶
run_with_history() -> CalibrationHistory
Runs the calibration from the initial guess and keeps every evaluation.
Returns:
| Type | Description |
|---|---|
CalibrationHistory
|
The result, and every evaluation of a feasible point the optimizer made, in order. Infeasible points, which the objective penalizes, are not kept. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If optimization fails. |
Source code in commol/api/calibrator.py
uncertainty ¶
uncertainty(method: UncertaintyMethod[ResultT]) -> ResultT
Run an uncertainty method on this calibration problem.
Each method is a configuration (a subclass of UncertaintyMethod)
whose type sets the result type; its runner is registered in
commol.api.inference.registry. The guide's table "Which method
answers which question" lists them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
UncertaintyMethod[ResultT]
|
The configuration of the method. |
required |
Returns:
| Type | Description |
|---|---|
ResultT
|
The result of the method. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If no runner is registered for the configuration's type (the message names the registered ones), or a setting, an input, the data or the model does not fit the method; the message says why. |
RuntimeError
|
If a computation of the method that could start fails: an engine run, an optimizer, every replicate, or a sampler that does not reach its target. |
InfeasibleStateError
|
If a draw of a prediction leaves the values its model allows. |
Source code in commol/api/calibrator.py
identifiability ¶
identifiability(method: IdentifiabilityMethod[ResultT]) -> ResultT
Run an identifiability method on this calibration problem.
Each method answers which parameters the model and the data
determine, from another kind of evidence: StructuralRank,
Collinearity, SampleIdentifiability or StartsIdentifiability.
Each returns an IdentifiabilityReport; IdentifiabilityReport.merge
joins them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
IdentifiabilityMethod[ResultT]
|
The configuration of the method. |
required |
Returns:
| Type | Description |
|---|---|
ResultT
|
The result of the method. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If no runner is registered for the configuration's type, or a setting, an input, the data or the model does not fit the method; the message says why. |
RuntimeError
|
If a computation of the method that could start fails: an engine run or an optimizer. |
Source code in commol/api/calibrator.py
CalibrationProblem ¶
Bases: RangeChecked
Defines a complete calibration problem.
This class encapsulates all the information needed to calibrate model parameters against observed data. It provides validation of the calibration setup but delegates the actual optimization to the Rust backend.
Attributes:
| Name | Type | Description |
|---|---|---|
observed_data |
list[ObservedDataPoint]
|
List of observed data points to fit against |
parameters |
list[CalibrationParameter]
|
List of parameters to calibrate with their bounds |
constraints |
list[CalibrationConstraint]
|
List of constraints on calibration parameters (optional, default: empty list) |
loss_function |
{sse, rmse, mae} | None
|
The loss that measures the fit, with the observation weights. A
problem has a loss or |
observation_models |
dict[str, ObservationModel] | None
|
One observation model per series label ( |
normalize_observations |
bool
|
When True, divide each residual by the RMS of its observation series before applying the loss metric (default: False). It needs a loss: observation models set the scale of each series with their noise. |
optimization_config |
OptimizationConfig
|
Configuration for the optimization algorithm |
initial_condition_remainder |
str | None
|
Expanded compartment or bin that takes what the calibrated initial conditions leave of the amounts the model states (default: None). It is not calibrated itself: it takes the sum of the amounts the model states, less every other compartment, so that sum does not change. A value that would make it negative is penalized. Without a remainder, calibrated initial conditions are applied as given, and the other compartments keep their amounts. |
replicates |
int | None
|
For a stochastic engine: how many replicates each evaluation runs,
with common random numbers (the same seeds, derived from |
replicate_summary |
{mean, median, crps} | Quantile | None
|
For a stochastic engine: what each observation is compared with. The
mean, the median or a |
seed |
int | None
|
Seed of every random number of a calibration (default: None, a seed
the engine draws when the calibrator is built, which |
Source code in commol/context/calibration.py
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 | |
Methods:¶
validate_loss_or_models ¶
Require a loss or observation models, exactly one.
Source code in commol/context/calibration.py
validate_unique_parameter_ids ¶
Ensure parameter IDs are unique.
Source code in commol/context/calibration.py
Quantile ¶
Bases: BaseModel
A quantile of the replicates of a stochastic engine, for
CalibrationProblem.replicate_summary.
It is the one quantile of commol, the one of weighted_quantiles and
SimulationReplicates.quantiles: with equal weights, NumPy's
method="hazen". Quantile(0.25) of the replicates 1, 2, 3, 4, 5 is
1.75.
Attributes:
| Name | Type | Description |
|---|---|---|
level |
float
|
The level, between 0 and 1, such as 0.5 for the median. |
Source code in commol/context/calibration.py
ObservedDataPoint ¶
Bases: RangeChecked
Represents a single observed data point for calibration.
An observation compares one output, or the sum of several outputs, with an observed value at a position on the axis.
Attributes:
| Name | Type | Description |
|---|---|---|
at |
float
|
Position of the observation on the axis. The engine decides which positions its model type accepts: a DifferentialEquations model any non-negative position, a DifferenceEquations model only an integer step. |
output |
str | None
|
The output being observed. Give either |
outputs |
list[str] | None
|
Outputs summed before comparing with this observation. Needs a
|
label |
str
|
Name of the observed series, used by reports, plots and the
per-series normalization. Defaults to |
value |
float
|
Observed value |
weight |
float
|
How much this observation counts in the loss (default: 1.0). Every
loss multiplies the squared or absolute residual by it: |
factor_id |
str | None
|
Optional factor parameter ID that multiplies the model output before comparison |
window |
float | None
|
Optional window length for a cumulative output: the prediction is the
output at |
trials |
int | None
|
The trials of this observation, for a |
Source code in commol/context/calibration.py
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 | |
Attributes¶
observed_outputs
property
¶
The outputs whose sum is compared: outputs, or output alone.
Methods:¶
validate_observed_outputs ¶
Require one of output and outputs; name the series.
Source code in commol/context/calibration.py
validate_window ¶
A window must not start before position 0, with the rule of the
engine (check_window_end of
crates/commol-calibration/src/observation.rs).
Source code in commol/context/calibration.py
Observation models¶
Guide: Observation Models.
ObservationModel ¶
ObservationModel = Annotated[NormalObservations | LogNormalObservations | StudentTObservations | PoissonObservations | NegativeBinomialObservations | BinomialObservations, Field(discriminator=kind)]
One observation model of a series.
NormalObservations ¶
Bases: _ObservationModel, RangeChecked
Normal noise: y ~ N(μ, sd²), with μ the prediction.
For continuous values with errors of the same size everywhere. With a
known sd the maximum-likelihood fit is the least-squares fit.
Attributes:
| Name | Type | Description |
|---|---|---|
sd |
float | str
|
The standard deviation, above 0, or the id of a noise parameter. |
Source code in commol/context/observation_models.py
LogNormalObservations ¶
Bases: _ObservationModel, RangeChecked
Log-normal noise: log y is normal with standard deviation sigma.
For positive values with errors that grow with the value. center
says what the prediction μ is, and has no default: "mean" makes
E[y] = μ (log y ~ N(log μ − σ²/2, σ²)), "median" makes the
median μ (log y ~ N(log μ, σ²), the proportional error
y = μ·e^ε). Every observed value must be above 0.
Attributes:
| Name | Type | Description |
|---|---|---|
sigma |
float | str
|
The standard deviation of |
center |
{mean, median}
|
What the prediction is. |
Source code in commol/context/observation_models.py
StudentTObservations ¶
Bases: _ObservationModel, RangeChecked
Student-t noise of center μ, the prediction: normal noise with heavier
tails, so an outlier pulls the fit less.
Attributes:
| Name | Type | Description |
|---|---|---|
df |
float | str
|
The degrees of freedom, above 0, or the id of a noise parameter. The
noise has a mean when |
scale |
float | str
|
The scale, above 0, or the id of a noise parameter. |
Source code in commol/context/observation_models.py
PoissonObservations ¶
Bases: _ObservationModel
Poisson counts of mean μ, the prediction: variance equal to the mean.
Every observed value must be a whole number, at least 0.
Source code in commol/context/observation_models.py
NegativeBinomialObservations ¶
Bases: _ObservationModel, RangeChecked
Negative binomial counts of mean μ, the prediction, and variance
μ + φμ²: counts that scatter more than a Poisson.
φ = 0 is the Poisson, so bounds [0, …] of a noise parameter hold
it. The dispersion k (size in R) is 1/φ.
Every observed value must be a whole number, at least 0.
Attributes:
| Name | Type | Description |
|---|---|---|
overdispersion |
float | str
|
|
Source code in commol/context/observation_models.py
BinomialObservations ¶
Bases: _ObservationModel, RangeChecked
Binomial counts of n trials and mean μ, the prediction: the
probability is μ / n, so the prediction is an expected count, not a
proportion.
trials gives n for every observation of the series; without it,
each observation of the series gives its own (ObservedDataPoint.trials),
for trials that change from one observation to the next. One source per
series. Every observed value must be a whole number between 0 and its
trials.
Attributes:
| Name | Type | Description |
|---|---|---|
trials |
int | None
|
The trials of every observation, or None (default) to read the trials of each observation. |
Source code in commol/context/observation_models.py
Unknowns, optimizers and results¶
CalibrationParameter ¶
Bases: BaseModel
Defines a parameter or initial condition to be calibrated with its bounds.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
Identifier (parameter ID for parameters, bin ID for initial conditions) |
parameter_type |
str
|
Type of value being calibrated |
min_bound |
float
|
Minimum allowed value for this parameter |
max_bound |
float
|
Maximum allowed value for this parameter |
initial_guess |
float | None
|
Optional starting value for optimization (if None, midpoint is used) |
Source code in commol/context/calibration.py
Methods:¶
validate_bounds ¶
Validate that max_bound > min_bound and initial_guess is within bounds.
Source code in commol/context/calibration.py
CalibrationConstraint ¶
Bases: RangeChecked
A constraint on calibration parameters defined as a mathematical expression.
Constraints are mathematical expressions that must evaluate to >= 0 for the constraint to be satisfied. When the expression evaluates to < 0, the constraint is violated and a penalty is applied during optimization.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
Unique identifier for this constraint |
expression |
str
|
Mathematical expression that must evaluate >= 0 for constraint satisfaction.
Can reference calibration parameters by their IDs. When |
description |
str | None
|
Human-readable description of the constraint (optional) |
weight |
float
|
Penalty weight multiplier (default: 1.0). Higher values make this constraint more important relative to others. The amount of a violation of this constraint is weight * |violation|, summed over its positions; the loss of a point that violates constraints is P * (1 + the sum of the amounts), with P much larger than any fit. |
at |
list[float] | None
|
Optional positions on the axis at which to evaluate this constraint. The engine decides which positions its model type accepts: a DifferenceEquations model only integer steps. If None, the constraint is evaluated once before simulation using parameter values only. If given, it is evaluated at each position and can reference output values. |
Examples:
>>> # k1/k2 must be <= 5
>>> constraint = CalibrationConstraint(
... id="ratio_bound",
... expression="5.0 - k1/k2",
... description="Ratio k1/k2 <= 5",
... )
>>> # k1 must be >= k2
>>> constraint = CalibrationConstraint(
... id="ordering",
... expression="k1 - k2",
... description="k1 >= k2",
... )
>>> # Sum of parameters <= 1.0
>>> constraint = CalibrationConstraint(
... id="sum_bound",
... expression="1.0 - (param1 + param2 + param3)",
... description="Sum of rates <= 1.0",
... )
>>> # At positions: bin B stays at or below 500 at specific positions
>>> constraint = CalibrationConstraint(
... id="peak_b",
... expression="500.0 - B",
... description="Peak B never exceeds 500",
... at=[10, 20, 30, 40, 50],
... )
Source code in commol/context/calibration.py
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 | |
Methods:¶
validate_expression
classmethod
¶
Perform security validation on the constraint expression.
Source code in commol/context/calibration.py
validate_positions ¶
Validate that the positions, when given, are not empty.
Source code in commol/context/calibration.py
NelderMeadConfig ¶
Bases: RangeChecked
Configuration for the Nelder-Mead optimization algorithm.
The Nelder-Mead method is a simplex-based derivative-free optimization algorithm, suitable for problems where gradients are not available.
Attributes:
| Name | Type | Description |
|---|---|---|
max_iterations |
int
|
Maximum number of iterations (default: 1000) |
sd_tolerance |
float
|
Convergence tolerance for standard deviation (default: 1e-6) |
initial_simplex_size |
float
|
Size of the initial simplex, as a fraction of each parameter's bound
width, in (0, 1] (default: 0.1). Nelder-Mead searches an unbounded
coordinate |
alpha |
float | None
|
Reflection coefficient (default: None, uses argmin's default) |
gamma |
float | None
|
Expansion coefficient (default: None, uses argmin's default) |
rho |
float | None
|
Contraction coefficient (default: None, uses argmin's default) |
sigma |
float | None
|
Shrink coefficient (default: None, uses argmin's default) |
verbose |
bool
|
Enable verbose output during optimization (default: False) |
header_interval |
int
|
Number of iterations between table header repeats in verbose output (default: 100) |
Source code in commol/context/calibration.py
ParticleSwarmConfig ¶
Bases: RangeChecked
Configuration for the Particle Swarm Optimization algorithm.
Attributes:
| Name | Type | Description |
|---|---|---|
particles |
int
|
Number of particles in the swarm (default: 20) |
max_iterations |
int
|
Maximum number of iterations (default: 1000) |
verbose |
bool
|
Enable verbose output (default: False) |
initialization |
str
|
Particle initialization strategy (default: "uniform") |
Methods:
| Name | Description |
|---|---|
inertia |
Set inertia weight strategy ("constant" or "chaotic") |
acceleration |
Set acceleration coefficients ("constant" or "time_varying") |
mutation |
Enable mutation to escape local optima |
velocity |
Configure velocity control |
improvement_stop |
Stop when the best loss stops improving |
radius_stop |
Stop when the swarm has gathered around its best position |
Source code in commol/context/calibration.py
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 | |
Attributes¶
inertia_config
property
¶
Get the inertia configuration (for internal use).
acceleration_config
property
¶
Get the acceleration configuration (for internal use).
mutation_config
property
¶
Get the mutation configuration (for internal use).
velocity_config
property
¶
Get the velocity configuration (for internal use).
improvement_stop_config
property
¶
Get the improvement stop rule (for internal use).
radius_stop_config
property
¶
Get the radius stop rule (for internal use).
Methods:¶
inertia ¶
Set inertia weight strategy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
type
|
str
|
Inertia strategy type: "constant" or "chaotic" |
required |
**kwargs
|
float
|
The settings of the strategy, listed under Other Parameters. |
{}
|
Other Parameters:
| Name | Type | Description |
|---|---|---|
factor |
float
|
Fixed inertia weight; the default is the weight of canonical PSO, 1/(2 ln 2) ≈ 0.72135, which a swarm with no inertia strategy uses. Only used when type="constant". |
w_min |
float
|
Minimum inertia weight. Only used when type="chaotic". |
w_max |
float
|
Maximum inertia weight (must be > w_min). Only used when type="chaotic". |
Returns:
| Type | Description |
|---|---|
Self
|
The config instance for method chaining |
Source code in commol/context/calibration.py
acceleration ¶
Set acceleration coefficient strategy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
type
|
str
|
Acceleration strategy type: "constant" or "time_varying" |
required |
**kwargs
|
float
|
The settings of the strategy, listed under Other Parameters. |
{}
|
Other Parameters:
| Name | Type | Description |
|---|---|---|
cognitive |
float
|
Cognitive coefficient (c1) - attraction to personal best; the default is the coefficient of canonical PSO, 0.5 + ln 2 ≈ 1.19315, which a swarm with no acceleration strategy uses. Only used when type="constant". |
social |
float
|
Social coefficient (c2) - attraction to swarm best, with the same default. Only used when type="constant". |
c1_initial |
float
|
Initial cognitive factor (typically high, e.g., 2.5). Only used when type="time_varying". |
c1_final |
float
|
Final cognitive factor (typically low, e.g., 0.5). Only used when type="time_varying". |
c2_initial |
float
|
Initial social factor (typically low, e.g., 0.5). Only used when type="time_varying". |
c2_final |
float
|
Final social factor (typically high, e.g., 2.5). Only used when type="time_varying". |
Returns:
| Type | Description |
|---|---|
Self
|
The config instance for method chaining |
Source code in commol/context/calibration.py
mutation ¶
Enable mutation to help escape local optima.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
strategy
|
str
|
Mutation distribution: "gaussian" or "cauchy". Cauchy has heavier tails for larger jumps. |
required |
scale
|
float
|
Standard deviation (gaussian) or scale parameter (cauchy) |
required |
probability
|
float
|
Mutation probability per iteration (0.0 to 1.0) |
required |
application
|
str
|
Which particles to mutate: "global_best", "all_particles", or "below_average" |
required |
Returns:
| Type | Description |
|---|---|
Self
|
The config instance for method chaining |
Source code in commol/context/calibration.py
velocity ¶
Configure velocity control.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
clamp_factor
|
float
|
Velocity clamping as fraction of search space (0.0-1.0). Typically 0.1-0.2. Prevents explosive velocities. |
None
|
mutation_threshold
|
float
|
Reinitialize velocities below this threshold. Typically 0.001-0.01. Prevents stagnation. |
None
|
Returns:
| Type | Description |
|---|---|
Self
|
The config instance for method chaining |
Source code in commol/context/calibration.py
improvement_stop ¶
Stop when the best loss stops improving.
The run stops when the best loss improved by at most
tol_abs + tol_rel * |best loss| over the last window iterations,
and reports converged=True. Off by default. A swarm can stall for
some iterations and then improve again, so a short window can stop it
early.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window
|
int
|
Iterations over which the improvement is measured (> 0). |
required |
tol_abs
|
float
|
Absolute tolerance on the improvement (>= 0). |
required |
tol_rel
|
float
|
Tolerance on the improvement relative to the best loss (>= 0). |
required |
Returns:
| Type | Description |
|---|---|
Self
|
The config instance for method chaining |
Source code in commol/context/calibration.py
radius_stop ¶
Stop when the swarm has gathered around its best position.
The run stops when the largest distance of a particle from the best
position, divided by the size of the search box, is at most tol, and
reports converged=True. Off by default. Mutation and velocity
mutation scatter the swarm again, so with them the radius can stay
above tol; values that the data do not tell apart keep the swarm
spread.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tol
|
float
|
Tolerance on the radius of the swarm, relative to the size of the search box (>= 0). |
required |
Returns:
| Type | Description |
|---|---|
Self
|
The config instance for method chaining |
Source code in commol/context/calibration.py
CalibrationResult ¶
Bases: ResultModel, RangeChecked
Result of a calibration: the best of its starts.
Attributes:
| Name | Type | Description |
|---|---|---|
best_parameters |
dict[str, float]
|
The calibrated value of each parameter, in the order of the problem's parameters. |
final_loss |
float
|
Loss at the best parameters. |
iterations |
int
|
Iterations of the best start. |
converged |
bool
|
Whether the best start converged. |
termination_reason |
str
|
Why the best start stopped. |
starts |
list[StartSummary]
|
Every start that finished, in order; the first is the initial guess. |
failed |
list[str]
|
Each start that failed: |
seed |
int
|
The seed of the calibration's random numbers ( |
Source code in commol/context/calibration.py
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 | |
Methods:¶
__str__ ¶
String representation of calibration result.
Source code in commol/context/calibration.py
StartSummary ¶
Bases: ResultModel
One start of a multi-start optimization.
Distinct ends with equal losses are a sign that the data do not identify the parameters.
Attributes:
| Name | Type | Description |
|---|---|---|
start |
dict[str, float]
|
The point the optimizer started from. |
end |
dict[str, float]
|
The best point it found. |
loss |
float
|
The loss at the end. |
converged |
bool
|
Whether the optimizer met its convergence criterion. |
Source code in commol/context/calibration.py
CalibrationHistory ¶
Bases: ResultModel
A calibration and every evaluation of a feasible point it made.
Attributes:
| Name | Type | Description |
|---|---|---|
result |
CalibrationResult
|
The result of the calibration. |
evaluations |
list[CalibrationEvaluation]
|
Every evaluation of a feasible point, in the order they were made. |
Source code in commol/context/calibration.py
CalibrationEvaluation ¶
Bases: ResultModel
One evaluation of a feasible point during an optimization.
Attributes:
| Name | Type | Description |
|---|---|---|
parameters |
dict[str, float]
|
The values the objective scored. |
loss |
float
|
The loss at these values. |
Source code in commol/context/calibration.py
LossFunction ¶
Bases: StrEnum
Available loss functions for calibration.
Values
SSE Sum of Squared Errors RMSE Root Mean Squared Error MAE Mean Absolute Error