Skip to content

Donut Models

Models for fitting single or multiple out-of-focus (donut) stellar images.

Base class

danish.donut_model.BaseDonutModel

Base class for donut models.

Parameters:

Name Type Description Default
factory DonutFactoryBase
required
bkg_order int

Order of polynomial background model to use. If -1, no background.

required
npix int

Number of pixels along image edge. Must be odd.

required
seed int

Random seed for use when creating noisy donut images.

required
atm_mode str

Atmospheric PSF parameterization. 'fwhm' for scalar FWHM (default), 'ixx' for second moment tensor (Ixx, Ixy, Iyy) in arcsec^2.

'fwhm'
loss_fn callable

Residual function with signature (data, model, var) -> array. Defaults to danish.loss.chi2_loss. Must be elementwise: pixel i's residual may depend on the model at pixel i only. An analytic jacobian additionally needs a loss whose derivative it knows, which at present means one from danish.loss.systematic_loss; see _dchi_dmodel.

None
Source code in danish/donut_model.py
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
class BaseDonutModel:
    """Base class for donut models.

    Parameters
    ----------
    factory : DonutFactoryBase
    bkg_order : int
        Order of polynomial background model to use.  If -1, no background.
    npix : int
        Number of pixels along image edge. Must be odd.
    seed : int
        Random seed for use when creating noisy donut images.
    atm_mode : str, optional
        Atmospheric PSF parameterization.  'fwhm' for scalar FWHM (default),
        'ixx' for second moment tensor (Ixx, Ixy, Iyy) in arcsec^2.
    loss_fn : callable, optional
        Residual function with signature ``(data, model, var) -> array``.
        Defaults to `danish.loss.chi2_loss`.  Must be elementwise: pixel i's
        residual may depend on the model at pixel i only.  An analytic
        jacobian additionally needs a loss whose derivative it knows, which at
        present means one from `danish.loss.systematic_loss`; see
        `_dchi_dmodel`.
    """
    # I think Ixx might formally diverge for a Kolmogorov profile, but we need
    # something to convert between FWHM and Ixx/Iyy for the atmospheric kernel,
    # So we will just use the constant factor here.  This is computed from
    # galsim.Kolmogorov(fwhm=1).calculateMomentRadius().  So we have:
    #   sigma = KOLM_CONST * fwhm
    #   Ixx = Iyy = sigma^2 = (KOLM_CONST * fwhm)^2
    # and
    #   fwhm = sigma / KOLM_CONST = sqrt(Ixx) / KOLM_CONST
    # which we will generalize to
    #   fwhm = sqrt((Ixx + Iyy) / 2) / KOLM_CONST

    KOLM_CONST = 0.651

    def __init__(
        self, factory, npix, seed, bkg_order, atm_mode='fwhm', loss_fn=None,
    ):
        assert npix % 2 == 1, "npix must be odd"
        assert atm_mode in ('fwhm', 'ixx'), "atm_mode must be 'fwhm' or 'ixx'"

        self.factory = factory
        self.npix = npix
        self.no2 = (npix-1)//2
        self.gsrng = galsim.BaseDeviate(seed)
        # arcseconds per pixel
        # This is only used for the atmospheric part of the model, where we
        # ignore distortion and draw a circular profile in image coordinates.
        self.sky_scale = (
            3600*np.rad2deg(1/factory.focal_length)*factory.pixel_scale
        )
        self.bkg_order = bkg_order
        self.nbkg = (bkg_order+1)*(bkg_order+2)//2
        self.atm_mode = atm_mode
        self.loss_fn = loss_fn if loss_fn is not None else chi2_loss
        # Triangle meshes for this model's field angles, keyed on (thx, thy).
        # Populated by _precompute_meshes once the subclass knows its angles.
        self._meshes = {}
        # Projection bases, keyed on donut index: each donut folds its own
        # reference wavefront into its projection constant, so donuts sharing
        # a field angle still get one each.  See _precompute_projections.
        self._projections = {}
        # Focal-plane offsets, constant across a fit.  Only the single-donut
        # model exposes them; the shared render paths read them from here so
        # that they do not have to know which subclass they are serving.
        self._x_offset = None
        self._y_offset = None

    @property
    def natm(self):
        """Number of atmospheric parameters (1 for fwhm, 3 for ixx)."""
        return 1 if self.atm_mode == 'fwhm' else 3

    def _precompute_meshes(self, thxs, thys):
        """Build this model's triangle meshes once, up front.

        A model's field angles are fixed at construction, so the meshes they
        imply can be built eagerly.

        No-op for factories that do not render from a mesh (the inverse
        factory), in which case `_opt_kernel` falls back to `factory.image`.

        Parameters
        ----------
        thxs, thys : sequence of float
            Field angles in radians.
        """
        if not hasattr(self.factory, '_build_mesh'):
            return
        for thx, thy in zip(thxs, thys):
            if (thx, thy) not in self._meshes:
                self._meshes[(thx, thy)] = self.factory._build_mesh(thx, thy)

    def _zernike_param_basis(self):
        """Construct a basis of per-donut Zernike coefficients, one slice per
        wavefront parameter.

        Each slice holds the Zernike coefficients this model's `_get_z_fits`
        produces for a unit of one wavefront parameter, so that

            z_fits = sum_i params[i] * basis[..., i]

        reproduces `_get_z_fits(params)`.  Equivalently each slice is
        d(Zernike coefficient)/d(parameter).

        Requires that `_get_z_fits` is a linear function of the wavefront
        parameters -- `test_zernike_param_basis_is_linear` pins the
        requirement.

        Returns
        -------
        array of float, shape (nstar, nzk, nwavefront)
            Zernike coefficients per donut for each wavefront parameter.
        """
        cols = []
        unit = np.zeros(self._nwavefront)
        for i in range(self._nwavefront):
            unit[i] = 1.0
            cols.append(np.array(self._get_z_fits(unit)))
            unit[i] = 0.0
        return np.stack(cols, axis=-1)

    def _precompute_projections(self, z_refs, x_offset=None, y_offset=None):
        """Precompute each mesh's vertex projection over the fitted subspace.

        Two bases meet here: `_zernike_param_basis` takes wavefront parameters
        to Zernike coefficients, and `pupil_to_focal_basis` takes Zernike
        coefficients to vertex pixel positions.  Only the coefficients the
        first can reach are worth carrying -- any Noll index absent from the
        parameterization is fixed for the whole fit, so its contribution is
        folded into a constant position and its column dropped.

        What is stored per donut is that constant plus the projection
        restricted to the reachable coefficients.  A model call projects with
        one matrix product over that subspace, and contracting the same matrix
        with `_zernike_param_basis` gives d(vertex)/d(wavefront parameter) for
        an analytic Jacobian.  The constant carries the donut's own fixed
        aberrations, so donuts sharing a field angle share only the mesh
        geometry, which depends on the angle alone.

        Requires `_precompute_meshes` to have run, and is a no-op without it.

        Parameters
        ----------
        z_refs : array of float
            Reference aberrations per donut, in meters.  Must be ordered to
            match `self.thxs`/`self.thys`.
        x_offset, y_offset : galsim.zernike.Zernike, optional
            Additional focal plane offsets, constant across the fit.
        """
        # A model with no wavefront parameters -- one simulating images rather
        # than fitting them -- has no subspace to build a basis over.
        if not self._meshes or not self._nwavefront:
            return
        factory = self.factory
        dzkdp = self._zernike_param_basis()
        nterm = dzkdp.shape[1]
        # coef[j] labels the jth Noll index, so coef[0] is unused and a
        # length-1 coefficient array carries no Zernike terms at all.
        if nterm < 2:
            return
        # A coefficient is reachable if any parameter moves it, in any donut.
        self._zk_reach = np.nonzero(np.any(dzkdp != 0, axis=(0, 2)))[0]
        self._dzkdp = dzkdp[:, self._zk_reach, :]
        reach = self._zk_reach
        # Complement of the above, for callers that have to check whether a
        # perturbation reaches outside the subspace the projection covers.
        self._zk_fixed = np.ones(nterm, dtype=bool)
        self._zk_fixed[reach] = False
        # Per donut rather than per mesh: _meshes is keyed by angle and so is
        # shorter than z_refs whenever two donuts share one.
        for i, z_ref in enumerate(z_refs):
            thx, thy = self.thxs[i], self.thys[i]
            verts = self._meshes[(thx, thy)]["vertices"]
            x0, y0, dxdz, dydz = pupil_to_focal_basis(
                verts[:, 0], verts[:, 1],
                aberrations=z_ref, nterm=nterm,
                R_outer=factory.R_outer, R_inner=factory.R_inner,
                focal_length=factory.focal_length,
                pixel_scale=factory.pixel_scale,
                x_offset=x_offset, y_offset=y_offset,
            )
            # Unreachable leading coefficients keep their reference value, so
            # they join the fixed tail already in x0/y0.
            fixed = np.zeros(nterm)
            fixed[:] = np.asarray(z_ref, dtype=float)[:nterm]
            fixed[reach] = 0.0
            self._projections[i] = (
                x0 + dxdz @ fixed,
                y0 + dydz @ fixed,
                np.ascontiguousarray(dxdz[:, reach]),
                np.ascontiguousarray(dydz[:, reach]),
            )

    @lru_cache(maxsize=1000)
    def _atm_kernel(self, dx, dy, Ixx, Ixy, Iyy):
        """Compute atmospheric kernel.

        Parameters
        ----------
        dx, dy : float
            Offset in arcseconds.
        Ixx, Ixy, Iyy : float, optional
            Second moment tensor in arcsec^2.

        Returns
        -------
        array of float
            Atmospheric kernel array.
        """
        fwhm = np.sqrt((Ixx + Iyy) / 2) / self.KOLM_CONST
        e1 = (Ixx - Iyy) / (Ixx + Iyy)
        e2 = 2*Ixy / (Ixx + Iyy)
        obj = galsim.Kolmogorov(fwhm=fwhm).shear(e1=e1, e2=e2).shift(dx, dy)
        img = obj.drawImage(nx=self.no2, ny=self.no2, scale=self.sky_scale)
        return img.array

    @lru_cache(maxsize=1000)
    def _opt_kernel(
        self,
        zk,
        thx, thy,
        x_offset=None, y_offset=None,
        idx=None,
    ):
        """Compute optical kernel.

        Parameters
        ----------
        zk : array of float
            Zernike coefficients.
        thx, thy : float
            Field angle in radians.
        x_offset, y_offset : galsim.zernike.Zernike, optional
            Additional pupil distortion coefficients.
        idx : int, optional
            Which donut this is, selecting its precomputed projection.
            Omitted, the projection is skipped and the full Zernike series
            evaluated instead -- slower, same image.

        Returns
        -------
        array of float
            Optical kernel array.
        """
        if hasattr(self.factory, '_image_from_mesh'):
            # This model's angles are precomputed; fall back to the factory's
            # own memo for any angle we were not constructed with.
            mesh = self._meshes.get((thx, thy))
            if mesh is None:
                mesh = self.factory._get_mesh(thx, thy)
            basis = None if idx is None else self._projections.get(idx)
            verts_px = None
            if basis is not None:
                x0, y0, dxdz, dydz = basis
                head = np.asarray(zk)[self._zk_reach]
                verts_px = np.column_stack(
                    [x0 + dxdz @ head, y0 + dydz @ head]
                )
            return self.factory._image_from_mesh(
                mesh,
                aberrations=zk,
                focal_length=self.factory.focal_length,
                pixel_scale=self.factory.pixel_scale,
                npix=self.npix,
                x_offset=x_offset, y_offset=y_offset,
                verts_px=verts_px,
            )
        result = self.factory.image(
            aberrations=zk,
            x_offset=x_offset, y_offset=y_offset,
            thx=thx, thy=thy,
            npix=self.npix,
        )
        return result

    @lru_cache(maxsize=1000)
    def _bkg(
        self,
        bkg
    ):
        """Compute background model.

        Parameters
        ----------
        bkg : array of float
            Background polynomial coefficients.

        Returns
        -------
        array of float
            Background model array.
        """
        no2 = self.no2
        zkbkg = galsim.zernike.Zernike([0]+list(bkg), R_outer=no2)
        result = zkbkg(*np.mgrid[-no2:no2+1, -no2:no2+1][::-1])
        return result

    @lru_cache(maxsize=100)
    def _model(
        self,
        flux, dx, dy, Ixx, Ixy, Iyy, zk, bkg,
        thx, thy,
        x_offset=None, y_offset=None,
        sky_level=None,
        idx=None
    ):
        """Compute model image.

        Parameters
        ----------
        flux : float
            Flux level at which to set image.
        dx, dy : float
            Offset in arcseconds.
        Ixx, Ixy, Iyy : float
            Second moment tensor in arcsec^2.
        zk : array of float
            Zernike coefficients.
        bkg : array of float
            Background polynomial coefficients.
        thx, thy : float
            Field angle in radians.
        x_offset, y_offset : galsim.zernike.Zernike, optional
            Additional pupil distortion coefficients.
        sky_level : float, optional
            Sky level to use when adding Poisson noise to image.
        idx : int, optional
            Which donut this is; selects the precomputed projection.  See
            `_opt_kernel`.

        Returns
        -------
        array of float
            Model image array.
        """
        atm = self._atm_kernel(dx, dy, Ixx, Ixy, Iyy)
        opt = self._opt_kernel(
            zk, thx, thy, x_offset=x_offset, y_offset=y_offset, idx=idx
        )
        arr = convolve(opt, atm)
        arr *= flux

        if bkg:
            arr += self._bkg(bkg)

        if sky_level is not None:
            pn = galsim.PoissonNoise(self.gsrng, sky_level=sky_level)
            img = galsim.Image(arr)
            img.addNoise(pn)
            arr = img.array

        return arr

    def _chi(
        self,
        data,
        model,
        var
    ):
        """Compute chi = (data - model)/error.

        Parameters
        ----------
        data : array of float
            Observed image data.
        model : array of float
            Model image data.
        var : array of float
            Variance of the observed data.

        Returns
        -------
        array of float
            Chi values for each pixel.
        """
        result = self.loss_fn(data, model, var).ravel()
        return result

    def _can_use_analytic(self):
        """Whether the analytic wavefront Jacobian is available.

        It needs the mesh renderer's projection bases, which only the triangle
        factory provides and only when the fit varies something.

        Covers the renderer alone.  The loss has to be differentiable too, but
        a loss that is not is a caller's mistake rather than a configuration
        to route around, so `_dchi_dmodel` raises on it instead of reporting
        it here and falling back to differencing.
        """
        return bool(self._projections)

    def _unpack_per_donut(self, params):
        """Unpack `params` into the per-donut view the shared renders want.

        The multi-donut parameterization is already per-donut, so this is just
        `unpack_params` there.  The single-donut one is scalar -- `flux` not
        `fluxes` -- and overrides this to present itself as the nstar=1 case.

        Parameters
        ----------
        params : sequence of float
            Packed parameters.

        Returns
        -------
        dict
            Keys 'fluxes', 'dxs', 'dys', 'bkgs' and 'wavefront_params', plus
            the atmospheric keys for this model's `atm_mode`.  The per-donut
            entries are indexable by donut.
        """
        return self.unpack_params(params)

    def _dchi_dmodel(self, datum, model, var):
        """d(chi)/d(model), elementwise.

        The loss divides by an error that is itself a function of the model, so
        this is not simply -1/sqrt(var + model).  Derived by differentiating
        `danish.loss.systematic_loss`, whose `alpha` is recovered from the loss
        rather than stored.

        One value per pixel presumes pixel i's residual depends on the model at
        pixel i alone, which is what makes d(chi)/d(model) a diagonal the
        caller can multiply elementwise.  A loss coupling pixels -- whitening
        by a non-diagonal covariance, say, or normalizing by a model-dependent
        scalar -- has a dense d(chi_i)/d(model_j) that no array of this shape
        can carry, so such a loss is refused here rather than approximated.

        Parameters
        ----------
        datum : array of float
            Observed image.
        model : array of float
            Model image.
        var : float or array of float
            Sky variance.

        Returns
        -------
        array of float
            d(chi)/d(model) at each pixel.

        Raises
        ------
        ValueError
            If the loss carries no `alpha`, and so no derivative this knows how
            to take.  `method='fd'` differences the loss as a whole and works
            for any of them.
        """
        alpha = getattr(self.loss_fn, 'alpha', None)
        if alpha is None:
            raise ValueError(
                "analytic jacobian needs a loss whose derivative is known;"
                f" {self.loss_fn!r} carries no 'alpha'. Use method='fd'."
            )
        denom = var + model + (alpha*model)**2
        return (
            -1.0/np.sqrt(denom)
            - (datum - model)*(1.0 + 2*alpha**2*model)/(2*denom**1.5)
        )

    def _wavefront_jac_analytic(self, params, data, vars):
        """Analytic d(chi)/d(wavefront parameter), one column per parameter.

        The wavefront reaches chi through the optical kernel alone, so

            d(chi)/dp = d(chi)/d(model) * flux * convolve(d(opt)/dp, atm)

        with d(opt)/dp coming from one clip pass over the mesh rather than a
        re-render per parameter.  The convolution is linear, so it applies to
        each derivative image just as it does to the kernel itself, and the
        loss' own dependence on the model enters through d(chi)/d(model).

        Written against the per-donut view every donut model shares --
        `nstar` field angles, their meshes and projections -- so it serves the
        single-donut case as the nstar=1 instance of it.  Only the wavefront
        columns are returned; where they belong in the full Jacobian is the
        caller's parameterization to know.

        Parameters
        ----------
        params : sequence of float
            Packed parameters, as for `jac`.
        data : array of float.  Shape: (nstar, npix, npix)
            Images against which chi is computed.
        vars : sequence of array or sequence of float
            Sky variances, as for `jac`.

        Returns
        -------
        array of float, shape (nstar*npix**2, nwavefront)
            Jacobian columns for the wavefront parameters.
        """
        npix = self.npix
        pdict = self._unpack_per_donut(params)
        nwavefront = self._dzkdp.shape[2]
        out = np.empty((self.nstar*npix**2, nwavefront))

        if self.atm_mode == 'fwhm':
            Ixx = Iyy = (pdict['fwhm'] * self.KOLM_CONST) ** 2
            Ixy = 0.0
        else:
            Ixx, Ixy, Iyy = pdict['Ixx'], pdict['Ixy'], pdict['Iyy']
        z_fits = self._get_z_fits(pdict['wavefront_params'])

        for i in range(self.nstar):
            thx, thy = self.thxs[i], self.thys[i]
            x0, y0, dxdz, dydz = self._projections[i]
            zk = np.array(self.z_refs[i])
            zk[:len(z_fits[i])] += z_fits[i]
            head = zk[self._zk_reach]
            verts_px = np.column_stack([x0 + dxdz @ head, y0 + dydz @ head])
            dverts = np.stack(
                [dxdz @ self._dzkdp[i], dydz @ self._dzkdp[i]], axis=1
            )
            dopt = self.factory._image_derivs_from_mesh(
                self._meshes[(thx, thy)], verts_px, dverts, npix=npix
            )

            atm = self._atm_kernel(pdict['dxs'][i], pdict['dys'][i], Ixx, Ixy, Iyy)
            model = self._model(
                pdict['fluxes'][i], pdict['dxs'][i], pdict['dys'][i],
                Ixx, Ixy, Iyy, tuple(zk), tuple(pdict['bkgs'][i]),
                thx=thx, thy=thy,
                x_offset=self._x_offset, y_offset=self._y_offset,
                idx=i,
            )
            dchi_dmodel = self._dchi_dmodel(data[i], model, vars[i])

            s = slice(i*npix**2, (i+1)*npix**2)
            for p in range(nwavefront):
                dmodel = pdict['fluxes'][i] * convolve(dopt[p], atm)
                out[s, p] = (dchi_dmodel * dmodel).ravel()
        return out

natm property

natm

Number of atmospheric parameters (1 for fwhm, 3 for ixx).

Single-donut model

danish.donut_model.SingleDonutModel

Bases: BaseDonutModel

Model individual donuts using single Zernike offsets to a reference single Zernike series.

Parameters:

Name Type Description Default
factory DonutFactoryBase
required
bkg_order int

Order of polynomial background model to use. If -1, no background.

-1
z_ref array of float

Constant reference Zernike coefs to add to fitted coefficients. [0] is ignored, [1] is piston, [4] is defocus, etc.

None
x_offset Zernike

Additional pupil distortion coefficients.

None
y_offset Zernike

Additional pupil distortion coefficients.

None
z_terms sequence of int

Which Zernike coefficients to include in the fit. E.g., [4,5,6,11] will fit defocus, astigmatism, and spherical.

()
thx float

Field angle in radians.

None
thy float

Field angle in radians.

None
npix int

Number of pixels along image edge. Must be odd.

181
seed int

Random seed for use when creating noisy donut images with this class.

57721
Source code in danish/donut_model.py
class SingleDonutModel(BaseDonutModel):
    """Model individual donuts using single Zernike offsets to a reference
    single Zernike series.

    Parameters
    ----------
    factory : DonutFactoryBase
    bkg_order : int, optional
        Order of polynomial background model to use.  If -1, no background.
    z_ref : array of float
        Constant reference Zernike coefs to add to fitted coefficients.
        [0] is ignored, [1] is piston, [4] is defocus, etc.
    x_offset, y_offset : galsim.zernike.Zernike, optional
        Additional pupil distortion coefficients.
    z_terms : sequence of int
        Which Zernike coefficients to include in the fit.  E.g.,
        [4,5,6,11] will fit defocus, astigmatism, and spherical.
    thx, thy : float
        Field angle in radians.
    npix : int
        Number of pixels along image edge.  Must be odd.
    seed : int
        Random seed for use when creating noisy donut images with this class.
    """
    def __init__(
        self,
        factory, *,
        bkg_order=-1,
        z_ref=None,
        x_offset=None, y_offset=None,
        z_terms=(),
        thx=None, thy=None,
        npix=181,
        seed=57721,
        loss_fn=None,
    ):
        super().__init__(
            factory, npix, seed, bkg_order, loss_fn=loss_fn,
        )
        self.z_ref = z_ref
        self.x_offset = x_offset
        self.y_offset = y_offset
        self._x_offset = x_offset
        self._y_offset = y_offset
        self.z_terms = z_terms
        self.thx = thx
        self.thy = thy
        self._nwavefront = len(z_terms)
        # One donut is the nstar=1 case of many, and the analytic Jacobian is
        # written against that per-donut view.  Expose it so the shared code
        # can address this model without special-casing; the scalar thx/thy/
        # z_ref above stay the ones `model()` and callers use.
        self.nstar = 1
        self.thxs = [thx]
        self.thys = [thy]
        self.z_refs = [z_ref]
        if thx is not None and thy is not None:
            self._precompute_meshes([thx], [thy])
            if z_ref is not None:
                self._precompute_projections(
                    [z_ref], x_offset=x_offset, y_offset=y_offset
                )

    def _get_z_fits(self, z_fit):
        """Convert this class's wavefront parameterization into individual
        donut Zernike coefficients.

        The parameters here *are* Zernike offsets, so this just scatters them
        into their Noll slots -- the same mapping `model` applies inline.

        Parameters
        ----------
        z_fit : array of float
            Zernike perturbations, one per entry of `z_terms`.

        Returns
        -------
        z_fits : array of float, shape (1, max(z_terms)+1)
            Single Zernike coefficients, wrapped in the one-donut outer
            dimension the shared code indexes by donut.
        """
        nzk = max(self.z_terms, default=0) + 1
        out = np.zeros((1, nzk))
        for i, term in enumerate(self.z_terms):
            out[0, term] = z_fit[i]
        return out

    def _unpack_per_donut(self, params):
        """Present this model's scalar parameters as the nstar=1 case.

        See `BaseDonutModel._unpack_per_donut`.
        """
        pdict = self.unpack_params(params)
        return dict(
            fluxes=[pdict["flux"]],
            dxs=[pdict["dx"]],
            dys=[pdict["dy"]],
            fwhm=pdict["fwhm"],
            wavefront_params=pdict["z_fit"],
            bkgs=[pdict["bkg"]],
        )

    def model(
        self,
        flux, dx, dy, fwhm, z_fit, *,
        bkg=(),
        sky_level=None,
    ):
        """Compute donut model image.

        Parameters
        ----------
        flux : float
            Flux level at which to set image.
        dx, dy : float
            Offset in arcseconds.
        fwhm : float
            Full width half maximum of Kolmogorov kernel.
        z_fit : sequence of float
            Zernike perturbations.
        bkg : sequence of float
            Background polynomial coefficients.
        sky_level : float
            Sky level to use when adding Poisson noise to image.

        Returns
        -------
        img : array of float
            Model image.
        """
        Ixx = Iyy = (fwhm * self.KOLM_CONST) ** 2
        Ixy = 0.0
        zk = np.array(self.z_ref)
        for i, term in enumerate(self.z_terms):
            zk[term] += z_fit[i]
        return self._model(
            flux, dx, dy, Ixx, Ixy, Iyy,
            tuple(zk), tuple(bkg),
            self.thx, self.thy,
            x_offset=self.x_offset, y_offset=self.y_offset,
            sky_level=sky_level,
            idx=0,  # the one donut
        )

    def pack_params(self, *, flux, dx, dy, fwhm, z_fit, bkg=()):
        """Pack parameters into a single tuple for optimization.

        Parameters
        ----------
        flux : float
            Flux level at which to set image.
        dx, dy : float
            Offset in arcseconds.
        fwhm : float
            Full width half maximum of Kolmogorov kernel.
        z_fit : array of float
            Zernike perturbations.
        bkg : array of float
            Background polynomial coefficients.

        Returns
        -------
        tuple of float
            Packed parameters.
        """
        return (flux, dx, dy, fwhm, *z_fit, *bkg)

    def unpack_params(self, params):
        """
        Unpack parameters from the single tuple used for optimization.

        Parameters
        ----------
        params : sequence of float
            Packed parameters tuple as returned by `pack_params`.

        Returns
        -------
        dict
            Dictionary with keys 'flux', 'dx', 'dy', 'fwhm', 'z_fit', and 'bkg'.
        """
        flux, dx, dy, fwhm, *rest = params
        out = dict(
            flux=flux,
            dx=dx,
            dy=dy,
            fwhm=fwhm,
        )
        split = len(rest) - self.nbkg
        out["z_fit"] = rest[:split]
        out["bkg"] = rest[split:]
        return out

    def chi(
        self, params, data, var
    ):
        """Compute chi = (data - model)/error.

        The error is modeled as sqrt(model + var).

        Parameters
        ----------
        params : sequence of float
            Order is: (flux, dx, dy, fwhm, *z_fit, *bkg)
        data : array of float (npix, npix)
            Image against which to compute chi.
        var : float or array of float (npix, npix)
            Variance of the sky only.  Do not include Poisson contribution of
            the signal, as this will be added from the current model.

        Returns
        -------
        chi : array of float
            Flattened array of chi residuals.
        """
        mod = self.model(**self.unpack_params(params))
        return self._chi(data, mod, var)

    def jac(
        self, params, data, var, method='analytic'
    ):
        """Compute jacobian d(chi)/d(param).

        Parameters
        ----------
        params : sequence of float
            Order is: (flux, dx, dy, fwhm, *z_fit, *bkg)
        data : array of float
            Image against which to compute chi.
        var : float or array of float (npix, npix)
            Variance of the sky only.  Do not include Poisson contribution of
            the signal, as this will be added from the current model.
        method : str, optional
            'analytic' (default) differentiates the Zernike columns in closed
            form, which is both faster and more accurate than the alternative
            -- a one-sided difference at 1e-8 m carries a few percent error.
            'fd' forces the difference quotient for every column.  Falls back
            to 'fd' where no analytic path exists, i.e. for any factory that
            does not render from a mesh.

        Returns
        -------
        jac : array of float
            Jacobian array d(chi)/d(param).  First dimension is pixels, second
            dimension is param.

        Raises
        ------
        ValueError
            If `method` is neither 'analytic' nor 'fd'.
        """
        _check_jac_method(method)
        out = np.zeros((self.npix**2, len(params)))
        chi0 = self.chi(params, data, var)

        flux = params[0]
        step = [
            1e-3 * flux,  # flux
            0.01,         # dx
            0.01,         # dy
            0.01          # fwhm
        ]
        step += [1e-8]*len(self.z_terms)  # Zernikes (in meters)
        step += [0.01]*self.nbkg

        # Zernike columns, which the analytic path replaces.  3 offsets plus
        # the atmospheric parameter precede them; see pack_params.
        wf0 = 3 + self.natm
        nwavefront = len(self.z_terms)
        analytic = method == 'analytic' and self._can_use_analytic()

        for i in range(len(params)):
            if analytic and wf0 <= i < wf0 + nwavefront:
                continue
            params1 = np.array(params)
            params1[i] += step[i]
            chi1 = self.chi(params1, data, var)
            out[:, i] = (chi1-chi0)/step[i]

        if analytic:
            out[:, wf0:wf0+nwavefront] = self._wavefront_jac_analytic(
                params, data[np.newaxis], [var]
            )

        return out

model

model(flux, dx, dy, fwhm, z_fit, *, bkg=(), sky_level=None)

Compute donut model image.

Parameters:

Name Type Description Default
flux float

Flux level at which to set image.

required
dx float

Offset in arcseconds.

required
dy float

Offset in arcseconds.

required
fwhm float

Full width half maximum of Kolmogorov kernel.

required
z_fit sequence of float

Zernike perturbations.

required
bkg sequence of float

Background polynomial coefficients.

()
sky_level float

Sky level to use when adding Poisson noise to image.

None

Returns:

Name Type Description
img array of float

Model image.

Source code in danish/donut_model.py
def model(
    self,
    flux, dx, dy, fwhm, z_fit, *,
    bkg=(),
    sky_level=None,
):
    """Compute donut model image.

    Parameters
    ----------
    flux : float
        Flux level at which to set image.
    dx, dy : float
        Offset in arcseconds.
    fwhm : float
        Full width half maximum of Kolmogorov kernel.
    z_fit : sequence of float
        Zernike perturbations.
    bkg : sequence of float
        Background polynomial coefficients.
    sky_level : float
        Sky level to use when adding Poisson noise to image.

    Returns
    -------
    img : array of float
        Model image.
    """
    Ixx = Iyy = (fwhm * self.KOLM_CONST) ** 2
    Ixy = 0.0
    zk = np.array(self.z_ref)
    for i, term in enumerate(self.z_terms):
        zk[term] += z_fit[i]
    return self._model(
        flux, dx, dy, Ixx, Ixy, Iyy,
        tuple(zk), tuple(bkg),
        self.thx, self.thy,
        x_offset=self.x_offset, y_offset=self.y_offset,
        sky_level=sky_level,
        idx=0,  # the one donut
    )

pack_params

pack_params(*, flux, dx, dy, fwhm, z_fit, bkg=())

Pack parameters into a single tuple for optimization.

Parameters:

Name Type Description Default
flux float

Flux level at which to set image.

required
dx float

Offset in arcseconds.

required
dy float

Offset in arcseconds.

required
fwhm float

Full width half maximum of Kolmogorov kernel.

required
z_fit array of float

Zernike perturbations.

required
bkg array of float

Background polynomial coefficients.

()

Returns:

Type Description
tuple of float

Packed parameters.

Source code in danish/donut_model.py
def pack_params(self, *, flux, dx, dy, fwhm, z_fit, bkg=()):
    """Pack parameters into a single tuple for optimization.

    Parameters
    ----------
    flux : float
        Flux level at which to set image.
    dx, dy : float
        Offset in arcseconds.
    fwhm : float
        Full width half maximum of Kolmogorov kernel.
    z_fit : array of float
        Zernike perturbations.
    bkg : array of float
        Background polynomial coefficients.

    Returns
    -------
    tuple of float
        Packed parameters.
    """
    return (flux, dx, dy, fwhm, *z_fit, *bkg)

unpack_params

unpack_params(params)

Unpack parameters from the single tuple used for optimization.

Parameters:

Name Type Description Default
params sequence of float

Packed parameters tuple as returned by pack_params.

required

Returns:

Type Description
dict

Dictionary with keys 'flux', 'dx', 'dy', 'fwhm', 'z_fit', and 'bkg'.

Source code in danish/donut_model.py
def unpack_params(self, params):
    """
    Unpack parameters from the single tuple used for optimization.

    Parameters
    ----------
    params : sequence of float
        Packed parameters tuple as returned by `pack_params`.

    Returns
    -------
    dict
        Dictionary with keys 'flux', 'dx', 'dy', 'fwhm', 'z_fit', and 'bkg'.
    """
    flux, dx, dy, fwhm, *rest = params
    out = dict(
        flux=flux,
        dx=dx,
        dy=dy,
        fwhm=fwhm,
    )
    split = len(rest) - self.nbkg
    out["z_fit"] = rest[:split]
    out["bkg"] = rest[split:]
    return out

chi

chi(params, data, var)

Compute chi = (data - model)/error.

The error is modeled as sqrt(model + var).

Parameters:

Name Type Description Default
params sequence of float

Order is: (flux, dx, dy, fwhm, *z_fit, *bkg)

required
data array of float (npix, npix)

Image against which to compute chi.

required
var float or array of float (npix, npix)

Variance of the sky only. Do not include Poisson contribution of the signal, as this will be added from the current model.

required

Returns:

Name Type Description
chi array of float

Flattened array of chi residuals.

Source code in danish/donut_model.py
def chi(
    self, params, data, var
):
    """Compute chi = (data - model)/error.

    The error is modeled as sqrt(model + var).

    Parameters
    ----------
    params : sequence of float
        Order is: (flux, dx, dy, fwhm, *z_fit, *bkg)
    data : array of float (npix, npix)
        Image against which to compute chi.
    var : float or array of float (npix, npix)
        Variance of the sky only.  Do not include Poisson contribution of
        the signal, as this will be added from the current model.

    Returns
    -------
    chi : array of float
        Flattened array of chi residuals.
    """
    mod = self.model(**self.unpack_params(params))
    return self._chi(data, mod, var)

jac

jac(params, data, var, method='analytic')

Compute jacobian d(chi)/d(param).

Parameters:

Name Type Description Default
params sequence of float

Order is: (flux, dx, dy, fwhm, *z_fit, *bkg)

required
data array of float

Image against which to compute chi.

required
var float or array of float (npix, npix)

Variance of the sky only. Do not include Poisson contribution of the signal, as this will be added from the current model.

required
method str

'analytic' (default) differentiates the Zernike columns in closed form, which is both faster and more accurate than the alternative -- a one-sided difference at 1e-8 m carries a few percent error. 'fd' forces the difference quotient for every column. Falls back to 'fd' where no analytic path exists, i.e. for any factory that does not render from a mesh.

'analytic'

Returns:

Name Type Description
jac array of float

Jacobian array d(chi)/d(param). First dimension is pixels, second dimension is param.

Raises:

Type Description
ValueError

If method is neither 'analytic' nor 'fd'.

Source code in danish/donut_model.py
def jac(
    self, params, data, var, method='analytic'
):
    """Compute jacobian d(chi)/d(param).

    Parameters
    ----------
    params : sequence of float
        Order is: (flux, dx, dy, fwhm, *z_fit, *bkg)
    data : array of float
        Image against which to compute chi.
    var : float or array of float (npix, npix)
        Variance of the sky only.  Do not include Poisson contribution of
        the signal, as this will be added from the current model.
    method : str, optional
        'analytic' (default) differentiates the Zernike columns in closed
        form, which is both faster and more accurate than the alternative
        -- a one-sided difference at 1e-8 m carries a few percent error.
        'fd' forces the difference quotient for every column.  Falls back
        to 'fd' where no analytic path exists, i.e. for any factory that
        does not render from a mesh.

    Returns
    -------
    jac : array of float
        Jacobian array d(chi)/d(param).  First dimension is pixels, second
        dimension is param.

    Raises
    ------
    ValueError
        If `method` is neither 'analytic' nor 'fd'.
    """
    _check_jac_method(method)
    out = np.zeros((self.npix**2, len(params)))
    chi0 = self.chi(params, data, var)

    flux = params[0]
    step = [
        1e-3 * flux,  # flux
        0.01,         # dx
        0.01,         # dy
        0.01          # fwhm
    ]
    step += [1e-8]*len(self.z_terms)  # Zernikes (in meters)
    step += [0.01]*self.nbkg

    # Zernike columns, which the analytic path replaces.  3 offsets plus
    # the atmospheric parameter precede them; see pack_params.
    wf0 = 3 + self.natm
    nwavefront = len(self.z_terms)
    analytic = method == 'analytic' and self._can_use_analytic()

    for i in range(len(params)):
        if analytic and wf0 <= i < wf0 + nwavefront:
            continue
        params1 = np.array(params)
        params1[i] += step[i]
        chi1 = self.chi(params1, data, var)
        out[:, i] = (chi1-chi0)/step[i]

    if analytic:
        out[:, wf0:wf0+nwavefront] = self._wavefront_jac_analytic(
            params, data[np.newaxis], [var]
        )

    return out

Multi-donut models

danish.donut_model.DZMultiDonutModel

Bases: BaseMultiDonutModel

Multi donut model that uses double Zernike coefficients to parameterize the wavefront.

Parameters:

Name Type Description Default
factory DonutFactoryBase
required
dz_terms sequence of tuple of int

List of (k, j) indices specifying which double Zernike terms to use.

()
bkg_order int

Order of the background polynomial to fit. If -1, no background.

required
dz_ref DoubleZernike

Double Zernike coefficients to use for constructing Single Zernike reference coefficients to use for each modeled donut. Either this kwarg or z_refs must be set.

required
z_refs array of float

Single Zernike reference coefficients for each donut. First dimension is donut, second dimension is pupil Zernike coefficient.

required
field_radius float

Field radius in radians. If dz_ref is provided, then this is ignored and the field radius will be inferred from dz_ref.

required
thxs float

Field angles in radians.

required
thys float

Field angles in radians.

required
npix int

Number of pixels along image edge. Must be odd.

required
seed int

Random seed for use when creating noisy donut images with this class.

required
Source code in danish/donut_model.py
class DZMultiDonutModel(BaseMultiDonutModel):
    """Multi donut model that uses double Zernike coefficients to parameterize the
    wavefront.

    Parameters
    ----------
    factory : DonutFactoryBase
    dz_terms : sequence of tuple of int
        List of (k, j) indices specifying which double Zernike terms to use.
    bkg_order : int, optional
        Order of the background polynomial to fit.  If -1, no background.
    dz_ref : DoubleZernike
        Double Zernike coefficients to use for constructing Single Zernike
        reference coefficients to use for each modeled donut.  Either this kwarg
        or `z_refs` must be set.
    z_refs : array of float
        Single Zernike reference coefficients for each donut.  First dimension
        is donut, second dimension is pupil Zernike coefficient.
    field_radius : float
        Field radius in radians.  If dz_ref is provided, then this is ignored and
        the field radius will be inferred from dz_ref.
    thxs, thys : float
        Field angles in radians.
    npix : int
        Number of pixels along image edge.  Must be odd.
    seed : int
        Random seed for use when creating noisy donut images with this class.
    """
    def __init__(self, *args, dz_terms=(), **kwargs):
        # Want dz_terms
        self.dz_terms = dz_terms
        self.k_max = max([term[0] for term in dz_terms], default=0)
        self.j_max = max([term[1] for term in dz_terms], default=0)
        self._nwavefront = len(dz_terms)
        super().__init__(*args, **kwargs)

    def _get_z_fits(self, dz_fit):
        """Convert this class's wavefront parameterization into individual donut
        Zernike coefficients.

        Parameters
        ----------
        dz_fit : array of float
            Array of double Zernike coefficients for this model.

        Returns
        -------
        z_fits : list of array of float
            List of single Zernike coefficients for each donut.
        """
        arr = np.zeros((self.k_max+1, self.j_max+1))
        for i, (k, j) in enumerate(self.dz_terms):
            arr[k, j] = dz_fit[i]
        dz = galsim.zernike.DoubleZernike(arr, uv_outer=self.field_radius)
        z_fits = []
        for thx, thy in zip(self.thxs, self.thys):
            z_fits.append(dz.xycoef(thx, thy))
        return z_fits

danish.donut_model.DZBasisMultiDonutModel

Bases: BaseMultiDonutModel

Multi donut model that uses a sensitivity matrix to convert mode coefficients into double Zernike coefficients to parameterize the wavefront.

Parameters:

Name Type Description Default
factory DonutFactoryBase
required
sensitivity array of float

Sensitivity matrix that converts mode coefficients into double Zernike coefficients. Dimensions are (nmode, k_max+1, j_max+1)

None
bkg_order int

Order of the background polynomial to fit. If -1, no background.

required
dz_ref DoubleZernike

Double Zernike coefficients to use for constructing Single Zernike reference coefficients to use for each modeled donut. Either this kwarg or z_refs must be set.

required
z_refs array of float

Single Zernike reference coefficients for each donut. First dimension is donut, second dimension is pupil Zernike coefficient.

required
field_radius float

Field radius in radians. If dz_ref is provided, then this is ignored and the field radius will be inferred from dz_ref.

required
thxs float

Field angles in radians.

required
thys float

Field angles in radians.

required
npix int

Number of pixels along image edge. Must be odd.

required
seed int

Random seed for use when creating noisy donut images with this class.

required
Source code in danish/donut_model.py
class DZBasisMultiDonutModel(BaseMultiDonutModel):
    """Multi donut model that uses a sensitivity matrix to convert mode coefficients
    into double Zernike coefficients to parameterize the wavefront.

    Parameters
    ----------
    factory : DonutFactoryBase
    sensitivity : array of float
        Sensitivity matrix that converts mode coefficients into double Zernike
        coefficients.  Dimensions are (nmode, k_max+1, j_max+1)
    bkg_order : int, optional
        Order of the background polynomial to fit.  If -1, no background.
    dz_ref : DoubleZernike
        Double Zernike coefficients to use for constructing Single Zernike
        reference coefficients to use for each modeled donut.  Either this kwarg
        or `z_refs` must be set.
    z_refs : array of float
        Single Zernike reference coefficients for each donut.  First dimension
        is donut, second dimension is pupil Zernike coefficient.
    field_radius : float
        Field radius in radians.  If dz_ref is provided, then this is ignored and
        the field radius will be inferred from dz_ref.
    thxs, thys : float
        Field angles in radians.
    npix : int
        Number of pixels along image edge.  Must be odd.
    seed : int
        Random seed for use when creating noisy donut images with this class.
    """
    def __init__(self, *args, sensitivity=None, **kwargs):
        if sensitivity is None:
            raise ValueError("Must provide sensitivity")
        self.sensitivity = sensitivity
        self.nmode = self.sensitivity.shape[0]
        self.k_max = self.sensitivity.shape[1]
        self.j_max = self.sensitivity.shape[2]
        self._nwavefront = self.nmode
        super().__init__(*args, **kwargs)

    def _get_z_fits(self, mode_coefs):
        """Convert this class's wavefront parameterization into individual donut
        Zernike coefficients.

        Parameters
        ----------
        mode_coefs : array of float
            Array of mode coefficients for this model.

        Returns
        -------
        z_fits : list of array of float
            List of single Zernike coefficients for each donut.
        """
        arr = np.einsum(
            "i,ikj->kj",
            mode_coefs,
            self.sensitivity
        )
        dz = galsim.zernike.DoubleZernike(arr, uv_outer=self.field_radius)
        z_fits = []
        for thx, thy in zip(self.thxs, self.thys):
            z_fits.append(dz.xycoef(thx, thy))
        return z_fits