Tasks, sources, and providers¶
optimize_partition ¶
optimize_partition(scores: ScoreSample | ArrayLike, *, weights: ArrayLike | None = None, n_bins: int, criterion: DOptimality | ProfiledDOptimality | None = None, config: PartitionConfig | None = None, provenance: ScoreProvenance | None = None, initial_labels: ArrayLike | None = None, execution: ExecutionConfig | None = None) -> PartitionResult
Optimize labels of one fixed score table without prediction semantics.
Both finite criteria accept either the exact positive-gain exchange or the guarded Mahalanobis-Lloyd solver; the guarded batch never accepts a step that the exactly rebuilt objective does not certify.
Parameters:
-
scores(ScoreSample | ArrayLike) –Either a :class:
~scorequant.ScoreSample-- the same weighted score law :func:fit_quantizertakes, carrying its own weights, schema and provenance -- or a raw score array, in which caseweightsandprovenancesupply those separately. Passing a sample together with either keyword is rejected rather than silently resolved.An observation source is deliberately not accepted here: converting observations to scores stays an explicit
provider.score(X)so the fixed-sample boundary remains visible. -
weights(ArrayLike | None, default:None) –Fixed-sample assignment contract described in the API guide.
-
n_bins(ArrayLike | None, default:None) –Fixed-sample assignment contract described in the API guide.
-
criterion(ArrayLike | None, default:None) –Fixed-sample assignment contract described in the API guide.
-
config(ArrayLike | None, default:None) –Fixed-sample assignment contract described in the API guide.
-
provenance(ArrayLike | None, default:None) –Fixed-sample assignment contract described in the API guide.
-
initial_labels(ArrayLike | None, default:None) –Optional starting labeling with shape
[N]and values in[0, n_bins), for exampleEfficientScoreBound.labels. Zero-weight rows carry no measure and their labels are ignored; identical score rows are merged before the solver runs and must therefore already agree on their bin, and every requested cell must remain nonempty afterwards. Supplied labels replace the seeding of the first exchange restart only, soinitandinitializer_restartsstill govern any further restart; the guarded Mahalanobis-Lloyd solver starts from them directly.
fit_quantizer ¶
fit_quantizer(source: Source, *, provider: ScoreProvider | None = None, validation: Source | None = None, n_bins: int, criterion: Criterion | None = None, config: QuantizerConfig | None = None, diagnostics: DiagnosticsMode = 'endpoints', execution: ExecutionConfig | None = None) -> QuantizerResult
Fit a reusable hard rule from an empirical or bounded score law.
A score callback alone is deliberately insufficient: observations must be paired with an empirical or integration source that defines their measure.
Parameters:
-
provider(ScoreProvider | None, default:None) –The observation-to-score map for an observation or integration source. It is the object contract :class:
~scorequant.ScoreProviderdescribes, not a score array or a bare callable, and it is rejected whensourceis already a :class:~scorequant.ScoreSample. -
diagnostics(DiagnosticsMode, default:'endpoints') –How much of the recorded center history to re-score into
trace.train_hard_retentionandtrace.validation_hard_retention."final"scores only the terminal centers (one full-dataset pass),"endpoints"(the default) scores the first and terminal centers (two passes), and"full"scores every recorded snapshot, matching the historical behavior. Snapshots that are not scored holdnan, so the returned history always stays aligned withtrace.steps. This only affects diagnostic reporting; it never changescenters,labels, or either report.
ScoreSample
dataclass
¶
ScoreSample(scores: ArrayLike, weights: ArrayLike | None = None, *, schema: ScoreSchema | None = None, provenance: ScoreProvenance | None = None)
A finite weighted score table representing an empirical score law.
Parameters:
-
scores(ArrayLike) –Score rows with shape
[N, P]and their nonnegative measure. -
weights(ArrayLike) –Score rows with shape
[N, P]and their nonnegative measure. -
schema(ScoreSchema | None, default:None) –Optional :class:
ScoreSchemanaming what each of thePcolumns differentiates. When present it must have exactlyPnames, and a profiled criterion may then declare its parameters of interest by name. -
provenance(ScoreProvenance | None, default:None) –Optional record of how the scores were obtained.
ScoreSchema
dataclass
¶
Name the parameter each score coordinate differentiates.
A score table is a matrix of partial derivatives, one column per model
parameter, and the column order is meaningful but invisible. Declaring the
names lets a profiled criterion say interest=("HSPCs",) instead of
interest=(4,), and lets reports and saved rules print the parameter
rather than its position.
This answers only what each coordinate means. Where the numbers came from
and at which reference point remains the job of
:class:ScoreProvenance, which already carries kind and
reference_point; the two are validated against each other rather than
duplicating the reference point.
Parameters:
-
parameters(tuple[str, ...]) –Parameter names in score-column order. Names must be non-empty, unique, and at least one must be present.
Examples:
>>> schema = ScoreSchema(("T cells", "B cells", "HSPCs"))
>>> schema.index("HSPCs")
2
>>> schema.select("B cells", "HSPCs")
(1, 2)
ObservationSample
dataclass
¶
A finite weighted observation table requiring a score provider.
IntegrationSource
dataclass
¶
IntegrationSource(bounds: ArrayLike, *, density: Callable[[ArrayLike], ArrayLike], quadrature: GaussLegendreConfig | None = None)
A finite box, density, and deterministic quadrature reference measure.
This source is intentionally limited to low-dimensional bounded domains. The density or intensity is mandatory; bounds alone never imply a uniform statistical measure.
materialize ¶
materialize() -> ObservationSample
Evaluate tensor quadrature nodes and density-weighted measure weights.
GaussLegendreConfig
dataclass
¶
Configure deterministic tensor-product Gauss-Legendre quadrature.
ScoreProvider ¶
Bases: Protocol
The observation-to-score contract every fitting route goes through.
ScoreQuant does not care how a score was obtained -- an analytic derivative, autodiff, a component model, a density-ratio estimator, or an external inference package -- only that observations can be mapped to a finite score matrix and that the mapping says what it is. Those are the two members here, so a caller can supply their own object rather than wrapping it:
.. code-block:: python
class MyExternalScore:
provenance = ScoreProvenance(kind="estimated_ratio")
def score(self, observations):
return my_package.evaluate(observations)
The built-in providers -- :class:ScoreFunction,
:class:LinearComponentScore, :class:DensityRatioScore and
:class:CentralLogRatioScore -- are convenience implementations of this
protocol, not a closed list of what is allowed.
A provider may additionally expose schema, a
:class:~scorequant.ScoreSchema naming its score columns; it is used when
present and is not part of the required contract.
Notes
score takes observations alone. The execution backend is ambient
context established by the public task, not an argument a provider has to
thread through, so an external implementation needs no knowledge of
:class:~scorequant.ExecutionConfig.
provenance
property
¶
provenance: ScoreProvenance
Describe how this score representation was obtained.
score ¶
Map observations with shape [N, D] to scores with shape [N, P].
ScoreFunction
dataclass
¶
ScoreFunction(function: Callable[[ArrayLike], ArrayLike], provenance: ScoreProvenance = ScoreProvenance(), schema: ScoreSchema | None = None)
LinearComponentScore
dataclass
¶
LinearComponentScore(model: LinearComponents, provenance: ScoreProvenance = ScoreProvenance(kind='exact', description='linear-component event score'))
Evaluate a frozen linear-component model and return local scores.
schema
property
¶
schema: ScoreSchema
Name each score column after the component it differentiates.
A linear-intensity model emits one score column per component and the component names are already declared, so the schema is derived rather than asked for.
score ¶
Evaluate components and their frozen reference score.
DensityRatioScore
dataclass
¶
DensityRatioScore(ratio: Callable[[ArrayLike], ArrayLike], parameterization: RatioParameterization, *, provenance: ScoreProvenance | None = None, schema: ScoreSchema | None = None)
Map observations to model density ratios and evaluate declared scores.
The ratio callback is the statistical representation: any oracle for the component density ratios — an analytic formula, a calibrated classifier, a direct ratio estimator such as KLIEP or uLSIF, or an external ratio model — determines the score once a parameterization declares how the components combine. Ratio estimation, calibration, and cross-fitting stay outside the library.
Parameters:
-
ratio(Callable[[ArrayLike], ArrayLike]) –Callable
[N, D] -> [N, K]returning finite nonnegative model density ratios, defined up to one common event-wise factor. -
parameterization(RatioParameterization) –IntensityParameterizationorMixtureParameterizationdeclaring the ratio-to-score map and the reference point. -
provenance(ScoreProvenance | None, default:None) –Optional score provenance. Estimated ratios are the default (
kind="estimated_ratio"); an analytic ratio may declarekind="exact"under the same caller responsibility asScoreFunction. Parameterization facts are always recorded inprovenance.ratioand a conflicting supplied record is rejected.
from_classifier
classmethod
¶
from_classifier(predict: Callable[[ArrayLike], ArrayLike], class_priors: ArrayLike, parameterization: RatioParameterization, *, calibration: str | None = None, description: str | None = None, metadata: Mapping[str, JsonValue] | None = None) -> DensityRatioScore
Build a ratio provider from a calibrated multiclass classifier.
The classifier is one estimator of density ratios: calibrated
posteriors eta_k under training priors pi_k give
r_k = eta_k / pi_k up to a common event-wise factor, so the
scores are (eta_k / pi_k) / sum_j theta_j eta_j / pi_j under the
intensity parameterization. When pi is proportional to
theta_0 the denominator is identically one. The provider always
records estimated provenance — a classifier-derived ratio can never
claim exact Fisher semantics.
Parameters:
-
predict(Callable[[ArrayLike], ArrayLike]) –Callable
[N, D] -> [N, K]returning calibrated posterior rows summing to one. -
class_priors(ArrayLike) –Strictly positive training priors with shape
[K]and unit sum. -
parameterization(RatioParameterization) –Ratio-to-score map;
Kmust match its component count. -
calibration(str | None, default:None) –Optional name of the upstream calibration method, recorded in provenance.
-
description(str | None, default:None) –Optional free-form provenance carried on the score record.
-
metadata(str | None, default:None) –Optional free-form provenance carried on the score record.
score ¶
Evaluate the ratio callback and apply the declared score map.
CentralLogRatioScore
dataclass
¶
CentralLogRatioScore(predict: Callable[[ArrayLike], ArrayLike], deltas: ArrayLike, class_priors: ArrayLike, *, description: str | None = None, metadata: Mapping[str, JsonValue] | None = None, schema: ScoreSchema | None = None)
Estimate central finite-difference scores from paired density ratios.
A calibrated classifier trained to separate samples generated at
theta_0 - delta e_p from theta_0 + delta e_p estimates the
directional log density ratio, and
(log(p_plus / p_minus) - log(pi_plus / pi_minus)) / (2 delta) is a
central finite-difference estimate of the score component s_p. The
prediction callback must return shape [N, P, 2] with class order
(minus, plus); a two-dimensional [N, 2] input is accepted for a
single score direction. Provenance is always estimated.
Parameters:
-
predict(Callable[[ArrayLike], ArrayLike]) –Callable returning calibrated minus/plus probability pairs.
-
deltas(ArrayLike) –Strictly positive finite-difference offsets with shape
[P]. -
class_priors(ArrayLike) –Training priors per direction with shape
[2]or[P, 2]; rows are normalized to sum to one. -
description(str | None, default:None) –Optional free-form provenance carried on the score record.
-
metadata(str | None, default:None) –Optional free-form provenance carried on the score record.
provenance
property
¶
provenance: ScoreProvenance
Return estimated-ratio provenance with the central-difference facts.
score ¶
Apply prior correction and divide central logits by 2 * delta.
ScoreProvenance
dataclass
¶
ScoreProvenance(kind: ScoreKind = 'unknown', description: str | None = None, reference_point: tuple[float, ...] | None = None, metadata: Mapping[str, JsonValue] = dict(), ratio: RatioProvenance | None = None)
Describe where supplied score coordinates came from.
exact_fisher is derived from kind rather than accepted as an
independent flag, so estimated scores cannot accidentally claim exact
Fisher semantics. Scores built from model density ratios additionally
carry a ratio record describing how the ratios were obtained.
RatioProvenance
dataclass
¶
RatioProvenance(estimator: str | None = None, parameterization: RatioParameterizationKind | None = None, coefficients: tuple[float, ...] | None = None, reference_fractions: tuple[float, ...] | None = None, reference_component: int | None = None, training_priors: tuple[float, ...] | tuple[tuple[float, float], ...] | None = None, calibration: str | None = None, deltas: tuple[float, ...] | None = None)
Describe how a model density-ratio representation was obtained.
Together with ScoreProvenance.kind and reference_point, these
fields reconstruct the statistical representation behind a ratio-derived
score: which estimator produced the ratios, under which training priors
and calibration, and through which parameterization they became scores.
Fields that do not apply to a given construction stay None.