Skip to content

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_quantizer takes, carrying its own weights, schema and provenance -- or a raw score array, in which case weights and provenance supply 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 example EfficientScoreBound.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, so init and initializer_restarts still 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.ScoreProvider describes, not a score array or a bare callable, and it is rejected when source is already a :class:~scorequant.ScoreSample.

  • diagnostics (DiagnosticsMode, default: 'endpoints' ) –

    How much of the recorded center history to re-score into trace.train_hard_retention and trace.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 hold nan, so the returned history always stays aligned with trace.steps. This only affects diagnostic reporting; it never changes centers, 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:ScoreSchema naming what each of the P columns differentiates. When present it must have exactly P names, 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.

ObservationSample dataclass

ObservationSample(
    observations: ArrayLike,
    weights: ArrayLike | None = None,
)

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

GaussLegendreConfig(
    order: int = 16, max_points: int = 1000000
)

Configure deterministic tensor-product Gauss-Legendre quadrature.

__post_init__

__post_init__() -> None

Validate quadrature capacity before materialization.

ScoreSchema dataclass

ScoreSchema(parameters: tuple[str, ...])

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)

dimension property

dimension: int

Return the number of score columns this schema describes.

__post_init__

__post_init__() -> None

Validate the name vector independently of any score table.

index

index(name: str) -> int

Return the score column of one named parameter.

Raises:

  • KeyError –

    When the name is not declared, naming the available parameters so a typo is diagnosable without reading the constructor call.

select

select(*names: str) -> tuple[int, ...]

Return the score columns of several named parameters, in the order given.

to_dict

to_dict() -> dict[str, JsonValue]

Return JSON-ready schema state.

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.

exact_fisher property

exact_fisher: bool

Return whether exact-Fisher language is permitted.

to_dict

to_dict() -> dict[str, JsonValue]

Return a JSON-compatible provenance mapping.

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, and the ratio providers in :mod:scorequant.ratios -- 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

score(observations: ArrayLike) -> ArrayLike

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,
)

Wrap an exact or estimated callable [N, D] -> [N, P].

__post_init__

__post_init__() -> None

Reject non-callable providers at construction time.

score

score(
    observations: ArrayLike,
    *,
    execution: ExecutionConfig | None = None,
) -> ndarray

Evaluate and validate a finite score matrix.

LinearComponentScore dataclass

LinearComponentScore(
    components: Mapping[str, ComponentFunction]
    | Sequence[ComponentFunction],
    coefficients: Mapping[str, float] | Sequence[float],
    *,
    variables: Sequence[str] | None = None,
    provenance: ScoreProvenance | None = None,
)

Score observations under a linear-intensity model of named components.

The model is lambda(x; theta) = sum_k theta_k phi_k(x), and its score at the reference coefficients theta_0 is phi_k(x) / lambda(x; theta_0), one column per component. Components and coefficients may be signed and need not be normalized; the reference intensity must be strictly positive at every evaluated row.

Parameters:

  • components (Mapping[str, ComponentFunction] | Sequence[ComponentFunction]) –

    Either an insertion-ordered mapping from names to callables or a sequence of callables. Each callable receives X with shape [N, K] and returns one finite value per row.

  • coefficients (Mapping[str, float] | Sequence[float]) –

    Reference coefficients theta_0: a mapping with exactly the component keys, or a sequence aligned with sequence components.

  • variables (Sequence[str] | None, default: None ) –

    Optional unique physical-variable names used to validate K.

  • provenance (ScoreProvenance | None, default: None ) –

    Score provenance. Exact by default, because the components are the model itself rather than an estimate of it.

Notes

Already evaluated component values are density ratios in the Lebesgue gauge, so scorequant.ratios.IntensityParameterization(coefficients) maps them to the same scores.

Validate and freeze component order, coefficients, and metadata.

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.

evaluate_components

evaluate_components(
    X: ArrayLike,
    *,
    execution: ExecutionConfig | None = None,
) -> ndarray

Evaluate every component function.

Parameters:

  • X (ArrayLike) –

    Finite numeric physical-variable matrix with shape [N, K].

Returns:

  • ndarray –

    Evaluated component matrix with shape [N, M].

score

score(
    observations: ArrayLike,
    *,
    execution: ExecutionConfig | None = None,
) -> ndarray

Evaluate the components and their reference score phi_k / lambda.