Optimize ARMA forecast loop to O(N) by using pre-allocated buffer - #33
Merged
Conversation
Replace the per-step np.concatenate in the nns_arma recursive forecast loop with a pre-allocated buffer and a length pointer. The previous approach reallocated and copied the entire series on every horizon step (O(N^2) over the horizon); writing into a fixed buffer and passing a view of the populated prefix to the helpers is O(1) per step and leaves the forecast math unchanged.
The editable package version recorded in the lockfile was stale (1.0.0a0); uv refreshed it to match pyproject.toml during a local test run.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Replaced the O(N²) array concatenation pattern in the ARMA forecast loop with a pre-allocated buffer and index-based writes, reducing time complexity to O(N).
Key Changes
values.size + horizon) once before the forecast loop instead of reallocating on each iterationnp.concatenate()calls with direct buffer writes using an index pointer (current_len)buffer[:current_len]) to helper functions to maintain identical mathematical behaviorImplementation Details
The original code used
np.concatenate((current, np.array([estimate])))at each iteration, which reallocates and copies the entire accumulated series. With a long horizon, this results in O(N²) total operations.The optimized version:
bufferwith capacity for the full history plus forecast horizon upfrontvaluescurrent_lenpointer as new estimates are computedThis change maintains numerical equivalence while dramatically improving performance for long-horizon forecasts.
https://claude.ai/code/session_01AN7vrBnRhxGd4eZv6A34VX