lsst.ip.isr
ga92a4e6fc1+12d102fd6a
Toggle main menu visibility
Loading...
Searching...
No Matches
python
lsst
ip
isr
intrinsicZernikes.py
Go to the documentation of this file.
1
# This file is part of ip_isr.
2
#
3
# Developed for the LSST Data Management System.
4
# This product includes software developed by the LSST Project
5
# (https://www.lsst.org).
6
# See the COPYRIGHT file at the top-level directory of this distribution
7
# for details of code ownership.
8
#
9
# This program is free software: you can redistribute it and/or modify
10
# it under the terms of the GNU General Public License as published by
11
# the Free Software Foundation, either version 3 of the License, or
12
# (at your option) any later version.
13
#
14
# This program is distributed in the hope that it will be useful,
15
# but WITHOUT ANY WARRANTY; without even the implied warranty of
16
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17
# GNU General Public License for more details.
18
#
19
# You should have received a copy of the GNU General Public License
20
# along with this program. If not, see <https://www.gnu.org/licenses/>.
21
"""
22
Intrinsic Zernikes storage class.
23
"""
24
25
__all__ = [
"IntrinsicZernikes"
]
26
27
import
numpy
as
np
28
from
astropy
import
units
as
u
29
from
astropy.table
import
Table
30
from
scipy.interpolate
import
LinearNDInterpolator
31
32
from
lsst.ip.isr
import
IsrCalib
33
34
35
class
IntrinsicZernikes
(
IsrCalib
):
36
"""Intrinsic Zernike coefficients.
37
38
Stores Zernike wavefront-error coefficients sampled at a set of
39
focal-plane field angles. At query time the coefficients are
40
interpolated to an arbitrary field position provided in CCS.
41
42
The coefficients are stored in two coordinate systems, each as an
43
independent set of sample points and values:
44
45
- the Camera Coordinate System (CCS), which corresponds to the
46
focal plane heights and any other CCS contribution and
47
- the Optical Coordinate System (OCS), corresponding to
48
the intrinsics, which are by nature defined in the optical
49
coordinates.
50
51
See `LSE-349 <https://ls.st/LSE-349>`_ for the definitions.
52
53
The CCS sample points and values are stored on the un-suffixed
54
``field_x``, ``field_y`` and ``values`` attributes (and serialized
55
under those same keys). These names are kept unchanged from version
56
1, which only stored the CCS system, so that version 1 calibrations
57
round-trip unchanged. The OCS system is stored alongside on the
58
``*_ocs`` attributes/keys.
59
60
Parameters
61
----------
62
table : `astropy.table.Table`, optional
63
Source table in the CCS. Must contain columns:
64
65
``"x"``
66
Field x positions with angular units (e.g. ``u.deg``).
67
``"y"``
68
Field y positions with angular units (e.g. ``u.deg``).
69
``"Z{j}"``
70
One column per Noll index *j*, with length units
71
(e.g. ``u.um``).
72
table_ocs : `astropy.table.Table`, optional
73
Source table in the OCS, with the same column layout as
74
``table``.
75
76
Attributes
77
----------
78
field_x, field_y : `numpy.ndarray`
79
CCS x/y field positions in degrees for all sample points,
80
shape ``(n_points_ccs,)``.
81
field_x_ocs, field_y_ocs : `numpy.ndarray`
82
OCS x/y field positions in degrees for all sample points,
83
shape ``(n_points_ocs,)``.
84
noll_indices : `numpy.ndarray`
85
Noll indices of the stored Zernike terms, shape ``(n_zernikes,)``.
86
values, values_ocs : `numpy.ndarray`
87
Zernike coefficients in microns for the CCS and OCS sample
88
points, shape ``(n_points, n_zernikes)``.
89
interpolator, interpolator_ocs : `scipy.interpolate.LinearNDInterpolator`
90
or `None`
91
Interpolators built from the CCS and OCS sample points and
92
values. ``None`` until the corresponding system is populated.
93
94
Version 1.1 adds the OCS coordinate system alongside the CCS system
95
stored by version 1.
96
"""
97
98
_OBSTYPE =
"INTRINSIC_ZERNIKES"
99
_SCHEMA =
"Intrinsic Zernikes"
100
_VERSION = 1.1
101
102
def
__init__
(self, table=None, table_ocs=None, **kwargs):
103
# CCS uses the un-suffixed names (field_x/field_y/values/
104
# interpolator) for backwards compatibility with version 1, which
105
# only stored the CCS system under those names.
106
self.
field_x
= np.array([])
107
self.
field_y
= np.array([])
108
self.
values
= np.array([])
109
self.
field_x_ocs
= np.array([])
110
self.
field_y_ocs
= np.array([])
111
self.
values_ocs
= np.array([])
112
self.
noll_indices
= np.array([])
113
self.
interpolator
=
None
114
self.
interpolator_ocs
=
None
115
116
super().
__init__
(**kwargs)
117
118
if
table
is
not
None
:
119
(self.
field_x
, self.
field_y
, self.
values
, self.
noll_indices
) = (
120
self.
_unpackTable
(table)
121
)
122
self.
interpolator
= self.
_makeInterpolator
(
123
self.
field_x
, self.
field_y
, self.
values
124
)
125
if
table_ocs
is
not
None
:
126
(self.
field_x_ocs
, self.
field_y_ocs
, self.
values_ocs
, noll_indices_ocs) = (
127
self.
_unpackTable
(table_ocs)
128
)
129
# The CCS and OCS systems are summed term-by-term at query time, so
130
# they must describe the same Noll indices. Store a single shared
131
# ``noll_indices`` and reject tables that disagree.
132
if
table
is
not
None
and
not
np.array_equal(noll_indices_ocs, self.
noll_indices
):
133
raise
ValueError(
134
"CCS and OCS tables must share the same Noll indices; got "
135
f
"{self.noll_indices.tolist()} (CCS) and "
136
f
"{noll_indices_ocs.tolist()} (OCS)."
137
)
138
self.
interpolator_ocs
= self.
_makeInterpolator
(
139
self.
field_x_ocs
, self.
field_y_ocs
, self.
values_ocs
140
)
141
142
# Don't assume sorted or contiguous.
143
self.
_noll_map
= {n: i
for
i, n
in
enumerate(self.
noll_indices
)}
144
145
self.
requiredAttributes
.update(
146
[
147
"field_x"
,
148
"field_y"
,
149
"values"
,
150
"field_x_ocs"
,
151
"field_y_ocs"
,
152
"values_ocs"
,
153
"noll_indices"
,
154
]
155
)
156
157
@staticmethod
158
def
_unpackTable
(table):
159
"""Unpack a source table into field positions, values, and Noll
160
indices.
161
162
Parameters
163
----------
164
table : `astropy.table.Table`
165
Source table with ``"x"``, ``"y"``, and ``"Z{j}"`` columns.
166
167
Returns
168
-------
169
field_x, field_y : `numpy.ndarray`
170
Field positions in degrees.
171
values : `numpy.ndarray`
172
Zernike coefficients in microns, shape
173
``(n_points, n_zernikes)`` ordered by ascending Noll index.
174
noll_indices : `numpy.ndarray`
175
Sorted Noll indices.
176
"""
177
field_x = table[
"x"
].to(
"deg"
).value
178
field_y = table[
"y"
].to(
"deg"
).value
179
zcols = [col
for
col
in
table.colnames
if
col.startswith(
"Z"
)]
180
noll_indices = np.array(sorted(int(col[1:])
for
col
in
zcols))
181
values = np.column_stack([table[f
"Z{j}"
].to(
"um"
).value
for
j
in
noll_indices])
182
return
field_x, field_y, values, noll_indices
183
184
@staticmethod
185
def
_makeInterpolator
(field_x, field_y, values):
186
"""Build a field-position interpolator, or `None` if there are no
187
sample points."""
188
if
np.asarray(field_x).size == 0:
189
return
None
190
return
LinearNDInterpolator(np.column_stack((field_x, field_y)), values)
191
192
@classmethod
193
def
fromDict
(cls, dictionary):
194
"""Construct an IntrinsicZernikes from dictionary of properties.
195
196
Parameters
197
----------
198
dictionary : `dict`
199
Dictionary of properties.
200
201
Returns
202
-------
203
calib : `lsst.ip.isr.IntrinsicZernikes`
204
Constructed calibration.
205
206
Raises
207
------
208
RuntimeError
209
Raised if the supplied dictionary is for a different
210
calibration type.
211
"""
212
calib = cls()
213
214
if
calib._OBSTYPE != dictionary[
"metadata"
][
"OBSTYPE"
]:
215
raise
RuntimeError(
216
f
"Incorrect intrinsic zernikes supplied. "
217
f
"Expected {calib._OBSTYPE}, found {dictionary['metadata']['OBSTYPE']}"
218
)
219
220
calib.setMetadata(dictionary[
"metadata"
])
221
# CCS keys (field_x/field_y/values) are always present, including
222
# in version 1 dictionaries. The OCS keys are optional, so version
223
# 1 dictionaries (CCS only) load with an empty OCS system.
224
calib.field_x = np.array(dictionary[
"field_x"
])
225
calib.field_y = np.array(dictionary[
"field_y"
])
226
calib.values = np.array(dictionary[
"values"
])
227
calib.field_x_ocs = np.array(dictionary.get(
"field_x_ocs"
, []))
228
calib.field_y_ocs = np.array(dictionary.get(
"field_y_ocs"
, []))
229
calib.values_ocs = np.array(dictionary.get(
"values_ocs"
, []))
230
calib.noll_indices = np.array(dictionary[
"noll_indices"
])
231
calib.interpolator = cls.
_makeInterpolator
(
232
calib.field_x, calib.field_y, calib.values
233
)
234
calib.interpolator_ocs = cls.
_makeInterpolator
(
235
calib.field_x_ocs, calib.field_y_ocs, calib.values_ocs
236
)
237
238
calib.updateMetadata()
239
return
calib
240
241
def
toDict
(self):
242
"""Return a dictionary containing the calibration properties.
243
244
The dictionary should be able to be round-tripped through
245
`fromDict`.
246
247
Returns
248
-------
249
dictionary : `dict`
250
Dictionary of properties.
251
"""
252
self.
updateMetadata
()
253
254
outDict = {}
255
outDict[
"metadata"
] = self.
getMetadata
()
256
outDict[
"field_x"
] = self.
field_x
.tolist()
257
outDict[
"field_y"
] = self.
field_y
.tolist()
258
outDict[
"values"
] = self.
values
.tolist()
259
outDict[
"field_x_ocs"
] = self.
field_x_ocs
.tolist()
260
outDict[
"field_y_ocs"
] = self.
field_y_ocs
.tolist()
261
outDict[
"values_ocs"
] = self.
values_ocs
.tolist()
262
outDict[
"noll_indices"
] = self.
noll_indices
.tolist()
263
264
return
outDict
265
266
@classmethod
267
def
fromTable
(cls, tableList):
268
"""Construct calibration from a list of tables.
269
270
Parameters
271
----------
272
tableList : `list` [`astropy.table.Table`]
273
List of tables to use to construct the intrinsic zernikes
274
calibration. Each table is dispatched to the CCS or OCS
275
coordinate system according to its ``coord_sys`` metadata
276
entry (defaulting to ``"CCS"``). A version 1 single-table
277
calibration, which has no ``coord_sys`` entry, is therefore
278
read as the CCS system.
279
280
Returns
281
-------
282
calib : `lsst.ip.isr.IntrinsicZernikes`
283
The calibration defined in the tables.
284
"""
285
tables = {}
286
for
table
in
tableList:
287
coord_sys = table.meta.get(
"coord_sys"
,
"CCS"
)
288
if
coord_sys
not
in
(
"CCS"
,
"OCS"
):
289
raise
RuntimeError(
290
f
"Invalid coordinate system {coord_sys} in table metadata; "
291
f
"expected 'CCS' or 'OCS'"
292
)
293
tables[coord_sys] = table
294
295
calib = cls(table=tables.get(
"CCS"
), table_ocs=tables.get(
"OCS"
,
None
))
296
# ``coord_sys`` is a per-table annotation used only to dispatch each
297
# table above; drop it so it does not leak into the calibration
298
# metadata (which must match across a toTable/fromTable round-trip).
299
meta = dict(tableList[0].meta)
300
meta.pop(
"coord_sys"
,
None
)
301
calib.setMetadata(meta)
302
calib.updateMetadata()
303
return
calib
304
305
def
toTable
(self):
306
"""Construct a list of tables containing the information in this
307
calibration.
308
309
One table is produced per populated coordinate system. The CCS
310
table is always emitted; the OCS table is only emitted when the
311
OCS system holds sample points, so a CCS-only calibration (e.g.
312
one read from a version 1 file) round-trips to a single table,
313
exactly as in version 1. The list of tables should be able to be
314
round-tripped through `fromTable`.
315
316
Returns
317
-------
318
tableList : `list` [`astropy.table.Table`]
319
List of tables containing the intrinsic zernikes calibration
320
information, one per populated coordinate system.
321
"""
322
self.
updateMetadata
()
323
324
inMeta = self.
getMetadata
().
toDict
()
325
baseMeta = {k: v
for
k, v
in
inMeta.items()
if
v
is
not
None
}
326
baseMeta.update({k:
""
for
k, v
in
inMeta.items()
if
v
is
None
})
327
328
systems = [(
"CCS"
, self.
field_x
, self.
field_y
, self.
values
)]
329
if
np.asarray(self.
field_x_ocs
).size > 0:
330
systems.append((
"OCS"
, self.
field_x_ocs
, self.
field_y_ocs
, self.
values_ocs
))
331
332
tableList = []
333
for
coord_sys, field_x, field_y, values
in
systems:
334
data = {
335
"x"
: field_x * u.deg,
336
"y"
: field_y * u.deg,
337
}
338
for
i, j
in
enumerate(self.
noll_indices
):
339
column = values[:, i]
if
values.ndim == 2
else
np.array([])
340
data[f
"Z{j}"
] = column * u.um
341
342
table = Table(data)
343
meta = dict(baseMeta)
344
meta[
"coord_sys"
] = coord_sys
345
table.meta = meta
346
tableList.append(table)
347
348
return
tableList
349
350
def
writeText
(self, filename, format="auto"):
351
raise
NotImplementedError(
"Text output not implemented for IntrinsicZernikes"
)
352
353
def
readText
(self, filename, format="auto"):
354
raise
NotImplementedError(
"Text input not implemented for IntrinsicZernikes"
)
355
356
def
getIntrinsicZernikes
(
357
self, field_x, field_y, rotTelPos=0.0, noll_indices=None
358
):
359
"""
360
Get the intrinsic Zernike coefficients at a given field position.
361
362
The returned coefficients are the sum of the CCS contribution
363
(heights_ccs), interpolated at the requested field position,
364
and the OCS contribution (measured_intrinsics),
365
interpolated at the field position rotated by
366
``rotTelPos``. For calibrations that only store one
367
coordinate system (e.g. version 1 files, which only carry CCS),
368
the missing OCS contribution is simply omitted from the sum.
369
370
Parameters
371
----------
372
field_x : `array-like`
373
x-field positions in degrees (CCS). Broadcast against
374
``field_y``.
375
field_y : `array-like`
376
y-field positions in degrees (CCS). Broadcast against
377
``field_x``.
378
rotTelPos : `float`, optional
379
Rotation angle in degrees applied to the query point before
380
interpolating the OCS contribution. Defaults to 0.
381
noll_indices : `list` [`int`], optional
382
List of Noll indices to return. If None, return all.
383
384
Returns
385
-------
386
zernikes : `numpy.ndarray`
387
Array of Zernike coefficient values in microns corresponding to the
388
requested Noll indices and field positions. The shape is the
389
broadcast shape of ``field_x`` and ``field_y`` followed by the
390
number of requested Noll indices.
391
"""
392
if
noll_indices
is
None
:
393
# Default to all stored terms. The CCS and OCS systems share these
394
# indices, so the output shape is the same whether or not an OCS
395
# system is present (an absent OCS simply adds nothing).
396
noll_indices = self.
noll_indices
397
noll_indices = np.array(noll_indices)
398
399
try
:
400
noll_mask = [self.
_noll_map
[j]
for
j
in
noll_indices]
401
except
KeyError
as
exc:
402
raise
ValueError(
403
f
"No intrinsic available for Noll index {exc.args[0]}"
404
)
from
None
405
406
field_x, field_y = np.broadcast_arrays(field_x, field_y)
407
# Interpolate over a flat list of points and restore the caller's
408
# shape afterwards.
409
shape = field_x.shape
410
field_x = field_x.ravel()
411
field_y = field_y.ravel()
412
points = np.stack((field_x, field_y), axis=-1)
413
total = self.
interpolator
(points)
414
415
if
self.
interpolator_ocs
is
not
None
:
416
# Rotate the query point into the OCS frame before interpolating.
417
theta = np.deg2rad(rotTelPos)
418
cos_a, sin_a = np.cos(theta), np.sin(theta)
419
x_ocs = cos_a * field_x - sin_a * field_y
420
y_ocs = sin_a * field_x + cos_a * field_y
421
points_ocs = np.stack((x_ocs, y_ocs), axis=-1)
422
# CCS and OCS share the same Noll indices (enforced in __init__),
423
# so the two interpolator outputs line up column-for-column and add
424
# element-wise.
425
total = total + self.
interpolator_ocs
(points_ocs)
426
427
total = total[:, noll_mask]
428
total = total.reshape(shape + total.shape[-1:])
429
return
total
lsst::ip::isr.calibType.IsrCalib
Definition
calibType.py:41
lsst::ip::isr.calibType.IsrCalib.requiredAttributes
requiredAttributes
Definition
calibType.py:90
lsst::ip::isr.calibType.IsrCalib.updateMetadata
updateMetadata(self, camera=None, detector=None, filterName=None, setCalibId=False, setCalibInfo=False, setDate=False, **kwargs)
Definition
calibType.py:210
lsst::ip::isr.calibType.IsrCalib.getMetadata
getMetadata(self)
Definition
calibType.py:174
lsst::ip::isr.intrinsicZernikes.IntrinsicZernikes
Definition
intrinsicZernikes.py:35
lsst::ip::isr.intrinsicZernikes.IntrinsicZernikes.getIntrinsicZernikes
getIntrinsicZernikes(self, field_x, field_y, rotTelPos=0.0, noll_indices=None)
Definition
intrinsicZernikes.py:358
lsst::ip::isr.intrinsicZernikes.IntrinsicZernikes.values
values
Definition
intrinsicZernikes.py:108
lsst::ip::isr.intrinsicZernikes.IntrinsicZernikes.values_ocs
values_ocs
Definition
intrinsicZernikes.py:111
lsst::ip::isr.intrinsicZernikes.IntrinsicZernikes.toDict
toDict(self)
Definition
intrinsicZernikes.py:241
lsst::ip::isr.intrinsicZernikes.IntrinsicZernikes.fromTable
fromTable(cls, tableList)
Definition
intrinsicZernikes.py:267
lsst::ip::isr.intrinsicZernikes.IntrinsicZernikes.readText
readText(self, filename, format="auto")
Definition
intrinsicZernikes.py:353
lsst::ip::isr.intrinsicZernikes.IntrinsicZernikes.field_y
field_y
Definition
intrinsicZernikes.py:107
lsst::ip::isr.intrinsicZernikes.IntrinsicZernikes._makeInterpolator
_makeInterpolator(field_x, field_y, values)
Definition
intrinsicZernikes.py:185
lsst::ip::isr.intrinsicZernikes.IntrinsicZernikes._noll_map
dict _noll_map
Definition
intrinsicZernikes.py:143
lsst::ip::isr.intrinsicZernikes.IntrinsicZernikes.field_x_ocs
field_x_ocs
Definition
intrinsicZernikes.py:109
lsst::ip::isr.intrinsicZernikes.IntrinsicZernikes.noll_indices
noll_indices
Definition
intrinsicZernikes.py:112
lsst::ip::isr.intrinsicZernikes.IntrinsicZernikes.field_y_ocs
field_y_ocs
Definition
intrinsicZernikes.py:110
lsst::ip::isr.intrinsicZernikes.IntrinsicZernikes.__init__
__init__(self, table=None, table_ocs=None, **kwargs)
Definition
intrinsicZernikes.py:102
lsst::ip::isr.intrinsicZernikes.IntrinsicZernikes.interpolator
interpolator
Definition
intrinsicZernikes.py:113
lsst::ip::isr.intrinsicZernikes.IntrinsicZernikes.field_x
field_x
Definition
intrinsicZernikes.py:106
lsst::ip::isr.intrinsicZernikes.IntrinsicZernikes.fromDict
fromDict(cls, dictionary)
Definition
intrinsicZernikes.py:193
lsst::ip::isr.intrinsicZernikes.IntrinsicZernikes.interpolator_ocs
interpolator_ocs
Definition
intrinsicZernikes.py:114
lsst::ip::isr.intrinsicZernikes.IntrinsicZernikes.toTable
toTable(self)
Definition
intrinsicZernikes.py:305
lsst::ip::isr.intrinsicZernikes.IntrinsicZernikes._unpackTable
_unpackTable(table)
Definition
intrinsicZernikes.py:158
lsst::ip::isr.intrinsicZernikes.IntrinsicZernikes.writeText
writeText(self, filename, format="auto")
Definition
intrinsicZernikes.py:350
lsst::ip::isr
Definition
applyLookupTable.h:34
Generated on
for lsst.ip.isr by
1.18.0