diff --git a/docs/site_pipeline.rst b/docs/site_pipeline.rst index c8d23bb18..e8693006a 100644 --- a/docs/site_pipeline.rst +++ b/docs/site_pipeline.rst @@ -1029,6 +1029,140 @@ the ``focal_plane`` dataset. This can be done like so: This will give you a dict of ``Receiver`` dataclasses with all the focal plane data. The keys of this dict are the start times for combined focal planes and the ``obs_id`` for per-obs. +solve_pointing_model +-------------------- + +This script solves for the pointing model parameters using moon observations. +The inputs are the the el_center, roll_center, and the UFM +center locations as fit by finalize_focal_plane, +per each moon observation. +The fitter uses lmfit with a Nelder-Mead minimization routine to minimize +the distance between modeled data points and the reference data points. +By default, the measured UFM centers are the reference points, +and the quaternion rotations of the pointing model are applied to the nominal, template, UFM center locations. +However, the model can be applied in reverse, with the template positions as reference -- some diagnostic plots are in this space, as it makes it easier to view residuals from multiple boresight orientations at once. +See the ``xieta_model`` parameter comments for more details. + +``solve_pointing_model`` can be iterated once after the first parameter fit. +Specifying ``iterate_cutoff`` in arcmin will exlude outliers from next round of fitting. + +.. automodule:: sotodlib.site_pipeline.solve_pointing_model + :members: + :undoc-members: + +Config file format +`````````````````` + +Here is an annotated basic configuration file. +The first block are mandatory entries. The second block are optional. + +.. code-block:: yaml + + # Mandatory to include in config file + + # Specify platform for the code to run on. (satp1, satp3 are supported) + platform: satp1 + # pm_version tells coords.pointing_model which pointing model to use. + # It determines the quaternion model. Don't change this. + pm_version: sat_v1 + # Tag for metadata versioning, will appended to output directory + solution_version_tag: YYMMDDr + # Output directory to save results in. + # A sub directory in {outdir} will be created as + #{platform}_pointing_model_{solution_version_tag}_{xieta_model}_{add_tag} + outdir: /your/save/directory + # Load data and reference focal plane templates + # ffp_path must be common mode subtracted version of focal_plane + ffp_path: "/path/to/centered/focal_plane/metadata/focal_plane_cmsub.h5" + # per_obs_fps are multiple per-observation focal_plane + # fits saved into one h5 file. These are fitted to moon measurements. + # only data from UFMs that had good detector fits are included. + per_obs_fps: /path/to/per-obs/finalize/focal/plane/results/per_obs/focal_plane.h5 + # The provided context file is used to load boresight/elevation data from + # obs_ids included in per_obs_fps + context: + path: "/so/metadata/satp1/contexts/nominal/focal_plane.h5" + # List of ufms in order of wafer slot, not currently future + # proof when new ufms are swapped in. + # This assists unpacking per_obs_fps with its sparse UFM info. + ufms: ['ufm_mv19', 'ufm_mv18', 'ufm_mv22', 'ufm_mv29', + 'ufm_mv7', 'ufm_mv9', 'ufm_mv15'] #satp1 + # ufms: ['ufm_mv5', 'ufm_mv27', 'ufm_mv35', 'ufm_mv12', + # 'ufm_mv23', 'ufm_mv33', 'ufm_mv17'] #satp3 + + # Optional configuration parameters + + # parameters included here will be fixed in the minimization. + # See comments for which to fix for different platforms. + fixed_params: + - az_rot #all + - base_tilt_cos #all + - base_tilt_sin #all + - fp_rot_eta0 #all + - fp_offset_eta0 #all + - fp_rot_xi0 #satp3 only + # "xieta_model" decides which parameter space the fitting occurs in. + # "measured": The fitter applies pointing model to template UFM xi-eta + # locations based on El and Roll of the obs, to get the modeled + # xi-etas to match the measured data points. + # Modeled data points get spread out based on boresight. + # "template": The fitter applies pointing model "backwards" on measured + # xieta data points to match them to template locations. + # The modeled data points cluster around + # the nominal template locations. + # Each method gives slightly different results. "measured" is default. + xieta_model: measured + # Define a weight cutoff for fitting routine. + weight_cutoff: 0.2 + # Cut out any known bad observations. + skip_tags: + - "_1713" #bad timing satp1 + - "1716423951" #Just a very bad fit satp1 + # Option to iterate parameter fitting. If not None, data points with + # fit residuals higher than cutoff will be excluded from second round of fits. + iterate_cutoff: None # or arcmin + # Make diagnostic plots. + make_plots: True + # any additional tag to append on results directory + append: "" + save_output: True + + +Output file format +`````````````````` + +The inputs and outputs ``solve_pointing_model`` are stored as an AxisManager, before saving to an .h5 file. +Only the pointing model parameters + version are saved to the ManifestdB ``db.sqlite``. + +.. code-block:: text + + - ancil (aman) + - az_enc (num_obs * 7) + - boresight_enc (num_obs * 7) + - el_enc (num_obs * 7) + - ffp_ufm_center_fits ((xi, eta, gamma), num_obs * 7) #This where the info from per_obs_fps gets stored + - nom_ufm_centers ((xi, eta, gamma), num_obs * 7) #This is where info from cmsub focal_plane goes. + - obs_info (aman) + - obs_ids (num_obs) + - roll_c (num_obs * 7) + - weights (num_obs * 7) + - model_fits (aman) + - eta (num_obs * 7) + - xi (num_obs * 7) + - pointing_model (aman) + - pm_version + - parameters by name + #- parameter_fit_stats #Not yet implemented in output, but visible in log file. + # - name + # - value + # - vary + # - min + # - max + # - stderr + # - correl #correlation with other fit params + #- excluded (Data points) + + preprocess-tod -------------- This script is set up to run a preprocessing pipeline using the preprocess diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 2974ba572..516e2f8bf 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -1,22 +1,188 @@ +""" +New Focal Plane contianers. +Supports transparent applications of all transforms including pointing model. +Calculated transforms can either be treated at properties for ease of +calculations or as static attributes for loading saved results. +""" + +# TODO: Reprs + +from __future__ import annotations + import logging import os -from dataclasses import InitVar, dataclass, field -from functools import cached_property, partial -from typing import Dict, List, Optional +from argparse import Namespace +from concurrent.futures import Executor +from copy import deepcopy +from dataclasses import dataclass, field +from functools import cached_property, reduce +from typing import ( + Any, + ClassVar, + Generic, + Iterable, + Literal, + Optional, + Self, + TypeVar, + cast, + overload, +) import h5py -import matplotlib.pyplot as plt import megham.transform as mt import megham.utils as mu import numpy as np -from numpy.typing import NDArray -from scipy.stats import binned_statistic -from sotodlib.coords import optics as op -from sotodlib.core import metadata -from sotodlib.io.metadata import read_dataset, write_dataset - -logger = logging.getLogger("finalize_focal_plane") -plt.style.use("tableau-colorblind10") +from jaxtyping import Bool, Float, Integer, Shaped +from scipy.cluster import vq +from scipy.optimize import minimize +from so3g.proj import quat +from sotodlib.coords.pointing_model import apply_pointing_model, param_defaults +from sotodlib.core import AxisManager, IndexAxis, metadata +from sotodlib.core.metadata import ManifestDb, MetadataSpec +from sotodlib.io.metadata import SuperLoader, read_dataset, write_dataset +from sotodlib.utils import epochs + +_COORDSYS_COLUMNS = { + "xieta": ("xi", "eta", "gamma"), + "horizon": ("az", "el", "roll"), + "fp": ("x_fp", "y_fp", "pol_fp"), + "ot": ("x_ot", "y_ot", "pol_ot"), +} + +logger = logging.getLogger("solve_static_pointing") + +T = TypeVar("T") + + +def make_manifestdb(system: PointingSystem, field: str, db_path: str, h5_path: str): + """ + Create a ManifestDB mapping `(obs:timestamp, array) -> template dataset` + for all templates contained in a PointingSystem. + Note that if an existing db is on disk this will delete it + + Parameters + ---------- + system : PointingSystem + System containing template focal planes. + field : str + The field within each saved `FocalPlaneCollection` to point to. + db_path : str + Output sqlite database path. + h5_path : str + HDF5 file containing the saved templates. + """ + if os.path.isfile(db_path): + os.remove(db_path) + scheme = metadata.ManifestScheme() + scheme.add_range_match("obs:timestamp") + scheme.add_exact_match("array") + scheme.add_data_field("dataset") + mdb = metadata.ManifestDb(scheme=scheme) + mdb.to_file(db_path) + mdb = metadata.ManifestDb(db_path) + h5_rel = os.path.relpath( + os.path.abspath(h5_path), os.path.dirname(os.path.abspath(db_path)) + ) + epoch_dict = {ep.name: ep for ep in system.era.epochs} + seen = set() + for rx_idx, rx in enumerate(system.receivers): + for epoch_name in rx.epoch.split("+"): + epoch = epoch_dict[epoch_name] + for cover in epoch.covers: + for ot in rx.optics_tubes: + for wafer_slot, fp in zip( + ot.wafer_slots, + ot.focal_planes, + ): + dataset = ( + f"/receivers/" + f"{rx_idx}_{rx.name}_{rx.epoch}/" + f"{ot.name}/" + f"{wafer_slot}-{fp.name}/" + f"{field}" + ) + + key = ( + cover.start, + cover.stop, + fp.name, + ) + if key in seen: + raise ValueError( + f"Duplicate entry for array={fp.name} and range=({cover.start}, {cover.stop})" + ) + seen.add(key) + mdb.add_entry( + { + "obs:timestamp": (cover.start, cover.stop), + "array": fp.name, + "dataset": dataset, + }, + filename=h5_rel, + ) + + +def make_per_obs_manifestdb( + system: PointingSystem, field: str, db_path: str, h5_path: str +): + """ + Create a ManifestDB mapping `(obs:obs_id, array) -> dataset` + for a field stored on each FocalPlane measurement. + + Parameters + ---------- + system : PointingSystem + System containing per-observation measurements. + field : str + Field within each saved FocalPlane measurement to point to. + db_path : str + Output sqlite database path. + h5_path : str + HDF5 file containing the saved system. + """ + if os.path.isfile(db_path): + os.remove(db_path) + scheme = metadata.ManifestScheme() + scheme.add_exact_match("obs:obs_id") + scheme.add_exact_match("array") + scheme.add_data_field("dataset") + mdb = metadata.ManifestDb(scheme=scheme) + mdb.to_file(db_path) + mdb = metadata.ManifestDb(db_path) + h5_rel = os.path.relpath( + os.path.abspath(h5_path), os.path.dirname(os.path.abspath(db_path)) + ) + seen = set() + for rx_idx, rx in enumerate(system.receivers): + for ot in rx.optics_tubes: + for wafer_slot, fp in zip(ot.wafer_slots, ot.focal_planes): + for meas_idx, meas in enumerate(fp.focal_planes): + dataset = ( + f"/receivers/" + f"{rx_idx}_{rx.name}_{rx.epoch}/" + f"{ot.name}/" + f"{wafer_slot}-{fp.name}/" + f"focal_planes/" + f"{meas_idx}_{meas.meas_id}/" + f"{field}" + ) + + key = (meas.meas_id, fp.name) + + if key in seen: + raise ValueError( + f"Duplicate entry for obs_id={meas.meas_id}, array={fp.name}" + ) + seen.add(key) + mdb.add_entry( + { + "obs:obs_id": meas.meas_id, + "array": fp.name, + "dataset": dataset, + }, + filename=h5_rel, + ) def _add_attrs(dset, attrs): @@ -27,16 +193,862 @@ def _add_attrs(dset, attrs): dset.attrs[k] = v +def _create_group(f, path, overwrite=True) -> h5py.Group: + if path in f: + if path == "/": + return f[path] + if not overwrite: + raise ValueError(f"HDF5 path already exists: {path}") + del f[path] + return f.create_group(path) + + +def gamma_fit(src, dst): + """ + Fit the transformation for gamma. + Note that the periodicity here assumes things are in radians. + + Arguments: + + src: Source gamma in radians + + dst: Destination gamma in radians + + Returns: + + scale: Scale applied to src + + shift: Shift applied to scale*src + """ + + def _gamma_min(pars, src, dst): + scale, shift = pars + transformed = np.sin(src * scale + shift) + diff = np.sin(dst) - transformed + + return np.sqrt(np.mean(diff**2)) + + res = minimize(_gamma_min, (1.0, 0.0), (src, dst)) + return res.x + + +def _transformed( + self: FocalPlane | FocalPlaneCollection, attr_name: str, transform: Transform +): + to_ret = deepcopy(self.template) + to_ret.xyz = mt.apply_transform( + self.template.xyz, transform.affine, transform.shift + ) + to_ret.center = None + if self.template.center is not None: + to_ret.center = mt.apply_transform( + np.atleast_2d(self.template.center), transform.affine, transform.shift + ).ravel() + if self.autofreeze: + setattr(self, attr_name, to_ret) + return to_ret + + +def _get_aff( + self: FocalPlane | FocalPlaneCollection, + data_name: str, + template_name: str, + weights_name: str, + attr_name: str, + apply_wmsk: bool = True, +): + to_ret = Transform.identity() + wmsk = self.wmsk + if np.sum(wmsk) < 4: + return to_ret + if apply_wmsk: + msk = wmsk + else: + msk = slice(None) + affine, shift = mt.get_affine_two_stage( + getattr(self, template_name).xyz[msk, :2], + getattr(self, data_name).xyz[msk, :2], + getattr(self, weights_name)[msk], + ) + to_ret.shift[:2] = shift + to_ret.affine[:2, :2] = affine + if not self.fake_gamma: + to_ret.affine[-1, -1], to_ret.shift[-1] = gamma_fit( + getattr(self, template_name).xyz[msk, 2], + getattr(self, data_name).xyz[msk, 2], + ) + if self.autofreeze: + setattr(self, attr_name, to_ret) + return to_ret + + +def setup_fit_params( + system: PointingSystem, cfg: Namespace, old_system: Optional[PointingSystem] +) -> tuple[np.ndarray, list[tuple[float, float]], np.ndarray]: + """ + Set up fit parameters, including nuisance parameters. + + Parameters + ---------- + system : PointingSystem + Pointing system containing the non-nuisance parameters. + cfg : Namespace + Configuration containing parameter initial values, bounds and static flags. + old_system : Optional[PointingSystem] + If not `None` then initial static and nuisance params/transforms + will be pulled from this depending on if `cfg.pars_from_old`, + `cfg.nuisance_from_old`, and `cfg.nuisance_transform_from_old` are True. + For static params this can be overwridden by setting `overwrite_old = True` + in the parameter config dict. + + Returns + ------- + params : np.ndarray + Initial fit parameter values, including nuisance parameters. + bounds : list[tuple[float, float]] + Parameter bounds, including nuisance parameter bounds. + scales : np.ndarray + Parameter scales, including nuisance parameter scales. + """ + old_names = [] + if old_system is not None: + old_names = old_system.parameter_names + + # Setup non-nuisance fit parameters + params = system.parameters.copy() + bounds = [(-np.inf, np.inf)] * len(params) + scales = np.ones(len(params)) + + for name, par in cfg.parameters.items(): + if name not in system.parameter_names: + logger.warning("Unknown parameter %s", name) + continue + idx = system.parameter_names.index(name) + params[idx] = float(par.get("init", params[idx])) + if par.get("static", False): + bounds[idx] = (params[idx], params[idx]) + continue + bounds[idx] = tuple(float(b) for b in par.get("bounds", bounds[idx]))[:2] # type: ignore + lo, hi = bounds[idx] + if np.isfinite(lo) and np.isfinite(hi) and hi > lo: + scales[idx] = hi - lo + if ( + cfg.pars_from_old + and not par.get("overwrite_old", False) + and name in old_names + and old_system is not None + ): + par[idx] = old_system.parameters[old_names.index(name)] + + # Setup nuisance fit parameters + nn = len(system.nuisance_params.params_flat) + nuisance_values = np.zeros(nn) + nuisance_bounds = [(-np.inf, np.inf) for _ in range(nn)] + nuisance_scales = np.ones(nn) + for meas_id, nidx in system.nuisance_params.obs_mapping.items(): + if old_system is not None and meas_id in old_system.nuisance_params.obs_mapping: + oidx = old_system.nuisance_params.obs_mapping[meas_id] + if cfg.nuisance_from_old: + system.nuisance_params.par_list[nidx] = ( + old_system.nuisance_params.par_list[oidx] + ) + if cfg.nuisance_transform_from_old: + system.nuisance_params.transform_list[nidx] = ( + old_system.nuisance_params.transform_list[oidx] + ) + par_dict = system.nuisance_params.par_list[nidx] + for name, value in par_dict.items(): + if name not in system.parameter_names: + logger.warning( + "No equivalent non-nuisance parameter found for nuisance parameter %s", + name, + ) + nuisance_values[nidx] = value + nuisance_bounds[nidx] = (-np.inf, np.inf) + nuisance_scales[nidx] = 1.0 + continue + idx = system.parameter_names.index(name) + nuisance_values[nidx] = value + lo, hi = bounds[idx] + nuisance_bounds[nidx] = ( + value - (value - lo) / cfg.nuisance_scale, + value + (hi - value) / cfg.nuisance_scale, + ) + nuisance_scales[nidx] = scales[idx] + + # Append nuisance parameters + params = np.concatenate([params, np.asarray(nuisance_values)]) + bounds.extend(nuisance_bounds) + scales = np.concatenate([scales, np.asarray(nuisance_scales)]) + + system.update_parameters(params) + + return params, bounds, scales + + +def _get_pm(meas): + return meas._pm_data_dyn + + +class StaticOrCached(Generic[T]): + """ + Wrapper that will get either: + + 1. precomputed static attribute: `_{name}_stat` + 2. dynamic property computation: `_{name}_dyn` + + dependint on if `static` is true or false. + """ + + def __init__(self, name: str): + self.name = name + + def __set_name__(self, owner, attr_name): + self.attr_name = attr_name + + @overload + def __get__(self, obj: None, owner: type) -> "StaticOrCached[T]": ... + + @overload + def __get__(self, obj: Any, owner: type | None = None) -> T: ... + + def __get__(self, obj: Any, owner: type | None = None) -> T | "StaticOrCached[T]": + if obj is None: + return self + + if obj.static: + if f"_{self.name}_stat" in obj.__dict__: + res = getattr(obj, f"_{self.name}_stat") + if res is not None: + return res + res = getattr(obj, f"_{self.name}_dyn") + setattr(obj, f"_{self.name}_stat", res) + return res + return getattr(obj, f"_{self.name}_dyn") + + @dataclass -class Transform: - shift: NDArray[np.floating] # (ndim,) - affine: NDArray[np.floating] # (ndim, ndim) - scale: NDArray[np.floating] = field(init=False) # (ndim,) - shear: float = field(init=False) - rot: float = field(init=False) +class NuisanceParams: + """ + Map and store of per observation nuisance parameters and transforms. + Can be indexed directly by `obs_id`. + + Attributes + ---------- + obs_mapping : dict[str, int] + Mapping from `obs_ids` to the matching + element in `par_list`. + par_list : list[dict[str, float]] + Each row is a set of nuicance params + for one observation, but `obs_mapping` + can map multiple `obs_id`s to one row here + to account for LAT OTs having seperate `obs_id`s. + transform_list : list[Transform] + Each element is a nuisance transform that can be applied when computing `pm_data`. + In the same order as par_list. + params_flat : Float[np.ndarray, "npar"] + (Property) Flattened array of all nuisance parameter values, concatenated + in `par_list` order and preserving the insertion order of each dictionary. + """ + + obs_mapping: dict[str, int] + par_list: list[dict[str, float]] + transform_list: list[Transform] + + def __getitem__(self, key) -> tuple[dict[str, float], Transform]: + if key not in self.obs_mapping: + return {}, Transform.identity() + idx = self.obs_mapping[key] + return self.par_list[idx], self.transform_list[idx] - def __post_init__(self): - self.decompose() + @property + def params_flat(self) -> Float[np.ndarray, "npar"]: + return np.array( + [value for par_dict in self.par_list for value in par_dict.values()], + dtype=float, + ) + + def update(self, params: Float[np.ndarray, "npar"]): + """ + Update nuisance parameters from a flattened parameter array. + + Parameters + ---------- + params : Float[np.ndarray, "npar"] + Flattened nuisance parameter values, ordered according to + `par_list` and the insertion order of each dictionary. + """ + idx = 0 + for par_dict in self.par_list: + for name in par_dict: + par_dict[name] = float(params[idx]) + idx += 1 + + def mean_zero(self, system: PointingSystem): + """ + Make all nuisance parameter distributions mean zero by + subtracting the mean from the nuisance parameters and adding + it to the corresponding static parameter. + + Parameters + system : PointingSystem + Pointing system whose pointing models will be modified. + """ + pm_mapping = {pm.epoch: [] for pm in system.pointing_models} + for rx in system.receivers: + for ot in rx.optics_tubes: + for fp in ot.focal_planes: + for meas in fp.focal_planes: + pm_mapping[meas.pointing_model.epoch] += [ + self.obs_mapping[meas.meas_id] + ] + + for pm in system.pointing_models: + pm_map = pm_mapping[pm.epoch] + pm_pars = dict( + zip( + self.par_list[0].keys(), + zip(*[self.par_list[m].values() for m in pm_map]), + ) + ) + for key, val in pm_pars.items(): + if key not in pm.parameters: + continue + avg = np.mean(val) + pm.parameters[key] += avg + for idx in np.unique(pm_map): + self.par_list[idx][key] -= avg + + @classmethod + def from_system( + cls, system: PointingSystem, nuisance_pars: dict[str, float], threshold: float + ) -> NuisanceParams: + """ + Construct nuisance parameters and transforms from a pointing system. + + Observations are grouped into epochs using their meas_ids + and timestamps. Each epoch is assigned a copy of `nuisance_pars` + and an identity transform. Multiple observation IDs belonging + to the same epoch map to the same nuisance parameter set. + + Parameters + ---------- + system : PointingSystem + Pointing system from which to collect obs_ids. + nuisance_pars : dict[str, float] + Initial nuisance parameter values assigned to each epoch. + threshold : float + Threshold passed to `epochs.group_obs` when grouping + observations into epochs. + + Returns + ------- + NuisanceParams + Nuisance parameter mapping, parameter sets, and identity + transforms corresponding to the observation epochs. + """ + obs_ids = [] + timestamps = [] + for rx in system.receivers: + for ot in rx.optics_tubes: + for fp in ot.focal_planes: + for meas in fp.focal_planes: + obs_ids += [meas.meas_id] + timestamps += [float(meas.meas_id.split("_")[1])] + obs_ids_split, _ = epochs.group_obs( + np.asarray(obs_ids), np.asarray(timestamps), threshold + ) + obs_mapping = {} + for i, obs_list in enumerate(obs_ids_split): + obs_mapping.update({obs_id: i for obs_id in obs_list}) + par_list = [nuisance_pars.copy() for _ in range(len(obs_ids_split))] + transform_list = [Transform.identity() for _ in range(len(obs_ids_split))] + return cls(obs_mapping, par_list, transform_list) + + @property + def rev_mapping(self): + rev_mapping = [[] for _ in range(len(self.transform_list))] + for meas_id, idx in self.obs_mapping.items(): + rev_mapping[idx] += [meas_id] + return rev_mapping + + def compute_transforms(self, system: PointingSystem): + r""" + Take in a system after a round of fitting and compute the nuisance transforms needed + to make a clean focal plane. If there are existing nuisance transforms we assume that + they were used to compute the current `pm_data` values and will be included in the net transform. + + We want to compute the transforms that reduce the obs-obs variance on `pm_data` without changing + the average boresight pointing. To start lets assume we have `pm_data` and `pm_transform` for each `FocalPlane` + and `cm_transform` for each `Receiver`. This we then compute `obs_transform` which is the common mode of `pm_transform` + for all `FocalPlane`s in a given observation. + The transform that then lines up `pm_data` along obs (relative to the boresight) is: + + $$ + T_{\mathrm{nuisance}} = \left(T_{\mathrm{obs}} \circ T_{\mathrm{cm}}^{-1}\right)^{-1} + $$ + + if we have some existing `nuisance_transform` then it was already included in + + $$ + \texttt{pm\_data} = T_{\mathrm{nuisance,old}}(\texttt{pointing\_model(data)}) + $$ + + so the new nuisance transform should chain them as + + $$ + T_{\mathrm{nuisance}} = T_{\mathrm{nuisance,new}} \circ T_{\mathrm{nuisance,old}} + $$ + + giving us: + + $$ + \begin{aligned} + \texttt{pm\_data} + &= T_{\mathrm{nuisance}}(\texttt{pointing\_model(data)}) \\ + &= (T_{\mathrm{nuisance,new}} \circ T_{\mathrm{nuisance,old}}) + (\texttt{pointing\_model(data)}) \\ + &= T_{\mathrm{nuisance,new}}(\texttt{pm\_data\_old}) + \end{aligned} + $$ + + This function does assume that all `FocalPlane`s in an obs are in the same `Receiver`. + If this is not true you set up some config wrong and should figure it out. + + Parameters + ---------- + system : PointingSystem + System after a round of fitting, containing the focal plane pointing + transforms (`pm_transform`) and receiver common-mode transforms + (`cm_transform`). + + + Raises + ------ + ValueError + If there are obs split across multiple receivers or the total + number of focal planes in the system does not match the mapping. + """ + rev_mapping = self.rev_mapping + done_idx = set() + for rx in system.receivers: + rx_aff_inv, rx_sft_inv = mt.invert_transform( + rx.cm_transform.affine, rx.cm_transform.shift + ) + affs = {} + sfts = {} + rx_ids = [] + for ot in rx.optics_tubes: + for fp in ot.focal_planes: + for meas in fp.focal_planes: + affs[meas.meas_id] = meas.pm_transform.affine + sfts[meas.meas_id] = meas.pm_transform.shift + rx_ids += [meas.meas_id] + rx_ids = np.array(rx_ids) + for i, meas_ids in enumerate(rev_mapping): + if i in done_idx: + continue + inrx = np.isin(meas_ids, rx_ids) + if not np.all(inrx): + if np.any(inrx): + raise ValueError( + f"Somehow obs_ids {meas_ids} are not all in the same Receiver!" + ) + continue + cm_aff, cm_shift = mt.get_common_mode( + [affs[mid] for mid in meas_ids], + [sfts[mid] for mid in meas_ids], + -2, + True, + fast=False, # True, + ) + n_aff, n_sft = mt.invert_transform( # cm_aff, cm_shift) + *mt.compose_transform(rx_aff_inv, rx_sft_inv, cm_aff, cm_shift) + ) + trf_old = self.transform_list[i] + n_aff, n_sft = mt.compose_transform( + trf_old.affine, trf_old.shift, n_aff, n_sft + ) + self.transform_list[i] = Transform(n_sft, n_aff) + done_idx.add(i) + if len(done_idx) != len(self.transform_list): + raise ValueError("Not all obs were completed! Check your receiver objects!") + + def save(self, f: h5py.File, path: str, overwrite: bool = True): + """ + Save the nuisance params to an HDF5 file. + + Parameters + ---------- + f : h5py.File + HDF5 file object to save to. + path : str + Path within the HDF5 file at which to save the pointing model. + overwrite : bool + If True, overwrite an existing pointing model at `path`. + """ + obs_ids = np.array(list(self.obs_mapping.keys())) + par_idx = np.array(list(self.obs_mapping.values())) + dtype = [("obs:obs_id", obs_ids.dtype), ("par_idx", par_idx.dtype)] + data = np.empty(len(obs_ids), dtype=dtype) + data["obs:obs_id"] = obs_ids + data["par_idx"] = par_idx + write_dataset( + metadata.ResultSet.from_friend(data), + f, + os.path.join(path, "obs_mapping"), + overwrite=overwrite, + ) + + npar = len(self.par_list[0]) if self.par_list else 0 + par_idx = np.repeat(np.arange(len(self.par_list)), npar) + par_name = np.array([name for pars in self.par_list for name in pars.keys()]) + par_value = np.array( + [value for pars in self.par_list for value in pars.values()] + ) + dtype = [ + ("par_idx", par_idx.dtype), + ("par_name", par_name.dtype), + ("par_value", par_value.dtype), + ] + data = np.empty(len(par_idx), dtype=dtype) + data["par_idx"] = par_idx + data["par_name"] = par_name + data["par_value"] = par_value + write_dataset( + metadata.ResultSet.from_friend(data), + f, + os.path.join(path, "par_list"), + overwrite=overwrite, + ) + + _ = _create_group(f, os.path.join(path, "transform_list"), overwrite) + for i, trf in enumerate(self.transform_list): + trf.save(f, os.path.join(path, "transform_list", f"{i}"), overwrite) + + @classmethod + def load(cls, f: h5py.File, path: str) -> Self: + """ + Load nuisance parameters from an HDF5 file. + + Parameters + ---------- + f : h5py.File + HDF5 file object containing the nuisance parameters. + path : str + Path within the HDF5 file from which to load the nuisance parameters. + + Returns + ------- + NuisanceParams + The loaded nuisance params. + """ + data = read_dataset(f, os.path.join(path, "obs_mapping")).asarray() + obs_mapping: dict[str, int] = { + str(row["obs:obs_id"]): int(row["par_idx"]) for row in data + } + + data = read_dataset(f, os.path.join(path, "par_list")).asarray() + npar = int(np.max(data["par_idx"])) + 1 if len(data) else 0 + par_list: list[dict[str, float]] = [{} for _ in range(npar)] + for row in data: + name = row["par_name"] + par_list[int(row["par_idx"])][str(name)] = float(row["par_value"]) + + if os.path.join(path, "transform_list") in f: + transform_list = [ + Transform.load(f, os.path.join(path, "transform_list", f"{i}")) + for i in range(len(par_list)) + ] + else: + transform_list = [Transform.identity() for _ in range(len(par_list))] + + return cls(obs_mapping, par_list, transform_list) + + +@dataclass +class PointingModel: + """ + Wrapper around a telescope pointing model and its application to + detector offsets. In the future this should also be able to handle + measurements from things like the starcamera. + + Attributes + ---------- + epoch : str + Human-readable identifier for the epoch associated with this + data. If this spans multiple epochs they will be seperated with a '+'. + parameters : dict + Dictionary of pointing-model parameters accepted by + `apply_pointing_model`. An empty dictionary corresponds to an + identity pointing model and leaves detector offsets unchanged. + force_zero_roll : bool + If True, ignore the encoder roll angle when applying the pointing + model and assume a zero-roll boresight solution. + pad : bool, default: False + If True, this model is excluded from fitting. + """ + + epoch: str + parameters: dict + nuisance_params: NuisanceParams + force_zero_roll: bool + pad: bool = False + + def apply_det( + self, + meas: FocalPlane, + tol: float = 2.42e-6, + max_iter: int = 5, + ) -> DetectorOffsets: + """ + Apply the inverse pointing model correction to a set of detector offsets. + + The correction is computed from the supplied encoder values using + `apply_pointing_model` and then propagated to each detector through + quaternion rotations. The returned detector offsets remain in the + `xieta` coordinate system but have the pointing model corrections removed. + + Focal plane distortions are removed iteratively by applying the + forward pointing model, estimating the resulting distortion, and + subtracting it from the detector offsets until convergence. + + Nuisance parameters associated with the measurement are added to + the pointing model parameters before computing the correction. + The nuisance transform is applied to the detector offsets before returning. + + If the pointing model contains no parameters, or if no detectors + are available for the inversion, the input detector offsets are + returned unchanged. + + When `self.force_zero_roll=True`, the encoder roll angle is ignored + during the correction and a zero-roll boresight solution is assumed. + + When `meas.fake_gamma=True`, detector polarization angles are ignored + and only detector positions (`xi`, `eta`) are propagated during the + iterative inversion. The returned detector offsets still contain + all three coordinates. + + Parameters + ---------- + meas : FocalPlane + Focal plane measurement containing detector offsets, encoder + values, detector weights, and associated metadata. Only + detectors selected by `meas.wmsk` are included in the inversion. + tol : float, default: 2.42e-6 + RMS convergence tolerance for the iterative distortion removal, + in radians. + max_iter : int, default: 5 + Maximum number of iterations for the distortion removal. + + Returns + ------- + DetectorOffsets + A copy of `meas.data` with the pointing-model correction removed. + The returned object has the same metadata and detector ordering + as the input but contains corrected detector coordinates. + + Raises + ------ + RuntimeError + If the iterative distortion removal does not converge within + `max_iter` iterations. + """ + to_ret = deepcopy(meas.data) + if len(self.parameters) == 0: + return to_ret + + # Apply nuisance + params_use = deepcopy(self.parameters) + npars, ntrf = self.nuisance_params[meas.meas_id] + for key, val in npars.items(): + params_use[key] += val + + # Start with the input detector coordinates + if not np.any(meas.wmsk): + return to_ret + estimate = meas.data_msk.xyz.copy() + if meas.fake_gamma: + estimate = estimate[:, :2] + fp_target = meas.data_msk + fp = meas.data_msk.fp + det_enc_msk = meas.enc_msk + ancil = det_enc_msk.ancil + if self.force_zero_roll: + q_enc = det_enc_msk.q_enc_zero_roll + else: + q_enc = det_enc_msk.q_enc + + err = np.inf + prev_err = np.inf + alpha = 1.0 + prev_distortion = np.zeros_like(estimate) + + for _ in range(max_iter): + fp.xi = estimate[:, 0] + fp.eta = estimate[:, 1] + + if meas.fake_gamma: + q_fp = quat.rotation_xieta(estimate[:, 0], estimate[:, 1]) + else: + fp.gamma = estimate[:, 2] + q_fp = quat.rotation_xieta( + estimate[:, 0], estimate[:, 1], estimate[:, 2] # type: ignore + ) + + bs, fp_corrected = apply_pointing_model(None, params_use, ancil, fp) + bs = cast(AxisManager, bs) + + xi, eta, gamma = quat.decompose_xieta( + ~quat.euler(2, bs.roll) + * ~quat.rotation_lonlat(-1 * np.asarray(bs.az), bs.el) + * q_enc + * q_fp + ) + + if fp_corrected is None: + to_ret.xyz[meas.wmsk] = np.column_stack((xi, eta, gamma)) + to_ret.xyz = mt.apply_transform(to_ret.xyz, ntrf.affine, ntrf.shift) + return to_ret + + if meas.fake_gamma: + dx = fp_corrected.xi - fp.xi + dy = fp_corrected.eta - fp.eta + + distortion = np.column_stack((dx, dy)) + resid = np.column_stack( + ( + fp_corrected.xi - fp_target.xi, + fp_corrected.eta - fp_target.eta, + ) + ) + else: + dx = fp_corrected.xi - fp.xi + dy = fp_corrected.eta - fp.eta + dg = fp_corrected.gamma - fp.gamma + + distortion = np.column_stack((dx, dy, dg)) + resid = np.column_stack( + ( + fp_corrected.xi - fp_target.xi, + fp_corrected.eta - fp_target.eta, + fp_corrected.gamma - fp_target.gamma, + ) + ) + + err = np.sqrt(np.nanmean(np.sum(resid * resid, axis=1))) + + if err > prev_err: + alpha *= 0.5 + distortion = prev_distortion + else: + alpha = min(1.0, alpha * 1.2) + prev_distortion = distortion.copy() + prev_err = err + + if err < tol: + to_ret.xyz[meas.wmsk] = np.column_stack((xi, eta, gamma)) + to_ret.xyz = mt.apply_transform(to_ret.xyz, ntrf.affine, ntrf.shift) + return to_ret + + estimate -= alpha * distortion + + raise RuntimeError( + f"Pointing-model inversion did not converge after {max_iter} iterations (error={err:.3e} rad)." + ) + + def save(self, f: h5py.File, path: str, overwrite: bool = True): + """ + Save the pointing model to an HDF5 file. + + Parameters + ---------- + f : h5py.File + HDF5 file object to save to. + path : str + Path within the HDF5 file at which to save the pointing model. + overwrite : bool + If True, overwrite an existing pointing model at `path`. + """ + group = _create_group(f, path, overwrite) + _add_attrs( + group, + { + "epoch": self.epoch, + "force_zero_roll": self.force_zero_roll, + "pad": self.pad, + }, + ) + + parameters = AxisManager() + for name, value in self.parameters.items(): + parameters.wrap(name, value) + parameters.save(f, f"{path}/parameters") + + @classmethod + def load(cls, f: h5py.File, path: str, nuisance_params: NuisanceParams) -> Self: + """ + Load a pointing model from an HDF5 file. + + Parameters + ---------- + f : h5py.File + HDF5 file object containing the pointing model. + path : str + Path within the HDF5 file from which to load the pointing model. + nuisance_params : NuisanceParams + Nuisance parameters and transforms to associate with the + loaded pointing model. + + Returns + ------- + PointingModel + The loaded pointing model. + """ + group = cast(h5py.Group, f[path]) + parameters = AxisManager.load(group["parameters"]) + parameters = {name: parameters[name] for name in parameters._fields} + + return cls( + epoch=cast(str, group.attrs["epoch"]), + parameters=parameters, + nuisance_params=nuisance_params, + force_zero_roll=cast(bool, group.attrs["force_zero_roll"]), + pad=cast(bool, group.attrs.get("pad", False)), + ) + + +@dataclass +class Transform: + """ + Class to hold and decompose an affine transform. + + Attributes + ---------- + shift : Float[np.ndarray, "ndim"] + The shift to apply as part of the transform + affine : Float[np.ndarray, "ndim ndim"] + The affine transformation matrix. + scale : Float[np.ndarray, "ndim"] + (Property) The scale along each axis. + shear : float + (Property) The shear parameter of the `xieta` portion of the + affine transformation. + rot : float + (Property) The rotation angle of the `xieta` plane. + decompose : tuple[Float[np.ndarray, "ndim"], float, float] + (Cached property) Decomposition of the affine transformation + into scale, shear, and rotation. Cache is cleared if `shift` + or `affine` is cleared. + """ + + shift: Float[np.ndarray, "ndim"] + affine: Float[np.ndarray, "ndim ndim"] + + def __setattr__(self, name: str, value: Any, /) -> None: + if name in ("shift", "affine"): + self.__dict__.pop("decompose", None) + return super().__setattr__(name, value) @classmethod def identity(cls): @@ -50,818 +1062,2599 @@ def from_split(cls, shift, xieta_affine, gamma_scale): return Transform(shift, affine) - def decompose(self): + @cached_property + def decompose(self) -> tuple[Float[np.ndarray, "ndim"], float, float]: + """ + Decompose into scale, shear, and rotation matrices. + + Returns + ------- + scale : Float["ndim"] + The scale in each axis. + shear : float + The shear parameter of only the xieta portion. + rot : float + The rotation of the xieta plane. + """ xieta_affine = self.affine[:2, :2] gamma_scale = self.affine[-1, -1] scale, shear, rot = mt.decompose_affine(xieta_affine) - self.scale = np.array((*scale, gamma_scale)) - self.shear = shear.item() - self.rot = mt.decompose_rotation(rot)[-1] + scale = np.array((*scale, gamma_scale)) + shear = shear.item() + rot = mt.decompose_rotation(rot)[-1] - def save(self, f, path, append=""): - if path not in f: - f.create_group(path) - _add_attrs( - f[path], - { - f"shift{append}": self.shift, - f"scale{append}": self.scale, - f"shear{append}": self.shear, - f"rot{append}": self.rot, - f"affine{append}": self.affine, - }, - ) + return scale, shear, rot - @classmethod - def load(cls, group, append=""): - shift = group.attrs[f"shift{append}"] - affine = group.attrs[f"affine{append}"] + @property + def scale(self): + return self.decompose[0] - return Transform(shift, affine) + @property + def shear(self): + return self.decompose[1] + @property + def rot(self): + return self.decompose[2] + + def save(self, f: h5py.File, path: str, overwrite: bool = True): + """ + Save the transform to an HDF5 group. + + Parameters + ---------- + f : h5py.File + Open HDF5 file. + path : str + Path within the HDF5 file where the transform should be stored. + overwrite : bool, default: True + If True overwrite any existing h5groups. + """ + group = _create_group(f, path, overwrite=overwrite) + group.create_dataset("shift", data=self.shift) + group.create_dataset("affine", data=self.affine) -@dataclass -class Template: - det_ids: NDArray[np.str_] # (ndet,) - fp: NDArray[np.floating] # (ndet, ndim) - optical: NDArray[np.bool_] # (ndet,) - pointing_cfg: InitVar[Dict] - center: NDArray[np.floating] = field(init=False) # (1, ndim) - spacing: NDArray[np.floating] = field(init=False) # (ndim,) - bandpass: NDArray[np.str_] = field(init=False) - pol: NDArray[np.str_] = field(init=False) - rhombus: NDArray[np.str_] = field(init=False) - - def __post_init__(self, pointing_cfg): - self.center = np.array( - op.get_focal_plane(None, x=0, y=0, pol=0, **pointing_cfg) - ).T - xieta_spacing = mu.estimate_spacing(self.fp[self.optical, :2]) - # For gamma rather than the spacing in real space we want the difference between bins - # This is a rough estimate but good enough for us - gamma_spacing = np.percentile(np.diff(np.sort(self.fp[2])), 99.9) - self.spacing = np.array([xieta_spacing, xieta_spacing, gamma_spacing]) - - self.bandpass = np.zeros_like(self.det_ids) - self.pol = np.zeros_like(self.det_ids) - self.rhombus = np.zeros_like(self.det_ids) - - def add_wafer_info(self, aman, template_msk): - self.__dict__.pop("id_strs", None) - self.__dict__.pop("valid_ids", None) - if not np.all( - np.isin(["bandpass", "pol", "rhombus"], list(aman.det_info.wafer.keys())) - ): - logger.warning( - "det_info.wafer seems to be missing metadata? Safe to ignore in rset mode." - ) - return - mapping = np.argsort(np.argsort(self.det_ids[template_msk])) - srt = np.argsort(aman.det_info.det_id) - self.bandpass[template_msk] = aman.det_info.wafer.bandpass[srt][mapping] - self.pol[template_msk] = aman.det_info.wafer.pol[srt][mapping] - self.rhombus[template_msk] = aman.det_info.wafer.rhombus[srt][mapping] + @classmethod + def load(cls, f: h5py.File, path: str) -> Self: + """ + Load a transform from an HDF5 group. - @cached_property - def id_strs(self): - return np.array([bp + "_" + pol for bp, pol in zip(self.bandpass, self.pol)]) + Parameters + ---------- + f : h5py.File + Open HDF5 file. + path : str + Path within the HDF5 file containing the transform. - @cached_property - def valid_ids(self): - ids = np.unique(self.id_strs) - valid = ~(np.char.startswith(ids, "_") * np.char.endswith(ids, "_")) - return ids[valid] + Returns + ------- + Transform + Loaded transform. + """ + group = cast(h5py.Group, f[path]) + shift = np.array(group["shift"]) + affine = np.array(group["affine"]) + + return cls(shift=shift, affine=affine) @dataclass -class FocalPlane: - stream_id: str - wafer_slot: str - det_ids: NDArray[np.str_] # (ndet,) - id_strs: NDArray[np.str_] # (ndet,) - avg_fp: NDArray[np.floating] # (ndim, ndet) - weights: NDArray[np.floating] # (ndet,) - det_boresight: NDArray[np.floating] # (ndim, ndet) - transformed: NDArray[np.floating] # (ndet, ndim) - center: NDArray[np.floating] # (1, ndim) - center_transformed: NDArray[np.floating] # (1, ndim) - n_point: NDArray[np.int_] # (ndet,) - n_gamma: NDArray[np.int_] # (ndet,) - have_gamma: bool = field(default=False) - template: Optional[Template] = field(default=None) - transform: Transform = field(default_factory=Transform.identity) - transform_nocm: Transform = field(default_factory=Transform.identity) - config: str = field(default="") - with_cm: bool = field(default=True) - full_fp: Optional[NDArray[np.floating]] = field( - init=False, default=None - ) # (ndet, ndim, n_aman) - tot_weight: Optional[NDArray[np.floating]] = field( - init=False, default=None - ) # (ndet,) +class DetectorOffsets: + """ + Class for storing detector offsets in `xieta`, `horizon`, `fp`, or `ot` + coordinates. The `xi`, `eta`, `gamma`, `az`, `el`, and `roll` properties + provide convenient access to individual coordinates and raise a + `ValueError` if accessed when `coordsys` is incompatible. + + Cached properties are cleared when `xyz` is assigned to. + + Attributes + ---------- + xyz : Float[np.ndarray, "ndet 3"] + Detector coordinates. The meaning of each column depends on + `coordsys`: + + - `xieta`: (`xi`, `eta`, `gamma`). + - `horizon`: (`az`, `el`, `roll`). + - `fp` and `ot`: Coordinates in the corresponding coordinate system. + det_id : Shaped[np.ndarray, "ndet"] + Detector ID associated with each row of `xyz`. + split : Shaped[np.ndarray, "ndet"] + String used to group detectors when plotting. Nominally, this + separates the four detectors behind the same feedhorn. + center : Optional[Float[np.ndarray, "3"]] + Center of the detector offsets, or `None` if unknown. + coordsys : str + Coordinate system of the detector offsets. Must be one of + `xieta`, `horizon`, `fp`, or `ot`. + xi : Float[np.ndarray, "ndet"] + (Property) First coordinate of `xyz` when `coordsys="xieta"`. + eta : Float[np.ndarray, "ndet"] + (Property) Second coordinate of `xyz` when `coordsys="xieta"`. + gamma : Float[np.ndarray, "ndet"] + (Property) Third coordinate of `xyz` when `coordsys="xieta"`. + az : Float[np.ndarray, "ndet"] + (Property) First coordinate of `xyz` when `coordsys="horizon"`. + el : Float[np.ndarray, "ndet"] + (Property) Second coordinate of `xyz` when `coordsys="horizon"`. + roll : Float[np.ndarray, "ndet"] + (Property) Third coordinate of `xyz` when `coordsys="horizon"`. + ancil : AxisManager + (Cached property) Encoder ancillary data constructed from the + horizon coordinates. Contains `az_enc`, `el_enc`, `roll_enc`, + and `boresight_enc`, with angles converted to degrees. + fp : AxisManager + (Cached property) Focal plane coordinates containing `xi`, `eta`, + and `gamma`. + q_enc : Quaternion + (Cached property) Quaternion representing encoder pointing, + constructed from azimuth, elevation, and roll. + q_enc_zero_roll : Quaternion + (Cached property) Quaternion representing encoder pointing + with roll set to zero. + """ + + xyz: Float[np.ndarray, "ndet 3"] + det_id: Shaped[np.ndarray, "ndet"] + split: Shaped[np.ndarray, "ndet"] + center: Optional[Float[np.ndarray, "3"]] + coordsys: str def __post_init__(self): - if self.template is not None and not np.all( - np.isclose(self.center, self.template.center) - ): - raise ValueError("Focalplane center does not match template") + if self.coordsys not in ("xieta", "horizon", "fp", "ot"): + raise ValueError(f"Invalid coordsys {self.coordsys}") + + def __setattr__(self, name: str, value: Any, /) -> None: + if name in ("xyz"): + self.__dict__.pop("ancil", None) + self.__dict__.pop("fp", None) + self.__dict__.pop("q_enc", None) + self.__dict__.pop("q_enc_zero_roll", None) + return super().__setattr__(name, value) + + def __getitem__(self, key) -> DetectorOffsets: + return DetectorOffsets( + xyz=self.xyz[key], + det_id=self.det_id[key], + split=self.split[key], + center=self.center, + coordsys=self.coordsys, + ) + + @classmethod + def empty(cls, coordsys): + xyz = np.zeros((0, 3)) + det_id = np.zeros(0, dtype=str) + split = np.zeros(0, dtype=str) + center = None + return cls(xyz, det_id, split, center, coordsys) @property - def template_fp(self): - if self.template is not None: - return self.template.fp - logger.warning( - "No template in focal plane %s, reconstructing from transformed. This will be wrong with_cm is set wrong!", - self.stream_id, - ) - transform = self.transform_nocm - if self.with_cm: - transform = self.transform - return (self.transformed - transform.shift) @ np.linalg.inv(transform.affine) + def xi(self): + if self.coordsys != "xieta": + raise ValueError("Must be in a xieta coordsys to get xi") + return self.xyz[:, 0] @property - def template_center(self): - if self.template is not None: - return self.template.center - logger.warning( - "No template in focal plane %s, reconstructing from transformed. This will be wrong with_cm is set wrong!", - self.stream_id, - ) - transform = self.transform_nocm - if self.with_cm: - transform = self.transform - return (self.center_transformed - transform.shift) @ np.linalg.inv( - transform.affine - ) + def eta(self): + if self.coordsys != "xieta": + raise ValueError("Must be in a xieta coordsys to get eta") + return self.xyz[:, 1] @property - def diff(self): - return self.avg_fp - self.transformed + def gamma(self): + if self.coordsys != "xieta": + raise ValueError("Must be in a xieta coordsys to get gamma") + return self.xyz[:, 2] @property - def isfinite(self): - return np.isfinite(self.diff[:, 0]) + def az(self): + if self.coordsys != "horizon": + raise ValueError("Must be in a horizon coordsys to get az") + return self.xyz[:, 0] @property - def dist(self): - if self.have_gamma: - return np.linalg.norm(self.diff, axis=1) - return np.linalg.norm(self.diff[:, :2], axis=1) + def el(self): + if self.coordsys != "horizon": + raise ValueError("Must be in a horizon coordsys to get el") + return self.xyz[:, 1] @property - def padded(self): - return self.tot_weight is None + def roll(self): + if self.coordsys != "horizon": + raise ValueError("Must be in a horizon coordsys to get roll") + return self.xyz[:, 2] - @classmethod - def empty(cls, template, stream_id, wafer_slot, n_aman, config=""): - if template is None: - raise TypeError("template must be an instance of Template, not None") - full_fp = np.full(template.fp.shape + (n_aman,), np.nan) - tot_weight = np.zeros((len(template.det_ids), 2)) - avg_fp = np.full_like(template.fp, np.nan) - weight = np.zeros((len(template.det_ids), 2)) - det_boresight = np.zeros((len(template.det_ids), 3)) + np.nan # az, el, roll - transformed = template.fp.copy() - center = template.center.copy() - center_transformed = template.center.copy() - n_point = np.zeros_like(template.det_ids, dtype=int) - n_gamma = np.zeros_like(template.det_ids, dtype=int) - - fp = FocalPlane( - stream_id, - wafer_slot, - template.det_ids, - template.id_strs, - avg_fp, - weight, - det_boresight, - transformed, - center, - center_transformed, - n_point, - n_gamma, - template=template, - config=config, - ) - fp.full_fp = full_fp - fp.tot_weight = tot_weight + @cached_property + def ancil(self): + ancil = AxisManager(IndexAxis("samps", len(self.xyz))) + ancil.wrap("az_enc", np.rad2deg(self.az)) + ancil.wrap("el_enc", np.rad2deg(self.el)) + ancil.wrap("roll_enc", np.rad2deg(self.roll)) + ancil.wrap("boresight_enc", -1 * np.rad2deg(self.roll)) # for SATs + return ancil + @cached_property + def fp(self): + fp = AxisManager(IndexAxis("samps", len(self.xyz))) + fp.wrap("xi", self.xi) + fp.wrap("eta", self.eta) + fp.wrap("gamma", self.gamma) return fp - def map_by_det_id(self, aman): - if self.template is not None and not np.array_equal( - self.det_ids, self.template.det_ids - ): - raise ValueError("det_ids don't match template, mapping is not valid!") - _, msk, template_msk = np.intersect1d( - aman.det_info.det_id, self.det_ids, return_indices=True - ) - if len(msk) != aman.dets.count: - logger.warning("There are matched dets not found in the focal plane") - mapping = np.argsort(np.argsort(self.det_ids[template_msk])) - srt = np.argsort(aman.det_info.det_id[msk]) - xi = aman.pointing.xi[msk][srt][mapping] - eta = aman.pointing.eta[msk][srt][mapping] - r2 = np.nan + np.zeros_like(eta) - az = np.deg2rad(aman.obs_info.az_center) * np.ones_like(eta) - el = np.deg2rad(aman.obs_info.el_center) * np.ones_like(eta) - roll = np.deg2rad(aman.obs_info.roll_center) * np.ones_like(eta) - if "R2" in aman.pointing: - r2 = aman.pointing.R2[msk][srt][mapping] - if "az" in aman.pointing: - az = aman.pointing.az[msk][srt][mapping] - if "el" in aman.pointing: - el = aman.pointing.el[msk][srt][mapping] - if "roll" in aman.pointing: - roll = aman.pointing.roll[msk][srt][mapping] - if "polarization" in aman: - # name of field just a placeholder for now - gamma = aman.polarization.polang[msk][srt][mapping] - elif "gamma" in aman.pointing: - gamma = aman.pointing.gamma[msk][srt][mapping] - else: - gamma = np.full(len(xi), np.nan) - fp = np.column_stack((xi, eta, gamma)) - det_boresight = np.column_stack((az, el, roll)) - return fp, r2, det_boresight, template_msk - - def add_fp(self, i, fp, weights, det_boresight, template_msk): - if self.full_fp is None or self.tot_weight is None or self.det_boresight is None: - raise ValueError("full_fp or tot_weight or det_boresight not initialized") - self.full_fp[template_msk, :, i] = fp * weights[:, 0][..., None] - weights = np.nan_to_num(weights) - self.tot_weight[template_msk] += weights - self.det_boresight[template_msk, :] = det_boresight - - def save(self, f, db_info, group): - logger.info("Saving %s", self.stream_id) - ndets = len(self.det_ids) - outdt = [ - ("dets:det_id", self.det_ids.dtype), - ("xi", np.float32), - ("eta", np.float32), - ("gamma", np.float32), - ("padded", np.bool_), - ] - fpout = np.fromiter( - zip( - self.det_ids, - *(self.transformed.T), - np.ones(len(self.det_ids), dtype=bool) * (self.padded), - ), - dtype=outdt, - count=ndets, - ) - write_dataset( - metadata.ResultSet.from_friend(fpout), - f, - f"{group}/focal_plane", - overwrite=True, + @cached_property + def q_enc(self): + return quat.rotation_lonlat(-1 * self.az, self.el) * quat.euler(2, self.roll) + + @cached_property + def q_enc_zero_roll(self): + return quat.rotation_lonlat(-1 * self.az, self.el) * quat.euler( + 2, 0 * self.roll ) - _add_attrs( - f[f"{group}/focal_plane"], - {"wafer_slot": str(self.wafer_slot), "measured_gamma": self.have_gamma}, - ) - entry = {"dets:stream_id": self.stream_id, "dataset": f"{group}/focal_plane"} - entry.update(db_info[1]) - db_info[0].add_entry(entry, filename=os.path.basename(f.filename), replace=True) - - outdt_full = [ - ("dets:det_id", self.det_ids.dtype), - ("id_strs", self.id_strs.dtype), - ("xi_t", np.float32), - ("eta_t", np.float32), - ("gamma_t", np.float32), - ("xi_m", np.float32), - ("eta_m", np.float32), - ("gamma_m", np.float32), - ("weights", np.float32), - ("r2", np.float32), - ("az", np.float32), - ("el", np.float32), - ("roll", np.float32), - ("n_point", np.int8), - ("n_gamma", np.int8), + + def save(self, f: h5py.File, path: str, overwrite: bool = True): + """Save detector offsets to an HDF5 ResultSet. + + The ResultSet contains one row per detector with columns for the + detector ID, coordinate values, and split. Coordinate column names + are determined by `coordsys`: `xi`, `eta`, `gamma` for + `xieta` and `az`, `el`, `roll` for `horizon`. + + The coordinate system and center are stored as HDF5 attributes. + + Parameters + ---------- + f : h5py.File + HDF5 file to save to. + path : str + Path within the HDF5 file at which to save the ResultSet. + overwrite : bool, default: True + Whether to overwrite an existing dataset at `path`. + """ + columns = _COORDSYS_COLUMNS[self.coordsys] + dtype = [ + ("dets:det_id", self.det_id.dtype), + *((name, self.xyz.dtype) for name in columns), + ("split", self.split.dtype), ] - fpfullout = np.fromiter( - zip( - self.det_ids, - self.id_strs, - *(self.transformed.T), - *(self.avg_fp.T), - *(self.weights.T), - *(self.det_boresight.T), - self.n_point, - self.n_gamma, - ), - dtype=outdt_full, - count=ndets, - ) + + data = np.empty(len(self.det_id), dtype=dtype) + data["dets:det_id"] = self.det_id + data[columns[0]] = self.xyz[:, 0] + data[columns[1]] = self.xyz[:, 1] + data[columns[2]] = self.xyz[:, 2] + data["split"] = self.split + write_dataset( - metadata.ResultSet.from_friend(fpfullout), + metadata.ResultSet.from_friend(data), f, - f"{group}/focal_plane_full", - overwrite=True, + path, + overwrite=overwrite, ) - - self.transform.save(f, f"{group}/transform") - self.transform_nocm.save(f, f"{group}/transform", "_nocm") _add_attrs( - f[f"{group}"], + f[path], { - "fit_centers": self.center_transformed, - "template_centers": self.center, - "config": self.config, - "with_cm": self.with_cm, - "tot_weight": self.tot_weight, + "coordsys": self.coordsys, + "center": self.center, }, ) @classmethod - def load(cls, group, include_cm=None): - stream_id = group.name.split("/")[-1] - fp_full = read_dataset(group.file, f"{group.name}/focal_plane_full") - if fp_full.keys is None: - raise ValueError("fp_full somehow has no keys") - det_ids = fp_full["dets:det_id"] - if "id_strs" in fp_full.keys: - id_strs = fp_full["id_strs"] + def load(cls, f: h5py.File, path: str) -> Self: + """Load detector offsets from an HDF5 ResultSet. + + Parameters + ---------- + f : h5py.File + HDF5 file containing the detector offsets. + path : str + Path within the HDF5 file containing the ResultSet. + + Returns + ------- + DetectorOffsets + Detector offsets loaded from the ResultSet. + """ + rs = read_dataset(f, path) + coordsys = cast(str, f[path].attrs["coordsys"]) + columns = _COORDSYS_COLUMNS[coordsys] + xyz = np.column_stack( + [ + np.asarray(rs[columns[0]]), + np.asarray(rs[columns[1]]), + np.asarray(rs[columns[2]]), + ] + ) + center = ( + np.asarray(f[path].attrs["center"]) if "center" in f[path].attrs else None + ) + + return cls( + xyz=xyz, + det_id=np.asarray(rs["dets:det_id"]), + split=np.asarray(rs["split"]), + center=center, + coordsys=coordsys, + ) + + +@dataclass +class FocalPlane: + """ + Container for a single focal plane measurement and its derived transforms. + + A `FocalPlane` represents one measured realization of a focal plane + (typically a single UFM) together with the information needed to compare + it against a reference template. The class stores the measured detector + positions, encoder values, detector weights, and an optional pointing + model. From these inputs it can derive several useful quantities: + + - Pointing model corrected detector positions (`pm_data`). + - The affine transform mapping the template onto the measured data + (`transform`). + - The transformed template (`transformed`). + - The affine transform after applying the pointing model (`pm_transform`). + - The transformed template in the pointing model corrected frame + (`pm_transformed`). + - The transformed template in the focal plane collection frame + (`fpc_transformed`). + + Derived quantities can be evaluated dynamically or stored as static + values. When `static=True`, the public properties return the frozen + values stored by `freeze`. When `static=False`, the quantities are + recomputed on access. If `autofreeze=True`, newly computed values + are automatically cached into the corresponding static fields. + + Assigning a new value to `wmsk` clears the cached properties. + + Attributes + ---------- + name : str + Human-readable identifier for the focal plane (e.g. UFM name). + meas_id : str + Identifier for the measurement from which this focal plane was + constructed. + data : DetectorOffsets + Measured detector offsets in focal plane coordinates. + enc : DetectorOffsets + Encoder values associated with the measurement. These are used when + applying the pointing model and are typically stored in the + `horizon` coordinate system. + weights : Float[np.ndarray, "ndet"] + Per-detector weights used when fitting transforms and combining + measurements. + wmsk : Bool[np.ndarray, "ndet"] + Boolean mask selecting detectors included in fitting and pointing + model inversion. + parent : FocalPlaneCollection + The collection that this measurement belongs to. + pointing_model : PointingModel + Pointing model to apply before computing corrected transforms. + static : bool + If True, return values from the frozen static fields instead of + recomputing them. + autofreeze : bool + If True, cache dynamically computed quantities into their + corresponding static fields. + fake_gamma : bool + If True, ignore gamma when fitting and applying transforms, + effectively treating the focal plane as two-dimensional. + pm_data : DetectorOffsets + Pointing model corrected detector offsets. Dynamically computed + using `pointing_model.apply_det` or returned from the frozen + static value. + transform : Transform + Best-fit affine transform mapping `template` to `data`. + transformed : DetectorOffsets + Template detector offsets after applying `transform`. + pm_transform : Transform + Best-fit affine transform mapping `template` to `pm_data`. + pm_transformed : DetectorOffsets + Template detector offsets after applying `pm_transform`. + fpc_transformed : DetectorOffsets + Template detector offsets after applying the parent collection's + transform. + resid : Float[np.ndarray, "ndet 3"] + Residuals between `data` and `transformed`. + pm_resid : Float[np.ndarray, "ndet 3"] + Residuals between `pm_data` and `pm_transformed`. + fpc_resid : Float[np.ndarray, "ndet 3"] + Residuals between `pm_data` and `fpc_transformed`. + template : DetectorOffsets + Reference detector layout used as the transform source on sky. + Provided by `parent`. + template_fp : DetectorOffsets + Reference detector layout used as the transform source in focal + plane coordinates. Provided by `parent`. + template_ot : DetectorOffsets + Reference detector layout used as the transform source in OT + coordinates. Provided by `parent`. + data_msk : DetectorOffsets + (Cached property) Detector offsets selected by `wmsk`. + enc_msk : DetectorOffsets + (Cached property) Encoder values selected by `wmsk`. + template_msk : DetectorOffsets + (Cached property) Template detector offsets selected by `wmsk`. + weights_msk : Float[np.ndarray, "nmsk"] + (Cached property) Detector weights selected by `wmsk`. + pm_data_msk : DetectorOffsets + (Property) Pointing model corrected detector offsets selected by `wmsk`. + """ + + name: str + meas_id: str + data: DetectorOffsets + enc: DetectorOffsets + weights: Float[np.ndarray, "ndet"] + wmsk: Bool[np.ndarray, "ndet"] + parent: FocalPlaneCollection + pointing_model: PointingModel + static: bool + autofreeze: bool + fake_gamma: bool + pm_data: ClassVar[StaticOrCached[DetectorOffsets]] = StaticOrCached("pm_data") + transform: ClassVar[StaticOrCached[Transform]] = StaticOrCached("transform") + transformed: ClassVar[StaticOrCached[DetectorOffsets]] = StaticOrCached( + "transformed" + ) + pm_transform: ClassVar[StaticOrCached[Transform]] = StaticOrCached("pm_transform") + pm_transformed: ClassVar[StaticOrCached[DetectorOffsets]] = StaticOrCached( + "pm_transformed" + ) + fpc_transformed: ClassVar[StaticOrCached[DetectorOffsets]] = StaticOrCached( + "fpc_transformed" + ) + _pm_data_stat: DetectorOffsets = field(init=False) + _transform_stat: Transform = field(init=False) + _transformed_stat: DetectorOffsets = field(init=False) + _pm_transform_stat: Transform = field(init=False) + _pm_transformed_stat: DetectorOffsets = field(init=False) + _fpc_transformed_stat: DetectorOffsets = field(init=False) + + def __setattr__(self, name: str, value: Any, /) -> None: + if name in ("wmsk"): + self.__dict__.pop("data_msk", None) + self.__dict__.pop("enc_msk", None) + self.__dict__.pop("template_msk", None) + self.__dict__.pop("weights_msk", None) + return super().__setattr__(name, value) + + @property + def template(self) -> DetectorOffsets: + return self.parent.template + + @property + def template_fp(self) -> DetectorOffsets: + return self.parent.template_fp + + @property + def template_ot(self) -> DetectorOffsets: + return self.parent.template_ot + + @cached_property + def data_msk(self) -> DetectorOffsets: + return self.data[self.wmsk] + + @cached_property + def enc_msk(self) -> DetectorOffsets: + return self.enc[self.wmsk] + + @cached_property + def template_msk(self) -> DetectorOffsets: + return self.template[self.wmsk] + + @cached_property + def weights_msk(self) -> Float[np.ndarray, "nmsk"]: + return self.weights[self.wmsk] + + @property + def pm_data_msk(self) -> DetectorOffsets: + return self.pm_data[self.wmsk] + + @classmethod + def from_aman( + cls, + name: str, + meas_id: str, + aman: AxisManager, + parent: FocalPlaneCollection, + pointing_model: PointingModel, + autofreeze: bool = False, + fake_gamma: bool = True, + weight_factor: float = 1000.0, + ) -> FocalPlane: + """ + Create a `FocalPlane` instance from a context loaded AxisManager. + Here we make the following assumptions: + + * The pointing information is in `aman.focal_plane` + * Detector matching information exists with `det_ids` in `aman.det_info.det_id`. + * The desired cuts (outlier, optical, hits, R2, etc.) have already been applied + * We either have per detector encoder fits in `aman.focal_plane` or the observation average in `aman.obs_info`. + + Parameters + ---------- + name : str + Name assigned to the resulting focal plane instance. + meas_id : str + Measurement identifier, probably the `obs_id`. + aman : AxisManager + Input data container holding focal plane and detector metadata. + See above for details on assumptions. + parent : FocalPlaneCollection + The collection that this measurement belongs to. + pointing_model : PointingModel + Pointing model associated with the observation. + autofreeze : bool, default: False + See class docstring. + fake_gamma : bool, default: True + See class docstring. + If True will also set `gamma` to `nan`. + weight_factor : float, default: 1000 + Scaling factor applied to spacing when computing weights. + + Returns + ------- + focal_plane : FocalPlane + A fully constructed focal plane object containing. + Note that this will have `static = False`. + """ + # Figure out mapping + template = parent.template + aman_det_ids = np.asarray(aman.det_info.det_id) + template_det_ids = np.asarray(template.det_id) + _, aman_idx, template_idx = np.intersect1d( + aman_det_ids, template_det_ids, return_indices=True + ) + order = np.argsort(template_idx) + aman_idx = aman_idx[order] + template_idx = template_idx[order] + template_msk = np.zeros(len(template.xyz), dtype=bool) + template_msk[template_idx] = True + valid_template = np.all(np.isfinite(template.xyz), axis=1) + valid_msk = template_msk * valid_template + + # Setup data + data = deepcopy(template) + xi = np.array(aman.focal_plane.xi) + eta = np.array(aman.focal_plane.eta) + gamma = ( + np.array(aman.focal_plane.gamma) + if not fake_gamma + else np.nan * np.ones_like(xi) + ) + data.xyz[template_idx] = np.column_stack((xi, eta, gamma))[aman_idx] + data.xyz[~template_msk] = np.nan + + # Setup enc + enc = deepcopy(template) + enc.coordsys = "horizon" + az = ( + np.array(aman.focal_plane.az) + if "az" in aman.focal_plane + else np.deg2rad(np.array(aman.obs_info.az_center)) * np.ones_like(xi) + ) + el = ( + np.array(aman.focal_plane.el) + if "el" in aman.focal_plane + else np.deg2rad(np.array(aman.obs_info.el_center)) * np.ones_like(xi) + ) + roll = ( + np.array(aman.focal_plane.roll) + if "roll" in aman.focal_plane + else np.deg2rad(np.array(aman.obs_info.roll_center)) * np.ones_like(xi) + ) + enc.xyz[template_idx] = np.column_stack((az, el, roll))[aman_idx] + enc.xyz[~template_msk] = np.nan + + # Use kmeans to kill any ghosts + fp_white = vq.whiten(data.xyz[valid_msk, :2]) + codebook, _ = vq.kmeans(fp_white, 2) + codes, _ = vq.vq(fp_white, codebook) + c0 = codes == 0 + c1 = codes == 1 + m0 = np.median(data.xyz[valid_msk, :2][c0], axis=0) + m1 = np.median(data.xyz[valid_msk, :2][c1], axis=0) + dist = np.linalg.norm(m0 - m1) + # If centroids are too far from each other use the bigger one + cent = template.center + if cent is None: + cent = np.nanmean(template.xyz, axis=0) + rad_thresh = 1.1 * np.nanmax( + np.linalg.norm(template.xyz[:, :2] - cent[:2], axis=1) + ) + if dist < rad_thresh: + cluster = c0 + c1 + elif np.sum(c0) >= np.sum(c1): + cluster = c0 else: - logger.warning("No id strings found in this focal plane, may be old.") - id_strs = np.zeros(len(fp_full), str) - avg_fp = np.column_stack( - ( - np.array(fp_full["xi_m"]), - np.array(fp_full["eta_m"]), - np.array(fp_full["gamma_m"]), + cluster = c1 + # Flag anything too far away from the center + cent = np.median(data.xyz[valid_msk, :2][cluster], axis=0) + r = np.linalg.norm(data.xyz[valid_msk, :2] - cent, axis=1) + valid_msk[valid_msk] *= cluster * (r <= rad_thresh) + + # Compute weights + aff, sft = mt.get_rigid(data.xyz[valid_msk, :2], template.xyz[valid_msk, :2]) + aligned = mt.apply_transform(data.xyz[:, :2], aff, sft) + xieta_spacing = mu.estimate_spacing(template.xyz[valid_msk, :2]) + # For gamma rather than the spacing in real space we want the difference between bins + # This is a rough estimate but good enough for us + gamma_sorted = np.sort(template.xyz[valid_msk, 2]) + gamma_spacing = np.percentile(np.diff(gamma_sorted), 99.9) + spacing = np.array([xieta_spacing, xieta_spacing, gamma_spacing]) + + weights = np.zeros(len(aligned)) + if not fake_gamma: + gscale, gsft = gamma_fit(data.xyz[:, 2], template.xyz[:, 2]) + weights[valid_msk] = mu.gen_weights( + np.column_stack((aligned[valid_msk], gscale * data.xyz[:, 2] + gsft)), + template.xyz[valid_msk], + spacing.ravel() / weight_factor, ) + else: + weights[valid_msk] = mu.gen_weights( + aligned[valid_msk], + template.xyz[valid_msk, :2], + spacing[:2].ravel() / weight_factor, + ) + + # ~1 sigma cut + weights[weights < 0.61] = 0 + valid_msk *= weights == 0 + + return cls( + name, + meas_id, + data, + enc, + weights, + valid_msk, + parent, + pointing_model, + False, + autofreeze, + fake_gamma, ) - det_boresight = np.column_stack( - ( - np.array(fp_full["az"]), - np.array(fp_full["el"]), - np.array(fp_full["roll"]), - ) + def freeze(self, static: bool, optimizer: bool): + """ + Save the current dynamic properties to the static fields. + + Parameters + ---------- + static : bool + What to set `self.static` to after freezing. + """ + self.static = True + self._pm_data_stat = self._pm_data_dyn + self._fpc_transformed_stat = self._fpc_transformed_dyn + if not optimizer: + self._transform_stat = self._transform_dyn + self._transformed_stat = self._transformed_dyn + self._pm_transform_stat = self._pm_transform_dyn + self._pm_transformed_stat = self._pm_transformed_dyn + self.static = static + + def thaw(self, static: bool): + """ + Clear the current values in static fields. + + Parameters + ---------- + static : bool + What to set `self.static` to after thawing. + """ + self.__dict__.pop("_pm_data_stat", None) + self.__dict__.pop("_fpc_transformed_stat", None) + self.__dict__.pop("_transform_stat", None) + self.__dict__.pop("_transformed_stat", None) + self.__dict__.pop("_pm_transform_stat", None) + self.__dict__.pop("_pm_transformed_stat", None) + self.static = static + + @property + def _pm_data_dyn(self) -> DetectorOffsets: + to_ret = self.pointing_model.apply_det(self) + if self.autofreeze: + self._pm_data_stat = to_ret + return to_ret + + @property + def _transform_dyn(self) -> Transform: + return _get_aff( + self, "data_msk", "template_msk", "weights_msk", "_transform_stat", False + ) + + @property + def _transformed_dyn(self) -> DetectorOffsets: + return _transformed(self, "_transformed_stat", self.transform) + + @property + def _pm_transform_dyn(self) -> Transform: + return _get_aff( + self, + "pm_data_msk", + "template_msk", + "weights_msk", + "_pm_transform_stat", + False, ) - # For backwards compatibility - weights = np.array(fp_full["weights"]) - if "r2" in fp_full.keys: - weights = np.column_stack((weights, np.array(fp_full["r2"]))) - transformed = np.column_stack( - ( - np.array(fp_full["xi_t"]), - np.array(fp_full["eta_t"]), - np.array(fp_full["gamma_t"]), + + @property + def _pm_transformed_dyn(self) -> DetectorOffsets: + return _transformed(self, "_pm_transformed_stat", self.pm_transform) + + @property + def _fpc_transformed_dyn(self) -> DetectorOffsets: + return _transformed(self, "_pm_transformed_stat", self.parent.transform) + + @property + def resid(self): + return self.data.xyz - self.transformed.xyz + + @property + def pm_resid(self): + return self.pm_data.xyz - self.pm_transformed.xyz + + @property + def fpc_resid(self): + return self.pm_data.xyz - self.fpc_transformed.xyz + + def save( + self, + f: h5py.File, + path: str, + pointing_models: tuple[PointingModel, ...], + overwrite: bool = True, + ): + """ + Save the focal plane to an HDF5 file. + + Parameters + ---------- + f : h5py.File + The HDF5 file object to save to. + path : str + The path within the HDF5 file where the focal plane will be saved. + pointing_models : tuple[PointingModel, ...] + The pointing models used by the focal-planes. + overwrite : bool, default: True + Whether to overwrite existing datasets. + """ + group = _create_group(f, path, overwrite) + pm_epcs = [pm.epoch for pm in pointing_models] + try: + pm_idx = pm_epcs.index(self.pointing_model.epoch) + except ValueError: + raise ValueError( + f"Can't find pointing model with epoch {self.pointing_model.epoch} (in {self.name}+{self.meas_id})" ) + + _add_attrs( + group, + { + "name": self.name, + "meas_id": self.meas_id, + "static": self.static, + "autofreeze": self.autofreeze, + "fake_gamma": self.fake_gamma, + "pm_idx": pm_idx, + }, ) - center = group.attrs["template_centers"] - center_transformed = group.attrs["fit_centers"] - n_point = fp_full["n_point"] - n_gamma = fp_full["n_gamma"] - have_gamma = group["focal_plane"].attrs["measured_gamma"] - template = None - transform = Transform.load(group["transform"]) - transform_nocm = Transform.load(group["transform"], "_nocm") - if "wafer_slot" in group["focal_plane"].attrs: - wafer_slot = group["focal_plane"].attrs["wafer_slot"] - else: - logger.warning("No wafer slot found in this focal plane, may be old.") - wafer_slot = "ws?" - config = group.attrs.get("config", "") - if config == "": - logger.warning("No config found in this focal plane, may be old.") - if "with_cm" in group.attrs: - with_cm = group.attrs["with_cm"] + + self.data.save(f, f"{path}/data", overwrite=overwrite) + self.enc.save(f, f"{path}/enc", overwrite=overwrite) + if f"{path}/weights" in f: + if overwrite: + del f[f"{path}/weights"] + else: + raise ValueError(f"{path}/weights already exists") + f.create_dataset(f"{path}/weights", data=self.weights) + f.create_dataset(f"{path}/wmsk", data=self.wmsk) + + if "_pm_data_stat" in self.__dict__: + self._pm_data_stat.save(f, f"{path}/pm_data", overwrite=overwrite) + if "_transform_stat" in self.__dict__: + self._transform_stat.save(f, f"{path}/transform", overwrite=overwrite) + if "_transformed_stat" in self.__dict__: + self._transformed_stat.save(f, f"{path}/transformed", overwrite=overwrite) + if "_pm_transform_stat" in self.__dict__: + self._pm_transform_stat.save(f, f"{path}/pm_transform", overwrite=overwrite) + if "_pm_transformed_stat" in self.__dict__: + self._pm_transformed_stat.save( + f, f"{path}/pm_transformed", overwrite=overwrite + ) + if "_fpc_transformed_stat" in self.__dict__: + self._fpc_transformed_stat.save( + f, f"{path}/fpc_transformed", overwrite=overwrite + ) + + @classmethod + def load( + cls, + f: h5py.File, + path: str, + parent: FocalPlaneCollection, + pointing_models: tuple[PointingModel, ...], + ) -> Self: + """ + Load a focal plane from an HDF5 file. + + Parameters + ---------- + f : h5py.File + The HDF5 file object containing the focal plane. + path : str + The path within the HDF5 file where the focal plane is stored. + template : DetectorOffsets + The template shared by the focal planes in the collection. + template_fp : DetectorOffsets + Reference detector layout used as the transform source in focal plane coords. + template_ot : DetectorOffsets + Reference detector layout used as the transform source in OT coords. + pointing_models : tuple[PointingModel, ...] + The pointing models used by the focal-planes. + + + Returns + ------- + FocalPlane + The loaded focal plane. + """ + group = cast(h5py.Group, f[path]) + data = DetectorOffsets.load(f, f"{path}/data") + enc = DetectorOffsets.load(f, f"{path}/enc") + weights = np.asarray(f[f"{path}/weights"]) + if "wmsk" in group: + wmsk = np.asarray(f[f"{path}/wmsk"]) else: - with_cm = True - logger.warning( - "No with_cm found in this focal plane, may be old. Attempting to set based on receiver!" + wmsk = np.isfinite(weights) * (weights > 0) + wmsk = np.isfinite(weights) * (weights > 0) + + pm_idx = cast(int, group.attrs["pm_idx"]) + fp = cls( + name=cast(str, group.attrs["name"]), + meas_id=cast(str, group.attrs["meas_id"]), + data=data, + enc=enc, + weights=weights, + wmsk=wmsk, + parent=parent, + pointing_model=pointing_models[pm_idx], + static=cast(bool, group.attrs["static"]), + autofreeze=cast(bool, group.attrs["autofreeze"]), + fake_gamma=cast(bool, group.attrs["fake_gamma"]), + ) + + if "pm_data" in group: + fp._pm_data_stat = DetectorOffsets.load(f, f"{path}/pm_data") + if "transform" in group: + fp._transform_stat = Transform.load(f, f"{path}/transform") + if "transformed" in group: + fp._transformed_stat = DetectorOffsets.load(f, f"{path}/transformed") + if "pm_transform" in group: + fp._pm_transform_stat = Transform.load(f, f"{path}/pm_transform") + if "pm_transformed" in group: + fp._pm_transformed_stat = DetectorOffsets.load(f, f"{path}/pm_transformed") + if "fpc_transformed" in group: + fp._fpc_transformed_stat = DetectorOffsets.load( + f, f"{path}/fpc_transformed" ) - if include_cm is None: - logger.warning("\tinclude_cm not set! Using True for with_cm") - else: - with_cm = include_cm - - fp = FocalPlane( - stream_id, - wafer_slot, - np.array(det_ids), - np.array(id_strs), - avg_fp, - np.array(weights), - det_boresight, - transformed, - center, - center_transformed, - np.array(n_point), - np.array(n_gamma), - have_gamma, - template, - transform, - transform_nocm, - config, - with_cm, - ) - fp.tot_weight = group.attrs.get("tot_weight", None) return fp @dataclass -class OpticsTube: - name: str - center: NDArray[np.floating] - transform: Transform = field(default_factory=Transform.identity) - transform_fullcm: Transform = field(default_factory=Transform.identity) - focal_planes: List[FocalPlane] = field(default_factory=list) - center_transformed: NDArray[np.floating] = field(init=False) +class FocalPlaneCollection: + """ + Container for multiple measurements of the same focal plane. + + A `FocalPlaneCollection` combines several `FocalPlane` instances that + share a common detector template and identical detector set. All + measurements are expected to contain the same detectors in + the same ordering. + + Individual measurements are merged using their detector weights to + produce a weighted-average focal plane, which can then be compared + against the reference template through a single affine transform. + + The collection operates on the pointing model corrected detector + positions (`FocalPlane.pm_data`) from each measurement. + Detector locations and weights are combined on a per-detector + basis, with missing values represented by `nan`s. + + As with `FocalPlane`, derived quantities can be evaluated dynamically + or stored as static values. When `static=True`, the public properties + return frozen values previously stored by `freeze`. When + `static=False`, quantities are recomputed on access. If + `autofreeze=True`, newly computed values are automatically cached into + the corresponding static fields. + + Attributes + ---------- + name : str + Human-readable identifier for the collection. + This is most likely the name of the UFM. + focal_planes : list[FocalPlane] + Individual focal-plane measurements to combine. All measurements + must contain the same detector set and detector ordering. + template : DetectorOffsets + Reference detector layout used as the transform source. + template_fp : DetectorOffsets + Reference detector layout used as the transform source in focal + plane coordinates. + template_ot : DetectorOffsets + Reference detector layout used as the transform source in OT + coordinates. + static : bool + If True, return values from the frozen static fields instead of + recomputing them. + autofreeze : bool + If True, cache dynamically computed quantities into their + corresponding static fields. + pad : bool + Flag indicating that this collection should be excluded from + common-mode calculations. Typically used for padded or otherwise + invalid focal-plane slots. + fake_gamma : bool + If True, ignore gamma when fitting transforms, effectively treating + the focal plane as two-dimensional. + parent : OpticsTube + The OT that this FocalPlane belongs to. + data : DetectorOffsets + Weighted-average detector offsets constructed from the + pointing-model-corrected measurements in `focal_planes`. + Dynamically computed or retrieved from the frozen static value. + weights : Float[np.ndarray, "ndet"] + Combined detector weights obtained by summing the weights from all + constituent measurements. + transform : Transform + Best-fit affine transform mapping `template` to `data`. + transformed : DetectorOffsets + Template detector offsets after applying `transform`. + resid : Float[np.ndarray, "ndet 3"] + Residuals between `data` and `transformed`. + ndet : int + (Property) Number of detectors in the reference template. + nobs : int + (Property) Number of focal-plane measurements in the collection. + wmsk : Bool[np.ndarray, "ndet"] + (Property) Boolean mask selecting detectors with finite, + positive combined weights. + residuals : Float[np.ndarray, "ndet*nobs"] + (Property) Flattened array of weighted residual magnitudes for + all measurements. Residuals are computed relative to the + collection's transformed template, using the number of + coordinates determined by each measurement's `fake_gamma` + setting. Detectors excluded by their measurement mask contribute + zero. + chisq : float + (Property) Sum of squared values in `residuals`. + """ - def __post_init__(self): - self.center_transformed = mt.apply_transform( - self.center, self.transform_fullcm.affine, self.transform_fullcm.shift - ) + name: str + focal_planes: list[FocalPlane] + template: DetectorOffsets + template_fp: DetectorOffsets + template_ot: DetectorOffsets + static: bool + autofreeze: bool + pad: bool + fake_gamma: bool + parent: OpticsTube + data: ClassVar[StaticOrCached[DetectorOffsets]] = StaticOrCached("data") + weights: ClassVar[StaticOrCached[Float[np.ndarray, "ndet"]]] = StaticOrCached( + "weights" + ) + transform: ClassVar[StaticOrCached[Transform]] = StaticOrCached("transform") + transformed: ClassVar[StaticOrCached[DetectorOffsets]] = StaticOrCached( + "transformed" + ) + _data_stat: DetectorOffsets = field(init=False) + _weights_stat: Float[np.ndarray, "ndet"] = field(init=False) + _transform_stat: Transform = field(init=False) + _transformed_stat: DetectorOffsets = field(init=False) + _residual_buffer: Float[np.ndarray, "n_data"] = field(init=False) + + def __getitem__(self, key): + fp_ids = [fp.meas_id for fp in self.focal_planes] + if key in fp_ids: + return self.focal_planes[fp_ids.index(key)] + raise IndexError(f"Invalid key: {key}") + + def freeze(self, static: bool): + """ + Save the current dynamic properties to the static fields. + + Parameters + ---------- + static : bool + What to set `self.static` to after freezing. + """ + if self.pad: + return + self.static = True + self._data_stat = self._data_dyn + self._weights_stat = self._weights_dyn + self._transform_stat = self._transform_dyn + self._transformed_stat = self._transformed_dyn + self.static = static + + def thaw(self, static: bool): + """ + Clear the current values in static fields. + + Parameters + ---------- + static : bool + What to set `self.static` to after thawing. + """ + self.__dict__.pop("_weights_stat", None) + self.__dict__.pop("_data_stat", None) + self.__dict__.pop("_transform_stat", None) + self.__dict__.pop("_transformed_stat", None) + self.static = static - def __setattr__(self, name, val): - self.__dict__[name] = val - if name == "focal_planes": - self.__dict__.pop("fp_dict", None) + @property + def ndet(self) -> int: + return len(self.template.xyz) @property - def num_fps(self): - fps = [fp for fp in self.focal_planes if fp.tot_weight is not None] - return len(fps) + def nobs(self) -> int: + return len(self.focal_planes) - @classmethod - def from_pointing_cfg(cls, pointing_cfg): - name = pointing_cfg["tube_slot"] - telescope_flavor = pointing_cfg["telescope_flavor"].upper() - if telescope_flavor not in ["LAT", "SAT"]: - raise ValueError("Telescope should be LAT or SAT") - - if telescope_flavor == "LAT": - if pointing_cfg["zemax_path"] is None: - raise ValueError("Must provide zemax_path for LAT") - xi, eta, gamma = op.LAT_focal_plane( - None, - pointing_cfg["zemax_path"], - x=0, - y=0, - pol=0, - roll=pointing_cfg.get("roll", 0), - tube_slot=name, - ) + @property + def residuals(self) -> Float[np.ndarray, "ndet*nobs"]: + n_data = self.ndet * self.nobs + if n_data == 0: + return np.empty(0) + if "_residual_buffer" in self.__dict__ and len(self._residual_buffer) == n_data: + resid = self._residual_buffer else: - xi, eta, gamma = op.SAT_focal_plane( - None, - x=0, - y=0, - pol=0, - roll=pointing_cfg.get("roll", 0), - mapping_data=pointing_cfg.get("mapping_data", None), + resid = np.empty(n_data) + self._residual_buffer = resid + i = 0 + for meas in self.focal_planes: + ndim = 3 - int(meas.fake_gamma) + r = np.linalg.norm(meas.fpc_resid[:, :ndim], axis=1) * meas.weights + r[~meas.wmsk] = 0 + resid[i : (i + len(r))] = r + i += len(r) + to_ret = np.nan_to_num( + resid, copy=False, nan=0.0, posinf=np.inf, neginf=-np.inf + ) + if to_ret is None: + raise TypeError + return to_ret + + @property + def chisq(self) -> float: + return np.sum(self.residuals**2) + + @property + def _data_dyn(self) -> DetectorOffsets: + to_ret = deepcopy(self.template) + to_ret.xyz[:] = 0 + fmsk = np.zeros(len(to_ret.xyz), dtype=bool) + all_fake = True + for meas in self.focal_planes: + fmsk += meas.wmsk + all_fake *= meas.fake_gamma + ndim = 3 - int(meas.fake_gamma) + to_ret.xyz[meas.wmsk, :ndim] += ( + meas.pm_data.xyz[meas.wmsk, :ndim] * meas.weights[meas.wmsk, None] ) - center = np.array((xi, eta, gamma)).reshape((1, 3)) + to_ret.xyz[~fmsk] = np.nan + to_ret.xyz[fmsk] /= self.weights[fmsk, None] + if all_fake: + to_ret.xyz[:, 2] = np.nan + to_ret.center = None + if self.autofreeze: + self._data_stat = to_ret + return to_ret - return OpticsTube(name, center) + @property + def _weights_dyn(self) -> Float[np.ndarray, "ndet"]: + weights_full = np.asarray([fp.weights for fp in self.focal_planes]) + to_ret = np.nansum(weights_full, axis=0) + if self.autofreeze: + self._weights_stat = to_ret + return to_ret - def delete_fp(self, stream_id): - self.focal_planes = [ - fp for fp in self.focal_planes if fp.stream_id != stream_id - ] + @property + def _transform_dyn(self) -> Transform: + if self.pad or np.sum(self.wmsk) == 0: + return self.parent.cm_transform + return _get_aff(self, "data", "template", "weights", "_transform_stat", True) - @cached_property - def fp_dict(self): - return {fp.stream_id: fp for fp in self.focal_planes} + @property + def _transformed_dyn(self) -> DetectorOffsets: + return _transformed(self, "_transformed_stat", self.transform) + + @property + def resid(self): + return self.data.xyz - self.transformed.xyz - def save(self, f, db_info, group="/"): - g = f[group] - g.create_group(self.name) + @property + def wmsk(self): + weights = self.weights + return np.isfinite(weights) * (weights > 0) + + def save( + self, + f: h5py.File, + path: str, + pointing_models: tuple[PointingModel, ...], + overwrite: bool = True, + ): + """ + Save the focal plane collection to an HDF5 file. + + Parameters + ---------- + f : h5py.File + The HDF5 file object to save to. + path : str + The path within the HDF5 file where the collection will be saved. + pointing_models : tuple[PointingModel, ...] + The pointing models used by the focal-planes. + overwrite : bool, default: True + Whether to overwrite existing datasets. + """ + meas_ids = [fp.meas_id for fp in self.focal_planes] + if len(meas_ids) != len(set(meas_ids)): + raise ValueError("FocalPlaneCollection contains overlapping meas_ids") + + group = _create_group(f, path, overwrite) _add_attrs( - g[self.name], - {"center": self.center, "center_transformed": self.center_transformed}, - ) - tr_path = os.path.join(group, self.name, "transform") - self.transform.save(f, tr_path) - self.transform_fullcm.save(f, tr_path, "_fullcm") - for focal_plane in self.focal_planes: - focal_plane.save( - f, db_info, os.path.join(group, self.name, focal_plane.stream_id) + group, + { + "name": self.name, + "static": self.static, + "autofreeze": self.autofreeze, + "pad": self.pad, + "fake_gamma": self.fake_gamma, + }, + ) + self.template.save(f, f"{path}/template", overwrite=overwrite) + self.template_fp.save(f, f"{path}/template_fp", overwrite=overwrite) + self.template_ot.save(f, f"{path}/template_ot", overwrite=overwrite) + for fp in self.focal_planes: + fp.save( + f, + f"{path}/focal_planes/{fp.meas_id}", + pointing_models=pointing_models, + overwrite=overwrite, ) + if "_data_stat" in self.__dict__: + self._data_stat.save(f, f"{path}/data", overwrite=overwrite) + if "_weights_stat" in self.__dict__: + if f"{path}/weights" in f: + if overwrite: + del f[f"{path}/weights"] + else: + raise ValueError(f"{path}/weights already exists") + f.create_dataset(f"{path}/weights", data=self._weights_stat) + if "_transform_stat" in self.__dict__: + self._transform_stat.save(f, f"{path}/transform") + if "_transformed_stat" in self.__dict__: + self._transformed_stat.save(f, f"{path}/transformed", overwrite=overwrite) + @classmethod - def load(cls, group, include_cm=None): - name = group.name.split("/")[-1] - center = group.attrs["center"] - transform = Transform.load(group["transform"]) - transform_fullcm = Transform.load(group["transform"], "_fullcm") - fps = [ - FocalPlane.load(group[grp], include_cm) - for grp in group.keys() - if "transform" not in grp - ] + def load( + cls, + f: h5py.File, + path: str, + pointing_models: tuple[PointingModel, ...], + parent: OpticsTube, + ) -> Self: + """ + Load a focal plane collection from an HDF5 file. + + Parameters + ---------- + f : h5py.File + The HDF5 file object containing the collection. + path : str + The path within the HDF5 file where the collection is stored. + pointing_models : tuple[PointingModel, ...] + The pointing models used by the focal-planes. + parent : OpticsTube + The OT that this FocalPlane belongs to. + + Returns + ------- + FocalPlaneCollection + The loaded focal plane collection. + """ + template = DetectorOffsets.load( + f, + f"{path}/template", + ) + template_fp = DetectorOffsets.load( + f, + f"{path}/template_fp", + ) + template_ot = DetectorOffsets.load( + f, + f"{path}/template_ot", + ) + group = cast(h5py.Group, f[path]) + + collection = cls( + name=cast(str, group.attrs["name"]), + focal_planes=[], + template=template, + template_fp=template_fp, + template_ot=template_ot, + static=cast(bool, group.attrs["static"]), + autofreeze=cast(bool, group.attrs["autofreeze"]), + pad=cast(bool, group.attrs["pad"]), + fake_gamma=cast(bool, group.attrs["fake_gamma"]), + parent=parent, + ) + + if "data" in group: + collection._data_stat = DetectorOffsets.load( + f, + f"{path}/data", + ) + if "weights" in group: + collection._weights_stat = np.asarray(f[f"{path}/weights"]) + # if "scatter" in group: + # collection._scatter_stat = np.asarray(f[f"{path}/scatter"]) + if "transform" in group: + collection._transform_stat = Transform.load(f, f"{path}/transform") + if "transformed" in group: + collection._transformed_stat = DetectorOffsets.load( + f, + f"{path}/transformed", + ) + + if "focal_planes" not in group: + return collection + for name in cast(h5py.Group, group["focal_planes"]): + collection.focal_planes.append( + FocalPlane.load( + f, + f"{path}/focal_planes/{name}", + parent=collection, + pointing_models=pointing_models, + ) + ) - return OpticsTube(name, center, transform, transform_fullcm, fps) + return collection @dataclass -class Receiver: - optics_tubes: List[OpticsTube] = field(default_factory=list) - center: NDArray[np.floating] = field( - default_factory=partial(np.zeros, shape=(1, 3)) +class OpticsTube: + """ + An `OpticsTube` groups one or more `FocalPlaneCollection` instances + associated with the same optics tube and + calculates tube-level common-mode transforms. These common-mode + transforms capture distortions that are shared across the focal planes + within the tube and can be used to separate optics-tube effects from + from per-array or full receiver effects. + + The tube common mode is computed from the affine transforms of all + non-padded focal planes in the collection. If no valid focal planes are + available, the identity transform is returned and the tube is marked as + containing only padded data. + + When `static=True`, the public properties return frozen values previously + stored by `freeze`. When `static=False`, quantities are recomputed on + access. If `autofreeze=True`, newly computed values are automatically + cached into the corresponding static fields. + + Attributes + ---------- + name : str + Human-readable identifier for the optics tube. + focal_planes : list[FocalPlaneCollection] + Focal-plane collections associated with this optics tube. + wafer_slots : list[str] + Wafer-slot identifiers corresponding to the entries in + `focal_planes`. These are used to support lookup by wafer slot + through `__getitem__`. + static : bool + If True, return values from the frozen static fields instead of + recomputing them. + autofreeze : bool + If True, cache dynamically computed quantities into their + corresponding static fields. + parent : Receiver + The Receiver that this OT belongs to. + cm_transform : Transform + Common-mode transform derived from the transforms of all + non-padded focal-plane collections. + cm_transform_norx : Transform + Copy of the optics-tube common-mode transform with a receiver common mode removed. + allpad : bool + (Property) Flag indicating whether all focal-plane collections in the optics + tube are padded and should therefore be excluded from common-mode + calculations. Returns True if the collection is empty. + """ + + name: str + focal_planes: list[FocalPlaneCollection] + wafer_slots: list[str] + static: bool + autofreeze: bool + parent: Receiver + cm_transform: ClassVar[StaticOrCached[Transform]] = StaticOrCached("cm_transform") + cm_transform_norx: ClassVar[StaticOrCached[Transform]] = StaticOrCached( + "cm_transform_norx" ) - include_cm: bool = field(default=False) - valid_ids: List[str] = field(default_factory=list) - transform: Transform = field(default_factory=Transform.identity) - center_transformed: NDArray[np.floating] = field(init=False) + _cm_transform_stat: Transform = field(init=False) + _cm_transform_norx_stat: Transform = field(init=False) + + def __getitem__(self, key): + if key in self.wafer_slots: + return self.focal_planes[self.wafer_slots.index(key)] + fp_names = [fp.name for fp in self.focal_planes] + if key in fp_names: + return self.focal_planes[fp_names.index(key)] + raise IndexError(f"Invalid key: {key}") + + def freeze(self, static: bool): + """ + Save the current dynamic properties to the static fields. + + Parameters + ---------- + static : bool + What to set `self.static` to after freezing. + """ + if self.allpad: + return + self.static = True + self._cm_transform_stat = self._cm_transform_dyn + self.static = static + + def thaw(self, static: bool): + """ + Clear the current values in static fields. + + Parameters + ---------- + static : bool + What to set `self.static` to after thawing. + """ + self.__dict__.pop("_cm_transform_stat", None) + self.static = static - def __post_init__(self): - self.center_transformed = mt.apply_transform( - self.center, self.transform.affine, self.transform.shift + @property + def allpad(self) -> bool: + if len(self.focal_planes) == 0: + return True + return bool(np.all([fp.pad for fp in self.focal_planes])) + + @property + def _cm_transform_dyn(self) -> Transform: + transforms = [ + fp.transform.affine for fp in self.focal_planes if fp.pad is False + ] + shifts = [fp.transform.shift for fp in self.focal_planes if fp.pad is False] + if len(transforms) == 0: + iden = Transform.identity() + cm_shift, cm_aff = iden.shift, iden.affine + elif len(transforms) == 1: + cm_aff, cm_shift = transforms[0], shifts[0] + else: + cm_aff, cm_shift = mt.get_common_mode( + transforms, shifts, -2, False, fast=True + ) + to_ret = Transform(cm_shift, cm_aff) + if self.autofreeze: + self._cm_transform_stat = to_ret + return to_ret + + @property + def _cm_transform_norx_dyn(self) -> Transform: + if self.allpad: + to_ret = Transform.identity() + else: + aff, sft = mt.decompose_transform( + self.cm_transform.affine, + self.cm_transform.shift, + self.parent.cm_transform.affine, + self.parent.cm_transform.shift, + ) + to_ret = Transform(sft, aff) + if self.autofreeze: + self._cm_transform_norx_stat = to_ret + return to_ret + + def save( + self, + f: h5py.File, + path: str, + pointing_models: tuple[PointingModel, ...], + overwrite: bool = True, + ): + """ + Save the optics tube to an HDF5 file. + + Parameters + ---------- + f : h5py.File + The HDF5 file object to save to. + path : str + The path within the HDF5 file where the optics tube will be saved. + pointing_models : tuple[PointingModel, ...] + The pointing models used by the focal-planes. + overwrite : bool, default: True + Whether to overwrite existing datasets. + """ + group = _create_group(f, path, overwrite) + _add_attrs( + group, + { + "name": self.name, + "wafer_slots": self.wafer_slots, + "static": self.static, + "autofreeze": self.autofreeze, + }, ) + for ws, fp in zip(self.wafer_slots, self.focal_planes): + fp.save(f, f"{path}/{ws}-{fp.name}", pointing_models, overwrite=overwrite) + if "_cm_transform_stat" in self.__dict__: + self._cm_transform_stat.save(f, f"{path}/cm_transform") + if "_cm_transform_norx_stat" in self.__dict__: + self.cm_transform_norx.save(f, f"{path}/cm_transform_norx") - def __setattr__(self, name, val): - self.__dict__[name] = val - if name == "optics_tubes": - self.__dict__.pop("ot_dict", None) + @classmethod + def load( + cls, + f: h5py.File, + path: str, + pointing_models: tuple[PointingModel, ...], + parent: Receiver, + ) -> Self: + """ + Load an optics tube from an HDF5 file. + + Parameters + ---------- + f : h5py.File + The HDF5 file object containing the optics tube. + path : str + The path within the HDF5 file where the optics tube is stored. + pointing_models : tuple[PointingModel, ...] + The pointing models used by the focal-planes. + + Returns + ------- + OpticsTube + The loaded optics tube. + """ + group = cast(h5py.Group, f[path]) + tube = cls( + name=cast(str, group.attrs["name"]), + focal_planes=[], + wafer_slots=list(np.asarray(group.attrs["wafer_slots"])), + static=cast(bool, group.attrs["static"]), + autofreeze=cast(bool, group.attrs["autofreeze"]), + parent=parent, + ) - def delete_ot(self, name): - self.focal_planes = [ot for ot in self.optics_tubes if ot.name != name] + if "cm_transform" in group: + tube._cm_transform_stat = Transform.load(f, f"{path}/cm_transform") + if "cm_transform_norx" in group: + tube._cm_transform_norx_stat = Transform.load( + f, f"{path}/cm_transform_norx" + ) + focal_planes = [] + group = cast(h5py.Group, f[path]) + for name in group: + if name in {"cm_transform", "cm_transform_norx"}: + continue + focal_planes.append( + FocalPlaneCollection.load( + f, f"{path}/{name}", pointing_models=pointing_models, parent=tube + ) + ) + tube.focal_planes = focal_planes + + return tube + + +@dataclass +class Receiver: + """ + A `Receiver` groups one or more `OpticsTube` instances and provides + methods for calculating receive common-mode transforms. The + receiver common mode captures distortions that are shared across + multiple optics tubes and can be used to separate receiver wide effects + from OT specific distortions. + + The receiver common mode is computed from the common-mode transforms of + all optics tubes that contain valid, non-padded data. If no valid + optics tubes are available, the identity transform is returned. + Note that unlike the OT common mode, we only compute a rigid transformation here. + + After computing a receiver common mode, `remove_rx_all` can be used + to propagate that common mode to all contained optics tubes, allowing + each tube to store an OT only common-mode transform in + `OpticsTube.cm_transform_norx`. + + When `static=True`, the public properties return frozen values previously + stored by `freeze`. When `static=False`, quantities are recomputed on + access. If `autofreeze=True`, newly computed values are automatically + cached into the corresponding static fields. + + Optics tubes may be accessed by name through `__getitem__`. + + Attributes + ---------- + name : str + Human-readable identifier for the receiver. + Probably just the telescope name. + epoch : str + Human-readable identifier for the epoch associated with this + data. If this spans multiple epochs they will be seperated with a '+'. + optics_tubes : list[OpticsTube] + Optics tubes associated with this receiver. + static : bool + If True, return values from the frozen static fields instead of + recomputing them. + autofreeze : bool + If True, cache dynamically computed quantities into their + corresponding static fields. + cm_transform : Transform + Receiver-level common-mode transform derived from the common-mode + transforms of all optics tubes containing valid data. + allpad : bool + (Property) Flag indicating whether all optics tube are padded + and should therefore be excluded from fitting. + """ + + name: str + epoch: str + optics_tubes: list[OpticsTube] + static: bool + autofreeze: bool + cm_transform: ClassVar[StaticOrCached[Transform]] = StaticOrCached("cm_transform") + _cm_transform_stat: Transform = field(init=False) + + def __getitem__(self, key): + ot_names = [ot.name for ot in self.optics_tubes] + if key in ot_names: + return self.optics_tubes[ot_names.index(key)] + raise IndexError(f"Invalid key: {key}") + + def find_fpc(self, ot_name: str, fp_name: str) -> Optional[FocalPlaneCollection]: + """ + Find a FocalPlaneCollection by its OpticsTube and collection names. + + Parameters + ---------- + ot_name : str + Name of the OpticsTube. + fp_name : str + Name of the FocalPlaneCollection. + + Returns + ------- + fpc : Optional[FocalPlaneCollection] + The matching focal-plane collection, or None if not found. + """ + try: + return self[ot_name][fp_name] + except IndexError: + return None + + def freeze(self, static: bool): + """ + Save the current dynamic properties to the static fields. + + Parameters + ---------- + static : bool + What to set `self.static` to after freezing. + """ + if self.allpad: + return + self.static = True + self._cm_transform_stat = self._cm_transform_dyn + self.static = static + + def thaw(self, static: bool): + """ + Clear the current values in static fields. + + Parameters + ---------- + static : bool + What to set `self.static` to after thawing. + """ + self.__dict__.pop("_cm_transform_stat", None) + self.static = static - def save(self, f, db_info, group="/"): + @property + def allpad(self) -> bool: + if len(self.optics_tubes) == 0: + return True + return bool(np.all([ot.allpad for ot in self.optics_tubes])) + + @property + def _cm_transform_dyn(self) -> Transform: + transforms = [ + ot.cm_transform.affine for ot in self.optics_tubes if ot.allpad is False + ] + shifts = [ + ot.cm_transform.shift for ot in self.optics_tubes if ot.allpad is False + ] + if len(transforms) == 0: + iden = Transform.identity() + cm_shift, cm_aff = iden.shift, iden.affine + elif len(transforms) == 1: + cm_aff, cm_shift = transforms[0], shifts[0] + else: + cm_aff, cm_shift = mt.get_common_mode( + transforms, shifts, -2, True, fast=True + ) + to_ret = Transform(cm_shift, cm_aff) + if self.autofreeze: + self._cm_transform_stat = to_ret + return to_ret + + def remove_rx_all(self): + """ + Remove the current receiver common mode from all optics tubes. + + This method calls `OpticsTube.remove_rx` for every optics tube in the + receiver using the current value of `cm_transform`. After execution, + each optics tube stores a receiver-corrected common-mode transform in + `cm_transform_norx`. + """ + for ot in self.optics_tubes: + ot.remove_rx(self.cm_transform) + + def save(self, f, path, pointing_models: tuple[PointingModel, ...], overwrite=True): + """ + Save the receiver and its optics tubes to an HDF5 file. + + Parameters + ---------- + f : h5py.File + HDF5 file object to save to. + path : str + Path within the HDF5 file at which to save the receiver. + pointing_models : tuple[PointingModel, ...] + The pointing models used by the focal-planes. + overwrite : bool, default: True + If True, overwrite an existing receiver at `path`. + + Raises + ------ + ValueError + If multiple optics tubes have the same name. + """ + group = _create_group(f, path, overwrite) _add_attrs( - f[group], + group, { - "center": self.center, - "center_transformed": self.center_transformed, - "include_cm": self.include_cm, - "valid_ids": self.valid_ids, + "name": self.name, + "epoch": self.epoch, + "static": self.static, + "autofreeze": self.autofreeze, }, ) - self.transform.save(f, os.path.join(group, "transform")) + if "_cm_transform_stat" in self.__dict__: + self._cm_transform_stat.save(f, f"{path}/cm_transform") + names = [ot.name for ot in self.optics_tubes] + if len(names) != len(set(names)): + raise ValueError("Optics tube names must be unique") for ot in self.optics_tubes: - ot.save(f, db_info, group) + ot.save(f, f"{path}/{ot.name}", pointing_models, overwrite=overwrite) @classmethod - def load(cls, f, group="/"): - center = f[group].attrs["center"] - include_cm = f[group].attrs["include_cm"] - valid_ids = f[group].attrs.get("valid_ids", []) - if len(valid_ids) == 0: - logger.warning("valid_ids list is empty! May be an old Receiver object!") - transform = Transform.load(f[group]["transform"]) - ots = [ - OpticsTube.load(f[group][grp], include_cm) - for grp in f[group].keys() - if "transform" not in grp + def load( + cls, f: h5py.File, path: str, pointing_models: tuple[PointingModel, ...] + ) -> Self: + """ + Load a receiver from an HDF5 file. + + Parameters + ---------- + f : h5py.File + The HDF5 file object containing the optics tube. + path : str + The path within the HDF5 file where the optics tube is stored. + pointing_models : tuple[PointingModel, ...] + The pointing models used by the focal-planes. + + Returns + ------- + Receiver + The loaded receiver. + """ + group = cast(h5py.Group, f[path]) + name = cast(str, group.attrs["name"]) + epoch = cast(str, group.attrs["epoch"]) + static = cast(bool, group.attrs["static"]) + autofreeze = cast(bool, group.attrs["autofreeze"]) + receiver = cls( + name=name, + epoch=epoch, + optics_tubes=[], + static=static, + autofreeze=autofreeze, + ) + + if "cm_transform" in group: + receiver._cm_transform_stat = Transform.load(f, f"{path}/cm_transform") + optics_tubes = [ + OpticsTube.load(f, f"{path}/{ot_name}", pointing_models, receiver) + for ot_name in group.keys() + if ot_name != "cm_transform" ] + receiver.optics_tubes = optics_tubes - return Receiver(ots, center, include_cm, list(valid_ids), transform) + return receiver - @classmethod - def load_file(cls, path): - with h5py.File(path, "r") as f: - # Check if its an old file: - if "transform" in f.keys(): - return {"": cls.load(f)} - return {grp: cls.load(f, grp) for grp in f.keys()} + +@dataclass +class PointingSystem: + """ + Collection of epoch-dependent pointing models and receiver data. + + A `PointingSystem` combines an observing era, a collection of pointing + models, and the corresponding receiver-level focal-plane data. It provides + a unified interface for managing pointing model parameters, evaluating + focal-plane residuals, calculating common-mode transforms, and optimizing + the complete pointing solution. + + Pointing model parameters are managed through `parameter_names` and + `parameter_map`. These define the independent parameters of the system + and specify which pointing models each parameter applies to. A parameter + may be shared across multiple epochs or restricted to a subset of epochs. + Nuisance parameters are managed separately through `NuisanceParams`. + + The receiver data are organized hierarchically: + `PointingSystem -> Receiver -> OpticsTube -> FocalPlaneCollection -> FocalPlane`. + + The system provides two objective functions for optimization: + + - `objective` evaluates the total chi-squared, including regularization + of receiver common-mode transforms. + - `objective_resid` returns the corresponding residual vector, allowing + least-squares optimizers to operate directly on the residuals. + + + Attributes + ---------- + era : epochs.Era + Collection of observing epochs represented by the system. + pointing_models : tuple[PointingModel, ...] + Pointing model associated with each epoch or epoch group. The ordering + must be consistent with the receiver and epoch organization. + receivers : tuple[Receiver, ...] + Receiver and focal-plane data associated with each epoch or epoch + group. Each receiver contains its associated optics tubes and + focal-plane collections. + nuisance_params : NuisanceParams + Additional nuisance parameters used by the pointing models. These + parameters are managed separately from the primary pointing model + parameters. + parameter_names : tuple[str, ...] + Names of the independent pointing model parameters. Names without + parentheses represent parameters shared across all applicable epochs. + Names with parentheses identify parameters restricted to the epochs + listed within the parentheses. + parameter_map : tuple[Integer[np.ndarray, "?npar"], ...] + Mapping between independent parameters and the indices of the + pointing models to which they apply. Each entry corresponds to the + parameter with the same index in `parameter_names`. + calender_str : str + Serialized calendar YAML string used to reconstruct the observing + calendar and associated era. + state_meta : dict[str, str] + String-based metadata associated with the current system state. + Used to preserve provenance and support subsequent data forensics. + parameters : Float[np.ndarray, "npar"] + (Property) Current values of the independent pointing model parameters. + Values are extracted from the corresponding pointing models according + to `parameter_map`. + parameters_full : Float[np.ndarray, "n"] + (Property) Concatenation of the independent pointing model parameters and the + flattened nuisance parameter values. + n_data : int + (Property) Total number of residual measurements included in the system, + excluding padded focal-plane collections. + residuals : Float[np.ndarray, "n_data"] + (Property) Concatenated residual vector from all non-padded focal-plane collections. + chisq : float + (Property) Total chi-squared of the system, calculated from the residuals of + all non-padded focal-plane collections. Does not include the + receiver common-mode regularization penalty applied by `objective`. + """ + + era: epochs.Era + pointing_models: tuple[PointingModel, ...] + receivers: tuple[Receiver, ...] + nuisance_params: NuisanceParams + parameter_names: tuple[str, ...] + parameter_map: tuple[Integer[np.ndarray, "?npar"], ...] + calender_str: str + state_meta: dict[str, str] + _residual_buffer: Float[np.ndarray, "n_data"] = field(init=False) + + def __post_init__(self): + # Force consistancy + self.update_parameters(self.parameters) @property - def focal_planes(self): - fps = [] - for ot in self.optics_tubes: - fps += ot.focal_planes - return fps + def parameters_full(self) -> Float[np.ndarray, "n"]: + return np.hstack((self.parameters, self.nuisance_params.params_flat)) + + def set_static(self, static: bool): + """ + Set `static` for all relevent childen. + + Parameters + ---------- + static : bool + The value to set `static` to for all relevent children. + """ + for rx in self.receivers: + rx.static = static + for ot in rx.optics_tubes: + ot.static = static + for fp in ot.focal_planes: + fp.static = static + for meas in fp.focal_planes: + meas.static = static + + def set_freeze(self, static: bool, optimizer: bool = False): + """ + Run freeze for all relevent childen. + + Parameters + ---------- + static : bool + The value to set `static` to for all relevent children. + """ + for rx in self.receivers: + for ot in rx.optics_tubes: + for fp in ot.focal_planes: + for meas in fp.focal_planes: + meas.freeze(True, optimizer) + fp.freeze(True) + ot.freeze(True) + rx.freeze(True) + self.set_static(static) + + def set_thaw(self, static: bool, thaw_meas: Optional[list[str]] = None): + """ + Run thaw for all relevent childen. + + Parameters + ---------- + static : bool + The value to set `static` to for all relevent children. + """ + for rx in self.receivers: + for ot in rx.optics_tubes: + for fp in ot.focal_planes: + for meas in fp.focal_planes: + if thaw_meas is not None and meas.meas_id not in thaw_meas: + continue + meas.thaw(static) + fp.thaw(static) + ot.thaw(static) + rx.thaw(static) + + def warm_pm_data(self, executor: Executor): + """ + Warm up the `FocalPlane.pm_data` cache in parallel. + This will set `_pm_data_stat` to the output of `_pm_data_dyn` + for all `FocalPlane`s, overwriting whatever the current cached static + value is regardless of if `FocalPlane.static` is `True` or if it was recently + frozen on thawed. + + This should be used with caution. + + Parameters + ---------- + executor : Executor + Executor used to evaluate `_pm_data_dyn` concurrently. + Doesn't need to be from `concurrent.futures` but must + implement a compatible API. + """ + all_meas = [ + meas + for rx in self.receivers + for ot in rx.optics_tubes + for fp in ot.focal_planes + for meas in fp.focal_planes + ] - @cached_property - def ot_dict(self): - return {ot.name: ot for ot in self.optics_tubes} + # futures = [ + # executor.submit(_get_pm, meas) + # for meas in all_meas + # ] + # wait(futures) + + # for meas, future in zip(all_meas, futures): + # meas._pm_data_stat = future.result() + + results = executor.map(_get_pm, all_meas) + + for meas, pm_data in zip(all_meas, results): + meas._pm_data_stat = pm_data + + @property + def parameters(self) -> Float[np.ndarray, "npar"]: + return np.array( + [ + self.pointing_models[par_map[0]].parameters[par.split("(")[0]] + for par, par_map in zip(self.parameter_names, self.parameter_map) + ] + ) + + def update_parameters(self, new_pars: Float[np.ndarray, "npar"]): + """ + Update the pointing model and nuisance parameter values. + + The independent pointing model parameters are distributed to the + corresponding `PointingModel` instances according to `parameter_map`. + Parameters mapped to multiple pointing models are updated consistently + across all associated epochs. + + If additional values are provided beyond the independent pointing + model parameters, they are passed to `NuisanceParams.update`. + + Updating parameters modifies the underlying `PointingModel` instances + and `NuisanceParams` in place. It does not explicitly freeze or thaw + the derived quantities of the pointing system. + + Parameters + ---------- + new_pars : Float[np.ndarray, "npar"] + New parameter values. The first `len(parameter_names)` entries + correspond to the independent pointing model parameters. Any + remaining entries correspond to the flattened nuisance parameters. + """ + npar = len(self.parameter_names) + if len(new_pars) < npar: + raise ValueError( + f"Expected at least {npar} parameters, got {len(new_pars)}" + ) + if len(new_pars) > npar + len(self.nuisance_params.params_flat): + raise ValueError("Too many parameters supplied") + + for val, par, par_map in zip( + new_pars[:npar], self.parameter_names, self.parameter_map + ): + name = par.split("(")[0] + for idx in par_map: + self.pointing_models[idx].parameters[name] = val + if npar < len(new_pars): + self.nuisance_params.update(new_pars[npar:]) @property - def lims(self): - xmax = np.max([np.nanmax(fp.transformed[:, 0]) for fp in self.focal_planes]) - xmin = np.min([np.nanmin(fp.transformed[:, 0]) for fp in self.focal_planes]) - ymax = np.max([np.nanmax(fp.transformed[:, 1]) for fp in self.focal_planes]) - ymin = np.min([np.nanmin(fp.transformed[:, 1]) for fp in self.focal_planes]) - return (xmin, xmax), (ymin, ymax) + def n_data(self) -> int: + n = 0 + for rx in self.receivers: + for ot in rx.optics_tubes: + for fp in ot.focal_planes: + if fp.pad: + continue + n += fp.ndet * fp.nobs + return n @property - def fp_valid_ids(self): - valid_ids = [] - for fp in self.focal_planes: - if fp.template is None: - continue - valid_ids += list(fp.template.valid_ids) - valid_ids = np.unique(valid_ids) - return valid_ids.tolist() - - -# Plotting Functions -def plot_ufm(focal_plane, plot_dir): - nominal = focal_plane.template_fp - measured = focal_plane.avg_fp - transformed = focal_plane.transformed - fig, (ax1, ax2) = plt.subplots(1, 2, constrained_layout=True) - # Plot pointing - ax1.scatter( - nominal[:, 0], - nominal[:, 1], - alpha=0.4, - color="blue", - label="nominal", - marker="P", - ) - ax1.scatter( - transformed[:, 0], - transformed[:, 1], - alpha=0.4, - color="black", - label="transformed", - marker="X", - ) - ax1.scatter(measured[:, 0], measured[:, 1], alpha=0.4, color="orange", label="fit") - ax1.set_xlabel("Xi (rad)") - ax1.set_ylabel("Eta (rad)") - ax1.set_aspect("equal") - ax1.legend() - - # Histogram of differences - dist = focal_plane.dist[focal_plane.isfinite] * 180 * 60 * 60 / np.pi - dist_thresh = np.percentile(dist, 97) - bins = max(int(len(dist) / 20), 10) - ax2.hist(dist[dist < dist_thresh], bins=bins) - ax2.set_xlabel("Residual (arcseconds)") - - fig.suptitle(f"{focal_plane.stream_id}") - fig.set_size_inches(2 * fig.get_size_inches()) - if plot_dir is None: - plt.show() - else: - os.makedirs(plot_dir, exist_ok=True) - plt.savefig( - os.path.join(plot_dir, f"{focal_plane.stream_id}.png"), bbox_inches="tight" - ) - plt.close() - - -def plot_ot(ot, plot_dir): - fig, (ax1, ax2) = plt.subplots(1, 2, constrained_layout=True) - dists = [ - fp.dist[fp.isfinite] * 180 * 60 * 60 / np.pi - for fp in ot.focal_planes - if fp.tot_weight is not None - ] - xis = [ - fp.transformed[fp.isfinite, 0] - for fp in ot.focal_planes - if fp.tot_weight is not None - ] - etas = [ - fp.transformed[fp.isfinite, 1] - for fp in ot.focal_planes - if fp.tot_weight is not None - ] - - # Plot the radial dist - r = np.sqrt(np.hstack(xis) ** 2 + np.hstack(etas) ** 2) - dist = np.hstack(dists) - dist_avg, edges, _ = binned_statistic(r, dist, "median", bins=50) - r_bins = (edges[:-1] + edges[1:]) / 2 - max_dist = np.max(dist) - - ax1.scatter(r, dist, alpha=0.1) - ax1.plot(r_bins, dist_avg, color="black") - ax1.set_ylim((None, np.percentile(dist, 95))) - ax1.set_xlabel("Radius (rad)") - ax2.set_ylabel("Residual (arcseconds)") - - # Plot a heatmap - cf = None - for dist, xi, eta in zip(dists, xis, etas): - cf = ax2.tricontourf( - xi, eta, dist, levels=20, vmin=-1 * max_dist, vmax=max_dist, cmap="coolwarm" - ) - if cf is not None: - fig.colorbar(cf, ax=ax2, label="arcseconds") - ax2.set_aspect("equal") - ax2.set_xlabel("Xi (rad)") - ax2.set_ylabel("Eta (rad)") - fig.suptitle(f"{ot.name}") - - fig.set_size_inches(2 * fig.get_size_inches()) - if plot_dir is None: - plt.show() - else: - os.makedirs(plot_dir, exist_ok=True) - plt.savefig(os.path.join(plot_dir, f"{ot.name}.png"), bbox_inches="tight") - plt.close() - - -def plot_by_gamma(focal_plane, plot_dir): - fig, axs = plt.subplots(1, 3, sharey=True, constrained_layout=True) - dist_thresh = np.percentile(focal_plane.dist[focal_plane.isfinite], 97) - msk = (focal_plane.dist < dist_thresh) + focal_plane.isfinite - rhombi = np.unique(focal_plane.template.rhombus) - gammas = (focal_plane.template.fp[msk, 2] * 180 / np.pi) % 180.0 - bins = np.linspace(0, 180, 13) - for i, name in enumerate(("xi", "eta", "gamma")): - d = focal_plane.diff[msk, i] * 180 * 60 * 60 / np.pi - axs[i].set_title(name) - if np.sum(np.isfinite(d)) == 0: - continue - medians, *_ = binned_statistic(gammas, d, statistic="median", bins=bins) - for rhombus in rhombi: - rmsk = focal_plane.template.rhombus[msk] == rhombus - if not (np.any(rmsk)): - continue - axs[i].scatter(gammas[rmsk], d[rmsk], alpha=0.2, label=f"Rhombus {rhombus}") - axs[i].scatter(np.arange(7.5, 180, 15), medians, color="black") - leg = axs[i].legend() - for lh in leg.legend_handles: - lh.set_alpha(1) - axs[0].set_ylabel("Diff (arcseconds)") - axs[1].set_xlabel("Nominal Gamma (deg)") - fig.suptitle(f"{focal_plane.stream_id} By Gamma") - fig.set_size_inches(2 * fig.get_size_inches()) - if plot_dir is None: - plt.show() - else: - os.makedirs(plot_dir, exist_ok=True) - plt.savefig( - os.path.join(plot_dir, f"{focal_plane.stream_id}_by_gamma.png"), - bbox_inches="tight", - ) - plt.close() - - -def plot_receiver(receiver, plot_dir): - valid_ids = receiver.valid_ids - max_diff = 0 - for fp in receiver.focal_planes: - diff = np.nanpercentile(np.abs(fp.diff), 97) - if diff > max_diff: - max_diff = diff - max_diff *= 180 * 60 * 60 / np.pi - xlims, ylims = receiver.lims - - fig, axs_all = plt.subplots( - len(valid_ids), 3, sharex="col", sharey="row", constrained_layout=True - ) - axs = axs_all.flat - axs[0].set_title("Xi") - axs[1].set_title("Eta") - axs[2].set_title("Gamma") - cf = None - for i in range(len(valid_ids)): - for j in range(3): - axs[3 * i + j].set_aspect("equal") - axs[3 * i + j].set_xlim(xlims) - axs[3 * i + j].set_ylim(ylims) - for fp in receiver.focal_planes: - if fp.tot_weight is None: - continue - msk = (fp.id_strs == valid_ids[i]) * fp.isfinite - if np.sum(msk) < 3: - continue - diff = fp.diff * 180 * 60 * 60 / np.pi - cf = axs[3 * i + 0].tricontourf( - fp.transformed[msk, 0], - fp.transformed[msk, 1], - diff[msk, 0], - levels=20, - vmin=-1 * max_diff, - vmax=max_diff, - cmap="coolwarm", + def residuals(self) -> Float[np.ndarray, "n_data"]: + n_data = self.n_data + if "_residual_buffer" in self.__dict__ and len(self._residual_buffer) == n_data: + resid = self._residual_buffer + else: + resid = np.empty(n_data) + self._residual_buffer = resid + i = 0 + for rx in self.receivers: + for ot in rx.optics_tubes: + for fp in ot.focal_planes: + if fp.pad: + continue + fpr = fp.residuals + resid[i : (i + len(fpr))] = fpr + i += len(fpr) + if i != n_data: + raise RuntimeError(f"Residual size mismatch: expected {n_data}, got {i}") + return resid + + @property + def chisq(self) -> float: + chisq = 0.0 + for rx in self.receivers: + for ot in rx.optics_tubes: + for fp in ot.focal_planes: + if fp.pad: + continue + chisq += fp.chisq + return chisq + + def objective( + self, + params: Float[np.ndarray, "npar"], + nresid: int, + cm_fac: float, + executor: Executor, + thaw_meas=None, + ) -> float: + """ + Evaluate the total chi-squared objective function. + + Updates the pointing model and nuisance parameters, thaws the + derived quantities throughout the pointing system, and evaluates + the total focal-plane chi-squared. + + A regularization penalty is added for the receiver common-mode + transforms to discourage receiver-wide distortions. The penalty + includes the translational and rotational components of each + receiver common mode. + + If a `RuntimeError` or `AssertionError` occurs during evaluation, + a large objective value of `1e6` is returned to indicate an + unsuccessful evaluation. + + Parameters + ---------- + params : Float[np.ndarray, "npar"] + Parameter values to evaluate, including nuisance parameters + when applicable. + nresid : int + Number of residual measurements used to scale the common-mode + regularization penalty. + cm_fac : float + Multiplicative factor controlling the strength of the + common-mode regularization penalty. + executor : Executor + Executor used to evaluate `_pm_data_dyn` concurrently. + See `warm_pm_data` for details. + + Returns + ------- + objective : float + Total objective value, consisting of the focal-plane chi-squared + and the receiver common-mode regularization penalty. + """ + print(".", end="", flush=True) + self.update_parameters(params) + self.set_thaw(True, thaw_meas) + self.warm_pm_data(executor) + try: + chisq = self.chisq + if np.isfinite(chisq): + for rx in self.receivers: + chisq += ( + np.sum((cm_fac * nresid * rx.cm_transform.shift) ** 2) + + (cm_fac * nresid * rx.cm_transform.rot) ** 2 + ) + return chisq + except (RuntimeError, AssertionError): + return 1e6 + + def objective_resid( + self, + params: Float[np.ndarray, "npar"], + nresid: int, + cm_fac: float, + executor: Executor, + thaw_meas=None, + ) -> Float[np.ndarray, "nresid_full"]: + """ + Evaluate the residual vector used by least-squares optimization. + + Updates the pointing model and nuisance parameters, thaws the + derived quantities throughout the pointing system, and evaluates + the focal-plane residuals. + + Receiver common-mode shifts and rotations are appended to the + residual vector as regularization terms. These terms penalize + receiver-wide distortions and are scaled by `cm_fac` and `nresid`. + + If a `RuntimeError` or `AssertionError` occurs during evaluation, + an array filled with `1e3` is returned. + + Parameters + ---------- + params : Float[np.ndarray, "npar"] + Parameter values to evaluate, including nuisance parameters + when applicable. + nresid : int + Number of focal-plane residual measurements used to scale the + common-mode regularization terms. Also determines the length + of the fallback residual vector if evaluation fails. + cm_fac : float + Multiplicative factor controlling the strength of the + common-mode regularization terms. + executor : Executor + Executor used to evaluate `_pm_data_dyn` concurrently. + See `warm_pm_data` for details. + + Returns + ------- + objective_resid : Float[np.ndarray, "nresid"] + Concatenated residual vector containing the focal-plane + residuals followed by the receiver common-mode shift and + rotation regularization terms. + """ + print(".", end="", flush=True) + self.update_parameters(params) + self.set_thaw(True, thaw_meas) + self.warm_pm_data(executor) + try: + resid = [ + self.residuals, + ] + for rx in self.receivers: + resid += [ + (cm_fac * nresid * rx.cm_transform.shift).ravel(), + np.atleast_1d(cm_fac * nresid * rx.cm_transform.rot).ravel(), + ] + return np.hstack(resid) + except (RuntimeError, AssertionError): + return np.full(nresid, 1e3) + + def log_prob( + self, + params: Float[np.ndarray, "npar"], + nresid: int, + cm_fac: float, + executor: Executor, + ) -> float: + """ + Calculate the log probability of the current parameter values. + + This is defined as -0.5 times the objective function evaluated + at the supplied parameters. + + Parameters + ---------- + params : Float[np.ndarray, "npar"] + Parameter values to evaluate. + nresid : int + Number of residuals used to scale the common-mode penalty. + cm_fac : float + Scaling factor applied to the common-mode penalty. + executor : Executor + Executor used to evaluate `_pm_data_dyn` concurrently. + See `warm_pm_data` for details. + + Returns + ------- + log_prob : float + Log probability of the supplied parameter values. + """ + return -0.5 * self.objective(params, nresid, cm_fac, executor, None) + + @overload + def search( + self, field: Literal["pointing_models"], timestamp: float + ) -> Optional[PointingModel]: ... + + @overload + def search( + self, field: Literal["receivers"], timestamp: float + ) -> Optional[Receiver]: ... + + def search( + self, field: Literal["pointing_models", "receivers"], timestamp: float + ) -> Optional[PointingModel | Receiver]: + """ + Get the first object associated with a specifc timestamp. + + Parameters + ---------- + field: Literal["pointing_models", "receivers"] + The field to search in. + Valid options are: "receivers" and "pointing_models". + timestamp : float + The time to search for. + + Returns + ------- + found : Optional[PointingModel | Receiver] + The first matching Epoch. + Will be None if no matches are found. + """ + if field not in ["pointing_models", "receivers"]: + raise ValueError(f"Invalud field to search in: {field}.") + dat = getattr(self, field) + epoch = self.era.find_epoch(timestamp) + if epoch is None: + return None + hits = [d for d in dat if epoch.name in d.epoch] + if len(hits) == 0: + return None + return hits[0] + + def set_pad(self, pad_epochs: list[str], pad_empty: bool): + """ + Set the padding status of pointing models and focal planes. + + Padding is enabled for pointing models and receiver associated + with epochs specified in `pad_epochs`. + If `pad_empty`` is True empty focal planes are also padded, + regardless of their receiver's epoch. + + Parameters + ---------- + pad_epochs : list of str + Epoch identifiers for which padding should be enabled. + pad_empty : bool + If True, enable padding for focal planes collections that + contain no focal planes. + """ + for pm in self.pointing_models: + pm.pad = pm.epoch in pad_epochs + for rx in self.receivers: + pad = rx.epoch in pad_epochs + for ot in rx.optics_tubes: + for fp in ot.focal_planes: + fp.pad = pad or (pad_empty and (len(fp.focal_planes) == 0)) + + def load_pm_from_mdb(self, mdb: ManifestDb): + """ + Load pointing model parameters from a ManifestDb into the current era. + + This method retrieves pointing model parameters for each epoch defined in + `self.era.epochs` from the provided ManifestDb, validates that the database + schema is compatible, and assigns the loaded parameters to + `self.pointing_models`. The checks performed are: + + * The ManifestDb must use a supported scheme with required params + ['obs:timestamp']. + * Each epoch's covering intervals must all resolve to the same database + match. + * A pointing model must exist for every epoch. + + + Note that here we also assume that the loaded pointing model has a flat structure + where each element is a scalar that maps to a pointing model parameter. + Note also here that for pointing models that join multiple epochs we use + the value from the latest epoch. + + Parameters + ---------- + mdb : ManifestDb + Database object containing pointing model data indexed by + 'obs:timestamp'. + + Raises + ------ + ValueError + If the ManifestDb scheme is unsupported. + If no database matches are found for an epoch. + If different intervals within an epoch resolve to inconsistent matches. + """ + loader = SuperLoader() + mspec = MetadataSpec.from_dict({"db": mdb, "unpack": "pointing_model"}) + if mdb.scheme.get_required_params() != ["obs:timestamp"]: + raise ValueError("Unsupported scheme for pointing model db!") + for epoch in self.era.epochs: + matches = [] + for interval in epoch.covers: + matches += [ + mdb.match({"obs:timestamp": interval.start}), + mdb.match({"obs:timestamp": interval.stop - 1}), + ] + if len(matches) == 0: + raise ValueError(f"No matches for epoch: {str(epoch)}") + if not all(x == matches[0] for x in matches): + raise ValueError( + f"Not all intervals have the same match in epoch: {str(epoch)}" + ) + pm_aman = loader.load_one( + mspec, {"obs:timestamp": epoch.covers[0].start}, [] ) - cf = axs[3 * i + 1].tricontourf( - fp.transformed[msk, 0], - fp.transformed[msk, 1], - diff[msk, 1], - levels=20, - vmin=-1 * max_diff, - vmax=max_diff, - cmap="coolwarm", + pm_dict = {key: pm_aman[key] for key in pm_aman.keys()} + pm = self.search("pointing_models", epoch.covers[0].start) + if pm is None: + raise ValueError( + f"Can't find pointing model for this epoch: {epoch.name}" + ) + pm.parameters = pm_dict + # Force consistancy + self.update_parameters(self.parameters) + + @classmethod + def empty(cls, era: epochs.Era, cfg: Namespace, calender_str: str) -> Self: + """ + Create an empty pointing system from an observing era. + + This initializes a `PointingModel` and `Receiver` for each epoch, + with empty focal-plane data constructed from the epoch's + `ws_mapping`. Pointing models and receivers are then combined + according to the configured epoch groups. + + Parameters + ---------- + era : epochs.Era + Era containing the epochs used to construct the pointing system. + Each epoch must contain consistent `ws_mapping` data. + cfg : Namespace + Configuration containing the receiver name, epoch groups, + pointing model settings, and focal plane options. + calender_str : str + A serialized calendar yaml string. + + Returns + ------- + pointing_system : PointingSystem + A pointing system containing the initialized pointing models + and receivers. + + Raises + ------ + ValueError + If `era` has missing or inconsistent `ws_mapping` data. + If any groups contain overlapping epochs. + If any groups contais an unknown epoch. + If an unknown pointing model parameter is passed. + """ + if not era.check_data("ws_mapping", True): + raise ValueError( + "Era is either missing or has inconsistent values for ws_mapping" ) - if fp.have_gamma: - cf = axs[3 * i + 2].tricontourf( - fp.transformed[msk, 0], - fp.transformed[msk, 1], - diff[msk, 2], - levels=20, - vmin=-1 * max_diff, - vmax=max_diff, - cmap="coolwarm", + nuisance_params = NuisanceParams({}, [], []) + rxs = [] + pms = [] + for epoch in era.epochs: + pms += [ + PointingModel( + epoch.name, {}, nuisance_params, cfg.force_zero_roll, False ) - axs[3 * i + 0].set_ylabel(f"{valid_ids[i]}\nEta (rad)") - if cf is not None: - fig.colorbar(cf, ax=axs_all.ravel().tolist(), label="arcsecs") - axs[-3].set_xlabel("Xi (rad)") - axs[-2].set_xlabel("Xi (rad)") - axs[-1].set_xlabel("Xi (rad)") - fig.suptitle("Full Receiver Residuals") - fig.set_size_inches(2 * fig.get_size_inches()) - if plot_dir is None: - plt.show() - else: - os.makedirs(plot_dir, exist_ok=True) - plt.savefig(os.path.join(plot_dir, f"receiver.png"), bbox_inches="tight") - plt.close() + ] + ws_map = epoch.covers[0].data["ws_mapping"] + ots = [] + for ot, arrays in ws_map.items(): + fps = [] + for _, (_, ufm) in arrays.items(): + fps += [ + FocalPlaneCollection( + ufm, + [], + DetectorOffsets.empty("xieta"), + DetectorOffsets.empty("fp"), + DetectorOffsets.empty("ot"), + False, + False, + True, + cfg.fake_gamma, + ) + ] + ots += [OpticsTube(ot, fps, list(arrays.keys()), False, False)] + rxs += [Receiver(cfg.tel, epoch.name, ots, False, False)] + + def _group_epochs(dat, groups, desc, check_fields): + if len(groups) == 0: + return dat + u, c = np.unique(np.concatenate(groups), return_counts=True) + ng = [d for d in dat if d.epoch not in u] + + if np.any(c > 1): + raise ValueError(f"Some {desc} groups have overlapping epochs!") + + ga = [] + for grp in groups: + if len(grp) == 0: + continue + for field in check_fields: + good = reduce( + epochs.OP_MAP["&"], + [ + e.check_data(field, True) + for e in era.epochs + if e.name in grp + ], + ) + if good: + allf = [ + e._internal.data[field] for e in era.epochs if e.name in grp + ] + good = all(x == allf[0] for x in allf) + if not good: + raise ValueError( + f"Inconsistent {field} values in {desc} group {grp}" + ) + in_group = [d for d in dat if d.epoch in grp] + if len(in_group) < len(grp): + raise ValueError(f"Unknown epoch in {desc} group {grp}") + new = in_group[0] + new.epoch = "+".join(d.epoch for d in in_group) + ga.append(new) + + return ng + ga + + rxs = _group_epochs(rxs, cfg.rx_groups, "receiver", ["ws_mapping"]) + pms = _group_epochs(pms, cfg.pm_groups, "pointing model", []) + + par_names = [] + for pm in pms: + pm_ver = cfg.pm_ver_override.get(pm.epoch, cfg.pm_ver) + pars = deepcopy(param_defaults[pm_ver]) + pars.update(cfg.pm_defaults_overrides[pm_ver]) + par_names += [ + name + for name, val in pars.items() + if isinstance(val, (int, float, np.number)) + ] + pars["version"] = pm_ver + pm.parameters = pars + par_names = np.unique(par_names).tolist() + par_map = [np.arange(len(pms), dtype=int).tolist() for _ in par_names] + pm_epochs = [pm.epoch for pm in pms] + par: str + for par, groups in cfg.par_groups.items(): + if par not in par_names: + raise ValueError(f"Unknown parameter {par}") + u, c = np.unique(np.concatenate(groups), return_counts=True) + if np.any(c > 1): + raise ValueError(f"Overlapping epochs in par group for {par}") + if np.any(~np.isin(u, pm_epochs)): + raise ValueError(f"Unknown epoch in par_group for {par}") + par_idx = par_names.index(par) + for grp in groups: + epc_idxs = [pm_epochs.index(epc) for epc in grp] + par_map[par_idx] = [i for i in par_map[par_idx] if i not in epc_idxs] + par_names += [par + "(" + ",".join(grp) + ")"] + par_map += [[epc_idxs]] + n_mapped = [len(pmap) for pmap in par_map] + par_names = tuple(name for name, n in zip(par_names, n_mapped) if n > 0) + par_map = tuple(np.array(pmap) for pmap, n in zip(par_map, n_mapped) if n > 0) + + return cls( + era, + tuple(pms), + tuple(rxs), + nuisance_params, + par_names, + par_map, + calender_str, + {}, + ) + + def set_pm_to_defaults(self, cfg): + params = self.parameters.copy() + def_pars = [] + for pm in self.pointing_models: + pm_ver = cfg.pm_ver_override.get(pm.epoch, cfg.pm_ver) + pars = deepcopy(param_defaults[pm_ver]) + pars.update(cfg.pm_defaults_overrides[pm_ver]) + def_pars += [pars] + for i, (p_idx, name) in enumerate( + zip(self.parameter_map, self.parameter_names) + ): + pars = def_pars[p_idx[0]] + par_name = name.split("(")[0] + params[i] = pars[par_name] + self.update_parameters(params) + + def save(self, f: h5py.File, path: str, overwrite: bool = True): + """ + Save the pointing system to an HDF5 file. + + The receiver-to-pointing-model relationship is stored explicitly as + an integer array. Element `i` of `receiver_pointing_model` gives + the index of the pointing model that should be passed to + `Receiver.load` for receiver `i`. + + Parameters + ---------- + f : h5py.File + Open HDF5 file to save to. + path : str + Path within the HDF5 file at which to save the pointing system. + overwrite : bool, default: True + Whether to overwrite an existing pointing system at ``path``. + + Raises + ------ + ValueError + If there are no pointing models but receivers are present. + If a receiver cannot be associated with a pointing model. + """ + group = _create_group(f, path, overwrite=overwrite) + _add_attrs( + group, + { + "calender_str": self.calender_str, + "era": self.era.name, + }, + ) + state_group = _create_group(f, f"{path}/state", overwrite=overwrite) + _add_attrs(state_group, self.state_meta) + _ = _create_group(f, f"{path}/pointing_models", overwrite=overwrite) + self.nuisance_params.save(f, f"{path}/nuisance", overwrite=overwrite) + for idx, pointing_model in enumerate(self.pointing_models): + pointing_model.save( + f, + f"{path}/pointing_models/{idx}_{pointing_model.epoch}", + overwrite=overwrite, + ) + _ = _create_group(f, f"{path}/receivers", overwrite=overwrite) + for rx_idx, receiver in enumerate(self.receivers): + receiver.save( + f, + f"{path}/receivers/{rx_idx}_{receiver.name}_{receiver.epoch}", + self.pointing_models, + overwrite=overwrite, + ) + group.attrs["parameter_names"] = np.asarray( + self.parameter_names, dtype=h5py.string_dtype() + ) + parameter_map_group = cast( + h5py.Group, _create_group(f, f"{path}/parameter_map", overwrite=overwrite) + ) + for idx, par_map in enumerate(self.parameter_map): + parameter_map_group.create_dataset( + str(idx), data=np.asarray(par_map, dtype=np.int64) + ) + + @classmethod + def load(cls, f: h5py.File, path: str) -> Self: + """ + Load a pointing system from an HDF5 file. + + Parameters + ---------- + f : h5py.File + Open HDF5 file containing the pointing system. + path : str + Path within the HDF5 file containing the pointing system. + + Returns + ------- + PointingSystem + The reconstructed pointing system. + """ + group = f[path] + calender_str = cast(str, group.attrs["calender_str"]) + era_str = cast(str, group.attrs["era"]) + cal = epochs.Calendar.load(calender_str) + era = cal.eras[era_str] + parameter_names = tuple( + str(name) for name in cast(Iterable[object], group.attrs["parameter_names"]) + ) + state_group = f[f"{path}/state"] + state_meta = {key: val for key, val in state_group.attrs.items()} + + parameter_map_group = cast(h5py.Group, f[f"{path}/parameter_map"]) + parameter_map = tuple( + np.asarray(parameter_map_group[name], dtype=np.int64) + for name in sorted(parameter_map_group.keys()) + ) + + if f"{path}/nuisance" in f: + nuisance_params = NuisanceParams.load(f, f"{path}/nuisance") + else: + nuisance_params = NuisanceParams({}, [], []) + pm_group = cast(h5py.Group, f[f"{path}/pointing_models"]) + pointing_models = tuple( + PointingModel.load(f, f"{path}/pointing_models/{name}", nuisance_params) + for name in sorted(pm_group.keys()) + ) + + rx_group = cast(h5py.Group, f[f"{path}/receivers"]) + receivers = tuple( + Receiver.load(f, f"{path}/receivers/{name}", pointing_models) + for name in sorted(rx_group.keys()) + ) + + return cls( + era=era, + pointing_models=pointing_models, + receivers=receivers, + nuisance_params=nuisance_params, + parameter_names=parameter_names, + parameter_map=parameter_map, + calender_str=calender_str, + state_meta=state_meta, + ) diff --git a/sotodlib/coords/fp_plots.py b/sotodlib/coords/fp_plots.py new file mode 100644 index 000000000..42a969681 --- /dev/null +++ b/sotodlib/coords/fp_plots.py @@ -0,0 +1,1190 @@ +import os +from copy import deepcopy +from typing import Optional + +import matplotlib as mpl +import matplotlib.pyplot as plt +import numpy as np +from matplotlib.cm import ScalarMappable +from matplotlib.colors import Normalize +from scipy.stats import binned_statistic + +from .fp_containers import ( + DetectorOffsets, + FocalPlane, + FocalPlaneCollection, + NuisanceParams, + OpticsTube, + Receiver, +) + + +def plot_detector_offsets( + ax: mpl.axes._axes.Axes, # type: ignore + offsets: DetectorOffsets, + text: Optional[str] = None, + fontsize: int = 16, + **scatter_kwargs, +): + """ + Plot detector offsets on an existing axes. + + Parameters + ---------- + ax : mpl.axes.Axes + Axes on which to plot. + offsets : DetectorOffsets + Detector offsets to plot. + text: Optional[str], default: None + Label used for the detector group. + Will be overlayed at the center of the array. + fontsize : int, default=16 + Font size for the group label. + **scatter_kwargs + kwargs to pass to scatter. + + Returns + ------- + matplotlib.collections.PathCollection + The scatter plot artist. + """ + scatter = ax.scatter(offsets.xyz[:, 0], offsets.xyz[:, 1], **scatter_kwargs) + if text is not None: + x0 = np.nanmedian(offsets.xyz[:, 0]) + y0 = np.nanmedian(offsets.xyz[:, 1]) + ax.text( + x0, y0, text, ha="center", va="center", fontsize=fontsize, fontweight="bold" + ) + + return scatter + + +def plot_receiver_templates( + receiver: Receiver, + ot_locs: dict, + output_dir: str, + fontsize: int = 16, +): + """Plot the templates contained in a Receiver. + + Parameters + ---------- + receiver : Receiver + Receiver containing the optics tubes and focal-plane templates. + ot_locs : dict + Optics-tube location information. Each entry should contain `dx` + and `dy`, matching the structure of `optics_tubes.yaml`. + output_dir : str + Directory in which to save the plots. + fontsize : int, default=16 + Font size used for focal-plane labels. + + Returns + ------- + dict[str, matplotlib.figure.Figure] + Generated figures keyed by plot name. + """ + outdir = os.path.join(output_dir, receiver.epoch, "nominal") + os.makedirs(outdir, exist_ok=True) + + # Give each OT a stable color. + ot_names = [ot.name for ot in receiver.optics_tubes] + ot_nums = {name: i + 1 for i, name in enumerate(ot_names)} + + def ot_color(ot_name): + return plt.cm.tab20((ot_nums[ot_name] - 1) % 20 / 20.0) + + def add_legend(ax): + handles, labels = ax.get_legend_handles_labels() + unique = {} + for handle, label_ in zip(handles, labels): + unique[label_] = handle + + if unique: + ax.legend( + list(unique.values())[::-1], + list(unique.keys())[::-1], + ) + + def save_and_finish(fig, name): + fig.savefig( + os.path.join(outdir, f"{receiver.name}_{receiver.epoch}_{name}.png") + ) + plt.close(fig) + + fig, ax = plt.subplots(figsize=(15, 15)) + for ot in receiver.optics_tubes: + for fp, ws in zip(ot.focal_planes, ot.wafer_slots): + plot_detector_offsets( + ax, + fp.template, + text=f"{fp.name}\n({ws})", + fontsize=fontsize, + color=ot_color(ot.name), + label=ot.name, + ) + add_legend(ax) + ax.set_xlabel("xi (rad)") + ax.set_ylabel("eta (rad)") + ax.set_title(f"{receiver.name.upper()} Template (On Sky)") + ax.set_aspect("equal") + save_and_finish(fig, "template_on_sky") + + # On sky, gamma colored + fig, ax = plt.subplots(figsize=(15, 15)) + gamma_scatter = None + for ot in receiver.optics_tubes: + for fp, ws in zip(ot.focal_planes, ot.wafer_slots): + gamma_scatter = plot_detector_offsets( + ax, + fp.template, + text=f"{fp.name}\n({ws})", + fontsize=fontsize, + c=fp.template.gamma, + ) + if gamma_scatter is not None: + fig.colorbar(gamma_scatter, ax=ax, label="gamma (rad)") + ax.set_xlabel("xi (rad)") + ax.set_ylabel("eta (rad)") + ax.set_title(f"{receiver.name.upper()} Template (On Sky)") + ax.set_aspect("equal") + save_and_finish(fig, "template_on_sky_gamma") + + # Back of receiver + fig, ax = plt.subplots(figsize=(15, 15)) + for ot in receiver.optics_tubes: + for fp, ws in zip(ot.focal_planes, ot.wafer_slots): + plot_detector_offsets( + ax, + fp.template_ot, + text=f"{fp.name}\n({ws})", + fontsize=fontsize, + color=ot_color(ot.name), + label=ot.name, + ) + add_legend(ax) + ax.set_xlabel("x (mm)") + ax.set_ylabel("y (mm)") + ax.set_title(f"{receiver.name.upper()} Template (From Back)") + ax.set_aspect("equal") + save_and_finish(fig, "template_back") + + # Front of receiver. + fig, ax = plt.subplots(figsize=(15, 15)) + for ot in receiver.optics_tubes: + dx = ot_locs[ot.name]["dx"] + dy = ot_locs[ot.name]["dy"] + for fp, ws in zip(ot.focal_planes, ot.wafer_slots): + template = deepcopy(fp.template_ot) + x = template.xyz[:, 0] - dx + y = template.xyz[:, 1] - dy + x = -1 * (-1 * x + dx) + y = -1 * y + dy + template.xyz[:, 0] = x + template.xyz[:, 1] = y + plot_detector_offsets( + ax, + template, + text=f"{fp.name}\n({ws})", + fontsize=fontsize, + color=ot_color(ot.name), + label=ot.name, + ) + add_legend(ax) + ax.set_xlabel("x (mm), Not Accurate!") + ax.set_ylabel("y (mm), Not Accurate!") + ax.set_title(f"{receiver.name.upper()} Template (At Window, From Front)") + ax.set_aspect("equal") + save_and_finish(fig, "template_front") + + +def plot_ufm( + focal_plane: FocalPlane | FocalPlaneCollection, + output_dir: str, + figsize: tuple[float, float] = (12, 6), + with_pm: bool = True, +): + """ + Plot the UFM focal-plane fit and residual distribution. + + Parameters + ---------- + focal_plane : FocalPlane | FocalPlaneCollection + Focal-plane object for a specefic observation. + output_dir : str + Directory in which to save the plot. + figsize : tuple[float, float], default: (12, 6) + Figure dimensions in inches. + with_pm : bool, default: True + If True then use `pm_data` if `False` use `data`. + Only matters for `FocalPlane`. + """ + wmsk = np.isfinite(focal_plane.weights) * (focal_plane.weights > 0) + fig, (ax1, ax2) = plt.subplots(1, 2, figsize=figsize, constrained_layout=True) + data = focal_plane.data + transformed = focal_plane.transformed + if isinstance(focal_plane, FocalPlane) and with_pm: + data = focal_plane.pm_data + transformed = focal_plane.pm_transformed + + # Plot focal-plane pointing. + plot_detector_offsets( + ax1, + focal_plane.template, + color="blue", + alpha=0.4, + label="template", + marker="P", + ) + plot_detector_offsets( + ax1, + transformed, + color="black", + alpha=0.4, + label="transformed", + marker="X", + ) + plot_detector_offsets( + ax1, + data[wmsk], + color="orange", + alpha=0.4, + label="measured", + ) + ax1.set_xlabel("Xi (rad)") + ax1.set_ylabel("Eta (rad)") + ax1.set_aspect("equal") + ax1.legend() + + # Plot histogram of residuals. + dist = 3600 * np.linalg.norm( + np.rad2deg((transformed.xyz - data.xyz)[wmsk, :2]), axis=1 + ) + if len(dist) > 0: + dist_thresh = np.percentile(dist, 97) + bins = max(int(len(dist) / 20), 10) + ax2.hist(dist[dist < dist_thresh], bins=bins) + + ax2.set_xlabel('Residual (")') + ax2.set_ylabel("Detectors") + + title = focal_plane.name + if isinstance(focal_plane, FocalPlane): + title += f" {focal_plane.meas_id}" + fig.suptitle(title.replace(" ", "\n")) + fig.savefig( + os.path.join(output_dir, f"{title.replace(' ', '+')}.png"), bbox_inches="tight" + ) + plt.close(fig) + + +def plot_optics_tube( + ot: OpticsTube, output_dir, figsize: tuple[float, float] = (12, 6), bins: int = 50 +): + """ + Plot radial residuals for the fitted focal-plane collections in an optics tube. + + The signed residual is the projection of `transformed.xyz - data.xyz` + onto the radial direction defined by `transformed.xyz`. Positive + values indicate an outward radial residual, while negative values + indicate an inward radial residual. + + Parameters + ---------- + ot : OpticsTube + OpticsTube containing fitted FocalPlaneCollection objects. + output_dir : str + Directory in which to save the plot. + figsize : tuple[float, float], default=(12, 6) + Figure dimensions in inches. + bins : int, default=50 + Number of radial bins used for the median residual profile. + """ + dists = [] + xis = [] + etas = [] + arcsec_per_rad = np.rad2deg(1.0) * 3600 + for fp in ot.focal_planes: + if fp.pad: + continue + data = fp.data + transformed = fp.transformed + xi = transformed.xyz[:, 0] + eta = transformed.xyz[:, 1] + dxi = transformed.xyz[:, 0] - data.xyz[:, 0] + deta = transformed.xyz[:, 1] - data.xyz[:, 1] + radius = np.hypot(xi, eta) + valid = ( + np.isfinite(fp.weights) + * (fp.weights > 0) + * np.isfinite(xi) + * np.isfinite(eta) + * np.isfinite(dxi) + * np.isfinite(deta) + * (radius > 0) + ) + if not np.any(valid): + continue + radial_residual = (dxi[valid] * xi[valid] + deta[valid] * eta[valid]) / radius[ + valid + ] + dists.append(radial_residual * arcsec_per_rad) + xis.append(xi[valid]) + etas.append(eta[valid]) + if not dists: + return None + + dist = np.hstack(dists) + xi = np.hstack(xis) + eta = np.hstack(etas) + radius = np.hypot(xi, eta) + finite = ( + np.isfinite(dist) * np.isfinite(radius) * np.isfinite(xi) * np.isfinite(eta) + ) + dist = dist[finite] + xi = xi[finite] + eta = eta[finite] + radius = radius[finite] + if len(dist) == 0: + return None + + fig, (ax1, ax2) = plt.subplots(1, 2, figsize=figsize, constrained_layout=True) + dist_avg, edges, _ = binned_statistic(radius, dist, statistic="median", bins=bins) + radius_bins = 0.5 * (edges[:-1] + edges[1:]) + ax1.scatter(radius, dist, s=6, alpha=0.1) + ax1.plot(radius_bins, dist_avg, color="black", linewidth=2, label="Median") + ax1.axhline(0, color="gray", linewidth=1) + limit = np.nanpercentile(np.abs(dist), 95) + if np.isfinite(limit) and limit > 0: + ax1.set_ylim(-limit, limit) + ax1.set_xlabel("Radius (rad)") + ax1.set_ylabel("Signed radial residual (arcseconds)") + ax1.legend() + + color_limit = np.nanpercentile(np.abs(dist), 99) + cf = None + if len(dist) >= 3 and np.isfinite(color_limit) and color_limit > 0: + cf = ax2.scatter( + xi, eta, c=dist, s=10, vmin=-color_limit, vmax=color_limit, cmap="coolwarm" + ) + if cf is not None: + fig.colorbar(cf, ax=ax2, label='Radial residual (")') + ax2.set_aspect("equal") + ax2.set_xlabel("Xi (rad)") + ax2.set_ylabel("Eta (rad)") + fig.suptitle(ot.name) + + os.makedirs(output_dir, exist_ok=True) + fig.savefig(os.path.join(output_dir, f"{ot.name}.png"), bbox_inches="tight") + plt.close(fig) + + +def plot_receiver( + receiver: Receiver, + output_dir: str, + percentile: float = 97, + levels: int = 21, + min_points: int = 3, + dpi: int = 180, +): + """ + Plot receiver-wide residual maps grouped by detector split. + + Splits are grouped such that any splits that appear together within + the same template are assigned to different rows, while splits that + never co-occur may share a row. The resulting rows are labeled by + the corresponding split names. + + If all focal-plane collections use fake gamma values + (`fake_gamma=True`) then the gamma column is omitted. + + Parameters + ---------- + receiver : Receiver + Receiver containing fitted optics tubes and focal-plane + collections. + output_dir : str + Directory in which to save the plot. + percentile : float, default=97 + Percentile of the absolute residual distribution used to define + the symmetric color scale. + levels : int, default=21 + Number of contour levels used for the residual maps. + min_points : int, default=3 + Minimum number of valid detectors required to plot a given split + within a focal-plane collection. + dpi : int, default=180 + Resolution used when saving the figure. + """ + arcsec_per_rad = 180 * 3600 / np.pi + focal_planes = [fp for ot in receiver.optics_tubes for fp in ot.focal_planes] + if len(focal_planes) == 0: + return None + + # Decide whether gamma should be plotted. + include_gamma = any(not fp.fake_gamma for fp in focal_planes) + + components = [0, 1] + titles = ["Xi", "Eta"] + if include_gamma: + components.append(2) + titles.append("Gamma") + ncols = len(components) + + # Build split groupings. + all_splits = set() + neighbors = {} + for fp in focal_planes: + valid = np.isfinite(fp.weights) * (fp.weights > 0) + splits = sorted(np.unique(np.asarray(fp.template.split)[valid]), key=str) + all_splits.update(splits) + for split in splits: + neighbors.setdefault(split, set()) + for i, split_a in enumerate(splits): + for split_b in splits[i + 1 :]: + neighbors[split_a].add(split_b) + neighbors[split_b].add(split_a) + split_to_group = {} + for split in sorted(all_splits, key=str): + unavailable = { + split_to_group[neighbor] + for neighbor in neighbors[split] + if neighbor in split_to_group + } + group = 0 + while group in unavailable: + group += 1 + split_to_group[split] = group + nrows = max(split_to_group.values()) + 1 + split_groups = [[] for _ in range(nrows)] + for split, group in split_to_group.items(): + split_groups[group].append(split) + for group in split_groups: + group.sort(key=str) + + # Gather plotting data. + entries = [] + all_residuals = [] + all_x = [] + all_y = [] + for fp in focal_planes: + if fp.pad: + continue + transformed = fp.transformed.xyz + data = fp.data.xyz + splits = np.asarray(fp.template.split) + residual = (transformed - data) * arcsec_per_rad + valid = ( + np.isfinite(fp.weights) + * (fp.weights > 0) + * np.isfinite(transformed[:, 0]) + * np.isfinite(transformed[:, 1]) + ) + for split in np.unique(splits): + msk = valid * (splits == split) + if np.sum(msk) < min_points: + continue + entry = { + "group": split_to_group[split], + "split": split, + "fp": fp, + "x": transformed[msk, 0], + "y": transformed[msk, 1], + "residual": residual[msk], + } + entries.append(entry) + all_x.append(entry["x"]) + all_y.append(entry["y"]) + all_residuals.append(entry["residual"][:, :2].ravel()) + if include_gamma and not fp.fake_gamma: + all_residuals.append(entry["residual"][:, 2]) + if len(entries) == 0: + return None + all_residuals = np.concatenate(all_residuals) + max_diff = np.nanpercentile(np.abs(all_residuals), percentile) + + if not np.isfinite(max_diff) or max_diff <= 0: + max_diff = np.nanmax(np.abs(all_residuals)) + if not np.isfinite(max_diff) or max_diff <= 0: + max_diff = 1.0 + + x = np.concatenate(all_x) + y = np.concatenate(all_y) + xmin = np.nanmin(x) + xmax = np.nanmax(x) + ymin = np.nanmin(y) + ymax = np.nanmax(y) + dx = xmax - xmin + dy = ymax - ymin + if dx <= 0: + dx = 1.0 + if dy <= 0: + dy = 1.0 + xlims = ( + xmin - 0.05 * dx, + xmax + 0.05 * dx, + ) + ylims = ( + ymin - 0.05 * dy, + ymax + 0.05 * dy, + ) + + fig, axs = plt.subplots( + nrows, + ncols, + figsize=(6 * ncols + 3, 6 * nrows + 3), + squeeze=False, + sharex=True, + sharey=True, + constrained_layout=True, + ) + contour_levels = np.linspace( + -max_diff, + max_diff, + levels, + ) + norm = Normalize( + vmin=-max_diff, + vmax=max_diff, + ) + for col, title in enumerate(titles): + axs[0, col].set_title( + title, + fontsize=18, + fontweight="bold", + ) + for row in range(nrows): + split_label = " / ".join(map(str, split_groups[row])) + axs[row, 0].set_ylabel( + f"{split_label}\nEta (rad)", + fontsize=14, + ) + for col in range(ncols): + ax = axs[row, col] + ax.set_aspect("equal") + ax.set_xlim(xlims) + ax.set_ylim(ylims) + ax.axhline(0, color="0.8", lw=0.5) + ax.axvline(0, color="0.8", lw=0.5) + + # Plot residual maps + for entry in entries: + row = entry["group"] + x = entry["x"] + y = entry["y"] + residual = entry["residual"] + for col, component in enumerate(components): + if component == 2 and entry["fp"].fake_gamma: + continue + z = residual[:, component] + valid = np.isfinite(x) * np.isfinite(y) * np.isfinite(z) + if np.sum(valid) < min_points: + continue + try: + axs[row, col].tricontourf( + x[valid], + y[valid], + z[valid], + levels=contour_levels, + cmap="coolwarm", + norm=norm, + extend="both", + ) + except (RuntimeError, ValueError): + axs[row, col].scatter( + x[valid], + y[valid], + c=z[valid], + cmap="coolwarm", + norm=norm, + s=8, + linewidths=0, + ) + + # Labels + for col in range(ncols): + axs[-1, col].set_xlabel("Xi (rad)", fontsize=14) + sm = ScalarMappable(norm=norm, cmap="coolwarm") + sm.set_array([]) + fig.colorbar( + sm, ax=axs.ravel().tolist(), label="Residual (arcseconds)", shrink=0.92 + ) + fig.suptitle(f"{receiver.name} Receiver Residuals", fontsize=22, fontweight="bold") + + os.makedirs(output_dir, exist_ok=True) + fig.savefig( + os.path.join( + output_dir, + f"{receiver.name}.png", + ), + dpi=dpi, + bbox_inches="tight", + ) + plt.close(fig) + + +def plot_displacements( + x0: np.ndarray, + y0: np.ndarray, + dx: np.ndarray, + dy: np.ndarray, + colorbys: list[tuple[Optional[str], Optional[np.ndarray]]], + output_dir: str, + filename_prefix: str, + title_prefix: str, + plot_scale: float, + scale_str: str, + figsize: tuple[float, float] = (14, 14), +): + """ + Plot displacement vectors, optionally colored by additional quantities. + + Parameters + ---------- + x0, y0 : np.ndarray + Starting coordinates of each displacement vector. + dx, dy : np.ndarray + Displacement components before plotting scale is applied. + colorbys : list[tuple[Optional[str], Optional[np.ndarray]]] + Quantities used to color the arrows. + output_dir : str + Directory in which to save the plots. + filename_prefix : str + Prefix used for output filenames. + title_prefix : str + Prefix used for plot titles. + plot_scale : float + Multiplicative scale applied to dx and dy. + scale_str : str + Description of the displacement scale for plot titles. + figsize : tuple[float, float], default=(14, 14) + Figure dimensions in inches. + """ + os.makedirs(output_dir, exist_ok=True) + dx = np.asarray(dx) * plot_scale + dy = np.asarray(dy) * plot_scale + nobs = len(dx) + for name, color_data in colorbys: + fig, ax = plt.subplots(figsize=figsize, constrained_layout=True) + + if name is None: + ax.quiver( + x0, + y0, + dx, + dy, + angles="xy", + scale_units="xy", + ) + title = f"{title_prefix} Observation Displacements" + fname = f"{filename_prefix}_displacements.png" + else: + if color_data is None: + raise ValueError(f"{name} specified without data") + if len(color_data) != nobs: + raise ValueError( + f"{name}: expected {nobs} values but got {len(color_data)}" + ) + q = ax.quiver( + x0, + y0, + dx, + dy, + color_data, + angles="xy", + scale_units="xy", + cmap="viridis", + ) + fig.colorbar(q, ax=ax, label=name) + title = ( + f"{title_prefix} Observation Displacements by {name}\n" f"{scale_str}" + ) + fname = f"{filename_prefix}_displacements_{name}.png" + ax.set_title(title) + ax.set_xlabel("Xi (rad)") + ax.set_ylabel("Eta (rad)") + ax.set_aspect("equal") + fig.savefig( + os.path.join(output_dir, fname), + dpi=200, + bbox_inches="tight", + ) + plt.close(fig) + + +def plot_receiver_displacements( + receiver: Receiver, + colorbys: list[tuple[Optional[str], Optional[np.ndarray]]], + output_dir: str, + figsize: tuple[float, float] = (14, 14), +): + """ + Plot observation-by-observation focal-plane displacements relative + to the final solved focal-plane collections. + + Each arrow corresponds to one FocalPlane measurement. Its location + is given by the associated focal-plane template center and its + direction is given by the median displacement between the + observation and the solved collection coordinates. + + Parameters + ---------- + receiver : Receiver + Receiver containing solved focal-plane collections. + colorbys : list[tuple[Optional[str], Optional[np.ndarray]]] + Quantities used to color the arrows. Each array must contain one + value per measurement in the receiver. Passing (None, None) + produces an uncolored plot. + output_dir : str + Directory in which to save the plots. + figsize : tuple[float, float], default=(14, 14) + Figure dimensions in inches. + """ + arcmin_per_rad = 180 * 60 / np.pi + plot_scale = 0.01 * arcmin_per_rad + scale_str = "1 arcmin = 0.01 rad" + x0 = [] + y0 = [] + dx = [] + dy = [] + for ot in receiver.optics_tubes: + for fp in ot.focal_planes: + if fp.pad or fp.template.center is None: + continue + xc, yc = fp.template.center[:2] + for meas in fp.focal_planes: + msk = np.isfinite(meas.weights) & (meas.weights > 0) + if np.sum(msk) == 0: + continue + disp_x = np.nanmedian( + meas.pm_transformed.xyz[msk, 0] - fp.transformed.xyz[msk, 0] + ) + disp_y = np.nanmedian( + meas.pm_transformed.xyz[msk, 1] - fp.transformed.xyz[msk, 1] + ) + x0.append(xc) + y0.append(yc) + dx.append(disp_x) + dy.append(disp_y) + + plot_displacements( + x0=np.asarray(x0), + y0=np.asarray(y0), + dx=np.asarray(dx), + dy=np.asarray(dy), + colorbys=colorbys, + output_dir=output_dir, + filename_prefix=receiver.name, + title_prefix=receiver.name, + plot_scale=plot_scale, + scale_str=scale_str, + figsize=figsize, + ) + + +def plot_receiver_nuisance_displacements( + receiver: Receiver, + nuisance_params: NuisanceParams, + params_to_plot: list[tuple[str, str, Optional[str], str, float]], + colorbys: list[tuple[Optional[str], Optional[np.ndarray]]], + output_dir: str, + figsize: tuple[float, float] = (14, 14), +): + """ + Plot observation-by-observation focal-plane displacements using + fitted nuisance parameters. + + Parameters + ---------- + receiver : Receiver + Receiver containing the focal-plane measurements. + nuisance_params : NuisanceParams + Per-observation nuisance parameters. + params_to_plot : list[tuple[str, str, Optional[str], str, float]] + Parameter combinations to plot. Each tuple contains: + - x: Nuisance parameter name for dx. + - y: Nuisance parameter name for dy. + - rot: Optional nuisance parameter name for rotation. + - xy_units: Units of the x and y parameters. + - scale: Parameter value corresponding to 0.01 rad. + colorbys : list[tuple[Optional[str], Optional[np.ndarray]]] + Quantities used to color the arrows. Each array must contain one + value per measurement in the receiver. Passing (None, None) + produces an uncolored plot. + output_dir : str + Directory in which to save the plots. + figsize : tuple[float, float], default=(14, 14) + Figure dimensions in inches. + """ + if len(params_to_plot) == 0: + return + x0 = [] + y0 = [] + obs_ids = [] + for ot in receiver.optics_tubes: + for fp in ot.focal_planes: + if fp.pad or fp.template.center is None: + continue + xc, yc = fp.template.center[:2] + for meas in fp.focal_planes: + msk = np.isfinite(meas.weights) * (meas.weights > 0) + if np.sum(msk) == 0: + continue + x0.append(xc) + y0.append(yc) + obs_ids.append(meas.meas_id) + x0 = np.asarray(x0) + y0 = np.asarray(y0) + for x_name, y_name, rot_name, xy_units, scale in params_to_plot: + dx = [] + dy = [] + for obs_id in obs_ids: + pars, _ = nuisance_params[obs_id] + if x_name not in pars or y_name not in pars: + raise ValueError( + f"Missing nuisance parameters {x_name!r} or {y_name!r} for observation {obs_id}" + ) + disp_x = pars[x_name] + disp_y = pars[y_name] + if rot_name is not None: + if rot_name not in pars: + raise ValueError( + f"Missing rotation parameter {rot_name!r} for observation {obs_id}" + ) + theta = pars[rot_name] + cos_theta = np.cos(theta) + sin_theta = np.sin(theta) + disp_x, disp_y = ( + cos_theta * disp_x - sin_theta * disp_y, + sin_theta * disp_x + cos_theta * disp_y, + ) + dx.append(disp_x) + dy.append(disp_y) + param_names = f"{x_name}, {y_name}" + if rot_name is not None: + param_names += f", {rot_name}" + label = f"{receiver.name} {param_names}" + plot_displacements( + x0=x0, + y0=y0, + dx=np.asarray(dx), + dy=np.asarray(dy), + colorbys=colorbys, + output_dir=output_dir, + filename_prefix=label.replace(" ", "_").replace(", ", "_"), + title_prefix=label, + plot_scale=0.01 / scale, + scale_str=f"{scale:g} {xy_units} = .01 rad", + figsize=figsize, + ) + + +def plot_receiver_nuisance_transform_displacements( + receiver: Receiver, + nuisance_params: NuisanceParams, + colorbys: list[tuple[Optional[str], Optional[np.ndarray]]], + output_dir: str, + figsize: tuple[float, float] = (14, 14), +): + """ + Plot observation-by-observation focal-plane displacements using + the nuisance transforms stored in NuisanceParams. + + Each arrow corresponds to one FocalPlane measurement. Its location + is given by the associated focal-plane template center, and its + direction is given by the translation component of the observation's + nuisance transform, rotated by the transform rotation angle. + + The first two elements of `transform.shift` are interpreted as dx + and dy, in radians. The displacement is rotated by `transform.rot`. + + Parameters + ---------- + receiver : Receiver + Receiver containing the focal-plane measurements. + nuisance_params : NuisanceParams + Per-observation nuisance parameters and transforms. + colorbys : list[tuple[Optional[str], Optional[np.ndarray]]] + Quantities used to color the arrows. Each array must contain one + value per measurement in the receiver. Passing (None, None) + produces an uncolored plot. + output_dir : str + Directory in which to save the plots. + figsize : tuple[float, float], default=(14, 14) + Figure dimensions in inches. + """ + arcmin_per_rad = 180 * 60 / np.pi + plot_scale = 0.01 * arcmin_per_rad + scale_str = "1 arcmin = 0.01 rad" + + x0 = [] + y0 = [] + dx = [] + dy = [] + + for ot in receiver.optics_tubes: + for fp in ot.focal_planes: + if fp.pad or fp.template.center is None: + continue + xc, yc = fp.template.center[:2] + for meas in fp.focal_planes: + msk = np.isfinite(meas.weights) & (meas.weights > 0) + if np.sum(msk) == 0: + continue + _, transform = nuisance_params[meas.meas_id] + disp_x, disp_y = transform.shift[:2] + theta = transform.rot + cos_theta = np.cos(theta) + sin_theta = np.sin(theta) + disp_x, disp_y = ( + cos_theta * disp_x - sin_theta * disp_y, + sin_theta * disp_x + cos_theta * disp_y, + ) + x0.append(xc) + y0.append(yc) + dx.append(disp_x) + dy.append(disp_y) + + plot_displacements( + x0=np.asarray(x0), + y0=np.asarray(y0), + dx=np.asarray(dx), + dy=np.asarray(dy), + colorbys=colorbys, + output_dir=output_dir, + filename_prefix=f"{receiver.name}_transforms", + title_prefix=f"{receiver.name} Nuisance Transforms", + plot_scale=plot_scale, + scale_str=scale_str, + figsize=figsize, + ) + + +def plot_receiver_resid_vs_enc( + receiver: Receiver, + output_dir: str, + figsize: tuple[float, float] = (18, 10), + alpha: float = 0.15, + markersize: float = 4, +): + """ + Plot focal-plane residuals versus encoder coordinates for an entire + receiver. + + Each row corresponds to a component of `fpc_resid` and each column + corresponds to an encoder coordinate `(az, el, roll)`. Residuals are + shown in arcseconds and encoder coordinates are shown in degrees. + + Points are colored by focalplane name. + + Parameters + ---------- + receiver : Receiver + Receiver containing fitted focal-plane collections. + output_dir : str + Directory in which to save the plot. + figsize : tuple[float, float], default=(18, 10) + Figure dimensions in inches. + alpha : float, default=0.15 + Point transparency. + markersize : float, default=4 + Marker size. + """ + + focal_planes = [fp for ot in receiver.optics_tubes for fp in ot.focal_planes] + if len(focal_planes) == 0: + return + + include_gamma = any(not fp.fake_gamma for fp in focal_planes) + resid_indices = [0, 1] + resid_labels = [ + 'Xi Residual (")', + 'Eta Residual (")', + ] + if include_gamma: + resid_indices.append(2) + resid_labels.append('Gamma Residual (")') + enc_labels = [ + "Az (deg)", + "El (deg)", + "Roll (deg)", + ] + nrows = len(resid_indices) + ncols = 3 + + fig, axs = plt.subplots( + nrows, + ncols, + figsize=figsize, + squeeze=False, + constrained_layout=True, + sharex="col", + ) + + colors = plt.cm.tab20(np.linspace(0, 1, len(focal_planes))) + for color, fp in zip(colors, focal_planes): + added_label = False + for meas in fp.focal_planes: + valid = np.isfinite(meas.weights) * (meas.weights > 0) + if np.sum(valid) == 0: + continue + + enc = np.rad2deg(meas.enc.xyz) + for row, resid_idx in enumerate(resid_indices): + resid = meas.fpc_resid[:, resid_idx] * 180 * 3600 / np.pi + valid_row = valid * np.isfinite(resid) + if np.sum(valid_row) == 0: + continue + for col in range(3): + msk = valid_row * np.isfinite(enc[:, col]) + if np.sum(msk) == 0: + continue + axs[row, col].scatter( + enc[msk, col], + resid[msk], + s=markersize, + alpha=alpha, + color=color, + label=( + fp.name + if not added_label and row == 0 and col == 0 + else None + ), + ) + added_label = True + + for row, label in enumerate(resid_labels): + axs[row, 0].set_ylabel(label) + for col, label in enumerate(enc_labels): + axs[0, col].set_title(label) + axs[-1, col].set_xlabel(label) + handles, labels = axs[0, 0].get_legend_handles_labels() + + if len(handles) > 0: + fig.legend( + handles, + labels, + loc="outside right upper", + ) + + fig.suptitle( + f"{receiver.name} Residuals vs Encoder Coordinates", + ) + os.makedirs(output_dir, exist_ok=True) + fig.savefig( + os.path.join( + output_dir, + f"{receiver.name}_resid_vs_enc.png", + ), + dpi=200, + bbox_inches="tight", + ) + plt.close(fig) + + +def plot_receiver_residuals( + receiver: Receiver, + output_dir: str, + bins: int = 100, + percentile: float = 99, + figsize: tuple[float, float] = (16, 5), + dpi: int = 180, +): + """ + Plot histograms of all focal-plane collection residuals in a system. + + Residuals from all measurements are collected across all receivers, + optics tubes, and focal-plane collections. Only detectors with + finite, positive weights are included. + + Parameters + ---------- + receiver : Receiver + Receiver containing fitted focal-plane collections. + output_dir : str + Directory in which to save the plot. + bins : int, default=100 + Number of histogram bins. + percentile : float, default=99 + Percentile of the absolute residual distribution used to limit + the histogram range. + figsize : tuple[float, float], default=(16, 5) + Figure dimensions in inches. + dpi : int, default=180 + Resolution used when saving the figure. + """ + arcsec_per_rad = 180 * 3600 / np.pi + residuals = [[], [], [], []] + for ot in receiver.optics_tubes: + for fp in ot.focal_planes: + if fp.pad: + continue + for meas in fp.focal_planes: + valid = np.isfinite(meas.weights) * (meas.weights > 0) + if not np.any(valid): + continue + resid = meas.fpc_resid * arcsec_per_rad + ndim = 3 - int(meas.fake_gamma) + for i in range(ndim): + msk = valid * np.isfinite(resid[:, i]) + if np.any(msk): + residuals[i].append(resid[msk, i]) + + resid_norm = np.linalg.norm(resid[:, :ndim], axis=1) + msk = valid * np.isfinite(resid_norm) + if np.any(msk): + residuals[3].append(resid_norm[msk]) + + residuals = [ + np.concatenate(component) if component else np.array([]) + for component in residuals + ] + + components = [0, 1] + labels = ['Xi Residual (")', 'Eta Residual (")'] + if len(residuals[2]) > 0: + components.append(2) + labels.append('Gamma Residual (")') + components.append(3) + labels.append('Residual Norm (")') + if not any(len(residuals[i]) > 0 for i in components): + return None + + fig, axs = plt.subplots( + 1, len(components), figsize=figsize, squeeze=False, constrained_layout=True + ) + for ax, idx, label in zip(axs[0], components, labels): + data = residuals[idx] + if len(data) == 0: + continue + + limit = np.nanpercentile(np.abs(data), percentile) + if not np.isfinite(limit) or limit <= 0: + limit = np.nanmax(np.abs(data)) + if np.isfinite(limit) and limit > 0: + data = data[np.abs(data) <= limit] + ax.hist(data, bins=bins, histtype="stepfilled", alpha=0.7) + + if idx != 3: + ax.axvline(0, color="black", linestyle="--", linewidth=1) + + median = np.median(data) + ax.axvline( + median, + color="red", + linestyle="-", + linewidth=1.5, + label=f"Median: {median:.3g}", + ) + ax.set_xlabel(label) + ax.set_ylabel("Detectors") + ax.legend() + + fig.suptitle(f"{receiver.name} Residuals") + os.makedirs(output_dir, exist_ok=True) + fig.savefig( + os.path.join(output_dir, f"{receiver.name}_residuals.png"), + dpi=dpi, + bbox_inches="tight", + ) + plt.close(fig) diff --git a/sotodlib/coords/fpc_old.py b/sotodlib/coords/fpc_old.py new file mode 100644 index 000000000..fb089c631 --- /dev/null +++ b/sotodlib/coords/fpc_old.py @@ -0,0 +1,840 @@ +import logging +import os +from dataclasses import InitVar, dataclass, field +from functools import cached_property, partial +from typing import Dict, List, Optional + +import h5py +import matplotlib.pyplot as plt +import megham.transform as mt +import megham.utils as mu +import numpy as np +from numpy.typing import NDArray +from scipy.stats import binned_statistic +from sotodlib.coords import optics as op +from sotodlib.core import metadata +from sotodlib.io.metadata import read_dataset, write_dataset + +logger = logging.getLogger("finalize_focal_plane") +plt.style.use("tableau-colorblind10") + + +def _add_attrs(dset, attrs): + for k, v in attrs.items(): + if v is None: + logger.warning("Not adding attribute %s because it is None", k) + continue + dset.attrs[k] = v + + +@dataclass +class Transform: + shift: NDArray[np.floating] # (ndim,) + affine: NDArray[np.floating] # (ndim, ndim) + scale: NDArray[np.floating] = field(init=False) # (ndim,) + shear: float = field(init=False) + rot: float = field(init=False) + + def __post_init__(self): + self.decompose() + + @classmethod + def identity(cls): + return Transform(np.zeros(3), np.eye(3)) + + @classmethod + def from_split(cls, shift, xieta_affine, gamma_scale): + affine = np.eye(len(xieta_affine) + 1) + affine[: len(xieta_affine), : len(xieta_affine)] = xieta_affine + affine[-1, -1] = gamma_scale + + return Transform(shift, affine) + + def decompose(self): + xieta_affine = self.affine[:2, :2] + gamma_scale = self.affine[-1, -1] + scale, shear, rot = mt.decompose_affine(xieta_affine) + self.scale = np.array((*scale, gamma_scale)) + self.shear = shear.item() + self.rot = mt.decompose_rotation(rot)[-1] + + def save(self, f, path, append=""): + if path not in f: + f.create_group(path) + _add_attrs( + f[path], + { + f"shift{append}": self.shift, + f"scale{append}": self.scale, + f"shear{append}": self.shear, + f"rot{append}": self.rot, + f"affine{append}": self.affine, + }, + ) + + @classmethod + def load(cls, group, append=""): + shift = group.attrs[f"shift{append}"] + affine = group.attrs[f"affine{append}"] + + return Transform(shift, affine) + + +@dataclass +class Template: + det_ids: NDArray[np.str_] # (ndet,) + fp: NDArray[np.floating] # (ndet, ndim) + optical: NDArray[np.bool_] # (ndet,) + pointing_cfg: InitVar[Dict] + center: NDArray[np.floating] = field(init=False) # (1, ndim) + spacing: NDArray[np.floating] = field(init=False) # (ndim,) + bandpass: NDArray[np.str_] = field(init=False) + pol: NDArray[np.str_] = field(init=False) + rhombus: NDArray[np.str_] = field(init=False) + + def __post_init__(self, pointing_cfg): + self.center = np.array( + op.get_focal_plane(None, x=0, y=0, pol=0, **pointing_cfg) + ).T + xieta_spacing = mu.estimate_spacing(self.fp[self.optical, :2]) + # For gamma rather than the spacing in real space we want the difference between bins + # This is a rough estimate but good enough for us + gamma_spacing = np.percentile(np.diff(np.sort(self.fp[2])), 99.9) + self.spacing = np.array([xieta_spacing, xieta_spacing, gamma_spacing]) + + self.bandpass = np.zeros_like(self.det_ids) + self.pol = np.zeros_like(self.det_ids) + self.rhombus = np.zeros_like(self.det_ids) + + def add_wafer_info(self, aman, template_msk): + self.__dict__.pop("id_strs", None) + self.__dict__.pop("valid_ids", None) + if not np.all( + np.isin(["bandpass", "pol", "rhombus"], list(aman.det_info.wafer.keys())) + ): + logger.warning( + "det_info.wafer seems to be missing metadata? Safe to ignore in rset mode." + ) + return + mapping = np.argsort(np.argsort(self.det_ids[template_msk])) + srt = np.argsort(aman.det_info.det_id) + self.bandpass[template_msk] = aman.det_info.wafer.bandpass[srt][mapping] + self.pol[template_msk] = aman.det_info.wafer.pol[srt][mapping] + self.rhombus[template_msk] = aman.det_info.wafer.rhombus[srt][mapping] + + @cached_property + def id_strs(self): + return np.array([bp + "_" + pol for bp, pol in zip(self.bandpass, self.pol)]) + + @cached_property + def valid_ids(self): + ids = np.unique(self.id_strs) + valid = ~(np.char.startswith(ids, "_") * np.char.endswith(ids, "_")) + return ids[valid] + + +@dataclass +class FocalPlane: + stream_id: str + wafer_slot: str + det_ids: NDArray[np.str_] # (ndet,) + id_strs: NDArray[np.str_] # (ndet,) + avg_fp: NDArray[np.floating] # (ndim, ndet) + weights: NDArray[np.floating] # (ndet,) + transformed: NDArray[np.floating] # (ndet, ndim) + center: NDArray[np.floating] # (1, ndim) + center_transformed: NDArray[np.floating] # (1, ndim) + n_point: NDArray[np.int_] # (ndet,) + n_gamma: NDArray[np.int_] # (ndet,) + have_gamma: bool = field(default=False) + template: Optional[Template] = field(default=None) + transform: Transform = field(default_factory=Transform.identity) + transform_nocm: Transform = field(default_factory=Transform.identity) + config: str = field(default="") + with_cm: bool = field(default=True) + full_fp: Optional[NDArray[np.floating]] = field( + init=False, default=None + ) # (ndet, ndim, n_aman) + tot_weight: Optional[NDArray[np.floating]] = field( + init=False, default=None + ) # (ndet,) + + def __post_init__(self): + if self.template is not None and not np.all( + np.isclose(self.center, self.template.center) + ): + raise ValueError("Focalplane center does not match template") + + @property + def template_fp(self): + if self.template is not None: + return self.template.fp + logger.warning( + "No template in focal plane %s, reconstructing from transformed. This will be wrong with_cm is set wrong!", + self.stream_id, + ) + transform = self.transform_nocm + if self.with_cm: + transform = self.transform + return (self.transformed - transform.shift) @ np.linalg.inv(transform.affine) + + @property + def template_center(self): + if self.template is not None: + return self.template.center + logger.warning( + "No template in focal plane %s, reconstructing from transformed. This will be wrong with_cm is set wrong!", + self.stream_id, + ) + transform = self.transform_nocm + if self.with_cm: + transform = self.transform + return (self.center_transformed - transform.shift) @ np.linalg.inv( + transform.affine + ) + + @property + def diff(self): + return self.avg_fp - self.transformed + + @property + def isfinite(self): + return np.isfinite(self.diff[:, 0]) + + @property + def dist(self): + if self.have_gamma: + return np.linalg.norm(self.diff, axis=1) + return np.linalg.norm(self.diff[:, :2], axis=1) + + @property + def padded(self): + return self.tot_weight is None + + @classmethod + def empty(cls, template, stream_id, wafer_slot, n_aman, config=""): + if template is None: + raise TypeError("template must be an instance of Template, not None") + full_fp = np.full(template.fp.shape + (n_aman,), np.nan) + tot_weight = np.zeros((len(template.det_ids), 2)) + avg_fp = np.full_like(template.fp, np.nan) + weight = np.zeros((len(template.det_ids), 2)) + transformed = template.fp.copy() + center = template.center.copy() + center_transformed = template.center.copy() + n_point = np.zeros_like(template.det_ids, dtype=int) + n_gamma = np.zeros_like(template.det_ids, dtype=int) + + fp = FocalPlane( + stream_id, + wafer_slot, + template.det_ids, + template.id_strs, + avg_fp, + weight, + transformed, + center, + center_transformed, + n_point, + n_gamma, + template=template, + config=config, + ) + fp.full_fp = full_fp + fp.tot_weight = tot_weight + + return fp + + def map_by_det_id(self, aman): + if self.template is not None and not np.array_equal( + self.det_ids, self.template.det_ids + ): + raise ValueError("det_ids don't match template, mapping is not valid!") + _, msk, template_msk = np.intersect1d( + aman.det_info.det_id, self.det_ids, return_indices=True + ) + if len(msk) != aman.dets.count: + logger.warning("There are matched dets not found in the focal plane") + mapping = np.argsort(np.argsort(self.det_ids[template_msk])) + srt = np.argsort(aman.det_info.det_id[msk]) + xi = aman.pointing.xi[msk][srt][mapping] + eta = aman.pointing.eta[msk][srt][mapping] + r2 = np.nan + np.zeros_like(eta) + if "R2" in aman.pointing: + r2 = aman.pointing.R2[msk][srt][mapping] + if "polarization" in aman: + # name of field just a placeholder for now + gamma = aman.polarization.polang[msk][srt][mapping] + elif "gamma" in aman.pointing: + gamma = aman.pointing.gamma[msk][srt][mapping] + else: + gamma = np.full(len(xi), np.nan) + fp = np.column_stack((xi, eta, gamma)) + return fp, r2, template_msk + + def add_fp(self, i, fp, weights, template_msk): + if self.full_fp is None or self.tot_weight is None: + raise ValueError("full_fp or tot_weight not initialized") + self.full_fp[template_msk, :, i] = fp * weights[:, 0][..., None] + weights = np.nan_to_num(weights) + self.tot_weight[template_msk] += weights + + def save(self, f, db_info, group): + logger.info("Saving %s", self.stream_id) + ndets = len(self.det_ids) + outdt = [ + ("dets:det_id", self.det_ids.dtype), + ("xi", np.float32), + ("eta", np.float32), + ("gamma", np.float32), + ("padded", np.bool_), + ] + fpout = np.fromiter( + zip( + self.det_ids, + *(self.transformed.T), + np.ones(len(self.det_ids), dtype=bool) * (self.padded), + ), + dtype=outdt, + count=ndets, + ) + write_dataset( + metadata.ResultSet.from_friend(fpout), + f, + f"{group}/focal_plane", + overwrite=True, + ) + _add_attrs( + f[f"{group}/focal_plane"], + {"wafer_slot": str(self.wafer_slot), "measured_gamma": self.have_gamma}, + ) + entry = {"dets:stream_id": self.stream_id, "dataset": f"{group}/focal_plane"} + entry.update(db_info[1]) + db_info[0].add_entry(entry, filename=os.path.basename(f.filename), replace=True) + + outdt_full = [ + ("dets:det_id", self.det_ids.dtype), + ("id_strs", self.id_strs.dtype), + ("xi_t", np.float32), + ("eta_t", np.float32), + ("gamma_t", np.float32), + ("xi_m", np.float32), + ("eta_m", np.float32), + ("gamma_m", np.float32), + ("weights", np.float32), + ("r2", np.float32), + ("n_point", np.int8), + ("n_gamma", np.int8), + ] + fpfullout = np.fromiter( + zip( + self.det_ids, + self.id_strs, + *(self.transformed.T), + *(self.avg_fp.T), + *(self.weights.T), + self.n_point, + self.n_gamma, + ), + dtype=outdt_full, + count=ndets, + ) + write_dataset( + metadata.ResultSet.from_friend(fpfullout), + f, + f"{group}/focal_plane_full", + overwrite=True, + ) + + self.transform.save(f, f"{group}/transform") + self.transform_nocm.save(f, f"{group}/transform", "_nocm") + _add_attrs( + f[f"{group}"], + { + "fit_centers": self.center_transformed, + "template_centers": self.center, + "config": self.config, + "with_cm": self.with_cm, + "tot_weight": self.tot_weight, + }, + ) + + @classmethod + def load(cls, group, include_cm=None): + stream_id = group.name.split("/")[-1] + fp_full = read_dataset(group.file, f"{group.name}/focal_plane_full") + if fp_full.keys is None: + raise ValueError("fp_full somehow has no keys") + det_ids = fp_full["dets:det_id"] + if "id_strs" in fp_full.keys: + id_strs = fp_full["id_strs"] + else: + logger.warning("No id strings found in this focal plane, may be old.") + id_strs = np.zeros(len(fp_full), str) + avg_fp = np.column_stack( + ( + np.array(fp_full["xi_m"]), + np.array(fp_full["eta_m"]), + np.array(fp_full["gamma_m"]), + ) + ) + # For backwards compatibility + weights = np.array(fp_full["weights"]) + if "r2" in fp_full.keys: + weights = np.column_stack((weights, np.array(fp_full["r2"]))) + transformed = np.column_stack( + ( + np.array(fp_full["xi_t"]), + np.array(fp_full["eta_t"]), + np.array(fp_full["gamma_t"]), + ) + ) + center = group.attrs["template_centers"] + center_transformed = group.attrs["fit_centers"] + n_point = fp_full["n_point"] + n_gamma = fp_full["n_gamma"] + have_gamma = group["focal_plane"].attrs["measured_gamma"] + template = None + transform = Transform.load(group["transform"]) + transform_nocm = Transform.load(group["transform"], "_nocm") + if "wafer_slot" in group["focal_plane"].attrs: + wafer_slot = group["focal_plane"].attrs["wafer_slot"] + else: + logger.warning("No wafer slot found in this focal plane, may be old.") + wafer_slot = "ws?" + config = group.attrs.get("config", "") + if config == "": + logger.warning("No config found in this focal plane, may be old.") + if "with_cm" in group.attrs: + with_cm = group.attrs["with_cm"] + else: + with_cm = True + logger.warning( + "No with_cm found in this focal plane, may be old. Attempting to set based on receiver!" + ) + if include_cm is None: + logger.warning("\tinclude_cm not set! Using True for with_cm") + else: + with_cm = include_cm + + fp = FocalPlane( + stream_id, + wafer_slot, + np.array(det_ids), + np.array(id_strs), + avg_fp, + np.array(weights), + transformed, + center, + center_transformed, + np.array(n_point), + np.array(n_gamma), + have_gamma, + template, + transform, + transform_nocm, + config, + with_cm, + ) + fp.tot_weight = group.attrs.get("tot_weight", None) + + return fp + + +@dataclass +class OpticsTube: + name: str + center: NDArray[np.floating] + transform: Transform = field(default_factory=Transform.identity) + transform_fullcm: Transform = field(default_factory=Transform.identity) + focal_planes: List[FocalPlane] = field(default_factory=list) + center_transformed: NDArray[np.floating] = field(init=False) + + def __post_init__(self): + self.center_transformed = mt.apply_transform( + self.center, self.transform_fullcm.affine, self.transform_fullcm.shift + ) + + def __setattr__(self, name, val): + self.__dict__[name] = val + if name == "focal_planes": + self.__dict__.pop("fp_dict", None) + + @property + def num_fps(self): + fps = [fp for fp in self.focal_planes if fp.tot_weight is not None] + return len(fps) + + @classmethod + def from_pointing_cfg(cls, pointing_cfg): + name = pointing_cfg["tube_slot"] + telescope_flavor = pointing_cfg["telescope_flavor"].upper() + if telescope_flavor not in ["LAT", "SAT"]: + raise ValueError("Telescope should be LAT or SAT") + + if telescope_flavor == "LAT": + if pointing_cfg["zemax_path"] is None: + raise ValueError("Must provide zemax_path for LAT") + xi, eta, gamma = op.LAT_focal_plane( + None, + pointing_cfg["zemax_path"], + x=0, + y=0, + pol=0, + roll=pointing_cfg.get("roll", 0), + tube_slot=name, + ) + else: + xi, eta, gamma = op.SAT_focal_plane( + None, + x=0, + y=0, + pol=0, + roll=pointing_cfg.get("roll", 0), + mapping_data=pointing_cfg.get("mapping_data", None), + ) + center = np.array((xi, eta, gamma)).reshape((1, 3)) + + return OpticsTube(name, center) + + def delete_fp(self, stream_id): + self.focal_planes = [ + fp for fp in self.focal_planes if fp.stream_id != stream_id + ] + + @cached_property + def fp_dict(self): + return {fp.stream_id: fp for fp in self.focal_planes} + + def save(self, f, db_info, group="/"): + g = f[group] + g.create_group(self.name) + _add_attrs( + g[self.name], + {"center": self.center, "center_transformed": self.center_transformed}, + ) + tr_path = os.path.join(group, self.name, "transform") + self.transform.save(f, tr_path) + self.transform_fullcm.save(f, tr_path, "_fullcm") + for focal_plane in self.focal_planes: + focal_plane.save( + f, db_info, os.path.join(group, self.name, focal_plane.stream_id) + ) + + @classmethod + def load(cls, group, include_cm=None): + name = group.name.split("/")[-1] + center = group.attrs["center"] + transform = Transform.load(group["transform"]) + transform_fullcm = Transform.load(group["transform"], "_fullcm") + fps = [ + FocalPlane.load(group[grp], include_cm) + for grp in group.keys() + if "transform" not in grp + ] + + return OpticsTube(name, center, transform, transform_fullcm, fps) + + +@dataclass +class Receiver: + optics_tubes: List[OpticsTube] = field(default_factory=list) + center: NDArray[np.floating] = field( + default_factory=partial(np.zeros, shape=(1, 3)) + ) + include_cm: bool = field(default=False) + valid_ids: List[str] = field(default_factory=list) + transform: Transform = field(default_factory=Transform.identity) + center_transformed: NDArray[np.floating] = field(init=False) + + def __post_init__(self): + self.center_transformed = mt.apply_transform( + self.center, self.transform.affine, self.transform.shift + ) + + def __setattr__(self, name, val): + self.__dict__[name] = val + if name == "optics_tubes": + self.__dict__.pop("ot_dict", None) + + def delete_ot(self, name): + self.focal_planes = [ot for ot in self.optics_tubes if ot.name != name] + + def save(self, f, db_info, group="/"): + _add_attrs( + f[group], + { + "center": self.center, + "center_transformed": self.center_transformed, + "include_cm": self.include_cm, + "valid_ids": self.valid_ids, + }, + ) + self.transform.save(f, os.path.join(group, "transform")) + for ot in self.optics_tubes: + ot.save(f, db_info, group) + + @classmethod + def load(cls, f, group="/"): + center = f[group].attrs["center"] + include_cm = f[group].attrs["include_cm"] + valid_ids = f[group].attrs.get("valid_ids", []) + if len(valid_ids) == 0: + logger.warning("valid_ids list is empty! May be an old Receiver object!") + transform = Transform.load(f[group]["transform"]) + ots = [ + OpticsTube.load(f[group][grp], include_cm) + for grp in f[group].keys() + if "transform" not in grp + ] + + return Receiver(ots, center, include_cm, list(valid_ids), transform) + + @classmethod + def load_file(cls, path): + with h5py.File(path, "r") as f: + # Check if its an old file: + if "transform" in f.keys(): + return {"": cls.load(f)} + return {grp: cls.load(f, grp) for grp in f.keys()} + + @property + def focal_planes(self): + fps = [] + for ot in self.optics_tubes: + fps += ot.focal_planes + return fps + + @cached_property + def ot_dict(self): + return {ot.name: ot for ot in self.optics_tubes} + + @property + def lims(self): + xmax = np.max([np.nanmax(fp.transformed[:, 0]) for fp in self.focal_planes]) + xmin = np.min([np.nanmin(fp.transformed[:, 0]) for fp in self.focal_planes]) + ymax = np.max([np.nanmax(fp.transformed[:, 1]) for fp in self.focal_planes]) + ymin = np.min([np.nanmin(fp.transformed[:, 1]) for fp in self.focal_planes]) + return (xmin, xmax), (ymin, ymax) + + @property + def fp_valid_ids(self): + valid_ids = [] + for fp in self.focal_planes: + if fp.template is None: + continue + valid_ids += list(fp.template.valid_ids) + valid_ids = np.unique(valid_ids) + return valid_ids.tolist() + + +# Plotting Functions +def plot_ufm(focal_plane, plot_dir): + nominal = focal_plane.template_fp + measured = focal_plane.avg_fp + transformed = focal_plane.transformed + fig, (ax1, ax2) = plt.subplots(1, 2, constrained_layout=True) + # Plot pointing + ax1.scatter( + nominal[:, 0], + nominal[:, 1], + alpha=0.4, + color="blue", + label="nominal", + marker="P", + ) + ax1.scatter( + transformed[:, 0], + transformed[:, 1], + alpha=0.4, + color="black", + label="transformed", + marker="X", + ) + ax1.scatter(measured[:, 0], measured[:, 1], alpha=0.4, color="orange", label="fit") + ax1.set_xlabel("Xi (rad)") + ax1.set_ylabel("Eta (rad)") + ax1.set_aspect("equal") + ax1.legend() + + # Histogram of differences + dist = focal_plane.dist[focal_plane.isfinite] * 180 * 60 * 60 / np.pi + dist_thresh = np.percentile(dist, 97) + bins = max(int(len(dist) / 20), 10) + ax2.hist(dist[dist < dist_thresh], bins=bins) + ax2.set_xlabel("Residual (arcseconds)") + + fig.suptitle(f"{focal_plane.stream_id}") + fig.set_size_inches(2 * fig.get_size_inches()) + if plot_dir is None: + plt.show() + else: + os.makedirs(plot_dir, exist_ok=True) + plt.savefig( + os.path.join(plot_dir, f"{focal_plane.stream_id}.png"), bbox_inches="tight" + ) + plt.close() + + +def plot_ot(ot, plot_dir): + fig, (ax1, ax2) = plt.subplots(1, 2, constrained_layout=True) + dists = [ + fp.dist[fp.isfinite] * 180 * 60 * 60 / np.pi + for fp in ot.focal_planes + if fp.tot_weight is not None + ] + xis = [ + fp.transformed[fp.isfinite, 0] + for fp in ot.focal_planes + if fp.tot_weight is not None + ] + etas = [ + fp.transformed[fp.isfinite, 1] + for fp in ot.focal_planes + if fp.tot_weight is not None + ] + + # Plot the radial dist + r = np.sqrt(np.hstack(xis) ** 2 + np.hstack(etas) ** 2) + dist = np.hstack(dists) + dist_avg, edges, _ = binned_statistic(r, dist, "median", bins=50) + r_bins = (edges[:-1] + edges[1:]) / 2 + max_dist = np.max(dist) + + ax1.scatter(r, dist, alpha=0.1) + ax1.plot(r_bins, dist_avg, color="black") + ax1.set_ylim((None, np.percentile(dist, 95))) + ax1.set_xlabel("Radius (rad)") + ax2.set_ylabel("Residual (arcseconds)") + + # Plot a heatmap + cf = None + for dist, xi, eta in zip(dists, xis, etas): + cf = ax2.tricontourf( + xi, eta, dist, levels=20, vmin=-1 * max_dist, vmax=max_dist, cmap="coolwarm" + ) + if cf is not None: + fig.colorbar(cf, ax=ax2, label="arcseconds") + ax2.set_aspect("equal") + ax2.set_xlabel("Xi (rad)") + ax2.set_ylabel("Eta (rad)") + fig.suptitle(f"{ot.name}") + + fig.set_size_inches(2 * fig.get_size_inches()) + if plot_dir is None: + plt.show() + else: + os.makedirs(plot_dir, exist_ok=True) + plt.savefig(os.path.join(plot_dir, f"{ot.name}.png"), bbox_inches="tight") + plt.close() + + +def plot_by_gamma(focal_plane, plot_dir): + fig, axs = plt.subplots(1, 3, sharey=True, constrained_layout=True) + dist_thresh = np.percentile(focal_plane.dist[focal_plane.isfinite], 97) + msk = (focal_plane.dist < dist_thresh) + focal_plane.isfinite + rhombi = np.unique(focal_plane.template.rhombus) + gammas = (focal_plane.template.fp[msk, 2] * 180 / np.pi) % 180.0 + bins = np.linspace(0, 180, 13) + for i, name in enumerate(("xi", "eta", "gamma")): + d = focal_plane.diff[msk, i] * 180 * 60 * 60 / np.pi + axs[i].set_title(name) + if np.sum(np.isfinite(d)) == 0: + continue + medians, *_ = binned_statistic(gammas, d, statistic="median", bins=bins) + for rhombus in rhombi: + rmsk = focal_plane.template.rhombus[msk] == rhombus + if not (np.any(rmsk)): + continue + axs[i].scatter(gammas[rmsk], d[rmsk], alpha=0.2, label=f"Rhombus {rhombus}") + axs[i].scatter(np.arange(7.5, 180, 15), medians, color="black") + leg = axs[i].legend() + for lh in leg.legend_handles: + lh.set_alpha(1) + axs[0].set_ylabel("Diff (arcseconds)") + axs[1].set_xlabel("Nominal Gamma (deg)") + fig.suptitle(f"{focal_plane.stream_id} By Gamma") + fig.set_size_inches(2 * fig.get_size_inches()) + if plot_dir is None: + plt.show() + else: + os.makedirs(plot_dir, exist_ok=True) + plt.savefig( + os.path.join(plot_dir, f"{focal_plane.stream_id}_by_gamma.png"), + bbox_inches="tight", + ) + plt.close() + + +def plot_receiver(receiver, plot_dir): + valid_ids = receiver.valid_ids + max_diff = 0 + for fp in receiver.focal_planes: + diff = np.nanpercentile(np.abs(fp.diff), 97) + if diff > max_diff: + max_diff = diff + max_diff *= 180 * 60 * 60 / np.pi + xlims, ylims = receiver.lims + + fig, axs_all = plt.subplots( + len(valid_ids), 3, sharex="col", sharey="row", constrained_layout=True + ) + axs = axs_all.flat + axs[0].set_title("Xi") + axs[1].set_title("Eta") + axs[2].set_title("Gamma") + cf = None + for i in range(len(valid_ids)): + for j in range(3): + axs[3 * i + j].set_aspect("equal") + axs[3 * i + j].set_xlim(xlims) + axs[3 * i + j].set_ylim(ylims) + for fp in receiver.focal_planes: + if fp.tot_weight is None: + continue + msk = (fp.id_strs == valid_ids[i]) * fp.isfinite + if np.sum(msk) < 3: + continue + diff = fp.diff * 180 * 60 * 60 / np.pi + cf = axs[3 * i + 0].tricontourf( + fp.transformed[msk, 0], + fp.transformed[msk, 1], + diff[msk, 0], + levels=20, + vmin=-1 * max_diff, + vmax=max_diff, + cmap="coolwarm", + ) + cf = axs[3 * i + 1].tricontourf( + fp.transformed[msk, 0], + fp.transformed[msk, 1], + diff[msk, 1], + levels=20, + vmin=-1 * max_diff, + vmax=max_diff, + cmap="coolwarm", + ) + if fp.have_gamma: + cf = axs[3 * i + 2].tricontourf( + fp.transformed[msk, 0], + fp.transformed[msk, 1], + diff[msk, 2], + levels=20, + vmin=-1 * max_diff, + vmax=max_diff, + cmap="coolwarm", + ) + axs[3 * i + 0].set_ylabel(f"{valid_ids[i]}\nEta (rad)") + if cf is not None: + fig.colorbar(cf, ax=axs_all.ravel().tolist(), label="arcsecs") + axs[-3].set_xlabel("Xi (rad)") + axs[-2].set_xlabel("Xi (rad)") + axs[-1].set_xlabel("Xi (rad)") + fig.suptitle("Full Receiver Residuals") + fig.set_size_inches(2 * fig.get_size_inches()) + if plot_dir is None: + plt.show() + else: + os.makedirs(plot_dir, exist_ok=True) + plt.savefig(os.path.join(plot_dir, f"receiver.png"), bbox_inches="tight") + plt.close() diff --git a/sotodlib/coords/pointing_model.py b/sotodlib/coords/pointing_model.py index 2ad055ace..f64ff2345 100644 --- a/sotodlib/coords/pointing_model.py +++ b/sotodlib/coords/pointing_model.py @@ -6,6 +6,10 @@ from .helpers import _valid_arg from .optics import _interp_func from so3g.proj import quat +from functools import lru_cache +from scipy.interpolate import RegularGridInterpolator, bisplev +from scipy.ndimage import map_coordinates, spline_filter + import logging logger = logging.getLogger(__name__) @@ -107,8 +111,9 @@ def apply_pointing_model(tod, pointing_model=None, ), "When using naive pointing model, wrap_focal_plane=... not supported" return apply_basic_pointing_model(tod), None - pointing_model = _valid_arg(pointing_model, "pointing_model", src=tod) - ancil = _valid_arg(ancil, "ancil", src=tod) + if tod is not None: + pointing_model = _valid_arg(pointing_model, "pointing_model", src=tod) + ancil = _valid_arg(ancil, "ancil", src=tod) if focal_plane_template is None: _ensure_focal_plane_template(tod) focal_plane_template = _valid_arg(focal_plane_template, @@ -136,7 +141,7 @@ def apply_pointing_model(tod, pointing_model=None, ]: if control is None: control = default - if control is not False: + if control is not False and tod is not None: tod.wrap(control, item, overwrite=True) return boresight, focal_plane @@ -368,31 +373,32 @@ def apply_lat_distortion_model(params, az, el, roll, focal_plane): return focal_plane elif dist_model == 'optics': - if len(roll) > 1: - # Check that roll is ~stable and get typical value. - droll = (roll - roll[0] + np.pi) % (2 * np.pi) - np.pi - roll_mean = roll[0] + droll.mean() - # Note a 5 degree tolerance here is pretty generous; this is - # meant to not choke on "type 3" obs, where there is a ~1 deg - # elevation nod during the scan. - assert droll.std() < 5 * DEG, \ - "This distortion approximation does not work when roll varies significantly." - else: - roll_mean = roll[0] + # if len(roll) > 1: + # # Check that roll is ~stable and get typical value. + # droll = (roll - roll[0] + np.pi) % (2 * np.pi) - np.pi + # roll_mean = roll[0] + droll.mean() + # # Note a 5 degree tolerance here is pretty generous; this is + # # meant to not choke on "type 3" obs, where there is a ~1 deg + # # elevation nod during the scan. + # assert droll.std() < 5 * DEG, \ + # "This distortion approximation does not work when roll varies significantly." + # else: + # roll_mean = roll[0] # Rotate focal plane template xi-eta into the space of the # secondary mirror. xi1, eta1, _ = quat.decompose_xieta( - quat.euler(2, roll_mean) + quat.euler(2, roll) * quat.rotation_xieta(focal_plane.xi, focal_plane.eta)) # Get distortion - dxi = _interp_func(xi1, eta1, LAT_ROLL_DIST_OPTICS_V1['d_xi_bsp']) - deta = _interp_func(xi1, eta1, LAT_ROLL_DIST_OPTICS_V1['d_eta_bsp']) + # dxi = _interp_func(xi1, eta1, LAT_ROLL_DIST_OPTICS_V1['d_xi_bsp']) + # deta = _interp_func(xi1, eta1, LAT_ROLL_DIST_OPTICS_V1['d_eta_bsp']) + dxi, deta = _interpolate_map_coordinates(xi1, eta1) # Apply distortion and return to un-rolled focal_plane. xi2, eta2, _ = quat.decompose_xieta( - quat.euler(2, -roll_mean) + quat.euler(2, -roll) * quat.rotation_xieta(xi1 + dxi, eta1 + deta)) focal_plane.xi[:] = xi2 @@ -683,3 +689,25 @@ def get_base_tilt_q_2nd(az, el, dE_C2A, dE_S2A, dA_C2A, dA_S2A): 3, 3 ], } + +@lru_cache(maxsize=1) +def _get_lat_optics_grids(n_grid=2048): + tx, ty, _, kx, ky = LAT_ROLL_DIST_OPTICS_V1['d_xi_bsp'] + xi_grid = np.linspace(tx[kx], tx[-kx-1], n_grid) + eta_grid = np.linspace(ty[ky], ty[-ky-1], n_grid) + dxi_grid = np.asarray(bisplev(xi_grid, eta_grid, LAT_ROLL_DIST_OPTICS_V1['d_xi_bsp'])) + deta_grid = np.asarray(bisplev(xi_grid, eta_grid, LAT_ROLL_DIST_OPTICS_V1['d_eta_bsp'])) + dxi_coeff = spline_filter(dxi_grid, order=3) + deta_coeff = spline_filter(deta_grid, order=3) + + return xi_grid, eta_grid, dxi_coeff, deta_coeff + +def _interpolate_map_coordinates(xi, eta): + xi_grid, eta_grid, dxi_coeff, deta_coeff = _get_lat_optics_grids() + xi_idx = np.interp(xi, xi_grid, np.arange(len(xi_grid))) + eta_idx = np.interp(eta, eta_grid, np.arange(len(eta_grid))) + coords = np.array([xi_idx, eta_idx]) + dxi = map_coordinates( dxi_coeff, coords, order=3, mode='nearest', prefilter=False) + deta = map_coordinates( deta_coeff, coords, order=3, mode='nearest', prefilter=False) + + return dxi, deta diff --git a/sotodlib/preprocess/processes.py b/sotodlib/preprocess/processes.py index 725b82a95..cce2dbb68 100644 --- a/sotodlib/preprocess/processes.py +++ b/sotodlib/preprocess/processes.py @@ -3722,4 +3722,4 @@ def process(self, aman, proc_aman, sim=False, data_aman=None): _Preprocess.register(SmurfGapsFlags) _Preprocess.register(GetTauHWP) _Preprocess.register(Move) -_Preprocess.register(CutBadDistribution) +_Preprocess.register(CutBadDistribution) \ No newline at end of file diff --git a/sotodlib/site_pipeline/cli.py b/sotodlib/site_pipeline/cli.py index b6257f985..18e40a97a 100644 --- a/sotodlib/site_pipeline/cli.py +++ b/sotodlib/site_pipeline/cli.py @@ -53,6 +53,7 @@ def main(obs_id=None, config_file=None, logger=None): make_source_flags, make_uncal_beam_map, preprocess_tod, + solve_pointing_model, update_g3tsmurf_db, update_hkdb, update_obsdb, @@ -77,6 +78,7 @@ def main(obs_id=None, config_file=None, logger=None): 'make-source-flags': make_source_flags, 'make-uncal-beam-map': make_uncal_beam_map, 'preprocess-tod': preprocess_tod, + 'solve-pointing-model': solve_pointing_model, 'update-g3tsmurf-db': update_g3tsmurf_db, 'update-hkdb': update_hkdb, 'update-obsdb': update_obsdb, diff --git a/sotodlib/site_pipeline/finalize_focal_plane.py b/sotodlib/site_pipeline/finalize_focal_plane.py index d43f2e05c..71523ede5 100644 --- a/sotodlib/site_pipeline/finalize_focal_plane.py +++ b/sotodlib/site_pipeline/finalize_focal_plane.py @@ -5,6 +5,7 @@ from copy import deepcopy from importlib import import_module from typing import List, Optional +from tqdm import tqdm import matplotlib matplotlib.use('Agg') @@ -33,10 +34,11 @@ ) from sotodlib.coords.pointing_model import apply_pointing_model from sotodlib.core import AxisManager, Context, IndexAxis, metadata -from sotodlib.io.metadata import read_dataset +from sotodlib.io.metadata import read_dataset, write_dataset, ResultSet from sotodlib.site_pipeline.utils.logging import init_logger logger = init_logger(__name__, "finalize_focal_plane: ") +metadata.loader.logger.setLevel(logging.ERROR) def _create_db(filename, per_obs, obs_ids, start_time, stop_time): @@ -54,7 +56,7 @@ def _create_db(filename, per_obs, obs_ids, start_time, stop_time): os.makedirs(os.path.dirname(filename), exist_ok=True) scheme = metadata.ManifestScheme() - scheme.add_exact_match("dets:stream_id") + scheme.add_exact_match("dets:wafer.array") if per_obs: scheme.add_exact_match("obs:obs_id") else: @@ -65,7 +67,11 @@ def _create_db(filename, per_obs, obs_ids, start_time, stop_time): return metadata.ManifestDb(filename), base, group -def _avg_focalplane(full_fp, tot_weight): +def _avg_focalplane(full_fp, tot_weight, dists): + if np.sum(np.isfinite(dists)) > 1: + msk = (dists - np.nanmin(dists))/np.nanstd(dists) > 3 + msk *= np.isnan(dists) + full_fp[:, :, msk] = np.nan # Figure out how many good pointings we have for each det msk = np.isfinite(full_fp) n_obs = np.sum(np.any(msk, axis=1), axis=-1) @@ -131,9 +137,14 @@ def _gamma_min(pars, src, dst): return res.x -def _load_template(template_path, ufm, pointing_cfg): - template_rset = read_dataset(template_path, ufm) +def _load_template(template_path, stream_id, pointing_cfg, ufm): + template_rset = read_dataset(template_path, stream_id) + if "wafer_name" in template_rset.keys: + idx = np.where(template_rset["wafer_name"] == f"ufm_{ufm}")[0] + template_rset = template_rset.subset(rows=idx) det_ids = template_rset["dets:det_id"] + det_ids, i = np.unique(np.array(det_ids), return_index=True) + template_rset = template_rset.subset(rows=i) template = np.column_stack( ( np.array(template_rset["xi"]), @@ -209,15 +220,17 @@ def _get_obs_ids( return np.intersect1d(obs_ids, all_obs) -def _load_ctx(config): +def _load_ctx(config, obsfile): ctx = Context(config["context"]["path"]) if ctx.obsdb is None: raise ValueError("No obsdb!") + per_obs = config.get("per_obs", False) tod_pointing_name = config["context"].get("tod_pointing", "tod_pointing") map_pointing_name = config["context"].get("map_pointing", "map_pointing") pol_name = config["context"].get("polarization", "polarization") dm_name = config["context"].get("detmap", "detmap") roll_range = config.get("roll_range", [-1 * np.inf, np.inf]) + roll_range = [float(rr) for rr in roll_range] obs_ids = _get_obs_ids( ctx, [tod_pointing_name, map_pointing_name, pol_name], @@ -234,12 +247,17 @@ def _load_ctx(config): amans = [] dets = config["context"].get("dets", {}) failed = [] - for obs_id in obs_ids: + run = [] + if per_obs and not config.get("overwrite", False): + run = np.genfromtxt(obsfile, dtype=str) + obs_ids = np.setdiff1d(obs_ids, run) + + for obs_id in tqdm(obs_ids): roll = ctx.obsdb.get(obs_id)["roll_center"] if roll is None: continue if roll < roll_range[0] or roll > roll_range[1]: - logger.info("%s has a roll that is out of range", obs_id) + logger.debug("%s has a roll that is out of range", obs_id) continue try: aman = ctx.get_meta(obs_id, dets=dets) @@ -266,7 +284,7 @@ def _load_ctx(config): if pol: aman.move(pol_name, "polarization") else: - logger.warning("No polarization data in context") + logger.debug("No polarization data in context") if tod_pointing_name in aman: _aman = aman.copy() @@ -283,111 +301,22 @@ def _load_ctx(config): logger.error("Failed to load %s", str(failed)) # Figure out stream_ids and OTs - query_all = f"type=='obs' and start_time>{config['start_time']} and stop_time<{config['stop_time']}" ot_sid = [] - for obs in ctx.obsdb.query(query_all): - if obs["wafer_slots_list"] is None or obs["stream_ids_list"] is None: - continue - ot = obs["tube_slot"] + for aman in amans: + ot = aman.obs_info.tube_slot + tel = aman.obs_info.telescope_flavor if ot == "stp1": ot = "st1" - ot_sid += [ - (obs["telescope_flavor"], ot, ws, sid) - for ws, sid in zip( - obs["wafer_slots_list"].split(","), obs["stream_ids_list"].split(",") - ) - ] + ws = [w1 if w1 != "ws." else w2 for w1, w2 in zip(aman.det_info.wafer_slot, aman.det_info.wafer.wafer_slot)] + sid = aman.det_info.stream_id + ufm = aman.det_info.wafer.array + dat = np.column_stack([[tel]*len(ws), [ot]*len(ws), ws, sid, ufm]).tolist() + ot_sid += dat ot_sid = np.unique(np.array(ot_sid), axis=0) return amans, obs_ids, ot_sid -def _load_rset_single(config): - obs_id = config["resultsets"].get("obs_id", "") - pointing_rset = read_dataset(*config["resultsets"]["pointing"]) - pointing_aman = pointing_rset.to_axismanager(axis_key="dets:readout_id") - aman = AxisManager(pointing_aman.dets) - aman = aman.wrap("pointing", pointing_aman) - - if "polarization" in config["resultsets"]: - polarization_rset = read_dataset(*config["resultsets"]["polarization"]) - polarization_aman = polarization_rset.to_axismanager(axis_key="dets:readout_id") - aman = aman.wrap("polarization", polarization_aman) - - det_info = AxisManager(aman.dets) - dm_rset = read_dataset(*config["resultsets"]["detmap"]) - dm_aman = dm_rset.to_axismanager(axis_key="readout_id") - det_info.wrap("wafer", dm_aman) - det_info.wrap("readout_id", det_info.dets.vals, [(0, det_info.dets)]) - det_info.wrap("det_id", det_info.wafer.det_id, [(0, det_info.dets)]) - det_info.wrap( - "stream_id", - np.array([config["stream_id"].lower()] * det_info.dets.count), - [(0, det_info.dets)], - ) - det_info.wrap( - "wafer_slot", - np.array([config["wafer_slot"].lower()] * det_info.dets.count), - [(0, det_info.dets)], - ) - det_info.restrict("dets", det_info.dets.vals[det_info.det_id != ""]) - det_info.det_id = np.char.strip(det_info.det_id) # Needed for some old results - aman = aman.wrap("det_info", det_info) - aman.restrict("dets", aman.dets.vals[aman.det_info.det_id != "NO_MATCH"]) - - obs_info = AxisManager() - obs_info.wrap("telescope_flavor", config["telescope_flavor"].lower()) - obs_info.wrap("tube_slot", config["tube_slot"].lower()) - aman.wrap("obs_info", obs_info) - - smurf = AxisManager(aman.dets) - if "band" in aman.pointing: - smurf.wrap("band", np.array(aman.pointing.band, dtype=int), [(0, smurf.dets)]) - elif "wafer" in det_info and "smurf_band" in det_info.wafer: - smurf.wrap( - "band", np.array(det_info.wafer.smurf_band, dtype=int), [(0, smurf.dets)] - ) - if "channel" in aman.pointing: - smurf.wrap( - "channel", np.array(aman.pointing.channel, dtype=int), [(0, smurf.dets)] - ) - elif "wafer" in det_info and "smurf_channel" in det_info.wafer: - smurf.wrap( - "channel", - np.array(det_info.wafer.smurf_channel, dtype=int), - [(0, smurf.dets)], - ) - aman.det_info.wrap("smurf", smurf) - - return aman, obs_id - - -def _load_rset(config): - stream_id = config["stream_id"] - telescope_flavor = config["telescope_flavor"].lower() - ot = config["tube_slot"].lower() - ws = config["wafer_slot"].lower() - obs = config["resultsets"] - _config = config.copy() - obs_ids = np.array(list(obs.keys())) - amans: List[Optional[AxisManager]] = [None] * len(obs_ids) - obs_info = AxisManager() - obs_info.wrap("stream_id", stream_id) - for i, (obs_id, rsets) in enumerate(obs.items()): - _config["resultsets"] = rsets - _config["resultsets"]["obs_id"] = obs_id - aman, _ = _load_rset_single(_config) - if "det_info" not in aman or "det_id" not in aman.det_info: - raise ValueError(f"No detmap for {obs_id}") - amans[i] = aman - - return ( - amans, - obs_ids, - [(telescope_flavor, ot, ws, stream_id)], - ) - - def _mk_pointing_config(telescope_flavor, tube_slot, wafer_slot, config): config_dir = config.get("pipeline_config_dir", os.environ["PIPELINE_CONFIG_DIR"]) config_path = os.path.join(config_dir, "shared/focalplane/ufm_to_fp.yaml") @@ -399,7 +328,7 @@ def _mk_pointing_config(telescope_flavor, tube_slot, wafer_slot, config): "tube_slot": tube_slot, "wafer_slot": wafer_slot, "config_path": config_path, - "ot_config_path": config_path, + "ot_config_path": ot_config_path, "zemax_path": zemax_path, "return_fp": False, } @@ -445,10 +374,11 @@ def _restrict_inliers(aman, focal_plane): # Now kill dets that seem too far from their match fp[~inliers] = np.nan - rot, sft = mt.get_rigid(fp, focal_plane.template.fp[template_msk, :2]) - fp_aligned = mt.apply_transform(fp, rot, sft) - likelihood = mu.gen_weights(fp_aligned, focal_plane.template.fp[template_msk, :2]) - inliers *= likelihood > 0.61 # ~1 sigma cut + if np.sum(inliers) >= 4: + rot, sft = mt.get_rigid(fp, focal_plane.template.fp[template_msk, :2]) + fp_aligned = mt.apply_transform(fp, rot, sft) + likelihood = mu.gen_weights(fp_aligned, focal_plane.template.fp[template_msk, :2]) + inliers *= likelihood > 0.61 # ~1 sigma cut # Now restrict the AxisManager inlier_det_ids = focal_plane.template.det_ids[template_msk][inliers] @@ -589,6 +519,7 @@ def main(): outpath = os.path.abspath(os.path.join(outdir, f"{froot}.h5")) dbpath = os.path.join(outdir, f"{dbroot}.sqlite") logpath = os.path.join(outdir, f"{froot}.log") + obspath = os.path.join(outdir, f"{froot}.txt") os.makedirs(outdir, exist_ok=True) plot_dir_base = config.get("plot_dir", None) if plot_dir_base is not None: @@ -601,6 +532,7 @@ def main(): # Log file logfile = logging.FileHandler(logpath) logger.addHandler(logfile) + obsfile = open(obspath, "a") # Time range config["start_time"] = config.get("start_time", 0) @@ -612,16 +544,12 @@ def main(): ) # Load data - if "context" in config: - amans, obs_ids, ot_sids = _load_ctx(config) - elif "resultsets" in config: - amans, obs_ids, ot_sids = _load_rset(config) - else: - raise ValueError("No valid inputs provided") + amans, obs_ids, ot_sids = _load_ctx(config, obspath) if len(ot_sids) == 0: raise ValueError("No stream_ids found!") if np.any(ot_sids[:, 0] != ot_sids[0][0]): raise ValueError("Not all AxisManagers agree on telescope!") + logger.info("%d obs loaded", len(amans)) weight_factor = config.get("weight_factor", 1000) min_points = config.get("min_points", 50) @@ -679,7 +607,7 @@ def main(): with h5py.File(outpath, "a") as f: if group in f: rx = Receiver.load(f, group) - for tel, ot, ws, stream_id in ot_sids: + for tel, ot, ws, stream_id, ufm in ot_sids: if len(stream_ids) > 0 and stream_id not in stream_ids: continue logger.info("Working on %s", stream_id) @@ -706,7 +634,7 @@ def main(): logger.error(message, stream_id) # Make pointing config - logger.info("\t%s is in %s %s %s", stream_id, tel, ot, ws) + logger.info("\t%s is in %s %s %s", ufm, tel, ot, ws) pointing_cfg = _mk_pointing_config(tel, ot, ws, config) # Cnstructing the OT if we need to @@ -732,19 +660,20 @@ def main(): ) elif have_template: logger.info("\tLoading template from %s", template_path) - template = _load_template(template_path, stream_id, pointing_cfg) + template = _load_template(template_path, stream_id, pointing_cfg, ufm) else: raise ValueError( "No template provided and unable to generate one for some reason" ) focal_plane = FocalPlane.empty( - template, stream_id, ws, len(amans), config=cfg_str + template, ufm, ws, len(amans), config=cfg_str ) if focal_plane.template is None: raise ValueError("Template is somehow None") n_obs = 0 + dists = np.zeros(focal_plane.full_fp.shape[-1]) + np.nan for i, (aman, obs_id) in enumerate(zip(amans_restrict, obs_ids_restrict)): logger.info("\tWorking on %s", obs_id) if aman.dets.count < min_points: @@ -825,6 +754,7 @@ def main(): focal_plane.add_fp(i, fp, weights, det_boresight, template_msk) n_obs += 1 + dists[i] = np.linalg.norm(sft) # Compute the average focal plane with weights ( @@ -832,13 +762,13 @@ def main(): focal_plane.weights, focal_plane.n_point, focal_plane.n_gamma, - ) = _avg_focalplane(focal_plane.full_fp, focal_plane.tot_weight) + ) = _avg_focalplane(focal_plane.full_fp, focal_plane.tot_weight, np.array(dists)) tot_points = np.sum((focal_plane.n_point > 0).astype(int)) focal_plane.id_strs = focal_plane.template.id_strs logger.info("\t%d points from %d obs in fit", tot_points, n_obs) if tot_points < min_points: logger.error("\tToo few points! Skipping...") - if config.get("pad", False): + if config.get("pad", False) and focal_plane.stream_id not in rx.ot_dict[ot].fp_dict: logger.info("\tPadding output with template") focal_plane.transformed = focal_plane.template.fp focal_plane.tot_weight = None @@ -1086,6 +1016,16 @@ def main(): f.create_group(group) receiver.save(f, (db, base), group) + # Make a dummy for the non-matched array in LF + outdt = [ ("dets:det_id", 'U8'), ("xi", np.float32), ("eta", np.float32), ("gamma", np.float32), ("padded", np.bool_), ] + fake = np.zeros((1,), outdt) + fake[0] = ("NO_MATCH", np.nan, np.nan, np.nan, True) + write_dataset(ResultSet.from_friend(fake), f, "fake", True) + entry = {"dets:wafer.array": "", "dataset": "fake"} + entry.update(base) # type: ignore + db.add_entry(entry, filename=os.path.basename(f.filename), replace=True) + obsfile.write("\n"+"\n".join(obs_ids)) + obsfile.flush() if __name__ == "__main__": main() diff --git a/sotodlib/site_pipeline/jobdb.py b/sotodlib/site_pipeline/jobdb.py index 6db544d1f..80e719970 100644 --- a/sotodlib/site_pipeline/jobdb.py +++ b/sotodlib/site_pipeline/jobdb.py @@ -167,6 +167,10 @@ class Tag(Base): job_id = sqy.Column(sqy.Integer, sqy.ForeignKey('jobs.id')) key = sqy.Column(sqy.String) value = sqy.Column(sqy.String) + __table_args__ = ( + sqy.Index("idx_tags_job_id", "job_id"), + sqy.UniqueConstraint("job_id", "key", name="uq_tags_job_key"), + ) def __repr__(self): return f'Tag(@job_id={self.id}:{self.key}={self.value})' @@ -382,6 +386,41 @@ def remove_job(self, job_id, check_locked=False): if n == 0: raise JobLockedError() + def update_jobs(self, jobs): + with self.session_scope() as session: + for job in jobs: + # Update scalar columns + session.query(Job).filter( + Job.id == job.id + ).update( + { + "jstate": job.jstate, + "visit_time": job.visit_time, + "visit_count": job.visit_count, + "lock": job.lock, + "lock_owner": job.lock_owner, + }, + synchronize_session=False, + ) + + # Figure out tags + existing_tags = {tag.key: tag.value for tag in session.query(Tag) .filter(Tag.job_id == job.id) .all()} + new_tags = {k: str(v) for k, v in job.tags.items()} + delete_keys = set(existing_tags) - set(new_tags) + if delete_keys: + session.query(Tag).filter( + Tag.job_id == job.id, + Tag.key.in_(delete_keys), + ).delete(synchronize_session=False) + for key, value in new_tags.items(): + if key not in existing_tags: + session.add(Tag(job_id=job.id, key=key, value=value)) + elif existing_tags[key] != value: # type: ignore + session.query(Tag).filter( + Tag.job_id == job.id, + Tag.key == key, + ).update({"value": value}, synchronize_session=False) + @contextmanager def locked(self, jobs, count=None, owner=None): """Context Manager to grant exclusive access to one or more diff --git a/sotodlib/site_pipeline/solve_pointing_model.py b/sotodlib/site_pipeline/solve_pointing_model.py new file mode 100644 index 000000000..aabf8c108 --- /dev/null +++ b/sotodlib/site_pipeline/solve_pointing_model.py @@ -0,0 +1,2305 @@ +import os +import sys +import h5py +import argparse +import yaml +import logging +import numpy as np +import so3g.proj.quat as quat + +import lmfit +from lmfit import minimize, Parameters, fit_report +import shutil + +import matplotlib + +matplotlib.use("agg") +import matplotlib.pyplot as plt +import matplotlib.cm as cm + +from sotodlib.coords.helpers import _valid_arg +from sotodlib.site_pipeline import util as sp_util +from sotodlib import core +from sotodlib.coords import pointing_model as pm +from sotodlib.coords import fp_containers as fpc + +fpc.logger.setLevel(logging.ERROR) +DEG = np.pi / 180.0 +ARCMIN = DEG / 60 + +plt.rcParams["axes.grid"] = True +plt.rcParams["grid.alpha"] = 0.5 +plt.rcParams['figure.dpi'] = 500 +plt.rcParams["figure.constrained_layout.use"] = True +plt.rcParams['font.size'] = 10 + + +def load_per_obs_data(config, t0, tf): + # Load per-observation UFM center data points and weights + platform = config.get("platform") + ffp_path = config.get("ffp_path") + ufms = config.get("ufms") + per_obs_fps = config.get("per_obs_fps") + skip_tags = config.get("skip_tags", []) + + # Load nominal template data for UFM Center locations. + nom_ufm_centers = np.zeros([7, 3]) * np.nan + rx = fpc.Receiver.load_file(ffp_path) + OT = rx["0"].optics_tubes[0] + for ufm in range(len(OT.focal_planes)): + try: + index = ufms.index(OT.focal_planes[ufm].stream_id) + except: + temp_ufms = config.get("temp_ufms") + index = temp_ufms.index(OT.focal_planes[ufm].stream_id) + nom_ufm_centers[index, :3] = OT.focal_planes[ufm].center + + # The per obs .h5 file a dict with obs_id for keys + rxs = fpc.Receiver.load_file(per_obs_fps) + filelist = [obs for obs in rxs.keys() if all(skip not in obs for skip in skip_tags)] + filelist = [obs for obs in filelist if int(obs.split("_")[1]) > t0 and int(obs.split("_")[1]) < tf] + if config.get("use_these_files") is not None: + filelist = [filelist[i] for i in config.get("use_these_files")] + obs_ufm_centers = np.zeros([len(filelist), 7, 3]) * np.nan + weights_ufm = np.zeros([len(filelist), 7]) + obs_index = [] + ot_list = [] + + for i, ffp in enumerate(filelist): + this_OT = rxs[ffp].optics_tubes[0] + for u in range(len(this_OT.focal_planes)): + index = ufms.index(this_OT.focal_planes[u].stream_id) + obs_ufm_centers[i, index, :3] = this_OT.focal_planes[u].center_transformed + weights_ufm[i, index] = np.nansum(this_OT.focal_planes[u].weights) + ot_list.append(this_OT.name) + obs_index.append(i) + + weights_ufm = weights_ufm / 1720.0 + weights_ufm[weights_ufm < config.get("weight_cutoff")] = 0.0 + initial_weights_mask = np.where(weights_ufm == 0) + obs_ufm_centers[initial_weights_mask] = np.nan + obs_index = np.array(obs_index) + ot_list = np.array(ot_list) + + # Load Boresight information + ctx = core.Context(config["context"]["path"]) + obs_info = [ctx.obsdb.get(obsid) for obsid in filelist] + az_c = np.array([obs["az_center"] for obs in obs_info]) + el_c = np.array([obs["el_center"] for obs in obs_info]) + roll_c = np.array([obs["roll_center"] for obs in obs_info]) + + ancil = core.AxisManager(core.IndexAxis("samps")) + ancil.wrap("az_enc", np.repeat(az_c, 7), [(0, "samps")]) + ancil.wrap("el_enc", np.repeat(el_c, 7), [(0, "samps")]) + ancil.wrap("roll_enc", np.repeat(el_c, 7), [(0, "samps")]) + if "lat" in platform: + ancil.wrap("corotator_enc", np.repeat((el_c - 60. - roll_c), 7), [(0, "samps")]) + if "sat" in platform: + ancil.wrap("boresight_enc", np.repeat(-1 * roll_c, 7), [(0, "samps")]) + + return filelist, obs_ufm_centers, weights_ufm, nom_ufm_centers, obs_index, ot_list, ancil, roll_c + +def load_nom_focal_plane_full(config, t0, ufm): + which_template = config.get("use_as_template", "ffp") + t0 = str(t0) + if which_template == "nominal": + ffp_path = config.get("nominal") + with h5py.File(ffp_path, "r") as template_fp: + det_ids = template_fp[ufm]["dets:det_id"][:] + xi = template_fp[ufm]["xi"][:] + eta = template_fp[ufm]["eta"][:] + gamma = template_fp[ufm]["gamma"][:] + nom_det_array = np.stack((xi, eta, gamma), axis=1) + + elif which_template == "ffp": + ffp_path = config.get("ffp_path") + with h5py.File(ffp_path, "r") as template_fp: + OT = template_fp[t0]["st1"] + fpf = np.array(OT[ufm]["focal_plane_full"][:]) + # Extracting specific columns using structured arrays + det_ids = fpf[ + "dets:det_id" + ] # Assuming 'f0' corresponds to the detector IDs + xi = fpf["xi_t"] # Assuming 'f1' corresponds to xi + eta = fpf["eta_t"] # Assuming 'f2' corresponds to eta + gamma = fpf["gamma_t"] # Assuming 'f3' corresponds to gamma + nom_det_array = np.stack((xi, eta, gamma), axis=1) + + return det_ids, nom_det_array + + +def _create_size_mask(obs_index): + #create comparably sized datasets of all obs. + unique, counts = np.unique(obs_index, return_counts=True) + min_count = min(counts) + limiting_mask = np.zeros_like(obs_index, dtype=bool) + for dataset in unique: + indices = np.where(obs_index == dataset)[0] + selected_indices = np.random.choice(indices, min_count, replace=False) + limiting_mask[selected_indices] = True + return limiting_mask + + +def _create_culling_mask(obs_index, cull_dets): + if cull_dets <= 1: + return np.ones_like(obs_index, dtype=bool) + # Remove a random fraction 1/cull_dets of each dataset + unique, counts = np.unique(obs_index, return_counts=True) + #min_count = min(counts) + culling_mask = np.zeros_like(obs_index, dtype=bool) + for dataset, count in zip(unique, counts): + indices = np.where(obs_index == dataset)[0] + selected_indices = np.random.choice(indices, (cull_dets - 1)* count // cull_dets, replace=False) + culling_mask[selected_indices] = True + return culling_mask + + +def load_per_detector_data(config, t0, tf, no_downsample=False, return_all_dets=False): + per_obs_fps = config.get("per_obs_fps") + skip_tags = config.get("skip_tags", []) + rxs = fpc.Receiver.load_file(per_obs_fps) + which_data = config.get("use_as_data") + which_weights = config.get("use_as_weights", None) + ctx = core.Context(config["context"]["path"]) + min_dets = config.get("min_per_obs_dets", 0) + weight_cutoff = config.get("weight_cutoff") + + if return_all_dets: + band = None + cull_dets = config.get("cull_dets", None) + cull_twice = config.get("cull_twice", False) + even_obs_size = False + which_ufm = None + filelist = [obs for obs in rxs.keys() if all(skip not in obs for skip in skip_tags)] + filelist = [obs for obs in filelist if int(obs.split("_")[1]) > t0 and int(obs.split("_")[1]) < tf] + + else: + band = config.get("band") + if band is not None: + band = band.encode("utf-8") + cull_dets = config.get("cull_dets", None) + cull_twice = config.get("cull_twice", False) + even_obs_size = config.get("even_obs_size", False) + which_ufm = config.get("which_ufm", None) + filelist = [obs for obs in rxs.keys() if all(skip not in obs for skip in skip_tags)] + filelist = [obs for obs in filelist if int(obs.split("_")[1]) > t0 and int(obs.split("_")[1]) < tf] + if config.get("use_these_files") is not None: + filelist = [filelist[i] for i in config.get("use_these_files")] + + obs_dets_fits, det_boresight, weights_dets, stream_id_list, ot_list, obs_index, all_det_ids, all_nom_det_array = [], [], [], [], [], [], [], [] + for i, ffp in enumerate(filelist): + obs_info = ctx.obsdb.get(ffp) + this_OT = rxs[ffp].optics_tubes[0] + for ufm in this_OT.focal_planes: + if ufm.padded: + continue + if which_ufm is not None and ufm.stream_id not in which_ufm: + continue + stream_id_list.append(ufm.stream_id) + if which_weights == "r2": + weights = ufm.weights[:, 1] + elif which_weights == "ffp": + weights = ufm.weights[:, 1] + elif which_weights == "both": + weights = ufm.weights[:, 0] * ufm.weights[:, 1] + else: + weights = np.ones(len(ufm.weights)) + wmsk = (weights > weight_cutoff) * np.isfinite(weights) + n = np.sum(wmsk) + weights_dets.append(weights[wmsk]) + data = ufm.avg_fp if which_data == "raw" else ufm.transformed + obs_dets_fits.append(data[wmsk]) + obs_index.append(np.repeat(i, n)) + ot_list.append([this_OT.name] * n) + all_det_ids.append(ufm.det_ids[wmsk]) + all_nom_det_array.append(ufm.template_fp[wmsk]) + try: + det_pointing = np.rad2deg(ufm.det_boresight) + #det_boresight.append(ufm.det_boresight) + except: + # ufm.det_boresight not found, filling with average boresight values. + az_c = np.ones(np.shape(data)[0]) * obs_info["az_center"] + el_c = np.ones(np.shape(data)[0]) * obs_info["el_center"] + roll_c = np.ones(np.shape(data)[0]) * obs_info["roll_center"] + det_pointing = np.column_stack([az_c, el_c, roll_c]) + det_pointing[:,2] = np.ones(np.shape(data)[0]) * obs_info["roll_center"] + det_boresight.append(det_pointing[wmsk]) + + all_det_ids = np.concatenate(all_det_ids) + all_nom_det_array = np.concatenate(all_nom_det_array, axis=0) + weights_dets = np.concatenate(weights_dets) + obs_dets_fits = np.concatenate(obs_dets_fits, axis=0) + det_boresight = np.concatenate(det_boresight, axis=0) + obs_index = np.concatenate(obs_index) + ot_list = np.concatenate(ot_list) + + #Order: [data fits, detector boresight, weights, nominal, ids, index] + data_group = [obs_dets_fits, det_boresight, weights_dets, all_nom_det_array, all_det_ids, obs_index, ot_list] + + mask = ~np.isnan(weights_dets) + if not no_downsample: + # Reduce detector counts for computation + if band is not None: + mask &= np.array([band in det for det in all_det_ids]) + data_group = [arr[mask] for arr in data_group] + + if even_obs_size: + m = _create_size_mask(data_group[-1]) + data_group = [arr[m] for arr in data_group] + + if cull_dets is not None: + for _ in range(2 if cull_twice else 1): + m = _create_culling_mask(data_group[-1], cull_dets) + data_group = [arr[m] for arr in data_group] + else: + # Only apply weights mask, (Used for plotting) + data_group = [arr[mask] for arr in data_group] + + return (filelist, *data_group) + + +def build_data_aman(config, t0, tf, per_det = True, no_downsample=False, return_all_dets=False): + aman = core.AxisManager(core.IndexAxis("samps")) + obs_info = core.AxisManager() + obs_info.wrap("platform", config.get("platform")) + + if not per_det: + ( + filelist, + obs_ufm_centers, + weights_ufm, + nom_ufm_centers, + obs_index, + ot_list, + ancil, + roll_c, + ) = load_per_obs_data(config, t0, tf) + obs_info.wrap("obs_ids", np.array(filelist)) + aman.wrap("obs_info", obs_info) + aman.wrap("ancil", ancil) + aman.wrap("roll_c", np.repeat(roll_c, 7), [(0, "samps")]) + aman.wrap( + "nominal_xieta_locs", + np.repeat([nom_ufm_centers], len(filelist), axis=0) + .reshape(len(filelist) * 7, 3) + .T, + [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"])), + (1, "samps")], + ) + aman.wrap( + "measured_xieta_data", + obs_ufm_centers.reshape(len(filelist) * 7, 3).T, + [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"])), + (1, "samps")], + ) + aman.wrap("weights", weights_ufm.reshape(-1), [(0, "samps")]) + aman.wrap("obs_index", obs_index) + + return aman + + else: + ( + filelist, + obs_dets_fits, + det_boresight, + weights_dets, + all_nom_det_array, + all_det_ids, + obs_index, + ot_list, + ) = load_per_detector_data(config, t0, tf, no_downsample, return_all_dets) + ancil = core.AxisManager(core.IndexAxis("samps")) + ancil.wrap("az_enc", det_boresight[:,0], [(0, "samps")]) + ancil.wrap("el_enc", det_boresight[:,1], [(0, "samps")]) + ancil.wrap("roll_c", det_boresight[:,2], [(0, "samps")]) + if "lat" in obs_info.platform: + ancil.wrap("corotator_enc", ancil.el_enc - 60. - ancil.roll_c, [(0, "samps")]) + elif "sat" in obs_info.platform: + ancil.wrap("boresight_enc", -1 * det_boresight[:,2], [(0, "samps")]) + obs_info.wrap("obs_ids", np.array(filelist)) + aman.wrap("obs_info", obs_info) + aman.wrap("ancil", ancil) + aman.wrap("roll_c", det_boresight[:,2], [(0, "samps")]) + aman.wrap( + "nominal_xieta_locs", all_nom_det_array.T, + [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"])), + (1, "samps")], + ) + aman.wrap( + "measured_xieta_data", obs_dets_fits.T, + [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"])), + (1, "samps")], + ) + aman.wrap("weights", weights_dets, [(0, "samps")]) + aman.wrap("det_ids", all_det_ids, [(0, "samps")]) + aman.wrap("obs_index", obs_index, [(0, "samps")]) + aman.wrap("ot_list", ot_list, [(0, "samps")]) + aman.wrap("unq_ots", np.unique(ot_list)) + + return aman + + +def _init_fit_params(config, epochs): + pm_version = config.get("pm_version") + initial_params = config.get("initial_params", {}) + fixed_params = config.get("fixed_params",[]) + float_ots = config.get("float_ots", False) + init_params = pm.param_defaults[pm_version] + init_params.update(initial_params) + init_min = {key:-np.inf for key in init_params.keys()} + init_max = {key:np.inf for key in init_params.keys()} + + # Add independant params + orig_pars = np.array(list(init_params.keys())) + par_list = orig_pars.copy() + all_ots = np.unique(np.concatenate([np.unique(epoch["solver_aman"].ot_list) for epoch in epochs])) + if float_ots: + for ot in all_ots: + ot_float_pars = [f"{n}_{ot}" for n in ["xioff", "etaoff", "rot", "xiscale", "etascale"]] + orig_pars = np.concatenate((orig_pars, ot_float_pars)) + par_list = np.concatenate((par_list, ot_float_pars)) + for p, d, mi, ma in zip(ot_float_pars, [0, 0, 0, 1, 1], [-.05, -.05, -np.pi, .9, .9], [.05, .05, np.pi, 1.1, 1.1]): + init_params[p] = d + init_min[p] = mi + init_max[p] = ma + for epoch in epochs: + indep_list = epoch["indep_list"] + if float_ots: + for ot in all_ots: + ot_float_pars = [f"{n}_{ot}" for n in ["xioff", "etaoff", "rot", "xiscale", "etascale"]] + indep_list += ot_float_pars + if ot not in epoch["solver_aman"].ot_list: + fixed_params += [f"{n}_{epoch['name']}" for n in ot_float_pars] + if np.sum(np.isin(indep_list, par_list)) != len(indep_list): + raise ValueError(f"Invalid independant parameters in epoch {epoch['name']}") + indep_list = [f"{n}_{epoch['name']}" for n in indep_list] + par_list = np.hstack((par_list, indep_list)) + for ipar, par in zip(indep_list, epoch["indep_list"]): + init_params[ipar] = init_params[par] + init_min[ipar] = init_min[par] + init_max[ipar] = init_max[par] + par_count = np.zeros(len(par_list)) + all_indep_list = [] + for epoch in epochs: + indep_list = epoch["indep_list"] + all_indep_list += indep_list + pmsk = np.zeros(len(par_list), bool) + pmsk[:len(orig_pars)] = True + pmsk[np.isin(par_list, indep_list)] = False + pmsk += np.array([epoch["name"] in par for par in par_list]) + if np.sum(pmsk) != len(orig_pars): + raise ValueError(f"Epoch {epoch['name']} somehow has the wrong number of parameters!") + par_count[pmsk] += 1 + epoch["params"] = par_list[pmsk] + fixed_params += par_list[par_count == 0].tolist() + all_indep_list = np.array(all_indep_list) + + # Initialize lmfit Parameter object + fit_params = Parameters() + for p in init_params.keys(): + if p in all_indep_list and np.sum(all_indep_list == p) == len(epochs): + continue + fit_params.add(p, value=init_params[p], vary=True, min=init_min[p], max=init_max[p]) + # Turn off various parameters depending on platform + for fix in fixed_params: + if fix in fit_params: + fit_params[fix].set(vary=False) + + return fit_params, epochs + + +def _apply_ot_float(xi_mod, eta_mod, solver_aman, params): + # For simplicity we do the floating of OTs to just the model + ot_float_pars = ["xioff", "etaoff", "rot", "xiscale", "etascale"] + ot_float_defaults = np.array([0., 0., 0., 1., 1.]) + ot_pars_full = np.array([[params.get(f"{n}_{ot}", d) for n, d in zip(ot_float_pars, ot_float_defaults)] for ot in solver_aman.unq_ots]) + # To avoid the fitter using this to eat up encoder offsets we remove a common mode + ot_pars_full[:, :3] -= np.mean(ot_pars_full[:, :3], axis=0) + for i, ot in enumerate(solver_aman.unq_ots): + if not np.all(np.isfinite(ot_pars_full[i])): + raise ValueError( + f"Non-finite OT parameters for {ot}: {ot_pars_full[i]}" + ) + ot_pars = ot_pars_full[i] + if np.array_equal(ot_pars, ot_float_defaults): + continue + msk = (solver_aman.ot_list == ot) + msk[msk] *= np.isfinite(xi_mod[msk]) * np.isfinite(eta_mod[msk]) + if np.sum(msk) == 0: + continue + xi_mod[msk] += ot_pars[0] + eta_mod[msk] += ot_pars[1] + theta = ot_pars[2] + R = np.array([[np.cos(theta), -np.sin(theta)], + [np.sin(theta), np.cos(theta)]]) + xi_cent = np.nanmean(xi_mod[msk]) + eta_cent = np.nanmean(eta_mod[msk]) + xi_mod[msk], eta_mod[msk] = R@np.vstack((xi_mod[msk] - xi_cent, eta_mod[msk] - eta_cent)) + xi_mod[msk] += xi_cent + eta_mod[msk] += eta_cent + xi_mod[msk] *= ot_pars[3] + eta_mod[msk] *= ot_pars[4] + return xi_mod, eta_mod + + +def objective_model_func_lmfit( + params, pm_version, solver_aman, xieta_model, weights=True +): + if xieta_model == "measured": + xi_mod, eta_mod = model_measured_xieta(params, pm_version, solver_aman) + xi_ref, eta_ref, _ = solver_aman.measured_xieta_data + elif xieta_model == "template": + xi_mod, eta_mod = model_template_xieta(params, pm_version, solver_aman) + xi_ref, eta_ref, _ = solver_aman.nominal_xieta_locs + else: + raise ValueError("xieta_model must be measured or template") + + xi_mod, eta_mod = _apply_ot_float(xi_mod, eta_mod, solver_aman, params) + + dist = np.sqrt((xi_ref - xi_mod) ** 2 + (eta_ref - eta_mod) ** 2) + weights_array = solver_aman.weights if weights else np.ones(len(dist)) + + return (np.nan_to_num(dist, False, 1e10) * np.sqrt(weights_array)) + + +def objective_model_func_lmfit_joint( + params, pm_version, epochs, xieta_model, fit_method, weights=True +): + params = params.valuesdict() + chisq = 0 + all_residuals=[] + for epoch in epochs: + epoch_params = {par.split(f"_{epoch['name']}")[0]:params[par] for par in epoch["params"]} + res = objective_model_func_lmfit(epoch_params, pm_version, epoch["solver_aman"], xieta_model, weights) + # res = 60*np.rad2deg(res) + if fit_method == "leastsq" or fit_method == "least_squares": + all_residuals.append(res) + else: + chisq += np.nansum(res**2) + if fit_method == "leastsq" or fit_method == "least_squares": + return np.concatenate(all_residuals) + return chisq + + +def model_template_xieta(params, pm_version, aman): + """ + Transform a measured (xi,eta) back into template position + Data to Template -- modeling data as true template + Quat math is based on this equation: + q_nomodel * q_det_meas == q_model * q_det_true + """ + xi_meas = aman.measured_xieta_data[0] + eta_meas = aman.measured_xieta_data[1] + params = params.valuesdict() if isinstance(params, Parameters) else params + params["version"] = pm_version + if "sat" in pm_version: + az, el, roll = pm._get_sat_enc_radians(aman.ancil) + + q_nomodel = quat.rotation_lonlat(-az, el, 0) + if "lat" in pm_version: + az, el, roll = pm._get_lat_enc_radians(aman.ancil) + q_nomodel = quat.rotation_lonlat(-az, el, roll) + boresight = pm.apply_pointing_model(aman, pointing_model=params, wrap=False) + az1, el1, roll1 = boresight.az, boresight.el, boresight.roll + q_model = quat.rotation_lonlat(-az1, el1, roll1) + q_det_meas = quat.rotation_xieta(xi_meas, eta_meas, 0) + xi_mod_true, eta_mod_true, _ = quat.decompose_xieta( + ~q_model * q_nomodel * q_det_meas + ) + return xi_mod_true, eta_mod_true + +def model_measured_xieta(params, pm_version, aman): + """ + Transform template (xi,eta) to match measured (xi,eta). + Template to Data -- modeling the template as measured data + Quat math is based on this equation: + q_nomodel * q_det_meas == q_model * q_det_true + """ + params = params.valuesdict() if isinstance(params, Parameters) else params + params["version"] = pm_version + xi_true, eta_true, gam_true = aman.nominal_xieta_locs + if "sat" in pm_version: + az, el, roll = pm._get_sat_enc_radians(aman.ancil) + q_nomodel = quat.rotation_lonlat(-az, el, 0) + elif "lat" in pm_version: + az, el, roll = pm._get_lat_enc_radians(aman.ancil) + q_nomodel = quat.rotation_lonlat(-az, el, roll) + else: + raise ValueError("Pointing model must be for sat or lat!") + + boresight = pm.apply_pointing_model(aman, pointing_model=params, wrap=False) + az1, el1, roll1 = boresight.az, boresight.el, boresight.roll + q_model = quat.rotation_lonlat(-az1, el1, roll1) + q_det_true = quat.rotation_xieta(xi_true, eta_true, 0) + xi_mod_meas, eta_mod_meas, _ = quat.decompose_xieta( + ~q_nomodel * q_model * q_det_true + ) + + return xi_mod_meas, eta_mod_meas + + +def calc_RMS_and_residuals(modeled_fits, model_reference, weights, use_inds=None): + diff = ((modeled_fits[0] - model_reference[0]) / ARCMIN) ** 2 +\ + ((modeled_fits[1] - model_reference[1]) / ARCMIN) ** 2 + if use_inds is not None: + diff = diff[use_inds] + weights = weights[use_inds] + diff[weights == 0] = np.nan + return np.sqrt(np.nansum(diff * weights) / np.nansum(weights)), diff**0.5 + + +def apply_model_params(xieta_model, pointing_model, pm_version, aman, use_inds=None): + #fetch_RMS_and_residuals + #Apply PM parameters to either template or data points, calc RMS, return residuals. + if xieta_model == "measured": + model_reference = aman.measured_xieta_data + modeled_fits = model_measured_xieta( + pointing_model, pm_version, aman + ) + elif xieta_model == "template": + model_reference = aman.nominal_xieta_locs + modeled_fits = model_template_xieta( + pointing_model, pm_version, aman + ) + modeled_fits = _apply_ot_float(modeled_fits[0], modeled_fits[1], aman, pointing_model) + rms, fit_residuals = calc_RMS_and_residuals(modeled_fits, model_reference, aman.weights, use_inds=use_inds) + return modeled_fits, fit_residuals, rms, model_reference + + +def _round_params(param_dict, decimal): + P = {} + for k in list(param_dict.keys()): + P[k] = np.round(param_dict[k], decimal) + return P + + +def get_full_correlation_matrix(lmfit_result, epoch_params): + """Returns a square matrix for ALL parameters, including fixed ones.""" + #param_names = list(lmfit_result.params.keys()) + param_names = epoch_params.tolist() + full_corr_mat = np.eye(len(param_names)) + for i, n1 in enumerate(param_names): + p1 = lmfit_result.params[n1] + if p1.vary and p1.correl: + for j, n2 in enumerate(param_names): + if i != j and n2 in p1.correl: + full_corr_mat[i, j] = p1.correl[n2] + return full_corr_mat, param_names + + +def analyze_PM_with_all_dets(config, t0, tf, params): + full_aman = build_data_aman(config, t0, tf, per_det = True, no_downsample=False, return_all_dets=True) + ufm_list = [ufm.split("_")[1] for ufm in config.get('ufms')] + xi_nom, eta_nom = full_aman.nominal_xieta_locs[0], full_aman.nominal_xieta_locs[1] + full_aman.wrap("radial", np.sqrt(xi_nom ** 2 + eta_nom ** 2) / DEG, [(0, "samps")]) + #np.sqrt(full_aman.nominal_xieta_locs[0]**2 + full_aman.nominal_xieta_locs[1]**2)/DEG, + det_ufms = np.array([d.decode('utf-8').split('_')[0].lower() for d in full_aman.det_ids]) + full_aman.wrap("det_ufm", det_ufms, [(0, "samps")]) + full_aman.wrap("det_wafer", + np.array([ufm_list.index(d) for d in det_ufms]), + [(0, "samps")]) + # Apply model to data. + xieta_model = config.get("xieta_model", "measured") + (full_modeled, full_residuals, rms, _ + ) = apply_model_params(xieta_model, + params, + config.get("pm_version"), + full_aman) + if xieta_model == "template": + to_comp = "nominal_xieta_locs" + if xieta_model == "measured": + to_comp = "measured_xieta_data" + full_aman.wrap("full_modeled", np.array(full_modeled), + [(0, core.LabelAxis("xieta", ["xi", "eta"])),(1, "samps")]) + full_aman.wrap("fit_residuals", full_residuals, [(0, "samps")]) + + # Just for compatibility + modelfit_aman = core.AxisManager() + modelfit_aman.wrap("xi", full_modeled[0], overwrite=True) + modelfit_aman.wrap("eta", full_modeled[1], overwrite=True) + full_aman.wrap("modeled_fits", modelfit_aman, overwrite=True) + + dxi_all = (full_aman.full_modeled[0] - full_aman[to_comp][0]) / DEG * 60 + deta_all = (full_aman.full_modeled[1] - full_aman[to_comp][1]) / DEG * 60 + + full_aman.wrap("dxi", dxi_all, [(0, "samps")]) + full_aman.wrap("deta", deta_all, [(0, "samps")]) + + stats_map = { + 'az' : full_aman.ancil.az_enc, 'el' : full_aman.ancil.el_enc, + 'roll' : full_aman.roll_c, 'resid' : full_aman.fit_residuals, + 'dxi': full_aman.dxi, 'deta': full_aman.deta, 'cr': getattr(full_aman.ancil, 'corotator_enc', None) + } + per_obs = {k: [] for k in stats_map if stats_map[k] is not None} + per_obs.update({'std_xi': [], 'std_eta': []}) + per_ufm = {k: [] for k in stats_map if stats_map[k] is not None} + per_ufm.update({'std_xi': [], 'std_eta': [], 'wafer_num': []}) + unique_obs_ids = np.unique(full_aman.obs_index) + for ob in unique_obs_ids: + o_mask = (full_aman.obs_index == ob) + for k, vals in stats_map.items(): + if vals is not None: + per_obs[k].append(np.nanmedian(vals[o_mask]) if k in ['az', 'el', 'roll', 'cr'] else np.nanmean(vals[o_mask])) + per_obs['std_xi'].append(np.nanstd(dxi_all[o_mask])) + per_obs['std_eta'].append(np.nanstd(deta_all[o_mask])) + #Calculate per ufm stats for this obs + ufm_row = {k: [] for k in per_ufm} + for ufm in ufm_list: + u_mask = o_mask & (full_aman.det_ufm == ufm) + for k, vals in stats_map.items(): + if vals is not None: + ufm_row[k].append(np.nanmedian(vals[u_mask]) if k in ['az', 'el', 'roll', 'cr'] else np.nanmean(vals[u_mask])) + ufm_row['std_xi'].append(np.nanstd(dxi_all[u_mask])) + ufm_row['std_eta'].append(np.nanstd(deta_all[u_mask])) + ufm_row['wafer_num'].append(np.nanmedian(full_aman.det_wafer[u_mask])) + + for k in per_ufm: + per_ufm[k].append(ufm_row[k]) + + per_ufm_stats = core.AxisManager() + per_obs_stats = core.AxisManager() + for k, vals in per_obs.items(): + per_obs_stats.wrap(k, np.array(vals)) + for k, vals in per_ufm.items(): + per_ufm_stats.wrap(k, np.array(vals)) + + #Add obsids and RMS stats + obsids=np.array([int(D.split('_')[1]) for D in full_aman.obs_info.obs_ids]) + per_obs_stats.wrap("obsids", obsids) + per_ufm_stats.wrap("obsids", + np.repeat(obsids, + np.shape(per_ufm_stats["dxi"])[1]) + ) + full_aman.wrap("obsids", obsids[full_aman.obs_index], [(0, "samps")]) + + #Calculate RMSs + for aman in [per_obs_stats, per_ufm_stats, full_aman]: + aman.wrap("rms", np.sqrt(np.nanmean(aman['dxi'] ** 2 + aman['deta'] ** 2))) + + full_aman.wrap("per_ufm_stats", per_ufm_stats) + full_aman.wrap("per_obs_stats", per_obs_stats) + + return full_aman + +def _create_db(filename, save_dir): + db_filename = os.path.join(save_dir, filename) + # Get Database ready + if os.path.exists(db_filename): + return core.metadata.ManifestDb(db_filename) + else: + os.makedirs(save_dir, exist_ok=True) + scheme = core.metadata.ManifestScheme() + scheme.add_range_match("obs:timestamp") + scheme.add_data_field("dataset") + core.metadata.ManifestDb(scheme=scheme).to_file(db_filename) + return core.metadata.ManifestDb(db_filename) + + +def get_parser(parser=None): + if parser is None: + parser = argparse.ArgumentParser() + parser.add_argument("config_path", help="Path to Configuration File") + return parser + + +def main(config_path: str): + # Read relevant config file info + with open(config_path, "r", encoding="utf-8") as file: + config = yaml.safe_load(file) + platform = config.get("platform") # e.g. satp1 + pm_version = config.get("pm_version") # e.g. sat_v1 + sv_tag = config.get("solution_version_tag") # e.g. YYMMDDr# + xieta_model = config.get("xieta_model", "measured") + fit_method = config.get("fit_method", "leastsq") + xe_tag = f"{xieta_model}_xieta" + iterate_cutoff = config.get("iterate_cutoff", None) + plotlims = config.get("plotlims", 20) + append_string = config.get("append", "") + if append_string is not None: + append_tag = f"{bool(append_string)*'_'}{append_string}" + else: + append_tag = "" + which_ufm = config.get("which_ufm", "") + if which_ufm is not None: + which_ufm = which_ufm if isinstance(which_ufm, list) else [which_ufm] + suffixes = [ufm.split("_")[-1] for ufm in which_ufm] + ufm_tag = "_" + "_".join(suffixes) + else: + ufm_tag = "" + band = config.get("band", None) + if config.get("band") is not None: + band_tag = f"_{band}" + else: + band_tag = "" + save_dir = os.path.join( + config.get("outdir"), + f"{platform}_pointing_model_{sv_tag}", + f"{xe_tag}{append_tag}{ufm_tag}{band_tag}", + ) + os.makedirs(save_dir, exist_ok=True) + shutil.copy(config_path, os.path.join(save_dir, "config.yaml")) + + # Initialize Logger + logger = sp_util.init_logger(__name__, "Solve pointing_model") + logpath = os.path.join(save_dir, "pointing_model.log") + logfile = logging.FileHandler(logpath) + logger.addHandler(logfile) + + if xieta_model != "measured" and xieta_model != "template": + logger.error( + 'Not recognized xieta_model. \ + Only "measured" or "template" accepted' + ) + sys.exit() + + epochs = config.get("epochs") + for epoch in epochs: + if "name" not in epoch: + epoch["name"] = f"t{epoch['begin_timerange']}" + if "indep_list" not in epoch: + epoch["indep_list"] = [] + if epochs is None: + raise ValueError("No epochs provided") + + if config.get("just_test_params"): + logger.info("Will test initial_parameters against pointing data.") + for epoch in epochs: + t0, tf = epoch["begin_timerange"], epoch["end_timerange"] + + test_params, epochs = _init_fit_params(config, epochs) + logger.info("Using these parameters to test pointing: ") + for p in test_params: + logger.info(f"{p}: {test_params[p].value}") + #logger.info(test_params) + full_aman = analyze_PM_with_all_dets(config, t0, tf, test_params) + logger.info(f"for epoch {epoch['name']}") + logger.info(f"full rms: {full_aman.rms:.3f} (arcmin) ") + logger.info(f"obs_rms: {full_aman.per_obs_stats.rms:.3f} (arcmin) ") + logger.info(f"ufm_rms: {full_aman.per_ufm_stats.rms:.3f} (arcmin) ") + plotter = ModelFitsPlotter(solver_aman=full_aman, + config=config, + save_dir=save_dir, + t0=t0, + tf=tf, + iteration_tag=f"_{epoch["name"]}", + save_figure=True, + plotlims=plotlims) + plotter.plot_full_residuals_across_focalplane() + plotter.plot_full_deltas_across_focalplane() + plotter.plot_full_histogram() + plotter.plot_full_unmodeled_residuals() + logger.info("done") + return + + logger.info( + "Pointing model will try to replicate (model) the %s data.", xieta_model + ) + fit_type = config.get("fit_type", "detector") + ########################################################## + ### Begin split for per-detector or per-UFM center fitting + ########################################################## + if fit_type == "detector": + + which_ufm = config.get("which_ufm", None) + if which_ufm is not None: + logger.info( + "Performing per-detector fits for subset of UFMs: %s. ", which_ufm + ) + else: + logger.info("Performing per-detector fits for all UFM data.") + + which_data = config.get("use_as_data") + use_weights = config.get("use_weights", True) + + + for epoch in epochs: + t0, tf = epoch["begin_timerange"], epoch["end_timerange"] + # Make axis manager with full detector set. + # Keep wafer/band/obs cuts but do not further downsample. + fitcheck_aman = build_data_aman(config, t0, tf, per_det = True, no_downsample=True) + logger.info("Loaded %s fit check data points", len(fitcheck_aman.weights)) + + #Now make axis manager that has down sampled data for computation + solver_aman = build_data_aman(config, t0, tf, per_det = True, no_downsample=False) + logger.info("Loaded %s data points", len(solver_aman.weights)) + + epoch["solver_aman"] = solver_aman + epoch["fitcheck_aman"] = fitcheck_aman + logger.info("Built axis manager for epoch %s", epoch["name"]) + + ########################################################################### + elif fit_type == "ufm_center": + use_weights = config.get("use_weights", True) + # Load in focal_plane and boresight data + for epoch in epochs: + t0, tf = epoch["begin_timerange"], epoch["end_timerange"] + solver_aman = build_data_aman(config, t0, tf, per_det=False) + logger.info("Loaded per-obs FFP data from %s: ", config.get("per_obs_fps")) + logger.info("Including data from these obs:") + logger.info(solver_aman.obs_info.obs_ids) + + epoch["solver_aman"] = solver_aman + logger.info("Built axis manager for epoch %s", epoch["name"]) + else: + raise ValueError("fit_type must be detector or ufm_center") + + ################################ + # END of SPLIT: Now fit the parameters + ################################ + + # Initialize Parameters to Fit with Model + fit_params, epochs = _init_fit_params(config, epochs) + logger.info("Initialized fit parameters") + + init_cut = config.get("init_cut", -1) + if init_cut > 0: + params = fit_params.valuesdict() + for epoch in epochs: + epoch_params = {par.split(f"_{epoch['name']}")[0]:params[par] for par in epoch["params"]} + res = 60*np.rad2deg(objective_model_func_lmfit(epoch_params, pm_version, epoch["solver_aman"], xieta_model, False)) + fres = 60*np.rad2deg(objective_model_func_lmfit(epoch_params, pm_version, epoch["fitcheck_aman"], xieta_model, False)) + fmed = np.median(fres) + msk = res - fmed > init_cut + fmsk = fres - fmed > init_cut + logger.info("Cutting %d (%d in full) samples that are more than %f arcmin away from median resid in epoch %s", int(np.sum(msk)), int(np.sum(fmsk)), init_cut, epoch['name']) + epoch["solver_aman"].weights[msk] = 0 + epoch["fitcheck_aman"].weights[fmsk] = 0 + + # Solve for Model Parameters + # use chosen xieta_model to solve for parameters + model_solved_params = minimize( + objective_model_func_lmfit_joint, + fit_params, + method=fit_method, + nan_policy="omit", + args=(pm_version, epochs, xieta_model, fit_method, use_weights), + **config.get("fit_options", {}), + ) + logger.info("Ran 1st Minimization") + + test_params = _round_params(model_solved_params.params.valuesdict(), 8) + test_params["version"] = pm_version + logger.info("Found best-fit pointing model parameters") + logger.info(test_params) + logger.info(model_solved_params.params.pretty_print(precision=5, colwidth=11)) + logger.info("Fit Report:") + logger.info(fit_report(model_solved_params)) + + # save pointing model parameters to axis manager + for epoch in epochs: + par_mapping = {par:par.split(f"_{epoch['name']}")[0] for par in epoch["params"]} + param_aman = core.AxisManager() + for k in list(par_mapping.keys()): + param_aman.wrap(par_mapping[k], test_params[k]) + param_aman.wrap("version", pm_version) + epoch["solver_aman"].wrap("pointing_model", param_aman) + + #Save Fit report statistics + model_fit_stats_aman = core.AxisManager() + stderr_aman = core.AxisManager() + for k in list(model_solved_params.params.values()): + if k.name in epoch["params"]: + stderr_aman.wrap(par_mapping[k.name], k.stderr) + model_fit_stats_aman.wrap('stderr', stderr_aman) + + fitreport_aman = core.AxisManager() + fitreport_aman.wrap('chisq', model_solved_params.chisqr) + fitreport_aman.wrap('redchi', model_solved_params.redchi) + fitreport_aman.wrap('success', int(model_solved_params.success)) # 1 for True, 0 for False + fitreport_aman.wrap('nfev', model_solved_params.nfev) # Num function evaluations + fitreport_aman.wrap('message', + str(model_solved_params.message)) + model_fit_stats_aman.wrap('fit_report', fitreport_aman) + + #if config.get("fit_method", "leastsq") == "leastsq": + mat, param_names = get_full_correlation_matrix(model_solved_params, epoch["params"]) + corrmtx_aman = core.AxisManager(core.LabelAxis('params', param_names)) + corrmtx_aman.wrap('matrix', mat, [(0, 'params'), (1, 'params')]) + corrmtx_aman.wrap('param_names', np.array(param_names), [(0, 'params')]) + model_fit_stats_aman.wrap('correlation_matrix', corrmtx_aman) + epoch["solver_aman"].wrap('model_fit_statistics', model_fit_stats_aman) + + # Model template and measured points using parameters found above + logger.info("Calculating RMS and cutoff for %s", epoch["name"]) + modeled_fits, fit_residuals_i1, rms_i1, model_reference = apply_model_params(xieta_model, epoch["solver_aman"].pointing_model, pm_version, epoch["solver_aman"]) + logger.info("RMS on fit: %f arcmin", rms_i1) + + # Save fit results to the axis manager + modelfit_aman = core.AxisManager() + modelfit_aman.wrap("xi", modeled_fits[0], overwrite=True) + modelfit_aman.wrap("eta", modeled_fits[1], overwrite=True) + epoch["solver_aman"].wrap("modeled_fits", modelfit_aman, overwrite=True) + epoch["solver_aman"].wrap("fit_residuals", fit_residuals_i1, overwrite=True) + epoch["solver_aman"].wrap("fit_rms", rms_i1, overwrite=True) + + if fit_type == "detector": + _, fit_residuals_full, rms_full, _ = apply_model_params(xieta_model, epoch["solver_aman"].pointing_model, pm_version, epoch["fitcheck_aman"]) + logger.info("RMS on FULL detector set: %f arcmin", rms_full) + epoch["solver_aman"].wrap("fit_residuals_full", fit_residuals_full, overwrite=True) + epoch["solver_aman"].wrap("fit_rms_full", rms_full, overwrite=True) + epoch["solver_aman"].wrap("obs_index_full", epoch["fitcheck_aman"].obs_index) + + cutoff = np.nanstd(fit_residuals_i1)*2 + np.nanmedian(fit_residuals_i1) + logger.info(f"2 stdev away from residual Median: {cutoff:.2f} arcmin") + + if config.get("make_plots"): + t0, tf = epoch["begin_timerange"], epoch["end_timerange"] + plotter = ModelFitsPlotter(solver_aman=epoch["solver_aman"], + config=config, + save_dir=save_dir, + t0=t0, + tf=tf, + iteration_tag=f"_{epoch['name']}_i1", + save_figure=True, + plotlims=plotlims) + if fit_type == "ufm_center": + plotter.plot_ws0_modeled_fits() + plotter.plot_template_space_fits_per_wafer() + plotter.plot_residuals_vs_ancil() + plotter.plot_xieta_cross_residuals() + plotter.plot_xieta_residuals() + plotter.plot_fit_correlation_matrix() + else: + plotter.plot_modeled_fits() + plotter.plot_template_space_fits_per_detector() + plotter.plot_residuals_vs_ancil() + plotter.plot_residuals_histograms() + plotter.plot_dets_in_these_obs() + plotter.plot_fit_correlation_matrix() + + tot_bad=0 + if iterate_cutoff is not None: + logger.info("Iterating parameter solution") + logger.info(f"Using {iterate_cutoff} as cutoff") + for epoch in epochs: + logger.info("Appylying cutoff to %s", epoch["name"]) + fit_residuals_i1 = epoch["solver_aman"].fit_residuals + cutoff = iterate_cutoff + if iterate_cutoff == "auto": + cutoff = np.nanstd(fit_residuals_i1)*2 + np.nanmedian(fit_residuals_i1) + logger.info(f"Using {cutoff} as cutoff") + bad_fit_inds = np.where(fit_residuals_i1 > cutoff)[0] + logger.info("Bad fit indices:") + logger.info(bad_fit_inds) + logger.info( + "%f data points are higher than %s arcmin", + len(bad_fit_inds), + cutoff, + ) + tot_bad += len(bad_fit_inds) + + if len(bad_fit_inds) != 0: + if fit_type == "ufm_center": + bad_filename = bad_fit_inds // 7 + bad_wafer = bad_fit_inds % 7 + logger.info("Outliers:") + for i, full_i in enumerate(bad_fit_inds): + logger.info( + f"{filelist[bad_filename[i]]}; ws{bad_wafer[i]}; Resid. {np.round(fit_residuals_i1[full_i], 4)}" + ) + logger.info( + f"--- Roll {solver_aman.roll_c[full_i]}; El {solver_aman.ancil.el_enc[full_i]}; weight {np.round(solver_aman.weights[full_i],4)}" + ) + + # Print RMS of initial fits without outlying data points before + # zero-ing the weights. + good_fit_inds = np.where(fit_residuals_i1 < cutoff)[0] + _, _, masked_rms, _ = apply_model_params(xieta_model, + epoch["solver_aman"].pointing_model, + pm_version, + epoch["solver_aman"], + use_inds=good_fit_inds) + + logger.info("RMS on initial fit without outliers: %f arcmin", masked_rms) + epoch["solver_aman"].weights[bad_fit_inds] = 0 + epoch["solver_aman"].wrap('bad_fit_inds', bad_fit_inds) + + if tot_bad == 0: + logger.info("No bad points found so not running second fit!") + if tot_bad > 0: + model_solved_params = minimize( + objective_model_func_lmfit_joint, + model_solved_params.params, + method=fit_method, + nan_policy="omit", + args=(pm_version, epochs, xieta_model, fit_method, use_weights), + **config.get("fit_options", {}) + ) + + test_params = _round_params(model_solved_params.params.valuesdict(), 8) + test_params["version"] = pm_version + logger.info("Found best-fit pointing model parameters, second iteration") + logger.info(test_params) + logger.info( + model_solved_params.params.pretty_print(precision=5, colwidth=11) + ) + logger.info("Fit Report:") + logger.info(lmfit.fit_report(model_solved_params)) + + # save pointing model parameters to axis manager + for epoch in epochs: + par_mapping = {par:par.split(f"_{epoch['name']}")[0] for par in epoch["params"]} + epoch["solver_aman"].move("pointing_model", "pointing_model_i1") + param_aman = core.AxisManager() + for k in list(par_mapping.keys()): + param_aman.wrap(par_mapping[k], test_params[k]) + param_aman.wrap("version", pm_version) + epoch["solver_aman"].wrap("pointing_model", param_aman) + + # save errors to axis manager + epoch["solver_aman"].move("model_fit_statistics", "model_fit_statistics_i1") + model_fit_stats_aman = core.AxisManager() + stderr_aman = core.AxisManager() + for k in list(model_solved_params.params.values()): + if k.name in epoch["params"]: + stderr_aman.wrap(par_mapping[k.name], k.stderr) + model_fit_stats_aman.wrap('stderr', stderr_aman) + + fitreport_aman = core.AxisManager() + fitreport_aman.wrap('chisq', model_solved_params.chisqr) + fitreport_aman.wrap('redchi', model_solved_params.redchi) + fitreport_aman.wrap('success', int(model_solved_params.success)) # 1 for True, 0 for False + fitreport_aman.wrap('nfev', model_solved_params.nfev) # Num function evaluations + fitreport_aman.wrap('message', str(model_solved_params.message)) + model_fit_stats_aman.wrap('fit_report', fitreport_aman) + + #if config.get("fit_method", "leastsq") == "leastsq": + mat, param_names = get_full_correlation_matrix(model_solved_params, epoch["params"]) + corrmtx_aman = core.AxisManager(core.LabelAxis('params', param_names)) + corrmtx_aman.wrap('matrix', mat, [(0, 'params'), (1, 'params')]) + corrmtx_aman.wrap('param_names', np.array(param_names), [(0, 'params')]) + model_fit_stats_aman.wrap('correlation_matrix', corrmtx_aman) + + epoch["solver_aman"].wrap('model_fit_statistics', model_fit_stats_aman) + + # Recalculate best-fit modeled points + logger.info("Calculating RMS for %s", epoch["name"]) + modeled_fits, fit_residuals_i2, rms_i2, model_reference = apply_model_params(xieta_model, + epoch["solver_aman"].pointing_model, + pm_version, + epoch["solver_aman"]) + + logger.info("RMS on secondary fit: %f arcmin", rms_i2) + + # Save fit results to the axis manager + modelfit_aman = core.AxisManager() + modelfit_aman.wrap("xi", modeled_fits[0], overwrite=True) + modelfit_aman.wrap("eta", modeled_fits[1], overwrite=True) + epoch["solver_aman"].wrap("modeled_fits", modelfit_aman, overwrite=True) + epoch["solver_aman"].move("fit_residuals", "fit_residuals_i1") + epoch["solver_aman"].wrap("fit_residuals", fit_residuals_i2, overwrite=True) + epoch["solver_aman"].move("fit_rms", "fit_rms_i1") + epoch["solver_aman"].wrap("fit_rms", rms_i2, overwrite=True) + + if fit_type == "detector": + _, fit_residuals_full, rms_full, _ = apply_model_params(xieta_model, epoch["solver_aman"].pointing_model, pm_version, epoch["fitcheck_aman"]) + logger.info("RMS on FULL detector set: %f arcmin", rms_full) + epoch["solver_aman"].move("fit_residuals_full", "fit_residuals_full_i1") + epoch["solver_aman"].move("fit_rms_full", "fit_rms_full_i1") + epoch["solver_aman"].wrap("fit_residuals_full", fit_residuals_full, overwrite=True) + epoch["solver_aman"].wrap("fit_rms_full", rms_full, overwrite=True) + + if config.get("make_plots"): + tag = f"_{epoch['name']}_i2" + t0, tf = epoch["begin_timerange"], epoch["end_timerange"] + plotter = ModelFitsPlotter(solver_aman=epoch["solver_aman"], + config=config, + save_dir=save_dir, + t0=t0, + tf=tf, + iteration_tag=tag, + save_figure=True, + plotlims=plotlims) + plotter.plot_total_residuals() + plotter.plot_residuals_vs_ancil() + if fit_type == "ufm_center": + plotter.plot_ws0_modeled_fits() + plotter.plot_template_space_fits_per_wafer() + plotter.plot_xieta_cross_residuals() + plotter.plot_xieta_residuals() + plotter.plot_fit_correlation_matrix() + else: + plotter.plot_modeled_fits() + plotter.plot_template_space_fits_per_detector() + plotter.plot_residuals_histograms() + plotter.plot_dets_in_these_obs() + plotter.plot_fit_correlation_matrix() + else: + if config.get("make_plots"): + for epoch in epochs: + t0, tf = epoch["begin_timerange"], epoch["end_timerange"] + plotter = ModelFitsPlotter(solver_aman=epoch["solver_aman"], + config=config, + save_dir=save_dir, + t0=t0, + tf=tf, + iteration_tag=f"_{epoch["name"]}", + save_figure=True, + plotlims=plotlims) + plotter.plot_total_residuals() + + if config.get("save_output"): + # Save .h5 and ManifestDb + h5_rel = "pointing_model_data.h5" + h5_filename = os.path.join(save_dir, h5_rel) + dbfile = "db.sqlite" + db = _create_db(dbfile, save_dir) + all_ots = np.unique(np.concatenate([epoch["solver_aman"].unq_ots for epoch in epochs])) + for epoch in epochs: + solver_aman = epoch["solver_aman"] + # Remove OT float parameters + if config.get("float_ots", False): + ot_float_aman = core.AxisManager() + for ot in all_ots: + for par in [f"{n}_{ot}" for n in ["xioff", "etaoff", "rot", "xiscale", "etascale"]]: + if par not in solver_aman.pointing_model._assignments: + continue + ot_float_aman.wrap(par, solver_aman.pointing_model[par]) + solver_aman.pointing_model.move(par, None) + solver_aman.wrap("ot_float_aman", ot_float_aman) + epoch["solver_aman"] = solver_aman + epoch["solver_aman"].save(h5_filename, group=epoch["name"], overwrite=True) + db.add_entry( + {"obs:timestamp": (epoch["begin_timerange"], epoch["end_timerange"]), "dataset": f"{epoch['name']}/pointing_model"}, + filename=h5_rel, + replace=True, + ) + + #Optional extra plotting + if config.get("make_full_analysis_plots", True): + for epoch in epochs: + #Fill up axis manager with ALL the data (only cuts from culling and time stamps remain) + t0, tf = epoch["begin_timerange"], epoch["end_timerange"] + + if "pointing_model_i1" in epoch["solver_aman"]: + test_params = epoch["solver_aman"].pointing_model_i1 + else: + test_params = epoch["solver_aman"].pointing_model + if "ot_float_aman" in epoch["solver_aman"]._assignments: + test_params = test_params.merge(epoch["solver_aman"].ot_float_aman) + full_aman = analyze_PM_with_all_dets(config, t0, tf, test_params) + logger.info(f"for this epoch: {epoch["name"]}") + logger.info(f"full rms: {full_aman.rms:.3f} (arcmin) ") + logger.info(f"obs_rms: {full_aman.per_obs_stats.rms:.3f} (arcmin) ") + logger.info(f"ufm_rms: {full_aman.per_ufm_stats.rms:.3f} (arcmin) ") + plotter = ModelFitsPlotter(solver_aman=full_aman, + config=config, + save_dir=save_dir, + t0 = t0, + tf = tf, + iteration_tag=f"_{epoch["name"]}", + save_figure=True, + plotlims=plotlims, + ) + plotter.plot_full_residuals_across_focalplane() + plotter.plot_full_deltas_across_focalplane() + plotter.plot_full_histogram() + plotter.plot_full_unmodeled_residuals() + + + logger.info("Done") + + +#################### +# Plotting Functions +#################### + +class ModelFitsPlotter: + def __init__(self, solver_aman, config, save_dir, t0, tf, iteration_tag="", save_figure=True, plotlims=None): + + self.aman = solver_aman + self.config = config + self.tag = iteration_tag + self.save_figure = save_figure + if plotlims is not None: + self.plotlims = plotlims + else: + self.plotlims = config.get("plotlims", 20) + plot_dir = os.path.join(save_dir, "plots") + os.makedirs(plot_dir, exist_ok=True) + self.plot_dir = plot_dir + self.t0 = t0 + self.tf = tf + self.platform = config.get("platform") + self.pm_version = config.get("pm_version") + self.ufms = config.get("ufms") + self.which_ufm = config.get("which_ufm",None) + self.xieta_model = config.get("xieta_model", "measured") + self.append_string = config.get("append","") + self.iterate_cutoff = config.get("iterate_cutoff", None) + + def plot_full_unmodeled_residuals(self): + platform = self.platform + plot_dir = self.plot_dir + tag = self.tag + append = self.append_string + + ancil = self.aman.ancil + modeled = self.aman.full_modeled + nominal_xieta_locs = self.aman.nominal_xieta_locs + per_ufm_stats = self.aman.per_ufm_stats + per_obs_stats = self.aman.per_obs_stats + roll_c = self.aman.roll_c + full_dxi_av = np.nanmean(self.aman.dxi) + full_deta_av = np.nanmean(self.aman.deta) + if "sat" in platform: + elmin, elmax = 40, 65 + rollmin, rollmax = -45, 45 + azmin, azmax = 0, 360 + if platform=="satp2": + plotlim = self.plotlims*0.7 + else: + plotlim = 8 + else: + plotlim = self.plotlims + elmin, elmax = None, None + rollmin, rollmax = -70, 40 + azmin, azmax = 0, 360 + + plt.figure(figsize=(7,5)) + plt.scatter((modeled[0] - nominal_xieta_locs[0])/DEG*60, + (modeled[1] - nominal_xieta_locs[1])/DEG*60, + c=roll_c, s=2.7, + alpha=0.15, marker='.', cmap='jet', + vmin=rollmin, vmax=rollmax) + plt.scatter(per_ufm_stats.dxi, per_ufm_stats.deta, + c=per_ufm_stats.roll, + alpha=0.6, marker='o', cmap='jet', + s=25, edgecolor='k', linewidth=0.7, + vmin=rollmin, vmax=rollmax, label='UFM Avg') + plt.scatter(per_obs_stats.dxi, per_obs_stats.deta, + c = per_obs_stats.roll, + alpha=0.99, marker='X', cmap='jet', + s=45, edgecolor='k', linewidth=0.7, + vmin=rollmin, vmax=rollmax, label='Obs Avg.') + plt.colorbar(label='Roll') + plt.xlabel('Xi Error (arcmin)') + plt.ylabel('Eta Error (arcmin)') + plt.axvline(0,0,1, color='k', alpha=0.4) + plt.axhline(0,0,1, color='k', alpha=0.4) + plt.axhline(0,0,1, color='k', alpha=0.4) + plt.xlim(-plotlim,plotlim); plt.ylim(-plotlim,plotlim) + plt.scatter(full_dxi_av, full_deta_av, color='r', marker='o', edgecolor='k', label='All Data Avg. Offset') + plt.legend(fontsize='small') + if self.save_figure: + plt.savefig(f"{plot_dir}/{platform}_full_2D_Residuals_Roll{tag}.png") + plt.close() + + + plt.figure(figsize=(7,5)) + plt.scatter((modeled[0] - nominal_xieta_locs[0])/DEG*60, + (modeled[1] - nominal_xieta_locs[1])/DEG*60, + c=ancil.el_enc, s=2.7, + alpha=0.15, marker='.', cmap='jet', + vmin=elmin, vmax=elmax) + plt.scatter(per_ufm_stats.dxi, per_ufm_stats.deta, + c=per_ufm_stats.el, + alpha=0.6, marker='o', cmap='jet', + s=25, edgecolor='k', linewidth=0.7, + vmin=elmin, vmax=elmax, label='UFM Avg') + plt.scatter(per_obs_stats.dxi, per_obs_stats.deta, + c = per_obs_stats.el, + alpha=0.99, marker='X', cmap='jet', + s=45, edgecolor='k', linewidth=0.7, + vmin=elmin, vmax=elmax, label='Obs Avg.') + plt.colorbar(label='Elevation') + plt.xlabel('Xi Error (arcmin)') + plt.ylabel('Eta Error (arcmin)') + plt.axvline(0,0,1, color='k', alpha=0.4) + plt.axhline(0,0,1, color='k', alpha=0.4) + plt.axhline(0,0,1, color='k', alpha=0.4) + plt.xlim(-plotlim,plotlim); plt.ylim(-plotlim,plotlim) + plt.scatter(full_dxi_av, full_deta_av, color='r', marker='o', edgecolor='k', label='All Data Avg. Offset') + plt.legend(fontsize='small') + if self.save_figure: + plt.savefig(f"{plot_dir}/{platform}_full_2D_Residuals_El{tag}.png") + plt.close() + + plt.figure(figsize=(7,5)) + plt.scatter((modeled[0] - nominal_xieta_locs[0])/DEG*60, + (modeled[1] - nominal_xieta_locs[1])/DEG*60, + c=ancil.az_enc%360, s=2.7, + alpha=0.15, marker='.', cmap='jet', + vmin=azmin, vmax=azmax) + plt.scatter(per_ufm_stats.dxi, per_ufm_stats.deta, + c=per_ufm_stats.az%360, + alpha=0.6, marker='o', cmap='jet', + s=25, edgecolor='k', linewidth=0.7, + vmin=azmin, vmax=azmax, label='UFM Avg') + plt.scatter(per_obs_stats.dxi, per_obs_stats.deta, + c = per_obs_stats.az%360, + alpha=0.99, marker='X', cmap='jet', + s=45, edgecolor='k', linewidth=0.7, + vmin=azmin, vmax=azmax, label='Obs Avg.') + plt.colorbar(label='Azimuth') + plt.xlabel('Xi Error (arcmin)') + plt.ylabel('Eta Error (arcmin)') + plt.axvline(0,0,1, color='k', alpha=0.4) + plt.axhline(0,0,1, color='k', alpha=0.4) + plt.axhline(0,0,1, color='k', alpha=0.4) + plt.xlim(-plotlim,plotlim); plt.ylim(-plotlim,plotlim) + plt.scatter(full_dxi_av, full_deta_av, color='r', marker='o', edgecolor='k', label='All Data Avg. Offset') + plt.legend(fontsize='small') + if self.save_figure: + plt.savefig(f"{plot_dir}/{platform}_full_2D_Residuals_Az{tag}.png") + plt.close() + + + def plot_full_residuals_across_focalplane(self): + platform = self.platform + plot_dir = self.plot_dir + tag = self.tag + append = self.append_string + ancil = self.aman.ancil + + weights = self.aman.weights + fit_residuals = self.aman.fit_residuals + nominal_xieta_locs = self.aman.nominal_xieta_locs + + fig, ax = plt.subplots() + im = ax.scatter(nominal_xieta_locs[0], nominal_xieta_locs[1], + c=fit_residuals, alpha=0.11, cmap='jet', + linewidth=0, s=15, vmax=self.plotlims) + sm = cm.ScalarMappable(cmap=im.cmap, norm=im.norm) + sm.set_array([]) + plt.colorbar(sm, ax=ax, label='Fit Residual (arcmin)') + ax.set_xlabel('Xi (rad)') + ax.set_ylabel('Eta (rad)') + plt.title('Fit Residuals across Focal Plane\n(Not averaged per det)') + if platform == 'lat': + plt.xlim(-.042, .042);plt.ylim(-.042, .042) + else: + plt.xlim(-.31, .31);plt.ylim(-.31, .31) + if self.save_figure: + plt.savefig(f"{plot_dir}/{platform}_full_FocalPlane_colored_FitResiduals{tag}.png") + + def plot_full_deltas_across_focalplane(self): + platform = self.platform + plot_dir = self.plot_dir + tag = self.tag + append = self.append_string + ancil = self.aman.ancil + + xi, eta, _ = self.aman.nominal_xieta_locs + dxi = self.aman.modeled_fits.xi - self.aman.nominal_xieta_locs[0] + deta = self.aman.modeled_fits.eta - self.aman.nominal_xieta_locs[1] + roll_c = self.aman.roll_c + + fig, ax = plt.subplots() + im = ax.quiver(xi, eta, dxi, deta, roll_c, angles='xy', scale=1/34.4, scale_units='xy', alpha=.2) + sm = cm.ScalarMappable(cmap=im.cmap, norm=im.norm) + sm.set_array([]) + plt.colorbar(sm, ax=ax, label='Roll') + ax.set_xlabel('Xi (rad)') + ax.set_ylabel('Eta (rad)') + plt.title('Fit Deltas across Focal Plane\n(Not averaged per det)') + if platform == 'lat': + plt.xlim(-.042, .042);plt.ylim(-.042, .042) + else: + plt.xlim(-.31, .31);plt.ylim(-.31, .31) + if self.save_figure: + plt.savefig(f"{plot_dir}/{platform}_full_FocalPlane_colored_FitDeltas{tag}.png") + + def plot_full_histogram(self): + platform = self.platform + plotlims = self.plotlims + plot_dir = self.plot_dir + tag = self.tag + append = self.append_string + + det_rms = self.aman.rms + ufm_rms = self.aman.per_ufm_stats.rms + obs_rms = self.aman.per_obs_stats.rms + fit_residuals = self.aman.fit_residuals + #median = np.nanmedian(fit_residuals) + + plt.figure() + plt.hist(fit_residuals, bins=50, range=(0, plotlims)) + plt.axvline(det_rms , 0, 1, color='k', + label=f'Full RMS {det_rms:.2f} arcmin') + plt.axvline(obs_rms, 0, 1, color='c', + label = f'Obs RMS {obs_rms:.2f} arcmin') + plt.axvline(ufm_rms, 0, 1, color='m', + label=f'UFM RMS {ufm_rms:.2f} arcmin') + #plt.axvline(median, 0, 1, color='r', linestyle=':', + # label='median arcmin') + #plt.axvline(median+np.nanmedian(np.abs(fit_residuals- median))*1.4826, + # 0, 1, color = 'y', linestyle=':') + plt.legend(fontsize='medium') + plt.title(platform + ' 1D residuals') + plt.xlabel('arcmin') + + if self.save_figure: + plt.savefig(f"{plot_dir}/{platform}_full_Hist_Residuals{tag}.png") + + def plot_dets_in_these_obs(self): + platform = self.platform + plot_dir = self.plot_dir + measured_xieta_data = self.aman.measured_xieta_data + weights = self.aman.weights + roll_c = self.aman.roll_c + elev = self.aman.ancil.el_enc + azim = self.aman.ancil.az_enc + if platform == 'lat': + elmin=10; elmax=90 + else: + elmin=40; elmax=65 + + plt.figure() + fig, ax = plt.subplots(2,2,figsize=(11,10)) + ax[0,0].set_title('color by boresight.roll', fontsize='medium') + a0 = ax[0,0].scatter(measured_xieta_data[0], measured_xieta_data[1], + c=roll_c, alpha=0.5, s=10, + cmap='jet',vmin=-45,vmax=45) + ax[1,0].set_title('color by fit Elevation', fontsize='medium') + a1= ax[1,0].scatter(measured_xieta_data[0], measured_xieta_data[1], + c=elev, alpha=0.3, s=10, cmap='jet', vmin=elmin, vmax=elmax) + ax[0,1].set_title('color by fit Azimuth', fontsize='medium') + a2= ax[0,1].scatter(measured_xieta_data[0], measured_xieta_data[1], + c=azim, alpha=0.3, s=10, cmap='jet', vmin=0, vmax=420) + ax[1,1].set_title('color by fit weights', fontsize='medium') + a3= ax[1,1].scatter(measured_xieta_data[0], measured_xieta_data[1], + c=weights, alpha=0.3, s=10, cmap='jet', vmin=0.8, vmax=1) + c0 = plt.colorbar(a0) + c1 = plt.colorbar(a1) + c2 = plt.colorbar(a2) + c3 = plt.colorbar(a3) + + plt.suptitle('Detectors hit in these observations') + if self.save_figure: + plt.savefig(f"{plot_dir}/{platform}_dets_in_these_obs.png") + plt.close() + + def plot_modeled_fits(self): + platform = self.platform + plot_dir = self.plot_dir + tag = self.tag + ancil = self.aman.ancil + nominal_xieta_locs = self.aman.nominal_xieta_locs + measured_xieta_data = self.aman.measured_xieta_data + weights = self.aman.weights + modeled_fits = self.aman.modeled_fits + fit_rms = self.aman.fit_rms + if self.which_ufm is not None: + if isinstance(self.which_ufm, list): + ufm_list = self.which_ufm + else: + ufm_list = [self.which_ufm] + else: + ufm_list = self.ufms + plotmask = np.where(weights) + if ufm_list is not None: + nom_array = np.concatenate( + [load_nom_focal_plane_full(self.config, self.t0, ufm)[1] for ufm in ufm_list], + axis=0, + ) + rms = np.round(fit_rms, 4) + xi_model_fit = modeled_fits.xi + eta_model_fit = modeled_fits.eta + if self.xieta_model == "measured": + xi_ref, eta_ref, _ = measured_xieta_data + elif self.xieta_model == "template": + xi_ref, eta_ref, _ = nominal_xieta_locs + if 'sat' in platform: + markercolor = ancil.boresight_enc.copy() + coloredby = "Boresight" + elif 'lat' in platform: + markercolor = ancil.corotator_enc.copy() + coloredby = "Corotator" + scale_weights = weights / np.nanmax(weights) + #### + fig = plt.figure(figsize=(6, 6)) + gs = fig.add_gridspec(2, 2) + ax = fig.add_subplot(gs[:, :]) + ax.scatter( + xi_ref[plotmask] / DEG, + eta_ref[plotmask] / DEG, + c=markercolor[plotmask], + alpha=0.4, + label="Data", + edgecolors="k", + linewidths=0.4, + s=130 * scale_weights[plotmask], + cmap="jet", + vmax=65, + ) + sc3 = ax.scatter( + xi_model_fit / DEG, + eta_model_fit / DEG, + marker="*", + c=markercolor, + cmap="jet", + alpha=0.4, + edgecolor="k", + lw=0.4, + s=65, + label=f"Model, RMS = {rms}", + vmax=65, + ) + if ufm_list is not None: + ax.scatter( + nom_array[:, 0] / DEG, + nom_array[:, 1] / DEG, + marker=".", + color="r", + alpha=0.2, + label="Nominal Center", + ) + offsets = sc3.get_offsets() + #xmin, ymin = offsets.min(axis=0) + #xmax, ymax = offsets.max(axis=0) + ax.legend(loc=1, fontsize="small") + ax.set_xlabel("Xi (deg)") + ax.set_ylabel("Eta (deg)") + cb = plt.colorbar(sc3, fraction=0.046, pad=0.04) + cb.ax.set_title(coloredby) + ax.set_title(f"Fits, Colored by {coloredby} (deg)") + + # Plot lines connecting data to modeled data point + xitoxi = np.empty((len(xi_model_fit), 2)) + xitoxi[:, 0] = xi_ref / DEG + xitoxi[:, 1] = xi_model_fit / DEG + etatoeta = np.empty((len(eta_model_fit), 2)) + etatoeta[:, 0] = eta_ref / DEG + etatoeta[:, 1] = eta_model_fit / DEG + ax.plot(xitoxi.T, etatoeta.T, "k", lw=0.4) + # plt.tight_layout() + if self.save_figure: + plt.savefig(f"{plot_dir}/{platform}_model_fits{tag}.png") + plt.close() + + + def plot_ws0_modeled_fits(self): + platform = self.platform + plot_dir = self.plot_dir + xieta_model = self.xieta_model + tag = self.tag + ancil = self.aman.ancil + nominal_xieta_locs = self.aman.nominal_xieta_locs + measured_xieta_data = self.aman.measured_xieta_data + weights = self.aman.weights + modeled_fits = self.aman.modeled_fits + fit_rms = self.aman.fit_rms + + xi_model_fit = modeled_fits.xi + eta_model_fit = modeled_fits.eta + if xieta_model == "measured": + xi_ref, eta_ref, _ = measured_xieta_data + elif xieta_model == "template": + xi_ref, eta_ref, _ = nominal_xieta_locs + markercolor = [ancil.el_enc.copy(), ancil.boresight_enc.copy(), ancil.az_enc.copy()] + coloredby = ["El", "Boresight", "Az"] + vmins = [40, -50, 0] + vmaxs = [65, 50, 360] + scale_weights = weights / np.nanmax(weights) + plotmask = np.where(weights)[0] + rms = np.round(fit_rms, 4) + + # Calculate lines connecting data to modeled data point + xitoxi = np.empty((len(xi_model_fit), 2)) + xitoxi[:, 0] = xi_ref / DEG + xitoxi[:, 1] = xi_model_fit / DEG + etatoeta = np.empty((len(eta_model_fit), 2)) + etatoeta[:, 0] = eta_ref / DEG + etatoeta[:, 1] = eta_model_fit / DEG + + #### + #fig = plt.figure(figsize=(6, 6)) + #gs = fig.add_gridspec(2, 2) + #ax = fig.add_subplot(gs[:, :]) + fig, ax = plt.subplots(1,3, figsize=(9,4), sharey=True) + for x in range(3): + ax[x].plot( + nominal_xieta_locs[0, : 7 + 1] / DEG, + nominal_xieta_locs[1, : 7 + 1] / DEG, + "rx", + label="Nominal Center", + ) + ax[x].scatter( + xi_ref[plotmask] / DEG, + eta_ref[plotmask] / DEG, + c=markercolor[x][plotmask], + alpha=0.4, + label="Data", + edgecolors="k", + linewidths=0.4, + s=130 * scale_weights[plotmask], + cmap="jet", + vmin=vmins[x], + vmax=vmaxs[x], + ) + im = ax[x].scatter( + xi_model_fit[plotmask] / DEG, + eta_model_fit[plotmask] / DEG, + marker="*", + c=markercolor[x][plotmask], + cmap="jet", + edgecolor="gray", + lw=0.3, + s=130, + label=f"Model, RMS = {rms}", + vmin=vmins[x], + vmax=vmaxs[x], + ) + ax[x].legend(loc=1, fontsize="small") + ax[x].set_xlabel("Xi (deg)") + ax[x].set_ylabel("Eta (deg)") + cb = plt.colorbar(im, fraction=0.046, pad=0.04) + cb.ax.set_title(coloredby[x]) + ax[x].set_title(f"Fits, Colored by {coloredby[x]} (deg)") + ax[x].plot(xitoxi.T, etatoeta.T, "k", lw=0.4,alpha=0.5) + ax[x].set_xlim(-1.05, 0.25) + ax[x].set_ylim(-0.2, 0.2) + # plt.subplots_adjust(left=0.1, right=0.90, bottom=0.05, hspace=0.3) + # plt.tight_layout() + if self.save_figure: + plt.savefig(f"{plot_dir}/{platform}_ws0_model_fits{tag}.png") + plt.close() + + + def plot_template_space_fits_per_wafer(self): + platform = self.platform + plot_dir = self.plot_dir + plotlims = self.plotlims + pm_version = self.pm_version + tag = self.tag + ancil = self.aman.ancil + roll_c = self.aman.roll_c + nominal_xieta_locs = self.aman.nominal_xieta_locs + measured_xieta_data = self.aman.measured_xieta_data + weights = self.aman.weights + pointing_model = self.aman.pointing_model + modeled_fits = self.aman.modeled_fits + fit_rms = self.aman.fit_rms + + scale_weights = weights / np.nanmax(weights) + xi_unmod, eta_unmod = model_template_xieta( + pointing_model, + pm_version, + self.aman + ) + xi0, eta0 = model_template_xieta( + pm.param_defaults[pm_version], + pm_version, + self.aman + ) + #Plot with Elevation as colorbar + fig, ax = plt.subplots(2, 4, figsize=(9, 6)) + for i in range(7): + ax[i // 4, i % 4].plot(0, 0, "kx", label="Nominal Center") + im = ax[i // 4, i % 4].scatter( + xi_unmod[i::7] / ARCMIN - nominal_xieta_locs[0, i] / ARCMIN, + eta_unmod[i::7] / ARCMIN - nominal_xieta_locs[1, i] / ARCMIN, + c=ancil.el_enc[i::7], + s=scale_weights[i::7] * 80, + edgecolor="gray", + lw=0.3, + marker="o", + alpha=0.5, + cmap="jet", + ) + ax[i // 4, i % 4].set_xlim(-1 * plotlims, plotlims) + ax[i // 4, i % 4].set_ylim(-1 * plotlims, plotlims) + ax[i // 4, i % 4].set_title(f"ws{i}") + ax[i // 4, i % 4].set_aspect('equal', adjustable='box') + plt.colorbar(im, ax[1, 3], label="Elevation (deg)", fraction=0.046, pad=0.04) + # plt.tight_layout() + if self.save_figure: + plt.savefig(f"{plot_dir}/{platform}_unmodeled_fits_WS_elevation{tag}.png") + plt.close() + #Plot with Roll as colorbar + fig, ax = plt.subplots(2, 4, figsize=(9, 6)) + if "sat" in pm_version: + markercolor = -1*ancil.boresight_enc[i::7].copy() + if "lat" in pm_version: + markercolor = roll_c[i::7].copy() + coloredby = "roll" + for i in range(7): + ax[i // 4, i % 4].plot(0, 0, "kx", label="Nominal Center") + im = ax[i // 4, i % 4].scatter( + xi_unmod[i::7] / ARCMIN - nominal_xieta_locs[0, i] / ARCMIN, + eta_unmod[i::7] / ARCMIN - nominal_xieta_locs[1, i] / ARCMIN, + c=markercolor, + s=scale_weights[i::7] * 80, + edgecolor="gray", + lw=0.3, + marker="o", + alpha=0.5, + cmap="jet", + ) + ax[i // 4, i % 4].set_xlim(-1 * plotlims, plotlims) + ax[i // 4, i % 4].set_ylim(-1 * plotlims, plotlims) + ax[i // 4, i % 4].set_title(f"ws{i}") + ax[i // 4, i % 4].set_aspect('equal', adjustable='box') + plt.colorbar(im, ax[1, 3], label=f"{coloredby} (deg)", fraction=0.046, pad=0.04) + if self.save_figure: + # plt.tight_layout() + plt.savefig(f"{plot_dir}/{platform}_unmodeled_fits_WS_roll{tag}.png") + + if "lat" in pm_version: + markercolor = ancil.corotator_enc[i::7].copy() + coloredby = "corotator" + fig, ax = plt.subplots(2, 4, figsize=(9, 6)) + for i in range(7): + ax[i // 4, i % 4].plot(0, 0, "kx", label="Nominal Center") + im = ax[i // 4, i % 4].scatter( + xi_unmod[i::7] / ARCMIN - nominal_xieta_locs[0, i] / ARCMIN, + eta_unmod[i::7] / ARCMIN - nominal_xieta_locs[1, i] / ARCMIN, + c=ancil.boresight_enc[i::7], + s=scale_weights[i::7] * 80, + edgecolor="gray", + lw=0.3, + marker="o", + alpha=0.5, + cmap="jet", + ) + ax[i // 4, i % 4].set_xlim(-1 * plotlims, plotlims) + ax[i // 4, i % 4].set_ylim(-1 * plotlims, plotlims) + ax[i // 4, i % 4].set_title(f"ws{i}") + ax[i // 4, i % 4].set_aspect('equal', adjustable='box') + plt.colorbar(im, ax[1, 3], label=f"{coloredby} (deg)", fraction=0.046, pad=0.04) + # plt.tight_layout() + if self.save_figure: + plt.savefig(f"{plot_dir}/{platform}_unmodeled_fits_WS_corotator{tag}.png") + plt.close() + + + def plot_template_space_fits_per_detector(self): + platform = self.platform + plot_dir = self.plot_dir + tag = self.tag + plotlims = self.plotlims + pm_version = self.pm_version + ancil = self.aman.ancil + roll_c = self.aman.roll_c + nominal_xieta_locs = self.aman.nominal_xieta_locs + measured_xieta_data = self.aman.measured_xieta_data + weights = self.aman.weights + pointing_model = self.aman.pointing_model + modeled_fits = self.aman.modeled_fits + fit_rms = self.aman.fit_rms + + scale_weights = weights / np.nanmax(weights) + xi_unmod, eta_unmod = model_template_xieta( + pointing_model, + pm_version, + self.aman + ) + xi0, eta0 = model_template_xieta( + pm.param_defaults[pm_version], + pm_version, + self.aman + ) + + #plot with weights as colorbar + fig, ax = plt.subplots(figsize=(9, 6)) + ax.plot(0, 0, "kx", label="Nominal Center") + im = ax.scatter( + xi_unmod / ARCMIN - nominal_xieta_locs[0] / ARCMIN, + eta_unmod / ARCMIN - nominal_xieta_locs[1] / ARCMIN, + c=ancil.az_enc, + s=scale_weights * 5, + edgecolor="gray", + lw=0.3, + marker="o", + alpha=0.2, + cmap="viridis", + vmin=0, + vmax=360 + ) + ax.set_xlim(-1 * plotlims, plotlims) + ax.set_ylim(-1 * plotlims, plotlims) + ax.set_aspect('equal', adjustable='box') + ax.set_title(f"Unmodeled fits, by azimuth") + cb = plt.colorbar(im, fraction=0.046, pad=0.04) + # plt.tight_layout() + if self.save_figure: + plt.savefig(f"{plot_dir}/{platform}_unmodeled_fits_WS_azimuth{tag}.png") + plt.close() + fig, ax = plt.subplots(figsize=(9, 6)) + ax.plot(0, 0, "kx", label="Nominal Center") + im = ax.scatter( + xi_unmod / ARCMIN - nominal_xieta_locs[0] / ARCMIN, + eta_unmod / ARCMIN - nominal_xieta_locs[1] / ARCMIN, + c=ancil.el_enc, + s=scale_weights * 5, + edgecolor="gray", + lw=0.3, + marker="o", + alpha=0.2, + cmap="jet", + ) + ax.set_xlim(-1 * plotlims, plotlims) + ax.set_ylim(-1 * plotlims, plotlims) + ax.set_aspect('equal', adjustable='box') + ax.set_title(f"Unmodeled fits, by elevation color") + cb = plt.colorbar(im, fraction=0.046, pad=0.04) + # plt.tight_layout() + if self.save_figure: + plt.savefig(f"{plot_dir}/{platform}_unmodeled_fits_WS_elevation{tag}.png") + plt.close() + + fig, ax = plt.subplots(figsize=(9, 6)) + if "sat" in pm_version: + markercolor = -1*ancil.boresight_enc + if "lat" in pm_version: + markercolor = roll_c + coloredby = "roll" + ax.plot(0, 0, "kx", label="Nominal Center") + im = ax.scatter( + xi_unmod / ARCMIN - nominal_xieta_locs[0] / ARCMIN, + eta_unmod / ARCMIN - nominal_xieta_locs[1] / ARCMIN, + c=markercolor, + s=scale_weights * 5, + edgecolor="gray", + lw=0.3, + marker="o", + alpha=0.2, + cmap="jet", + ) + ax.set_xlim(-1 * plotlims, plotlims) + ax.set_ylim(-1 * plotlims, plotlims) + ax.set_aspect('equal', adjustable='box') + ax.set_title(f"Unmodeled fits, colored by {coloredby} angle") + cb = plt.colorbar(im, fraction=0.046, pad=0.04) + # plt.tight_layout() + if self.save_figure: + plt.savefig(f"{plot_dir}/{platform}_unmodeled_fits_WS_roll{tag}.png") + plt.close() + + if "lat" in pm_version: + markercolor = ancil.corotator_enc.copy() + coloredby = "corotator" + fig, ax = plt.subplots(figsize=(9, 6)) + ax.plot(0, 0, "kx", label="Nominal Center") + im = ax.scatter( + xi_unmod / ARCMIN - nominal_xieta_locs[0] / ARCMIN, + eta_unmod / ARCMIN - nominal_xieta_locs[1] / ARCMIN, + c=markercolor, + s=scale_weights * 5, + edgecolor="gray", + lw=0.3, + marker="o", + alpha=0.2, + cmap="jet", + ) + ax.set_xlim(-1 * plotlims, plotlims) + ax.set_ylim(-1 * plotlims, plotlims) + ax.set_title(f"Unmodeled fits, colored by {coloredby} angle") + cb = plt.colorbar(im, fraction=0.046, pad=0.04) + # plt.tight_layout() + if self.save_figure: + plt.savefig(f"{plot_dir}/{platform}_unmodeled_fits_WS_corotator{tag}.png") + plt.close() + + def plot_residuals_vs_ancil(self): + platform = self.platform + plot_dir = self.plot_dir + tag = self.tag + pm_version = self.pm_version + xieta_model = self.xieta_model + plotlims = self.plotlims + ancil = self.aman.ancil + roll_c = self.aman.roll_c + nominal_xieta_locs = self.aman.nominal_xieta_locs + measured_xieta_data = self.aman.measured_xieta_data + weights = self.aman.weights + pointing_model = self.aman.pointing_model + modeled_fits = self.aman.modeled_fits + fit_rms = self.aman.fit_rms + + scale_weights = weights / np.nanmax(weights) + plotmask = np.where(weights) + xi_model_fit = modeled_fits.xi + eta_model_fit = modeled_fits.eta + if xieta_model == "measured": + xi_ref, eta_ref, _ = measured_xieta_data + elif xieta_model == "template": + xi_ref, eta_ref, _ = nominal_xieta_locs + else: + raise ValueError("xieta_model must be measured or template") + + if "sat" in platform: + third_enc = ancil.boresight_enc.copy() + third_enc_name = "Boresight" + elif "lat" in platform: + third_enc = ancil.corotator_enc.copy() + third_enc_name = "Corotator" + else: + raise ValueError("Platform must be sat or lat") + fig, ax = plt.subplots(2, 3, figsize=(8, 6), sharex="col", sharey="row") + plt.setp(ax[0, 1].get_yticklabels(), visible=False) + plt.suptitle(r"$\delta \xi$, $\delta \eta$" + f" vs Az, El, {third_enc_name} ({tag.split('_')[1]})") + for k in range(6): + i = k // 3 + j = k % 3 + if i == 0: + model = xi_model_fit + ref = xi_ref + elif i == 1: + model = eta_model_fit + ref = eta_ref + else: + raise ValueError("Trying to plot an axis that doesn't exist?") + if j == 0: + x = ancil.az_enc % 360 + elif j == 1: + x = ancil.el_enc + elif j == 2: + x = third_enc + else: + raise ValueError("Trying to plot an encoder that doesn't exist?") + ax[i, j].scatter( + x[plotmask], + (model - ref)[plotmask] / ARCMIN, + color="k", + marker=".", + alpha=0.1, + lw=0, + s=scale_weights[plotmask] * 80, + ) + ax[i, j].axhline(0, xmin=0, xmax=1, color="k", lw=2, alpha=0.5) + mxb = np.polyfit( + x[plotmask], + (model[plotmask] - ref[plotmask]) / ARCMIN, + 1, + w=scale_weights[plotmask], + ) + xrange = np.arange(np.nanmin(x), np.nanmax(x)) + ax[i, j].errorbar( + xrange, + mxb[0] * xrange + mxb[1], + color="r", + lw=1, + label=f"Slope {np.round(mxb[0],4)} \n [arcmin/deg]", + ) + ax[i, j].legend(fontsize="small") + ax[0, 0].set_ylabel("dXi [arcmin]") + ax[1, 0].set_ylabel("dEta [arcmin]") + ax[1, 0].set_xlabel("Azimuth [deg]") + ax[1, 1].set_xlabel("Elevation [deg]") + ax[1, 2].set_xlabel(f"{third_enc_name} [deg]") + # plt.tight_layout() + if self.save_figure: + plt.savefig(f"{plot_dir}/{platform}_residuals_vs_ancillary{tag}.png") + plt.close() + + def plot_total_residuals(self): + platform = self.platform + plot_dir = self.plot_dir + tag = self.tag + plotlims = self.plotlims + pm_version = self.pm_version + ancil = self.aman.ancil + roll_c = self.aman.roll_c + weights = self.aman.weights + fit_rms = self.aman.fit_rms + obs_index = self.aman.obs_index + + scale_weights = weights / np.nanmax(weights) + effobs =np.where(np.diff(np.append(obs_index, obs_index[-1]+1))>0)[0] + try: + two_fits = np.any(_valid_arg("fit_residuals_i1", 'signal', src=self.aman)) + except: + two_fits = False + if two_fits: + iterate_cutoff = self.config.get("iterate_cutoff") + if iterate_cutoff == "auto": + iterate_cutoff = np.nanstd(self.aman.fit_residuals_i1)*2 + np.nanmedian(self.aman.fit_residuals_i1) + bad_fit_inds = self.aman.bad_fit_inds + fit_residuals_i1 = self.aman.fit_residuals_i1 + fit_residuals_i2 = self.aman.fit_residuals + fig = plt.figure(figsize=(6, 4)) + gs = fig.add_gridspec(7, 1) + ax1 = fig.add_subplot(gs[0:-2, :]) + ax2 = fig.add_subplot(gs[-2:, :]) + # Plot first fit iteration residuals + ax1.plot( + np.arange(len(fit_residuals_i1)), + fit_residuals_i1, + "r.", + mew=0, + alpha=0.6, + lw=0, + label="1st Fit", + ) + ax1.set_ylabel(r"Fit Residual $\left|\Delta$(xi, eta)$\right|$ [arcmin]") + ax1.set_xlabel("Data point") + ax1.axhline( + iterate_cutoff, + #xmin=0, + #xmax=1, + color="k", + linestyle=":", + lw=0.8, + label="Cutoff", + ) + # Plot second fit iteration residuals + ax1.plot( + np.arange(len(fit_residuals_i2)), + fit_residuals_i2, + "b*", + alpha=0.5, + lw=0, + mew=0, + label="2nd fit", + ) + xtox = np.empty((len(fit_residuals_i2), 2)) + xtox[:, 0] = np.arange(len(fit_residuals_i1)) + xtox[:, 1] = np.arange(len(fit_residuals_i2)) + ytoy = np.empty((len(fit_residuals_i1), 2)) + ytoy[:, 0] = fit_residuals_i1 + ytoy[:, 1] = fit_residuals_i2 + ax1.plot(xtox.T, ytoy.T, "k", lw=0.4) + + ax1.axhline(0, xmin=0, xmax=1, color="k", alpha=0.5, lw=0.8) + ax1.set_ylabel(r"Fit Residual $\left|\Delta\text{(xi, eta)}\right|$ [arcmin]") + ax1.legend(loc=2, fontsize="small") + + ax2.scatter( + np.arange(len(fit_residuals_i1)), + (fit_residuals_i2 - fit_residuals_i1), + c="k", + marker="o", + s=scale_weights * 50, + lw=0, + alpha=0.6, + label="Res i2 - Res i1", + ) + ax2.plot( + np.arange(len(fit_residuals_i1))[bad_fit_inds], + (fit_residuals_i2 - fit_residuals_i1)[bad_fit_inds], + "kx", + ms=7, + lw=0.2, + alpha=0.6, + label="Excl. from i2 fit", + ) + ax2.axhline(0, xmin=0, xmax=1, color="k", alpha=0.5, lw=0.8) + for e in effobs: + ax1.axvline(e,linestyle=':',color='k') + ax2.axvline(e,linestyle=':',color='k') + ax2.legend(fontsize="x-small") + ax2.set_xlabel("Data points") + ax2.set_ylabel(r"$\Delta$ Residuals") + if self.save_figure: + plt.savefig(f"{plot_dir}/{platform}_total_residuals{tag}.png") + plt.close() + else: + # Plot first fit iteration residuals only + fit_residuals_i1 = self.aman.fit_residuals + fig, ax1 = plt.subplots() + im = ax1.scatter( + np.arange(len(fit_residuals_i1)), + fit_residuals_i1, + s=scale_weights * 50, + #c=obs_index, + c=weights, + lw=0, + alpha=0.4, + label="1st Fit", + vmax=1, + ) + for e in effobs: + ax1.axvline(e,linestyle=':',color='k') + plt.colorbar(im, label='fit weights', fraction=0.046, pad=0.04) + ax1.set_ylabel(r"Fit Residual $\left|\Delta\text{(xi, eta)}\right|$ [arcmin]") + ax1.set_xlabel("Data points") + plt.title("Fit Residuals") + plt.legend(loc=2) + if self.save_figure: + plt.savefig(f"{plot_dir}/{platform}_total_residuals{tag}.png") + plt.close() + + + def plot_residuals_histograms(self): + platform = self.platform + plot_dir = self.plot_dir + tag = self.tag + append = self.append_string + ancil = self.aman.ancil + weights = self.aman.weights + fit_rms = self.aman.fit_rms + fit_residuals = self.aman.fit_residuals + fit_rms_full = self.aman.fit_rms_full + fit_residuals_full = self.aman.fit_residuals_full + + xmax = np.nanmax(fit_residuals_full) * 1.1 + title = f"{append} {tag}" + plt.figure() + plt.hist(fit_residuals_full, + bins = 25, + range = (0, xmax), + alpha=0.7, + label='All dets above weight threshold' + ) + plt.hist(fit_residuals, + bins = 25, + range = (0, xmax), + alpha=0.7, + label='Subset in Fit' + ) + plt.axvline(fit_rms_full,color='C0', + label=f'Weighted RMSE (all): {fit_rms_full:.3f} arcmin') + plt.axvline(fit_rms, color='C1', + label=f'Weighted RMSE (set): {fit_rms:.3f} arcmin') + plt.xlabel('Fit Residuals (arcmin)') + plt.ylabel('# Detectors') + plt.title(append) + plt.legend() + if self.save_figure: + plt.savefig(f"{plot_dir}/{platform}_residuals_hists{tag}.png") + plt.close() + + def plot_xieta_residuals(self): + platform = self.platform + plot_dir = self.plot_dir + tag = self.tag + xieta_model = self.xieta_model + weights = self.aman.weights + modeled_fits = self.aman.modeled_fits + nominal_xieta_locs = self.aman.nominal_xieta_locs + measured_xieta_data = self.aman.measured_xieta_data + + scale_weights = weights / np.nanmax(weights) + plotmask = np.where(weights) + xi_model_fit = modeled_fits.xi + eta_model_fit = modeled_fits.eta + if xieta_model == "measured": + xi_ref, eta_ref, _ = measured_xieta_data + elif xieta_model == "template": + xi_ref, eta_ref, _ = nominal_xieta_locs + + fig, ax = plt.subplots(2, 1) + for i, xe in enumerate(["Xi", "Eta"]): + if xe == "Xi": + xaxis_ref = xi_ref + xlabel = "Xi" + yref = xi_ref + ymodel = xi_model_fit + ylabel = "dXi" + elif xe == "Eta": + xaxis_ref = eta_ref + xlabel = "Eta" + yref = eta_ref + ymodel = eta_model_fit + ylabel = "dEta" + # xi residuals vs xi + im = ax[i].scatter( + xaxis_ref[plotmask] / DEG, + (ymodel - yref)[plotmask] / ARCMIN, + marker=".", + c=xaxis_ref[plotmask], + cmap="jet", + s=100 * scale_weights[plotmask], + alpha=scale_weights[plotmask], + edgecolors="k", + linewidths=0.4, + ) + cb = plt.colorbar(im, fraction=0.046, pad=0.04) + cb.ax.set_title(xlabel) + ax[i].axhline(0, xmin=0, xmax=1, color="k", lw=0.8, alpha=0.6) + ax[i].axvline(0, ymin=0, ymax=1, color="k", lw=0.8, alpha=0.5) + ax[i].set_ylim(-self.plotlims, self.plotlims) + ax[i].set_xlabel(f"{xlabel} (deg)", fontsize="small") + ax[i].set_ylabel(f"{ylabel} [arcmin]") + # plt.tight_layout() + if self.save_figure: + plt.savefig(f"{plot_dir}/{platform}_xieta_residuals{tag}.png") + plt.close() + + + def plot_xieta_cross_residuals(self): + platform = self.platform + plot_dir = self.plot_dir + tag = self.tag + xieta_model = self.xieta_model + weights = self.aman.weights + modeled_fits = self.aman.modeled_fits + nominal_xieta_locs = self.aman.nominal_xieta_locs + measured_xieta_data = self.aman.measured_xieta_data + + scale_weights = weights / np.nanmax(weights) + plotmask = np.where(weights) + xi_model_fit = modeled_fits.xi + eta_model_fit = modeled_fits.eta + if xieta_model == "measured": + xi_ref, eta_ref, _ = measured_xieta_data + elif xieta_model == "template": + xi_ref, eta_ref, _ = nominal_xieta_locs + + fig, ax = plt.subplots(2, 1) + for i, xe in enumerate(["Xi", "Eta"]): + if xe == "Xi": + xaxis_ref = eta_ref + xlabel = "Eta" + yref = xi_ref + ymodel = xi_model_fit + ylabel = "dXi" + elif xe == "Eta": + xaxis_ref = xi_ref + xlabel = "Xi" + yref = eta_ref + ymodel = eta_model_fit + ylabel = "dEta" + # xi residuals vs xi + im = ax[i].scatter( + xaxis_ref[plotmask] / DEG, + (ymodel - yref)[plotmask] / ARCMIN, + marker=".", + c=xaxis_ref[plotmask], + cmap="jet", + s=100 * scale_weights[plotmask], + alpha=scale_weights[plotmask], + edgecolors="k", + linewidths=0.4, + ) + cb = plt.colorbar(im, fraction=0.046, pad=0.04) + cb.ax.set_title(xlabel) + ax[i].axhline(0, xmin=0, xmax=1, color="k", lw=0.8, alpha=0.6) + ax[i].axvline(0, ymin=0, ymax=1, color="k", lw=0.8, alpha=0.5) + ax[i].set_ylim(-self.plotlims, self.plotlims) + ax[i].set_xlabel(f"{xlabel} (deg)", fontsize="small") + ax[i].set_ylabel(f"{ylabel} [arcmin]") + # plt.tight_layout() + if self.save_figure: + plt.savefig(f"{plot_dir}/{platform}_xieta_cross_residuals{tag}.png") + plt.close() + + def plot_fit_correlation_matrix(self): + platform = self.platform + plot_dir = self.plot_dir + tag = self.tag + CM = self.aman.model_fit_statistics.correlation_matrix.matrix + names = self.aman.model_fit_statistics.correlation_matrix.param_names + n_param = len(names) + mask = np.triu_indices(n_param, k=1) + CM_plot = CM.copy() + CM_plot[mask] = np.nan + + fig, ax = plt.subplots(figsize=(9, 8)) + im = ax.imshow(CM_plot,cmap='RdBu_r', vmin=-1, vmax=1) + cbar = fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04) + cbar.set_label('Correlation Coefficient', rotation=270, labelpad=15) + ax.set_xticks(np.arange(n_param)) + ax.set_yticks(np.arange(n_param)) + ax.set_xticklabels(names) + ax.set_yticklabels(names) + + plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") + for i in range(n_param): + for j in range(n_param): + if i>=j: + val = CM_plot[i, j] + color = "white" if abs(val) > 0.5 else "black" + ax.text(j, i, f"{val:.2f}", ha="center", va="center", color=color) + ax.spines['top'].set_visible(False) + ax.spines['right'].set_visible(False) + plt.grid(False) # Grid usually looks messy on masked heatmaps + if self.save_figure: + plt.savefig(f"{plot_dir}/{platform}_correlation_matrix{tag}.png") + plt.close() +############ + +if __name__ == "__main__": + sp_util.main_launcher(main, get_parser) diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py new file mode 100644 index 000000000..e5030dccd --- /dev/null +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -0,0 +1,1362 @@ +""" +Jointly solve for the static pointing model +and detector offset. Should eventually also +include the ability to incorporate external +datasets (starcamera, tiltmeter, etc.). +""" + +import argparse as ap +import datetime as dt +import hashlib +import os +import shutil +from concurrent.futures import Executor +from copy import deepcopy +from enum import Enum +from functools import partial +from typing import cast + +import corner +import emcee +import git +import h5py +import matplotlib.pyplot as plt +import numpy as np +import pyinstrument +import sotodlib.coords.fp_containers as fpc +import sotodlib.coords.fp_plots as fpp +import sotodlib.utils.jdb_utils as ju +import sqlalchemy as sqy +import yaml +from scipy.optimize import least_squares, minimize +from scipy.sparse import csr_array +from sotodlib.coords import optics +from sotodlib.core import Context, metadata +from sotodlib.io.metadata import read_dataset +from sotodlib.site_pipeline import jobdb +from sotodlib.site_pipeline.utils.logging import init_logger +from sotodlib.utils import epochs +from sotodlib.utils.config import load_config_namespace + +logger = init_logger(__name__, "solve_static_pointing: ") +default_config = { + "tel": "LAT", + "fake_gamma": True, + "force_zero_roll": False, + "rx_groups": [], + "pm_groups": [], + "pad_epochs": [], + "pm_ver_override": {}, + "pm_defaults_overrides": {}, + "par_groups": {}, + "root_dir": "~", + "project_dir": "pointing", + "append": "", + "point_meta": "focal_plane", + "obs_whitelist": [], + "obs_blacklist": [], + "weight_factor": 1000, + "min_frac_dets": 0.1, + "max_dscale": 0.1, + "max_shear": 0.05, + "min_hits": 3, + "min_r2": 0.3, + "pad_empty": True, + "parameters": {}, + "n_rounds": 3, + "outlier_sigma": 20, + "mcmc_steps": 0, + "nwalkers": 32, + "save_every": 10, + "nuisance_params": {}, + "obs_time_thresh": 180, + "nuisance_scale": 10, + "activate_nuisance": 1, + "activate_nuisance_transforms": 1, + "least_squares": True, + "cm_fac": 1e-4, + "proposal_factor": 1e-2, + "pars_from_old": False, + "nuisance_from_old": False, + "nuisance_transform_from_old": False, + "pool_type": "thread", + "pool_size": 1, + "zero_nuisance": False, +} + + +class ErrCode(Enum): + NO_ERR = 0 + LOADER = 1 + MIN_DETS = 2 + AFF_ERR = 3 + HIGH_SCALE = 4 + HIGH_SHEAR = 5 + PLOT = 6 + FPINIT = 7 + + +def least_squares_fixed(fun, x0, bounds, x_scale, jac_sparsity, args=(), **kwargs): + x0 = np.asarray(x0, dtype=float) + lb = np.asarray(bounds[0], dtype=float) + ub = np.asarray(bounds[1], dtype=float) + fixed_mask = lb == ub + free_mask = ~fixed_mask + x_fixed = x0.copy() + x_fixed[fixed_mask] = lb[fixed_mask] + if jac_sparsity is not None: + jac_sparsity = jac_sparsity[:, free_mask] + + def wrapped_fun(x_free, *args): + x = x_fixed.copy() + x[free_mask] = x_free + return fun(x, *args) + + result = least_squares( + wrapped_fun, + x0[free_mask], + args=args, + bounds=(lb[free_mask], ub[free_mask]), + x_scale=x_scale[free_mask], + jac_sparsity=jac_sparsity, + **kwargs, + ) + + x_full = x_fixed.copy() + x_full[free_mask] = result.x + result.x = x_full + result.fixed_mask = fixed_mask + + return result + + +def _report_fit(res, cfg, system, npar, x0, report_static, report_nuisance): + logger.info(res.message) + logger.info("Success: %s", res.success) + logger.info("Objective: %g", res.cost if cfg.least_squares else res.fun) + if cfg.least_squares: + logger.info("Optimality: %g", res.optimality) + if report_static: + changes = system.parameters - x0[:npar] + header = f"{'Parameter Name':<35} {'Optimized Value':>18} {'Change':>18}" + logger.info("Parameter changes:\n%s", header) + logger.info("-" * len(header)) + for name, value, change in zip( + system.parameter_names, system.parameters, changes + ): + logger.info(f"{name:<35} {value:>18.8g} {change:>18.8g}") + if report_nuisance: + nn = len(cfg.nuisance_params) + cur = system.nuisance_params.params_flat.reshape((-1, nn)) + avg = np.mean(cur, axis=0) + tot = np.sum(cur, axis=0) + changes = (system.nuisance_params.params_flat - x0[npar:]).reshape((-1, nn)) + avg_change = np.mean(changes, axis=0) + tot_change = np.sum(changes, axis=0) + header = f"{'Nuisance Name':<35} {'Average Value':>18} {'Average Change':>18} {'Net Value':>18} {'Net Change':>18}" + logger.info("Parameter changes:\n%s", header) + logger.info("-" * len(header)) + for name, a, ac, t, tc in zip( + cfg.nuisance_params.keys(), avg, avg_change, tot, tot_change + ): + logger.info(f"{name:<35} {a:>18.8g} {ac:>18.8g} {t:>18.8g} {tc:>18.8g}") + + +def _fit_round( + system, + x0, + bounds, + scales, + nresid, + use_least_squares, + jac_sparsity, + cm_fac, + executor, + thaw_meas=None, + **kwargs, +): + if use_least_squares: + lb = np.array([b[0] for b in bounds]) + ub = np.array([b[1] for b in bounds]) + res = least_squares_fixed( + system.objective_resid, + x0, + bounds=(lb, ub), + x_scale=scales, + jac_sparsity=jac_sparsity, + args=(nresid, cm_fac, executor, thaw_meas), + method="trf", + loss="linear", # "soft_l1", + tr_solver="lsmr", + verbose=2, + **kwargs, + ) + + return res, res.x + + scaled_bounds = [ + (lo / scale, hi / scale) for (lo, hi), scale in zip(bounds, scales) + ] + + def scaled_objective(z): + return system.objective(z * scales, nresid, cm_fac, executor, thaw_meas) + + res = minimize( + scaled_objective, + x0 / scales, + # method="L-BFGS-B", + method="powell", + bounds=scaled_bounds, + **kwargs, + ) + + return res, res.x * scales + + +def _run_mcmc(system, nresid, cfg, bounds, scales, data_dir, plot_dir, executor): + system.set_static(False) + system.set_thaw(True) + + x0 = system.parameters_full.copy() + ndim = len(x0) + npar = len(system.parameters) + nnuisance = ndim - npar + + scales = np.asarray(scales, dtype=float) + lb = np.asarray([b[0] for b in bounds], dtype=float) + ub = np.asarray([b[1] for b in bounds], dtype=float) + + if len(scales) != ndim or len(bounds) != ndim: + raise ValueError("Inconsistent parameter dimensions.") + + fixed_mask = lb == ub + free_mask = ~fixed_mask + + # Divide the parameters into two blocks + physical_mask = np.zeros(ndim, dtype=bool) + physical_mask[:npar] = True + nuisance_mask = ~physical_mask + physical_free = physical_mask * free_mask + nuisance_free = nuisance_mask * free_mask + nphysical = np.sum(physical_free) + nnuisance_free = np.sum(nuisance_free) + + if nphysical + nnuisance_free == 0: + raise ValueError("All parameters are fixed; nothing to sample.") + + # Enforce fixed parameter values + x = x0.copy() + x[fixed_mask] = lb[fixed_mask] + + # Proposal scales + proposal_scales = scales * cfg.proposal_factor + proposal_scales[npar:] /= 10 + if np.any(proposal_scales[free_mask] <= 0): + raise ValueError("All free parameters must have positive proposal scales.") + + logger.info( + "Gibbs MCMC: %d physical, %d nuisance, %d fixed parameters", + nphysical, + nnuisance_free, + np.sum(fixed_mask), + ) + logger.info("Running %d Gibbs iterations", cfg.mcmc_steps) + + # Full joint log probability + def log_prob(x): + if np.any(x < lb) or np.any(x > ub): + return -np.inf + try: + value = system.log_prob(x, nresid, cfg.cm_fac, executor) + except ( + RuntimeError, + AssertionError, + ValueError, + FloatingPointError, + ): + return -np.inf + if not np.isfinite(value): + return -np.inf + return value + + current_logp = log_prob(x) + + if not np.isfinite(current_logp): + raise RuntimeError("Initial parameter vector has invalid log probability.") + diagnostics = { + "physical": { + "bounds": 0, + "nonfinite": 0, + "errors": 0, + "metropolis": 0, + "accepted": 0, + "log_alpha": [], + }, + "nuisance": { + "bounds": 0, + "nonfinite": 0, + "errors": 0, + "metropolis": 0, + "accepted": 0, + "log_alpha": [], + }, + } + + def metropolis_step(x, current_logp, mask, block_name): + indices = np.where(mask)[0] + + if len(indices) == 0: + return x, current_logp, False + + proposal = x.copy() + + proposal[indices] += rng.normal(size=len(indices)) * proposal_scales[indices] + + if np.any(proposal[indices] < lb[indices]) or np.any( + proposal[indices] > ub[indices] + ): + diagnostics[block_name]["bounds"] += 1 + return x, current_logp, False + + try: + proposal_logp = log_prob(proposal) + except Exception: + diagnostics[block_name]["errors"] += 1 + raise + + if not np.isfinite(proposal_logp): + diagnostics[block_name]["nonfinite"] += 1 + return x, current_logp, False + + log_alpha = proposal_logp - current_logp + + diagnostics[block_name]["log_alpha"].append(log_alpha) + + if np.log(rng.random()) < min(0.0, log_alpha): + diagnostics[block_name]["accepted"] += 1 + return proposal, proposal_logp, True + + diagnostics[block_name]["metropolis"] += 1 + return x, current_logp, False + + rng = np.random.default_rng() + + # Initialize chain storage + samples = np.empty((cfg.mcmc_steps, ndim)) + physical_accept = 0 + nuisance_accept = 0 + + # Gibbs sampling + for i in range(cfg.mcmc_steps): + # Sample physical parameters conditional on the current nuisance parameters + x, current_logp, accepted = metropolis_step( + x, current_logp, physical_free, "physical" + ) + physical_accept += accepted + + # Sample nuisance parameters conditional on the newly sampled physical parameters. + x, current_logp, accepted = metropolis_step( + x, current_logp, nuisance_free, "nuisance" + ) + nuisance_accept += accepted + + samples[i] = x + + if (i + 1) % cfg.save_every == 0: + logger.info( + "Gibbs iteration %d/%d | " + "logp = %.5f | " + "physical acceptance = %.3f | " + "nuisance acceptance = %.3f", + i + 1, + cfg.mcmc_steps, + current_logp, + physical_accept / (i + 1), + nuisance_accept / (i + 1), + ) + + for name, d in diagnostics.items(): + logger.info( + "%s diagnostics: bounds=%d, nonfinite=%d, " + "errors=%d, metropolis=%d, accepted=%d", + name, + d["bounds"], + d["nonfinite"], + d["errors"], + d["metropolis"], + d["accepted"], + ) + + if d["log_alpha"]: + logger.info( + "%s log_alpha: median=%.3g, min=%.3g, max=%.3g", + name, + np.median(d["log_alpha"]), + np.min(d["log_alpha"]), + np.max(d["log_alpha"]), + ) + + # Acceptance diagnostics + physical_fraction = physical_accept / cfg.mcmc_steps + nuisance_fraction = nuisance_accept / cfg.mcmc_steps + + logger.info("Physical acceptance fraction: %.3f", physical_fraction) + logger.info("Nuisance acceptance fraction: %.3f", nuisance_fraction) + + try: + tau = emcee.autocorr.integrated_time(samples, quiet=True) + discard = int(2 * np.nanmax(tau)) + logger.info("Autocorrelation times: %s", tau) + logger.info( + "Estimated effective sample sizes: %s", + np.round(cfg.mcmc_steps / tau).astype(int), + ) + except emcee.autocorr.AutocorrError: + logger.warning("Chain too short to estimate autocorrelation time.") + discard = int(0.1 * cfg.mcmc_steps) + except ValueError: + logger.warning("Estimating autocorrelation time raised a ValueError.") + discard = int(0.1 * cfg.mcmc_steps) + + if discard >= cfg.mcmc_steps: + raise RuntimeError("MCMC chain too short relative to autocorrelation time.") + logger.info("Discarding %d burn-in iterations", discard) + + posterior_samples = samples[discard:] + + if len(posterior_samples) == 0: + raise RuntimeError("No samples remaining after burn-in.") + + # Posterior summaries + median = np.median(posterior_samples, axis=0) + lower = np.percentile(posterior_samples, 16, axis=0) + upper = np.percentile(posterior_samples, 84, axis=0) + + system.update_parameters(median) + system.set_thaw(True) + system.set_freeze(True) + + # Log physical parameter estimates. + header = ( + f"{'Parameter Name':<35}" f"{'Median':>18}" f"{'Lower':>18}" f"{'Upper':>18}" + ) + + logger.info("Physical parameter estimates:\n%s", header) + logger.info("-" * len(header)) + + for i, (name, med, lo, hi) in enumerate( + zip( + system.parameter_names, + median[:npar], + lower[:npar], + upper[:npar], + ) + ): + suffix = " (fixed)" if fixed_mask[i] else "" + + logger.info( + f"{name + suffix:<35}" f"{med:>18.8g}" f"{lo:>18.8g}" f"{hi:>18.8g}" + ) + + # Log nuisance parameter estimates + if nnuisance > 0: + nuisance_names = list(cfg.nuisance_params.keys()) + + logger.info("Nuisance parameter estimates:") + + for j, name in enumerate(nuisance_names): + idx = npar + j + + logger.info( + "%-35s %18.8g %18.8g %18.8g", + name, + median[idx], + lower[idx], + upper[idx], + ) + + # Corner plot for physical parameters. + plot_mask = physical_free + physical_samples = posterior_samples[:, plot_mask] + physical_names = [ + name + for name, include in zip(system.parameter_names, plot_mask[:npar]) + if include + ] + if physical_samples.shape[1] > 0: + fig = corner.corner( + physical_samples, + labels=physical_names, + quantiles=[0.16, 0.50, 0.84], + show_titles=True, + title_fmt=".4g", + truths=median[plot_mask], + ) + + fig.savefig( + os.path.join(plot_dir, "mcmc_corner.png"), dpi=200, bbox_inches="tight" + ) + plt.close(fig) + _plot_fit(system, plot_dir, "mcmc", cfg) + logger.info("Gibbs MCMC complete") + + # Save the chain. + logger.info("Saving MCMC") + system.set_static(True) + outfile = os.path.join(data_dir, "static_pointing_mcmc.h5") + with h5py.File(outfile, "a") as f: + system.save(f, "/", True) + group = f.create_group("chain") + group.create_dataset("samples", data=samples, compression="gzip") + group.create_dataset( + "posterior_samples", data=posterior_samples, compression="gzip" + ) + group.create_dataset("fixed_mask", data=fixed_mask) + group.attrs["ndim"] = ndim + group.attrs["npar"] = npar + group.attrs["nuisance_params"] = nnuisance + group.attrs["discard"] = discard + group.attrs["physical_acceptance"] = physical_fraction + group.attrs["nuisance_acceptance"] = nuisance_fraction + + return samples, posterior_samples + + +def _get_jobdict_po(jdb): + return { + f"{job.tags['obs_id']}+{job.tags['wafer_slot']}+{job.tags['array']}": job + for job in jdb.get_jobs(jclass="per_obs") + } + + +def _get_jobit_po(jdb, obslist, system): + _ = jdb + jobit = [] + for obs in obslist: + try: + rx = system.search("receivers", obs["timestamp"]) + if rx is None: + continue + ot = rx[obs["tube_slot"]] + except IndexError: + continue + for ws, fp in zip(ot.wafer_slots, ot.focal_planes): + jobit += [(obs, ws, fp.name)] + return jobit + + +def _get_jobstr_po(info): + obs, wafer_slot, array = info + return f"{obs['obs_id']}+{wafer_slot}+{array}" + + +def _get_tags_po(info): + obs, wafer_slot, array = info + return { + "obs_id": obs["obs_id"], + "ot": obs["tube_slot"], + "timestamp": obs["timestamp"], + "array": array, + "wafer_slot": wafer_slot, + "errcode": 0, + "message": "", + } + + +def _setup_paths(root_dir, project, tel, append=""): + plot_dir = os.path.join( + root_dir, "plots", project, tel, "solve_static_pointing" + append + ) + data_dir = os.path.join( + root_dir, "data", project, tel, "solve_static_pointing" + append + ) + plot_dir = os.path.expanduser(plot_dir) + data_dir = os.path.expanduser(data_dir) + os.makedirs(plot_dir, exist_ok=True) + os.makedirs(data_dir, exist_ok=True) + + return plot_dir, data_dir + + +def _compute_templates_and_copy_old(system, cfg, old_system, old_cfg, ctx, plot_dir): + logger.info("Computing templates and copying old data if compatible") + dbs = [ + (metadata.ManifestDb(md["db"]), os.path.dirname(md["db"])) + for md in ctx["metadata"] + if "wafer_info" in (md.get("name", ""), md.get("label", "")) + ] + if len(dbs) == 0: + raise ValueError("wafer_info not in context!") + db, db_dir = dbs[0] + if db.scheme.cols != [ + ("dets:stream_id", "out", "exact", "numeric"), + ("dataset", "out", "exact", "numeric"), + ]: + raise ValueError( + "wafer_info has unexpected ManifestScheme! Please annoy one of the usual suspects to modify this code!" + ) + + if "zemax_path" in cfg.optics_config: + system.state_meta["zemax_hash"] = hashlib.md5( + open(cfg.optics_config["zemax_path"], "rb").read() + ).hexdigest() + + with open(cfg.optics_config["fp_to_ot"]) as f: + ot_locs = yaml.safe_load(f) + + check_old = old_system is not None and old_cfg is not None + if check_old and old_cfg is not None: + check_old = { + key: val for key, val in cfg.optics_config.items() if key != "zemax_path" + } == { + key: val + for key, val in old_cfg.optics_config.items() + if key != "zemax_path" + } + if "zemax_path" in cfg.optics_config and old_system is not None: + if "zemax_hash" not in old_system.state_meta: + check_old = False + else: + check_old *= ( + system.state_meta["zemax_hash"] + == old_system.state_meta["zemax_hash"] + ) + if check_old is False: + logger.info("Old system has incompatible optics config") + epc_dict = {epoch.name: epoch for epoch in system.era.epochs} + for rx in system.receivers: + logger.info("Working on templates for %s", f"{rx.name}_{rx.epoch}") + epoch = epc_dict[rx.epoch.split("+")[0]] + ws_mapping = epoch._internal.data["ws_mapping"] # ot : ws : (stream_id, array) + old_rx = None + if check_old and old_system is not None: + matches = [ + orx + for orx in old_system.receivers + if f"{orx.name}_{orx.epoch}" == f"{rx.name}_{rx.epoch}" + ] + if len(matches) == 1: + old_rx = matches[0] + for ot in rx.optics_tubes: + old_ot = None + if old_rx is not None: + matches = [ + oot for oot in old_rx.optics_tubes if f"{oot.name}" == f"{ot.name}" + ] + if len(matches) == 1: + old_ot = matches[0] + for i, (fp, ws) in enumerate(zip(ot.focal_planes, ot.wafer_slots)): + fp_str = f"{rx.name}_{rx.epoch}:{ot.name}:{ws}:{fp.name}" + old_fp = None + if old_ot is not None: + matches = [ + ofp + for ofp, ows in zip(old_ot.focal_planes, old_ot.wafer_slots) + if f"{ofp.name}" == f"{fp.name}" and ows == ws + ] + if len(matches) == 1: + old_fp = matches[0] + if old_fp is not None: + logger.info( + "%s: Matching focal plane found in old data! Copying template and data.", + fp_str, + ) + ot.focal_planes[i] = old_fp + continue + logger.info("%s: computing fresh template", fp_str) + sid, arr = ws_mapping[ot.name][ws] + res = db.inspect({"dets:stream_id": sid}) + if len(res) == 0: + raise ValueError("%s not found in wafer_info!", sid) + elif len(res) > 1: + raise ValueError("%s found multiple times in wafer_info?", sid) + wafer = read_dataset( + os.path.join(db_dir, res[0]["filename"]), res[0]["dataset"] + ) + idx = np.where(np.isin(np.asarray(wafer["dets:wafer.array"]), [arr]))[0] + wafer = wafer.subset(rows=idx) + det_ids = np.asarray(wafer["dets:det_id"]) + det_x = wafer["dets:wafer.x"] + det_y = wafer["dets:wafer.y"] + det_pol = wafer["dets:wafer.angle"] + split = np.array([f"{t}_{b}_{p}" for t, b, p in zip(wafer["dets:wafer.type"], wafer["dets:wafer.bandpass"], wafer["dets:wafer.pol"])]) # type: ignore + + focal_plane_args = ( + 0, + cfg.tel[:3].upper(), + ot.name, + ws, + cfg.optics_config["ufm_to_fp"], + None, + cfg.optics_config["fp_to_ot"], + None, + cfg.optics_config.get("zemax_path"), + None, + True, + ) + + # fmt: off + coords = optics.get_focal_plane(None, det_x, det_y, det_pol, *focal_plane_args) # type: ignore + centers = optics.get_focal_plane(None, np.zeros(1), np.zeros(1), np.zeros(1), *focal_plane_args) # type: ignore + xi, eta, gamma, x_fp, y_fp, pol_fp, x_ot, y_ot, pol_ot = coords # type: ignore + xi_c, eta_c, gamma_c, x_fp_c, y_fp_c, pol_fp_c, x_ot_c, y_ot_c, pol_ot_c = centers # type: ignore + # fmt: on + + for name, values, center in ( + ("xieta", (xi, eta, gamma), (xi_c, eta_c, gamma_c)), + ("fp", (x_fp, y_fp, pol_fp), (x_fp_c, y_fp_c, pol_fp_c)), + ("ot", (x_ot, y_ot, pol_ot), (x_ot_c, y_ot_c, pol_ot_c)), + ): + setattr( + fp, + f"template_{name}" if name != "xieta" else "template", + fpc.DetectorOffsets( + np.column_stack(values), + det_ids, + split, + np.asarray(center).ravel(), + name, + ), + ) + logger.info("Plotting %s", f"{rx.name}_{rx.epoch}") + fpp.plot_receiver_templates(rx, ot_locs, plot_dir) + + +def _get_old(outfile, overwrite, backup): + old_system = None + old_cfg = None + if not os.path.isfile(outfile): + return old_system, old_cfg + logger.info("Existing file found at %s", outfile) + if backup: + with h5py.File(outfile) as f: + ts = f["state"].attrs["timestamp"] + new_path = f"{outfile}.{ts}" + logger.info("Copying old file to %s", new_path) + if overwrite: + shutil.move(outfile, new_path) + else: + shutil.copyfile(outfile, new_path) + if overwrite: + return old_system, old_cfg + with h5py.File(outfile) as f: + old_system = fpc.PointingSystem.load(f, "/") + old_cfg, _ = load_config_namespace(old_system.state_meta["config"]) + logger.warning( + "Running with overwrite=False and an existing file. This mean that wherever possible we will fall back on existing data. Some compatibility checks will be done but if a key piece of metadata (wafer_info, det_match, etc.) has changed you will wan't to do a fresh run!" + ) + return old_system, old_cfg + + +def _get_obslist(ctx, cfg, system): + if ctx.obsdb is None: + raise ValueError("No obsdb!") + + # Make sure we have the metadata we want + point_db = None + required = ["assignment", "det_info", "wafer_info", cfg.point_meta] + for req in required: + dbs = [ + md + for md in ctx["metadata"] + if md.get("name", "") == req or md.get("label", "") == req + ] + if len(dbs) == 0 or len(dbs) > 1: + raise ValueError( + f"Found {len(dbs)} entries in Context for required metadata: {req}" + ) + if req == cfg.point_meta: + point_db = metadata.ManifestDb(dbs[0]["db"]) + if point_db is None: + raise ValueError("Pointing metadata not found") + + # Get all of the obs ids in our pointing db + cols = [c[0] for c in point_db.scheme.cols] + if "obs:obs_id" not in cols: + raise ValueError("Pointing metadata not indexed on obsdb!") + obsids = np.unique(np.array([entry["obs:obs_id"] for entry in point_db.inspect()])) + # obsids = ["obs_1782128967_lati1_111"] + # obsids = ["obs_1777500417_lati6_111"] + + # Validate against black and whitelist + if len(cfg.obs_whitelist) > 0: + obsids = np.intersect1d(obsids, cfg.obs_whitelist) + if len(cfg.obs_blacklist) > 0: + obsids = np.setdiff1d(obsids, cfg.obs_blacklist) + + # Load obsdb rows and filter by timestamp + obslist = [ctx.obsdb.get(obs_id) for obs_id in obsids] + obslist = [ + obs + for obs in obslist + if system.search("receivers", obs["timestamp"]) is not None + ] + + return obslist + + +def _load_obs(aman, obs_id, array, ctx, system, cfg, job): + obs = ctx.obsdb.get(obs_id) + rx = system.search("receivers", obs["timestamp"]) + pm = system.search("pointing_models", obs["timestamp"]) + fp = rx.find_fpc(obs["tube_slot"], array) + if fp is None: + raise ValueError("Array {array} not found in {rx.name} {rx.epoch}") + # Cuts + if "hits" in aman.focal_plane: + aman.restrict("dets", aman.focal_plane.hits >= cfg.min_hits) + if "R2" in aman.focal_plane: + aman.restrict("dets", aman.focal_plane.R2 > cfg.min_r2) + dfrac = aman.dets.count / len(fp.template.xyz) + if dfrac < cfg.min_frac_dets: + msg = f"Only {100*np.round(dfrac, 2)}% of dets uncut" + ju.fail(job, ErrCode.MIN_DETS, msg, logger) + return None, rx, fp + loaded = fpc.FocalPlane.from_aman( + fp.name, + obs["obs_id"], + aman, + fp, + pm, + fp.autofreeze, + fp.fake_gamma, + cfg.weight_factor, + ) + + # Not adding to the system so that we can leave ourselves open to parallelism + return loaded, rx, fp + + +def _run_per_obs(open_jobs, done_jobs, jdb, ctx, system, cfg, plot_dir, outfile): + job = None + njobs = len(open_jobs) + if njobs == 0: + logger.info("No new per-obs jobs to run!") + return + logger.info( + "Starting per-obs mode with %d open jobs and %d already done", + njobs, + len(done_jobs), + ) + open_jobs += [None] + pm_pars = deepcopy(system.parameters) # Cache a copy of the pars + system.set_pm_to_defaults(cfg) + for i, j in enumerate(open_jobs): + if job is not None: + logger.debug("Writing to db") + ju.update_jobs_retry(jdb, [job], 10, logger) + job = None + if j is not None: + with jdb.session_scope() as session: + job = session.get(jobdb.Job, j.id) + if job is not None: + session.expunge(job) + if job is None: + continue + + job.mark_visited() + obs_id = job.tags["obs_id"] + ws = job.tags["wafer_slot"] + array = job.tags["array"] + jstr = f"{obs_id}+{ws}+{array}" + logger.info("Loading and processing %s (%d/%d)", jstr, i + 1, njobs) + + # Load + try: + aman = ctx.get_meta(obs_id, dets={"wafer.array": array}) + except Exception as e: + msg = f"Failed to load with error: {e}" + ju.fail(job, ErrCode.LOADER, msg, logger) + continue + + # Init the fp + try: + meas, rx, fp = _load_obs(aman, obs_id, array, ctx, system, cfg, job) + except Exception as e: + msg = f"Failed to build focal plane with error: {e}" + ju.fail(job, ErrCode.FPINIT, msg, logger) + continue + if meas is None: + continue + + # Check min dets + dfrac = np.nansum(meas.weights) / len(meas.weights) + if dfrac < cfg.min_frac_dets: + msg = f"Only {100*np.round(dfrac, 2)}% of weighted dets uncut" + ju.fail(job, ErrCode.MIN_DETS, msg, logger) + continue + + # Lets make sure transformed is initid + try: + meas.freeze(True, False) + except Exception as e: + msg = f"Failed to compute affine with error: {e}" + ju.fail(job, ErrCode.AFF_ERR, msg, logger) + continue + + # Cut on scale and shear + try: + scale, shear, _ = meas.transform.decompose + except Exception as e: + msg = f"Failed to compute affine with error: {e}" + ju.fail(job, ErrCode.AFF_ERR, msg, logger) + continue + if abs(1 - np.max(scale)) > cfg.max_dscale: + msg = f"Scale too high: {str(scale)}" + ju.fail(job, ErrCode.HIGH_SCALE, msg, logger) + continue + if shear > cfg.max_shear: + msg = f"Shear too high: {np.round(shear, 2)}" + ju.fail(job, ErrCode.HIGH_SHEAR, msg, logger) + continue + + # Plot + pdir = os.path.join( + plot_dir, rx.epoch, "per-obs", str(job.tags["timestamp"])[:5] + ) + os.makedirs(pdir, exist_ok=True) + try: + fpp.plot_ufm(meas, pdir) + except Exception as e: + msg = f"Failed to plot with error: {e}" + ju.fail(job, ErrCode.PLOT, msg, logger) + continue + + # Add to system + fp.focal_planes += [meas] + job.jstate = cast(sqy.Column[str], jobdb.JState.done) + + if i > 0 and i % cfg.save_every == 10: + with h5py.File(outfile, "a") as f: + system.save(f, "/", True) + system.update_parameters(pm_pars) + logger.info("Done with per-obs mode!") + + +def _check_jobs(system, jdb, done_jobs, open_jobs): + to_open = [] + in_system = [] + for rx in system.receivers: + for ot in rx.optics_tubes: + for fp in ot.focal_planes: + in_system += [f"{meas.meas_id}+{meas.name}" for meas in fp.focal_planes] + done_ids = [f"{job.tags['obs_id']}+{job.tags['array']}" for job in done_jobs] + open_ids = [f"{job.tags['obs_id']}+{job.tags['array']}" for job in open_jobs] + all_ids = done_ids + open_ids + + # Check if there are any measurements without a job + not_in_jdb = np.setdiff1d(in_system, all_ids) + if len(not_in_jdb) > 0: + raise ValueError( + f"{len(not_in_jdb)} jobs in current system but not found in jdb!\n{not_in_jdb}" + ) + + # Check if there are any jobs marked done not in the system and reopen them + not_in_system = np.setdiff1d(done_ids, in_system) + to_open = np.array(done_jobs)[np.isin(done_ids, not_in_system)] + if len(not_in_system) > 0: + for job in to_open: + job.jstate = cast(sqy.Column[str], jobdb.JState.open) + logger.info("Opening %s old jobs", len(to_open)) + jdb.update_jobs(to_open) + with jdb.session_scope() as session: + for job in to_open: # updated_jobs: + jid = job.id + refreshed_job = session.get(jobdb.Job, jid) + session.expunge(refreshed_job) + open_jobs.append(refreshed_job) + done_jobs = [job for job, jid in zip(done_jobs, done_ids) if jid in not_in_system] + + # Anything that is an open job needs to be removed from the system + open_ids += [f"{job.tags['obs_id']}+{job.tags['array']}" for job in to_open] + for rx in system.receivers: + for ot in rx.optics_tubes: + for fp in ot.focal_planes: + fp.focal_planes = [ + meas + for meas in fp.focal_planes + if f"{meas.meas_id}+{meas.name}" not in open_ids + ] + + return open_jobs, done_jobs + + +def _plot_fit(system, plot_dir, i, cfg): + logger.info("Plotting fitted focal-plane collections for round %s", i) + for rx in system.receivers: + if rx.allpad: + continue + pdir = os.path.join(plot_dir, rx.epoch, f"fit_{i}") + os.makedirs(pdir, exist_ok=True) + fpp.plot_receiver(rx, pdir) + fpp.plot_receiver_displacements(rx, [(None, None)], pdir) + fpp.plot_receiver_nuisance_displacements( + rx, system.nuisance_params, cfg.nuisance_plot, [(None, None)], pdir + ) + fpp.plot_receiver_nuisance_transform_displacements( + rx, system.nuisance_params, [(None, None)], pdir + ) + fpp.plot_receiver_resid_vs_enc(rx, pdir) + fpp.plot_receiver_residuals(rx, pdir) + for ot in rx.optics_tubes: + if ot.allpad: + continue + fpp.plot_optics_tube(ot, pdir) + for fp in ot.focal_planes: + if fp.pad: + continue + fpp.plot_ufm(fp, pdir) + + +def _make_executor(pool_type: str, pool_size: int) -> Executor: + if pool_type == "thread": + from concurrent.futures import ThreadPoolExecutor + + return ThreadPoolExecutor(max_workers=pool_size) + if pool_type == "process": + from concurrent.futures import ProcessPoolExecutor + + return ProcessPoolExecutor(max_workers=pool_size) + if pool_type == "interpreter": + from concurrent.futures import ( + InterpreterPoolExecutor, + ) # type: ignore[reportAttributeAccessIssue] + + return InterpreterPoolExecutor(max_workers=pool_size) + if pool_type == "mizu": + import pymizu + + return pymizu.PoolExecutor.create(pool_size) + raise ValueError(f"Invalid pool type: {pool_type}") + + +def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): + # Load config + require = ( + "optics_config", + "calendar", + "era", + "context", + ) # Not bothering with things we have defaults for + cfg, cfg_str = load_config_namespace(config_path, default_config, None, require) + cal = epochs.Calendar.load(cfg.calendar) + ctx = Context(cfg.context) + with open(cfg.calendar) as f: + cal_str = f.read() + with open(cfg.context) as f: + ctx_str = f.read() + + # Figure out paths + plot_dir, data_dir = _setup_paths( + cfg.root_dir, cfg.project_dir, cfg.tel, cfg.append + ) + os.makedirs(data_dir, exist_ok=True) + os.makedirs(plot_dir, exist_ok=True) + outfile = os.path.join(data_dir, "static_pointing.h5") + + # Setup output + old_system, old_cfg = _get_old(outfile, overwrite, backup) + system = fpc.PointingSystem.empty(cal.eras[cfg.era], cfg, cal_str) + system.state_meta["timestamp"] = timestamp + system.state_meta["config"] = cfg_str + system.state_meta["context"] = ctx_str + repo = git.Repo( + os.path.abspath(os.path.dirname(__file__)), search_parent_directories=True + ) + system.state_meta["git_sha"] = ( + f"{repo.head.object.hexsha}{'_dirty'*repo.is_dirty()}" + ) + + # Setup executor + executor = _make_executor(cfg.pool_type, cfg.pool_size) + + # Make templates and load old data if we can + _compute_templates_and_copy_old(system, cfg, old_system, old_cfg, ctx, plot_dir) + + # Save our template + logger.info("Saving templates") + with h5py.File(outfile, "a") as f: + system.save(f, "/", True) + fpc.make_manifestdb( + system, "template", os.path.join(data_dir, "template.sqlite"), outfile + ) + + # Mark pad epochs as pad + logger.info("Padding epochs") + system.set_pad(cfg.pad_epochs, False) + + # Get obs list + logger.info("Getting obslist") + obslist = _get_obslist(ctx, cfg, system) + + # Set up per-obs jobs + logger.info("Setting up per-obs jobs") + jdb_path = os.path.join(data_dir, "jobdb.sqlite") + jdb, open_jobs = ju.setup_jobs( + None, + jdb_path, + "per_obs", + _get_jobdict_po, + partial(_get_jobit_po, obslist=obslist, system=system), + _get_jobstr_po, + _get_tags_po, + [], + overwrite, + False, + None, + 0, + False, + logger, + ) + done_jobs = jdb.get_jobs(jclass="per_obs", jstate="done") + open_jobs, done_jobs = _check_jobs(system, jdb, done_jobs, open_jobs) + + # Load in all obs and populate in per-obs mode, probably want some sort of parallelism here + _run_per_obs(open_jobs, done_jobs, jdb, ctx, system, cfg, plot_dir, outfile) + + # Pad empty if needed + if cfg.pad_empty: + logger.info("Padding empty") + system.set_pad(cfg.pad_epochs, True) + + # Force pointing model consistancy + pm_epcs = [pm.epoch for pm in system.pointing_models] + for rx in system.receivers: + for ot in rx.optics_tubes: + for fp in ot.focal_planes: + for meas in fp.focal_planes: + try: + pm_idx = pm_epcs.index(meas.pointing_model.epoch) + except ValueError: + raise ValueError( + f"Can't find pointing model with epoch {meas.pointing_model.epoch} (in {meas.name}+{meas.meas_id})" + ) + meas.pointing_model = system.pointing_models[pm_idx] + + # Setup nuisance + nuisance_params = fpc.NuisanceParams.from_system( + system, cfg.nuisance_params, cfg.obs_time_thresh + ) + system.nuisance_params = nuisance_params + for pm in system.pointing_models: + pm.nuisance_params = nuisance_params + + # Save our per-obs results + logger.info("Saving per-obs") + system.set_static(True) + with h5py.File(outfile, "a") as f: + system.save(f, "/", True) + fpc.make_per_obs_manifestdb( + system, "transformed", os.path.join(data_dir, "per_obs.sqlite"), outfile + ) + + # Setup fit params + params, bounds, scales = fpc.setup_fit_params(system, cfg, old_system) + logger.info(params[: len(system.parameters)]) + npar = len(system.parameters) + nresid = len(system.residuals) + nresid_full = len( + system.objective_resid(system.parameters_full, nresid, cfg.cm_fac, executor) + ) + jac_sparsity = None + if len(cfg.nuisance_params) > 0 and cfg.least_squares and cfg.n_rounds > 0: + jac_sparsity = np.zeros((len(system.parameters_full), nresid_full), dtype=int) + jac_n = jac_sparsity[npar:].reshape((-1, len(cfg.nuisance_params), nresid_full)) + n = 0 + for rx in system.receivers: + for ot in rx.optics_tubes: + for fp in ot.focal_planes: + for meas in fp.focal_planes: + idx = system.nuisance_params.obs_mapping[meas.meas_id] + ndet = len(meas.weights) + jac_n[idx, :, n : (n + ndet)] = meas.wmsk.astype(int) + n += ndet + jac_sparsity[npar:, nresid:] = 1 + jac_sparsity = csr_array(jac_sparsity.T, dtype=bool) + + system.set_thaw(True) + system.set_freeze(True) + logger.info("Initial chisq is %.5f", system.chisq) + _plot_fit(system, plot_dir, 0, cfg) + + # Fit for pointing model and focal planes + for i in range(cfg.n_rounds): + logger.info("Starting fit round %d", i + 1) + system.set_thaw(True) + + par_list = system.nuisance_params.par_list + transform_list = system.nuisance_params.transform_list + if cfg.zero_nuisance: + par_list = deepcopy(par_list) + transform_list = deepcopy(transform_list) + x0 = system.parameters_full.copy() + x0[npar:] = 0 + system.update_parameters(x0) + system.nuisance_params.transform_list = [ + fpc.Transform.identity() for _ in range(len(transform_list)) + ] + + # Just static + logger.info("Fitting static for round %d", i + 1) + x0 = system.parameters_full.copy() + x0 = x0[:npar] + scales_use = scales[:npar] + bounds_use = bounds[:npar] + res, params_fit = _fit_round( + system, + x0, + bounds_use, + scales_use, + nresid, + cfg.least_squares, + None, + cfg.cm_fac, + executor, + ) + system.update_parameters(params_fit) + _report_fit(res, cfg, system, npar, x0, True, False) + system.set_thaw(True) + system.set_freeze(True) + _plot_fit(system, plot_dir, i + 1, cfg) + + if cfg.zero_nuisance: + system.nuisance_params.par_list = par_list + + # Now nuisance + if len(cfg.nuisance_params) > 0 and i + 1 >= cfg.activate_nuisance: + system.set_thaw(True) + rev_mapping = system.nuisance_params.rev_mapping + logger.info("Fitting nuisance for round %d", i + 1) + x0 = system.parameters_full.copy() + nn = len(cfg.nuisance_params) + scales_use = scales + for j in range(len(system.nuisance_params.par_list)): + logger.info( + "Fitting %d/%d", j + 1, len(system.nuisance_params.par_list) + ) + bounds_fixed = [(val, val) for val in system.parameters_full] + par_start, par_stop = npar + (j * nn), npar + ((j + 1) * nn) + bounds_use = ( + bounds_fixed[:par_start] + + bounds[par_start:par_stop] + + bounds_fixed[par_stop:] + ) + res, params_fit = _fit_round( + system, + x0, + bounds_use, + scales_use, + nresid, + cfg.least_squares, + jac_sparsity, + cfg.cm_fac, + executor, + thaw_meas=rev_mapping[i], + xtol=1e-6, + ftol=1e-4, + ) + system.update_parameters(params_fit.copy()) + _report_fit(res, cfg, system, npar, x0, False, True) + x0 = params_fit.copy() + system.nuisance_params.mean_zero(system) + system.set_thaw(True) + system.set_freeze(True) + _plot_fit(system, plot_dir, f"{i + 1}_np", cfg) + + # Now do the fp nuisance transforms + if i + 1 >= cfg.activate_nuisance_transforms: + system.set_thaw(True) + logger.info("Fitting nuisance transforms for round %d", i + 1) + system.nuisance_params.compute_transforms(system) + system.set_thaw(True) + system.set_freeze(True) + _plot_fit(system, plot_dir, f"{i + 1}_fp", cfg) + + if cfg.zero_nuisance: + system.nuisance_params.transform_list = transform_list + + # Cut outliers + tot_cut = 0 + for rx in system.receivers: + for ot in rx.optics_tubes: + for fp in ot.focal_planes: + if fp.pad: + continue + all_errs = [] + wmsks = [] + for meas in fp.focal_planes: + wmsk = np.isfinite(meas.weights) * (meas.weights > 0) + if meas.fake_gamma: + err = np.linalg.norm(meas.fpc_resid[:, :2], axis=1) + else: + err = np.linalg.norm(meas.fpc_resid, axis=1) + err[~wmsk] = np.nan + all_errs.append(err) + wmsks.append(wmsk) + errs_full = np.hstack(all_errs) + err_cutoff = np.nanmean(errs_full) + cfg.outlier_sigma * np.nanstd( + errs_full + ) + print(err_cutoff) + for meas, err, wmsk in zip(fp.focal_planes, all_errs, wmsks): + mrmsk = err > err_cutoff + # meas.weights[mrmsk] = 0 + meas.wmsk[mrmsk] = False + meas.wmsk = meas.wmsk.copy() # reset cache + tot_cut += np.sum(mrmsk[wmsk]) + + if tot_cut == 0 and i >= cfg.activate_nuisance: + logger.info("None cut! Stopping optimization.") + break + logger.info("Done fitting!") + + # Save + logger.info("Saving final fit") + system.set_static(True) + with h5py.File(outfile, "a") as f: + system.save(f, "/", True) + fpc.make_manifestdb( + system, "transformed", os.path.join(data_dir, "focal_plane.sqlite"), outfile + ) + + # Run MCMC if we want + if cfg.mcmc_steps > 0: + _ = _run_mcmc(system, nresid, cfg, bounds, scales, data_dir, plot_dir, executor) + + # Shutdown executor + executor.shutdown() + + +def main(): + # Load arguments + parser = ap.ArgumentParser() + parser.add_argument("config_path", help="Location of the config file") + parser.add_argument("--profile", "-p", action="store_true", help="Run a profiler") + parser.add_argument( + "--overwrite", "-o", action="store_true", help="Overwrite existing data" + ) + parser.add_argument( + "--backup", "-b", action="store_true", help="Backup existing data" + ) + args = parser.parse_args() + + profiler = None + timestamp = dt.datetime.now(dt.timezone.utc).strftime("%Y%m%d_%H%M%S") + logger.info("Starting at %s", timestamp) + if args.profile: + logger.info("Running with profiler") + profiler = pyinstrument.Profiler() + profiler.start() + + try: + run(args.config_path, args.overwrite, args.backup, timestamp) + finally: + if args.profile and profiler is not None: + prof_out = f"solve_static_pointing_{timestamp}.html" + profiler.stop() + profiler.write_html(prof_out) + logger.info("Saving profile to %s", prof_out) + + +if __name__ == "__main__": + main() diff --git a/sotodlib/utils/config.py b/sotodlib/utils/config.py new file mode 100644 index 000000000..653d979e5 --- /dev/null +++ b/sotodlib/utils/config.py @@ -0,0 +1,160 @@ +import os +from argparse import Namespace +from copy import deepcopy +from typing import Any, Optional + +import yaml + + +def deep_merge(a: dict[str, Any], b: dict[str, Any]) -> dict[str, Any]: + """ + Recursively merge two dictionaries. + + Values from `b` take precedence over values from `a`. When a key + exists in both dictionaries and both corresponding values are + dictionaries, those dictionaries are merged recursively. All other + values from `b` replace the corresponding values from `a`. + Values are deep-copied when inserted into the result, so mutable values + in the input dictionaries are not shared with the returned dictionary. + + Parameters + ---------- + a : dict[str, Any] + The base dictionary. + b : dict[str, Any] + The dictionary whose values take precedence. + + Returns + ------- + dict[str, Any] + A new dictionary containing the recursively merged values. Neither + input dictionary is modified. + """ + result = deepcopy(a) + for bk, bv in b.items(): + av = result.get(bk) + if isinstance(av, dict) and isinstance(bv, dict): + result[bk] = deep_merge(av, bv) + else: + result[bk] = deepcopy(bv) + return result + + +def load_config(start_cfg: dict[str, Any], cfg_path: str) -> dict[str, Any]: + """ + Load a configuration file and recursively merge its base configuration. + + The configuration at `cfg_path` is loaded and merged with + `start_cfg`. If the loaded configuration contains a `base` key then + the referenced base configuration is loaded recursively and is merged in. + + Values from the more specific configuration take precedence over values + from its base configuration. + + Note that relative ``"base"`` paths are resolved relative to the directory + containing the configuration file that references them. + + Parameters + ---------- + start_cfg : dict[str, Any] + Configuration values that take precedence over values loaded from `cfg_path`. + cfg_path : str + Path to the YAML configuration file to load. + + Returns + ------- + dict[str, Any] + The fully merged configuration. + + Raises + ------ + FileNotFoundError + If `cfg_path` or a referenced base configuration does not exist. + yaml.YAMLError + If a configuration file contains invalid YAML. + """ + with open(cfg_path) as file: + new_cfg = yaml.safe_load(file) + + cfg = deep_merge(new_cfg, start_cfg) + if "base" in new_cfg: + base_path = new_cfg["base"] + if not os.path.isabs(base_path): + base_path = os.path.join(os.path.dirname(cfg_path), base_path) + return load_config(cfg, base_path) + + return cfg + + +def load_config_namespace(cfg_or_path: str, defaults: Optional[dict[str, Any]] = None, replace: Optional[dict[str, str]] = None, require: tuple[str,...] = tuple()) -> tuple[Namespace, str]: + """ + Load configuration into an argparse namespace. + + `cfg_or_path` may be either a path to a YAML configuration file or a + YAML-formatted string. Configuration keys can optionally be renamed using + `replace`, and missing keys can be populated from `defaults`. + + Replacement keys are applied before default values are added. If a + replacement target already exists, its value is overwritten by the + value from the original key. + + Parameters + ---------- + cfg_or_path : str + Path to a YAML configuration file, or a YAML-formatted string. + defaults : Optional[dict[str, Any]], default: None + Default configuration values. A default is only used when its key is + not already present in the loaded configuration. + replace : Optional[dict[str, str]], default: None + Mapping from existing configuration keys to their replacement names. + When a key is present, its value is moved to the new key and the + original key is removed. + require : tuple[str,...], default: (,) + List of keys in the final config that are required. + Will raise a `KeyError` if a required key is not found. + + Returns + ------- + cfg + The loaded configuration as an `argparse.Namespace`. + cfg_str + The configuration serialized as a YAML string. + This is the fully collated config with the base configs + merged in and the renamed and defaults applied. + + Raises + ------ + FileNotFoundError + If `cfg_or_path` is interpreted as a file path but the file does + not exist. + yaml.YAMLError + If the configuration contains invalid YAML. + KeyError + If we are missing a required key. + """ + if defaults is None: + defaults = {} + if replace is None: + replace = {} + + if os.path.isfile(cfg_or_path): + cfg = load_config({}, cfg_or_path) + else: + cfg = yaml.safe_load(cfg_or_path) + + for o, n in replace.items(): + if o not in cfg: + continue + cfg[n] = cfg[o] + del cfg[o] + + for k, v in defaults.items(): + cfg[k] = cfg.get(k, v) + + missing = set(require) - set(cfg.keys()) + if len(missing) > 0: + raise KeyError(f"Missing config keys: {missing}") + + cfg_str = yaml.dump(cfg) + return Namespace(**cfg), cfg_str + diff --git a/sotodlib/utils/epochs.py b/sotodlib/utils/epochs.py new file mode 100644 index 000000000..0f64c379a --- /dev/null +++ b/sotodlib/utils/epochs.py @@ -0,0 +1,704 @@ +import os +import operator +import re +from bisect import bisect_right +from copy import deepcopy +from dataclasses import dataclass, field +from functools import reduce +from typing import Any, Literal, Optional, Self, cast, overload +from jaxtyping import Float, Shaped + +import numpy as np +import yaml +from deepdiff import DeepDiff + +OP_MAP = { + "|": operator.or_, + "&": operator.and_, + "*": operator.mul, + "+": operator.add, + "/": operator.truediv, + "-": operator.sub, + "**": operator.pow, + "@": operator.matmul, +} + + +def group_obs( obs_ids: Shaped[np.ndarray, "n"], timestamps: Float[np.ndarray, "n"], threshold: float,) -> tuple[list[Shaped[np.ndarray, "?m"]], list[Float[np.ndarray, "?m"]]]: + """ + Group observations based on timestamp proximity. + Mostly to group different OTs for the LAT since they have + seperate obs_ids with slightly different timestamps. + + Parameters + ---------- + obs_ids : Shaped[np.ndarray, "n"] + obs_ids corresponding to each timestamp. + timestamps : Float[np.ndarray, "n"] + Timestamps associated with each observation. + threshold : float + Maximum allowed difference between consecutive timestamps within a group. + + Returns + ------- + split_obs_ids : list[Shaped[np.ndarray, "?m"]] + obs_ids split into groups by their timestamp. + split_timestamps : Float[np.ndarray, "?m"]] + Timestamps split into groups in the same order as split_obs_ids. + """ + sort_idx = np.argsort(timestamps) + sorted_timestamps = timestamps[sort_idx] + sorted_obs_ids = obs_ids[sort_idx] + split_indices = np.where(np.diff(sorted_timestamps) > threshold)[0] + 1 + split_timestamps = np.split(sorted_timestamps, split_indices) + split_obs_ids = np.split(sorted_obs_ids, split_indices) + + return split_obs_ids, split_timestamps + +@dataclass +class Interval: + """ + Smallest unit of the epoch system. + Here we have a time interval containing a set of tags and an arbitrary dict of data. + This can be sliced with standard slicing notation, but the indices are ctime. + + Two `Interval` instances can be combined with the following operators, + all operators are functionally addition but with differing checks: + + * `|`: Intervals must overlap; data and tags may differ. + * `&`: Gaps are allowed; data and tags may differ. + * `*`: Intervals must overlap; data must be identical, but tags may differ. + * `+`: Gaps are allowed; data must be identical, but tags may differ. + * `/`: Intervals must overlap; tags must be identical, but data may differ. + * `-`: Gaps are allowed; tags must be identical, but data may differ. + * `**`: Intervals must overlap; data and tags must both be identical. + * `@`: Gaps are allowed; data and tags must both be identical. + + In cases where `data` is not the same but the `Invervals` are combined, + the new `data` will keep values from the right hand `Inverval` for overlapping keys. + """ + + name: str + start: float + stop: float + tags: set[str] + data: dict[str, Any] + + def __repr__(self) -> str: + return f"{self.name}[{self.start}:{self.stop}]" + + def __getitem__(self: Self, val) -> Self: + to_ret = deepcopy(self) + if not isinstance(val, slice): + val = slice(val) + if val.start is not None: + if self.start > val.start: + raise IndexError( + f"Start of slice out of range, interval starts at {self.start} but slice starts at {val.start}!" + ) + to_ret.start = val.start + if val.stop is not None: + if self.stop < val.stop: + raise IndexError( + f"End of slice out of range, interval stops at {self.stop} but slice stops at {val.stop}!" + ) + to_ret.stop = val.stop + return to_ret + + def __eq__(self, other) -> bool: + if not isinstance(other, Interval): + return False + diff = DeepDiff(self.data, other.data) + return bool( + (str(self) == str(other)) * (self.tags == other.tags) * (len(diff) == 0) + ) + + def combine( + self: Self, + tocombine: Self, + in_place: bool = True, + allow_gap: bool = False, + same_data: bool = False, + same_tag: bool = False, + ) -> Self: + if not isinstance(tocombine, Interval): + raise TypeError( + f"Can only add intervals to other intervals, not {type(tocombine)}!" + ) + combined = self + if in_place: + combined = deepcopy(self) + if not allow_gap and ( + self.start > tocombine.stop or self.stop < tocombine.start + ): + raise ValueError( + "Can't combine without overlapping time ranges with allow_gap=False" + ) + combined.start = min(self.start, tocombine.start) + combined.stop = max(self.stop, tocombine.stop) + + if same_tag and self.tags != tocombine.tags: + raise ValueError("Can't combine without identical tags with same_tag=True") + combined.tags = self.tags.union(tocombine.tags) + + diff = DeepDiff(self.data, tocombine.data) + if same_data and len(diff) != 0: + raise ValueError("Can't combine without identical data with same_data=True") + combined.data.update(tocombine.data) + + combined.name = self.name + "+" + tocombine.name + + return combined + + def __or__(self, tocombine) -> Self: + return self.combine(tocombine, False, False, False, False) + + def __ior__(self, tocombine) -> Self: + return self.combine(tocombine, True, False, False, False) + + def __and__(self, tocombine) -> Self: + return self.combine(tocombine, False, True, False, False) + + def __iand__(self, tocombine) -> Self: + return self.combine(tocombine, True, True, False, False) + + def __mul__(self, tocombine) -> Self: + return self.combine(tocombine, False, False, True, False) + + def __imul__(self, tocombine) -> Self: + return self.combine(tocombine, True, False, True, False) + + def __add__(self, tocombine) -> Self: + return self.combine(tocombine, False, True, True, False) + + def __iadd__(self, tocombine) -> Self: + return self.combine(tocombine, True, True, True, False) + + def __truediv__(self, tocombine) -> Self: + return self.combine(tocombine, False, False, False, True) + + def __itruediv__(self, tocombine) -> Self: + return self.combine(tocombine, True, False, False, True) + + def __sub__(self, tocombine) -> Self: + return self.combine(tocombine, False, True, False, True) + + def __isub__(self, tocombine) -> Self: + return self.combine(tocombine, True, True, False, True) + + def __pow__(self, tocombine) -> Self: + return self.combine(tocombine, False, False, True, True) + + def __ipow__(self, tocombine) -> Self: + return self.combine(tocombine, True, False, True, True) + + def __matmul__(self, tocombine) -> Self: + return self.combine(tocombine, False, True, True, True) + + def __imatmul__(self, tocombine) -> Self: + return self.combine(tocombine, True, True, True, True) + + +@dataclass +class Epoch: + """ + Dataclass for storing a collection of `Invervals`s. + `Inverval`s must be overlapping. + + Attributes + ---------- + name : str + Name for this epoch. + era_name : str + Name of the era that this epoch belongs to. + covers : tuple[Interval] + Collections of overlapping `Invervals` that make up an `Epoch`. + operator : str + The operator to use when constructing the interal combined `_interval`. + This acts as a check on strictness, so choose the operator most appropraite to + checking what your requirements are. + """ + + name: str + era_name: str + covers: tuple[Interval, ...] + operator: str + _internal: Interval = field(init=False) + + def __post_init__(self): + if self.operator not in OP_MAP: + raise ValueError(f"Invalid operator: {self.operator}") + self._internal = cast(Interval, reduce(OP_MAP[self.operator], self.covers)) + + def __repr__(self) -> str: + return ( + self.name + + "(" + + ",".join([str(ival) for ival in self.covers]) + + ")" + + (self.operator) + ) + + def __setattr__(self, name, value): + if (name == "covers" or name == "strict") and "_internal" in self.__dict__: + self.__post_init__() + return super().__setattr__(name, value) + + def __eq__(self, other): + if not isinstance(other, Epoch): + return False + return str(self) == str(other) + + def check_data(self, field: str, strict: bool = True) -> bool: + """ + Check that all `Interval`s in this `Epoch` contain a certain data field. + Optinally check that they each contain the same value for the field across all intervals. + + Parameters + ---------- + field : str + The name of the data field to check for. + strict : str + If True then all `Inverval`s within the `Epoch` must share the same + value for the data field. If `False` they simply need to exist. + + """ + if field not in self._internal.data: + return False + if strict: + tester = deepcopy(self) + try: + tester.operator = "+" + except ValueError: + return False + return True + return cast( + bool, reduce(OP_MAP["&"], [field in ival.data for ival in self.covers]) + ) + + +@dataclass +class Era: + """ + Dataclass for storing a collection of `Epoch`s. + `Epoch`s must be non-overlapping but can have gaps in time between them. + + Attributes + ---------- + name : str + Name for this era. + epochs : tuple[Epoch] + Collections of non-overlapping `Epochs` that make up an `Era`. + operator : str + The operator to use when constructing the interal combined `_interval`. + This acts as a check on strictness, so choose the operator most appropraite to + checking what your requirements are. + """ + + name: str + epochs: tuple[Epoch, ...] + operator: str + _internal: Interval = field(init=False) + _lookup: tuple[tuple[float, float, int], ...] = field(init=False) + + def __post_init__(self): + if self.operator not in OP_MAP: + raise ValueError(f"Invalid operator: {self.operator}") + self._internal = cast( + Interval, reduce(OP_MAP[self.operator], [e._internal for e in self.epochs]) + ) + self._lookup = sorted( + (ival.start, ival.stop, i) + for i, epoch in enumerate(self.epochs) + for ival in epoch.covers + ) + + def __setattr__(self, name, value): + if (name == "epochs" or name == "strict") and ( + "_internal" in self.__dict__ or "_lookup" in self.__dict__ + ): + self.__post_init__() + return super().__setattr__(name, value) + + def check_data(self, field: str, strict: bool = True) -> bool: + """ + Check that all `Epoch`s in this `Era` contain a certain data field. + Optinally check that all of their `Invervals` also contain the same value for the field. + + Parameters + ---------- + field : str + The name of the data field to check for. + strict : str + If True then all `Inverval`s within each `Epoch` must share the same + value for the data field. If `False` they simply need to exist. + + """ + return cast( + bool, + reduce(OP_MAP["&"], [e.check_data(field, strict) for e in self.epochs]), + ) + + def find_epoch(self, timestamp: float) -> Optional[Epoch]: + """ + Find the epoch from that a timestamp matches to. + Note that if your operator allows for overlapping Epochs then this will + just find the first epoch that matches. + + Parameters + ---------- + timestamp : float + The time to search for. + + Returns + ------- + found : Optional[Epoch] + The first matching Epoch. + Will be None if no matches are found. + """ + starts = [x[0] for x in self._lookup] + j = bisect_right(starts, timestamp) - 1 + if j >= 0 and timestamp < self._lookup[j][1]: + return self.epochs[self._lookup[j][2]] + return None + + +@dataclass +class Calendar: + """ + Class to manage intervals, epochs, and eras in a unified way. + It is reccomended to modify relationships between these using this class, + the `Calender` is not aware of direct modifications. + """ + + intervals: dict[str, Interval] + epochs: dict[str, Epoch] + eras: dict[str, Era] + data: dict[str, dict[str, Any]] + orphan_epochs: list[Epoch] + + @overload + def find_tagged(self, tag: str, search_in: Literal["eras"]) -> list[Era]: ... + + @overload + def find_tagged(self, tag: str, search_in: Literal["epochs"]) -> list[Epoch]: ... + + @overload + def find_tagged( + self, tag: str, search_in: Literal["intervals"] + ) -> list[Interval]: ... + + def find_tagged( + self, tag: str, search_in: Literal["intervals", "epochs", "eras"] + ) -> list: + """ + Return all objects containing a specific tag. + The `search_in` parameter specifies which type of object to search for. + + Parameters + ---------- + tag : str + The tag to search for. + search_in : Literal["intervals", "eras", "epochs"] + What type of objects to search for. + Note that orphaned epochs will not be searched. + + Returns + ------ + found : list + A list of obects of type `search_in` containing this tag. + """ + if search_in == "intervals": + return [ival for ival in self.intervals.values() if tag in ival.tags] + elif search_in == "epochs": + return [ + epoch for epoch in self.epochs.values() if tag in epoch._internal.tags + ] + elif search_in == "eras": + return [era for era in self.eras.values() if tag in era._internal.tags] + else: + raise ValueError(f"Invalid search_in: {search_in}") + + @overload + def find_data_field(self, field: str, search_in: Literal["eras"]) -> list[Era]: ... + + @overload + def find_data_field( + self, field: str, search_in: Literal["epochs"] + ) -> list[Epoch]: ... + + @overload + def find_data_field( + self, field: str, search_in: Literal["intervals"] + ) -> list[Interval]: ... + + def find_data_field( + self, field: str, search_in: Literal["intervals", "epochs", "eras"] + ) -> list: + """ + Return all objects containing a specific data field. + The `search_in` parameter specifies which type of object to search for. + To check that a specific `Era` has a field in all of it's epochs use `Era.check_data`. + + Parameters + ---------- + field : str + The name of the field to check + search_in : Literal["intervals", "eras", "epochs"] + What type of objects to search for. + Note that orphaned epochs will not be searched. + + Returns + ------ + found : list + A list of obects of type `search_in` containing this data field. + """ + if search_in == "intervals": + return [ival for ival in self.intervals.values() if field in ival.data] + elif search_in == "epochs": + return [ + epoch for epoch in self.epochs.values() if field in epoch._internal.data + ] + elif search_in == "eras": + return [era for era in self.eras.values() if field in era._internal.data] + else: + raise ValueError(f"Invalid search_in: {search_in}") + + def change_strictness( + self, strictness: bool, era: str, epoch: Optional[str] = None + ): + """ + Change the strictness for an `Era` or an `Epoch`. + + Parameters + ---------- + strictness : bool + The new strictness. + era : str + The name of the era to modify. + epoch : Optional, default: None + The name of epoch to modify. + To modify only the era set `epoch` to `None`. + To modify all `Epoch`s in an era set to `all`. + """ + if epoch is None: + self.eras[era].strict = strictness + else: + self.epochs[f"{era}.{epoch}"].strict = strictness + + def add_epoch(self, era: str, epoch: Epoch): + """ + Add an `Epoch` to an `Era`. + If the `Epoch` is in the orphans list it will be removed. + + Parameters + ---------- + era : str + The name of the era to modify. + epoch : Epoch + The new epoch to add. + """ + epoch.era_name = era + epoch_list = list(self.eras[era].epochs) + [epoch] + self.eras[era].epochs = tuple(epoch_list) + self.epochs[f"{era}.{epoch.name}"] + self.epoch_orphans = [e for e in self.epoch_orphans if e != epoch] + + def del_epoch(self, era: str, epoch: str): + """ + Delete an `Epoch` from an `Era`. + This will add it to the orphans list + + Parameters + ---------- + era : str + The name of the era to modify. + epoch : str + The name of the epoch to remove. + """ + to_remove = self.epochs[f"{era}.{epoch}"] + self.epoch_orphans += [to_remove] + self.eras[era].epochs = tuple( + e for e in self.eras[era].epochs if e != to_remove + ) + del self.epochs[f"{era}.{epoch}"] + + def add_interval(self, era: str, epoch: str, interval: Interval): + """ + Add an `Inverval` to an `Epoch`. + + Parameters + ---------- + era : str + The name of the era to modify. + epoch : Epoch + The name of epoch to modify, + interval : Interval + The interval to add. + """ + self.epochs[f"{era}.{epoch}"].covers = tuple( + list(self.epochs[f"{era}.{epoch}"].covers) + [interval] + ) + self.intervals[str(interval)] = interval + + def del_interval(self, era: str, epoch: str, interval: str): + """ + Delete an `Inverval` from an `Epoch`. + + Parameters + ---------- + era : str + The name of the era to modify. + epoch : Epoch + The name of epoch to modify, + interval : str + The name of interval (with its slice) to delete. + """ + self.epochs[f"{era}.{epoch}"].covers = tuple( + i + for i in self.epochs[f"{era}.{epoch}"].covers + if i != self.intervals[interval] + ) + + def find_slices(self, interval_name: str) -> list[Interval]: + """ + Find all slices for an interval. + + Parameters + ---------- + interval_name : str + The name of the interval to find slices for. + + Returns + ------- + slices : list[Interval] + List of slices with the correct name. + """ + ikeys = list(self.intervals.keys()) + r = re.compile(f"{interval_name}\\[.*:.*\\]") + ikeys = filter(r.match, ikeys) + slices = [self.intervals[ikey] for ikey in ikeys] + + return slices + + def get_membership(self, interval: str) -> list[tuple[Era, Epoch]]: + """ + Get the `Epochs` than an interval belongs to. + This does not search oprhaned `Epoch`s. + + Parameters + ---------- + interval : str + The name of the interval (with its slice) to search for. + + Returns + ------- + membership : list[tuple[Era, Epoch]] + A list a tuples where each element is an `(Era, Epoch)` pair + where the `Epoch` contains the interval. + """ + ival = self.intervals[interval] + membership = [] + for era in self.eras.values(): + for epoch in era.epochs: + for i in epoch.covers: + if i == ival: + membership += [(era, epoch)] + break + return membership + + @classmethod + def load(cls, fpath: str) -> Self: + if os.path.isfile(fpath): + with open(fpath, "r") as f: + cfg = yaml.safe_load(f) + else: + cfg = yaml.safe_load(fpath) + if "intervals" not in cfg: + raise ValueError("At minimum an intervals section must be provided") + + # Collate information in string form + intervals = cfg["intervals"] + eras = {} + data = {} + for key, val in cfg.items(): + if key == "intervals": + continue + if key[0] == "_": + data[key[1:]] = val + continue + eras[key] = val + + # Load intervals + interval_dict = {} + for name, interval in intervals.items(): + interval_data = {} + for key, val in interval.get("data", {}).items(): + val = val.split(".") + if len(val) != 2: + raise ValueError("Data must have format X.Y") + interval_data[key] = data[val[0]][val[1]] + ival = Interval( + name, + interval.get("start", 0), + interval.get("stop", 20000000000), + set(interval.get("tags", [])), + interval_data, + ) + interval_dict[str(ival)] = ival + intervals[name] = ival + + # Load epochs + epoch_dict = {} + for ename, era in eras.items(): + era_op = era.get("era_op", "&") + epoch_op = era.get("epoch_op", "&") + epochs = [] + for name, ec in era.items(): + if name in ["epoch_op", "era_op"]: + continue + covers = [] + for cname in ec.get("covers", []): + csplt = cname.split("[") + if len(csplt) == 1: + iname = cname + slstr = ":" + elif len(csplt) == 2: + iname, slstr = csplt + slstr = slstr[:-1] + else: + raise ValueError(f"Invalid cover string {cname}") + slc = slice( + *map( + lambda x: float(x.strip()) if x.strip() else None, + slstr.split(":"), + ) + ) + # Now allow for two cases + # Case 1: this is simply an interval ref + if iname in intervals: + ival = intervals[iname] + interval_dict[str(ival)] = ival + covers += [ival[slc]] + # Case 2: we are refering to a previously defined epoch + if iname in epoch_dict: + # In this case we want to add the intervals that this epoch covers + # But no need to add this to the interval dict + for ival in epoch_dict[iname].covers: + islc = slice( + max( + slc.start if slc.start is not None else -1 * np.inf, + ival.start, + ), + min( + slc.stop if slc.stop is not None else np.inf, + ival.stop, + ), + ) + covers += [ival[islc]] + epoch = Epoch(name, ename, tuple(covers), operator=epoch_op) + epochs += [epoch] + epoch_dict[f"{ename}.{name}"] = epoch + eras[ename] = Era(ename, tuple(epochs), era_op) + + return cls(interval_dict, epoch_dict, eras, data, []) diff --git a/sotodlib/utils/jdb_utils.py b/sotodlib/utils/jdb_utils.py new file mode 100644 index 000000000..5445bbf58 --- /dev/null +++ b/sotodlib/utils/jdb_utils.py @@ -0,0 +1,492 @@ +""" +Tools for setting up the JobDB. + +TODO: Add some quick tools for inspecting the jobdb here. +""" + +import logging +import os +import shutil +import sqlite3 +import sys +import time +from enum import Enum +from typing import TYPE_CHECKING, Any, Callable, Iterable, Optional, Sequence, cast + +import sqlalchemy as sqy +from sotodlib.site_pipeline import jobdb +from sqlalchemy.exc import OperationalError +from sqlalchemy.pool import NullPool + +LoggerLike = logging.Logger | logging.LoggerAdapter[logging.Logger] + +if TYPE_CHECKING: + from mpi4py.MPI import Comm + +# try: +# from mpi4py import MPI +# +# comm = MPI.COMM_WORLD +# except ImportError: +# comm = None + + +def set_tag(job: jobdb.Job, key: str, new_val: Any): + """ + Set the value of an existing tag on a job. + + Parameters + ---------- + job : jobdb.Job + The job whose tag should be updated. + key : str + The key identifying the tag to update. + new_val : Any + The new value to assign to the tag. + + Raises + ------ + ValueError + If the job does not contain a tag with the specified key. + """ + for tag in job._tags: + if tag.key == key: + tag.value = new_val + return + + raise ValueError(f'No tag called "{key}"') + + +def fail(job: jobdb.Job, errcode: Enum, msg: str, logger: Optional[LoggerLike] = None): + """ + Mark a job as failed and record its error information. + + Parameters + ---------- + job : jobdb.Job + Job to mark as failed. + errcode : Enum + Enum member representing the error code. + msg : str + Detailed error message. + logger : Optional[LoggerLike] + Optional logger for recording the error. + """ + if logger is not None: + logger.error("%s (Err %s: %s)", msg, errcode.value, errcode.name) + set_tag(job, "message", msg) + if "errcode" in job.tags: + set_tag(job, "errcode", errcode.value) + job.jstate = cast(sqy.Column[str], jobdb.JState.failed) + + +def sync_jobs(db_a_path: str, db_b_path: str, classes: Optional[Sequence[str]] = None): + """ + Copy selected jobs and their tags from one SQLite database to another. + + Jobs are selected from the source database, optionally filtered by + job class. A job is copied if it does not exist in the destination or + if its creation_time matches the existing destination record. + This check on creation_time is just a course check that its actually + the oritinal job. + + Use this function with care! Its mostly for some specific edge cases + and should not be used unsupervised on databases that are not backed up! + + Parameters + ---------- + db_a_path : str + Path to the source database. + db_b_path : str + Path to the destination database. + classes : Optional[Sequence[str]] + Job classes to select. If None, all classes are selected. + An empty sequence selects no jobs. + + Raises + ------ + sqlite3.Error + If a database operation fails. Destination changes are rolled back. + """ + conn_a = sqlite3.connect(db_a_path) + conn_b = sqlite3.connect(db_b_path) + + try: + if classes is not None and len(classes) == 0: + return + where_clause = "" + params: Sequence[str] = () + if classes is not None: + placeholders = ", ".join("?" for _ in classes) + where_clause = f"WHERE jclass IN ({placeholders})" + params = classes + jobs = conn_a.execute( + f""" + SELECT + id, + jclass, + jstate, + lock, + lock_owner, + creation_time, + visit_time, + visit_count + FROM jobs + {where_clause} + """, + params, + ).fetchall() + + for job in jobs: + job_id, _, _, _, _, creation_time, _, _ = job + existing = conn_b.execute( + "SELECT creation_time FROM jobs WHERE id = ?", + (job_id,), + ).fetchone() + + should_copy = existing is None or creation_time == existing[0] + if not should_copy: + continue + + conn_b.execute( + """ + INSERT OR REPLACE INTO jobs ( + id, jclass, jstate, lock, lock_owner, + creation_time, visit_time, visit_count + ) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + """, + job, + ) + + conn_b.execute( + "DELETE FROM tags WHERE job_id = ?", + (job_id,), + ) + + tags = conn_a.execute( + 'SELECT "key", value FROM tags WHERE job_id = ?', + (job_id,), + ).fetchall() + + conn_b.executemany( + 'INSERT INTO tags (job_id, "key", value) VALUES (?, ?, ?)', + [(job_id, key, value) for key, value in tags], + ) + + conn_b.commit() + except Exception: + conn_b.rollback() + raise + finally: + conn_a.close() + conn_b.close() + + +def make_jobdb( + comm: Optional["Comm"], + path: str, + merge_from: str = "", + merge_classes: Optional[Sequence[str]] = None, +) -> jobdb.JobManager: + """ + Open or initialize a job database. + + Rank 0 initializes the database and clears existing job locks. + When merge_from identifies an existing database, its jobs are + copied into the target database if the target exists, or the + source database is copied if the target does not exist. + + Other MPI ranks wait for initialization to finish before opening + the database. + + Parameters + ---------- + comm : Optional[Comm] + MPI communicator, or None when MPI is not being used. + path : str + Full path to the target SQLite database. + merge_from : str + Optional path to the source database to merge or copy. + If you pass an empty string or a path that doensn't exist + no merge is done. + merge_classes : Optional[Sequence[str]] + Optional job classes to select when merging. None selects all + job classes. + + Returns + ------- + jobdb.JobManager + Database manager using a ten-second SQLite timeout and NullPool. + """ + myrank = 0 + if comm is not None: + myrank = comm.Get_rank() + # Let rank 0 make jobdb first to avoid race conditions + jdb = None + if myrank == 0: + if merge_from != "" and os.path.isfile(merge_from): + if os.path.isfile(path): + sync_jobs(merge_from, path, merge_classes) + else: + shutil.copyfile(merge_from, path) + engine = sqy.create_engine( + f"sqlite:///{path}", + connect_args={"timeout": 10}, + poolclass=NullPool, + ) + jdb = jobdb.JobManager(engine=engine) + jdb.clear_locks(jobs="all") + + if comm is None: + return jdb + if comm is not None: + comm.barrier() + if myrank != 0: + engine = sqy.create_engine( + f"sqlite:///{path}", + connect_args={"timeout": 10}, + poolclass=NullPool, + ) + jdb = jobdb.JobManager(engine=engine) + if jdb is None: + raise ValueError("Jobdb is none somehow!") + return jdb + + +def setup_jobs( + comm: Optional["Comm"], + jdb: str | jobdb.JobManager, + jclass: str, + get_jobdict: Callable[[jobdb.JobManager], dict[str, jobdb.Job]], + get_jobit: Callable[[jobdb.JobManager], Iterable[Any]], + get_jobstr: Callable[[Any], Optional[str]], + get_tags: Callable[[Any], dict[str, str]], + tag_check: list[tuple[str, Sequence[Any]]], + overwrite: bool, + retry_failed: bool, + job_memory: Optional[float], + job_memory_buffer: float, + include_done: bool, + logger: LoggerLike, +) -> tuple[jobdb.JobManager, list[jobdb.Job]]: + """ + Discover, create, and select jobs for execution. + + Existing jobs are loaded from the job database and matched against a + collection of candidate jobs generated by `get_jobit`. Missing jobs are + created, eligible jobs are reopened when requested, and a consolidated + list of jobs to process is returned. + + Jobs may be filtered by lock status, tags, recent visit time, and + job state. Database writes are serialized across MPI ranks to avoid + contention. + + Parameters + ---------- + comm : Optional[Comm] + MPI communicator used to prevent deadlock between processes. + jdb : str | jobdb.JobManager + Either the path to the db or an already loaded db. + jclass : str + Job class name passed to `JobManager.create_job` when creating + missing jobs. + get_jobdict : Callable[[jobdb.JobManager], dict[str, jobdb.Job]] + Function that returns a mapping from job identifier strings to + existing jobs in the database. + get_jobit : Callable[[jobdb.JobManager], Iterable[Any]] + Function that returns an iterable of candidate job descriptions. + get_jobstr : Callable[[Any], Optional[str]] + Function that converts a candidate job description into its unique + job identifier string. Returning `None` causes the candidate to be + skipped. + get_tags : Callable[[Any], dict[str, str]] + Function that generates the tag dictionary used when creating a new + job from a candidate job description. + tag_check : Sequence[tuple[str, Sequence[Any]]] + Tag filters. Each pair contains a tag name and the allowed values + for that tag. Jobs with a present tag whose value is not allowed + are skipped. Jobs missing the tag are not excluded by this filter. + overwrite : bool + If True, reopen non-open jobs and include them for processing. + retry_failed : bool + If True, include failed jobs for processing. + job_memory : Optional[float] + Recent-visit exclusion window in hours. None disables this filter. + job_memory_buffer : float + Buffer in minutes: jobs visited more recently than this are not + excluded by the job-memory filter. + include_done : bool + If True, include jobs in the done state. + logger : LoggerLike + Logger to log to. + + Returns + ------- + jdb : jobdb.JobManager + Job database manager instance. + jobs : list[jobdb.Job] + Complete list of jobs selected for processing across all MPI ranks. + """ + if isinstance(jdb, str): + jdb = make_jobdb(comm, jdb) + myrank, nproc = 0, 1 + if comm is not None: + myrank = comm.Get_rank() + nproc = comm.Get_size() + # Get the jobs, make them if we need to + now = time.time() + logger.info("Setting up jobdb") + joblist = [] + jobs_to_make = [] + jobs_to_open = [] + logger.info("Getting jobdict") + jobdict = None + if myrank == 0: + jobdict = get_jobdict(jdb) + if comm is not None: + jobdict = comm.bcast(jobdict) + if jobdict is None: + raise ValueError("jobdict is None!") + logger.info("Getting potential jobs") + it = get_jobit(jdb) + logger.info("Processing possible jobs") + for info in it: + sys.stdout.flush() + jobstr = get_jobstr(info) + ignore_lock = False + if jobstr is None: + continue + if jobstr in jobdict: + job = jobdict[jobstr] + else: + tags = get_tags(info) + job = jdb.create_job( + jclass=jclass, tags=tags, check_existing=False, commit=False + ) + jobs_to_make += [job] + ignore_lock = True + if cast(bool, job.lock) and not ignore_lock: + continue + tag_filt = False + for tag, tag_list in tag_check: + if tag not in job.tags: + continue + if job.tags[tag] not in tag_list: + tag_filt = True + break + if tag_filt: + continue + visit_time = cast(Optional[float], job.visit_time) + if ( + visit_time is not None + and job_memory is not None + and now - visit_time < 60 * 60 * job_memory + and now - visit_time > 60 * job_memory_buffer + ): + continue + + if ( + overwrite + or job.jstate.name == "open" + or (job.jstate.name == "failed" and retry_failed) + ): + if job.jstate.name != "open": + job.jstate = cast(sqy.Column[str], jobdb.JState.open) + jobs_to_open += [job] + else: + joblist += [job] + elif include_done and job.jstate.name == "done": + joblist += [job] + if comm is not None: + comm.barrier() + + # Make the missing jobs + # Doing this serially so that we don't lock up the db + tot_missing = len(jobs_to_make) + if comm is not None: + tot_missing = comm.reduce(len(jobs_to_make), root=0) + logger.info("Adding %s new jobs", tot_missing) + tot_opening = len(jobs_to_open) + if comm is not None: + tot_opening = comm.reduce(len(jobs_to_open), root=0) + logger.info("Opening %s old jobs", tot_opening) + t0 = time.time() + for i in range(nproc): + if myrank == i: + logger.debug("\tRank %s writing", i) + jdb.commit_jobs(jobs_to_make) + jdb.clear_locks(jobs=joblist) + if len(jobs_to_open) > 0: + jdb.update_jobs(jobs_to_open) + with jdb.session_scope() as session: + for job in jobs_to_open: # updated_jobs: + jid = job.id + refreshed_job = session.get(jobdb.Job, jid) + session.expunge(refreshed_job) + joblist.append(refreshed_job) + if comm is not None: + comm.barrier() + t1 = time.time() + logger.info("Took %s seconds to add", t1 - t0) + + # Get the final job list + if comm is not None: + all_jobs = comm.allgather(joblist) + all_jobs = [job for jobs in all_jobs for job in jobs] + else: + all_jobs = joblist + logger.info("%s jobs to run!", len(all_jobs)) + + return jdb, all_jobs + + +def update_jobs_retry( + jdb: jobdb.JobManager, + jobs: Sequence[jobdb.Job], + max_retries: int, + logger: Optional[LoggerLike] = None, +): + """ + Update jobs, retrying when SQLite reports a database lock. + + Parameters + ---------- + jdb : jobdb.JobManager + Database manager used to persist the jobs. + jobs : Sequence[jobdb.Job] + Jobs to update. + max_retries : int + Maximum number of attempts, with at least one attempt made. + logger : Optional[LoggerLike] + Optional logger for reporting success or failure. + + Raises + ------ + OperationalError + If a database operational error occurs for a reason other than + a database lock. + """ + t0 = time.time() + attempts = max(1, max_retries) + for attempt in range(1, attempts + 1): + try: + jdb.update_jobs(jobs) + elapsed = time.time() - t0 + msg = f"Took {elapsed:.2f} seconds to write in {attempt} attempt(s)" + if logger is None: + print(msg) + else: + logger.debug(msg) + return + except OperationalError as exc: + if "database is locked" not in str(exc).lower(): + raise + if attempt == attempts: + msg = f"Failed to write after {attempt} attempt(s): {exc}" + if logger is None: + print(msg) + else: + logger.error(msg) + raise + time.sleep(1)