ezmsg-learn 1.16.2__tar.gz → 1.17.0__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 (87) hide show
  1. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/PKG-INFO +3 -3
  2. ezmsg_learn-1.17.0/docs/source/_templates/navbar-logo.html +18 -0
  3. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/docs/source/conf.py +4 -1
  4. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/pyproject.toml +2 -2
  5. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/__version__.py +2 -2
  6. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/collection/sample_adapt_regressor.py +10 -2
  7. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/dim_reduce/adaptive_decomp.py +32 -9
  8. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/dim_reduce/incremental_decomp.py +7 -4
  9. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/process/adaptive_linear_regressor.py +18 -3
  10. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/process/linear_regressor.py +32 -6
  11. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/process/mlp_old.py +13 -0
  12. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/process/refit_kalman.py +36 -5
  13. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/process/rnn.py +21 -0
  14. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/process/seqseqsampler.py +4 -2
  15. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/process/sgd.py +43 -28
  16. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/process/sklearn.py +37 -17
  17. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/process/slda.py +31 -10
  18. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/process/ssr.py +19 -5
  19. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/process/torch.py +35 -0
  20. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/process/transformer.py +9 -0
  21. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/util.py +10 -0
  22. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/integration/test_refit_kalman_system.py +2 -1
  23. ezmsg_learn-1.17.0/tests/unit/test_reset_scope.py +299 -0
  24. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/unit/test_sklearn.py +42 -0
  25. ezmsg_learn-1.17.0/tests/unit/test_stream_contract.py +216 -0
  26. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/.github/workflows/docs.yml +0 -0
  27. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/.github/workflows/python-publish.yml +0 -0
  28. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/.github/workflows/python-tests.yml +0 -0
  29. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/.gitignore +0 -0
  30. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/.pre-commit-config.yaml +0 -0
  31. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/LICENSE +0 -0
  32. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/README.md +0 -0
  33. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/docs/Makefile +0 -0
  34. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/docs/make.bat +0 -0
  35. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/docs/source/_templates/autosummary/module.rst +0 -0
  36. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/docs/source/api/index.rst +0 -0
  37. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/docs/source/guides/array_api.rst +0 -0
  38. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/docs/source/guides/classification.rst +0 -0
  39. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/docs/source/index.rst +0 -0
  40. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/__init__.py +0 -0
  41. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/_optional.py +0 -0
  42. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/collection/__init__.py +0 -0
  43. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/dim_reduce/__init__.py +0 -0
  44. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/linear_model/__init__.py +0 -0
  45. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/linear_model/adaptive_linear_regressor.py +0 -0
  46. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/linear_model/cca.py +0 -0
  47. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/linear_model/linear_regressor.py +0 -0
  48. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/linear_model/sgd.py +0 -0
  49. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/linear_model/slda.py +0 -0
  50. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/model/__init__.py +0 -0
  51. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/model/cca.py +0 -0
  52. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/model/mlp.py +0 -0
  53. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/model/mlp_old.py +0 -0
  54. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/model/refit_kalman.py +0 -0
  55. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/model/rnn.py +0 -0
  56. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/model/transformer.py +0 -0
  57. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/nlin_model/__init__.py +0 -0
  58. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/nlin_model/mlp.py +0 -0
  59. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/process/__init__.py +0 -0
  60. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/process/base.py +0 -0
  61. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/src/ezmsg/learn/process/flatten.py +0 -0
  62. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/benchmark/bench_lrr.py +0 -0
  63. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/dim_reduce/test_adaptive_decomp.py +0 -0
  64. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/dim_reduce/test_incremental_decomp.py +0 -0
  65. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/integration/conftest.py +0 -0
  66. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/integration/test_mlp_system.py +0 -0
  67. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/integration/test_rnn_system.py +0 -0
  68. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/integration/test_sklearn_system.py +0 -0
  69. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/integration/test_torch_system.py +0 -0
  70. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/integration/test_transformer_system.py +0 -0
  71. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/unit/test_adaptive_linear_regressor.py +0 -0
  72. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/unit/test_axis_fingerprint_priming.py +0 -0
  73. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/unit/test_cca.py +0 -0
  74. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/unit/test_flatten.py +0 -0
  75. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/unit/test_linear_regressor.py +0 -0
  76. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/unit/test_mlp.py +0 -0
  77. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/unit/test_mlp_old.py +0 -0
  78. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/unit/test_optional_deps.py +0 -0
  79. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/unit/test_refit_kalman.py +0 -0
  80. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/unit/test_rnn.py +0 -0
  81. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/unit/test_sample_adapt_regressor.py +0 -0
  82. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/unit/test_seqseqsampler.py +0 -0
  83. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/unit/test_sgd.py +0 -0
  84. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/unit/test_slda.py +0 -0
  85. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/unit/test_ssr.py +0 -0
  86. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/unit/test_torch.py +0 -0
  87. {ezmsg_learn-1.16.2 → ezmsg_learn-1.17.0}/tests/unit/test_transformer.py +0 -0
@@ -1,14 +1,14 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: ezmsg-learn
3
- Version: 1.16.2
3
+ Version: 1.17.0
4
4
  Summary: ezmsg namespace package for machine learning
5
5
  Author-email: Chadwick Boulay <chadwick.boulay@gmail.com>
6
6
  License-Expression: MIT
7
7
  License-File: LICENSE
8
8
  Requires-Python: >=3.10
9
9
  Requires-Dist: array-api-compat
10
- Requires-Dist: ezmsg-baseproc>=1.15.0
11
- Requires-Dist: ezmsg-sigproc>=3.10.0
10
+ Requires-Dist: ezmsg-baseproc>=1.17.0
11
+ Requires-Dist: ezmsg-sigproc>=3.13.0
12
12
  Requires-Dist: ezmsg>=3.10.0b5
13
13
  Requires-Dist: numpy
14
14
  Requires-Dist: scipy
@@ -0,0 +1,18 @@
1
+ {# Override of pydata-sphinx-theme's navbar-logo component.
2
+ Splits the brand into two links: the logo image goes to the ezmsg.org
3
+ landing page (``logo.link``) and the title text goes to this site's root. #}
4
+ {% set org_href = theme_logo.get("link") or pathto(root_doc) %}
5
+ {% set alt = theme_logo.get("alt_text", "ezmsg.org") %}
6
+ {% if "light" in theme_logo["image_relative"] %}
7
+ {% if default_mode is undefined or default_mode == "auto" %}
8
+ {% set default_mode = "light" %}
9
+ {% endif %}
10
+ {% set js_mode = "light" if default_mode == "dark" else "dark" %}
11
+ <a class="navbar-brand logo" href="{{ org_href }}" title="ezmsg.org" style="margin-right: 0.75rem;">
12
+ <img src="{{ theme_logo['image_relative'][default_mode] }}" class="logo__image only-{{ default_mode }}" alt="{{ alt }}"/>
13
+ <img src="{{ theme_logo['image_relative'][js_mode] }}" class="logo__image only-{{ js_mode }} pst-js-only" alt="{{ alt }}"/>
14
+ </a>
15
+ {% endif %}
16
+ <a class="navbar-brand logo" href="{{ pathto(root_doc) }}">
17
+ <p class="title logo__title">{{ theme_logo.get("text") or docstitle }}</p>
18
+ </a>
@@ -87,7 +87,10 @@ html_baseurl = "https://www.ezmsg.org/ezmsg-learn/"
87
87
  html_theme_options = {
88
88
  "logo": {
89
89
  "text": f"ezmsg.learn {version}",
90
- "link": "https://ezmsg.org", # Link back to main site
90
+ "link": "https://www.ezmsg.org",
91
+ "image_light": "https://www.ezmsg.org/_static/_images/ezmsg_logo.png",
92
+ "image_dark": "https://www.ezmsg.org/_static/_images/ezmsg_logo.png",
93
+ "alt_text": "ezmsg.org",
91
94
  },
92
95
  "header_links_before_dropdown": 4,
93
96
  "navbar_start": ["navbar-logo"],
@@ -14,8 +14,8 @@ dependencies = [
14
14
  # left to the transitive requirement: uv only enables pre-releases for a
15
15
  # package named with a pre-release marker in *this* file.
16
16
  "ezmsg>=3.10.0b5",
17
- "ezmsg-baseproc>=1.15.0",
18
- "ezmsg-sigproc>=3.10.0", # Window/Resample must resolve stream_dim from axis=None
17
+ "ezmsg-baseproc>=1.17.0",
18
+ "ezmsg-sigproc>=3.13.0", # AffineTransform keeps its weights across a segment; config_id chaining
19
19
  "numpy",
20
20
  "scipy",
21
21
  "array-api-compat",
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
18
18
  commit_id: str | None
19
19
  __commit_id__: str | None
20
20
 
21
- __version__ = version = '1.16.2'
22
- __version_tuple__ = version_tuple = (1, 16, 2)
21
+ __version__ = version = '1.17.0'
22
+ __version_tuple__ = version_tuple = (1, 17, 0)
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -21,6 +21,7 @@ from ezmsg.baseproc import (
21
21
  warn_axis_deprecated,
22
22
  )
23
23
  from ezmsg.sigproc.resample import ResampleSettings, ResampleUnit
24
+ from ezmsg.sigproc.util.segment import ConfigJoin
24
25
  from ezmsg.sigproc.window import Window, WindowSettings
25
26
  from ezmsg.util.messages.axisarray import AxisArray
26
27
  from ezmsg.util.messages.util import replace
@@ -70,6 +71,8 @@ class DecodeOutputAdapterSettings(ez.Settings):
70
71
  @processor_state
71
72
  class DecodeOutputAdapterState:
72
73
  ch_axis: AxisArray.CoordinateAxis | None = None
74
+ configs: ConfigJoin | None = None
75
+ """Derives the output's config_id from the input's and the output channel axis."""
73
76
 
74
77
 
75
78
  class DecodeOutputAdapterProcessor(
@@ -94,10 +97,11 @@ class DecodeOutputAdapterProcessor(
94
97
  self.state.ch_axis = with_fingerprint(
95
98
  AxisArray.CoordinateAxis(data=np.asarray(self.settings.output_labels), dims=["ch"])
96
99
  )
100
+ self.state.configs = ConfigJoin()
97
101
 
98
102
  def _process(self, message: AxisArray) -> AxisArray | None:
99
103
  data = np.asarray(message.data, dtype=float)
100
- if data.size == 0:
104
+ if data.size == 0 and data.ndim < 2:
101
105
  return None
102
106
 
103
107
  if self.settings.output_labels is not None:
@@ -105,7 +109,9 @@ class DecodeOutputAdapterProcessor(
105
109
  data = data.reshape((-1, n_outputs))
106
110
  ch_axis = self.state.ch_axis
107
111
  else:
108
- data = data.reshape((data.shape[0], -1)) if data.ndim > 1 else data.reshape((1, -1))
112
+ # An explicit width rather than -1, so that an empty (end-of-stream) message reshapes too.
113
+ width = int(np.prod(data.shape[1:]))
114
+ data = data.reshape((data.shape[0], width)) if data.ndim > 1 else data.reshape((1, -1))
109
115
  ch_axis = with_fingerprint(
110
116
  AxisArray.CoordinateAxis(data=np.asarray([f"ch{i}" for i in range(data.shape[-1])]), dims=["ch"])
111
117
  )
@@ -127,6 +133,8 @@ class DecodeOutputAdapterProcessor(
127
133
  dims=["time", "ch"],
128
134
  axes={"ch": ch_axis, "time": message.axes["time"]},
129
135
  key=f"{message.key}_pred",
136
+ stream_dim="time",
137
+ config_id=self.state.configs.update(message.config_id, own=(ch_axis.fingerprint,)),
130
138
  )
131
139
 
132
140
 
@@ -20,6 +20,7 @@ from ezmsg.baseproc import (
20
20
  resolve_stream_dim,
21
21
  warn_axis_deprecated,
22
22
  )
23
+ from ezmsg.sigproc.util.segment import ConfigChain
23
24
  from ezmsg.util.messages.axisarray import AxisArray, replace
24
25
 
25
26
  from .._optional import missing_extra
@@ -59,6 +60,8 @@ class AdaptiveDecompState:
59
60
  template: AxisArray | None = None
60
61
  axis_groups: tuple[str, list[str], list[str]] | None = None
61
62
  estimator: typing.Any = None
63
+ configs: ConfigChain | None = None
64
+ """Derives the output's config_id from the input's and the decomposed layout."""
62
65
 
63
66
 
64
67
  EstimatorType = typing.TypeVar("EstimatorType", bound=typing.Union[IncrementalPCA, MiniBatchNMF])
@@ -125,11 +128,28 @@ class AdaptiveDecompTransformer(
125
128
  off_targ_axes = [_ for _ in (message.dims[:it_ax_ix] + message.dims[it_ax_ix + 1 :]) if _ != axis]
126
129
  self._state.axis_groups = iter_axis, targ_axes, off_targ_axes
127
130
 
131
+ def _hash_message(self, message: AxisArray) -> int:
132
+ # The estimator and template are sized to the shape off the iteration axis, and which dims get
133
+ # folded depends on the dims. Key, labels, dtype and backend do not matter (sklearn sees numpy).
134
+ axis = self.settings.axis
135
+ iter_axis = axis[1:] if axis and axis.startswith("!") else resolve_stream_dim(message, self.STREAMING_DIMS)
136
+ shape = tuple(n for dim, n in zip(message.dims, message.data.shape) if dim != iter_axis)
137
+ return hash((iter_axis, tuple(message.dims), shape))
138
+
139
+ def _reset_segment(self, message: AxisArray) -> None:
140
+ # Nothing here tracks the stream position: each output takes its iteration axis from its input.
141
+ pass
142
+
128
143
  def _reset_state(self, message: AxisArray) -> None:
129
144
  """Reset state"""
130
145
  self._calculate_axis_groups(message)
131
146
  iter_axis, targ_axes, off_targ_axes = self._state.axis_groups
132
147
 
148
+ # Keep a fitted estimator unless it was fitted to another number of features.
149
+ n_features = math.prod(message.data.shape[message.get_axis_idx(ax)] for ax in targ_axes)
150
+ if getattr(self._state.estimator, "n_features_in_", n_features) != n_features:
151
+ self._state.estimator = self._create_estimator()
152
+
133
153
  # Template
134
154
  out_dims = [iter_axis] + off_targ_axes
135
155
  out_axes = {
@@ -156,14 +176,22 @@ class AdaptiveDecompTransformer(
156
176
  dims=out_dims,
157
177
  axes=out_axes,
158
178
  )
179
+ self._state.configs = ConfigChain(tuple(out_dims), out_axes[targ_ax_name].fingerprint)
159
180
 
160
181
  def _process(self, message: AxisArray) -> AxisArray:
161
182
  iter_axis, targ_axes, off_targ_axes = self._state.axis_groups
162
183
  ax_idx = message.get_axis_idx(iter_axis)
163
184
  in_dat = message.data
164
185
 
186
+ # Key and axes come from the message: a change in them does not reset the template.
187
+ stamp = {
188
+ "segment": message.segment,
189
+ "config_id": self._state.configs.update(message.config_id),
190
+ "key": message.key,
191
+ "axes": {**self._state.template.axes, **{ax: message.axes[ax] for ax in (iter_axis, *off_targ_axes)}},
192
+ }
165
193
  if in_dat.shape[ax_idx] == 0:
166
- return self._state.template
194
+ return replace(self._state.template, **stamp)
167
195
 
168
196
  xp = get_namespace(in_dat)
169
197
 
@@ -179,9 +207,7 @@ class AdaptiveDecompTransformer(
179
207
  d2 = math.prod(in_dat.shape[len(off_targ_axes) + 1 :])
180
208
  in_dat = xp.reshape(in_dat, (-1, d2))
181
209
 
182
- replace_kwargs = {
183
- "axes": {**self._state.template.axes, iter_axis: message.axes[iter_axis]},
184
- }
210
+ replace_kwargs = dict(stamp)
185
211
 
186
212
  # Transform data — sklearn needs numpy
187
213
  if hasattr(self._state.estimator, "components_"):
@@ -195,11 +221,8 @@ class AdaptiveDecompTransformer(
195
221
  return replace(self._state.template, **replace_kwargs)
196
222
 
197
223
  def partial_fit(self, message: AxisArray) -> None:
198
- # Check if we need to reset state
199
- msg_hash = self._hash_message(message)
200
- if self._hash != msg_hash:
201
- self._reset_state(message)
202
- self._hash = msg_hash
224
+ # Reset on a new configuration or segment, exactly as for a signal message.
225
+ self._prepare_state(message)
203
226
 
204
227
  iter_axis, targ_axes, off_targ_axes = self._state.axis_groups
205
228
  ax_idx = message.get_axis_idx(iter_axis)
@@ -104,9 +104,11 @@ class IncrementalDecompTransformer(CompositeProcessor[IncrementalDecompSettings,
104
104
 
105
105
  return {"decomp": decomp}
106
106
 
107
- def _partial_fit_windowed(self, train_msg: AxisArray) -> None:
107
+ def _partial_fit_windowed(self, train_msg: AxisArray, config_id: int) -> None:
108
108
  """
109
109
  Helper function to do the partial_fit on the windowed message.
110
+
111
+ ``config_id`` is that of the message the windows were cut from: each slice has its layout.
110
112
  """
111
113
  if np.prod(train_msg.data.shape) > 0:
112
114
  # Windowing created a new "win" axis, but we don't actually want to use that
@@ -132,6 +134,7 @@ class IncrementalDecompTransformer(CompositeProcessor[IncrementalDecompSettings,
132
134
  ),
133
135
  },
134
136
  stream_dim="time",
137
+ config_id=config_id,
135
138
  )
136
139
  self._procs["decomp"].partial_fit(_msg)
137
140
 
@@ -148,7 +151,7 @@ class IncrementalDecompTransformer(CompositeProcessor[IncrementalDecompSettings,
148
151
  self._procs["decomp"].partial_fit(message)
149
152
  elif "windowing" in self._procs:
150
153
  state["windowing"], train_msg = self._procs["windowing"].stateful_op(state.get("windowing", None), message)
151
- self._partial_fit_windowed(train_msg)
154
+ self._partial_fit_windowed(train_msg, message.config_id)
152
155
 
153
156
  # Process the incoming message
154
157
  state["decomp"], result = self._procs["decomp"].stateful_op(state.get("decomp", None), message)
@@ -168,7 +171,7 @@ class IncrementalDecompTransformer(CompositeProcessor[IncrementalDecompSettings,
168
171
  elif "windowing" in self._procs:
169
172
  # If windowing is enabled, extract training samples and perform partial_fit
170
173
  train_msg = await self._procs["windowing"].__acall__(message)
171
- self._partial_fit_windowed(train_msg) # Non async
174
+ self._partial_fit_windowed(train_msg, message.config_id) # Non async
172
175
 
173
176
  # Process the incoming message
174
177
  decomp_result = await self._procs["decomp"].__acall__(message)
@@ -183,7 +186,7 @@ class IncrementalDecompTransformer(CompositeProcessor[IncrementalDecompSettings,
183
186
  elif "windowing" in self._procs:
184
187
  # If windowing is enabled, extract training samples and perform partial_fit
185
188
  train_msg = self._procs["windowing"](message)
186
- self._partial_fit_windowed(train_msg)
189
+ self._partial_fit_windowed(train_msg, message.config_id)
187
190
 
188
191
  # Process the incoming message
189
192
  decomp_result = self._procs["decomp"](message)
@@ -19,7 +19,8 @@ from ezmsg.baseproc import (
19
19
  BaseAdaptiveTransformerUnit,
20
20
  processor_state,
21
21
  )
22
- from ezmsg.util.messages.axisarray import AxisArray, replace
22
+ from ezmsg.sigproc.util.segment import ConfigChain
23
+ from ezmsg.util.messages.axisarray import AxisArray, compute_config_id, replace
23
24
 
24
25
  from .._optional import missing_extra
25
26
  from ..util import AdaptiveLinearRegressor, RegressorType, get_regressor, with_fingerprint
@@ -48,6 +49,8 @@ class AdaptiveLinearRegressorState:
48
49
  | sklearn.base.RegressorMixin
49
50
  | None
50
51
  ) = None
52
+ configs: ConfigChain | None = None
53
+ """Derives the output's config_id from the input's and ``template``; None when ``template`` changes."""
51
54
 
52
55
 
53
56
  def _normalize_axis_label(label):
@@ -153,6 +156,9 @@ class AdaptiveLinearRegressorTransformer(
153
156
  # cheapest possible hash. Zero rather than -1: -1 is the sentinel
154
157
  # `_hash` starts at and that `_request_reset()` writes, so returning it
155
158
  # made an explicitly requested reset compare equal and be swallowed.
159
+ # ponytail: a feature-count change is not caught (sklearn models then raise on predict). A
160
+ # feature-count hash is impossible while SampleAdaptRegressor trains this on raw (time, ch)
161
+ # samples and predicts on wider flattened lag windows; revisit if that collection is redesigned.
156
162
  return 0
157
163
 
158
164
  def _reset_state(self, message: AxisArray) -> None:
@@ -214,6 +220,7 @@ class AdaptiveLinearRegressorTransformer(
214
220
  self.state.model.partial_fit(X_np, message.attrs["trigger"].value.data)
215
221
 
216
222
  self.state.template = _prediction_template(message.attrs["trigger"].value)
223
+ self.state.configs = None
217
224
 
218
225
  def _process(self, message: AxisArray) -> AxisArray | None:
219
226
  if self.state.model is None:
@@ -250,12 +257,17 @@ class AdaptiveLinearRegressorTransformer(
250
257
  else:
251
258
  # sklearn path: needs numpy
252
259
  data_np = np.asarray(message.data) if not is_numpy_array(message.data) else message.data
253
- preds = self.state.model.predict(data_np)
254
- preds = preds.reshape((len(preds), -1))
260
+ # sklearn will not predict for no samples (e.g. an end-of-stream marker); its regressors are 1-D.
261
+ preds = self.state.model.predict(data_np) if len(data_np) else np.zeros((0,))
262
+ if preds.ndim == 1:
263
+ preds = preds[:, None]
255
264
  template = self.state.template
256
265
  if template is None:
257
266
  template = _prediction_template_from_signal(message, self._prediction_labels(preds.shape[1]))
258
267
  self.state.template = template
268
+ self.state.configs = None
269
+ if self.state.configs is None:
270
+ self.state.configs = ConfigChain(compute_config_id(template))
259
271
  return replace(
260
272
  template,
261
273
  data=preds,
@@ -263,6 +275,9 @@ class AdaptiveLinearRegressorTransformer(
263
275
  **template.axes,
264
276
  "time": message.axes["time"],
265
277
  },
278
+ stream_dim="time",
279
+ segment=message.segment,
280
+ config_id=self.state.configs.update(message.config_id),
266
281
  )
267
282
 
268
283
 
@@ -7,10 +7,11 @@ from ezmsg.baseproc import (
7
7
  BaseAdaptiveTransformerUnit,
8
8
  processor_state,
9
9
  )
10
- from ezmsg.util.messages.axisarray import AxisArray, replace
10
+ from ezmsg.sigproc.util.segment import ConfigChain
11
+ from ezmsg.util.messages.axisarray import AxisArray, compute_config_id, replace
11
12
 
12
13
  from .._optional import missing_extra
13
- from ..util import RegressorType, StaticLinearRegressor, get_regressor
14
+ from ..util import RegressorType, StaticLinearRegressor, feature_count, get_regressor
14
15
 
15
16
  try:
16
17
  from sklearn.linear_model._base import LinearModel
@@ -28,6 +29,8 @@ class LinearRegressorSettings(ez.Settings):
28
29
  class LinearRegressorState:
29
30
  template: AxisArray | None = None
30
31
  model: LinearModel | None = None
32
+ configs: ConfigChain | None = None
33
+ """Derives the output's config_id from the input's and ``template``."""
31
34
 
32
35
 
33
36
  class LinearRegressorTransformer(
@@ -43,6 +46,9 @@ class LinearRegressorTransformer(
43
46
 
44
47
  def __init__(self, *args, **kwargs):
45
48
  super().__init__(*args, **kwargs)
49
+ self._init_model()
50
+
51
+ def _init_model(self) -> None:
46
52
  if self.settings.settings_path is not None:
47
53
  # Load model from file
48
54
  import pickle
@@ -53,14 +59,26 @@ class LinearRegressorTransformer(
53
59
  regressor_klass = get_regressor(RegressorType.STATIC, self.settings.model_type)
54
60
  self.state.model = regressor_klass(**self.settings.model_kwargs)
55
61
 
62
+ def _hash_message(self, message: AxisArray) -> int:
63
+ # The fitted model is sized to the features per sample; labels, key and dtype do not matter to it.
64
+ return feature_count(message, "time")
65
+
56
66
  def _reset_state(self, message: AxisArray) -> None:
57
- # So far, there is nothing to reset.
58
- # .model and .template are initialized in __init__
59
- pass
67
+ # A new feature count: the fit no longer applies, so start again from the settings' model.
68
+ self._init_model()
69
+ self.state.template = None
70
+ expected = getattr(self.state.model, "n_features_in_", None)
71
+ n_features = feature_count(message, "time")
72
+ if expected is not None and expected != n_features:
73
+ raise ValueError(
74
+ f"Model from {self.settings.settings_path} expects {expected} features, but got {n_features}"
75
+ )
60
76
 
61
77
  def partial_fit(self, message: AxisArray) -> None:
62
78
  if np.any(np.isnan(message.data)):
63
79
  return
80
+ # Reset on a new feature count, exactly as for a signal message (so the first call keeps this fit).
81
+ self._prepare_state(message)
64
82
 
65
83
  X = message.data
66
84
  y = message.attrs["trigger"].value.data
@@ -71,11 +89,16 @@ class LinearRegressorTransformer(
71
89
  data=np.array([[]]),
72
90
  key=message.attrs["trigger"].value.key + "_pred",
73
91
  )
92
+ self.state.configs = ConfigChain(compute_config_id(self.state.template))
74
93
 
75
94
  def _process(self, message: AxisArray) -> AxisArray:
76
95
  if self.state.template is None:
77
96
  return AxisArray(np.array([[]]), dims=["time", "ch"])
78
- preds = self.state.model.predict(message.data)
97
+ if message.data.shape[0]:
98
+ preds = self.state.model.predict(message.data)
99
+ else:
100
+ # sklearn will not predict for no samples (e.g. an end-of-stream marker).
101
+ preds = np.zeros((0, *np.shape(self.state.model.coef_)[:-1]))
79
102
  return replace(
80
103
  self.state.template,
81
104
  data=preds,
@@ -86,6 +109,9 @@ class LinearRegressorTransformer(
86
109
  offset=message.axes["time"].offset,
87
110
  ),
88
111
  },
112
+ stream_dim="time",
113
+ segment=message.segment,
114
+ config_id=self.state.configs.update(message.config_id),
89
115
  )
90
116
 
91
117
 
@@ -7,6 +7,7 @@ from ezmsg.baseproc import (
7
7
  BaseAdaptiveTransformerUnit,
8
8
  processor_state,
9
9
  )
10
+ from ezmsg.sigproc.util.segment import ConfigChain
10
11
  from ezmsg.util.messages.axisarray import AxisArray
11
12
  from ezmsg.util.messages.util import replace
12
13
 
@@ -63,9 +64,19 @@ class MLPState:
63
64
  scheduler: torch.optim.lr_scheduler.LRScheduler | None = None
64
65
  template: AxisArray | None = None
65
66
  device: object | None = None
67
+ configs: ConfigChain | None = None
68
+ """Derives the output's config_id from the input's and the output channel axis."""
66
69
 
67
70
 
68
71
  class MLPProcessor(BaseAdaptiveTransformer[MLPSettings, AxisArray, AxisArray, MLPState]):
72
+ def _reset_segment(self, message: AxisArray) -> None:
73
+ # All state is the (possibly trained) model and its optimizer; a gap does not invalidate them.
74
+ pass
75
+
76
+ def _hash_message(self, message: AxisArray) -> int:
77
+ # The model is built for the number of input channels; input is cast to the settings' dtype.
78
+ return message.data.shape[message.get_axis_idx("ch")]
79
+
69
80
  def _reset_state(self, message: AxisArray) -> None:
70
81
  # Create the model
71
82
  self._state.model = MLP(
@@ -116,6 +127,7 @@ class MLPProcessor(BaseAdaptiveTransformer[MLPSettings, AxisArray, AxisArray, ML
116
127
  self._state.chan_ax = with_fingerprint(
117
128
  AxisArray.CoordinateAxis(data=np.array([f"ch{_}" for _ in range(n_output_channels)]), dims=["ch"])
118
129
  )
130
+ self._state.configs = ConfigChain(self._state.chan_ax.fingerprint, self.settings.single_precision)
119
131
 
120
132
  def save_checkpoint(self, path: str) -> None:
121
133
  """Save the current model state to a checkpoint file.
@@ -173,6 +185,7 @@ class MLPProcessor(BaseAdaptiveTransformer[MLPSettings, AxisArray, AxisArray, ML
173
185
  **message.axes,
174
186
  "ch": self.state.chan_ax,
175
187
  },
188
+ config_id=self.state.configs.update(message.config_id),
176
189
  )
177
190
 
178
191
 
@@ -7,6 +7,7 @@
7
7
  is stacked via ``xp.stack``.
8
8
  """
9
9
 
10
+ import math
10
11
  import pickle
11
12
  from pathlib import Path
12
13
 
@@ -19,6 +20,7 @@ from ezmsg.baseproc import (
19
20
  processor_state,
20
21
  )
21
22
  from ezmsg.sigproc.util.array import array_device, xp_create
23
+ from ezmsg.sigproc.util.segment import ConfigJoin
22
24
  from ezmsg.util.messages.axisarray import AxisArray
23
25
  from ezmsg.util.messages.util import replace
24
26
 
@@ -61,6 +63,9 @@ class RefitKalmanFilterState:
61
63
  P: object | None = None # Array API; namespace matches source data.
62
64
  """Current state covariance matrix (n_states x n_states)."""
63
65
 
66
+ configs: ConfigJoin | None = None
67
+ """Derives the output's config_id from the input's and the state dimension."""
68
+
64
69
  buffer_neural: list | None = None
65
70
  """Buffer for storing neural activity data for refitting."""
66
71
 
@@ -240,6 +245,22 @@ class RefitKalmanFilterProcessor(
240
245
  if self._state.model.A_state_transition_matrix is not None:
241
246
  state_dim = self._state.model.A_state_transition_matrix.shape[0]
242
247
 
248
+ H = self._state.model.H_observation_matrix
249
+ if message is not None and H is not None and H.shape[0] != math.prod(message.data.shape[1:]):
250
+ # The observation model cannot be rebuilt for other features without refitting.
251
+ raise ValueError(
252
+ f"Kalman model expects {H.shape[0]} measurement features, but got {math.prod(message.data.shape[1:])}"
253
+ )
254
+
255
+ self._reset_trajectory(message, state_dim)
256
+
257
+ self._state.buffer_neural = []
258
+ self._state.buffer_state = []
259
+ self._state.buffer_cursor_positions = []
260
+ self._state.buffer_target_positions = []
261
+ self._state.buffer_hold_flags = []
262
+
263
+ def _reset_trajectory(self, message: AxisArray | None, state_dim: int) -> None:
243
264
  # Derive xp/dev from message data when available; default to numpy.
244
265
  if message is not None:
245
266
  xp = get_namespace(message.data)
@@ -250,11 +271,18 @@ class RefitKalmanFilterProcessor(
250
271
  self._state.x = xp_create(xp.zeros, (state_dim,), dtype=xp.float64, device=dev)
251
272
  self._state.P = xp_create(xp.eye, state_dim, dtype=xp.float64, device=dev)
252
273
 
253
- self._state.buffer_neural = []
254
- self._state.buffer_state = []
255
- self._state.buffer_cursor_positions = []
256
- self._state.buffer_target_positions = []
257
- self._state.buffer_hold_flags = []
274
+ def _reset_segment(self, message: AxisArray) -> None:
275
+ # A gap breaks the trajectory, not the model or the logged training pairs: restart x and P only.
276
+ model = self._state.model
277
+ self._reset_trajectory(message, model.A_state_transition_matrix.shape[0])
278
+ if model.is_fitted and not model.steady_state:
279
+ # Without a steady-state gain the model carries the trajectory's covariance and gain itself.
280
+ model._compute_gain()
281
+
282
+ def _hash_message(self, message: AxisArray) -> int:
283
+ # Measurement features per sample (the observation model is sized to them; samples run along
284
+ # axis 0, as _process reads them), and the array backend, because x and P live in it.
285
+ return hash((math.prod(message.data.shape[1:]), type(message.data).__module__.partition(".")[0]))
258
286
 
259
287
  def _process(self, message: AxisArray) -> AxisArray:
260
288
  """
@@ -284,6 +312,8 @@ class RefitKalmanFilterProcessor(
284
312
  state_dim = self._state.model.A_state_transition_matrix.shape[0]
285
313
  if self._state.x is None:
286
314
  self._state.x = xp_create(xp.zeros, (state_dim,), dtype=xp.float64, device=dev)
315
+ if self._state.configs is None:
316
+ self._state.configs = ConfigJoin()
287
317
 
288
318
  filtered_data = xp_create(
289
319
  xp.zeros,
@@ -310,6 +340,7 @@ class RefitKalmanFilterProcessor(
310
340
  data=filtered_data,
311
341
  dims=["time", "state"],
312
342
  key=f"{message.key}_filtered" if hasattr(message, "key") else "filtered",
343
+ config_id=self._state.configs.update(message.config_id, own=("state", state_dim)),
313
344
  )
314
345
 
315
346
  def partial_fit(self, message: AxisArray) -> None:
@@ -51,6 +51,9 @@ class RNNProcessor(
51
51
  TorchProcessorMixin,
52
52
  ModelInitMixin,
53
53
  ):
54
+ # The mixin follows the base class in the MRO, so its hash must be named here to take effect.
55
+ _hash_message = TorchProcessorMixin._hash_message
56
+
54
57
  def _infer_output_sizes(self, model: torch.nn.Module, n_input: int) -> dict[str, int]:
55
58
  """Simple inference to get output channel size."""
56
59
  dummy_input = torch.zeros(1, 50, n_input, device=self._state.device)
@@ -71,6 +74,10 @@ class RNNProcessor(
71
74
  batch_size = 1 if message.data.ndim == 2 else message.data.shape[0]
72
75
  self.reset_hidden(batch_size)
73
76
 
77
+ def _reset_segment(self, message: AxisArray) -> None:
78
+ # Keep the (possibly trained) model; the hidden state describes samples before the gap.
79
+ self.reset_hidden(1 if message.data.ndim == 2 else message.data.shape[0])
80
+
74
81
  def _maybe_reset_state(self, message: AxisArray, batch_size: int) -> bool:
75
82
  preserve_state = self.settings.preserve_state_across_windows
76
83
  if preserve_state == "auto":
@@ -107,6 +114,19 @@ class RNNProcessor(
107
114
  return preserve_state
108
115
 
109
116
  def _process(self, message: AxisArray) -> list[AxisArray]:
117
+ if 0 in message.data.shape:
118
+ # No samples (e.g. an end-of-stream marker): the RNN cannot run on an empty sequence.
119
+ dtype = np.float32 if self.settings.single_precision else np.float64
120
+ return [
121
+ replace(
122
+ message,
123
+ data=np.zeros((*message.data.shape[:-1], ax.data.shape[0]), dtype=dtype),
124
+ axes={**message.axes, "ch": ax},
125
+ key=key,
126
+ config_id=self._state.configs[key].update(message.config_id),
127
+ )
128
+ for key, ax in self._state.chan_ax.items()
129
+ ]
110
130
  x = message.data
111
131
  if not isinstance(x, torch.Tensor):
112
132
  x = torch.tensor(
@@ -147,6 +167,7 @@ class RNNProcessor(
147
167
  data=out,
148
168
  axes={**message.axes, "ch": self._state.chan_ax[key]},
149
169
  key=key,
170
+ config_id=self._state.configs[key].update(message.config_id),
150
171
  )
151
172
  for key, out in y_data.items()
152
173
  ]
@@ -258,9 +258,9 @@ class SeqSeqSampler:
258
258
  raise ValueError(f"Invalid target: {target}")
259
259
 
260
260
  ax_ix = message.get_axis_idx("time")
261
- # TODO: Check if we need to reset the buffer because the input changed.
262
261
 
263
- if buffer is None:
262
+ # A new segment or configuration does not continue what is buffered: start again from this message.
263
+ if buffer is None or message.segment != buffer.segment or message.config_id != buffer.config_id:
264
264
  buffer = copy.deepcopy(message)
265
265
  if target == "value":
266
266
  self._value_buffer = buffer
@@ -278,6 +278,8 @@ class SeqSeqSampler:
278
278
  else:
279
279
  n_times = buffer.data.shape[buffer.get_axis_idx("time")]
280
280
  tvec = buffer.axes["time"].value(np.arange(n_times))
281
+ if len(tvec) == 0:
282
+ return # Nothing to trim (e.g. an end-of-stream message).
281
283
  t_min = tvec[-1] - self._max_buffer_dur
282
284
  b_keep = tvec >= t_min
283
285
  if not np.all(b_keep):