Skip to content

API reference

Sequential testing

anywatch.sequential.BettingEProcess(null_mean, alternative='less', alpha=0.05, max_bet_fraction=0.5, keep_history=True)

Anytime-valid sequential test for the mean of observations in [0, 1].

Parameters:

Name Type Description Default
null_mean float

Boundary value :math:m of the null hypothesis, strictly inside (0, 1).

required
alternative Alternative

"less" tests :math:H_0: \mu \ge m against :math:\mu < m. "greater" tests :math:H_0: \mu \le m against :math:\mu > m. "two-sided" tests :math:H_0: \mu = m with a hedged e-process that averages the two one-sided wealth processes.

'less'
alpha float

Type I error level. The null is rejected the first time the e-process reaches 1 / alpha.

0.05
max_bet_fraction float

Fraction c in (0, 1) of the largest admissible bet. Smaller values are more conservative and more robust. The default 0.5 follows Waudby-Smith and Ramdas (2024).

0.5
keep_history bool

Store the e-process after every observation.

True
Notes

The bet size uses the approximate GRAPA rule, a predictable plug-in that approximately maximises the expected log wealth:

.. math::

\lambda_t = \frac{\hat\mu_{t-1} - m}
{\hat\sigma^2_{t-1} + (\hat\mu_{t-1} - m)^2},

truncated to the admissible range. Because the bet depends only on past data the guarantee holds for every data generating process with bounded support, including dependent streams, as long as the conditional mean satisfies the null at every step.

Examples:

>>> import numpy as np
>>> rng = np.random.default_rng(0)
>>> test = BettingEProcess(null_mean=0.9, alternative="less", alpha=0.05)
>>> _ = test.update(rng.binomial(1, 0.8, size=500))
>>> test.rejected
True

n property

Number of observations processed.

evalue property

Current value of the e-process.

log_evalue property

Natural logarithm of the current e-process value.

max_evalue property

Largest value the e-process has reached so far.

rejected property

Whether the e-process has ever reached 1 / alpha.

rejection_time property

Number of observations at the first crossing, or None.

rejection_evalue property

E-process value at the first crossing, or NaN.

rejection_estimate property

Sample mean at the first crossing, or NaN.

anytime_pvalue property

Anytime-valid p-value min(1, 1 / max_t E_t).

estimate property

Sample mean of the observations, or NaN before the first one.

history property

E-process values after each observation.

reset()

Forget all observations and return to the initial state.

update(x)

Process one observation or an ordered batch of observations.

Parameters:

Name Type Description Default
x ArrayLike

A scalar or a one dimensional array with values in [0, 1].

required

Returns:

Type Description
BettingEProcess

The instance itself, so calls can be chained.

summary()

Return a JSON-serialisable summary of the current state.

anywatch.sequential.EmpiricalBernsteinCS(alpha=0.05, max_bet_fraction=0.5, running_intersection=True, keep_history=True)

Bases: ConfidenceSequence

Predictable plug-in empirical Bernstein confidence sequence.

Parameters:

Name Type Description Default
alpha float

One minus the time-uniform coverage probability.

0.05
max_bet_fraction float

Upper truncation c of the bet sizes. Must lie in (0, 1).

0.5
running_intersection bool

Intersect each interval with all previous ones. This keeps validity and makes the bounds monotone.

True
keep_history bool

Store the interval after every observation.

True
Notes

With :math:\psi_E(\lambda) = (-\log(1 - \lambda) - \lambda) / 4 and :math:v_i = 4 (X_i - \hat\mu_{i-1})^2 the interval at time :math:t is

.. math::

\frac{\sum_i \lambda_i X_i}{\sum_i \lambda_i} \pm
\frac{\log(2/\alpha) + \sum_i v_i \psi_E(\lambda_i)}{\sum_i \lambda_i}.

Examples:

>>> cs = EmpiricalBernsteinCS(alpha=0.05)
>>> _ = cs.update([1, 1, 0, 1] * 100)
>>> lower, upper = cs.interval
>>> lower < 0.75 < upper
True

reset()

Forget all observations.

anywatch.sequential.BettingCS(alpha=0.05, grid_size=1000, max_bet_fraction=0.5, theta=0.5, running_intersection=True, keep_history=True)

Bases: ConfidenceSequence

Hedged betting confidence sequence computed on a grid.

Parameters:

Name Type Description Default
alpha float

One minus the time-uniform coverage probability.

0.05
grid_size int

Number of candidate means in (0, 1). The reported interval is widened by one grid step on each side so that it always contains the continuous confidence set.

1000
max_bet_fraction float

Upper truncation c of the bet sizes. Must lie in (0, 1).

0.5
theta float

Weight of the upward bet in the hedged wealth. The default 1/2 gives a symmetric interval.

0.5
running_intersection bool

Intersect each confidence set with all previous ones.

True
keep_history bool

Store the interval after every observation.

True
Notes

For each candidate mean :math:m the hedged wealth is

.. math::

K_t(m) = \theta \prod_{i \le t} (1 + \lambda_i^+(m)(X_i - m))
+ (1 - \theta) \prod_{i \le t} (1 - \lambda_i^-(m)(X_i - m)),

and the confidence set is :math:\{m : K_t(m) < 1/\alpha\}.

Examples:

>>> cs = BettingCS(alpha=0.05, grid_size=200)
>>> _ = cs.update([1, 0, 1, 1] * 100)
>>> lower, upper = cs.interval
>>> lower < 0.75 < upper
True

reset()

Forget all observations.

anywatch.sequential.sequential_mean_test(x, null_mean, alternative='less', alpha=0.05, max_bet_fraction=0.5)

Run a betting e-process over an ordered sample.

The observations are processed in the given order, as if they had arrived one at a time. The result is valid whatever stopping rule produced the sample.

Parameters:

Name Type Description Default
x ArrayLike

Ordered observations with values in [0, 1].

required
null_mean float

Boundary of the null hypothesis, strictly inside (0, 1).

required
alternative Alternative

"less", "greater" or "two-sided". See :class:~anywatch.sequential.BettingEProcess.

'less'
alpha float

Type I error level.

0.05
max_bet_fraction float

Truncation constant of the bet sizes.

0.5

Returns:

Type Description
SequentialTestResult

Examples:

>>> result = sequential_mean_test([1] * 80 + [0] * 20, null_mean=0.95)
>>> result.rejected
True

anywatch.sequential.SequentialTestResult(rejected, rejection_time, n, estimate, final_evalue, max_evalue, anytime_pvalue, alpha, null_mean, alternative) dataclass

Outcome of an anytime-valid test run over a complete data set.

Attributes:

Name Type Description
rejected bool

Whether the null hypothesis was rejected at some time.

rejection_time int | None

Number of observations at the first rejection, or None.

n int

Total number of observations.

estimate float

Sample mean of all observations.

final_evalue float

E-process value after the last observation.

max_evalue float

Largest e-process value over the whole stream.

anytime_pvalue float

min(1, 1 / max_evalue).

alpha, null_mean, alternative

Settings of the test.

to_dict()

Return the result as a plain dictionary.

anywatch.sequential.PairedDifferenceEProcess(margin=0.0, alternative='less', alpha=0.05, max_bet_fraction=0.5)

Anytime-valid test for the mean difference of paired bounded outcomes.

Each observation is a pair :math:(A_i, B_i) \in [0, 1]^2, for example whether the deployed model and a reference model were correct on the same case. The test concerns :math:\delta = E[A - B] and reduces to :class:~anywatch.sequential.BettingEProcess applied to :math:Z_i = (A_i - B_i + 1) / 2.

Parameters:

Name Type Description Default
margin float

Boundary :math:\delta_0 of the null hypothesis, strictly inside (-1, 1). With alternative="less" the null is :math:\delta \ge \delta_0, so a negative margin encodes a non-inferiority tolerance.

0.0
alternative Alternative

"less", "greater" or "two-sided".

'less'
alpha float

Type I error level.

0.05
max_bet_fraction float

Truncation constant of the bet sizes.

0.5

Examples:

>>> test = PairedDifferenceEProcess(margin=-0.02, alternative="less")
>>> _ = test.update([0] * 300, [1] * 300)
>>> test.rejected
True

n property

Number of pairs processed.

estimate property

Mean difference of the pairs seen so far.

evalue property

Current e-process value.

rejected property

Whether the null hypothesis has been rejected.

rejection_time property

Number of pairs at the first rejection, or None.

anytime_pvalue property

Anytime-valid p-value.

update(a, b)

Process paired observations in order.

summary()

Return a JSON-serialisable summary of the current state.

Subgroups

anywatch.subgroups.SubgroupMonitor(metric, target, groups, alpha=0.05, correction='bonferroni', alternative=None, max_bet_fraction=0.5, name=None)

Monitor a classification metric against a target in every subgroup.

For each subgroup :math:g the monitor runs a betting e-process for

.. math::

H_{0,g}: \text{metric}_g \ge \text{target}

(or :math:\le for metrics where high values are bad, such as the error rate) together with an empirical Bernstein confidence sequence for the metric.

Parameters:

Name Type Description Default
metric str

Name of a metric in :data:anywatch.subgroups.METRICS, for example "sensitivity" or "error_rate".

required
target float

Acceptable boundary value of the metric, strictly inside (0, 1).

required
groups Iterable[Any]

All subgroup labels that will be monitored. Declaring them in advance is what makes the multiplicity correction valid.

required
alpha float

Overall error level.

0.05
correction Correction

"bonferroni" runs every subgroup at level alpha / K. Combined with Ville's inequality this bounds the probability of any false alarm in any subgroup at any time by alpha. "none" runs each subgroup at level alpha.

'bonferroni'
alternative Alternative | None

Override the direction implied by the metric.

None
max_bet_fraction float

Truncation constant passed to the e-processes.

0.5
name str | None

Name used in alarms and reports.

None

Examples:

>>> import numpy as np
>>> rng = np.random.default_rng(1)
>>> monitor = SubgroupMonitor("sensitivity", target=0.9, groups=["a", "b"])
>>> y_true = np.ones(2000, dtype=int)
>>> group = np.repeat(["a", "b"], 1000)
>>> y_pred = np.r_[rng.binomial(1, 0.97, 1000), rng.binomial(1, 0.80, 1000)]
>>> alarms = monitor.update(y_true, y_pred, group)
>>> [alarm.source for alarm in alarms]
['sensitivity[b]']

n property

Number of cases processed across all groups.

alarms property

All alarms raised so far.

any_alarm property

Whether any subgroup has alarmed.

reset()

Forget all observations.

update(y_true, y_pred, group=None)

Process a batch of labelled cases in arrival order.

Parameters:

Name Type Description Default
y_true ArrayLike

Reference labels, 0 or 1.

required
y_pred ArrayLike

Model predictions, 0 or 1.

required
group ArrayLike | None

Subgroup label of every case. May be omitted when the monitor has a single group.

None

Returns:

Type Description
list of Alarm

Alarms raised by this batch. Each subgroup alarms at most once.

counts(group)

Confusion counts of group so far.

status()

Return the current :class:SubgroupStatus of every group.

ebh_discoveries(alpha=None)

Subgroups flagged by e-BH applied to the current e-values.

The e-value of a betting e-process at a stopping time is a valid e-value, so this controls the false discovery rate at alpha at the time it is called, under any dependence between groups. It is less conservative than the Bonferroni alarms when many groups are monitored.

summary()

Return a JSON-serialisable summary used by the reporting module.

anywatch.subgroups.SubgroupStatus(group, n_cases, n_eligible, estimate, ci_lower, ci_upper, evalue, max_evalue, anytime_pvalue, alarm, alarm_time) dataclass

State of one subgroup at the current time.

Attributes:

Name Type Description
group str

Subgroup label.

n_cases int

All cases seen in the subgroup.

n_eligible int

Cases that enter the metric, for example positives for sensitivity.

estimate float

Point estimate of the metric, NaN if there are no eligible cases.

ci_lower, ci_upper

Bounds of the time-uniform confidence sequence at the per-group level.

evalue float

Current e-process value.

max_evalue float

Running maximum of the e-process.

anytime_pvalue float

Anytime-valid p-value at the per-group level.

alarm bool

Whether the subgroup has crossed its threshold.

alarm_time int | None

Number of eligible cases in the subgroup at the crossing.

to_dict()

Return the status as a JSON friendly dictionary.

anywatch.subgroups.ConfusionCounts(tp=0, fp=0, tn=0, fn=0) dataclass

Counts of a binary confusion matrix with derived metrics.

Metrics whose denominator is zero are reported as NaN.

n property

Total number of cases.

sensitivity property

TP / (TP + FN).

specificity property

TN / (TN + FP).

ppv property

TP / (TP + FP).

npv property

TN / (TN + FN).

accuracy property

(TP + TN) / n.

error_rate property

(FP + FN) / n.

false_negative_rate property

FN / (TP + FN).

false_positive_rate property

FP / (TN + FP).

metric(name)

Return the metric called name.

to_dict()

Return counts and all metrics as a dictionary.

anywatch.subgroups.confusion_counts(y_true, y_pred)

Count true and false positives and negatives.

Examples:

>>> confusion_counts([1, 1, 0, 0], [1, 0, 0, 1])
ConfusionCounts(tp=1, fp=1, tn=1, fn=1)

anywatch.subgroups.subgroup_metrics(y_true, y_pred, groups)

Compute :class:ConfusionCounts separately for every subgroup.

Examples:

>>> out = subgroup_metrics([1, 1, 0, 1], [1, 0, 0, 1], ["a", "a", "b", "b"])
>>> out["a"].sensitivity, out["b"].sensitivity
(0.5, 1.0)

anywatch.subgroups.metric_observations(metric, y_true, y_pred)

Translate labels and predictions into observations for metric.

Returns:

Name Type Description
mask _BoolArray

Boolean mask of the cases that enter the metric.

outcomes NDArray[float64]

Binary outcome for every case, as floats. Only entries where mask is true are meaningful.

Examples:

>>> mask, outcome = metric_observations("sensitivity", [1, 0, 1], [1, 1, 0])
>>> mask.tolist(), outcome[mask].tolist()
([True, False, True], [1.0, 0.0])

anywatch.subgroups.ebh(evalues, alpha=0.05)

E-Benjamini-Hochberg procedure.

Rejects the hypotheses with the :math:k^* largest e-values, where

.. math::

k^* = \max\{k : e_{(k)} \ge K / (\alpha k)\}

and :math:e_{(1)} \ge \dots \ge e_{(K)}. The false discovery rate is at most alpha under any dependence structure.

Parameters:

Name Type Description Default
evalues ArrayLike

One e-value per hypothesis.

required
alpha float

Target false discovery rate.

0.05

Returns:

Type Description
ndarray

Boolean rejection indicator in the input order.

Examples:

>>> ebh([100.0, 50.0, 1.0, 0.2], alpha=0.1).tolist()
[True, True, False, False]

anywatch.subgroups.bonferroni_evalues(evalues, alpha=0.05)

Reject every hypothesis whose e-value is at least K / alpha.

Controls the family-wise error rate at alpha. When applied to the running maxima of e-processes the control holds uniformly over time.

Examples:

>>> bonferroni_evalues([100.0, 50.0, 1.0], alpha=0.05).tolist()
[True, False, False]

anywatch.subgroups.merge_evalues(evalues, method='mean', weights=None)

Combine several e-values into one.

Parameters:

Name Type Description Default
evalues ArrayLike

E-values to combine.

required
method Literal['mean', 'product']

"mean" returns a weighted average, which is an e-value under any dependence. "product" returns the product, which is an e-value only when the e-values are independent or sequentially valid.

'mean'
weights ArrayLike | None

Nonnegative weights for "mean". They are normalised to sum to one.

None

Examples:

>>> merge_evalues([4.0, 0.0])
2.0

Drift

anywatch.drift.QuantileDriftDetector(reference, quantiles=(0.1, 0.25, 0.5, 0.75, 0.9), alpha=0.05, name='quantile_drift')

Distribution-free drift detector based on reference quantiles.

For every probability level :math:q the detector computes the reference quantile :math:r_q and monitors the indicator :math:1\{X_t \le r_q\}, whose mean should equal the reference proportion :math:p_q \approx q. One two-sided betting e-process runs per level, each at level alpha / len(quantiles), so the probability of any false alarm at any time is at most alpha. No bounds on the feature are needed.

Parameters:

Name Type Description Default
reference ArrayLike

Reference sample of the feature.

required
quantiles tuple[float, ...]

Probability levels in (0, 1).

(0.1, 0.25, 0.5, 0.75, 0.9)
alpha float

Overall false alarm probability.

0.05
name str

Name used in alarms and reports.

'quantile_drift'

Examples:

>>> import numpy as np
>>> rng = np.random.default_rng(0)
>>> detector = QuantileDriftDetector(rng.normal(size=5000))
>>> _ = detector.update(rng.normal(loc=1.0, size=500))
>>> detector.drift_detected
True

n property

Number of observations processed.

drift_detected property

Whether any quantile test has alarmed.

evalues property

Current e-values, one per quantile.

alarms property

Alarms raised so far.

update(x)

Process new observations and return any new alarms.

summary()

Return a JSON-serialisable summary used by the reporting module.

anywatch.drift.MeanShiftDetector(reference_mean, lower, upper, alpha=0.05, name='mean_shift')

Anytime-valid two-sided test for a shift in the mean of a bounded feature.

Parameters:

Name Type Description Default
reference_mean float

Mean of the feature under normal operation.

required
lower float

Known bounds of the feature. Values are rescaled to [0, 1]. Values outside the bounds raise an error, because the guarantee needs them.

required
upper float

Known bounds of the feature. Values are rescaled to [0, 1]. Values outside the bounds raise an error, because the guarantee needs them.

required
alpha float

Probability of a false alarm at any time while the mean is unchanged.

0.05
name str

Name used in alarms and reports.

'mean_shift'

Examples:

>>> detector = MeanShiftDetector(reference_mean=0.3, lower=0.0, upper=1.0)
>>> _ = detector.update([0.6] * 200)
>>> detector.drift_detected
True

n property

Number of observations processed.

estimate property

Mean of the live stream on the original scale.

evalue property

Current e-process value.

drift_detected property

Whether the detector has alarmed.

alarms property

Alarms raised so far.

from_reference(reference, lower, upper, alpha=0.05, name='mean_shift') classmethod

Create a detector whose reference mean is the mean of reference.

update(x)

Process new observations and return any new alarm.

summary()

Return a JSON-serialisable summary used by the reporting module.

anywatch.drift.population_stability_index(reference, current, bins=10, eps=0.0001)

Compute the population stability index between a reference and a current sample.

The bins are quantiles of the reference sample. The index is

.. math::

\mathrm{PSI} = \sum_b (c_b - r_b) \log(c_b / r_b),

where :math:r_b and :math:c_b are the bin proportions. It is a descriptive measure and carries no error guarantee. Common rules of thumb read values below 0.1 as stable and above 0.25 as a major shift.

Examples:

>>> import numpy as np
>>> rng = np.random.default_rng(0)
>>> ref = rng.normal(size=5000)
>>> population_stability_index(ref, rng.normal(size=5000)) < 0.1
True

anywatch.drift.PerformanceDegradationDetector(baseline, tolerance=0.0, alpha=0.05, higher_is_better=True, name='performance')

Alarm when a performance score falls below baseline - tolerance.

Parameters:

Name Type Description Default
baseline float

Performance established before deployment, for example validation accuracy, in (0, 1).

required
tolerance float

Acceptable loss relative to the baseline. The null hypothesis is that the mean score is at least baseline - tolerance.

0.0
alpha float

Probability of a false alarm at any time while the null holds.

0.05
higher_is_better bool

Set to False for scores such as an error indicator. The null then becomes that the mean is at most baseline + tolerance.

True
name str

Name used in alarms and reports.

'performance'

Examples:

>>> detector = PerformanceDegradationDetector(baseline=0.92, tolerance=0.02)
>>> _ = detector.update([1] * 800 + [0] * 200)
>>> detector.degraded
True

n property

Number of cases processed.

estimate property

Mean score so far.

evalue property

Current e-process value.

degraded property

Whether degradation has been detected.

history property

E-process values after each case.

alarms property

Alarms raised so far.

update(scores)

Process per-case scores in [0, 1] and return any new alarm.

summary()

Return a JSON-serialisable summary used by the reporting module.

anywatch.drift.ChangeDetector(pre_change_mean, direction='decrease', arl=1000.0, n_bets=12, statistic='sr', restart=True, name='change')

Nonparametric e-detector for a change in the mean of bounded scores.

Before the change the scores :math:X_t \in [0, 1] have conditional mean at least pre_change_mean (for direction="decrease"). The detector runs, for each bet :math:\lambda in a fixed grid, the Shiryaev-Roberts recursion

.. math::

R_t(\lambda) = (R_{t-1}(\lambda) + 1)\,(1 + \lambda(m - X_t)),
\qquad R_0(\lambda) = 0,

and alarms when the average over the grid reaches arl. The average is an e-detector, so the expected time to a false alarm is at least arl (Shin, Ramdas and Rinaldo, 2024). With statistic="cusum" the recursion uses :math:\max(R_{t-1}, 1) instead of :math:R_{t-1} + 1.

Parameters:

Name Type Description Default
pre_change_mean float

Boundary of acceptable performance, strictly inside (0, 1).

required
direction Literal['decrease', 'increase']

"decrease" detects a drop of the mean below pre_change_mean, "increase" detects a rise above it.

'decrease'
arl float

Target average run length to a false alarm. Must exceed one.

1000.0
n_bets int

Number of bet sizes in the mixture.

12
statistic Literal['sr', 'cusum']

"sr" (Shiryaev-Roberts) or "cusum".

'sr'
restart bool

Restart the detector after each alarm.

True
name str

Name used in alarms and reports.

'change'

Examples:

>>> import numpy as np
>>> rng = np.random.default_rng(3)
>>> x = np.r_[rng.binomial(1, 0.95, 2000), rng.binomial(1, 0.80, 500)]
>>> detector = ChangeDetector(pre_change_mean=0.93, arl=1000)
>>> alarms = detector.update(x)
>>> alarms[0].time > 2000
True

log_statistic property

Logarithm of the current mixture statistic.

n property

Number of observations processed.

value property

Current value of the mixture statistic.

alarms property

Alarms raised so far.

reset()

Clear all state, including the alarm list.

update(x)

Process scores in [0, 1] in order and return any new alarms.

summary()

Return a JSON-serialisable summary used by the reporting module.

Reporting

anywatch.reporting.AuditTrail()

Append-only event log with a SHA-256 hash chain.

Every entry stores the hash of the previous entry, so any later change to an entry breaks the chain and is detected by :meth:verify.

Examples:

>>> trail = AuditTrail()
>>> _ = trail.record("monitor_created", metric="sensitivity", target=0.9)
>>> trail.verify()
True

entries property

Copies of all entries.

head property

Hash of the latest entry.

record(event, **details)

Append an event and return the stored entry.

verify()

Return True if no entry has been altered, removed or reordered.

to_dict()

Return the trail with its integrity status.

to_json(indent=2)

Serialise the trail to JSON.

from_entries(entries) classmethod

Rebuild a trail from stored entries. Call :meth:verify afterwards.

anywatch.reporting.SystemInfo(name, version, provider, intended_purpose, deployment_context='', contact='', identifier='') dataclass

Identification of the monitored AI system.

Attributes:

Name Type Description
name str

Product or system name.

version str

Model or software version under monitoring.

provider str

Legal entity responsible for the system (provider under the AI Act, manufacturer under FDA regulations).

intended_purpose str

Intended purpose as stated in the technical documentation.

deployment_context str

Where and how the system is used, for example the deploying site.

contact str

Person or function responsible for post-market monitoring.

identifier str

Registration, UDI or internal identifier.

to_dict()

Return the fields as a dictionary.

anywatch.reporting.PostMarketMonitoringPlan(data_sources, collection_frequency, responsible_person, review_interval='At least annually and after every alarm.', corrective_action_procedure='An alarm triggers a documented root cause review. Where the system is found not to be in conformity, corrective actions under Article 20 are taken and deployers and distributors are informed.', serious_incident_procedure='Serious incidents are reported to the market surveillance authorities of the Member States concerned in accordance with Article 73.', other_systems='') dataclass

Elements of the post-market monitoring plan referred to in Article 72(3).

Attributes:

Name Type Description
data_sources list[str]

Where performance data come from, for example deployer feedback or linked outcome registries.

collection_frequency str

How often data are collected and analysed.

responsible_person str

Function responsible for post-market monitoring.

review_interval str

How often the plan and its thresholds are reviewed.

corrective_action_procedure str

What happens after an alarm (Article 20).

serious_incident_procedure str

How serious incidents are reported (Article 73).

other_systems str

Interaction with other AI systems, where relevant (Article 72(2)).

to_dict()

Return the plan as a dictionary.

anywatch.reporting.build_art72_report(system, monitors, plan, audit=None, period_start=None, period_end=None, notes=None)

Assemble an Article 72 post-market monitoring report.

Parameters:

Name Type Description Default
system SystemInfo

Identification of the AI system.

required
monitors Iterable[SupportsSummary]

Monitors whose summary() provides the statistical evidence.

required
plan PostMarketMonitoringPlan

The post-market monitoring plan.

required
audit AuditTrail | None

Optional audit trail. Its integrity is verified and reported.

None
period_start str | None

Monitoring period covered by the report, as ISO 8601 dates.

None
period_end str | None

Monitoring period covered by the report, as ISO 8601 dates.

None
notes Iterable[str] | None

Additional free text remarks appended to the conclusion.

None

Returns:

Type Description
RegulatoryReport

Render with to_markdown(), to_html() or to_json().

anywatch.reporting.ModificationProtocol(description_of_modifications, data_management, retraining, performance_evaluation, update_procedures, impact_assessment, acceptance_criteria=list()) dataclass

Textual PCCP components supplied by the manufacturer.

Attributes:

Name Type Description
description_of_modifications str

The planned modifications covered by the PCCP.

data_management str

Data management practices for training and test data.

retraining str

Re-training practices.

performance_evaluation str

Performance evaluation protocol, including the statistical plan.

update_procedures str

How updates are rolled out and communicated to users.

impact_assessment str

Assessment of benefits and risks of the planned modifications.

acceptance_criteria list[str]

Explicit, testable acceptance criteria.

to_dict()

Return the protocol as a dictionary.

anywatch.reporting.build_pccp_report(system, monitors, protocol, audit=None, period_start=None, period_end=None)

Assemble a PCCP performance evaluation report.

Parameters:

Name Type Description Default
system SystemInfo

Identification of the device software function.

required
monitors Iterable[SupportsSummary]

Monitors whose summary() provides the statistical evidence.

required
protocol ModificationProtocol

Textual PCCP components.

required
audit AuditTrail | None

Optional audit trail. Its integrity is verified and reported.

None
period_start str | None

Period covered by the report, as ISO 8601 dates.

None
period_end str | None

Period covered by the report, as ISO 8601 dates.

None

Returns:

Type Description
RegulatoryReport

anywatch.reporting.RegulatoryReport(framework, template, title, system, monitors, sections, period_start=None, period_end=None, audit=None, generated_at=_utc_now(), generator=f'anywatch {__version__}', disclaimer=DISCLAIMER) dataclass

Structured monitoring report that can be rendered in several formats.

Instances are normally created by :func:~anywatch.reporting.build_art72_report or :func:~anywatch.reporting.build_pccp_report.

alarms property

All alarms from all monitors.

overall_status property

"alarm" if any monitor alarmed, otherwise "no_alarm".

to_dict()

Return the report as a JSON friendly dictionary.

to_json(indent=2)

Serialise the report to JSON after validating it against the schema.

to_markdown()

Render the report as Markdown.

to_html()

Render the report as a standalone HTML page.

save(path)

Write the report to path. The format follows the file suffix.

Supported suffixes are .json, .md and .html.

anywatch.reporting.validate_report(report)

Raise :class:~anywatch.exceptions.ReportValidationError if invalid.

Alarms

anywatch.alarms.Alarm(source, time, statistic, threshold, message, severity='warning', timestamp=_utc_now()) dataclass

A single alarm raised by a monitor.

Parameters:

Name Type Description Default
source str

Name of the monitor or subgroup that raised the alarm.

required
time int

Number of observations processed by the source when the alarm fired.

required
statistic float

Value of the monitoring statistic (an e-value or e-detector) at that time.

required
threshold float

Threshold the statistic crossed.

required
message str

Human readable description.

required
severity Severity

"info", "warning" or "critical".

'warning'
timestamp str

UTC wall clock time in ISO 8601 format.

_utc_now()

to_dict()

Return the alarm as a plain dictionary.

anywatch.alarms.AlarmLog()

Collect alarms and forward them to optional callbacks.

Examples:

>>> log = AlarmLog()
>>> log.subscribe(lambda alarm: None)
>>> log.extend([])
>>> len(log)
0

alarms property

All alarms in the order they were added.

subscribe(callback)

Call callback for every alarm added from now on.

add(alarm)

Store alarm and notify subscribers.

extend(alarms)

Add several alarms in order.

to_list()

Return all alarms as dictionaries.

Datasets

anywatch.datasets.make_classification_stream(n, groups=('all',), prevalence=0.2, sensitivity=0.92, specificity=0.9, group_probs=None, change_point=None, post_change_sensitivity=None, post_change_specificity=None, seed=None)

Simulate a stream of cases from a binary classifier.

Parameters:

Name Type Description Default
n int

Number of cases.

required
groups Sequence[str]

Subgroup labels.

('all',)
prevalence float

Probability that a case is positive.

0.2
sensitivity float | Mapping[str, float]

Operating characteristics before the change, either one value or one value per group.

0.92
specificity float | Mapping[str, float]

Operating characteristics before the change, either one value or one value per group.

0.92
group_probs Sequence[float] | None

Probability of each group. Uniform by default.

None
change_point int | None

Index from which the post-change characteristics apply.

None
post_change_sensitivity float | Mapping[str, float] | None

Operating characteristics after the change. Unchanged by default.

None
post_change_specificity float | Mapping[str, float] | None

Operating characteristics after the change. Unchanged by default.

None
seed int | Generator | None

Seed or generator for reproducibility.

None

Examples:

>>> stream = make_classification_stream(1000, groups=["a", "b"], seed=0)
>>> len(stream)
1000

anywatch.datasets.make_feature_stream(n, change_point=None, shift=0.5, scale=1.0, seed=None)

Simulate a normally distributed feature whose mean shifts at change_point.

Examples:

>>> x = make_feature_stream(100, change_point=50, shift=2.0, seed=0)
>>> bool(x[50:].mean() > x[:50].mean())
True