You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@otava.apache.org by "henrikingo (via GitHub)" <gi...@apache.org> on 2025/08/01 16:23:21 UTC

[I] Push window_len down into the core e-divisive computation [otava]

henrikingo opened a new issue, #84:
URL: https://github.com/apache/otava/issues/84

   In Otava, Piotr introduced window_len as a user facing parameter, and for a given data point, only `window_len/2` data points are included in the computation. This gives better quality results, in particular it makes it possible to find two adjacent change points. This is because computation is focused on the local neighborhood of each candidate change point, and data points far away are completely ignored.
   
   In Piotr's version, the input data is split into `2*datapoints/window_len` windows and the regular e-divisive is run on each window. After this there is a process to merge the small windows together. The windows also overlap, so the same point could be found once or twice, with different p-value for each.
   
   Mathematically it would be more elegant, and consistent, and potentially also a performance improvement (because we don't count every point twice because no need for overlap) to rather just do a single pass, as in the original e-divisive, but incorporate window length into the core e-divisive code. This could be something like this:
   
   https://github.com/mongodb/signal-processing-algorithms/blob/74d6a8fa3a377ee5dce4821ba9dfd2f2528790b2/src/signal_processing_algorithms/e_divisive.py#L222-L250
   
           length = window_len
           n = 1   # Note: this is 2 in the quoted code, but that is unnecessarily conservative.
           w_start = max( n - window_len / 2, 0)
           w_stop = min( n + window_len / 2, len(series) )
           m = w_stop - n
   
           # term1 = sum(diffs[i][j] for i in range(w_start, n) for j in range(n, w_stop))
           term1 = np.sum(diffs[w_start:n, n:w_stop])
   
           # term2 = sum(diffs[i][k] for i in range(w_start, n) for k in range(i + 1, n))
           term2 = np.sum(np.triu(diffs[w_start:n, w_start:n], 0))
   
           # term3 = sum(diffs[j][k] for j in range(n, w_stop)
           #                         for k in range(j + 1, w_stop)) 
           term3 = np.sum(np.triu(diffs[n:w_stop, n + 1 : w_stop], 0))
   
           qhat_values[n] = self.calculate_q(term1, term2, term3, m, n)
   
           for n in range(3, (length - 2)):
               w_start = max( n - window_len / 2, 0)
               w_stop = min( n + window_len / 2, len(series) )
               m = w_stop - n
   
               # TODO: may need a +1 and / or -1 somewhere
               column_delta = np.sum(diffs[n - 1, w_start : n - 1])
               row_delta = np.sum(diffs[n:w_stop, n - 1])
   
               term1 = term1 - column_delta + row_delta
               term2 = term2 + column_delta
               term3 = term3 - row_delta
   
               qhat_values[n] = self.calculate_q(term1, term2, term3, m, n-w_start)
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@otava.apache.org.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [I] Push window_len down into the core e-divisive computation [otava]

Posted by "henrikingo (via GitHub)" <gi...@apache.org>.
henrikingo commented on issue #84:
URL: https://github.com/apache/otava/issues/84#issuecomment-6471832449

   Hi @Phoenix1504e 
   
   I continue to believe this is the right path to an optimal e-divisive implementation. I also just commented on #154 and I have faith in that the deterministic variation will turn out to be the superior one, and if nothing else, what you are proposing will reduce the needed computation. But it would be interesting to see examples of data sets where an implementation of this ticket also performs better in terms of correctness of the results.
   
   So yes I encourage you to explore this and tell us what you learn! Keep an eye on where #154 lands.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@otava.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [I] Push window_len down into the core e-divisive computation [otava]

Posted by "Phoenix1504e (via GitHub)" <gi...@apache.org>.
Phoenix1504e commented on issue #84:
URL: https://github.com/apache/otava/issues/84#issuecomment-6470193132

   **Update: revising the proposal after the kappa fix (#96) and #154**
   
   The code sketch in the issue description references the old `signal_processing_algorithms/e_divisive.py` structure (`term1/term2/term3` single pass). That structure no longer exists in Otava master: `PairDistanceCalculator._get_Q_vals(start, end)` now computes the kappa-corrected `Q(τ, κ)` matrix (both the split point τ *and* the right segment end κ are optimized) using the vectorized `V`/`H` cumulative sums. So "push `window_len` into the core" needs to be reformulated in `Q(τ, κ)` terms.
   
   **Do we still need it?** With kappa fixed, part of the original motivation (finding adjacent change points) is addressed by optimizing over κ — as noted in #154, split-merge may even become unnecessary. I'd still argue for pushing windowing into the core rather than dropping it: (1) **locality** — on long series with many change points, a candidate's statistic shouldn't be dominated by far-away data; (2) **performance** — windowed computation is O(N·W) vs O(N²) for the full matrix, which matters for long series.
   
   **Proposed semantics:** for a candidate at τ, restrict the statistic to a symmetric local neighborhood — right segment length `κ − τ ≤ W/2`, and left segment starting at `max(start, τ − W/2)` instead of `start`, with the A/B/C normalizations using the window-local boundaries. This matches the original intent ("for a given data point, only `window_len/2` data points are included in the computation") while staying consistent with the kappa fix.
   
   **Implementation sketch:** in `_get_Q_vals` this is (a) masking Q entries with `κ − τ > W/2`, and (b) replacing the cumulative sums with sliding-window (banded) sums — a windowed sum is just the difference of two entries of the same cumsum, so it stays fully vectorized. Note we should **not** port the incremental `term1 − column_delta + row_delta` recurrence from the issue description: it's only valid while the window edges are stationary; once the left edge starts sliding, points leave/enter the window and the recurrence needs extra correction terms (that's exactly where the "TODO: may need a +1/-1" in the description comes from). The banded-cumsum formulation avoids that bookkeeping entirely.
   
   **On the MongoDB reference:** [`numpy_windowed_calculator.py`](https://github.com/mongodb/signal-processing-algorithms/blob/75312e873543f0f89aace75f43ded783395425c5/docs/profiling/numpy_windowed_calculator.py) (linked above) is marked *"Only used for profiling, don't use this in production"* — it recomputes all terms per point and normalizes with *global* m/n instead of window-local counts. Treat it as prior art / cross-check material only.
   
   **Validation plan:**
   1. `window_len ≥ 2·len(series)` ⇒ results identical to the unwindowed path (the `window_len=10000` check from #154)
   2. brute-force on small random series: masked-Q argmax vs `QQ(X, Y)` computed directly from the definition for every (τ, κ)
   3. two change points closer than `W/2` apart are both found (the motivating case of this issue)
   4. existing test suite + benchmark: old `split()` vs single-pass on a long series
   
   **Open questions:**
   - Windowed path in the default (split/merge) variant only, or also in the deterministic variant from #154 (where it may be redundant, or useful purely as a performance knob)?
   - Incremental append: keep `new_data`/`old_weak_cp` behavior, or recompute from the last old change point as v1 (as #154 suggests)?
   - Window definition details: symmetric ±W/2 per candidate vs "max right-segment length W"? Handling of odd `window_len`?
   
   If there's agreement on semantics, I can prototype the windowed `_get_Q_vals` + brute-force test, and document the chosen definition in `docs/MATH.md`.
   
   (the above comment is rephrased with the help of ai to better explain my understanding)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@otava.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [I] Push window_len down into the core e-divisive computation [otava]

Posted by "Phoenix1504e (via GitHub)" <gi...@apache.org>.
Phoenix1504e commented on issue #84:
URL: https://github.com/apache/otava/issues/84#issuecomment-6516647206

   **Update — I went ahead and ran the validation plan from my previous comment.**
   
   Prototype: **draft PR [apache/otava#186](https://github.com/apache/otava/pull/186)** (branch
   `windowed-qvals` on my fork); demo scripts, figures, raw results and the patch:
   [the `windowed-qvals-demos` branch](https://github.com/Phoenix1504e/otava/tree/windowed-qvals-demos).
   5 files, +396 lines, definition documented in `docs/MATH.md` ("Windowed Computation (issue #84)").
   Reproduce:
   
   ```
   git clone https://github.com/apache/otava && cd otava
   git fetch origin pull/186/head:windowed-qvals && git checkout windowed-qvals
   python -m pip install numpy scipy pytest
   python -m pytest tests/windowed_calculator_test.py tests/change_point_divisive_test.py tests/analysis_test.py
   # 46 passed
   ```
   
   **1. Equivalence property holds.** `window_len >= 2·len(series)` reproduces the unwindowed
   candidate exactly (same index, same qhat), so the `window_len=10000`-style check from #154
   transfers to this implementation as-is. Brute force: for 5 seeds × 5 window sizes (plus
   sub-intervals with `start > 0`), the masked-Q matrix, the O(N·W) production scan, and a
   direct-from-definition `QQ(X, Y)` for every (τ, κ) agree to 1e-8.
   
   **2. The motivating case.** Two change points 20/40/80 apart with `window_len=60` (closer than
   W/2): both found in 60/60, 59/60, 60/60 runs (no-window reference: 60/60, 59/60, 60/60).
   Detection parity — but see (3) for why the legacy path still answers a different question.
   
   **3. Correctness example: the same regression gets a different answer depending on unrelated
   history.** <img width="1425" height="1080" alt="Image" src="https://github.com/user-attachments/assets/eca49e07-f8bb-4230-a7b8-665f81b5a283" /> 
   One clean +2σ step at index 177 of a 250-point series, `window_len=60`. The
   data around the change is bit-identical in all cases; only 0/15/30 flat points are prepended,
   which shifts `split()`'s chunk grid (30 seeds per row):
   
   | prepend | legacy: found | legacy: kept p (shown seed) | windowed core |
   |---|---|---|---|
   | 0 | 23/30 | 6e-3 | 24/30, p = 3e-25 |
   | 15 | 29/30 | 2e-8 | 24/30, p = 3e-25 |
   | 30 | 24/30 | 5e-3 | 24/30, p = 3e-25 |
   
   The legacy p-value for the *same change* spans 6 orders of magnitude with grid alignment, and two
   of the three alignments land above `max_pvalue=0.001` — the change is dropped. <img width="1350" height="630" alt="Image" src="https://github.com/user-attachments/assets/a8278679-e7f0-4c01-a530-2b65c77d03f7" /> 
   The core anchors the window at the *candidate*, so its evidence is a deterministic function of the data.
   Related quantification: whenever `split()`'s weak list contains the true CP, the p-value kept by
   index-dedup is >10× worse than the same CP's full-context p-value in **32/32** observed cases —
   i.e. "every point counted twice, same point found twice with different p-values" from the issue
   description, measured.
   
   **4. Suite + randomized sweep.** Full existing suite + new tests: 46 passed. Randomized sweep
   (250-point series, `window_len=60`, 30 seeds/config; "sp" = spurious CPs > 5 points from any true
   CP):
   
   | config | legacy | core (t-test) | core (perm) | no-window perm ref |
   |---|---|---|---|---|
   | single Δ=1.5σ | 28/30 (sp 8) | **29/30** (sp 36) | 24/30 (sp 2) | 29/30 (sp 1) |
   | single Δ=2.0σ | 30/30 (sp 6) | 30/30 (sp 34) | 29/30 (sp 0) | 30/30 (sp 0) |
   | twins 20 apart | 60/60 (sp 6) | **60/60** (sp 34) | 56/60 (sp 3) | 60/60 (sp 0) |
   | twins 40 apart | 59/60 (sp 8) | 59/60 (sp 31) | 59/60 (sp 1) | 59/60 (sp 1) |
   | twins 80 apart | 60/60 (sp 7) | **60/60** (sp 35) | 60/60 (sp 0) | 60/60 (sp 0) |
   | triple 70/140/210 | 87/90 (sp 9) | **88/90** (sp 40) | 82/90 (sp 4) | 88/90 (sp 2) |
   
   Recall parity or better at every config. Honest purity reading: the 10×-relaxed t-test first pass
   admits ~1 spurious weak CP/run that survives merge at `min_magnitude=0` (legacy: ~0.2); the
   per-data permutation null removes it (sp 0–4 per 30 runs) at the cost of recall on ~1σ shifts.
   
   **5. Honest cost accounting.** As implemented, the t-test core is *slower* end-to-end than
   `split()` (N=8000: 3.6 s vs 0.36 s). Profiled causes, all addressable: the one-time O(N²) padded
   cumsum (2 GB at N=16000 — exactly what the banded cumsum from my previous comment replaces,
   giving O(N·W) time *and* memory), fancy-indexing constants, and the weak-candidate flood
   multiplying rescans. The windowed scan itself is cheap and linear: 48 ms per candidate eval at
   N=10000. Core+permutation is already 1.6× faster than the no-window reference at N=2000. <img width="1275" height="690" alt="Image" src="https://github.com/user-attachments/assets/96e75ff0-0789-437a-83a8-b1a48b090bd2" />
   
   **Learnings beyond the numbers:**
   
   - The subtle part wasn't the statistic, it was **evidence-window consistency**: a candidate found
     on a local window must be *tested* on that same window (clipping the sides to it). Tested on
     full-interval sides, short excursions get diluted and can never pass. So "windowed-Q" alone
     isn't a complete semantics — the significance test has to agree with it.
   - Hunter's 10× relaxed first-pass threshold was compensation for chunk-grid truncation. With
     candidate-anchored windows there is no truncation, so strict `max_pvalue` or the permutation
     null looks better-calibrated (open question 1 from my previous comment, now with data).
   - Termination policy matters: stop-at-first-insignificant can stop early when a noise candidate
     outranks a real one under local qhats (costs a few seeds around Δ≈2σ).
   
   **Separately**, unrelated to windowing: `ChangePointDetector.get_change_points()` only applies
   `series[start:end]` slicing for list input — for ndarray input the bounds are silently ignored
   but the found indexes still get shifted by `start` (`detector.py`, the
   `isinstance(series, np.ndarray)` branch). In `split()` this yields change points beyond the end
   of the series and a `ValueError`. I'll file that as its own issue so it doesn't get lost here.
   
   The three open questions from my previous comment still stand — especially whether `window_len`
   survives into the #154 world at all. Happy to rebase this onto the deterministic variant once it
   lands; the equivalence test transfers unchanged.
   
   *(demo scripts + raw results: `demo_alignment.py`, `demo_stress.py`, `demo_perf.py`,
   `demo_phantom.py` on the demos branch; run from the repo root, e.g. `python demos/demo_alignment.py`)*


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@otava.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [I] Push window_len down into the core e-divisive computation [otava]

Posted by "Phoenix1504e (via GitHub)" <gi...@apache.org>.
Phoenix1504e commented on issue #84:
URL: https://github.com/apache/otava/issues/84#issuecomment-6470627457

   **Update — this issue predates #96, and intersects with the still-open #154**
   
   Timing context: this was filed in Aug 2025. Since then, **#96 (merged Dec 2025)** replaced the
   MongoDB `signal_processing_algorithms` package with an internal implementation and fixed the kappa
   bug: `PairDistanceCalculator._get_Q_vals(start, end)` now computes the kappa-corrected `Q(τ, κ)`
   matrix (both the split point τ *and* the right segment end κ are optimized, per Matteson & James).
   So the `term1/term2/term3` sketch in the issue description references code that no longer exists —
   "push `window_len` into the core" has to be reformulated in `Q(τ, κ)` terms. (I checked the
   tracker — no other open or closed issue/PR covers this, so this issue remains the place for it.)
   
   Where windowing stands today:
   
   - **Default (split/merge) path**: still implemented as overlapping windows in `split()` —
     step `W/2`, detector run per window, dedupe by index, merge filters weak points — with exactly
     the downsides from the issue description (every point counted twice, same point found twice with
     different p-values).
   - **`orig_edivisive` (#96)**: no windowing, O(N²).
   - **#154 (open)**: deterministic variant, no windowing either — and with kappa fixed, the hope
     there was that split-merge becomes unnecessary. Per #152, #150/#154 are expected to merge soon,
     so this decision is timely.
   
   **Proposal:** implement windowed-Q **in the calculator itself**, so it's variant-independent
   rather than living in `split()`.
   
   *Semantics:* for a candidate at τ, restrict the statistic to a symmetric local neighborhood —
   `κ − τ ≤ W/2`, and left boundary `max(start, τ − W/2)` instead of `start`, with the A/B/C
   normalizations using the window-local boundaries. This matches the original intent ("for a given
   data point, only `window_len/2` data points are included") and composes cleanly with the kappa fix.
   
   *Implementation:* a correctness baseline is almost free — mask Q entries with `κ − τ > W/2` and
   substitute the left boundary in the coefficient formulas. The O(N·W) performance version then
   replaces the cumulative sums with sliding-window (banded) sums — a windowed sum is just the
   difference of two entries of the same cumsum. Note we should **not** port the
   `term1 − column_delta + row_delta` recurrence from the issue description: it's only valid while
   the window edges are stationary; once the left edge slides, points leave/enter the window and
   extra correction terms appear (that's the source of the "TODO: may need a +1/-1" in the
   description).
   
   *(The MongoDB
   [`numpy_windowed_calculator.py`](https://github.com/mongodb/signal-processing-algorithms/blob/75312e873543f0f89aace75f43ded783395425c5/docs/profiling/numpy_windowed_calculator.py)
   linked above is marked *"Only used for profiling, don't use this in production"* — it recomputes
   all terms per point and normalizes with global m/n. Cross-check material only.)*
   
   **Why bother if #154 lands?**
   1. **Locality** — on long series with many change points, a candidate's statistic shouldn't be
      dominated by far-away data.
   2. **Performance** — orig/deterministic are O(N²); windowed-Q can be O(N·W), which is orders of
      magnitude for long series.
   3. It fixes the current default path's overlapping-window artifacts in the meantime, whichever
      variant wins.
   4. Gerrrr's testing showing orig ≈ deterministic suggests the variants are close enough that a
      well-defined window knob with a clean equivalence property fits right in.
   
   This also parallels the `min_segment_len` discussion in #152: that option was deliberately *not*
   added to the split/merge variant because the two features work against each other. `window_len`
   has the same relationship to split/merge — it exists *because of* the chunking — so its role needs
   re-evaluating whenever split/merge itself does.
   
   **Validation plan:**
   1. `window_len ≥ 2·len(series)` ⇒ identical to the unwindowed path — the same `window_len=10000`
      property Stephan agreed to check in #154, so the same test rig serves both
   2. brute-force on small random series: masked-Q argmax vs `QQ(X, Y)` computed directly from the
      definition for every (τ, κ)
   3. two change points closer than `W/2` apart are both found (the motivating case of this issue)
   4. existing test suite + benchmark vs `split()`
   
   **Open questions:**
   - Since #154 is expected to become the default before 1.0: should windowed-Q land in the
     calculator after #154 merges, or is `window_len` obsolete in that world? (This is really the
     decision I'm looking for on this issue.)
   - If kept: incremental append — keep `new_data`/`old_weak_cp` behavior, or recompute from the last
     old change point as v1 (as #154 suggests)?
   - Semantics details: symmetric ±W/2 per candidate vs "max right-segment length W"? Handling of odd
     `window_len`?
   
   Happy to prototype the windowed `_get_Q_vals` + brute-force test once there's agreement on
   semantics, and document the definition in `docs/MATH.md`. Tracking this via the #152 umbrella as
   well.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@otava.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [I] Push window_len down into the core e-divisive computation [otava]

Posted by "henrikingo (via GitHub)" <gi...@apache.org>.
henrikingo commented on issue #84:
URL: https://github.com/apache/otava/issues/84#issuecomment-3160025943

   Actually, this seems to have been implemeńted at MongoDB in newer versions of their e-divisive code: https://github.com/mongodb/signal-processing-algorithms/blob/75312e873543f0f89aace75f43ded783395425c5/docs/profiling/numpy_windowed_calculator.py


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@otava.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org