Uncertainty API¶
What every uncertainty method takes and returns: the configuration bases, the weighted parameter sample, the predictive and its observation noise, and the scenarios. Then the methods of each family with their results (resampling, profile likelihood, sequential Monte Carlo, local approximations and conformal prediction), the scores and the one quantile. Guide: Uncertainty.
InferenceMethod ¶
Bases: BaseModel, Generic[ResultT]
The configuration of a method that reads a calibration problem or a
sensitivity analysis, whose result is ResultT.
A method subclasses one of its kinds, UncertaintyMethod,
IdentifiabilityMethod or SensitivityMethod, with its result type, and
registers its runner (commol.api.inference.registry.register).
Source code in commol/context/inference/method.py
UncertaintyMethod ¶
Bases: InferenceMethod[ResultT], Generic[ResultT]
The configuration of an uncertainty method, whose result is ResultT.
A method subclasses it with its result type, for example
class BayesianBootstrap(UncertaintyMethod[BootstrapResult]), and
registers its runner (commol.api.inference.registry.register).
Calibrator.uncertainty(method) returns that result type, so a static
type checker infers it from the configuration's type.
Source code in commol/context/inference/method.py
ParameterSample ¶
Bases: ResultModel
Draws of the parameters of a calibration problem, each with a weight.
A method that has draws returns them in a sample: a bootstrap, a sequential Monte Carlo run, a Markov chain. Plots, reports, the predictive and the scores read a sample, never the result of one method. Every statistic is weighted and computed in Rust; with equal weights it is the unweighted statistic.
A sample has no single set of parameters: to run one draw, take it from
draws.
Attributes:
| Name | Type | Description |
|---|---|---|
names |
list[str]
|
One name per column, in the order of the problem's parameters. |
bounds |
list[tuple[float, float]]
|
The bounds of each parameter; every value lies inside them. |
values |
list[list[float]]
|
One row per draw, one column per name. |
log_weights |
list[float]
|
The natural logarithm of each draw's weight, normalized so that the
weights sum to 1. A draw of weight zero has |
groups |
list[int] | None
|
The group of each draw (a chain, a replicate or a wave), or None. |
method |
SampleMethod
|
What made the sample. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a value is not finite or outside its bounds, a log weight is NaN or
|
Source code in commol/context/inference/sample.py
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 | |
Attributes¶
rust_sample
property
¶
The sample in Rust, for the runners of methods and the predictive.
effective_size
property
¶
Kish's effective sample size, 1 / Σ wᵢ²: between 1 and the number
of draws; equal weights give the number of draws.
Methods:¶
normalize_log_weights
classmethod
¶
Check the invariants in Rust and normalize the log weights; with a field before them that is not valid, pydantic reports that field.
Source code in commol/context/inference/sample.py
build_rust_sample ¶
Keep the Rust sample that computes the statistics.
Source code in commol/context/inference/sample.py
equally_weighted
classmethod
¶
equally_weighted(names: list[str], bounds: list[tuple[float, float]], values: list[list[float]], method: SampleMethod, groups: list[int] | None = None) -> Self
A sample whose draws have equal weights.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
names
|
list[str]
|
One name per column. |
required |
bounds
|
list[tuple[float, float]]
|
The bounds of each parameter. |
required |
values
|
list[list[float]]
|
One row per draw. |
required |
method
|
SampleMethod
|
What made the sample. |
required |
groups
|
list[int] | None
|
The group of each draw. |
None
|
Returns:
| Type | Description |
|---|---|
ParameterSample
|
The sample. |
Source code in commol/context/inference/sample.py
__len__ ¶
draws ¶
Every draw, as a mapping of parameter name to value.
Yields:
| Type | Description |
|---|---|
dict[str, float]
|
One draw, in the order of |
Source code in commol/context/inference/sample.py
mean ¶
The weighted mean of each parameter.
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
One mean per name. |
covariance ¶
The weighted covariance matrix, in the order of names.
With weights w that sum to 1 it is
Σ wᵢ(xᵢ − x̄)(yᵢ − ȳ) / (1 − Σ wᵢ²): with equal weights, the
sample covariance. It is NaN for a sample of one effective draw.
Returns:
| Type | Description |
|---|---|
list[list[float]]
|
One row per name. |
Source code in commol/context/inference/sample.py
correlation ¶
The weighted correlation matrix, in the order of names.
Returns:
| Type | Description |
|---|---|
list[list[float]]
|
One row per name; NaN for a parameter with no spread. |
Source code in commol/context/inference/sample.py
quantiles ¶
The weighted quantiles of each parameter.
The quantile is the inverse of the weighted empirical distribution,
interpolated between the midpoints of the cumulative weights; with
equal weights it is NumPy's method="hazen".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
levels
|
list[float]
|
Quantile levels, each between 0 and 1. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, list[float]]
|
One quantile per level for each name. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a level is not between 0 and 1. |
Source code in commol/context/inference/sample.py
interval ¶
The central interval of each parameter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
confidence_level
|
float
|
Strictly between 0 and 1, such as 0.95. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, tuple[float, float]]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the confidence level is not strictly between 0 and 1. |
Source code in commol/context/inference/sample.py
resample ¶
resample(count: int, seed: int) -> ParameterSample
Draw count draws with replacement, each with probability its weight.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
count
|
int
|
Number of draws. |
required |
seed
|
int
|
Seed of the generator. |
required |
Returns:
| Type | Description |
|---|---|
ParameterSample
|
A sample of equal weights. |
Source code in commol/context/inference/sample.py
summary ¶
summary(confidence_level: float) -> dict[str, ParameterSummary]
Weighted statistics of each parameter, for a report.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
confidence_level
|
float
|
Confidence level of the interval, strictly between 0 and 1. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, ParameterSummary]
|
One summary per name. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the confidence level is not strictly between 0 and 1. |
Source code in commol/context/inference/sample.py
SampleMethod ¶
Bases: ResultModel
What made a sample: the name of the method and its settings.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The name of the method, such as |
settings |
dict[str, JsonValue]
|
The settings the method ran with. |
Source code in commol/context/inference/sample.py
ParameterSummary ¶
Bases: ResultModel
Weighted statistics of one parameter of a sample.
Attributes:
| Name | Type | Description |
|---|---|---|
mean |
float
|
The weighted mean. |
median |
float
|
The weighted median. |
std |
float
|
The weighted standard deviation ( |
lower |
float
|
The lower end of the central interval of the confidence level. |
upper |
float
|
The upper end of the central interval of the confidence level. |
min |
float
|
The smallest value of positive weight. |
max |
float
|
The largest value of positive weight. |
Source code in commol/context/inference/sample.py
Predictive ¶
The run of every draw of a parameter sample.
The draws run in parallel in Rust, through the forward model of a calibration problem or of a sensitivity analysis: with a stochastic engine every replicate of a draw is a draw of the predictive, with an equal share of its weight. A band reduces the draws position by position with their weights; without observation noise it is a band of the model, not a prediction interval.
Source code in commol/api/inference/predictive.py
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 | |
Attributes¶
draw_seeds
property
¶
The seed of each draw of sample, in its order.
With a stochastic engine, replicate i of draw j runs with the
seed replicate i of Simulation.replicates(count, seed=draw_seeds[j])
takes, so those replicates of the model at that draw give its runs.
plot
property
¶
plot: PredictivePlot
The figures of the draws: plot.series() and plot.cumulative(),
the weighted median and the band of each series.
Methods:¶
__init__ ¶
__init__(source: PredictiveSource, sample: ParameterSample, positions: Sequence[float]) -> None
Run every draw of sample at positions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
PredictiveSource
|
The calibration problem the sample is a sample of ( |
required |
sample
|
ParameterSample
|
Its parameters, in the order of the problem or the analysis. |
required |
positions
|
Sequence[float]
|
Positions to report at, sorted and unique. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
Before any draw runs: if the sample's parameters are not the source's, or the positions are not sorted and unique or the engine does not report at one of them (a difference engine reports only at integer steps). |
InfeasibleStateError
|
If a draw leaves the values its model allows. The message names the parameter set, then says what the run says (the compartment, the step and the flows), or what the initial amounts exceed. |
Source code in commol/api/inference/predictive.py
runs ¶
runs() -> list[SimulationResults]
The trajectory of every draw, in the order of weights.
Returns:
| Type | Description |
|---|---|
list[SimulationResults]
|
One run per draw, at |
Source code in commol/api/inference/predictive.py
quantities ¶
The quantities of interest of every draw, in the order of weights.
Each run is reduced on its own, as SimulationResults.quantities
reduces one, with the Rust code of Propagation. The predictive runs
at positions, so they must hold quantity_schedule(quantities).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
quantities
|
Sequence[Quantity]
|
The quantities; a |
required |
Returns:
| Type | Description |
|---|---|
list[dict[str, float]]
|
One dict per draw of the predictive, with one value per label of the quantities. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If there is no quantity, two scalars have one label, a quantity
names an output the model does not have, or |
Source code in commol/api/inference/predictive.py
report ¶
report(confidence_level: float, positions: Sequence[float], window: float, windows: int, observed_data: Iterable[ObservedDataPoint] = (), accumulators: Iterable[str] = (), prediction_intervals: PredictionIntervals | None = None) -> SimulationReport
Report the runs of the draws as SimulationResults.report reports one.
Every number becomes a {mean, median, ci_lower, ci_upper, min,
max} block, reduced draw by draw with the weights of the draws; the
layout is the one of the report of a run. Each leaf comes from the
draws only, so the report takes no point estimate. The outputs of an
accumulator come from the model of the source.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
confidence_level
|
float
|
Confidence level of the reported intervals, strictly between 0 and 1. |
required |
positions
|
Sequence[float]
|
Positions the series and cumulative accumulators are sampled at;
each must be one of |
required |
window
|
float
|
Length of one window on the axis. |
required |
windows
|
int
|
Number of windows on the observed and windowed axes. |
required |
observed_data
|
Iterable[ObservedDataPoint]
|
The calibration targets to report alongside the draws. |
()
|
accumulators
|
Iterable[str]
|
Accumulator ids to report. |
()
|
prediction_intervals
|
PredictionIntervals | None
|
Prediction intervals of a conformal method
( |
None
|
Returns:
| Type | Description |
|---|---|
SimulationReport
|
Keys |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the confidence level is out of range, or the predictive has no value at a position the report reads. |
KeyError
|
If an accumulator is not a bin or accumulator of the model. |
Source code in commol/api/inference/predictive.py
band ¶
band(confidence_level: float) -> PredictiveBand
The band of every output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
confidence_level
|
float
|
Strictly between 0 and 1. |
required |
Returns:
| Type | Description |
|---|---|
PredictiveBand
|
The weighted mean, median and central interval of each output at each position. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the confidence level is not strictly between 0 and 1. |
Source code in commol/api/inference/predictive.py
series_band ¶
series_band(outputs: Sequence[str], confidence_level: float, cumulative: bool = False) -> SeriesBand
The band of the sum of some outputs, or of its running total.
Each draw is reduced to the series first, then the series are reduced across the draws.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
outputs
|
Sequence[str]
|
The outputs summed. |
required |
confidence_level
|
float
|
Strictly between 0 and 1. |
required |
cumulative
|
bool
|
Whether the series is the running total along the positions. |
False
|
Returns:
| Type | Description |
|---|---|
SeriesBand
|
One value per position. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If an output is unknown or the confidence level is out of range. |
Source code in commol/api/inference/predictive.py
at_observations ¶
at_observations(observed_data: Sequence[ObservedDataPoint], noise: ObservationNoise) -> ObservationDraws
Every draw's value of each observation, with observation noise.
The observations need not be the ones the problem was fitted to: held out data are read the same way, through the observation operator, and so are the observations of the model of an analysis. The noise is drawn from the calibrator's seed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
observed_data
|
Sequence[ObservedDataPoint]
|
The observations. |
required |
noise
|
NoNoise | ResidualNoise | DistributionNoise
|
What an observation shows around a draw's prediction, with no
default: |
required |
Returns:
| Type | Description |
|---|---|
ObservationDraws
|
Each draw's value of each observation. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If an observation names an unknown output or factor, a series the
residual noise has no residuals of, or a series with no
observation model; |
InfeasibleStateError
|
If a draw leaves the values its model allows. The message names the parameter set, then says what the run says (the compartment, the step and the flows), or what the initial amounts exceed. |
Source code in commol/api/inference/predictive.py
PredictiveBand ¶
Bases: ResultModel
The band of every output of a predictive.
Attributes:
| Name | Type | Description |
|---|---|---|
confidence_level |
float
|
The level of the central interval. |
positions |
list[float]
|
Where the values are. |
mean, median, lower, upper |
dict[str, list[float]]
|
For each output, one value per position, reduced across the draws with their weights. |
Source code in commol/api/inference/predictive.py
SeriesBand ¶
Bases: ResultModel
The band of one series: four values at each of its positions.
Attributes:
| Name | Type | Description |
|---|---|---|
confidence_level |
float
|
The level of the central interval. |
positions |
list[float]
|
Where the values are. |
mean |
list[float]
|
The weighted mean across the draws. |
median |
list[float]
|
The weighted median. |
lower |
list[float]
|
The quantile |
upper |
list[float]
|
The quantile |
Source code in commol/api/inference/predictive.py
ObservationDraws ¶
Every draw's value of a set of observations.
The values are read through the observation operator of the calibration problem (sums of outputs, windows, factors), the one the loss uses. Without observation noise their interval is a band of the model, not a prediction interval.
Source code in commol/api/inference/predictive.py
Attributes¶
values
property
¶
Each draw's value of each observation, [draw][observation].
Methods:¶
__init__ ¶
__init__(observations: Sequence[ObservedDataPoint], draws: ObservationDrawsProtocol) -> None
Wrap the draws of observations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
observations
|
Sequence[ObservedDataPoint]
|
The observations, in the order of each draw's values. |
required |
draws
|
ObservationDrawsProtocol
|
The draws, computed in Rust. |
required |
Source code in commol/api/inference/predictive.py
band ¶
band(confidence_level: float) -> SeriesBand
The band of each observation across the draws.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
confidence_level
|
float
|
Strictly between 0 and 1. |
required |
Returns:
| Type | Description |
|---|---|
SeriesBand
|
One value per observation, at its position. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the confidence level is not strictly between 0 and 1. |
Source code in commol/api/inference/predictive.py
Scenarios ¶
Bases: Mapping[str, Predictive]
Every draw of a sample run under each scenario, with the draws paired.
A scenario is a set of parameter values that override those of the model
of the source; the source and its model stay unchanged. Each scenario
holds the Predictive of the sample on a copy of the model with its
values, built from the source with the seed of the source
(with_model). So run k of every scenario is the same draw, and with
a stochastic engine it runs with the same seed: common random numbers,
whose noise cancels in a difference.
Scenarios is a mapping from the name of a scenario to its Predictive,
so plot_compared(scenarios) draws them on the same panels.
Source code in commol/api/inference/scenarios.py
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 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 | |
Attributes¶
weights
property
¶
The weight of each run, the same in every scenario; they sum to 1.
Methods:¶
__init__ ¶
__init__(source: PredictiveSource, sample: ParameterSample, scenarios: Mapping[str, Mapping[str, ParameterUpdate]], positions: Sequence[float]) -> None
Run every draw of sample under each scenario, at positions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
PredictiveSource
|
The calibration problem the sample is a sample of ( |
required |
sample
|
ParameterSample
|
Its parameters, in the order of the problem or the analysis. |
required |
scenarios
|
Mapping[str, Mapping[str, ParameterUpdate]]
|
Each scenario by name: the value of each parameter it overrides,
any value |
required |
positions
|
Sequence[float]
|
Positions to report at, sorted and unique. A comparison reads the
runs here, so they hold |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
Before any draw runs: if there is no scenario, a scenario sets a
parameter of the sample or one the model does not have (the
message names the scenario and the parameter), or a value does
not fit the model. Then as |
InfeasibleStateError
|
If a draw leaves the values its model allows, as |
Source code in commol/api/inference/scenarios.py
__getitem__ ¶
__getitem__(name: str) -> Predictive
The predictive of one scenario.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the scenario. |
required |
Returns:
| Type | Description |
|---|---|
Predictive
|
The runs of every draw under the scenario. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If there is no scenario of that name; the message lists the names. |
Source code in commol/api/inference/scenarios.py
__iter__ ¶
__len__ ¶
summary ¶
summary(name: str, quantities: Sequence[QuantityBase], confidence_level: float) -> list[ScenarioSummary]
The weighted distribution of each quantity across the runs of one scenario.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The scenario. |
required |
quantities
|
Sequence[Quantity]
|
The quantities; a |
required |
confidence_level
|
float
|
Strictly between 0 and 1. |
required |
Returns:
| Type | Description |
|---|---|
list[ScenarioSummary]
|
One summary per label of the quantities, in their order. With one run, the value of that run and no interval. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If there is no scenario of that name. |
ValueError
|
If the confidence level is not strictly between 0 and 1, a
quantity does not fit the runs (as |
Source code in commol/api/inference/scenarios.py
compare ¶
compare(name: str, baseline: str, quantities: Sequence[QuantityBase], confidence_level: float) -> list[ScenarioSummary]
The weighted distribution of the difference of each quantity between two scenarios, taken run by run.
The difference name − baseline is taken within each run, where
both scenarios have the same draw and seed, and then reduced across
the runs with their weights. So its interval is the interval of the
paired differences, not the difference of two intervals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The scenario compared. |
required |
baseline
|
str
|
The scenario subtracted. |
required |
quantities
|
Sequence[Quantity]
|
The quantities; a |
required |
confidence_level
|
float
|
Strictly between 0 and 1. |
required |
Returns:
| Type | Description |
|---|---|
list[ScenarioSummary]
|
One summary per label of the quantities, in their order. With one run, the difference of that run and no interval. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If there is no scenario of either name. |
ValueError
|
If the confidence level is not strictly between 0 and 1, a
quantity does not fit the runs (as |
Source code in commol/api/inference/scenarios.py
ScenarioSummary ¶
Bases: ResultModel
The weighted distribution of one quantity across the runs of a scenario, or of its difference between two scenarios.
Attributes:
| Name | Type | Description |
|---|---|---|
label |
str
|
The quantity, as |
confidence_level |
float
|
The level of the central interval. |
mean |
float
|
The weighted mean. |
median |
float
|
The weighted median. |
lower |
float | None
|
The quantile |
upper |
float | None
|
The quantile |
Source code in commol/api/inference/scenarios.py
NoNoise ¶
Bases: BaseModel
No observation noise: an observation shows the prediction of each draw.
The band of a predictive with NoNoise is a band of the model. It says
where the model curve lies, not where the next observation falls, so its
coverage of data is below its level.
Source code in commol/context/inference/noise.py
ResidualNoise ¶
Bases: RangeChecked
Observation noise made of the residuals of a fit, with no noise model.
Each draw adds moving blocks of block_length positions of residuals of
the fit, drawn with replacement across every series at once, to its
predictions, on residual_scale. The band is then a prediction interval.
It serves the series the fit has residuals of, at any position: the
residual of a series at a drawn position is the one at the nearest
position where the series was observed.
Attributes:
| Name | Type | Description |
|---|---|---|
fit |
CalibrationResult
|
The fit whose residuals are added. |
block_length |
int
|
Positions per block, at least 1 and at most the number of distinct positions of the problem's observations. A bootstrap reports the length it used in its diagnostics. |
residual_scale |
{additive, multiplicative}
|
|
Source code in commol/context/inference/noise.py
DistributionNoise ¶
Bases: BaseModel
Observation noise of the problem's observation models.
Each draw draws every observation from the model of its series around
the draw's prediction, with the draw's noise parameters, so the band is a
prediction interval of the posterior or bootstrap predictive. It needs a
problem with observation_models, and serves the series they name. A
prediction outside the means a model allows, such as a negative count,
draws at the nearest allowed one.
Source code in commol/context/inference/noise.py
Resampling¶
Guide: Resampling.
BayesianBootstrap ¶
Bases: UncertaintyMethod[BootstrapResult], RangeChecked
The Bayesian (weighted) bootstrap by blocks.
Each replicate draws one Dirichlet(1, …, 1) weight per block, scaled to mean 1, multiplies the weight of every observation of the block by it, and fits. With a loss it is the loss-likelihood bootstrap of Lyddon, Holmes and Walker (2019); with one position per block, the Bayesian bootstrap of Rubin (1981) and the weighted likelihood bootstrap of Newton and Raftery (1994). The observed values never change.
Attributes:
| Name | Type | Description |
|---|---|---|
replicates |
int
|
Number of replicates, at least 1. |
block_length |
int | auto
|
Positions per block. |
starts |
int
|
Starts of the fit and of each replicate (default 1): the fit, then rows of a Latin hypercube over the bounds. |
Source code in commol/context/inference/resampling.py
ResidualBootstrap ¶
Bases: UncertaintyMethod[BootstrapResult], RangeChecked
The residual block bootstrap.
Each replicate joins blocks of residuals of the fit, drawn with
replacement across every series at once, adds them to the fitted values
on residual_scale, and fits the synthetic data.
Attributes:
| Name | Type | Description |
|---|---|---|
replicates |
int
|
Number of replicates, at least 1. |
block_length |
int | auto
|
Positions per block; with |
residual_scale |
{additive, multiplicative}
|
|
scheme |
{moving, stationary}
|
|
starts |
int
|
Starts of the fit and of each replicate (default 1). |
Source code in commol/context/inference/resampling.py
WildBootstrap ¶
Bases: UncertaintyMethod[BootstrapResult], RangeChecked
The wild block bootstrap.
Each replicate multiplies the additive residuals of each block by one
draw of multipliers and fits ŷ + r · v. Every residual stays at its
own position, so it holds under noise whose size changes along the
series.
Attributes:
| Name | Type | Description |
|---|---|---|
replicates |
int
|
Number of replicates, at least 1. |
block_length |
int | auto
|
Positions per block. |
multipliers |
{rademacher, mammen}
|
|
starts |
int
|
Starts of the fit and of each replicate (default 1). |
Source code in commol/context/inference/resampling.py
BlockJackknife ¶
Bases: UncertaintyMethod[JackknifeResult], RangeChecked
The block jackknife (Künsch 1989): one fit per block left out.
It gives a standard error and a bias of each parameter, and the influence of each block, with as many fits as blocks. A block is left out by giving its observations weight 0.
Attributes:
| Name | Type | Description |
|---|---|---|
block_length |
int | auto
|
Positions per block; it must leave at least two blocks. |
starts |
int
|
Starts of the fit and of each leave-out fit (default 1). |
Source code in commol/context/inference/resampling.py
ParametricBootstrap ¶
Bases: UncertaintyMethod[BootstrapResult], RangeChecked
The parametric bootstrap of the problem's observation models.
Each replicate draws every observed value from the model of its series
at the fit, around the fitted prediction and with the fitted noise
parameters, and fits the new data. It needs a problem with
observation_models; the observations of a replicate are independent
given the fit, so it assumes the models hold.
Attributes:
| Name | Type | Description |
|---|---|---|
replicates |
int
|
Number of replicates, at least 1. |
starts |
int
|
Starts of the fit and of each replicate (default 1): the fit, then rows of a Latin hypercube over the bounds. |
Source code in commol/context/inference/resampling.py
BootstrapResult ¶
Bases: ResultModel
The result of a bootstrap.
Attributes:
| Name | Type | Description |
|---|---|---|
fit |
CalibrationResult
|
The fit every replicate starts from: |
sample |
ParameterSample
|
One draw per replicate that did not fail, with equal weights; the group of a draw is its replicate. |
failed |
list[str]
|
Each replicate that failed: |
not_converged |
int
|
Replicates kept although their optimizer did not converge. |
diagnostics |
ResamplingDiagnostics
|
The block length, and the synthetic values below zero. |
Source code in commol/context/inference/resampling.py
Methods:¶
interval_error ¶
interval_error(confidence_level: float) -> dict[str, BoundError]
The Monte Carlo error of the central interval of each parameter.
More replicates make it smaller; when it is wide against the interval, run more.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
confidence_level
|
float
|
Strictly between 0 and 1. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, BoundError]
|
The error of each bound, by parameter. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the confidence level is not strictly between 0 and 1. |
Source code in commol/context/inference/resampling.py
JackknifeResult ¶
Bases: ResultModel
The result of a block jackknife.
With B fits θ̂₍₋ᵦ₎ that leave one block out, around the fit
θ̂, and their mean θ̄: the bias is (B − 1)(θ̄ − θ̂), the
standard error √((B − 1)/B · Σ (θ̂₍₋ᵦ₎ − θ̄)²), and the pseudo-value of
block b is B θ̂ − (B − 1) θ̂₍₋ᵦ₎. The pseudo-values are not draws:
their percentiles are not an interval.
Attributes:
| Name | Type | Description |
|---|---|---|
fit |
CalibrationResult
|
The fit with every observation. |
estimate |
dict[str, float]
|
The bias-corrected estimate of each parameter. |
bias |
dict[str, float]
|
The jackknife bias of each parameter. |
standard_error |
dict[str, float]
|
The jackknife standard error of each parameter. |
blocks |
list[tuple[float, float]]
|
The first and last position of each block that was left out and fitted, in order. |
pseudo_values |
dict[str, list[float]]
|
The pseudo-values of each parameter, one per block. |
influence |
dict[str, list[float]]
|
How far leaving each block out moves each parameter, in standard
errors: |
failed |
list[str]
|
Each block whose fit failed: |
not_converged |
int
|
Fits kept although their optimizer did not converge. |
diagnostics |
ResamplingDiagnostics
|
The block length. |
Source code in commol/context/inference/resampling.py
ResamplingDiagnostics ¶
Bases: ResultModel
The blocks of a resampling method, and the synthetic values below zero.
Attributes:
| Name | Type | Description |
|---|---|---|
block_length |
int | None
|
The block length the method ran with; None for the parametric bootstrap, which draws no blocks. |
block_length_estimates |
dict[str, float] | None
|
With |
negative_values |
int
|
Synthetic observed values below zero, over every replicate. They are
kept; many of them point to |
Source code in commol/context/inference/resampling.py
BoundError ¶
Bases: ResultModel
The Monte Carlo error of the bounds of an interval: for each bound, an order-statistic interval that holds the bound of infinitely many replicates with about 95 % probability.
Attributes:
| Name | Type | Description |
|---|---|---|
lower |
tuple[float, float]
|
The error interval of the lower bound. |
upper |
tuple[float, float]
|
The error interval of the upper bound. |
Source code in commol/context/inference/resampling.py
Profile likelihood¶
Guide: Profile Likelihood.
ProfileLikelihood ¶
Bases: UncertaintyMethod['ProfileResult'], RangeChecked
The profile likelihood of parameters (Raue et al. 2009).
Each parameter is held at values that step away from the fit, in both
directions, and the others are fitted again with the problem's own
optimizer. The step grows while the profile rises slowly and shrinks
when it jumps, and each point starts from a line through the two points
before it. A side ends past the threshold, at a bound, or after
max_steps points. Parameters run in parallel.
Attributes:
| Name | Type | Description |
|---|---|---|
parameters |
list[str]
|
The parameters to profile, at least one. |
threshold |
Threshold
|
The threshold of the statistic. |
max_steps |
int
|
The most points on each side of a profile (default 100). |
starts |
int
|
Starts of the fit (default 1): the fit, then rows of a Latin hypercube over the bounds. |
Source code in commol/context/inference/profiles.py
PredictionProfile ¶
Bases: UncertaintyMethod['ProfileResult'], RangeChecked
The profile likelihood of predictions (Kreutz et al. 2012).
Each prediction is held at values that step away from its value at the fit, as an equality constraint met by an augmented Lagrangian whose inner solver is the problem's own optimizer, and the parameters are fitted again. The interval of a prediction is the set of values the data do not reject; several specs at several positions give a band.
Attributes:
| Name | Type | Description |
|---|---|---|
specs |
list[PredictionSpec]
|
The predictions, at least one, with distinct labels. |
threshold |
Threshold
|
The threshold of the statistic. |
max_steps |
int
|
The most points on each side of a profile (default 100). |
starts |
int
|
Starts of the fit (default 1). |
Source code in commol/context/inference/profiles.py
Methods:¶
check_labels ¶
Each prediction has a label of its own.
Source code in commol/context/inference/profiles.py
PredictionSpec ¶
Bases: RangeChecked
A prediction to profile: an output, or a sum of outputs, at a position, read as an observation is.
Attributes:
| Name | Type | Description |
|---|---|---|
at |
float
|
The position. |
output |
str | None
|
The output. Give either |
outputs |
list[str] | None
|
Outputs summed. Needs a |
label |
str
|
The name of the prediction in the result; defaults to |
window |
float | None
|
A window length: the prediction is the output at |
factor_id |
str | None
|
A factor parameter that multiplies the prediction. |
Source code in commol/context/inference/profiles.py
Methods:¶
as_observation ¶
as_observation() -> ObservedDataPoint
The observation that reads this prediction; its value is not read.
Returns:
| Type | Description |
|---|---|
ObservedDataPoint
|
The observation. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the outputs or the label are not valid. |
Source code in commol/context/inference/profiles.py
Threshold ¶
Bases: RangeChecked
How far the statistic of a profile may rise above the fit inside an
interval of confidence_level.
Build one with chi_square, beale or bootstrap_calibrated.
Attributes:
| Name | Type | Description |
|---|---|---|
kind |
{chi_square, beale, bootstrap_calibrated}
|
The rule. |
confidence_level |
float
|
The level of each pointwise interval, strictly between 0 and 1. |
bootstrap |
BayesianBootstrap | ParametricBootstrap | ResidualBootstrap | WildBootstrap | None
|
The bootstrap of |
Source code in commol/context/inference/profiles.py
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 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 | |
Methods:¶
check_bootstrap ¶
A bootstrap goes with "bootstrap_calibrated", and only with it.
Source code in commol/context/inference/profiles.py
chi_square
classmethod
¶
½ χ²₁(confidence_level) on −log L (Wilks): the threshold of a
problem with observation models.
It assumes that the models hold and that the statistic is near its large-sample distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
confidence_level
|
float
|
The level of each interval, strictly between 0 and 1. |
required |
Returns:
| Type | Description |
|---|---|
Threshold
|
The threshold. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in commol/context/inference/profiles.py
beale
classmethod
¶
Beale's threshold of a sum of squares:
S(θ̂) · F(1, n − p; confidence_level) / (n − p), with n
observations of positive weight and p parameters.
It assumes independent Gaussian errors of one variance, and is exact
for a model linear in its parameters. It needs the loss "sse".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
confidence_level
|
float
|
The level of each interval, strictly between 0 and 1. |
required |
Returns:
| Type | Description |
|---|---|
Threshold
|
The threshold. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in commol/context/inference/profiles.py
bootstrap_calibrated
classmethod
¶
The threshold of each quantity calibrated by bootstrap
(prepivoting, Beran 1988), for any loss.
Each replicate of the bootstrap, rebuilt from the problem's seed as
Calibrator.uncertainty(bootstrap) builds it, is fitted
(θ̂_b) and then fitted again with the quantity held at its value
at the fit of the original data: the rise of the replicate is
PL_b(θ̂ⱼ) − L_b(θ̂_b). The threshold is the quantile
confidence_level of the rises. It costs one fit and one refit per
quantity for each replicate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bootstrap
|
BayesianBootstrap | ParametricBootstrap | ResidualBootstrap | WildBootstrap
|
The bootstrap, with its replicates and starts. |
required |
confidence_level
|
float
|
The level of each interval, strictly between 0 and 1. |
required |
Returns:
| Type | Description |
|---|---|
Threshold
|
The threshold. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in commol/context/inference/profiles.py
ProfileResult ¶
Bases: _FrozenResult
The result of a profile likelihood.
Attributes:
| Name | Type | Description |
|---|---|---|
fit |
CalibrationResult
|
The fit every profile starts from. |
quantity |
{parameter, prediction}
|
What the profiles hold fixed: parameters ( |
threshold |
Threshold
|
The threshold the profiles ran with. |
profiles |
dict[str, Profile]
|
The profile of each parameter or prediction, by name. |
intervals |
dict[str, ProfileInterval]
|
The interval of each. |
verdicts |
dict[str, ProfileVerdictName | None]
|
What the shape of each profile says: |
structure |
dict[str, ProfileStructure]
|
For each profile of a parameter that does not cross on both sides, what resetting the other parameters says. |
tolerance |
float
|
The numerical tolerance of the statistic: |
evaluation_floor |
float | None
|
The floor of a comparison of two evaluations of the objective; None when it cannot be computed. |
notes |
list[str]
|
What a reader should know, such as a threshold below the tolerance or a refit below the fit. |
failed |
list[str]
|
With a bootstrap threshold, each replicate that failed:
|
not_converged |
int
|
With a bootstrap threshold, the replicates kept although their optimizer did not converge; 0 with any other threshold. |
Source code in commol/context/inference/profiles.py
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 | |
Methods:¶
plot ¶
plot(output_file: str | None = None, config: PlotConfig | None = None, axes: Figure | None = None) -> Figure
Draw each profile: one panel per parameter or prediction, with the statistic of each point, the threshold, and the ends of the interval.
A profile that stays under the threshold up to a bound is open on that side; a flat one stays near 0 over its whole range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_file
|
str | None
|
Path to save the figure to. If None, the figure is only returned. |
None
|
config
|
PlotConfig | None
|
Layout and style. If None, the defaults. |
None
|
axes
|
Figure | None
|
A figure of commol to draw on: each panel is the |
None
|
Returns:
| Type | Description |
|---|---|
Figure
|
The matplotlib figure. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
ImportError
|
If matplotlib is not installed ( |
Source code in commol/context/inference/profiles.py
identifiability ¶
identifiability() -> IdentifiabilityReport
The verdicts of the profiled parameters as an identifiability report,
with a profile section; its report() gives them as data.
identifiable gives the practical verdict determined and
practically_non_identifiable the practical verdict
poorly_determined. structurally_non_identifiable gives the
structural verdict of its structure, in_combination or
non_identifiable, with no combination: the reason names the
compensating parameters. A flat profile with no structural verdict
gives the practical verdict poorly_determined. Every reason says
that the verdict holds with the other parameters at their fitted
values. A parameter with no profile, or no verdict, gets neither.
IdentifiabilityReport.merge joins it with the reports of other
methods.
Returns:
| Type | Description |
|---|---|
IdentifiabilityReport
|
One entry per parameter of the problem, in problem order. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the result holds prediction profiles, which have no verdict on a parameter. |
Source code in commol/context/inference/profiles.py
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 | |
Profile ¶
Bases: _FrozenResult
The profile of one parameter or prediction.
Attributes:
| Name | Type | Description |
|---|---|---|
center |
float
|
The value at the fit. |
threshold |
float
|
The threshold of the statistic. |
values |
list[float]
|
The value of each point, increasing; the fit is one of them. |
statistics |
list[float]
|
The statistic of each point: the objective of its refit less that of the fit. |
parameters |
list[dict[str, float]]
|
Every parameter of each refit. |
multipliers |
list[float | None]
|
For a prediction, the multiplier of each point: minus the slope of the profile there. |
converged |
list[bool]
|
Whether each refit converged. |
ends |
tuple[ProfileEndName, ProfileEndName]
|
Why the side below and the side above the fit end. |
evaluations |
int
|
Evaluations of the objective. |
replicate_rises |
list[float] | None
|
With a bootstrap threshold, the rise of each replicate kept. |
box_crossings |
tuple[str | None, str | None]
|
For the side below and the side above, the free parameter whose bound
makes the profile cross the threshold: it is on a bound at the
crossing point that it is not on over the whole side from the fit.
Such a side counts as open; its interval end stays, flagged in
|
refit_error |
float | None
|
For a parameter, |
Source code in commol/context/inference/profiles.py
ProfileInterval ¶
Bases: _FrozenResult
The pointwise interval of a quantity: where its profile crosses the threshold.
Attributes:
| Name | Type | Description |
|---|---|---|
lower, upper |
float | None
|
The ends; None on a side that does not cross. |
Source code in commol/context/inference/profiles.py
ProfileStructure ¶
Bases: _FrozenResult
What resetting the other parameters says about a profile.
A profile is flat because other parameters compensate the parameter along it, or because nothing the data read depends on it. At each point of the profile inside the box, and at both ends of the box of the parameter, the other parameters are reset to their fitted values and the objective is evaluated once, with no optimizer; each reset is compared with the objective at the fit.
Attributes:
| Name | Type | Description |
|---|---|---|
verdict |
{in_combination, non_identifiable} | None
|
|
largest_rise |
float | None
|
The largest rise of a feasible reset over the objective at the fit; None when none was feasible. |
compensated_by |
list[str]
|
The parameters whose reset alone, where each moves most along the profile, raises it above the threshold. Noise parameters of observation models are never named. |
joint_rise |
float | None
|
The largest rise of resetting the parameters not named together, at
the outermost point of each side, over the objective of that point,
when it is above the evaluation floor: |
undetermined |
UndeterminedName | None
|
Why there is no verdict. |
on_bound |
str | None
|
With |
Source code in commol/context/inference/profiles.py
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 | |
Methods:¶
reason ¶
The reason of the verdict of parameter name in a report.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The parameter. |
required |
threshold
|
float
|
The threshold of its profile. |
required |
floor
|
float | None
|
The evaluation floor of the result. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The reason, which says that the verdict holds with the other parameters at their fitted values. |
Source code in commol/context/inference/profiles.py
Sequential Monte Carlo¶
Guide: Sequential Monte Carlo.
Priors ¶
Bases: BaseModel
One prior per calibrated parameter.
A sampling method takes its priors with no default: what is known about
each parameter before the data is a modelling choice. Give a mapping of
parameter to distribution, or uniform_on_bounds for Uniform() on
every parameter.
Attributes:
| Name | Type | Description |
|---|---|---|
distributions |
dict[str, Distribution] | None
|
The prior of each parameter; None gives |
Source code in commol/context/inference/distributions.py
Methods:¶
uniform_on_bounds
classmethod
¶
Uniform() on the bounds of every parameter.
Returns:
| Type | Description |
|---|---|
Priors
|
The priors; every parameter needs finite bounds. |
Source code in commol/context/inference/distributions.py
rust_priors ¶
The priors as the Rust runners read them; None is uniform.
Source code in commol/context/inference/distributions.py
Uniform ¶
Bases: DistributionBase
The uniform distribution on the bounds; they must be finite.
Source code in commol/context/inference/distributions.py
LogUniform ¶
Bases: DistributionBase
The log-uniform distribution on the bounds: log x is uniform, the
density is proportional to 1/x. The bounds must be finite and the
lower one above 0.
Source code in commol/context/inference/distributions.py
Beta ¶
Bases: DistributionBase, RangeChecked
The beta distribution of shapes a and b, scaled to the bounds; they
must be finite.
Attributes:
| Name | Type | Description |
|---|---|---|
a |
float
|
The first shape, above 0. |
b |
float
|
The second shape, above 0. |
Source code in commol/context/inference/distributions.py
Normal ¶
Bases: DistributionBase, RangeChecked
The normal distribution, truncated to the bounds.
Attributes:
| Name | Type | Description |
|---|---|---|
mean |
float
|
The mean before truncation. |
sd |
float
|
The standard deviation before truncation, above 0. |
Source code in commol/context/inference/distributions.py
LogNormal ¶
Bases: DistributionBase, RangeChecked
The log-normal distribution, truncated to the bounds and to (0, ∞):
log x is normal. The upper bound must be above 0.
Attributes:
| Name | Type | Description |
|---|---|---|
mu |
float
|
The mean of |
sigma |
float
|
The standard deviation of |
Source code in commol/context/inference/distributions.py
Gamma ¶
Bases: DistributionBase, RangeChecked
The gamma distribution of shape shape and rate rate (mean
shape / rate), truncated to the bounds and to (0, ∞). The upper
bound must be above 0.
Attributes:
| Name | Type | Description |
|---|---|---|
shape |
float
|
The shape, above 0. |
rate |
float
|
The rate, above 0. |
Source code in commol/context/inference/distributions.py
GibbsPosterior ¶
Bases: WithPriors, UncertaintyMethod[GibbsResult], RangeChecked
The Gibbs posterior π(θ) ∝ prior(θ) · exp(−η · loss(θ)) of the
problem's loss, with its weights and normalization, sampled by sequential
Monte Carlo from the priors (temperature 0) to the posterior
(temperature 1).
η sets how much the data weigh against the priors; the loss has no
scale of its own, so η has no default.
Attributes:
| Name | Type | Description |
|---|---|---|
priors |
Priors | dict[str, Distribution]
|
The prior of each calibrated parameter, or
|
eta |
float | InformationMatchingEta | BootstrapCoverageEta
|
A number above 0, |
particles |
int
|
Number of particles, at least 2. |
target_cess |
float
|
The conditional effective sample size of each step, as a share of the particles, strictly between 0 and 1: the next temperature is the highest that keeps it. |
resample_threshold |
float
|
Resample when the effective size falls below this share of the
particles, in |
stay_probability |
float
|
The probability that a particle does not move in a step, strictly
between 0 and 1: each step moves every particle
|
Source code in commol/context/inference/smc.py
BayesianPosterior ¶
Bases: WithPriors, UncertaintyMethod[SMCResult], RangeChecked
The posterior π(θ) ∝ prior(θ) · L(θ) of the problem's observation
models, sampled by sequential Monte Carlo from the priors (temperature
0) to the posterior (temperature 1), with its log evidence.
It needs a problem with observation_models: their likelihood sets the
weight of the data, so it has no η. The noise parameters are sampled
with the others, so each needs a prior.
Attributes:
| Name | Type | Description |
|---|---|---|
priors |
Priors | dict[str, Distribution]
|
The prior of each calibrated parameter, or
|
particles |
int
|
Number of particles, at least 2. |
target_cess |
float
|
The conditional effective sample size of each step, as a share of the particles, strictly between 0 and 1: the next temperature is the highest that keeps it. |
resample_threshold |
float
|
Resample when the effective size falls below this share of the
particles, in |
stay_probability |
float
|
The probability that a particle does not move in a step, strictly
between 0 and 1: each step moves every particle
|
Source code in commol/context/inference/smc.py
InformationMatchingEta ¶
Bases: RangeChecked
Calibrate η by information matching: η = tr(J I⁻¹ J) / tr(J) at the
fit, with J the Gauss–Newton curvature of the objective and I the
variance of the scores of its terms, summed over blocks of positions as
the meat of Sandwich (Holmes and Walker 2017; Lyddon, Holmes and Walker
2019). For the sum of squares of a model with Gaussian noise of variance
σ² it estimates 1/(2σ²); for a correct observation model, 1.
It needs loss_function="sse" or observation models, and a
deterministic engine, and is cheap and local. The variance sums the
scores over blocks of positions, so it holds under dependence inside a
block.
Attributes:
| Name | Type | Description |
|---|---|---|
block_length |
int | auto
|
Positions per block of the scores; there must be more blocks than parameters. |
starts |
int
|
Starts of the fit (default 1): the initial guess, then rows of a Latin hypercube over the bounds. |
Source code in commol/context/inference/smc.py
BootstrapCoverageEta ¶
Bases: RangeChecked
Calibrate η by bootstrap coverage: the η at which the central
intervals of confidence_level of the Gibbs posteriors of
Bayesian-bootstrap data sets hold the fit at that rate, over the
replicates and the parameters (Syring and Martin 2019).
It works with any loss and engine, and costs one sampler per replicate.
Attributes:
| Name | Type | Description |
|---|---|---|
replicates |
int
|
Number of Bayesian-bootstrap data sets, at least 1. |
block_length |
int | auto
|
Positions per block of the bootstrap. |
confidence_level |
float
|
The level of the intervals, strictly between 0 and 1. |
starts |
int
|
Starts of the fit (default 1): the initial guess, then rows of a Latin hypercube over the bounds. |
Source code in commol/context/inference/smc.py
ABCSMC ¶
Bases: WithPriors, UncertaintyMethod[SMCResult], RangeChecked
Approximate Bayesian computation by sequential Monte Carlo (Del Moral,
Doucet and Jasra 2012): the tolerance ε falls step by step, and a
particle is inside when the distance of its run is at most ε.
Each next tolerance keeps the weighted share target_cess of the
particles: with weights of 0 or 1, the weighted quantile of their
distances. With a stochastic engine each distance reads one fresh
replicate, which the particle keeps until a move replaces it. The run
stops when the first move of a step accepts less than min_acceptance,
and keeps the sample of the tolerance before.
Attributes:
| Name | Type | Description |
|---|---|---|
priors |
Priors | dict[str, Distribution]
|
The prior of each calibrated parameter, or
|
distance |
LossDistance | SeriesDistance
|
How far a run is from the observations. |
particles |
int
|
Number of particles, at least 2. |
target_cess |
float
|
The weighted share of the particles each tolerance keeps, strictly between 0 and 1. |
min_acceptance |
float
|
The acceptance rate below which the run stops, strictly between 0 and 1. |
stay_probability |
float
|
The probability that a particle does not move in a step, strictly between 0 and 1. |
Source code in commol/context/inference/smc.py
ABCRejection ¶
Bases: WithPriors, UncertaintyMethod[SMCResult], RangeChecked
ABC rejection: draws draws of the priors, of which the closest share
quantile is kept, with equal weights. It is one step of ABCSMC with
no move. With a stochastic engine each distance reads one fresh
replicate.
Attributes:
| Name | Type | Description |
|---|---|---|
priors |
Priors | dict[str, Distribution]
|
The prior of each calibrated parameter, or
|
distance |
LossDistance | SeriesDistance
|
How far a run is from the observations. |
draws |
int
|
Number of draws of the priors, at least 2. |
quantile |
float
|
The share of the draws kept, strictly between 0 and 1. |
Source code in commol/context/inference/smc.py
LossDistance ¶
Bases: BaseModel
The problem's loss as the distance of ABC: loss_function with the
observation weights and normalize_observations. With a stochastic
engine it reads one fresh replicate per evaluation, so the problem's
replicates and replicate_summary do not apply.
Source code in commol/context/inference/smc.py
SeriesDistance ¶
Bases: BaseModel
The largest distance over the series: metric of each series on its
residuals divided by the root mean square of its observed values, so
series in different units compare on one scale.
Attributes:
| Name | Type | Description |
|---|---|---|
metric |
{rmse, mae}
|
The weighted root mean square or mean absolute value of the scaled residuals of a series. |
Source code in commol/context/inference/smc.py
SMCResult ¶
Bases: ResultModel
The result of a sequential Monte Carlo method.
Attributes:
| Name | Type | Description |
|---|---|---|
sample |
ParameterSample
|
The weighted particles at the last level. |
levels |
list[float]
|
The level of each step: the temperature of a Gibbs posterior, from above 0 to 1, or the tolerance of ABC, falling. |
kept |
list[float | None]
|
The value each particle of the sample keeps, in its order: the loss of a Gibbs posterior, the log-likelihood of a Bayesian posterior, or the distance of ABC; None for a particle outside the support. |
log_evidence |
float
|
The log of the product of the mean incremental weights: for a Gibbs
posterior, the log of |
diagnostics |
SMCDiagnostics
|
The effective sizes, acceptance rates and move counts of each step. |
Source code in commol/context/inference/smc.py
GibbsResult ¶
Bases: SMCResult
The result of a Gibbs posterior: the attributes of SMCResult, and these.
Attributes:
| Name | Type | Description |
|---|---|---|
eta |
float
|
The |
fit |
CalibrationResult | None
|
The fit a calibration of |
coverage |
float | None
|
With |
failed |
list[str]
|
With |
Source code in commol/context/inference/smc.py
SMCDiagnostics ¶
Bases: ResultModel
What happened at each step of a sequential Monte Carlo run.
Attributes:
| Name | Type | Description |
|---|---|---|
effective_sizes |
list[float]
|
Kish's effective size of the weights after the reweighting of each step. A step that keeps few particles has a small one. |
resampled |
list[bool]
|
Whether each step resampled. |
acceptance_rates |
list[float]
|
The share of the proposals of the first move of each step that were accepted; for ABC rejection, the share of draws kept. |
move_counts |
list[int]
|
How many times each particle moved in each step:
|
evaluations |
int
|
The number of model runs. |
stop_reason |
str | None
|
Why the run stopped before its last level, or None. |
notes |
list[str]
|
What the reader of the sample should know, such as settings of the problem that do not apply. |
Source code in commol/context/inference/smc.py
Local approximations¶
Guide: Local Approximations.
Laplace ¶
Bases: UncertaintyMethod[LaplaceResult], RangeChecked
The Laplace approximation of the problem's observation models: the normal
N(θ̂, H⁻¹) on the unbounded scale of the parameters, centred on the
fit, with H the curvature of −log L there.
It needs observation_models: a loss has no noise scale, so its
curvature is no inverse variance (use Sandwich). A fit on a bound of
its parameter is refused: on the unbounded scale its variance is
infinite there.
Attributes:
| Name | Type | Description |
|---|---|---|
draws |
int
|
Number of draws of the normal, at least 1. |
curvature |
{gauss_newton, hessian}
|
The curvature (default |
starts |
int
|
Starts of the fit (default 1): the initial guess, then rows of a Latin hypercube over the bounds. |
Source code in commol/context/inference/local.py
Sandwich ¶
Bases: UncertaintyMethod[SandwichResult], RangeChecked
The sandwich covariance H⁻¹ B H⁻¹ at the fit, with the meat B
summed over blocks of positions (the clustered estimator CR1):
B = G/(G − 1) · Σ_b s_b s_bᵀ, with s_b the sum of the gradients
of the terms of the observations of block b.
It needs no noise model: with a loss, H is the curvature of the loss;
with observation models, of −log L. It holds when the noise depends
on its neighbours inside a block, when its size changes, and when the
noise model is wrong but the mean is right. Intervals and draws read a
Student t with G − 1 degrees of freedom; with G blocks not above
the parameters it is refused, since B would have rank below them.
loss_function="mae" is refused: its sandwich needs a density of the
residuals at 0 and a bandwidth (use a bootstrap).
Attributes:
| Name | Type | Description |
|---|---|---|
block_length |
int | auto
|
Positions per block; |
draws |
int
|
Number of draws of the Student t, at least 1. |
curvature |
{gauss_newton, hessian}
|
The curvature |
starts |
int
|
Starts of the fit (default 1): the initial guess, then rows of a Latin hypercube over the bounds. |
Source code in commol/context/inference/local.py
LaplaceMixture ¶
Bases: UncertaintyMethod[ImportanceResult], RangeChecked
The Laplace mixture: a Laplace approximation at each distinct optimum of a multi-start fit, weighted by its Laplace evidence, as the proposal of importance sampling of a posterior, with the largest weights smoothed (Pareto-smoothed importance sampling, Vehtari et al. 2024).
The ends of the starts merge into a component when they are closer than
one Mahalanobis unit to it. Every draw is weighted by the target over
the mixture, on the unbounded scale. k_hat says whether the mixture
covers the target: above 0.7 the sample is marked unreliable.
Attributes:
| Name | Type | Description |
|---|---|---|
starts |
int
|
Starts of the fit (default 1): the initial guess, then rows of a Latin hypercube over the bounds. |
draws |
int
|
Number of draws of the mixture, at least 25, so that the tail of the weights has 5. |
target |
LikelihoodTarget | GibbsTarget
|
The posterior of the observation models with priors, or the Gibbs
posterior of the loss with priors and |
curvature |
{gauss_newton, hessian}
|
The curvature of each component (default |
Source code in commol/context/inference/local.py
LikelihoodTarget ¶
Bases: WithPriors
The posterior of the problem's observation models,
π(θ) ∝ prior(θ) · L(θ), as the target of a LaplaceMixture.
Attributes:
| Name | Type | Description |
|---|---|---|
priors |
Priors | dict[str, Distribution]
|
The prior of each calibrated parameter, or
|
Source code in commol/context/inference/local.py
GibbsTarget ¶
Bases: WithPriors, RangeChecked
The Gibbs posterior of the problem's loss,
π(θ) ∝ prior(θ) · exp(−η · loss(θ)), as the target of a
LaplaceMixture.
Attributes:
| Name | Type | Description |
|---|---|---|
priors |
Priors | dict[str, Distribution]
|
The prior of each calibrated parameter, or
|
eta |
float
|
The scale of the loss, above 0. |
Source code in commol/context/inference/local.py
LocalResult ¶
Bases: ResultModel
What every local approximation returns: a distribution on the unbounded scale of the parameters, centred on the fit.
Attributes:
| Name | Type | Description |
|---|---|---|
fit |
CalibrationResult
|
The fit the approximation is centred on: |
covariance |
list[list[float]]
|
The covariance of the distribution on the unbounded scale of the parameters, in the order of the problem's parameters. |
sample |
ParameterSample
|
Draws of the distribution, mapped back to the parameters, with equal weights. |
notes |
list[str]
|
The entries of the curvature whose estimated error is not small against their scale; each is also logged as a warning. |
Source code in commol/context/inference/local.py
LaplaceResult ¶
Bases: LocalResult
The result of a Laplace approximation: the normal N(θ̂, Σ) on the
unbounded scale, Σ = H⁻¹.
Attributes:
| Name | Type | Description |
|---|---|---|
fit |
CalibrationResult
|
The fit the approximation is centred on: |
covariance |
list[list[float]]
|
|
sample |
ParameterSample
|
Draws of the normal, mapped back to the parameters, with equal weights. |
notes |
list[str]
|
The entries of the curvature whose estimated error is not small against their scale. |
Source code in commol/context/inference/local.py
SandwichResult ¶
Bases: LocalResult
The result of a sandwich: a Student t on the unbounded scale of the
parameters, centred on the fit, of covariance H⁻¹ B H⁻¹ and
blocks − 1 degrees of freedom.
Attributes:
| Name | Type | Description |
|---|---|---|
fit |
CalibrationResult
|
The fit the sandwich is centred on: |
covariance |
list[list[float]]
|
|
sample |
ParameterSample
|
Draws of the Student t, mapped back to the parameters, with equal weights. |
notes |
list[str]
|
The entries of the curvature whose estimated error is not small against their scale. |
blocks |
int
|
The number of blocks |
block_length |
int
|
The positions per block. |
block_length_estimates |
dict[str, float] | None
|
With |
Source code in commol/context/inference/local.py
DeltaBand ¶
Bases: ResultModel
The band of every output by the delta method (Calibrator.delta_band):
the prediction at the fit
plus and minus a quantile times the standard deviation of the
linearized model, J Σ Jᵀ, with no run of the draws.
Attributes:
| Name | Type | Description |
|---|---|---|
confidence_level |
float
|
The level of the central interval. |
positions |
list[float]
|
Where the values are. |
center, lower, upper |
dict[str, list[float]]
|
For each output, one value per position: the prediction at the fit and the ends of the interval. |
Source code in commol/context/inference/local.py
ImportanceResult ¶
Bases: ResultModel
The result of a Laplace mixture: draws of the mixture weighted by the target over the mixture, smoothed by Pareto-smoothed importance sampling.
Attributes:
| Name | Type | Description |
|---|---|---|
fit |
CalibrationResult
|
The multi-start fit whose ends made the components:
|
sample |
ParameterSample
|
The draws with their smoothed weights. |
components |
list[MixtureComponent]
|
The components, in order of their objective. |
k_hat |
float
|
The Pareto shape of the tail of the weights. Up to 0.5 the weights have a finite variance; above 0.7 the estimate is unreliable. |
effective_size |
float
|
Kish's effective size of the smoothed weights. |
reliable |
bool
|
Whether |
notes |
list[str]
|
Ends that gave no component, and an unreliable sample, in words. |
Source code in commol/context/inference/local.py
MixtureComponent ¶
Bases: ResultModel
One component of a Laplace mixture: the Laplace approximation at one optimum of the starts.
Attributes:
| Name | Type | Description |
|---|---|---|
center |
dict[str, float]
|
The optimum, by parameter. |
weight |
float
|
Its weight in the mixture: its Laplace evidence over the sum. |
covariance |
list[list[float]]
|
Its covariance on the unbounded scale of the parameters. |
log_evidence |
float
|
The log of its Laplace evidence,
|
Source code in commol/context/inference/local.py
Conformal prediction¶
Guide: Conformal Prediction Intervals.
ConformalMethod ¶
Bases: UncertaintyMethod[ConformalResult]
What every conformal method takes: a score, the pooling of its quantiles, and a confidence level, none of them with a default.
Attributes:
| Name | Type | Description |
|---|---|---|
score |
{absolute, normalized, spread}
|
The nonconformity score. |
by |
{series, all}
|
Whether each series gets its own quantile, or all series share one. |
confidence_level |
float
|
The level of the intervals, strictly between 0 and 1. |
Source code in commol/context/inference/conformal.py
Methods:¶
check_score_and_by
classmethod
¶
Check, in Rust, that score and by are given and fit together.
Source code in commol/context/inference/conformal.py
SplitConformal ¶
Bases: ConformalMethod, RangeChecked
Split conformal prediction.
It fits the problem's observations and scores calibration_data,
observations held out of the fit. When the scores of the held-out and of
new observations are exchangeable, each interval covers a new
observation with probability at least confidence_level.
It takes score, by and confidence_level, as every ConformalMethod.
Attributes:
| Name | Type | Description |
|---|---|---|
calibration_data |
list[ObservedDataPoint]
|
Held-out observations; each of their series gets intervals. |
positions |
list[float]
|
Where the intervals are, for each series of |
sample |
ParameterSample | None
|
None: the prediction is the fit. A sample: the prediction is the
weighted median of its predictive, and its weighted standard
deviation is the spread of |
starts |
int
|
Starts of the fit (default 1). |
Source code in commol/context/inference/conformal.py
RollingConformal ¶
Bases: ConformalMethod, RangeChecked
Rolling-origin conformal prediction: intervals ahead of the data, one quantile per horizon.
Each origin fits the observations at or before it and scores the later
ones. Horizon k is the k-th observation of a series after the
origin: a count, not a distance on the axis.
It takes score, by and confidence_level, as every ConformalMethod.
Attributes:
| Name | Type | Description |
|---|---|---|
origins |
list[float]
|
The positions of the origins. |
positions |
list[float]
|
Where the intervals are, all after the data; the |
starts |
int
|
Starts of each fit (default 1). |
Source code in commol/context/inference/conformal.py
Methods:¶
check_spread ¶
Reject score="spread": one fit per origin has no spread.
Source code in commol/context/inference/conformal.py
JackknifePlus ¶
Bases: ConformalMethod, RangeChecked
Jackknife+ (Barber et al. 2021) with blocks: one refit per block left out, and intervals from the left-out residuals and predictions.
With exchangeable blocks it covers at least 1 − 2α when each block
holds one observation, and the CV+ bound with K blocks otherwise.
It takes score, by and confidence_level, as every ConformalMethod.
Attributes:
| Name | Type | Description |
|---|---|---|
block_length |
int | auto
|
Positions per block; it must leave at least two blocks. |
positions |
list[float]
|
Where the intervals are, for each series of the problem. |
starts |
int
|
Starts of the fit and of each refit (default 1). |
Source code in commol/context/inference/conformal.py
EnbPI ¶
Bases: ConformalMethod, RangeChecked
Ensemble batch prediction intervals (Xu and Xie 2021).
Each replicate draws blocks with replacement and fits. The replicates that left out the block of an observation give its leave-one-out prediction and score; their mean over every observation is the point prediction.
It takes score, by and confidence_level, as every ConformalMethod.
Attributes:
| Name | Type | Description |
|---|---|---|
replicates |
int
|
Number of replicates, at least 2. |
block_length |
int | auto
|
Positions per block. |
positions |
list[float]
|
Where the intervals are, for each series of the problem. |
starts |
int
|
Starts of the fit and of each replicate (default 1). |
Source code in commol/context/inference/conformal.py
AdaptiveConformal ¶
Bases: ConformalMethod, RangeChecked
Adaptive conformal inference (Gibbs and Candès 2021).
It fits the problem's observations and walks stream in order of
position. The interval of each point is the quantile, at the working
level 1 − α_t, of the scores of the earlier points of the stream;
then the working level moves by α_{t+1} = α_t + γ (α − err_t). The
long-run share of misses tends to α, with no assumption on the data.
It takes score, by and confidence_level, as every ConformalMethod.
Attributes:
| Name | Type | Description |
|---|---|---|
step |
float
|
The step |
stream |
list[ObservedDataPoint]
|
The observations that arrive after the data. |
sample |
ParameterSample | None
|
As in |
starts |
int
|
Starts of the fit (default 1). |
Source code in commol/context/inference/conformal.py
ConformalResult ¶
Bases: ResultModel
The result of a conformal method.
Attributes:
| Name | Type | Description |
|---|---|---|
intervals |
PredictionIntervals
|
The intervals at the positions the method was given. |
scores |
dict[str, list[float]]
|
The scores of each series, by label, in the order the method took them. |
guarantee |
str
|
The coverage the method guarantees, and what the guarantee assumes. |
failed |
list[str]
|
Each refit that failed, which gives no score: |
not_converged |
int
|
Refits kept although their optimizer did not converge; 0 for a method that does not refit. |
Source code in commol/context/inference/conformal.py
PredictionIntervals ¶
Bases: ResultModel
Prediction intervals for observations: where new observations of each series fall, at a confidence level.
Attributes:
| Name | Type | Description |
|---|---|---|
confidence_level |
float
|
The level of the intervals, |
series |
dict[str, SeriesIntervals]
|
The intervals of each series, by label. |
unbounded |
dict[str, list[float]]
|
The positions of each series whose interval is unbounded, because
its quantile had fewer than |
Source code in commol/context/inference/conformal.py
SeriesIntervals ¶
Bases: ResultModel
The prediction intervals of one series.
Attributes:
| Name | Type | Description |
|---|---|---|
positions |
list[float]
|
Where the intervals are. |
prediction |
list[float]
|
The point prediction at each position. |
lower |
list[float]
|
The lower end of each interval; |
upper |
list[float]
|
The upper end of each interval; |
Source code in commol/context/inference/conformal.py
Scores and intervals¶
scores ¶
Scores of a predictive against observations.
Every score is computed in Rust, per observation and per series: from each
draw's value of the observations (Predictive.at_observations), or, for the
log score, from the density of the observation models at each draw's
prediction. Which observations to score, for example the ones held out of the
calibration, and the observation noise are arguments with no default: a band
of the model (NoNoise) compared with data covers less than its level.
Classes¶
Score ¶
Bases: ResultModel
One score of a predictive at a set of observations.
Attributes:
| Name | Type | Description |
|---|---|---|
per_observation |
list[float]
|
The score of each observation, in the order given. |
per_series |
dict[str, float]
|
The mean score of each series (observation label), in order of first appearance. |
mean |
float
|
The mean over every observation. |
Source code in commol/api/inference/scores.py
Functions:¶
coverage ¶
coverage(predictive: Predictive, observations: Sequence[ObservedDataPoint], noise: ObservationNoise, confidence_level: float) -> Score
The empirical coverage of the central interval of confidence_level.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictive
|
Predictive
|
The predictive. |
required |
observations
|
Sequence[ObservedDataPoint]
|
The observations to score. |
required |
noise
|
NoNoise | ResidualNoise | DistributionNoise
|
The observation noise of the draws ( |
required |
confidence_level
|
float
|
Strictly between 0 and 1. |
required |
Returns:
| Type | Description |
|---|---|
Score
|
1 for each observation inside its interval, 0 outside; the means are
the coverage. A calibrated interval covers about |
Source code in commol/api/inference/scores.py
interval_score ¶
interval_score(predictive: Predictive, observations: Sequence[ObservedDataPoint], noise: ObservationNoise, confidence_level: float) -> Score
The interval score: (u − l) + (2/α)(l − y)₊ + (2/α)(y − u)₊.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictive
|
Predictive
|
The predictive. |
required |
observations
|
Sequence[ObservedDataPoint]
|
The observations to score. |
required |
noise
|
NoNoise | ResidualNoise | DistributionNoise
|
The observation noise of the draws ( |
required |
confidence_level
|
float
|
The level |
required |
Returns:
| Type | Description |
|---|---|
Score
|
Lower is better. |
Source code in commol/api/inference/scores.py
weighted_interval_score ¶
weighted_interval_score(predictive: Predictive, observations: Sequence[ObservedDataPoint], noise: ObservationNoise, confidence_levels: Sequence[float]) -> Score
The weighted interval score of Bracher et al. (2021).
(½|y − m| + Σₖ (αₖ/2) IS_αₖ) / (K + ½), with m the median and
αₖ = 1 − cₖ for each confidence level cₖ.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictive
|
Predictive
|
The predictive. |
required |
observations
|
Sequence[ObservedDataPoint]
|
The observations to score. |
required |
noise
|
NoNoise | ResidualNoise | DistributionNoise
|
The observation noise of the draws ( |
required |
confidence_levels
|
Sequence[float]
|
The levels of the central intervals. |
required |
Returns:
| Type | Description |
|---|---|
Score
|
Lower is better. |
References
Bracher, J., Ray, E. L., Gneiting, T., & Reich, N. G. (2021). Evaluating epidemic forecasts in an interval format. PLOS Computational Biology, 17(2), e1008618. https://doi.org/10.1371/journal.pcbi.1008618
Source code in commol/api/inference/scores.py
crps ¶
crps(predictive: Predictive, observations: Sequence[ObservedDataPoint], noise: ObservationNoise) -> Score
The continuous ranked probability score of the weighted draws.
Σ wᵢ|xᵢ − y| − ½ Σᵢⱼ wᵢwⱼ|xᵢ − xⱼ|, the function the CRPS loss of a
stochastic calibration uses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictive
|
Predictive
|
The predictive. |
required |
observations
|
Sequence[ObservedDataPoint]
|
The observations to score. |
required |
noise
|
NoNoise | ResidualNoise | DistributionNoise
|
The observation noise of the draws ( |
required |
Returns:
| Type | Description |
|---|---|
Score
|
Lower is better; in the unit of the observations. |
Source code in commol/api/inference/scores.py
pit ¶
pit(predictive: Predictive, observations: Sequence[ObservedDataPoint], noise: ObservationNoise) -> Score
The probability integral transform of each observation.
F(y) of the weighted draws, randomized between F(y⁻) and F(y)
where draws tie with y, so a discrete predictive gives uniform values
too. The ties take their random numbers from the seed of the source of
the predictive (Calibrator.seed or SensitivityAnalysis.seed), the
seed of the draws, so the same draws give the same values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictive
|
Predictive
|
The predictive. |
required |
observations
|
Sequence[ObservedDataPoint]
|
The observations to score. |
required |
noise
|
NoNoise | ResidualNoise | DistributionNoise
|
The observation noise of the draws ( |
required |
Returns:
| Type | Description |
|---|---|
Score
|
Values in |
Source code in commol/api/inference/scores.py
log_score ¶
log_score(predictive: Predictive, observations: Sequence[ObservedDataPoint], noise: DistributionNoise) -> Score
The log score of each observation: the log density of its value under the predictive.
The predictive density is the mixture over the draws of the observation
models, log Σ_d w_d · p(y | μ_d), with μ_d the prediction of draw
d and its noise parameters. It needs the densities of the models, so
only DistributionNoise has one. A proper scoring rule; higher is
better, and an observation the predictive gives no mass scores -inf.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictive
|
Predictive
|
The predictive, of a problem with |
required |
observations
|
Sequence[ObservedDataPoint]
|
The observations to score. |
required |
noise
|
DistributionNoise
|
The observation models of the problem. |
required |
Returns:
| Type | Description |
|---|---|
Score
|
The log score of each observation. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If the problem has a loss, an observation names an unknown output or factor or a series with no observation model, or the predictive is of a sensitivity analysis, which has no observation models. |
Source code in commol/api/inference/scores.py
weighted_quantiles ¶
weighted_quantiles(values: Sequence[float], levels: Sequence[float], weights: Sequence[float] | None = None) -> list[float]
Quantiles of weighted values, by the one convention of commol.
The quantile is the inverse of the weighted empirical distribution,
interpolated between the midpoints of the cumulative weights. With equal
weights it equals numpy.percentile(..., method="hazen"). A weight of
zero removes a value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
Sequence[float]
|
The values. |
required |
levels
|
Sequence[float]
|
Quantile levels, each between 0 and 1. |
required |
weights
|
Sequence[float] | None
|
One non-negative weight per value, of any scale. None gives equal weights. |
None
|
Returns:
| Type | Description |
|---|---|
list[float]
|
One quantile per level. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the lengths differ, no weight is positive or a level is not in
|
Source code in commol/api/inference/intervals.py
member_statistics ¶
member_statistics(per_member: Sequence[float], confidence_level: float, weights: Sequence[float] | None = None) -> dict[str, float]
member_statistics(per_member: EnsembleValues, confidence_level: float, weights: Sequence[float] | None = None) -> dict[str, float] | dict[str, list[float]] | dict[str, float | list[float]]
Spread of one quantity across the members of an ensemble.
Each member must already be reduced to the quantity of interest, so that
the reported interval is a quantile of member values
(:func:weighted_quantiles).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
per_member
|
Sequence[float] | Sequence[Sequence[float]] | NDArray
|
One entry per ensemble member. Entries may be scalars, in which case every returned statistic is a scalar, or equal-length series, in which case every returned statistic is a series reduced across members at each position. A numpy array is accepted, but its rank is not visible to a type checker; pass a list of lists for a precise return type. |
required |
confidence_level
|
float
|
Confidence level of the reported interval, strictly between 0 and 1. |
required |
weights
|
Sequence[float] | None
|
One weight per member, such as the weights of a
:class: |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, float] | dict[str, list[float]]
|
Keys |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in commol/api/inference/intervals.py
ci_percentiles ¶
Lower and upper percentile points of a two-sided confidence interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
confidence_level
|
float
|
Confidence level of the interval, strictly between 0 and 1. |
required |
Returns:
| Type | Description |
|---|---|
tuple[float, float]
|
Lower and upper percentile points, on the 0-100 scale. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |