# Uncertainties, Biases & Selection

Every observable in Plumb carries an explicit affine forward model from physical truth to recorded numbers:

$$x = \mu + A\epsilon + S u + W \delta$$

- $\mu$ is the central value (after any deterministic `transform`).
- $A\epsilon$ is independent statistical noise (`noise gaussian(...)`).
- $S u$ are **shared Gaussian nuisances** (`nuisance` attached via `shared ... along ...`).
- $W \delta$ are **deterministic bounded systematics** (`bounded` attached inline or via top-level `shared ... along ...`).

## Published centres and fixed covariates

A published centre or event count can be recorded with `value` alone. To score it statistically, declare the applicable uncertainty model. A shared or bounded term can supply the entire declared uncertainty. When a comparison reads a bare empirical centre on either side, including through a derived `value`, Plumb reports `blocked unspecified_uncertainty` and names the source. Adding Gaussian noise downstream leaves that source unresolved. When a definition transforms an observable, pass the observable as an argument, for example `value normalize(reading)`. This carries its uncertainty through the calculation.

When a scalar or vector is a fixed input for a particular test, state the premise at its declaration. For example, a test may use the tabulated ordinates of a published likelihood scan exactly as released.

<!-- plumb:check -->
```plumb
role scan.statistic: Dimensionless
assumption stat.use_printed_grid: StatisticalModel "Use q at the precision tabulated for this grid point."
inference released_ordinate: scan.statistic {
  value 2.71
  noise none assuming stat.use_printed_grid
}
measurement cutoff: scan.statistic {
  value 5.99
  noise published_limit(confidence = 0.95)
}
compare inside: cutoff ~ released_ordinate
  expect compared
  by exclusion_contour
```

The assumption appears in the comparison ledger. A noiseless theoretical prediction can still be written as a `prediction`. For a separate analysis that supplies a distribution for a published centre, declare the centre and its noise together in a new inference, name the model assumption, and record the original summary with `derived from`. This records provenance and leaves the original record available on its own terms.

## Two-sided published intervals

Use `published_interval` when a source supplies both scalar endpoints, the interval level, and its statistical construction. Express the endpoints in the observable's physical dimension and the level as a fraction strictly between zero and one. Give the construction a `StatisticalModel` name. For a confidence interval, describe how the source established coverage. For a credible interval, state its prior and posterior construction. A likelihood-profile quantile can be reported in the source's own terms. A quoted pair of asymmetric errors alone does not specify any of these constructions.

<!-- plumb:check -->
```plumb
role illustration.distance: m
assumption stat.illustrative_posterior: StatisticalModel "Illustrative central 90% credible interval from a posterior with a uniform prior on distance between 0 and 10 m."
inference released_distance: illustration.distance {
  noise published_interval(lower = 2 m, upper = 5 m, level = 0.9) assuming stat.illustrative_posterior
}
theory reference_distance {
  d: m
  predict illustration.distance = d
}
compare upper_endpoint: released_distance ~ reference_distance
  at d = 5 m
  expect compared
  by exclusion_contour
```

A source may also supply a `value` within the interval. Both endpoints are included at their declared precision. The checker compares one scalar prediction with one published set. A bounded shift shared by the endpoints translates the entire interval coherently. Shared shifts on the prediction pool with those on the interval. The receipt records `interval.lower`, `interval.upper`, `interval.level` and the prediction relative to those endpoint shifts. An entire predicted range inside the set gives `compared`, and a disjoint range gives `conflict`. Attainable bounded shifts on both sides of the membership decision give `systematics_limited`. Uncertified numerical overlap gives `unresolved`. Use a separate observation with a source-backed likelihood for Gaussian scoring or joint fits.

## Rule 1: Deterministic Bounds Never Enter Statistical Covariance (`P0312`)

If a systematic error only has a worst-case limit ("this calibration drift is at most $\pm 0.02\text{ mag}$"), it is **not** a Gaussian random variable. Plumb forbids placing a `bounded` symbol inside a `gaussian(...)` covariance (`P0312`).

Instead:
- Use `gaussian_ldlt` when there are no bounded systematics (only statistical noise + shared Gaussian nuisances).
- Use `bounded_gaussian` (or `consistency_graph`) when bounded systematics are present. Plumb evaluates the exact best-case and worst-case $\chi^2$ across the bounded box:
  - If **every** point in the box satisfies the budget -> **`compared`**.
  - If **no** point in the box satisfies the budget -> **`conflict`**.
  - If the box **straddles** the budget (some systematic shifts pass, others fail) -> **`systematics_limited`**, naming the exact `limited_by` systematic(s)!

## Rule 2: Shared biases pool coherently and cancel exactly

Plumb tracks every shared `nuisance` and top-level `bounded` systematic by its **canonical defining symbol** (even across module imports and `as` aliases).

- **When combining two measurements jointly (`compare obs_a, obs_b ~ theory`):**
  Shared Gaussian nuisances add the full rank-1 cross-covariance $\sigma^2 S S^T$ across both blocks (including off-diagonal terms!). Shared bounded systematics share one single $\delta$ coordinate across both observables.
- **When differencing two measurements (`inference diff ... value obs_b - obs_a` or `compare obs_b ~ obs_a`):**
  Their response vectors subtract! If both carry `shared zp_phot along 1` and `shared ceph_metal_sys along 1`, then $1 - 1 = 0$: **both shared systematics cancel completely and exactly**.

This runnable example uses two synthetic Cepheid magnitudes and locally declared biases to demonstrate pooling, exact cancellation and a `systematics_limited` result. The nuisance scales are chosen for the example.

<!-- plumb:check -->
```plumb
assumption calibration.synthetic_photometric_offset: CalibrationAndInstrument "Simulated shared magnitude zero-point."
assumption calibration.synthetic_metallicity_shift: CalibrationAndInstrument "Simulated shared abundance-related magnitude shift."
assumption stat.synthetic_cepheid_scatter: StatisticalModel "Simulated independent Gaussian magnitude errors."

nuisance zp_phot: mag ~ gaussian(sigma = 0.015 mag)
  assuming calibration.synthetic_photometric_offset, stat.synthetic_cepheid_scatter

bounded ceph_metal_sys: abs(delta) <= 0.020 mag
  assuming calibration.synthetic_metallicity_shift

roles ceph {
  anchor_mag: mag
  host_mag: mag
  delta_mag: mag
}

measurement anchor_ceph: ceph.anchor_mag = 12.583 +- 0.01 mag {
  assuming stat.synthetic_cepheid_scatter
  shared zp_phot along 1
  shared ceph_metal_sys along 1
}

measurement host_ceph: ceph.host_mag = 22.583 +- 0.01 mag {
  assuming stat.synthetic_cepheid_scatter
  shared zp_phot along 1
  shared ceph_metal_sys along 1
}

-- Taking the differential magnitude cancels BOTH zp_phot and ceph_metal_sys exactly!
inference delta_ceph: ceph.delta_mag {
  value host_ceph - anchor_ceph
}

theory ceph_model {
  mu_anchor: mag
  mu_host: mag
  M_W: mag
  predict anchor_prediction {
    ceph.anchor_mag = mu_anchor + M_W
  }
  predict ceph.host_mag = mu_host + M_W
  predict ceph.delta_mag = mu_host - mu_anchor
}

-- 1. Coherent pooling: zp_phot pools across both rows, and ceph_metal_sys shares one box coordinate.
compare joint_pooled_passes: anchor_ceph, host_ceph ~ ceph_model
  at mu_anchor = 18.477 mag, mu_host = 28.477 mag, M_W = -5.894 mag
  accept chi2 <= 2
  expect compared
  by bounded_gaussian

-- 2. Exact cancellation: because both shared biases cancelled, plain gaussian_ldlt succeeds!
compare differential_cancels_biases: delta_ceph ~ ceph_model
  at mu_anchor = 18.477 mag, mu_host = 28.477 mag
  accept chi2 <= 1
  expect compared
  by gaussian_ldlt

-- 3. Systematics-limited: shifting M_W by +0.03 mag makes the bounded systematic box straddle chi2 <= 4.
compare joint_systematics_limited: anchor_ceph, host_ceph ~ ceph_model
  at mu_anchor = 18.477 mag, mu_host = 28.477 mag, M_W = -5.864 mag
  accept chi2 <= 4
  expect systematics_limited
  by bounded_gaussian
```

## Rule 3: Never double-count nuisances (`includes` vs `shared`)

Sometimes a published covariance matrix already marginalizes over a calibration nuisance. Declare that on the matrix artifact (and/or inside the JSON matrix's `"includes"` array):

```plumb
artifact cov_with_zp : Matrix from "data/sn.cov_full.json" axes sn_axes includes zp_cal
```

Plumb then enforces two automatic protections:
1. **Same observable (`P0315`):** Declaring `shared zp_cal` on an observable whose covariance already `includes zp_cal` is a compile-time error.
2. **Cross-observable (`UnknownDatasetDependence`):** Combining, stacking, or directly comparing Observable A (whose covariance `includes zp_cal`, hiding its sensitivity vector) with Observable B (which either `shared zp_cal` or also `includes zp_cal`) is refused because the cross-covariance between A and B cannot be reconstructed. To combine them honestly, use statistical-only covariances plus explicit `shared zp_cal along ...` on both!

## Rule 4: Selection stages — Covariate Masks vs Outcome Truncation

Plumb enforces stage ordering and distinguishes two kinds of row selection:

1. **Covariate mask (`select mask covariate <expr>`):** Drops rows based only on independent covariates (e.g., `R > 2 kpc` or `z < 1.5`). Safe for Gaussian likelihoods — unless the mask secretly reads the measured outcome column (directly, through a `def`, or through an aliased table file), in which case Plumb detects the leak and refuses with `UnconsumedBias`!
2. **Outcome truncation (`select truncate observed <expr>`):** Drops rows based on the noisy measured value itself (e.g., Malmquist magnitude cut `x < 24.5 mag`). A plain Gaussian likelihood (`gaussian_ldlt` / `bounded_gaussian`) cannot ignore outcome truncation and refuses with `Blocked(UnconsumedBias)`.

## Correlations between observations

Declare the cross-covariance when comparing two observations from a shared release or posterior.

```plumb
correlated cal_flow: sn_cal, sn_flow cov survey_cov assuming stat.joint_gaussian
```

The checker matches selected rows against the matrix axes by release and row ID. A full covariance must also agree with each observation's own statistical covariance on the rows it covers. The assembled joint statistical covariance must be positive definite. A repeated data row still blocks the comparison.

For two scalars, the covariance may be a quantity in the product of their units. A covariance between a speed per distance and a distance therefore has units of speed. Declare the source and conditioning premises of that covariance with `assuming`.

A linear fit propagates the signed responses to each shared Gaussian nuisance
and bounded systematic into its emitted coordinates. The statistical
covariance stays separate. If the residuals also constrain a systematic, the
receipt lists its symbol in `residual_constrained_systematics`. A joint check
that shares this symbol needs the original observations in one fit.
