Pipeline and reports¶
Running a scenario suite and reading, saving and replaying its report:
Pipeline, ForecastRun, TestReport and the result types from timegym,
with plots in timegym.plotting and schema constants in timegym.provenance and timegym.reporting.
Pipeline(model, window_length=12, reduction="recursive", *,
target_transform=None, name=None) takes the model to test first, as one of:
- a model: anything with
fit(history)andpredict(future_index), copied fresh before every case (throughclone_unfitted()when it has one), even if it can also be called; - a list of scikit-learn steps ending in a regressor, such as
Pipeline([StandardScaler(), Ridge()], window_length=24), which becomes one scikit-learn pipeline; a scikit-learn pipeline you already have is taken as it is; - a class, or a function that returns a fresh model, called for every case.
A scikit-learn regressor forecasts from windows of the last window_length
steps; reduction selects one of REDUCTIONS, with the case horizon as the
reduction horizon. Neither changes native models. Reports and the scorecard
name a scikit-learn pipeline by its steps, such as "StandardScaler + Ridge".
target_transform is an instance implementing clone_unfitted(),
fit_transform(history) and inverse_transform(forecast). A fresh copy is
fitted on each history before the model and inverts the forecast the model
returns, so evaluation sees the original scale.
name names the model once for everything a run shows:
Pipeline(RandomForestRegressor(), window_length=12, name="Forest") titles
the scorecard "Forest", heads plot_forecasts() and plot_errors(), labels
the run in a comparison and is result.metadata["name"], while
result.metadata["model"] still names the class. The name is saved with the
pipeline's configuration, so a replay keeps it. Without a name, the scorecard
is titled by the model and the plots have no heading.
The older ways still work, with their old behaviour, and warn:
.add(estimator, **parameters) adds one step at a time and makes the same
forecasts as the list; model_factory=make_model is Pipeline(make_model);
and a pipeline with no model tests the last value, as
Pipeline(LastValueForecaster()) does. They will be removed in a later
release.
.predict(history, future_index) returns the model's Forecast for inspection.
history may be a DataFrame, a Series, or a list or NumPy array (labelled 0, 1,
2, ...), and future_index any sequence of the labels to forecast, such as
range(120, 132) after 120 values.
A model's predict(future_index) returns one value per requested step: a list
or NumPy array (one column per series when there are several), a Forecast, a
pandas DataFrame indexed by the requested dates with one column per series,
or a Series for a single series. A list or array has no dates, so its rows are
taken as the requested steps in order. A DataFrame keeps its own index and
column names, so wrong dates or a wrong series order still fail their checks.
.run(scenarios=None, seeds=None, *, seed=0, instances=None, cases=None,
noise_levels=None, history_length=None, horizon=None, keep_data=False,
simulate_attainable=False, interval_level=None, metrics=None, checks=None) forecasts
every case with a fresh model, checks each forecast and measures its errors,
and returns a ForecastRun. It is the one call for testing a model:
from timegym import LastValueForecaster, Pipeline
result = Pipeline(LastValueForecaster()).run()
result.scorecard.plot() # the scorecard picture
print(result.scorecard) # the same as a table
result.assert_passed() # raises if a forecast failed an output check
result.save("report.json") # the report, to read back with TestReport.load
What to forecast goes first. With nothing, run() draws the scorecard's ten
kinds of series at low and high noise, 120 steps of history and 24 to
forecast, 10 times each: 200 series. Keys of PATTERNS such as
["trend", "seasonal"], and Pattern objects of your own beside them, give
those rows of the scorecard; noise_levels, history_length and horizon
set its columns and lengths. Scenario objects, or anything with
generate(seed) and kind, are drawn as they were built, one row each.
Kinds of series and scenarios you built cannot be mixed in one run.
One seed drives the whole run: each row is drawn instances times (10 by
default) with seeds seed, seed + 1, ..., so the default equals
seeds=list(range(10)). seed=None draws a fresh seed and records it, with
the instance count, in result.metadata. An explicit seeds list is used as
given and cannot be combined with seed or instances. Run seeds override a
Scenario's default seed. Model/evaluation exceptions are recorded with
traceback evidence. Invalid scenario configuration is a caller error and is
raised rather than counted as a model fault.
The result holds the report and the scorecard. result.report is the
TestReport; result.checks, result.assert_passed(), result.save(path)
and result.to_json() read it directly. result.scorecard is a
Scorecard (Scorecards and the scenario grid), titled by
the pipeline's name or, without one, by its model; simulate_attainable and
interval_level (0.95 by default) are its settings. A run of your own data
has no scorecard, because nobody knows the answer key of real data: reading
result.scorecard then raises an error that points to result.checks and the
errors against what happened in result.metrics.
Each entry of result.cases is an EvaluatedCase that answers for its case
directly:
for entry in result.cases:
entry.history # the past the model saw, one column per series
entry.future_index # the dates it forecast
entry.observed # what happened on them
entry.reference # the answer key (None for your own data)
entry.forecast # what the model returned (None if it crashed)
entry.metrics["mae"] # each metric by name
entry.diagnostics # every finding
entry.manifest # the case's description: its kind, seed, ...
metrics, diagnostics and manifest are the case's entry in the report,
result.report.cases. entry.case is the whole Case, to hand to another
call, and scenario_index and seed_index place it in the run.
entry.result, the old way to the report's entry, still works and warns.
result.metrics puts every case's metrics in one table, a pandas DataFrame
with one row per case, in order. The case's labels come first and tell the
scenarios apart. On the scorecard's kinds of series they are the scorecard's
row and column, pattern and noise (such as "Low noise"), then the
seed, so grouping by pattern and noise gives one value per cell of the
scorecard. Scenarios you built are labelled by scenario, the name of their
row on the scorecard: the kind, such as "ar1", then "ar1 (2)" for a
second scenario of that kind. Cases cut from your own data are labelled by
kind (the name given to cases_from_series) and origin, where the history
ends. One column per metric follows, in alphabetical order. A case that
crashed or failed an output check is not scored, so its metrics are NaN. The
table reads only the metrics, so it works whether or not the run kept its
data. The run records its scenarios' labels in
result.metadata["scenario_labels"], so report.metrics gives the same table
on a report, also one read back from its file; a report saved before this
release has kind and seed there instead.
errors = result.metrics["avoidable_mse"] # one value per case
result.metrics.groupby(["pattern", "noise"])["mae"].mean() # one value per cell of the scorecard
By default the run drops the series, answer keys and forecasts once every
case is measured, so a large run stays small in memory: history,
future_index, observed, reference, forecast and case are then
None, while metrics, diagnostics and manifest stay, and
result.kept_data is False. The report, the scorecard (with its picture)
and result.plot_errors() work either way. keep_data=True keeps them for
result.plot_forecasts(), result.calibration() and your own
reading. This in-memory object keeps arrays separate from the portable report
schema.
.test(...) and .scorecard(...) still work, with their old behaviour, and
warn. pipeline.test(...) is pipeline.run(...).report, except that with no
scenarios it draws the five kinds of default_scenarios(), 3 times each.
pipeline.scorecard(patterns, ...) is
pipeline.run(patterns, ..., keep_data=True).scorecard. Both will be removed
in a later release.
metrics= records more metrics in every case and checks= adds output checks
of your own (Metrics and diagnostics).
checks=[dependence()], with dependence from timegym.checks, adds the check
that the sample paths of each case move together as its answer key says; the
report records its settings under metadata["diagnostic_settings"]. The old
arguments that asked for it, check_dependence, n_calibration, alpha and
dependence_seed_offset, still work and warn.
cases=[...] tests ready-made Case objects instead of drawing them, for
example cases cut from your own data with
cases_from_series. Each case gets a
fresh model, fitted on its history only, and the same output checks and
metrics as a drawn case. Cases that share a manifest kind share a row of the
plots, in the order given. cases cannot be combined with scenarios,
seeds, seed, instances or the scorecard's settings, and the report's
metadata has no seed. Pass a list, even of one case.
ForecastRun.from_forecasts(cases, forecasts, *, name=None, metadata=None,
metrics=None, checks=None) checks forecasts made earlier and measures their errors,
with no model: forecasts[i] belongs to cases[i] and can take any form a
model's predict returns. None marks a case with no recorded forecast, which
fails "Runs without errors". The result is a ForecastRun, so its report and
plots work as usual. name says what made the forecasts, as
Pipeline(..., name=...) does: it is run.metadata["name"], heads the plots
and labels the run in a comparison. metadata is added to the run's
metadata, for example {"made_on": "2024-05-01"}; naming the forecasts there
with {"model": ...} still works and warns. With the rain cases from
Your own data:
import numpy as np
from timegym import ForecastRun
recorded = [np.full(7, case.task.history.iloc[-1, 0]) for case in cases] # made elsewhere
run = ForecastRun.from_forecasts(cases, recorded, name="repeat last")
run.report.assert_passed()
run.plot_forecasts(*, show_quantiles=False, figsize=None, history=None) needs
a run made with keep_data=True. It draws
scenario/target rows and seed columns in the scorecard's look: gray dots are
observations, the black line is the answer key, blue crosses are the forecast,
and one key above the panels names them. history is how many past steps each
panel shows: four times the horizon by default, "all" for the whole history.
Optional shading shows marginal intervals. Above each panel, the case's 0-100
score sits in its colored band (as on the scorecard), next to its error against
the answer key and its error against what happened.
run.plot_errors(metric="avoidable_mse", *, bins=None, missing="raise",
figsize=None) shows one value of the metric per whole case, with a black line at each row's
median; missing="annotate" explicitly permits unavailable values and labels
their counts and reasons. metric="mean_reference_mse", the old name of the
default, still works and warns. run.titles optionally names each scenario position in plain
words for both plots; a run of kinds of series sets them to the kind and noise
level, so pipeline.run(["trend"], keep_data=True).plot_forecasts() zooms
into those rows of the scorecard. Neither method refits models. Matplotlib is installed with
TimeGym and imported only when a plot is drawn.
.to_config() describes the configured model and .from_config(config) can
restore allowlisted built-in models with a bundled target transform or none.
Factories, custom models, sklearn steps and other target transforms are
explicitly marked non-replayable. A JSON report records model configuration,
source fingerprint, dependency versions and diagnostic settings. Use
report.replay_case(case_index=0) or python examples/reproduce_report.py report.json
to reproduce a supported built-in case. Replay draws the case again from its
manifest, so it refuses, saying why, a case that was not drawn from a TimeGym
scenario, such as one cut from your own data, and a report with no pipeline
configuration, such as one made by ForecastRun.from_forecasts. Keep your data
and the code that made the forecasts to reproduce those. The script prints the comparison and exits
with status 1 when the case is not reproduced.
Replay accepts a TestReport; load dictionaries through TestReport.from_dict
first. The metadata["replay"] result contains reproduced (metrics, diagnostics,
and manifest agree) and same_environment (source, dependencies, and Python
version agree). Diagnostic comparison excludes traceback fields, including those
in nested exception evidence; traceback_match records their exact agreement
separately. A changed exception type, message, or other evidence still prevents
reproduction. No arbitrary module import is performed
from a report. Reproduction on different numerical-library versions may require
tolerance rather than exact floating-point equality.
DiagnosticStatus defines PASS, FAIL, INCONCLUSIVE, UNSUPPORTED, and
ERROR. Only FAIL and ERROR count as failures (DiagnosticResult.failed).
DiagnosticCategory defines correctness (forecast contracts), evaluation
(evaluator inputs), capability (descriptive metrics), uncertainty (intervals),
distribution (joint-law checks), metamorphic (declared transformations), and
execution (model execution). A check keeps its category across outcomes;
reference_covariance is always distribution, shift_equivariance always
metamorphic, and metric_<name> always capability.
Both enums and DiagnosticResult and CaseResult are importable from timegym.
Result construction validates these fields, nonempty names, dictionary evidence,
nonnegative integer or absent seeds, and finite numeric metrics. Serialization
canonicalizes NumPy scalars and builtin subclasses and rejects nonfinite values
in evidence and metadata as well as metrics; it also revalidates mutable results.
report.save(path) writes diagnostics, measurements and manifests to a JSON
file, and report.to_json() returns the same JSON as text. to_json(path),
the old way to write the file, still does and warns.
TestReport.load(path), TestReport.from_json(text), and
TestReport.from_dict(payload) load reports without executing saved model
descriptions; TestReport.read(path), the old name of load, still works and
warns.
They reject unknown schemas/statuses/categories, nonfinite values, duplicate JSON keys,
malformed records, and stored summary counts that disagree with the diagnostics.
from_json always expects JSON text; use load for a file. Evidence and metadata
are copied so later edits to the input dictionary cannot change the loaded report.
report.checks counts, per output check in plain words, the cases that passed
and failed: one {"check", "title", "passed", "failed"} dictionary per check
that ran (runs, dates, series, shape, finite, quantiles, and
dependence when checks=[dependence()] asked for it), then one per check
asked for with checks=, such as within(0, None)
(your own output checks).
Metrics are not checks: they have no pass mark.
report.metrics is every case's metrics in one table, one row per case with
its labels first, as result.metrics above.
report.assert_passed() raises for detected FAIL/ERROR outcomes. Its message
names each failed check first, for example Forecasts the requested dates:
failed in 4 of 4 cases, then lists the underlying diagnostics. Callers must
inspect unsupported/inconclusive checks to decide whether their CI coverage is
adequate. A pass is always scoped to a check.
Report schema¶
timegym.reporting.REPORT_SCHEMA_VERSION = "2.0" identifies the report envelope.
timegym.provenance.PIPELINE_CONFIG_SCHEMA_VERSION = 3 identifies current
pipeline configuration writes, which add target_transform (null or a
description of the transform). Schema 2 configurations, written without that
field, remain readable; schema 1 configurations, which used strategy, are
rejected. A named pipeline's configuration also holds its name; one without
a name writes none. Scenario manifests use integer version 1,
named by timegym.scenarios.MANIFEST_SCHEMA_VERSION. These are independent
schemas: the report version is a string, while configuration and
manifest versions are integers.
Signatures¶
timegym.Pipeline
¶
Pipeline(model=None, window_length=12, reduction='recursive', *, model_factory=None, target_transform=None, name=None)
Evaluate fresh model instances on independent, seeded scenarios.
The model goes first, as one of:
- a model: anything with
fit(history)andpredict(future_index), copied fresh before every case, even if it can also be called; - a list of scikit-learn steps ending in a regressor, such as
[StandardScaler(), Ridge()], which becomes one scikit-learn pipeline; a scikit-learn pipeline you already have is taken as it is; - a class, or a function that returns a fresh model, called for every case,
as
Pattern(attainable_by=...)takes them.
The history is the past as a DataFrame, one row per time step and one
column per series (y for one series). future_index holds the labels
of the steps to forecast, continuing the history's index. predict
returns one value per step: a list or NumPy array (one column per series
when there are several), a Series or DataFrame indexed by future_index,
or a Forecast, which can also carry quantiles and samples. A scikit-learn
regressor forecasts from windows of the last window_length steps, with
one of REDUCTIONS; neither setting changes native models. An optional
target_transform is refitted on each history before the model and
inverted on the forecast it returns.
name names the model wherever a run shows it: Pipeline(model,
name="Forest") titles the scorecard "Forest", heads the run's plots,
labels it in a comparison and is result.metadata["name"],
while result.metadata["model"] still names the class. The name is
saved with the pipeline's configuration, so replay keeps it. Without a
name the scorecard is titled by the model, such as
GaussianAR1Forecaster(...) or "StandardScaler + Ridge".
add() and model_factory= still work and warn, and so does a
pipeline with no model, which tests the last value as NaiveForecaster.
add
¶
add(estimator, **parameters)
Add an sklearn transformer or final regressor and return the pipeline; pass a list of steps instead.
Pipeline(window_length=12).add(StandardScaler()).add(Ridge()) makes
the same forecasts as Pipeline([StandardScaler(), Ridge()],
window_length=12). add still works and warns once for each
pipeline, and will be removed in a later release.
to_config
¶
to_config()
Return JSON-safe configuration and whether safe automatic replay is supported.
from_config
classmethod
¶
from_config(config)
Rebuild allowlisted built-in models and target transforms without dynamic imports.
predict
¶
predict(history, future_index)
Fit on the history and predict the supplied index, without future targets.
history is the past: a DataFrame with one column per series, a
Series, or a list or NumPy array, whose rows are labelled 0, 1, 2, ...
future_index is any sequence of the labels to forecast; after a
list of 120 values the next 12 steps are range(120, 132).
A target transform is refitted on this history alone and the model sees
only the transformed history. A forecast that meets its contract is
inverted to the original scale; one that violates it is returned
unchanged, so evaluation reports the model's fault, not the inversion's.
The old keyword context= still works and warns.
run
¶
run(scenarios=None, seeds=None, *, seed=0, instances=None, cases=None, noise_levels=None, history_length=None, horizon=None, keep_data=False, simulate_attainable=False, interval_level=None, metrics=None, checks=None, **old_arguments)
Forecast every case with a fresh model, check each forecast and measure its errors; return a ForecastRun.
What to forecast, as the first argument:
- nothing: the scorecard's ten kinds of series (
timegym.PATTERNS) at low and high noise, 120 steps of history and 24 to forecast; - keys of
timegym.PATTERNSsuch as["trend", "seasonal"], andPatternobjects of your own beside them: those rows of the scorecard.noise_levels,history_lengthandhorizonset its columns and lengths, as inscenario_grid; Scenarioobjects, or anything withgenerate(seed)andkind: each as it was built, one row of the scorecard each.
Each is drawn instances times (10 by default). Draw i uses seed
seed + i in every row, so rows are compared on the same random
draws. seed=None picks a fresh base seed and records it in
result.metadata["seed"]. An explicit seeds list replaces both.
cases takes ready-made cases instead, such as your own data cut
with timegym.cases_from_series: each is forecast as given and
nothing is generated, so it cannot be combined with what to forecast,
seeds, seed, instances or the scorecard's settings. A
case's manifest needs no kind or seed; without them it is
labelled case and has no seed. Cases with the same kind share a
row of the plots. Real data has no answer key, so such a run has no
scorecard.
The result holds every case's metrics and output checks:
result.scorecard (a Scorecard: result.scorecard.plot(),
print(result.scorecard)), result.assert_passed(),
result.save(path), result.checks, result.report and
result.plot_errors(). The series, answer keys and forecasts are
dropped once every case is measured, unless keep_data=True: then
result.cases holds them and result.plot_forecasts() can draw
them. The scorecard keeps what its picture draws either way.
simulate_attainable and interval_level are the scorecard's own settings;
its title is the pipeline's name, or the model's when it has none.
interval_level says how cautious the interval around each score
is: 0.95 by default, 0.99 gives a wider one. attainable in its
table is what the pattern's own model family, fitted to each history,
scores on 200 fresh series of the row. The default grid's values are
stored. Off the default grid (another noise level, history_length
or horizon) the column is NaN unless simulate_attainable=True, which
simulates the missing values once per session: about 3 to 5 seconds
for each autoregressive or random-walk cell and well under a second for
the others. A pattern of your own has no stored values: with
Pattern.attainable_by and simulate_attainable=True its attainable score
is simulated in the same way, otherwise it is NaN.
metrics records more metrics in every case, as in
timegym.diagnostics.evaluate_forecast: names of functions in
timegym.metrics such as "brier", your own functions, or a
dictionary from name to function. result.metadata["metrics"] lists
them, and says which replay can compute again. scores, their old
name, still works and warns.
checks adds output checks of your own to every case, as in
evaluate_forecast: functions such as timegym.checks.within(0,
None), or a dictionary from name to function. They appear in
result.checks and assert_passed like the built-in checks.
result.metadata["checks"] lists them with their titles, and says
which replay can run again. timegym.checks.dependence() among them
checks that the sample paths of every case move together as its answer
key says; its row in result.checks is "dependence", and
result.metadata["diagnostic_settings"] records its settings for
replay. check_dependence, n_calibration, alpha and
dependence_seed_offset, its old form, still work and warn.
test
¶
test(scenarios=None, seeds=None, *, seed=0, instances=None, cases=None, metrics=None, checks=None, **old_arguments)
Evaluate each scenario on each instance and return a TestReport; use run instead.
pipeline.test(...) is pipeline.run(...).report with the old
defaults: with no scenarios it draws default_scenarios(), the five
core kinds, 3 times each. It warns and will be removed in a later
release; run returns the same report as result.report, with
result.assert_passed(), result.save(path) and the scorecard.
scorecard
¶
scorecard(patterns=None, *, noise_levels=2, instances=10, seed=0, history_length=120, horizon=24, title=None, simulate_attainable=False, interval_level=0.95)
Score the model on a grid of patterns and noise levels and return a Scorecard; use run instead.
pipeline.scorecard(...) is pipeline.run(..., keep_data=True).scorecard
with the same arguments, the patterns first: card.run keeps every
series and forecast, as it always did. It warns and will be removed
in a later release. See run for the settings and Scorecard for
what the card holds. title heads the card in place of the
pipeline's name. context_length is the old name of
history_length, and attainable of simulate_attainable; they
still work and warn.
plot_tests
¶
plot_tests(scenarios=None, seeds=None, *, seed=0, instances=None, show_quantiles=False, figsize=None, history=None, **diagnostic_settings)
Fit a display suite and return its forecast matrix Figure.
Display defaults use 240 steps of history and 80 to forecast;
test and run keep their defaults of 120 steps of history and 12
steps. To make several figures from the same fits, use run and its
plot methods.
plot_errors
¶
plot_errors(scenarios=None, seeds=None, *, seed=0, instances=None, metric='avoidable_mse', bins=None, missing='raise', figsize=None, **diagnostic_settings)
Fit once per requested case and plot the retained distribution of one metric.
This convenience call draws 20 instances by default. Use an existing
run's plot_errors method to inspect previously evaluated forecasts.
timegym.ForecastRun
dataclass
¶
ForecastRun(cases: list[EvaluatedCase], metadata: dict[str, Any] = dict(), titles: list[str] = list(), kept_data: bool = True)
What Pipeline.run returns: every case's metrics and checks, and its scorecard.
scorecard is the run's Scorecard, metrics every case's metrics in
one table, assert_passed() fails on a crash or a malformed forecast,
save(path) saves the report, checks counts the output checks,
and report is the JSON-ready TestReport, which holds no histories,
observations or forecast arrays. Each entry of cases holds one
case's parts, such as result.cases[0].observed.
kept_data says whether each case still holds its series, answer key
and forecast. Pipeline.run drops them once every case is scored
unless it was called with keep_data=True; the scorecard keeps what it
draws. plot_forecasts() and calibration() read
the forecasts, so they need a run that kept them; plot_errors() reads
only the metrics. titles optionally names each scenario position in
plain words for the plots (a run on the scorecard's kinds of series sets
them to the pattern and noise level); they are not saved in the report.
metadata["name"], when the pipeline or the recorded forecasts were
given a name, heads both plots.
scorecard
property
¶
scorecard
The run's Scorecard: a score per kind of series and noise level, drawn as one picture.
A run on the scorecard's kinds of series, or on patterns of your own, gives the usual card; a run on scenarios you built gives one row per scenario. Runs on ready-made cases, such as your own data, have no scorecard: nobody knows the answer key of real data.
metrics
property
¶
metrics
Every case's metrics as a table, one row per case: TestReport.metrics of this run.
Its labels come first: the scorecard's pattern and noise, or
for scenarios you built their scenario, then the seed; for
your own data its name and where its history ends. One column per
metric follows. A case that
crashed or failed an output check has NaN metrics. It reads only the
metrics, so it works whether or not the run kept its data.
from_forecasts
classmethod
¶
from_forecasts(cases, forecasts, *, name=None, metadata=None, metrics=None, checks=None, **old_arguments)
Check forecasts made earlier, one per case, and measure their errors, without a model.
forecasts[i] is the forecast recorded for cases[i], in any form
a model's predict may return: a list or NumPy array, a pandas Series
or DataFrame, or a Forecast. None means nothing was recorded,
and that case fails "Runs without errors". Each forecast gets the output
checks and metrics of Pipeline.run, and the run's report and plots
work as usual. name says what made the forecasts, for example
name="weather service": it is result.metadata["name"], heads
the plots and labels the run in a comparison, as
Pipeline(..., name=...) does. metadata is added to the run's
metadata, for example {"made_on": "2024-05-01"}; naming the
forecasts there with {"model": ...} still works and warns.
metrics records more metrics and checks adds output checks of
your own, as in Pipeline.run, timegym.checks.dependence()
included. No model is kept, so these cases cannot be replayed.
scores, the old name of metrics, still works and warns, and so
do check_dependence, n_calibration, alpha and
dependence_seed_offset, the old form of dependence().
assert_passed
¶
assert_passed()
Raise AssertionError when any case crashed or failed an output check, as in TestReport.
compare
¶
compare(baseline, *, metric, by=None, cluster=None, alpha=0.05, higher_is_better=False, seed=0)
Compare this run with baseline on the same cases, one metric at a time; returns a ReportComparison.
result.compare(baseline, metric="mae") is
compare_reports(result, baseline, metric="mae"), as in
TestReport.compare: baseline is a run, or a report, made on the
same cases in the same order. It reads only the metrics, so it works
whether or not either run kept its data. To set several candidates
against one baseline at once, use compare_reports([a, b], baseline, ...).
calibration
¶
calibration(*, bins=10, cluster=None, interval_level=0.95, seed=0)
How often this run's yes/no forecasts came true, and the calibration slope; returns a Calibration.
result.calibration() is timegym.diagnostics.calibration(result).
It reads every forecast of a 0/1 outcome, such as rain or no rain, and
what happened, so the run must keep its data (keep_data=True).
bins splits the chances into that many bins of equal width;
cluster names a manifest key whose cases are resampled together,
such as cluster="station"; the slope's interval is at
interval_level, from bootstrap resamples drawn with seed.
calibration(observed, predicted) reads arrays instead.
save
¶
save(path)
Write the run's report to a JSON file at path and return path; series stay out of it.
TestReport.load(path) reads it back, and replay_case reruns a case from it.
to_json
¶
to_json(path=None)
Return the run's report as JSON text; series stay out of it. save(path) writes it to a file.
to_json(path), the old way to write the file, still writes it,
returns the text and warns.
plot_forecasts
¶
plot_forecasts(*, show_quantiles=False, figsize=None, history=None)
Draw timegym.plotting.plot_forecasts for this run's retained forecasts.
plot_errors
¶
plot_errors(metric='avoidable_mse', *, bins=None, missing='raise', figsize=None)
Draw timegym.plotting.plot_errors for this run's retained metrics.
timegym.EvaluatedCase
dataclass
¶
EvaluatedCase(case, forecast, result, scenario_index, seed_index)
One case of a run: what the model saw, what it forecast, what happened and what was measured.
history is the past the model was given, one column per series,
future_index the dates it forecast, observed what happened on
them and reference the answer key (None for your own data).
forecast is what the model returned, None when it crashed.
metrics, diagnostics and manifest are the case's entry in the
report, result.report.cases: each metric by name, every finding, and
the description of the case, with its kind and seed. In a run made
with keep_data=False, the default of Pipeline.run, the series,
the answer key and the forecast are None; the metrics, diagnostics and
manifest stay.
case is the whole Case, to hand to another call such as
ForecastRun.from_forecasts. scenario_index and seed_index
place the case in the run, so two identical scenarios, or two equal
seeds, stay apart. result, the old way to the metrics, diagnostics
and manifest, still works and warns.
history
property
¶
history
The past the model was given, one column per series; None once the run dropped its data.
future_index
property
¶
future_index
The dates the model forecast; None once the run dropped its data.
observed
property
¶
observed
What happened on the forecast dates, one column per series; None once the run dropped its data.
reference
property
¶
reference
The answer key, a Reference; None for your own data and once the run dropped its data.
metrics
property
¶
metrics
Each metric's value by name, as in the report; empty when the model crashed.
diagnostics
property
¶
diagnostics
Every finding about this case, a list of DiagnosticResult, as in the report.
manifest
property
¶
manifest
The description of the case, as in the report: its kind, seed and how it was made.
result
property
writable
¶
result
The case's entry in the report; it still works and warns: read its parts on the entry.
timegym.TestReport
dataclass
¶
TestReport(cases: list[CaseResult], metadata: dict = dict())
Diagnostics and metrics for every case of one run, with run metadata.
A PASS is scoped to a check; unsupported checks do not establish success.
summary
property
¶
summary
Count cases, diagnostics by status, and failed cases.
A case fails when any of its diagnostics is FAIL or ERROR.
metrics
property
¶
metrics
Every case's metrics as a table: one row per case, in order, its labels first.
The labels tell the scenarios apart. A run on the scorecard's kinds
of series labels each case by its row and column on the scorecard,
pattern and noise, so
report.metrics.groupby(["pattern", "noise"])["mae"].mean() gives
one value per cell. A run of scenarios you built labels each by
scenario, the name of its row on the scorecard: its kind, such as
"ar1", then "ar1 (2)" for a second scenario of that kind.
Both add the case's seed. The run records these labels in
metadata["scenario_labels"], so a report read back from its file
has them too. Cases of your own data are labelled by kind, the
name they were cut under, and origin, where their history ends; a
report saved before runs recorded their labels gets kind and
seed. One column per metric follows, in alphabetical order.
A case that crashed or failed an output check is not scored, so its
metrics are NaN, as in compare and the scorecard;
case.metrics still holds any it recorded. The row label is the
case's position in report.cases. The table is made from the cases
each time it is read, so it follows any change to them.
checks
property
¶
checks
Count, per plain-language output check, the cases that passed and failed.
Returns one dictionary per check that ran on at least one case, in the
order of CHECKS and then the checks asked for with checks=:
{"check", "title", "passed", "failed"}. Metrics are not checks:
they have no pass mark.
to_json
¶
to_json(path=None)
Return the report as indented JSON text; save(path) writes it to a file.
to_json(path), the old way to write the file, still writes it,
returns the text and warns.
save
¶
save(path)
Write the report to a JSON file at path and return path; TestReport.load(path) reads it back.
The file holds every case's metrics, findings and manifest and the
run's metadata, as to_json() gives them: enough to replay a case
with replay_case, and no series or forecasts.
from_dict
classmethod
¶
from_dict(payload)
Load schema 2.0 data without importing or constructing saved models.
Unknown fields/statuses, malformed records, nonfinite metrics, and a
saved summary inconsistent with the diagnostics are rejected. Metadata
and evidence remain JSON data. The returned report owns copied values.
A metric saved under an old name, such as mean_reference_mse by
TimeGym 1.14.1, loads under its name now, avoidable_mse, so old and
new reports compare and replay.
from_json
classmethod
¶
from_json(text)
Parse JSON text/bytes, rejecting duplicate keys and nonfinite numbers.
This method never interprets a string as a path. Use load(path)
for a saved report. Loading data does not execute replay or model code.
load
classmethod
¶
load(path)
Read and validate the report file at path, as save wrote it; paths are explicit, never guessed.
assert_passed
¶
assert_passed()
Raise when an output check failed or the model raised; otherwise return self.
The error names each failed check in plain words, then lists every failing case. Metrics never fail this gate: TimeGym sets no accuracy pass mark, so INCONCLUSIVE and UNSUPPORTED results do not raise.
compare
¶
compare(baseline, *, metric, by=None, cluster=None, alpha=0.05, higher_is_better=False, seed=0)
Compare this report with baseline on the same cases, one metric at a time; returns a ReportComparison.
report.compare(baseline, metric="mae") is
compare_reports(report, baseline, metric="mae"): the same paired
test, the same table and the same arguments. baseline is a report,
or a run, made on the same cases in the same order; by gives one
row per value of a manifest key, cluster names a manifest key whose
cases move together, and lower is better unless
higher_is_better=True. To set several candidates against one
baseline at once, use compare_reports([a, b], baseline, ...).
replay_case
¶
replay_case(case_index=0)
Re-evaluate one case when its built-in model configuration is replayable.
timegym.CaseResult
dataclass
¶
CaseResult(scenario: str, seed: int | None, diagnostics: list[DiagnosticResult] = list(), metrics: dict = dict(), manifest: dict = dict())
The diagnostics and metrics recorded for one case.
scenario labels the case and seed is its generator seed.
metrics maps metric names to finite numbers, and manifest is the
case manifest that replay rebuilds a generated scenario from. A case with
an answer key has avoidable_mse, the squared distance from the
forecast to it; reading it under its old name, "mean_reference_mse",
still works and warns.
timegym.DiagnosticResult
dataclass
¶
DiagnosticResult(name: str, status: str, category: str, message: str, evidence: dict = dict())
One named finding: its status, category, message and evidence.
status and category are checked against DiagnosticStatus and
DiagnosticCategory and stored as strings. evidence is copied into
JSON-safe values.
timegym.DiagnosticStatus
¶
The five outcomes a diagnostic can report.
PASS and FAIL are verdicts of an implemented check. INCONCLUSIVE
marks evidence without a verdict, UNSUPPORTED a check that does not
apply and ERROR an execution failure. Members equal their string values.
timegym.DiagnosticCategory
¶
The kind of evidence a diagnostic records; members equal their string values.
correctness is a forecast contract, evaluation the evaluator's own
inputs, capability and uncertainty descriptive metrics,
distribution a statistical check against a reference law,
metamorphic a declared relation and execution a model exception.
timegym.plotting.plot_forecasts
¶
plot_forecasts(run, *, show_quantiles=False, figsize=None, history=None)
Plot retained forecasts as scenario/target rows and seed columns.
Each panel uses the scorecard's look: gray dots are observations, the
black line is the answer key, blue crosses are the forecast. Above it, the
case's 0-100 score sits in its colored band beside its error against the
answer key and against what happened. history is how many past steps
to show: four times the horizon by default, "all" for the whole
history. Bands, when requested, are marginal intervals, never
simultaneous path regions. A run whose pipeline has a name, such as
Pipeline(model, name="Forest"), shows it above the panels.
timegym.plotting.plot_errors
¶
plot_errors(run, metric='avoidable_mse', *, bins=None, missing='raise', figsize=None)
Show distributions of retained whole-case metrics, one row per scenario.
metric names a metric in case.metrics; the default,
"avoidable_mse", is the error against the answer key, and
"mean_reference_mse", its old name, still works and warns.
These are distributions over evaluated cases, not over predictive sample
draws or dependent coordinates. A black line marks each row's median.
Scenario positions remain distinct even when their kind strings match.
Missing or nonfinite values raise by default; missing='annotate'
shows their counts and diagnostic reasons in each panel instead, so they
are never silently dropped. A named run shows its name above the panels.