"""Full-frame slitless grating images: the wcc_etc.grating model placed on the detector.
Under development, as is wcc_etc.grating: the grating design is provisional.
wcc_etc.GratingSimulation supplies the physics for one star on one half of the
grating (coating, diffraction efficiency, dispersion, dispersed PSF image and the
slitless sky rate). This module places it on the array:
- The grating has two halves, split at detector column `split_x` (default the
array centre). The blue half (350-700 nm) is on the left and disperses along
+x (rows); the red half (600-1100 nm) is on the right and disperses along +y
(columns). Each star's zeroth order is at its catalogue position.
- The grating sits in front of the sensor, so the converging beam of a star has a
finite footprint on it (`beam_radius_px`, 620 px on the IMX455). A star closer
to the split than that sends part of its light through each half and gets both
spectra, each scaled by the fraction of the beam on that half (blue_fraction).
The sky rate changes across the split in the same way.
- Every star of one spectral type shares one dispersed template per half
(grating_template), scaled by its G magnitude.
Not modelled: the PSF of a beam clipped by the split (both spectra use the
full-pupil PSF, and the central obscuration is ignored in the beam fraction),
PSF wings and scattered light beyond the template (65 px across the dispersion),
extended sources, defocus, and what wcc_etc.grating leaves out (static wavefront
error, the dispersion change across the tilted sensor).
"""
import secrets
from functools import lru_cache
import numpy as np
from astropy import units as u
from wcc_etc import Simulation
from wcc_etc.grating import GratingSimulation
from wcc_etc.io import KIND_NAMES, SENSORFILTER_FOCUS
from wcc_etc.scene import get_scene
from .catalog import query_gaia
from .detectors import detector_frame, get_geometry, saturation_level_e
from .pipeline import SimulatedField, _placed_catalog, _validate_inputs
from .render import add_noise_and_digitize
from .starflux import (REF_MAG, color_fallback, column_floats, gaia_g_bandpass,
rates_for_catalog)
DEFAULT_ORDERS = (-1, 0, 1, 2)
def _sensor_kind(sensor):
kind = str(sensor).split(":")[0]
kind = KIND_NAMES.get(kind, kind)
if kind not in ("zwo", "qcmos"):
raise ValueError(f"sensor must be 'zwo' (IMX455) or 'qcmos' (HWK4123), got {sensor!r}")
return kind
[docs]
def blue_fraction(x, split_x, beam_radius_px):
"""Fraction of the beam of a source at column `x` that passes the blue (left) half.
The beam footprint on the grating is taken as a filled circle of radius
`beam_radius_px` centred on the source; the fraction is the area of the
circle left of `split_x`: 1 well left of the split, 0.5 on it, 0 well right.
"""
d = np.clip((split_x - np.asarray(x, dtype=float)) / beam_radius_px, -1.0, 1.0)
return 0.5 + (d * np.sqrt(1.0 - d * d) + np.arcsin(d)) / np.pi
[docs]
class GratingTemplate:
"""Dispersed image of one star [e-/s at G = REF_MAG] on a fine grid, detector-oriented.
`fine` has `oversample` fine pixels per detector pixel; the zeroth order is at
the centre of detector pixel `origin` = (y0, x0) of the stamp. `total` is the
rate in the template (all rendered orders).
"""
def __init__(self, fine, origin, oversample):
self.fine, self.origin, self.oversample = fine, origin, int(oversample)
self.total = float(fine.sum())
self._stamps = {}
[docs]
def stamp(self, sy=0, sx=0):
"""Detector-resolution stamp with the source moved by (sy, sx) fine pixels; cached."""
if (sy, sx) not in self._stamps:
k = self.oversample
ny, nx = self.fine.shape[0] // k, self.fine.shape[1] // k
rolled = np.roll(self.fine, (sy, sx), axis=(0, 1))
self._stamps[sy, sx] = rolled.reshape(ny, k, nx, k).sum(axis=(1, 3)).astype(
np.float32)
return self._stamps[sy, sx]
[docs]
def add(self, image, x, y, scale):
"""Add `scale` x the template to `image` with the zeroth order at float pixel (x, y)."""
k = self.oversample
xi, yi = int(round(x)), int(round(y))
stamp = self.stamp(int(round((y - yi) * k)), int(round((x - xi) * k)))
y_lo, x_lo = yi - self.origin[0], xi - self.origin[1]
y_hi, x_hi = y_lo + stamp.shape[0], x_lo + stamp.shape[1]
iy_lo, ix_lo = max(y_lo, 0), max(x_lo, 0)
iy_hi, ix_hi = min(y_hi, image.shape[0]), min(x_hi, image.shape[1])
if iy_lo >= iy_hi or ix_lo >= ix_hi:
return
image[iy_lo:iy_hi, ix_lo:ix_hi] += np.float32(scale) * stamp[
iy_lo - y_lo:iy_hi - y_lo, ix_lo - x_lo:ix_hi - x_lo]
def _grating_simulation(sim, half, orders, grating_kw):
return GratingSimulation(sim, half=half, orders=orders, **dict(grating_kw))
@lru_cache(maxsize=None)
def _template(spt, kind, half, oversample, orders, grating_kw):
# as starflux.make_star_simulation, on the no-filter band of the sensor
scene = get_scene(spt, mag=REF_MAG, magsys="vegamag", bandpass=gaia_g_bandpass())
sim = Simulation.from_sensor_and_scene(f"{kind}:nofilter", scene)
g = _grating_simulation(sim, half, orders, grating_kw)
_, _, x0, y0 = g.canvas()
fine = g.oriented(g.rate_image(source_only=True, oversample=oversample))
return GratingTemplate(fine, (y0, x0) if half == "blue" else (x0, y0), oversample)
[docs]
def grating_template(spt, sensor="zwo", half="blue", oversample=5, orders=DEFAULT_ORDERS,
grating=None):
"""GratingTemplate of a Pickles type `spt` at G = REF_MAG on one half; memoized.
`grating` (dict) passes design overrides to wcc_etc.GratingSimulation
(lines_per_mm, distance_mm, psf_npix, ...).
"""
return _template(str(spt), _sensor_kind(sensor), half, int(oversample),
tuple(int(m) for m in orders), tuple(sorted((grating or {}).items())))
[docs]
def simulate_grating_field(
ra,
dec,
sensor="zwo",
exptime=90.0,
n_reads=1,
pa=0.0,
mag_limit=21.0,
add_noise=True,
seed=None,
output=None,
catalog=None,
shape=None,
oversample=5,
orders=DEFAULT_ORDERS,
split_x=None,
grating=None,
cache_dir=None,
write_clean=True,
gain_mode=None,
offset_arcsec=(0.0, 0.0),
):
"""Simulate one slitless-grating exposure of the Gaia field at (ra, dec) -> SimulatedField.
Under development (the grating design is provisional). See the module
docstring for the layout and what is not modelled. The arguments not listed
below (exptime, n_reads, pa, mag_limit, add_noise, seed, output, catalog,
shape, cache_dir, write_clean, gain_mode, offset_arcsec) are those of
simulate_field.
Parameters
----------
ra, dec : float
Pointing [deg, ICRS], the array centre (before `offset_arcsec`).
sensor : str, default "zwo"
"zwo" (Sony IMX455) or "qcmos" (HWK4123).
oversample : int, default 5
Fine pixels per detector pixel of the templates (positive, odd); stars are
placed to 1 / (2 oversample) px.
orders : tuple of int, default (-1, 0, 1, 2)
Diffraction orders rendered.
split_x : float, optional
Column [px of this frame] of the boundary between the blue (left) and red
(right) half. Default (nx - 1) / 2, the centre of the (sub)array.
grating : dict, optional
Design overrides for wcc_etc.GratingSimulation (lines_per_mm, distance_mm,
levels, coating_peak, edge_width_nm, psf, psf_npix).
Returns
-------
SimulatedField
CAT columns added: x, y (zeroth order), spt, spt_fallback, blue_fraction,
rate_e_s (rendered rate, all orders and both halves), in_image, saturated
(the star's own brightest pixel, any order, reaches the per-frame ceiling;
the SATMASK extension has the pixels, sky and neighbours included).
params holds the geometry an extraction needs: grating_split_x,
grating_beam_radius_px, grating_dispersion_px_nm, grating_orders.
"""
_validate_inputs(ra, dec, None, exptime, n_reads, mag_limit, oversample, shape,
None, 1.0, catalog)
kind = _sensor_kind(sensor)
orders = tuple(int(m) for m in orders)
grating_kw = tuple(sorted((grating or {}).items()))
sensorfilter = f"{kind}:nofilter"
# frame and geometry do not depend on the filter; nofilter is not in wcc_etc's
# sensorfilter table, so any filter of this sensor stands in for them
geom_key = next(k for k in sorted(SENSORFILTER_FOCUS) if k.startswith(kind + ":"))
sim = Simulation.from_sensor_and_scene(sensorfilter, get_scene("G2V", mag=15.0),
gain_mode=gain_mode)
geom = get_geometry(geom_key, sim=sim)
frame = detector_frame(geom_key, (ra, dec), offset_arcsec=offset_arcsec, pa=pa,
shape=shape)
centre = (float(ra), float(dec))
ra, dec = frame.pointing
wcs, shape = frame.wcs, frame.shape
ny, nx = shape
halves = {h: _grating_simulation(sim, h, orders, grating_kw) for h in ("blue", "red")}
g0 = halves["blue"]
beam_radius_px = 0.5 * g0.distance_mm / float(sim.telescope.f_num) * 1e3 / geom.pixel_size_um
split_x = (nx - 1) / 2.0 if split_x is None else float(split_x)
reach_px = max(max(g.canvas()[:2]) for g in halves.values())
radius_arcsec = ((0.5 * np.hypot(nx, ny) + reach_px) * geom.plate_scale_mas / 1000.0
+ 10.0)
queried = catalog is None
if queried:
catalog = query_gaia(ra, dec, radius_arcsec, mag_limit=mag_limit, cache_dir=cache_dir)
catalog, xs, ys = _placed_catalog(catalog.copy(), wcs)
n = len(catalog)
image = np.zeros(shape, dtype=np.float32)
rates = np.zeros(n)
peak_e_s = np.zeros(n) # brightest pixel of each star's own light
frac_blue = blue_fraction(xs, split_x, beam_radius_px) if n else np.array([])
spts = np.array([], dtype=str)
fallback = np.array([], dtype=bool)
if n:
_, spts = rates_for_catalog(catalog, geom_key) # the types do not depend on the band
fallback = color_fallback(catalog)
flux = 10.0 ** (-0.4 * (column_floats(catalog, "phot_g_mean_mag") - REF_MAG))
for spt in np.unique(spts):
for half, frac in (("blue", frac_blue), ("red", 1.0 - frac_blue)):
sel = np.flatnonzero((spts == spt) & (frac > 0.0))
if not len(sel):
continue
template = _template(str(spt), kind, half, int(oversample), orders, grating_kw)
rates[sel] += template.total * flux[sel] * frac[sel]
peak_e_s[sel] = np.maximum(peak_e_s[sel],
template.stamp().max() * flux[sel] * frac[sel])
for i in sel:
template.add(image, float(xs[i]), float(ys[i]),
flux[i] * frac[i] * exptime)
sky_half = {h: g.background_rate_per_pix() for h, g in halves.items()}
pixel_blue = blue_fraction(np.arange(nx), split_x, beam_radius_px)
sky = (pixel_blue * sky_half["blue"] + (1.0 - pixel_blue) * sky_half["red"])[None, :]
if seed is None:
seed = secrets.randbits(32)
out = add_noise_and_digitize(image, sim, exptime, n_reads, np.random.default_rng(seed),
add_noise=add_noise, sky=sky)
catalog["x"] = np.asarray(xs, dtype=float)
catalog["y"] = np.asarray(ys, dtype=float)
catalog["spt"] = spts
catalog["spt_fallback"] = np.asarray(fallback, dtype=bool)
catalog["blue_fraction"] = np.asarray(frac_blue, dtype=float)
catalog["rate_e_s"] = rates
in_image = ((xs > -0.5) & (xs < nx - 0.5) & (ys > -0.5) & (ys < ny - 0.5)
if n else np.array([], dtype=bool))
catalog["in_image"] = in_image
sensor_ = sim.sensor
catalog["saturated"] = peak_e_s * exptime / int(n_reads) >= saturation_level_e(sensor_)
params = {
"ra": float(ra), "dec": float(dec), "pa": float(pa),
"sensorfilter": sensorfilter,
"exptime": float(exptime), "n_reads": int(n_reads),
"jitter_sigma_mas": float(sim.telescope.jitter_sigma.to("mas").value),
"mag_limit": float(mag_limit) if queried else None,
"seed": seed,
"gaia_radius_arcsec": float(radius_arcsec),
"n_sources": int(n),
"nx": int(nx), "ny": int(ny), "n_pixels": int(nx) * int(ny),
"stamp_npix": int(g0.psf_npix),
"oversample": int(oversample),
"add_noise": bool(add_noise),
"pixel_size_um": float(geom.pixel_size_um),
"plate_scale_mas": float(geom.plate_scale_mas),
"gain": float(sensor_.gain.to(u.electron / u.ct).value),
"bias": float(sensor_.bias_level.to(u.ct).value),
"gain_mode": gain_mode,
"saturation_e": float(saturation_level_e(sensor_)),
"read_noise": float(sensor_.read_noise.value),
"dark_e_s": float(sensor_.dark_current.to(u.electron / u.pix / u.s).value),
"well_depth": (float(sensor_.meta["well_depth"])
if sensor_.meta.get("well_depth") is not None else None),
"grating": True,
"grating_split_x": split_x,
"grating_beam_radius_px": float(beam_radius_px),
"grating_dispersion_px_nm": float(g0.dispersion_px_per_nm),
"grating_orders": ",".join(str(m) for m in orders),
"sky_blue_e_s": float(sky_half["blue"]),
"sky_red_e_s": float(sky_half["red"]),
}
if frame.offset_arcsec != (0.0, 0.0):
params.update(centre_ra=centre[0], centre_dec=centre[1],
offset_ra_arcsec=frame.offset_arcsec[0],
offset_dec_arcsec=frame.offset_arcsec[1])
result = SimulatedField(
image_adu=out["image_adu"], image_e=out["image_e"], image_clean=out["image_clean"],
saturation_mask=out["satmask"], wcs=wcs, catalog=catalog, params=params,
models={"sky_e_s": sky[0], "gratings": halves},
)
if output is not None:
result.write(output, write_clean=write_clean)
return result