tiptilt 0.1.0__py3-none-any.whl

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.
tiptilt/__init__.py ADDED
@@ -0,0 +1,137 @@
1
+ """tiptilt -- differentiable wavefront-error generation and control.
2
+
3
+ A downstream consumer of physicaloptix (the differentiable propagation engine)
4
+ and optixstuff (the hardware and speckle-field contracts), parallel to
5
+ coronagraphoto (image simulation). It owns the two halves of the wavefront
6
+ program that the propagation engine deliberately does not:
7
+
8
+ - **Aberration generation.** A physically meaningful mode basis (segment
9
+ piston/tip/tilt, deformable-mirror influence functions, Zernikes) plus
10
+ per-mode temporal statistics produce a drifting wavefront-error realization,
11
+ delivered as a time-varying speckle residual that implements the
12
+ ``optixstuff.AbstractSpeckleField`` contract on top of the ``(E_nom, G)``
13
+ linearization the engine provides.
14
+ - **Wavefront control.** Wavefront-sensor estimators, a reconstructor over the
15
+ same ``(E_nom, G)`` product (electric-field conjugation in space, a modal
16
+ loop on the ground), and the differentiable control loop that commands the
17
+ deformable mirror.
18
+
19
+ The library keeps its devices and control loop private and exposes only the
20
+ resulting residual through the speckle seam, so the image and yield layers pick
21
+ it up without any change. Space wavefront control is the priority; atmospheric
22
+ turbulence shares the loop, the mode basis, and the residual interface.
23
+
24
+ Named for tip and tilt, the humblest wavefront correction.
25
+ """
26
+
27
+ from tiptilt._version import __version__
28
+ from tiptilt.control import (
29
+ AbstractController,
30
+ DarkZoneModel,
31
+ EFCController,
32
+ PredictiveController,
33
+ StrokeMinController,
34
+ close_dark_hole,
35
+ )
36
+ from tiptilt.dm import DeformableMirror, HardwareDM, dm_influence_basis
37
+ from tiptilt.lowfs import lowfs_calibrate, run_pointing_loop
38
+ from tiptilt.maintenance import (
39
+ maintain_dark_hole,
40
+ maintained_residual_field,
41
+ make_detector,
42
+ )
43
+ from tiptilt.multichannel import (
44
+ FeedForwardController,
45
+ MultiChannelModel,
46
+ run_multichannel,
47
+ shared_dm_command,
48
+ )
49
+ from tiptilt.sensing import (
50
+ AbstractEstimator,
51
+ KalmanEstimator,
52
+ KalmanFieldEstimator,
53
+ OracleEstimator,
54
+ PairwiseEstimator,
55
+ estimate_field_pairwise,
56
+ pairwise_estimate,
57
+ probe_set,
58
+ zwfs_calibrate,
59
+ zwfs_reconstruct,
60
+ )
61
+ from tiptilt.speckle import (
62
+ TabulatedSpeckleField,
63
+ correlated_channel_fields,
64
+ correlated_drift_field,
65
+ )
66
+ from tiptilt.testbed import (
67
+ ALGORITHMS,
68
+ Metrics,
69
+ RunResult,
70
+ Scenario,
71
+ compute_metrics,
72
+ dig_from_cold,
73
+ dual_science_common_mode,
74
+ hardware_dm,
75
+ hold_against_drift,
76
+ ncpa_limited,
77
+ one_dm_vs_two_dm,
78
+ pointing_jitter,
79
+ run,
80
+ sweep,
81
+ wfs_plus_science,
82
+ wfs_private_aliasing,
83
+ )
84
+ from tiptilt.turbulence import frozen_flow_sequence, von_karman_screen
85
+
86
+ __all__ = [
87
+ "ALGORITHMS",
88
+ "AbstractController",
89
+ "AbstractEstimator",
90
+ "DarkZoneModel",
91
+ "DeformableMirror",
92
+ "EFCController",
93
+ "FeedForwardController",
94
+ "HardwareDM",
95
+ "KalmanEstimator",
96
+ "KalmanFieldEstimator",
97
+ "Metrics",
98
+ "MultiChannelModel",
99
+ "OracleEstimator",
100
+ "PairwiseEstimator",
101
+ "PredictiveController",
102
+ "RunResult",
103
+ "Scenario",
104
+ "StrokeMinController",
105
+ "TabulatedSpeckleField",
106
+ "__version__",
107
+ "close_dark_hole",
108
+ "compute_metrics",
109
+ "correlated_channel_fields",
110
+ "correlated_drift_field",
111
+ "dig_from_cold",
112
+ "dm_influence_basis",
113
+ "dual_science_common_mode",
114
+ "estimate_field_pairwise",
115
+ "frozen_flow_sequence",
116
+ "hardware_dm",
117
+ "hold_against_drift",
118
+ "lowfs_calibrate",
119
+ "maintain_dark_hole",
120
+ "maintained_residual_field",
121
+ "make_detector",
122
+ "ncpa_limited",
123
+ "one_dm_vs_two_dm",
124
+ "pairwise_estimate",
125
+ "pointing_jitter",
126
+ "probe_set",
127
+ "run",
128
+ "run_multichannel",
129
+ "run_pointing_loop",
130
+ "shared_dm_command",
131
+ "sweep",
132
+ "von_karman_screen",
133
+ "wfs_plus_science",
134
+ "wfs_private_aliasing",
135
+ "zwfs_calibrate",
136
+ "zwfs_reconstruct",
137
+ ]
tiptilt/_version.py ADDED
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '0.1.0'
22
+ __version_tuple__ = version_tuple = (0, 1, 0)
23
+
24
+ __commit_id__ = commit_id = None
tiptilt/control.py ADDED
@@ -0,0 +1,527 @@
1
+ """Deformable-mirror wavefront control: models, controllers, and the EFC loop.
2
+
3
+ The control problem factors onto two symmetric seams sharing one currency:
4
+
5
+ - ``DarkZoneModel``: the controller-facing linearization of a path -- the
6
+ stacked dark-zone Jacobian ``g_dz = d(E_dz)/d(command)`` (broadband via
7
+ sqrt-weighted per-wavelength stacking), built ONCE at an operating point,
8
+ plus the command plumbing (``set_commands``/``focal_of``/``contrast``).
9
+ - ``AbstractController``: ``command_delta(estimate) -> (new_self, delta)``.
10
+ Stateless laws (EFC / stroke minimization) return themselves unchanged;
11
+ stateful ones (a predictive AR feed-forward) advance their state.
12
+ - ``AbstractEstimator`` (in ``tiptilt.sensing``): ``estimate(model,
13
+ command, key) -> (new_self, e_hat)``, the measurement half.
14
+
15
+ ``close_dark_hole`` is a thin driver over these seams: the oracle loop is a
16
+ ``lax.scan`` with ONE propagation per step (read the true field, correct);
17
+ the estimated loops are Python-unrolled (probing is a multi-propagation,
18
+ keyed-noise step). Every propagation is pure, so the loops differentiate
19
+ through the feedback.
20
+ """
21
+
22
+ import equinox as eqx
23
+ import jax
24
+ import jax.numpy as jnp
25
+ from jaxtyping import Array
26
+ from physicaloptix import PhaseScreen
27
+
28
+ from tiptilt.sensing import KalmanEstimator, PairwiseEstimator
29
+
30
+
31
+ def _dm_coeffs(path, dm_index):
32
+ return path.stages[dm_index].op.basis.coeffs
33
+
34
+
35
+ class DarkZoneModel(eqx.Module):
36
+ """The controller-facing dark-zone linearization of one optical path.
37
+
38
+ Carries the stacked control Jacobian and the command plumbing every
39
+ estimator and controller shares. The dark-zone ordering is
40
+ wavelength-major, pixel-minor; ``stack_weights`` (sqrt of the spectrum
41
+ weights, ones for mono) map an UNWEIGHTED field estimate onto the
42
+ Jacobian's weighted stacking.
43
+
44
+ Attributes:
45
+ path: The optical path (commands applied by ``set_commands``).
46
+ indices: DM stage indices, in command-stacking order.
47
+ split_points: Cumulative mode counts carving the stacked command.
48
+ mask: Boolean dark-zone mask.
49
+ weights: Spectrum weights (ones for a monochromatic field).
50
+ sqrt_weights: Their square roots.
51
+ stack_weights: Per-(wavelength, pixel) sqrt weights, stacked.
52
+ g_dz: The dark-zone Jacobian, shape ``(n_stack, n_total)``.
53
+ operating_point: The command the Jacobian was built at.
54
+ """
55
+
56
+ path: eqx.Module
57
+ indices: tuple = eqx.field(static=True)
58
+ split_points: tuple = eqx.field(static=True)
59
+ mask: Array
60
+ weights: Array
61
+ sqrt_weights: Array
62
+ stack_weights: Array
63
+ g_dz: Array
64
+ operating_point: Array
65
+
66
+ @property
67
+ def n_total(self):
68
+ """Total stacked command length."""
69
+ return self.g_dz.shape[1]
70
+
71
+ def set_commands(self, command):
72
+ """The path with the stacked ``command`` split onto its mirrors."""
73
+ chunks = jnp.split(command, list(self.split_points))
74
+ return eqx.tree_at(
75
+ lambda p: [_dm_coeffs(p, i) for i in self.indices],
76
+ self.path,
77
+ list(chunks),
78
+ )
79
+
80
+ def focal_of(self, command, field):
81
+ """The focal data for a command applied to a given entrance field."""
82
+ out, _ = self.set_commands(command).propagate(field)
83
+ return out.data
84
+
85
+ def dark_zone_unweighted(self, data):
86
+ """Flattened complex dark-zone vector, unweighted (mono or stacked)."""
87
+ if data.ndim == 2:
88
+ return data[self.mask]
89
+ return data[:, self.mask].reshape(-1)
90
+
91
+ def contrast(self, data):
92
+ """Weight-averaged mean dark-zone intensity (broadband contrast)."""
93
+ if data.ndim == 2:
94
+ return jnp.mean(jnp.abs(data[self.mask]) ** 2)
95
+ intensity = jnp.abs(data[:, self.mask]) ** 2 # (nlam, n_dz)
96
+ return jnp.mean(jnp.tensordot(self.weights, intensity, axes=1))
97
+
98
+ @classmethod
99
+ def build(
100
+ cls, path, dm_indices, dark_zone_mask, *, jacobian_field, operating_point=None
101
+ ):
102
+ """Linearize a path's dark zone about an operating point.
103
+
104
+ Args:
105
+ path: An ``OpticalPath`` whose ``dm_indices`` stages are
106
+ ``PhaseScreen`` deformable mirrors.
107
+ dm_indices: A stage index or tuple of stage indices.
108
+ dark_zone_mask: Boolean focal-plane mask (static).
109
+ jacobian_field: The entrance field the Jacobian is built on (the
110
+ DESIGN model for an honest loop; the true field for an
111
+ oracle).
112
+ operating_point: Stacked command to linearize at; defaults to
113
+ zeros (the dig-from-cold base point). A maintenance loop
114
+ passes the pre-dug command.
115
+
116
+ Returns:
117
+ A ``DarkZoneModel``.
118
+ """
119
+ indices = (dm_indices,) if isinstance(dm_indices, int) else tuple(dm_indices)
120
+ for i in indices:
121
+ stage_op = path.stages[i].op
122
+ if not isinstance(stage_op, PhaseScreen):
123
+ raise TypeError(
124
+ f"stage {i} is not a PhaseScreen deformable mirror; got "
125
+ f"{type(stage_op).__name__}"
126
+ )
127
+ mask = jnp.asarray(dark_zone_mask)
128
+ if not bool(jnp.any(mask)):
129
+ raise ValueError("dark_zone_mask selects no pixels")
130
+
131
+ mode_counts = [path.stages[i].op.basis.n_modes for i in indices]
132
+ n_total = sum(mode_counts)
133
+ split_points = []
134
+ running = 0
135
+ for count in mode_counts[:-1]:
136
+ running += count
137
+ split_points.append(running)
138
+
139
+ spectrum = jacobian_field.spectrum
140
+ weights = jnp.ones(1) if spectrum is None else spectrum.weights
141
+ sqrt_weights = jnp.sqrt(weights)
142
+ n_dark = int(jnp.sum(mask))
143
+ stack_weights = jnp.repeat(sqrt_weights, n_dark)
144
+ if operating_point is None:
145
+ operating_point = jnp.zeros(n_total)
146
+
147
+ # A weighted view for the Jacobian only; the model's public
148
+ # dark-zone vector stays unweighted (the estimators' convention).
149
+ def weighted_dark_zone(data):
150
+ if data.ndim == 2:
151
+ return data[mask]
152
+ return (sqrt_weights[:, jnp.newaxis] * data[:, mask]).reshape(-1)
153
+
154
+ model = cls(
155
+ path=path,
156
+ indices=indices,
157
+ split_points=tuple(split_points),
158
+ mask=mask,
159
+ weights=weights,
160
+ sqrt_weights=sqrt_weights,
161
+ stack_weights=stack_weights,
162
+ g_dz=jnp.zeros((0, n_total)), # placeholder, replaced below
163
+ operating_point=operating_point,
164
+ )
165
+ g_dz = jax.jacfwd(
166
+ lambda c: weighted_dark_zone(model.focal_of(c, jacobian_field))
167
+ )(operating_point)
168
+ return eqx.tree_at(lambda m: m.g_dz, model, g_dz)
169
+
170
+
171
+ class AbstractController(eqx.Module):
172
+ """The control seam: a field estimate in, a command delta out.
173
+
174
+ ``command_delta`` returns ``(new_self, delta)`` so stateful laws (a
175
+ predictive feed-forward carrying an AR state) advance while stateless
176
+ ones (EFC, stroke minimization) return themselves unchanged.
177
+ """
178
+
179
+ def command_delta(self, estimate):
180
+ """The command update for an unweighted dark-zone field estimate."""
181
+ raise NotImplementedError
182
+
183
+
184
+ class EFCController(AbstractController):
185
+ """Electric-field conjugation: one regularized real least squares.
186
+
187
+ The classic dark-hole law: stack the Jacobian's real and imaginary rows
188
+ (a real command cancels a complex field), Tikhonov-regularize, and apply
189
+ a fixed gain. Energy minimization with a fixed multiplier is the same
190
+ matrix; stroke minimization differs only in how the multiplier is chosen.
191
+
192
+ Attributes:
193
+ control_matrix: ``(n_total, 2 n_stack)`` solve of the regularized
194
+ normal equations.
195
+ stack_weights: The model's per-(wavelength, pixel) sqrt weights.
196
+ gain: Loop gain (a differentiable leaf).
197
+ """
198
+
199
+ control_matrix: Array
200
+ stack_weights: Array
201
+ gain: Array
202
+
203
+ @classmethod
204
+ def build(cls, model, *, gain, regularization):
205
+ """The EFC law for a dark-zone model.
206
+
207
+ Args:
208
+ model: The ``DarkZoneModel`` (its ``g_dz`` is the plant).
209
+ gain: Loop gain.
210
+ regularization: Positive Tikhonov term.
211
+
212
+ Returns:
213
+ An ``EFCController``.
214
+ """
215
+ if regularization <= 0.0:
216
+ raise ValueError(f"regularization must be positive, got {regularization}")
217
+ response = jnp.concatenate([jnp.real(model.g_dz), jnp.imag(model.g_dz)], axis=0)
218
+ gram = response.T @ response + regularization * jnp.eye(model.n_total)
219
+ return cls(
220
+ control_matrix=jnp.linalg.solve(gram, response.T),
221
+ stack_weights=model.stack_weights,
222
+ gain=jnp.asarray(gain),
223
+ )
224
+
225
+ def command_delta(self, estimate):
226
+ """Weight the estimate, stack Re/Im, and apply the control matrix."""
227
+ weighted = self.stack_weights * estimate.reshape(-1)
228
+ residual = jnp.concatenate([jnp.real(weighted), jnp.imag(weighted)])
229
+ return self, -self.gain * (self.control_matrix @ residual)
230
+
231
+
232
+ class StrokeMinController(AbstractController):
233
+ """Stroke minimization: the least command that reaches a target contrast.
234
+
235
+ The dual framing of the same convex program as EFC: instead of a fixed
236
+ Tikhonov weight, pick per step the LARGEST multiplier (least stroke)
237
+ whose predicted linear residual still meets ``target_contrast``, falling
238
+ back to the deepest available correction when the target is out of
239
+ reach. Stateless.
240
+
241
+ Attributes:
242
+ response: Stacked real Jacobian rows ``[Re g_dz; Im g_dz]``.
243
+ rtr: Its Gram matrix.
244
+ stack_weights: The model's stacked sqrt weights.
245
+ n_dark: Dark-zone pixel count (contrast normalization).
246
+ mu_grid: Candidate multipliers, ascending.
247
+ target_contrast: The contrast the step tries to reach.
248
+ gain: Step gain on the chosen delta.
249
+ """
250
+
251
+ response: Array
252
+ rtr: Array
253
+ stack_weights: Array
254
+ n_dark: int = eqx.field(static=True)
255
+ mu_grid: Array
256
+ target_contrast: Array
257
+ gain: Array
258
+
259
+ @classmethod
260
+ def build(cls, model, *, target_contrast, mu_grid=None, gain=1.0):
261
+ """The stroke-minimizing law for a dark-zone model.
262
+
263
+ Args:
264
+ model: The ``DarkZoneModel``.
265
+ target_contrast: Dark-zone mean intensity to reach per step.
266
+ mu_grid: Candidate Lagrange multipliers (ascending); defaults to
267
+ a wide log grid.
268
+ gain: Step gain on the chosen delta.
269
+
270
+ Returns:
271
+ A ``StrokeMinController``.
272
+ """
273
+ if mu_grid is None:
274
+ mu_grid = jnp.logspace(-12, 0, 13)
275
+ response = jnp.concatenate([jnp.real(model.g_dz), jnp.imag(model.g_dz)], axis=0)
276
+ n_dark = int(jnp.sum(model.mask))
277
+ return cls(
278
+ response=response,
279
+ rtr=response.T @ response,
280
+ stack_weights=model.stack_weights,
281
+ n_dark=n_dark,
282
+ mu_grid=jnp.asarray(mu_grid),
283
+ target_contrast=jnp.asarray(target_contrast),
284
+ gain=jnp.asarray(gain),
285
+ )
286
+
287
+ def command_delta(self, estimate):
288
+ """Pick the least-stroke multiplier that meets the target contrast."""
289
+ weighted = self.stack_weights * estimate.reshape(-1)
290
+ residual = jnp.concatenate([jnp.real(weighted), jnp.imag(weighted)])
291
+ rhs = self.response.T @ residual
292
+ eye = jnp.eye(self.rtr.shape[0])
293
+
294
+ def candidate(mu):
295
+ delta = -jnp.linalg.solve(self.rtr + mu * eye, rhs)
296
+ predicted = residual + self.response @ delta
297
+ contrast = jnp.sum(jnp.abs(predicted) ** 2) / self.n_dark
298
+ return delta, contrast
299
+
300
+ deltas, contrasts = jax.vmap(candidate)(self.mu_grid)
301
+ feasible = contrasts <= self.target_contrast
302
+ # Largest feasible mu = least stroke; else the deepest correction.
303
+ least_stroke = jnp.argmax(
304
+ jnp.where(feasible, jnp.arange(self.mu_grid.shape[0]), -1)
305
+ )
306
+ deepest = jnp.argmin(contrasts)
307
+ chosen = jnp.where(jnp.any(feasible), least_stroke, deepest)
308
+ return self, self.gain * deltas[chosen]
309
+
310
+
311
+ class PredictiveController(AbstractController):
312
+ """A linear predictive feed-forward wrapped around EFC. Stateful.
313
+
314
+ Extrapolates the field estimate one step ahead
315
+ (``e_pred = e + alpha (e - e_prev)``) before applying the EFC law, so a
316
+ steadily drifting field is corrected at its predicted, not lagged,
317
+ value. ``alpha = 0`` reduces exactly to EFC.
318
+
319
+ Attributes:
320
+ efc: The inner EFC law.
321
+ prev_estimate: Last step's estimate (the carried state).
322
+ alpha: Extrapolation weight.
323
+ primed: Whether ``prev_estimate`` is real data yet.
324
+ """
325
+
326
+ efc: EFCController
327
+ prev_estimate: Array
328
+ alpha: Array
329
+ primed: Array
330
+
331
+ @classmethod
332
+ def build(cls, model, *, gain, regularization, alpha=1.0):
333
+ """A predictive law sharing EFC's matrix.
334
+
335
+ Args:
336
+ model: The ``DarkZoneModel``.
337
+ gain: Loop gain of the inner EFC.
338
+ regularization: Tikhonov term of the inner EFC.
339
+ alpha: Extrapolation weight (0 = plain EFC).
340
+
341
+ Returns:
342
+ A ``PredictiveController``.
343
+ """
344
+ n_stack = model.stack_weights.shape[0]
345
+ return cls(
346
+ efc=EFCController.build(model, gain=gain, regularization=regularization),
347
+ prev_estimate=jnp.zeros(n_stack, dtype=complex),
348
+ alpha=jnp.asarray(alpha),
349
+ primed=jnp.asarray(False),
350
+ )
351
+
352
+ def command_delta(self, estimate):
353
+ """Extrapolate the estimate, apply EFC, and advance the state."""
354
+ flat = estimate.reshape(-1)
355
+ predicted = jnp.where(
356
+ self.primed, flat + self.alpha * (flat - self.prev_estimate), flat
357
+ )
358
+ _, delta = self.efc.command_delta(predicted)
359
+ new_self = eqx.tree_at(
360
+ lambda c: (c.prev_estimate, c.primed),
361
+ self,
362
+ (flat, jnp.asarray(True)),
363
+ )
364
+ return new_self, delta
365
+
366
+
367
+ def close_dark_hole(
368
+ path,
369
+ input_field,
370
+ dm_indices,
371
+ dark_zone_mask,
372
+ *,
373
+ n_steps,
374
+ gain,
375
+ regularization,
376
+ estimator="oracle",
377
+ model_field=None,
378
+ probes=None,
379
+ probe_dm=None,
380
+ detector=None,
381
+ key=None,
382
+ ):
383
+ """Dig a dark hole with deformable mirrors by electric-field conjugation.
384
+
385
+ Linearizes the focal field with respect to the stacked DM command ONCE (the
386
+ control Jacobian is constant to first order in the small-signal dark-hole
387
+ regime), builds a regularized real control matrix, then runs a differentiable
388
+ ``lax.scan`` that RE-PROPAGATES for the measurement and updates the command
389
+ each step by swapping every DM's coefficients with ``eqx.tree_at`` -- never a
390
+ reconstruction, which would re-run the propagator's construction-time gates.
391
+ Because every propagation is a pure function, the loop differentiates through
392
+ the feedback (e.g. the final contrast with respect to the loop gain).
393
+
394
+ With one pupil DM the loop reaches only the PHASE quadrature, so it corrects a
395
+ one-sided dark zone and floors on any amplitude speckle. Adding a second,
396
+ out-of-pupil DM (a ``PhaseScreen`` at an ``INTERMEDIATE`` plane, reached
397
+ through a ``Fresnel`` relay) supplies the amplitude quadrature via the Talbot
398
+ conversion, which is what a symmetric (two-sided) or broadband dark hole needs.
399
+ The commands of every listed DM are concatenated into one vector, jointly
400
+ linearized, and solved together.
401
+
402
+ A chromatic ``input_field`` digs a BROADBAND hole: the dark-zone response is
403
+ stacked across wavelengths (each weighted by ``sqrt`` of the spectrum weight,
404
+ so the solve is a weighted least-squares) and the reported contrast is the
405
+ weight-averaged dark-zone intensity. Broadband correction is the second reason
406
+ for two DMs, since the amplitude chromaticity a single DM leaves is exactly
407
+ what the out-of-pupil DM cancels. The control Jacobian is a dense
408
+ ``jax.jacfwd`` over the full command, so it materializes the
409
+ ``(n_dark_zone, sum_modes)`` array -- fine for modest mode counts, but chunk it
410
+ or reuse a streamed linearization at scale. ``dark_zone_mask`` must be a
411
+ concrete (static) array for the loop to jit.
412
+
413
+ The ``estimator`` selects how the dark-zone field is measured each step. The
414
+ default ``"oracle"`` reads the true field by re-propagation (perfect
415
+ knowledge, the achievable-contrast reference). ``"pairwise"`` instead
416
+ estimates the field from probe images (see
417
+ :func:`tiptilt.sensing.estimate_field_pairwise`), the hardware-realistic
418
+ loop: it builds the control Jacobian on the ``model_field`` and floors on the
419
+ model mismatch rather than digging arbitrarily deep. A chromatic
420
+ ``input_field`` drives a BROADBAND estimated loop by sub-band probing: the
421
+ field is estimated per wavelength (``probe_measurement`` reads a per-sub-band
422
+ image) and the DMs are driven against the same stacked, ``sqrt``-weighted
423
+ per-wavelength response the oracle broadband loop uses.
424
+
425
+ This is a thin driver over the ``DarkZoneModel`` / ``AbstractEstimator`` /
426
+ ``AbstractController`` seams; swap the law or the sensor by driving those
427
+ seams directly (the maintenance driver does).
428
+
429
+ Args:
430
+ path: An ``OpticalPath`` ending at the focal plane whose ``dm_indices``
431
+ stages are ``PhaseScreen`` deformable mirrors.
432
+ input_field: The entrance field carrying the aberration to correct.
433
+ dm_indices: A stage index, or a tuple of stage indices, each a
434
+ ``PhaseScreen`` DM. A bare int is treated as a single-DM loop.
435
+ dark_zone_mask: Boolean ``(y, x)`` focal-plane region to null (must
436
+ select at least one pixel).
437
+ n_steps: Number of control iterations.
438
+ gain: Loop gain (the fraction of the computed correction applied).
439
+ regularization: Positive Tikhonov regularization for the control-matrix
440
+ inverse.
441
+ estimator: ``"oracle"`` (read the true field) or ``"pairwise"`` (estimate
442
+ it by probing).
443
+ model_field: Design entrance field (no aberration) for the ``"pairwise"``
444
+ control Jacobian and probe model; defaults to ``input_field``.
445
+ probes: Probe command vectors for the probe deformable mirror (required
446
+ for ``"pairwise"``; see :func:`tiptilt.sensing.probe_set`).
447
+ probe_dm: Stage index of the probe deformable mirror; defaults to the
448
+ first of ``dm_indices``.
449
+ detector: Optional ``callable(image, key) -> image`` applying measurement
450
+ noise to each probe image in the ``"pairwise"`` loop.
451
+ key: PRNG key for the detector, split per step.
452
+
453
+ Returns:
454
+ ``(command, dark_zone_history)``: the final stacked DM command (the DMs'
455
+ coefficients concatenated in ``dm_indices`` order) and the mean dark-zone
456
+ intensity at each iteration.
457
+
458
+ Raises:
459
+ TypeError: If any ``dm_indices`` stage is not a ``PhaseScreen``.
460
+ ValueError: If ``regularization`` is not positive, the dark zone is
461
+ empty, ``estimator`` is unknown, or an estimated loop is missing
462
+ ``probes``.
463
+ """
464
+ indices = (dm_indices,) if isinstance(dm_indices, int) else tuple(dm_indices)
465
+ if estimator not in ("oracle", "pairwise", "kalman"):
466
+ raise ValueError(
467
+ f"estimator must be 'oracle', 'pairwise', or 'kalman', got {estimator!r}"
468
+ )
469
+ estimated = estimator in ("pairwise", "kalman")
470
+ if estimated:
471
+ if probes is None:
472
+ raise ValueError(f"estimator={estimator!r} requires probes")
473
+ if probe_dm is None:
474
+ probe_dm = indices[0]
475
+ # The control Jacobian is known from the model; the honest estimated loop
476
+ # builds it on the unaberrated model field, not the (unknown) true field.
477
+ jacobian_field = (
478
+ model_field if (estimated and model_field is not None) else input_field
479
+ )
480
+ dz_model = DarkZoneModel.build(
481
+ path, indices, dark_zone_mask, jacobian_field=jacobian_field
482
+ )
483
+ controller = EFCController.build(dz_model, gain=gain, regularization=regularization)
484
+
485
+ if estimated:
486
+ # Probe-and-estimate loops: Python-unrolled (still a pure composition,
487
+ # so they differentiate); probing is a multi-propagation, keyed step.
488
+ keys = (
489
+ list(jax.random.split(key, n_steps))
490
+ if key is not None
491
+ else [None] * n_steps
492
+ )
493
+ model = input_field if model_field is None else model_field
494
+ if estimator == "pairwise":
495
+ sensor = PairwiseEstimator(
496
+ input_field=input_field,
497
+ model_field=model,
498
+ probes=tuple(probes),
499
+ probe_dm=probe_dm,
500
+ detector=detector,
501
+ regularization=regularization,
502
+ )
503
+ else:
504
+ sensor = KalmanEstimator.build(
505
+ dz_model,
506
+ input_field=input_field,
507
+ model_field=model,
508
+ probes=tuple(probes),
509
+ probe_dm=probe_dm,
510
+ detector=detector,
511
+ )
512
+ command = jnp.zeros(dz_model.n_total)
513
+ history = []
514
+ for i in range(n_steps):
515
+ history.append(dz_model.contrast(dz_model.focal_of(command, input_field)))
516
+ sensor, e_hat = sensor.estimate(dz_model, command, key=keys[i])
517
+ controller, delta = controller.command_delta(e_hat)
518
+ command = command + delta
519
+ return command, jnp.stack(history)
520
+
521
+ def step(command, _):
522
+ data = dz_model.focal_of(command, input_field) # ONE oracle read
523
+ estimate = dz_model.dark_zone_unweighted(data)
524
+ _, delta = controller.command_delta(estimate)
525
+ return command + delta, dz_model.contrast(data)
526
+
527
+ return jax.lax.scan(step, jnp.zeros(dz_model.n_total), None, length=n_steps)