Adding a distributional family#

A distributional family is a small adapter between the generic SuperLSS machinery and a family-owned likelihood. The family declares an ordered set of natural parameters, binds the response and resolved weights into an immutable plan, initializes those parameters, and evaluates row likelihood derivatives. The fixed-fit, REML/EFS, inference, and public API layers stay family-neutral.

Do not infer a family’s parameter names or arity from its class suffix. LS and LSS follow established model names, while the ordered family.parameters tuple is the executable contract. The built-ins currently expose:

  • two parameters: GaussianLS, GammaLS, LogNormalLS, NegativeBinomialLS, GeneralizedParetoLSS, LomaxLSS, and LogLogisticLSS;

  • three parameters: TweedieLSS, GeneralizedGammaLSS, TwoPieceLogNormalLSS, and TwoPieceNormalLSS;

  • one per named response component: DirichletLSS, with canonical parameters alpha_0, alpha_1, and so on, and positive log links.

Scalar response shape is the default. A vector family declares a frozen ResponseSpec(shape=(K,), component_names=(...)); shape metadata grants no observation or diagnostic capability by itself. Validate original shape, labels and index before positive-weight selection; validate retained raw values in the family before generic float64 conversion. This preserves exact counts, composition policy and original-row provenance. A vector default prediction declares its component columns explicitly. Dirichlet’s joint density has a zero carrier and supplied-share identity, with normalized log shares prepared once per immutable plan. Runtime arithmetic remains portable float64.

Responsibility map#

Internal declared scalar families#

Lomax and log-logistic share families/_declared.py; existing families need not migrate. To add an internal law:

  1. Add a natural-coordinate Declaration to tools/generate_severity_families.py, reusing its stable primitives. Run uv run python tools/generate_severity_families.py and commit the generated module. --check must then pass. Weibull and Burr declarations remain test fixtures, not public families.

  2. Put support/limit paths, window admission and prediction numerics in a small kernels/<law>.py wrapper. It exposes PARAMETERS, COORDINATES, density_jets, a separately multiplied carrier, and the operations the family actually offers. Generated jets are natural derivatives; core orders are exactly integer 0–2, higher packed jets are separate. Unrequested levels must not be allocated or evaluated.

  3. Define a frozen DeclaredScalarSpec constant with a versioned law key, kernel module string, parameter metadata, response support and capabilities. A named top-level dataclass selects explicit mixins and its own initializer. The adapter validates coordinates, parameter order and core capabilities. It freezes response/carrier/observation identity and weights, including after slicing and pickle restoration. No dynamic registry or pickled closure defines the law. Audited reuse registration is for the exact concrete class; subclasses and arbitrary custom links do not inherit it. Carriers are stored with a diagnostic digest. If the spec supplies justified carrier_rounding_parameters=(error_units, beta), replay uses the existing CarrierRounding sum bound instead of hashing transcendental results into semantic identity. Lomax’s carrier is exactly zero; log-logistic’s is -mass*log(y). Without an explicit certificate, exact carrier identity is retained. No legacy identifier tag is needed for these new plans.

  4. Prove row laws and packed mixed derivatives with independently written high-precision references; prove carrier/window frequency accounting, domain refusals, complete fits and fresh-process serialization. Runtime imports may not require SymPy, mpmath, the generator or research modules. Register exact import edges in the architecture test and generated kernels in warmup.

The first pilots admit derivative parameters in [2^-200, 2^200], keeping fourth powers and reciprocals normal. This is a numerical evaluation envelope, not a fitted shape wall. Range-invalid evaluations remain distinguishable from mathematically divergent moments. Ordinary positive-response jets use generated Numba kernels; no unimplemented array fallback is advertised.

Lomax windows reuse log-tail differences and narrow-window quadrature. Its response-coordinate integration retains the finite zero limit and avoids the known extreme fourth log-CDF instability. Its higher directional methods decline quadrature windows with UnsupportedLikelihoodContractError; a real-arithmetic density remainder is not a certificate for rounded nodes or mixed derivatives. Independent adjacent-response tests check its core channels at rounding scale.

Log-logistic finite positive windows use the exact identity log P = -softplus(-z_hi) - softplus(z_lo) + log(-expm1(-d)), where z_i = shape*log(endpoint_i/scale) and d = shape*log(hi/lo) are formed from centered log ratios. The first four derivatives are evaluated from endpoint logistic derivatives, with a centered tanh expression for the scale score. This avoids both rounded tail differences and unrepresentable interior quadrature nodes. All mixed natural and log-coordinate channels have independent high-precision checks.

There is a separate small-shape restriction for finite positive log-logistic windows. Set r = shape*max(1, abs(log(lo/scale)), abs(log(hi/scale))). Core window derivatives are declined when r < 2^-8; analytic third/fourth directions require r >= 1/8. Density and window pure shape derivatives share terms of order shape^-j; subtracting them for a truncated likelihood can lose the conditional remainder, with rounding amplification of order u/r^j. The restriction prevents finite but wrong normalized derivatives, while order-zero probabilities and likelihoods remain available. It does not clip the shape or require finite moments. Ordinary closed-form directions compose through the existing link helpers; unavailable higher directions retain the existing finite-difference route and its evidence.

Both named families declare scale recession through CensoredSeparationFamily. Their strict monotone likelihood ratios in scale survive fixed truncation, so one-sided censored intercepts and categorical levels use the existing separation="warn", "error", or "ignore" policy. The scan owns actual-link admission. No general shape-recession or arbitrary custom-link claim is made.

The laws follow the SciPy Lomax definition and Fisk definition, with location fixed at zero. SciPy is an independent test reference, not a runtime fitting wrapper. The runtime dependency floor remains SciPy 1.15.

Location

Responsibility

src/superglm/distributional/family.py

Own the shared structural protocols, parameter and observation metadata, initialization/evaluation records, and family-neutral validation. It does not own a particular distribution’s formulas.

src/superglm/distributional/weights.py

Resolve and certify prior or frequency weights, their provenance, retained rows, and slicing identity. A family consumes ResolvedLikelihoodWeights; it does not reinterpret raw weights.

src/superglm/distributional/families/<name>.py

Own the family adapter: parameter metadata, observation admission, the bound likelihood plan, initialization, to_config(), translation to and from a numerical kernel, and any optional structural protocols the family can support.

src/superglm/distributional/kernels/<name>.py (optional)

Own primitive row numerics, local numerical-domain checks, a local weight-semantics type, and an immutable kernel result. It imports no distributional contract or aggregate namespace; a dedicated sibling numerical backend is the only permitted package-internal dependency.

src/superglm/distributional/serialization.py

Own the pickler that lets a fitted SuperLSS pass through pickle and joblib. It registers no family: any family that pickles saves.

tests/

Prove the family law against independent row and derivative oracles, weight identities, initialization and refusal boundaries, packed-channel order, public fitting, optional behavior, pickle round trips, and import boundaries.

Solver-facing adapter contract#

The four-method DistributionalFamily interface is the solver-facing adapter contract. Its current public signature is:

from typing import Protocol, runtime_checkable

from numpy.typing import NDArray

from superglm.distributional import (
    FamilyLikelihoodPlan,
    InitialParameterState,
    NaturalLikelihoodEvaluation,
    ObservationContract,
    ParameterSpec,
    ResolvedLikelihoodWeights,
)


@runtime_checkable
class DistributionalFamily(Protocol):
    @property
    def parameters(self) -> tuple[ParameterSpec, ...]: ...

    def bind_likelihood(
        self,
        y: NDArray,
        weights: ResolvedLikelihoodWeights,
        observation: ObservationContract,
    ) -> FamilyLikelihoodPlan: ...

    def initialize(
        self,
        y: NDArray,
        plan: FamilyLikelihoodPlan,
    ) -> InitialParameterState: ...

    def evaluate_natural(
        self,
        y: NDArray,
        theta: NDArray,
        plan: FamilyLikelihoodPlan,
        *,
        derivative_order: int = 2,
    ) -> NaturalLikelihoodEvaluation: ...

parameters fixes the natural-parameter order used by predictors, scores, and curvature channels. bind_likelihood() owns the resolved weights in a plan; take() on that plan must preserve their certified row identity. initialize() returns a finite n × k natural-parameter matrix. evaluate_natural() returns weighted row likelihood values and exactly the requested derivatives. A derivative order of zero has neither score nor Hessian, order one has a score but no Hessian, and order two has both. Values other than an integer from zero through two, including booleans, are refused. Wherever order two is valid, order zero must also be valid and return the same optimizing likelihood values and carrier terms. Dense backtracking can use order zero to reject a trial cheaply; it rechecks acceptance with order two before retaining a point.

For k parameters, hessian_packed has width k * (k + 1) // 2. It is the raw signed Hessian of the weighted per-row optimizing log likelihood, in canonical upper-triangular order:

(0, 0), (0, 1), ..., (0, k - 1), (1, 1), ..., (k - 1, k - 1)

It is not negated curvature or Fisher information. For four parameters the ten channels are (a,a), (a,b), (a,c), (a,d), (b,b), (b,c), (b,d), (c,c), (c,d), (d,d), so the diagonal indices are (0, 4, 7, 9).

Complete-fit configuration#

Complete fitting has a separate structural metadata requirement:

from collections.abc import Mapping
from typing import Protocol, runtime_checkable


@runtime_checkable
class ConfigurableDistributionalFamily(Protocol):
    def to_config(self) -> Mapping[str, object]: ...

to_config() must return a nonempty mapping whose keys are nonempty strings. The mapping should completely identify configuration that can change the family’s fitted law. Current null fitting deep-copies and snapshots this mapping as read-only fit metadata, so later caller mutation cannot rewrite the accepted state. Consequently, ConfigurableDistributionalFamily metadata is required for a complete fit.

Optional structural protocols#

Optional behavior is detected structurally with the public runtime-checkable protocols below. Do not add family-name branches to a solver or facade.

Protocol

Member and responsibility

Behavior when absent

LikelihoodPlanValidatingFamily

validate_likelihood_plan(y, plan) performs one-shot family-owned plan validation and returns the canonical, finite, exact-shape, read-only float64 response.

Fixed fitting validates the plan’s structural invariants and freezes the supplied finite response itself.

ExpectedInformationFamily

expected_information_natural(theta, plan) returns natural-scale Fisher information. The solver adds the penalty for fallback when the terminal penalized observed Hessian is materially indefinite; coefficient_curvature="fisher" on SuperLSS requests Fisher scoring for the whole solve.

The default coefficient solve is the same: Newton on the observed Hessian. coefficient_curvature="fisher" on SuperLSS refuses at construction and a route explicitly requesting Fisher chunking refuses. Repeated material indefiniteness of the terminal penalized observed Hessian does not refuse the fit: the solver uses the nearest positive semidefinite curvature, warns, and records the warning in result_.warnings.

PredictorCurvatureDirectionalFamily

predictor_curvature_directional_derivative(y, eta, eta_direction, links, plan) supplies the exact directional derivative of curvature_packed (the negated predictor-scale Hessian, packed upper-triangular) along eta_direction.

The engine differences the family’s own order-two evaluation along the unit direction (Richardson order four, link-scale step 1e-3) and carries an error certificate into the endpoint decision band; the evidence is labelled finite-difference-curvature-direction/v1. Implement the analytic method only when you need matched_certified.

PredictorCurvatureSecondDirectionalFamily

predictor_curvature_second_directional_derivative(y, eta, a, b, links, plan) supplies the second directional derivative of curvature_packed along a then b, the row’s fourth derivatives in the predictors contracted with both; a and b may be stacked (m, n, K) pairs that share one evaluation. families._base.natural_curvature_second_direction composes natural fourth derivatives with the links (each link needs deriv4_inverse). A family that bounds a series instead of closing a form, or whose curvature jumps close to a row (the two-piece join), also implements certified_predictor_curvature_second_directional_derivative, returning a certificate beside the values; it takes the engine’s derivative step as a keyword, the reach a near-kink certificate uses, which a series bound ignores.

The LAML Hessian takes second differences of the family’s order-two evaluation along every axis pair (1 + 4K + 4K(K-1)/2 evaluations, fewer when the gradient pass’s stencils are reused) and carries their certificate.

DefaultPredictionFamily

default_prediction_name names the response quantity and default_prediction(theta) computes it.

predict_parameters() remains available; predict() raises NotImplementedError and tells the caller to use predict_parameters().

DistributionFunctionFamily

cdf(y, theta) and quantile(p, theta) row-wise from natural parameters; backs predict_cdf() / predict_quantile().

Both facade methods raise NotImplementedError naming predict_parameters().

FitFailureDiagnosingFamily

diagnose_repeated_curvature_failure(y, weights) returns a family-specific exception that explains why the terminal curvature fell back, or None. A fit never raises it: when the final curvature fell back, the fit finishes and appends the exception’s text to result_.warnings. A family that gains ExpectedInformationFamily also sets the class attribute diagnoses_any_curvature_fallback = True (as NegativeBinomialLS does) when every fallback of it used to refuse; the fit then discloses a Fisher fallback whether or not the diagnosis fires, where the default is to accept a Fisher fallback silently. A nearest-semidefinite fallback is always disclosed.

No family-specific text is added. A missing, failing, or non-exception diagnosis never fails the fit.

LimitRowDisclosingFamily

limit_row_count(theta, plan) returns the index of a parameter and the number of rows the family’s kernel treats as at that parameter’s limit, where it has no expected information; limit_row_disclosure(n_limit, n_rows, constant_offered, offset_varies) returns the warning text. A fit calls them after the final solve, and appends the text to result_.warnings when rows are at the limit and the fit’s own terminal rank decision leaves a coefficient of that parameter not estimable (within the retained face when REML removed a term through an exact face). The fit does not ask whether the limit rows cause that null direction, so a block singular by construction (nested factors, or a level term beside its own factor smooth) is disclosed whenever any row is at the limit. constant_offered is true when a constant parameter is offered as a remedy: the predictor has terms to drop, and either its intercept carries terminal data curvature or, with no intercept, some row is off the limit (an unchecked offer, since the fit holds no curvature for a constant it never estimated); offset_varies is true when its offset differs across rows. NegativeBinomialLS implements it for the size, for the exact class only: a derived class may change the likelihood, so it reports no rows and no text.

No limit-row text is added. A hook that raises never fails the fit.

PriorWeightedDistributionFunctionFamily

cdf_prior_weighted(y, theta, weights) and quantile_prior_weighted(p, theta, weights) give the row law when a prior weight is part of it — the Gaussian variance sigma^2 / w, the gamma shape and scale, the Tweedie dispersion phi / w.

Every caller that needs a row law under non-unit prior weights refuses and names the family, rather than quietly reading the unit-weight distribution function. Residuals, calibration, predictive draws and posterior bounds are all affected; unit prior weights and frequency semantics are unaffected.

ExpectedShortfallFamily

expected_shortfall(p, theta) gives the certified row-wise upper conditional tail mean for an interior probability. This is independent of distribution-function support: generic quantile quadrature is not a certified tail mean.

The named ("expected_shortfall", p) posterior quantity refuses and asks for this protocol.

PriorWeightedExpectedShortfallFamily

expected_shortfall_prior_weighted(p, theta, weights) gives the same tail mean when a non-unit prior weight changes the row law.

Non-unit prior-weighted expected shortfall refuses rather than substituting the unit law. Unit weights take the unweighted path exactly.

AtomFamily

cdf_left_limit(y, theta, weights=None) gives P(Y < y), which is the bottom of the jump at a point mass.

The probability-integral transform is read as continuous. For a family with an atom that silently makes the transform non-uniform on the atom’s rows, so a family with a point mass must implement it.

VarianceFamily

variance(theta) gives Var(Y | theta) in closed form at unit prior weight.

The actual-versus-expected table simulates the variance from plug-in predictive draws instead and records variance_law as "draws".

PriorWeightedVarianceFamily

variance_prior_weighted(theta, weights) gives the same second moment when a prior weight is inside the row’s law.

The table falls back to simulation on the weighted law where the family has one ("prior_weighted_draws"), and only then to the unit-weight variance ("family_unit_law"), which ignores the weight and says so.

Implementing ExpectedInformationFamily does not change how a family is fitted by default; it adds the indefiniteness fallback and the opt-in Fisher scoring request.

Unit-law and prior-weighted capabilities are separate on purpose. LogNormalLS, for example, is not reproductive and refuses non-unit prior weights, but still implements its unit-law distribution function, variance and expected shortfall. GaussianLS, GammaLS and TweedieLSS implement both the unit and prior-weighted distribution-function and variance protocols.

Expected-shortfall support is narrower and always family-owned through ExpectedShortfallFamily. Its certified unit-law implementations are GaussianLS, GammaLS, LogNormalLS, GeneralizedGammaLSS, GeneralizedParetoLSS and LomaxLSS; only Gaussian and gamma also implement PriorWeightedExpectedShortfallFamily. TweedieLSS, both two-piece families, NegativeBinomialLS and LogLogisticLSS refuse expected shortfall. Protocol membership states structural availability, not that every representable tail can be resolved: Gamma, log-normal and generalized-gamma rows refuse when their float64 tail certificate fails. Generalized-gamma location form returns +∞ when the upper first moment does not exist; mean form rejects that cell because a finite mean parameter would be outside its model. Named posterior intervals refuse a non-finite plug-in value or any non-finite posterior draw instead of reducing such values into an interval.

CDF query support is distinct from response admission. The positive continuous families return zero for every finite threshold y ≤ 0, including mixed inside/outside vector calls, while bind_likelihood() keeps enforcing the family’s declared response support. Tweedie’s value at zero is instead its atom. A runtime-checkable protocol checks every member it declares, so folding a weighted method into its unit-law protocol would silently remove the unit capability from a non-reproductive family.

The generic score layer follows the resolved weight contract. Prior semantics changes the row law and aggregates over retained physical rows. Frequency semantics uses the unit law and literal replication mass for CRPS, threshold-weighted CRPS, Murphy curves, paired standard errors and default thresholds as well as log score. Zero-weight rows are omitted, and a comparison with mixed semantics refuses whenever any retained weight is not exactly one.

Families with response-owning plans implement LikelihoodPlanValidatingFamily and return the plan’s canonical read-only response after checking the supplied response. This includes Gamma, NB, the positive continuous adapters, the two-piece families and Dirichlet. Tweedie’s bounded plan also owns its original response; its complete plan and Gaussian retain their generic response snapshot. Never replace a censored limit in stored response identity with an internal density placeholder. Plan admission is structural rather than exact-lineage based: subclasses of every plan are admitted when their field invariants hold.

PredictorCurvatureDirectionalFamily has a smoothness precondition that no amount of algebra removes: the row log-likelihood must be C³ in every natural parameter over the whole support the links can reach, because the hook is the third derivative contracted with a predictor direction. The Gaussian, gamma, negative-binomial, Tweedie, log-normal, generalized gamma and generalized Pareto laws qualify. The two-piece laws do not: their curvature jumps at the mode, so the true LAML gradient carries the density at the kink times that jump, which a pointwise third derivative drops. For such a family the differenced route with its certificate is the correct method and the hook must not be implemented. The derivative orders each stage of the fit needs, and which family supplies which, are tabulated in Derivative orders, and which families supply them.

Primitive kernel rule#

A family whose formulas merit a separate numerical module uses a primitive kernel shaped like this:

from dataclasses import dataclass
from typing import Literal

import numpy as np
from numpy.typing import NDArray

WeightSemantics = Literal["prior", "frequency"]


@dataclass(frozen=True)
class ExampleKernelEvaluation:
    optimizing_log_likelihood: NDArray[np.float64]
    score: NDArray[np.float64] | None
    hessian_packed: NDArray[np.float64] | None
    valid: NDArray[np.bool_]


def evaluate_example_rows(
    response: NDArray,
    first_parameter: NDArray,
    second_parameter: NDArray,
    weights: NDArray,
    semantics: WeightSemantics,
    *,
    derivative_order: int,
) -> ExampleKernelEvaluation:
    ...

WeightSemantics is local to the kernel. The result type is also kernel-owned and must own read-only output arrays. The primitive module imports numerical libraries and standard-library types, but no distributional contract, family adapter, or aggregate namespace. A dedicated sibling numerical backend is the only exception. Its family adapter passes primitive arrays and the resolved semantics directly to this numerical owner, then constructs the public NaturalLikelihoodEvaluation. Application and extension code should use the public family contracts, not import private kernel modules.

Worked four-parameter family#

This complete public-only example is the extensibility regression. It supplies four natural parameters and therefore ten packed Hessian channels, explicitly admits only the complete observation contract, and provides nonempty complete-fit configuration. A family that also takes truncated and censored rows does the following; GaussianLS is the reference.

  • It declares FamilyCapabilities(censored_response=True) and binds the "censored_truncated" contract, whose bounds are ResponseBounds.

  • It validates every original window before clipping it to support. For a continuous law, lower bounds at or below support are ineffective; an atom requires bind_observation(..., atom_at_lower=True), so equality excludes the atom and only strictly lower endpoints are ineffective. NB additionally owns its count-lattice intersection and preserves an explicitly supplied bounded plan’s finite-NB policy in its identity. The other scalar adapters reduce contracts with no effective bounded row to complete. Thus truncation=(0, None) is ineffective for a positive continuous law but excludes zero for NB and Tweedie.

  • It separates finite censor thresholds from exact-density support using validated_observation_response, passing the boolean bounds.side != 0 and original input positions. Exact values reach the family’s original validator before conversion. Density evaluation and initialization may use harmless private representatives; observation windows, carriers and plan identity retain the original thresholds. Right limits at/below continuous support can be valid; impossible left events still fail.

  • Its plan exposes the bound contract as plan.observation, and its plan identifier includes the bounds. The diagnostics, the corrected covariance and the solver’s curvature choice read plan.observation, and a fit with bounds refuses a plan without it.

  • It refuses complete-row expected information on a bounded plan with UnsupportedLikelihoodContractError. Analytic third/fourth directions need separate bounded-law evidence; NB, Tweedie and both two-piece adapters explicitly refuse them. The older continuous adapters supply admitted directions, with the numerical restrictions described above. A refusal preserves the existing finite-difference smoothing fallback.

  • It supplies log_window_probability(lower, upper, theta, weights=None) (ResponseWindowFamily), built from log tails rather than a difference of CDF values. Window capability is distinct from CDF/quantile capability: bounded NB fitting/log scoring does not enable quantile diagnostics, and bounded Tweedie atom residuals remain unsupported.

  • It may declare censored_recession(bounds) (CensoredSeparationFamily): one flag per row and predictor, true where that censored row’s bound probability nears its supremum only as the predictor walks off one way. A level whose rows are all censored on one side and all flagged is reported; a family that declares nothing is not scanned. A flag that is monotone in its parameter is read on the parameter’s default link and on links that map the line one-to-one onto an open interval (identity, log, logit, probit, cloglog, cauchit); a link such as sqrt reaches an end of its range at a finite coefficient and is not read. A parameter whose flags are not monotone, such as the normal scale, where P(Y > c | Y > a) nears 1 both as the scale grows and as it shrinks with the location above c, is named in the class attribute censored_recession_link_sensitive, a tuple of parameter names; its flags are then read only on the parameter’s default link, since a bounded link such as a logit can stop short of the limit and leave the level a finite estimate.

Every built-in scalar adapter now supplies actual core orders 0–2 for these observations. tests/test_all_scalar_observations.py tests each family and both log-normal/two-piece-log-normal forms against independent normalized laws, including linked Hessians, literal frequency replication, prior-law weights, atoms, count-rate endpoints and plan takes. A capability flag or a numerical refusal does not satisfy an ordinary-domain matrix cell.

New bounded NB/Tweedie/two-piece plans store complete normalized values with zero carriers. For stable normalized overrides, bounded_channels requires an explicit zero carrier and excludes selected rows from its ordinary numerator/denominator route. The callback supplies unit-frequency jets; the helper multiplies once. Identical events are algebraic zero, and strongly conditioned laws may need shared anchors to avoid subtracting large common density/carrier terms. Shared weight takes require unique indices; replication uses frequency weights or a newly bound replicated sample.

Unresolved requested channels become invalid trial rows with finite placeholders, allowing ordinary backtracking and convergence disclosure. Public probability queries raise a useful numerical error. Keep numerical work/range restrictions separate from mathematical support and from empty events. No high-precision or symbolic dependency belongs on the runtime path. Register new compiled primitive callers with the generator; classify every dispatcher in the warmup census. NB/beta core entry points and the Python-called gamma operand routes used by Tweedie are warmed at orders 0–2, while optional third/fourth and uncommon endpoint fallbacks retain first-use compilation.

from dataclasses import dataclass

import numpy as np
import pandas as pd

from superglm import SuperLSS, bind_predictor
from superglm.distributional import (
    COMPLETE_OBSERVATION,
    FamilyLikelihoodPlan,
    InitialParameterState,
    NaturalLikelihoodEvaluation,
    ObservationContract,
    ParameterSpec,
    ParameterSupport,
    ResolvedLikelihoodWeights,
    UnsupportedLikelihoodContractError,
)
from superglm.links import IdentityLink


def parameter(name: str) -> ParameterSpec:
    return ParameterSpec(
        name=name,
        default_link=IdentityLink(),
        role=name,
        support=ParameterSupport(),
        curvature="observed",
    )


@dataclass(frozen=True)
class FourParameterPlan:
    weights: ResolvedLikelihoodWeights

    @property
    def plan_identifier(self) -> str:
        return f"four-parameter/v1:{self.weights.digest}"

    def take(self, indices: np.ndarray) -> "FourParameterPlan":
        return FourParameterPlan(self.weights.take(indices))


@dataclass(frozen=True)
class FourParameterFamily:
    parameters = tuple(parameter(name) for name in ("a", "b", "c", "d"))

    def to_config(self) -> dict[str, object]:
        return {"type": "FourParameterFamily", "parameters": 4}

    @staticmethod
    def targets(y: np.ndarray) -> np.ndarray:
        return np.column_stack(
            (
                y,
                np.full(len(y), 0.25),
                np.full(len(y), -0.5),
                np.full(len(y), 1.0),
            )
        )

    def bind_likelihood(
        self,
        y: np.ndarray,
        weights: ResolvedLikelihoodWeights,
        observation: ObservationContract,
    ) -> FourParameterPlan:
        response = np.asarray(y, dtype=np.float64)
        if observation != COMPLETE_OBSERVATION:
            raise UnsupportedLikelihoodContractError("complete observations are required")
        if response.shape != weights.values.shape or not np.all(np.isfinite(response)):
            raise ValueError("response and resolved weights must contain the same finite rows")
        return FourParameterPlan(weights)

    def initialize(
        self,
        y: np.ndarray,
        plan: FamilyLikelihoodPlan,
    ) -> InitialParameterState:
        if not isinstance(plan, FourParameterPlan):
            raise TypeError("FourParameterFamily requires FourParameterPlan")
        return InitialParameterState(self.targets(np.asarray(y, dtype=np.float64)))

    def evaluate_natural(
        self,
        y: np.ndarray,
        theta: np.ndarray,
        plan: FamilyLikelihoodPlan,
        *,
        derivative_order: int = 2,
    ) -> NaturalLikelihoodEvaluation:
        if not isinstance(plan, FourParameterPlan):
            raise TypeError("FourParameterFamily requires FourParameterPlan")
        if (
            isinstance(derivative_order, bool | np.bool_)
            or not isinstance(derivative_order, int | np.integer)
            or int(derivative_order) not in (0, 1, 2)
        ):
            raise ValueError("derivative_order must be an integer from zero through two")
        order = int(derivative_order)
        targets = self.targets(np.asarray(y, dtype=np.float64))
        residual = targets - np.asarray(theta, dtype=np.float64)
        weights = plan.weights.values
        score = None if order == 0 else weights[:, None] * residual
        hessian = None
        if order == 2:
            hessian = np.zeros((len(targets), 10), dtype=np.float64)
            hessian[:, (0, 4, 7, 9)] = -weights[:, None]
        return NaturalLikelihoodEvaluation(
            optimizing_log_likelihood=-0.5 * weights * np.sum(residual * residual, axis=1),
            parameter_independent_carrier=np.zeros(len(targets)),
            score=score,
            hessian_packed=hessian,
            valid=np.ones(len(targets), dtype=bool),
        )


frame = pd.DataFrame({"row": np.linspace(-1.0, 1.0, 12)})
response = np.linspace(-0.8, 1.2, len(frame))
family = FourParameterFamily()
model = SuperLSS(
    family,
    *(bind_predictor(family, name) for name in ("a", "b", "c", "d")),
).fit(frame, response, lambdas={})
parameters = model.predict_parameters(frame)

The nonempty to_config() metadata is load-bearing: this family needs it to complete null fitting. It can nevertheless complete the public fixed fit and call predict_parameters() without implementing DefaultPredictionFamily. model.predict(frame) produces the actionable default-prediction refusal and directs callers to predict_parameters().

Replaying the likelihood plan#

The corrected covariance rebinds the plan from the retained response and weights and compares plan_identifier with the one the fit recorded, so the identifier hashes only inputs stored exactly: tags, the weight digest and, where the plan keeps one, the response digest. A carrier the plan computes with log or gammaln rounds differently on other CPUs and C libraries, so it stays out of the identifier. A plan with such a carrier implements carrier_rounding(), returning a superglm.distributional.likelihood_identity.CarrierRounding, and the replay checks the carrier’s sum against the fit’s within the bound derived in that module. A new family’s plan leaves out legacy_identifier_tag, or sets it to None. A built-in family whose earlier identifiers hashed the carrier names their tag in that plan attribute, such as GammaLS/v1, so those identifiers are matched by tag and carrier sum. The tag is a plain attribute, not a CarrierRounding field, so a fit can check it without building the carrier: a fit refuses a plan whose legacy tag is the tag of its own identifiers, because the replay would then accept any identifier under that tag.

Evidence checklist#

Before proposing a package-provided family, record all applicable evidence:

  • [ ] Configuration admission rejects a missing or non-callable to_config(), an empty/non-mapping result, and non-string or empty keys; snapshot tests prove caller mutation cannot change accepted metadata.

  • [ ] An independent row likelihood and derivative oracle covers ordinary and adversarial natural-parameter points without reusing production formulas.

  • [ ] Derivative-order laziness proves order zero omits score and Hessian, order one omits Hessian, order two supplies both, and invalid orders refuse.

  • [ ] Prior/frequency identities prove the documented prior-weight law and literal frequency-row replication, including every response carrier and the score, comparison, standard-error and default-threshold reductions that read those semantics; zero rows and mixed-semantics refusals are covered.

  • [ ] Initialization/refusal tests prove finite supported starts and named, deterministic domain refusals rather than silent clipping or fallback.

  • [ ] Packed width is exactly k * (k + 1) // 2, with every score and Hessian channel checked in canonical upper-triangular order.

  • [ ] A public fixed fit through SuperLSS proves predictor ordering, parameter prediction, and generic curvature-channel telemetry without an engine family branch.

  • [ ] Optional protocols are tested both when present and absent, including default prediction, distribution functions, expected shortfall and its prior-weighted variant, plan validation, Fisher information, directional curvature, and failure diagnosis.

  • [ ] Positive continuous CDF tests distinguish a finite outside-support query (y ≤ 0 gives zero) from likelihood response admission, and atom families retain their jump at zero.

  • [ ] AST import checks keep public integration tests on documented namespaces and keep primitive kernels free of reverse distributional imports.

  • [ ] Ruff check and format checks pass for production and test code.

  • [ ] Focused family, kernel, public API, and pickle round-trip tests pass before any broader suite is used as integration evidence.

Change checklist#

For a normal package-provided family, production changes are limited to the family adapter with to_config(), an optional primitive kernel and its public export. External structural families need no production registration merely to fit.

Keep each added or materially changed function within the ordinary ≤60-line target. Give one lifecycle per class. Do not introduce nested callback choreography or a one-line forwarding ladder. Permit at most two pass-through hops carrying substantially the same arguments, and have the family adapter call its numerical owner directly.

Edits to fixed fitting, REML/EFS, inference, diagnostics, or API admission in order to add a family indicate a boundary failure. Stop and request design review instead of teaching those generic layers the new family’s name.