SequentialSystem#
- class optika.systems.SequentialSystem(surfaces, object=None, sensor=None, grid_input=None, axis_surface='surface', axis_wavelength=None, axis_field=None, axis_pupil=None, transformation=None, kwargs_plot=None)[source]#
Bases:
AbstractSequentialSystemA sequential optical system is a composition of a sequence of
optika.surfaces.AbstractSurfaceinstances and a default grid to sample them with.Examples
Here is an example of a simple Newtonian telescope, with a parabolic primary mirror, a 45 degree fold mirror, and a detector.
import dataclasses import matplotlib.pyplot as plt import astropy.units as u import astropy.visualization import named_arrays as na import optika # store the coordinates of the primary mirror, fold mirror, # and sensor, so we can determine the focal length of the # primary mirror. primary_mirror_z = 200 * u.mm fold_mirror_z = 50 * u.mm sensor_x = 50 * u.mm # Define the front aperture surface. front = optika.surfaces.Surface( name="front", ) # Define the parabolic primary mirror. primary_mirror = optika.surfaces.Surface( name="mirror", sag=optika.sags.ParabolicSag( focal_length=-(primary_mirror_z - fold_mirror_z + sensor_x), ), aperture=optika.apertures.RectangularAperture(40 * u.mm), material=optika.materials.Mirror(), is_pupil_stop=True, transformation=na.transformations.Cartesian3dTranslation( z=primary_mirror_z, ), ) # Define the flat fold mirror which directs light # to the detector surface. fold_mirror = optika.surfaces.Surface( name="fold_mirror", aperture=optika.apertures.RectangularAperture(25 * u.mm), material=optika.materials.Mirror(), transformation=na.transformations.TransformationList([ na.transformations.Cartesian3dRotationY((90 + 45) * u.deg), na.transformations.Cartesian3dTranslation( z=fold_mirror_z, ), ]), ) # Define the central obscuration, the back face # of the fold mirror which blocks some of the # incoming light. obscuration = optika.surfaces.Surface( name="obscuration", aperture=dataclasses.replace(fold_mirror.aperture, inverted=True), transformation=fold_mirror.transformation, ) # define the imaging sensor surface sensor = optika.sensors.ImagingSensor( name="sensor", width_pixel=20 * u.um, axis_pixel=na.Cartesian2dVectorArray("detector_x", "detector_y"), num_pixel=na.Cartesian2dVectorArray(128, 128), timedelta_exposure=1 * u.s, transformation=na.transformations.TransformationList([ na.transformations.Cartesian3dRotationY(-90 * u.deg), na.transformations.Cartesian3dTranslation( x=-sensor_x, z=fold_mirror_z, ), ]), is_field_stop=True, ) # Define the grid of normalized field coordinates, field = na.Cartesian2dVectorLinearSpace( start=-1, stop=1, axis=na.Cartesian2dVectorArray("field_x", "field_y"), num=5, centers=True, ) # Define the grid of normalized pupil coordinates # in a similar fashion to the normalized field # coordinates pupil = na.Cartesian2dVectorLinearSpace( start=-1, stop=1, axis=na.Cartesian2dVectorArray("pupil_x", "pupil_y"), num=5, centers=True, ) # define the optical system using the surfaces # and the normalized field/pupil coordinates system = optika.systems.SequentialSystem( surfaces=[ front, obscuration, primary_mirror, fold_mirror, ], sensor=sensor, grid_input=optika.vectors.ObjectVectorArray( wavelength=500 * u.nm, field=field, pupil=pupil, ), ) # plot the system with astropy.visualization.quantity_support(): fig, ax = plt.subplots(constrained_layout=True) ax.set_aspect("equal") system.plot( ax=ax, components=("z", "x"), kwargs_rays=dict( color="tab:blue", ), color="black", zorder=10, )
Using this model, we can simulate an image of an airforce target
# Define the number of points to sample num_field = 2 * system.sensor.num_pixel # Define the scene as an airforce target. # Note how the coordinates (inputs) are defined on # cell vertices and the values (outputs) are # defined on cell centers. scene = na.FunctionArray( inputs=na.SpectralPositionalVectorArray( wavelength=na.linspace(530, 531, axis="wavelength", num=2) * u.nm, position=na.Cartesian2dVectorLinearSpace( start=system.field_min, stop=system.field_max, axis=na.Cartesian2dVectorArray("field_x", "field_y"), num=num_field + 1, ), ), outputs=optika.targets.airforce( axis_x="field_x", axis_y="field_y", num_x=num_field.x, num_y=num_field.y, ) * 100 * u.photon / u.s / u.m ** 2 / u.arcsec ** 2 / u.nm, ) # Simulate an image of the scene using the optical system image = system.image(scene) # Plot the original scene and the simulated image with astropy.visualization.quantity_support(): fig, ax = plt.subplots( ncols=2, figsize=(8, 5), constrained_layout=True, ) mappable_scene = na.plt.pcolormesh( scene.inputs.position, C=scene.outputs.value, ax=ax[0], ) mappable_image = na.plt.pcolormesh( image.inputs.position, C=image.outputs.value, ax=ax[1], ) cbar_0 = fig.colorbar( mappable=mappable_scene.ndarray.item(), ax=ax[0], location="top", ) cbar_0.set_label(f"radiance ({scene.outputs.unit:latex_inline})") cbar_1 = fig.colorbar( mappable=mappable_image.ndarray.item(), ax=ax[1], location="top", ) cbar_1.set_label(f"measured charge ({image.outputs.unit:latex_inline})") ax[0].set_aspect("equal") ax[1].set_aspect("equal")
The result is flipped vertically and horizontally due to the layout of the optical system. The noise on the image is from the stratified random sampling used to generate the grid of rays traced through the system, there is no additional noise sources, such as photon shot noise in this simulation.
Attributes
The logical axes of
grid_inputcorresponding to changing field coordinate.Normalized version of
axis_field.The axis along the edge of the field stop.
The logical axes of
grid_inputcorresponding to changing pupil coordinate.Normalized version of
axis_pupil.The axis along the edge of the pupil stop.
The axes along the edges of the two stop surfaces.
The name of the logical axis representing the sequence of surfaces.
The logical axis of
grid_inputcorresponding to changing wavelength.Normalized version of
axis_wavelength.The field coordinates at the edge of this optical system's field of view.
The upper right corner of this optical system's field of view.
The lower left corner of this optical system's field of view.
The field stop surface.
The input grid to sample with rays.
The index of the field stop in
surfaces_all.The index of the pupil stop in
surfaces_all.Additional keyword arguments used by default in
plot().The external object being imaged or illuminated by this system.
A boolean flag indicating if the object is at infinity.
The coordinates at the edge of this optical system's entrance pupil.
The entrance pupil of the system, fit as a function of field position at the wavelengths of
grid_input.The upper right corner of this optical system's entrance pupil in physical units.
The lower left corner of this optical system's entrance pupil in physical units.
The pupil stop surface.
Computes the rays in local coordinates at the last surface in the system as a function of input wavelength and position using
grid_input.The rays which graze the edges of both the field stop and the pupil stop, expressed in the frame of the object surface.
The imaging sensor that measures the light captured by this system.
The array shape of this object.
A sequence of surfaces representing this optical system.
Concatenate
objectwithsurfacesinto a single list of surfaces.A optional coordinate transformation to apply to the entire optical system.
Methods
__init__(surfaces[, object, sensor, ...])area_effective([wavelength, field, pupil, ...])Estimate the wavelength-dependent effective area of this system by tracing rays through it.
backproject(image, coordinates, *[, ...])Not implemented: a ray-traced
SequentialSystemis not a linear operator, so it has no transpose.beam_footprint(index[, wavelength, ...])The outline of the beam on one surface of this system: the convex hull of the points where the light which reaches the end of the system crosses that surface.
distortion([wavelength, field, pupil, ...])Fit a polynomial distortion model to the rays traced through this system.
field_stop_polygon([wavelength])The field of view of this system as a polygon in field coordinates: its half-light outline.
image(scene, *[, axis_wavelength, ...])Forward model of the optical system.
linearize([wavelength, field, pupil, ...])Construct a linear approximation of this system by fitting its distortion, vignetting, and effective area models.
plate_scale([wavelength])Compute the field of view divided by the pixels it spans.
plot([ax, transformation, components, ...])Plot the surfaces of the system and the default raytrace.
radius_spot([wavelength, field, pupil, ...])Compute the RMS radius of the spot which each field position makes on the sensor.
rayfunction([intensity, wavelength, field, ...])Given the wavelength, field position, and pupil position of some input rays, trace those rays through the system and return the resulting rays in local coordinates of the sensor (if it exists).
raytrace([intensity, wavelength, field, ...])Given the wavelength, field position, and pupil position of some input rays, trace those rays through the system and return the result in global coordinates, optionally including all intermediate rays.
replace(**changes)A copy of this object with the given fields replaced.
spot_diagram([figsize, s, cmap])Create a spot diagram of the rays at each field point to inspect the performance of this optical system.
to_dxf(file, unit[, transformation])Write a drawing of this object to a DXF file.
to_string([prefix])Public-facing version of the
__repr__method that allows for defining a prefix string, which can be used to calculate how much whitespace to add to the beginning of each line of the result.vignetting([wavelength, field, pupil, ...])Fit a polynomial vignetting model to the rays traced through this system.
Inheritance Diagram

- Parameters:
surfaces (Sequence[AbstractSurface])
object (AbstractSurface)
sensor (AbstractImagingSensor)
grid_input (ObjectVectorArray)
axis_surface (str)
axis_wavelength (None | str)
transformation (None | AbstractTransformation)
- area_effective(wavelength=None, field=None, pupil=None, normalized_field=True, normalized_pupil=True, seed_field=0, seed_pupil=0)#
Estimate the wavelength-dependent effective area of this system by tracing rays through it.
For each wavelength and field position, rays are traced across the pupil and the throughput of each ray (the product of the efficiency of every surface it encounters: reflectivity, transmissivity, diffraction efficiency, and the absorbance of the sensor) is weighted by the area of its pupil cell and summed, giving the effective area at that field position. Rays blocked by an aperture are excluded from the sum, except by the field stop and the sensor, which are left open as
vignetting()leaves them. The result is then averaged over the field positions inside the half-light outline of the field of view, whether or not their light lands on the sensor, and returned as anInterpolatedEffectiveAreaModel, which linearly interpolates in wavelength.The average is taken over the same field positions that
vignetting()normalizes its illumination over, and that model carries the size of each field position’s entrance pupil, so that the two can be multiplied together to recover the effective area at a given field position. Both halves of that are needed: an average over one set of field positions and a normalization over another would rescale the result by the ratio of the two, and an illumination which left out the size of its pupil would be wrong wherever the pupil is not the same size across the field.The components of pupil are interpreted as the vertices of a grid of cells, and one ray is traced per cell, so that each ray can be weighted by the physical area of its cell. A normalized pupil is mapped onto the entrance pupil of each ray’s own field position, which is where the cell’s area is measured, so a pupil which walks across the field is sampled in full at every field position.
The throughput includes the absorbance of the sensor but not its charge collection efficiency, which is applied separately, so this is the effective area up to the absorption of photons in the detector.
If the object is at infinity, the pupil is measured in units of length and the effective area has units of area (such as \(cm^2\)). If the object is at a finite distance, the pupil is measured in units of angle and the result instead has units of solid angle (such as \(deg^2\)).
- Parameters:
wavelength (None | Quantity | AbstractScalar) – The wavelengths at which to evaluate the effective area, which must vary along a single logical axis. If
None(the default),self.grid_input.wavelengthwill be used.field (None | AbstractCartesian2dVectorArray) – The vertices of the field grid, in either normalized or physical units. One ray is traced per cell, at a point drawn uniformly inside it, and the result is averaged over the cells which lie in the field of view. If
None(the default), \(12 \times 12\) vertices spanning the normalized field, so \(11 \times 11\) cells.pupil (None | AbstractCartesian2dVectorArray) – The vertices of the pupil grid, in either normalized or physical units. The area of each pupil cell is computed from these vertices and used to weight the throughput, and one ray is traced per cell, at a point drawn uniformly inside it. If
None(the default), \(12 \times 12\) vertices spanning the normalized pupil, so \(11 \times 11\) cells.normalized_field (bool) – A boolean flag indicating whether the field parameter is given in normalized or physical units.
normalized_pupil (bool) – A boolean flag indicating whether the pupil parameter is given in normalized or physical units.
seed_field (None | int) – The seed of the draw which places a field position inside each field cell, or
Noneto take the center of each cell instead, seevignetting(). Zero by default, so that estimating the same system twice gives the same effective area, and so that this method andlinearize()agree when neither is given a seed. Any other integer gives a different fixed sample, and the spread of the estimate over several of them is its spread over the sampling.seed_pupil (None | int) – The seed of the draw which places a pupil position inside each pupil cell, drawn afresh at every field position, or
Noneto take the center of each cell instead, seevignetting(). Zero by default, for the same reasons as seed_field.
- Raises:
ValueError – If the wavelength grid does not vary along a single logical axis.
- Return type:
- backproject(image, coordinates, *, axis_wavelength=None, axis_field=None, integrate=True, **kwargs)#
Not implemented: a ray-traced
SequentialSystemis not a linear operator, so it has no transpose. Build aLinearSystem(for example withlinearize()) to backproject.- Parameters:
image (FunctionArray[SpectralPositionalVectorArray, AbstractScalar])
coordinates (SpectralPositionalVectorArray)
axis_wavelength (None | str)
integrate (bool)
kwargs (Any)
- Return type:
FunctionArray[SpectralPositionalVectorArray, AbstractScalar]
- beam_footprint(index, wavelength=None, samples_field_stop=401, samples_pupil_stop=401)#
The outline of the beam on one surface of this system: the convex hull of the points where the light which reaches the end of the system crosses that surface.
The hull is that of two sets of rays, each traced through the whole system, of which only those which reach its end are kept:
the rays which graze the edges of both stops, solved for as they are for
rayfunction_stops;the rays of
grid_input, traced at wavelength asraytrace()traces them.
Where the stops bound the beam, every ray which reaches the end of the system passes inside both stops, and the outermost of them pass through the edges of both: as long as the system carries its stops onto the surface nearly linearly, a ray through the inside of either stop lands between rays through its edge. Where another aperture cuts the beam, the corners it makes where its edge crosses the outline of the beam it cuts are found from these rays too, to within the spacing of the samples along the edges.
A grid of rays over the field and the pupil finds the corners of the hull only to within the spacing of the grid, which shrinks as the fourth root of the number of rays traced. Along the edges of the stops the spacing shrinks as the square root, so the hull of the rays along them is much sharper for the same number.
The rays of the grid fill in what the rays along the edges of the stops miss, to within the spacing of the grid: a corner of another aperture which lies inside the beam, and a beam which another aperture, smaller than it everywhere, bounds instead of the stops, so that it blocks every ray along their edges. So the outline holds every ray of the grid which reaches the end of the system, but where the stops do not bound the beam, it is only as close to the beam as the grid is fine.
Each ray along the edges lies on the edge of both stops, where rounding would block about half of them, so both stops are left open for their trace, the way
_surfaces_openleaves the field stop. If more than one surface is marked as either stop, these are the pair the solve finishes on, see_pairs_stops(), and the others vignette the rays like any other aperture.The outline is convex, so where an obscuration cuts a notch into the beam, the outline spans it.
- Parameters:
index (int) – The index in
surfaces_allof the surface to outline the beam on.wavelength (None | Quantity | AbstractScalar) – The wavelengths of the beam. If
None(the default),self.grid_input.wavelengthis used.samples_field_stop (int) – The number of points along the edge of the field stop. A polygonal stop with fewer corners than this is sampled at every one of them.
samples_pupil_stop (int) – The number of points along the edge of the pupil stop, sampled the same way.
- Returns:
The outline of the beam, in the local coordinates of the surface.
An aperture with a transformation of its own gives its vertices
before that transformation, so on a stop the outline matches
aperture.transformation(aperture.vertices)rather thanaperture.vertices. The vertices of the outline vary along anaxis named
vertex, asnamed_arrays.geometry.convex_hull()gives them, and every other axis of the system, of wavelength and
of
grid_inputother than its field and pupil gets anoutline of its own. The vertices of an outline which no ray
reaches are all NaN.
- Return type:
- distortion(wavelength=None, field=None, pupil=None, normalized_field=True, normalized_pupil=True, degree=2, seed_field=0, seed_pupil=0)#
Fit a polynomial distortion model to the rays traced through this system.
The components of field and pupil are interpreted as the vertices of a grid of cells, and one ray is traced per cell at a point drawn uniformly inside it, which is how
vignetting(),area_effective(), andlinearize()trace as well. Handed the same grids, degree, and seeds,linearize()returns this very model as itsdistortion.As in
vignetting(), the field stop and the sensor are left open while the rays are traced, and the model is fit over the field cells whose centers lie inside the field of view and whose light lands on the sensor.- Parameters:
wavelength (None | Quantity | AbstractScalar) – The wavelengths at which to sample the system. If
None(the default),self.grid_input.wavelengthwill be used.field (None | AbstractCartesian2dVectorArray) – The vertices of the field grid, in either normalized or physical units. One ray is traced per cell, at a point drawn uniformly inside it. If
None(the default), \(12 \times 12\) vertices spanning the normalized field, so \(11 \times 11\) cells.pupil (None | AbstractCartesian2dVectorArray) –
The vertices of the pupil grid, in either normalized or physical units. One ray is traced per cell, at a point drawn uniformly inside it, and the sensor position of each field cell is the mean over them. If
None(the default), \(12 \times 12\) vertices spanning the normalized pupil, so \(11 \times 11\) cells.Both grids are the ones
area_effective()uses when given none, so passing these defaults back describes the same grid as leaving them out.normalized_field (bool) – A boolean flag indicating whether the field parameter is given in normalized or physical units.
normalized_pupil (bool) – A boolean flag indicating whether the pupil parameter is given in normalized or physical units.
degree (int) – The degree of the polynomial distortion model.
seed_field (None | int) –
The seed of the draw which places a field position inside each field cell, as described above, or
Noneto take the center of each cell instead. Zero by default, so that fitting the same system twice gives the same model, and so that this method andlinearize()agree when neither is given a seed. Any other integer gives a different fixed sample, and the spread of the model over several of them is its spread over the sampling.The centers lay the measurements out on a regular grid, which is the clearer way to show the model. Whether the light of a cell lands on the sensor is decided at the field position drawn in it, so only at the centers is the edge of the sensor drawn as the cells it covers, as the edge of the field stop always is.
seed_pupil (None | int) –
The seed of the draw which places a pupil position inside each pupil cell, drawn afresh at every field position, or
Noneto take the center of each cell instead. Zero by default, for the same reasons as seed_field. The two seeds drive separate streams, so either can be changed while the samples of the other grid stay where they were, and the same integer handed to both still draws the two grids independently.The centers are the same pupil positions at every field position, so where the edge of an aperture falls between two of them is decided once for a whole row of the field rather than averaged over it, and the model comes out in bands.
- Raises:
ValueError – If the wavelength grid does not vary along a single logical axis, or if fewer than
degree + 1of its wavelengths bring any of the sampled field positions onto the sensor.- Return type:
- field_stop_polygon(wavelength=None)#
The field of view of this system as a polygon in field coordinates: its half-light outline.
Each vertex is the average of the rays through one point on the edge of the field stop from around the edge of the pupil stop, in angle if the object is at infinity and in position if it is not.
A field stop at an image of the object passes a field position whole or not at all, and every ray through a point on its edge lands at the same place, so the polygon is then the image of the stop. One which is not at an image has a soft edge: a field position a little outside the image of the stop still passes the part of its pupil which clears it, and one a little inside loses the part which does not. The polygon runs through the middle of that falloff, where half of the pupil clears the stop, which is where a measured edge of the field of view sits.
linearize()blocks the scene there, and the models it fits are normalized over the field positions inside it.A field stop ahead of every dispersive element gives the same polygon at every wavelength. One behind a dispersive element gives a different polygon at each, and the vertices then vary along the wavelength axis: vertex for vertex, since each is the same point on the edge of the stop at every wavelength.
linearize()fits them in wavelength withPolynomialFieldStopModel.- Parameters:
wavelength (None | Quantity | AbstractScalar) – The wavelengths at which to solve for the stop rays. If
None(the default),self.grid_input.wavelengthis used, and the cachedrayfunction_stopsare read.- Return type:
- image(scene, *, axis_wavelength=None, axis_field=None, integrate=True, noise=True, pupil=None, axis_pupil=None, seed=None)#
Forward model of the optical system. Maps the given spectral radiance of a scene to detector counts.
- Parameters:
scene (FunctionArray[SpectralPositionalVectorArray, AbstractScalar]) – The spectral radiance of the scene as a function of wavelength and field position. The inputs must be cell vertices.
axis_wavelength (None | str) – The logical axis of scene corresponding to changing wavelength coordinate. If
None,set(scene.inputs.wavelength.shape) - set(self.shape), should have only one element.axis_field (None | tuple[str, str]) – The two logical axes of scene corresponding to changing field coordinate. If
None,set(scene.inputs.position.shape) - set(self.shape) - {axis_wavelength}, should have exactly two elements.integrate (bool) – Whether to integrate the wavelength axis. Real images usually have the wavelength axis integrated since they use a black/white sensor, but it can be useful to leave the wavelengths separate for introspective purposes.
noise (bool) – Whether to add noise to the result.
pupil (None | AbstractCartesian2dVectorArray) – The vertices of the pupil grid in either normalized or physical coordinates. If
None(the default), the pupil grid will only have one cell.axis_pupil (None | tuple[str, str]) – The two logical axes of pupil corresponding to changing pupil coordinate. If
None,set(pupil.shape) - set(self.shape) - {axis_wavelength,} - set(axis_field), should have exactly two elements. If pupil isNone, this parameter is ignored.seed (None | int) – The seed of the draw which places a ray at a random position inside each cell of the wavelength, field, and pupil grids, or
Noneto draw different positions every time. The noise is not seeded.
- Return type:
FunctionArray[SpectralPositionalVectorArray, AbstractScalar]
- linearize(wavelength=None, field=None, pupil=None, normalized_field=True, normalized_pupil=True, degree=2, degree_distortion=None, degree_vignetting=None, seed_field=0, seed_pupil=0, field_stop=True)#
Construct a linear approximation of this system by fitting its distortion, vignetting, and effective area models.
The result is an
LinearSystem, a fast forward model which images scenes by conservative regridding instead of raytracing each one.All three models are fit to one set of rays, traced the way
area_effective()traces them: one ray per cell of the field and pupil grids, at a point drawn uniformly inside it, with the pupil drawn afresh at every field position. The distortion model reads where those rays land, the vignetting model which of them survive, and the effective area what they carry.The field of view is carried on the result as a
PolynomialFieldStopModel: the half-light outline offield_stop_polygon()at each sampled wavelength, fit in wavelength so that it can be evaluated at any other. Every scene cell outside it is blocked before the wavelengths are summed, which keeps one line’s light out of the field of another’s in a slitless spectrograph. The field stop is left open while the rays are traced, seevignetting(), so the vignetting model does not fall off at the edge of the field of view, and without the field stop light from beyond that edge gets through.The field of view is taken to be bounded by the field stop alone. Another aperture which cuts the field with a hard edge of its own, such as an object surface with an aperture when some other surface is the field stop, is not carried by the linear system: the field positions it blocks pass no light, so they are not fit, and the vignetting model runs on across them at full strength. Mark such an aperture as the field stop, or keep it clear of the field of view.
The half-light outline is where an edge measured in an image sits. Across a soft edge, a field stop cut there blocks the light just outside it and passes the unattenuated light just inside it, and the two balance to first order, so the light collected is right. What it cannot keep is where that light is: it images a soft edge as a hard one. It is also the edge
footprint()maps onto the sensor.- Parameters:
wavelength (None | Quantity | AbstractScalar) – The wavelengths at which to sample the system. If
None(the default),self.grid_input.wavelengthwill be used.field (None | AbstractCartesian2dVectorArray) – The vertices of the field grid, in either normalized or physical units. One ray is traced per cell, at a point drawn uniformly inside it. If
None(the default), \(12 \times 12\) vertices spanning the normalized field, so \(11 \times 11\) cells.pupil (None | AbstractCartesian2dVectorArray) –
The vertices of the pupil grid, in either normalized or physical units. The area of each pupil cell is computed from these vertices and used to weight the throughput, and one ray is traced per cell, at a point drawn uniformly inside it. If
None(the default), \(12 \times 12\) vertices spanning the normalized pupil, so \(11 \times 11\) cells.Both grids are the ones
area_effective()uses when given none, so passing these defaults back describes the same grid as leaving them out.normalized_field (bool) – A boolean flag indicating whether the field parameter is given in normalized or physical units.
normalized_pupil (bool) – A boolean flag indicating whether the pupil parameter is given in normalized or physical units.
degree (int) – The degree of the polynomial distortion and vignetting models, unless either is given one of its own.
degree_distortion (None | int) – The degree of the polynomial distortion model, and of the polynomials in wavelength which carry the field stop, whose vertices move with wavelength as the distortion does. If
None(the default), degree.degree_vignetting (None | int) –
The degree of the polynomial vignetting model. If
None(the default), degree.The two need not agree, and the distortion of a spectrograph can need a higher degree than its vignetting. On ESIS, with \(11 \times 11\) field and pupil cells, a quadratic distortion is accurate to 0.01 pixels, while a quadratic vignetting model fits the noise of the sampling, with an error of up to 2.8% against 1.1% for a linear one.
seed_field (None | int) – The seed of the draw which places a field position inside each field cell, or
Noneto take the center of each cell instead, seevignetting(). Zero by default, so that linearizing the same system twice gives the same forward model: code which builds one linear system to make images and another to invert them would otherwise be using two different operators. Any other integer gives a different fixed sample, and the spread of these models over several of them is their spread over the sampling.seed_pupil (None | int) – The seed of the draw which places a pupil position inside each pupil cell, drawn afresh at every field position, or
Noneto take the center of each cell instead, seevignetting(). Zero by default, for the same reasons as seed_field.field_stop (bool) – Whether to carry the field of view on the result, see above. Fit with degree_distortion, held one below the number of wavelengths sampled.
- Raises:
ValueError – If the wavelength grid does not vary along a single logical axis, or if fewer of its wavelengths than one more than either degree bring any of the sampled field positions onto the sensor.
- Return type:
- plate_scale(wavelength=None)#
Compute the field of view divided by the pixels it spans.
The plate scale is reported along each axis of the sensor, in field coordinates per pixel: in angle if the object is at infinity, and in position if it is not.
It is measured along the two lines through the center of the field, one along each axis of the field. The chief rays of the field positions at either end of each line, at -1 and 1 in normalized field coordinates, give the span of the field along each line, and the span of its image on the sensor in pixels. The spans of the field, over the spans of the image, give the field per pixel along each axis of the sensor.
The ends of the lines are where they meet the edges of the box which bounds the field of view. For a field of view which is symmetric about its center and aligned with the axes of the field, such as a circle, a regular polygon, or a rectangle, that is the edge of the field of view itself. For one which is not, such as a rotated rectangle, the lines run past the field of view, and the plate scale is measured across more of the field than the system passes.
The spans are divided as matrices, one column for each axis of the field, rather than component by component. This keeps the result along the axes of the sensor however the sensor is rolled against the field, and lets the two axes differ, as they do behind a grating, which magnifies the image along its dispersion, or on a tilted sensor.
The plate scale varies across the field of view with the distortion of the system, and dividing the spans averages it along each line: the span of the image is the integral of its derivative with respect to the field, so the result is the plate scale of the mean derivative along each line. It does not average how the plate scale along one axis varies along the other. The plate scale also varies with wavelength behind a dispersive element, which is why it is computed at a wavelength.
The image is traced whether or not it lands on the sensor, so the plate scale is defined at wavelengths whose image falls partly or wholly off the sensor. It is NaN where the chief rays do not reach the sensor at all, such as at a wavelength whose order of diffraction does not propagate.
For an object at infinity, the field is in the azimuth and elevation of
optika.angles(), which are angles on the sky only near the axis of the object. A step in azimuth at an elevation covers the cosine of that elevation times as much sky, so the plate scale of a field of view centered far from the axis is not its angle on the sky per pixel.- Parameters:
wavelength (None | Quantity | AbstractScalar) – The wavelengths at which to compute the plate scale. If
None(the default),self.grid_input.wavelengthis used. Several wavelengths are given as a named array, along an axis which the result keeps.- Return type:
Examples
The plate scale of a spherical mirror focusing onto a sensor at its focus, which is the width of a pixel over the focal length.
import astropy.units as u import named_arrays as na import optika system = optika.systems.SequentialSystem( surfaces=[ optika.surfaces.Surface( name="mirror", sag=optika.sags.SphericalSag(-200 * u.mm), material=optika.materials.Mirror(), aperture=optika.apertures.CircularAperture(20 * u.mm), is_pupil_stop=True, transformation=na.transformations.Cartesian3dTranslation( z=100 * u.mm, ), ), ], sensor=optika.sensors.ImagingSensor( name="sensor", width_pixel=15 * u.um, axis_pixel=na.Cartesian2dVectorArray("detector_x", "detector_y"), timedelta_exposure=1 * u.s, num_pixel=na.Cartesian2dVectorArray(128, 128), is_field_stop=True, ), grid_input=optika.vectors.ObjectVectorArray( wavelength=500 * u.nm, field=0, pupil=0, ), ) system.plate_scale().to(u.arcsec / u.pix)
Cartesian2dVectorArray( x=ScalarArray( ndarray=30.93881836 arcsec / pix, shape={}, ), y=ScalarArray( ndarray=30.93881975 arcsec / pix, shape={}, ), )
- plot(ax=None, transformation=None, components=None, plot_rays=True, plot_rays_vignetted=False, kwargs_rays=None, unit=None, **kwargs)#
Plot the surfaces of the system and the default raytrace.
- Parameters:
ax (None | Axes | ScalarArray[NDArray]) – The matplotlib axes on which to plot the system
transformation (None | AbstractTransformation) – Any additional transformation to apply to the system before plotting.
components (None | tuple[str, ...]) – The vector components to plot if ax is 2-dimensional.
plot_rays (bool) – Boolean flag indicating whether to plot the rays.
plot_rays_vignetted (bool) – Boolean flag indicating whether to plot the vignetted rays.
kwargs_rays (None | dict[str, Any]) – Any additional keyword arguments to use when plotting the rays.
unit (None | UnitBase) –
The unit to express every plotted length in.
A system is free to describe its parts in whichever units suit them, and a detector measured in microns alongside optics measured in millimeters is quite normal. Matplotlib is told about units by
astropy.visualization.quantity_support(), which reconciles them on a 2D axes but not on a 3D one, where a surface given in microns is drawn a thousand times too large.Giving a unit here converts everything to it first, so the system is drawn to one scale whatever the axes. Leaving it as
None, the default, passes the lengths through as they are.kwargs – Any additional keyword arguments to use when plotting the surfaces.
- Return type:
- radius_spot(wavelength=None, field=None, pupil=None, axis_pupil=None, normalized_field=True, normalized_pupil=True)#
Compute the RMS radius of the spot which each field position makes on the sensor.
Each spot is traced through a grid of positions on the pupil, and its radius is measured from its centroid, so that the result is the size of the spot and not where it lands. The rays are weighted by their intensity on the sensor, the throughput of the system along each ray, so that a part of the pupil which passes less light counts for less, in the centroid as well as in the radius. The result is the geometric size of the spot, without diffraction.
The rays are traced with the sensor left open, so that a spot which straddles the edge of the sensor is measured whole rather than by the part of it which lands on the pixels. A spot whose centroid misses the pixels is NaN. So is a spot which the rest of the system vignettes wholly, such as one from a field position outside the field of view, or none of whose light reaches the sensor, and a spot which it vignettes in part is measured over the rays which pass.
The radius is in the units of position on the sensor. Divide it by
sensor.width_pixel / u.pixto have it in pixels.- Parameters:
wavelength (None | Quantity | AbstractScalar) – The wavelengths of the spots. If
None(the default),self.grid_input.wavelengthis used.field (None | AbstractCartesian2dVectorArray) – The field positions of the spots, in either normalized or physical units. If
None(the default),self.grid_input.fieldis used.pupil (None | AbstractCartesian2dVectorArray) – The positions on the pupil to trace for each spot, in either normalized or physical units. If
None(the default),self.grid_input.pupilis used.axis_pupil (None | tuple[str, str]) – The two logical axes of the pupil positions to measure each spot over. If
None(the default) and pupil isNone,axis_pupilis used. If that isNonetoo, or if pupil is given, the pupil positions should vary along only two axes other than those ofshape, the wavelengths, and the field positions.normalized_field (bool) – A boolean flag indicating whether the field parameter is given in normalized or physical units.
normalized_pupil (bool) – A boolean flag indicating whether the pupil parameter is given in normalized or physical units.
- Return type:
Examples
The RMS spot size of a spherical mirror focusing onto a sensor at its paraxial focus, which is the spherical aberration of the mirror.
import astropy.units as u import named_arrays as na import optika system = optika.systems.SequentialSystem( surfaces=[ optika.surfaces.Surface( name="mirror", sag=optika.sags.SphericalSag(-200 * u.mm), material=optika.materials.Mirror(), aperture=optika.apertures.CircularAperture(20 * u.mm), is_pupil_stop=True, transformation=na.transformations.Cartesian3dTranslation( z=100 * u.mm, ), ), ], sensor=optika.sensors.ImagingSensor( name="sensor", width_pixel=15 * u.um, axis_pixel=na.Cartesian2dVectorArray("detector_x", "detector_y"), timedelta_exposure=1 * u.s, num_pixel=na.Cartesian2dVectorArray(128, 128), is_field_stop=True, ), grid_input=optika.vectors.ObjectVectorArray( wavelength=500 * u.nm, field=0, pupil=na.Cartesian2dVectorLinearSpace( start=-1, stop=1, axis=na.Cartesian2dVectorArray("pupil_x", "pupil_y"), num=21, ), ), ) system.radius_spot().to(u.um)
ScalarArray( ndarray=51.50973886 um, shape={}, )
- rayfunction(intensity=None, wavelength=None, field=None, pupil=None, normalized_field=True, normalized_pupil=True, efficiency=True)#
Given the wavelength, field position, and pupil position of some input rays, trace those rays through the system and return the resulting rays in local coordinates of the sensor (if it exists).
- Parameters:
intensity (None | float | Quantity | AbstractScalar) – The energy density of the input rays.
wavelength (None | Quantity | AbstractScalar) – The wavelengths of the input rays. If
None(the default),self.grid_input.wavelengthwill be used.field (None | AbstractCartesian2dVectorArray) – The field positions of the input rays, in either normalized or physical units. If
None(the default),self.grid_input.fieldwill be used.pupil (None | AbstractCartesian2dVectorArray) – The pupil positions of the input rays, in either normalized or physical units. If
None(the default),self.grid_input.pupilwill be used.normalized_field (bool) – A boolean flag indicating whether the field parameter is given in normalized or physical units.
normalized_pupil (bool) – A boolean flag indicating whether the pupil parameter is given in normalized or physical units.
efficiency (bool) – A boolean flag indicating whether to accumulate the efficiency of each surface into
intensity. IfFalse, the intensity of the result is meaningless, but the geometry andunvignettedare unchanged and much cheaper to compute.
- Return type:
See also
raytraceSimilar to rayfunction except it can compute all the intermediate rays, and it returns results in global coordinates.
- raytrace(intensity=None, wavelength=None, field=None, pupil=None, axis=None, normalized_field=True, normalized_pupil=True, accumulate=True, efficiency=True)#
Given the wavelength, field position, and pupil position of some input rays, trace those rays through the system and return the result in global coordinates, optionally including all intermediate rays.
- Parameters:
intensity (None | float | Quantity | AbstractScalar) – The energy density of the input rays.
wavelength (None | Quantity | AbstractScalar) – The wavelengths of the input rays. If
None(the default),self.grid_input.wavelengthwill be used.field (None | AbstractCartesian2dVectorArray) – The field positions of the input rays, in either normalized or physical units. If
None(the default),self.grid_input.fieldwill be used.pupil (None | AbstractCartesian2dVectorArray) – The pupil positions of the input rays, in either normalized or physical units. If
None(the default),self.grid_input.pupilwill be used.axis (None | str) – The axis along which the rays are accumulated. If
None(the default),axis_surfacewill be used.normalized_field (bool) – A boolean flag indicating whether the field parameter is given in normalized or physical units.
normalized_pupil (bool) – A boolean flag indicating whether the pupil parameter is given in normalized or physical units.
accumulate (bool) – Whether to include intermediate rays in the result.
efficiency (bool) – A boolean flag indicating whether to accumulate the efficiency of each surface into
intensity. IfFalse, the intensity of the result is meaningless, but the geometry andunvignettedare unchanged and much cheaper to compute.
- Return type:
See also
rayfunctionSimilar to raytrace except it only returns the rays at the last surface in local coordinates.
- replace(**changes)#
A copy of this object with the given fields replaced.
A method version of
dataclasses.replace(), matchingnamed_arrays.AbstractArray.replace(), so that a nested change reads the same at every level:system.replace( surface=system.surface.replace( sag=system.surface.sag.replace(radius=r), ), )
The copy is shallow, as
dataclasses.replace()is: every field which is not named is shared with the original, and mutating one through the copy is mutating it in both. Takecopy.deepcopy()of the result where that matters.- Parameters:
changes – The fields to overwrite in the copy.
- Return type:
- spot_diagram(figsize=(8, 6), s=5, cmap=None)#
Create a spot diagram of the rays at each field point to inspect the performance of this optical system.
- to_dxf(file, unit, transformation=None)#
Write a drawing of this object to a DXF file.
A DXF file cannot represent uncertainty, so if this object has any uncertain parameters, the drawing is of its nominal value.
- Parameters:
file (Path) – The path of the DXF file to write.
unit (Unit) – The length units to use for this file.
transformation (None | AbstractTransformation) – An additional transformation to apply to the coordinate system before writing to the DXF file.
- to_string(prefix=None)#
Public-facing version of the
__repr__method that allows for defining a prefix string, which can be used to calculate how much whitespace to add to the beginning of each line of the result.
- vignetting(wavelength=None, field=None, pupil=None, normalized_field=True, normalized_pupil=True, degree=2, seed_field=0, seed_pupil=0)#
Fit a polynomial vignetting model to the rays traced through this system.
The relative illumination at each scene coordinate is estimated from the unvignetted area of that field position’s entrance pupil, normalized so that its average over the field of view is unity.
The field stop and the sensor are left open while the rays are traced. Both sit at or near an image of the object, where each cuts across the field in a step which no polynomial can follow, and a field position drawn inside that step would otherwise be fit with whatever part of its beam got through, depending on where in its cell it happened to fall. With both open, the illumination is the vignetting by the rest of the system, which is smooth. The model is fit over the field cells whose centers lie inside the half-light outline of the field of view,
field_stop_polygon(), and whose light lands on the sensor, and it is normalized over every field position inside that outline, whether or not its light lands on the sensor, so that every wavelength is normalized over the same part of the field. The field stop is applied on its own bylinearize(), as that polygon, and the edge of the sensor by the pixels the light lands on. The plots of the model draw the cells it was fit over, so they stop at both edges.Carrying the size of the pupil, rather than the bare fraction of it which survives, is what lets this model and
area_effective()be multiplied together; see the latter for why.The components of field and pupil are interpreted as the vertices of a grid of cells, and one ray is traced per cell at a point drawn uniformly inside it, which is how
area_effective()andlinearize()trace as well. Handed the same grids, degree, and seeds,linearize()returns this very model as itsvignetting.- Parameters:
wavelength (None | Quantity | AbstractScalar) – The wavelengths at which to sample the system. If
None(the default),self.grid_input.wavelengthwill be used.field (None | AbstractCartesian2dVectorArray) – The vertices of the field grid, in either normalized or physical units. One ray is traced per cell, at a point drawn uniformly inside it. If
None(the default), \(12 \times 12\) vertices spanning the normalized field, so \(11 \times 11\) cells.pupil (None | AbstractCartesian2dVectorArray) –
The vertices of the pupil grid, in either normalized or physical units. The area of each pupil cell is computed from these vertices and summed over the unvignetted cells, and one ray is traced per cell, at a point drawn uniformly inside it. If
None(the default), \(12 \times 12\) vertices spanning the normalized pupil, so \(11 \times 11\) cells.Both grids are the ones
area_effective()uses when given none, so passing these defaults back describes the same grid as leaving them out.normalized_field (bool) – A boolean flag indicating whether the field parameter is given in normalized or physical units.
normalized_pupil (bool) – A boolean flag indicating whether the pupil parameter is given in normalized or physical units.
degree (int) – The degree of the polynomial vignetting model.
seed_field (None | int) –
The seed of the draw which places a field position inside each field cell, as described above, or
Noneto take the center of each cell instead. Zero by default, so that fitting the same system twice gives the same model, and so that this method andlinearize()agree when neither is given a seed. Any other integer gives a different fixed sample, and the spread of the model over several of them is its spread over the sampling.A cell counts toward the average over the field of view if its field position lies inside the field stop, which one drawn at random does with a probability equal to the fraction of the cell inside it, so the average carries none of the bias a fixed rule has wherever the edge of the field crosses a cell. The centers lay the measurements out on a regular grid, which is the clearer way to show the model. Whether the light of a cell lands on the sensor is decided at the field position drawn in it, so only at the centers is the edge of the sensor drawn as the cells it covers, as the edge of the field stop always is.
seed_pupil (None | int) –
The seed of the draw which places a pupil position inside each pupil cell, drawn afresh at every field position, or
Noneto take the center of each cell instead. Zero by default, for the same reasons as seed_field. The two seeds drive separate streams, so either can be changed while the samples of the other grid stay where they were, and the same integer handed to both still draws the two grids independently.The centers are the same pupil positions at every field position, so where the edge of an aperture falls between two of them is decided once for a whole row of the field rather than averaged over it, and the model comes out in bands.
- Raises:
ValueError – If the wavelength grid does not vary along a single logical axis, or if fewer than
degree + 1of its wavelengths bring any of the sampled field positions onto the sensor.- Return type:
- axis_field: None | tuple[str, str] = None#
The logical axes of
grid_inputcorresponding to changing field coordinate.If
None(the default),grid_input.fieldshould have only two axes other than those inshapeandaxis_wavelength.
- property axis_field_: tuple[str, str]#
Normalized version of
axis_field.
- axis_field_stop: ClassVar[str] = '_stop_field'#
The axis along the edge of the field stop.
Named by this system, in the same way and for the same reason as
axis_pupil_stop.
- axis_pupil: None | tuple[str, str] = None#
The logical axes of
grid_inputcorresponding to changing pupil coordinate.If
None(the default),grid_input.pupilshould have only two axes other than those inshape,axis_wavelength, andaxis_field.
- property axis_pupil_: tuple[str, str]#
Normalized version of
axis_pupil.
- axis_pupil_stop: ClassVar[str] = '_stop_pupil'#
The axis along the edge of the pupil stop.
This system names the axis rather than taking a name for it, since it is swept internally and not by the caller. The leading underscore marks it as such, and keeps it from colliding with an axis somebody else named.
- property axis_stops: tuple[str, str]#
The axes along the edges of the two stop surfaces.
These are the axes of
field_boundaryandpupil_boundary, and so the ones to reduce over to turn either outline into a measurement of the system.
- axis_wavelength: None | str = None#
The logical axis of
grid_inputcorresponding to changing wavelength.If
None(the default),grid_input.wavelengthshould have at most one logical axis other than the axes inshape.
- property axis_wavelength_: tuple[str, ...]#
Normalized version of
axis_wavelength.An empty
tupleifgrid_input.wavelengthdoes not vary along its own logical axis.
- property field_boundary: AbstractCartesian2dVectorArray#
The field coordinates at the edge of this optical system’s field of view.
These are the rays which graze the edges of both stops, so they trace the outline of the field rather than filling it. In angle if the object is at infinity, and in position if it is not.
How wide a field of view this outline represents is a question the outline alone does not answer, and different instruments answer it differently. For a field stop which is not a circle, the extent of the field depends on the direction it is measured along, and on how the system is rolled about its optical axis. An octagonal stop, for instance, is wider corner to corner than edge to edge by a factor of \(1 / \cos(22.5^\circ)\). Reduce this outline in whichever way the instrument at hand takes to be its field of view;
field_minandfield_maxare two such reductions.
- property field_max: AbstractCartesian2dVectorArray#
The upper right corner of this optical system’s field of view.
- property field_min: AbstractCartesian2dVectorArray#
The lower left corner of this optical system’s field of view.
- property field_stop: AbstractSurface#
The field stop surface.
- grid_input: ObjectVectorArray = None#
The input grid to sample with rays.
This grid is simultaneously projected onto both the field stop and the pupil stop.
Positions on the stop can be specified in either absolute or normalized coordinates. Using normalized coordinates allows for injecting different grid types (cylindrical, stratified random, etc.) without specifying the scale of the stop surface.
If positions are specified in absolute units, they are measured in the coordinate system of the corresponding stop surface.
- property index_field_stop: int#
The index of the field stop in
surfaces_all.
- property index_pupil_stop: int#
The index of the pupil stop in
surfaces_all.
- object: AbstractSurface = None#
The external object being imaged or illuminated by this system.
If
None, the object is assumed to be an empty surface at the origin.
- property object_is_at_infinity: bool#
A boolean flag indicating if the object is at infinity.
If
objectdoesn’t have an aperture, it is assumed that the object is at infinity.
- property pupil_boundary: AbstractCartesian2dVectorArray#
The coordinates at the edge of this optical system’s entrance pupil.
The counterpart of
field_boundary, in position if the object is at infinity and in angle if it is not.
- property pupil_fit: None | tuple[PolynomialFitFunctionArray, PolynomialFitFunctionArray]#
The entrance pupil of the system, fit as a function of field position at the wavelengths of
grid_input.Noneif the fit is singular, in which case the box shared by every field point is used instead. Cached; see the notes onAbstractSequentialSystembefore changing a system in place.
- property pupil_max#
The upper right corner of this optical system’s entrance pupil in physical units.
- property pupil_min: AbstractCartesian2dVectorArray#
The lower left corner of this optical system’s entrance pupil in physical units.
- property pupil_stop: AbstractSurface#
The pupil stop surface.
- property rayfunction_default: RayFunctionArray#
Computes the rays in local coordinates at the last surface in the system as a function of input wavelength and position using
grid_input.Cached; see the notes on
AbstractSequentialSystembefore changing a system in place.
- property rayfunction_stops: RayFunctionArray#
The rays which graze the edges of both the field stop and the pupil stop, expressed in the frame of the object surface.
They trace the outline of the field and of the entrance pupil, along
axis_field_stopandaxis_pupil_stop. Cached; see the notes onAbstractSequentialSystembefore changing a system in place.
- sensor: AbstractImagingSensor = None#
The imaging sensor that measures the light captured by this system.
This is the last surface in the optical system.
- surfaces: Sequence[AbstractSurface] = <dataclasses._MISSING_TYPE object>#
A sequence of surfaces representing this optical system.
At least one of these surfaces needs to be marked as the pupil surface, and if the object surface is not marked as the field stop, one of these surfaces needs to be marked as the field stop.
- property surfaces_all: list[AbstractSurface]#
Concatenate
objectwithsurfacesinto a single list of surfaces.The object surface defines the reference frame of the system and so is left untouched, while
transformationis composed onto every other surface. Settingtransformationtherefore repositions the optics relative to a fixed object, instead of moving the object and the optics together as a rigid whole.
- transformation: None | AbstractTransformation = None#
A optional coordinate transformation to apply to the entire optical system.