diff --git a/README.md b/README.md index 8b0cc96..fe98f5a 100644 --- a/README.md +++ b/README.md @@ -15,9 +15,10 @@ weighted values. Weighted variance requires choosing between treating weights as frequencies or as precision. A top-1% share requires deciding what happens to a record that straddles the cutoff. Each of these is a decision, and hand-rolling it per analysis means making it differently each time. `microdf` makes each choice -once, documents it, and tests it — quantiles follow the inverse CDF so they can be -checked against R's `survey::svyquantile`, and variance treats weights as -frequencies so integer weights agree with `numpy` on the replicated sample. +once, documents it, and tests it — quantiles use the lower-endpoint inverse CDF +convention of R's `survey::svyquantile` with `qrule = "math"` (the default since +survey 4.1), and variance treats weights as frequencies so integer weights +agree with `numpy` on the replicated sample. **Weights have to survive the pipeline.** Before any estimator runs, weights must stay aligned with their rows through merges, filters, grouping and reindexing. When diff --git a/microdf/microseries.py b/microdf/microseries.py index 36ece1d..dc18129 100644 --- a/microdf/microseries.py +++ b/microdf/microseries.py @@ -625,9 +625,10 @@ def corr( def quantile(self, q: np.ndarray, skipna: bool = True) -> pd.Series: """Calculates weighted quantiles of the MicroSeries. - Uses the inverse CDF method: the q-th quantile is the smallest - value where the cumulative weight proportion >= q. This matches - the default behavior of R's survey::svyquantile. + The inverse CDF returns the smallest value whose cumulative share + of positive weight reaches q. This is the lower-endpoint convention + of R's survey::svyquantile with qrule="math", the default since + survey 4.1. Floating-point accumulation can affect boundary values. :param q: Quantile(s) to calculate, must be in [0, 1]. :type q: float or np.ndarray @@ -715,13 +716,13 @@ def replicate_standard_error( The factor and centering convention must match the survey design. Supported schemes use a common factor: jackknife covers unstratified - JK1 or common-factor delete-group replication, not arbitrary stratified - jackknife. Averaged bootstrap requiring additional factors is not - supported. See :func:`microdf.replication.replicate_variance` for factors. + JK1 without a finite population correction and delete-group replication + using the same factor. See + :func:`microdf.replication.replicate_variance` for factors. - Changing main weights without corresponding design-consistent replicate - adjustments invalidates the original replicates. Calibration can be - valid when repeated appropriately for every replicate. + Changing main weights alone can invalidate the original replicates. + Apply design-consistent adjustments to both sets of weights when + needed. For calibration, repeat the procedure for each replicate. :param statistic: Callable taking a MicroSeries and returning a float, e.g. ``lambda s: s.median()``. diff --git a/microdf/replication.py b/microdf/replication.py index a8923dc..c0b8925 100644 --- a/microdf/replication.py +++ b/microdf/replication.py @@ -13,10 +13,9 @@ schemes, not arbitrary stratified jackknife or averaged-bootstrap designs that require additional or replicate-specific factors. -Changing the main weights without corresponding design-consistent adjustments -to the replicate weights invalidates the original replicates. Calibration can -be valid when the required calibration is repeated appropriately for every -replicate. +Changing the main weights alone can invalidate the original replicates. Apply +design-consistent adjustments to both sets of weights when needed. For +calibration, repeat the calibration procedure for each replicate. """ from __future__ import annotations @@ -29,13 +28,13 @@ # Scale applied to the sum of squared deviations from the selected center. # R is the number of replicates. METHOD_FACTORS = { - # Unstratified JK1 / common-factor delete-group jackknife: (R - 1) / R. + # Unstratified JK1 without an FPC and compatible delete-group jackknife. "jackknife": lambda r: (r - 1) / r, # Balanced repeated replication: 1 / R. "brr": lambda r: 1 / r, - # Bootstrap replicates: 1 / R. - "bootstrap": lambda r: 1 / r, - # Successive difference replication, as used for the ACS and CPS: 4 / R. + # Standard scale for supplied, non-averaged bootstrap weights: 1 / (R - 1). + "bootstrap": lambda r: 1 / (r - 1), + # ACS successive difference replication and CPS ASEC both use 4 / R. "successive-difference": lambda r: 4 / r, } @@ -60,15 +59,18 @@ def replicate_variance( Variance is the method's scale factor times the sum of squared deviations of replicate estimates from the selected center. The supported factors - are ``(R - 1) / R`` for unstratified JK1 or common-factor delete-group - jackknife, ``1 / R`` for BRR and bootstrap, ``4 / R`` for successive - difference, and ``1 / (R * (1 - fay_k)**2)`` for Fay's BRR. Select the - factor and center specified by the survey; arbitrary stratified jackknife - and averaged-bootstrap schemes requiring other factors are unsupported. + are ``(R - 1) / R`` for unstratified JK1 without a finite population + correction or delete-group jackknife using the same scale, ``1 / R`` for BRR, + ``1 / (R - 1)`` for supplied, non-averaged bootstrap weights with the + standard scale, ``4 / R`` for successive difference, and + ``1 / (R * (1 - fay_k)**2)`` for Fay's BRR. + Select the factor and center specified by the survey. Designs that + need other factors, such as arbitrary stratified jackknife and + averaged bootstrap, are unsupported. Validity also depends on the statistic: nonsmooth quantiles can require an appropriate replication method or smoothing of replicate estimates. - :param series: A MicroSeries. Its own weights give the point estimate. + :param series: A MicroSeries. Its own weights give the full-sample center. :param statistic: Callable taking a MicroSeries and returning a float, for example ``lambda s: s.gini()``. :param replicate_weights: Array or frame of shape ``(len(series), R)`` @@ -76,7 +78,7 @@ def replicate_variance( DataFrame index labels are ignored. :param method: One of ``jackknife``, ``brr``, ``bootstrap``, ``successive-difference``, or ``fay`` (which requires ``fay_k``). - :param fay_k: Fay's perturbation constant, required when + :param fay_k: Fay's perturbation constant in ``[0, 1)``, required when ``method="fay"``. :param centering: ``full-sample`` (default) centers on ``statistic(series)``; ``replicate-mean`` centers on the mean of the replicate estimates. diff --git a/microdf/tests/test_replication.py b/microdf/tests/test_replication.py index dea219e..ebaa7d6 100644 --- a/microdf/tests/test_replication.py +++ b/microdf/tests/test_replication.py @@ -55,7 +55,7 @@ def test_works_for_statistics_with_no_analytic_variance( [ ("jackknife", 199 / 200), ("brr", 1 / 200), - ("bootstrap", 1 / 200), + ("bootstrap", 1 / 199), ("successive-difference", 4 / 200), ], ) @@ -71,6 +71,48 @@ def test_each_method_applies_its_own_scale( assert variance == pytest.approx(reference * expected_factor * 200, rel=1e-9) +def test_delete_one_jackknife_mean_matches_analytic_variance(): + values = np.array([1, 3, 4, 8]) + n = len(values) + series = MicroSeries(values, weights=np.ones(n)) + replicates = (np.ones((n, n)) - np.eye(n)) * n / (n - 1) + + observed = replicate_variance( + series, MicroSeries.mean, replicates, method="jackknife" + ) + + assert observed == pytest.approx(np.var(values, ddof=1) / n) + + +@pytest.mark.parametrize( + "method,fay_k,factor", + [ + ("jackknife", None, 3 / 4), + ("brr", None, 1 / 4), + ("bootstrap", None, 1 / 3), + ("successive-difference", None, 4 / 4), + ("fay", 0.25, 4 / 9), + ], +) +@pytest.mark.parametrize("centering", ["full-sample", "replicate-mean"]) +def test_replicate_variance_matches_numpy(method, fay_k, factor, centering): + values = np.array([1, 3, 8]) + weights = np.array([1, 2, 3]) + replicates = np.array([[3, 1, 0, 2], [1, 4, 1, 1], [0, 1, 5, 2]]) + series = MicroSeries(values, weights=weights) + estimates = values @ replicates / replicates.sum(axis=0) + center = ( + np.average(values, weights=weights) + if centering == "full-sample" + else np.mean(estimates) + ) + expected = factor * np.sum((estimates - center) ** 2) + + assert replicate_variance( + series, MicroSeries.mean, replicates, method, fay_k, centering=centering + ) == pytest.approx(expected) + + def test_fay_requires_and_uses_its_constant(series_and_replicates): series, replicates = series_and_replicates @@ -161,7 +203,7 @@ def test_replicates_preserve_exact_large_integer_categories(dtype): [ ("jackknife", None, 1088 / 3, 3136 / 9), ("brr", None, 544 / 3, 1568 / 9), - ("bootstrap", None, 544 / 3, 1568 / 9), + ("bootstrap", None, 544 / 2, 1568 / 6), ("successive-difference", None, 2176 / 3, 6272 / 9), ("fay", 0.5, 2176 / 3, 6272 / 9), ], @@ -197,7 +239,7 @@ def squared_total(sample): def test_default_centering_retains_full_sample_estimate(): series = MicroSeries([1, 3], weights=[1, 1]) replicates = np.array([[2, 1, 0], [0, 1, 2]]) - expected_variance = 544 / 3 + expected_variance = 544 / 2 def squared_total(sample): return sample.sum() ** 2 @@ -261,7 +303,7 @@ def _replication_result(series, statistic, replicates, api, **kwargs): [ ("jackknife", None, 5e153, 1.75e308), ("brr", None, 1e154, 1e308), - ("bootstrap", None, 1e154, 1e308), + ("bootstrap", None, 1e154, 1e308 * (8 / 7)), ("successive-difference", None, 5e153, 1e308), ("fay", 0.5, 5e153, 1e308), ], @@ -273,7 +315,7 @@ def test_large_finite_replicate_variance( ): series = MicroSeries([0.0, 2 * amplitude], weights=[1, 1]) replicates = np.tile([[2, 0], [0, 2]], (1, 4)) - # Eight deviations are +/- amplitude. The factors are 7/8, 1/8 or 1/2. + # Eight deviations are +/- amplitude. The factors are 7/8, 1/8, 1/7 or 1/2. # Every method has a finite variance despite an overflowing raw sum. expected = expected_variance if api == "variance" else np.sqrt(expected_variance) observed = _replication_result( @@ -312,7 +354,7 @@ def test_identical_large_replicates_have_zero_variance(centering, api): [ ("jackknife", None, 3), ("brr", None, 1), - ("bootstrap", None, 1), + ("bootstrap", None, 4 / 3), ("successive-difference", None, 4), ("fay", 0.5, 4), ],