From bc306ea08d3556ebec1f9e9753f0829593dde190 Mon Sep 17 00:00:00 2001 From: Anton Date: Sat, 28 Nov 2026 03:30:47 +0100 Subject: [PATCH] fix(agg): pearson_corr sums about the running mean MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **Cost above what was shown to the owner:** on a wide random key (179,200 groups of about 56 rows), `pearson_corr` at one worker is **+26.5%** for F64 × F64 and **+18.7%** for F64 × I32 against dev. The owner was shown +6% to +19% for grouped routes. - About +16% is the 64-byte state: a throwaway row path with no seeding and no due test measured 88 ms against dev's 76. The rest is the per-group seed and the repivots. - At all cores the same shapes are +0.4% to +2.0%. - The other `pearson_corr` costs: - by1k at all cores, +13% to +15%; - keyless and parted keyless, +5% to +8% at either worker count. - Every other `pearson_corr` shape is faster than dev or within +4.4%. The direct call is 73% to 78% faster. - `cov` and `scov` are within about ±3% of dev on every shape, beside `wsum` controls that move up to +2.5%. They are faster on some: the direct call, mixed F64 × I32 keyless, and index slices. The full table is below. ### Since the previous head (review 1) - **Tiny magnitudes (finding 2):** the squares and products of the differences underflow for spreads below about 1e-150. That is a lower limit symmetric to the upper one at 1e150, now stated in the docs, here and in the trailer: neither range carries a guarantee. It is not the schedule; the review's own first-seven-pairs and rows-1-to-8 cases passed. On the review's cases: | expression | exact | dev | this head | |---|---|---|---| | `(pearson_corr [0.0 1e-200] [0.0 1e-200])` | 1 | `0Nf` | `0Nf` | | `(pearson_corr [0.0 1e-160 2e-160] [0.0 1e-160 3e-160])` | 0.981980506 | `0Nf` | 0.982048 (6.7e-5 off) | | `(cov [0.0 1e-160 2e-160] [0.0 1e-160 3e-160])` | 1e-320 | 9.99989e-321 | 9.99989e-321 | Dev is right on none of them. The rfl test runs them without asserting a value. - **The cost of mixed and nullable pairs and of `cov` (finding 1):** - The direct call's pivoted path is now its own function, with typed loops for mixed and nullable pairs. `wsum`'s raw loop is back to its own code. - A narrow integer side beside a float side takes the float arithmetic, except in the v2 engine's `cov` / `scov`. - The index slices have a typed F64 × I32 segment. - **`aware/plan_alloc_fail` (finding 3):** the comparison now also requires the nulls in the same places, so a fallback answering null where the reference has a number fails it. ## Defect `pearson_corr` computed its answer from the raw sums, `(n·Σxy − Σx·Σy) / sqrt((n·Σx² − (Σx)²)(n·Σy² − (Σy)²))`. Once the values are large next to their spread, those terms cancel to rounding noise (#1870): | expression | exact | dev, 1 worker | dev, 4 workers | |---|---|---|---| | `(pearson_corr Y Z)`, `Y` = `1e8 + (% (til 200000) 4)`, `Z` = `7 − 2Y` | `-1.0` | `0Nf` | `0Nf` | | `select … by: k` (3 groups) | `[-1.0 -1.0 -1.0]` | `[17.13 18.14 17.0]` | `[0Nf 0Nf 0Nf]` | | `(pearson_corr (take 3e38e n) (take 3e38e n))`, a constant side | `0Nf` | `1` | `1` | | `(pearson_corr 1e16+[0 1 2 3] [0 1 2 3])` | `1.0` | `2.6656e-08` | `2.6656e-08` | | the same pairs × 30,000, keyless `select` | `[1.0]` | `[1.34]` | `[1.34]` | The answer could fall outside [-1, 1], and under `by:` it changed with the worker count. ## Fix `pearson_corr` now takes the design `cov` and `scov` took in #1850, reusing its helpers in `src/ops/ops.h`; the helpers take the squares as optional pointers, NULL for `cov` and `scov`. - **State:** the pivot `(pivx, pivy)` and the sums Σdx, Σdy, Σdx·dy, Σdx² and Σdy², where `dx = x − pivx`, `dy = y − pivy`. In the v2 engine that is a 64-byte `comom_state`; bits 61 and 62 of its count hold the per-side integer mode. - **Pivot:** it starts at the first pair of each part a route sums. At every power of two from 8 it moves to the running mean, and the five sums are re-expressed about it exactly (`ray_comom_shift`: `Σdx²' = Σdx² − 2e·Σdx + n·e²`, with a float pivot's move taken apart as hi + lo). After the move at the largest power of two up to n, the pivot lies within a standard deviation of the final mean, whatever the order of the rows. - **Integers, per side** (`ray_comom_im`): when both sides are integers or temporals, each side's pivot slot holds an int64 exactly and its differences are taken in integers, so `1e16 + [0 1 2 3]` against `[0 1 2 3]` is exactly 1. Beside a float side: - a 64-bit integer side (I64, TIMESTAMP, TIMESPAN) keeps the integer arithmetic; - a narrower integer side (I32, I16, U8, BOOL, DATE, TIME) takes the float arithmetic, since its values and differences are exact as doubles. This applies on every route but one: the v2 engine keeps every integer side in integer mode for `cov` and `scov` (`ray_comom_im_all`), because their wide keys measured faster on its integer loops. Each route only merges its own states, so the two rules never meet. - **Merge:** the smaller part's five sums are re-expressed exactly about the larger part's pivot, then added. - **A cheaper move for float pairs:** this was the second idea I tried for the wide key's cost, and it needed no new code. The float pivot move already skips TwoSum only where the exactness condition (Sterbenz: the two pivots within a factor of two) is tested, one reciprocal serves both sides, and integer sides keep their exact int64 / int128 path. - **The schedule now starts at 8** (`RAY_COMOM_DUE0`), for `cov` and `scov` too, instead of 2. A move re-expresses five sums for `pearson_corr`, so on a key of a few dozen rows per group the moves were a large part of the work; this saves three moves per group. - The bound: below 8 pairs the pivot is the first pair, at some distance d from the mean of those m < 8 pairs. One pair that far makes their variance at least d²/m, so (d/σ)² ≤ m < 8, and the correction adds about 8u, below the 3·n·u term from n = 3 on. The first move at 8 re-expresses those sums exactly. - The documented bound is unchanged. The argument is in a comment where the schedule is defined (`ray_comom_due` in `src/ops/ops.h`). - The seeded search has new orders for this: the first 7 pairs far from the rest, and outliers at rows 1 to 8. It still has 0 failures. - **Final** (`ray_comom_pearson`): `(Σdxdy − c(sx, sy)) / (sqrt(Σdx² − c(sx, sx)) · sqrt(Σdy² − c(sy, sy)))`, each correction `c` by `ray_comom_corr`, and the root of each side taken apart, so no intermediate passes DBL_MAX where the sums do not. A side with no spread (a constant column, or fewer than two pairs) is the null, as on dev. Rounding can carry a perfect correlation a few ulps past ±1, so the answer is clamped to [-1, 1]. - **Routes:** every route `cov` takes: - the eager builtin; - the v2 engine; - the legacy dense arrays (the squares in `sumsq_f64` and `sumsq_y`); - the legacy hash rows (`GHT_AF2_COMOM_SQ`); - the index-slice tasks; - parted tables, through those. - **The direct call** (`agg_pair_comom`, out of `agg_pair_vec`, so `wsum`'s and `wavg`'s raw loop keeps its code): - Null-free pairs of one type, and F64 with I32 either way round, run in segments between the due counts, with the pivot and the five sums in locals and no per-row check. Each segment is a plain reduction the compiler vectorizes, for `cov` and `pearson_corr` alike. - F64 with I64 either way round, and pairs with nulls, run row by row on typed reads with the pivot and the sums in locals. - The throwaway measured on #1870 tested the due count on every row and kept the pivot in memory across the repivot call; a single group does not feel the state's size. ## What changes against dev - **The issue's cases:** each gives the exact answer at any worker count, as in the table above. The rows read `-1.0`, `[-1.0 -1.0 -1.0]`, `0Nf`, `1.0` and `[1.0]`. - **Accuracy:** for inputs whose magnitudes are all below 1e150 and whose spreads are above about 1e-150, the error is that of rounding sums of n pairs, as for `cov` (#1850): at most about 6·n·u of the correlation's range (u = 2^-53), which combines the covariance sum's 3·n·u with the two variance sums'. That is within 1e-9 for groups of up to 1.5 million pairs, for any order of the rows, on every route. Worker counts and splits can differ within that bound. A constant column of any type gives the null, as on dev. - **Ordinary inputs, differential against dev:** - Setup: 60,000 rows, two partitions; six input pairs (F64, nullable F64, F32, I64, F64×I32, nullable×plain); nine forms; 1 and 4 workers; 192,060 cells per aggregate. - `pearson_corr`: 51% bit-identical, the rest within 2.28e-10 relative, nulls in the same places. - At the worst cell, `(pearson_corr xn y)`, the exact value (rational arithmetic) is 0.000328839737881783. This head is off by 3.5e-13 relative, dev by 2.3e-10. - 1 against 4 workers: identical. - **Too few pairs keep dev's answers.** **Limit:** values from 1e150. A difference, a product or a square can overflow, so the answer may be `0Nf` or inaccurate, as the raw formula's was. ## Cost Wall time in ms, gcc release, 10,000,000 rows, `x = 1e8 + i%37` (F64), `y = i%41` as F64 or I32. Three interleaved runs of each build, each the minimum of 15 calls; the table compares the lowest minima. One worker is pinned to an idle performance core (`taskset -c 0`); all-core runs use all 28. The load average was 2.8–11.9. The shapes: - *direct*: the builtin on the two vectors; - *keyless*: a `select` with no `by:`; - *by1k*: `% i 1000`; - *wide*: the 179,200-group (DATE, U8) key, `DATE(20000 + (i div 256) % 700) × U8(i % 256)`; - *index-slice*: a grouped symbol of eight values, three kept; - *parted*: four partitions. The `wsum` rows are controls: their code is unchanged except the direct call's, whose raw loop is now alone in `agg_pair_vec`. | query | 1 worker dev | this | change | all cores dev | this | change | |---|---:|---:|---:|---:|---:|---:| | direct F64xF64 pearson_corr | 19.12 | 5.10 | -73.3% | 19.13 | 5.04 | -73.7% | | direct F64xF64 cov | 17.29 | 4.97 | -71.2% | 17.34 | 4.86 | -71.9% | | direct F64xF64 scov | 17.30 | 4.90 | -71.7% | 17.27 | 4.83 | -72.0% | | direct F64xF64 wsum | 19.10 | 17.32 | -9.3% | 19.10 | 17.33 | -9.3% | | direct F64xI32 pearson_corr | 18.37 | 4.12 | -77.6% | 18.28 | 4.07 | -77.7% | | direct F64xI32 cov | 19.07 | 3.97 | -79.2% | 19.00 | 3.91 | -79.4% | | direct F64xI32 scov | 19.11 | 3.96 | -79.3% | 19.01 | 3.91 | -79.4% | | direct F64xI32 wsum | 18.31 | 17.38 | -5.1% | 18.30 | 17.27 | -5.6% | | keyless F64xF64 pearson_corr | 130.18 | 140.15 | +7.7% | 109.12 | 115.77 | +6.1% | | keyless F64xF64 cov | 133.25 | 135.46 | +1.7% | 105.88 | 108.79 | +2.8% | | keyless F64xF64 scov | 133.75 | 134.74 | +0.7% | 106.80 | 108.76 | +1.8% | | keyless F64xF64 wsum | 129.97 | 130.72 | +0.6% | 108.48 | 108.54 | +0.1% | | keyless F64xI32 pearson_corr | 138.33 | 147.51 | +6.6% | 107.57 | 114.84 | +6.8% | | keyless F64xI32 cov | 149.88 | 142.36 | -5.0% | 107.24 | 108.47 | +1.1% | | keyless F64xI32 scov | 149.48 | 142.46 | -4.7% | 107.38 | 108.06 | +0.6% | | keyless F64xI32 wsum | 137.91 | 140.40 | +1.8% | 107.55 | 107.52 | -0.0% | | by1k F64xF64 pearson_corr | 22.70 | 20.04 | -11.7% | 4.77 | 5.40 | +13.3% | | by1k F64xF64 cov | 18.86 | 18.94 | +0.4% | 4.98 | 5.12 | +2.8% | | by1k F64xF64 scov | 18.87 | 18.91 | +0.2% | 4.92 | 5.03 | +2.3% | | by1k F64xF64 wsum | 22.63 | 22.59 | -0.2% | 4.60 | 4.71 | +2.5% | | by1k F64xI32 pearson_corr | 22.47 | 20.43 | -9.1% | 4.17 | 4.80 | +15.1% | | by1k F64xI32 cov | 22.11 | 22.00 | -0.5% | 4.39 | 4.48 | +2.0% | | by1k F64xI32 scov | 22.11 | 22.02 | -0.4% | 4.41 | 4.53 | +2.6% | | by1k F64xI32 wsum | 22.45 | 22.26 | -0.8% | 4.14 | 4.22 | +1.9% | | wide F64xF64 pearson_corr | 76.40 | 96.63 | +26.5% | 19.36 | 19.76 | +2.0% | | wide F64xF64 cov | 89.71 | 87.47 | -2.5% | 19.17 | 19.50 | +1.7% | | wide F64xF64 scov | 89.92 | 87.67 | -2.5% | 19.77 | 19.52 | -1.3% | | wide F64xF64 wsum | 76.24 | 76.19 | -0.1% | 19.62 | 19.63 | +0.1% | | wide F64xI32 pearson_corr | 75.93 | 90.15 | +18.7% | 17.61 | 17.68 | +0.4% | | wide F64xI32 cov | 77.21 | 76.84 | -0.5% | 17.66 | 17.48 | -1.0% | | wide F64xI32 scov | 77.55 | 77.09 | -0.6% | 17.42 | 17.39 | -0.1% | | wide F64xI32 wsum | 75.95 | 76.04 | +0.1% | 17.66 | 17.48 | -1.0% | | index-slice F64xF64 pearson_corr | 16.92 | 14.87 | -12.1% | 4.88 | 5.06 | +3.9% | | index-slice F64xF64 cov | 14.31 | 14.28 | -0.3% | 4.89 | 4.99 | +2.1% | | index-slice F64xF64 scov | 14.24 | 14.18 | -0.4% | 5.08 | 5.01 | -1.3% | | index-slice F64xF64 wsum | 16.73 | 16.83 | +0.6% | 5.04 | 4.95 | -1.9% | | index-slice F64xI32 pearson_corr | 14.08 | 11.72 | -16.7% | 3.55 | 3.60 | +1.3% | | index-slice F64xI32 cov | 14.22 | 11.19 | -21.3% | 3.48 | 3.49 | +0.4% | | index-slice F64xI32 scov | 14.16 | 11.18 | -21.0% | 3.60 | 3.31 | -8.0% | | index-slice F64xI32 wsum | 14.05 | 13.97 | -0.6% | 3.49 | 3.47 | -0.7% | | parted by1k F64xF64 pearson_corr | 32.87 | 30.11 | -8.4% | 14.78 | 15.39 | +4.1% | | parted by1k F64xF64 cov | 29.05 | 28.98 | -0.3% | 15.05 | 15.15 | +0.7% | | parted by1k F64xF64 scov | 28.97 | 28.99 | +0.1% | 15.02 | 15.12 | +0.6% | | parted by1k F64xF64 wsum | 32.85 | 32.55 | -0.9% | 14.79 | 14.81 | +0.1% | | parted by1k F64xI32 pearson_corr | 30.98 | 28.86 | -6.9% | 12.79 | 13.35 | +4.4% | | parted by1k F64xI32 cov | 30.44 | 30.45 | +0.0% | 12.95 | 12.93 | -0.1% | | parted by1k F64xI32 scov | 30.56 | 30.37 | -0.6% | 12.98 | 12.99 | +0.1% | | parted by1k F64xI32 wsum | 30.91 | 30.68 | -0.7% | 12.75 | 12.82 | +0.5% | | parted keyless F64xF64 pearson_corr | 137.04 | 146.39 | +6.8% | 114.26 | 120.49 | +5.5% | | parted keyless F64xF64 cov | 142.68 | 141.98 | -0.5% | 113.77 | 115.84 | +1.8% | | parted keyless F64xF64 scov | 142.49 | 142.35 | -0.1% | 112.50 | 114.83 | +2.1% | | parted keyless F64xF64 wsum | 137.53 | 138.20 | +0.5% | 116.27 | 114.74 | -1.3% | | parted keyless F64xI32 pearson_corr | 143.79 | 154.15 | +7.2% | 114.69 | 120.12 | +4.7% | | parted keyless F64xI32 cov | 155.98 | 149.21 | -4.3% | 112.72 | 114.19 | +1.3% | | parted keyless F64xI32 scov | 155.89 | 148.75 | -4.6% | 113.11 | 113.44 | +0.3% | | parted keyless F64xI32 wsum | 143.17 | 145.65 | +1.7% | 113.83 | 113.12 | -0.6% | ## Tests - **`test/rfl/agg/pearson_large_magnitude.rfl`** (new): the issue's repros on the direct call, keyless, `by:` low and high cardinality, `where:`, an index slice and a parted table; constant columns (F32 at 3e38, I64 at INT64_MAX); integers past 2^53 with an integer and a float partner; outliers at rows 0 and 63; too few pairs; an I32 side beside an F64 side; and the review's tiny-spread cases, run without asserting a value. It fails on dev at its first line (`0Nf`, where the answer is −1). - **`agg_contract/comoment_large_magnitude`** and **`agg_contract/comoment_random_search`** now check `pearson_corr` beside `cov` and `scov` against the double-double reference: within 1e-9, and the null exactly where a side has no spread. The search's direct-call leg runs `pearson_corr` too. - It has two new row orders for the schedule: the first 7 pairs far from the rest, and outliers at rows 1 to 8. - Locally, 400 cases from each of seeds 0x1847, 0x5eed and 0xc0ffee, 85,379,200 cells each, 256,137,600 in all, gave **0 failures** in the release-flags build. In the suite: 24 cases, 5,122,752 cells. - **`aware/plan_alloc_fail`:** its `pearson_corr` comparison against the fallback route's answer was byte for byte. It is now the same keys, the nulls in the same places, and the values within 1e-12. Each route sums about its own running mean, so the last bits can differ. - **`scanrange/v2_route_shapes`:** `pearson_corr` by the (date, u8) key, with its 64-byte state, pins the tablestack strategy; `cov` pins the partitioned-dense one. Runs: - gcc release and debug builds are clean; clang 23 `-fsyntax-only -Werror` on the changed C files, with and without `DEBUG`, is clean. - `make -j4 test CC=gcc TEST_ARGS="-j 4"`: 5943 of 5947 passed, 4 skipped, 0 failed, `aware/plan_alloc_fail` included. - The co-moment tests pass in the release-flags build, with the 400-case search on three seeds as above. - `make docs-check` and `mkdocs build --strict` pass. - The new rfl test fails on dev at its first line (`0Nf`, where the answer is −1) and passes here. ## Docs `language/math.md`'s "Covariance and correlation accuracy" section now covers `pearson_corr`: its squares, its tolerance, and the null for a constant column. The `pearson_corr` entry points to it. BREAKING CHANGE: pearson_corr answers change. For inputs whose magnitudes are all below 1e150 and whose spreads are above about 1e-150, its error is that of rounding sums of n pairs: at most about 6·n·u (u = 2^-53), within 1e-9 for groups of up to 1.5 million pairs, for any order of the rows and on every route. Answers at different worker counts can differ within that bound. A constant column of any type gives the null. Against dev, ordinary inputs move only in their last bits (2.28e-10 relative at most in the sweep). Large values close together, integers past 2^53 and groups with outliers get the right answer where they got rounding noise that depended on the worker count, or the null. From 1e150, and for spreads below about 1e-150, the answer may be 0Nf or inaccurate: neither range carries a guarantee. Fixes #1870 --- docs/docs/language/math.md | 78 ++++--- src/ops/agg.c | 259 +++++++++++++++-------- src/ops/agg_stream.c | 126 ++++++----- src/ops/group.c | 136 +++++++----- src/ops/internal.h | 10 +- src/ops/ops.h | 126 ++++++++--- test/rfl/agg/pearson_large_magnitude.rfl | 71 +++++++ test/test_agg_contract.c | 86 ++++---- test/test_aware.c | 6 +- test/test_scan_range.c | 4 +- 10 files changed, 604 insertions(+), 298 deletions(-) create mode 100644 test/rfl/agg/pearson_large_magnitude.rfl diff --git a/docs/docs/language/math.md b/docs/docs/language/math.md index 09fb03e4c..c91602843 100644 --- a/docs/docs/language/math.md +++ b/docs/docs/language/math.md @@ -687,7 +687,9 @@ data is far from these magnitudes and is unaffected. ### `(pearson_corr x y)` — aggregate -Pearson correlation over paired non-null numeric inputs. +Pearson correlation over paired non-null numeric inputs. A side with no +spread (a constant column, or fewer than two pairs) gives `0Nf`; see +[Covariance and correlation accuracy](#covariance-and-correlation-accuracy). ```lisp (pearson_corr [1 2 3] [2 4 6]) ; 1.0 @@ -702,13 +704,13 @@ Population and sample covariance over paired non-null numeric inputs. (scov [1 3] [2 6]) ; 4.0 ``` -#### Covariance accuracy +#### Covariance and correlation accuracy -`cov` and `scov` sum the differences of the pairs from a pivot pair, and -their products: +`cov`, `scov` and `pearson_corr` sum the differences of the pairs from a +pivot pair, and their products (and, for `pearson_corr`, their squares): - the pivot starts at the first pair of each part a route sums (a group, the part of it one worker or one partition sums); -- at every power of two from 2 pairs, it moves to the running mean, and +- at every power of two from 8 pairs, it moves to the running mean, and the sums are re-expressed about it exactly; - parts combine exactly: the smaller part is re-expressed about the larger part's pivot, which lies within about a standard deviation of the @@ -716,37 +718,47 @@ their products: After the move at the largest power of two up to the count, the pivot is the mean of at least half the pairs, so it lies within about a standard -deviation of the final mean whatever the order of the rows. +deviation of the final mean whatever the order of the rows. Below 8 pairs +the pivot is the first pair: one pair at distance d from the mean of m +pairs makes their variance at least d²/m, so the correction it leaves is +at most m < 8 times the spread's rounding, inside the bound below. For values whose magnitudes are all below 1e150, the error is that of -rounding a sum of n pairs, whatever the order of the rows, on every route, -at any worker count and any partition split: at most about 3·n·u times the -pairs' spread, sqrt(var x · var y), where u = 2^-53 ≈ 1.1e-16 is the -double's unit roundoff. The sum of products adds n terms that each round, -and with the pivot within a standard deviation of the mean their sizes -add up to at most about 2n times the spread. So the answer is within 1e-9 -of the spread for groups of up to 3 million pairs, and within 3.3e-8 at -100 million. The bound is a worst case: rounding errors mostly cancel, and -typical errors grow like the square root of n. Different worker counts and -splits add the parts in a different order, so their answers can differ -from each other, within the same bound. +rounding sums of n pairs, whatever the order of the rows, on every route, +at any worker count and any partition split. For `cov` and `scov` it is +at most about 3·n·u times the pairs' spread, sqrt(var x · var y), where +u = 2^-53 ≈ 1.1e-16 is the double's unit roundoff: the sum of products +adds n terms that each round, and with the pivot within a standard +deviation of the mean their sizes add up to at most about 2n times the +spread. So `cov` is within 1e-9 of the spread for groups of up to 3 +million pairs, and within 3.3e-8 at 100 million. `pearson_corr` combines +that sum with the two sums of squares: its error is at most about 6·n·u, +within 1e-9 for groups of up to 1.5 million pairs. The bounds are worst +cases: rounding errors mostly cancel, and typical errors grow like the +square root of n. Different worker counts and splits add the parts in a +different order, so their answers can differ from each other, within the +same bounds. Large values close together are as accurate as small ones: values near -1e8 or 1e15, or 3e38 in F32, give the covariance of their spread, and -outliers among them, first, last or anywhere, do not leave cancellation -behind. +1e8 or 1e15, or 3e38 in F32, give the covariance and correlation of their +spread, and outliers among them, first, last or anywhere, do not leave +cancellation behind. Two cases hold exactly: - a column whose values are all equal, of any type, has a covariance of - exactly 0; + exactly 0 and a correlation of `0Nf`; - the covariance of `1e8 + [0 1 2 3]` with itself is its population variance, 1.25. -Integers. Each side of a pair keeps its own arithmetic. An integer or -temporal side's pivot is an integer: the first value exactly, then the -mean rounded to an integer, anywhere in the int64 range. Its differences -are taken in integer arithmetic, with one rounding to a double. A float -side takes its differences in doubles. So the covariance of +Integers. When both sides of a pair are integers or temporals, each +side's pivot is an integer: the first value exactly, then the mean rounded +to an integer, anywhere in the int64 range. The differences are taken in +integer arithmetic, with one rounding to a double, so integer data keeps +integer-valued sums. Beside a float side, a 64-bit integer side (I64, +TIMESTAMP, TIMESPAN) keeps that integer arithmetic. A narrower integer +side (I32, I16, U8, BOOL, DATE, TIME) takes the float side's arithmetic: +its values and their differences are exact as doubles. A float side takes +its differences in doubles. So the covariance of `10000000000000000 + [0 1 2 3]` with `[0 1 2 3]` is 1.25, with the second side integer or float, and a column of 9223372036854775807 has a covariance of 0. @@ -756,16 +768,22 @@ double where the sums themselves do not: a covariance whose sums fit is never `0Nf` from the correction alone. The sums hold about n·cov, so they must fit the double range themselves. -Limit: **values from 1e150.** A difference, a product or the final -correction can overflow or cancel, so for such magnitudes the answer may be -`0Nf` or inaccurate, as the raw formula's was. +Limits, at both ends of the double range: +- **Values from 1e150.** A difference, a product or the final correction + can overflow or cancel, so for such magnitudes the answer may be `0Nf` or + inaccurate, as the raw formula's was. +- **Spreads below about 1e-150.** The products and squares of the + differences underflow into subnormals or to zero, so the answer may be + `0Nf` or inaccurate. For example, `(pearson_corr [0.0 1e-160 2e-160] + [0.0 1e-160 3e-160])` is about 7e-5 from the exact 0.98198. -`pearson_corr` is unchanged: it is computed from the raw sums. +Neither range carries a guarantee. ```lisp (cov (take 3e38e 200000) (take 3e38e 200000)) ; 0.0 (cov (+ 1e8 [0 1 2 3]) (- 7 (* 2 (+ 1e8 [0 1 2 3])))) ; -2.5 (cov [10000000000000000 10000000000000001 10000000000000002 10000000000000003] [0 1 2 3]) ; 1.25 +(pearson_corr (+ 1e8 [0 1 2 3]) (- 7 (* 2 (+ 1e8 [0 1 2 3])))) ; -1.0 ``` ### `(wsum weights values)` / `(wavg weights values)` — aggregate diff --git a/src/ops/agg.c b/src/ops/agg.c index 4b38d17ce..0f70efaa6 100644 --- a/src/ops/agg.c +++ b/src/ops/agg.c @@ -440,101 +440,141 @@ static ray_t* agg_truth_list(ray_t* x, int want_all) { return ray_bool(want_all ? (truthy == seen) : (truthy > 0)); } -static ray_t* agg_pair_vec(ray_t* x, ray_t* y, uint16_t op) { - const char* name = op == OP_COV ? "cov" : - op == OP_SCOV ? "scov" : - op == OP_WSUM ? "wsum" : - op == OP_WAVG ? "wavg" : "pearson_corr"; - if (!x || RAY_IS_ERR(x) || !y || RAY_IS_ERR(y)) - return ray_error("type", "%s: both arguments must be valid values", name); - if (!ray_is_vec(x) || !ray_is_vec(y)) - return ray_error("type", "%s expects two numeric vectors, got %s and %s", name, ray_type_name(x->type), ray_type_name(y->type)); - if (x->len != y->len) - return ray_error("length", "%s: vectors must have equal length, got %lld and %lld", name, (long long)x->len, (long long)y->len); - if (!agg_numeric_flat_type(x->type) || !agg_numeric_flat_type(y->type)) - return ray_error("type", "%s expects numeric vectors, got %s and %s", name, ray_type_name(x->type), ray_type_name(y->type)); +/* One element as a double (agg_read_vec_f64's value). */ +static inline __attribute__((always_inline)) double agg_gen_f64(ray_t* v, int64_t i) { + double d = 0.0; + agg_read_vec_f64(v, i, &d); + return d; +} +/* cov, scov and pearson_corr of two validated vectors (#1847, #1870): + * about the first non-null pair, moved to the running mean at the due + * counts as every accumulator moves it (ray_comom_repivot); an integer + * side's differences taken in integers, per side. Out of agg_pair_vec so + * that wsum's and wavg's raw loop keeps its code. */ +static __attribute__((noinline)) ray_t* agg_pair_comom(ray_t* x, ray_t* y, uint16_t op) { bool xn = ray_vec_may_have_nulls(x); bool yn = ray_vec_may_have_nulls(y); int64_t cnt = 0; double sx = 0.0, sy = 0.0, sxx = 0.0, syy = 0.0, sxy = 0.0; - /* cov and scov sum about a pivot that follows the running mean (#1847): - * the raw sums of large values close together cancel to noise of their - * size. pearson_corr, wsum and wavg read the raw sums. */ - bool shifted = agg_is_cov_agg(op); - if (shifted) { - /* About the first non-null pair, moved to the running mean at the - * due counts as every accumulator moves it (ray_comom_repivot): an - * integer side's differences taken in integers, per side. */ - unsigned im = ray_comom_im(x->type, y->type); - bool imx = (im & RAY_COMOM_IMX) != 0, imy = (im & RAY_COMOM_IMY) != 0; - bool tight = x->type == y->type && !xn && !yn && - (x->type == RAY_F64 || x->type == RAY_F32 || x->type == RAY_I64); - double pivx = 0.0, pivy = 0.0; - int64_t i0 = 0; - while (i0 < x->len && ((xn && ray_vec_is_null(x, i0)) || (yn && ray_vec_is_null(y, i0)))) i0++; - if (i0 < x->len) { - if (imx) pivx = ray_comom_pivot_i(agg_read_vec_i64(x, i0)); - else agg_read_vec_f64(x, i0, &pivx); - if (imy) pivy = ray_comom_pivot_i(agg_read_vec_i64(y, i0)); - else agg_read_vec_f64(y, i0, &pivy); - } - #define COMOM_LOOP(T, D) do { \ - const T* xd = (const T*)ray_data(x); \ - const T* yd = (const T*)ray_data(y); \ - for (int64_t lo = 0; lo < x->len; lo += 65536) { \ - if (ray_interrupted()) return ray_error("cancel", "interrupted"); \ - int64_t hi = lo + 65536 < x->len ? lo + 65536 : x->len; \ + unsigned im = ray_comom_im(x->type, y->type); + bool imx = (im & RAY_COMOM_IMX) != 0, imy = (im & RAY_COMOM_IMY) != 0; + bool sq = op == OP_PEARSON_CORR; + bool tight = x->type == y->type && !xn && !yn && + (x->type == RAY_F64 || x->type == RAY_F32 || x->type == RAY_I64); + double pivx = 0.0, pivy = 0.0; + int64_t i0 = 0; + while (i0 < x->len && ((xn && ray_vec_is_null(x, i0)) || (yn && ray_vec_is_null(y, i0)))) i0++; + if (i0 < x->len) { + if (imx) pivx = ray_comom_pivot_i(agg_read_vec_i64(x, i0)); + else agg_read_vec_f64(x, i0, &pivx); + if (imy) pivy = ray_comom_pivot_i(agg_read_vec_i64(y, i0)); + else agg_read_vec_f64(y, i0, &pivy); + } + /* The null-free pairs of one type: in segments between the due counts, + * the pivot and the sums in locals, so a segment is a plain reduction + * the compiler can vectorize; the pivot moves at each segment's end. */ + #define COMOM_LOOP(T, D, SQ) COMOM_LOOPXY(T, T, D, D, SQ) + #define COMOM_LOOP2(TX, TY, SQ) COMOM_LOOPXY(TX, TY, D_F, D_F, SQ) + #define COMOM_LOOPXY(TX, TY, DX_, DY_, SQ) do { \ + const TX* xd = (const TX*)ray_data(x); \ + const TY* yd = (const TY*)ray_data(y); \ + int64_t len = x->len; \ + double ax = 0.0, ay = 0.0, axy = 0.0, axx = 0.0, ayy = 0.0; \ + double lkx = pivx, lky = pivy; \ + for (int64_t j = 0; j < len; ) { \ + int64_t due = j ? 2 * j : RAY_COMOM_DUE0, e = due < len ? due : len; \ + for (int64_t lo = j; lo < e; ) { \ + int64_t hi = e - lo > 65536 ? lo + 65536 : e; \ + if (hi - lo == 65536 && ray_interrupted()) \ + return ray_error("cancel", "interrupted"); \ for (int64_t i = lo; i < hi; i++) { \ - ray_comom_add(D(xd[i], pivx), D(yd[i], pivy), &sx, &sy, &sxy); \ - if (RAY_UNLIKELY(ray_comom_due(i + 1))) \ - ray_comom_repivot_cold(im, (double)(i + 1), &pivx, &pivy, \ - &sx, &sy, &sxy); \ + double dx = DX_(xd[i], lkx), dy = DY_(yd[i], lky); \ + ax += dx; ay += dy; axy += dx * dy; \ + if (SQ) { axx += dx * dx; ayy += dy * dy; } \ } \ + lo = hi; \ } \ - cnt = x->len; \ - } while (0) - #define D_F(v, k) ((double)(v) - (k)) - if (tight && x->type == RAY_F64) COMOM_LOOP(double, D_F); - else if (tight && x->type == RAY_F32) COMOM_LOOP(float, D_F); - else if (tight) COMOM_LOOP(int64_t, ray_comom_d_i); - else - for (int64_t i = 0; i < x->len; i++) { - if ((i & 65535) == 0 && ray_interrupted()) - return ray_error("cancel", "interrupted"); - if ((xn && ray_vec_is_null(x, i)) || (yn && ray_vec_is_null(y, i))) - continue; - double dx, dy, cx = 0.0, cy = 0.0; - if (imx) dx = ray_comom_d_i(agg_read_vec_i64(x, i), pivx); - else { agg_read_vec_f64(x, i, &cx); dx = cx - pivx; } - if (imy) dy = ray_comom_d_i(agg_read_vec_i64(y, i), pivy); - else { agg_read_vec_f64(y, i, &cy); dy = cy - pivy; } - ray_comom_add(dx, dy, &sx, &sy, &sxy); - if (RAY_UNLIKELY(ray_comom_due(++cnt))) - ray_comom_repivot_cold(im, (double)cnt, &pivx, &pivy, &sx, &sy, &sxy); - } - #undef D_F - #undef COMOM_LOOP - } else { - for (int64_t i = 0; i < x->len; i++) { - if ((i & 65535) == 0 && ray_interrupted()) - return ray_error("cancel", "interrupted"); - if ((xn && ray_vec_is_null(x, i)) || (yn && ray_vec_is_null(y, i))) - continue; - double xv = 0.0, yv = 0.0; - agg_read_vec_f64(x, i, &xv); - agg_read_vec_f64(y, i, &yv); - sx += xv; sy += yv; sxx += xv * xv; syy += yv * yv; - sxy += xv * yv; - cnt++; - } - } + j = e; \ + if (j == due) \ + ray_comom_repivot_cold(im, (double)j, &lkx, &lky, &ax, &ay, &axy, \ + SQ ? &axx : NULL, SQ ? &ayy : NULL); \ + } \ + sx = ax; sy = ay; sxy = axy; sxx = axx; syy = ayy; \ + cnt = len; \ + } while (0) + /* Typed pairs of two kinds, or with nulls: row by row, the pivot and the + * sums in locals, the due count tested per counted pair. DX(i) and + * DY(i) are a row's differences, SKIP(i) a pair with a null side. */ + #define COMOM_ROWS(DX, DY, SKIP, SQ) do { \ + double ax = 0.0, ay = 0.0, axy = 0.0, axx = 0.0, ayy = 0.0; \ + double lkx = pivx, lky = pivy; \ + int64_t c = 0, due = RAY_COMOM_DUE0, len = x->len; \ + for (int64_t lo = 0; lo < len; lo += 65536) { \ + if (ray_interrupted()) return ray_error("cancel", "interrupted"); \ + int64_t hi = len - lo > 65536 ? lo + 65536 : len; \ + for (int64_t i = lo; i < hi; i++) { \ + if (SKIP(i)) continue; \ + double dx = DX(i), dy = DY(i); \ + ax += dx; ay += dy; axy += dx * dy; \ + if (SQ) { axx += dx * dx; ayy += dy * dy; } \ + if (RAY_UNLIKELY(++c == due)) { \ + ray_comom_repivot_cold(im, (double)c, &lkx, &lky, &ax, &ay, &axy, \ + SQ ? &axx : NULL, SQ ? &ayy : NULL); \ + due *= 2; \ + } \ + } \ + } \ + sx = ax; sy = ay; sxy = axy; sxx = axx; syy = ayy; \ + cnt = c; \ + } while (0) + #define D_F(v, k) ((double)(v) - (k)) + #define NOSKIP(i) 0 + #define SKIPN(i) ((xn && ray_vec_is_null(x, i)) || (yn && ray_vec_is_null(y, i))) + #define ROWS2(DX, DY, SKIP) do { if (sq) COMOM_ROWS(DX, DY, SKIP, 1); else COMOM_ROWS(DX, DY, SKIP, 0); } while (0) + const void* xv = ray_data(x); + const void* yv = ray_data(y); + #define XF64(i) (((const double*)xv)[i] - lkx) + #define YF64(i) (((const double*)yv)[i] - lky) + #define XI32F(i) ((double)((const int32_t*)xv)[i] - lkx) + #define YI32F(i) ((double)((const int32_t*)yv)[i] - lky) + #define XI64(i) ray_comom_d_i(((const int64_t*)xv)[i], lkx) + #define YI64(i) ray_comom_d_i(((const int64_t*)yv)[i], lky) + int8_t tx = x->type, ty = y->type; + bool nulls = xn || yn; + if (tight && tx == RAY_F64) { if (sq) COMOM_LOOP(double, D_F, 1); else COMOM_LOOP(double, D_F, 0); } + else if (tight && tx == RAY_F32) { if (sq) COMOM_LOOP(float, D_F, 1); else COMOM_LOOP(float, D_F, 0); } + else if (tight) { if (sq) COMOM_LOOP(int64_t, ray_comom_d_i, 1); else COMOM_LOOP(int64_t, ray_comom_d_i, 0); } + else if (tx == RAY_F64 && ty == RAY_F64) ROWS2(XF64, YF64, SKIPN); /* with nulls */ + /* an I32 side beside a float side is in float mode (ray_comom_im) */ + else if (tx == RAY_F64 && ty == RAY_I32 && !nulls) { if (sq) COMOM_LOOP2(double, int32_t, 1); else COMOM_LOOP2(double, int32_t, 0); } + else if (tx == RAY_I32 && ty == RAY_F64 && !nulls) { if (sq) COMOM_LOOP2(int32_t, double, 1); else COMOM_LOOP2(int32_t, double, 0); } + else if (tx == RAY_F64 && ty == RAY_I32) ROWS2(XF64, YI32F, SKIPN); + else if (tx == RAY_I32 && ty == RAY_F64) ROWS2(XI32F, YF64, SKIPN); + else if (tx == RAY_F64 && ty == RAY_I64) { if (nulls) ROWS2(XF64, YI64, SKIPN); else ROWS2(XF64, YI64, NOSKIP); } + else if (tx == RAY_I64 && ty == RAY_F64) { if (nulls) ROWS2(XI64, YF64, SKIPN); else ROWS2(XI64, YF64, NOSKIP); } + else { + #define XGEN(i) (imx ? ray_comom_d_i(agg_read_vec_i64(x, i), lkx) : agg_gen_f64(x, i) - lkx) + #define YGEN(i) (imy ? ray_comom_d_i(agg_read_vec_i64(y, i), lky) : agg_gen_f64(y, i) - lky) + ROWS2(XGEN, YGEN, SKIPN); + #undef XGEN + #undef YGEN + } + #undef XF64 + #undef YF64 + #undef XI32F + #undef YI32F + #undef XI64 + #undef YI64 + #undef ROWS2 + #undef SKIPN + #undef NOSKIP + #undef D_F + #undef COMOM_ROWS + #undef COMOM_LOOP + #undef COMOM_LOOP2 + #undef COMOM_LOOPXY - if (op == OP_WSUM) return ray_f64(ray_f64_fin(sxy)); - if (op == OP_WAVG) { - if (cnt <= 0 || sx == 0.0) return ray_typed_null(-RAY_F64); - return ray_f64(ray_f64_fin(sxy / sx)); - } if (op == OP_COV) { if (cnt <= 0) return ray_typed_null(-RAY_F64); double dn = (double)cnt; @@ -546,12 +586,47 @@ static ray_t* agg_pair_vec(ray_t* x, ray_t* y, uint16_t op) { return ray_f64(ray_f64_fin((sxy - ray_comom_corr(sx, sy, dn)) / (dn - 1.0))); } if (cnt < 2) return ray_typed_null(-RAY_F64); - double dn = (double)cnt; - double num = dn * sxy - sx * sy; - double dx = dn * sxx - sx * sx; - double dy = dn * syy - sy * sy; - if (dx <= 0.0 || dy <= 0.0) return ray_typed_null(-RAY_F64); - return ray_f64(ray_f64_fin(num / sqrt(dx * dy))); + double r = ray_f64_fin(ray_comom_pearson((double)cnt, sx, sy, sxx, syy, sxy)); + return r == r ? ray_f64(r) : ray_typed_null(-RAY_F64); +} + +static ray_t* agg_pair_vec(ray_t* x, ray_t* y, uint16_t op) { + const char* name = op == OP_COV ? "cov" : + op == OP_SCOV ? "scov" : + op == OP_WSUM ? "wsum" : + op == OP_WAVG ? "wavg" : "pearson_corr"; + if (!x || RAY_IS_ERR(x) || !y || RAY_IS_ERR(y)) + return ray_error("type", "%s: both arguments must be valid values", name); + if (!ray_is_vec(x) || !ray_is_vec(y)) + return ray_error("type", "%s expects two numeric vectors, got %s and %s", name, ray_type_name(x->type), ray_type_name(y->type)); + if (x->len != y->len) + return ray_error("length", "%s: vectors must have equal length, got %lld and %lld", name, (long long)x->len, (long long)y->len); + if (!agg_numeric_flat_type(x->type) || !agg_numeric_flat_type(y->type)) + return ray_error("type", "%s expects numeric vectors, got %s and %s", name, ray_type_name(x->type), ray_type_name(y->type)); + + /* cov, scov and pearson_corr sum about a pivot that follows the running + * mean (#1847, #1870), in agg_pair_comom; wsum and wavg read the raw + * sums here. */ + if (agg_is_comoment_agg(op)) return agg_pair_comom(x, y, op); + bool xn = ray_vec_may_have_nulls(x); + bool yn = ray_vec_may_have_nulls(y); + int64_t cnt = 0; + double sx = 0.0, sxy = 0.0; + for (int64_t i = 0; i < x->len; i++) { + if ((i & 65535) == 0 && ray_interrupted()) + return ray_error("cancel", "interrupted"); + if ((xn && ray_vec_is_null(x, i)) || (yn && ray_vec_is_null(y, i))) + continue; + double xv = 0.0, yv = 0.0; + agg_read_vec_f64(x, i, &xv); + agg_read_vec_f64(y, i, &yv); + sx += xv; sxy += xv * yv; + cnt++; + } + + if (op == OP_WSUM) return ray_f64(ray_f64_fin(sxy)); + if (cnt <= 0 || sx == 0.0) return ray_typed_null(-RAY_F64); + return ray_f64(ray_f64_fin(sxy / sx)); } /* Per-chunk aggregates of an integer column's chunk-zone index, or NULL: diff --git a/src/ops/agg_stream.c b/src/ops/agg_stream.c index 23cf38b52..a3ebf2635 100644 --- a/src/ops/agg_stream.c +++ b/src/ops/agg_stream.c @@ -750,7 +750,7 @@ static inline int64_t cov_read_i64(const ray_valid_t* v, int64_t i) { * value an int64. */ #define COV_SIDE_K(v, I) ((I) ? ray_comom_pivot_i((int64_t)(v)) : (double)(v)) #define COV_SIDE_D(v, k, I) ((I) ? ray_comom_d_i((int64_t)(v), (k)) : (double)(v) - (k)) -#define COV_STATE_ROW(st, xi, yi, XI, YI) do { \ +#define COV_STATE_ROW(st, xi, yi, XI, YI, SXX, SYY) do { \ if ((st)->n == 0) { \ (st)->pivx = COV_SIDE_K(xi, XI); \ (st)->pivy = COV_SIDE_K(yi, YI); \ @@ -758,12 +758,12 @@ static inline int64_t cov_read_i64(const ray_valid_t* v, int64_t i) { } \ double dx_ = COV_SIDE_D(xi, (st)->pivx, XI); \ double dy_ = COV_SIDE_D(yi, (st)->pivy, YI); \ - ray_comom_add(dx_, dy_, &(st)->sx, &(st)->sy, &(st)->sxy); \ + ray_comom_add(dx_, dy_, &(st)->sx, &(st)->sy, &(st)->sxy, SXX, SYY); \ int64_t c_ = (++(st)->n) & RAY_COMOM_N_MASK; \ if (RAY_UNLIKELY(ray_comom_due(c_))) \ ray_comom_repivot_cold(((XI) ? RAY_COMOM_IMX : 0u) | ((YI) ? RAY_COMOM_IMY : 0u), \ (double)c_, &(st)->pivx, &(st)->pivy, \ - &(st)->sx, &(st)->sy, &(st)->sxy); \ + &(st)->sx, &(st)->sy, &(st)->sxy, SXX, SYY); \ } while (0) /* One side's element `i`: an int64 (integer mode) or a double. */ @@ -771,7 +771,8 @@ static inline int64_t cov_read_i64(const ray_valid_t* v, int64_t i) { #define COV_RF(val, i) pearson_read_f64((val), (i)) /* The pairs of a batch whose sides are both valid: ROW(i, x, y), each side * read by its reader RX / RY (a tight loop for null-free I64, F64 and F32 - * pairs of one type, and F64 with I32 or I64 either way round). */ + * pairs of one type, F64 with I32 either way round in either mode, and + * F64 with I64 either way round, the I64 side in integer mode). */ #define PAIR_FOR_EACH(valx, valy, n, RX, RY, TIGHT, ROW) do { \ bool nn_ = !(valx)->has_nulls && !(valy)->has_nulls; \ if (TIGHT == 1 && nn_ && (valx)->type == RAY_I64 && (valy)->type == RAY_I64) { \ @@ -783,6 +784,12 @@ static inline int64_t cov_read_i64(const ray_valid_t* v, int64_t i) { } else if (TIGHT == 2 && nn_ && (valx)->type == RAY_F32 && (valy)->type == RAY_F32) { \ const float* xd_ = (valx)->base; const float* yd_ = (valy)->base; \ for (int64_t i = 0; i < (n); i++) ROW(i, (double)xd_[i], (double)yd_[i]); \ + } else if (TIGHT == 2 && nn_ && (valx)->type == RAY_F64 && (valy)->type == RAY_I32) { \ + const double* xd_ = (valx)->base; const int32_t* yd_ = (valy)->base; \ + for (int64_t i = 0; i < (n); i++) ROW(i, xd_[i], (double)yd_[i]); \ + } else if (TIGHT == 2 && nn_ && (valx)->type == RAY_I32 && (valy)->type == RAY_F64) { \ + const int32_t* xd_ = (valx)->base; const double* yd_ = (valy)->base; \ + for (int64_t i = 0; i < (n); i++) ROW(i, (double)xd_[i], yd_[i]); \ } else if (TIGHT == 3 && nn_ && (valx)->type == RAY_F64 && (valy)->type == RAY_I32) { \ const double* xd_ = (valx)->base; const int32_t* yd_ = (valy)->base; \ for (int64_t i = 0; i < (n); i++) ROW(i, xd_[i], (int64_t)yd_[i]); \ @@ -805,57 +812,78 @@ static inline int64_t cov_read_i64(const ray_valid_t* v, int64_t i) { } \ } while (0) -static void cov_update2(void* base, size_t stride, const uint32_t* gids, - const void* vx, const void* vy, - const ray_valid_t* valx, const ray_valid_t* valy, - int64_t n, acc_arena_t* a) { - (void)a; (void)vx; (void)vy; - #define COV_ROW(i, xv, yv, XI, YI) do { \ - cov_state* st = (cov_state*)((char*)base + (size_t)gids[i]*stride); \ - COV_STATE_ROW(st, xv, yv, XI, YI); \ - } while (0) - #define COV_ROW_II(i, xv, yv) COV_ROW(i, xv, yv, true, true) - #define COV_ROW_IF(i, xv, yv) COV_ROW(i, xv, yv, true, false) - #define COV_ROW_FI(i, xv, yv) COV_ROW(i, xv, yv, false, true) - #define COV_ROW_FF(i, xv, yv) COV_ROW(i, xv, yv, false, false) - switch (ray_comom_im(valx->type, valy->type)) { - case RAY_COMOM_IMX | RAY_COMOM_IMY: PAIR_FOR_EACH(valx, valy, n, COV_RI, COV_RI, 1, COV_ROW_II); break; - case RAY_COMOM_IMX: PAIR_FOR_EACH(valx, valy, n, COV_RI, COV_RF, 4, COV_ROW_IF); break; - case RAY_COMOM_IMY: PAIR_FOR_EACH(valx, valy, n, COV_RF, COV_RI, 3, COV_ROW_FI); break; - default: PAIR_FOR_EACH(valx, valy, n, COV_RF, COV_RF, 2, COV_ROW_FF); break; - } - #undef COV_ROW - #undef COV_ROW_II - #undef COV_ROW_IF - #undef COV_ROW_FI - #undef COV_ROW_FF +/* IMF: the integer-mode rule, ray_comom_im_all for cov / scov (their wide + * keys run faster on the integer loops), ray_comom_im for pearson_corr + * (faster on the float ones, a narrow integer side being exact as a + * double). */ +#define COMOM_UPDATE2_FN(NAME, ST, IMF) \ +static void NAME(void* base, size_t stride, const uint32_t* gids, \ + const void* vx, const void* vy, \ + const ray_valid_t* valx, const ray_valid_t* valy, \ + int64_t n, acc_arena_t* a) { \ + (void)a; (void)vx; (void)vy; \ + switch (IMF(valx->type, valy->type)) { \ + case RAY_COMOM_IMX | RAY_COMOM_IMY: \ + PAIR_FOR_EACH(valx, valy, n, COV_RI, COV_RI, 1, ROW_II); break; \ + case RAY_COMOM_IMX: \ + PAIR_FOR_EACH(valx, valy, n, COV_RI, COV_RF, 4, ROW_IF); break; \ + case RAY_COMOM_IMY: \ + PAIR_FOR_EACH(valx, valy, n, COV_RF, COV_RI, 3, ROW_FI); break; \ + default: \ + PAIR_FOR_EACH(valx, valy, n, COV_RF, COV_RF, 2, ROW_FF); break; \ + } \ } +#define COMOM_ROW(ST, SXXP, SYYP, i, xv, yv, XI, YI) do { \ + ST* st = (ST*)((char*)base + (size_t)gids[i]*stride); \ + COV_STATE_ROW(st, xv, yv, XI, YI, SXXP, SYYP); \ +} while (0) + +#define ROW_II(i, xv, yv) COMOM_ROW(cov_state, NULL, NULL, i, xv, yv, true, true) +#define ROW_IF(i, xv, yv) COMOM_ROW(cov_state, NULL, NULL, i, xv, yv, true, false) +#define ROW_FI(i, xv, yv) COMOM_ROW(cov_state, NULL, NULL, i, xv, yv, false, true) +#define ROW_FF(i, xv, yv) COMOM_ROW(cov_state, NULL, NULL, i, xv, yv, false, false) +COMOM_UPDATE2_FN(cov_update2, cov_state, ray_comom_im_all) +#undef ROW_II +#undef ROW_IF +#undef ROW_FI +#undef ROW_FF static void cov_merge(void* dd, const void* ss, acc_arena_t* a) { (void)a; cov_state* d = dd; const cov_state* s = ss; int64_t nd = d->n & RAY_COMOM_N_MASK, ns = s->n & RAY_COMOM_N_MASK; if (ns == 0) return; unsigned im = RAY_COMOM_N_IMOF(d->n | s->n); - ray_comom_merge(im, (double)nd, &d->pivx, &d->pivy, &d->sx, &d->sy, &d->sxy, - (double)ns, s->pivx, s->pivy, s->sx, s->sy, s->sxy); + ray_comom_merge(im, (double)nd, &d->pivx, &d->pivy, &d->sx, &d->sy, &d->sxy, NULL, NULL, + (double)ns, s->pivx, s->pivy, s->sx, s->sy, s->sxy, 0.0, 0.0); + d->n = RAY_COMOM_N_IM(im) | (nd + ns); +} + +/* pearson_corr (#1870): the same co-moments about the running mean, with + * the squares, in 64 bytes. */ +typedef struct { double pivx, pivy, sx, sy, sxy, sxx, syy; int64_t n; } comom_state; +static void comom_init(void* s) { memset(s, 0, sizeof(comom_state)); } +#define ROW_II(i, xv, yv) COMOM_ROW(comom_state, &st->sxx, &st->syy, i, xv, yv, true, true) +#define ROW_IF(i, xv, yv) COMOM_ROW(comom_state, &st->sxx, &st->syy, i, xv, yv, true, false) +#define ROW_FI(i, xv, yv) COMOM_ROW(comom_state, &st->sxx, &st->syy, i, xv, yv, false, true) +#define ROW_FF(i, xv, yv) COMOM_ROW(comom_state, &st->sxx, &st->syy, i, xv, yv, false, false) +COMOM_UPDATE2_FN(comom_update2, comom_state, ray_comom_im) +#undef ROW_II +#undef ROW_IF +#undef ROW_FI +#undef ROW_FF +static void comom_merge(void* dd, const void* ss, acc_arena_t* a) { + (void)a; comom_state* d = dd; const comom_state* s = ss; + int64_t nd = d->n & RAY_COMOM_N_MASK, ns = s->n & RAY_COMOM_N_MASK; + if (ns == 0) return; + unsigned im = RAY_COMOM_N_IMOF(d->n | s->n); + ray_comom_merge(im, (double)nd, &d->pivx, &d->pivy, &d->sx, &d->sy, &d->sxy, &d->sxx, &d->syy, + (double)ns, s->pivx, s->pivy, s->sx, s->sy, s->sxy, s->sxx, s->syy); d->n = RAY_COMOM_N_IM(im) | (nd + ns); } static double pearson_final_result(const void* s) { - const pearson_state* st = s; - double dn = (double)st->n; - double num = dn*st->sxy - st->sx*st->sy, - dx = dn*st->sxx - st->sx*st->sx, - dy = dn*st->syy - st->sy*st->sy; - /* dx and dy are >= 0 mathematically (Cauchy-Schwarz), but a CONSTANT - * column cancels to a small NEGATIVE residue in doubles. Relying on - * sqrt(<=0) to produce NaN only works when exactly ONE side is - * negative: with both negative the product is positive, the root is - * finite and a garbage "correlation" outside [-1,1] is emitted - * (#555). Test the two denominators separately, as the legacy keyed - * path does (group.c), and report the undefined case as null. - * - * n < 2 leaves dx = dy = 0, so the same guard covers it. */ - if (dx <= 0.0 || dy <= 0.0) return NULL_F64; - return ray_f64_fin(num / sqrt(dx*dy)); + const comom_state* st = s; + /* n < 2 or a constant side leaves no spread: the null (#555) */ + return ray_f64_fin(ray_comom_pearson((double)(st->n & RAY_COMOM_N_MASK), st->sx, st->sy, + st->sxx, st->syy, st->sxy)); } AGG_SCALAR_FINAL(pearson_final, double, ray_f64, value != value) static double cov_final_result(const void* s) { @@ -886,9 +914,9 @@ static double wavg_final_result(const void* s) { } AGG_SCALAR_FINAL(wavg_final, double, ray_f64, value != value) static const agg_vtable_t PEARSON_F64 = { - .state_size = sizeof(pearson_state), .kind = ACC_STREAMING, .out_type = RAY_F64, - .init = pearson_init, .update_batch2 = pearson_update2, - .merge = pearson_merge, .finalize = pearson_final, .finalize_value = pearson_final_value, + .state_size = sizeof(comom_state), .kind = ACC_STREAMING, .out_type = RAY_F64, + .init = comom_init, .update_batch2 = comom_update2, + .merge = comom_merge, .finalize = pearson_final, .finalize_value = pearson_final_value, }; static const agg_vtable_t COV_F64 = { .state_size = sizeof(cov_state), .kind = ACC_STREAMING, .out_type = RAY_F64, diff --git a/src/ops/group.c b/src/ops/group.c index 5a4bc4d3b..f37b79f64 100644 --- a/src/ops/group.c +++ b/src/ops/group.c @@ -5904,13 +5904,15 @@ bool ght_compute_layout(ght_layout_t* out, uint32_t n_keys, uint32_t n_aggs, af2 |= GHT_AF2_VAR; out->need_flags |= GHT_NEED_VARK; } - if (agg_ops && vslot >= 0 && agg_is_cov_agg(agg_ops[a])) { + if (agg_ops && vslot >= 0 && agg_is_comoment_agg(agg_ops[a])) { af2 |= GHT_AF2_COMOM; + if (agg_ops[a] == OP_PEARSON_CORR) af2 |= GHT_AF2_COMOM_SQ; out->need_flags |= GHT_NEED_VARK; /* a mixed pair keeps its integer side's int64 (#1847) */ if ((af & GHT_AF_F64) && agg_vecs[a] && agg_vecs2 && agg_vecs2[a]) { - if (ray_comom_int_type(agg_vecs[a]->type)) af2 |= GHT_AF2_X_I64; - if (ray_comom_int_type(agg_vecs2[a]->type)) af2 |= GHT_AF2_Y_I64; + unsigned im = ray_comom_im(agg_vecs[a]->type, agg_vecs2[a]->type); + if (im & RAY_COMOM_IMX) af2 |= GHT_AF2_X_I64; + if (im & RAY_COMOM_IMY) af2 |= GHT_AF2_Y_I64; } } if (vslot >= 0 && agg_vecs[a]) { @@ -6724,7 +6726,7 @@ static inline void init_accum_from_entry(char* row, const char* entry, double xy = x * y; memcpy(row + ly->off_sumxy + s * 8, &xy, 8); if (aflags2[a] & GHT_AF2_COMOM) { - /* cov / scov about the opening pair (#1847): it is the + /* cov / scov / pearson_corr about the opening pair (#1847): it is the * pivot (an integer pair's exactly, ray_comom_pivot_i), so * the sums start at 0 */ double pivx, pivy, dx = 0.0, dy = 0.0; @@ -6738,6 +6740,10 @@ static inline void init_accum_from_entry(char* row, const char* entry, memcpy(row + ly->off_sum + s * 8, &dx, 8); memcpy(row + ly->off_sum_y + s * 8, &dy, 8); memcpy(row + ly->off_sumxy + s * 8, &dxy, 8); + if (aflags2[a] & GHT_AF2_COMOM_SQ) { + memcpy(row + ly->off_sumsq + s * 8, &dxy, 8); /* 0 */ + memcpy(row + ly->off_sumsq_y + s * 8, &dxy, 8); + } } } /* Seed per-slot row-index bounds with the row that opened this @@ -6778,7 +6784,7 @@ static inline void ght_var_add(char* row, const ght_layout_t* ly, int8_t s, uint } } -/* A cov / scov pair (GHT_AF2_COMOM, #1847) at slots s, s+1 of an entry into +/* A cov / scov / pearson_corr pair (GHT_AF2_COMOM, #1847) at slots s, s+1 of an entry into * slot s of an HT row, the n-th pair of the slot: about the row's pivot in * off_var_k (slots s, s+1), which the first pair seeds and each due count * moves to the running mean (ray_comom_repivot); an integer pair's (no @@ -6804,9 +6810,11 @@ ght_comom_add(char* row, const ght_layout_t* ly, int8_t s, uint8_t af, uint8_t a double* sx = &ROW_WR_F64(row, ly->off_sum, s); double* sy = &ROW_WR_F64(row, ly->off_sum_y, s); double* sxy = &ROW_WR_F64(row, ly->off_sumxy, s); - ray_comom_add(dx, dy, sx, sy, sxy); + double* sxx = (af2 & GHT_AF2_COMOM_SQ) ? &ROW_WR_F64(row, ly->off_sumsq, s) : NULL; + double* syy = (af2 & GHT_AF2_COMOM_SQ) ? &ROW_WR_F64(row, ly->off_sumsq_y, s) : NULL; + ray_comom_add(dx, dy, sx, sy, sxy, sxx, syy); if (RAY_UNLIKELY(ray_comom_due(n))) - ray_comom_repivot_cold(im, (double)n, pivx, pivy, sx, sy, sxy); + ray_comom_repivot_cold(im, (double)n, pivx, pivy, sx, sy, sxy, sxx, syy); } /* Accumulate into existing group from entry's inline agg values */ @@ -8628,8 +8636,8 @@ static void radix_phase3_fn(void* ctx, uint32_t worker_id, int64_t start, int64_ * NaN (canonicalize folds to null upstream). */ if ((op == OP_PEARSON_CORR || op == OP_SCOV) && nn < 2) { v = NULL_F64; grp_set_null(ao->vec, di); break; } if ((op == OP_COV || op == OP_WAVG) && nn < 1) { v = NULL_F64; grp_set_null(ao->vec, di); break; } - /* a cov / scov slot sums doubles whatever its types (#1847) */ - double sx = sf || agg_is_cov_agg(op) ? ROW_RD_F64(row, ly->off_sum, s) + /* a co-moment slot sums doubles whatever its types (#1847) */ + double sx = sf || agg_is_comoment_agg(op) ? ROW_RD_F64(row, ly->off_sum, s) : (double)ROW_RD_I64(row, ly->off_sum, s); double sxx = ly->off_sumsq ? ROW_RD_F64(row, ly->off_sumsq, s) : 0.0; double sy = ly->off_sum_y ? ROW_RD_F64(row, ly->off_sum_y, s) : 0.0; @@ -8641,15 +8649,12 @@ static void radix_phase3_fn(void* ctx, uint32_t worker_id, int64_t start, int64_ * count otherwise. cnt here would overcount and * skew pearson/cov whenever the group has nulls. */ double dn = (double)nn; - double num = dn * sxy - sx * sy; - double dx = dn * sxx - sx * sx; - double dy = dn * syy - sy * sy; if (op == OP_WSUM) { v = sxy; break; } if (op == OP_WAVG) { if (sx == 0.0) { v = NULL_F64; break; } v = sxy / sx; break; } if (op == OP_COV) { v = (sxy - ray_comom_corr(sx, sy, dn)) / dn; break; } if (op == OP_SCOV) { v = (sxy - ray_comom_corr(sx, sy, dn)) / (dn - 1.0); break; } - if (dx <= 0.0 || dy <= 0.0) { v = NULL_F64; break; } - v = num / sqrt(dx * dy); + /* about the slot's pivot (#1870); a side with no spread is NaN */ + v = ray_comom_pearson(dn, sx, sy, sxx, syy, sxy); break; } default: v = 0.0; break; @@ -9683,10 +9688,11 @@ static inline void da_var_merge(da_accum_t* dst, size_t di, da_accum_t* src, siz src->sumsq_f64[si] = 0; } -/* A cov / scov slot (#1847) si of src into di - * of dst: src's sums re-expressed about dst's pair (ray_comom_merge), then - * left zero, as da_var_merge leaves them, for the merge that adds the rest. */ -static void da_comom_merge(da_accum_t* dst, size_t di, da_accum_t* src, size_t si) { +/* A cov / scov / pearson_corr slot (#1847, #1870) si of src into di of + * dst: src's sums re-expressed about dst's pair (ray_comom_merge), with the + * squares when sq, then left zero, as da_var_merge leaves them, for the + * merge that adds the rest. */ +static void da_comom_merge(da_accum_t* dst, size_t di, da_accum_t* src, size_t si, bool sq) { int64_t ns = src->var_n[si] & RAY_COMOM_N_MASK; if (ns == 0) return; int64_t nd = dst->var_n[di] & RAY_COMOM_N_MASK; @@ -9694,14 +9700,17 @@ static void da_comom_merge(da_accum_t* dst, size_t di, da_accum_t* src, size_t s double kxd = 0.0, kxs; if (nd) memcpy(&kxd, &dst->var_k[di], sizeof kxd); memcpy(&kxs, &src->var_k[si], sizeof kxs); + sq = sq && dst->sumsq_f64 && src->sumsq_f64; ray_comom_merge(im, (double)nd, &kxd, &dst->cov_ky[di], &dst->sum[di].f, &dst->sum_y[di], - &dst->sumxy[di], (double)ns, kxs, src->cov_ky[si], src->sum[si].f, - src->sum_y[si], src->sumxy[si]); + &dst->sumxy[di], sq ? &dst->sumsq_f64[di] : NULL, sq ? &dst->sumsq_y[di] : NULL, + (double)ns, kxs, src->cov_ky[si], src->sum[si].f, src->sum_y[si], + src->sumxy[si], sq ? src->sumsq_f64[si] : 0.0, sq ? src->sumsq_y[si] : 0.0); memcpy(&dst->var_k[di], &kxd, sizeof kxd); dst->var_n[di] = RAY_COMOM_N_IM(im) | (nd + ns); src->sum[si].f = 0; src->sum_y[si] = 0; src->sumxy[si] = 0; + if (sq) { src->sumsq_f64[si] = 0; src->sumsq_y[si] = 0; } } /* Every variance-family and co-moment slot of slots [lo, hi) (n_aggs per @@ -9714,8 +9723,8 @@ static void da_var_merge_slots(da_accum_t* dst, da_accum_t* src, size_t lo, size for (uint32_t a = 0; a < n_aggs; a++) { if (agg_op_is_var(ops[a])) da_var_merge(dst, sl * n_aggs + a, src, sl * n_aggs + a, group_fp_type(types[a])); - else if (comom && agg_is_cov_agg(ops[a])) - da_comom_merge(dst, sl * n_aggs + a, src, sl * n_aggs + a); + else if (comom && agg_is_comoment_agg(ops[a])) + da_comom_merge(dst, sl * n_aggs + a, src, sl * n_aggs + a, ops[a] == OP_PEARSON_CORR); } } @@ -9942,13 +9951,9 @@ static void emit_agg_columns(ray_t** result, ray_graph_t* g, const ray_op_ext_t* double dn = (double)cnt; if (agg_op == OP_COV) { v = (sxy - ray_comom_corr(sx, sy, dn)) / dn; break; } if (agg_op == OP_SCOV) { v = (sxy - ray_comom_corr(sx, sy, dn)) / (dn - 1.0); break; } - double num = dn * sxy - sx * sy; - double dx = dn * sxx - sx * sx; - double dy = dn * syy - sy * sy; - if (dx <= 0.0 || dy <= 0.0) { - v = NULL_F64; ray_vec_set_null(new_col, gi, true); break; - } - v = num / sqrt(dx * dy); + /* about the slot's pivot (#1870); a side with no spread is the null */ + v = ray_comom_pearson(dn, sx, sy, sxx, syy, sxy); + if (v != v) { v = NULL_F64; ray_vec_set_null(new_col, gi, true); } break; } default: v = 0.0; break; @@ -12408,28 +12413,33 @@ RAY_INLINE void da_accum_row_body(da_ctx_t* c, da_accum_t* acc, int32_t gid, int double yval = y_is_f ? yv : (double)yi; bool y_null = y_is_f ? !(yval == yval) : false; if (RAY_LIKELY(!is_null && !y_null)) { - if (acc->cov_ky && agg_is_cov_agg(op)) { - /* about the slot's pivot (#1847): an integer side's + if (acc->cov_ky && agg_is_comoment_agg(op)) { + /* about the slot's pivot (#1847, #1870): an integer side's * differences in integers, the per-side mode in var_n * (RAY_COMOM_N_IM) */ - unsigned im = (is_f ? 0u : RAY_COMOM_IMX) | (y_is_f ? 0u : RAY_COMOM_IMY); + unsigned im = ray_comom_im(c->agg_types[a], c->agg_types2[a]); + bool fx = !(im & RAY_COMOM_IMX), fy = !(im & RAY_COMOM_IMY); double pivx; int64_t* vn = &acc->var_n[idx]; if (*vn == 0) { - pivx = is_f ? xv : ray_comom_pivot_i(iv); - acc->cov_ky[idx] = y_is_f ? yval : ray_comom_pivot_i(yi); + pivx = fx ? xv : ray_comom_pivot_i(iv); + acc->cov_ky[idx] = fy ? yval : ray_comom_pivot_i(yi); memcpy(&acc->var_k[idx], &pivx, sizeof pivx); *vn = RAY_COMOM_N_IM(im); } int64_t vc = (++*vn) & RAY_COMOM_N_MASK; memcpy(&pivx, &acc->var_k[idx], sizeof pivx); double pivy = acc->cov_ky[idx]; - double dx = is_f ? xv - pivx : ray_comom_d_i(iv, pivx); - double dy = y_is_f ? yval - pivy : ray_comom_d_i(yi, pivy); - ray_comom_add(dx, dy, &acc->sum[idx].f, &acc->sum_y[idx], &acc->sumxy[idx]); + double dx = fx ? xv - pivx : ray_comom_d_i(iv, pivx); + double dy = fy ? yval - pivy : ray_comom_d_i(yi, pivy); + bool sq = op == OP_PEARSON_CORR && acc->sumsq_f64; + double* pxx = sq ? &acc->sumsq_f64[idx] : NULL; + double* pyy = sq ? &acc->sumsq_y[idx] : NULL; + ray_comom_add(dx, dy, &acc->sum[idx].f, &acc->sum_y[idx], &acc->sumxy[idx], pxx, pyy); if (RAY_UNLIKELY(ray_comom_due(vc))) { ray_comom_repivot_cold(im, (double)vc, &pivx, &acc->cov_ky[idx], - &acc->sum[idx].f, &acc->sum_y[idx], &acc->sumxy[idx]); + &acc->sum[idx].f, &acc->sum_y[idx], &acc->sumxy[idx], + pxx, pyy); memcpy(&acc->var_k[idx], &pivx, sizeof pivx); } } else { @@ -15638,32 +15648,41 @@ static inline void sg_pair_accum(ray_t* x, ray_t* y, uint16_t op, * pivot held in locals. The slice path admits no null. */ static void sg_comom_accum(ray_t* x, ray_t* y, const int64_t* rows, int64_t n, bool contig, int64_t r0, double* kxo, double* kyo, double* sx, double* sy, - double* sxy) { + double* sxy, double* sxx, double* syy) { unsigned im = ray_comom_im(x->type, y->type); bool imx = (im & RAY_COMOM_IMX) != 0, imy = (im & RAY_COMOM_IMY) != 0; bool f64 = x->type == RAY_F64 && y->type == RAY_F64; const void* xd = ray_data(x); const void* yd = ray_data(y); - double ax = 0.0, ay = 0.0, axy = 0.0, pivx = 0.0, pivy = 0.0; + double ax = 0.0, ay = 0.0, axy = 0.0, axx = 0.0, ayy = 0.0, pivx = 0.0, pivy = 0.0; + bool sq = sxx != NULL; if (n > 0) { int64_t rk = contig ? r0 : rows[0]; pivx = imx ? ray_comom_pivot_i(read_col_i64(xd, rk, x->type, x->attrs)) : sg_num_at(x, rk); pivy = imy ? ray_comom_pivot_i(read_col_i64(yd, rk, y->type, y->attrs)) : sg_num_at(y, rk); } - #define SG_COMOM_SEG(ROW) do { \ + #define SG_COMOM_SEG1(ROW, SQ) do { \ for (int64_t j_ = j; j_ < e; j_++) { \ int64_t r = contig ? r0 + j_ : rows[j_]; \ double dx, dy; \ ROW; \ ax += dx; ay += dy; axy += dx * dy; \ + if (SQ) { axx += dx * dx; ayy += dy * dy; } \ } \ } while (0) + #define SG_COMOM_SEG(ROW) do { \ + if (sq) SG_COMOM_SEG1(ROW, 1); else SG_COMOM_SEG1(ROW, 0); \ + } while (0) for (int64_t j = 0; j < n; ) { - int64_t due = j ? 2 * j : 2, e = due < n ? due : n; + int64_t due = j ? 2 * j : RAY_COMOM_DUE0, e = due < n ? due : n; if (f64) { const double* xf = (const double*)xd; const double* yf = (const double*)yd; SG_COMOM_SEG((dx = xf[r] - pivx, dy = yf[r] - pivy)); + } else if (x->type == RAY_F64 && y->type == RAY_I32 && !im) { + const double* xf = (const double*)xd; + const int32_t* yi = (const int32_t*)yd; + SG_COMOM_SEG((dx = xf[r] - pivx, dy = (double)yi[r] - pivy)); } else if (im) { SG_COMOM_SEG((dx = imx ? ray_comom_d_i(read_col_i64(xd, r, x->type, x->attrs), pivx) : sg_num_at(x, r) - pivx, @@ -15673,11 +15692,15 @@ static void sg_comom_accum(ray_t* x, ray_t* y, const int64_t* rows, int64_t n, b SG_COMOM_SEG((dx = sg_num_at(x, r) - pivx, dy = sg_num_at(y, r) - pivy)); } j = e; - if (j == due) ray_comom_repivot_cold(im, (double)j, &pivx, &pivy, &ax, &ay, &axy); + if (j == due) + ray_comom_repivot_cold(im, (double)j, &pivx, &pivy, &ax, &ay, &axy, + sq ? &axx : NULL, sq ? &ayy : NULL); } #undef SG_COMOM_SEG + #undef SG_COMOM_SEG1 *kxo = pivx; *kyo = pivy; *sx = ax; *sy = ay; *sxy = axy; + if (sq) { *sxx = axx; *syy = ayy; } } /* The value a slice's VAR/STDDEV sums are taken about (#1666): its first @@ -15722,11 +15745,12 @@ static void sg_accum_fn(void* raw, uint32_t wid, int64_t tstart, int64_t tend) { uint16_t op = c->agg_ops[a]; if (agg_is_binary_agg(op)) { double sx = 0.0, sy = 0.0, sxx = 0.0, syy = 0.0, sxy = 0.0; - if (agg_is_cov_agg(op) && c->partial_k) + if (agg_is_comoment_agg(op) && c->partial_k) /* about the task's own pivot; the fold re-centres (#1847) */ sg_comom_accum(c->agg_vecs[a], c->agg_vecs2[a], rows, n, contig, r0, &c->partial_k[2 * idx], &c->partial_k[2 * idx + 1], - &sx, &sy, &sxy); + &sx, &sy, &sxy, op == OP_PEARSON_CORR ? &sxx : NULL, + op == OP_PEARSON_CORR ? &syy : NULL); else sg_pair_accum(c->agg_vecs[a], c->agg_vecs2[a], op, rows, n, contig, r0, &sx, &sy, &sxx, &syy, &sxy); @@ -16238,14 +16262,17 @@ static ray_t* exec_group_slices(ray_graph_t* g, ray_op_t* op, ray_t* tbl, size_t di = (size_t)gi * n_aggs + a; size_t si = (size_t)ti * n_aggs + a; bool pair = agg_is_binary_agg(ext->agg_ops[a]); - if (pair && agg_is_cov_agg(ext->agg_ops[a])) { + if (pair && agg_is_comoment_agg(ext->agg_ops[a])) { /* re-centred onto the larger part's pivot (#1847) */ double ns = (double)(tasks[ti].hi - tasks[ti].lo); double nd = (double)counts[gi] - ns; unsigned im = ray_comom_im(agg_vecs[a]->type, agg_vecs2[a]->type); + bool sq = ext->agg_ops[a] == OP_PEARSON_CORR && sumsq && sumsq_y; ray_comom_merge(im, nd, &grp_k[2 * di], &grp_k[2 * di + 1], &sums[di].f, &sum_y[di], - &sumxy[di], ns, part_k[2 * si], part_k[2 * si + 1], - partials[si].f, part_sum_y[si], part_sumxy[si]); + &sumxy[di], sq ? &sumsq[di] : NULL, sq ? &sumsq_y[di] : NULL, + ns, part_k[2 * si], part_k[2 * si + 1], + partials[si].f, part_sum_y[si], part_sumxy[si], + sq ? part_sumsq[si] : 0.0, sq ? part_sumsq_y[si] : 0.0); continue; } if (pair || prod[a].enabled || ext->agg_ops[a] == OP_COUNT || @@ -19634,7 +19661,7 @@ da_path:; else if (agg_is_binary_agg(aop)) { need_flags |= DA_NEED_SUM; need_flags |= DA_NEED_SUMSQ; need_flags |= DA_NEED_PAIR; /* a cov / scov slot keeps its pair in var_k/cov_ky (#1847) */ - if (agg_is_cov_agg(aop)) { need_flags |= DA_NEED_VARK; da_need_comom = true; } + if (agg_is_comoment_agg(aop)) { need_flags |= DA_NEED_VARK; da_need_comom = true; } } else if (aop == OP_MIN) need_flags |= DA_NEED_MIN; else if (aop == OP_MAX) need_flags |= DA_NEED_MAX; @@ -23298,8 +23325,8 @@ sequential_fallback:; case OP_WAVG: { if ((agg_op == OP_PEARSON_CORR || agg_op == OP_SCOV) && nn < 2) { v = NULL_F64; ray_vec_set_null(new_col, gi, true); break; } if ((agg_op == OP_COV || agg_op == OP_WAVG) && nn < 1) { v = NULL_F64; ray_vec_set_null(new_col, gi, true); break; } - /* a cov / scov slot sums doubles whatever its types (#1847) */ - double sx = is_f64 || agg_is_cov_agg(agg_op) ? ROW_RD_F64(row, ly->off_sum, s) + /* a co-moment slot sums doubles whatever its types (#1847) */ + double sx = is_f64 || agg_is_comoment_agg(agg_op) ? ROW_RD_F64(row, ly->off_sum, s) : (double)ROW_RD_I64(row, ly->off_sum, s); double sxx = ly->off_sumsq ? ROW_RD_F64(row, ly->off_sumsq, s) : 0.0; double sy = ly->off_sum_y ? ROW_RD_F64(row, ly->off_sum_y, s) : 0.0; @@ -23308,15 +23335,12 @@ sequential_fallback:; /* Divisor = number of accumulated (x,y) pairs (see the * radix emitter): nn on nullable layouts, cnt otherwise. */ double dn = (double)nn; - double num = dn * sxy - sx * sy; - double dx = dn * sxx - sx * sx; - double dy = dn * syy - sy * sy; if (agg_op == OP_WSUM) { v = sxy; break; } if (agg_op == OP_WAVG) { if (sx == 0.0) { v = NULL_F64; break; } v = sxy / sx; break; } if (agg_op == OP_COV) { v = (sxy - ray_comom_corr(sx, sy, dn)) / dn; break; } if (agg_op == OP_SCOV) { v = (sxy - ray_comom_corr(sx, sy, dn)) / (dn - 1.0); break; } - if (dx <= 0.0 || dy <= 0.0) { v = NULL_F64; break; } - v = num / sqrt(dx * dy); + /* about the slot's pivot (#1870); a side with no spread is NaN */ + v = ray_comom_pearson(dn, sx, sy, sxx, syy, sxy); break; } default: v = 0.0; break; diff --git a/src/ops/internal.h b/src/ops/internal.h index 2629d1ccf..7ab56ff3c 100644 --- a/src/ops/internal.h +++ b/src/ops/internal.h @@ -2307,13 +2307,17 @@ static inline double ray_var_final(uint16_t op, int64_t n, double s1, double s2, * canonicalizes int y nulls (NaN in F64-packed * entries, NULL_I64 in int-packed ones). */ #define GHT_AF2_VAR 8u /* VAR/STDDEV slot: accumulates about off_var_k */ -#define GHT_AF2_COMOM 16u /* cov/scov slot (#1847): a pair whose +#define GHT_AF2_COMOM 16u /* cov/scov/pearson_corr slot (#1847): a pair whose * co-moments accumulate about the pivot in * off_var_k at slots s (x) and s+1 (y) */ #define GHT_AF2_X_I64 32u /* a COMOM slot packed F64 (the other side is a - * float) whose x is an integer column: its - * entry slot keeps the int64 (#1847) */ + * float) whose x is a 64-bit integer column + * (ray_comom_im): its entry slot keeps the + * int64 (#1847) */ #define GHT_AF2_Y_I64 64u /* the same for the y side */ +#define GHT_AF2_COMOM_SQ 128u /* a COMOM slot that keeps the squares too, in + * off_sumsq and off_sumsq_y (pearson_corr, + * #1870) */ /* key_flags bits */ #define GHT_KEYF_WIDE 1u /* key does not fit in 8 B (RAY_GUID / RAY_STR) */ #define GHT_KEYF_INLINE_STR 2u /* key stores a 16 B ray_str_t descriptor inline */ diff --git a/src/ops/ops.h b/src/ops/ops.h index a6509d4e3..a4c8c9d73 100644 --- a/src/ops/ops.h +++ b/src/ops/ops.h @@ -380,14 +380,16 @@ static inline bool agg_is_binary_agg(uint16_t op) { op == OP_WSUM || op == OP_WAVG; } -/* cov and scov sum about a pivot pair (#1847) that follows the running - * mean, so a group of large values close together keeps sums the size of - * its spread. pearson_corr, wsum and wavg read the raw sums. +/* cov, scov (#1847) and pearson_corr (#1870) sum about a pivot pair that + * follows the running mean, so a group of large values close together + * keeps sums the size of its spread. wsum and wavg read the raw sums. * * The state of n pairs: the pivot (pivx, pivy) and the sums of the differences - * dx = x - pivx, dy = y - pivy: sx = sum dx, sy = sum dy, sxy = sum dx*dy. + * dx = x - pivx, dy = y - pivy: sx = sum dx, sy = sum dy, sxy = sum dx*dy, and + * for pearson_corr sxx = sum dx^2, syy = sum dy^2. The helpers take sxx + * and syy as pointers, NULL for cov and scov. * - * The pivot starts at the first pair. At every power of two from 2 + * The pivot starts at the first pair. At every power of two from 8 * (ray_comom_due) it moves to the running mean, pivot + sum/n, and the sums * are re-expressed about it exactly (ray_comom_repivot): after the move at * the largest power of two up to n the pivot is the mean of at least half @@ -399,19 +401,21 @@ static inline bool agg_is_binary_agg(uint16_t op) { * formed so that no intermediate passes DBL_MAX where the sums do not * (ray_comom_corr). * - * Integer mode, per side (RAY_COMOM_IMX, RAY_COMOM_IMY: that side an - * integer or temporal column): the side's pivot slot holds an int64 + * Integer mode, per side (RAY_COMOM_IMX, RAY_COMOM_IMY, ray_comom_im): + * both sides when both are integer or temporal columns, and beside a float + * side a 64-bit integer side only. The side's pivot slot holds an int64 * exactly (its bits, ray_comom_pivot_i), first the first value and then the * mean rounded to an integer, anywhere in the int64 range, and a difference * is taken in integers (one rounding, to the double). Integer data keeps * integer-valued sums, and a constant column, INT64_MAX included, sums - * exact zeros. A float side takes its differences in doubles; a mixed pair - * keeps each side's own arithmetic. + * exact zeros. A float side, and a narrower integer side beside it, takes + * its differences in doubles, exact for such an integer. * * Values from about 1e150 can overflow a difference, a product or the - * final correction: no answer is promised for them. */ -static inline bool agg_is_cov_agg(uint16_t op) { - return op == OP_COV || op == OP_SCOV; + * final correction, and spreads below about 1e-150 underflow the products + * and squares: no answer is promised at either end. */ +static inline bool agg_is_comoment_agg(uint16_t op) { + return op == OP_COV || op == OP_SCOV || op == OP_PEARSON_CORR; } /* Integer mode for one side's type: an integer or a temporal. */ @@ -421,9 +425,28 @@ static inline bool ray_comom_int_type(int8_t t) { } #define RAY_COMOM_IMX 1u #define RAY_COMOM_IMY 2u -static inline unsigned ray_comom_im(int8_t tx, int8_t ty) { +/* A 64-bit integer side (I64, TIMESTAMP, TIMESPAN): its values and their + * differences need not fit a double. */ +static inline bool ray_comom_wide_int_type(int8_t t) { + return t == RAY_I64 || t == RAY_TIMESTAMP || t == RAY_TIMESPAN; +} +/* The pair's per-side integer mode: both sides when both are integers (so + * integer data keeps integer-valued sums); beside a float side, only a + * 64-bit integer side. A narrower integer side (I32, I16, U8, BOOL, DATE, + * TIME) is exact as a double, and so are its differences, so beside a float + * it takes the float arithmetic, at the float's cost (#1870). */ +/* Every integer or temporal side in integer mode, beside a float side too: + * the v2 engine's rule, whose integer loops run its scattered wide keys + * faster than the float ones. */ +static inline unsigned ray_comom_im_all(int8_t tx, int8_t ty) { return (ray_comom_int_type(tx) ? RAY_COMOM_IMX : 0u) | (ray_comom_int_type(ty) ? RAY_COMOM_IMY : 0u); } +static inline unsigned ray_comom_im(int8_t tx, int8_t ty) { + bool ix = ray_comom_int_type(tx), iy = ray_comom_int_type(ty); + if (ix && iy) return RAY_COMOM_IMX | RAY_COMOM_IMY; + return (ix && ray_comom_wide_int_type(tx) ? RAY_COMOM_IMX : 0u) | + (iy && ray_comom_wide_int_type(ty) ? RAY_COMOM_IMY : 0u); +} /* A state's count with the integer-mode mask in bits 61-62, where the state * has no other room to say which kind its pivot slots hold (the v2 state, @@ -452,16 +475,22 @@ static inline double ray_comom_d_i(int64_t x, double kslot) { return (double)((__int128)x - (__int128)k); } -/* One pair's differences into the sums. */ -static inline void ray_comom_add(double dx, double dy, double* sx, double* sy, double* sxy) { +/* One pair's differences into the sums (sxx, syy NULL for cov). */ +static inline void ray_comom_add(double dx, double dy, double* sx, double* sy, double* sxy, + double* sxx, double* syy) { *sx += dx; *sy += dy; *sxy += dx * dy; + if (sxx) *sxx += dx * dx; + if (syy) *syy += dy * dy; } /* Sums of n pairs about a pivot re-expressed about that pivot plus (ex, ey): - * sxy' = sxy - ex*sy - ey*sx + n*ex*ey sx' = sx - n*ex sy' = sy - n*ey */ + * sxy' = sxy - ex*sy - ey*sx + n*ex*ey sx' = sx - n*ex sy' = sy - n*ey + * sxx' = sxx - 2*ex*sx + n*ex^2 (and syy', when they are kept) */ static inline void ray_comom_shift(double n, double* sx, double* sy, double* sxy, - double ex, double ey) { + double* sxx, double* syy, double ex, double ey) { *sxy = *sxy - ex * *sy - ey * *sx + n * ex * ey; + if (sxx) *sxx = *sxx - 2.0 * ex * *sx + n * ex * ex; + if (syy) *syy = *syy - 2.0 * ey * *sy + n * ey * ey; *sx -= n * ex; *sy -= n * ey; } @@ -538,12 +567,13 @@ static inline void ray_comom_move_side(bool im, double* k, double m, double* hi, /* The sums of n pairs about the pivot slot pair (pivx, pivy) re-expressed about * that pivot moved by about (mx, my), each side in its own mode. */ static inline void ray_comom_move(unsigned im, double n, double* pivx, double* pivy, double* sx, - double* sy, double* sxy, double mx, double my) { + double* sy, double* sxy, double* sxx, double* syy, + double mx, double my) { double hx, lx, hy, ly; ray_comom_move_side((im & RAY_COMOM_IMX) != 0, pivx, mx, &hx, &lx); ray_comom_move_side((im & RAY_COMOM_IMY) != 0, pivy, my, &hy, &ly); - ray_comom_shift(n, sx, sy, sxy, hx, hy); - if (lx != 0.0 || ly != 0.0) ray_comom_shift(n, sx, sy, sxy, lx, ly); + ray_comom_shift(n, sx, sy, sxy, sxx, syy, hx, hy); + if (lx != 0.0 || ly != 0.0) ray_comom_shift(n, sx, sy, sxy, sxx, syy, lx, ly); } /* The final correction sx*sy/n of the finalizers. The product is formed @@ -556,23 +586,36 @@ static inline double ray_comom_corr(double sx, double sy, double dn) { } /* The counts at which the pivot moves to the running mean: every power of - * two from 2. */ -static inline bool ray_comom_due(int64_t n) { return n >= 2 && (n & (n - 1)) == 0; } + * two from RAY_COMOM_DUE0 = 8. + * + * Why the bound holds. After the move at the largest power of two P <= n + * the pivot is the mean of the first P >= n/2 pairs, within a standard + * deviation of the final mean, so the sums carry the rounding of n terms of + * the spread's size: about 3*n*u of it for cov. Below 8 pairs the pivot + * is the first pair, at some distance d from the mean of those m < 8 pairs; + * one pair that far makes their variance at least d^2/m, so (d/sigma)^2 <= + * m < 8, and the correction sx*sy/n is at most 8 times the spread's size: + * it adds about 8u, below the 3*n*u term from n = 3 on. The first move at + * 8 then re-expresses those sums exactly, as every move does. Starting at + * 8 rather than 2 saves three moves a group, most of the moves of a group + * of a few dozen pairs (#1870). */ +#define RAY_COMOM_DUE0 8 +static inline bool ray_comom_due(int64_t n) { return n >= RAY_COMOM_DUE0 && (n & (n - 1)) == 0; } /* At a due count n (a power of two, so sum/n is exact): the pivot moves to * the mean of the n pairs. */ static inline void ray_comom_repivot(unsigned im, double n, double* pivx, double* pivy, double* sx, - double* sy, double* sxy) { + double* sy, double* sxy, double* sxx, double* syy) { double inv = 1.0 / n; - ray_comom_move(im, n, pivx, pivy, sx, sy, sxy, *sx * inv, *sy * inv); + ray_comom_move(im, n, pivx, pivy, sx, sy, sxy, sxx, syy, *sx * inv, *sy * inv); } /* ray_comom_repivot out of line, for the row loops (one copy per * translation unit). */ static __attribute__((noinline, unused)) void ray_comom_repivot_cold(unsigned im, double n, double* pivx, double* pivy, double* sx, double* sy, - double* sxy) { - ray_comom_repivot(im, n, pivx, pivy, sx, sy, sxy); + double* sxy, double* sxx, double* syy) { + ray_comom_repivot(im, n, pivx, pivy, sx, sy, sxy, sxx, syy); } /* The exact distance b - a of two pivot slots of one side, as hi + lo. */ @@ -597,11 +640,13 @@ static inline void ray_comom_kdiff(bool im, double b, double a, double* hi, doub * caller adds the counts. */ static __attribute__((noinline, unused)) void ray_comom_merge(unsigned im, double nd, double* pivx, double* pivy, double* sx, double* sy, - double* sxy, double ns, double kxs, double kys, double sxs, double sys, - double sxys) { + double* sxy, double* sxx, double* syy, double ns, double kxs, double kys, + double sxs, double sys, double sxys, double sxxs, double syys) { if (ns <= 0) return; if (nd <= 0) { *pivx = kxs; *pivy = kys; *sx = sxs; *sy = sys; *sxy = sxys; + if (sxx) *sxx = sxxs; + if (syy) *syy = syys; return; } if (ns > nd) { @@ -610,15 +655,36 @@ ray_comom_merge(unsigned im, double nd, double* pivx, double* pivy, double* sx, t = *pivx; *pivx = kxs; kxs = t; t = *pivy; *pivy = kys; kys = t; t = *sx; *sx = sxs; sxs = t; t = *sy; *sy = sys; sys = t; t = *sxy; *sxy = sxys; sxys = t; + if (sxx) { t = *sxx; *sxx = sxxs; sxxs = t; } + if (syy) { t = *syy; *syy = syys; syys = t; } t = nd; nd = ns; ns = t; } /* the source's sums about its pivot ks re-expressed about kd = ks + (kd - ks) */ double hx, lx, hy, ly; ray_comom_kdiff((im & RAY_COMOM_IMX) != 0, *pivx, kxs, &hx, &lx); ray_comom_kdiff((im & RAY_COMOM_IMY) != 0, *pivy, kys, &hy, &ly); - ray_comom_shift(ns, &sxs, &sys, &sxys, hx, hy); - if (lx != 0.0 || ly != 0.0) ray_comom_shift(ns, &sxs, &sys, &sxys, lx, ly); + double* pxx = sxx ? &sxxs : NULL; + double* pyy = syy ? &syys : NULL; + ray_comom_shift(ns, &sxs, &sys, &sxys, pxx, pyy, hx, hy); + if (lx != 0.0 || ly != 0.0) ray_comom_shift(ns, &sxs, &sys, &sxys, pxx, pyy, lx, ly); *sx += sxs; *sy += sys; *sxy += sxys; + if (sxx) *sxx += sxxs; + if (syy) *syy += syys; +} + +/* pearson_corr of n pairs from their sums of differences about any pivot: + * (sxy - sx*sy/n) / sqrt((sxx - sx^2/n) * (syy - sy^2/n)), each correction + * by ray_comom_corr and the root of each side taken apart, so no + * intermediate passes DBL_MAX where the sums do not. A side with no + * spread (a constant column, or fewer than two pairs) is NaN, the null. */ +static inline double ray_comom_pearson(double dn, double sx, double sy, double sxx, + double syy, double sxy) { + double vx = sxx - ray_comom_corr(sx, sx, dn); + double vy = syy - ray_comom_corr(sy, sy, dn); + if (!(vx > 0.0) || !(vy > 0.0)) return __builtin_nan(""); + double r = (sxy - ray_comom_corr(sx, sy, dn)) / (__builtin_sqrt(vx) * __builtin_sqrt(vy)); + /* rounding can carry a perfect correlation a few ulps past 1 */ + return r > 1.0 ? 1.0 : r < -1.0 ? -1.0 : r; } static inline bool agg_is_truth_agg(uint16_t op) { diff --git a/test/rfl/agg/pearson_large_magnitude.rfl b/test/rfl/agg/pearson_large_magnitude.rfl new file mode 100644 index 000000000..c78a9b70d --- /dev/null +++ b/test/rfl/agg/pearson_large_magnitude.rfl @@ -0,0 +1,71 @@ +;; pearson_corr is translation-invariant: shifting both columns by a +;; constant must not change it. It was computed from the raw sums, +;; (n*sxy - sx*sy) / sqrt((n*sxx - sx^2)(n*syy - sy^2)), which cancel to +;; noise once the values are large next to their spread: 1e8 + [0 1 2 3] +;; against 7 - 2x gave the null where the answer is -1, by: gave numbers +;; outside [-1, 1] that changed with the worker count, and a constant 3e38 +;; column gave 1 (#1870). It now sums about the running mean, on every +;; route, as cov and scov do. +(set n 200000) +(set Y (+ 1e8 (as 'F64 (% (til n) 4)))) +(set Z (- 7.0 (* 2.0 Y))) +(pearson_corr Y Z) -- -1.0 +(set TY (table [k x y] (list (% (til n) 3) Y Z))) +(at (select {r: (pearson_corr x y) from: TY by: k}) 'r) -- [-1.0 -1.0 -1.0] +(at (select {r: (pearson_corr x y) from: TY}) 'r) -- [-1.0] +(at (select {r: (pearson_corr x y) from: TY by: k where: (> x 0.0)}) 'r) -- [-1.0 -1.0 -1.0] +(set TH (table [k x y] (list (div (til n) 4) Y Z))) +(distinct (at (select {r: (pearson_corr x y) from: TH by: k}) 'r)) -- [-1.0] + +;; a constant column has no correlation: the null, F32 at 3e38 included +(pearson_corr (take 3e38e n) (take 3e38e n)) -- 0Nf +(at (select {r: (pearson_corr x x) from: (table [k x] (list (take 'a n) (take 3e38e n))) by: k}) 'r) -- [0Nf] +(pearson_corr (take 9223372036854775807 1000) (til 1000)) -- 0Nf + +;; integers past 2^53: their differences in integers, so the low bits stay +(set XI [10000000000000000 10000000000000001 10000000000000002 10000000000000003]) +(pearson_corr XI [0 1 2 3]) -- 1.0 +(pearson_corr XI [0.0 1.0 2.0 3.0]) -- 1.0 +(set TI (table [g x y] (list (take 0 120000) (take XI 120000) (take [0 1 2 3] 120000)))) +(at (select {r: (pearson_corr x y) from: TI}) 'r) -- [1.0] +(at (select {r: (pearson_corr x y) from: TI by: g}) 'r) -- [1.0] +(at (select {r: (pearson_corr x y) from: TI by: g where: (>= y 0)}) 'r) -- [1.0] + +;; the index-slice route and a parted table +(set S (take ['a 'b 'c] n)) +(set TS (table [s x y] (list (.attr.set 'grouped S) Y Z))) +(at (select {r: (pearson_corr x y) from: TS by: s where: (in s ['a 'b])}) 'r) -- [-1.0 -1.0] +(.sys.exec "rm -rf /tmp/rf_pearson_large") +(.db.splayed.set "/tmp/rf_pearson_large/2024.01.01/t/" (table [k x y] (list (% (til 1000) 3) (take Y 1000) (take Z 1000)))) +(.db.splayed.set "/tmp/rf_pearson_large/2024.01.02/t/" (table [k x y] (list (% (til 1000) 3) (take Y 1000) (take Z 1000)))) +(set PT (.db.parted.get "/tmp/rf_pearson_large/" 't)) +(at (select {r: (pearson_corr x y) from: PT}) 'r) -- [-1.0] +(at (select {r: (pearson_corr x y) from: PT by: k}) 'r) -- [-1.0 -1.0 -1.0] +(.sys.exec "rm -rf /tmp/rf_pearson_large") + +;; outliers at rows 0 and 63 among small values leave no pivot far from the +;; mean: the correlation of x with 2x + 1 is 1 +(set X4 (as 'F64 (map (fn [i] (if (in i [0 63]) 1e8 (as 'F64 (% i 5)))) (til 120000)))) +(< (abs (- (pearson_corr X4 (+ (* 2.0 X4) 1.0)) 1.0)) 1e-12) -- true +(< (abs (- (first (at (select {r: (pearson_corr x y) from: (table [g x y] (list (take 0 120000) X4 (+ (* 2.0 X4) 1.0))) by: g}) 'r)) 1.0)) 1e-12) -- true + +;; too few pairs, and the ordinary case, keep their answers +(pearson_corr [1.0] [2.0]) -- 0Nf +(pearson_corr [1 2 3] [2 4 6]) -- 1.0 +(pearson_corr [1 2 3] [5 5 5]) -- 0Nf + +;; spreads below about 1e-150 underflow the squares and products: no answer +;; is promised there (the docs' lower limit); they must not fail +(pearson_corr [0.0 1e-200] [0.0 1e-200]) +(pearson_corr [0.0 1e-160 2e-160] [0.0 1e-160 3e-160]) +(cov [0.0 1e-160 2e-160] [0.0 1e-160 3e-160]) +(select {p: (pearson_corr x y) c: (cov x y) from: (table [g x y] (list [0 0 0] [0.0 1e-160 2e-160] [0.0 1e-160 3e-160])) by: g}) + +;; a narrow integer side beside a float side takes the float arithmetic, +;; exact as a double: an I32 column against F64 gives the same correlation +(set XJ (as 'I32 (% (til 100000) 37))) +(set YJ (+ 1e8 (* 2.0 (as 'F64 XJ)))) +(pearson_corr XJ YJ) -- 1.0 +(pearson_corr YJ XJ) -- 1.0 +(at (select {r: (pearson_corr x y) from: (table [g x y] (list (% (til 100000) 7) XJ YJ)) by: g}) 'r) -- [1.0 1.0 1.0 1.0 1.0 1.0 1.0] + diff --git a/test/test_agg_contract.c b/test/test_agg_contract.c index 3b8cd5fe4..252c0f4bb 100644 --- a/test/test_agg_contract.c +++ b/test/test_agg_contract.c @@ -6729,7 +6729,7 @@ static test_result_t test_timespan_key_v2_route(void) { PASS(); } -/* cov and scov against an independent two-pass reference in double-double +/* cov, scov and pearson_corr against an independent two-pass reference in double-double * arithmetic (about 106 bits), on every route: the direct call, the default * v2 route, the legacy direct-array and hash/radix routes (route 1, 2), * keyless, by a low- and a high-cardinality key, with and without where:, @@ -6748,12 +6748,14 @@ static test_result_t test_timespan_key_v2_route(void) { * * The tolerance is 1e-9 of the pair's spread, sqrt(var x * var y), for any * order of the rows: the sums are taken about a pivot that moves to the - * running mean at every power of two (a merge re-expresses the smaller + * running mean at every power of two from 8 (a merge re-expresses the smaller * part about the larger part's pivot), so they carry the rounding of a sum * of n terms of the spread's size, at most about 3*n*u of the spread * (u = 2^-53): 4e-11 at these 120,000 rows, within the tolerance. The * bound grows with n, so 1e-9 holds up to about 3 million rows a group, - * not beyond. A constant side gives 0 exactly. The reference scales each side by a power of two first, so + * not beyond. pearson_corr is checked to 1e-9 of the correlation (its + * bound about 6*n*u, 8e-11 here), and must be the null exactly where a side + * has no spread. A constant side gives cov 0 exactly. The reference scales each side by a power of two first, so * its squares never overflow. */ typedef struct { double hi, lo; } cdd_t; static cdd_t cdd_qsum(double a, double b) { double s = a + b; return (cdd_t){ s, b - (s - a) }; } @@ -6905,7 +6907,8 @@ static void comom_ref_build(ray_t* x, ray_t* y, const int64_t* gid, int64_t n, i * ref[group] for groups 0..ng (keyed by column 0 when keyed); unchecked: a * side reaches 1e150, where no answer is promised. */ static test_result_t comom_check(ray_t* out, const char* q, bool keyed, const comom_ref_t* ref, - int64_t ng, int ex, int ey, const char* tag, bool unchecked) { + int64_t ng, int ex, int ey, const char* tag, bool unchecked, + const char* cols) { TEST_ASSERT_FMT(out && !RAY_IS_ERR(out), "%s %s failed: %s", tag, q, out ? ray_err_code(out) : "NULL"); int64_t rows = out->type == RAY_TABLE ? ray_table_nrows(out) : 1; TEST_ASSERT_FMT(rows == ng, "%s %s: %lld groups", tag, q, (long long)rows); @@ -6922,29 +6925,30 @@ static test_result_t comom_check(ray_t* out, const char* q, bool keyed, const co const comom_ref_t* e = &ref[g]; double cxx = e->cxx.hi, cyy = e->cyy.hi; double scale = sqrt(cxx / e->n) * sqrt(cyy / e->n); /* scaled units */ - double want[2] = { cdd_div(e->cxy, e->n).hi, e->n > 1 ? cdd_div(e->cxy, e->n - 1).hi : 0 }; - for (int a = 0; a < 2; a++) { + for (int a = 0; cols[a]; a++) { + char k = cols[a]; /* c cov, s scov, p pearson_corr */ double got; - bool isnull; if (out->type == RAY_TABLE) { ray_t* col = ray_table_get_col_idx(out, (keyed ? 1 : 0) + a); got = ((double*)ray_data(col))[r]; - isnull = got != got; } else { - got = out->f64; isnull = got != got; /* the direct call answers one atom (column c only) */ - if (a > 0) break; + got = out->f64; /* the direct call answers one atom */ } - if (e->n < (a == 0 ? 1 : 2)) { - TEST_ASSERT_FMT(isnull, "%s %s group %lld agg %d: %.17g, want the null", tag, q, (long long)g, a, got); + bool isnull = got != got; + bool want_null = e->n < (k == 'c' ? 1 : 2) || (k == 'p' && (!(cxx > 0) || !(cyy > 0))); + if (want_null) { + TEST_ASSERT_FMT(isnull, "%s %s group %lld agg %c: %.17g, want the null", tag, q, (long long)g, k, got); continue; } if (unchecked) continue; - TEST_ASSERT_FMT(!isnull, "%s %s group %lld agg %d: the null, want %.17g", tag, q, (long long)g, a, - ldexp(want[a], ex + ey)); - double gs = ldexp(got, -(ex + ey)); - double tol = 1e-9 * scale + 1e-300; - TEST_ASSERT_FMT(fabs(gs - want[a]) <= tol, "%s %s group %lld agg %d: got %.17g want %.17g", - tag, q, (long long)g, a, got, ldexp(want[a], ex + ey)); + double want = k == 'c' ? cdd_div(e->cxy, e->n).hi : k == 's' ? cdd_div(e->cxy, e->n - 1).hi + : e->cxy.hi / (sqrt(cxx) * sqrt(cyy)); + TEST_ASSERT_FMT(!isnull, "%s %s group %lld agg %c: the null, want %.17g", tag, q, (long long)g, k, + k == 'p' ? want : ldexp(want, ex + ey)); + double gs = k == 'p' ? got : ldexp(got, -(ex + ey)); + double tol = k == 'p' ? 1e-9 : 1e-9 * scale + 1e-300; + TEST_ASSERT_FMT(fabs(gs - want) <= tol, "%s %s group %lld agg %c: got %.17g want %.17g", + tag, q, (long long)g, k, got, k == 'p' ? want : ldexp(want, ex + ey)); } } PASS(); @@ -7037,25 +7041,26 @@ static test_result_t test_comoment_large_magnitude(void) { for (int where = 0; where < 2; where++) for (int route = 0; route <= 2; route++) { char q[256]; - snprintf(q, sizeof q, "(select {c:(cov x y) s:(scov x y) " + snprintf(q, sizeof q, "(select {c:(cov x y) s:(scov x y) p:(pearson_corr x y) " "from:comt%s%s%s})", kf ? " by:" : "", kf ? keys[kf] : "", where ? " where:(>= klo 0)" : ""); ray_group_test_route(route); ray_t* out = ray_eval_str(q); ray_group_test_route(0); - test_result_t tr = comom_check(out, q, kf > 0, ref, ng, ex, ey, tag, big); + test_result_t tr = comom_check(out, q, kf > 0, ref, ng, ex, ey, tag, big, "csp"); ray_release(out); if (tr.status != TEST_PASS) { free(ref); return tr; } } static const char* const extra[2][3] = { { "(cov (at comt 'x) (at comt 'y))", - "(select {c:(cov x y) s:(scov x y) from:comp})", NULL }, - { "(select {c:(cov x y) s:(scov x y) from:comts by:sk where:(in sk ['a 'b 'c])})", - "(select {c:(cov x y) s:(scov x y) from:comp by:klo})", NULL }, + "(select {c:(cov x y) s:(scov x y) p:(pearson_corr x y) from:comp})", NULL }, + { "(select {c:(cov x y) s:(scov x y) p:(pearson_corr x y) from:comts by:sk where:(in sk ['a 'b 'c])})", + "(select {c:(cov x y) s:(scov x y) p:(pearson_corr x y) from:comp by:klo})", NULL }, }; for (int j = 0; kf < 2 && extra[kf][j]; j++) { ray_t* out = ray_eval_str(extra[kf][j]); - test_result_t tr = comom_check(out, extra[kf][j], kf > 0, ref, ng, ex, ey, tag, big); + test_result_t tr = comom_check(out, extra[kf][j], kf > 0, ref, ng, ex, ey, tag, big, + strncmp(extra[kf][j], "(cov", 4) == 0 ? "c" : "csp"); ray_release(out); if (tr.status != TEST_PASS) { free(ref); return tr; } } @@ -7126,7 +7131,7 @@ static test_result_t test_comoment_alloc_fail(void) { } -/* A seeded randomized search for cov and scov against the double-double +/* A seeded randomized search for cov, scov and pearson_corr against the double-double * reference (#1847): each case draws a type pair (F64, F32, I64, I32, and * mixed I64 x F64, F64 x I64, I32 x F64), a magnitude up to 1e149 (1e37 for * F32, int64's range for an integer side), a spread relative to it down to 1e-15, a @@ -7136,7 +7141,8 @@ static test_result_t test_comoment_alloc_fail(void) { * and a high-cardinality column with and without where:, under routes 0, 1 * and 2, and an index slice, at 1 and 4 workers. Every cell must be within * 1e-9 of its group's spread: groups hold at most 70,000 rows, where the - * rounding bound of a sum of n terms, about 3*n*u of the spread, is 2.3e-11. COMOM_SEARCH_CASES cases from COMOM_SEARCH_SEED. */ + * rounding bound of a sum of n terms, about 3*n*u of the spread, is 2.3e-11 + * (pearson_corr: 1e-9 of the correlation, its bound about 6*n*u). COMOM_SEARCH_CASES cases from COMOM_SEARCH_SEED. */ #ifndef COMOM_SEARCH_CASES #define COMOM_SEARCH_CASES 24 #endif @@ -7156,7 +7162,9 @@ static int comom_cmp_d(const void* a, const void* b) { } /* One side's values: base + spread * u, outliers at the order's places, * reordered (0 shuffled, 1 sorted, 2 reversed, 3 outliers first, 4 last, - * 5 at the powers of two, 6 two alternating clusters, 7 at random rows). + * 5 at the powers of two, 6 two alternating clusters, 7 at random rows, + * 8 the first 7 rows, 9 rows 1 to 8: the rows about the schedule's first + * move at 8). * A float side's magnitude is drawn up to maxmag, a third of the time from * its top decade; an integer side is built in int64 arithmetic (vi), a * third of the time near INT64_MAX or INT64_MIN with outliers at the other @@ -7175,6 +7183,8 @@ static void comom_search_side(uint64_t* st, double* v, int64_t* vi, int64_t n, b else if (order == 4) o = i >= n - nout; else if (order == 5) o = i > 0 && (i & (i - 1)) == 0; else if (order == 6) o = (i % 2) != 0; + else if (order == 8) o = i < 7; /* the 7 pairs before the first move */ + else if (order == 9) o = i >= 1 && i <= 8; /* rows 1 to 8, about the first move */ else o = (int64_t)(comom_su(st) * (double)n) < nout; rank[i] = o ? -1 - j : j; } @@ -7241,7 +7251,7 @@ static test_result_t test_comoment_random_search(void) { for (int c = 0; c < COMOM_SEARCH_CASES; c++) { int64_t n = (c % 4 == 0) ? 70000 : (c % 4 == 1) ? 20000 : (c % 4 == 2) ? 4000 : 777; int pair = (int)(comom_sm(&st) % 7); - int order = (int)(comom_sm(&st) % 8); + int order = (int)(comom_sm(&st) % 10); bool nulls = comom_su(&st) < 0.25; int64_t nhi = n / 4 + 1; int64_t* perm = malloc((size_t)n * sizeof(int64_t)); @@ -7301,31 +7311,35 @@ static test_result_t test_comoment_random_search(void) { for (int where = 0; where < 2; where++) for (int route = 0; route <= 2; route++) { char q[256]; - snprintf(q, sizeof q, "(select {c:(cov x y) s:(scov x y) from:comr%s%s})", + snprintf(q, sizeof q, "(select {c:(cov x y) s:(scov x y) p:(pearson_corr x y) from:comr%s%s})", kf == 0 ? "" : kf == 1 ? " by:klo" : " by:khi", where ? " where:(>= klo 0)" : ""); ray_group_test_route(route); ray_t* out = ray_eval_str(q); ray_group_test_route(0); - test_result_t tr = comom_check(out, q, kf > 0, ref, ng, ex, ey, tag, false); + test_result_t tr = comom_check(out, q, kf > 0, ref, ng, ex, ey, tag, false, "csp"); ray_release(out); if (tr.status != TEST_PASS) return tr; - cells += 2 * ng; + cells += 3 * ng; } if (kf == 0) { ray_t* out = ray_eval_str("(cov (at comr 'x) (at comr 'y))"); - test_result_t tr = comom_check(out, "direct", false, ref, 1, ex, ey, tag, false); + test_result_t tr = comom_check(out, "direct cov", false, ref, 1, ex, ey, tag, false, "c"); ray_release(out); if (tr.status != TEST_PASS) return tr; - cells += 1; + out = ray_eval_str("(pearson_corr (at comr 'x) (at comr 'y))"); + tr = comom_check(out, "direct pearson_corr", false, ref, 1, ex, ey, tag, false, "p"); + ray_release(out); + if (tr.status != TEST_PASS) return tr; + cells += 2; } if (kf == 1) { - const char* q = "(select {c:(cov x y) s:(scov x y) from:comrs by:sk where:(in sk ['a 'b 'c])})"; + const char* q = "(select {c:(cov x y) s:(scov x y) p:(pearson_corr x y) from:comrs by:sk where:(in sk ['a 'b 'c])})"; ray_t* out = ray_eval_str(q); - test_result_t tr = comom_check(out, q, true, ref, 3, ex, ey, tag, false); + test_result_t tr = comom_check(out, q, true, ref, 3, ex, ey, tag, false, "csp"); ray_release(out); if (tr.status != TEST_PASS) return tr; - cells += 6; + cells += 9; } } } diff --git a/test/test_aware.c b/test/test_aware.c index 6f5cb0bbf..e481d8df2 100644 --- a/test/test_aware.c +++ b/test/test_aware.c @@ -7324,7 +7324,11 @@ static test_result_t test_plan_alloc_fail(void) { NULL, NULL, NULL, NULL, NULL, "(all (== (ser (select {from: Q asc: k})) (ser (select {from: R0 asc: k}))))", NULL, NULL, - "(all (== (ser (select {from: Q asc: j})) (ser (select {from: R0 asc: j}))))", + /* pearson_corr sums about each route's running mean (#1870): the + * same keys, nulls in the same places, the values to 1e-12 */ + "(and (all (== (at (select {from: Q asc: j}) 'j) (at (select {from: R0 asc: j}) 'j))) " + "(all (== (nil? (at (select {from: Q asc: j}) 'c)) (nil? (at (select {from: R0 asc: j}) 'c)))) " + "(all (< (abs (- (at (select {from: Q asc: j}) 'c) (at (select {from: R0 asc: j}) 'c))) 1e-12)))", NULL, NULL, }; aw_eval_ok("(set D (dict ['f] (list neg)))"); /* a computed call head: rewritten to its name */ diff --git a/test/test_scan_range.c b/test/test_scan_range.c index edd8712fd..a6b773ad4 100644 --- a/test/test_scan_range.c +++ b/test/test_scan_range.c @@ -4678,7 +4678,9 @@ static test_result_t test_v2_route_shapes(void) { { "(select {c: (count k) s: (sum f) mn: (min n) from: T by: nk})", R_LOCAL }, { "(select {sv: (sum f) v: (var n) from: T where: (> g 2) by: s})", R_LOCAL }, { "(select {x: (max f) c: (count k) from: T where: (> k 1000) by: {d: d u: u}})", R_PART }, - { "(select {x: (sum f) p: (pearson_corr f n) from: T by: {d: d u: u}})", R_PART }, + { "(select {x: (sum f) p: (cov f n) from: T by: {d: d u: u}})", R_PART }, + /* pearson_corr's 64-byte pivoted state (#1870): the tablestack strategy */ + { "(select {x: (sum f) p: (pearson_corr f n) from: T by: {d: d u: u}})", R_TS }, { "(select {c: (count k) a: (avg nk) from: T by: {nk: nk s: s}})", R_LOCAL }, { "(select {p: (pearson_corr f g) w: (wavg g f) from: T by: g})", R_LOCAL }, /* binary inputs */ };