oups 2025.9.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. oups-2025.9.5/LICENSE +201 -0
  2. oups-2025.9.5/PKG-INFO +44 -0
  3. oups-2025.9.5/README.md +17 -0
  4. oups-2025.9.5/oups/__init__.py +40 -0
  5. oups-2025.9.5/oups/date_utils.py +62 -0
  6. oups-2025.9.5/oups/defines.py +26 -0
  7. oups-2025.9.5/oups/numpy_utils.py +114 -0
  8. oups-2025.9.5/oups/stateful_loop/__init__.py +14 -0
  9. oups-2025.9.5/oups/stateful_loop/loop_persistence_io.py +55 -0
  10. oups-2025.9.5/oups/stateful_loop/stateful_loop.py +654 -0
  11. oups-2025.9.5/oups/stateful_loop/validate_loop_usage.py +338 -0
  12. oups-2025.9.5/oups/stateful_ops/__init__.py +22 -0
  13. oups-2025.9.5/oups/stateful_ops/aggstream/__init__.py +12 -0
  14. oups-2025.9.5/oups/stateful_ops/aggstream/aggstream.py +1524 -0
  15. oups-2025.9.5/oups/stateful_ops/aggstream/cumsegagg.py +580 -0
  16. oups-2025.9.5/oups/stateful_ops/aggstream/jcumsegagg.py +416 -0
  17. oups-2025.9.5/oups/stateful_ops/aggstream/segmentby.py +1018 -0
  18. oups-2025.9.5/oups/stateful_ops/aggstream/utils.py +71 -0
  19. oups-2025.9.5/oups/stateful_ops/asof_merger/__init__.py +11 -0
  20. oups-2025.9.5/oups/stateful_ops/asof_merger/asof_merger.py +750 -0
  21. oups-2025.9.5/oups/stateful_ops/asof_merger/get_config.py +401 -0
  22. oups-2025.9.5/oups/stateful_ops/asof_merger/validate_params.py +285 -0
  23. oups-2025.9.5/oups/store/__init__.py +15 -0
  24. oups-2025.9.5/oups/store/filepath_utils.py +68 -0
  25. oups-2025.9.5/oups/store/indexer.py +457 -0
  26. oups-2025.9.5/oups/store/ordered_parquet_dataset/__init__.py +19 -0
  27. oups-2025.9.5/oups/store/ordered_parquet_dataset/metadata_filename.py +50 -0
  28. oups-2025.9.5/oups/store/ordered_parquet_dataset/ordered_parquet_dataset/__init__.py +15 -0
  29. oups-2025.9.5/oups/store/ordered_parquet_dataset/ordered_parquet_dataset/base.py +863 -0
  30. oups-2025.9.5/oups/store/ordered_parquet_dataset/ordered_parquet_dataset/read_only.py +252 -0
  31. oups-2025.9.5/oups/store/ordered_parquet_dataset/parquet_adapter.py +157 -0
  32. oups-2025.9.5/oups/store/ordered_parquet_dataset/write/__init__.py +19 -0
  33. oups-2025.9.5/oups/store/ordered_parquet_dataset/write/iter_merge_split_data.py +131 -0
  34. oups-2025.9.5/oups/store/ordered_parquet_dataset/write/merge_split_strategies/__init__.py +22 -0
  35. oups-2025.9.5/oups/store/ordered_parquet_dataset/write/merge_split_strategies/base.py +784 -0
  36. oups-2025.9.5/oups/store/ordered_parquet_dataset/write/merge_split_strategies/n_rows_strategy.py +297 -0
  37. oups-2025.9.5/oups/store/ordered_parquet_dataset/write/merge_split_strategies/time_period_strategy.py +319 -0
  38. oups-2025.9.5/oups/store/ordered_parquet_dataset/write/write.py +270 -0
  39. oups-2025.9.5/oups/store/store/__init__.py +11 -0
  40. oups-2025.9.5/oups/store/store/dataset_cache.py +50 -0
  41. oups-2025.9.5/oups/store/store/iter_intersections.py +397 -0
  42. oups-2025.9.5/oups/store/store/store.py +345 -0
  43. oups-2025.9.5/pyproject.toml +120 -0
oups-2025.9.5/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025, pierrot
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
oups-2025.9.5/PKG-INFO ADDED
@@ -0,0 +1,44 @@
1
+ Metadata-Version: 2.3
2
+ Name: oups
3
+ Version: 2025.9.5
4
+ Summary: Out-of-core pipelines over ordered data: StatefulLoop, stateful ops, and ordered Parquet Store.
5
+ License: Apache-2.0
6
+ Keywords: out-of-core,streaming,stateful,time-series,pandas,parquet,data-engineering
7
+ Author: pierrot
8
+ Requires-Python: >=3.13,<4.0
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.13
12
+ Requires-Dist: cloudpickle (>=3.1.1)
13
+ Requires-Dist: fastparquet (>=2023.10.1)
14
+ Requires-Dist: flufl-lock (>=8.2.0)
15
+ Requires-Dist: joblib (>=1.3.2)
16
+ Requires-Dist: numba (>=0.61.2)
17
+ Requires-Dist: numpy (>=2.0)
18
+ Requires-Dist: pandas (>=2.2.3)
19
+ Requires-Dist: sortedcontainers (>=2.4.0)
20
+ Project-URL: Changelog, https://codeberg.org/pierrot/oups/src/branch/main/CHANGELOG.md
21
+ Project-URL: Documentation, https://codeberg.org/pierrot/oups/src/branch/main/docs
22
+ Project-URL: Homepage, https://codeberg.org/pierrot/oups
23
+ Project-URL: Issues, https://codeberg.org/pierrot/oups/issues
24
+ Project-URL: Source, https://codeberg.org/pierrot/oups
25
+ Description-Content-Type: text/markdown
26
+
27
+ # Welcome to oups!
28
+
29
+ ## What is oups?
30
+ *oups* stands for Ordered Unified Processing Stack — out-of-core processing for ordered data (batch + live).
31
+
32
+ *oups* is a Python toolkit for building end-to-end pipelines over ordered data with the same code in offline training and live streaming/batch contexts.
33
+
34
+ It centers on ``StatefulLoop`` (``loop.bind_function_state``, ``loop.iterate``, ``loop.buffer``), which binds and persists function/object state, orchestrates chunked iteration, and buffers DataFrames under a memory cap with flush-on-limit or last-iteration semantics.
35
+ Complementing the loop, ``stateful_ops`` provides vectorized, chunk-friendly primitives like ``AsofMerger`` for multi-DataFrame as-of joins (with optional windows of previous values) and ``SegmentedAggregator`` (planned) for streamed segmentation and aggregation.
36
+ The ``store`` package manages ordered Parquet datasets via schema-driven keys (``@toplevel``), supports incremental updates (``store[key].write(...)``) and duplicate handling, and offers synchronized iteration across datasets via ``store.iter_intersections(...)`` with optional warm-up (``n_prev``).
37
+
38
+ Together these pieces enable out-of-core processing with resumability, and deterministic buffering. The design favors explicit, minimal APIs and reproducible results, aligning offline feature generation with online serving.
39
+
40
+ ## Links
41
+
42
+ - 📖 **[Documentation](https://pierrot.codeberg.page/oups/)** - Guides and API reference
43
+ - 📋 **[Changelog](CHANGELOG.md)** - Release notes and version history
44
+
@@ -0,0 +1,17 @@
1
+ # Welcome to oups!
2
+
3
+ ## What is oups?
4
+ *oups* stands for Ordered Unified Processing Stack — out-of-core processing for ordered data (batch + live).
5
+
6
+ *oups* is a Python toolkit for building end-to-end pipelines over ordered data with the same code in offline training and live streaming/batch contexts.
7
+
8
+ It centers on ``StatefulLoop`` (``loop.bind_function_state``, ``loop.iterate``, ``loop.buffer``), which binds and persists function/object state, orchestrates chunked iteration, and buffers DataFrames under a memory cap with flush-on-limit or last-iteration semantics.
9
+ Complementing the loop, ``stateful_ops`` provides vectorized, chunk-friendly primitives like ``AsofMerger`` for multi-DataFrame as-of joins (with optional windows of previous values) and ``SegmentedAggregator`` (planned) for streamed segmentation and aggregation.
10
+ The ``store`` package manages ordered Parquet datasets via schema-driven keys (``@toplevel``), supports incremental updates (``store[key].write(...)``) and duplicate handling, and offers synchronized iteration across datasets via ``store.iter_intersections(...)`` with optional warm-up (``n_prev``).
11
+
12
+ Together these pieces enable out-of-core processing with resumability, and deterministic buffering. The design favors explicit, minimal APIs and reproducible results, aligning offline feature generation with online serving.
13
+
14
+ ## Links
15
+
16
+ - 📖 **[Documentation](https://pierrot.codeberg.page/oups/)** - Guides and API reference
17
+ - 📋 **[Changelog](CHANGELOG.md)** - Release notes and version history
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Created on Wed Dec 1 18:35:00 2021.
4
+
5
+ @author: pierrot
6
+
7
+ """
8
+ import sys
9
+
10
+ # Import version dynamically from Poetry
11
+ from importlib.metadata import PackageNotFoundError
12
+ from importlib.metadata import version
13
+
14
+
15
+ # Conditional import for stateful_ops to avoid numba issues during documentation builds
16
+ if "sphinx" in sys.modules:
17
+ # During documentation builds, skip heavy stateful_ops imports
18
+ AggStream = None
19
+ by_x_rows = None
20
+ else:
21
+ from .stateful_ops import AggStream
22
+ from .stateful_ops import by_x_rows
23
+
24
+ from .stateful_loop import StatefulLoop
25
+ from .stateful_ops import AsofMerger
26
+ from .store import OrderedParquetDataset
27
+ from .store import Store
28
+ from .store import check_cmidx
29
+ from .store import conform_cmidx
30
+ from .store import is_toplevel
31
+ from .store import sublevel
32
+ from .store import toplevel
33
+ from .store import write
34
+
35
+
36
+ try:
37
+ __version__ = version("oups")
38
+ except PackageNotFoundError:
39
+ # Package is not installed, likely in development
40
+ __version__ = "development"
@@ -0,0 +1,62 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Created on Sat May 24 18:35:00 2025.
4
+
5
+ @author: pierrot
6
+
7
+ """
8
+ from pandas import Timedelta
9
+ from pandas import Timestamp
10
+ from pandas import date_range
11
+
12
+
13
+ def floor_ts(ts: Timestamp, freq: str) -> Timestamp:
14
+ """
15
+ Floor a timestamp even if using non-fixed frequency.
16
+
17
+ Parameters
18
+ ----------
19
+ ts : Timestamp
20
+ Timestamp to floor.
21
+ freq : str
22
+ Frequency string.
23
+ https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliases
24
+
25
+
26
+ Returns
27
+ -------
28
+ Timestamp
29
+ Floored timestamp.
30
+
31
+ """
32
+ try:
33
+ return ts.floor(freq)
34
+ except ValueError:
35
+ return date_range(end=ts.normalize(), periods=1, freq=freq)[0]
36
+
37
+
38
+ def ceil_ts(ts: Timestamp, freq: str) -> Timestamp:
39
+ """
40
+ Ceil a timestamp even if using non-fixed frequency.
41
+
42
+ Parameters
43
+ ----------
44
+ ts : Timestamp
45
+ Timestamp to ceil.
46
+ freq : str
47
+ Frequency string.
48
+ https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliases
49
+
50
+ Returns
51
+ -------
52
+ Timestamp
53
+ Ceiled timestamp.
54
+
55
+ """
56
+ try:
57
+ # Can't use 'ceil' from pandas because it does not work on 'D'aily
58
+ # frequency.
59
+ # return ts.ceil(freq)
60
+ return (ts + Timedelta(1, unit=freq)).floor(freq)
61
+ except ValueError:
62
+ return date_range(start=floor_ts(ts, freq), periods=2, freq=freq)[1]
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Created on Wed Dec 1 18:35:00 2021.
4
+
5
+ @author: pierrot
6
+
7
+ """
8
+ # Central key in oups world, used as ID of the column name according which
9
+ # dataframes are ordered.
10
+ KEY_ORDERED_ON = "ordered_on"
11
+ # Other shared keys.
12
+ KEY_FILE_IDS = "file_ids"
13
+ KEY_N_ROWS = "n_rows"
14
+ KEY_ORDERED_ON_MINS = "ordered_on_mins"
15
+ KEY_ORDERED_ON_MAXS = "ordered_on_maxs"
16
+ # A specific key for a function parameter with a three-fold type:
17
+ # - None, meaning no duplicates check,
18
+ # - an empty list, meaning identify duplicate on all columns of the dataframe,
19
+ # - a not empty list of a string, the columns to identify row duplicates.
20
+ KEY_DUPLICATES_ON = "duplicates_on"
21
+ # In a fastparquet `ParquetFile`, oups-specific metadata is stored as value for
22
+ # key `KEY_METADATA_KEY`.
23
+ KEY_OUPS_METADATA = "oups"
24
+ # Parameters for 'write()' function.
25
+ KEY_ROW_GROUP_TARGET_SIZE = "row_group_target_size"
26
+ KEY_MAX_N_OFF_TARGET_RGS = "max_n_off_target_rgs"
@@ -0,0 +1,114 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Created on Mon Jun 02 18:35:00 2025.
4
+
5
+ @author: pierrot
6
+
7
+ """
8
+
9
+ from numpy import arange
10
+ from numpy import flip
11
+ from numpy import isnan
12
+ from numpy import maximum
13
+ from numpy import ones
14
+ from numpy import searchsorted
15
+ from numpy import where
16
+ from numpy.typing import NDArray
17
+
18
+
19
+ def isnotin_ordered(
20
+ sorted_array: NDArray,
21
+ query_elements: NDArray,
22
+ return_insert_positions: bool = False,
23
+ ) -> NDArray | tuple[NDArray, NDArray]:
24
+ """
25
+ Check if query elements are not present in a sorted array.
26
+
27
+ Parameters
28
+ ----------
29
+ sorted_array : NDArray
30
+ Sorted array in which to search for elements.
31
+ Must be sorted in ascending order.
32
+ query_elements : NDArray
33
+ Array of elements to search for.
34
+ Must be sorted in ascending order if containing elements which are
35
+ are larger than the largest element in 'sorted_array'.
36
+ return_insert_positions : bool, optional
37
+ If True, also return the insert positions where unfound elements
38
+ could be inserted into 'sorted_array', maintaining sort order.
39
+ Default is False.
40
+
41
+ Returns
42
+ -------
43
+ Union[NDArray, tuple[NDArray, NDArray]]
44
+ If 'return_insert_positions' is False:
45
+ Array of booleans with same length as 'query_elements', where
46
+ True indicates the element is not found in 'sorted_array'.
47
+ If 'return_insert_positions' is True:
48
+ Tuple containing:
49
+ - Array of booleans indicating which query elements are not found,
50
+ - Array of insert positions for unfound elements (where they could
51
+ be inserted into 'sorted_array', maintaining sort order)
52
+
53
+ Examples
54
+ --------
55
+ >>> sorted_arr = np.array([1, 3, 5, 7, 9])
56
+ >>> queries = np.array([2, 3, 6, 7])
57
+ >>> isnotin_ordered(sorted_arr, queries)
58
+ array([True, False, True, False])
59
+
60
+ >>> not_found, insert_positions = isnotin_ordered(sorted_arr, queries, return_insert_positions=True)
61
+ >>> not_found
62
+ array([True, False, True, False])
63
+ >>> insert_positions
64
+ array([1, 3]) # positions where 2 and 6 could be inserted
65
+
66
+ """
67
+ insert_idx = searchsorted(sorted_array, query_elements, side="left")
68
+ # Check if elements are found: they exist if insert position is valid
69
+ # and the element at that position matches the query
70
+ found_max_idx = searchsorted(insert_idx, len(sorted_array))
71
+ is_not_found = ones(len(query_elements), dtype=bool)
72
+ is_not_found[:found_max_idx] = sorted_array[insert_idx[:found_max_idx]] != query_elements[:found_max_idx]
73
+ return (is_not_found, insert_idx[is_not_found]) if return_insert_positions else is_not_found
74
+
75
+
76
+ def ffill1d(arr: NDArray) -> NDArray:
77
+ """
78
+ Forward fill 1D array in-place.
79
+
80
+ Parameters
81
+ ----------
82
+ arr : NDArray
83
+ Array to fill.
84
+
85
+ Returns
86
+ -------
87
+ None
88
+
89
+ Notes
90
+ -----
91
+ If first value is nan, it is kept as nan.
92
+
93
+ """
94
+ mask = isnan(arr)
95
+ idx = where(~mask, arange(mask.size), 0)
96
+ maximum.accumulate(idx, out=idx)
97
+ arr[mask] = arr[idx[mask]]
98
+
99
+
100
+ def bfill1d(arr: NDArray) -> NDArray:
101
+ """
102
+ Backward fill 1D array in-place.
103
+
104
+ Parameters
105
+ ----------
106
+ arr : NDArray
107
+ Array to fill.
108
+
109
+ Returns
110
+ -------
111
+ None
112
+
113
+ """
114
+ ffill1d(flip(arr, 0))
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ OUPS Stateful Loop Module.
4
+
5
+ This module provides the core stateful loop functionality.
6
+
7
+ """
8
+
9
+ from .stateful_loop import StatefulLoop
10
+
11
+
12
+ __all__ = [
13
+ "StatefulLoop",
14
+ ]
@@ -0,0 +1,55 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Created on Wed Jun 1 18:35:00 2025.
4
+
5
+ Loop persistence I/O helpers for the stateful loop.
6
+
7
+ """
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from cloudpickle import dump
12
+ from cloudpickle import load
13
+
14
+
15
+ KEY_ID = "id"
16
+ KEY_VERSION = "version"
17
+ KEY_STATES = "states"
18
+ PERSISTENCE_ID = "stateful_loop"
19
+ PERSISTENCE_VERSION = 1
20
+
21
+
22
+ class LoopPersistenceIO:
23
+ """
24
+ Helper for reading and writing the loop persistence file with schema validation.
25
+
26
+ Schema: {"id": "stateful_loop", "version": 1, "states": {...}}.
27
+
28
+ """
29
+
30
+ @staticmethod
31
+ def load(path: Path) -> dict[str, dict[str, Any]]:
32
+ """
33
+ Load and validate states from ``path``.
34
+ """
35
+ with open(path, "rb") as f:
36
+ payload = load(f)
37
+ if not isinstance(payload, dict):
38
+ raise ValueError("invalid persistence file format.")
39
+ if payload[KEY_ID] != PERSISTENCE_ID:
40
+ raise ValueError("invalid persistence file id.")
41
+ if payload[KEY_VERSION] != PERSISTENCE_VERSION:
42
+ raise ValueError("unsupported persistence file version.")
43
+ states = payload[KEY_STATES]
44
+ if not isinstance(states, dict):
45
+ raise ValueError("invalid 'states' content in persistence file.")
46
+ return states
47
+
48
+ @staticmethod
49
+ def save(path: Path, states: dict[str, dict[str, Any]]) -> None:
50
+ """
51
+ Save ``states`` to ``path`` with schema and version.
52
+ """
53
+ payload = {KEY_ID: PERSISTENCE_ID, KEY_VERSION: PERSISTENCE_VERSION, KEY_STATES: states}
54
+ with open(path, "wb") as f:
55
+ dump(payload, f)