From 6a10d5bae861ff12a7671c9acbb9adae1f44a81a Mon Sep 17 00:00:00 2001 From: Tomoki Terasaki Date: Tue, 19 Mar 2024 02:05:11 +0000 Subject: [PATCH 001/132] initial commit --- sotodlib/coords/mapbased_pointing.py | 545 ++++++++++++++++++ .../site_pipeline/combine_focal_planes.py | 1 + .../site_pipeline/make_mapbased_pointing.py | 102 ++++ sotodlib/site_pipeline/update_pointing.py | 196 +++++++ 4 files changed, 844 insertions(+) create mode 100644 sotodlib/coords/mapbased_pointing.py create mode 100644 sotodlib/site_pipeline/combine_focal_planes.py create mode 100644 sotodlib/site_pipeline/make_mapbased_pointing.py create mode 100644 sotodlib/site_pipeline/update_pointing.py diff --git a/sotodlib/coords/mapbased_pointing.py b/sotodlib/coords/mapbased_pointing.py new file mode 100644 index 000000000..276c4dd7a --- /dev/null +++ b/sotodlib/coords/mapbased_pointing.py @@ -0,0 +1,545 @@ +import os +import re +from tqdm import tqdm +import numpy as np +from scipy import interpolate +from scipy.optimize import curve_fit + +from sotodlib import core +from sotodlib import coords +from sotodlib.coords import optics +from sotodlib.core import metadata +from sotodlib.io.metadata import write_dataset, read_dataset + +from so3g.proj import quat +from pixell import enmap +import h5py +from scipy.ndimage import maximum_filter + +def get_planet_trajectry(tod, planet, _split=20, return_model=False): + """ + Generate the trajectory of a given planet over a specified time range. + + Parameters: + tod : An axis manager + planet (str): The name of the planet for which to generate the trajectory. + _split (int, optional): Number of points to interpolate the trajectory. Defaults to 20. + return_model (bool, optional): If True, returns interpolation functions of az and el. Defaults to False. + + Returns: + If return_model is True: + tuple: Tuple containing interpolation functions for azimuth and elevation. + If return_model is False: + array: Array of quaternions representing trajectry of the planet at each timestamp. + """ + timestamps_sparse = np.linspace(tod.timestamps[0], tod.timestamps[-1], _split) + + planet_az_sparse = np.zeros_like(timestamps_sparse) + planet_el_sparse = np.zeros_like(timestamps_sparse) + for i, timestamp in enumerate(timestamps_sparse): + az, el, _ = coords.planets.get_source_azel(planet, timestamp) + planet_az_sparse[i] = az + planet_el_sparse[i] = el + planet_az_func = interpolate.interp1d(timestamps_sparse, planet_az_sparse, kind="quadratic", fill_value='extrapolate') + planet_el_func = interpolate.interp1d(timestamps_sparse, planet_el_sparse, kind="quadratic", fill_value='extrapolate') + if return_model: + return planet_az_func, planet_el_func + else: + planet_az = planet_az_func(tod.timestamps) + planet_el = planet_el_func(tod.timestamps) + q_planet = quat.rotation_lonlat(planet_az, planet_el) + return q_planet + +def get_wafer_centered_sight(tod, planet, q_planet=None, q_bs=None, q_wafer=None): + """ + Calculate the sightline vector from the focal plane, centered on the wafer, to a planet. + + Parameters: + tod : An axis manager + planet (str): The name of the planet to calculate the sightline vector. + q_planet (optional): Quaternion representing the trajectry of the planet. + If None, it will be computed using get_planet_trajectory. Defaults to None. + q_bs (optional): Quaternion representing the trajectry of the boresight. + If None, it will be computed using the current boresight angles from tod. Defaults to None. + q_wafer (optional): Quaternion representing the center of wafer to the center of boresight. + If None, it will be computed using the median of the focal plane xi and eta from tod.focal_plane. + Defaults to None. + + Returns: + Sightline vector for the planet trajectry centered on the center of the wafer. + """ + if q_planet is None: + q_planet = get_planet_trajectry(tod, planet) + if q_bs is None: + q_bs = quat.rotation_lonlat(tod.boresight.az, tod.boresight.el) + if q_wafer is None: + q_wafer = quat.rotation_xieta(np.nanmedian(tod.focal_plane.xi), + np.nanmedian(tod.focal_plane.eta)) + + xi_wafer, eta_wafer, _ = quat.decompose_xieta(q_wafer) + q_wafer_f = quat.rotation_xieta(-xi_wafer, eta_wafer) + z_to_x = quat.rotation_lonlat(0, 0) + sight = z_to_x * ~(q_bs * q_wafer_f) * q_planet + return sight + +def get_wafer_xieta(wafer_slot, optics_config_fn, xieta_bs_offset=(0., 0.), + roll_bs_offset=0., tod=None, wrap_to_tod=True,): + """ + Calculate the xi and eta coordinates for a given wafer slot on the focal plane. + + Parameters: + wafer_slot (str): The slot identifier of the wafer. + optics_config_fn (str): File name containing the optics configuration. + xieta_bs_offset (tuple): Offset in xieta coordinates for the focal plane, default is (0., 0.). + roll_bs_offset (float): Boresight roll offset. Default is 0 + tod (TimeOrderedData): TOD object to which focal plane infomation that all detectors have uniform pointing at center of the wafer is wrapped. + wrap_to_tod (bool): If True, wrap the calculated xi and eta coordinates to the Time-Ordered Data (TOD), default is True. + + Returns: + tuple: A tuple containing the calculated xi and eta coordinates for the specified wafer slot. + """ + + optics_config = optics.load_ufm_to_fp_config(optics_config_fn)['SAT'] + wafer_x, wafer_y = optics_config[wafer_slot]['dx'], optics_config[wafer_slot]['dy'] + wafer_r = np.sqrt(wafer_x**2 + wafer_y**2) + wafer_theta = np.arctan2(wafer_y, wafer_x) + + fp_to_sky = optics.sat_to_sky(optics.SAT_X, optics.SAT_LON) + lon = fp_to_sky(wafer_r) + + q1 = quat.rotation_iso(lon, 0) + + q2 = quat.rotation_iso(0, 0, np.pi/2 - wafer_theta - roll_bs_offset) + q3 = quat.rotation_xieta(xieta_bs_offset[0], xieta_bs_offset[1]) + q = q3 * q2 * q1 + + xi_wafer, eta_wafer, _ = quat.decompose_xieta(q) + if wrap_to_tod: + if tod is None: + raise ValueError('tod is not provided.') + if 'focal_plane' in tod._fields.keys(): + tod.move('focal_plane', None) + focal_plane = core.AxisManager(tod.dets) + focal_plane.wrap('xi', np.ones(tod.dets.count, dtype='float32') * xi_wafer, [(0, 'dets')]) + focal_plane.wrap('eta', np.ones(tod.dets.count, dtype='float32') * eta_wafer, [(0, 'dets')]) + focal_plane.wrap('gamma', np.zeros(tod.dets.count, dtype='float32'), [(0, 'dets')]) + tod.wrap('focal_plane', focal_plane) + tod.boresight.roll *= 0. + return xi_wafer, eta_wafer + + +def make_wafer_centered_maps(tod, planet, optics_config_fn, map_hdf, + xieta_bs_offset=(0., 0.), roll_bs_offset=None, + signal='signal', wcs_kernel=None, res=0.3*coords.DEG, cuts=None,): + """ + Generate boresight-centered maps from Time-Ordered Data (TOD) for each individual detector. + + Parameters: + tod : an axismanager object + planet (str): Name of the planet for which the trajectory is calculated. + optics_config_fn (str): File name containing the optics configuration. + map_hdf (str): Path to the HDF5 file where the maps will be saved. + xieta_bs_offset (tuple): Offset in xieta coordinates for the boresight, default is (0., 0.). + roll_bs_offset (float): Offset in roll angle for the boresight, default is None. + signal (str): Name of the signal to be used, default is 'signal'. + wcs_kernel (ndarray): WCS kernel for mapping, default is None. + res (float): Resolution of the map in degrees, default is 0.3 degrees. + cuts (tuple): Cuts to be applied to the map, default is None. + + Returns: + None + """ + + if wcs_kernel is None: + wcs_kernel = coords.get_wcs_kernel('car', 0, 0, res) + + q_planet = get_planet_trajectry(tod, planet) + q_bs = quat.rotation_lonlat(tod.boresight.az, tod.boresight.el) + + if roll_bs_offset is None: + roll_bs_offset = np.mean(tod.boresight.roll) + + # wafer + if np.unique(tod.det_info.wafer_slot).shape[0] > 1: + raise ValueError('tod include detectors from more than one wafer') + wafer_slot = tod.det_info.wafer_slot[0] + xi_wafer, eta_wafer = get_wafer_xieta(wafer_slot=wafer_slot, + xieta_bs_offset=xieta_bs_offset, + roll_bs_offset=roll_bs_offset, + tod=tod, + optics_config_fn=optics_config_fn, + wrap_to_tod=True) + + coords.planets.compute_source_flags(tod, center_on=planet, max_pix=100000000, + wrap=planet, mask={'shape':'circle', 'xyr':[0,0,8]}) + + q_wafer = quat.rotation_xieta(xi_wafer, eta_wafer) + sight = get_wafer_centered_sight(tod, planet, q_planet, q_bs, q_wafer) + + + + xi0 = tod.focal_plane.xi[0] + eta0 = tod.focal_plane.eta[0] + xi_bs_offset, eta_bs_offset = xieta_bs_offset + + tod.focal_plane.xi *= 0. + tod.focal_plane.eta *= 0. + tod.boresight.roll *= 0. + + if cuts is None: + cuts = ~tod.flags[planet] + P = coords.P.for_tod(tod=tod, wcs_kernel=wcs_kernel, comps='T', cuts=cuts, sight=sight, threads=False) + for di, det in enumerate(tqdm(tod.dets.vals)): + det_weights = np.zeros(tod.dets.count, dtype='float32') + det_weights[di] = 1. + mT_weighted = P.to_map(tod=tod, signal=signal, comps='T', det_weights=det_weights) + wT = P.to_weights(tod, signal=signal, comps='T', det_weights=det_weights) + mT = P.remove_weights(signal_map=mT_weighted, weights_map=wT, comps='T')[0] + + enmap.write_hdf(map_hdf, mT, address=det, + extra={'xi0': xi0, 'eta0': eta0, + 'xi_bs_offset': xi_bs_offset, 'eta_bs_offset': eta_bs_offset, 'roll_bs_offset': roll_bs_offset}) + return + +def detect_peak_xieta(mT, filter_size=None): + """ + Detects the peak in a given pixcell map and converts it to ξ and η coordinates. + + Parameters: + - mT (enmap.ndmap): a map object + - filter_size (int, optional): Size of the filter window for peak detection. + If not provided, it's calculated as a fraction + of the minimum dimension of mT. + + Returns: + - xi_peak (float): xi coordinate of the peak. + - eta_peak (float): eta coordinate of the peak. + - ra_peak (float): ra coordinate of the peak. + - dec_peak (float): dec coordinate of the peak. + - peak_i (int): Row index of the peak. + - peak_j (int): Column index of the peak. + """ + if filter_size is None: + filter_size = int(np.min(mT.shape)//10) + local_max = maximum_filter(mT, footprint=np.ones((filter_size, filter_size)), + mode='constant', cval=np.nan) + peak_i, peak_j = np.where(mT == np.nanmax(local_max)) + peak_i = int(np.median(peak_i)) + peak_j = int(np.median(peak_j)) + dec_grid, ra_grid = mT.posmap() + + ra_peak = ra_grid[peak_i][peak_j] + dec_peak = dec_grid[peak_i][peak_j] + xi_peak, eta_peak = _radec2xieta(ra_peak, dec_peak) + return xi_peak, eta_peak, ra_peak, dec_peak, peak_i, peak_j + +def get_center_of_mass(x, y, z, + circle_mask={'x0':0, 'y0':0, 'r_circle':3.0*coords.DEG}, + percentile_mask = {'q': 50}): + """ + Calculates the center of mass of a dataset within specified masks. + + Parameters: + - x (ndarray): Array of x-coordinates. + - y (ndarray): Array of y-coordinates. + - z (ndarray): Array of data values corresponding to the coordinates. + - circle_mask (dict, optional): Parameters defining circular mask. + Should contain keys 'x0', 'y0', and 'r_circle'. + Defaults to a circle centered at (0, 0) with radius 3.0 degrees. + - percentile_mask (dict, optional): Parameters defining percentile mask. + Should contain key 'q' representing the percentile threshold. + Defaults to the 50th percentile. + + Returns: + - x_center (float): x-coordinate of the center of mass. + - y_center (float): y-coordinate of the center of mass. + """ + mask = ~np.isnan(z) + if circle_mask is not None: + x0, y0 = circle_mask['x0'], circle_mask['y0'] + r_circle = circle_mask['r_circle'] + r = np.sqrt((x-x0)**2 + (y-y0)**2) + mask = np.logical_and(mask, rnp.nanpercentile(z[mask], q)) + + _x = x[mask] + _y = y[mask] + _z = z[mask] + + total_mass = np.nansum(_z) + x_center = np.nansum(_x * _z) / total_mass + y_center = np.nansum(_y * _z) / total_mass + return x_center, y_center + +def get_edgemap(mT, edge_avoidance=1*coords.DEG, edge_check='nan'): + """ + Generates an edge map for a given map, marking regions near the edges where data is potentially unreliable. + + Parameters: + - mT (enmap.ndmap): a map object + - edge_avoidance (float, optional): Size of the edge avoidance region, defaults to 1 degree. + - edge_check (str, optional): Method for checking edges. Should be one of {'nan', 'zero'}. + 'nan': Checks for NaN values at edges. + 'zero': Checks for zero values at edges. + Defaults to 'nan'. + + Returns: + - edge_map (enmap.ndmap): 2D boolean array representing the edge map, where True indicates regions near the edges. + """ + if edge_check not in ('nan', 'zero'): + raise ValueError('only `nan` or `zero` is supported') + + edge_map = enmap.zeros(mT.shape, mT.wcs) + edge_margin_size = int(edge_avoidance/np.mean(mT.pixshape())) + + for i, row in enumerate(mT): + if edge_check == 'nan': + nonzero_idxes = np.where(~np.isnan(row))[0] + elif edge_check == 'zero': + nonzero_idxes = np.where(row != 0)[0] + if len(nonzero_idxes>0): + edge_map[i, :nonzero_idxes[0] + edge_margin_size] = True + edge_map[i, nonzero_idxes[-1] - edge_margin_size:] = True + else: + edge_map[i, :] = True + + for j, col in enumerate(mT.T): + if edge_check == 'nan': + nonzero_idxes = np.where(~np.isnan(col))[0] + elif edge_check == 'zero': + nonzero_idxes = np.where(col != 0)[0] + if len(nonzero_idxes>0): + edge_map[:nonzero_idxes[0] + edge_margin_size, j] = True + edge_map[nonzero_idxes[-1] - edge_margin_size:, j] = True + else: + edge_map[:, j] = True + return edge_map + + + +def map_to_xieta(mT, edge_avoidance=1.0*coords.DEG, edge_check='nan', + r_tune_circle=1.0*coords.DEG, q_tune=50, + r_fit_circle=3.0*coords.DEG, beam_sigma_init=0.5*coords.DEG, ): + """ + Derive (xi,eta) coordinate of a peak from a given map and calculates the coefficient of determination (R^2) + as a measure of how well the data fits a Gaussian model around the peak. + + Parameters: + - mT (enmap.ndmap): a map object. + - edge_avoidance (float, optional): Size of the edge avoidance region, defaults to 1 degree. + - edge_check (str, optional): Method for checking edges. Should be one of {'nan', 'zero'}. Defaults to 'nan'. + - r_tune_circle (float, optional): Radius of the circle used for tuning the peak position, specified in radians. Defaults to 1 degree. + - q_tune (int, optional): Percentile threshold used for tuning the peak position. Defaults to 50. + - r_fit_circle (float, optional): Radius of the circle used for fitting the Gaussian model, specified in radians. Defaults to 3 degrees. + - beam_sigma_init (float, optional): Initial guess for the sigma parameter of the Gaussian beam, specified in radians. Defaults to 0.5 degree. + + Returns: + - xi_det (float): ξ coordinate of the detected peak. + - eta_det (float): η coordinate of the detected peak. + - R2_det (float): Coefficient of determination (R^2) indicating the goodness of fit of the data around the peak. + If no valid peak is detected or if fitting fails, returns NaN. + """ + if np.all(np.isnan(mT)): + xi_det, eta_det, R2_det = np.nan, np.nan, np.nan + + else: + xi_peak, eta_peak, ra_peak, dec_peak, peak_i, peak_j = detect_peak_xieta(mT) + if edge_avoidance > 0.: + edge_map = get_edgemap(mT, edge_avoidance=edge_avoidance, edge_check=edge_check) + edge_valid = not edge_map[peak_i, peak_j] + else: + edge_valid = True + + if edge_valid: + dec_flat, ra_flat = mT.posmap() + dec_flat, ra_flat = dec_flat.flatten(), ra_flat.flatten() + xi_flat, eta_flat = _radec2xieta(ra_flat, dec_flat) + + circle_mask = {'x0':xi_peak, 'y0':eta_peak, 'r_circle':r_tune_circle} + percentile_mask = {'q': q_tune} + xi_peak, eta_peak = get_center_of_mass(xi_flat, eta_flat, mT.flatten(), + circle_mask=circle_mask, percentile_mask=percentile_mask) + + # check R2(=coefficient of determination) + r = np.sqrt((xi_flat - xi_peak)**2 + (eta_flat - eta_peak)**2) + z = mT.flatten() + mask_fit = np.logical_and(~np.isnan(z), r R2_threshold + if np.all(~mask): + xi, eta, gamma, R2 = np.nan, np.nan, np.nan, np.nan + else: + if method == 'highest_R2': + idx = np.argmax(val['R2'][mask]) + xi, eta, gamma, R2 = val['xi'][mask][idx], val['eta'][mask][idx], val['gamma'][mask][idx], val['R2'][mask][idx] + elif method == 'mean': + xi, eta, gamma = np.mean(val['xi'][mask]), np.mean(val['eta'][mask]), np.mean(val['gamma'][mask]) + R2 = np.nan + elif method == 'median': + xi, eta, gamma = np.median(val['xi'][mask]), np.median(val['eta'][mask]), np.median(val['gamma'][mask]) + R2 = np.nan + else: + raise ValueError('Not supported method. Supported methods are `highest_R2`, `mean` or `median`') + focal_plane.rows.append((det, band, channel, R2, xi, eta, gamma)) + if save: + if output_dir is None: + output_dir = os.path.join(os.getcwd(), 'combined_pointing_results') + if not os.path.exists(output_dir): + os.makedirs(output_dir) + if save_name is None: + ctimes = np.atleast_1d([]) + wafer_slots = np.atleast_1d([]) + + for file in pointing_result_files: + filename = os.path.basename(file) + match = re.search('\d{10}', filename) + ctime = int(match.group(0) if match else None) + match = re.search('ws\d{1}', filename) + ws = match.group(0) + ctimes = np.append(ctimes, ctime) + wafer_slots = np.append(wafer_slots, ws) + ctimes = ctimes.astype('int') + wafer_slots = np.sort(np.unique(wafer_slots.astype('U3'))) + save_name = f'focal_plane_{ctimes.min()}_{ctimes.max()}_' + ''.join(wafer_slots) + '.hdf' + + write_dataset(focal_plane, os.path.join(output_dir, save_name), 'focal_plane', overwrite=True) + return focal_plane \ No newline at end of file diff --git a/sotodlib/site_pipeline/combine_focal_planes.py b/sotodlib/site_pipeline/combine_focal_planes.py new file mode 100644 index 000000000..b190074fa --- /dev/null +++ b/sotodlib/site_pipeline/combine_focal_planes.py @@ -0,0 +1 @@ +# combine multiple results \ No newline at end of file diff --git a/sotodlib/site_pipeline/make_mapbased_pointing.py b/sotodlib/site_pipeline/make_mapbased_pointing.py new file mode 100644 index 000000000..82feaf79e --- /dev/null +++ b/sotodlib/site_pipeline/make_mapbased_pointing.py @@ -0,0 +1,102 @@ +import os +import numpy as np +import yaml +import argparse + +from sotodlib import core +from sotodlib import coords +from sotodlib import tod_ops +from sotodlib.tod_ops.filters import high_pass_sine2, low_pass_sine2, fourier_filter +from sotodlib.coords import mapbased_pointing as mbp +from sotodlib.site_pipeline import update_pointing as up +from sotodlib.io.metadata import write_dataset + +from sotodlib.site_pipeline import util +logger = util.init_logger(__name__, 'make_mapbased_pointing: ') + +def filter_tod(tod, cutoff_high=0.01, cutoff_low=1.8): + if cutoff_low is not None: + tod.signal = fourier_filter(tod, filt_function=low_pass_sine2(cutoff=cutoff_low),) + if cutoff_high is not None: + tod.signal = fourier_filter(tod, filt_function=high_pass_sine2(cutoff=cutoff_high),) + return + +def tod_process(tod): + tod_ops.detrend_tod(tod) + tod_ops.apodize_cosine(tod, apodize_samps=2000) + filter_tod(tod) + tod.restrict('samps', (tod.samps.offset+2000, tod.samps.offset+tod.samps.count-2000)) + return + +def main(ctx_file, obs_id, wafer_slot, + sso_name, optics_config_fn, + map_dir, mapbased_result_dir, todbased_result_dir, + tune_by_tod=True, R2_threshold=0.3, restrict_dets=False): + + ctx = core.Context(ctx_file) + meta = ctx.get_meta(obs_id) + meta.restrict('dets', meta.dets.vals[meta.det_info.wafer_slot == wafer_slot]) + if restrict_dets: + meta.restrict('dets', meta.dets.vals[:100]) + logger.info('loading data') + tod = ctx.get_obs(meta) + logger.info('tod processing') + tod_process(tod) + + if not os.path.exists(map_dir): + logger.info(f'Make a directory: f{map_dir}') + os.makedirs(map_dir) + + logger.info(f'Making single detector maps') + map_hdf = os.path.join(map_dir, f'{obs_id}_{wafer_slot}.hdf') + mbp.make_wafer_centered_maps(tod, sso_name, optics_config_fn, map_hdf=map_hdf,) + + logger.info(f'Making map-based pointing results') + result_filename = f'focal_plane_{obs_id}_{wafer_slot}.hdf' + focal_plane_rset_mapbased = mbp.get_xieta_from_maps(map_hdf, + save=True, + output_dir=mapbased_result_dir, + filename=result_filename, + force_zero_roll=False, + edge_avoidance=1.0*coords.DEG) + + if tune_by_tod: + focal_plane = core.AxisManager(tod.dets) + focal_plane.wrap('xi', focal_plane_rset_mapbased['xi'], [(0, 'dets')]) + focal_plane.wrap('eta', focal_plane_rset_mapbased['eta'], [(0, 'dets')]) + focal_plane.wrap('gamma', focal_plane_rset_mapbased['gamma'], [(0, 'dets')]) + is_low_R2 = focal_plane_rset_mapbased['R2'] < R2_threshold + focal_plane.xi[is_low_R2] = np.nan + focal_plane.eta[is_low_R2] = np.nan + + tod.focal_plane = focal_plane + tod.flags.move(sso_name, None) + logger.info(f'Making tod-based pointing results') + focal_plane_rset_todbased = up.update_xieta(tod, sso_name, ds_factor=10, + save=True, + result_dir=todbased_result_dir, + filename=result_filename) + return + + + +def get_parser(): + parser = argparse.ArgumentParser(description="Process TOD data and update pointing") + parser.add_argument("ctx_file", type=str, help="Path to the context file") + parser.add_argument("obs_id", type=str, help="Observation ID") + parser.add_argument("wafer_slot", type=int, help="Wafer slot number") + parser.add_argument("sso_name", type=str, help="Name of Solar System Object (SSO)") + parser.add_argument("optics_config_fn", type=str, help="Path to optics configuration file") + parser.add_argument("map_dir", type=str, help="Directory to save map data") + parser.add_argument("mapbased_result_dir", type=str, help="Directory to save map-based result") + parser.add_argument("todbased_result_dir", type=str, help="Directory to save TOD-based result") + parser.add_argument("--tune_by_tod", action="store_true", help="Whether to tune by TOD data") + parser.add_argument("--R2_threshold", type=float, default=0.3, + help="Threshold for R2 value. If R2 of map-domain result is lower than the threshold,\ + the tod-fitting for that detector is skipped.") + parser.add_argument("--restrict_dets", action="store_true", + help="If specified, number of detectors are restricted to 100") + return parser + +if __name__ == '__main__': + util.main_launcher(main, get_parser) diff --git a/sotodlib/site_pipeline/update_pointing.py b/sotodlib/site_pipeline/update_pointing.py new file mode 100644 index 000000000..2fe72094b --- /dev/null +++ b/sotodlib/site_pipeline/update_pointing.py @@ -0,0 +1,196 @@ +import os +import numpy as np +import yaml +import h5py +import matplotlib.pyplot as plt +from tqdm import tqdm +import scipy +from scipy.optimize import minimize +from sotodlib.core import metadata +from sotodlib.io.metadata import write_dataset + +from sotodlib import core +from sotodlib import coords +from sotodlib import tod_ops +import so3g +from so3g.proj import quat +import sotodlib.coords.planets as planets + +from sotodlib.tod_ops import pca +from so3g.proj import Ranges, RangesMatrix +from pixell import enmap, enplot +from sotodlib.tod_ops.filters import high_pass_sine2, low_pass_sine2, fourier_filter + +from sotodlib.site_pipeline import util +logger = util.init_logger(__name__, 'update_pointing: ') + +def _gaussian2d(xi, eta, a, xi0, eta0, fwhm_xi, fwhm_eta, phi): + """Simulate a time stream with an Gaussian beam model + Args + ------ + xi, eta: cordinates in the detector's system + a: float + amplitude of the Gaussian beam model + xi0, eta0: float, float + center position of the Gaussian beam model + fwhm_xi, fwhm_eta, phi: float, float, float + fwhm along the xi, eta axis (rotated) + and the rotation angle (in radians) + + Ouput: + ------ + sim_data: 1d array of float + Time stream at sampling points given by xieta + """ + xi_rot = xi * np.cos(phi) - eta * np.sin(phi) + eta_rot = xi * np.sin(phi) + eta * np.cos(phi) + factor = 2 * np.sqrt(2 * np.log(2)) + xi_coef = -0.5 * (xi_rot - xi0) ** 2 / (fwhm_xi / factor) ** 2 + eta_coef = -0.5 * (eta_rot - eta0) ** 2 / (fwhm_eta / factor) ** 2 + sim_data = a * np.exp(xi_coef + eta_coef) + return sim_data + +def filter_tod(tod, cutoff_high=0.01, cutoff_low=1.8): + if cutoff_low is not None: + tod.signal = fourier_filter(tod, filt_function=low_pass_sine2(cutoff=cutoff_low),) + if cutoff_high is not None: + tod.signal = fourier_filter(tod, filt_function=high_pass_sine2(cutoff=cutoff_high),) + return + +def tod_process(tod): + tod_ops.detrend_tod(tod) + tod_ops.apodize_cosine(tod, apodize_samps=2000) + filter_tod(tod) + tod.restrict('samps', (tod.samps.offset+2000, tod.samps.offset+tod.samps.count-2000)) + return + +def update_xieta(tod, sso_name='moon', ds_factor=10, fwhm = 1.*coords.DEG, + save=False, result_dir=None, filename=None): + """ + Update xieta parameters for each detector by tod fitting of a point source observation + + Parameters: + - tod : an Axismanager object + - sso_name (str): Name of the Solar System Object (SSO). + - ds_factor (int): Downsampling factor for processing TOD. + - fwhm (float): Full width at half maximum of the Gaussian model. + - save (bool): Flag indicating whether to save the updated focal plane data. + - result_dir (str): Directory where the updated data will be saved. + - filename (str): Name of the file to save the updated data. + + Returns: + - focal_plane (ResultSet): ResultSet containing updated xieta parameters for each detector. + """ + mask_ds = slice(None, None, ds_factor) + + fp_isnan = np.isnan(tod.focal_plane.xi) + if np.any(fp_isnan): + tod.focal_plane.xi[fp_isnan] = 0. + tod.focal_plane.eta[fp_isnan] = 0. + tod.focal_plane.gamma[fp_isnan] = 0. + + coords.planets.compute_source_flags(tod, center_on=sso_name, max_pix=100000000, + wrap=sso_name, mask={'shape':'circle', 'xyr':[0,0,3]}) + + summed_flag = np.sum(tod.flags[sso_name].mask()[~fp_isnan], axis=0).astype('bool') + idx_hit = np.where(summed_flag)[0] + idx_first, idx_last = idx_hit[0], idx_hit[-1] + tod.restrict('samps', (tod.samps.offset+idx_first, tod.samps.offset+idx_last)) + csl = so3g.proj.CelestialSightLine.az_el(tod.timestamps[mask_ds], tod.boresight.az[mask_ds], + tod.boresight.el[mask_ds], weather="typical") + q_bore = csl.Q + + ts_ds = tod.timestamps[mask_ds] + sig_ds = tod.signal[:, mask_ds] + source_flags_ds = tod.flags[sso_name].mask()[:, mask_ds] + xieta_dict = {} + for di, det in enumerate(tqdm(tod.dets.vals)): + if fp_isnan[di]: + xieta_dict[det] = {'xi':np.nan, 'eta':np.nan, 'R2':np.nan} + else: + mask_di = source_flags_ds[di] + ts = ts_ds[mask_di] + + xieta_det = np.array([tod.focal_plane.xi[di], tod.focal_plane.eta[di]]) + q_det = so3g.proj.quat.rotation_xieta(xieta_det[0], xieta_det[1]) + d1_unix = np.median(ts) + planet = planets.SlowSource.for_named_source(sso_name, d1_unix * 1.) + ra0, dec0 = planet.pos(d1_unix) + q_obj = so3g.proj.quat.rotation_lonlat(ra0, dec0) + q_total = ~q_det * ~q_bore * q_obj + + xi_src, eta_src, _ = quat.decompose_xieta(q_total) + xieta_src = np.array([xi_src, eta_src]) + xieta_src = xieta_src[:, mask_di] + + + + sig = sig_ds[di][mask_di] + amp = np.ptp(sig) + def fit_func(xi0, eta0): + model_tod = _gaussian2d(xieta_src[0], xieta_src[1], amp, xi0, eta0, fwhm, fwhm, 0) + residual = sig - model_tod + return np.sum(residual ** 2) + + res = minimize(lambda x: fit_func(*x), [0, 0]) + R2 = 1 - res.fun/np.sum((sig - np.mean(sig))**2) + + if np.rad2deg(np.sqrt(np.sum(res.x**2))) > 1.0: + xieta_dict[det] = {'xi':np.nan, 'eta':np.nan, 'R2':np.nan} + else: + xieta_det += res.x + xieta_dict[det] = {'xi':xieta_det[0], 'eta':xieta_det[1], 'R2':R2} + + focal_plane = metadata.ResultSet(keys=['dets:readout_id', 'band', 'channel', 'R2', 'xi', 'eta', 'gamma']) + for det in tod.dets.vals: + band = int(det.split('_')[-2]) + channel = int(det.split('_')[-1]) + focal_plane.rows.append((det, band, channel, xieta_dict[det]['R2'], + xieta_dict[det]['xi'], xieta_dict[det]['eta'], 0.)) + if save: + assert result_dir is not None + assert filename is not None + if not os.path.exists(result_dir): + os.makedirs(result_dir) + write_dataset(focal_plane, + filename=os.path.join(result_dir, filename), + address='focal_plane', + overwrite=True) + return focal_plane + +def main(ctx_file, obs_id, wafer_slot, sso_name, result_dir, + ds_factor=10, fwhm = 1.*coords.DEG, restrict_dets=False): + ctx = core.Context(ctx_file) + meta = ctx.get_meta(obs_id) + meta.restrict('dets', meta.dets.vals[meta.det_info.wafer_slot == wafer_slot]) + if restrict_dets: + meta.restrict('dets', meta.dets.vals[:100]) + + logger.info('loading data') + tod = ctx.get_obs(meta) + logger.info('tod processing') + tod_process(tod) + + if not os.path.exists(result_dir): + logger.info(f'Make a directory: f{result_dir}') + os.makedirs(result_dir) + + result_filename = f'focal_plane_{obs_id}_{wafer_slot}.hdf' + focal_plane_rset = update_xieta(tod=tod, sso_name=sso_name, ds_factor=ds_factor, fwhm=fwhm, + save=True, result_dir=result_dir, filename=result_filename) + return + +def get_parser(): + parser = argparse.ArgumentParser(description="Description of the script.") + parser.add_argument("ctx_file", type=str, help="Path to the context file.") + parser.add_argument("obs_id", type=str, help="Observation ID.") + parser.add_argument("wafer_slot", type=int, help="Wafer slot number.") + parser.add_argument("sso_name", type=str, help="Name of the Solar System Object (SSO).") + parser.add_argument("result_dir", type=str, help="Directory to save the result.") + parser.add_argument("--ds_factor", type=int, default=10, help="Downsampling factor for TOD processing.") + parser.add_argument("--fwhm", type=float, default=1.0, help="Full width at half maximum of the Gaussian model.") + parser.add_argument("--restrict_dets", action="store_true", help="Flag to restrict the number of detectors.") + return parser + +if __name__ == '__main__': + util.main_launcher(main, get_parser) From 0af181a458224aca53ee095a7466101da75bcc9b Mon Sep 17 00:00:00 2001 From: Tomoki Terasaki Date: Tue, 19 Mar 2024 05:36:51 +0000 Subject: [PATCH 002/132] add combine_focal_planes.py --- sotodlib/coords/mapbased_pointing.py | 65 --------- .../site_pipeline/combine_focal_planes.py | 131 +++++++++++++++++- sotodlib/site_pipeline/update_pointing.py | 2 +- 3 files changed, 131 insertions(+), 67 deletions(-) diff --git a/sotodlib/coords/mapbased_pointing.py b/sotodlib/coords/mapbased_pointing.py index 276c4dd7a..a374a621e 100644 --- a/sotodlib/coords/mapbased_pointing.py +++ b/sotodlib/coords/mapbased_pointing.py @@ -478,68 +478,3 @@ def _add_xieta(xieta1, xieta2): xi_add, eta_add, _ = quat.decompose_xieta(q_add) return xi_add, eta_add -def combine_pointings(pointing_result_files, method='mean', R2_threshold=0.3, - save=False, output_dir=None, save_name=None): - combined_dict = {} - for file in pointing_result_files: - rset = read_dataset(file, 'focal_plane') - for row in rset[:]: - if row['dets:readout_id'] not in combined_dict.keys(): - combined_dict[row['dets:readout_id']] = {} - combined_dict[row['dets:readout_id']]['band'] = row['band'] - combined_dict[row['dets:readout_id']]['channel'] = row['channel'] - - combined_dict[row['dets:readout_id']]['R2'] = np.atleast_1d([]) - combined_dict[row['dets:readout_id']]['xi'] = np.atleast_1d([]) - combined_dict[row['dets:readout_id']]['eta'] = np.atleast_1d([]) - combined_dict[row['dets:readout_id']]['gamma'] = np.atleast_1d([]) - - combined_dict[row['dets:readout_id']]['R2'] = np.append(combined_dict[row['dets:readout_id']]['R2'], row['R2']) - combined_dict[row['dets:readout_id']]['xi'] = np.append(combined_dict[row['dets:readout_id']]['xi'], row['xi']) - combined_dict[row['dets:readout_id']]['eta'] = np.append(combined_dict[row['dets:readout_id']]['eta'], row['eta']) - combined_dict[row['dets:readout_id']]['gamma'] = np.append(combined_dict[row['dets:readout_id']]['gamma'], row['gamma']) - - focal_plane = metadata.ResultSet(keys=['dets:readout_id', 'band', 'channel', 'R2', 'xi', 'eta', 'gamma']) - for det, val in combined_dict.items(): - band = int(val['band']) - channel = int(val['channel']) - - mask = val['R2'] > R2_threshold - if np.all(~mask): - xi, eta, gamma, R2 = np.nan, np.nan, np.nan, np.nan - else: - if method == 'highest_R2': - idx = np.argmax(val['R2'][mask]) - xi, eta, gamma, R2 = val['xi'][mask][idx], val['eta'][mask][idx], val['gamma'][mask][idx], val['R2'][mask][idx] - elif method == 'mean': - xi, eta, gamma = np.mean(val['xi'][mask]), np.mean(val['eta'][mask]), np.mean(val['gamma'][mask]) - R2 = np.nan - elif method == 'median': - xi, eta, gamma = np.median(val['xi'][mask]), np.median(val['eta'][mask]), np.median(val['gamma'][mask]) - R2 = np.nan - else: - raise ValueError('Not supported method. Supported methods are `highest_R2`, `mean` or `median`') - focal_plane.rows.append((det, band, channel, R2, xi, eta, gamma)) - if save: - if output_dir is None: - output_dir = os.path.join(os.getcwd(), 'combined_pointing_results') - if not os.path.exists(output_dir): - os.makedirs(output_dir) - if save_name is None: - ctimes = np.atleast_1d([]) - wafer_slots = np.atleast_1d([]) - - for file in pointing_result_files: - filename = os.path.basename(file) - match = re.search('\d{10}', filename) - ctime = int(match.group(0) if match else None) - match = re.search('ws\d{1}', filename) - ws = match.group(0) - ctimes = np.append(ctimes, ctime) - wafer_slots = np.append(wafer_slots, ws) - ctimes = ctimes.astype('int') - wafer_slots = np.sort(np.unique(wafer_slots.astype('U3'))) - save_name = f'focal_plane_{ctimes.min()}_{ctimes.max()}_' + ''.join(wafer_slots) + '.hdf' - - write_dataset(focal_plane, os.path.join(output_dir, save_name), 'focal_plane', overwrite=True) - return focal_plane \ No newline at end of file diff --git a/sotodlib/site_pipeline/combine_focal_planes.py b/sotodlib/site_pipeline/combine_focal_planes.py index b190074fa..b8a1184a4 100644 --- a/sotodlib/site_pipeline/combine_focal_planes.py +++ b/sotodlib/site_pipeline/combine_focal_planes.py @@ -1 +1,130 @@ -# combine multiple results \ No newline at end of file +import os +import re +import glob +import numpy as np + +from sotodlib.core import metadata +from sotodlib.io.metadata import write_dataset, read_dataset + +from sotodlib.site_pipeline import util +logger = util.init_logger(__name__, 'combine_focal_planes: ') + +def combine_pointings(pointing_result_files, method='highest_R2', R2_threshold=0.3, + save=False, output_dir=None, save_name=None): + combined_dict = {} + for file in pointing_result_files: + rset = read_dataset(file, 'focal_plane') + for row in rset[:]: + if row['dets:readout_id'] not in combined_dict.keys(): + combined_dict[row['dets:readout_id']] = {} + combined_dict[row['dets:readout_id']]['band'] = row['band'] + combined_dict[row['dets:readout_id']]['channel'] = row['channel'] + + combined_dict[row['dets:readout_id']]['R2'] = np.atleast_1d([]) + combined_dict[row['dets:readout_id']]['xi'] = np.atleast_1d([]) + combined_dict[row['dets:readout_id']]['eta'] = np.atleast_1d([]) + combined_dict[row['dets:readout_id']]['gamma'] = np.atleast_1d([]) + + combined_dict[row['dets:readout_id']]['R2'] = np.append(combined_dict[row['dets:readout_id']]['R2'], row['R2']) + combined_dict[row['dets:readout_id']]['xi'] = np.append(combined_dict[row['dets:readout_id']]['xi'], row['xi']) + combined_dict[row['dets:readout_id']]['eta'] = np.append(combined_dict[row['dets:readout_id']]['eta'], row['eta']) + combined_dict[row['dets:readout_id']]['gamma'] = np.append(combined_dict[row['dets:readout_id']]['gamma'], row['gamma']) + + focal_plane = metadata.ResultSet(keys=['dets:readout_id', 'band', 'channel', 'R2', 'xi', 'eta', 'gamma']) + for det, val in combined_dict.items(): + band = int(val['band']) + channel = int(val['channel']) + + mask = val['R2'] > R2_threshold + if np.all(~mask): + xi, eta, gamma, R2 = np.nan, np.nan, np.nan, np.nan + else: + if method == 'highest_R2': + idx = np.argmax(val['R2'][mask]) + xi, eta, gamma, R2 = val['xi'][mask][idx], val['eta'][mask][idx], val['gamma'][mask][idx], val['R2'][mask][idx] + elif method == 'mean': + xi, eta, gamma = np.mean(val['xi'][mask]), np.mean(val['eta'][mask]), np.mean(val['gamma'][mask]) + R2 = np.nan + elif method == 'median': + xi, eta, gamma = np.median(val['xi'][mask]), np.median(val['eta'][mask]), np.median(val['gamma'][mask]) + R2 = np.nan + else: + raise ValueError('Not supported method. Supported methods are `highest_R2`, `mean` or `median`') + focal_plane.rows.append((det, band, channel, R2, xi, eta, gamma)) + if save: + if output_dir is None: + output_dir = os.path.join(os.getcwd(), 'combined_pointing_results') + if not os.path.exists(output_dir): + os.makedirs(output_dir) + if save_name is None: + ctimes = np.atleast_1d([]) + wafer_slots = np.atleast_1d([]) + for file in pointing_result_files: + filename = os.path.basename(file) + match = re.search('\d{10}', filename) + ctime = int(match.group(0) if match else None) + match = re.search('ws\d{1}', filename) + ws = match.group(0) + ctimes = np.append(ctimes, ctime) + wafer_slots = np.append(wafer_slots, ws) + ctimes = ctimes.astype('int') + wafer_slots = np.sort(np.unique(wafer_slots.astype('U3'))) + save_name = f'focal_plane_{ctimes.min()}_{ctimes.max()}_' + ''.join(wafer_slots) + '.hdf' + + write_dataset(focal_plane, os.path.join(output_dir, save_name), 'focal_plane', overwrite=True) + return focal_plane + +def combine_onewafer_results(pointing_dir, ws, output_dir, filename=None, + method='highest_R2', R2_threshold=0.3,): + pointing_result_files = glob.glob(os.path.join(pointing_dir, f'focal_plane*{ws}.hdf')) + if filename is None: + filename = f'focal_plane_{ws}_combined.hdf' + _ = combine_pointings(pointing_result_files, save=True, output_dir=output_dir, save_name=filename) + return + +def combine_allwafer_results(pointing_dir, output_dir, filename=None, + method='highest_R2', R2_threshold=0.3,): + pointing_result_files = glob.glob(os.path.join(pointing_dir, 'focal_plane*.hdf')) + if filename is None: + filename = f'focal_plane_combined.hdf' + _ = combine_pointings(pointing_result_files, save=True, output_dir=output_dir, save_name=filename) + return + +def make_detabase(focal_plane_file, db_file,): + scheme = metadata.ManifestScheme().add_data_field('dataset') + db = metadata.ManifestDb(scheme=scheme) + db.add_entry({'dataset': 'focal_plane'}, filename=focal_plane_file) + db.to_file(db_file) + return + +def main(pointing_dir, output_dir=None, method='highest_R2', R2_threshold=0.3,): + if output_dir is None: + output_dir = os.path.join(os.getcwd(), 'combined_results') + + logger.info('Combining each wafer resluts') + wafer_slots = [f'ws{i}' for i in range(7)] + for ws in wafer_slots: + combine_onewafer_results(pointing_dir=pointing_dir, ws=ws, + output_dir=output_dir, filename=None, + method=method, R2_threshold=R2_threshold) + + logger.info('Combining all wafer resluts') + combine_allwafer_results(pointing_dir=pointing_dir, output_dir=output_dir, filename='focal_plane_combined.hdf', + method=method, R2_threshold=R2_threshold) + + logger.info('Making a database') + focal_plane_file = os.path.join(output_dir, 'focal_plane_combined.hdf') + db_file = os.path.join(output_dir, 'focal_plane_combined.sqlite') + make_detabase(focal_plane_file, db_file,) + return + +def get_parser(): + parser = argparse.ArgumentParser(description="Combine multiple result of pointing.") + parser.add_argument('--pointing_dir', type=str, required=True, help='Directory containing pointing result files.') + parser.add_argument('--output_dir', type=str, default=None, help='Directory to save combined results. Default is "combined_results".') + parser.add_argument('--method', type=str, default='highest_R2', choices=['highest_R2', 'mean', 'median'], help='Combination method. Default is "highest_R2".') + parser.add_argument('--R2_threshold', type=float, default=0.3, help='Threshold for R2 value. Default is 0.3.') + return parser + +if __name__ == '__main__': + util.main_launcher(main, get_parser) diff --git a/sotodlib/site_pipeline/update_pointing.py b/sotodlib/site_pipeline/update_pointing.py index 2fe72094b..d3015d688 100644 --- a/sotodlib/site_pipeline/update_pointing.py +++ b/sotodlib/site_pipeline/update_pointing.py @@ -181,7 +181,7 @@ def main(ctx_file, obs_id, wafer_slot, sso_name, result_dir, return def get_parser(): - parser = argparse.ArgumentParser(description="Description of the script.") + parser = argparse.ArgumentParser(description="Get updated result of pointings with tod-based results") parser.add_argument("ctx_file", type=str, help="Path to the context file.") parser.add_argument("obs_id", type=str, help="Observation ID.") parser.add_argument("wafer_slot", type=int, help="Wafer slot number.") From 32e24af07371958171d1134f3bfb4170ef0d6edd Mon Sep 17 00:00:00 2001 From: Tomoki Terasaki Date: Tue, 19 Mar 2024 05:47:57 +0000 Subject: [PATCH 003/132] resolve wrong git operations --- sotodlib/coords/demod.py | 42 +---------------------------------- tests/test_demod_map.py | 48 ---------------------------------------- 2 files changed, 1 insertion(+), 89 deletions(-) diff --git a/sotodlib/coords/demod.py b/sotodlib/coords/demod.py index 709c34462..c6b9dcd66 100644 --- a/sotodlib/coords/demod.py +++ b/sotodlib/coords/demod.py @@ -140,44 +140,4 @@ def make_map(tod, output = {'map': mTQU, 'weighted_map': mTQU_weighted, 'weight': wTQU} - return output - -def from_map(tod, signal_map, cuts=None, flip_gamma=True, wrap=False, modulated=False): - """ - Generate simulated TOD with HWP from a given signal map. - - Args: - tod : an axisManager object - signal_map: pixell.enmap.ndmap containing (Tmap, Qmap, Umap) representing the signal. - cuts (RangesMatrix, optional): Cuts to apply to the data. Default is None. - flip_gamma (bool, optional): Whether to flip detector coordinate. If you use the HWP, keep it `True`. Default is True. - wrap (bool, optional): Whether to wrap the simulated data. Default is False. - modulated (bool, optional): If True, return modulated signal. If False, return the demodulated signal - (`dsT`, `demodQ`, and `demodU`). Default is False. - - Returns: - `modulate==False`: A tuple containing the TOD (np.array) of dsT, demodQ and demodU. - `modulate==True` : The modulated TOD (np.array) - - """ - Tmap, Qmap, Umap = signal_map - - P = coords.P.for_tod(tod=tod, geom=signal_map.geometry, cuts=cuts, - comps='QU', hwp=flip_gamma) - dsT_sim = P.from_map(Tmap, comps='T') - demodQ_sim = P.from_map(enmap.enmap([Qmap, Umap]), comps='QU') - demodU_sim = P.from_map(enmap.enmap([Umap, -Qmap]), comps='QU') - - if modulated is False: - if wrap: - tod.wrap('dsT', dsT_sim, [(0, 'dets'), (1, 'samps')]) - tod.wrap('demodQ', demodQ_sim, [(0, 'dets'), (1, 'samps')]) - tod.wrap('demodU', demodU_sim, [(0, 'dets'), (1, 'samps')]) - return dsT_sim, demodQ_sim, demodU_sim - else: - assert 'hwp_angle' in tod._fields - signal_sim = dsT_sim + demodQ_sim*np.cos(4*tod.hwp_angle) + demodU_sim*np.sin(4*tod.hwp_angle) - if wrap: - tod.wrap('signal', signal_sim, [(0, 'dets'), (1, 'samps')]) - return signal_sim - \ No newline at end of file + return output \ No newline at end of file diff --git a/tests/test_demod_map.py b/tests/test_demod_map.py index 525f35467..36d1b7853 100644 --- a/tests/test_demod_map.py +++ b/tests/test_demod_map.py @@ -130,52 +130,4 @@ def test_10_mod_demod(self): means = [m[s].mean() for m in m0] print(means) assert(abs(means[1] - Q_stream) < TOL) - assert(abs(means[2] - U_stream) < TOL) - - def test_from_map_demodulated(self): - """Test the coords.demod.from_map function of demodulated signal. - - """ - tod = quick_tod(10, 10000) - TOL = 0.0001 - - shape, wcs = enmap.fullsky_geometry(res=0.5*coords.DEG) - signal_map = enmap.zeros((3, *shape), wcs) - T_stream, Q_stream, U_stream = 1., 0.25, 0.01 - signal_map[0] += T_stream - signal_map[1] += Q_stream - signal_map[2] += U_stream - _ = coords.demod.from_map(tod, signal_map, modulated=False, wrap=True) - - results = coords.demod.make_map(tod) - m0 = results['map'] - s = m0[1] != 0 - means = [m[s].mean() for m in m0] - assert(abs(means[1] - Q_stream) < TOL) - assert(abs(means[2] - U_stream) < TOL) - - def test_from_map_modulated(self): - """Test the coords.demod.from_map function of modulated signal. - - """ - tod = quick_tod(10, 10000) - tod.move('signal', None) - TOL = .01 - - shape, wcs = enmap.fullsky_geometry(res=0.5*coords.DEG) - signal_map = enmap.zeros((3, *shape), wcs) - - T_stream, Q_stream, U_stream = 1., 0.25, 0.01 - signal_map[0] += T_stream - signal_map[1] += Q_stream - signal_map[2] += U_stream - - _ = coords.demod.from_map(tod, signal_map, modulated=True, wrap=True) - hwp.demod_tod(tod) - results = coords.demod.make_map(tod) - - m0 = results['map'] - s = m0[1] != 0. - means = [m[s].mean() for m in m0] - assert(abs(means[1] - Q_stream) < TOL) assert(abs(means[2] - U_stream) < TOL) \ No newline at end of file From 76db4c563d54c1ab9a7029bd6498f8ff9396bda1 Mon Sep 17 00:00:00 2001 From: Tomoki Terasaki Date: Tue, 30 Apr 2024 09:02:35 +0000 Subject: [PATCH 004/132] using a new preprocess style in map_based pointing reconstruction --- ...ased_pointing.py => map_based_pointing.py} | 0 .../site_pipeline/make_mapbased_pointing.py | 128 ++++++++++-------- 2 files changed, 68 insertions(+), 60 deletions(-) rename sotodlib/coords/{mapbased_pointing.py => map_based_pointing.py} (100%) diff --git a/sotodlib/coords/mapbased_pointing.py b/sotodlib/coords/map_based_pointing.py similarity index 100% rename from sotodlib/coords/mapbased_pointing.py rename to sotodlib/coords/map_based_pointing.py diff --git a/sotodlib/site_pipeline/make_mapbased_pointing.py b/sotodlib/site_pipeline/make_mapbased_pointing.py index 82feaf79e..c898e015f 100644 --- a/sotodlib/site_pipeline/make_mapbased_pointing.py +++ b/sotodlib/site_pipeline/make_mapbased_pointing.py @@ -7,95 +7,103 @@ from sotodlib import coords from sotodlib import tod_ops from sotodlib.tod_ops.filters import high_pass_sine2, low_pass_sine2, fourier_filter -from sotodlib.coords import mapbased_pointing as mbp +from sotodlib.coords import map_based_pointing as mbp from sotodlib.site_pipeline import update_pointing as up from sotodlib.io.metadata import write_dataset from sotodlib.site_pipeline import util -logger = util.init_logger(__name__, 'make_mapbased_pointing: ') - -def filter_tod(tod, cutoff_high=0.01, cutoff_low=1.8): - if cutoff_low is not None: - tod.signal = fourier_filter(tod, filt_function=low_pass_sine2(cutoff=cutoff_low),) - if cutoff_high is not None: - tod.signal = fourier_filter(tod, filt_function=high_pass_sine2(cutoff=cutoff_high),) - return - -def tod_process(tod): - tod_ops.detrend_tod(tod) - tod_ops.apodize_cosine(tod, apodize_samps=2000) - filter_tod(tod) - tod.restrict('samps', (tod.samps.offset+2000, tod.samps.offset+tod.samps.count-2000)) - return +from sotodlib.preprocess import Pipeline +logger = util.init_logger(__name__, 'make_map_based_pointing: ') + +def main(configs, obs_id, wafer_slot, + sso_name=None, optics_config_fn=None, + single_det_maps_dir=None, map_based_result_dir=None, tod_based_result_dir=None, + tune_by_tod=None, restrict_dets_for_debug=False): + + if type(configs) == str: + configs = yaml.safe_load(open(configs, "r")) + + # Derive parameters from config file + if optics_config_fn is None: + optics_config_fn = configs.get('optics_config_fn') + if single_det_maps_dir is None: + single_det_maps_dir = configs.get('single_det_maps_dir') + if map_based_result_dir is None: + map_based_result_dir = configs.get('map_based_result_dir') + if tod_based_result_dir is None: + tod_based_result_dir = configs.get('tod_based_result_dir') -def main(ctx_file, obs_id, wafer_slot, - sso_name, optics_config_fn, - map_dir, mapbased_result_dir, todbased_result_dir, - tune_by_tod=True, R2_threshold=0.3, restrict_dets=False): + res_deg = configs.get('res_deg') + edge_avoidance_deg = configs.get('edge_avoidance_deg') + tune_by_tod = configs.get('tune_by_tod') + R2_threshold = configs.get('R2_threshold') + ds_factor = configs.get('ds_factor') - ctx = core.Context(ctx_file) - meta = ctx.get_meta(obs_id) - meta.restrict('dets', meta.dets.vals[meta.det_info.wafer_slot == wafer_slot]) - if restrict_dets: - meta.restrict('dets', meta.dets.vals[:100]) + + ctx = core.Context(configs.get('context_file')) + # If sso_name is not specified, get sso name from observation tags + obs_tags = ctx.obsdb.get(obs_id, tags=True)['tags'] + if sso_name is None: + if 'moon' in obs_tags: + sso_name = 'moon' + elif 'jupiter' in obs_tags: + sso_name = 'jupiter' + else: + raise ValueError('sso_name is not specified') + + # Load data logger.info('loading data') + meta = ctx.get_meta(obs_id, dets={'wafer_slot': wafer_slot}) + if restrict_dets_for_debug is not False: + meta.restrict('dets', meta.dets.vals[:restrict_dets_for_debug]) tod = ctx.get_obs(meta) - logger.info('tod processing') - tod_process(tod) - if not os.path.exists(map_dir): - logger.info(f'Make a directory: f{map_dir}') - os.makedirs(map_dir) + # tod processing + logger.info('tod processing') + pipe = Pipeline(configs["process_pipe"], logger=logger) + proc_aman, success = pipe.run(tod) - logger.info(f'Making single detector maps') - map_hdf = os.path.join(map_dir, f'{obs_id}_{wafer_slot}.hdf') - mbp.make_wafer_centered_maps(tod, sso_name, optics_config_fn, map_hdf=map_hdf,) + # make single detecctor maps + logger.info(f'Making single detector maps') + os.makedirs(single_det_maps_dir, exist_ok=True) + map_hdf = os.path.join(single_det_maps_dir, f'{obs_id}_{wafer_slot}.hdf') + mbp.make_wafer_centered_maps(tod, sso_name, optics_config_fn, map_hdf=map_hdf, res=res_deg*coords.DEG) + # reconstruct pointing from single detector maps logger.info(f'Making map-based pointing results') result_filename = f'focal_plane_{obs_id}_{wafer_slot}.hdf' - focal_plane_rset_mapbased = mbp.get_xieta_from_maps(map_hdf, - save=True, - output_dir=mapbased_result_dir, + focal_plane_rset_map_based = mbp.get_xieta_from_maps(map_hdf, save=True, + output_dir=map_based_result_dir, filename=result_filename, force_zero_roll=False, - edge_avoidance=1.0*coords.DEG) + edge_avoidance = edge_avoidance_deg*coords.DEG) if tune_by_tod: focal_plane = core.AxisManager(tod.dets) - focal_plane.wrap('xi', focal_plane_rset_mapbased['xi'], [(0, 'dets')]) - focal_plane.wrap('eta', focal_plane_rset_mapbased['eta'], [(0, 'dets')]) - focal_plane.wrap('gamma', focal_plane_rset_mapbased['gamma'], [(0, 'dets')]) - is_low_R2 = focal_plane_rset_mapbased['R2'] < R2_threshold + focal_plane.wrap('xi', focal_plane_rset_map_based['xi'], [(0, 'dets')]) + focal_plane.wrap('eta', focal_plane_rset_map_based['eta'], [(0, 'dets')]) + focal_plane.wrap('gamma', focal_plane_rset_map_based['gamma'], [(0, 'dets')]) + is_low_R2 = focal_plane_rset_map_based['R2'] < R2_threshold focal_plane.xi[is_low_R2] = np.nan focal_plane.eta[is_low_R2] = np.nan tod.focal_plane = focal_plane tod.flags.move(sso_name, None) logger.info(f'Making tod-based pointing results') - focal_plane_rset_todbased = up.update_xieta(tod, sso_name, ds_factor=10, - save=True, - result_dir=todbased_result_dir, - filename=result_filename) + focal_plane_rset_tod_based = up.update_xieta(tod, sso_name, ds_factor=ds_factor, save=True, + result_dir=tod_based_result_dir, filename=result_filename) return - - def get_parser(): parser = argparse.ArgumentParser(description="Process TOD data and update pointing") - parser.add_argument("ctx_file", type=str, help="Path to the context file") - parser.add_argument("obs_id", type=str, help="Observation ID") + parser.add_argument("configs", type=str, help="Path to the configuration file") + parser.add_argument("obs_id", type=int, help="Observation ID") parser.add_argument("wafer_slot", type=int, help="Wafer slot number") - parser.add_argument("sso_name", type=str, help="Name of Solar System Object (SSO)") - parser.add_argument("optics_config_fn", type=str, help="Path to optics configuration file") - parser.add_argument("map_dir", type=str, help="Directory to save map data") - parser.add_argument("mapbased_result_dir", type=str, help="Directory to save map-based result") - parser.add_argument("todbased_result_dir", type=str, help="Directory to save TOD-based result") - parser.add_argument("--tune_by_tod", action="store_true", help="Whether to tune by TOD data") - parser.add_argument("--R2_threshold", type=float, default=0.3, - help="Threshold for R2 value. If R2 of map-domain result is lower than the threshold,\ - the tod-fitting for that detector is skipped.") - parser.add_argument("--restrict_dets", action="store_true", - help="If specified, number of detectors are restricted to 100") + parser.add_argument("--sso_name", type=str, default=None, help="Name of solar system object (e.g., 'moon', 'jupiter')") + parser.add_argument("--optics_config_fn", type=str, default=None, help="Path to optics configuration file") + parser.add_argument("--single_det_maps_dir", type=str, default=None, help="Directory to save single detector maps") + parser.add_argument("--map_based_result_dir", type=str, default=None, help="Directory to save map-based pointing results") + parser.add_argument("--tod_based_result_dir", type=str, default=None, help="Directory to save TOD-based pointing results") return parser if __name__ == '__main__': From 20b522cf00b1eec129600d17c604acdeff78c713 Mon Sep 17 00:00:00 2001 From: Tomoki Terasaki Date: Tue, 30 Apr 2024 12:23:26 +0000 Subject: [PATCH 005/132] added except method in flags.reduce --- sotodlib/core/flagman.py | 4 +++- sotodlib/preprocess/processes.py | 7 ++++++- sotodlib/site_pipeline/update_pointing.py | 2 -- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/sotodlib/core/flagman.py b/sotodlib/core/flagman.py index 4a513278b..3a64faf50 100644 --- a/sotodlib/core/flagman.py +++ b/sotodlib/core/flagman.py @@ -172,7 +172,7 @@ def reduce(self, flags=None, method='union', wrap=False, new_flag=None, flags: List of flags to collapse together. Uses their names. If flags is None then all flags are reduced method: How to collapse the data. Accepts 'union','intersect', - or function. + 'except', or function. wrap: if True, add reduced flag to self new_flag: name of new flag, required if wrap is True remove_reduced: if True, remove all reduced flags from self @@ -198,6 +198,8 @@ def reduce(self, flags=None, method='union', wrap=False, new_flag=None, op = lambda x, y: x+y elif method == 'intersect': op = lambda x, y: x*y + elif method == 'except': + op = lambda x, y: x*~y else: op = method out = reduce(op, to_reduce) diff --git a/sotodlib/preprocess/processes.py b/sotodlib/preprocess/processes.py index 1e1293344..baae3cae6 100644 --- a/sotodlib/preprocess/processes.py +++ b/sotodlib/preprocess/processes.py @@ -782,7 +782,11 @@ def plot(self, aman, proc_aman, filename): for sso in proc_aman.sso_footprint._assignments.keys(): planet_aman = proc_aman.sso_footprint[sso] plot_sso_footprint(aman, planet_aman, sso, filename=filename.replace('{name}', f'{sso}_sso_footprint'), **self.plot_cfgs) - + +class ComputeSourceFlags(_Preprocess): + name = 'compute_source_flags' + def process(self, aman, proc_aman): + planets.compute_source_flags(aman, **self.process_cfgs) class FourierFilter(_Preprocess): """ @@ -882,3 +886,4 @@ def save(self, proc_aman, rc_aman): _Preprocess.register(SubPolyf) _Preprocess.register(DetBiasFlags) _Preprocess.register(SSOFootprint) +_Preprocess.register(ComputeSourceFlags) diff --git a/sotodlib/site_pipeline/update_pointing.py b/sotodlib/site_pipeline/update_pointing.py index d3015d688..a1cfade81 100644 --- a/sotodlib/site_pipeline/update_pointing.py +++ b/sotodlib/site_pipeline/update_pointing.py @@ -122,8 +122,6 @@ def update_xieta(tod, sso_name='moon', ds_factor=10, fwhm = 1.*coords.DEG, xi_src, eta_src, _ = quat.decompose_xieta(q_total) xieta_src = np.array([xi_src, eta_src]) xieta_src = xieta_src[:, mask_di] - - sig = sig_ds[di][mask_di] amp = np.ptp(sig) From 740f1e30d804936731b1bb32af151fa7b8f9d17b Mon Sep 17 00:00:00 2001 From: Tomoki Terasaki Date: Tue, 30 Apr 2024 12:50:03 +0000 Subject: [PATCH 006/132] added ReduceFlags function in preprocessing --- sotodlib/preprocess/processes.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/sotodlib/preprocess/processes.py b/sotodlib/preprocess/processes.py index baae3cae6..14adb046f 100644 --- a/sotodlib/preprocess/processes.py +++ b/sotodlib/preprocess/processes.py @@ -783,6 +783,11 @@ def plot(self, aman, proc_aman, filename): planet_aman = proc_aman.sso_footprint[sso] plot_sso_footprint(aman, planet_aman, sso, filename=filename.replace('{name}', f'{sso}_sso_footprint'), **self.plot_cfgs) +class ReduceFlags(_Preprocess): + name = 'reduce_flags' + def process(self, aman, proc_aman): + aman.flags.reduce(**self.process_cfgs) + class ComputeSourceFlags(_Preprocess): name = 'compute_source_flags' def process(self, aman, proc_aman): @@ -887,3 +892,4 @@ def save(self, proc_aman, rc_aman): _Preprocess.register(DetBiasFlags) _Preprocess.register(SSOFootprint) _Preprocess.register(ComputeSourceFlags) +_Preprocess.register(ReduceFlags) From 7b403a78b50a681241dd9a1d2cbacfbc328a40c5 Mon Sep 17 00:00:00 2001 From: Tomoki Terasaki Date: Thu, 2 May 2024 12:44:39 +0000 Subject: [PATCH 007/132] new fitting code --- sotodlib/coords/map_based_pointing.py | 47 ++-- .../site_pipeline/make_mapbased_pointing.py | 37 ++- sotodlib/site_pipeline/update_pointing.py | 224 +++++++++++++----- 3 files changed, 220 insertions(+), 88 deletions(-) diff --git a/sotodlib/coords/map_based_pointing.py b/sotodlib/coords/map_based_pointing.py index a374a621e..294a350a2 100644 --- a/sotodlib/coords/map_based_pointing.py +++ b/sotodlib/coords/map_based_pointing.py @@ -108,8 +108,7 @@ def get_wafer_xieta(wafer_slot, optics_config_fn, xieta_bs_offset=(0., 0.), lon = fp_to_sky(wafer_r) q1 = quat.rotation_iso(lon, 0) - - q2 = quat.rotation_iso(0, 0, np.pi/2 - wafer_theta - roll_bs_offset) + q2 = quat.rotation_iso(0, 0, np.pi/2 - wafer_theta + roll_bs_offset) q3 = quat.rotation_xieta(xieta_bs_offset[0], xieta_bs_offset[1]) q = q3 * q2 * q1 @@ -124,36 +123,39 @@ def get_wafer_xieta(wafer_slot, optics_config_fn, xieta_bs_offset=(0., 0.), focal_plane.wrap('eta', np.ones(tod.dets.count, dtype='float32') * eta_wafer, [(0, 'dets')]) focal_plane.wrap('gamma', np.zeros(tod.dets.count, dtype='float32'), [(0, 'dets')]) tod.wrap('focal_plane', focal_plane) + + # set boresight roll to zero + tod.boresight.wrap('roll_original', tod.boresight.roll, [(0, 'samps')]) tod.boresight.roll *= 0. + return xi_wafer, eta_wafer -def make_wafer_centered_maps(tod, planet, optics_config_fn, map_hdf, +def make_wafer_centered_maps(tod, sso_name, optics_config_fn, map_hdf, xieta_bs_offset=(0., 0.), roll_bs_offset=None, - signal='signal', wcs_kernel=None, res=0.3*coords.DEG, cuts=None,): + signal='signal', wafer_mask_deg=8., res_deg=0.3, cuts=None,): """ Generate boresight-centered maps from Time-Ordered Data (TOD) for each individual detector. Parameters: tod : an axismanager object - planet (str): Name of the planet for which the trajectory is calculated. + sso_name (str): Name of the planet for which the trajectory is calculated. optics_config_fn (str): File name containing the optics configuration. map_hdf (str): Path to the HDF5 file where the maps will be saved. xieta_bs_offset (tuple): Offset in xieta coordinates for the boresight, default is (0., 0.). roll_bs_offset (float): Offset in roll angle for the boresight, default is None. signal (str): Name of the signal to be used, default is 'signal'. wcs_kernel (ndarray): WCS kernel for mapping, default is None. - res (float): Resolution of the map in degrees, default is 0.3 degrees. + res_deg (float): Resolution of the map in degrees, default is 0.3 degrees. cuts (tuple): Cuts to be applied to the map, default is None. Returns: None """ - if wcs_kernel is None: - wcs_kernel = coords.get_wcs_kernel('car', 0, 0, res) + - q_planet = get_planet_trajectry(tod, planet) + q_planet = get_planet_trajectry(tod, sso_name) q_bs = quat.rotation_lonlat(tod.boresight.az, tod.boresight.el) if roll_bs_offset is None: @@ -170,25 +172,26 @@ def make_wafer_centered_maps(tod, planet, optics_config_fn, map_hdf, optics_config_fn=optics_config_fn, wrap_to_tod=True) - coords.planets.compute_source_flags(tod, center_on=planet, max_pix=100000000, - wrap=planet, mask={'shape':'circle', 'xyr':[0,0,8]}) + coords.planets.compute_source_flags(tod, center_on=sso_name, max_pix=100000000, + wrap='source', mask={'shape':'circle', 'xyr':[0., 0., wafer_mask_deg]}) - q_wafer = quat.rotation_xieta(xi_wafer, eta_wafer) - sight = get_wafer_centered_sight(tod, planet, q_planet, q_bs, q_wafer) - - + + q_wafer = quat.rotation_xieta(xi_wafer, eta_wafer) + sight = get_wafer_centered_sight(tod, sso_name, q_planet, q_bs, q_wafer) xi0 = tod.focal_plane.xi[0] eta0 = tod.focal_plane.eta[0] - xi_bs_offset, eta_bs_offset = xieta_bs_offset - + xi_bs_offset, eta_bs_offset = xieta_bs_offset tod.focal_plane.xi *= 0. tod.focal_plane.eta *= 0. tod.boresight.roll *= 0. + + box = np.deg2rad([[-wafer_mask_deg, -wafer_mask_deg], [wafer_mask_deg, wafer_mask_deg]]) + geom = enmap.geometry(pos=box, res=res_deg*coords.DEG) if cuts is None: - cuts = ~tod.flags[planet] - P = coords.P.for_tod(tod=tod, wcs_kernel=wcs_kernel, comps='T', cuts=cuts, sight=sight, threads=False) + cuts = ~tod.flags['source'] + P = coords.P.for_tod(tod=tod, geom=geom, comps='T', cuts=cuts, sight=sight, threads=False) for di, det in enumerate(tqdm(tod.dets.vals)): det_weights = np.zeros(tod.dets.count, dtype='float32') det_weights[di] = 1. @@ -337,8 +340,8 @@ def map_to_xieta(mT, edge_avoidance=1.0*coords.DEG, edge_check='nan', - beam_sigma_init (float, optional): Initial guess for the sigma parameter of the Gaussian beam, specified in radians. Defaults to 0.5 degree. Returns: - - xi_det (float): ξ coordinate of the detected peak. - - eta_det (float): η coordinate of the detected peak. + - xi_det (float): xi coordinate of the detected peak. + - eta_det (float): eta coordinate of the detected peak. - R2_det (float): Coefficient of determination (R^2) indicating the goodness of fit of the data around the peak. If no valid peak is detected or if fitting fails, returns NaN. """ @@ -432,7 +435,7 @@ def get_xieta_from_maps(map_hdf_file, q1 = quat.rotation_xieta(xi, eta) q2 = quat.rotation_xieta(xi_bs_offset, eta_bs_offset) - q3 = quat.rotation_iso(0, 0, roll_bs_offset) + q3 = quat.rotation_iso(0, 0, -roll_bs_offset) # q = q3 * ~q2 * q1 xieta = quat.decompose_xieta(q) xi, eta = xieta[0], xieta[1] diff --git a/sotodlib/site_pipeline/make_mapbased_pointing.py b/sotodlib/site_pipeline/make_mapbased_pointing.py index c898e015f..e566dbf21 100644 --- a/sotodlib/site_pipeline/make_mapbased_pointing.py +++ b/sotodlib/site_pipeline/make_mapbased_pointing.py @@ -33,8 +33,12 @@ def main(configs, obs_id, wafer_slot, if tod_based_result_dir is None: tod_based_result_dir = configs.get('tod_based_result_dir') - res_deg = configs.get('res_deg') - edge_avoidance_deg = configs.get('edge_avoidance_deg') + xieta_bs_offset = configs.get('xieta_bs_offset', [0., 0.]) + wafer_mask_deg = configs.get('wafer_mask_deg', 8.) + res_deg = configs.get('res_deg', 0.3) + edge_avoidance_deg = configs.get('edge_avoidance_deg', 0.3) + save_force_zero_roll = configs.get('save_force_zero_roll', True) + tune_by_tod = configs.get('tune_by_tod') R2_threshold = configs.get('R2_threshold') ds_factor = configs.get('ds_factor') @@ -67,12 +71,14 @@ def main(configs, obs_id, wafer_slot, logger.info(f'Making single detector maps') os.makedirs(single_det_maps_dir, exist_ok=True) map_hdf = os.path.join(single_det_maps_dir, f'{obs_id}_{wafer_slot}.hdf') - mbp.make_wafer_centered_maps(tod, sso_name, optics_config_fn, map_hdf=map_hdf, res=res_deg*coords.DEG) + mbp.make_wafer_centered_maps(tod, sso_name, optics_config_fn, map_hdf=map_hdf, + xieta_bs_offset=xieta_bs_offset, + wafer_mask_deg=wafer_mask_deg, res_deg=res_deg) # reconstruct pointing from single detector maps - logger.info(f'Making map-based pointing results') + logger.info(f'Saving map-based pointing results') result_filename = f'focal_plane_{obs_id}_{wafer_slot}.hdf' - focal_plane_rset_map_based = mbp.get_xieta_from_maps(map_hdf, save=True, + fp_rset_map_based = mbp.get_xieta_from_maps(map_hdf, save=True, output_dir=map_based_result_dir, filename=result_filename, force_zero_roll=False, @@ -80,18 +86,27 @@ def main(configs, obs_id, wafer_slot, if tune_by_tod: focal_plane = core.AxisManager(tod.dets) - focal_plane.wrap('xi', focal_plane_rset_map_based['xi'], [(0, 'dets')]) - focal_plane.wrap('eta', focal_plane_rset_map_based['eta'], [(0, 'dets')]) - focal_plane.wrap('gamma', focal_plane_rset_map_based['gamma'], [(0, 'dets')]) - is_low_R2 = focal_plane_rset_map_based['R2'] < R2_threshold + focal_plane.wrap('xi', fp_rset_map_based['xi'], [(0, 'dets')]) + focal_plane.wrap('eta', fp_rset_map_based['eta'], [(0, 'dets')]) + focal_plane.wrap('gamma', fp_rset_map_based['gamma'], [(0, 'dets')]) + is_low_R2 = fp_rset_map_based['R2'] < R2_threshold focal_plane.xi[is_low_R2] = np.nan focal_plane.eta[is_low_R2] = np.nan tod.focal_plane = focal_plane tod.flags.move(sso_name, None) logger.info(f'Making tod-based pointing results') - focal_plane_rset_tod_based = up.update_xieta(tod, sso_name, ds_factor=ds_factor, save=True, - result_dir=tod_based_result_dir, filename=result_filename) + fp_rset_tod_based = up.update_xieta(tod, sso_name, ds_factor=ds_factor, save=True, + result_dir=tod_based_result_dir, filename=result_filename) + + if save_force_zero_roll: + logger.info(f'Saving map-based pointing results (force-zero-roll)') + output_dir = map_based_result_dir + '_force_zero_roll' + fp_rset_map_based_force_zero_roll = mbp.get_xieta_from_maps(map_hdf, save=True, + output_dir=output_dir, + filename=result_filename, + force_zero_roll=True, + edge_avoidance = edge_avoidance_deg*coords.DEG) return def get_parser(): diff --git a/sotodlib/site_pipeline/update_pointing.py b/sotodlib/site_pipeline/update_pointing.py index a1cfade81..65472819c 100644 --- a/sotodlib/site_pipeline/update_pointing.py +++ b/sotodlib/site_pipeline/update_pointing.py @@ -5,9 +5,9 @@ import matplotlib.pyplot as plt from tqdm import tqdm import scipy -from scipy.optimize import minimize +from scipy.optimize import curve_fit from sotodlib.core import metadata -from sotodlib.io.metadata import write_dataset +from sotodlib.io.metadata import read_dataset, write_dataset from sotodlib import core from sotodlib import coords @@ -24,48 +24,110 @@ from sotodlib.site_pipeline import util logger = util.init_logger(__name__, 'update_pointing: ') -def _gaussian2d(xi, eta, a, xi0, eta0, fwhm_xi, fwhm_eta, phi): +def _gaussian2d(xieta, xi0, eta0, fwhm_xi, fwhm_eta, phi, a): """Simulate a time stream with an Gaussian beam model Args ------ xi, eta: cordinates in the detector's system + xi0, eta0: float, float + center position of the Gaussian beam model + fwhm_xi, fwhm_eta, phi: float, float, float + fwhm along the xi, eta axis (rotated) + and the rotation angle (in radians) a: float amplitude of the Gaussian beam model + + Ouput: + ------ + sim_data: 1d array of float + Time stream at sampling points given by xieta + """ + xi, eta = xieta + xi_rot = xi * np.cos(phi) - eta * np.sin(phi) + eta_rot = xi * np.sin(phi) + eta * np.cos(phi) + factor = 2 * np.sqrt(2 * np.log(2)) + xi_coef = -0.5 * (xi_rot - xi0) ** 2 / (fwhm_xi / factor) ** 2 + eta_coef = -0.5 * (eta_rot - eta0) ** 2 / (fwhm_eta / factor) ** 2 + sim_data = a * np.exp(xi_coef + eta_coef) + return sim_data + +def _gaussian2d_nonlin(xieta, xi0, eta0, fwhm_xi, fwhm_eta, phi, a, b2,): + """Simulate a time stream with an Gaussian beam model with non-linear response + Args + ------ + xi, eta: cordinates in the detector's system xi0, eta0: float, float center position of the Gaussian beam model fwhm_xi, fwhm_eta, phi: float, float, float fwhm along the xi, eta axis (rotated) and the rotation angle (in radians) + a: float + amplitude of the Gaussian beam model + b2: float + coefficient of 2nd-order term Ouput: ------ sim_data: 1d array of float Time stream at sampling points given by xieta """ + xi, eta = xieta xi_rot = xi * np.cos(phi) - eta * np.sin(phi) eta_rot = xi * np.sin(phi) + eta * np.cos(phi) factor = 2 * np.sqrt(2 * np.log(2)) xi_coef = -0.5 * (xi_rot - xi0) ** 2 / (fwhm_xi / factor) ** 2 eta_coef = -0.5 * (eta_rot - eta0) ** 2 / (fwhm_eta / factor) ** 2 - sim_data = a * np.exp(xi_coef + eta_coef) + _y = np.exp(xi_coef + eta_coef) + sim_data = a * (_y + b2*_y**2) return sim_data -def filter_tod(tod, cutoff_high=0.01, cutoff_low=1.8): - if cutoff_low is not None: - tod.signal = fourier_filter(tod, filt_function=low_pass_sine2(cutoff=cutoff_low),) - if cutoff_high is not None: - tod.signal = fourier_filter(tod, filt_function=high_pass_sine2(cutoff=cutoff_high),) - return +# def filter_tod(tod, cutoff_high=0.01, cutoff_low=1.8): +# if cutoff_low is not None: +# tod.signal = fourier_filter(tod, filt_function=low_pass_sine2(cutoff=cutoff_low),) +# if cutoff_high is not None: +# tod.signal = fourier_filter(tod, filt_function=high_pass_sine2(cutoff=cutoff_high),) +# return -def tod_process(tod): - tod_ops.detrend_tod(tod) - tod_ops.apodize_cosine(tod, apodize_samps=2000) - filter_tod(tod) - tod.restrict('samps', (tod.samps.offset+2000, tod.samps.offset+tod.samps.count-2000)) - return +# def tod_process(tod): +# tod_ops.detrend_tod(tod) +# tod_ops.apodize_cosine(tod, apodize_samps=2000) +# filter_tod(tod) +# tod.restrict('samps', (tod.samps.offset+2000, tod.samps.offset+tod.samps.count-2000)) +# return + +def wrap_fp_from_hdf(tod, fp_hdf_file, data_set='focal_plane'): + fp_rset = read_dataset(fp_hdf_file, data_set) + tod.restrict('dets', tod.dets.vals[np.in1d(tod.dets.vals, fp_rset['dets:readout_id'])]) + focal_plane = core.AxisManager(tod.dets) + focal_plane.wrap_new('xi', shape=('dets', )) + focal_plane.wrap_new('eta', shape=('dets', )) + focal_plane.wrap_new('gamma', shape=('dets', )) -def update_xieta(tod, sso_name='moon', ds_factor=10, fwhm = 1.*coords.DEG, - save=False, result_dir=None, filename=None): + for di, det in enumerate(tod.dets.vals): + di_rset = np.where(fp_rset['dets:readout_id'] == det)[0][0] + focal_plane.xi[di] = fp_rset['xi'][di_rset] + focal_plane.eta[di] = fp_rset['eta'][di_rset] + focal_plane.gamma[di] = fp_rset['gamma'][di_rset] + + if 'focal_plane' in tod._fields.keys(): + tod.move('focal_plane', None) + tod.wrap('focal_plane', focal_plane) + return + + +def update_xieta(tod, + sso_name='moon', + fp_hdf_file=None, + input_force_zero_roll=False, + pipe=None, + ds_factor=10, + mask_deg=3, + fit_func_name = '_gaussian2d_nonlin', + fwhm_init_deg = 0.5, + error_estimation_method='force_one_redchi2', # rms_from_data + flag_name_rms_calc = 'source', + flag_rms_calc_exclusive = True, + save=False, result_dir=None, filename=None): """ Update xieta parameters for each detector by tod fitting of a point source observation @@ -81,70 +143,122 @@ def update_xieta(tod, sso_name='moon', ds_factor=10, fwhm = 1.*coords.DEG, Returns: - focal_plane (ResultSet): ResultSet containing updated xieta parameters for each detector. """ - mask_ds = slice(None, None, ds_factor) + # if focal_plane result is specified, use the information as a prior + if fp_hdf_file is not None: + wrap_fp_from_hdf(tod, fp_hdf_file) + + # set dets without focal_plane info to have (xi, eta, gamma) = (0, 0, 0), just to avoid error + xieta_isnan = (np.isnan(tod.focal_plane.xi)) | (np.isnan(tod.focal_plane.eta)) + gamma_isnan = np.isnan(tod.focal_plane.gamma) + tod.focal_plane.xi[xieta_isnan] = 0. + tod.focal_plane.eta[xieta_isnan] = 0. + tod.focal_plane.gamma[gamma_isnan] = 0. - fp_isnan = np.isnan(tod.focal_plane.xi) - if np.any(fp_isnan): - tod.focal_plane.xi[fp_isnan] = 0. - tod.focal_plane.eta[fp_isnan] = 0. - tod.focal_plane.gamma[fp_isnan] = 0. + # If input focal_plane is a result with `force_zero_roll`, set the roll to be zero + # Original value is stored to `roll_original` + if input_force_zero_roll: + if 'roll_original' in tod.boresight._fields.keys(): + pass + else: + tod.boresight.wrap('roll_original', tod.boresight.roll, [(0, 'samps')]) + tod.boresight.roll *= 0. - coords.planets.compute_source_flags(tod, center_on=sso_name, max_pix=100000000, - wrap=sso_name, mask={'shape':'circle', 'xyr':[0,0,3]}) + # compute source flags + if 'source' in tod.flags._fields.keys(): + tod.flags.move('source', None) + coords.planets.compute_source_flags(tod, + center_on=sso_name, + max_pix=1e10, + wrap='source', + mask={'shape':'circle', 'xyr':[0.,0.,mask_deg]}) - summed_flag = np.sum(tod.flags[sso_name].mask()[~fp_isnan], axis=0).astype('bool') + # restrict data to duration when at least one detector hit the source + summed_flag = np.sum(tod.flags['source'].mask()[~xieta_isnan], axis=0).astype('bool') idx_hit = np.where(summed_flag)[0] idx_first, idx_last = idx_hit[0], idx_hit[-1] tod.restrict('samps', (tod.samps.offset+idx_first, tod.samps.offset+idx_last)) - csl = so3g.proj.CelestialSightLine.az_el(tod.timestamps[mask_ds], tod.boresight.az[mask_ds], - tod.boresight.el[mask_ds], weather="typical") - q_bore = csl.Q + # run preprocess pipeline if provided + if pipe is not None: + proc_aman, success = pipe.run(tod) + + # get rms of flagged region for later error estimation + if flag_rms_calc_exclusive: + mask_for_rms_calc = tod.flags[flag_name_rms_calc].mask() + else: + mask_for_rms_calc = ~tod.flags[flag_name_rms_calc].mask() + rms = np.ma.std(np.ma.masked_array(tod.signal, mask_for_rms_calc), axis=1).data + tod.wrap('rms', rms, [(0, 'dets')]) + + # use downsampled data for faster fitting + mask_ds = slice(None, None, ds_factor) ts_ds = tod.timestamps[mask_ds] + q_bore = so3g.proj.CelestialSightLine.az_el(ts_ds, tod.boresight.az[mask_ds], + tod.boresight.el[mask_ds], weather="typical").Q + q_bore_roll = quat.rotation_iso(0, 0, np.median(tod.boresight.roll)) sig_ds = tod.signal[:, mask_ds] - source_flags_ds = tod.flags[sso_name].mask()[:, mask_ds] + source_flags_ds = tod.flags['source'].mask()[:, mask_ds] + + # fit each detector data xieta_dict = {} for di, det in enumerate(tqdm(tod.dets.vals)): - if fp_isnan[di]: - xieta_dict[det] = {'xi':np.nan, 'eta':np.nan, 'R2':np.nan} + mask_di = source_flags_ds[di] + if np.any([xieta_isnan[di], np.all(mask_di==False), tod.rms[di]==0.]): + xieta_dict[det] = {'xi': np.nan, 'eta': np.nan, 'xi_err': np.nan, 'eta_err': np.nan, + 'R2': np.nan, 'redchi2': np.nan} else: - mask_di = source_flags_ds[di] ts = ts_ds[mask_di] - + d1_unix = np.median(ts) xieta_det = np.array([tod.focal_plane.xi[di], tod.focal_plane.eta[di]]) + q_det = so3g.proj.quat.rotation_xieta(xieta_det[0], xieta_det[1]) - d1_unix = np.median(ts) planet = planets.SlowSource.for_named_source(sso_name, d1_unix * 1.) ra0, dec0 = planet.pos(d1_unix) q_obj = so3g.proj.quat.rotation_lonlat(ra0, dec0) - q_total = ~q_det * ~q_bore * q_obj + q_total = ~q_det * ~q_bore_roll * ~q_bore * q_obj xi_src, eta_src, _ = quat.decompose_xieta(q_total) xieta_src = np.array([xi_src, eta_src]) xieta_src = xieta_src[:, mask_di] - sig = sig_ds[di][mask_di] - amp = np.ptp(sig) - def fit_func(xi0, eta0): - model_tod = _gaussian2d(xieta_src[0], xieta_src[1], amp, xi0, eta0, fwhm, fwhm, 0) - residual = sig - model_tod - return np.sum(residual ** 2) - res = minimize(lambda x: fit_func(*x), [0, 0]) - R2 = 1 - res.fun/np.sum((sig - np.mean(sig))**2) + ptp_val = np.ptp(np.percentile(sig, [0.1, 99.9])) + + if fit_func_name == '_gaussian2d': + p0 = (0., 0., fwhm_init_deg*coords.DEG, fwhm_init_deg*coords.DEG, 0., ptp_val) + fit_func = _gaussian2d + elif fit_func_name == '_gaussian2d_nonlin': + p0 = (0., 0., fwhm_init_deg*coords.DEG, fwhm_init_deg*coords.DEG, 0., ptp_val, -0.1,) + fit_func = _gaussian2d_nonlin + + popt, pcov = curve_fit(fit_func, xdata=xieta_src, ydata=sig, p0=p0, sigma=tod.rms[di]*np.ones_like(sig), + absolute_sigma=True, maxfev=int(1e5)) - if np.rad2deg(np.sqrt(np.sum(res.x**2))) > 1.0: - xieta_dict[det] = {'xi':np.nan, 'eta':np.nan, 'R2':np.nan} + chi2 = np.sum(((fit_func(xieta_src, *popt) - sig)/tod.rms[di])**2) + redchi2 = chi2 / (np.prod(xieta_src.shape) - popt.shape[0]) + R2 = 1. - np.sum((fit_func(xieta_src, *popt) - sig)**2) / np.sum((sig - sig.mean())**2) + xi_opt, eta_opt = popt[0], popt[1] + + if error_estimation_method == 'rms_from_data': + xi_err, eta_err = np.sqrt(pcov[0,0]), np.sqrt(pcov[1,1]) + elif error_estimation_method == 'force_one_redchi2': + # The error of (xi, eta) is equivalent the case if the error bar of each data point is set + # as the reduced chi-square is equal to unity. + xi_err, eta_err = np.sqrt(pcov[0,0] * redchi2), np.sqrt(pcov[1,1] * redchi2) + redchi2 = 1. else: - xieta_det += res.x - xieta_dict[det] = {'xi':xieta_det[0], 'eta':xieta_det[1], 'R2':R2} - - focal_plane = metadata.ResultSet(keys=['dets:readout_id', 'band', 'channel', 'R2', 'xi', 'eta', 'gamma']) + raise NameError("Unsupported name for 'error_estimation_method'") + + xieta_det += np.array([xi_opt, eta_opt]) + xieta_dict[det] = {'xi': xieta_det[0], 'eta': xieta_det[1], 'xi_err': xi_err, 'eta_err': eta_err, + 'R2': R2, 'redchi2': redchi2} + + focal_plane = metadata.ResultSet(keys=['dets:readout_id', 'xi', 'eta', 'gamma', 'xi_err', 'eta_err', 'R2', 'redchi2']) for det in tod.dets.vals: - band = int(det.split('_')[-2]) - channel = int(det.split('_')[-1]) - focal_plane.rows.append((det, band, channel, xieta_dict[det]['R2'], - xieta_dict[det]['xi'], xieta_dict[det]['eta'], 0.)) + focal_plane.rows.append((det, xieta_dict[det]['xi'], xieta_dict[det]['eta'], 0., + xieta_dict[det]['xi_err'], xieta_dict[det]['eta_err'], + xieta_dict[det]['R2'], xieta_dict[det]['redchi2'], + )) if save: assert result_dir is not None assert filename is not None From 5101736a1950e3df2a0ccdfaa731271519f9e889 Mon Sep 17 00:00:00 2001 From: Tomoki Terasaki Date: Tue, 7 May 2024 02:27:21 +0000 Subject: [PATCH 008/132] added argument save_normal_roll --- .../site_pipeline/make_mapbased_pointing.py | 121 ++++--- sotodlib/site_pipeline/update_pointing.py | 296 +++++++++++------- 2 files changed, 256 insertions(+), 161 deletions(-) diff --git a/sotodlib/site_pipeline/make_mapbased_pointing.py b/sotodlib/site_pipeline/make_mapbased_pointing.py index e566dbf21..23f15416d 100644 --- a/sotodlib/site_pipeline/make_mapbased_pointing.py +++ b/sotodlib/site_pipeline/make_mapbased_pointing.py @@ -16,7 +16,7 @@ logger = util.init_logger(__name__, 'make_map_based_pointing: ') def main(configs, obs_id, wafer_slot, - sso_name=None, optics_config_fn=None, + sso_name=None, single_det_maps_dir=None, map_based_result_dir=None, tod_based_result_dir=None, tune_by_tod=None, restrict_dets_for_debug=False): @@ -24,35 +24,42 @@ def main(configs, obs_id, wafer_slot, configs = yaml.safe_load(open(configs, "r")) # Derive parameters from config file - if optics_config_fn is None: - optics_config_fn = configs.get('optics_config_fn') + ctx = core.Context(configs.get('context_file')) if single_det_maps_dir is None: single_det_maps_dir = configs.get('single_det_maps_dir') if map_based_result_dir is None: map_based_result_dir = configs.get('map_based_result_dir') if tod_based_result_dir is None: tod_based_result_dir = configs.get('tod_based_result_dir') - + optics_config_fn = configs.get('optics_config_fn') xieta_bs_offset = configs.get('xieta_bs_offset', [0., 0.]) wafer_mask_deg = configs.get('wafer_mask_deg', 8.) res_deg = configs.get('res_deg', 0.3) edge_avoidance_deg = configs.get('edge_avoidance_deg', 0.3) + save_normal_roll = configs.get('save_normal_roll', True) save_force_zero_roll = configs.get('save_force_zero_roll', True) + # parameters for tod tuning tune_by_tod = configs.get('tune_by_tod') - R2_threshold = configs.get('R2_threshold') - ds_factor = configs.get('ds_factor') + if tune_by_tod: + tod_ds_factor = configs.get('tod_ds_factor') + tod_mask_deg = configs.get('tod_mask_deg') + tod_fit_func_name = configs.get('tod_fit_func_name') + tod_max_non_linear_order = configs.get('tod_max_non_linear_order') + tod_fwhm_init_deg = configs.get('tod_fwhm_init_deg') + tod_error_estimation_method = configs.get('tod_error_estimation_method') + tod_flag_name_rms_calc = configs.get('tod_flag_name_rms_calc') + tod_flag_rms_calc_exclusive = configs.get('tod_flag_rms_calc_exclusive') - ctx = core.Context(configs.get('context_file')) # If sso_name is not specified, get sso name from observation tags obs_tags = ctx.obsdb.get(obs_id, tags=True)['tags'] if sso_name is None: - if 'moon' in obs_tags: - sso_name = 'moon' - elif 'jupiter' in obs_tags: - sso_name = 'jupiter' - else: + known_source_names = ['moon', 'jupiter'] + for _source_name in known_source_names: + if _source_name in obs_tags: + sso_name = _source_name + if _source_name is None: raise ValueError('sso_name is not specified') # Load data @@ -76,49 +83,83 @@ def main(configs, obs_id, wafer_slot, wafer_mask_deg=wafer_mask_deg, res_deg=res_deg) # reconstruct pointing from single detector maps - logger.info(f'Saving map-based pointing results') - result_filename = f'focal_plane_{obs_id}_{wafer_slot}.hdf' - fp_rset_map_based = mbp.get_xieta_from_maps(map_hdf, save=True, - output_dir=map_based_result_dir, - filename=result_filename, - force_zero_roll=False, - edge_avoidance = edge_avoidance_deg*coords.DEG) - - if tune_by_tod: - focal_plane = core.AxisManager(tod.dets) - focal_plane.wrap('xi', fp_rset_map_based['xi'], [(0, 'dets')]) - focal_plane.wrap('eta', fp_rset_map_based['eta'], [(0, 'dets')]) - focal_plane.wrap('gamma', fp_rset_map_based['gamma'], [(0, 'dets')]) - is_low_R2 = fp_rset_map_based['R2'] < R2_threshold - focal_plane.xi[is_low_R2] = np.nan - focal_plane.eta[is_low_R2] = np.nan - - tod.focal_plane = focal_plane - tod.flags.move(sso_name, None) - logger.info(f'Making tod-based pointing results') - fp_rset_tod_based = up.update_xieta(tod, sso_name, ds_factor=ds_factor, save=True, - result_dir=tod_based_result_dir, filename=result_filename) + if save_normal_roll: + logger.info(f'Saving map-based pointing results') + result_filename = f'focal_plane_{obs_id}_{wafer_slot}.hdf' + fp_rset_map_based = mbp.get_xieta_from_maps(map_hdf, save=True, + output_dir=map_based_result_dir, + filename=result_filename, + force_zero_roll=False, + edge_avoidance = edge_avoidance_deg*coords.DEG) + + if tune_by_tod: + logger.info(f'Making tod-based pointing results') + up.wrap_fp_rset(tod, fp_rset_map_based) + fp_rset_tod_based = up.update_xieta( tod, + sso_name=sso_name, + fp_hdf_file=None, + force_zero_roll=False, + pipe=None, + ds_factor=tod_ds_factor, + mask_deg=tod_mask_deg, + fit_func_name = tod_fit_func_name, + max_non_linear_order = tod_max_non_linear_order, + fwhm_init_deg = tod_fwhm_init_deg, + error_estimation_method=tod_error_estimation_method, + flag_name_rms_calc = tod_flag_name_rms_calc, + flag_rms_calc_exclusive = tod_flag_rms_calc_exclusive, + ) + os.makedirs(tod_based_result_dir, exist_ok=True) + write_dataset(fp_rset_tod_based, + filename=os.path.join(tod_based_result_dir, f'focal_plane_{obs_id}_{wafer_slot}.hdf'), + address='focal_plane', + overwrite=True) if save_force_zero_roll: logger.info(f'Saving map-based pointing results (force-zero-roll)') - output_dir = map_based_result_dir + '_force_zero_roll' + map_based_result_dir_force_zero_roll = map_based_result_dir + '_force_zero_roll' fp_rset_map_based_force_zero_roll = mbp.get_xieta_from_maps(map_hdf, save=True, - output_dir=output_dir, + output_dir=map_based_result_dir_force_zero_roll, filename=result_filename, force_zero_roll=True, - edge_avoidance = edge_avoidance_deg*coords.DEG) + edge_avoidance = edge_avoidance_deg*coords.DEG) + if tune_by_tod: + logger.info(f'Making tod-based pointing results (force-zero-roll)') + up.wrap_fp_rset(tod, fp_rset_map_based_force_zero_roll) + tod_based_result_dir_force_zero_roll = tod_based_result_dir + '_force_zero_roll' + fp_rset_tod_based_force_zero_roll = up.update_xieta( tod, + sso_name=sso_name, + fp_hdf_file=None, + force_zero_roll=False, + pipe=None, + ds_factor=tod_ds_factor, + mask_deg=tod_mask_deg, + fit_func_name = tod_fit_func_name, + max_non_linear_order = tod_max_non_linear_order, + fwhm_init_deg = tod_fwhm_init_deg, + error_estimation_method=tod_error_estimation_method, + flag_name_rms_calc = tod_flag_name_rms_calc, + flag_rms_calc_exclusive = tod_flag_rms_calc_exclusive, + ) + os.makedirs(tod_based_result_dir_force_zero_roll, exist_ok=True) + write_dataset(fp_rset_tod_based_force_zero_roll, + filename=os.path.join(tod_based_result_dir_force_zero_roll, f'focal_plane_{obs_id}_{wafer_slot}.hdf'), + address='focal_plane', + overwrite=True) + + return def get_parser(): parser = argparse.ArgumentParser(description="Process TOD data and update pointing") parser.add_argument("configs", type=str, help="Path to the configuration file") - parser.add_argument("obs_id", type=int, help="Observation ID") - parser.add_argument("wafer_slot", type=int, help="Wafer slot number") + parser.add_argument("obs_id", type=str, help="Observation id") + parser.add_argument("wafer_slot", type=str, help="Wafer slot") parser.add_argument("--sso_name", type=str, default=None, help="Name of solar system object (e.g., 'moon', 'jupiter')") - parser.add_argument("--optics_config_fn", type=str, default=None, help="Path to optics configuration file") parser.add_argument("--single_det_maps_dir", type=str, default=None, help="Directory to save single detector maps") parser.add_argument("--map_based_result_dir", type=str, default=None, help="Directory to save map-based pointing results") parser.add_argument("--tod_based_result_dir", type=str, default=None, help="Directory to save TOD-based pointing results") + parser.add_argument("--restrict_dets_for_debug", type=int, default=False) return parser if __name__ == '__main__': diff --git a/sotodlib/site_pipeline/update_pointing.py b/sotodlib/site_pipeline/update_pointing.py index 65472819c..1d107c0e7 100644 --- a/sotodlib/site_pipeline/update_pointing.py +++ b/sotodlib/site_pipeline/update_pointing.py @@ -24,8 +24,8 @@ from sotodlib.site_pipeline import util logger = util.init_logger(__name__, 'update_pointing: ') -def _gaussian2d(xieta, xi0, eta0, fwhm_xi, fwhm_eta, phi, a): - """Simulate a time stream with an Gaussian beam model +def gaussian2d_nonlin(xieta, xi0, eta0, fwhm_xi, fwhm_eta, phi, a, nonlin_coeffs): + """ An Gaussian beam model with non-linear response Args ------ xi, eta: cordinates in the detector's system @@ -36,11 +36,12 @@ def _gaussian2d(xieta, xi0, eta0, fwhm_xi, fwhm_eta, phi, a): and the rotation angle (in radians) a: float amplitude of the Gaussian beam model - + nonlin_coeffs: float + Coefficient of non-linear term normalized by linear term (from 2nd term). + The order is ascending. Ouput: ------ - sim_data: 1d array of float - Time stream at sampling points given by xieta + Model at xieta """ xi, eta = xieta xi_rot = xi * np.cos(phi) - eta * np.sin(phi) @@ -48,55 +49,18 @@ def _gaussian2d(xieta, xi0, eta0, fwhm_xi, fwhm_eta, phi, a): factor = 2 * np.sqrt(2 * np.log(2)) xi_coef = -0.5 * (xi_rot - xi0) ** 2 / (fwhm_xi / factor) ** 2 eta_coef = -0.5 * (eta_rot - eta0) ** 2 / (fwhm_eta / factor) ** 2 - sim_data = a * np.exp(xi_coef + eta_coef) - return sim_data - -def _gaussian2d_nonlin(xieta, xi0, eta0, fwhm_xi, fwhm_eta, phi, a, b2,): - """Simulate a time stream with an Gaussian beam model with non-linear response - Args - ------ - xi, eta: cordinates in the detector's system - xi0, eta0: float, float - center position of the Gaussian beam model - fwhm_xi, fwhm_eta, phi: float, float, float - fwhm along the xi, eta axis (rotated) - and the rotation angle (in radians) - a: float - amplitude of the Gaussian beam model - b2: float - coefficient of 2nd-order term + lin_gauss = np.exp(xi_coef + eta_coef) + polycoeffs_discending = np.hstack([nonlin_coeffs[::-1], [1, 0]]) + return a * np.poly1d(polycoeffs_discending)(lin_gauss) - Ouput: - ------ - sim_data: 1d array of float - Time stream at sampling points given by xieta +def wrapper_gaussian2d_nonlin(xieta, xi0, eta0, fwhm_xi, fwhm_eta, phi, a, *args): """ - xi, eta = xieta - xi_rot = xi * np.cos(phi) - eta * np.sin(phi) - eta_rot = xi * np.sin(phi) + eta * np.cos(phi) - factor = 2 * np.sqrt(2 * np.log(2)) - xi_coef = -0.5 * (xi_rot - xi0) ** 2 / (fwhm_xi / factor) ** 2 - eta_coef = -0.5 * (eta_rot - eta0) ** 2 / (fwhm_eta / factor) ** 2 - _y = np.exp(xi_coef + eta_coef) - sim_data = a * (_y + b2*_y**2) - return sim_data - -# def filter_tod(tod, cutoff_high=0.01, cutoff_low=1.8): -# if cutoff_low is not None: -# tod.signal = fourier_filter(tod, filt_function=low_pass_sine2(cutoff=cutoff_low),) -# if cutoff_high is not None: -# tod.signal = fourier_filter(tod, filt_function=high_pass_sine2(cutoff=cutoff_high),) -# return - -# def tod_process(tod): -# tod_ops.detrend_tod(tod) -# tod_ops.apodize_cosine(tod, apodize_samps=2000) -# filter_tod(tod) -# tod.restrict('samps', (tod.samps.offset+2000, tod.samps.offset+tod.samps.count-2000)) -# return + A wrapper for `gaussian2d_nonlin` + """ + nonlin_coeffs = np.array(args) + return gaussian2d_nonlin(xieta, xi0, eta0, fwhm_xi, fwhm_eta, phi, a, nonlin_coeffs) -def wrap_fp_from_hdf(tod, fp_hdf_file, data_set='focal_plane'): - fp_rset = read_dataset(fp_hdf_file, data_set) +def wrap_fp_rset(tod, fp_rset): tod.restrict('dets', tod.dets.vals[np.in1d(tod.dets.vals, fp_rset['dets:readout_id'])]) focal_plane = core.AxisManager(tod.dets) focal_plane.wrap_new('xi', shape=('dets', )) @@ -114,31 +78,68 @@ def wrap_fp_from_hdf(tod, fp_hdf_file, data_set='focal_plane'): tod.wrap('focal_plane', focal_plane) return +def wrap_fp_from_hdf(tod, fp_hdf_file, data_set='focal_plane'): + fp_rset = read_dataset(fp_hdf_file, data_set) + wrap_fp_rset(tod, fp_rset) + return + def update_xieta(tod, sso_name='moon', fp_hdf_file=None, - input_force_zero_roll=False, + save_dir=None, pipe=None, + force_zero_roll=False, ds_factor=10, mask_deg=3, - fit_func_name = '_gaussian2d_nonlin', + fit_func_name = 'gaussian2d_nonlin', + max_non_linear_order = 1, fwhm_init_deg = 0.5, error_estimation_method='force_one_redchi2', # rms_from_data flag_name_rms_calc = 'source', flag_rms_calc_exclusive = True, - save=False, result_dir=None, filename=None): + save=True, ): """ - Update xieta parameters for each detector by tod fitting of a point source observation + Update xieta parameters for each detector by TOD fitting of a point source observation. Parameters: - - tod : an Axismanager object - - sso_name (str): Name of the Solar System Object (SSO). - - ds_factor (int): Downsampling factor for processing TOD. - - fwhm (float): Full width at half maximum of the Gaussian model. - - save (bool): Flag indicating whether to save the updated focal plane data. - - result_dir (str): Directory where the updated data will be saved. - - filename (str): Name of the file to save the updated data. + - tod : + an Axismanager object + - sso_name (str): + Name of the Solar System Object (SSO). + - fp_hdf_file (str or None): + Path to the HDF file containing focal plane information. Default is None. + If None, tod.focal_plane is used for focal plane information. + - save_dir (str or None): + Directory where the updated data will be saved. Required if save is True. + - force_zero_roll (bool): + Flag indicating whether to force the roll to be zero. Default is False. + If True, input and output focal plane information assumes force_zero_roll condition. + - pipe (Pipeline or None): + Preprocessing pipeline to be applied to the TOD. Default is None, which + do not apply any processing. + - ds_factor (int): + Downsampling factor for fitting. Default is 10. + - mask_deg (float): + Mask radius in degrees for source flagging. Default is 3. + - fit_func_name (str): + Name of the fitting function. Default is 'gaussian2d_nonlin'. 'gaussian2d_nonlin' is only supported. + - max_non_linear_order (int): + Maximum non-linear order for fitting function. Default is 1. If you want to use simple gaussian set it to be 1. + Higher order is for the case that detector response is distorted by non-point-like source or too-strogng source, such as the Moon. + - fwhm_init_deg (float): + Initial guess for full width at half maximum in degrees. Default is 0.5. + - error_estimation_method (str): + Method for error estimation. Default is 'rms_from_data'. 'rms_from_data' and 'force_one_redchi2' are supported. + If 'rms_from_data', errorbar of each data point is set by root-mean-square of the data points flaged by 'flag_name_rms_calc', + and errorbar of xi,eta is set from the fit covariance matrix. If 'force_one_redchi2', the errorbar of (xi,eta) is equivalent the case + if the error bar of each data point is set as the reduced chi-square is equal to unity. + - flag_name_rms_calc (str): + Name of the flag used for RMS calculation. Default is 'source'. + - flag_rms_calc_exclusive (bool): + Flag indicating whether the RMS calculation is exclusive to the flag. Default is True. + - save (bool): + Flag indicating whether to save the updated focal plane data. Default is True. Returns: - focal_plane (ResultSet): ResultSet containing updated xieta parameters for each detector. @@ -156,7 +157,7 @@ def update_xieta(tod, # If input focal_plane is a result with `force_zero_roll`, set the roll to be zero # Original value is stored to `roll_original` - if input_force_zero_roll: + if force_zero_roll: if 'roll_original' in tod.boresight._fields.keys(): pass else: @@ -188,6 +189,8 @@ def update_xieta(tod, else: mask_for_rms_calc = ~tod.flags[flag_name_rms_calc].mask() rms = np.ma.std(np.ma.masked_array(tod.signal, mask_for_rms_calc), axis=1).data + if 'rms' in tod._fields.keys(): + tod.move('rms', None) tod.wrap('rms', rms, [(0, 'dets')]) # use downsampled data for faster fitting @@ -220,38 +223,50 @@ def update_xieta(tod, xi_src, eta_src, _ = quat.decompose_xieta(q_total) xieta_src = np.array([xi_src, eta_src]) xieta_src = xieta_src[:, mask_di] - sig = sig_ds[di][mask_di] - + sig = sig_ds[di][mask_di] ptp_val = np.ptp(np.percentile(sig, [0.1, 99.9])) - if fit_func_name == '_gaussian2d': - p0 = (0., 0., fwhm_init_deg*coords.DEG, fwhm_init_deg*coords.DEG, 0., ptp_val) - fit_func = _gaussian2d - elif fit_func_name == '_gaussian2d_nonlin': - p0 = (0., 0., fwhm_init_deg*coords.DEG, fwhm_init_deg*coords.DEG, 0., ptp_val, -0.1,) - fit_func = _gaussian2d_nonlin - - popt, pcov = curve_fit(fit_func, xdata=xieta_src, ydata=sig, p0=p0, sigma=tod.rms[di]*np.ones_like(sig), - absolute_sigma=True, maxfev=int(1e5)) - - chi2 = np.sum(((fit_func(xieta_src, *popt) - sig)/tod.rms[di])**2) - redchi2 = chi2 / (np.prod(xieta_src.shape) - popt.shape[0]) - R2 = 1. - np.sum((fit_func(xieta_src, *popt) - sig)**2) / np.sum((sig - sig.mean())**2) - xi_opt, eta_opt = popt[0], popt[1] - - if error_estimation_method == 'rms_from_data': - xi_err, eta_err = np.sqrt(pcov[0,0]), np.sqrt(pcov[1,1]) - elif error_estimation_method == 'force_one_redchi2': - # The error of (xi, eta) is equivalent the case if the error bar of each data point is set - # as the reduced chi-square is equal to unity. - xi_err, eta_err = np.sqrt(pcov[0,0] * redchi2), np.sqrt(pcov[1,1] * redchi2) - redchi2 = 1. + if fit_func_name == 'gaussian2d_nonlin': + p0 = np.array([0., 0., fwhm_init_deg*coords.DEG, fwhm_init_deg*coords.DEG, 0., ptp_val]) + bounds = np.array( + [[-np.inf, -np.inf, 0.1*fwhm_init_deg*coords.DEG, 0.1*fwhm_init_deg*coords.DEG, -np.pi, 0.1*ptp_val], + [np.inf, np.inf, 10*fwhm_init_deg*coords.DEG, 10*fwhm_init_deg*coords.DEG, np.pi, 10*ptp_val]] + ) + if max_non_linear_order >= 2: + p0 = np.append(p0, np.zeros(max_non_linear_order-1)) + bounds = np.hstack([bounds, + np.vstack([[-np.inf * np.ones(max_non_linear_order-1), + np.inf * np.ones(max_non_linear_order-1)]]) + ]) + fit_func = wrapper_gaussian2d_nonlin else: - raise NameError("Unsupported name for 'error_estimation_method'") + raise NameError("Unsupported name for 'fit_func_name'") - xieta_det += np.array([xi_opt, eta_opt]) - xieta_dict[det] = {'xi': xieta_det[0], 'eta': xieta_det[1], 'xi_err': xi_err, 'eta_err': eta_err, - 'R2': R2, 'redchi2': redchi2} + try: + popt, pcov = curve_fit(fit_func, xdata=xieta_src, ydata=sig, sigma=tod.rms[di]*np.ones_like(sig), + p0=p0, bounds=bounds, absolute_sigma=True) + + chi2 = np.sum(((fit_func(xieta_src, *popt) - sig)/tod.rms[di])**2) + redchi2 = chi2 / (np.prod(xieta_src.shape) - popt.shape[0]) + R2 = 1. - np.sum((fit_func(xieta_src, *popt) - sig)**2) / np.sum((sig - sig.mean())**2) + xi_opt, eta_opt = popt[0], popt[1] + + if error_estimation_method == 'rms_from_data': + xi_err, eta_err = np.sqrt(pcov[0,0]), np.sqrt(pcov[1,1]) + elif error_estimation_method == 'force_one_redchi2': + # The error of (xi, eta) is equivalent the case if the error bar of each data point is set + # as the reduced chi-square is equal to unity. + xi_err, eta_err = np.sqrt(pcov[0,0] * redchi2), np.sqrt(pcov[1,1] * redchi2) + redchi2 = 1. + else: + raise NameError("Unsupported name for 'error_estimation_method'") + + xieta_det += np.array([xi_opt, eta_opt]) + xieta_dict[det] = {'xi': xieta_det[0], 'eta': xieta_det[1], 'xi_err': xi_err, 'eta_err': eta_err, + 'R2': R2, 'redchi2': redchi2} + except RuntimeError: + xieta_dict[det] = {'xi': np.nan, 'eta': np.nan, 'xi_err': np.nan, 'eta_err': np.nan, + 'R2': np.nan, 'redchi2': np.nan} focal_plane = metadata.ResultSet(keys=['dets:readout_id', 'xi', 'eta', 'gamma', 'xi_err', 'eta_err', 'R2', 'redchi2']) for det in tod.dets.vals: @@ -259,37 +274,78 @@ def update_xieta(tod, xieta_dict[det]['xi_err'], xieta_dict[det]['eta_err'], xieta_dict[det]['R2'], xieta_dict[det]['redchi2'], )) - if save: - assert result_dir is not None - assert filename is not None - if not os.path.exists(result_dir): - os.makedirs(result_dir) - write_dataset(focal_plane, - filename=os.path.join(result_dir, filename), - address='focal_plane', - overwrite=True) + return focal_plane -def main(ctx_file, obs_id, wafer_slot, sso_name, result_dir, - ds_factor=10, fwhm = 1.*coords.DEG, restrict_dets=False): - ctx = core.Context(ctx_file) - meta = ctx.get_meta(obs_id) - meta.restrict('dets', meta.dets.vals[meta.det_info.wafer_slot == wafer_slot]) - if restrict_dets: - meta.restrict('dets', meta.dets.vals[:100]) - +def main(configs, obs_id, wafer_slot, sso_name=None, + fp_hdf_file=None, save_dir=None, restrict_dets_for_debug=False): + if type(configs) == str: + configs = yaml.safe_load(open(configs, "r")) + + # Derive parameters from config file + ctx = core.Context(configs.get('context_file')) + if fp_hdf_file is None: + fp_hdf_file = configs.get('fp_hdf_file', None) + if save_dir is None: + save_dir = configs.get('save_dir', None) + + # get sso_name if it is not specified + obs_tags = ctx.obsdb.get(obs_id, tags=True)['tags'] + if sso_name is None: + known_source_names = ['moon', 'jupiter'] + for _source_name in known_source_names: + if _source_name in obs_tags: + sso_name = _source_name + if _source_name is None: + raise ValueError('sso_name is not specified') + + # construct pipeline from configs + pipe = Pipeline(configs["process_pipe"]) + for pipe_component in pipe: + if pipe_component.name == 'compute_source_flags': + pipe_component.process_cfgs['center_on'] = sso_name + + # Other parameters + force_zero_roll = configs.get('force_zero_roll') + ds_factor = configs.get('ds_factor') + mask_deg = configs.get('mask_deg') + fit_func_name = configs.get('fit_func_name') + max_non_linear_order = configs.get('max_non_linear_order') + fwhm_init_deg = configs.get('fwhm_init_deg') + error_estimation_method = configs.get('error_estimation_method') + flag_name_rms_calc = configls.get('flag_name_rms_calc') + flag_rms_calc_exclusive = configls.get('flag_rms_calc_exclusive') + + + # Load data logger.info('loading data') + meta = ctx.get_meta(obs_id, dets={'wafer_slot': wafer_slot}) + if restrict_dets_for_debug is not False: + meta.restrict('dets', meta.dets.vals[:restrict_dets_for_debug]) tod = ctx.get_obs(meta) - logger.info('tod processing') - tod_process(tod) - if not os.path.exists(result_dir): - logger.info(f'Make a directory: f{result_dir}') - os.makedirs(result_dir) + # get pointing + focal_plane_rset = update_xieta( tod, + sso_name=sso_name, + fp_hdf_file=fp_hdf_file, + force_zero_roll=force_zero_roll, + pipe=pipe, + ds_factor=ds_factor, + mask_deg=mask_deg, + fit_func_name = fit_func_name, + max_non_linear_order = max_non_linear_order, + fwhm_init_deg = fwhm_init_deg, + error_estimation_method=error_estimation_method, + flag_name_rms_calc = flag_name_rms_calc, + flag_rms_calc_exclusive = flag_rms_calc_exclusive, + ) - result_filename = f'focal_plane_{obs_id}_{wafer_slot}.hdf' - focal_plane_rset = update_xieta(tod=tod, sso_name=sso_name, ds_factor=ds_factor, fwhm=fwhm, - save=True, result_dir=result_dir, filename=result_filename) + os.makedirs(save_dir, exist_ok=True) + write_dataset(focal_plane_rset, + filename=os.path.join(save_dir, f'focal_plane_{obs_id}_{wafer_slot}.hdf'), + address='focal_plane', + overwrite=True) + return def get_parser(): @@ -297,11 +353,9 @@ def get_parser(): parser.add_argument("ctx_file", type=str, help="Path to the context file.") parser.add_argument("obs_id", type=str, help="Observation ID.") parser.add_argument("wafer_slot", type=int, help="Wafer slot number.") - parser.add_argument("sso_name", type=str, help="Name of the Solar System Object (SSO).") - parser.add_argument("result_dir", type=str, help="Directory to save the result.") - parser.add_argument("--ds_factor", type=int, default=10, help="Downsampling factor for TOD processing.") - parser.add_argument("--fwhm", type=float, default=1.0, help="Full width at half maximum of the Gaussian model.") - parser.add_argument("--restrict_dets", action="store_true", help="Flag to restrict the number of detectors.") + parser.add_argument("sso_name", type=str, default=None, help="Name of the Solar System Object (SSO).") + parser.add_argument("save_dir", type=str, help="Directory to save the result.") + parser.add_argument("restrict_dets_for_debug", action="store_true", help="Flag to restrict the number of detectors.") return parser if __name__ == '__main__': From d708edb7f980f51b2e5c0aab0400e8e14b37e031 Mon Sep 17 00:00:00 2001 From: Tomoki Terasaki Date: Tue, 7 May 2024 09:49:37 +0000 Subject: [PATCH 009/132] tod based fitting is automated --- sotodlib/coords/map_based_pointing.py | 35 ++++++- .../site_pipeline/make_mapbased_pointing.py | 60 ++++++++++-- sotodlib/site_pipeline/update_pointing.py | 97 ++++++++++++++----- 3 files changed, 159 insertions(+), 33 deletions(-) diff --git a/sotodlib/coords/map_based_pointing.py b/sotodlib/coords/map_based_pointing.py index 294a350a2..9f87ae406 100644 --- a/sotodlib/coords/map_based_pointing.py +++ b/sotodlib/coords/map_based_pointing.py @@ -50,7 +50,7 @@ def get_planet_trajectry(tod, planet, _split=20, return_model=False): q_planet = quat.rotation_lonlat(planet_az, planet_el) return q_planet -def get_wafer_centered_sight(tod, planet, q_planet=None, q_bs=None, q_wafer=None): +def get_wafer_centered_sight(tod=None, planet=None, q_planet=None, q_bs=None, q_wafer=None): """ Calculate the sightline vector from the focal plane, centered on the wafer, to a planet. @@ -131,6 +131,34 @@ def get_wafer_xieta(wafer_slot, optics_config_fn, xieta_bs_offset=(0., 0.), return xi_wafer, eta_wafer +def get_rough_hit_time(tod, wafer_slot, sso_name, circle_r_deg=7.,optics_config_fn=None): + """ + Estimate the rough hit time for a axismanager, wafer_slot, and sso_name. + + Parameters: + tod : An AxisManager object + wafer_slot (str): Identifier for the wafer slot. + sso_name (str): Name of the Solar System Object (e.g., 'moon', 'jupiter'). + circle_r_deg (float, optional): Radius in degrees defining the circular region around the wafer center. + Defaults to 7 degrees. + + Returns: + float: Estimated rough hit time within the circular region around the wafer center. + """ + q_bs = quat.rotation_lonlat(tod.boresight.az, tod.boresight.el) + q_planet = get_planet_trajectry(tod, sso_name) + xi_wafer, eta_wafer = get_wafer_xieta(wafer_slot, optics_config_fn=optics_config_fn, + roll_bs_offset=np.median(tod.boresight.roll), wrap_to_tod=False) + q_wafer = quat.rotation_xieta(xi_wafer, eta_wafer) + + q_wafer_centered = get_wafer_centered_sight(q_planet=q_planet, q_bs=q_bs, q_wafer=q_wafer) + x_to_z = ~quat.rotation_lonlat(0, 0) + xi_wafer_centered, eta_wafer_centered, _ = quat.decompose_xieta(x_to_z * q_wafer_centered) + r_wafer_centered = np.sqrt(xi_wafer_centered**2 + eta_wafer_centered**2) + hit_time = (tod.timestamps[-1] - tod.timestamps[0]) * np.mean(np.rad2deg(r_wafer_centered) < circle_r_deg) + return hit_time + + def make_wafer_centered_maps(tod, sso_name, optics_config_fn, map_hdf, xieta_bs_offset=(0., 0.), roll_bs_offset=None, signal='signal', wafer_mask_deg=8., res_deg=0.3, cuts=None,): @@ -151,10 +179,7 @@ def make_wafer_centered_maps(tod, sso_name, optics_config_fn, map_hdf, Returns: None - """ - - - + """ q_planet = get_planet_trajectry(tod, sso_name) q_bs = quat.rotation_lonlat(tod.boresight.az, tod.boresight.el) diff --git a/sotodlib/site_pipeline/make_mapbased_pointing.py b/sotodlib/site_pipeline/make_mapbased_pointing.py index 23f15416d..3adc0a401 100644 --- a/sotodlib/site_pipeline/make_mapbased_pointing.py +++ b/sotodlib/site_pipeline/make_mapbased_pointing.py @@ -14,8 +14,8 @@ from sotodlib.site_pipeline import util from sotodlib.preprocess import Pipeline logger = util.init_logger(__name__, 'make_map_based_pointing: ') - -def main(configs, obs_id, wafer_slot, + +def main_one_wafer(configs, obs_id, wafer_slot, sso_name=None, single_det_maps_dir=None, map_based_result_dir=None, tod_based_result_dir=None, tune_by_tod=None, restrict_dets_for_debug=False): @@ -82,10 +82,11 @@ def main(configs, obs_id, wafer_slot, xieta_bs_offset=xieta_bs_offset, wafer_mask_deg=wafer_mask_deg, res_deg=res_deg) + result_filename = f'focal_plane_{obs_id}_{wafer_slot}.hdf' # reconstruct pointing from single detector maps if save_normal_roll: logger.info(f'Saving map-based pointing results') - result_filename = f'focal_plane_{obs_id}_{wafer_slot}.hdf' + fp_rset_map_based = mbp.get_xieta_from_maps(map_hdf, save=True, output_dir=map_based_result_dir, filename=result_filename, @@ -146,19 +147,66 @@ def main(configs, obs_id, wafer_slot, filename=os.path.join(tod_based_result_dir_force_zero_roll, f'focal_plane_{obs_id}_{wafer_slot}.hdf'), address='focal_plane', overwrite=True) - - return +def main(configs, obs_id, wafer_slots, + sso_name=None, + single_det_maps_dir=None, map_based_result_dir=None, tod_based_result_dir=None, + tune_by_tod=None, hit_time_threshold=1200, hit_circle_r_deg=7.0, + restrict_dets_for_debug=False): + + logger.info('get wafer_slots which hit the source because wafer_slots are not specified') + if wafer_slots is None: + if type(configs) == str: + configs = yaml.safe_load(open(configs, "r")) + + ctx = core.Context(configs.get('context_file')) + optics_config_fn = configs.get('optics_config_fn') + + obs_tags = ctx.obsdb.get(obs_id, tags=True)['tags'] + if sso_name is None: + known_source_names = ['moon', 'jupiter'] + for _source_name in known_source_names: + if _source_name in obs_tags: + sso_name = _source_name + if _source_name is None: + raise ValueError('sso_name is not specified') + + wafer_slots = [] + tod = ctx.get_obs(obs_id, dets=[]) + for ws in [f'ws{i}' for i in range(7)]: + hit_time = mbp.get_rough_hit_time(tod, wafer_slot=ws, sso_name=sso_name, circle_r_deg=hit_circle_r_deg, + optics_config_fn=optics_config_fn) + logger.info(f'hit_time for {ws} is {hit_time:.1f} [sec]') + if hit_time > hit_time_threshold: + wafer_slots.append(ws) + assert np.all(np.array(wafer_slots, dtype='U2') == 'ws') + + logger.info(f'wafer_slots which pointing calculated: {wafer_slots}') + for wafer_slot in wafer_slots: + main_one_wafer(configs=configs, + obs_id=obs_id, + wafer_slot=wafer_slot, + sso_name=sso_name, + single_det_maps_dir=single_det_maps_dir, + map_based_result_dir=map_based_result_dir, + tod_based_result_dir=tod_based_result_dir, + tune_by_tod=tune_by_tod, + restrict_dets_for_debug=restrict_dets_for_debug) + def get_parser(): parser = argparse.ArgumentParser(description="Process TOD data and update pointing") parser.add_argument("configs", type=str, help="Path to the configuration file") parser.add_argument("obs_id", type=str, help="Observation id") - parser.add_argument("wafer_slot", type=str, help="Wafer slot") + parser.add_argument("--wafer_slots", nargs='*', default=None, help="Wafer slots to be processed") parser.add_argument("--sso_name", type=str, default=None, help="Name of solar system object (e.g., 'moon', 'jupiter')") parser.add_argument("--single_det_maps_dir", type=str, default=None, help="Directory to save single detector maps") parser.add_argument("--map_based_result_dir", type=str, default=None, help="Directory to save map-based pointing results") parser.add_argument("--tod_based_result_dir", type=str, default=None, help="Directory to save TOD-based pointing results") + parser.add_argument("--hit_time_threshold", type=float, default=1200, + help="Minimum hit time. If calculated wafer hit time is smaller than that, pointing calculation for that wafer is skipped") + parser.add_argument("--hit_circle_r_deg", type=float, default=7., + help="circle radius for wafer hit time calculation") parser.add_argument("--restrict_dets_for_debug", type=int, default=False) return parser diff --git a/sotodlib/site_pipeline/update_pointing.py b/sotodlib/site_pipeline/update_pointing.py index 1d107c0e7..9c98c2f69 100644 --- a/sotodlib/site_pipeline/update_pointing.py +++ b/sotodlib/site_pipeline/update_pointing.py @@ -2,26 +2,21 @@ import numpy as np import yaml import h5py -import matplotlib.pyplot as plt +import argparse from tqdm import tqdm import scipy from scipy.optimize import curve_fit from sotodlib.core import metadata from sotodlib.io.metadata import read_dataset, write_dataset - +from sotodlib.coords import map_based_pointing as mbp from sotodlib import core from sotodlib import coords from sotodlib import tod_ops import so3g from so3g.proj import quat import sotodlib.coords.planets as planets - -from sotodlib.tod_ops import pca -from so3g.proj import Ranges, RangesMatrix -from pixell import enmap, enplot -from sotodlib.tod_ops.filters import high_pass_sine2, low_pass_sine2, fourier_filter - from sotodlib.site_pipeline import util +from sotodlib.preprocess import Pipeline logger = util.init_logger(__name__, 'update_pointing: ') def gaussian2d_nonlin(xieta, xi0, eta0, fwhm_xi, fwhm_eta, phi, a, nonlin_coeffs): @@ -109,9 +104,7 @@ def update_xieta(tod, Name of the Solar System Object (SSO). - fp_hdf_file (str or None): Path to the HDF file containing focal plane information. Default is None. - If None, tod.focal_plane is used for focal plane information. - - save_dir (str or None): - Directory where the updated data will be saved. Required if save is True. + If None, tod.focal_plane is used for focal plane information. - force_zero_roll (bool): Flag indicating whether to force the roll to be zero. Default is False. If True, input and output focal plane information assumes force_zero_roll condition. @@ -229,8 +222,8 @@ def update_xieta(tod, if fit_func_name == 'gaussian2d_nonlin': p0 = np.array([0., 0., fwhm_init_deg*coords.DEG, fwhm_init_deg*coords.DEG, 0., ptp_val]) bounds = np.array( - [[-np.inf, -np.inf, 0.1*fwhm_init_deg*coords.DEG, 0.1*fwhm_init_deg*coords.DEG, -np.pi, 0.1*ptp_val], - [np.inf, np.inf, 10*fwhm_init_deg*coords.DEG, 10*fwhm_init_deg*coords.DEG, np.pi, 10*ptp_val]] + [[-np.inf, -np.inf, fwhm_init_deg*coords.DEG/5., fwhm_init_deg*coords.DEG/5., -np.pi, 0.1*ptp_val], + [np.inf, np.inf, fwhm_init_deg*coords.DEG*5, fwhm_init_deg*coords.DEG*5, np.pi, 10*ptp_val]] ) if max_non_linear_order >= 2: p0 = np.append(p0, np.zeros(max_non_linear_order-1)) @@ -277,15 +270,28 @@ def update_xieta(tod, return focal_plane -def main(configs, obs_id, wafer_slot, sso_name=None, - fp_hdf_file=None, save_dir=None, restrict_dets_for_debug=False): +def main_one_wafer(configs, obs_id, wafer_slot, + sso_name=None, fp_hdf_file=None, fp_hdf_dir=None, + save_dir=None, restrict_dets_for_debug=False): if type(configs) == str: configs = yaml.safe_load(open(configs, "r")) # Derive parameters from config file ctx = core.Context(configs.get('context_file')) + + # get prior if fp_hdf_file is None: fp_hdf_file = configs.get('fp_hdf_file', None) + if fp_hdf_dir is None: + fp_hdf_dir = configs.get('fp_hdf_dir', None) + if fp_hdf_file is None: + if fp_hdf_dir is None: + pass + else: + fp_hdf_file = os.path.join(fp_hdf_dir, f'focal_plane_{obs_id}_{wafer_slot}.hdf') + if not os.path.exists(fp_hdf_file): + fp_hdf_file = None + if save_dir is None: save_dir = configs.get('save_dir', None) @@ -313,8 +319,8 @@ def main(configs, obs_id, wafer_slot, sso_name=None, max_non_linear_order = configs.get('max_non_linear_order') fwhm_init_deg = configs.get('fwhm_init_deg') error_estimation_method = configs.get('error_estimation_method') - flag_name_rms_calc = configls.get('flag_name_rms_calc') - flag_rms_calc_exclusive = configls.get('flag_rms_calc_exclusive') + flag_name_rms_calc = configs.get('flag_name_rms_calc') + flag_rms_calc_exclusive = configs.get('flag_rms_calc_exclusive') # Load data @@ -348,14 +354,61 @@ def main(configs, obs_id, wafer_slot, sso_name=None, return +def main(configs, obs_id, wafer_slots=None, + sso_name=None, fp_hdf_file=None, fp_hdf_dir=None, save_dir=None, + hit_time_threshold=1200, hit_circle_r_deg=7.0, + restrict_dets_for_debug=False): + logger.info('get wafer_slots which hit the source because wafer_slots are not specified') + if wafer_slots is None: + if type(configs) == str: + configs = yaml.safe_load(open(configs, "r")) + + ctx = core.Context(configs.get('context_file')) + optics_config_fn = configs.get('optics_config_fn') + + obs_tags = ctx.obsdb.get(obs_id, tags=True)['tags'] + if sso_name is None: + known_source_names = ['moon', 'jupiter'] + for _source_name in known_source_names: + if _source_name in obs_tags: + sso_name = _source_name + if _source_name is None: + raise ValueError('sso_name is not specified') + + wafer_slots = [] + tod = ctx.get_obs(obs_id, dets=[]) + for ws in [f'ws{i}' for i in range(7)]: + hit_time = mbp.get_rough_hit_time(tod, wafer_slot=ws, sso_name=sso_name, circle_r_deg=hit_circle_r_deg, + optics_config_fn=optics_config_fn) + logger.info(f'hit_time for {ws} is {hit_time:.1f} [sec]') + if hit_time > hit_time_threshold: + wafer_slots.append(ws) + assert np.all(np.array(wafer_slots, dtype='U2') == 'ws') + + logger.info(f'wafer_slots which pointing calculated: {wafer_slots}') + for wafer_slot in wafer_slots: + main_one_wafer(configs, + obs_id, + wafer_slot, + sso_name=sso_name, + fp_hdf_file=fp_hdf_file, + fp_hdf_dir=fp_hdf_dir, + save_dir=save_dir, + restrict_dets_for_debug=restrict_dets_for_debug) + return + + def get_parser(): parser = argparse.ArgumentParser(description="Get updated result of pointings with tod-based results") - parser.add_argument("ctx_file", type=str, help="Path to the context file.") + parser.add_argument("configs", type=str, help="Path to the configuration file") parser.add_argument("obs_id", type=str, help="Observation ID.") - parser.add_argument("wafer_slot", type=int, help="Wafer slot number.") - parser.add_argument("sso_name", type=str, default=None, help="Name of the Solar System Object (SSO).") - parser.add_argument("save_dir", type=str, help="Directory to save the result.") - parser.add_argument("restrict_dets_for_debug", action="store_true", help="Flag to restrict the number of detectors.") + parser.add_argument("--wafer_slots", nargs='*', default=None, help="Wafer slots to be processed") + parser.add_argument("--sso_name", type=str, default=None, help="Name of the Solar System Object (SSO).") + parser.add_argument("--fp_hdf_file", type=str, default=None, help="File path to the focal_plane hdf file used as a prior") + parser.add_argument("--fp_hdf_dir", type=str, default=None, + help="Directory path where focal_plane hdf file of each observation are stored. Used only fp_hdf_file is not specified.") + parser.add_argument("--save_dir", type=str, help="Directory to save the result.") + parser.add_argument("--restrict_dets_for_debug", type=int, help="Flag to restrict the number of detectors.") return parser if __name__ == '__main__': From 34481e7108541aeef800e1a48b8c4c5f444ef3b7 Mon Sep 17 00:00:00 2001 From: tterasaki Date: Thu, 9 May 2024 07:45:20 +0000 Subject: [PATCH 010/132] main function is done --- sotodlib/coords/map_based_pointing.py | 8 +- .../site_pipeline/make_mapbased_pointing.py | 343 +++++++++++------- sotodlib/site_pipeline/update_pointing.py | 288 ++++++++++----- 3 files changed, 414 insertions(+), 225 deletions(-) diff --git a/sotodlib/coords/map_based_pointing.py b/sotodlib/coords/map_based_pointing.py index 9f87ae406..23e814713 100644 --- a/sotodlib/coords/map_based_pointing.py +++ b/sotodlib/coords/map_based_pointing.py @@ -477,12 +477,10 @@ def get_xieta_from_maps(map_hdf_file, filename = 'focal_plane_' + os.path.splitext(os.path.basename(map_hdf_file))[0] + '.hdf' output_file = os.path.join(output_dir, filename) - focal_plane = metadata.ResultSet(keys=['dets:readout_id', 'band', 'channel', 'R2', 'xi', 'eta', 'gamma']) + focal_plane = metadata.ResultSet(keys=['dets:readout_id', 'xi', 'eta', 'gamma', 'R2']) for det in dets: - band = int(det.split('_')[-2]) - channel = int(det.split('_')[-1]) - focal_plane.rows.append((det, band, channel, xieta_dict[det]['R2'], - xieta_dict[det]['xi'], xieta_dict[det]['eta'], 0.)) + focal_plane.rows.append((det, xieta_dict[det]['xi'], xieta_dict[det]['eta'], 0., + xieta_dict[det]['R2'])) write_dataset(focal_plane, output_file, 'focal_plane', overwrite=True) return focal_plane diff --git a/sotodlib/site_pipeline/make_mapbased_pointing.py b/sotodlib/site_pipeline/make_mapbased_pointing.py index 3adc0a401..faed09a43 100644 --- a/sotodlib/site_pipeline/make_mapbased_pointing.py +++ b/sotodlib/site_pipeline/make_mapbased_pointing.py @@ -2,66 +2,61 @@ import numpy as np import yaml import argparse +import time +import glob from sotodlib import core from sotodlib import coords from sotodlib import tod_ops -from sotodlib.tod_ops.filters import high_pass_sine2, low_pass_sine2, fourier_filter from sotodlib.coords import map_based_pointing as mbp from sotodlib.site_pipeline import update_pointing as up -from sotodlib.io.metadata import write_dataset +from sotodlib.io import metadata +from sotodlib.io.metadata import read_dataset, write_dataset from sotodlib.site_pipeline import util from sotodlib.preprocess import Pipeline logger = util.init_logger(__name__, 'make_map_based_pointing: ') -def main_one_wafer(configs, obs_id, wafer_slot, - sso_name=None, - single_det_maps_dir=None, map_based_result_dir=None, tod_based_result_dir=None, - tune_by_tod=None, restrict_dets_for_debug=False): +def _get_sso_names_from_tags(ctx, obs_id, candidate_names=['moon', 'jupiter']): + obs_tags = ctx.obsdb.get(obs_id, tags=True)['tags'] + sso_names = [] + for _name in candidate_names: + if _name in obs_tags: + sso_names.append(_name) + if len(sso_names) == 0: + raise NameError('Could not find sso_name from observation tags') + else: + return sso_names +def main_one_wafer(configs, obs_id, wafer_slot, sso_name=None, + restrict_dets_for_debug=False): if type(configs) == str: configs = yaml.safe_load(open(configs, "r")) # Derive parameters from config file + # required parameters ctx = core.Context(configs.get('context_file')) - if single_det_maps_dir is None: - single_det_maps_dir = configs.get('single_det_maps_dir') - if map_based_result_dir is None: - map_based_result_dir = configs.get('map_based_result_dir') - if tod_based_result_dir is None: - tod_based_result_dir = configs.get('tod_based_result_dir') + single_det_maps_dir = configs.get('single_det_maps_dir') + result_dir = configs.get('result_dir') optics_config_fn = configs.get('optics_config_fn') + save_normal_roll = configs.get('save_normal_roll') + save_force_zero_roll = configs.get('save_force_zero_roll') + + # optional parameters xieta_bs_offset = configs.get('xieta_bs_offset', [0., 0.]) wafer_mask_deg = configs.get('wafer_mask_deg', 8.) res_deg = configs.get('res_deg', 0.3) edge_avoidance_deg = configs.get('edge_avoidance_deg', 0.3) - save_normal_roll = configs.get('save_normal_roll', True) - save_force_zero_roll = configs.get('save_force_zero_roll', True) - # parameters for tod tuning - tune_by_tod = configs.get('tune_by_tod') - if tune_by_tod: - tod_ds_factor = configs.get('tod_ds_factor') - tod_mask_deg = configs.get('tod_mask_deg') - tod_fit_func_name = configs.get('tod_fit_func_name') - tod_max_non_linear_order = configs.get('tod_max_non_linear_order') - tod_fwhm_init_deg = configs.get('tod_fwhm_init_deg') - tod_error_estimation_method = configs.get('tod_error_estimation_method') - tod_flag_name_rms_calc = configs.get('tod_flag_name_rms_calc') - tod_flag_rms_calc_exclusive = configs.get('tod_flag_rms_calc_exclusive') - - - # If sso_name is not specified, get sso name from observation tags - obs_tags = ctx.obsdb.get(obs_id, tags=True)['tags'] if sso_name is None: - known_source_names = ['moon', 'jupiter'] - for _source_name in known_source_names: - if _source_name in obs_tags: - sso_name = _source_name - if _source_name is None: - raise ValueError('sso_name is not specified') - + logger.info('deriving sso_name from observation tag') + obs_tags = ctx.obsdb.get(obs_id, tags=True)['tags'] + sso_names = _get_sso_names_from_tags(ctx, obs_id) + sso_name = sso_names[0] + if len(sso_names) >= 2: + logger.info(f'sso_names of {sso_names} are found from observation tags.' + + f'Processing only {sso_name}') + # Load data logger.info('loading data') meta = ctx.get_meta(obs_id, dets={'wafer_slot': wafer_slot}) @@ -88,125 +83,203 @@ def main_one_wafer(configs, obs_id, wafer_slot, logger.info(f'Saving map-based pointing results') fp_rset_map_based = mbp.get_xieta_from_maps(map_hdf, save=True, - output_dir=map_based_result_dir, - filename=result_filename, - force_zero_roll=False, - edge_avoidance = edge_avoidance_deg*coords.DEG) - - if tune_by_tod: - logger.info(f'Making tod-based pointing results') - up.wrap_fp_rset(tod, fp_rset_map_based) - fp_rset_tod_based = up.update_xieta( tod, - sso_name=sso_name, - fp_hdf_file=None, - force_zero_roll=False, - pipe=None, - ds_factor=tod_ds_factor, - mask_deg=tod_mask_deg, - fit_func_name = tod_fit_func_name, - max_non_linear_order = tod_max_non_linear_order, - fwhm_init_deg = tod_fwhm_init_deg, - error_estimation_method=tod_error_estimation_method, - flag_name_rms_calc = tod_flag_name_rms_calc, - flag_rms_calc_exclusive = tod_flag_rms_calc_exclusive, - ) - os.makedirs(tod_based_result_dir, exist_ok=True) - write_dataset(fp_rset_tod_based, - filename=os.path.join(tod_based_result_dir, f'focal_plane_{obs_id}_{wafer_slot}.hdf'), - address='focal_plane', - overwrite=True) + output_dir=result_dir, + filename=result_filename, + force_zero_roll=False, + edge_avoidance = edge_avoidance_deg*coords.DEG) if save_force_zero_roll: logger.info(f'Saving map-based pointing results (force-zero-roll)') - map_based_result_dir_force_zero_roll = map_based_result_dir + '_force_zero_roll' + result_dir_force_zero_roll = result_dir + '_force_zero_roll' fp_rset_map_based_force_zero_roll = mbp.get_xieta_from_maps(map_hdf, save=True, - output_dir=map_based_result_dir_force_zero_roll, + output_dir=result_dir_force_zero_roll, filename=result_filename, force_zero_roll=True, edge_avoidance = edge_avoidance_deg*coords.DEG) - if tune_by_tod: - logger.info(f'Making tod-based pointing results (force-zero-roll)') - up.wrap_fp_rset(tod, fp_rset_map_based_force_zero_roll) - tod_based_result_dir_force_zero_roll = tod_based_result_dir + '_force_zero_roll' - fp_rset_tod_based_force_zero_roll = up.update_xieta( tod, - sso_name=sso_name, - fp_hdf_file=None, - force_zero_roll=False, - pipe=None, - ds_factor=tod_ds_factor, - mask_deg=tod_mask_deg, - fit_func_name = tod_fit_func_name, - max_non_linear_order = tod_max_non_linear_order, - fwhm_init_deg = tod_fwhm_init_deg, - error_estimation_method=tod_error_estimation_method, - flag_name_rms_calc = tod_flag_name_rms_calc, - flag_rms_calc_exclusive = tod_flag_rms_calc_exclusive, - ) - os.makedirs(tod_based_result_dir_force_zero_roll, exist_ok=True) - write_dataset(fp_rset_tod_based_force_zero_roll, - filename=os.path.join(tod_based_result_dir_force_zero_roll, f'focal_plane_{obs_id}_{wafer_slot}.hdf'), - address='focal_plane', - overwrite=True) return -def main(configs, obs_id, wafer_slots, - sso_name=None, - single_det_maps_dir=None, map_based_result_dir=None, tod_based_result_dir=None, - tune_by_tod=None, hit_time_threshold=1200, hit_circle_r_deg=7.0, - restrict_dets_for_debug=False): - - logger.info('get wafer_slots which hit the source because wafer_slots are not specified') - if wafer_slots is None: - if type(configs) == str: - configs = yaml.safe_load(open(configs, "r")) - - ctx = core.Context(configs.get('context_file')) - optics_config_fn = configs.get('optics_config_fn') +def main_one_wafer_dummy(configs, obs_id, wafer_slot, restrict_dets_for_debug=False): + if type(configs) == str: + configs = yaml.safe_load(open(configs, "r")) + ctx = core.Context(configs.get('context_file')) + single_det_maps_dir = configs.get('single_det_maps_dir') + result_dir = configs.get('result_dir') + save_normal_roll = configs.get('save_normal_roll', True) + save_force_zero_roll = configs.get('save_force_zero_roll', True) + + meta = ctx.get_meta(obs_id, dets={'wafer_slot': wafer_slot}) + if restrict_dets_for_debug is not False: + meta.restrict('dets', meta.dets.vals[:restrict_dets_for_debug]) + result_filename = f'focal_plane_{obs_id}_{wafer_slot}.hdf' + + fp_rset_dummy_map_based = metadata.ResultSet(keys=['dets:readout_id', 'xi', 'eta', 'gamma', 'R2']) + for det in meta.dets.vals: + fp_rset_dummy_map_based.rows.append((det, np.nan, np.nan, np.nan, np.nan)) + if save_normal_roll: + os.makedirs(result_dir, exist_ok=True) + write_dataset(fp_rset_dummy_map_based, + filename=os.path.join(result_dir, result_filename), + address='focal_plane', + overwrite=True) + + if save_force_zero_roll: + result_dir_force_zero_roll = result_dir + '_force_zero_roll' + os.makedirs(result_dir_force_zero_roll, exist_ok=True) + write_dataset(fp_rset_dummy_map_based, + filename=os.path.join(result_dir_force_zero_roll, result_filename), + address='focal_plane', + overwrite=True) + return + +def combine_pointings(pointing_result_files): + combined_dict = {} + for file in pointing_result_files: + rset = read_dataset(file, 'focal_plane') + for row in rset[:]: + if row['dets:readout_id'] not in combined_dict.keys(): + combined_dict[row['dets:readout_id']] = {} + combined_dict[row['dets:readout_id']]['xi'] = row['xi'] + combined_dict[row['dets:readout_id']]['eta'] = row['eta'] + combined_dict[row['dets:readout_id']]['gamma'] = row['gamma'] + combined_dict[row['dets:readout_id']]['R2'] = row['R2'] + + focal_plane = metadata.ResultSet(keys=['dets:readout_id', 'xi', 'eta', 'gamma', 'R2']) + + for det, val in combined_dict.items(): + focal_plane.rows.append((det, val['xi'], val['eta'], val['gamma'], val['R2'])) + return focal_plane + +def main_one_obs(configs, obs_id, sso_name=None, + restrict_dets_for_debug=False): + if type(configs) == str: + configs = yaml.safe_load(open(configs, "r")) + ctx = core.Context(configs.get('context_file')) + optics_config_fn = configs.get('optics_config_fn') + + result_dir = configs.get('result_dir') + save_normal_roll = configs.get('save_normal_roll') + save_force_zero_roll = configs.get('save_force_zero_roll') + + hit_time_threshold = configs.get('hit_time_threshold', 600) + hit_circle_r_deg = configs.get('hit_circle_r_deg', 7.0) + + if sso_name is None: + logger.info('deriving sso_name from observation tag') obs_tags = ctx.obsdb.get(obs_id, tags=True)['tags'] - if sso_name is None: - known_source_names = ['moon', 'jupiter'] - for _source_name in known_source_names: - if _source_name in obs_tags: - sso_name = _source_name - if _source_name is None: - raise ValueError('sso_name is not specified') - - wafer_slots = [] - tod = ctx.get_obs(obs_id, dets=[]) - for ws in [f'ws{i}' for i in range(7)]: - hit_time = mbp.get_rough_hit_time(tod, wafer_slot=ws, sso_name=sso_name, circle_r_deg=hit_circle_r_deg, - optics_config_fn=optics_config_fn) - logger.info(f'hit_time for {ws} is {hit_time:.1f} [sec]') - if hit_time > hit_time_threshold: - wafer_slots.append(ws) - assert np.all(np.array(wafer_slots, dtype='U2') == 'ws') - - logger.info(f'wafer_slots which pointing calculated: {wafer_slots}') - for wafer_slot in wafer_slots: + sso_names = _get_sso_names_from_tags(ctx, obs_id) + sso_name = sso_names[0] + if len(sso_names) >= 2: + logger.info(f'sso_names of {sso_names} are found from observation tags.' + + f'Processing only {sso_name}') + + tod = ctx.get_obs(obs_id, dets=[]) + streamed_wafer_slots = ['ws{}'.format(index) for index, bit in enumerate(obs_id.split('_')[-1]) if bit == '1'] + processed_wafer_slots = [] + skipped_wafer_slots = [] + + for ws in streamed_wafer_slots: + hit_time = mbp.get_rough_hit_time(tod, wafer_slot=ws, sso_name=sso_name, circle_r_deg=hit_circle_r_deg, + optics_config_fn=optics_config_fn) + logger.info(f'hit_time for {ws} is {hit_time:.1f} [sec]') + if hit_time > hit_time_threshold: + processed_wafer_slots.append(ws) + else: + skipped_wafer_slots.append(ws) + + logger.info(f'wafer_slots which pointing calculated: {processed_wafer_slots}') + for wafer_slot in processed_wafer_slots: + logger.info(f'Processing {obs_id}, {wafer_slot}') main_one_wafer(configs=configs, obs_id=obs_id, wafer_slot=wafer_slot, sso_name=sso_name, - single_det_maps_dir=single_det_maps_dir, - map_based_result_dir=map_based_result_dir, - tod_based_result_dir=tod_based_result_dir, - tune_by_tod=tune_by_tod, restrict_dets_for_debug=restrict_dets_for_debug) + + logger.info(f'create dummy hdf for non-hitting wafer: {skipped_wafer_slots}') + for wafer_slot in skipped_wafer_slots: + main_one_wafer_dummy(configs=configs, + obs_id=obs_id, + wafer_slot=wafer_slot, + restrict_dets_for_debug=restrict_dets_for_debug) + + logger.info('making combined result') + if save_normal_roll: + pointing_result_files = glob.glob(os.path.join(result_dir, f'focal_plane_{obs_id}_ws[0-6].hdf')) + fp_rset_full = combine_pointings(pointing_result_files) + fp_rset_full_file = os.path.join(os.path.join(result_dir, f'focal_plane_{obs_id}_all.hdf')) + write_dataset(fp_rset_full, filename=fp_rset_full_file, + address='focal_plane', overwrite=True) + + + if save_force_zero_roll: + result_dir_force_zero_roll = result_dir + '_force_zero_roll' + pointing_result_files = glob.glob(os.path.join(result_dir_force_zero_roll, f'focal_plane_{obs_id}_ws[0-6].hdf')) + fp_rset_full = combine_pointings(pointing_result_files) + fp_rset_full_file = os.path.join(os.path.join(result_dir_force_zero_roll, f'focal_plane_{obs_id}_all.hdf')) + write_dataset(fp_rset_full, filename=fp_rset_full_file, + address='focal_plane', overwrite=True) + + + return + +def main(configs, min_ctime=None, max_ctime=None, update_delay=None, + obs_id=None, wafer_slot=None, sso_name=None, restrict_dets_for_debug=False): + if (min_ctime is None) and (update_delay is not None): + # If min_ctime is provided it will use that.. + # Otherwise it will use update_delay to set min_ctime. + min_ctime = int(time.time()) - update_delay*86400 + + if type(configs) == str: + configs = yaml.safe_load(open(configs, "r")) + ctx = core.Context(configs.get('context_file')) + + if obs_id is None: + query_text = configs.get('query_text', None) + query_tags = configs.get('query_tags', None) + tot_query = "and " + if query_text is not None: + tot_query += f"{query_text} and " + if min_ctime is not None: + tot_query += f"timestamp>={min_ctime} and " + if max_ctime is not None: + tot_query += f"timestamp<={max_ctime} and " + tot_query = tot_query[4:-4] + if tot_query == "": + tot_query = "1" + + logger.info(f'tot_query: {tot_query}') + obs_list= ctx.obsdb.query(tot_query, query_tags) + + for obs in obs_list: + obs_id = obs['obs_id'] + logger.info(f'Processing {obs_id}') + main_one_obs(configs=configs, obs_id=obs_id, + restrict_dets_for_debug=restrict_dets_for_debug) + + elif obs_id is not None: + if wafer_slot is None: + main_one_obs(configs=configs, obs_id=obs_id, sso_name=sso_name, + restrict_dets_for_debug=restrict_dets_for_debug) + else: + main_one_wafer(configs=configs, obs_id=obs_id, wafer_slot=wafer_slot, sso_name=sso_name, + restrict_dets_for_debug=restrict_dets_for_debug) def get_parser(): parser = argparse.ArgumentParser(description="Process TOD data and update pointing") parser.add_argument("configs", type=str, help="Path to the configuration file") - parser.add_argument("obs_id", type=str, help="Observation id") - parser.add_argument("--wafer_slots", nargs='*', default=None, help="Wafer slots to be processed") - parser.add_argument("--sso_name", type=str, default=None, help="Name of solar system object (e.g., 'moon', 'jupiter')") - parser.add_argument("--single_det_maps_dir", type=str, default=None, help="Directory to save single detector maps") - parser.add_argument("--map_based_result_dir", type=str, default=None, help="Directory to save map-based pointing results") - parser.add_argument("--tod_based_result_dir", type=str, default=None, help="Directory to save TOD-based pointing results") - parser.add_argument("--hit_time_threshold", type=float, default=1200, - help="Minimum hit time. If calculated wafer hit time is smaller than that, pointing calculation for that wafer is skipped") - parser.add_argument("--hit_circle_r_deg", type=float, default=7., - help="circle radius for wafer hit time calculation") + parser.add_argument('--min_ctime', type=int, help="Minimum timestamp for the beginning of an observation list") + parser.add_argument('--max_ctime', type=int, help="Maximum timestamp for the beginning of an observation list") + parser.add_argument('--update-delay', type=int, help="Number of days (unit is days) in the past to start observation list.") + parser.add_argument("--obs_id", type=str, + help="Specific observation obs_id to process. If provided, overrides other filtering parameters.") + + parser.add_argument("--wafer_slot", type=str, default=None, + help="Wafer slot to be processed (e.g., 'ws0', 'ws3'). Valid only when obs_id is specified.") + + parser.add_argument("--sso_name", type=str, default=None, + help="Name of solar system object (e.g., 'moon', 'jupiter'). If not specified, get sso_name from observation tags. "\ + + "Valid only when obs_id is specified") parser.add_argument("--restrict_dets_for_debug", type=int, default=False) return parser diff --git a/sotodlib/site_pipeline/update_pointing.py b/sotodlib/site_pipeline/update_pointing.py index 9c98c2f69..7f1c73b31 100644 --- a/sotodlib/site_pipeline/update_pointing.py +++ b/sotodlib/site_pipeline/update_pointing.py @@ -3,8 +3,10 @@ import yaml import h5py import argparse +import time +import glob from tqdm import tqdm -import scipy + from scipy.optimize import curve_fit from sotodlib.core import metadata from sotodlib.io.metadata import read_dataset, write_dataset @@ -19,6 +21,17 @@ from sotodlib.preprocess import Pipeline logger = util.init_logger(__name__, 'update_pointing: ') +def _get_sso_names_from_tags(ctx, obs_id, candidate_names=['moon', 'jupiter']): + obs_tags = ctx.obsdb.get(obs_id, tags=True)['tags'] + sso_names = [] + for _name in candidate_names: + if _name in obs_tags: + sso_names.append(_name) + if len(sso_names) == 0: + raise NameError('Could not find sso_name from observation tags') + else: + return sso_names + def gaussian2d_nonlin(xieta, xi0, eta0, fwhm_xi, fwhm_eta, phi, a, nonlin_coeffs): """ An Gaussian beam model with non-linear response Args @@ -80,20 +93,19 @@ def wrap_fp_from_hdf(tod, fp_hdf_file, data_set='focal_plane'): def update_xieta(tod, - sso_name='moon', + sso_name=None, fp_hdf_file=None, - save_dir=None, - pipe=None, force_zero_roll=False, + pipe=None, ds_factor=10, mask_deg=3, fit_func_name = 'gaussian2d_nonlin', max_non_linear_order = 1, fwhm_init_deg = 0.5, - error_estimation_method='force_one_redchi2', # rms_from_data + error_estimation_method='force_one_redchi2', flag_name_rms_calc = 'source', flag_rms_calc_exclusive = True, - save=True, ): + ): """ Update xieta parameters for each detector by TOD fitting of a point source observation. @@ -123,7 +135,7 @@ def update_xieta(tod, - fwhm_init_deg (float): Initial guess for full width at half maximum in degrees. Default is 0.5. - error_estimation_method (str): - Method for error estimation. Default is 'rms_from_data'. 'rms_from_data' and 'force_one_redchi2' are supported. + Method for error estimation. Default is 'force_one_redchi2'. 'force_one_redchi2' and 'rms_from_data' are supported. If 'rms_from_data', errorbar of each data point is set by root-mean-square of the data points flaged by 'flag_name_rms_calc', and errorbar of xi,eta is set from the fit covariance matrix. If 'force_one_redchi2', the errorbar of (xi,eta) is equivalent the case if the error bar of each data point is set as the reduced chi-square is equal to unity. @@ -131,8 +143,6 @@ def update_xieta(tod, Name of the flag used for RMS calculation. Default is 'source'. - flag_rms_calc_exclusive (bool): Flag indicating whether the RMS calculation is exclusive to the flag. Default is True. - - save (bool): - Flag indicating whether to save the updated focal plane data. Default is True. Returns: - focal_plane (ResultSet): ResultSet containing updated xieta parameters for each detector. @@ -270,9 +280,8 @@ def update_xieta(tod, return focal_plane -def main_one_wafer(configs, obs_id, wafer_slot, - sso_name=None, fp_hdf_file=None, fp_hdf_dir=None, - save_dir=None, restrict_dets_for_debug=False): +def main_one_wafer(configs, obs_id, wafer_slot, sso_name=None, + restrict_dets_for_debug=False): if type(configs) == str: configs = yaml.safe_load(open(configs, "r")) @@ -280,47 +289,45 @@ def main_one_wafer(configs, obs_id, wafer_slot, ctx = core.Context(configs.get('context_file')) # get prior + fp_hdf_file = configs.get('fp_hdf_file', None) + fp_hdf_dir = configs.get('fp_hdf_dir', None) if fp_hdf_file is None: - fp_hdf_file = configs.get('fp_hdf_file', None) - if fp_hdf_dir is None: - fp_hdf_dir = configs.get('fp_hdf_dir', None) - if fp_hdf_file is None: - if fp_hdf_dir is None: - pass - else: + if fp_hdf_dir is not None: fp_hdf_file = os.path.join(fp_hdf_dir, f'focal_plane_{obs_id}_{wafer_slot}.hdf') if not os.path.exists(fp_hdf_file): fp_hdf_file = None - - if save_dir is None: - save_dir = configs.get('save_dir', None) + + result_dir = configs.get('result_dir') + force_zero_roll = configs.get('force_zero_roll', True) + if force_zero_roll: + result_dir = result_dir + '_force_zero_roll' # get sso_name if it is not specified - obs_tags = ctx.obsdb.get(obs_id, tags=True)['tags'] if sso_name is None: - known_source_names = ['moon', 'jupiter'] - for _source_name in known_source_names: - if _source_name in obs_tags: - sso_name = _source_name - if _source_name is None: - raise ValueError('sso_name is not specified') + logger.info('deriving sso_name from observation tag') + obs_tags = ctx.obsdb.get(obs_id, tags=True)['tags'] + sso_names = _get_sso_names_from_tags(ctx, obs_id) + sso_name = sso_names[0] + if len(sso_names) >= 2: + logger.info(f'sso_names of {sso_names} are found from observation tags.' + + f'Processing only {sso_name}') # construct pipeline from configs - pipe = Pipeline(configs["process_pipe"]) + pipe = Pipeline(configs["process_pipe"], logger=logger) for pipe_component in pipe: if pipe_component.name == 'compute_source_flags': pipe_component.process_cfgs['center_on'] = sso_name # Other parameters force_zero_roll = configs.get('force_zero_roll') - ds_factor = configs.get('ds_factor') - mask_deg = configs.get('mask_deg') - fit_func_name = configs.get('fit_func_name') - max_non_linear_order = configs.get('max_non_linear_order') - fwhm_init_deg = configs.get('fwhm_init_deg') - error_estimation_method = configs.get('error_estimation_method') - flag_name_rms_calc = configs.get('flag_name_rms_calc') - flag_rms_calc_exclusive = configs.get('flag_rms_calc_exclusive') + ds_factor = configs.get('ds_factor', 20) + mask_deg = configs.get('mask_deg', 3.0) + fit_func_name = configs.get('fit_func_name', 'gaussian2d_nonlin') + max_non_linear_order = configs.get('max_non_linear_order', 2) + fwhm_init_deg = configs.get('fwhm_init_deg', 0.5) + error_estimation_method = configs.get('error_estimation_method', 'force_one_redchi2') + flag_name_rms_calc = configs.get('flag_name_rms_calc', 'source') + flag_rms_calc_exclusive = configs.get('flag_rms_calc_exclusive', True) # Load data @@ -346,69 +353,180 @@ def main_one_wafer(configs, obs_id, wafer_slot, flag_rms_calc_exclusive = flag_rms_calc_exclusive, ) - os.makedirs(save_dir, exist_ok=True) + os.makedirs(result_dir, exist_ok=True) write_dataset(focal_plane_rset, - filename=os.path.join(save_dir, f'focal_plane_{obs_id}_{wafer_slot}.hdf'), + filename=os.path.join(result_dir, f'focal_plane_{obs_id}_{wafer_slot}.hdf'), address='focal_plane', overwrite=True) return -def main(configs, obs_id, wafer_slots=None, - sso_name=None, fp_hdf_file=None, fp_hdf_dir=None, save_dir=None, - hit_time_threshold=1200, hit_circle_r_deg=7.0, - restrict_dets_for_debug=False): - logger.info('get wafer_slots which hit the source because wafer_slots are not specified') - if wafer_slots is None: - if type(configs) == str: - configs = yaml.safe_load(open(configs, "r")) - - ctx = core.Context(configs.get('context_file')) - optics_config_fn = configs.get('optics_config_fn') +def main_one_wafer_dummy(configs, obs_id, wafer_slot, restrict_dets_for_debug=False): + if type(configs) == str: + configs = yaml.safe_load(open(configs, "r")) + ctx = core.Context(configs.get('context_file')) + result_dir = configs.get('result_dir') + force_zero_roll = configs.get('force_zero_roll', True) + if force_zero_roll: + result_dir = result_dir + '_force_zero_roll' + + meta = ctx.get_meta(obs_id, dets={'wafer_slot': wafer_slot}) + if restrict_dets_for_debug is not False: + meta.restrict('dets', meta.dets.vals[:restrict_dets_for_debug]) + result_filename = f'focal_plane_{obs_id}_{wafer_slot}.hdf' + + fp_rset_dummy = metadata.ResultSet(keys=['dets:readout_id', 'xi', 'eta', 'gamma', + 'xi_err', 'eta_err', 'R2', 'redchi2']) + for det in meta.dets.vals: + fp_rset_dummy.rows.append((det, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan)) + os.makedirs(result_dir, exist_ok=True) + write_dataset(fp_rset_dummy, + filename=os.path.join(result_dir, result_filename), + address='focal_plane', + overwrite=True) + return + +def combine_pointings(pointing_result_files): + combined_dict = {} + for file in pointing_result_files: + rset = read_dataset(file, 'focal_plane') + for row in rset[:]: + if row['dets:readout_id'] not in combined_dict.keys(): + combined_dict[row['dets:readout_id']] = {} + combined_dict[row['dets:readout_id']]['xi'] = row['xi'] + combined_dict[row['dets:readout_id']]['eta'] = row['eta'] + combined_dict[row['dets:readout_id']]['gamma'] = row['gamma'] + combined_dict[row['dets:readout_id']]['xi_err'] = row['xi_err'] + combined_dict[row['dets:readout_id']]['eta_err'] = row['eta_err'] + combined_dict[row['dets:readout_id']]['R2'] = row['R2'] + combined_dict[row['dets:readout_id']]['redchi2'] = row['redchi2'] + + focal_plane = metadata.ResultSet(keys=['dets:readout_id', 'xi', 'eta', 'gamma', 'xi_err', 'eta_err', 'R2', 'redchi2']) + + for det, val in combined_dict.items(): + focal_plane.rows.append((det, val['xi'], val['eta'], val['gamma'], val['xi_err'], val['eta_err'], val['R2'], val['redchi2'])) + return focal_plane + +def main_one_obs(configs, obs_id, sso_name=None, + restrict_dets_for_debug=False): + if type(configs) == str: + configs = yaml.safe_load(open(configs, "r")) + ctx = core.Context(configs.get('context_file')) + result_dir = configs.get('result_dir') + force_zero_roll = configs.get('force_zero_roll', True) + if force_zero_roll: + result_dir = result_dir + '_force_zero_roll' + optics_config_fn = configs.get('optics_config_fn') + + hit_time_threshold = configs.get('hit_time_threshold', 600) + hit_circle_r_deg = configs.get('hit_circle_r_deg', 7.0) + + if sso_name is None: + logger.info('deriving sso_name from observation tag') obs_tags = ctx.obsdb.get(obs_id, tags=True)['tags'] - if sso_name is None: - known_source_names = ['moon', 'jupiter'] - for _source_name in known_source_names: - if _source_name in obs_tags: - sso_name = _source_name - if _source_name is None: - raise ValueError('sso_name is not specified') - - wafer_slots = [] - tod = ctx.get_obs(obs_id, dets=[]) - for ws in [f'ws{i}' for i in range(7)]: - hit_time = mbp.get_rough_hit_time(tod, wafer_slot=ws, sso_name=sso_name, circle_r_deg=hit_circle_r_deg, - optics_config_fn=optics_config_fn) - logger.info(f'hit_time for {ws} is {hit_time:.1f} [sec]') - if hit_time > hit_time_threshold: - wafer_slots.append(ws) - assert np.all(np.array(wafer_slots, dtype='U2') == 'ws') - - logger.info(f'wafer_slots which pointing calculated: {wafer_slots}') - for wafer_slot in wafer_slots: - main_one_wafer(configs, - obs_id, - wafer_slot, + sso_names = _get_sso_names_from_tags(ctx, obs_id) + sso_name = sso_names[0] + if len(sso_names) >= 2: + logger.info(f'sso_names of {sso_names} are found from observation tags.' + + f'Processing only {sso_name}') + + tod = ctx.get_obs(obs_id, dets=[]) + streamed_wafer_slots = ['ws{}'.format(index) for index, bit in enumerate(obs_id.split('_')[-1]) if bit == '1'] + processed_wafer_slots = [] + skipped_wafer_slots = [] + for ws in streamed_wafer_slots: + hit_time = mbp.get_rough_hit_time(tod, wafer_slot=ws, sso_name=sso_name, circle_r_deg=hit_circle_r_deg, + optics_config_fn=optics_config_fn) + logger.info(f'hit_time for {ws} is {hit_time:.1f} [sec]') + if hit_time > hit_time_threshold: + processed_wafer_slots.append(ws) + else: + skipped_wafer_slots.append(ws) + + logger.info(f'wafer_slots which pointing calculated: {processed_wafer_slots}') + for wafer_slot in processed_wafer_slots: + logger.info(f'Processing {obs_id}, {wafer_slot}') + main_one_wafer(configs=configs, + obs_id=obs_id, + wafer_slot=wafer_slot, sso_name=sso_name, - fp_hdf_file=fp_hdf_file, - fp_hdf_dir=fp_hdf_dir, - save_dir=save_dir, restrict_dets_for_debug=restrict_dets_for_debug) + + logger.info(f'create dummy hdf for non-hitting wafer: {skipped_wafer_slots}') + for wafer_slot in skipped_wafer_slots: + main_one_wafer_dummy(configs=configs, + obs_id=obs_id, + wafer_slot=wafer_slot, + restrict_dets_for_debug=restrict_dets_for_debug) + + logger.info('making combined result') + pointing_result_files = glob.glob(os.path.join(result_dir, f'focal_plane_{obs_id}_ws[0-6].hdf')) + fp_rset_full = combine_pointings(pointing_result_files) + fp_rset_full_file = os.path.join(os.path.join(result_dir, f'focal_plane_{obs_id}_all.hdf')) + write_dataset(fp_rset_full, filename=fp_rset_full_file, + address='focal_plane', overwrite=True) + +def main(configs, min_ctime=None, max_ctime=None, update_delay=None, + obs_id=None, wafer_slot=None, sso_name=None, restrict_dets_for_debug=False): + if (min_ctime is None) and (update_delay is not None): + # If min_ctime is provided it will use that.. + # Otherwise it will use update_delay to set min_ctime. + min_ctime = int(time.time()) - update_delay*86400 + + if type(configs) == str: + configs = yaml.safe_load(open(configs, "r")) + ctx = core.Context(configs.get('context_file')) + + if obs_id is None: + query_text = configs.get('query_text', None) + query_tags = configs.get('query_tags', None) + tot_query = "and " + if query_text is not None: + tot_query += f"{query_text} and " + if min_ctime is not None: + tot_query += f"timestamp>={min_ctime} and " + if max_ctime is not None: + tot_query += f"timestamp<={max_ctime} and " + tot_query = tot_query[4:-4] + if tot_query == "": + tot_query = "1" + + logger.info(f'tot_query: {tot_query}') + obs_list= ctx.obsdb.query(tot_query, query_tags) + + for obs in obs_list: + obs_id = obs['obs_id'] + logger.info(f'Processing {obs_id}') + main_one_obs(configs=configs, obs_id=obs_id, + restrict_dets_for_debug=restrict_dets_for_debug) + + elif obs_id is not None: + if wafer_slot is None: + main_one_obs(configs=configs, obs_id=obs_id, sso_name=sso_name, + restrict_dets_for_debug=restrict_dets_for_debug) + else: + main_one_wafer(configs=configs, obs_id=obs_id, wafer_slot=wafer_slot, sso_name=sso_name, + restrict_dets_for_debug=restrict_dets_for_debug) return def get_parser(): parser = argparse.ArgumentParser(description="Get updated result of pointings with tod-based results") parser.add_argument("configs", type=str, help="Path to the configuration file") - parser.add_argument("obs_id", type=str, help="Observation ID.") - parser.add_argument("--wafer_slots", nargs='*', default=None, help="Wafer slots to be processed") - parser.add_argument("--sso_name", type=str, default=None, help="Name of the Solar System Object (SSO).") - parser.add_argument("--fp_hdf_file", type=str, default=None, help="File path to the focal_plane hdf file used as a prior") - parser.add_argument("--fp_hdf_dir", type=str, default=None, - help="Directory path where focal_plane hdf file of each observation are stored. Used only fp_hdf_file is not specified.") - parser.add_argument("--save_dir", type=str, help="Directory to save the result.") - parser.add_argument("--restrict_dets_for_debug", type=int, help="Flag to restrict the number of detectors.") + parser.add_argument('--min_ctime', type=int, help="Minimum timestamp for the beginning of an observation list") + parser.add_argument('--max_ctime', type=int, help="Maximum timestamp for the beginning of an observation list") + parser.add_argument('--update-delay', type=int, help="Number of days (unit is days) in the past to start observation list.") + parser.add_argument("--obs_id", type=str, + help="Specific observation obs_id to process. If provided, overrides other filtering parameters.") + + parser.add_argument("--wafer_slot", type=str, default=None, + help="Wafer slot to be processed (e.g., 'ws0', 'ws3'). Valid only when obs_id is specified.") + + parser.add_argument("--sso_name", type=str, default=None, + help="Name of solar system object (e.g., 'moon', 'jupiter'). If not specified, get sso_name from observation tags. "\ + + "Valid only when obs_id is specified") + parser.add_argument("--restrict_dets_for_debug", type=int, default=False) return parser if __name__ == '__main__': From 2da796509a015182df4d0f33f46f9992c1bd859f Mon Sep 17 00:00:00 2001 From: tterasaki Date: Fri, 10 May 2024 05:11:48 +0000 Subject: [PATCH 011/132] removed combine_focal_plane.py which is no longer used --- .../site_pipeline/combine_focal_planes.py | 130 ------------------ 1 file changed, 130 deletions(-) delete mode 100644 sotodlib/site_pipeline/combine_focal_planes.py diff --git a/sotodlib/site_pipeline/combine_focal_planes.py b/sotodlib/site_pipeline/combine_focal_planes.py deleted file mode 100644 index b8a1184a4..000000000 --- a/sotodlib/site_pipeline/combine_focal_planes.py +++ /dev/null @@ -1,130 +0,0 @@ -import os -import re -import glob -import numpy as np - -from sotodlib.core import metadata -from sotodlib.io.metadata import write_dataset, read_dataset - -from sotodlib.site_pipeline import util -logger = util.init_logger(__name__, 'combine_focal_planes: ') - -def combine_pointings(pointing_result_files, method='highest_R2', R2_threshold=0.3, - save=False, output_dir=None, save_name=None): - combined_dict = {} - for file in pointing_result_files: - rset = read_dataset(file, 'focal_plane') - for row in rset[:]: - if row['dets:readout_id'] not in combined_dict.keys(): - combined_dict[row['dets:readout_id']] = {} - combined_dict[row['dets:readout_id']]['band'] = row['band'] - combined_dict[row['dets:readout_id']]['channel'] = row['channel'] - - combined_dict[row['dets:readout_id']]['R2'] = np.atleast_1d([]) - combined_dict[row['dets:readout_id']]['xi'] = np.atleast_1d([]) - combined_dict[row['dets:readout_id']]['eta'] = np.atleast_1d([]) - combined_dict[row['dets:readout_id']]['gamma'] = np.atleast_1d([]) - - combined_dict[row['dets:readout_id']]['R2'] = np.append(combined_dict[row['dets:readout_id']]['R2'], row['R2']) - combined_dict[row['dets:readout_id']]['xi'] = np.append(combined_dict[row['dets:readout_id']]['xi'], row['xi']) - combined_dict[row['dets:readout_id']]['eta'] = np.append(combined_dict[row['dets:readout_id']]['eta'], row['eta']) - combined_dict[row['dets:readout_id']]['gamma'] = np.append(combined_dict[row['dets:readout_id']]['gamma'], row['gamma']) - - focal_plane = metadata.ResultSet(keys=['dets:readout_id', 'band', 'channel', 'R2', 'xi', 'eta', 'gamma']) - for det, val in combined_dict.items(): - band = int(val['band']) - channel = int(val['channel']) - - mask = val['R2'] > R2_threshold - if np.all(~mask): - xi, eta, gamma, R2 = np.nan, np.nan, np.nan, np.nan - else: - if method == 'highest_R2': - idx = np.argmax(val['R2'][mask]) - xi, eta, gamma, R2 = val['xi'][mask][idx], val['eta'][mask][idx], val['gamma'][mask][idx], val['R2'][mask][idx] - elif method == 'mean': - xi, eta, gamma = np.mean(val['xi'][mask]), np.mean(val['eta'][mask]), np.mean(val['gamma'][mask]) - R2 = np.nan - elif method == 'median': - xi, eta, gamma = np.median(val['xi'][mask]), np.median(val['eta'][mask]), np.median(val['gamma'][mask]) - R2 = np.nan - else: - raise ValueError('Not supported method. Supported methods are `highest_R2`, `mean` or `median`') - focal_plane.rows.append((det, band, channel, R2, xi, eta, gamma)) - if save: - if output_dir is None: - output_dir = os.path.join(os.getcwd(), 'combined_pointing_results') - if not os.path.exists(output_dir): - os.makedirs(output_dir) - if save_name is None: - ctimes = np.atleast_1d([]) - wafer_slots = np.atleast_1d([]) - for file in pointing_result_files: - filename = os.path.basename(file) - match = re.search('\d{10}', filename) - ctime = int(match.group(0) if match else None) - match = re.search('ws\d{1}', filename) - ws = match.group(0) - ctimes = np.append(ctimes, ctime) - wafer_slots = np.append(wafer_slots, ws) - ctimes = ctimes.astype('int') - wafer_slots = np.sort(np.unique(wafer_slots.astype('U3'))) - save_name = f'focal_plane_{ctimes.min()}_{ctimes.max()}_' + ''.join(wafer_slots) + '.hdf' - - write_dataset(focal_plane, os.path.join(output_dir, save_name), 'focal_plane', overwrite=True) - return focal_plane - -def combine_onewafer_results(pointing_dir, ws, output_dir, filename=None, - method='highest_R2', R2_threshold=0.3,): - pointing_result_files = glob.glob(os.path.join(pointing_dir, f'focal_plane*{ws}.hdf')) - if filename is None: - filename = f'focal_plane_{ws}_combined.hdf' - _ = combine_pointings(pointing_result_files, save=True, output_dir=output_dir, save_name=filename) - return - -def combine_allwafer_results(pointing_dir, output_dir, filename=None, - method='highest_R2', R2_threshold=0.3,): - pointing_result_files = glob.glob(os.path.join(pointing_dir, 'focal_plane*.hdf')) - if filename is None: - filename = f'focal_plane_combined.hdf' - _ = combine_pointings(pointing_result_files, save=True, output_dir=output_dir, save_name=filename) - return - -def make_detabase(focal_plane_file, db_file,): - scheme = metadata.ManifestScheme().add_data_field('dataset') - db = metadata.ManifestDb(scheme=scheme) - db.add_entry({'dataset': 'focal_plane'}, filename=focal_plane_file) - db.to_file(db_file) - return - -def main(pointing_dir, output_dir=None, method='highest_R2', R2_threshold=0.3,): - if output_dir is None: - output_dir = os.path.join(os.getcwd(), 'combined_results') - - logger.info('Combining each wafer resluts') - wafer_slots = [f'ws{i}' for i in range(7)] - for ws in wafer_slots: - combine_onewafer_results(pointing_dir=pointing_dir, ws=ws, - output_dir=output_dir, filename=None, - method=method, R2_threshold=R2_threshold) - - logger.info('Combining all wafer resluts') - combine_allwafer_results(pointing_dir=pointing_dir, output_dir=output_dir, filename='focal_plane_combined.hdf', - method=method, R2_threshold=R2_threshold) - - logger.info('Making a database') - focal_plane_file = os.path.join(output_dir, 'focal_plane_combined.hdf') - db_file = os.path.join(output_dir, 'focal_plane_combined.sqlite') - make_detabase(focal_plane_file, db_file,) - return - -def get_parser(): - parser = argparse.ArgumentParser(description="Combine multiple result of pointing.") - parser.add_argument('--pointing_dir', type=str, required=True, help='Directory containing pointing result files.') - parser.add_argument('--output_dir', type=str, default=None, help='Directory to save combined results. Default is "combined_results".') - parser.add_argument('--method', type=str, default='highest_R2', choices=['highest_R2', 'mean', 'median'], help='Combination method. Default is "highest_R2".') - parser.add_argument('--R2_threshold', type=float, default=0.3, help='Threshold for R2 value. Default is 0.3.') - return parser - -if __name__ == '__main__': - util.main_launcher(main, get_parser) From 8d8fae46b9c7b03368bd0bbdbb288b5ed026ad2c Mon Sep 17 00:00:00 2001 From: tterasaki Date: Thu, 30 May 2024 09:04:47 +0000 Subject: [PATCH 012/132] removed planets.close() --- sotodlib/coords/map_based_pointing.py | 1 + sotodlib/coords/planets.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/sotodlib/coords/map_based_pointing.py b/sotodlib/coords/map_based_pointing.py index 23e814713..43305b37c 100644 --- a/sotodlib/coords/map_based_pointing.py +++ b/sotodlib/coords/map_based_pointing.py @@ -32,6 +32,7 @@ def get_planet_trajectry(tod, planet, _split=20, return_model=False): If return_model is False: array: Array of quaternions representing trajectry of the planet at each timestamp. """ + print(planet) timestamps_sparse = np.linspace(tod.timestamps[0], tod.timestamps[-1], _split) planet_az_sparse = np.zeros_like(timestamps_sparse) diff --git a/sotodlib/coords/planets.py b/sotodlib/coords/planets.py index 322cd7e66..0c96c40d2 100644 --- a/sotodlib/coords/planets.py +++ b/sotodlib/coords/planets.py @@ -303,7 +303,7 @@ def _get_astrometric(source_name, timestamp, site='_default'): sf_timestamp = timescale.from_datetime( datetime.datetime.fromtimestamp(timestamp, tz=skyfield_api.utc)) astrometric = observatory.at(sf_timestamp).observe(target) - planets.close() + #planets.close() return astrometric From 59f55ce515db4315b9b852b5a7beb6bbe4ac206e Mon Sep 17 00:00:00 2001 From: tterasaki Date: Fri, 31 May 2024 04:57:22 +0000 Subject: [PATCH 013/132] tuning for master branch --- sotodlib/preprocess/processes.py | 3 +++ sotodlib/site_pipeline/update_pointing.py | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/sotodlib/preprocess/processes.py b/sotodlib/preprocess/processes.py index f10cd4d49..9d3d72ceb 100644 --- a/sotodlib/preprocess/processes.py +++ b/sotodlib/preprocess/processes.py @@ -845,6 +845,9 @@ class SourceFlags(_Preprocess): """ name = "source_flags" + def process(self, aman, proc_aman): + tod_ops.flags.get_source_flags(aman, **self.process_cfgs) + def calc_and_save(self, aman, proc_aman): center_on = self.calc_cfgs.get('center_on', 'planet') # Get source from tags diff --git a/sotodlib/site_pipeline/update_pointing.py b/sotodlib/site_pipeline/update_pointing.py index 7f1c73b31..9af4fc96f 100644 --- a/sotodlib/site_pipeline/update_pointing.py +++ b/sotodlib/site_pipeline/update_pointing.py @@ -315,7 +315,7 @@ def main_one_wafer(configs, obs_id, wafer_slot, sso_name=None, # construct pipeline from configs pipe = Pipeline(configs["process_pipe"], logger=logger) for pipe_component in pipe: - if pipe_component.name == 'compute_source_flags': + if pipe_component.name == 'source_flags': pipe_component.process_cfgs['center_on'] = sso_name # Other parameters From 5b80e503cec9c8fa68d6cddf50d7d8076885fe13 Mon Sep 17 00:00:00 2001 From: tterasaki Date: Fri, 31 May 2024 06:21:39 +0000 Subject: [PATCH 014/132] fix preprocessing stuff --- sotodlib/preprocess/processes.py | 3 --- sotodlib/site_pipeline/update_pointing.py | 2 +- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/sotodlib/preprocess/processes.py b/sotodlib/preprocess/processes.py index 7998ac517..0b236c782 100644 --- a/sotodlib/preprocess/processes.py +++ b/sotodlib/preprocess/processes.py @@ -844,9 +844,6 @@ class SourceFlags(_Preprocess): .. autofunction:: sotodlib.tod_ops.flags.get_source_flags """ name = "source_flags" - - def process(self, aman, proc_aman): - tod_ops.flags.get_source_flags(aman, **self.process_cfgs) def calc_and_save(self, aman, proc_aman): center_on = self.calc_cfgs.get('center_on', 'planet') diff --git a/sotodlib/site_pipeline/update_pointing.py b/sotodlib/site_pipeline/update_pointing.py index 9af4fc96f..2098ebbd3 100644 --- a/sotodlib/site_pipeline/update_pointing.py +++ b/sotodlib/site_pipeline/update_pointing.py @@ -316,7 +316,7 @@ def main_one_wafer(configs, obs_id, wafer_slot, sso_name=None, pipe = Pipeline(configs["process_pipe"], logger=logger) for pipe_component in pipe: if pipe_component.name == 'source_flags': - pipe_component.process_cfgs['center_on'] = sso_name + pipe_component.calc_cfgs['center_on'] = sso_name # Other parameters force_zero_roll = configs.get('force_zero_roll') From 6e91879c17bf3f98fcf90367d0f1252a3d9538bd Mon Sep 17 00:00:00 2001 From: Elle Claire Shaw Date: Fri, 11 Oct 2024 11:17:08 -0700 Subject: [PATCH 015/132] Added script that solves satv1 pointing model parameters. --- .../site_pipeline/solve_pointing_model.py | 278 ++++++++++++++++++ 1 file changed, 278 insertions(+) create mode 100644 sotodlib/site_pipeline/solve_pointing_model.py diff --git a/sotodlib/site_pipeline/solve_pointing_model.py b/sotodlib/site_pipeline/solve_pointing_model.py new file mode 100644 index 000000000..218d9b36d --- /dev/null +++ b/sotodlib/site_pipeline/solve_pointing_model.py @@ -0,0 +1,278 @@ +import os, sys, pickle, math, h5py +import numpy as np +import argparse as ap +import so3g.proj.quat as quat +import lmfit +from lmfit import minimize, Parameters +import yaml +import logging + +from sotodlib.site_pipeline import util +from sotodlib import core +from sotodlib.coords import pointing_model as pm +from sotodlib.coords import fp_containers as fpc + +DEG = np.pi / 180.0 +ARCMIN = DEG / 60 + + +def _load_nom_centers(config): + # Load Nominal UFM Center Locations from centered focal_plane + ffp_path = config.get("ffp_path") + ufms = config.get("ufms") + nom_ufm_centers = np.zeros([1, 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)): + index = ufms.index(OT.focal_planes[ufm].stream_id) + nom_ufm_centers[0, index, :3] = OT.focal_planes[ufm].center + nom_ufm_centers = nom_ufm_centers[0] + + return nom_ufm_centers + + +# obsdb_entries = [ctx.obsdb.get(obsid) for obsid in filelist] +def _load_per_obs_data(config): + # Load per-observation UFM center data points and weights + # The per obs .h5 file a dict with obs_id for keys + per_obs_fps = config.get("per_obs_fps") + ufms = config.get("ufms") + rxs = fpc.Receiver.load_file(per_obs_fps) + if config.get("platform") == "satp1": + filelist = list(rxs.keys()) + # the following are known to be bad fits: + filelist = [ + item + for item in filelist + if "_1713" not in item and "1716423951" not in item + ] + else: + filelist = list(rxs.keys()) + obsidnum = np.array( + [filelist[id].split("_")[1] for id, _ in enumerate(filelist)], dtype=int + ) + obs_ufm_centers = np.zeros([len(filelist), 7, 3]) * np.nan + weights_ufm = np.zeros([len(filelist), 7]) + + 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) + weights_ufm = weights_ufm / 1720.0 + weights_ufm[weights_ufm < config.get("weight_cutoff")] = 0.0 + + return filelist, obs_ufm_centers, weights_ufm + + +def _load_obs_boresight(config, filelist): + # Load boresight elevation information from each observation + # Put into an axis manager + ctx = core.Context(config["context"]["path"]) + az_c = [ctx.obsdb.get(obsid)["az_center"] for obsid in filelist] + el_c = [ctx.obsdb.get(obsid)["el_center"] for obsid in filelist] + roll_c = [ctx.obsdb.get(obsid)["roll_center"] for obsid in filelist] + az_c = np.round(np.array(az_c), 4) + el_c = np.round(np.array(el_c), 4) + roll_c = np.round(np.array(roll_c), 4) + roll_c[np.where(roll_c == 0)[0]] = 0 # rounding gives negative 0 sometimes. + + ancil = core.AxisManager(core.IndexAxis("samps")) + ancil.wrap("az_enc", np.repeat(az_c, 7), [(0, "samps")]) + ancil.wrap("boresight_enc", np.repeat(-1 * roll_c, 7), [(0, "samps")]) + ancil.wrap("el_enc", np.repeat(el_c, 7), [(0, "samps")]) + + return ancil, roll_c + + +def _init_fit_params(config): + default_params = pm.defaults_sat_v1 + fixed_params = config.get("fixed_params") + # Initialize lmfit Parameter object + fit_params = Parameters() + for p in list(default_params.keys()): + fit_params.add(p, value=0.0, vary=True) + # Turn off various parameters depending on platform + for fix in fixed_params: + fit_params[fix].set(vary=False) + + return fit_params + + +def chi_sq(weights, dist): + N = np.identity(len(dist)) * weights + chi2 = dist.T * N * dist + return chi2 + + +def objective_model_func_lmfit(params, solver_aman, return_fit=False, weights=True): + if type(params) == lmfit.parameter.Parameters: + params = params.valuesdict() + xi_nom, eta_nom, gam_nom = solver_aman.nom_ufm_centers + az, el, roll = pm._get_sat_enc_radians(solver_aman.ancil) + az1, el1, roll1 = pm.model_sat_v1(params, az, el, roll) + ## Quat math is based on this equation: q_nomodel * q_det_data == q_model * q_det_true + q_nomodel = quat.rotation_lonlat(-az, el, 0) + q_model = quat.rotation_lonlat(-az1, el1, roll1) + q_det_true = quat.rotation_xieta(xi_nom, eta_nom, 0) + xi_mod, eta_mod, gamma_mod = quat.decompose_xieta(~q_nomodel * q_model * q_det_true) + xi_ffp, eta_ffp, gamma_ffp = solver_aman.ffp_ufm_center_fits + if return_fit: + return xi_mod, eta_mod, gamma_mod + else: + dist = [] + for i in range(len(xi_mod)): + dist.append(math.dist([xi_ffp[i], eta_ffp[i]], [xi_mod[i], eta_mod[i]])) + if weights: + return chi_sq(solver_aman.weights, np.array(dist)) + else: + return chi_sq(np.ones(len(dist)), np.array(dist)) + + +def get_RMS(model_xieta, data_xieta, weights): + diff = (model_xieta[0] / ARCMIN - data_xieta[0] / DEG * 60) ** 2 + ( + model_xieta[1] / ARCMIN - data_xieta[1] / DEG * 60 + ) ** 2 + return (np.nansum(diff * weights) / np.nansum(weights)) ** 0.5 + + +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 _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_data_field("dataset") + return core.metadata.ManifestDb(db_filename, scheme=scheme) + + +def main(): + # Read input parameters + parser = ap.ArgumentParser() + parser.add_argument("config_path", help="Location of the config file") + args = parser.parse_args() + + # Read relevant config file info + with open(args.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 + solution_version_tag = config.get("solution_version_tag") # e.g. YYMMDDr# + save_dir = os.path.join( + config.get("outdir"), f"{platform}_pointing_model_{solution_version_tag}" + ) + if not os.path.exists(save_dir): + os.makedirs(save_dir) + # savemeta_dir = os.path.join(config.get("savemeta_dir"), solution_version_tag) + # if not os.path.exists(savemeta_dir): + # os.makedirs(savemeta_dir, exists_ok=False) + + # Initialize Logger + logger = util.init_logger(__name__, "Solve pointing_model") + logpath = os.path.join(save_dir, "pointing_model.log") + logfile = logging.FileHandler(logpath) + logger.addHandler(logfile) + + # Load in focal_plane and boresigt data + nom_ufm_centers = _load_nom_centers(config) + logger.info("Loaded nominal UFM centers from %s: ", config.get("ffp_path")) + filelist, obs_ufm_centers, weights_ufm = _load_per_obs_data(config) + logger.info("Loaded per-obs FFP data from %s: ", config.get("per_obs_fps")) + logger.info("Including data from these obs:") + logger.info(filelist) + ancil, roll_c = _load_obs_boresight(config, filelist) + logger.info("Loaded boresight data from obs ids.") + + # Build Axis Managers + obs_info = core.AxisManager() + obs_info.wrap("obs_ids", np.array(filelist)) + + solver_aman = core.AxisManager(core.IndexAxis("samps")) + solver_aman.wrap("ancil", ancil) + solver_aman.wrap("obs_info", obs_info) + solver_aman.wrap("roll_c", np.repeat(roll_c, 7), [(0, "samps")]) + solver_aman.wrap( + "nom_ufm_centers", + np.repeat([nom_ufm_centers], len(filelist), axis=0) + .reshape(len(filelist) * 7, 3) + .T, + [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], + [(1, "samps")], + ) + solver_aman.wrap( + "ffp_ufm_center_fits", + obs_ufm_centers.reshape(len(filelist) * 7, 3).T, + [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], + [(1, "samps")], + ) + solver_aman.wrap("weights", weights_ufm.reshape(-1), [(0, "samps")]) + + weights_mask = np.where(solver_aman["weights"] == 0)[0] + solver_aman["ffp_ufm_center_fits"][:, weights_mask] = np.nan + + logger.info("Built axis manager") + + # Initialize Parameters to Fit with Model + fit_params = _init_fit_params(config) + + # Solve for Model Paramters + model_solved_params = lmfit.minimize( + objective_model_func_lmfit, + fit_params, + method="nelder", + nan_policy="omit", + args=(solver_aman, False, True), + ) + model_fits = objective_model_func_lmfit( + model_solved_params.params, solver_aman, return_fit=True + ) + + 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( + "RMS on fit: %f", + get_RMS(model_fits, solver_aman.ffp_ufm_center_fits, solver_aman.weights), + ) + + # Save fit results to the axis manager + modelfit_aman = core.AxisManager() + modelfit_aman.wrap("xi", model_fits[0]) + modelfit_aman.wrap("eta", model_fits[1]) + # modelfit_aman.wrap("gamma", model_fits[2]) + solver_aman.wrap("model_fits", modelfit_aman) + + param_aman = core.AxisManager() + for k in list(test_params.keys()): + param_aman.wrap(k, test_params[k]) + solver_aman.wrap("pointing_model", param_aman) + solver_aman.wrap( + "fit_rms", + get_RMS(model_fits, solver_aman.ffp_ufm_center_fits, solver_aman.weights), + ) + + # Save .h5 and ManifestDb + h5_rel = "pointing_model_data.h5" + h5_filename = os.path.join(save_dir, h5_rel) + solver_aman.save(h5_filename, overwrite=True) + dbfile = "db.sqlite" + db = _create_db(dbfile, save_dir) + db.add_entry({"dataset": "pointing_model"}, filename=h5_rel, replace=True) + db.to_file(os.path.join(save_dir, dbfile)) + +############ + +if __name__ == "__main__": + main() From 51093ed8b1d4a6c3f3ce5ef6d4fd123ecce8e22c Mon Sep 17 00:00:00 2001 From: Elle Claire Shaw Date: Mon, 21 Oct 2024 12:33:56 -0700 Subject: [PATCH 016/132] Make solve_pointing_model match site_pipeline standards. Added plotting functionality, added fit iteration, added documentation. --- docs/site_pipeline.rst | 126 +++ sotodlib/site_pipeline/cli.py | 4 +- .../site_pipeline/solve_pointing_model.py | 730 +++++++++++++++--- 3 files changed, 767 insertions(+), 93 deletions(-) diff --git a/docs/site_pipeline.rst b/docs/site_pipeline.rst index baee5ead1..709fb47a9 100644 --- a/docs/site_pipeline.rst +++ b/docs/site_pipeline.rst @@ -560,6 +560,132 @@ 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. +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 + + pointing_model_data.h5 + - 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 + + + + preprocess-tod -------------- This script is set up to run a preprocessing pipeline using the preprocess diff --git a/sotodlib/site_pipeline/cli.py b/sotodlib/site_pipeline/cli.py index a11ca65f1..6b6ec05cc 100644 --- a/sotodlib/site_pipeline/cli.py +++ b/sotodlib/site_pipeline/cli.py @@ -49,7 +49,8 @@ def main(obs_id=None, config_file=None, logger=None): preprocess_tod, update_g3tsmurf_db, update_obsdb, - make_cosamp_hk + make_cosamp_hk, + solve_pointing_model ) # Dictionary matching element name to a submodule (which must have @@ -68,6 +69,7 @@ def main(obs_id=None, config_file=None, logger=None): 'update-g3tsmurf-db': update_g3tsmurf_db, 'update-obsdb': update_obsdb, 'make-cosamp-hk': make_cosamp_hk, + 'solve-pointing-model': solve_pointing_model } CLI_NAME = 'so-site-pipeline' diff --git a/sotodlib/site_pipeline/solve_pointing_model.py b/sotodlib/site_pipeline/solve_pointing_model.py index 218d9b36d..06eff0bd8 100644 --- a/sotodlib/site_pipeline/solve_pointing_model.py +++ b/sotodlib/site_pipeline/solve_pointing_model.py @@ -1,13 +1,17 @@ import os, sys, pickle, math, h5py import numpy as np -import argparse as ap +import argparse import so3g.proj.quat as quat import lmfit from lmfit import minimize, Parameters import yaml import logging +import matplotlib -from sotodlib.site_pipeline import util +matplotlib.use("agg") +import matplotlib.pyplot as plt + +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 @@ -15,42 +19,34 @@ DEG = np.pi / 180.0 ARCMIN = DEG / 60 +plt.rcParams["axes.grid"] = True +plt.rcParams["grid.alpha"] = 0.5 + -def _load_nom_centers(config): +def load_nom_centers(config): # Load Nominal UFM Center Locations from centered focal_plane ffp_path = config.get("ffp_path") ufms = config.get("ufms") - nom_ufm_centers = np.zeros([1, 7, 3]) * np.nan + 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)): index = ufms.index(OT.focal_planes[ufm].stream_id) - nom_ufm_centers[0, index, :3] = OT.focal_planes[ufm].center - nom_ufm_centers = nom_ufm_centers[0] + nom_ufm_centers[index, :3] = OT.focal_planes[ufm].center return nom_ufm_centers -# obsdb_entries = [ctx.obsdb.get(obsid) for obsid in filelist] def _load_per_obs_data(config): # Load per-observation UFM center data points and weights # The per obs .h5 file a dict with obs_id for keys per_obs_fps = config.get("per_obs_fps") ufms = config.get("ufms") + skip_tags = config.get("skip_tags", []) rxs = fpc.Receiver.load_file(per_obs_fps) - if config.get("platform") == "satp1": - filelist = list(rxs.keys()) - # the following are known to be bad fits: - filelist = [ - item - for item in filelist - if "_1713" not in item and "1716423951" not in item - ] - else: - filelist = list(rxs.keys()) - obsidnum = np.array( - [filelist[id].split("_")[1] for id, _ in enumerate(filelist)], dtype=int - ) + filelist = list(rxs.keys()) + for skip in skip_tags: + filelist = [obs for obs in filelist if skip not in obs] obs_ufm_centers = np.zeros([len(filelist), 7, 3]) * np.nan weights_ufm = np.zeros([len(filelist), 7]) @@ -70,9 +66,10 @@ def _load_obs_boresight(config, filelist): # Load boresight elevation information from each observation # Put into an axis manager ctx = core.Context(config["context"]["path"]) - az_c = [ctx.obsdb.get(obsid)["az_center"] for obsid in filelist] - el_c = [ctx.obsdb.get(obsid)["el_center"] for obsid in filelist] - roll_c = [ctx.obsdb.get(obsid)["roll_center"] for obsid in filelist] + obs_info = [ctx.obsdb.get(obsid) for obsid in filelist] + az_c = [obs["az_center"] for obs in obs_info] + el_c = [obs["el_center"] for obs in obs_info] + roll_c = [obs["roll_center"] for obs in obs_info] az_c = np.round(np.array(az_c), 4) el_c = np.round(np.array(el_c), 4) roll_c = np.round(np.array(roll_c), 4) @@ -106,33 +103,80 @@ def chi_sq(weights, dist): return chi2 -def objective_model_func_lmfit(params, solver_aman, return_fit=False, weights=True): +def model_template_xieta(params, pm_version, solver_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 = solver_aman.ffp_ufm_center_fits[0] + eta_meas = solver_aman.ffp_ufm_center_fits[1] + if type(params) == lmfit.parameter.Parameters: + params = params.valuesdict() + params["version"] = pm_version + if "sat" in pm_version: + az, el, roll = pm._get_sat_enc_radians(solver_aman.ancil) + boresight = pm.apply_pointing_model(solver_aman, pointing_model=params, wrap=False) + az1, el1, roll1 = boresight.az, boresight.el, boresight.roll + q_nomodel = quat.rotation_lonlat(-az, el, 0) + 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, solver_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 + """ if type(params) == lmfit.parameter.Parameters: params = params.valuesdict() - xi_nom, eta_nom, gam_nom = solver_aman.nom_ufm_centers - az, el, roll = pm._get_sat_enc_radians(solver_aman.ancil) - az1, el1, roll1 = pm.model_sat_v1(params, az, el, roll) - ## Quat math is based on this equation: q_nomodel * q_det_data == q_model * q_det_true + params["version"] = pm_version + xi_true, eta_true, gam_true = solver_aman.nom_ufm_centers + if "sat" in pm_version: + az, el, roll = pm._get_sat_enc_radians(solver_aman.ancil) + boresight = pm.apply_pointing_model(solver_aman, pointing_model=params, wrap=False) + az1, el1, roll1 = boresight.az, boresight.el, boresight.roll + q_nomodel = quat.rotation_lonlat(-az, el, 0) q_model = quat.rotation_lonlat(-az1, el1, roll1) - q_det_true = quat.rotation_xieta(xi_nom, eta_nom, 0) - xi_mod, eta_mod, gamma_mod = quat.decompose_xieta(~q_nomodel * q_model * q_det_true) - xi_ffp, eta_ffp, gamma_ffp = solver_aman.ffp_ufm_center_fits - if return_fit: - return xi_mod, eta_mod, gamma_mod + 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 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.ffp_ufm_center_fits + elif xieta_model == "template": + xi_mod, eta_mod = model_template_xieta(params, pm_version, solver_aman) + xi_ref, eta_ref, _ = solver_aman.nom_ufm_centers + + dist = [] + for i in range(len(xi_mod)): + dist.append(math.dist([xi_ref[i], eta_ref[i]], [xi_mod[i], eta_mod[i]])) + if weights: + return chi_sq(solver_aman.weights, np.array(dist)) else: - dist = [] - for i in range(len(xi_mod)): - dist.append(math.dist([xi_ffp[i], eta_ffp[i]], [xi_mod[i], eta_mod[i]])) - if weights: - return chi_sq(solver_aman.weights, np.array(dist)) - else: - return chi_sq(np.ones(len(dist)), np.array(dist)) - - -def get_RMS(model_xieta, data_xieta, weights): - diff = (model_xieta[0] / ARCMIN - data_xieta[0] / DEG * 60) ** 2 + ( - model_xieta[1] / ARCMIN - data_xieta[1] / DEG * 60 + return chi_sq(np.ones(len(dist)), np.array(dist)) + + +def get_RMS(model_xieta, ref_xieta, weights): + diff = (model_xieta[0] / ARCMIN - ref_xieta[0] / ARCMIN) ** 2 + ( + model_xieta[1] / ARCMIN - ref_xieta[1] / ARCMIN ) ** 2 return (np.nansum(diff * weights) / np.nansum(weights)) ** 0.5 @@ -156,40 +200,83 @@ def _create_db(filename, save_dir): return core.metadata.ManifestDb(db_filename, scheme=scheme) -def main(): - # Read input parameters - parser = ap.ArgumentParser() - parser.add_argument("config_path", help="Location of the config file") - args = parser.parse_args() +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 build_param_fit_stat_aman(output): + # takes output of lmfit.minimize() + parameter_fit_stats = core.AxisManager(core.IndexAxis("parameters")) + parameter_fit_stats.wrap( + "name", np.array([output.params[p].name for p in output.params]) + ) + parameter_fit_stats.wrap( + "value", np.array([output.params[p].value for p in output.params]) + ) + parameter_fit_stats.wrap( + "vary", np.array([output.params[p].vary for p in output.params]) + ) + parameter_fit_stats.wrap( + "min", np.array([output.params[p].min for p in output.params]) + ) + parameter_fit_stats.wrap( + "max", np.array([output.params[p].max for p in output.params]) + ) + parameter_fit_stats.wrap( + "stderr", np.array([output.params[p].stderr for p in output.params]) + ) + parameter_fit_stats.wrap( + "correl", np.array([output.params[p].correl for p in output.params]) + ) + return parameter_fit_stats + +def main(config_path: str): # Read relevant config file info - with open(args.config_path, "r", encoding="utf-8") as file: + 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 - solution_version_tag = config.get("solution_version_tag") # e.g. YYMMDDr# + sv_tag = config.get("solution_version_tag") # e.g. YYMMDDr# + xieta_model = config.get("xieta_model", "measured") + xe_tag = f"{xieta_model}_xieta" + iterate_cutoff = config.get("iterate_cutoff", None) + append = config.get("append", "") + append_tag = f"{bool(append)*'_'}{append}" save_dir = os.path.join( - config.get("outdir"), f"{platform}_pointing_model_{solution_version_tag}" + config.get("outdir"), f"{platform}_pointing_model_{sv_tag}", f"{xe_tag}{append_tag}" ) - if not os.path.exists(save_dir): - os.makedirs(save_dir) - # savemeta_dir = os.path.join(config.get("savemeta_dir"), solution_version_tag) - # if not os.path.exists(savemeta_dir): - # os.makedirs(savemeta_dir, exists_ok=False) + os.makedirs(save_dir, exist_ok=True) # Initialize Logger - logger = util.init_logger(__name__, "Solve pointing_model") + 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' + ) + exit + logger.info( + "Pointing model will try to replicate (model) the %s data.", xieta_model + ) + # Load in focal_plane and boresigt data - nom_ufm_centers = _load_nom_centers(config) + nom_ufm_centers = load_nom_centers(config) logger.info("Loaded nominal UFM centers from %s: ", config.get("ffp_path")) + logger.info(nom_ufm_centers) + filelist, obs_ufm_centers, weights_ufm = _load_per_obs_data(config) logger.info("Loaded per-obs FFP data from %s: ", config.get("per_obs_fps")) logger.info("Including data from these obs:") logger.info(filelist) + ancil, roll_c = _load_obs_boresight(config, filelist) logger.info("Loaded boresight data from obs ids.") @@ -217,62 +304,521 @@ def main(): ) solver_aman.wrap("weights", weights_ufm.reshape(-1), [(0, "samps")]) - weights_mask = np.where(solver_aman["weights"] == 0)[0] - solver_aman["ffp_ufm_center_fits"][:, weights_mask] = np.nan - + # Make weights/data cuts + # solver_aman.weights[solver_aman.ancil.az_enc > 360] = 0.0 logger.info("Built axis manager") # Initialize Parameters to Fit with Model fit_params = _init_fit_params(config) - - # Solve for Model Paramters + if xieta_model == "measured": + model_reference = solver_aman.ffp_ufm_center_fits + elif xieta_model == "template": + model_reference = solver_aman.nom_ufm_centers + + # Solve for Model Parameters + # use chosen xieta_model to solve for parameters + use_weights = True model_solved_params = lmfit.minimize( objective_model_func_lmfit, fit_params, method="nelder", nan_policy="omit", - args=(solver_aman, False, True), - ) - model_fits = objective_model_func_lmfit( - model_solved_params.params, solver_aman, return_fit=True + args=(pm_version, solver_aman, xieta_model, use_weights), ) 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( - "RMS on fit: %f", - get_RMS(model_fits, solver_aman.ffp_ufm_center_fits, solver_aman.weights), - ) - - # Save fit results to the axis manager - modelfit_aman = core.AxisManager() - modelfit_aman.wrap("xi", model_fits[0]) - modelfit_aman.wrap("eta", model_fits[1]) - # modelfit_aman.wrap("gamma", model_fits[2]) - solver_aman.wrap("model_fits", modelfit_aman) + logger.info(model_solved_params.params.pretty_print(precision=5, colwidth=11)) + # save pointing model parameters to axis manager param_aman = core.AxisManager() for k in list(test_params.keys()): param_aman.wrap(k, test_params[k]) solver_aman.wrap("pointing_model", param_aman) + + # parameter_fit_stats = build_param_fit_stat_aman(model_solved_params) + # solver_aman.wrap("parameter_fit_stats", parameter_fit_stats) + + # Model template and measured points using parameters found above + if xieta_model == "measured": + model_fits = model_measured_xieta( + solver_aman.pointing_model, pm_version, solver_aman + ) + elif xieta_model == "template": + model_fits = model_template_xieta( + solver_aman.pointing_model, pm_version, solver_aman + ) + + logger.info( + "RMS on fit: %f", get_RMS(model_fits, model_reference, solver_aman.weights) + ) + + fit_residual_i1 = np.array( + [ + math.dist( + [model_reference[0][i], model_reference[1][i]], + [model_fits[0][i], model_fits[1][i]], + ) + for i in range(len(model_fits[0])) + ] + ) + + # Save fit results to the axis manager + modelfit_aman = core.AxisManager() + modelfit_aman.wrap("xi", model_fits[0], overwrite=True) + modelfit_aman.wrap("eta", model_fits[1], overwrite=True) + solver_aman.wrap("model_fits", modelfit_aman, overwrite=True) solver_aman.wrap( "fit_rms", - get_RMS(model_fits, solver_aman.ffp_ufm_center_fits, solver_aman.weights), + get_RMS(model_fits, model_reference, solver_aman.weights), + overwrite=True, ) - # Save .h5 and ManifestDb - h5_rel = "pointing_model_data.h5" - h5_filename = os.path.join(save_dir, h5_rel) - solver_aman.save(h5_filename, overwrite=True) - dbfile = "db.sqlite" - db = _create_db(dbfile, save_dir) - db.add_entry({"dataset": "pointing_model"}, filename=h5_rel, replace=True) - db.to_file(os.path.join(save_dir, dbfile)) + if config.get("make_plots"): + tag = "_i1" + plot_ws0_model_fits(solver_aman, config, save_dir, tag) + plot_template_space_fits_per_wafer(solver_aman, config, save_dir, tag) + plot_residuals_vs_ancil(solver_aman, config, save_dir, tag) + plot_xieta_cross_residuals(solver_aman, config, save_dir, tag) + plot_xieta_residuals(solver_aman, config, save_dir, tag) + + + if iterate_cutoff is not None: + logger.info("Iterating parameter solution") + + cutoff = np.nanstd(fit_residual_i1) + np.nanmedian(fit_residual_i1) + logger.info(f"1 std away from residual Median: {cutoff / ARCMIN} arcmin") + logger.info(f"Using {iterate_cutoff} as cutoff") + bad_fit_mask = np.where((fit_residual_i1 / ARCMIN) > iterate_cutoff)[0] + logger.info("Bad fit indices:") + logger.info(bad_fit_mask) + logger.info( + "%f data points are higher than %s arcmin", + len(bad_fit_mask), + iterate_cutoff, + ) + bad_filename = bad_fit_mask // 7 + bad_wafer = bad_fit_mask % 7 + for mask_ind, full_ind in enumerate(bad_fit_mask): + logger.info( + f"{filelist[bad_filename[mask_ind]]} ws{bad_wafer[mask_ind]} is bad. Roll {solver_aman.roll_c[full_ind]}, El {solver_aman.ancil.el_enc[full_ind]}" + ) + + solver_aman.weights[bad_fit_mask] = 0.0 + use_weights = True + model_solved_params = lmfit.minimize( + objective_model_func_lmfit, + fit_params, + method="nelder", + nan_policy="omit", + args=(pm_version, solver_aman, xieta_model, use_weights), + ) + + 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(model_solved_params.params.pretty_print(precision=5, colwidth=11)) + + # save pointing model parameters to axis manager + param_aman = core.AxisManager() + for k in list(test_params.keys()): + param_aman.wrap(k, test_params[k]) + solver_aman.wrap("pointing_model", param_aman, overwrite=True) + + # parameter_fit_stats = build_param_fit_stat_aman(model_solved_params) + # solver_aman.wrap("parameter_fit_stats", parameter_fit_stats, overwrite=True) + + # Recalculate best fit modeled points + if xieta_model == "measured": + model_fits = model_measured_xieta( + solver_aman.pointing_model, pm_version, solver_aman + ) + elif xieta_model == "template": + model_fits = model_template_xieta( + solver_aman.pointing_model, pm_version, solver_aman + ) + logger.info( + "RMS on fit: %f", get_RMS(model_fits, model_reference, solver_aman.weights) + ) + fit_residual_i2 = np.array( + [ + math.dist( + [model_reference[0][i], model_reference[1][i]], + [model_fits[0][i], model_fits[1][i]], + ) + for i in range(len(model_fits[0])) + ] + ) + # Save fit results to the axis manager + modelfit_aman = core.AxisManager() + modelfit_aman.wrap("xi", model_fits[0], overwrite=True) + modelfit_aman.wrap("eta", model_fits[1], overwrite=True) + solver_aman.wrap("model_fits", modelfit_aman, overwrite=True) + solver_aman.wrap( + "fit_rms", + get_RMS(model_fits, model_reference, solver_aman.weights), + overwrite=True, + ) + if config.get("make_plots"): + tag = "_i2" + plot_ws0_model_fits(solver_aman, config, save_dir, tag) + plot_template_space_fits_per_wafer(solver_aman, config, save_dir, tag) + plot_residuals_vs_ancil(solver_aman, config, save_dir, tag) + plot_xieta_cross_residuals(solver_aman, config, save_dir, tag) + plot_xieta_residuals(solver_aman, config, save_dir, tag) + plot_total_residuals(solver_aman, config, save_dir, tag, fit_residual_i1, fit_residual_i2, bad_fit_mask) + else: + if config.get("make_plots"): + plot_total_residuals(solver_aman, config, save_dir, tag='', fit_residual_i1=fit_residual_i1) + + + if config.get("save_output"): + # Save .h5 and ManifestDb + h5_rel = "pointing_model_data.h5" + h5_filename = os.path.join(save_dir, h5_rel) + solver_aman.save(h5_filename, overwrite=True) + dbfile = "db.sqlite" + db = _create_db(dbfile, save_dir) + db.add_entry({"dataset": "pointing_model"}, filename=h5_rel, replace=True) + db.to_file(os.path.join(save_dir, dbfile)) + + +#################### +# Plotting Functions +#################### + +def plot_ws0_model_fits(solver_aman, config, save_dir, tag=""): + plot_dir = os.path.join(save_dir, "plots") + os.makedirs(plot_dir, exist_ok=True) + platform = config.get("platform") + plotmask = np.where(solver_aman.weights) + rms = np.round(solver_aman.fit_rms, 4) + xi_model_fit = solver_aman.model_fits.xi + eta_model_fit = solver_aman.model_fits.eta + if config.get("xieta_model") == "measured": + xi_ref, eta_ref, _ = solver_aman.ffp_ufm_center_fits + elif config.get("xieta_model") == "template": + xi_ref, eta_ref, _ = solver_aman.nom_ufm_centers + markercolor = solver_aman.ancil.el_enc + coloredby = "El" + scale_weights = solver_aman.weights / np.nanmax(solver_aman.weights) + + #### + fig = plt.figure(figsize=(6, 6)) + gs = fig.add_gridspec(2, 2) + ax = fig.add_subplot(gs[:, :]) + ax.plot( + solver_aman["nom_ufm_centers"][0, : 7 + 1] / DEG, + solver_aman["nom_ufm_centers"][1, : 7 + 1] / DEG, + "rx", + label="Nominal Center", + ) + ax.scatter( + xi_ref[plotmask] / DEG, + eta_ref[plotmask] / DEG, + c=markercolor[plotmask], + alpha=0.5, + label="Data", + edgecolors="k", + linewidths=0.4, + s=130 * scale_weights[plotmask], + cmap="jet", + vmax=65, + ) + im = ax.scatter( + xi_model_fit / DEG, + eta_model_fit / DEG, + marker="*", + c=markercolor, + cmap="jet", + edgecolor="gray", + lw=0.3, + s=130, + label=f"Model, RMS = {rms}", + vmax=65, + ) + ax.legend(loc=1, fontsize="small") + ax.set_xlabel("Xi (deg)") + ax.set_ylabel("Eta (deg)") + plt.colorbar(im, location="top", fraction=0.046, pad=0.04) + ax.set_title(f"Fits, Colored by {coloredby} (deg)\n\n\n") + + # 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) + ax.set_xlim(-1, 1); ax.set_ylim(-1, 1) + plt.subplots_adjust(left=0.1, right=0.90, bottom=0.05, hspace=0.3) + plt.savefig(f"{plot_dir}/{platform}_ws0_model_fits{tag}.png", dpi=350) + plt.close() + + +def plot_template_space_fits_per_wafer(solver_aman, config, save_dir, tag=""): + plot_dir = os.path.join(save_dir, "plots") + os.makedirs(plot_dir, exist_ok=True) + pm_version = config.get("pm_version") + platform = config.get("platform") + scale_weights = solver_aman.weights / np.nanmax(solver_aman.weights) + xi_unmod, eta_unmod = model_template_xieta( + solver_aman.pointing_model, pm_version, solver_aman + ) + xi0, eta0 = model_template_xieta(pm.defaults_sat_v1, pm_version, solver_aman) + + 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 - solver_aman.nom_ufm_centers[0, i] / ARCMIN, + eta_unmod[i::7] / ARCMIN - solver_aman.nom_ufm_centers[1, i] / ARCMIN, + c=solver_aman.ancil.el_enc[i::7], + s=scale_weights[i::7] * 80, + marker="o", + lw=0, + alpha=0.5, + cmap="jet", + ) + plt.colorbar(im, ax[1, 3], label="Elevation (deg)", fraction=0.046, pad=0.04) + plt.tight_layout() + plt.savefig(f"{plot_dir}/{platform}_unmodeled_fits_WS_elevation{tag}.png", dpi=350) + plt.close() + + 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 - solver_aman.nom_ufm_centers[0, i] / ARCMIN, + eta_unmod[i::7] / ARCMIN - solver_aman.nom_ufm_centers[1, i] / ARCMIN, + c=solver_aman.ancil.boresight_enc[i::7], + s=scale_weights[i::7] * 80, + marker="o", + lw=0, + alpha=0.5, + cmap="jet", + ) + ax[i // 4, i % 4].set_xlim(-15, 15) + ax[i // 4, i % 4].set_ylim(-15, 15) + ax[i // 4, i % 4].set_title(f"ws{i}") + plt.colorbar(im, ax[1, 3], label="Boresight (deg)", fraction=0.046, pad=0.04) + plt.tight_layout() + plt.savefig(f"{plot_dir}/{platform}_unmodeled_fits_WS_boresight{tag}.png", dpi=350) + plt.close() + + +def plot_residuals_vs_ancil(solver_aman, config, save_dir, tag): + plot_dir = os.path.join(save_dir, "plots") + os.makedirs(plot_dir, exist_ok=True) + platform = config.get("platform") + scale_weights = solver_aman.weights / np.nanmax(solver_aman.weights) + plotmask = np.where(solver_aman.weights) + xi_model_fit = solver_aman.model_fits.xi + eta_model_fit = solver_aman.model_fits.eta + if config.get("xieta_model") == "measured": + xi_ref, eta_ref, _ = solver_aman.ffp_ufm_center_fits + elif config.get("xieta_model") == "template": + xi_ref, eta_ref, _ = solver_aman.nom_ufm_centers + + 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$ vs Az, El, Boresight") + 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 + if j == 0: + x = solver_aman.ancil.az_enc % 360 + elif j == 1: + x = solver_aman.ancil.el_enc + elif j == 2: + x = solver_aman.ancil.boresight_enc + + ax[i, j].scatter( + x[plotmask], + (model - ref)[plotmask] / ARCMIN, + color="k", + marker=".", + alpha=0.3, + 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].plot(xrange, mxb[0] * xrange + mxb[1], "r", lw=1) + 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("Boresight [deg]") + plt.tight_layout() + plt.savefig(f"{plot_dir}/{platform}_residuals_vs_ancillary{tag}.png", dpi=350) + plt.close() + +def plot_total_residuals(solver_aman, config, save_dir, tag, fit_residual_i1, fit_residual_i2=None, bad_fit_mask=None): + plot_dir = os.path.join(save_dir, "plots") + os.makedirs(plot_dir, exist_ok=True) + iterate_cutoff = config.get("iterate_cutoff", None) + platform = config.get("platform") + + if fit_residual_i2 is not None: + 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_residual_i1)), fit_residual_i1 / ARCMIN, + 'r.', mew=0, alpha=0.6, lw=0, label = '1st Fit') + ax1.set_ylabel(f'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_residual_i2)), + fit_residual_i2 / ARCMIN, 'b*', + alpha=0.5, lw=0, mew=0, label = '2nd fit') + 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) + + ax2.plot(np.arange(len(fit_residual_i1)), (fit_residual_i2 - fit_residual_i1) / ARCMIN, + 'k.', mew=0, alpha = 0.6, label = "Res i2 - Res i1") + ax2.plot(np.arange(len(fit_residual_i1))[bad_fit_mask], (fit_residual_i2 - fit_residual_i1)[bad_fit_mask] / ARCMIN, + 'kx', 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) + ax2.legend(fontsize='x-small') + ax2.set_xlabel('Data points') + ax2.set_ylabel(r'$\Delta$ Residuals') + plt.savefig(f"{plot_dir}/{platform}_total_residuals{tag}.png", dpi=350) + + else: + fig, ax = plt.subplots() + #Plot first fit iteration residuals + ax.plot(np.arange(len(fit_residual_i1)), fit_residual_i1 / ARCMIN, + 'r.', mew=0, alpha=0.6, lw=0, label = '1st Fit') + ax.set_ylabel(r'Fit Residual $\left|\Delta\text{(xi, eta)}\right|$ [arcmin]') + ax.set_xlabel('Data points') + plt.legend(loc=2) + plt.savefig(f"{plot_dir}/{platform}_total_residuals{tag}.png", dpi=350) + plt.close() + +def plot_xieta_residuals(solver_aman, config, save_dir, tag): + plot_dir = os.path.join(save_dir, "plots") + os.makedirs(plot_dir, exist_ok=True) + scale_weights = solver_aman.weights / np.nanmax(solver_aman.weights) + plotmask = np.where(solver_aman.weights) + platform = config.get("platform") + xi_model_fit = solver_aman.model_fits.xi + eta_model_fit = solver_aman.model_fits.eta + if config.get("xieta_model") == "measured": + xi_ref, eta_ref, _ = solver_aman.ffp_ufm_center_fits + elif config.get("xieta_model") == "template": + xi_ref, eta_ref, _ = solver_aman.nom_ufm_centers + + 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(-10, 20) + ax[i].set_xlabel(f"{xlabel} (deg)", fontsize="small") + ax[i].set_ylabel(f"{ylabel} [arcmin]") + plt.tight_layout() + plt.savefig(f"{plot_dir}/{platform}_xieta_residuals{tag}.png", dpi=350) + plt.close() + + +def plot_xieta_cross_residuals(solver_aman, config, save_dir, tag): + plot_dir = os.path.join(save_dir, "plots") + os.makedirs(plot_dir, exist_ok=True) + scale_weights = solver_aman.weights / np.nanmax(solver_aman.weights) + plotmask = np.where(solver_aman.weights) + platform = config.get("platform") + xi_model_fit = solver_aman.model_fits.xi + eta_model_fit = solver_aman.model_fits.eta + if config.get("xieta_model") == "measured": + xi_ref, eta_ref, _ = solver_aman.ffp_ufm_center_fits + elif config.get("xieta_model") == "template": + xi_ref, eta_ref, _ = solver_aman.nom_ufm_centers + + 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(-10, 20) + ax[i].set_xlabel(f"{xlabel} (deg)", fontsize="small") + ax[i].set_ylabel(f"{ylabel} [arcmin]") + plt.tight_layout() + plt.savefig(f"{plot_dir}/{platform}_xieta_cross_residuals{tag}.png", dpi=350) + plt.close() + + ############ if __name__ == "__main__": - main() + sp_util.main_launcher(main, get_parser) From 0e5ef43de4d6c767a65483d7b56da337a11c8d58 Mon Sep 17 00:00:00 2001 From: Elle Claire Shaw Date: Mon, 21 Oct 2024 12:46:04 -0700 Subject: [PATCH 017/132] Edits to documentation --- docs/site_pipeline.rst | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/docs/site_pipeline.rst b/docs/site_pipeline.rst index 709fb47a9..0eb686775 100644 --- a/docs/site_pipeline.rst +++ b/docs/site_pipeline.rst @@ -575,12 +575,14 @@ 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. + 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) @@ -654,6 +656,7 @@ 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 pointing_model_data.h5 @@ -673,15 +676,15 @@ Only the pointing model parameters + version are saved to the ManifestdB ``db.sq - 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 + #- 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) From 63308fd1a0293b018943cdc3385cb592793262c2 Mon Sep 17 00:00:00 2001 From: Elle Claire Shaw Date: Mon, 21 Oct 2024 13:21:13 -0700 Subject: [PATCH 018/132] Trying again with docs syntax. --- docs/site_pipeline.rst | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/docs/site_pipeline.rst b/docs/site_pipeline.rst index 0eb686775..8e2ab08a2 100644 --- a/docs/site_pipeline.rst +++ b/docs/site_pipeline.rst @@ -562,13 +562,14 @@ The keys of this dict are the start times for combined focal planes and the ``ob 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, +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. @@ -576,8 +577,13 @@ 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. @@ -652,14 +658,15 @@ The first block are mandatory entries. The second block are optional. 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 - - pointing_model_data.h5 +.. code_block:: text + - ancil (aman) - az_enc (num_obs * 7) - boresight_enc (num_obs * 7) @@ -687,8 +694,6 @@ Only the pointing model parameters + version are saved to the ManifestdB ``db.sq #- excluded (Data points) - - preprocess-tod -------------- This script is set up to run a preprocessing pipeline using the preprocess From fd14407527574c8f787bbf43860ab59eacb4a8b2 Mon Sep 17 00:00:00 2001 From: Elle Claire Shaw Date: Mon, 21 Oct 2024 13:38:15 -0700 Subject: [PATCH 019/132] Edit docs syntax. Surely it is getting close by now. --- docs/site_pipeline.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/site_pipeline.rst b/docs/site_pipeline.rst index 8e2ab08a2..e810f2bf0 100644 --- a/docs/site_pipeline.rst +++ b/docs/site_pipeline.rst @@ -616,10 +616,10 @@ The first block are mandatory entries. The second block are optional. # 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 + 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 From b8c6ed9c46d08efcc40f15bf044ceced2e7eb449 Mon Sep 17 00:00:00 2001 From: Elle Claire Shaw Date: Mon, 21 Oct 2024 13:41:42 -0700 Subject: [PATCH 020/132] Edit documentation. Fingers crossed. --- docs/site_pipeline.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/site_pipeline.rst b/docs/site_pipeline.rst index e810f2bf0..73393844a 100644 --- a/docs/site_pipeline.rst +++ b/docs/site_pipeline.rst @@ -665,7 +665,7 @@ 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 +.. code-block:: text - ancil (aman) - az_enc (num_obs * 7) From 2071000e8f5d89ab59170c3595d8ebea0c50b9aa Mon Sep 17 00:00:00 2001 From: Elle Claire Shaw Date: Mon, 21 Oct 2024 15:32:12 -0700 Subject: [PATCH 021/132] Added lmfit to list of modules to mock import. --- docs/conf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/conf.py b/docs/conf.py index 610559890..631caf779 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -103,7 +103,7 @@ 'skyfield', 'h5py', 'pyfftw', 'scipy', 'toast', 'pixell', 'scikit', 'skimage', 'numdifftools', 'traitlets', 'ephem', 'influxdb', 'megham', 'detmap', - 'sodetlib'): + 'sodetlib', 'lmfit'): try: foo = import_module(missing) except ImportError: From 22470038829bcc86cabb7c38f0cfd09672577c23 Mon Sep 17 00:00:00 2001 From: Elle Claire Shaw Date: Mon, 21 Oct 2024 16:42:53 -0700 Subject: [PATCH 022/132] Small change to logger output for outliers after iteration. Includes more information on weights and residuals of outlying data points. --- .../site_pipeline/solve_pointing_model.py | 49 ++++++++++++------- 1 file changed, 31 insertions(+), 18 deletions(-) diff --git a/sotodlib/site_pipeline/solve_pointing_model.py b/sotodlib/site_pipeline/solve_pointing_model.py index 06eff0bd8..93031c6e1 100644 --- a/sotodlib/site_pipeline/solve_pointing_model.py +++ b/sotodlib/site_pipeline/solve_pointing_model.py @@ -174,10 +174,14 @@ def objective_model_func_lmfit( return chi_sq(np.ones(len(dist)), np.array(dist)) -def get_RMS(model_xieta, ref_xieta, weights): - diff = (model_xieta[0] / ARCMIN - ref_xieta[0] / ARCMIN) ** 2 + ( - model_xieta[1] / ARCMIN - ref_xieta[1] / ARCMIN - ) ** 2 +def get_RMS(model_xieta, ref_xieta, weights, use_inds=None): + if use_inds is not None: + diff = ((model_xieta[0] - ref_xieta[0])[use_inds] / ARCMIN) ** 2 + \ + ((model_xieta[1] - ref_xieta[1])[use_inds] / ARCMIN) ** 2 + weights = weights[use_inds] + else: + diff = ((model_xieta[0] - ref_xieta[0]) / ARCMIN) ** 2 + \ + ((model_xieta[1] - ref_xieta[1]) / ARCMIN) ** 2 return (np.nansum(diff * weights) / np.nansum(weights)) ** 0.5 @@ -390,22 +394,31 @@ def main(config_path: str): cutoff = np.nanstd(fit_residual_i1) + np.nanmedian(fit_residual_i1) logger.info(f"1 std away from residual Median: {cutoff / ARCMIN} arcmin") logger.info(f"Using {iterate_cutoff} as cutoff") - bad_fit_mask = np.where((fit_residual_i1 / ARCMIN) > iterate_cutoff)[0] + bad_fit_inds = np.where((fit_residual_i1 / ARCMIN) > iterate_cutoff)[0] logger.info("Bad fit indices:") - logger.info(bad_fit_mask) + logger.info(bad_fit_inds) logger.info( "%f data points are higher than %s arcmin", - len(bad_fit_mask), + len(bad_fit_inds), iterate_cutoff, ) - bad_filename = bad_fit_mask // 7 - bad_wafer = bad_fit_mask % 7 - for mask_ind, full_ind in enumerate(bad_fit_mask): - logger.info( - f"{filelist[bad_filename[mask_ind]]} ws{bad_wafer[mask_ind]} is bad. Roll {solver_aman.roll_c[full_ind]}, El {solver_aman.ancil.el_enc[full_ind]}" - ) + 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_residual_i1[full_i] / ARCMIN, 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)}") + + num_bad_non_zero = sum([solver_aman.weights[ind] > 0 for ind in bad_fit_inds]) + logger.info(f"Only {num_bad_non_zero} outliers with non-zero weight.") + + #Print RMS of initial fits without outlying data points before + #zero-ing the weights. + good_fit_inds = np.where((fit_residual_i1 / ARCMIN) < iterate_cutoff)[0] + masked_rms = get_RMS(model_fits, model_reference, solver_aman.weights, use_inds = good_fit_inds) + logger.info("RMS on initial fit without outliers: %f", masked_rms) - solver_aman.weights[bad_fit_mask] = 0.0 + solver_aman.weights[bad_fit_inds] = 0.0 use_weights = True model_solved_params = lmfit.minimize( objective_model_func_lmfit, @@ -439,7 +452,7 @@ def main(config_path: str): solver_aman.pointing_model, pm_version, solver_aman ) logger.info( - "RMS on fit: %f", get_RMS(model_fits, model_reference, solver_aman.weights) + "RMS on secondary fit: %f", get_RMS(model_fits, model_reference, solver_aman.weights) ) fit_residual_i2 = np.array( [ @@ -467,7 +480,7 @@ def main(config_path: str): plot_residuals_vs_ancil(solver_aman, config, save_dir, tag) plot_xieta_cross_residuals(solver_aman, config, save_dir, tag) plot_xieta_residuals(solver_aman, config, save_dir, tag) - plot_total_residuals(solver_aman, config, save_dir, tag, fit_residual_i1, fit_residual_i2, bad_fit_mask) + plot_total_residuals(solver_aman, config, save_dir, tag, fit_residual_i1, fit_residual_i2, bad_fit_inds) else: if config.get("make_plots"): plot_total_residuals(solver_aman, config, save_dir, tag='', fit_residual_i1=fit_residual_i1) @@ -668,7 +681,7 @@ def plot_residuals_vs_ancil(solver_aman, config, save_dir, tag): plt.savefig(f"{plot_dir}/{platform}_residuals_vs_ancillary{tag}.png", dpi=350) plt.close() -def plot_total_residuals(solver_aman, config, save_dir, tag, fit_residual_i1, fit_residual_i2=None, bad_fit_mask=None): +def plot_total_residuals(solver_aman, config, save_dir, tag, fit_residual_i1, fit_residual_i2=None, bad_fit_inds=None): plot_dir = os.path.join(save_dir, "plots") os.makedirs(plot_dir, exist_ok=True) iterate_cutoff = config.get("iterate_cutoff", None) @@ -696,7 +709,7 @@ def plot_total_residuals(solver_aman, config, save_dir, tag, fit_residual_i1, f ax2.plot(np.arange(len(fit_residual_i1)), (fit_residual_i2 - fit_residual_i1) / ARCMIN, 'k.', mew=0, alpha = 0.6, label = "Res i2 - Res i1") - ax2.plot(np.arange(len(fit_residual_i1))[bad_fit_mask], (fit_residual_i2 - fit_residual_i1)[bad_fit_mask] / ARCMIN, + ax2.plot(np.arange(len(fit_residual_i1))[bad_fit_inds], (fit_residual_i2 - fit_residual_i1)[bad_fit_inds] / ARCMIN, 'kx', 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) ax2.legend(fontsize='x-small') From 64a96965bc1b55a93239ad1ce6e06939a9aa7d7a Mon Sep 17 00:00:00 2001 From: Elle Claire Shaw Date: Wed, 23 Oct 2024 13:25:24 -0700 Subject: [PATCH 023/132] Made changes to log file and diagnostic plots. --- .../site_pipeline/solve_pointing_model.py | 96 ++++++++++++++----- 1 file changed, 70 insertions(+), 26 deletions(-) diff --git a/sotodlib/site_pipeline/solve_pointing_model.py b/sotodlib/site_pipeline/solve_pointing_model.py index 93031c6e1..8adead517 100644 --- a/sotodlib/site_pipeline/solve_pointing_model.py +++ b/sotodlib/site_pipeline/solve_pointing_model.py @@ -58,6 +58,8 @@ def _load_per_obs_data(config): weights_ufm[i, index] = np.nansum(this_OT.focal_planes[u].weights) 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 return filelist, obs_ufm_centers, weights_ufm @@ -333,7 +335,10 @@ def main(config_path: str): 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(lmfit.fit_report(model_solved_params)) # save pointing model parameters to axis manager param_aman = core.AxisManager() @@ -409,9 +414,6 @@ def main(config_path: str): logger.info(f"{filelist[bad_filename[i]]}; ws{bad_wafer[i]}; Resid. {np.round(fit_residual_i1[full_i] / ARCMIN, 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)}") - num_bad_non_zero = sum([solver_aman.weights[ind] > 0 for ind in bad_fit_inds]) - logger.info(f"Only {num_bad_non_zero} outliers with non-zero weight.") - #Print RMS of initial fits without outlying data points before #zero-ing the weights. good_fit_inds = np.where((fit_residual_i1 / ARCMIN) < iterate_cutoff)[0] @@ -431,7 +433,11 @@ def main(config_path: str): 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 param_aman = core.AxisManager() @@ -480,10 +486,21 @@ def main(config_path: str): plot_residuals_vs_ancil(solver_aman, config, save_dir, tag) plot_xieta_cross_residuals(solver_aman, config, save_dir, tag) plot_xieta_residuals(solver_aman, config, save_dir, tag) - plot_total_residuals(solver_aman, config, save_dir, tag, fit_residual_i1, fit_residual_i2, bad_fit_inds) + plot_total_residuals(solver_aman=solver_aman, + config=config, + save_dir=save_dir, + tag=tag, + fit_residual_i1=fit_residual_i1, + fit_residual_i2=fit_residual_i2, + bad_fit_inds=bad_fit_inds, + ) else: if config.get("make_plots"): - plot_total_residuals(solver_aman, config, save_dir, tag='', fit_residual_i1=fit_residual_i1) + plot_total_residuals(solver_aman, + config, + save_dir, + tag='', + fit_residual_i1=fit_residual_i1) if config.get("save_output"): @@ -495,6 +512,7 @@ def main(config_path: str): db = _create_db(dbfile, save_dir) db.add_entry({"dataset": "pointing_model"}, filename=h5_rel, replace=True) db.to_file(os.path.join(save_dir, dbfile)) + logger.info("Done") #################### @@ -531,7 +549,7 @@ def plot_ws0_model_fits(solver_aman, config, save_dir, tag=""): xi_ref[plotmask] / DEG, eta_ref[plotmask] / DEG, c=markercolor[plotmask], - alpha=0.5, + alpha=0.4, label="Data", edgecolors="k", linewidths=0.4, @@ -554,8 +572,9 @@ def plot_ws0_model_fits(solver_aman, config, save_dir, tag=""): ax.legend(loc=1, fontsize="small") ax.set_xlabel("Xi (deg)") ax.set_ylabel("Eta (deg)") - plt.colorbar(im, location="top", fraction=0.046, pad=0.04) - ax.set_title(f"Fits, Colored by {coloredby} (deg)\n\n\n") + cb = plt.colorbar(im, 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)) @@ -565,8 +584,9 @@ def plot_ws0_model_fits(solver_aman, config, save_dir, tag=""): etatoeta[:, 0] = eta_ref / DEG etatoeta[:, 1] = eta_model_fit / DEG ax.plot(xitoxi.T, etatoeta.T, "k", lw=0.4) - ax.set_xlim(-1, 1); ax.set_ylim(-1, 1) - plt.subplots_adjust(left=0.1, right=0.90, bottom=0.05, hspace=0.3) + ax.set_xlim(-1, .25); ax.set_ylim(-.5, .5) + #plt.subplots_adjust(left=0.1, right=0.90, bottom=0.05, hspace=0.3) + plt.tight_layout() plt.savefig(f"{plot_dir}/{platform}_ws0_model_fits{tag}.png", dpi=350) plt.close() @@ -590,11 +610,15 @@ def plot_template_space_fits_per_wafer(solver_aman, config, save_dir, tag=""): eta_unmod[i::7] / ARCMIN - solver_aman.nom_ufm_centers[1, i] / ARCMIN, c=solver_aman.ancil.el_enc[i::7], s=scale_weights[i::7] * 80, + edgecolor="gray", + lw=0.3, marker="o", - lw=0, alpha=0.5, cmap="jet", ) + ax[i // 4, i % 4].set_xlim(-12, 12) + ax[i // 4, i % 4].set_ylim(-12, 12) + ax[i // 4, i % 4].set_title(f"ws{i}") plt.colorbar(im, ax[1, 3], label="Elevation (deg)", fraction=0.046, pad=0.04) plt.tight_layout() plt.savefig(f"{plot_dir}/{platform}_unmodeled_fits_WS_elevation{tag}.png", dpi=350) @@ -608,13 +632,14 @@ def plot_template_space_fits_per_wafer(solver_aman, config, save_dir, tag=""): eta_unmod[i::7] / ARCMIN - solver_aman.nom_ufm_centers[1, i] / ARCMIN, c=solver_aman.ancil.boresight_enc[i::7], s=scale_weights[i::7] * 80, + edgecolor="gray", + lw=0.3, marker="o", - lw=0, alpha=0.5, cmap="jet", ) - ax[i // 4, i % 4].set_xlim(-15, 15) - ax[i // 4, i % 4].set_ylim(-15, 15) + ax[i // 4, i % 4].set_xlim(-12, 12) + ax[i // 4, i % 4].set_ylim(-12, 12) ax[i // 4, i % 4].set_title(f"ws{i}") plt.colorbar(im, ax[1, 3], label="Boresight (deg)", fraction=0.046, pad=0.04) plt.tight_layout() @@ -671,7 +696,10 @@ def plot_residuals_vs_ancil(solver_aman, config, save_dir, tag): w=scale_weights[plotmask], ) xrange = np.arange(np.nanmin(x), np.nanmax(x)) - ax[i, j].plot(xrange, mxb[0] * xrange + mxb[1], "r", lw=1) + ax[i, j].plot(xrange, mxb[0] * xrange + mxb[1], "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]") @@ -681,12 +709,19 @@ def plot_residuals_vs_ancil(solver_aman, config, save_dir, tag): plt.savefig(f"{plot_dir}/{platform}_residuals_vs_ancillary{tag}.png", dpi=350) plt.close() -def plot_total_residuals(solver_aman, config, save_dir, tag, fit_residual_i1, fit_residual_i2=None, bad_fit_inds=None): +def plot_total_residuals(solver_aman, + config, + save_dir, + tag, + fit_residual_i1, + fit_residual_i2=None, + bad_fit_inds=None, + ): plot_dir = os.path.join(save_dir, "plots") os.makedirs(plot_dir, exist_ok=True) iterate_cutoff = config.get("iterate_cutoff", None) platform = config.get("platform") - + scale_weights = solver_aman.weights / np.nanmax(solver_aman.weights) if fit_residual_i2 is not None: fig = plt.figure(figsize=(6,4)) gs = fig.add_gridspec(7,1) @@ -703,14 +738,23 @@ def plot_total_residuals(solver_aman, config, save_dir, tag, fit_residual_i1, f ax1.plot(np.arange(len(fit_residual_i2)), fit_residual_i2 / ARCMIN, 'b*', alpha=0.5, lw=0, mew=0, label = '2nd fit') + xtox = np.empty((len(fit_residual_i2), 2)) + xtox[:, 0] = np.arange(len(fit_residual_i1)) + xtox[:, 1] = np.arange(len(fit_residual_i2)) + ytoy = np.empty((len(fit_residual_i1), 2)) + ytoy[:, 0] = fit_residual_i1 / ARCMIN + ytoy[:, 1] = fit_residual_i2 / ARCMIN + 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) + ax1.legend(loc=2,fontsize='small') - ax2.plot(np.arange(len(fit_residual_i1)), (fit_residual_i2 - fit_residual_i1) / ARCMIN, - 'k.', mew=0, alpha = 0.6, label = "Res i2 - Res i1") + ax2.scatter(np.arange(len(fit_residual_i1)), (fit_residual_i2 - fit_residual_i1) / ARCMIN, c='k', + marker = 'o', s = scale_weights*50, + lw=0, alpha = 0.6, label = "Res i2 - Res i1") ax2.plot(np.arange(len(fit_residual_i1))[bad_fit_inds], (fit_residual_i2 - fit_residual_i1)[bad_fit_inds] / ARCMIN, - 'kx', lw=0.2, alpha = 0.6, label = "Excl. from i2 fit") + '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) ax2.legend(fontsize='x-small') ax2.set_xlabel('Data points') @@ -718,12 +762,12 @@ def plot_total_residuals(solver_aman, config, save_dir, tag, fit_residual_i1, f plt.savefig(f"{plot_dir}/{platform}_total_residuals{tag}.png", dpi=350) else: - fig, ax = plt.subplots() + fig, ax1 = plt.subplots() #Plot first fit iteration residuals - ax.plot(np.arange(len(fit_residual_i1)), fit_residual_i1 / ARCMIN, - 'r.', mew=0, alpha=0.6, lw=0, label = '1st Fit') - ax.set_ylabel(r'Fit Residual $\left|\Delta\text{(xi, eta)}\right|$ [arcmin]') - ax.set_xlabel('Data points') + ax1.scatter(np.arange(len(fit_residual_i1)), fit_residual_i1 / ARCMIN, + s = scale_weights*50, color='r', lw=0, alpha=0.6, label = '1st Fit') + ax1.set_ylabel(r'Fit Residual $\left|\Delta\text{(xi, eta)}\right|$ [arcmin]') + ax1.set_xlabel('Data points') plt.legend(loc=2) plt.savefig(f"{plot_dir}/{platform}_total_residuals{tag}.png", dpi=350) plt.close() From 89ec639c88d5e511501a91b6fc50da83a6ecb0f8 Mon Sep 17 00:00:00 2001 From: Elle Shaw Date: Fri, 23 May 2025 13:00:48 -0700 Subject: [PATCH 024/132] Renamed map_based_pointing and update pointing to get_brightsrc_pointing_step1 and step2. Added functionality to run as parallel processing job on a cluster. Included some documentation in site_pipeline.rst --- docs/site_pipeline.rst | 184 ++++++++++++++++++ ...ased_pointing.py => brightsrc_pointing.py} | 33 ++-- ...ing.py => get_brightsrc_pointing_step1.py} | 116 ++++++++--- ...ing.py => get_brightsrc_pointing_step2.py} | 87 +++++++-- 4 files changed, 361 insertions(+), 59 deletions(-) rename sotodlib/coords/{map_based_pointing.py => brightsrc_pointing.py} (96%) rename sotodlib/site_pipeline/{make_mapbased_pointing.py => get_brightsrc_pointing_step1.py} (75%) rename sotodlib/site_pipeline/{update_pointing.py => get_brightsrc_pointing_step2.py} (88%) diff --git a/docs/site_pipeline.rst b/docs/site_pipeline.rst index d228a5580..4f8d7481b 100644 --- a/docs/site_pipeline.rst +++ b/docs/site_pipeline.rst @@ -157,6 +157,190 @@ work, here's a more basic example that will work:: stream_id: ufm_mv9 + +get_brightsrc_pointing_part1 and get_brightsrc_pointing_part2 +---------------------------------------------------------------- + +The two-part ``get_brightsrc_pointing`` script set will will run solve for the xieta +coordinates of detectors that observe a bright source during an observation. + +It is a two part process that requires a map step and then a tod step. +To run, the scripts require config files described below. + +The code will process all wafers unless otherwise specified. +It is recommended to run with ``parallel_job: True`` in the config files if analyzing +multiple wafers at once. Otherwise, specify a wafer slot or restrict detectors in CL args. + +Recommended SLURM settings + - ``--nodes=1`` + - ``--ntasks=1`` + - ``--time=00:45:00`` + - ``--cpus-per-task=14`` + - ``--mem=150G`` + - export OMP_NUM_THREADS=1 + + +Recommended Command Line arguments: + - ``configs`` + - ``--obs_id`` + - ``--sso_name`` + +Optional Command Line arguments: + - ``--wafer_slot`` e.g. ws0 + - ``--restrict_dets_for_debug`` integer, or comma separated list of det readout_ids. + +Options to include min_ctime and max_ctime arguments, which will proces all obs +in the time frame. + +.. argparse:: + :module: sotodlib.site_pipeline.get_brightsrc_pointing_part1 or _part2 + :func: get_parser + + + +Generated results +``````````````````` +Saves results as ResultSet .hdf file in the results_dir. +ResultSet<[dets:readout_id, xi, eta, gamma, xi_err, eta_err, R2, redchi2], N rows> + +Load data with sotodlib.io.metadata.read_dataset( results.hdf, 'focal_plane') + +Configuration +````````````````` +These scripts take in a config yaml file + +Part 1 is the map-based step. Its config file should look like the following: +The parameters in these examples are used for SAT mid-freq moon observations. + +.. code-block:: yaml + + context_file: /path/to/context.yaml + query_tags: ['moon', 'jupiter', 'mars'] (alternatively specify --sso_name in kwargs + + optics_config_fn: /path/to/ufm_to_fp.yaml + single_det_maps_dir: /path/to/results/single_det_maps + results_dir: /path/to/results/map_based_results + + parallel_job: True + wafer_mask_det: 8. + res_deg: 0.3 + xieta_bs_offset: [0., 0.] + save_normal_roll: False #false for SAT, true for LAT + save_force_zero_roll: True #true for SAT, false for LAT + + hit_time_threshold: 600 #seconds + hit_circle_r_deg: 7. + + process_pipe: + - name: 'detrend' + process: + count: 2000 + method: 'linear' + - name: 'apodize' + process: + apodize_samps: 2000 + - name: 'fourier_filter' + process: + signal_name: "signal" + wrap_name: null + filt_function: "low_pass_sine2" + trim_samps: null + filter_params: + cutoff: 1.9 + width: 0.2 + - name: 'fourier_filter' + process: + signal_name: "signal" + wrap_name: null + filt_function: "high_pass_sine2" + trim_samps: 2000 + filter_params: + cutoff: 0.05 + width: 0.1 + +Part 2 is the TOD-based step. Its config file should look like the following. +The parameters in these examples are used for SAT mid-freq moon observations. + +.. code-block:: yaml + + context_file: /path/to/context.yaml + query_tags: ['moon', 'jupiter', 'mars'] (alternatively specify --sso_name in kwargs + + optics_config_fn: /path/to/ufm_to_fp.yaml + + fp_hdf_dir: /path/to/results/map_based_results from step 1 config file. + # If force_zero_roll is was True, then append _force_zero_roll to the end + result_dir: /path/to/resuls/tod_based_results + + parallel_job: True + force_zero_roll: True + + ds_factor: 40 + mask_deg: 2.5 + fit_func_name: 'gaussian2d_nonlin' + max_non_linear_order: 3 + fwhm_init_deg: 0.5 + error_estimation_method: 'force_one_redchi2' + flag_name_rms_calc: 'around_source' + flag_rms_calc_exclusive: False + + process_pipe: + - name: 'detrend' + process: + count: 2000 + method: 'linear' + - name: 'fourier_filter' + process: + signal_name: 'signal' + filt_function: 'iir_filter' + trim_samps: null + filter_params: + invert: True + - name: 'apodize' + process: + apodize_samps: 2000 + - name: 'fourier_filter' + process: + signal_name: "signal" + wrap_name: null + filt_function: "low_pass_sine2" + trim_samps: null + filter_params: + cutoff: 1.9 + width: 0.2 + - name: 'source_flags' + calc: + merge: True + max_pix: 10000000000 + source_flags_name: 'source_wide' + mask: + shape: circle + xyr: [0., 0., 5.0] + - name: 'source_flags' + calc: + merge: True + max_pix: 10000000000 + source_flags_name: 'source_narrow' + mask: + shape: circle + xyr: [0., 0., 3.0] + - name: 'reduce_flags' + process: + flags: ['source_wide', 'source_narrow'] + method: 'except' + wrap: True + new_flag: 'around_source' + - name: 'flag_turnarounds' + process: + truncate: True + - name: 'sub_polyf' + process: + method: 'legendre' + degree: 2 + mask: 'around_source' + exclusive: False + + make_read_det_match ``````````````````` This script generates the readout ID to detector ID mapping required to diff --git a/sotodlib/coords/map_based_pointing.py b/sotodlib/coords/brightsrc_pointing.py similarity index 96% rename from sotodlib/coords/map_based_pointing.py rename to sotodlib/coords/brightsrc_pointing.py index 43305b37c..5985da6fe 100644 --- a/sotodlib/coords/map_based_pointing.py +++ b/sotodlib/coords/brightsrc_pointing.py @@ -4,6 +4,7 @@ import numpy as np from scipy import interpolate from scipy.optimize import curve_fit +from joblib import Parallel, delayed from sotodlib import core from sotodlib import coords @@ -16,7 +17,8 @@ import h5py from scipy.ndimage import maximum_filter -def get_planet_trajectry(tod, planet, _split=20, return_model=False): + +def get_planet_trajectory(tod, planet, _split=20, return_model=False): """ Generate the trajectory of a given planet over a specified time range. @@ -30,7 +32,7 @@ def get_planet_trajectry(tod, planet, _split=20, return_model=False): If return_model is True: tuple: Tuple containing interpolation functions for azimuth and elevation. If return_model is False: - array: Array of quaternions representing trajectry of the planet at each timestamp. + array: Array of quaternions representing trajectory of the planet at each timestamp. """ print(planet) timestamps_sparse = np.linspace(tod.timestamps[0], tod.timestamps[-1], _split) @@ -58,19 +60,19 @@ def get_wafer_centered_sight(tod=None, planet=None, q_planet=None, q_bs=None, q_ Parameters: tod : An axis manager planet (str): The name of the planet to calculate the sightline vector. - q_planet (optional): Quaternion representing the trajectry of the planet. + q_planet (optional): Quaternion representing the trajectory of the planet. If None, it will be computed using get_planet_trajectory. Defaults to None. - q_bs (optional): Quaternion representing the trajectry of the boresight. + q_bs (optional): Quaternion representing the trajectory of the boresight. If None, it will be computed using the current boresight angles from tod. Defaults to None. q_wafer (optional): Quaternion representing the center of wafer to the center of boresight. If None, it will be computed using the median of the focal plane xi and eta from tod.focal_plane. Defaults to None. Returns: - Sightline vector for the planet trajectry centered on the center of the wafer. + Sightline vector for the planet trajectory centered on the center of the wafer. """ if q_planet is None: - q_planet = get_planet_trajectry(tod, planet) + q_planet = get_planet_trajectory(tod, planet) if q_bs is None: q_bs = quat.rotation_lonlat(tod.boresight.az, tod.boresight.el) if q_wafer is None: @@ -147,7 +149,7 @@ def get_rough_hit_time(tod, wafer_slot, sso_name, circle_r_deg=7.,optics_config_ float: Estimated rough hit time within the circular region around the wafer center. """ q_bs = quat.rotation_lonlat(tod.boresight.az, tod.boresight.el) - q_planet = get_planet_trajectry(tod, sso_name) + q_planet = get_planet_trajectory(tod, sso_name) xi_wafer, eta_wafer = get_wafer_xieta(wafer_slot, optics_config_fn=optics_config_fn, roll_bs_offset=np.median(tod.boresight.roll), wrap_to_tod=False) q_wafer = quat.rotation_xieta(xi_wafer, eta_wafer) @@ -159,13 +161,11 @@ def get_rough_hit_time(tod, wafer_slot, sso_name, circle_r_deg=7.,optics_config_ hit_time = (tod.timestamps[-1] - tod.timestamps[0]) * np.mean(np.rad2deg(r_wafer_centered) < circle_r_deg) return hit_time - def make_wafer_centered_maps(tod, sso_name, optics_config_fn, map_hdf, xieta_bs_offset=(0., 0.), roll_bs_offset=None, signal='signal', wafer_mask_deg=8., res_deg=0.3, cuts=None,): """ Generate boresight-centered maps from Time-Ordered Data (TOD) for each individual detector. - Parameters: tod : an axismanager object sso_name (str): Name of the planet for which the trajectory is calculated. @@ -181,9 +181,8 @@ def make_wafer_centered_maps(tod, sso_name, optics_config_fn, map_hdf, Returns: None """ - q_planet = get_planet_trajectry(tod, sso_name) + q_planet = get_planet_trajectory(tod, sso_name) q_bs = quat.rotation_lonlat(tod.boresight.az, tod.boresight.el) - if roll_bs_offset is None: roll_bs_offset = np.mean(tod.boresight.roll) @@ -218,16 +217,22 @@ def make_wafer_centered_maps(tod, sso_name, optics_config_fn, map_hdf, if cuts is None: cuts = ~tod.flags['source'] P = coords.P.for_tod(tod=tod, geom=geom, comps='T', cuts=cuts, sight=sight, threads=False) + + wT = None for di, det in enumerate(tqdm(tod.dets.vals)): det_weights = np.zeros(tod.dets.count, dtype='float32') det_weights[di] = 1. mT_weighted = P.to_map(tod=tod, signal=signal, comps='T', det_weights=det_weights) - wT = P.to_weights(tod, signal=signal, comps='T', det_weights=det_weights) + if wT is None: + wT = P.to_weights(tod, signal=signal, comps='T', det_weights=det_weights) mT = P.remove_weights(signal_map=mT_weighted, weights_map=wT, comps='T')[0] enmap.write_hdf(map_hdf, mT, address=det, - extra={'xi0': xi0, 'eta0': eta0, - 'xi_bs_offset': xi_bs_offset, 'eta_bs_offset': eta_bs_offset, 'roll_bs_offset': roll_bs_offset}) + extra={'xi0': xi0, + 'eta0': eta0, + 'xi_bs_offset': xi_bs_offset, + 'eta_bs_offset': eta_bs_offset, + 'roll_bs_offset': roll_bs_offset}) return def detect_peak_xieta(mT, filter_size=None): diff --git a/sotodlib/site_pipeline/make_mapbased_pointing.py b/sotodlib/site_pipeline/get_brightsrc_pointing_step1.py similarity index 75% rename from sotodlib/site_pipeline/make_mapbased_pointing.py rename to sotodlib/site_pipeline/get_brightsrc_pointing_step1.py index faed09a43..2b7aea511 100644 --- a/sotodlib/site_pipeline/make_mapbased_pointing.py +++ b/sotodlib/site_pipeline/get_brightsrc_pointing_step1.py @@ -4,12 +4,12 @@ import argparse import time import glob +from joblib import Parallel, delayed from sotodlib import core from sotodlib import coords from sotodlib import tod_ops -from sotodlib.coords import map_based_pointing as mbp -from sotodlib.site_pipeline import update_pointing as up +from sotodlib.coords import brightsrc_pointing as bsp from sotodlib.io import metadata from sotodlib.io.metadata import read_dataset, write_dataset @@ -17,7 +17,7 @@ from sotodlib.preprocess import Pipeline logger = util.init_logger(__name__, 'make_map_based_pointing: ') -def _get_sso_names_from_tags(ctx, obs_id, candidate_names=['moon', 'jupiter']): +def _get_sso_names_from_tags(ctx, obs_id, candidate_names=['moon', 'jupiter', 'mars']): obs_tags = ctx.obsdb.get(obs_id, tags=True)['tags'] sso_names = [] for _name in candidate_names: @@ -58,31 +58,44 @@ def main_one_wafer(configs, obs_id, wafer_slot, sso_name=None, f'Processing only {sso_name}') # Load data - logger.info('loading data') + logger.info(f'loading meta data: {wafer_slot}') meta = ctx.get_meta(obs_id, dets={'wafer_slot': wafer_slot}) + logger.info(f'finished loading meta data: {wafer_slot}') + try: + meta.restrict('dets', meta.detcal.bg > -1) + except: + pass if restrict_dets_for_debug is not False: - meta.restrict('dets', meta.dets.vals[:restrict_dets_for_debug]) + try: + restrict_dets_for_debug = int(restrict_dets_for_debug) + meta.restrict('dets', meta.dets.vals[:restrict_dets_for_debug]) + except ValueError: + _testdets = restrict_dets_for_debug.split(',') + restrict_list = [det.split('\'')[1].strip() for det in _testdets] + meta.restrict('dets', restrict_list) + logger.info(f'loading tod data: {wafer_slot}') tod = ctx.get_obs(meta) - + logger.info(f'finished loading tod data: {wafer_slot}') # tod processing - logger.info('tod processing') + logger.info(f'tod processing {wafer_slot}') pipe = Pipeline(configs["process_pipe"], logger=logger) proc_aman, success = pipe.run(tod) - + logger.info(f'done with tod processing {wafer_slot}') # make single detecctor maps logger.info(f'Making single detector maps') os.makedirs(single_det_maps_dir, exist_ok=True) map_hdf = os.path.join(single_det_maps_dir, f'{obs_id}_{wafer_slot}.hdf') - mbp.make_wafer_centered_maps(tod, sso_name, optics_config_fn, map_hdf=map_hdf, + bsp.make_wafer_centered_maps(tod, sso_name, optics_config_fn, map_hdf=map_hdf, xieta_bs_offset=xieta_bs_offset, wafer_mask_deg=wafer_mask_deg, res_deg=res_deg) - + + #next step result_filename = f'focal_plane_{obs_id}_{wafer_slot}.hdf' # reconstruct pointing from single detector maps if save_normal_roll: logger.info(f'Saving map-based pointing results') - fp_rset_map_based = mbp.get_xieta_from_maps(map_hdf, save=True, + fp_rset_map_based = bsp.get_xieta_from_maps(map_hdf, save=True, output_dir=result_dir, filename=result_filename, force_zero_roll=False, @@ -91,7 +104,7 @@ def main_one_wafer(configs, obs_id, wafer_slot, sso_name=None, if save_force_zero_roll: logger.info(f'Saving map-based pointing results (force-zero-roll)') result_dir_force_zero_roll = result_dir + '_force_zero_roll' - fp_rset_map_based_force_zero_roll = mbp.get_xieta_from_maps(map_hdf, save=True, + fp_rset_map_based_force_zero_roll = bsp.get_xieta_from_maps(map_hdf, save=True, output_dir=result_dir_force_zero_roll, filename=result_filename, force_zero_roll=True, @@ -109,7 +122,13 @@ def main_one_wafer_dummy(configs, obs_id, wafer_slot, restrict_dets_for_debug=Fa meta = ctx.get_meta(obs_id, dets={'wafer_slot': wafer_slot}) if restrict_dets_for_debug is not False: - meta.restrict('dets', meta.dets.vals[:restrict_dets_for_debug]) + try: + restrict_dets_for_debug = int(restrict_dets_for_debug) + meta.restrict('dets', meta.dets.vals[:restrict_dets_for_debug]) + except ValueError: + _testdets = restrict_dets_for_debug.split(',') + restrict_list = [det.split('\'')[1].strip() for det in _testdets] + meta.restrict('dets', restrict_list) result_filename = f'focal_plane_{obs_id}_{wafer_slot}.hdf' fp_rset_dummy_map_based = metadata.ResultSet(keys=['dets:readout_id', 'xi', 'eta', 'gamma', 'R2']) @@ -150,6 +169,15 @@ def combine_pointings(pointing_result_files): focal_plane.rows.append((det, val['xi'], val['eta'], val['gamma'], val['R2'])) return focal_plane +def parallel_process_wafer_slot(configs, obs_id, wafer_slot, sso_name, restrict_dets_for_debug): + logger.info(f'Processing {obs_id}, {wafer_slot}') + main_one_wafer(configs=configs, + obs_id=obs_id, + wafer_slot=wafer_slot, + sso_name=sso_name, + restrict_dets_for_debug=restrict_dets_for_debug) + + def main_one_obs(configs, obs_id, sso_name=None, restrict_dets_for_debug=False): if type(configs) == str: @@ -176,26 +204,57 @@ def main_one_obs(configs, obs_id, sso_name=None, tod = ctx.get_obs(obs_id, dets=[]) streamed_wafer_slots = ['ws{}'.format(index) for index, bit in enumerate(obs_id.split('_')[-1]) if bit == '1'] processed_wafer_slots = [] + finished_wafer_slots = [] skipped_wafer_slots = [] + check_dir = result_dir + '_force_zero_roll' if save_force_zero_roll else result_dir for ws in streamed_wafer_slots: - hit_time = mbp.get_rough_hit_time(tod, wafer_slot=ws, sso_name=sso_name, circle_r_deg=hit_circle_r_deg, - optics_config_fn=optics_config_fn) + hit_time = bsp.get_rough_hit_time(tod, + wafer_slot=ws, + sso_name=sso_name, + circle_r_deg=hit_circle_r_deg, + optics_config_fn=optics_config_fn) logger.info(f'hit_time for {ws} is {hit_time:.1f} [sec]') - if hit_time > hit_time_threshold: - processed_wafer_slots.append(ws) + if hit_time >= hit_time_threshold: + if os.path.exists(os.path.join(check_dir, f'focal_plane_{obs_id}_{ws}.hdf')): + finished_wafer_slots.append(ws) + else: + processed_wafer_slots.append(ws) else: skipped_wafer_slots.append(ws) - logger.info(f'wafer_slots which pointing calculated: {processed_wafer_slots}') - for wafer_slot in processed_wafer_slots: - logger.info(f'Processing {obs_id}, {wafer_slot}') - main_one_wafer(configs=configs, - obs_id=obs_id, - wafer_slot=wafer_slot, - sso_name=sso_name, - restrict_dets_for_debug=restrict_dets_for_debug) - + logger.info(f'Found saved data for these wafer_slots: {finished_wafer_slots}') + logger.info(f'Will continue for these wafer_slots: {processed_wafer_slots}') + + if configs.get('parallel_job'): + logger.info('Continuing with parallel job') + try: + n_jobs = int(os.environ.get('SLURM_CPUS_PER_TASK', 1)) + except: + n_jobs = -1 + + logger.info('Entering wafer pool') + Parallel(n_jobs=n_jobs)( + delayed(parallel_process_wafer_slot)( + configs, + obs_id, + wafer_slot, + sso_name, + restrict_dets_for_debug, + ) + for wafer_slot in processed_wafer_slots + ) + logger.info('Exiting wafer pool') + else: + logger.info('Continuing with serial processing of wafers.') + for wafer_slot in processed_wafer_slots: + logger.info(f'Processing {obs_id}, {wafer_slot}') + main_one_wafer(configs=configs, + obs_id=obs_id, + wafer_slot=wafer_slot, + sso_name=sso_name, + restrict_dets_for_debug=restrict_dets_for_debug) + logger.info(f'create dummy hdf for non-hitting wafer: {skipped_wafer_slots}') for wafer_slot in skipped_wafer_slots: main_one_wafer_dummy(configs=configs, @@ -220,7 +279,7 @@ def main_one_obs(configs, obs_id, sso_name=None, write_dataset(fp_rset_full, filename=fp_rset_full_file, address='focal_plane', overwrite=True) - + logger.info(f'ta da! Finished with {obs_id}') return def main(configs, min_ctime=None, max_ctime=None, update_delay=None, @@ -258,6 +317,7 @@ def main(configs, min_ctime=None, max_ctime=None, update_delay=None, restrict_dets_for_debug=restrict_dets_for_debug) elif obs_id is not None: + logger.info(f'Processing {obs_id}') if wafer_slot is None: main_one_obs(configs=configs, obs_id=obs_id, sso_name=sso_name, restrict_dets_for_debug=restrict_dets_for_debug) @@ -280,7 +340,7 @@ def get_parser(): parser.add_argument("--sso_name", type=str, default=None, help="Name of solar system object (e.g., 'moon', 'jupiter'). If not specified, get sso_name from observation tags. "\ + "Valid only when obs_id is specified") - parser.add_argument("--restrict_dets_for_debug", type=int, default=False) + parser.add_argument("--restrict_dets_for_debug", type=str, default=False) return parser if __name__ == '__main__': diff --git a/sotodlib/site_pipeline/update_pointing.py b/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py similarity index 88% rename from sotodlib/site_pipeline/update_pointing.py rename to sotodlib/site_pipeline/get_brightsrc_pointing_step2.py index 2098ebbd3..6081d1800 100644 --- a/sotodlib/site_pipeline/update_pointing.py +++ b/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py @@ -6,11 +6,12 @@ import time import glob from tqdm import tqdm +from joblib import Parallel, delayed from scipy.optimize import curve_fit from sotodlib.core import metadata from sotodlib.io.metadata import read_dataset, write_dataset -from sotodlib.coords import map_based_pointing as mbp +from sotodlib.coords import brightsrc_pointing as bsp from sotodlib import core from sotodlib import coords from sotodlib import tod_ops @@ -334,7 +335,14 @@ def main_one_wafer(configs, obs_id, wafer_slot, sso_name=None, logger.info('loading data') meta = ctx.get_meta(obs_id, dets={'wafer_slot': wafer_slot}) if restrict_dets_for_debug is not False: - meta.restrict('dets', meta.dets.vals[:restrict_dets_for_debug]) + try: + restrict_dets_for_debug = int(restrict_dets_for_debug) + meta.restrict('dets', meta.dets.vals[:restrict_dets_for_debug]) + except ValueError: + _testdets = restrict_dets_for_debug.split(',') + restrict_list = [det.split('\'')[1].strip() for det in _testdets] + meta.restrict('dets', restrict_list) + tod = ctx.get_obs(meta) # get pointing @@ -372,7 +380,13 @@ def main_one_wafer_dummy(configs, obs_id, wafer_slot, restrict_dets_for_debug=Fa meta = ctx.get_meta(obs_id, dets={'wafer_slot': wafer_slot}) if restrict_dets_for_debug is not False: - meta.restrict('dets', meta.dets.vals[:restrict_dets_for_debug]) + try: + restrict_dets_for_debug = int(restrict_dets_for_debug) + meta.restrict('dets', meta.dets.vals[:restrict_dets_for_debug]) + except ValueError: + _testdets = restrict_dets_for_debug.split(',') + restrict_list = [det.split('\'')[1].strip() for det in _testdets] + meta.restrict('dets', restrict_list) result_filename = f'focal_plane_{obs_id}_{wafer_slot}.hdf' fp_rset_dummy = metadata.ResultSet(keys=['dets:readout_id', 'xi', 'eta', 'gamma', @@ -408,6 +422,14 @@ def combine_pointings(pointing_result_files): focal_plane.rows.append((det, val['xi'], val['eta'], val['gamma'], val['xi_err'], val['eta_err'], val['R2'], val['redchi2'])) return focal_plane +def parallel_process_wafer_slot(configs, obs_id, wafer_slot, sso_name, restrict_dets_for_debug): + logger.info(f'Processing {obs_id}, {wafer_slot}') + main_one_wafer(configs=configs, + obs_id=obs_id, + wafer_slot=wafer_slot, + sso_name=sso_name, + restrict_dets_for_debug=restrict_dets_for_debug) + def main_one_obs(configs, obs_id, sso_name=None, restrict_dets_for_debug=False): if type(configs) == str: @@ -434,25 +456,54 @@ def main_one_obs(configs, obs_id, sso_name=None, tod = ctx.get_obs(obs_id, dets=[]) streamed_wafer_slots = ['ws{}'.format(index) for index, bit in enumerate(obs_id.split('_')[-1]) if bit == '1'] processed_wafer_slots = [] + finished_wafer_slots = [] skipped_wafer_slots = [] + check_dir = result_dir + '_force_zero_roll' if force_zero_roll else result_dir + for ws in streamed_wafer_slots: - hit_time = mbp.get_rough_hit_time(tod, wafer_slot=ws, sso_name=sso_name, circle_r_deg=hit_circle_r_deg, - optics_config_fn=optics_config_fn) + hit_time = bsp.get_rough_hit_time(tod, + wafer_slot=ws, + sso_name=sso_name, + circle_r_deg=hit_circle_r_deg, + optics_config_fn=optics_config_fn) logger.info(f'hit_time for {ws} is {hit_time:.1f} [sec]') - if hit_time > hit_time_threshold: - processed_wafer_slots.append(ws) + if hit_time >= hit_time_threshold: + if os.path.exists(os.path.join(check_dir, f'focal_plane_{obs_id}_{ws}.hdf')): + finished_wafer_slots.append(ws) + else: + processed_wafer_slots.append(ws) else: skipped_wafer_slots.append(ws) - - logger.info(f'wafer_slots which pointing calculated: {processed_wafer_slots}') - for wafer_slot in processed_wafer_slots: - logger.info(f'Processing {obs_id}, {wafer_slot}') - main_one_wafer(configs=configs, - obs_id=obs_id, - wafer_slot=wafer_slot, - sso_name=sso_name, - restrict_dets_for_debug=restrict_dets_for_debug) - + + logger.info(f'Found saved data for these wafer_slots: {finished_wafer_slots}') + logger.info(f'Will continue for these wafer_slots: {processed_wafer_slots}') + + if configs.get('parallel_job'): + logger.info('Continuing with parallel job') + try: + n_jobs = int(os.environ.get('SLURM_CPUS_PER_TASK', 1)) + except: + n_jobs = -1 + Parallel(n_jobs=n_jobs)( + delayed(parallel_process_wafer_slot)( + configs, + obs_id, + wafer_slot, + sso_name, + restrict_dets_for_debug + ) + for wafer_slot in processed_wafer_slots + ) + else: + logger.info('Continuing with serial processing of wafers.') + for wafer_slot in processed_wafer_slots: + logger.info(f'Processing {obs_id}, {wafer_slot}') + main_one_wafer(configs=configs, + obs_id=obs_id, + wafer_slot=wafer_slot, + sso_name=sso_name, + restrict_dets_for_debug=restrict_dets_for_debug) + logger.info(f'create dummy hdf for non-hitting wafer: {skipped_wafer_slots}') for wafer_slot in skipped_wafer_slots: main_one_wafer_dummy(configs=configs, @@ -466,6 +517,7 @@ def main_one_obs(configs, obs_id, sso_name=None, fp_rset_full_file = os.path.join(os.path.join(result_dir, f'focal_plane_{obs_id}_all.hdf')) write_dataset(fp_rset_full, filename=fp_rset_full_file, address='focal_plane', overwrite=True) + logger.info(f'ta da! Finsihed with {obs_id}') def main(configs, min_ctime=None, max_ctime=None, update_delay=None, obs_id=None, wafer_slot=None, sso_name=None, restrict_dets_for_debug=False): @@ -502,6 +554,7 @@ def main(configs, min_ctime=None, max_ctime=None, update_delay=None, restrict_dets_for_debug=restrict_dets_for_debug) elif obs_id is not None: + logger.info(f'Processing {obs_id}') if wafer_slot is None: main_one_obs(configs=configs, obs_id=obs_id, sso_name=sso_name, restrict_dets_for_debug=restrict_dets_for_debug) From 4ac7e450ccffeb11b5fe5ee5798dd3c2071ca6ed Mon Sep 17 00:00:00 2001 From: Elle Shaw Date: Tue, 15 Jul 2025 16:57:06 -0700 Subject: [PATCH 025/132] Major update to solve_pointing_model.py to include per-detector fitting option and new plotting class. --- .../site_pipeline/solve_pointing_model.py | 2047 ++++++++++++----- 1 file changed, 1431 insertions(+), 616 deletions(-) diff --git a/sotodlib/site_pipeline/solve_pointing_model.py b/sotodlib/site_pipeline/solve_pointing_model.py index 8adead517..b1b21fb57 100644 --- a/sotodlib/site_pipeline/solve_pointing_model.py +++ b/sotodlib/site_pipeline/solve_pointing_model.py @@ -1,16 +1,25 @@ -import os, sys, pickle, math, h5py -import numpy as np +import os +import pickle +import math +import h5py import argparse -import so3g.proj.quat as quat -import lmfit -from lmfit import minimize, Parameters import yaml import logging +import numpy as np +import so3g.proj.quat as quat +import pdb +# import lmfit +import lmfit +from lmfit import minimize, Parameters, fit_report +import time +import shutil + import matplotlib matplotlib.use("agg") import matplotlib.pyplot as plt +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 @@ -23,7 +32,7 @@ plt.rcParams["grid.alpha"] = 0.5 -def load_nom_centers(config): +def load_nom_ufm_centers(config): # Load Nominal UFM Center Locations from centered focal_plane ffp_path = config.get("ffp_path") ufms = config.get("ufms") @@ -31,24 +40,33 @@ def load_nom_centers(config): rx = fpc.Receiver.load_file(ffp_path) OT = rx["0"].optics_tubes[0] for ufm in range(len(OT.focal_planes)): - index = ufms.index(OT.focal_planes[ufm].stream_id) + 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 return nom_ufm_centers - -def _load_per_obs_data(config): +def load_per_obs_data(config): # Load per-observation UFM center data points and weights # The per obs .h5 file a dict with obs_id for keys per_obs_fps = config.get("per_obs_fps") ufms = config.get("ufms") skip_tags = config.get("skip_tags", []) + t0 = config.get("begin_timerange", 0) + tf = config.get("end_timerange", 3000000000) rxs = fpc.Receiver.load_file(per_obs_fps) - filelist = list(rxs.keys()) - for skip in skip_tags: - filelist = [obs for obs in filelist if skip not in obs] + + 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 = [] for i, ffp in enumerate(filelist): this_OT = rxs[ffp].optics_tubes[0] @@ -56,70 +74,260 @@ def _load_per_obs_data(config): 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) + obs_index.append(np.repeat(i, 7)) + 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.concatenate(obs_index) + #obs_index[initial_weights_mask] = np.nan + + return filelist, obs_ufm_centers, weights_ufm, obs_index + +def load_nom_focal_plane_full(config, ufm): + which_template = config.get("use_as_template", "ffp") + 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["0/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): + # 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, return_all_dets=False): + per_obs_fps = config.get("per_obs_fps") + skip_tags = config.get("skip_tags", []) + t0 = config.get("begin_timerange", 0) + tf = config.get("end_timerange", int(time.time())) + rxs = fpc.Receiver.load_file(per_obs_fps) + 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) + + 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")] + + weights_dets, obs_dets_fits, stream_id_list, obs_index = [], [], [], [] + which_ufm = config.get("which_ufm", None) + which_data = config.get("use_as_data") + which_weights = config.get("use_as_weights", None) + + for i, ffp in enumerate(filelist): + this_OT = rxs[ffp].optics_tubes[0] + for ufm in this_OT.focal_planes: + if which_ufm is not None and ufm.stream_id not in which_ufm: + continue + stream_id_list.append(ufm.stream_id) + weights = ufm.weights[:, 1] if which_weights == "r2" else ufm.weights[:, 0] + data = ufm.avg_fp if which_data == "raw" else ufm.transformed + weights_dets.append(weights) + obs_dets_fits.append(data) + obs_index.append(np.repeat(i, len(ufm.weights))) + + nom_data = [load_nom_focal_plane_full(config, s) for s in stream_id_list] + all_det_ids, all_nom_det_array = map(np.concatenate, zip(*nom_data)) + weights_dets = np.concatenate(weights_dets) + obs_dets_fits = np.concatenate(obs_dets_fits, axis=0) + obs_index = np.concatenate(obs_index) + + weights_dets[weights_dets < config.get("weight_cutoff")] = 0.0 + obs_dets_fits[np.where(weights_dets == 0)] = np.nan + mask = ~np.isnan(weights_dets) + + if return_all_dets: + #plotting use-case to compare subset fits with the entire dataset. + return ( + filelist, + obs_dets_fits[mask], + weights_dets[mask], + all_nom_det_array[mask], + all_det_ids[mask], + obs_index[mask], + ) - return filelist, obs_ufm_centers, weights_ufm - + else: + # Reduce detector counts for computation + if band is not None: + mask &= np.array([band in det for det in all_det_ids]) + #apply weights and band mask + obs_dets_fits = obs_dets_fits[mask] + weights_dets = weights_dets[mask] + all_nom_det_array = all_nom_det_array[mask] + all_det_ids = all_det_ids[mask] + obs_index = obs_index[mask] + if even_obs_size: + mask = create_size_mask(obs_index) + obs_dets_fits = obs_dets_fits[mask] + weights_dets = weights_dets[mask] + all_nom_det_array = all_nom_det_array[mask] + all_det_ids = all_det_ids[mask] + obs_index = obs_index[mask] + if cull_dets is not None: + for _ in range(2 if cull_twice else 1): + mask = create_culling_mask(obs_index, cull_dets) + obs_dets_fits = obs_dets_fits[mask] + weights_dets = weights_dets[mask] + all_nom_det_array = all_nom_det_array[mask] + all_det_ids = all_det_ids[mask] + obs_index = obs_index[mask] + return ( + filelist, + obs_dets_fits, + weights_dets, + all_nom_det_array, + all_det_ids, + obs_index + ) -def _load_obs_boresight(config, filelist): +def load_obs_boresight(config, filelist): # Load boresight elevation information from each observation # Put into an axis manager + pm_version = config.get("pm_version") ctx = core.Context(config["context"]["path"]) obs_info = [ctx.obsdb.get(obsid) for obsid in filelist] - az_c = [obs["az_center"] for obs in obs_info] - el_c = [obs["el_center"] for obs in obs_info] - roll_c = [obs["roll_center"] for obs in obs_info] - az_c = np.round(np.array(az_c), 4) - el_c = np.round(np.array(el_c), 4) - roll_c = np.round(np.array(roll_c), 4) - roll_c[np.where(roll_c == 0)[0]] = 0 # rounding gives negative 0 sometimes. + 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]) + #az_c = np.round(np.array(az_c), 4) + #el_c = np.round(np.array(el_c), 4) + #roll_c = np.round(np.array(roll_c), 4) + #roll_c[np.where(roll_c == 0)[0]] = 0 # rounding gives negative 0 sometimes. ancil = core.AxisManager(core.IndexAxis("samps")) ancil.wrap("az_enc", np.repeat(az_c, 7), [(0, "samps")]) - ancil.wrap("boresight_enc", np.repeat(-1 * roll_c, 7), [(0, "samps")]) ancil.wrap("el_enc", np.repeat(el_c, 7), [(0, "samps")]) + if "lat" in pm_version: + ancil.wrap("corotator_enc", np.repeat((el_c - 60. - roll_c), 7), [(0, "samps")]) + if "sat" in pm_version: + ancil.wrap("boresight_enc", np.repeat(-1 * roll_c, 7), [(0, "samps")]) + return ancil, roll_c + + +def load_obs_boresight_per_detector(config, filelist, obs_ind): + # Load boresight elevation information from each observation + # Put into an axis manager + platform = config.get("platform") + 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")) + if platform == 'lat': + roll_c = np.array([roll_c[i] for i in obs_ind]) + ancil.wrap("az_enc", np.array([az_c[i] for i in obs_ind]), [(0, "samps")]) + ancil.wrap("el_enc", np.array([el_c[i] for i in obs_ind]), [(0, "samps")]) + ancil.wrap("corotator_enc", ancil.el_enc - 60. - roll_c, [(0, "samps")]) + else: + roll_c = np.array([roll_c[i] for i in obs_ind]) + ancil.wrap("az_enc", np.array([az_c[i] for i in obs_ind]), [(0, "samps")]) + ancil.wrap("el_enc", np.array([el_c[i] for i in obs_ind]), [(0, "samps")]) + ancil.wrap("boresight_enc", -1 * roll_c, [(0, "samps")]) return ancil, roll_c def _init_fit_params(config): - default_params = pm.defaults_sat_v1 - fixed_params = config.get("fixed_params") + pm_version = config.get("pm_version") + init_params = config.get("initial_params", pm.param_defaults[pm_version]) + fixed_params = config.get("fixed_params",None) # Initialize lmfit Parameter object fit_params = Parameters() - for p in list(default_params.keys()): - fit_params.add(p, value=0.0, vary=True) + for p in init_params.keys(): + fit_params.add(p, value=init_params[p], vary=True) # Turn off various parameters depending on platform - for fix in fixed_params: - fit_params[fix].set(vary=False) + if fixed_params is not None: + for fix in fixed_params: + fit_params[fix].set(vary=False) return fit_params +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 + dist = np.sqrt((xi_ref - xi_mod) ** 2 + (eta_ref - eta_mod) ** 2) + #print(np.nansum(dist)) + weights_array = solver_aman.weights if weights else np.ones(len(dist)) + return chi_sq(weights_array, dist) def chi_sq(weights, dist): N = np.identity(len(dist)) * weights chi2 = dist.T * N * dist + #chi2 = dist.T @ N @ dist return chi2 - -def model_template_xieta(params, pm_version, solver_aman): +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 = solver_aman.ffp_ufm_center_fits[0] - eta_meas = solver_aman.ffp_ufm_center_fits[1] - if type(params) == lmfit.parameter.Parameters: - params = params.valuesdict() + xi_meas = aman.measured_xieta_data[0] + eta_meas = aman.measured_xieta_data[1] + params = params.valuesdict() if isinstance(params, Parameters) else params + # if type(params) == lmfit.parameter.Parameters: + # params = params.valuesdict() params["version"] = pm_version if "sat" in pm_version: - az, el, roll = pm._get_sat_enc_radians(solver_aman.ancil) - boresight = pm.apply_pointing_model(solver_aman, pointing_model=params, wrap=False) + az, el, roll = pm._get_sat_enc_radians(aman.ancil) + if "lat" in pm_version: + az, el, roll = pm._get_lat_enc_radians(aman.ancil) + boresight = pm.apply_pointing_model(aman, pointing_model=params, wrap=False) az1, el1, roll1 = boresight.az, boresight.el, boresight.roll q_nomodel = quat.rotation_lonlat(-az, el, 0) q_model = quat.rotation_lonlat(-az1, el1, roll1) @@ -127,24 +335,25 @@ def model_template_xieta(params, pm_version, solver_aman): 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, solver_aman): + +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 """ - if type(params) == lmfit.parameter.Parameters: - params = params.valuesdict() + params = params.valuesdict() if isinstance(params, Parameters) else params + # if type(params) == lmfit.parameter.Parameters: + # params = params.valuesdict() params["version"] = pm_version - xi_true, eta_true, gam_true = solver_aman.nom_ufm_centers + xi_true, eta_true, gam_true = aman.nominal_xieta_locs if "sat" in pm_version: - az, el, roll = pm._get_sat_enc_radians(solver_aman.ancil) - boresight = pm.apply_pointing_model(solver_aman, pointing_model=params, wrap=False) + az, el, roll = pm._get_sat_enc_radians(aman.ancil) + if "lat" in pm_version: + az, el, roll = pm._get_lat_enc_radians(aman.ancil) + boresight = pm.apply_pointing_model(aman, pointing_model=params, wrap=False) az1, el1, roll1 = boresight.az, boresight.el, boresight.roll q_nomodel = quat.rotation_lonlat(-az, el, 0) @@ -157,34 +366,30 @@ def model_measured_xieta(params, pm_version, solver_aman): return xi_mod_meas, eta_mod_meas -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.ffp_ufm_center_fits - elif xieta_model == "template": - xi_mod, eta_mod = model_template_xieta(params, pm_version, solver_aman) - xi_ref, eta_ref, _ = solver_aman.nom_ufm_centers - - dist = [] - for i in range(len(xi_mod)): - dist.append(math.dist([xi_ref[i], eta_ref[i]], [xi_mod[i], eta_mod[i]])) - if weights: - return chi_sq(solver_aman.weights, np.array(dist)) - else: - return chi_sq(np.ones(len(dist)), np.array(dist)) - - -def get_RMS(model_xieta, ref_xieta, weights, use_inds=None): +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 = ((model_xieta[0] - ref_xieta[0])[use_inds] / ARCMIN) ** 2 + \ - ((model_xieta[1] - ref_xieta[1])[use_inds] / ARCMIN) ** 2 + diff = diff[use_inds] weights = weights[use_inds] - else: - diff = ((model_xieta[0] - ref_xieta[0]) / ARCMIN) ** 2 + \ - ((model_xieta[1] - ref_xieta[1]) / ARCMIN) ** 2 - return (np.nansum(diff * weights) / np.nansum(weights)) ** 0.5 + 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 + ) + 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): @@ -202,6 +407,7 @@ def _create_db(filename, save_dir): else: os.makedirs(save_dir, exist_ok=True) scheme = core.metadata.ManifestScheme() + scheme.add_range_match("obs:obs_timestamp") scheme.add_data_field("dataset") return core.metadata.ManifestDb(db_filename, scheme=scheme) @@ -213,33 +419,6 @@ def get_parser(parser=None): return parser -def build_param_fit_stat_aman(output): - # takes output of lmfit.minimize() - parameter_fit_stats = core.AxisManager(core.IndexAxis("parameters")) - parameter_fit_stats.wrap( - "name", np.array([output.params[p].name for p in output.params]) - ) - parameter_fit_stats.wrap( - "value", np.array([output.params[p].value for p in output.params]) - ) - parameter_fit_stats.wrap( - "vary", np.array([output.params[p].vary for p in output.params]) - ) - parameter_fit_stats.wrap( - "min", np.array([output.params[p].min for p in output.params]) - ) - parameter_fit_stats.wrap( - "max", np.array([output.params[p].max for p in output.params]) - ) - parameter_fit_stats.wrap( - "stderr", np.array([output.params[p].stderr for p in output.params]) - ) - parameter_fit_stats.wrap( - "correl", np.array([output.params[p].correl for p in output.params]) - ) - return parameter_fit_stats - - def main(config_path: str): # Read relevant config file info with open(config_path, "r", encoding="utf-8") as file: @@ -250,12 +429,32 @@ def main(config_path: str): xieta_model = config.get("xieta_model", "measured") xe_tag = f"{xieta_model}_xieta" iterate_cutoff = config.get("iterate_cutoff", None) - append = config.get("append", "") - append_tag = f"{bool(append)*'_'}{append}" + 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}" + 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") @@ -273,64 +472,158 @@ def main(config_path: str): "Pointing model will try to replicate (model) the %s data.", xieta_model ) - # Load in focal_plane and boresigt data - nom_ufm_centers = load_nom_centers(config) - logger.info("Loaded nominal UFM centers from %s: ", config.get("ffp_path")) - logger.info(nom_ufm_centers) - - filelist, obs_ufm_centers, weights_ufm = _load_per_obs_data(config) - logger.info("Loaded per-obs FFP data from %s: ", config.get("per_obs_fps")) - logger.info("Including data from these obs:") - logger.info(filelist) - - ancil, roll_c = _load_obs_boresight(config, filelist) - logger.info("Loaded boresight data from obs ids.") - - # Build Axis Managers - obs_info = core.AxisManager() - obs_info.wrap("obs_ids", np.array(filelist)) - - solver_aman = core.AxisManager(core.IndexAxis("samps")) - solver_aman.wrap("ancil", ancil) - solver_aman.wrap("obs_info", obs_info) - solver_aman.wrap("roll_c", np.repeat(roll_c, 7), [(0, "samps")]) - solver_aman.wrap( - "nom_ufm_centers", - np.repeat([nom_ufm_centers], len(filelist), axis=0) - .reshape(len(filelist) * 7, 3) - .T, - [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], - [(1, "samps")], - ) - solver_aman.wrap( - "ffp_ufm_center_fits", - obs_ufm_centers.reshape(len(filelist) * 7, 3).T, - [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], - [(1, "samps")], - ) - solver_aman.wrap("weights", weights_ufm.reshape(-1), [(0, "samps")]) + ########################################################## + ### Begin split for per-detector or per-UFM center fitting + ########################################################## + + fit_type = config.get("fit_type", "detector") + 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 = False if which_data == 'raw' else config.get("use_weights", True) + use_weights = config.get("use_weights", True) + + #Make axis manager with full detector set. + # Keep wafer/band/obs cuts but do not further downsample. + fitcheck_aman = core.AxisManager(core.IndexAxis("samps")) + ( + filelist, + obs_dets_fits, + weights_dets, + all_nom_det_array, + all_det_ids, + obs_index, + ) = load_per_detector_data(config, return_all_dets=True) + ancil, roll_c = load_obs_boresight_per_detector(config, filelist, obs_index) + + fitcheck_aman.wrap("ancil", ancil) + fitcheck_aman.wrap( + "nominal_xieta_locs", all_nom_det_array.T, + [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], + [(1, "samps")], + ) + fitcheck_aman.wrap( + "measured_xieta_data", obs_dets_fits.T, + [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], + [(1, "samps")], + ) + fitcheck_aman.wrap("weights", weights_dets, [(0, "samps")]) + fitcheck_aman.wrap("obs_index", obs_index, [(0, "samps")]) + + #Now make axis manager that has down sampled data for computation + ( + filelist, + obs_dets_fits, + weights_dets, + all_nom_det_array, + all_det_ids, + obs_index, + ) = load_per_detector_data(config) + + logger.info("Loaded %s data points", len(weights_dets)) + ancil, roll_c = load_obs_boresight_per_detector(config, filelist, obs_index) + + # Build Axis Managers + obs_info = core.AxisManager() + obs_info.wrap("obs_ids", np.array(filelist)) + + + solver_aman = core.AxisManager(core.IndexAxis("samps")) + solver_aman.wrap("ancil", ancil) + solver_aman.wrap("obs_info", obs_info) + solver_aman.wrap("roll_c", roll_c, [(0, "samps")]) + solver_aman.wrap( + "nominal_xieta_locs", + all_nom_det_array.T, + [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], + [(1, "samps")], + ) + solver_aman.wrap( + "measured_xieta_data", + obs_dets_fits.T, + [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], + [(1, "samps")], + ) + solver_aman.wrap("weights", weights_dets, [(0, "samps")]) + solver_aman.wrap("obs_index", obs_index) + # Make weights/data cuts + logger.info("Built axis manager") + + ########################################################################### + elif fit_type == "ufm_center": + use_weights = config.get("use_weights", True) + # Load in focal_plane and boresight data + nom_ufm_centers = load_nom_ufm_centers(config) + logger.info("Loaded nominal UFM centers from %s: ", config.get("ffp_path")) + logger.info(nom_ufm_centers) + + filelist, obs_ufm_centers, weights_ufm, obs_index = load_per_obs_data(config) + logger.info("Loaded per-obs FFP data from %s: ", config.get("per_obs_fps")) + logger.info("Including data from these obs:") + logger.info(filelist) + + ancil, roll_c = load_obs_boresight(config, filelist) + logger.info("Loaded boresight data from obs ids.") + + # Build Axis Managers + obs_info = core.AxisManager() + obs_info.wrap("obs_ids", np.array(filelist)) + + solver_aman = core.AxisManager(core.IndexAxis("samps")) + solver_aman.wrap("ancil", ancil) + solver_aman.wrap("obs_info", obs_info) + solver_aman.wrap("roll_c", np.repeat(roll_c, 7), [(0, "samps")]) + solver_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")], + ) + solver_aman.wrap( + "measured_xieta_data", + obs_ufm_centers.reshape(len(filelist) * 7, 3).T, + [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], + [(1, "samps")], + ) + solver_aman.wrap("weights", weights_ufm.reshape(-1), [(0, "samps")]) + solver_aman.wrap("obs_index", obs_index) + # Make weights/data cuts + logger.info("Built axis manager") - # Make weights/data cuts - # solver_aman.weights[solver_aman.ancil.az_enc > 360] = 0.0 - logger.info("Built axis manager") + ############################ + # END SPLIT + ############################ # Initialize Parameters to Fit with Model fit_params = _init_fit_params(config) + logger.info("Initialized fit parameters") + """ if xieta_model == "measured": - model_reference = solver_aman.ffp_ufm_center_fits + model_reference = solver_aman.measured_xieta_data elif xieta_model == "template": - model_reference = solver_aman.nom_ufm_centers - + model_reference = solver_aman.nominal_xieta_locs + """ # Solve for Model Parameters # use chosen xieta_model to solve for parameters - use_weights = True - model_solved_params = lmfit.minimize( + # use_weights = config.get("use_weights",True) + model_solved_params = minimize( objective_model_func_lmfit, fit_params, method="nelder", nan_policy="omit", args=(pm_version, solver_aman, xieta_model, use_weights), ) + logger.info("Ran 1st Minimization") test_params = _round_params(model_solved_params.params.valuesdict(), 8) test_params["version"] = pm_version @@ -338,7 +631,7 @@ def main(config_path: str): 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)) + logger.info(fit_report(model_solved_params)) # save pointing model parameters to axis manager param_aman = core.AxisManager() @@ -346,60 +639,67 @@ def main(config_path: str): param_aman.wrap(k, test_params[k]) solver_aman.wrap("pointing_model", param_aman) + # save errors to axis manager + error_aman = core.AxisManager() + for k in list(model_solved_params.params.values()): + error_aman.wrap(k.name, k.stderr) + solver_aman.wrap("pointing_model_errors", error_aman) + # parameter_fit_stats = build_param_fit_stat_aman(model_solved_params) # solver_aman.wrap("parameter_fit_stats", parameter_fit_stats) # Model template and measured points using parameters found above - if xieta_model == "measured": - model_fits = model_measured_xieta( - solver_aman.pointing_model, pm_version, solver_aman - ) - elif xieta_model == "template": - model_fits = model_template_xieta( - solver_aman.pointing_model, pm_version, solver_aman - ) - + modeled_fits, fit_residuals_i1, rms_i1, model_reference = apply_model_params(xieta_model, solver_aman.pointing_model, pm_version, solver_aman) logger.info( - "RMS on fit: %f", get_RMS(model_fits, model_reference, solver_aman.weights) - ) - - fit_residual_i1 = np.array( - [ - math.dist( - [model_reference[0][i], model_reference[1][i]], - [model_fits[0][i], model_fits[1][i]], - ) - for i in range(len(model_fits[0])) - ] - ) + "RMS on fit: %f arcmin", rms_i1) # Save fit results to the axis manager modelfit_aman = core.AxisManager() - modelfit_aman.wrap("xi", model_fits[0], overwrite=True) - modelfit_aman.wrap("eta", model_fits[1], overwrite=True) - solver_aman.wrap("model_fits", modelfit_aman, overwrite=True) - solver_aman.wrap( - "fit_rms", - get_RMS(model_fits, model_reference, solver_aman.weights), - overwrite=True, - ) + modelfit_aman.wrap("xi", modeled_fits[0], overwrite=True) + modelfit_aman.wrap("eta", modeled_fits[1], overwrite=True) + solver_aman.wrap("modeled_fits", modelfit_aman, overwrite=True) + solver_aman.wrap("fit_residuals", fit_residuals_i1, overwrite=True) + solver_aman.wrap("fit_rms", rms_i1, overwrite=True) + + + if fit_type == "detector": + _, fit_residuals_full, rms_full, _ = apply_model_params(xieta_model, solver_aman.pointing_model, pm_version, fitcheck_aman) + logger.info("RMS on FULL detector set: %f arcmin", rms_full) + solver_aman.wrap("fit_residuals_full", fit_residuals_full, overwrite=True) + solver_aman.wrap("fit_rms_full", rms_full, overwrite=True) + solver_aman.wrap("obs_index_full", 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"): tag = "_i1" - plot_ws0_model_fits(solver_aman, config, save_dir, tag) - plot_template_space_fits_per_wafer(solver_aman, config, save_dir, tag) - plot_residuals_vs_ancil(solver_aman, config, save_dir, tag) - plot_xieta_cross_residuals(solver_aman, config, save_dir, tag) - plot_xieta_residuals(solver_aman, config, save_dir, tag) - + plotter = ModelFitsPlotter(solver_aman=solver_aman, + config=config, + save_dir=save_dir, + iteration_tag=tag, + 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() + 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() if iterate_cutoff is not None: logger.info("Iterating parameter solution") - - cutoff = np.nanstd(fit_residual_i1) + np.nanmedian(fit_residual_i1) - logger.info(f"1 std away from residual Median: {cutoff / ARCMIN} arcmin") logger.info(f"Using {iterate_cutoff} as cutoff") - bad_fit_inds = np.where((fit_residual_i1 / ARCMIN) > iterate_cutoff)[0] + if iterate_cutoff == "auto": + iterate_cutoff = np.nanstd(fit_residuals_i1)*2 + np.nanmedian(fit_residuals_i1) + logger.info(f"Using {iterate_cutoff} as cutoff") + bad_fit_inds = np.where(fit_residuals_i1 > iterate_cutoff)[0] logger.info("Bad fit indices:") logger.info(bad_fit_inds) logger.info( @@ -407,101 +707,123 @@ def main(config_path: str): len(bad_fit_inds), iterate_cutoff, ) - 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_residual_i1[full_i] / ARCMIN, 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_residual_i1 / ARCMIN) < iterate_cutoff)[0] - masked_rms = get_RMS(model_fits, model_reference, solver_aman.weights, use_inds = good_fit_inds) - logger.info("RMS on initial fit without outliers: %f", masked_rms) - - solver_aman.weights[bad_fit_inds] = 0.0 - use_weights = True - model_solved_params = lmfit.minimize( - objective_model_func_lmfit, - fit_params, - method="nelder", - nan_policy="omit", - args=(pm_version, solver_aman, xieta_model, use_weights), - ) - - 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 - param_aman = core.AxisManager() - for k in list(test_params.keys()): - param_aman.wrap(k, test_params[k]) - solver_aman.wrap("pointing_model", param_aman, overwrite=True) - - # parameter_fit_stats = build_param_fit_stat_aman(model_solved_params) - # solver_aman.wrap("parameter_fit_stats", parameter_fit_stats, overwrite=True) - # Recalculate best fit modeled points - if xieta_model == "measured": - model_fits = model_measured_xieta( - solver_aman.pointing_model, pm_version, solver_aman + 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 < iterate_cutoff)[0] + _, _, masked_rms, _ = apply_model_params(xieta_model, + solver_aman.pointing_model, + pm_version, + solver_aman, + use_inds=good_fit_inds) + + logger.info("RMS on initial fit without outliers: %f arcmin", masked_rms) + solver_aman.wrap('bad_fit_inds', bad_fit_inds) + solver_aman.weights[bad_fit_inds] = 0.0 + + model_solved_params = minimize( + objective_model_func_lmfit, + fit_params, + method="nelder", + nan_policy="omit", + args=(pm_version, solver_aman, xieta_model, use_weights), ) - elif xieta_model == "template": - model_fits = model_template_xieta( - solver_aman.pointing_model, pm_version, solver_aman + + 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( - "RMS on secondary fit: %f", get_RMS(model_fits, model_reference, solver_aman.weights) - ) - fit_residual_i2 = np.array( - [ - math.dist( - [model_reference[0][i], model_reference[1][i]], - [model_fits[0][i], model_fits[1][i]], - ) - for i in range(len(model_fits[0])) - ] - ) - # Save fit results to the axis manager - modelfit_aman = core.AxisManager() - modelfit_aman.wrap("xi", model_fits[0], overwrite=True) - modelfit_aman.wrap("eta", model_fits[1], overwrite=True) - solver_aman.wrap("model_fits", modelfit_aman, overwrite=True) - solver_aman.wrap( - "fit_rms", - get_RMS(model_fits, model_reference, solver_aman.weights), - overwrite=True, - ) - if config.get("make_plots"): - tag = "_i2" - plot_ws0_model_fits(solver_aman, config, save_dir, tag) - plot_template_space_fits_per_wafer(solver_aman, config, save_dir, tag) - plot_residuals_vs_ancil(solver_aman, config, save_dir, tag) - plot_xieta_cross_residuals(solver_aman, config, save_dir, tag) - plot_xieta_residuals(solver_aman, config, save_dir, tag) - plot_total_residuals(solver_aman=solver_aman, - config=config, - save_dir=save_dir, - tag=tag, - fit_residual_i1=fit_residual_i1, - fit_residual_i2=fit_residual_i2, - bad_fit_inds=bad_fit_inds, - ) + logger.info("Fit Report:") + logger.info(lmfit.fit_report(model_solved_params)) + + # save pointing model parameters to axis manager + solver_aman.move("pointing_model", "pointing_model_i1") + param_aman = core.AxisManager() + for k in list(test_params.keys()): + param_aman.wrap(k, test_params[k]) + solver_aman.wrap("pointing_model", param_aman, overwrite=True) + + # save errors to axis manager + solver_aman.move("pointing_model_errors", "pointing_model_errors_i1") + error_aman = core.AxisManager() + for k in list(model_solved_params.params.values()): + error_aman.wrap(k.name, k.stderr) + solver_aman.wrap("pointing_model_errors", error_aman, overwrite=True) + + # parameter_fit_stats = build_param_fit_stat_aman(model_solved_params) + # solver_aman.wrap("parameter_fit_stats", parameter_fit_stats, overwrite=True) + + # Recalculate best-fit modeled points + modeled_fits, fit_residuals_i2, rms_i2, model_reference = apply_model_params(xieta_model, + solver_aman.pointing_model, + pm_version, + 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) + solver_aman.wrap("modeled_fits", modelfit_aman, overwrite=True) + solver_aman.move("fit_residuals", "fit_residuals_i1") + solver_aman.wrap("fit_residuals", fit_residuals_i2, overwrite=True) + solver_aman.move("fit_rms", "fit_rms_i1") + solver_aman.wrap("fit_rms", rms_i2, overwrite=True) + + if fit_type == "detector": + _, fit_residuals_full, rms_full, _ = apply_model_params(xieta_model, solver_aman.pointing_model, pm_version, fitcheck_aman) + logger.info("RMS on FULL detector set: %f arcmin", rms_full) + solver_aman.move("fit_residuals_full", "fit_residuals_full_i1") + solver_aman.move("fit_rms_full", "fit_rms_full_i1") + solver_aman.wrap("fit_residuals_full", fit_residuals_full, overwrite=True) + solver_aman.wrap("fit_rms_full", rms_full, overwrite=True) + + if config.get("make_plots"): + tag = "_i2" + plotter = ModelFitsPlotter(solver_aman=solver_aman, + config=config, + save_dir=save_dir, + 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() + else: + plotter.plot_modeled_fits() + plotter.plot_template_space_fits_per_detector() + plotter.plot_residuals_histograms() + plotter.plot_dets_in_these_obs() else: if config.get("make_plots"): - plot_total_residuals(solver_aman, - config, - save_dir, - tag='', - fit_residual_i1=fit_residual_i1) - + plotter = ModelFitsPlotter(solver_aman=solver_aman, + config=config, + save_dir=save_dir, + iteration_tag="", + save_figure=True, + plotlims=plotlims) + plotter.plot_total_residuals() if config.get("save_output"): # Save .h5 and ManifestDb @@ -509,372 +831,865 @@ def main(config_path: str): h5_filename = os.path.join(save_dir, h5_rel) solver_aman.save(h5_filename, overwrite=True) dbfile = "db.sqlite" + t0 = config.get("begin_timerange", 0) + t1 = config.get("end_timerange", int(time.time())) + Epoch_Name = config.get("epoch_name") db = _create_db(dbfile, save_dir) - db.add_entry({"dataset": "pointing_model"}, filename=h5_rel, replace=True) + db.add_entry( + {"obs:obs_timestamp": (t0, t1), "dataset": f"{Epoch_Name}_parameters"}, + filename=h5_rel, + replace=True, + ) db.to_file(os.path.join(save_dir, dbfile)) logger.info("Done") - + #################### # Plotting Functions #################### -def plot_ws0_model_fits(solver_aman, config, save_dir, tag=""): - plot_dir = os.path.join(save_dir, "plots") - os.makedirs(plot_dir, exist_ok=True) - platform = config.get("platform") - plotmask = np.where(solver_aman.weights) - rms = np.round(solver_aman.fit_rms, 4) - xi_model_fit = solver_aman.model_fits.xi - eta_model_fit = solver_aman.model_fits.eta - if config.get("xieta_model") == "measured": - xi_ref, eta_ref, _ = solver_aman.ffp_ufm_center_fits - elif config.get("xieta_model") == "template": - xi_ref, eta_ref, _ = solver_aman.nom_ufm_centers - markercolor = solver_aman.ancil.el_enc - coloredby = "El" - scale_weights = solver_aman.weights / np.nanmax(solver_aman.weights) - - #### - fig = plt.figure(figsize=(6, 6)) - gs = fig.add_gridspec(2, 2) - ax = fig.add_subplot(gs[:, :]) - ax.plot( - solver_aman["nom_ufm_centers"][0, : 7 + 1] / DEG, - solver_aman["nom_ufm_centers"][1, : 7 + 1] / DEG, - "rx", - label="Nominal Center", - ) - 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, - ) - im = ax.scatter( - xi_model_fit / DEG, - eta_model_fit / DEG, - marker="*", - c=markercolor, - cmap="jet", - edgecolor="gray", - lw=0.3, - s=130, - label=f"Model, RMS = {rms}", - vmax=65, - ) - ax.legend(loc=1, fontsize="small") - ax.set_xlabel("Xi (deg)") - ax.set_ylabel("Eta (deg)") - cb = plt.colorbar(im, 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) - ax.set_xlim(-1, .25); ax.set_ylim(-.5, .5) - #plt.subplots_adjust(left=0.1, right=0.90, bottom=0.05, hspace=0.3) - plt.tight_layout() - plt.savefig(f"{plot_dir}/{platform}_ws0_model_fits{tag}.png", dpi=350) - plt.close() - - -def plot_template_space_fits_per_wafer(solver_aman, config, save_dir, tag=""): - plot_dir = os.path.join(save_dir, "plots") - os.makedirs(plot_dir, exist_ok=True) - pm_version = config.get("pm_version") - platform = config.get("platform") - scale_weights = solver_aman.weights / np.nanmax(solver_aman.weights) - xi_unmod, eta_unmod = model_template_xieta( - solver_aman.pointing_model, pm_version, solver_aman - ) - xi0, eta0 = model_template_xieta(pm.defaults_sat_v1, pm_version, solver_aman) - - 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 - solver_aman.nom_ufm_centers[0, i] / ARCMIN, - eta_unmod[i::7] / ARCMIN - solver_aman.nom_ufm_centers[1, i] / ARCMIN, - c=solver_aman.ancil.el_enc[i::7], - s=scale_weights[i::7] * 80, - edgecolor="gray", - lw=0.3, - marker="o", - alpha=0.5, +class ModelFitsPlotter: + def __init__(self, solver_aman, config, save_dir, iteration_tag="", save_figure=True, plotlims=None): + + self.solver_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.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_dets_in_these_obs(self): + platform = self.platform + plot_dir = self.plot_dir + measured_xieta_data = self.solver_aman.measured_xieta_data + weights = self.solver_aman.weights + roll_c = self.solver_aman.roll_c + elev = self.solver_aman.ancil.el_enc + azim = self.solver_aman.ancil.az_enc + + plt.figure() + fig, ax = plt.subplots(2,2,figsize=(11,10)) + 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) + a1= ax[1,0].scatter(measured_xieta_data[0], measured_xieta_data[1], + c=elev, alpha=0.3, s=10, cmap='jet',vmin=45,vmax=65) + 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) + 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) + ax[0,0].set_title('color by boresight.roll', fontsize='medium') + ax[1,0].set_title('color by fit Elevation', fontsize='medium') + ax[0,1].set_title('color by fit Azimuth', fontsize='medium') + ax[1,1].set_title('color by fit weights', fontsize='medium') + plt.suptitle('Detectors hit in these observations') + if self.save_figure: + plt.savefig(f"{plot_dir}/{platform}_dets_in_these_obs.png", dpi=350) + plt.close() + + def plot_modeled_fits(self): + platform = self.platform + plot_dir = self.plot_dir + tag = self.tag + ancil = self.solver_aman.ancil + nominal_xieta_locs = self.solver_aman.nominal_xieta_locs + measured_xieta_data = self.solver_aman.measured_xieta_data + weights = self.solver_aman.weights + modeled_fits = self.solver_aman.modeled_fits + fit_rms = self.solver_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) + nom_array = np.concatenate( + [load_nom_focal_plane_full(self.config, 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, ) - ax[i // 4, i % 4].set_xlim(-12, 12) - ax[i // 4, i % 4].set_ylim(-12, 12) - ax[i // 4, i % 4].set_title(f"ws{i}") - plt.colorbar(im, ax[1, 3], label="Elevation (deg)", fraction=0.046, pad=0.04) - plt.tight_layout() - plt.savefig(f"{plot_dir}/{platform}_unmodeled_fits_WS_elevation{tag}.png", dpi=350) - plt.close() - - 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 - solver_aman.nom_ufm_centers[0, i] / ARCMIN, - eta_unmod[i::7] / ARCMIN - solver_aman.nom_ufm_centers[1, i] / ARCMIN, - c=solver_aman.ancil.boresight_enc[i::7], - s=scale_weights[i::7] * 80, - edgecolor="gray", - lw=0.3, - marker="o", - alpha=0.5, + 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, ) - ax[i // 4, i % 4].set_xlim(-12, 12) - ax[i // 4, i % 4].set_ylim(-12, 12) - ax[i // 4, i % 4].set_title(f"ws{i}") - plt.colorbar(im, ax[1, 3], label="Boresight (deg)", fraction=0.046, pad=0.04) - plt.tight_layout() - plt.savefig(f"{plot_dir}/{platform}_unmodeled_fits_WS_boresight{tag}.png", dpi=350) - plt.close() - - -def plot_residuals_vs_ancil(solver_aman, config, save_dir, tag): - plot_dir = os.path.join(save_dir, "plots") - os.makedirs(plot_dir, exist_ok=True) - platform = config.get("platform") - scale_weights = solver_aman.weights / np.nanmax(solver_aman.weights) - plotmask = np.where(solver_aman.weights) - xi_model_fit = solver_aman.model_fits.xi - eta_model_fit = solver_aman.model_fits.eta - if config.get("xieta_model") == "measured": - xi_ref, eta_ref, _ = solver_aman.ffp_ufm_center_fits - elif config.get("xieta_model") == "template": - xi_ref, eta_ref, _ = solver_aman.nom_ufm_centers - - 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$ vs Az, El, Boresight") - 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 - if j == 0: - x = solver_aman.ancil.az_enc % 360 - elif j == 1: - x = solver_aman.ancil.el_enc - elif j == 2: - x = solver_aman.ancil.boresight_enc - - ax[i, j].scatter( - x[plotmask], - (model - ref)[plotmask] / ARCMIN, - color="k", + ax.scatter( + nom_array[:, 0] / DEG, + nom_array[:, 1] / DEG, marker=".", - alpha=0.3, - 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], + color="r", + alpha=0.2, + label="Nominal Center", ) - xrange = np.arange(np.nanmin(x), np.nanmax(x)) - ax[i, j].plot(xrange, mxb[0] * xrange + mxb[1], "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("Boresight [deg]") - plt.tight_layout() - plt.savefig(f"{plot_dir}/{platform}_residuals_vs_ancillary{tag}.png", dpi=350) - plt.close() + 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)") -def plot_total_residuals(solver_aman, - config, - save_dir, - tag, - fit_residual_i1, - fit_residual_i2=None, - bad_fit_inds=None, - ): - plot_dir = os.path.join(save_dir, "plots") - os.makedirs(plot_dir, exist_ok=True) - iterate_cutoff = config.get("iterate_cutoff", None) - platform = config.get("platform") - scale_weights = solver_aman.weights / np.nanmax(solver_aman.weights) - if fit_residual_i2 is not None: - 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_residual_i1)), fit_residual_i1 / ARCMIN, - 'r.', mew=0, alpha=0.6, lw=0, label = '1st Fit') - ax1.set_ylabel(f'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_residual_i2)), - fit_residual_i2 / ARCMIN, 'b*', - alpha=0.5, lw=0, mew=0, label = '2nd fit') - xtox = np.empty((len(fit_residual_i2), 2)) - xtox[:, 0] = np.arange(len(fit_residual_i1)) - xtox[:, 1] = np.arange(len(fit_residual_i2)) - ytoy = np.empty((len(fit_residual_i1), 2)) - ytoy[:, 0] = fit_residual_i1 / ARCMIN - ytoy[:, 1] = fit_residual_i2 / ARCMIN - ax1.plot(xtox.T, ytoy.T, "k", lw=0.4) + # 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", dpi=350) + 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.solver_aman.ancil + nominal_xieta_locs = self.solver_aman.nominal_xieta_locs + measured_xieta_data = self.solver_aman.measured_xieta_data + weights = self.solver_aman.weights + modeled_fits = self.solver_aman.modeled_fits + fit_rms = self.solver_aman.fit_rms - 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') + 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) - ax2.scatter(np.arange(len(fit_residual_i1)), (fit_residual_i2 - fit_residual_i1) / ARCMIN, c='k', - marker = 'o', s = scale_weights*50, - lw=0, alpha = 0.6, label = "Res i2 - Res i1") - ax2.plot(np.arange(len(fit_residual_i1))[bad_fit_inds], (fit_residual_i2 - fit_residual_i1)[bad_fit_inds] / ARCMIN, - '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) - ax2.legend(fontsize='x-small') - ax2.set_xlabel('Data points') - ax2.set_ylabel(r'$\Delta$ Residuals') - plt.savefig(f"{plot_dir}/{platform}_total_residuals{tag}.png", dpi=350) + # 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 - else: - fig, ax1 = plt.subplots() - #Plot first fit iteration residuals - ax1.scatter(np.arange(len(fit_residual_i1)), fit_residual_i1 / ARCMIN, - s = scale_weights*50, color='r', lw=0, alpha=0.6, label = '1st Fit') - ax1.set_ylabel(r'Fit Residual $\left|\Delta\text{(xi, eta)}\right|$ [arcmin]') - ax1.set_xlabel('Data points') - plt.legend(loc=2) - plt.savefig(f"{plot_dir}/{platform}_total_residuals{tag}.png", dpi=350) - plt.close() - -def plot_xieta_residuals(solver_aman, config, save_dir, tag): - plot_dir = os.path.join(save_dir, "plots") - os.makedirs(plot_dir, exist_ok=True) - scale_weights = solver_aman.weights / np.nanmax(solver_aman.weights) - plotmask = np.where(solver_aman.weights) - platform = config.get("platform") - xi_model_fit = solver_aman.model_fits.xi - eta_model_fit = solver_aman.model_fits.eta - if config.get("xieta_model") == "measured": - xi_ref, eta_ref, _ = solver_aman.ffp_ufm_center_fits - elif config.get("xieta_model") == "template": - xi_ref, eta_ref, _ = solver_aman.nom_ufm_centers + #### + #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", dpi=350) + plt.close() - 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], + + 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.solver_aman.ancil + roll_c = self.solver_aman.roll_c + nominal_xieta_locs = self.solver_aman.nominal_xieta_locs + measured_xieta_data = self.solver_aman.measured_xieta_data + weights = self.solver_aman.weights + pointing_model = self.solver_aman.pointing_model + modeled_fits = self.solver_aman.modeled_fits + fit_rms = self.solver_aman.fit_rms + + scale_weights = weights / np.nanmax(weights) + xi_unmod, eta_unmod = model_template_xieta( + pointing_model, + pm_version, + self.solver_aman + ) + xi0, eta0 = model_template_xieta( + pm.param_defaults[pm_version], + pm_version, + self.solver_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", dpi=350) + 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", dpi=350) + + 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", dpi=350) + 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.solver_aman.ancil + roll_c = self.solver_aman.roll_c + nominal_xieta_locs = self.solver_aman.nominal_xieta_locs + measured_xieta_data = self.solver_aman.measured_xieta_data + weights = self.solver_aman.weights + pointing_model = self.solver_aman.pointing_model + modeled_fits = self.solver_aman.modeled_fits + fit_rms = self.solver_aman.fit_rms + + scale_weights = weights / np.nanmax(weights) + xi_unmod, eta_unmod = model_template_xieta( + pointing_model, + pm_version, + self.solver_aman + ) + xi0, eta0 = model_template_xieta( + pm.param_defaults[pm_version], + pm_version, + self.solver_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=weights, + s=scale_weights * 5, + edgecolor="gray", + lw=0.3, + marker="o", + alpha=0.4, + cmap="viridis", + vmin=self.config.get("weight_cutoff"), + vmax=1 + ) + 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 fit weight") + 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_weights{tag}.png", dpi=350) + 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.4, cmap="jet", - s=100 * scale_weights[plotmask], - alpha=scale_weights[plotmask], - edgecolors="k", - linewidths=0.4, ) + 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) - 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(-10, 20) - ax[i].set_xlabel(f"{xlabel} (deg)", fontsize="small") - ax[i].set_ylabel(f"{ylabel} [arcmin]") - plt.tight_layout() - plt.savefig(f"{plot_dir}/{platform}_xieta_residuals{tag}.png", dpi=350) - plt.close() - - -def plot_xieta_cross_residuals(solver_aman, config, save_dir, tag): - plot_dir = os.path.join(save_dir, "plots") - os.makedirs(plot_dir, exist_ok=True) - scale_weights = solver_aman.weights / np.nanmax(solver_aman.weights) - plotmask = np.where(solver_aman.weights) - platform = config.get("platform") - xi_model_fit = solver_aman.model_fits.xi - eta_model_fit = solver_aman.model_fits.eta - if config.get("xieta_model") == "measured": - xi_ref, eta_ref, _ = solver_aman.ffp_ufm_center_fits - elif config.get("xieta_model") == "template": - xi_ref, eta_ref, _ = solver_aman.nom_ufm_centers - - 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], + plt.tight_layout() + if self.save_figure: + plt.savefig(f"{plot_dir}/{platform}_unmodeled_fits_WS_elevation{tag}.png", dpi=350) + 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.4, cmap="jet", - s=100 * scale_weights[plotmask], - alpha=scale_weights[plotmask], - edgecolors="k", - linewidths=0.4, ) + 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) - 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(-10, 20) - ax[i].set_xlabel(f"{xlabel} (deg)", fontsize="small") + plt.tight_layout() + if self.save_figure: + plt.savefig(f"{plot_dir}/{platform}_unmodeled_fits_WS_roll{tag}.png", dpi=350) + 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.4, + 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", dpi=350) + 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.solver_aman.ancil + roll_c = self.solver_aman.roll_c + nominal_xieta_locs = self.solver_aman.nominal_xieta_locs + measured_xieta_data = self.solver_aman.measured_xieta_data + weights = self.solver_aman.weights + pointing_model = self.solver_aman.pointing_model + modeled_fits = self.solver_aman.modeled_fits + fit_rms = self.solver_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 + + 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" + 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}") + 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 + if j == 0: + x = ancil.az_enc % 360 + elif j == 1: + x = ancil.el_enc + elif j == 2: + x = third_enc + 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].plot( + xrange, + mxb[0] * xrange + mxb[1], + "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", dpi=350) + 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.solver_aman.ancil + roll_c = self.solver_aman.roll_c + weights = self.solver_aman.weights + fit_rms = self.solver_aman.fit_rms + obs_index = self.solver_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.solver_aman)) + except: + two_fits = False + if two_fits: + iterate_cutoff = self.config.get("iterate_cutoff") + if iterate_cutoff == "auto": + iterate_cutoff = np.nanstd(self.solver_aman.fit_residuals_i1)*2 + np.nanmedian(self.solver_aman.fit_residuals_i1) + bad_fit_inds = self.solver_aman.bad_fit_inds + fit_residuals_i1 = self.solver_aman.fit_residuals_i1 + fit_residuals_i2 = self.solver_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", dpi=350) + plt.close() + else: + # Plot first fit iteration residuals only + fit_residuals_i1 = self.solver_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", dpi=350) + plt.close() + + + def plot_residuals_histograms(self): + platform = self.platform + plot_dir = self.plot_dir + tag = self.tag + append = self.append_string + ancil = self.solver_aman.ancil + weights = self.solver_aman.weights + fit_rms = self.solver_aman.fit_rms + fit_residuals = self.solver_aman.fit_residuals + fit_rms_full = self.solver_aman.fit_rms_full + fit_residuals_full = self.solver_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", dpi=350) + 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.solver_aman.weights + modeled_fits = self.solver_aman.modeled_fits + nominal_xieta_locs = self.solver_aman.nominal_xieta_locs + measured_xieta_data = self.solver_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", dpi=350) + 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.solver_aman.weights + modeled_fits = self.solver_aman.modeled_fits + nominal_xieta_locs = self.solver_aman.nominal_xieta_locs + measured_xieta_data = self.solver_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() - plt.savefig(f"{plot_dir}/{platform}_xieta_cross_residuals{tag}.png", dpi=350) - plt.close() - - - + plt.tight_layout() + if self.save_figure: + plt.savefig(f"{plot_dir}/{platform}_xieta_cross_residuals{tag}.png", dpi=350) + plt.close() + ############ if __name__ == "__main__": From 8042065813a670c8e6b883bcd960a1ca7cc033fe Mon Sep 17 00:00:00 2001 From: Elle Shaw Date: Mon, 4 Aug 2025 09:44:36 -0700 Subject: [PATCH 026/132] Fixed issue so now works for fitting LAT parameters. Minor changes to formatting. --- .../site_pipeline/solve_pointing_model.py | 68 ++++++++----------- 1 file changed, 29 insertions(+), 39 deletions(-) diff --git a/sotodlib/site_pipeline/solve_pointing_model.py b/sotodlib/site_pipeline/solve_pointing_model.py index b1b21fb57..ff8120e07 100644 --- a/sotodlib/site_pipeline/solve_pointing_model.py +++ b/sotodlib/site_pipeline/solve_pointing_model.py @@ -305,9 +305,9 @@ def objective_model_func_lmfit( return chi_sq(weights_array, dist) def chi_sq(weights, dist): - N = np.identity(len(dist)) * weights - chi2 = dist.T * N * dist + #N = np.identity(len(dist)) * weights #chi2 = dist.T @ N @ dist + chi2 = np.nansum(dist ** 2 * weights) return chi2 def model_template_xieta(params, pm_version, aman): @@ -320,16 +320,15 @@ def model_template_xieta(params, pm_version, aman): xi_meas = aman.measured_xieta_data[0] eta_meas = aman.measured_xieta_data[1] params = params.valuesdict() if isinstance(params, Parameters) else params - # if type(params) == lmfit.parameter.Parameters: - # params = params.valuesdict() 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_nomodel = quat.rotation_lonlat(-az, el, 0) 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( @@ -345,18 +344,17 @@ def model_measured_xieta(params, pm_version, aman): q_nomodel * q_det_meas == q_model * q_det_true """ params = params.valuesdict() if isinstance(params, Parameters) else params - # if type(params) == lmfit.parameter.Parameters: - # params = params.valuesdict() 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) 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_nomodel = quat.rotation_lonlat(-az, el, 0) 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( @@ -455,7 +453,6 @@ def main(config_path: str): 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") @@ -488,7 +485,6 @@ def main(config_path: str): logger.info("Performing per-detector fits for all UFM data.") which_data = config.get("use_as_data") - # use_weights = False if which_data == 'raw' else config.get("use_weights", True) use_weights = config.get("use_weights", True) #Make axis manager with full detector set. @@ -519,6 +515,7 @@ def main(config_path: str): fitcheck_aman.wrap("obs_index", obs_index, [(0, "samps")]) #Now make axis manager that has down sampled data for computation + solver_aman = core.AxisManager(core.IndexAxis("samps")) ( filelist, obs_dets_fits, @@ -527,17 +524,13 @@ def main(config_path: str): all_det_ids, obs_index, ) = load_per_detector_data(config) - logger.info("Loaded %s data points", len(weights_dets)) ancil, roll_c = load_obs_boresight_per_detector(config, filelist, obs_index) - # Build Axis Managers + # Build Axis Managers + solver_aman.wrap("ancil", ancil) obs_info = core.AxisManager() obs_info.wrap("obs_ids", np.array(filelist)) - - - solver_aman = core.AxisManager(core.IndexAxis("samps")) - solver_aman.wrap("ancil", ancil) solver_aman.wrap("obs_info", obs_info) solver_aman.wrap("roll_c", roll_c, [(0, "samps")]) solver_aman.wrap( @@ -554,7 +547,6 @@ def main(config_path: str): ) solver_aman.wrap("weights", weights_dets, [(0, "samps")]) solver_aman.wrap("obs_index", obs_index) - # Make weights/data cuts logger.info("Built axis manager") ########################################################################### @@ -600,22 +592,16 @@ def main(config_path: str): # Make weights/data cuts logger.info("Built axis manager") - ############################ - # END SPLIT - ############################ + ################################ + # END of SPLIT: Now fit the parameters + ################################ # Initialize Parameters to Fit with Model fit_params = _init_fit_params(config) logger.info("Initialized fit parameters") - """ - if xieta_model == "measured": - model_reference = solver_aman.measured_xieta_data - elif xieta_model == "template": - model_reference = solver_aman.nominal_xieta_locs - """ + # Solve for Model Parameters # use chosen xieta_model to solve for parameters - # use_weights = config.get("use_weights",True) model_solved_params = minimize( objective_model_func_lmfit, fit_params, @@ -650,8 +636,7 @@ def main(config_path: str): # Model template and measured points using parameters found above modeled_fits, fit_residuals_i1, rms_i1, model_reference = apply_model_params(xieta_model, solver_aman.pointing_model, pm_version, solver_aman) - logger.info( - "RMS on fit: %f arcmin", rms_i1) + logger.info("RMS on fit: %f arcmin", rms_i1) # Save fit results to the axis manager modelfit_aman = core.AxisManager() @@ -661,7 +646,6 @@ def main(config_path: str): solver_aman.wrap("fit_residuals", fit_residuals_i1, overwrite=True) solver_aman.wrap("fit_rms", rms_i1, overwrite=True) - if fit_type == "detector": _, fit_residuals_full, rms_full, _ = apply_model_params(xieta_model, solver_aman.pointing_model, pm_version, fitcheck_aman) logger.info("RMS on FULL detector set: %f arcmin", rms_full) @@ -880,25 +864,31 @@ def plot_dets_in_these_obs(self): roll_c = self.solver_aman.roll_c elev = self.solver_aman.ancil.el_enc azim = self.solver_aman.ancil.az_enc + if platform == 'lat': + elmin=10; elmax=90 + else: + elmin=45; 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) + 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=45,vmax=65) + 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) + 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) + 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) - ax[0,0].set_title('color by boresight.roll', fontsize='medium') - ax[1,0].set_title('color by fit Elevation', fontsize='medium') - ax[0,1].set_title('color by fit Azimuth', fontsize='medium') - ax[1,1].set_title('color by fit weights', fontsize='medium') + plt.suptitle('Detectors hit in these observations') if self.save_figure: plt.savefig(f"{plot_dir}/{platform}_dets_in_these_obs.png", dpi=350) From dde423673f1e5e64099849a7252bb68b3d74d29b Mon Sep 17 00:00:00 2001 From: Elle Shaw Date: Mon, 4 Aug 2025 16:42:17 -0700 Subject: [PATCH 027/132] Added plotting capabilities to show effect of solved pointing parameters on full set of detector data. --- .../site_pipeline/solve_pointing_model.py | 547 +++++++++++++++--- 1 file changed, 454 insertions(+), 93 deletions(-) diff --git a/sotodlib/site_pipeline/solve_pointing_model.py b/sotodlib/site_pipeline/solve_pointing_model.py index ff8120e07..8ca5d41e5 100644 --- a/sotodlib/site_pipeline/solve_pointing_model.py +++ b/sotodlib/site_pipeline/solve_pointing_model.py @@ -18,6 +18,7 @@ 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 @@ -135,27 +136,37 @@ def create_culling_mask(obs_index, cull_dets): return culling_mask -def load_per_detector_data(config, return_all_dets=False): +def load_per_detector_data(config, no_downsample_set=False, return_all_dets=False): per_obs_fps = config.get("per_obs_fps") skip_tags = config.get("skip_tags", []) t0 = config.get("begin_timerange", 0) tf = config.get("end_timerange", int(time.time())) rxs = fpc.Receiver.load_file(per_obs_fps) - 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) - 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")] + 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")] weights_dets, obs_dets_fits, stream_id_list, obs_index = [], [], [], [] - which_ufm = config.get("which_ufm", None) + #which_ufm = config.get("which_ufm", None) which_data = config.get("use_as_data") which_weights = config.get("use_as_weights", None) @@ -181,7 +192,7 @@ def load_per_detector_data(config, return_all_dets=False): obs_dets_fits[np.where(weights_dets == 0)] = np.nan mask = ~np.isnan(weights_dets) - if return_all_dets: + if no_downsample_set: #plotting use-case to compare subset fits with the entire dataset. return ( filelist, @@ -497,7 +508,7 @@ def main(config_path: str): all_nom_det_array, all_det_ids, obs_index, - ) = load_per_detector_data(config, return_all_dets=True) + ) = load_per_detector_data(config, no_downsample_set=True) ancil, roll_c = load_obs_boresight_per_detector(config, filelist, obs_index) fitcheck_aman.wrap("ancil", ancil) @@ -513,6 +524,7 @@ def main(config_path: str): ) fitcheck_aman.wrap("weights", weights_dets, [(0, "samps")]) fitcheck_aman.wrap("obs_index", obs_index, [(0, "samps")]) + logger.info("Loaded %s fit check data points", len(weights_dets)) #Now make axis manager that has down sampled data for computation solver_aman = core.AxisManager(core.IndexAxis("samps")) @@ -772,7 +784,7 @@ def main(config_path: str): solver_aman.wrap("fit_rms", rms_i2, overwrite=True) if fit_type == "detector": - _, fit_residuals_full, rms_full, _ = apply_model_params(xieta_model, solver_aman.pointing_model, pm_version, fitcheck_aman) + _, fit_residuals_full, rms_full, _ = pm.apply_model_params(xieta_model, solver_aman.pointing_model, pm_version, fitcheck_aman) logger.info("RMS on FULL detector set: %f arcmin", rms_full) solver_aman.move("fit_residuals_full", "fit_residuals_full_i1") solver_aman.move("fit_rms_full", "fit_rms_full_i1") @@ -825,6 +837,183 @@ def main(config_path: str): replace=True, ) db.to_file(os.path.join(save_dir, dbfile)) + + #Optional extra plotting + if config.get("make_full_analysis_plots", True): + #Fill up axis manager with ALL the data (only cuts from culling and time stamps remain) + + ( + filelist, + obs_dets_fits, + weights_dets, + all_nom_det_array, + all_det_ids, + obs_index, + ) = load_per_detector_data(config, return_all_dets=True) + ancil, roll_c = load_obs_boresight_per_detector(config, filelist, obs_index) + ufm_list = [ufm.split("_")[1] for ufm in config.get('ufms')] + + obs_info = core.AxisManager() + obs_info.wrap("obs_ids", np.array(filelist)) + + full_aman = core.AxisManager(core.IndexAxis("samps")) + full_aman.wrap("obs_info", obs_info) + full_aman.wrap("ancil", ancil) + full_aman.wrap( + "nominal_xieta_locs", all_nom_det_array.T, + [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], + [(1, "samps")], + ) + full_aman.wrap( + "measured_xieta_data", obs_dets_fits.T, + [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], + [(1, "samps")], + ) + full_aman.wrap("weights", weights_dets, [(0, "samps")]) + full_aman.wrap("obs_index", obs_index) + full_aman.wrap("roll_c", roll_c, [(0, "samps")]) + full_aman.wrap("det_ids", all_det_ids, [(0, "samps")]) + full_aman.wrap("radial", + np.sqrt(full_aman.nominal_xieta_locs[0]**2 + full_aman.nominal_xieta_locs[1]**2)/DEG, + [(0, "samps")]) + full_aman.wrap("det_ufm", + np.array([detid.decode('utf-8').split('_')[0].lower() for detid in full_aman.det_ids]) + , [(0, "samps")]) + full_aman.wrap("det_wafer", np.array([ufm_list.index(d) for d in full_aman.det_ufm]), [(0, "samps")]) + + try: + full_modeled, full_residuals, rms, _ = apply_model_params("template", + solver_aman.pointing_model_i1, + config.get("pm_version"), + full_aman) + except: + full_modeled, fit_residuals, rms, _ = apply_model_params("template", + solver_aman.pointing_model, + config.get("pm_version"), + full_aman) + + full_aman.wrap("full_modeled", np.array(full_modeled), + [(0, core.LabelAxis("xieta", ["xi", "eta"]))], + [(1, "samps")]) + full_aman.wrap("fit_residuals", fit_residuals, [(0, "samps")]) + del(full_modeled) + del(fit_residuals) + + (obs_az, obs_el, obs_roll, + obs_resid, obs_dxi, obs_deta, + obs_std_xi, obs_std_eta + ) = [], [], [], [], [], [], [], [] + (all_ufm_az, all_ufm_el, all_ufm_roll, + all_ufm_resid, all_ufm_dxi, all_ufm_deta, + all_ufm_std_xi, all_ufm_std_eta, all_ufm_wafer_num + ) = [], [], [], [], [], [], [], [], [] + for ob in np.unique(full_aman.obs_index): + inds = np.where(full_aman.obs_index == ob)[0] + obs_az.append(np.nanmedian(full_aman.ancil.az_enc[inds])) + obs_el.append(np.nanmedian(full_aman.ancil.el_enc[inds])) + obs_roll.append(np.nanmedian(full_aman.roll_c[inds])) + obs_resid.append(np.nanmean(full_aman.fit_residuals[inds])) + obs_dxi.append(np.nanmean((full_aman.full_modeled[0] - + full_aman.nominal_xieta_locs[0])[inds]/DEG*60)) + obs_deta.append(np.nanmean((full_aman.full_modeled[1] - + full_aman.nominal_xieta_locs[1])[inds]/DEG*60)) + obs_std_xi.append(np.nanstd((full_aman.full_modeled[0] - + full_aman.nominal_xieta_locs[0])[inds]/DEG*60)) + obs_std_eta.append(np.nanstd((full_aman.full_modeled[1] - + full_aman.nominal_xieta_locs[1])[inds]/DEG*60)) + (ufm_az, ufm_el, ufm_roll, ufm_resid, + ufm_dxi, ufm_deta, ufm_std_xi, + ufm_std_eta, ufm_wafer_num + )= [], [], [], [], [], [], [], [], [] + for ufm in ufm_list: + ufm_inds = np.where(full_aman.det_ufm[inds] == ufm)[0] + ufm_az.append(np.nanmedian(full_aman.ancil.az_enc[inds][ufm_inds])) + ufm_el.append(np.nanmedian(full_aman.ancil.el_enc[inds][ufm_inds])) + ufm_roll.append(np.nanmedian(full_aman.roll_c[inds][ufm_inds])) + ufm_resid.append(np.nanmean(full_aman.fit_residuals[inds][ufm_inds])) + ufm_dxi.append(np.nanmean((full_aman.full_modeled[0] - + full_aman.nominal_xieta_locs[0])[inds][ufm_inds]/DEG*60)) + ufm_deta.append(np.nanmean((full_aman.full_modeled[1] - + full_aman.nominal_xieta_locs[1])[inds][ufm_inds]/DEG*60)) + ufm_std_xi.append(np.nanstd((full_aman.full_modeled[0] - + full_aman.nominal_xieta_locs[0])[inds][ufm_inds]/DEG*60)) + ufm_std_eta.append(np.nanstd((full_aman.full_modeled[1] - + full_aman.nominal_xieta_locs[1])[inds][ufm_inds]/DEG*60)) + ufm_wafer_num.append(np.nanmedian(full_aman.det_wafer[inds][ufm_inds])) + all_ufm_az.append(ufm_az) + all_ufm_el.append(ufm_el) + all_ufm_roll.append(ufm_roll) + all_ufm_resid.append(ufm_resid) + all_ufm_deta.append(ufm_deta) + all_ufm_dxi.append(ufm_dxi) + all_ufm_std_xi.append(ufm_std_xi) + all_ufm_std_eta.append(ufm_std_eta) + all_ufm_wafer_num.append(ufm_wafer_num) + + per_ufm_stats = core.AxisManager() + per_obs_stats = core.AxisManager() + + per_obs_stats.wrap("el", np.array(obs_el)) + per_obs_stats.wrap("roll", np.array(obs_roll)) + per_obs_stats.wrap("az", np.array(obs_az)) + per_obs_stats.wrap("resid", np.array(obs_resid)) + per_obs_stats.wrap("dxi", np.array(obs_dxi)) + per_obs_stats.wrap("deta", np.array(obs_deta)) + per_obs_stats.wrap("std_xi", np.array(obs_std_xi)) + per_obs_stats.wrap("std_eta", np.array(obs_std_eta)) + + per_ufm_stats.wrap("az", np.array(all_ufm_az)) + per_ufm_stats.wrap("el", np.array(all_ufm_el)) + per_ufm_stats.wrap("roll", np.array(all_ufm_roll)) + per_ufm_stats.wrap("resid", np.array(all_ufm_resid)) + per_ufm_stats.wrap("dxi", np.array(all_ufm_dxi)) + per_ufm_stats.wrap("deta", np.array(all_ufm_deta)) + per_ufm_stats.wrap("std_xi", np.array(all_ufm_std_xi)) + per_ufm_stats.wrap("std_eta", np.array(all_ufm_std_eta)) + per_ufm_stats.wrap("wafer_num", np.array(all_ufm_wafer_num)) + + if platform == "lat": + obs_cr = [] + all_ufm_cr = [] + for ob in np.unique(full_aman.obs_index): + inds = np.where(full_aman.obs_index == ob)[0] + obs_cr.append(np.nanmedian(full_aman.ancil.corotator_enc[inds])) + ufm_cr = [] + for ufm in ufm_list: + ufm_cr.append(np.nanmedian(full_aman.ancil.corotator_enc[inds][ufm_inds])) + all_ufm_cr.append(ufm_cr) + per_obs_stats.wrap("cr", np.array(obs_cr)) + per_ufm_stats.wrap("cr", np.array(all_ufm_cr)) + + full_aman.wrap("dxi", (full_aman.full_modeled[0] - + full_aman.nominal_xieta_locs[0])/DEG*60, [(0, "samps")]) + full_aman.wrap("deta", (full_aman.full_modeled[1] - + full_aman.nominal_xieta_locs[1])/DEG*60, [(0, "samps")]) + + #full_dxi_av = np.nanmean(full_dxi) + #full_deta_av = np.nanmean(full_deta) + 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]) + + #Calculate RMSs + per_obs_stats.wrap("rms", np.sqrt(np.nanmean(per_obs_stats["dxi"]**2 + per_obs_stats["deta"]**2))) + per_ufm_stats.wrap("rms", np.sqrt(np.nanmean(per_ufm_stats["dxi"]**2 + per_ufm_stats["deta"]**2))) + full_aman.wrap("rms", np.sqrt(np.nanmean(full_aman["dxi"]**2 + full_aman["deta"]**2))) + full_aman.wrap("per_ufm_stats", per_ufm_stats) + full_aman.wrap("per_obs_stats", per_obs_stats) + + plotter = ModelFitsPlotter(solver_aman=full_aman, + config=config, + save_dir=save_dir, + iteration_tag="", + save_figure=True, + plotlims=plotlims) + plotter.plot_full_residuals_across_focalplane() + plotter.plot_full_histogram() + plotter.plot_full_unmodeled_residuals() + logger.info("Done") @@ -835,7 +1024,7 @@ def main(config_path: str): class ModelFitsPlotter: def __init__(self, solver_aman, config, save_dir, iteration_tag="", save_figure=True, plotlims=None): - self.solver_aman = solver_aman + self.aman = solver_aman self.config = config self.tag = iteration_tag self.save_figure = save_figure @@ -854,16 +1043,187 @@ def __init__(self, solver_aman, config, save_dir, iteration_tag="", save_figure= 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 = 45, 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", dpi=350) + 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", dpi=350) + 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", dpi=350) + 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", dpi=350) + + 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 + + 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.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", dpi=350) + def plot_dets_in_these_obs(self): platform = self.platform plot_dir = self.plot_dir - measured_xieta_data = self.solver_aman.measured_xieta_data - weights = self.solver_aman.weights - roll_c = self.solver_aman.roll_c - elev = self.solver_aman.ancil.el_enc - azim = self.solver_aman.ancil.az_enc + 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: @@ -898,12 +1258,12 @@ def plot_modeled_fits(self): platform = self.platform plot_dir = self.plot_dir tag = self.tag - ancil = self.solver_aman.ancil - nominal_xieta_locs = self.solver_aman.nominal_xieta_locs - measured_xieta_data = self.solver_aman.measured_xieta_data - weights = self.solver_aman.weights - modeled_fits = self.solver_aman.modeled_fits - fit_rms = self.solver_aman.fit_rms + 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 @@ -996,12 +1356,12 @@ def plot_ws0_modeled_fits(self): plot_dir = self.plot_dir xieta_model = self.xieta_model tag = self.tag - ancil = self.solver_aman.ancil - nominal_xieta_locs = self.solver_aman.nominal_xieta_locs - measured_xieta_data = self.solver_aman.measured_xieta_data - weights = self.solver_aman.weights - modeled_fits = self.solver_aman.modeled_fits - fit_rms = self.solver_aman.fit_rms + 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 @@ -1085,25 +1445,25 @@ def plot_template_space_fits_per_wafer(self): plotlims = self.plotlims pm_version = self.pm_version tag = self.tag - ancil = self.solver_aman.ancil - roll_c = self.solver_aman.roll_c - nominal_xieta_locs = self.solver_aman.nominal_xieta_locs - measured_xieta_data = self.solver_aman.measured_xieta_data - weights = self.solver_aman.weights - pointing_model = self.solver_aman.pointing_model - modeled_fits = self.solver_aman.modeled_fits - fit_rms = self.solver_aman.fit_rms + 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.solver_aman + self.aman ) xi0, eta0 = model_template_xieta( pm.param_defaults[pm_version], pm_version, - self.solver_aman + self.aman ) #Plot with Elevation as colorbar fig, ax = plt.subplots(2, 4, figsize=(9, 6)) @@ -1192,25 +1552,25 @@ def plot_template_space_fits_per_detector(self): tag = self.tag plotlims = self.plotlims pm_version = self.pm_version - ancil = self.solver_aman.ancil - roll_c = self.solver_aman.roll_c - nominal_xieta_locs = self.solver_aman.nominal_xieta_locs - measured_xieta_data = self.solver_aman.measured_xieta_data - weights = self.solver_aman.weights - pointing_model = self.solver_aman.pointing_model - modeled_fits = self.solver_aman.modeled_fits - fit_rms = self.solver_aman.fit_rms + 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.solver_aman + self.aman ) xi0, eta0 = model_template_xieta( pm.param_defaults[pm_version], pm_version, - self.solver_aman + self.aman ) #plot with weights as colorbar fig, ax = plt.subplots(figsize=(9, 6)) @@ -1223,7 +1583,7 @@ def plot_template_space_fits_per_detector(self): edgecolor="gray", lw=0.3, marker="o", - alpha=0.4, + alpha=0.2, cmap="viridis", vmin=self.config.get("weight_cutoff"), vmax=1 @@ -1247,7 +1607,7 @@ def plot_template_space_fits_per_detector(self): edgecolor="gray", lw=0.3, marker="o", - alpha=0.4, + alpha=0.2, cmap="jet", ) ax.set_xlim(-1 * plotlims, plotlims) @@ -1275,7 +1635,7 @@ def plot_template_space_fits_per_detector(self): edgecolor="gray", lw=0.3, marker="o", - alpha=0.4, + alpha=0.2, cmap="jet", ) ax.set_xlim(-1 * plotlims, plotlims) @@ -1301,7 +1661,7 @@ def plot_template_space_fits_per_detector(self): edgecolor="gray", lw=0.3, marker="o", - alpha=0.4, + alpha=0.2, cmap="jet", ) ax.set_xlim(-1 * plotlims, plotlims) @@ -1321,14 +1681,14 @@ def plot_residuals_vs_ancil(self): pm_version = self.pm_version xieta_model = self.xieta_model plotlims = self.plotlims - ancil = self.solver_aman.ancil - roll_c = self.solver_aman.roll_c - nominal_xieta_locs = self.solver_aman.nominal_xieta_locs - measured_xieta_data = self.solver_aman.measured_xieta_data - weights = self.solver_aman.weights - pointing_model = self.solver_aman.pointing_model - modeled_fits = self.solver_aman.modeled_fits - fit_rms = self.solver_aman.fit_rms + 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) @@ -1404,25 +1764,25 @@ def plot_total_residuals(self): tag = self.tag plotlims = self.plotlims pm_version = self.pm_version - ancil = self.solver_aman.ancil - roll_c = self.solver_aman.roll_c - weights = self.solver_aman.weights - fit_rms = self.solver_aman.fit_rms - obs_index = self.solver_aman.obs_index + 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.solver_aman)) + 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.solver_aman.fit_residuals_i1)*2 + np.nanmedian(self.solver_aman.fit_residuals_i1) - bad_fit_inds = self.solver_aman.bad_fit_inds - fit_residuals_i1 = self.solver_aman.fit_residuals_i1 - fit_residuals_i2 = self.solver_aman.fit_residuals + 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, :]) @@ -1501,7 +1861,7 @@ def plot_total_residuals(self): plt.close() else: # Plot first fit iteration residuals only - fit_residuals_i1 = self.solver_aman.fit_residuals + fit_residuals_i1 = self.aman.fit_residuals fig, ax1 = plt.subplots() im = ax1.scatter( np.arange(len(fit_residuals_i1)), @@ -1531,12 +1891,12 @@ def plot_residuals_histograms(self): plot_dir = self.plot_dir tag = self.tag append = self.append_string - ancil = self.solver_aman.ancil - weights = self.solver_aman.weights - fit_rms = self.solver_aman.fit_rms - fit_residuals = self.solver_aman.fit_residuals - fit_rms_full = self.solver_aman.fit_rms_full - fit_residuals_full = self.solver_aman.fit_residuals_full + 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}" @@ -1570,10 +1930,10 @@ def plot_xieta_residuals(self): plot_dir = self.plot_dir tag = self.tag xieta_model = self.xieta_model - weights = self.solver_aman.weights - modeled_fits = self.solver_aman.modeled_fits - nominal_xieta_locs = self.solver_aman.nominal_xieta_locs - measured_xieta_data = self.solver_aman.measured_xieta_data + 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) @@ -1628,10 +1988,10 @@ def plot_xieta_cross_residuals(self): plot_dir = self.plot_dir tag = self.tag xieta_model = self.xieta_model - weights = self.solver_aman.weights - modeled_fits = self.solver_aman.modeled_fits - nominal_xieta_locs = self.solver_aman.nominal_xieta_locs - measured_xieta_data = self.solver_aman.measured_xieta_data + 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) @@ -1679,7 +2039,8 @@ def plot_xieta_cross_residuals(self): if self.save_figure: plt.savefig(f"{plot_dir}/{platform}_xieta_cross_residuals{tag}.png", dpi=350) plt.close() - + + ############ if __name__ == "__main__": From 41aa7f1daa9bbc610a45c3fbeb901482ee2c9892 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Wed, 6 Aug 2025 11:07:01 -0700 Subject: [PATCH 028/132] feat: add joint fitting and some db fixes --- .../site_pipeline/solve_pointing_model.py | 915 ++++++++++-------- 1 file changed, 487 insertions(+), 428 deletions(-) diff --git a/sotodlib/site_pipeline/solve_pointing_model.py b/sotodlib/site_pipeline/solve_pointing_model.py index 8ca5d41e5..2a7c4a520 100644 --- a/sotodlib/site_pipeline/solve_pointing_model.py +++ b/sotodlib/site_pipeline/solve_pointing_model.py @@ -50,14 +50,12 @@ def load_nom_ufm_centers(config): return nom_ufm_centers -def load_per_obs_data(config): +def load_per_obs_data(config, t0, tf): # Load per-observation UFM center data points and weights # The per obs .h5 file a dict with obs_id for keys per_obs_fps = config.get("per_obs_fps") ufms = config.get("ufms") skip_tags = config.get("skip_tags", []) - t0 = config.get("begin_timerange", 0) - tf = config.get("end_timerange", 3000000000) 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)] @@ -136,11 +134,9 @@ def create_culling_mask(obs_index, cull_dets): return culling_mask -def load_per_detector_data(config, no_downsample_set=False, return_all_dets=False): +def load_per_detector_data(config, t0, tf, no_downsample_set=False, return_all_dets=False): per_obs_fps = config.get("per_obs_fps") skip_tags = config.get("skip_tags", []) - t0 = config.get("begin_timerange", 0) - tf = config.get("end_timerange", int(time.time())) rxs = fpc.Receiver.load_file(per_obs_fps) if return_all_dets: @@ -286,20 +282,45 @@ def load_obs_boresight_per_detector(config, filelist, obs_ind): return ancil, roll_c -def _init_fit_params(config): +def _init_fit_params(config, epochs): pm_version = config.get("pm_version") init_params = config.get("initial_params", pm.param_defaults[pm_version]) - fixed_params = config.get("fixed_params",None) + fixed_params = config.get("fixed_params",[]) + + # Add independant params + orig_pars = np.array(list(init_params.keys())) + par_list = orig_pars.copy() + for epoch in epochs: + indep_list = epoch["indep_list"] + if np.sum(np.isin(indep_list, par_list)) != len(indep_list): + raise ValueError(f"Invalid independant parameters in time range starting with {t0}") + 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] + par_count = np.zeros(len(par_list)) + for epoch in epochs: + indep_list = epoch["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() + # Initialize lmfit Parameter object fit_params = Parameters() for p in init_params.keys(): fit_params.add(p, value=init_params[p], vary=True) # Turn off various parameters depending on platform - if fixed_params is not None: - for fix in fixed_params: + for fix in fixed_params: + if fix in fit_params: fit_params[fix].set(vary=False) - return fit_params + return fit_params, epochs def objective_model_func_lmfit( params, pm_version, solver_aman, xieta_model, weights=True @@ -315,6 +336,16 @@ def objective_model_func_lmfit( weights_array = solver_aman.weights if weights else np.ones(len(dist)) return chi_sq(weights_array, dist) +def objective_model_func_lmfit_joint( + params, pm_version, epochs, xieta_model, weights=True +): + params = params.valuesdict() + chisq = 0 + for epoch in epochs: + chisq += objective_model_func_lmfit({par.split(f"_{epoch['name']}")[0]:params[par] for par in epoch["params"]}, pm_version, epoch["solver_aman"], xieta_model, weights) + return chisq + + def chi_sq(weights, dist): #N = np.identity(len(dist)) * weights #chi2 = dist.T @ N @ dist @@ -416,9 +447,10 @@ def _create_db(filename, save_dir): else: os.makedirs(save_dir, exist_ok=True) scheme = core.metadata.ManifestScheme() - scheme.add_range_match("obs:obs_timestamp") + scheme.add_range_match("obs:timestamp") scheme.add_data_field("dataset") - return core.metadata.ManifestDb(db_filename, scheme=scheme) + core.metadata.ManifestDb(scheme=scheme).to_file(db_filename) + return core.metadata.ManifestDb(db_filename) def get_parser(parser=None): @@ -483,7 +515,14 @@ def main(config_path: str): ########################################################## ### Begin split for per-detector or per-UFM center fitting ########################################################## - + 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") fit_type = config.get("fit_type", "detector") if fit_type == "detector": @@ -500,66 +539,70 @@ def main(config_path: str): #Make axis manager with full detector set. # Keep wafer/band/obs cuts but do not further downsample. - fitcheck_aman = core.AxisManager(core.IndexAxis("samps")) - ( - filelist, - obs_dets_fits, - weights_dets, - all_nom_det_array, - all_det_ids, - obs_index, - ) = load_per_detector_data(config, no_downsample_set=True) - ancil, roll_c = load_obs_boresight_per_detector(config, filelist, obs_index) - - fitcheck_aman.wrap("ancil", ancil) - fitcheck_aman.wrap( - "nominal_xieta_locs", all_nom_det_array.T, - [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], - [(1, "samps")], - ) - fitcheck_aman.wrap( - "measured_xieta_data", obs_dets_fits.T, - [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], - [(1, "samps")], - ) - fitcheck_aman.wrap("weights", weights_dets, [(0, "samps")]) - fitcheck_aman.wrap("obs_index", obs_index, [(0, "samps")]) - logger.info("Loaded %s fit check data points", len(weights_dets)) - - #Now make axis manager that has down sampled data for computation - solver_aman = core.AxisManager(core.IndexAxis("samps")) - ( - filelist, - obs_dets_fits, - weights_dets, - all_nom_det_array, - all_det_ids, - obs_index, - ) = load_per_detector_data(config) - logger.info("Loaded %s data points", len(weights_dets)) - ancil, roll_c = load_obs_boresight_per_detector(config, filelist, obs_index) - - # Build Axis Managers - solver_aman.wrap("ancil", ancil) - obs_info = core.AxisManager() - obs_info.wrap("obs_ids", np.array(filelist)) - solver_aman.wrap("obs_info", obs_info) - solver_aman.wrap("roll_c", roll_c, [(0, "samps")]) - solver_aman.wrap( - "nominal_xieta_locs", - all_nom_det_array.T, - [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], - [(1, "samps")], - ) - solver_aman.wrap( - "measured_xieta_data", - obs_dets_fits.T, - [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], - [(1, "samps")], - ) - solver_aman.wrap("weights", weights_dets, [(0, "samps")]) - solver_aman.wrap("obs_index", obs_index) - logger.info("Built axis manager") + for epoch in epochs: + t0, tf = epoch["begin_timerange"], epoch["end_timerange"] + fitcheck_aman = core.AxisManager(core.IndexAxis("samps")) + ( + filelist, + obs_dets_fits, + weights_dets, + all_nom_det_array, + all_det_ids, + obs_index, + ) = load_per_detector_data(config, t0, tf, no_downsample_set=True) + ancil, roll_c = load_obs_boresight_per_detector(config, filelist, obs_index) + + fitcheck_aman.wrap("ancil", ancil) + fitcheck_aman.wrap( + "nominal_xieta_locs", all_nom_det_array.T, + [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], + [(1, "samps")], + ) + fitcheck_aman.wrap( + "measured_xieta_data", obs_dets_fits.T, + [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], + [(1, "samps")], + ) + fitcheck_aman.wrap("weights", weights_dets, [(0, "samps")]) + fitcheck_aman.wrap("obs_index", obs_index, [(0, "samps")]) + logger.info("Loaded %s fit check data points", len(weights_dets)) + + #Now make axis manager that has down sampled data for computation + solver_aman = core.AxisManager(core.IndexAxis("samps")) + ( + filelist, + obs_dets_fits, + weights_dets, + all_nom_det_array, + all_det_ids, + obs_index, + ) = load_per_detector_data(config, t0, tf) + logger.info("Loaded %s data points", len(weights_dets)) + ancil, roll_c = load_obs_boresight_per_detector(config, filelist, obs_index) + + # Build Axis Managers + solver_aman.wrap("ancil", ancil) + obs_info = core.AxisManager() + obs_info.wrap("obs_ids", np.array(filelist)) + solver_aman.wrap("obs_info", obs_info) + solver_aman.wrap("roll_c", roll_c, [(0, "samps")]) + solver_aman.wrap( + "nominal_xieta_locs", + all_nom_det_array.T, + [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], + [(1, "samps")], + ) + solver_aman.wrap( + "measured_xieta_data", + obs_dets_fits.T, + [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], + [(1, "samps")], + ) + solver_aman.wrap("weights", weights_dets, [(0, "samps")]) + solver_aman.wrap("obs_index", obs_index) + 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": @@ -569,57 +612,60 @@ def main(config_path: str): logger.info("Loaded nominal UFM centers from %s: ", config.get("ffp_path")) logger.info(nom_ufm_centers) - filelist, obs_ufm_centers, weights_ufm, obs_index = load_per_obs_data(config) - logger.info("Loaded per-obs FFP data from %s: ", config.get("per_obs_fps")) - logger.info("Including data from these obs:") - logger.info(filelist) - - ancil, roll_c = load_obs_boresight(config, filelist) - logger.info("Loaded boresight data from obs ids.") - - # Build Axis Managers - obs_info = core.AxisManager() - obs_info.wrap("obs_ids", np.array(filelist)) - - solver_aman = core.AxisManager(core.IndexAxis("samps")) - solver_aman.wrap("ancil", ancil) - solver_aman.wrap("obs_info", obs_info) - solver_aman.wrap("roll_c", np.repeat(roll_c, 7), [(0, "samps")]) - solver_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")], - ) - solver_aman.wrap( - "measured_xieta_data", - obs_ufm_centers.reshape(len(filelist) * 7, 3).T, - [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], - [(1, "samps")], - ) - solver_aman.wrap("weights", weights_ufm.reshape(-1), [(0, "samps")]) - solver_aman.wrap("obs_index", obs_index) - # Make weights/data cuts - logger.info("Built axis manager") + for epoch in epochs: + t0, tf = epoch["begin_timerange"], epoch["end_timerange"] + filelist, obs_ufm_centers, weights_ufm, obs_index = load_per_obs_data(config, t0, tf) + logger.info("Loaded per-obs FFP data from %s: ", config.get("per_obs_fps")) + logger.info("Including data from these obs:") + logger.info(filelist) + + ancil, roll_c = load_obs_boresight(config, filelist) + logger.info("Loaded boresight data from obs ids.") + + # Build Axis Managers + obs_info = core.AxisManager() + obs_info.wrap("obs_ids", np.array(filelist)) + + solver_aman = core.AxisManager(core.IndexAxis("samps")) + solver_aman.wrap("ancil", ancil) + solver_aman.wrap("obs_info", obs_info) + solver_aman.wrap("roll_c", np.repeat(roll_c, 7), [(0, "samps")]) + solver_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")], + ) + solver_aman.wrap( + "measured_xieta_data", + obs_ufm_centers.reshape(len(filelist) * 7, 3).T, + [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], + [(1, "samps")], + ) + solver_aman.wrap("weights", weights_ufm.reshape(-1), [(0, "samps")]) + solver_aman.wrap("obs_index", obs_index) + # Make weights/data cuts + epoch["solver_aman"] = solver_aman + logger.info("Built axis manager for epoch %s", epoch["name"]) ################################ # END of SPLIT: Now fit the parameters ################################ # Initialize Parameters to Fit with Model - fit_params = _init_fit_params(config) + fit_params, epochs = _init_fit_params(config, epochs) logger.info("Initialized fit parameters") # Solve for Model Parameters # use chosen xieta_model to solve for parameters model_solved_params = minimize( - objective_model_func_lmfit, + objective_model_func_lmfit_joint, fit_params, method="nelder", nan_policy="omit", - args=(pm_version, solver_aman, xieta_model, use_weights), + args=(pm_version, epochs, xieta_model, use_weights), ) logger.info("Ran 1st Minimization") @@ -632,144 +678,158 @@ def main(config_path: str): logger.info(fit_report(model_solved_params)) # save pointing model parameters to axis manager - param_aman = core.AxisManager() - for k in list(test_params.keys()): - param_aman.wrap(k, test_params[k]) - solver_aman.wrap("pointing_model", param_aman) - - # save errors to axis manager - error_aman = core.AxisManager() - for k in list(model_solved_params.params.values()): - error_aman.wrap(k.name, k.stderr) - solver_aman.wrap("pointing_model_errors", error_aman) - - # parameter_fit_stats = build_param_fit_stat_aman(model_solved_params) - # solver_aman.wrap("parameter_fit_stats", parameter_fit_stats) - - # Model template and measured points using parameters found above - modeled_fits, fit_residuals_i1, rms_i1, model_reference = apply_model_params(xieta_model, solver_aman.pointing_model, pm_version, 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) - solver_aman.wrap("modeled_fits", modelfit_aman, overwrite=True) - solver_aman.wrap("fit_residuals", fit_residuals_i1, overwrite=True) - solver_aman.wrap("fit_rms", rms_i1, overwrite=True) - - if fit_type == "detector": - _, fit_residuals_full, rms_full, _ = apply_model_params(xieta_model, solver_aman.pointing_model, pm_version, fitcheck_aman) - logger.info("RMS on FULL detector set: %f arcmin", rms_full) - solver_aman.wrap("fit_residuals_full", fit_residuals_full, overwrite=True) - solver_aman.wrap("fit_rms_full", rms_full, overwrite=True) - solver_aman.wrap("obs_index_full", fitcheck_aman.obs_index) + for epoch in epochs: + logger.info("Calculating RMS and cutoff for %s", epoch["name"]) + 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 errors to axis manager + error_aman = core.AxisManager() + for k in list(model_solved_params.params.values()): + if k.name in epoch["params"]: + error_aman.wrap(par_mapping[k.name], k.stderr) + epoch["solver_aman"].wrap("pointing_model_errors", error_aman) + + # parameter_fit_stats = build_param_fit_stat_aman(model_solved_params) + # solver_aman.wrap("parameter_fit_stats", parameter_fit_stats) + + # Model template and measured points using parameters found above + 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) - 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"): - tag = "_i1" - plotter = ModelFitsPlotter(solver_aman=solver_aman, - config=config, - save_dir=save_dir, - iteration_tag=tag, - 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() - 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() + 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"): + tag = f"{epoch['name']}_i1" + plotter = ModelFitsPlotter(solver_aman=epoch["solver_aman"], + config=config, + save_dir=save_dir, + iteration_tag=tag, + 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() + 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() if iterate_cutoff is not None: logger.info("Iterating parameter solution") logger.info(f"Using {iterate_cutoff} as cutoff") - if iterate_cutoff == "auto": - iterate_cutoff = np.nanstd(fit_residuals_i1)*2 + np.nanmedian(fit_residuals_i1) - logger.info(f"Using {iterate_cutoff} as cutoff") - bad_fit_inds = np.where(fit_residuals_i1 > iterate_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), - iterate_cutoff, - ) - - 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 < iterate_cutoff)[0] - _, _, masked_rms, _ = apply_model_params(xieta_model, - solver_aman.pointing_model, - pm_version, - solver_aman, - use_inds=good_fit_inds) - - logger.info("RMS on initial fit without outliers: %f arcmin", masked_rms) - solver_aman.wrap('bad_fit_inds', bad_fit_inds) - solver_aman.weights[bad_fit_inds] = 0.0 - - model_solved_params = minimize( - objective_model_func_lmfit, - fit_params, - method="nelder", - nan_policy="omit", - args=(pm_version, solver_aman, xieta_model, use_weights), - ) - - 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) + 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( - model_solved_params.params.pretty_print(precision=5, colwidth=11) + "%f data points are higher than %s arcmin", + len(bad_fit_inds), + cutoff, ) - logger.info("Fit Report:") - logger.info(lmfit.fit_report(model_solved_params)) - # save pointing model parameters to axis manager - solver_aman.move("pointing_model", "pointing_model_i1") + 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"].wrap('bad_fit_inds', bad_fit_inds) + epoch["solver_aman"].weights[bad_fit_inds] = 0.0 + + model_solved_params = minimize( + objective_model_func_lmfit_joint, + fit_params, + method="nelder", + nan_policy="omit", + args=(pm_version, epochs, xieta_model, use_weights), + ) + + 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: + logger.info("Calculating RMS for %s", epoch["name"]) + 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(test_params.keys()): - param_aman.wrap(k, test_params[k]) - solver_aman.wrap("pointing_model", param_aman, overwrite=True) + 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 - solver_aman.move("pointing_model_errors", "pointing_model_errors_i1") + epoch["solver_aman"].move("pointing_model_errors", "pointing_model_errors_i1") error_aman = core.AxisManager() for k in list(model_solved_params.params.values()): - error_aman.wrap(k.name, k.stderr) - solver_aman.wrap("pointing_model_errors", error_aman, overwrite=True) + if k.name in epoch["params"]: + error_aman.wrap(par_mapping[k.name], k.stderr) + epoch["solver_aman"].wrap("pointing_model_errors", error_aman) # parameter_fit_stats = build_param_fit_stat_aman(model_solved_params) - # solver_aman.wrap("parameter_fit_stats", parameter_fit_stats, overwrite=True) + # epoch["solver_aman"].wrap("parameter_fit_stats", parameter_fit_stats, overwrite=True) # Recalculate best-fit modeled points modeled_fits, fit_residuals_i2, rms_i2, model_reference = apply_model_params(xieta_model, - solver_aman.pointing_model, + epoch["solver_aman"].pointing_model, pm_version, - solver_aman) + epoch["solver_aman"]) logger.info("RMS on secondary fit: %f arcmin", rms_i2) @@ -777,23 +837,23 @@ def main(config_path: str): modelfit_aman = core.AxisManager() modelfit_aman.wrap("xi", modeled_fits[0], overwrite=True) modelfit_aman.wrap("eta", modeled_fits[1], overwrite=True) - solver_aman.wrap("modeled_fits", modelfit_aman, overwrite=True) - solver_aman.move("fit_residuals", "fit_residuals_i1") - solver_aman.wrap("fit_residuals", fit_residuals_i2, overwrite=True) - solver_aman.move("fit_rms", "fit_rms_i1") - solver_aman.wrap("fit_rms", rms_i2, 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, _ = pm.apply_model_params(xieta_model, solver_aman.pointing_model, pm_version, fitcheck_aman) + _, 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) - solver_aman.move("fit_residuals_full", "fit_residuals_full_i1") - solver_aman.move("fit_rms_full", "fit_rms_full_i1") - solver_aman.wrap("fit_residuals_full", fit_residuals_full, overwrite=True) - solver_aman.wrap("fit_rms_full", rms_full, overwrite=True) + 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 = "_i2" - plotter = ModelFitsPlotter(solver_aman=solver_aman, + tag = f"{epoch['name']}_i2" + plotter = ModelFitsPlotter(solver_aman=epoch["solver_aman"], config=config, save_dir=save_dir, iteration_tag=tag, @@ -813,206 +873,205 @@ def main(config_path: str): plotter.plot_dets_in_these_obs() else: if config.get("make_plots"): - plotter = ModelFitsPlotter(solver_aman=solver_aman, - config=config, - save_dir=save_dir, - iteration_tag="", - save_figure=True, - plotlims=plotlims) - plotter.plot_total_residuals() + for epoch in epochs: + plotter = ModelFitsPlotter(solver_aman=epoch["solver_aman"], + config=config, + save_dir=save_dir, + iteration_tag=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) - solver_aman.save(h5_filename, overwrite=True) dbfile = "db.sqlite" - t0 = config.get("begin_timerange", 0) - t1 = config.get("end_timerange", int(time.time())) - Epoch_Name = config.get("epoch_name") db = _create_db(dbfile, save_dir) - db.add_entry( - {"obs:obs_timestamp": (t0, t1), "dataset": f"{Epoch_Name}_parameters"}, - filename=h5_rel, - replace=True, - ) - db.to_file(os.path.join(save_dir, dbfile)) + for epoch in epochs: + 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): - #Fill up axis manager with ALL the data (only cuts from culling and time stamps remain) - - ( - filelist, - obs_dets_fits, - weights_dets, - all_nom_det_array, - all_det_ids, - obs_index, - ) = load_per_detector_data(config, return_all_dets=True) - ancil, roll_c = load_obs_boresight_per_detector(config, filelist, obs_index) - ufm_list = [ufm.split("_")[1] for ufm in config.get('ufms')] - - obs_info = core.AxisManager() - obs_info.wrap("obs_ids", np.array(filelist)) - - full_aman = core.AxisManager(core.IndexAxis("samps")) - full_aman.wrap("obs_info", obs_info) - full_aman.wrap("ancil", ancil) - full_aman.wrap( - "nominal_xieta_locs", all_nom_det_array.T, - [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], - [(1, "samps")], - ) - full_aman.wrap( - "measured_xieta_data", obs_dets_fits.T, - [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], - [(1, "samps")], - ) - full_aman.wrap("weights", weights_dets, [(0, "samps")]) - full_aman.wrap("obs_index", obs_index) - full_aman.wrap("roll_c", roll_c, [(0, "samps")]) - full_aman.wrap("det_ids", all_det_ids, [(0, "samps")]) - full_aman.wrap("radial", - np.sqrt(full_aman.nominal_xieta_locs[0]**2 + full_aman.nominal_xieta_locs[1]**2)/DEG, - [(0, "samps")]) - full_aman.wrap("det_ufm", - np.array([detid.decode('utf-8').split('_')[0].lower() for detid in full_aman.det_ids]) - , [(0, "samps")]) - full_aman.wrap("det_wafer", np.array([ufm_list.index(d) for d in full_aman.det_ufm]), [(0, "samps")]) - - try: - full_modeled, full_residuals, rms, _ = apply_model_params("template", - solver_aman.pointing_model_i1, - config.get("pm_version"), - full_aman) - except: + 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"] + ( + filelist, + obs_dets_fits, + weights_dets, + all_nom_det_array, + all_det_ids, + obs_index, + ) = load_per_detector_data(config, t0, tf, return_all_dets=True) + ancil, roll_c = load_obs_boresight_per_detector(config, filelist, obs_index) + ufm_list = [ufm.split("_")[1] for ufm in config.get('ufms')] + + obs_info = core.AxisManager() + obs_info.wrap("obs_ids", np.array(filelist)) + + full_aman = core.AxisManager(core.IndexAxis("samps")) + full_aman.wrap("obs_info", obs_info) + full_aman.wrap("ancil", ancil) + full_aman.wrap( + "nominal_xieta_locs", all_nom_det_array.T, + [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], + [(1, "samps")], + ) + full_aman.wrap( + "measured_xieta_data", obs_dets_fits.T, + [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], + [(1, "samps")], + ) + full_aman.wrap("weights", weights_dets, [(0, "samps")]) + full_aman.wrap("obs_index", obs_index) + full_aman.wrap("roll_c", roll_c, [(0, "samps")]) + full_aman.wrap("det_ids", all_det_ids, [(0, "samps")]) + full_aman.wrap("radial", + np.sqrt(full_aman.nominal_xieta_locs[0]**2 + full_aman.nominal_xieta_locs[1]**2)/DEG, + [(0, "samps")]) + full_aman.wrap("det_ufm", + np.array([detid.decode('utf-8').split('_')[0].lower() for detid in full_aman.det_ids]) + , [(0, "samps")]) + full_aman.wrap("det_wafer", np.array([ufm_list.index(d) for d in full_aman.det_ufm]), [(0, "samps")]) + + # try: + # full_modeled, full_residuals, rms, _ = apply_model_params("template", + # epoch["solver_aman"].pointing_model_i1, + # config.get("pm_version"), + # full_aman) + # except: full_modeled, fit_residuals, rms, _ = apply_model_params("template", - solver_aman.pointing_model, - config.get("pm_version"), - full_aman) - - full_aman.wrap("full_modeled", np.array(full_modeled), - [(0, core.LabelAxis("xieta", ["xi", "eta"]))], - [(1, "samps")]) - full_aman.wrap("fit_residuals", fit_residuals, [(0, "samps")]) - del(full_modeled) - del(fit_residuals) - - (obs_az, obs_el, obs_roll, - obs_resid, obs_dxi, obs_deta, - obs_std_xi, obs_std_eta - ) = [], [], [], [], [], [], [], [] - (all_ufm_az, all_ufm_el, all_ufm_roll, - all_ufm_resid, all_ufm_dxi, all_ufm_deta, - all_ufm_std_xi, all_ufm_std_eta, all_ufm_wafer_num - ) = [], [], [], [], [], [], [], [], [] - for ob in np.unique(full_aman.obs_index): - inds = np.where(full_aman.obs_index == ob)[0] - obs_az.append(np.nanmedian(full_aman.ancil.az_enc[inds])) - obs_el.append(np.nanmedian(full_aman.ancil.el_enc[inds])) - obs_roll.append(np.nanmedian(full_aman.roll_c[inds])) - obs_resid.append(np.nanmean(full_aman.fit_residuals[inds])) - obs_dxi.append(np.nanmean((full_aman.full_modeled[0] - - full_aman.nominal_xieta_locs[0])[inds]/DEG*60)) - obs_deta.append(np.nanmean((full_aman.full_modeled[1] - - full_aman.nominal_xieta_locs[1])[inds]/DEG*60)) - obs_std_xi.append(np.nanstd((full_aman.full_modeled[0] - - full_aman.nominal_xieta_locs[0])[inds]/DEG*60)) - obs_std_eta.append(np.nanstd((full_aman.full_modeled[1] - - full_aman.nominal_xieta_locs[1])[inds]/DEG*60)) - (ufm_az, ufm_el, ufm_roll, ufm_resid, - ufm_dxi, ufm_deta, ufm_std_xi, - ufm_std_eta, ufm_wafer_num - )= [], [], [], [], [], [], [], [], [] - for ufm in ufm_list: - ufm_inds = np.where(full_aman.det_ufm[inds] == ufm)[0] - ufm_az.append(np.nanmedian(full_aman.ancil.az_enc[inds][ufm_inds])) - ufm_el.append(np.nanmedian(full_aman.ancil.el_enc[inds][ufm_inds])) - ufm_roll.append(np.nanmedian(full_aman.roll_c[inds][ufm_inds])) - ufm_resid.append(np.nanmean(full_aman.fit_residuals[inds][ufm_inds])) - ufm_dxi.append(np.nanmean((full_aman.full_modeled[0] - - full_aman.nominal_xieta_locs[0])[inds][ufm_inds]/DEG*60)) - ufm_deta.append(np.nanmean((full_aman.full_modeled[1] - - full_aman.nominal_xieta_locs[1])[inds][ufm_inds]/DEG*60)) - ufm_std_xi.append(np.nanstd((full_aman.full_modeled[0] - - full_aman.nominal_xieta_locs[0])[inds][ufm_inds]/DEG*60)) - ufm_std_eta.append(np.nanstd((full_aman.full_modeled[1] - - full_aman.nominal_xieta_locs[1])[inds][ufm_inds]/DEG*60)) - ufm_wafer_num.append(np.nanmedian(full_aman.det_wafer[inds][ufm_inds])) - all_ufm_az.append(ufm_az) - all_ufm_el.append(ufm_el) - all_ufm_roll.append(ufm_roll) - all_ufm_resid.append(ufm_resid) - all_ufm_deta.append(ufm_deta) - all_ufm_dxi.append(ufm_dxi) - all_ufm_std_xi.append(ufm_std_xi) - all_ufm_std_eta.append(ufm_std_eta) - all_ufm_wafer_num.append(ufm_wafer_num) + epoch["solver_aman"].pointing_model, + config.get("pm_version"), + full_aman) - per_ufm_stats = core.AxisManager() - per_obs_stats = core.AxisManager() - - per_obs_stats.wrap("el", np.array(obs_el)) - per_obs_stats.wrap("roll", np.array(obs_roll)) - per_obs_stats.wrap("az", np.array(obs_az)) - per_obs_stats.wrap("resid", np.array(obs_resid)) - per_obs_stats.wrap("dxi", np.array(obs_dxi)) - per_obs_stats.wrap("deta", np.array(obs_deta)) - per_obs_stats.wrap("std_xi", np.array(obs_std_xi)) - per_obs_stats.wrap("std_eta", np.array(obs_std_eta)) - - per_ufm_stats.wrap("az", np.array(all_ufm_az)) - per_ufm_stats.wrap("el", np.array(all_ufm_el)) - per_ufm_stats.wrap("roll", np.array(all_ufm_roll)) - per_ufm_stats.wrap("resid", np.array(all_ufm_resid)) - per_ufm_stats.wrap("dxi", np.array(all_ufm_dxi)) - per_ufm_stats.wrap("deta", np.array(all_ufm_deta)) - per_ufm_stats.wrap("std_xi", np.array(all_ufm_std_xi)) - per_ufm_stats.wrap("std_eta", np.array(all_ufm_std_eta)) - per_ufm_stats.wrap("wafer_num", np.array(all_ufm_wafer_num)) - - if platform == "lat": - obs_cr = [] - all_ufm_cr = [] + full_aman.wrap("full_modeled", np.array(full_modeled), + [(0, core.LabelAxis("xieta", ["xi", "eta"]))], + [(1, "samps")]) + full_aman.wrap("fit_residuals", fit_residuals, [(0, "samps")]) + del(full_modeled) + del(fit_residuals) + + (obs_az, obs_el, obs_roll, + obs_resid, obs_dxi, obs_deta, + obs_std_xi, obs_std_eta + ) = [], [], [], [], [], [], [], [] + (all_ufm_az, all_ufm_el, all_ufm_roll, + all_ufm_resid, all_ufm_dxi, all_ufm_deta, + all_ufm_std_xi, all_ufm_std_eta, all_ufm_wafer_num + ) = [], [], [], [], [], [], [], [], [] for ob in np.unique(full_aman.obs_index): - inds = np.where(full_aman.obs_index == ob)[0] - obs_cr.append(np.nanmedian(full_aman.ancil.corotator_enc[inds])) - ufm_cr = [] + inds = np.where(full_aman.obs_index == ob)[0] + obs_az.append(np.nanmedian(full_aman.ancil.az_enc[inds])) + obs_el.append(np.nanmedian(full_aman.ancil.el_enc[inds])) + obs_roll.append(np.nanmedian(full_aman.roll_c[inds])) + obs_resid.append(np.nanmean(full_aman.fit_residuals[inds])) + obs_dxi.append(np.nanmean((full_aman.full_modeled[0] - + full_aman.nominal_xieta_locs[0])[inds]/DEG*60)) + obs_deta.append(np.nanmean((full_aman.full_modeled[1] - + full_aman.nominal_xieta_locs[1])[inds]/DEG*60)) + obs_std_xi.append(np.nanstd((full_aman.full_modeled[0] - + full_aman.nominal_xieta_locs[0])[inds]/DEG*60)) + obs_std_eta.append(np.nanstd((full_aman.full_modeled[1] - + full_aman.nominal_xieta_locs[1])[inds]/DEG*60)) + (ufm_az, ufm_el, ufm_roll, ufm_resid, + ufm_dxi, ufm_deta, ufm_std_xi, + ufm_std_eta, ufm_wafer_num + )= [], [], [], [], [], [], [], [], [] for ufm in ufm_list: - ufm_cr.append(np.nanmedian(full_aman.ancil.corotator_enc[inds][ufm_inds])) - all_ufm_cr.append(ufm_cr) - per_obs_stats.wrap("cr", np.array(obs_cr)) - per_ufm_stats.wrap("cr", np.array(all_ufm_cr)) - - full_aman.wrap("dxi", (full_aman.full_modeled[0] - - full_aman.nominal_xieta_locs[0])/DEG*60, [(0, "samps")]) - full_aman.wrap("deta", (full_aman.full_modeled[1] - - full_aman.nominal_xieta_locs[1])/DEG*60, [(0, "samps")]) - - #full_dxi_av = np.nanmean(full_dxi) - #full_deta_av = np.nanmean(full_deta) - 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]) - - #Calculate RMSs - per_obs_stats.wrap("rms", np.sqrt(np.nanmean(per_obs_stats["dxi"]**2 + per_obs_stats["deta"]**2))) - per_ufm_stats.wrap("rms", np.sqrt(np.nanmean(per_ufm_stats["dxi"]**2 + per_ufm_stats["deta"]**2))) - full_aman.wrap("rms", np.sqrt(np.nanmean(full_aman["dxi"]**2 + full_aman["deta"]**2))) - full_aman.wrap("per_ufm_stats", per_ufm_stats) - full_aman.wrap("per_obs_stats", per_obs_stats) - - plotter = ModelFitsPlotter(solver_aman=full_aman, - config=config, - save_dir=save_dir, - iteration_tag="", - save_figure=True, - plotlims=plotlims) - plotter.plot_full_residuals_across_focalplane() - plotter.plot_full_histogram() - plotter.plot_full_unmodeled_residuals() + ufm_inds = np.where(full_aman.det_ufm[inds] == ufm)[0] + ufm_az.append(np.nanmedian(full_aman.ancil.az_enc[inds][ufm_inds])) + ufm_el.append(np.nanmedian(full_aman.ancil.el_enc[inds][ufm_inds])) + ufm_roll.append(np.nanmedian(full_aman.roll_c[inds][ufm_inds])) + ufm_resid.append(np.nanmean(full_aman.fit_residuals[inds][ufm_inds])) + ufm_dxi.append(np.nanmean((full_aman.full_modeled[0] - + full_aman.nominal_xieta_locs[0])[inds][ufm_inds]/DEG*60)) + ufm_deta.append(np.nanmean((full_aman.full_modeled[1] - + full_aman.nominal_xieta_locs[1])[inds][ufm_inds]/DEG*60)) + ufm_std_xi.append(np.nanstd((full_aman.full_modeled[0] - + full_aman.nominal_xieta_locs[0])[inds][ufm_inds]/DEG*60)) + ufm_std_eta.append(np.nanstd((full_aman.full_modeled[1] - + full_aman.nominal_xieta_locs[1])[inds][ufm_inds]/DEG*60)) + ufm_wafer_num.append(np.nanmedian(full_aman.det_wafer[inds][ufm_inds])) + all_ufm_az.append(ufm_az) + all_ufm_el.append(ufm_el) + all_ufm_roll.append(ufm_roll) + all_ufm_resid.append(ufm_resid) + all_ufm_deta.append(ufm_deta) + all_ufm_dxi.append(ufm_dxi) + all_ufm_std_xi.append(ufm_std_xi) + all_ufm_std_eta.append(ufm_std_eta) + all_ufm_wafer_num.append(ufm_wafer_num) + + per_ufm_stats = core.AxisManager() + per_obs_stats = core.AxisManager() + + per_obs_stats.wrap("el", np.array(obs_el)) + per_obs_stats.wrap("roll", np.array(obs_roll)) + per_obs_stats.wrap("az", np.array(obs_az)) + per_obs_stats.wrap("resid", np.array(obs_resid)) + per_obs_stats.wrap("dxi", np.array(obs_dxi)) + per_obs_stats.wrap("deta", np.array(obs_deta)) + per_obs_stats.wrap("std_xi", np.array(obs_std_xi)) + per_obs_stats.wrap("std_eta", np.array(obs_std_eta)) + + per_ufm_stats.wrap("az", np.array(all_ufm_az)) + per_ufm_stats.wrap("el", np.array(all_ufm_el)) + per_ufm_stats.wrap("roll", np.array(all_ufm_roll)) + per_ufm_stats.wrap("resid", np.array(all_ufm_resid)) + per_ufm_stats.wrap("dxi", np.array(all_ufm_dxi)) + per_ufm_stats.wrap("deta", np.array(all_ufm_deta)) + per_ufm_stats.wrap("std_xi", np.array(all_ufm_std_xi)) + per_ufm_stats.wrap("std_eta", np.array(all_ufm_std_eta)) + per_ufm_stats.wrap("wafer_num", np.array(all_ufm_wafer_num)) + + if platform == "lat": + obs_cr = [] + all_ufm_cr = [] + for ob in np.unique(full_aman.obs_index): + inds = np.where(full_aman.obs_index == ob)[0] + obs_cr.append(np.nanmedian(full_aman.ancil.corotator_enc[inds])) + ufm_cr = [] + for ufm in ufm_list: + ufm_cr.append(np.nanmedian(full_aman.ancil.corotator_enc[inds][ufm_inds])) + all_ufm_cr.append(ufm_cr) + per_obs_stats.wrap("cr", np.array(obs_cr)) + per_ufm_stats.wrap("cr", np.array(all_ufm_cr)) + + full_aman.wrap("dxi", (full_aman.full_modeled[0] - + full_aman.nominal_xieta_locs[0])/DEG*60, [(0, "samps")]) + full_aman.wrap("deta", (full_aman.full_modeled[1] - + full_aman.nominal_xieta_locs[1])/DEG*60, [(0, "samps")]) + + #full_dxi_av = np.nanmean(full_dxi) + #full_deta_av = np.nanmean(full_deta) + 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]) + + #Calculate RMSs + per_obs_stats.wrap("rms", np.sqrt(np.nanmean(per_obs_stats["dxi"]**2 + per_obs_stats["deta"]**2))) + per_ufm_stats.wrap("rms", np.sqrt(np.nanmean(per_ufm_stats["dxi"]**2 + per_ufm_stats["deta"]**2))) + full_aman.wrap("rms", np.sqrt(np.nanmean(full_aman["dxi"]**2 + full_aman["deta"]**2))) + full_aman.wrap("per_ufm_stats", per_ufm_stats) + full_aman.wrap("per_obs_stats", per_obs_stats) + + plotter = ModelFitsPlotter(solver_aman=full_aman, + config=config, + save_dir=save_dir, + iteration_tag=epoch["name"], + save_figure=True, + plotlims=plotlims) + plotter.plot_full_residuals_across_focalplane() + plotter.plot_full_histogram() + plotter.plot_full_unmodeled_residuals() logger.info("Done") From f60187289b716c378df32f2627ddf6fce594e418 Mon Sep 17 00:00:00 2001 From: Elle Shaw Date: Wed, 6 Aug 2025 14:26:16 -0700 Subject: [PATCH 029/132] Added just_test_params functionality to only test initial params against full dataset. --- .../site_pipeline/solve_pointing_model.py | 402 ++++++++++-------- 1 file changed, 225 insertions(+), 177 deletions(-) diff --git a/sotodlib/site_pipeline/solve_pointing_model.py b/sotodlib/site_pipeline/solve_pointing_model.py index 2a7c4a520..d371ee90c 100644 --- a/sotodlib/site_pipeline/solve_pointing_model.py +++ b/sotodlib/site_pipeline/solve_pointing_model.py @@ -439,6 +439,178 @@ def _round_params(param_dict, decimal): return P +def analyze_PM_with_all_dets(config, t0, tf, params): + platform = config.get("platform") + + (filelist, obs_dets_fits, + weights_dets, all_nom_det_array, + all_det_ids, obs_index, + ) = load_per_detector_data(config, t0, tf, return_all_dets=True) + + ancil, roll_c = load_obs_boresight_per_detector(config, filelist, obs_index) + ufm_list = [ufm.split("_")[1] for ufm in config.get('ufms')] + + obs_info = core.AxisManager() + obs_info.wrap("obs_ids", np.array(filelist)) + full_aman = core.AxisManager(core.IndexAxis("samps")) + full_aman.wrap("obs_info", obs_info) + full_aman.wrap("ancil", ancil) + full_aman.wrap( + "nominal_xieta_locs", all_nom_det_array.T, + [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], + [(1, "samps")], + ) + full_aman.wrap( + "measured_xieta_data", obs_dets_fits.T, + [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], + [(1, "samps")], + ) + full_aman.wrap("weights", weights_dets, [(0, "samps")]) + full_aman.wrap("obs_index", obs_index) + full_aman.wrap("roll_c", roll_c, [(0, "samps")]) + full_aman.wrap("det_ids", all_det_ids, [(0, "samps")]) + full_aman.wrap("radial", + np.sqrt(full_aman.nominal_xieta_locs[0]**2 + + full_aman.nominal_xieta_locs[1]**2)/DEG, + [(0, "samps")]) + full_aman.wrap("det_ufm", + np.array([detid.decode('utf-8').split('_')[0].lower() for detid in full_aman.det_ids]) + , [(0, "samps")]) + full_aman.wrap("det_wafer", + np.array([ufm_list.index(d) for d in full_aman.det_ufm]), + [(0, "samps")]) + # Apply model to data. + (full_modeled, full_residuals, rms, _ + ) = apply_model_params("template", + params, + config.get("pm_version"), + full_aman) + 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")]) + del(full_modeled) + del(full_residuals) + + (obs_az, obs_el, obs_roll, obs_resid, + obs_dxi, obs_deta, obs_std_xi, obs_std_eta + ) = [], [], [], [], [], [], [], [] + (all_ufm_az, all_ufm_el, all_ufm_roll, all_ufm_resid, + all_ufm_dxi, all_ufm_deta, all_ufm_std_xi, + all_ufm_std_eta, all_ufm_wafer_num + ) = [], [], [], [], [], [], [], [], [] + for ob in np.unique(full_aman.obs_index): + inds = np.where(full_aman.obs_index == ob)[0] + obs_az.append(np.nanmedian(full_aman.ancil.az_enc[inds])) + obs_el.append(np.nanmedian(full_aman.ancil.el_enc[inds])) + obs_roll.append(np.nanmedian(full_aman.roll_c[inds])) + obs_resid.append(np.nanmean(full_aman.fit_residuals[inds])) + obs_dxi.append(np.nanmean((full_aman.full_modeled[0] - + full_aman.nominal_xieta_locs[0])[inds]/DEG*60)) + obs_deta.append(np.nanmean((full_aman.full_modeled[1] - + full_aman.nominal_xieta_locs[1])[inds]/DEG*60)) + obs_std_xi.append(np.nanstd((full_aman.full_modeled[0] - + full_aman.nominal_xieta_locs[0])[inds]/DEG*60)) + obs_std_eta.append(np.nanstd((full_aman.full_modeled[1] - + full_aman.nominal_xieta_locs[1])[inds]/DEG*60)) + (ufm_az, ufm_el, ufm_roll, ufm_resid, + ufm_dxi, ufm_deta, ufm_std_xi, + ufm_std_eta, ufm_wafer_num + )= [], [], [], [], [], [], [], [], [] + for ufm in ufm_list: + ufm_inds = np.where(full_aman.det_ufm[inds] == ufm)[0] + ufm_az.append(np.nanmedian(full_aman.ancil.az_enc[inds][ufm_inds])) + ufm_el.append(np.nanmedian(full_aman.ancil.el_enc[inds][ufm_inds])) + ufm_roll.append(np.nanmedian(full_aman.roll_c[inds][ufm_inds])) + ufm_resid.append(np.nanmean(full_aman.fit_residuals[inds][ufm_inds])) + ufm_dxi.append(np.nanmean((full_aman.full_modeled[0] - + full_aman.nominal_xieta_locs[0])[inds][ufm_inds]/DEG*60)) + ufm_deta.append(np.nanmean( + (full_aman.full_modeled[1] - + full_aman.nominal_xieta_locs[1])[inds][ufm_inds]/DEG*60)) + ufm_std_xi.append(np.nanstd( + (full_aman.full_modeled[0] - + full_aman.nominal_xieta_locs[0])[inds][ufm_inds]/DEG*60)) + ufm_std_eta.append(np.nanstd( + (full_aman.full_modeled[1] - + full_aman.nominal_xieta_locs[1])[inds][ufm_inds]/DEG*60)) + ufm_wafer_num.append(np.nanmedian(full_aman.det_wafer[inds][ufm_inds])) + all_ufm_az.append(ufm_az) + all_ufm_el.append(ufm_el) + all_ufm_roll.append(ufm_roll) + all_ufm_resid.append(ufm_resid) + all_ufm_deta.append(ufm_deta) + all_ufm_dxi.append(ufm_dxi) + all_ufm_std_xi.append(ufm_std_xi) + all_ufm_std_eta.append(ufm_std_eta) + all_ufm_wafer_num.append(ufm_wafer_num) + + per_ufm_stats = core.AxisManager() + per_obs_stats = core.AxisManager() + per_obs_stats.wrap("el", np.array(obs_el)) + per_obs_stats.wrap("roll", np.array(obs_roll)) + per_obs_stats.wrap("az", np.array(obs_az)) + per_obs_stats.wrap("resid", np.array(obs_resid)) + per_obs_stats.wrap("dxi", np.array(obs_dxi)) + per_obs_stats.wrap("deta", np.array(obs_deta)) + per_obs_stats.wrap("std_xi", np.array(obs_std_xi)) + per_obs_stats.wrap("std_eta", np.array(obs_std_eta)) + per_ufm_stats.wrap("az", np.array(all_ufm_az)) + per_ufm_stats.wrap("el", np.array(all_ufm_el)) + per_ufm_stats.wrap("roll", np.array(all_ufm_roll)) + per_ufm_stats.wrap("resid", np.array(all_ufm_resid)) + per_ufm_stats.wrap("dxi", np.array(all_ufm_dxi)) + per_ufm_stats.wrap("deta", np.array(all_ufm_deta)) + per_ufm_stats.wrap("std_xi", np.array(all_ufm_std_xi)) + per_ufm_stats.wrap("std_eta", np.array(all_ufm_std_eta)) + per_ufm_stats.wrap("wafer_num", np.array(all_ufm_wafer_num)) + + if platform == "lat": + obs_cr = [] + all_ufm_cr = [] + for ob in np.unique(full_aman.obs_index): + inds = np.where(full_aman.obs_index == ob)[0] + obs_cr.append(np.nanmedian(full_aman.ancil.corotator_enc[inds])) + ufm_cr = [] + for ufm in ufm_list: + ufm_cr.append(np.nanmedian(full_aman.ancil.corotator_enc[inds][ufm_inds])) + all_ufm_cr.append(ufm_cr) + per_obs_stats.wrap("cr", np.array(obs_cr)) + per_ufm_stats.wrap("cr", np.array(all_ufm_cr)) + + full_aman.wrap("dxi", + (full_aman.full_modeled[0] - + full_aman.nominal_xieta_locs[0])/DEG*60, + [(0, "samps")]) + full_aman.wrap("deta", + (full_aman.full_modeled[1] - + full_aman.nominal_xieta_locs[1])/DEG*60, + [(0, "samps")]) + 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]) + + #Calculate RMSs + per_obs_stats.wrap("rms", + np.sqrt(np.nanmean(per_obs_stats["dxi"]**2 + per_obs_stats["deta"]**2)) + ) + per_ufm_stats.wrap("rms", + np.sqrt(np.nanmean(per_ufm_stats["dxi"]**2 + + per_ufm_stats["deta"]**2)) + ) + full_aman.wrap("rms", + np.sqrt(np.nanmean(full_aman["dxi"]**2 + + full_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 @@ -508,13 +680,7 @@ def main(config_path: str): Only "measured" or "template" accepted' ) exit - logger.info( - "Pointing model will try to replicate (model) the %s data.", xieta_model - ) - - ########################################################## - ### Begin split for per-detector or per-UFM center fitting - ########################################################## + epochs = config.get("epochs") for epoch in epochs: if "name" not in epoch: @@ -523,7 +689,40 @@ def main(config_path: str): 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 paramters 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, + iteration_tag=f"_{epoch["name"]}", + save_figure=True, + plotlims=plotlims) + plotter.plot_full_residuals_across_focalplane() + plotter.plot_full_histogram() + plotter.plot_full_unmodeled_residuals() + logger.info("done") + + 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) @@ -719,12 +918,11 @@ def main(config_path: str): 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"): - tag = f"{epoch['name']}_i1" + if config.get("make_plots"): plotter = ModelFitsPlotter(solver_aman=epoch["solver_aman"], config=config, save_dir=save_dir, - iteration_tag=tag, + iteration_tag=f"_{epoch['name']}_i1", save_figure=True, plotlims=plotlims) if fit_type == "ufm_center": @@ -852,7 +1050,7 @@ def main(config_path: str): epoch["solver_aman"].wrap("fit_rms_full", rms_full, overwrite=True) if config.get("make_plots"): - tag = f"{epoch['name']}_i2" + tag = f"_{epoch['name']}_i2" plotter = ModelFitsPlotter(solver_aman=epoch["solver_aman"], config=config, save_dir=save_dir, @@ -877,7 +1075,7 @@ def main(config_path: str): plotter = ModelFitsPlotter(solver_aman=epoch["solver_aman"], config=config, save_dir=save_dir, - iteration_tag=epoch["name"], + iteration_tag=f"_{epoch["name"]}", save_figure=True, plotlims=plotlims) plotter.plot_total_residuals() @@ -901,177 +1099,27 @@ def main(config_path: str): 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"] - ( - filelist, - obs_dets_fits, - weights_dets, - all_nom_det_array, - all_det_ids, - obs_index, - ) = load_per_detector_data(config, t0, tf, return_all_dets=True) - ancil, roll_c = load_obs_boresight_per_detector(config, filelist, obs_index) - ufm_list = [ufm.split("_")[1] for ufm in config.get('ufms')] - - obs_info = core.AxisManager() - obs_info.wrap("obs_ids", np.array(filelist)) - full_aman = core.AxisManager(core.IndexAxis("samps")) - full_aman.wrap("obs_info", obs_info) - full_aman.wrap("ancil", ancil) - full_aman.wrap( - "nominal_xieta_locs", all_nom_det_array.T, - [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], - [(1, "samps")], - ) - full_aman.wrap( - "measured_xieta_data", obs_dets_fits.T, - [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], - [(1, "samps")], - ) - full_aman.wrap("weights", weights_dets, [(0, "samps")]) - full_aman.wrap("obs_index", obs_index) - full_aman.wrap("roll_c", roll_c, [(0, "samps")]) - full_aman.wrap("det_ids", all_det_ids, [(0, "samps")]) - full_aman.wrap("radial", - np.sqrt(full_aman.nominal_xieta_locs[0]**2 + full_aman.nominal_xieta_locs[1]**2)/DEG, - [(0, "samps")]) - full_aman.wrap("det_ufm", - np.array([detid.decode('utf-8').split('_')[0].lower() for detid in full_aman.det_ids]) - , [(0, "samps")]) - full_aman.wrap("det_wafer", np.array([ufm_list.index(d) for d in full_aman.det_ufm]), [(0, "samps")]) - - # try: - # full_modeled, full_residuals, rms, _ = apply_model_params("template", - # epoch["solver_aman"].pointing_model_i1, - # config.get("pm_version"), - # full_aman) - # except: - full_modeled, fit_residuals, rms, _ = apply_model_params("template", - epoch["solver_aman"].pointing_model, - config.get("pm_version"), - full_aman) - - full_aman.wrap("full_modeled", np.array(full_modeled), - [(0, core.LabelAxis("xieta", ["xi", "eta"]))], - [(1, "samps")]) - full_aman.wrap("fit_residuals", fit_residuals, [(0, "samps")]) - del(full_modeled) - del(fit_residuals) - - (obs_az, obs_el, obs_roll, - obs_resid, obs_dxi, obs_deta, - obs_std_xi, obs_std_eta - ) = [], [], [], [], [], [], [], [] - (all_ufm_az, all_ufm_el, all_ufm_roll, - all_ufm_resid, all_ufm_dxi, all_ufm_deta, - all_ufm_std_xi, all_ufm_std_eta, all_ufm_wafer_num - ) = [], [], [], [], [], [], [], [], [] - for ob in np.unique(full_aman.obs_index): - inds = np.where(full_aman.obs_index == ob)[0] - obs_az.append(np.nanmedian(full_aman.ancil.az_enc[inds])) - obs_el.append(np.nanmedian(full_aman.ancil.el_enc[inds])) - obs_roll.append(np.nanmedian(full_aman.roll_c[inds])) - obs_resid.append(np.nanmean(full_aman.fit_residuals[inds])) - obs_dxi.append(np.nanmean((full_aman.full_modeled[0] - - full_aman.nominal_xieta_locs[0])[inds]/DEG*60)) - obs_deta.append(np.nanmean((full_aman.full_modeled[1] - - full_aman.nominal_xieta_locs[1])[inds]/DEG*60)) - obs_std_xi.append(np.nanstd((full_aman.full_modeled[0] - - full_aman.nominal_xieta_locs[0])[inds]/DEG*60)) - obs_std_eta.append(np.nanstd((full_aman.full_modeled[1] - - full_aman.nominal_xieta_locs[1])[inds]/DEG*60)) - (ufm_az, ufm_el, ufm_roll, ufm_resid, - ufm_dxi, ufm_deta, ufm_std_xi, - ufm_std_eta, ufm_wafer_num - )= [], [], [], [], [], [], [], [], [] - for ufm in ufm_list: - ufm_inds = np.where(full_aman.det_ufm[inds] == ufm)[0] - ufm_az.append(np.nanmedian(full_aman.ancil.az_enc[inds][ufm_inds])) - ufm_el.append(np.nanmedian(full_aman.ancil.el_enc[inds][ufm_inds])) - ufm_roll.append(np.nanmedian(full_aman.roll_c[inds][ufm_inds])) - ufm_resid.append(np.nanmean(full_aman.fit_residuals[inds][ufm_inds])) - ufm_dxi.append(np.nanmean((full_aman.full_modeled[0] - - full_aman.nominal_xieta_locs[0])[inds][ufm_inds]/DEG*60)) - ufm_deta.append(np.nanmean((full_aman.full_modeled[1] - - full_aman.nominal_xieta_locs[1])[inds][ufm_inds]/DEG*60)) - ufm_std_xi.append(np.nanstd((full_aman.full_modeled[0] - - full_aman.nominal_xieta_locs[0])[inds][ufm_inds]/DEG*60)) - ufm_std_eta.append(np.nanstd((full_aman.full_modeled[1] - - full_aman.nominal_xieta_locs[1])[inds][ufm_inds]/DEG*60)) - ufm_wafer_num.append(np.nanmedian(full_aman.det_wafer[inds][ufm_inds])) - all_ufm_az.append(ufm_az) - all_ufm_el.append(ufm_el) - all_ufm_roll.append(ufm_roll) - all_ufm_resid.append(ufm_resid) - all_ufm_deta.append(ufm_deta) - all_ufm_dxi.append(ufm_dxi) - all_ufm_std_xi.append(ufm_std_xi) - all_ufm_std_eta.append(ufm_std_eta) - all_ufm_wafer_num.append(ufm_wafer_num) - - per_ufm_stats = core.AxisManager() - per_obs_stats = core.AxisManager() - - per_obs_stats.wrap("el", np.array(obs_el)) - per_obs_stats.wrap("roll", np.array(obs_roll)) - per_obs_stats.wrap("az", np.array(obs_az)) - per_obs_stats.wrap("resid", np.array(obs_resid)) - per_obs_stats.wrap("dxi", np.array(obs_dxi)) - per_obs_stats.wrap("deta", np.array(obs_deta)) - per_obs_stats.wrap("std_xi", np.array(obs_std_xi)) - per_obs_stats.wrap("std_eta", np.array(obs_std_eta)) - - per_ufm_stats.wrap("az", np.array(all_ufm_az)) - per_ufm_stats.wrap("el", np.array(all_ufm_el)) - per_ufm_stats.wrap("roll", np.array(all_ufm_roll)) - per_ufm_stats.wrap("resid", np.array(all_ufm_resid)) - per_ufm_stats.wrap("dxi", np.array(all_ufm_dxi)) - per_ufm_stats.wrap("deta", np.array(all_ufm_deta)) - per_ufm_stats.wrap("std_xi", np.array(all_ufm_std_xi)) - per_ufm_stats.wrap("std_eta", np.array(all_ufm_std_eta)) - per_ufm_stats.wrap("wafer_num", np.array(all_ufm_wafer_num)) - - if platform == "lat": - obs_cr = [] - all_ufm_cr = [] - for ob in np.unique(full_aman.obs_index): - inds = np.where(full_aman.obs_index == ob)[0] - obs_cr.append(np.nanmedian(full_aman.ancil.corotator_enc[inds])) - ufm_cr = [] - for ufm in ufm_list: - ufm_cr.append(np.nanmedian(full_aman.ancil.corotator_enc[inds][ufm_inds])) - all_ufm_cr.append(ufm_cr) - per_obs_stats.wrap("cr", np.array(obs_cr)) - per_ufm_stats.wrap("cr", np.array(all_ufm_cr)) - - full_aman.wrap("dxi", (full_aman.full_modeled[0] - - full_aman.nominal_xieta_locs[0])/DEG*60, [(0, "samps")]) - full_aman.wrap("deta", (full_aman.full_modeled[1] - - full_aman.nominal_xieta_locs[1])/DEG*60, [(0, "samps")]) - - #full_dxi_av = np.nanmean(full_dxi) - #full_deta_av = np.nanmean(full_deta) - 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]) - - #Calculate RMSs - per_obs_stats.wrap("rms", np.sqrt(np.nanmean(per_obs_stats["dxi"]**2 + per_obs_stats["deta"]**2))) - per_ufm_stats.wrap("rms", np.sqrt(np.nanmean(per_ufm_stats["dxi"]**2 + per_ufm_stats["deta"]**2))) - full_aman.wrap("rms", np.sqrt(np.nanmean(full_aman["dxi"]**2 + full_aman["deta"]**2))) - full_aman.wrap("per_ufm_stats", per_ufm_stats) - full_aman.wrap("per_obs_stats", per_obs_stats) + if "pointing_model_i1" in solver_aman: + test_params = epoch["solver_aman"].pointing_model_i1 + else: + test_params = epoch["solver_aman"].pointing_model + 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, - iteration_tag=epoch["name"], - save_figure=True, - plotlims=plotlims) + config=config, + save_dir=save_dir, + iteration_tag=f"_{epoch["name"]}", + save_figure=True, + plotlims=plotlims) plotter.plot_full_residuals_across_focalplane() plotter.plot_full_histogram() plotter.plot_full_unmodeled_residuals() + logger.info("Done") From 954bdd5502183cb20faaa5a620ee1abebe16b8e1 Mon Sep 17 00:00:00 2001 From: Elle Shaw Date: Mon, 25 Aug 2025 14:12:29 -0700 Subject: [PATCH 030/132] Made small changes to make code be compatible with latest master branch. --- sotodlib/coords/brightsrc_pointing.py | 2 +- sotodlib/preprocess/processes.py | 3 ++- sotodlib/site_pipeline/get_brightsrc_pointing_step2.py | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/sotodlib/coords/brightsrc_pointing.py b/sotodlib/coords/brightsrc_pointing.py index 5985da6fe..8330fce1f 100644 --- a/sotodlib/coords/brightsrc_pointing.py +++ b/sotodlib/coords/brightsrc_pointing.py @@ -107,7 +107,7 @@ def get_wafer_xieta(wafer_slot, optics_config_fn, xieta_bs_offset=(0., 0.), wafer_r = np.sqrt(wafer_x**2 + wafer_y**2) wafer_theta = np.arctan2(wafer_y, wafer_x) - fp_to_sky = optics.sat_to_sky(optics.SAT_X, optics.SAT_LON) + fp_to_sky = optics.sat_to_sky(optics.SAT_R_FP, optics.SAT_R_SKY) lon = fp_to_sky(wafer_r) q1 = quat.rotation_iso(lon, 0) diff --git a/sotodlib/preprocess/processes.py b/sotodlib/preprocess/processes.py index ad274bf9d..cbfd0f7a0 100644 --- a/sotodlib/preprocess/processes.py +++ b/sotodlib/preprocess/processes.py @@ -1705,7 +1705,7 @@ def process(self, aman, proc_aman, sim=False): class ReduceFlags(_Preprocess): name = 'reduce_flags' - def process(self, aman, proc_aman): + def process(self, aman, proc_aman, sim=False): aman.flags.reduce(**self.process_cfgs) class DetcalNanCuts(_Preprocess): @@ -2506,6 +2506,7 @@ def save(self, proc_aman, flag_aman): if self.save_cfgs: proc_aman.wrap("smurfgaps", flag_aman) +_Preprocess.register(ReduceFlags) _Preprocess.register(SplitFlags) _Preprocess.register(SubtractT2P) _Preprocess.register(EstimateT2P) diff --git a/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py b/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py index 6081d1800..89354f9d3 100644 --- a/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py +++ b/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py @@ -70,7 +70,7 @@ def wrapper_gaussian2d_nonlin(xieta, xi0, eta0, fwhm_xi, fwhm_eta, phi, a, *args return gaussian2d_nonlin(xieta, xi0, eta0, fwhm_xi, fwhm_eta, phi, a, nonlin_coeffs) def wrap_fp_rset(tod, fp_rset): - tod.restrict('dets', tod.dets.vals[np.in1d(tod.dets.vals, fp_rset['dets:readout_id'])]) + tod.restrict('dets', tod.dets.vals[np.isin(tod.dets.vals, fp_rset['dets:readout_id'])]) focal_plane = core.AxisManager(tod.dets) focal_plane.wrap_new('xi', shape=('dets', )) focal_plane.wrap_new('eta', shape=('dets', )) From 092b2ab8b8fc7b413b0751bdff06ce0c29de3f18 Mon Sep 17 00:00:00 2001 From: Elle Shaw Date: Fri, 29 Aug 2025 12:28:38 -0700 Subject: [PATCH 031/132] Removed offensive square brackets in a get_obs call --- sotodlib/site_pipeline/get_brightsrc_pointing_step1.py | 2 +- sotodlib/site_pipeline/get_brightsrc_pointing_step2.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sotodlib/site_pipeline/get_brightsrc_pointing_step1.py b/sotodlib/site_pipeline/get_brightsrc_pointing_step1.py index 2b7aea511..331165ce6 100644 --- a/sotodlib/site_pipeline/get_brightsrc_pointing_step1.py +++ b/sotodlib/site_pipeline/get_brightsrc_pointing_step1.py @@ -201,7 +201,7 @@ def main_one_obs(configs, obs_id, sso_name=None, logger.info(f'sso_names of {sso_names} are found from observation tags.' + f'Processing only {sso_name}') - tod = ctx.get_obs(obs_id, dets=[]) + tod = ctx.get_obs(obs_id, no_signal=True) streamed_wafer_slots = ['ws{}'.format(index) for index, bit in enumerate(obs_id.split('_')[-1]) if bit == '1'] processed_wafer_slots = [] finished_wafer_slots = [] diff --git a/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py b/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py index 89354f9d3..6842cbce6 100644 --- a/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py +++ b/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py @@ -453,7 +453,7 @@ def main_one_obs(configs, obs_id, sso_name=None, logger.info(f'sso_names of {sso_names} are found from observation tags.' + f'Processing only {sso_name}') - tod = ctx.get_obs(obs_id, dets=[]) + tod = ctx.get_obs(obs_id, no_signal=True) streamed_wafer_slots = ['ws{}'.format(index) for index, bit in enumerate(obs_id.split('_')[-1]) if bit == '1'] processed_wafer_slots = [] finished_wafer_slots = [] From 951de7a33dee74fcef02442599447bce891e04e2 Mon Sep 17 00:00:00 2001 From: Elle Shaw Date: Wed, 3 Sep 2025 12:05:52 -0700 Subject: [PATCH 032/132] add saturn to possible source objects --- sotodlib/site_pipeline/get_brightsrc_pointing_step1.py | 4 ++-- sotodlib/site_pipeline/get_brightsrc_pointing_step2.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/sotodlib/site_pipeline/get_brightsrc_pointing_step1.py b/sotodlib/site_pipeline/get_brightsrc_pointing_step1.py index 331165ce6..17d99f039 100644 --- a/sotodlib/site_pipeline/get_brightsrc_pointing_step1.py +++ b/sotodlib/site_pipeline/get_brightsrc_pointing_step1.py @@ -17,7 +17,7 @@ from sotodlib.preprocess import Pipeline logger = util.init_logger(__name__, 'make_map_based_pointing: ') -def _get_sso_names_from_tags(ctx, obs_id, candidate_names=['moon', 'jupiter', 'mars']): +def _get_sso_names_from_tags(ctx, obs_id, candidate_names=['moon', 'jupiter', 'mars', 'saturn']): obs_tags = ctx.obsdb.get(obs_id, tags=True)['tags'] sso_names = [] for _name in candidate_names: @@ -225,7 +225,7 @@ def main_one_obs(configs, obs_id, sso_name=None, logger.info(f'Found saved data for these wafer_slots: {finished_wafer_slots}') logger.info(f'Will continue for these wafer_slots: {processed_wafer_slots}') - + logger.info("using filelock") if configs.get('parallel_job'): logger.info('Continuing with parallel job') try: diff --git a/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py b/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py index 6842cbce6..20ba5b754 100644 --- a/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py +++ b/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py @@ -22,7 +22,7 @@ from sotodlib.preprocess import Pipeline logger = util.init_logger(__name__, 'update_pointing: ') -def _get_sso_names_from_tags(ctx, obs_id, candidate_names=['moon', 'jupiter']): +def _get_sso_names_from_tags(ctx, obs_id, candidate_names=['moon', 'jupiter', 'mars', 'saturn']): obs_tags = ctx.obsdb.get(obs_id, tags=True)['tags'] sso_names = [] for _name in candidate_names: From 2a38cb3ecc46eb25785100d85dbfeafbbf7a156c Mon Sep 17 00:00:00 2001 From: Elle Shaw Date: Thu, 11 Sep 2025 07:41:41 -0700 Subject: [PATCH 033/132] removed obsolete logger entry --- sotodlib/site_pipeline/get_brightsrc_pointing_step1.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sotodlib/site_pipeline/get_brightsrc_pointing_step1.py b/sotodlib/site_pipeline/get_brightsrc_pointing_step1.py index 17d99f039..e29c3bc76 100644 --- a/sotodlib/site_pipeline/get_brightsrc_pointing_step1.py +++ b/sotodlib/site_pipeline/get_brightsrc_pointing_step1.py @@ -225,7 +225,7 @@ def main_one_obs(configs, obs_id, sso_name=None, logger.info(f'Found saved data for these wafer_slots: {finished_wafer_slots}') logger.info(f'Will continue for these wafer_slots: {processed_wafer_slots}') - logger.info("using filelock") + if configs.get('parallel_job'): logger.info('Continuing with parallel job') try: From 512d4eb085bf124080157473cd669120f5c92405 Mon Sep 17 00:00:00 2001 From: Elle Shaw Date: Wed, 19 Nov 2025 14:31:42 -0800 Subject: [PATCH 034/132] fixed bug on including a list of detectors to debug with --- sotodlib/site_pipeline/get_brightsrc_pointing_step2.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py b/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py index 20ba5b754..b648010a1 100644 --- a/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py +++ b/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py @@ -579,7 +579,7 @@ def get_parser(): parser.add_argument("--sso_name", type=str, default=None, help="Name of solar system object (e.g., 'moon', 'jupiter'). If not specified, get sso_name from observation tags. "\ + "Valid only when obs_id is specified") - parser.add_argument("--restrict_dets_for_debug", type=int, default=False) + parser.add_argument("--restrict_dets_for_debug", type=str, default=False) return parser if __name__ == '__main__': From a7fef706a50a49eacdb20a4ea2578958a2eb0070 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Sun, 26 Oct 2025 22:25:25 -0700 Subject: [PATCH 035/132] fix: fix supplying only some init pars and plotting when culled --- sotodlib/site_pipeline/solve_pointing_model.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/sotodlib/site_pipeline/solve_pointing_model.py b/sotodlib/site_pipeline/solve_pointing_model.py index d371ee90c..946ceb5ab 100644 --- a/sotodlib/site_pipeline/solve_pointing_model.py +++ b/sotodlib/site_pipeline/solve_pointing_model.py @@ -284,8 +284,10 @@ def load_obs_boresight_per_detector(config, filelist, obs_ind): def _init_fit_params(config, epochs): pm_version = config.get("pm_version") - init_params = config.get("initial_params", pm.param_defaults[pm_version]) + initial_params = config.get("initial_params", {}) fixed_params = config.get("fixed_params",[]) + init_params = pm.param_defaults[pm_version] + init_params.update(initial_params) # Add independant params orig_pars = np.array(list(init_params.keys())) @@ -293,7 +295,7 @@ def _init_fit_params(config, epochs): for epoch in epochs: indep_list = epoch["indep_list"] if np.sum(np.isin(indep_list, par_list)) != len(indep_list): - raise ValueError(f"Invalid independant parameters in time range starting with {t0}") + 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"]): @@ -573,6 +575,7 @@ def analyze_PM_with_all_dets(config, t0, tf, params): obs_cr.append(np.nanmedian(full_aman.ancil.corotator_enc[inds])) ufm_cr = [] for ufm in ufm_list: + ufm_inds = np.where(full_aman.det_ufm[inds] == ufm)[0] ufm_cr.append(np.nanmedian(full_aman.ancil.corotator_enc[inds][ufm_inds])) all_ufm_cr.append(ufm_cr) per_obs_stats.wrap("cr", np.array(obs_cr)) @@ -596,7 +599,8 @@ def analyze_PM_with_all_dets(config, t0, tf, params): #Calculate RMSs per_obs_stats.wrap("rms", - np.sqrt(np.nanmean(per_obs_stats["dxi"]**2 + per_obs_stats["deta"]**2)) + np.sqrt(np.nanmean(per_obs_stats["dxi"]**2 + + per_obs_stats["deta"]**2)) ) per_ufm_stats.wrap("rms", np.sqrt(np.nanmean(per_ufm_stats["dxi"]**2 + @@ -980,8 +984,8 @@ def main(config_path: str): use_inds=good_fit_inds) logger.info("RMS on initial fit without outliers: %f arcmin", masked_rms) - epoch["solver_aman"].wrap('bad_fit_inds', bad_fit_inds) epoch["solver_aman"].weights[bad_fit_inds] = 0.0 + epoch["solver_aman"].wrap('bad_fit_inds', bad_fit_inds) model_solved_params = minimize( objective_model_func_lmfit_joint, From e7f007fd1a7e215ef55ddbde792d0c6283ec9b25 Mon Sep 17 00:00:00 2001 From: Elle Shaw Date: Tue, 20 Jan 2026 15:19:16 -0800 Subject: [PATCH 036/132] Updated rst documentation with example NERSC submission script --- docs/site_pipeline.rst | 142 ++++++++++++++++++++++++++++------------- 1 file changed, 96 insertions(+), 46 deletions(-) diff --git a/docs/site_pipeline.rst b/docs/site_pipeline.rst index e87110890..6a103d981 100644 --- a/docs/site_pipeline.rst +++ b/docs/site_pipeline.rst @@ -197,28 +197,26 @@ if it does not exist. get_brightsrc_pointing_part1 and get_brightsrc_pointing_part2 ----------------------------------------------------------------- +--------------------------------------------------------------- The two-part ``get_brightsrc_pointing`` script set will will run solve for the xieta coordinates of detectors that observe a bright source during an observation. -It is a two part process that requires a map step and then a tod step. -To run, the scripts require config files described below. +It is a two part process that requires a map step and then a TOD step. +The scripts require the settings and preprocessing config files described below. + +For job submission and parallelization, see example NERSC slurm submission config at the end of this section. The code will process all wafers unless otherwise specified. It is recommended to run with ``parallel_job: True`` in the config files if analyzing -multiple wafers at once. Otherwise, specify a wafer slot or restrict detectors in CL args. - -Recommended SLURM settings - - ``--nodes=1`` - - ``--ntasks=1`` - - ``--time=00:45:00`` - - ``--cpus-per-task=14`` - - ``--mem=150G`` - - export OMP_NUM_THREADS=1 +multiple wafers at once. +Otherwise, specify a wafer slot or restrict detectors in command line args to debug. +.. argparse:: + :module: sotodlib.site_pipeline.get_brightsrc_pointing_part1 or _part2 + :func: get_parser -Recommended Command Line arguments: +Command Line arguments: - ``configs`` - ``--obs_id`` - ``--sso_name`` @@ -227,47 +225,55 @@ Optional Command Line arguments: - ``--wafer_slot`` e.g. ws0 - ``--restrict_dets_for_debug`` integer, or comma separated list of det readout_ids. -Options to include min_ctime and max_ctime arguments, which will proces all obs -in the time frame. - -.. argparse:: - :module: sotodlib.site_pipeline.get_brightsrc_pointing_part1 or _part2 - :func: get_parser - +There are options to include min_ctime and max_ctime arguments, which will process all observations +in the time frame. (not recommended) Generated results ``````````````````` -Saves results as ResultSet .hdf file in the results_dir. -ResultSet<[dets:readout_id, xi, eta, gamma, xi_err, eta_err, R2, redchi2], N rows> +The Step 1 map-based analysis scripts will generate the following outputs in the specified directory: -Load data with sotodlib.io.metadata.read_dataset( results.hdf, 'focal_plane') + 1. Single detector maps in ``/results/single_det_maps/_.hdf``. -Configuration -````````````````` -These scripts take in a config yaml file + * All single maps are packaged in a single hdf file, with detector readout_id as the keys in the h5py file. -Part 1 is the map-based step. Its config file should look like the following: -The parameters in these examples are used for SAT mid-freq moon observations. + 2. Fitted xi-eta focal plane position results saved as ResultSet in ``/path/to/results/map_based_results`` as specified in the Step 1 config file. Script will append 'force_zero_roll' onto the specified results_dir if True in config file. Load ResultSet with keyword 'focal_plane' + + * Contents: ``ResultSet<[dets:readout_id, xi, eta, gamma, R2], N rows>`` + + +The Step 2 TOD-based analysis scripts will use the map-based results as a starting point and then generate the finalized outputs in the specified directory: + + 1. Fitted xi-eta focal plane position results saved as ResultSet in ``/path/to/results/tod_based_results`` as specified in config file for Step-2. Script will append 'force_zero_roll' onto the specified results_dir if True in config file. Load ResultSet with keyword 'focal_plane' + + * Contents: ``ResultSet<[dets:readout_id, xi, eta, gamma, xi_err, eta_err, R2, redchi2], N rows>`` + +Configuration Files +``````````````````` +The configuration files to be input as ``configs`` in the command line arguments should have the following arguments as well as any preprocessing steps wished to be taken. Only processing steps that are agnostic of det-match can be used to do initial analyses without formalized metadata. + +The parameters in these examples could be used for SAT mid-freq moon observations. + +Step 1 Config: .. code-block:: yaml context_file: /path/to/context.yaml - query_tags: ['moon', 'jupiter', 'mars'] (alternatively specify --sso_name in kwargs + query_tags: ['moon'=1] #(alternatively specify --sso_name in kwargs) - optics_config_fn: /path/to/ufm_to_fp.yaml + optics_config_fn: '/global/cfs/cdirs/sobs/users/elleshaw/process_brightsrc/ufm_to_fp.yaml' single_det_maps_dir: /path/to/results/single_det_maps results_dir: /path/to/results/map_based_results - parallel_job: True - wafer_mask_det: 8. + parallel_job: True #For job submission. Parallel across wafers. + wafer_mask_det: 8. #mask around detector to cut TOD when source too far away. res_deg: 0.3 - xieta_bs_offset: [0., 0.] + xieta_bs_offset: [0., 0.] #Good to input xieta offset in radians. (!!! for satp2) save_normal_roll: False #false for SAT, true for LAT save_force_zero_roll: True #true for SAT, false for LAT - hit_time_threshold: 600 #seconds - hit_circle_r_deg: 7. + hit_circle_r_deg: 7. # radial mask to decide which UFMs are hit by source and should be analyzed. + hit_time_threshold: 600 #seconds, if hit_time not met then UFM does not get analyzed. process_pipe: - name: 'detrend' @@ -302,22 +308,20 @@ The parameters in these examples are used for SAT mid-freq moon observations. .. code-block:: yaml context_file: /path/to/context.yaml - query_tags: ['moon', 'jupiter', 'mars'] (alternatively specify --sso_name in kwargs - - optics_config_fn: /path/to/ufm_to_fp.yaml + query_tags: ['moon'=1] #(alternatively specify --sso_name in kwargs) + optics_config_fn: '/global/cfs/cdirs/sobs/users/elleshaw/process_brightsrc/ufm_to_fp.yaml' fp_hdf_dir: /path/to/results/map_based_results from step 1 config file. - # If force_zero_roll is was True, then append _force_zero_roll to the end - result_dir: /path/to/resuls/tod_based_results + # If force_zero_roll is was True, then append _force_zero_roll to the end. Just make sure it matches where the results from Step 1 are. + result_dir: /path/to/resuls/tod_based_results #Where you want the final Step2 results to show up. parallel_job: True - force_zero_roll: True - + force_zero_roll: True #Results will show up roatated in the xi-eta results as they are on the sky. ds_factor: 40 - mask_deg: 2.5 + mask_deg: 2.5 # size for circular mask around SSO (helps exclude focal plane reflections too) fit_func_name: 'gaussian2d_nonlin' - max_non_linear_order: 3 - fwhm_init_deg: 0.5 + max_non_linear_order: 3 #Suggested to use 1 for jupiter or sso's that do not saturate. + fwhm_init_deg: 0.5 # Lower for SATp2 error_estimation_method: 'force_one_redchi2' flag_name_rms_calc: 'around_source' flag_rms_calc_exclusive: False @@ -378,9 +382,55 @@ The parameters in these examples are used for SAT mid-freq moon observations. mask: 'around_source' exclusive: False +Example NERSC slurm job submission config file +`````````````````````````````````````````````` + +.. code-block:: yaml + #!/bin/bash -l + + #SBATCH --qos=shared + #SBATCH --constraint=cpu + #SBATCH --nodes=1 + #SBATCH --ntasks=1 + + #SBATCH --cpus-per-task=14 + #SBATCH --time=00:30:00 + #SBATCH --mem=220G`` #(may require regular queue and up to 400 Gb for extra long observations) + + export OMP_NUM_THREADS=1 + set -e + + tele=$1 + obs=$2 + map=$3 + basis=$4 + source="moon_from_moon" + + ymldir="/path/to/processing_settings_config_folder" + yfile="${ymldir}/preprocess_config_moon_${basis}_based_${tele}.yaml" + + if (($map)); then + echo submitted map job; + srun -n 1 -N 1 -c 14 python3 /path/to/sotodlib/site_pipeline/get_brightsrc_pointing_step1.py $yfile --obs_id=${2} --sso_name="moon"; + else + echo submitted tod job; + srun -n 1 -N 1 -c 14 python3 /path/to/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py $yfile --obs_id=${2} --sso_name="moon"; + fi + + +Submit the job submission file with the following commands: + +1. For Step 1 map-based + + * ``sbatch submit_moon_job_script.sh 1 map`` + +2. For Step 2 TOD based + + * ``sbatch submit_moon_job_script.sh 0 tod`` + make_read_det_match -``````````````````` +------------------- This script generates the readout ID to detector ID mapping required to translate between the detector hardware information (ex: pixel position) and the readout IDs of the resonators used to index the SMuRF data. The script uses the From 2de0b169fb2964146746e061602a83eed10f15d9 Mon Sep 17 00:00:00 2001 From: Elle Shaw Date: Mon, 16 Feb 2026 12:38:11 -0800 Subject: [PATCH 037/132] Changes according to requested comments. Condensed ReduceFlags into CombineFlags, implemented MPI parallel processing, and other syntax updates. --- docs/site_pipeline.rst | 96 +++++++++++-------- sotodlib/coords/brightsrc_pointing.py | 17 ++-- sotodlib/preprocess/processes.py | 32 +++---- .../get_brightsrc_pointing_step1.py | 61 ++++++------ .../get_brightsrc_pointing_step2.py | 69 +++++++------ sotodlib/tod_ops/sub_polyf.py | 7 +- 6 files changed, 152 insertions(+), 130 deletions(-) diff --git a/docs/site_pipeline.rst b/docs/site_pipeline.rst index 6a103d981..ea9ea5537 100644 --- a/docs/site_pipeline.rst +++ b/docs/site_pipeline.rst @@ -196,10 +196,10 @@ The output database ``wafer_info.sqlite`` and HDF5 file if it does not exist. -get_brightsrc_pointing_part1 and get_brightsrc_pointing_part2 ---------------------------------------------------------------- +get_brightsrc_pointing_part1 +---------------------------- -The two-part ``get_brightsrc_pointing`` script set will will run solve for the xieta +The two-part ``get_brightsrc_pointing_part{}`` script set will solve for the xieta coordinates of detectors that observe a bright source during an observation. It is a two part process that requires a map step and then a TOD step. @@ -212,21 +212,14 @@ It is recommended to run with ``parallel_job: True`` in the config files if anal multiple wafers at once. Otherwise, specify a wafer slot or restrict detectors in command line args to debug. +Command Line arguments: .. argparse:: - :module: sotodlib.site_pipeline.get_brightsrc_pointing_part1 or _part2 + :module: sotodlib.site_pipeline.get_brightsrc_pointing_part1 :func: get_parser -Command Line arguments: - - ``configs`` - - ``--obs_id`` - - ``--sso_name`` - -Optional Command Line arguments: - - ``--wafer_slot`` e.g. ws0 - - ``--restrict_dets_for_debug`` integer, or comma separated list of det readout_ids. -There are options to include min_ctime and max_ctime arguments, which will process all observations -in the time frame. (not recommended) +There options to include min_ctime and max_ctime arguments, which will process all observations +in the time frame, is not recommended unless severely restricting the detectors for debugging. Generated results @@ -237,20 +230,28 @@ The Step 1 map-based analysis scripts will generate the following outputs in the * All single maps are packaged in a single hdf file, with detector readout_id as the keys in the h5py file. - 2. Fitted xi-eta focal plane position results saved as ResultSet in ``/path/to/results/map_based_results`` as specified in the Step 1 config file. Script will append 'force_zero_roll' onto the specified results_dir if True in config file. Load ResultSet with keyword 'focal_plane' + 2. Fitted xi-eta focal plane position results saved as ResultSet in ``/path/to/results/map_based_results`` + as specified in the Step 1 config file. Script will append 'force_zero_roll' onto the specified results_dir + if True in config file. Load ResultSet with keyword 'focal_plane' * Contents: ``ResultSet<[dets:readout_id, xi, eta, gamma, R2], N rows>`` -The Step 2 TOD-based analysis scripts will use the map-based results as a starting point and then generate the finalized outputs in the specified directory: +The Step 2 TOD-based analysis scripts will use the map-based results as a starting point + and then generate the finalized outputs in the specified directory: - 1. Fitted xi-eta focal plane position results saved as ResultSet in ``/path/to/results/tod_based_results`` as specified in config file for Step-2. Script will append 'force_zero_roll' onto the specified results_dir if True in config file. Load ResultSet with keyword 'focal_plane' + 1. Fitted xi-eta focal plane position results saved as ResultSet in ``/path/to/results/tod_based_results`` + as specified in config file for Step-2. Script will append 'force_zero_roll' onto the specified results_dir + if True in config file. Load ResultSet with keyword 'focal_plane' * Contents: ``ResultSet<[dets:readout_id, xi, eta, gamma, xi_err, eta_err, R2, redchi2], N rows>`` Configuration Files ``````````````````` -The configuration files to be input as ``configs`` in the command line arguments should have the following arguments as well as any preprocessing steps wished to be taken. Only processing steps that are agnostic of det-match can be used to do initial analyses without formalized metadata. +The configuration files to be input as ``configs`` in the command line should +have the following arguments as well as any preprocessing steps wished to be taken. +Only processing steps that are agnostic of det-match can be used to do +initial analyses without formalized metadata. The parameters in these examples could be used for SAT mid-freq moon observations. @@ -259,14 +260,14 @@ Step 1 Config: .. code-block:: yaml context_file: /path/to/context.yaml - query_tags: ['moon'=1] #(alternatively specify --sso_name in kwargs) + query_tags: ['moon=1'] #(alternatively specify --sso_name in kwargs) optics_config_fn: '/global/cfs/cdirs/sobs/users/elleshaw/process_brightsrc/ufm_to_fp.yaml' single_det_maps_dir: /path/to/results/single_det_maps results_dir: /path/to/results/map_based_results parallel_job: True #For job submission. Parallel across wafers. - wafer_mask_det: 8. #mask around detector to cut TOD when source too far away. + wafer_mask_det: 8. # (degrees) mask around detector to cut TOD when source too far away. res_deg: 0.3 xieta_bs_offset: [0., 0.] #Good to input xieta offset in radians. (!!! for satp2) save_normal_roll: False #false for SAT, true for LAT @@ -308,20 +309,22 @@ The parameters in these examples are used for SAT mid-freq moon observations. .. code-block:: yaml context_file: /path/to/context.yaml - query_tags: ['moon'=1] #(alternatively specify --sso_name in kwargs) + query_tags: ['moon=1'] #(alternatively specify --sso_name in kwargs) optics_config_fn: '/global/cfs/cdirs/sobs/users/elleshaw/process_brightsrc/ufm_to_fp.yaml' fp_hdf_dir: /path/to/results/map_based_results from step 1 config file. - # If force_zero_roll is was True, then append _force_zero_roll to the end. Just make sure it matches where the results from Step 1 are. + # If force_zero_roll is was True, then append _force_zero_roll to the end. + # Just make sure it matches where the results from Step 1 are. result_dir: /path/to/resuls/tod_based_results #Where you want the final Step2 results to show up. parallel_job: True force_zero_roll: True #Results will show up roatated in the xi-eta results as they are on the sky. ds_factor: 40 - mask_deg: 2.5 # size for circular mask around SSO (helps exclude focal plane reflections too) + mask_deg: 2.5 # (degrees) size for circular mask around SSO (helps exclude focal plane reflections too) fit_func_name: 'gaussian2d_nonlin' - max_non_linear_order: 3 #Suggested to use 1 for jupiter or sso's that do not saturate. - fwhm_init_deg: 0.5 # Lower for SATp2 + max_non_linear_order: 3 #Suggested to use 1 for jupiter or sso's + #that do not saturate. + fwhm_init_deg: 0.5 # (degrees) Lower for SATp2 error_estimation_method: 'force_one_redchi2' flag_name_rms_calc: 'around_source' flag_rms_calc_exclusive: False @@ -351,27 +354,28 @@ The parameters in these examples are used for SAT mid-freq moon observations. cutoff: 1.9 width: 0.2 - name: 'source_flags' + source_flags_name: 'source_wide' + save: True calc: - merge: True - max_pix: 10000000000 - source_flags_name: 'source_wide' mask: shape: circle xyr: [0., 0., 5.0] - - name: 'source_flags' - calc: merge: True max_pix: 10000000000 - source_flags_name: 'source_narrow' + - name: 'source_flags' + source_flags_name: 'source_narrow' + save: True + calc: mask: shape: circle xyr: [0., 0., 3.0] - - name: 'reduce_flags' + merge: True + max_pix: 10000000000 + - name: 'combine_flags' process: - flags: ['source_wide', 'source_narrow'] - method: 'except' - wrap: True - new_flag: 'around_source' + flag_labels: ['source_wide.moon', 'source_narrow.moon'] + method: 'except' + total_flags_label: 'around_source' - name: 'flag_turnarounds' process: truncate: True @@ -395,7 +399,7 @@ Example NERSC slurm job submission config file #SBATCH --cpus-per-task=14 #SBATCH --time=00:30:00 - #SBATCH --mem=220G`` #(may require regular queue and up to 400 Gb for extra long observations) + #SBATCH --mem=220G`` #(may need regular queue & up to 400 Gb for long obs) export OMP_NUM_THREADS=1 set -e @@ -411,10 +415,14 @@ Example NERSC slurm job submission config file if (($map)); then echo submitted map job; - srun -n 1 -N 1 -c 14 python3 /path/to/sotodlib/site_pipeline/get_brightsrc_pointing_step1.py $yfile --obs_id=${2} --sso_name="moon"; + srun -n 1 -N 1 -c 14 python3 + /path/to/sotodlib/site_pipeline/get_brightsrc_pointing_step1.py $yfile + --obs_id=${2} --sso_name="moon"; else echo submitted tod job; - srun -n 1 -N 1 -c 14 python3 /path/to/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py $yfile --obs_id=${2} --sso_name="moon"; + srun -n 1 -N 1 -c 14 python3 + /path/to/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py $yfile + --obs_id=${2} --sso_name="moon"; fi @@ -499,6 +507,16 @@ entries mater. det_info: true multi: true + +get_brightsrc_pointing_part2 +---------------------------- +See Part 1 for description + +.. argparse:: + :module: sotodlib.site_pipeline.get_brightsrc_pointing_part2 + :func: get_parser + + update_det_match ------------------ diff --git a/sotodlib/coords/brightsrc_pointing.py b/sotodlib/coords/brightsrc_pointing.py index 8330fce1f..2cb8605d6 100644 --- a/sotodlib/coords/brightsrc_pointing.py +++ b/sotodlib/coords/brightsrc_pointing.py @@ -1,10 +1,12 @@ +# These functions are used for fitting detector positions from bright point sources +# called by site_pipeline.get_brightsrc_pointing_step1 and site_pipeline.get_brightsrc_pointing_step2 import os import re from tqdm import tqdm import numpy as np from scipy import interpolate from scipy.optimize import curve_fit -from joblib import Parallel, delayed +#from joblib import Parallel, delayed from sotodlib import core from sotodlib import coords @@ -20,11 +22,12 @@ def get_planet_trajectory(tod, planet, _split=20, return_model=False): """ - Generate the trajectory of a given planet over a specified time range. + Generate the trajectory in horizon coordinates of a given planet over a specified time range. Parameters: - tod : An axis manager - planet (str): The name of the planet for which to generate the trajectory. + tod : An axis manager containing a timestamps field, which is used to + determine the time range and generate the trajectory. + planet (str): The name of the object for which to generate the trajectory. e.g. "moon" or "saturn" _split (int, optional): Number of points to interpolate the trajectory. Defaults to 20. return_model (bool, optional): If True, returns interpolation functions of az and el. Defaults to False. @@ -34,7 +37,6 @@ def get_planet_trajectory(tod, planet, _split=20, return_model=False): If return_model is False: array: Array of quaternions representing trajectory of the planet at each timestamp. """ - print(planet) timestamps_sparse = np.linspace(tod.timestamps[0], tod.timestamps[-1], _split) planet_az_sparse = np.zeros_like(timestamps_sparse) @@ -136,7 +138,8 @@ def get_wafer_xieta(wafer_slot, optics_config_fn, xieta_bs_offset=(0., 0.), def get_rough_hit_time(tod, wafer_slot, sso_name, circle_r_deg=7.,optics_config_fn=None): """ - Estimate the rough hit time for a axismanager, wafer_slot, and sso_name. + Estimate the rough hit time, which is the amount of time for which the source + is within some distance from the center of a wafer slot. Parameters: tod : An AxisManager object @@ -166,6 +169,8 @@ def make_wafer_centered_maps(tod, sso_name, optics_config_fn, map_hdf, signal='signal', wafer_mask_deg=8., res_deg=0.3, cuts=None,): """ Generate boresight-centered maps from Time-Ordered Data (TOD) for each individual detector. + This script modifies tod.focal_plane and tod.boresight + Parameters: tod : an axismanager object sso_name (str): Name of the planet for which the trajectory is calculated. diff --git a/sotodlib/preprocess/processes.py b/sotodlib/preprocess/processes.py index f6ee863ee..1b77db1da 100644 --- a/sotodlib/preprocess/processes.py +++ b/sotodlib/preprocess/processes.py @@ -1,3 +1,4 @@ +import pdb import numpy as np from operator import attrgetter import copy @@ -1784,7 +1785,7 @@ def calc_and_save(self, aman, proc_aman): source_aman.wrap(source + '_inv', RangesMatrix.ones([aman.dets.count, aman.samps.count]), [(0, 'dets'), (1, 'samps')]) - + self.save(proc_aman, source_aman) return aman, proc_aman @@ -1991,12 +1992,7 @@ def process(self, aman, proc_aman, sim=False): aman.samps.offset + aman.samps.count - trim)) proc_aman.restrict('samps', (proc_aman.samps.offset + trim, proc_aman.samps.offset + proc_aman.samps.count - trim)) - return aman, proc_aman - -class ReduceFlags(_Preprocess): - name = 'reduce_flags' - def process(self, aman, proc_aman, sim=False): - aman.flags.reduce(**self.process_cfgs) + return aman, proc_aman class DetcalNanCuts(_Preprocess): """ @@ -2524,9 +2520,9 @@ def process(self, aman, proc_aman, sim=False): aman['flags'].wrap(self.process_cfgs['total_flags_label'], total_flags) return aman, proc_aman - + class CombineFlags(_Preprocess): - """Do the conbine of relevant flags for mapping + """Do the combination of relevant flags for mapping Saves results for aman under the "flags.[total_flags_label]" field. @@ -2537,8 +2533,11 @@ class CombineFlags(_Preprocess): process: flag_labels: ['glitches.glitch_flags', 'source_flags.jupiter_inv'] total_flags_label: 'glitch_flags' - method: 'union' # You can select a method from ['union', '+', 'intersect', '*']. - #method: ['+', '*'] # Or you can pass individual method for each flags as a list. Lentgh must match the length of flag_labels. + method: 'union' # You can select a method from ['union', '+', 'intersect', '*', 'except', '-']. + #method: ['+', '*'] # Or you can pass individual method for each flags as a list. + # Length of list must match the length of flag_labels. + # If a list, the first method must be '+', as if adding the first flag set to an empty flag set. + # Operations are performed strictly from Left to Right, '*' are not performed first. """ name = "combine_flags" @@ -2548,13 +2547,12 @@ def process(self, aman, proc_aman, sim=False): if isinstance(self.process_cfgs['method'], list): if len(self.process_cfgs['flag_labels']) != len(self.process_cfgs['method']): raise ValueError("The length of method does not match to the length of flag_labels") - elif any(method not in ['+', 'union', '*', 'intersect'] for method in self.process_cfgs['method']): - raise ValueError("The method provided does not match one of '+', '*', 'union', or 'intersect'") - elif self.process_cfgs['method'] in ['+', 'union', '*', 'intersect']: + elif any(method not in ['+', 'union', '*', 'intersect', '-', 'except'] for method in self.process_cfgs['method']): + raise ValueError("One or more methods in list are not valid") + elif self.process_cfgs['method'] in ['+', 'union', '*', 'intersect', '-', 'except']: self.process_cfgs['method'] = ['+'] + (len(self.process_cfgs['flag_labels']) - 1)*[self.process_cfgs['method']] else: - raise ValueError("The method matches neither list nor the one of the ['+', 'union', '*', 'intersect']") - + raise ValueError("The method matches neither list nor the one of the valid operations") total_flags = RangesMatrix.zeros([proc_aman.dets.count, proc_aman.samps.count]) # get an empty flags with shape (Ndets,Nsamps) for i, (method, label) in enumerate(zip(self.process_cfgs['method'], self.process_cfgs['flag_labels'])): _label = attrgetter(label) @@ -2567,6 +2565,8 @@ def process(self, aman, proc_aman, sim=False): total_flags += _label(proc_aman) # The + operator is the union operator in this case elif method in ['*', 'intersect']: total_flags *= _label(proc_aman) # The * operator is the intersect operator in this case + elif method in ['-', 'except']: + total_flags *= ~ _label(proc_aman) # The - operator is the except operator in this case if 'flags' not in aman._fields: from sotodlib.core import FlagManager diff --git a/sotodlib/site_pipeline/get_brightsrc_pointing_step1.py b/sotodlib/site_pipeline/get_brightsrc_pointing_step1.py index e29c3bc76..c77a229d6 100644 --- a/sotodlib/site_pipeline/get_brightsrc_pointing_step1.py +++ b/sotodlib/site_pipeline/get_brightsrc_pointing_step1.py @@ -4,7 +4,7 @@ import argparse import time import glob -from joblib import Parallel, delayed +import logging from sotodlib import core from sotodlib import coords @@ -12,10 +12,14 @@ from sotodlib.coords import brightsrc_pointing as bsp from sotodlib.io import metadata from sotodlib.io.metadata import read_dataset, write_dataset - -from sotodlib.site_pipeline import util +from sotodlib.site_pipeline.utils.pipeline import main_launcher from sotodlib.preprocess import Pipeline -logger = util.init_logger(__name__, 'make_map_based_pointing: ') +from sotodlib.utils.procs_pool import get_exec_env +from sotodlib.site_pipeline.utils.logging import init_logger as sp_init_logger + +logger = logging.getLogger("get_brightsrc_pointing_step1") +if not logger.hasHandlers(): + sp_init_logger("get_brightsrc_pointing_step1") def _get_sso_names_from_tags(ctx, obs_id, candidate_names=['moon', 'jupiter', 'mars', 'saturn']): obs_tags = ctx.obsdb.get(obs_id, tags=True)['tags'] @@ -109,7 +113,7 @@ def main_one_wafer(configs, obs_id, wafer_slot, sso_name=None, filename=result_filename, force_zero_roll=True, edge_avoidance = edge_avoidance_deg*coords.DEG) - return + return f"Finished processing {obs_id}, {wafer_slot}" def main_one_wafer_dummy(configs, obs_id, wafer_slot, restrict_dets_for_debug=False): if type(configs) == str: @@ -169,15 +173,6 @@ def combine_pointings(pointing_result_files): focal_plane.rows.append((det, val['xi'], val['eta'], val['gamma'], val['R2'])) return focal_plane -def parallel_process_wafer_slot(configs, obs_id, wafer_slot, sso_name, restrict_dets_for_debug): - logger.info(f'Processing {obs_id}, {wafer_slot}') - main_one_wafer(configs=configs, - obs_id=obs_id, - wafer_slot=wafer_slot, - sso_name=sso_name, - restrict_dets_for_debug=restrict_dets_for_debug) - - def main_one_obs(configs, obs_id, sso_name=None, restrict_dets_for_debug=False): if type(configs) == str: @@ -234,17 +229,19 @@ def main_one_obs(configs, obs_id, sso_name=None, n_jobs = -1 logger.info('Entering wafer pool') - Parallel(n_jobs=n_jobs)( - delayed(parallel_process_wafer_slot)( - configs, - obs_id, - wafer_slot, - sso_name, - restrict_dets_for_debug, - ) - for wafer_slot in processed_wafer_slots - ) - logger.info('Exiting wafer pool') + rank, executor, as_completed_callable = get_exec_env(nprocs=n_jobs) + futures = [executor.submit( + main_one_wafer, + configs=configs, + obs_id=obs_id, + wafer_slot=wafer_slot, + sso_name=sso_name, + restrict_dets_for_debug=restrict_dets_for_debug, + ) + for wafer_slot in processed_wafer_slots] + for future in as_completed_callable(futures): + logger.info(future.result()) + else: logger.info('Continuing with serial processing of wafers.') for wafer_slot in processed_wafer_slots: @@ -328,20 +325,20 @@ def main(configs, min_ctime=None, max_ctime=None, update_delay=None, def get_parser(): parser = argparse.ArgumentParser(description="Process TOD data and update pointing") parser.add_argument("configs", type=str, help="Path to the configuration file") - parser.add_argument('--min_ctime', type=int, help="Minimum timestamp for the beginning of an observation list") - parser.add_argument('--max_ctime', type=int, help="Maximum timestamp for the beginning of an observation list") + parser.add_argument('--min-ctime', type=int, help="Minimum timestamp for the beginning of an observation list") + parser.add_argument('--max-ctime', type=int, help="Maximum timestamp for the beginning of an observation list") parser.add_argument('--update-delay', type=int, help="Number of days (unit is days) in the past to start observation list.") - parser.add_argument("--obs_id", type=str, + parser.add_argument("--obs-id", type=str, help="Specific observation obs_id to process. If provided, overrides other filtering parameters.") - parser.add_argument("--wafer_slot", type=str, default=None, + parser.add_argument("--wafer-slot", type=str, default=None, help="Wafer slot to be processed (e.g., 'ws0', 'ws3'). Valid only when obs_id is specified.") - parser.add_argument("--sso_name", type=str, default=None, + parser.add_argument("--sso-name", type=str, default=None, help="Name of solar system object (e.g., 'moon', 'jupiter'). If not specified, get sso_name from observation tags. "\ + "Valid only when obs_id is specified") - parser.add_argument("--restrict_dets_for_debug", type=str, default=False) + parser.add_argument("--restrict-dets-for-debug", type=str, default=False) return parser if __name__ == '__main__': - util.main_launcher(main, get_parser) + main_launcher(main, get_parser) diff --git a/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py b/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py index b648010a1..17cb2a7ff 100644 --- a/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py +++ b/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py @@ -6,7 +6,7 @@ import time import glob from tqdm import tqdm -from joblib import Parallel, delayed +import logging from scipy.optimize import curve_fit from sotodlib.core import metadata @@ -18,9 +18,14 @@ import so3g from so3g.proj import quat import sotodlib.coords.planets as planets -from sotodlib.site_pipeline import util +from sotodlib.site_pipeline.utils.pipeline import main_launcher from sotodlib.preprocess import Pipeline -logger = util.init_logger(__name__, 'update_pointing: ') +from sotodlib.utils.procs_pool import get_exec_env +from sotodlib.site_pipeline.utils.logging import init_logger as sp_init_logger + +logger = logging.getLogger("get_brightsrc_pointing_step2") +if not logger.hasHandlers(): + sp_init_logger("get_brightsrc_pointing_step2") def _get_sso_names_from_tags(ctx, obs_id, candidate_names=['moon', 'jupiter', 'mars', 'saturn']): obs_tags = ctx.obsdb.get(obs_id, tags=True)['tags'] @@ -71,16 +76,14 @@ def wrapper_gaussian2d_nonlin(xieta, xi0, eta0, fwhm_xi, fwhm_eta, phi, a, *args def wrap_fp_rset(tod, fp_rset): tod.restrict('dets', tod.dets.vals[np.isin(tod.dets.vals, fp_rset['dets:readout_id'])]) + _, ind_tod, ind_rset = core.util.get_coindices(tod.dets.vals, fp_rset['dets:readout_id']) focal_plane = core.AxisManager(tod.dets) focal_plane.wrap_new('xi', shape=('dets', )) focal_plane.wrap_new('eta', shape=('dets', )) - focal_plane.wrap_new('gamma', shape=('dets', )) - - for di, det in enumerate(tod.dets.vals): - di_rset = np.where(fp_rset['dets:readout_id'] == det)[0][0] - focal_plane.xi[di] = fp_rset['xi'][di_rset] - focal_plane.eta[di] = fp_rset['eta'][di_rset] - focal_plane.gamma[di] = fp_rset['gamma'][di_rset] + focal_plane.wrap_new('gamma', shape=('dets', )) + focal_plane.xi[ind_tod] = fp_rset['xi'][ind_rset] + focal_plane.eta[ind_tod] = fp_rset['eta'][ind_rset] + focal_plane.gamma[ind_tod] = fp_rset['gamma'][ind_rset] if 'focal_plane' in tod._fields.keys(): tod.move('focal_plane', None) @@ -367,7 +370,7 @@ def main_one_wafer(configs, obs_id, wafer_slot, sso_name=None, address='focal_plane', overwrite=True) - return + return f"Finished processing {obs_id}, {wafer_slot}" def main_one_wafer_dummy(configs, obs_id, wafer_slot, restrict_dets_for_debug=False): if type(configs) == str: @@ -422,14 +425,6 @@ def combine_pointings(pointing_result_files): focal_plane.rows.append((det, val['xi'], val['eta'], val['gamma'], val['xi_err'], val['eta_err'], val['R2'], val['redchi2'])) return focal_plane -def parallel_process_wafer_slot(configs, obs_id, wafer_slot, sso_name, restrict_dets_for_debug): - logger.info(f'Processing {obs_id}, {wafer_slot}') - main_one_wafer(configs=configs, - obs_id=obs_id, - wafer_slot=wafer_slot, - sso_name=sso_name, - restrict_dets_for_debug=restrict_dets_for_debug) - def main_one_obs(configs, obs_id, sso_name=None, restrict_dets_for_debug=False): if type(configs) == str: @@ -484,16 +479,18 @@ def main_one_obs(configs, obs_id, sso_name=None, n_jobs = int(os.environ.get('SLURM_CPUS_PER_TASK', 1)) except: n_jobs = -1 - Parallel(n_jobs=n_jobs)( - delayed(parallel_process_wafer_slot)( - configs, - obs_id, - wafer_slot, - sso_name, - restrict_dets_for_debug - ) - for wafer_slot in processed_wafer_slots - ) + rank, executor, as_completed_callable = get_exec_env(nprocs=n_jobs) + futures = [executor.submit( + main_one_wafer, + configs=configs, + obs_id=obs_id, + wafer_slot=wafer_slot, + sso_name=sso_name, + restrict_dets_for_debug=restrict_dets_for_debug, + ) + for wafer_slot in processed_wafer_slots] + for future in as_completed_callable(futures): + logger.info(future.result()) else: logger.info('Continuing with serial processing of wafers.') for wafer_slot in processed_wafer_slots: @@ -567,20 +564,20 @@ def main(configs, min_ctime=None, max_ctime=None, update_delay=None, def get_parser(): parser = argparse.ArgumentParser(description="Get updated result of pointings with tod-based results") parser.add_argument("configs", type=str, help="Path to the configuration file") - parser.add_argument('--min_ctime', type=int, help="Minimum timestamp for the beginning of an observation list") - parser.add_argument('--max_ctime', type=int, help="Maximum timestamp for the beginning of an observation list") + parser.add_argument('--min-ctime', type=int, help="Minimum timestamp for the beginning of an observation list") + parser.add_argument('--max-ctime', type=int, help="Maximum timestamp for the beginning of an observation list") parser.add_argument('--update-delay', type=int, help="Number of days (unit is days) in the past to start observation list.") - parser.add_argument("--obs_id", type=str, + parser.add_argument("--obs-id", type=str, help="Specific observation obs_id to process. If provided, overrides other filtering parameters.") - parser.add_argument("--wafer_slot", type=str, default=None, + parser.add_argument("--wafer-slot", type=str, default=None, help="Wafer slot to be processed (e.g., 'ws0', 'ws3'). Valid only when obs_id is specified.") - parser.add_argument("--sso_name", type=str, default=None, + parser.add_argument("--sso-name", type=str, default=None, help="Name of solar system object (e.g., 'moon', 'jupiter'). If not specified, get sso_name from observation tags. "\ + "Valid only when obs_id is specified") - parser.add_argument("--restrict_dets_for_debug", type=str, default=False) + parser.add_argument("--restrict-dets-for-debug", type=str, default=False) return parser if __name__ == '__main__': - util.main_launcher(main, get_parser) + main_launcher(main, get_parser) diff --git a/sotodlib/tod_ops/sub_polyf.py b/sotodlib/tod_ops/sub_polyf.py index 57bf35a31..66aeec36c 100644 --- a/sotodlib/tod_ops/sub_polyf.py +++ b/sotodlib/tod_ops/sub_polyf.py @@ -44,6 +44,7 @@ def subscan_polyfilter(aman, degree, signal_name="signal", exclude_turnarounds=F """ if method not in ["polyfit", "legendre"] : raise ValueError("Only polyfit and legendre are acceptable.") + if exclude_turnarounds: if ("left_scan" not in aman.flags) or ("turnarounds" not in aman.flags): logger.warning('aman does not have left/right scan or turnarounds flag. `sotodlib.flags.get_turnaround_flags` will be ran with default parameters') @@ -113,6 +114,7 @@ def subscan_polyfilter(aman, degree, signal_name="signal", exclude_turnarounds=F elif method == "legendre": degree_corr = degree + 1 + time = np.copy(aman["timestamps"]) for start, end in subscan_indices: @@ -123,6 +125,7 @@ def subscan_polyfilter(aman, degree, signal_name="signal", exclude_turnarounds=F # Get each subscan to be filtered tod_mat = copy.deepcopy(signal[:, start:end]) + # Scale time range into [-1,1] x = np.linspace(-1, 1, tod_mat.shape[1]) dx = np.mean(np.diff(x)) @@ -163,13 +166,15 @@ def subscan_polyfilter(aman, degree, signal_name="signal", exclude_turnarounds=F tod_mat[idet,msk_indx] = interped else : pass - + + means = np.mean(tod_mat, axis=1)[:, np.newaxis] tod_mat -= means # Make model to be subtracted coeffs = np.dot(arr_legendre, tod_mat.T) model = np.dot((coeffs/norm_vector[:, np.newaxis]).T,arr_legendre)*dx + model += means signal[:,start:end] -= model From f3befaae72272685532f0bc0a1d48ef7bb8507f8 Mon Sep 17 00:00:00 2001 From: Elle Shaw Date: Tue, 24 Feb 2026 16:37:03 -0800 Subject: [PATCH 038/132] Fixed issues with lonlat quat rotations and hacky negative xi solutions --- sotodlib/coords/brightsrc_pointing.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/sotodlib/coords/brightsrc_pointing.py b/sotodlib/coords/brightsrc_pointing.py index 2cb8605d6..0ed141e21 100644 --- a/sotodlib/coords/brightsrc_pointing.py +++ b/sotodlib/coords/brightsrc_pointing.py @@ -52,7 +52,7 @@ def get_planet_trajectory(tod, planet, _split=20, return_model=False): else: planet_az = planet_az_func(tod.timestamps) planet_el = planet_el_func(tod.timestamps) - q_planet = quat.rotation_lonlat(planet_az, planet_el) + q_planet = quat.rotation_lonlat(-1 * planet_az, planet_el) return q_planet def get_wafer_centered_sight(tod=None, planet=None, q_planet=None, q_bs=None, q_wafer=None): @@ -73,18 +73,18 @@ def get_wafer_centered_sight(tod=None, planet=None, q_planet=None, q_bs=None, q_ Returns: Sightline vector for the planet trajectory centered on the center of the wafer. """ + #breakpoint() if q_planet is None: q_planet = get_planet_trajectory(tod, planet) if q_bs is None: - q_bs = quat.rotation_lonlat(tod.boresight.az, tod.boresight.el) + q_bs = quat.rotation_lonlat(-1 * tod.boresight.az, tod.boresight.el) if q_wafer is None: q_wafer = quat.rotation_xieta(np.nanmedian(tod.focal_plane.xi), np.nanmedian(tod.focal_plane.eta)) xi_wafer, eta_wafer, _ = quat.decompose_xieta(q_wafer) - q_wafer_f = quat.rotation_xieta(-xi_wafer, eta_wafer) z_to_x = quat.rotation_lonlat(0, 0) - sight = z_to_x * ~(q_bs * q_wafer_f) * q_planet + sight = z_to_x * ~(q_bs * q_wafer) * q_planet return sight def get_wafer_xieta(wafer_slot, optics_config_fn, xieta_bs_offset=(0., 0.), @@ -151,7 +151,7 @@ def get_rough_hit_time(tod, wafer_slot, sso_name, circle_r_deg=7.,optics_config_ Returns: float: Estimated rough hit time within the circular region around the wafer center. """ - q_bs = quat.rotation_lonlat(tod.boresight.az, tod.boresight.el) + q_bs = quat.rotation_lonlat(-1 * tod.boresight.az, tod.boresight.el) q_planet = get_planet_trajectory(tod, sso_name) xi_wafer, eta_wafer = get_wafer_xieta(wafer_slot, optics_config_fn=optics_config_fn, roll_bs_offset=np.median(tod.boresight.roll), wrap_to_tod=False) @@ -186,8 +186,9 @@ def make_wafer_centered_maps(tod, sso_name, optics_config_fn, map_hdf, Returns: None """ + #breakpoint() q_planet = get_planet_trajectory(tod, sso_name) - q_bs = quat.rotation_lonlat(tod.boresight.az, tod.boresight.el) + q_bs = quat.rotation_lonlat(-1 * tod.boresight.az, tod.boresight.el) if roll_bs_offset is None: roll_bs_offset = np.mean(tod.boresight.roll) @@ -419,7 +420,7 @@ def map_to_xieta(mT, edge_avoidance=1.0*coords.DEG, edge_check='nan', (np.inf, beam_sigma_init*5, np.inf),), max_nfev = 1000000) R2 = 1 - np.sum((_z - _gauss1d(_r, *popt))**2)/np.sum((_z - np.mean(_z))**2) - xi_det, eta_det, R2_det = -xi_peak, eta_peak, R2 + xi_det, eta_det, R2_det = xi_peak, eta_peak, R2 else: xi_det, eta_det, R2_det = np.nan, np.nan, np.nan return xi_det, eta_det, R2_det From 76ae8dfe5719ce2372e21ccc8d53a4c1e7d004a9 Mon Sep 17 00:00:00 2001 From: Elle Shaw Date: Wed, 4 Mar 2026 13:06:05 -0800 Subject: [PATCH 039/132] Find boresight azimuth and elevation during detector crossings. --- .../get_brightsrc_pointing_step2.py | 22 +++++++++++++------ 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py b/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py index 17cb2a7ff..34d82839c 100644 --- a/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py +++ b/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py @@ -8,6 +8,10 @@ from tqdm import tqdm import logging +import matplotlib +matplotlib.use('Agg') +import matplotlib.pyplot as plt + from scipy.optimize import curve_fit from sotodlib.core import metadata from sotodlib.io.metadata import read_dataset, write_dataset @@ -154,7 +158,7 @@ def update_xieta(tod, # if focal_plane result is specified, use the information as a prior if fp_hdf_file is not None: wrap_fp_from_hdf(tod, fp_hdf_file) - + # set dets without focal_plane info to have (xi, eta, gamma) = (0, 0, 0), just to avoid error xieta_isnan = (np.isnan(tod.focal_plane.xi)) | (np.isnan(tod.focal_plane.eta)) gamma_isnan = np.isnan(tod.focal_plane.gamma) @@ -213,14 +217,17 @@ def update_xieta(tod, xieta_dict = {} for di, det in enumerate(tqdm(tod.dets.vals)): mask_di = source_flags_ds[di] + bs_az = np.nanmedian(tod.boresight.az[mask_ds][mask_di]) + bs_el = np.nanmedian(tod.boresight.el[mask_ds][mask_di]) + if np.any([xieta_isnan[di], np.all(mask_di==False), tod.rms[di]==0.]): xieta_dict[det] = {'xi': np.nan, 'eta': np.nan, 'xi_err': np.nan, 'eta_err': np.nan, - 'R2': np.nan, 'redchi2': np.nan} + 'R2': np.nan, 'redchi2': np.nan, 'az': np.nan, 'el': np.nan} else: ts = ts_ds[mask_di] d1_unix = np.median(ts) - xieta_det = np.array([tod.focal_plane.xi[di], tod.focal_plane.eta[di]]) + xieta_det = np.array([tod.focal_plane.xi[di], tod.focal_plane.eta[di]]) q_det = so3g.proj.quat.rotation_xieta(xieta_det[0], xieta_det[1]) planet = planets.SlowSource.for_named_source(sso_name, d1_unix * 1.) ra0, dec0 = planet.pos(d1_unix) @@ -232,7 +239,7 @@ def update_xieta(tod, xieta_src = xieta_src[:, mask_di] sig = sig_ds[di][mask_di] ptp_val = np.ptp(np.percentile(sig, [0.1, 99.9])) - + if fit_func_name == 'gaussian2d_nonlin': p0 = np.array([0., 0., fwhm_init_deg*coords.DEG, fwhm_init_deg*coords.DEG, 0., ptp_val]) bounds = np.array( @@ -270,16 +277,17 @@ def update_xieta(tod, xieta_det += np.array([xi_opt, eta_opt]) xieta_dict[det] = {'xi': xieta_det[0], 'eta': xieta_det[1], 'xi_err': xi_err, 'eta_err': eta_err, - 'R2': R2, 'redchi2': redchi2} + 'R2': R2, 'redchi2': redchi2, 'az' : bs_az, 'el': bs_el} except RuntimeError: xieta_dict[det] = {'xi': np.nan, 'eta': np.nan, 'xi_err': np.nan, 'eta_err': np.nan, - 'R2': np.nan, 'redchi2': np.nan} + 'R2': np.nan, 'redchi2': np.nan, 'az': np.nan, 'el': np.nan} - focal_plane = metadata.ResultSet(keys=['dets:readout_id', 'xi', 'eta', 'gamma', 'xi_err', 'eta_err', 'R2', 'redchi2']) + focal_plane = metadata.ResultSet(keys=['dets:readout_id', 'xi', 'eta', 'gamma', 'xi_err', 'eta_err', 'R2', 'redchi2', 'az', 'el']) for det in tod.dets.vals: focal_plane.rows.append((det, xieta_dict[det]['xi'], xieta_dict[det]['eta'], 0., xieta_dict[det]['xi_err'], xieta_dict[det]['eta_err'], xieta_dict[det]['R2'], xieta_dict[det]['redchi2'], + xieta_dict[det]['az'], xieta_dict[det]['el'], )) return focal_plane From 81ac88696a15da661398b7b0b16a444e7081cc2a Mon Sep 17 00:00:00 2001 From: Elle Shaw Date: Tue, 17 Mar 2026 20:26:47 -0700 Subject: [PATCH 040/132] propagate addition of az and el and roll to result set output in dummy wafer and final full wafer products --- .../get_brightsrc_pointing_step2.py | 24 +++++++++++-------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py b/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py index 34d82839c..ef1a77853 100644 --- a/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py +++ b/sotodlib/site_pipeline/get_brightsrc_pointing_step2.py @@ -183,7 +183,7 @@ def update_xieta(tod, max_pix=1e10, wrap='source', mask={'shape':'circle', 'xyr':[0.,0.,mask_deg]}) - + # restrict data to duration when at least one detector hit the source summed_flag = np.sum(tod.flags['source'].mask()[~xieta_isnan], axis=0).astype('bool') idx_hit = np.where(summed_flag)[0] @@ -219,10 +219,11 @@ def update_xieta(tod, mask_di = source_flags_ds[di] bs_az = np.nanmedian(tod.boresight.az[mask_ds][mask_di]) bs_el = np.nanmedian(tod.boresight.el[mask_ds][mask_di]) + bs_roll = np.nanmedian(tod.boresight.roll[mask_ds][mask_di]) if np.any([xieta_isnan[di], np.all(mask_di==False), tod.rms[di]==0.]): xieta_dict[det] = {'xi': np.nan, 'eta': np.nan, 'xi_err': np.nan, 'eta_err': np.nan, - 'R2': np.nan, 'redchi2': np.nan, 'az': np.nan, 'el': np.nan} + 'R2': np.nan, 'redchi2': np.nan, 'az': np.nan, 'el': np.nan, 'roll': np.nan} else: ts = ts_ds[mask_di] d1_unix = np.median(ts) @@ -277,17 +278,17 @@ def update_xieta(tod, xieta_det += np.array([xi_opt, eta_opt]) xieta_dict[det] = {'xi': xieta_det[0], 'eta': xieta_det[1], 'xi_err': xi_err, 'eta_err': eta_err, - 'R2': R2, 'redchi2': redchi2, 'az' : bs_az, 'el': bs_el} + 'R2': R2, 'redchi2': redchi2, 'az' : bs_az, 'el': bs_el, 'roll': bs_roll} except RuntimeError: xieta_dict[det] = {'xi': np.nan, 'eta': np.nan, 'xi_err': np.nan, 'eta_err': np.nan, - 'R2': np.nan, 'redchi2': np.nan, 'az': np.nan, 'el': np.nan} + 'R2': np.nan, 'redchi2': np.nan, 'az': np.nan, 'el': np.nan, 'roll': np.nan} - focal_plane = metadata.ResultSet(keys=['dets:readout_id', 'xi', 'eta', 'gamma', 'xi_err', 'eta_err', 'R2', 'redchi2', 'az', 'el']) + focal_plane = metadata.ResultSet(keys=['dets:readout_id', 'xi', 'eta', 'gamma', 'xi_err', 'eta_err', 'R2', 'redchi2', 'az', 'el', 'roll']) for det in tod.dets.vals: focal_plane.rows.append((det, xieta_dict[det]['xi'], xieta_dict[det]['eta'], 0., xieta_dict[det]['xi_err'], xieta_dict[det]['eta_err'], xieta_dict[det]['R2'], xieta_dict[det]['redchi2'], - xieta_dict[det]['az'], xieta_dict[det]['el'], + xieta_dict[det]['az'], xieta_dict[det]['el'], xieta_dict[det]['roll'], )) return focal_plane @@ -401,9 +402,9 @@ def main_one_wafer_dummy(configs, obs_id, wafer_slot, restrict_dets_for_debug=Fa result_filename = f'focal_plane_{obs_id}_{wafer_slot}.hdf' fp_rset_dummy = metadata.ResultSet(keys=['dets:readout_id', 'xi', 'eta', 'gamma', - 'xi_err', 'eta_err', 'R2', 'redchi2']) + 'xi_err', 'eta_err', 'R2', 'redchi2', 'az', 'el', 'roll']) for det in meta.dets.vals: - fp_rset_dummy.rows.append((det, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan)) + fp_rset_dummy.rows.append((det, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan)) os.makedirs(result_dir, exist_ok=True) write_dataset(fp_rset_dummy, @@ -426,11 +427,14 @@ def combine_pointings(pointing_result_files): combined_dict[row['dets:readout_id']]['eta_err'] = row['eta_err'] combined_dict[row['dets:readout_id']]['R2'] = row['R2'] combined_dict[row['dets:readout_id']]['redchi2'] = row['redchi2'] + combined_dict[row['dets:readout_id']]['az'] = row['az'] + combined_dict[row['dets:readout_id']]['el'] = row['el'] + combined_dict[row['dets:readout_id']]['roll'] = row['roll'] - focal_plane = metadata.ResultSet(keys=['dets:readout_id', 'xi', 'eta', 'gamma', 'xi_err', 'eta_err', 'R2', 'redchi2']) + focal_plane = metadata.ResultSet(keys=['dets:readout_id', 'xi', 'eta', 'gamma', 'xi_err', 'eta_err', 'R2', 'redchi2', 'az', 'el', 'roll']) for det, val in combined_dict.items(): - focal_plane.rows.append((det, val['xi'], val['eta'], val['gamma'], val['xi_err'], val['eta_err'], val['R2'], val['redchi2'])) + focal_plane.rows.append((det, val['xi'], val['eta'], val['gamma'], val['xi_err'], val['eta_err'], val['R2'], val['redchi2'],val['az'], val['el'], val['roll'])) return focal_plane def main_one_obs(configs, obs_id, sso_name=None, From 5879bf3323232c6e5a3a656fb59f1749c386db7c Mon Sep 17 00:00:00 2001 From: Elle Shaw Date: Wed, 25 Mar 2026 08:46:49 -0700 Subject: [PATCH 041/132] Added ability to pass az el and roll values from get_brightsrc datasets through to the outputs of finalize focal plane. Useful for per-obs usecase, and when loaded with Receiver.load the values will be under det_boresight --- docs/site_pipeline.rst | 11 +++++-- sotodlib/coords/fp_containers.py | 33 +++++++++++++++++-- .../site_pipeline/finalize_focal_plane.py | 12 ++++--- 3 files changed, 46 insertions(+), 10 deletions(-) diff --git a/docs/site_pipeline.rst b/docs/site_pipeline.rst index ea9ea5537..89f728908 100644 --- a/docs/site_pipeline.rst +++ b/docs/site_pipeline.rst @@ -242,9 +242,10 @@ The Step 2 TOD-based analysis scripts will use the map-based results as a starti 1. Fitted xi-eta focal plane position results saved as ResultSet in ``/path/to/results/tod_based_results`` as specified in config file for Step-2. Script will append 'force_zero_roll' onto the specified results_dir - if True in config file. Load ResultSet with keyword 'focal_plane' + if True in config file. Load ResultSet with keyword 'focal_plane'. + The median boresight values from small time range the source was visible to each detector is included. - * Contents: ``ResultSet<[dets:readout_id, xi, eta, gamma, xi_err, eta_err, R2, redchi2], N rows>`` + * Contents: ``ResultSet<[dets:readout_id, xi, eta, gamma, xi_err, eta_err, R2, redchi2, az, el, roll], N rows>`` Configuration Files ``````````````````` @@ -762,6 +763,10 @@ The ``focal_plane_full`` dataset contains nine columns: - ``eta_m``: The measured eta in radians - ``gamma_m``: The measured gamma in radians. - ``weights``: The average weights of the measurements for this det. +- ``r2``: The fit weight passed in from the get_brightsrc_pointing dataset +- ``az``: The median Az value in radians from source-detector crossing +- ``el``: The median El value in radians from source-detector crossing +- ``roll``: The median Roll value in radians from source-detector crossing - ``n_point``: The number of pointing fits used for the det. - ``n_gamma``: The number of gamma fits used for this det. @@ -802,7 +807,7 @@ always be ``(1, 1, 1)`` and ``shear`` will be ``0``. ``finalize_focal_plane`` will also output a ``ManifestDb`` as a file called ``db.sqlite`` in the output directory. By default this will be indexed by ``stream_id`` and ``obs:timestamp`` and will point to the ``focal_plane`` dataset. -If you are running in ``per_obs`` mode then it wirbe indexed by ``obs_id`` and will point +If you are running in ``per_obs`` mode then it will be indexed by ``obs_id`` and will point to results associated with data observation. Be warned that in this case there will only be entries for observations with pointing fits, so design your context accordingly. diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index fb089c631..976e7e36d 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -141,6 +141,7 @@ class FocalPlane: 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) @@ -219,6 +220,7 @@ def empty(cls, template, stream_id, wafer_slot, n_aman, config=""): 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() @@ -232,6 +234,7 @@ def empty(cls, template, stream_id, wafer_slot, n_aman, config=""): template.id_strs, avg_fp, weight, + det_boresight, transformed, center, center_transformed, @@ -260,8 +263,17 @@ def map_by_det_id(self, aman): xi = aman.pointing.xi[msk][srt][mapping] eta = aman.pointing.eta[msk][srt][mapping] r2 = np.nan + np.zeros_like(eta) + az = np.nan + np.zeros_like(eta) + el = np.nan + np.zeros_like(eta) + roll = np.nan + np.zeros_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] @@ -270,14 +282,16 @@ def map_by_det_id(self, aman): else: gamma = np.full(len(xi), np.nan) fp = np.column_stack((xi, eta, gamma)) - return fp, r2, template_msk + det_boresight = np.column_stack((az, el, roll)) + return fp, r2, det_boresight, template_msk - def add_fp(self, i, fp, weights, template_msk): - if self.full_fp is None or self.tot_weight is None: + 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 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) @@ -323,6 +337,9 @@ def save(self, f, db_info, group): ("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), ] @@ -333,6 +350,7 @@ def save(self, f, db_info, group): *(self.transformed.T), *(self.avg_fp.T), *(self.weights.T), + *(self.det_boresight.T), self.n_point, self.n_gamma, ), @@ -378,6 +396,14 @@ def load(cls, group, include_cm=None): np.array(fp_full["gamma_m"]), ) ) + + det_boresight = np.column_stack( + ( + np.array(fp_full["az"]), + np.array(fp_full["el"]), + np.array(fp_full["roll"]), + ) + ) # For backwards compatibility weights = np.array(fp_full["weights"]) if "r2" in fp_full.keys: @@ -424,6 +450,7 @@ def load(cls, group, include_cm=None): np.array(id_strs), avg_fp, np.array(weights), + det_boresight, transformed, center, center_transformed, diff --git a/sotodlib/site_pipeline/finalize_focal_plane.py b/sotodlib/site_pipeline/finalize_focal_plane.py index fe19a6e97..8df8a9c59 100644 --- a/sotodlib/site_pipeline/finalize_focal_plane.py +++ b/sotodlib/site_pipeline/finalize_focal_plane.py @@ -6,6 +6,10 @@ from importlib import import_module from typing import List, Optional +import matplotlib +matplotlib.use('Agg') +import matplotlib.pyplot as plt + import git import h5py import megham.transform as mt @@ -399,7 +403,7 @@ def _mk_pointing_config(telescope_flavor, tube_slot, wafer_slot, config): def _restrict_inliers(aman, focal_plane): # TODO: Use gamma as well # Map to template - fp, _, template_msk = focal_plane.map_by_det_id(aman) + fp, _, _, template_msk = focal_plane.map_by_det_id(aman) fp = fp[:, :2] inliers = np.ones(len(fp), dtype=bool) @@ -651,7 +655,7 @@ def main(): plot_dir = os.path.join(plot_dir_base, str(config["start_time"])) os.makedirs(plot_dir, exist_ok=True) logger.info("Working on batch containing: %s", str(obs_ids)) - + # Setup db and Receiver db, base, group = _create_db( dbpath, @@ -771,7 +775,7 @@ def main(): _restrict_inliers(aman, focal_plane) # Mapping to template - fp, r2, template_msk = focal_plane.map_by_det_id(aman) + fp, r2, det_boresight, template_msk = focal_plane.map_by_det_id(aman) focal_plane.template.add_wafer_info(aman, template_msk) # Try an initial alignment and get weights @@ -808,7 +812,7 @@ def main(): # Store weighted values weights = np.column_stack((weights, r2)) - focal_plane.add_fp(i, fp, weights, template_msk) + focal_plane.add_fp(i, fp, weights, det_boresight, template_msk) n_obs += 1 From 3dbb7edaf4cb6100898f230994ab95476d0e0096 Mon Sep 17 00:00:00 2001 From: Elle Shaw Date: Thu, 26 Mar 2026 15:46:02 -0700 Subject: [PATCH 042/132] Pre-fill detector pointing with central values from obs_info if per detector pointing not included in inputs --- sotodlib/coords/fp_containers.py | 6 +++--- sotodlib/site_pipeline/finalize_focal_plane.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 976e7e36d..3e8a4ab92 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -263,9 +263,9 @@ def map_by_det_id(self, aman): xi = aman.pointing.xi[msk][srt][mapping] eta = aman.pointing.eta[msk][srt][mapping] r2 = np.nan + np.zeros_like(eta) - az = np.nan + np.zeros_like(eta) - el = np.nan + np.zeros_like(eta) - roll = 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: diff --git a/sotodlib/site_pipeline/finalize_focal_plane.py b/sotodlib/site_pipeline/finalize_focal_plane.py index 8b8f0d826..0a0209cfb 100644 --- a/sotodlib/site_pipeline/finalize_focal_plane.py +++ b/sotodlib/site_pipeline/finalize_focal_plane.py @@ -663,7 +663,7 @@ def main(): plot_dir = os.path.join(plot_dir_base, str(config["start_time"])) os.makedirs(plot_dir, exist_ok=True) logger.info("Working on batch containing: %s", str(obs_ids)) - + # Setup db and Receiver db, base, group = _create_db( dbpath, From 2bf265f04368dd298367ffd8aac62a183f537fe1 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Wed, 1 Apr 2026 18:45:10 -0400 Subject: [PATCH 043/132] feat: barebones epochs system implementation --- sotodlib/utils/epochs.py | 216 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 216 insertions(+) create mode 100644 sotodlib/utils/epochs.py diff --git a/sotodlib/utils/epochs.py b/sotodlib/utils/epochs.py new file mode 100644 index 000000000..78c6b3566 --- /dev/null +++ b/sotodlib/utils/epochs.py @@ -0,0 +1,216 @@ +from copy import deepcopy +from dataclasses import dataclass, field +from itertools import accumulate +from operator import add, mul +from typing import Any, Self + +import yaml +from deepdiff import DeepDiff + + +@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: + + * `|`: naive addition, combines `tags` and `data` and simply returns the most inclusive time range + * `+`: same as `|` but will error if time ranges are not overlapping + * `&`: same as `|` but will error if `tags` or `data` are not the same + * `*`: same as `+` but will error if `data` is not the same + * `@`: same as `*` but will error if `tags` is not the same + + 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 __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 combine( + self: Self, + tocombine: Self, + in_place: bool = True, + time_check: bool = False, + tag_check: bool = False, + data_check: 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 time_check and (self.start > tocombine.stop or self.stop < tocombine.start): + raise ValueError( + "Can't combine without overlapping time ranges with time_check=True" + ) + combined.start = min(self.start, tocombine.start) + combined.stop = max(self.stop, tocombine.stop) + + if tag_check and self.tags != tocombine.tags: + raise ValueError("Can't combine without identical tags with tag_check=True") + combined.tags = self.tags.union(tocombine.tags) + + diff = DeepDiff(self.data, self.data) + if data_check and len(diff) != 0: + raise ValueError( + "Can't combine without identical data with data_check=True" + ) + combined.data.update(tocombine.data) + + 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 __add__(self, tocombine) -> Self: + return self.combine(tocombine, False, True, False, False) + + def __iadd__(self, tocombine) -> Self: + return self.combine(tocombine, True, True, False, False) + + def __and__(self, tocombine) -> Self: + return self.combine(tocombine, False, False, True, True) + + def __iand__(self, tocombine) -> Self: + return self.combine(tocombine, True, False, True, True) + + def __mul__(self, tocombine) -> Self: + return self.combine(tocombine, False, True, False, True) + + def __imul__(self, tocombine) -> Self: + return self.combine(tocombine, True, True, False, 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: + name: str + covers: tuple[Interval] + strict: bool + _internal: Interval = field(init=False) + + def __post_init__(self): + self._internal = accumulate(self.covers, mul if self.strict else add) + + def __setattr__(self, name, value): + if name == "covers" or name == "strict": + self.__post_init__() + return super().__setattr__(name, value) + + +@dataclass +class Era: + name: str + epochs: tuple[Epoch] + strict: bool + _internal: Interval = field(init=False) + + def __post_init__(self): + self._internal = accumulate( + [e._internal for e in self.epochs], mul if self.strict else add + ) + + def __setattr__(self, name, value): + if name == "covers" or name == "strict": + self.__post_init__() + return super().__setattr__(name, value) + + +@dataclass +class Calendar: + intervals: dict[str, Interval] + eras: dict[str, Era] + data: dict[str, dict[str, Any]] + + @classmethod + def load(cls, fpath: str): + with open(fpath, "r") as f: + cfg = yaml.safe_load(f) + 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: + if key == "intervals": + continue + if key[0] == "_": + data[key[1:]] = val + 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]] + interval_dict[name] = Interval( + name, + interval.get("start", 0), + interval.get("stop", 20000000000), + interval.get("tags", []), + interval_data, + ) + + # Load epochs + for ename, era in eras.items(): + strict = era.get("strict", True) + epochs = [] + for name, ec in era.items(): + covers = [] + for cname in ec.get("covers", []): + iname, slstr = cname.split("[") + slstr = slstr[:-1] + ival = intervals[iname] + slc = slice( + *map( + lambda x: float(x.strip()) if x.strip() else None, + slstr.split(":"), + ) + ) + covers += [ival[slc]] + epochs[name] = Epoch(name, tuple(covers), strict) + eras[ename] = Era(ename, tuple(epochs), strict) + + return Calendar(interval_dict, eras, data) From 139dc0d5b5cf12976129ba7cebeb21f977667230 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Wed, 1 Apr 2026 18:53:38 -0400 Subject: [PATCH 044/132] fix: adjust era strictness --- sotodlib/utils/epochs.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sotodlib/utils/epochs.py b/sotodlib/utils/epochs.py index 78c6b3566..94263005a 100644 --- a/sotodlib/utils/epochs.py +++ b/sotodlib/utils/epochs.py @@ -1,7 +1,7 @@ from copy import deepcopy from dataclasses import dataclass, field from itertools import accumulate -from operator import add, mul +from operator import add, mul, or_ from typing import Any, Self import yaml @@ -143,7 +143,7 @@ class Era: def __post_init__(self): self._internal = accumulate( - [e._internal for e in self.epochs], mul if self.strict else add + [e._internal for e in self.epochs], add if self.strict else or_ ) def __setattr__(self, name, value): From 6c471af97368f36ae6d80788cb580cb29944e05f Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Wed, 1 Apr 2026 18:56:45 -0400 Subject: [PATCH 045/132] fix: cast output of accumulate --- sotodlib/utils/epochs.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/sotodlib/utils/epochs.py b/sotodlib/utils/epochs.py index 94263005a..6ccef79f9 100644 --- a/sotodlib/utils/epochs.py +++ b/sotodlib/utils/epochs.py @@ -2,7 +2,7 @@ from dataclasses import dataclass, field from itertools import accumulate from operator import add, mul, or_ -from typing import Any, Self +from typing import Any, Self, cast import yaml from deepdiff import DeepDiff @@ -126,7 +126,9 @@ class Epoch: _internal: Interval = field(init=False) def __post_init__(self): - self._internal = accumulate(self.covers, mul if self.strict else add) + self._internal = cast( + Interval, accumulate(self.covers, mul if self.strict else add) + ) def __setattr__(self, name, value): if name == "covers" or name == "strict": @@ -142,8 +144,9 @@ class Era: _internal: Interval = field(init=False) def __post_init__(self): - self._internal = accumulate( - [e._internal for e in self.epochs], add if self.strict else or_ + self._internal = cast( + Interval, + accumulate([e._internal for e in self.epochs], add if self.strict else or_), ) def __setattr__(self, name, value): From 4fae6dc116b9ea6af5b72822b23e43475e565c52 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Wed, 1 Apr 2026 19:05:02 -0400 Subject: [PATCH 046/132] fix: correct variable name in era post init --- sotodlib/utils/epochs.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sotodlib/utils/epochs.py b/sotodlib/utils/epochs.py index 6ccef79f9..d0293b08a 100644 --- a/sotodlib/utils/epochs.py +++ b/sotodlib/utils/epochs.py @@ -150,7 +150,7 @@ def __post_init__(self): ) def __setattr__(self, name, value): - if name == "covers" or name == "strict": + if name == "epochs" or name == "strict": self.__post_init__() return super().__setattr__(name, value) From 852e2143ade3e94074c0867cd5727dbbed8f9636 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Thu, 2 Apr 2026 14:20:12 -0400 Subject: [PATCH 047/132] feat: better strictness system --- sotodlib/utils/epochs.py | 116 +++++++++++++++++++++++++++++---------- 1 file changed, 88 insertions(+), 28 deletions(-) diff --git a/sotodlib/utils/epochs.py b/sotodlib/utils/epochs.py index d0293b08a..11c73da2b 100644 --- a/sotodlib/utils/epochs.py +++ b/sotodlib/utils/epochs.py @@ -1,12 +1,16 @@ from copy import deepcopy from dataclasses import dataclass, field from itertools import accumulate -from operator import add, mul, or_ +from operator import add, and_, mul, or_ from typing import Any, Self, cast import yaml from deepdiff import DeepDiff +# TODO: Add check for a specific piece of data -> existance and strictness +# TODO: Add method to search via tags +# TODO: Make Invtervals aware of what Epochs they are members of and make Epochs aware of what Eras they are members of + @dataclass class Interval: @@ -18,11 +22,14 @@ class Interval: Two `Interval` instances can be combined with the following operators, all operators are functionally addition but with differing checks: - * `|`: naive addition, combines `tags` and `data` and simply returns the most inclusive time range - * `+`: same as `|` but will error if time ranges are not overlapping - * `&`: same as `|` but will error if `tags` or `data` are not the same - * `*`: same as `+` but will error if `data` is not the same - * `@`: same as `*` but will error if `tags` is not the same + * `|`: Allow gaps between intervals, but data and tags can differ + * `&`: Intervals must be overlapping, but data and tags can differ + * `*`: Allow gaps between intervals, data must be the same but tags can differ + * `+`: Invervals must be overlapping, data must be the same but tags can differ + * `/`: Allow gaps between intervals, data can differ but tags must be the same + * `-`: Invervals must be overlapping, data can differ but tags must be the same + * `**`: Allow gaps between invervals, data and tags must be the same + * `@`: Allow gaps between intervals, data and tags must be the same 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. @@ -56,9 +63,9 @@ def combine( self: Self, tocombine: Self, in_place: bool = True, - time_check: bool = False, - tag_check: bool = False, - data_check: bool = False, + allow_gap: bool = False, + same_data: bool = False, + same_tag: bool = False, ) -> Self: if not isinstance(tocombine, Interval): raise TypeError( @@ -67,21 +74,23 @@ def combine( combined = self if in_place: combined = deepcopy(self) - if time_check and (self.start > tocombine.stop or self.stop < tocombine.start): + if not allow_gap and ( + self.start > tocombine.stop or self.stop < tocombine.start + ): raise ValueError( - "Can't combine without overlapping time ranges with time_check=True" + "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 tag_check and self.tags != tocombine.tags: - raise ValueError("Can't combine without identical tags with tag_check=True") + if not same_tag and self.tags != tocombine.tags: + raise ValueError("Can't combine without identical tags with same_tag=False") combined.tags = self.tags.union(tocombine.tags) diff = DeepDiff(self.data, self.data) - if data_check and len(diff) != 0: + if not same_data and len(diff) != 0: raise ValueError( - "Can't combine without identical data with data_check=True" + "Can't combine without identical data with same_data=False" ) combined.data.update(tocombine.data) @@ -93,24 +102,42 @@ def __or__(self, tocombine) -> Self: def __ior__(self, tocombine) -> Self: return self.combine(tocombine, True, False, False, False) - def __add__(self, tocombine) -> Self: + def __and__(self, tocombine) -> Self: return self.combine(tocombine, False, True, False, False) - def __iadd__(self, tocombine) -> Self: + def __iand__(self, tocombine) -> Self: return self.combine(tocombine, True, True, False, False) - def __and__(self, tocombine) -> Self: - return self.combine(tocombine, False, False, True, True) + def __mul__(self, tocombine) -> Self: + return self.combine(tocombine, False, False, True, False) - def __iand__(self, tocombine) -> Self: - return self.combine(tocombine, True, False, True, True) + def __imul__(self, tocombine) -> Self: + return self.combine(tocombine, True, False, True, False) - def __mul__(self, tocombine) -> Self: + 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 __div__(self, tocombine) -> Self: + return self.combine(tocombine, False, False, False, True) + + def __idiv__(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 __imul__(self, tocombine) -> Self: + def __isub__(self, tocombine) -> Self: return self.combine(tocombine, True, True, False, True) + def __pow__(self, tocombine) -> Self: + return self.combine(tocombine, False, False, False, True) + + def __ipow__(self, tocombine) -> Self: + return self.combine(tocombine, True, False, False, True) + def __matmul__(self, tocombine) -> Self: return self.combine(tocombine, False, True, True, True) @@ -120,6 +147,21 @@ def __imatmul__(self, tocombine) -> Self: @dataclass class Epoch: + """ + Dataclass for storing a collection of `Invervals`s. + `Inverval`s must be overlapping. + + Attributes + ---------- + name : str + Name for this epoch. + covers: tuple[Interval] + Collections of overlapping `Invervals` that make up an `Epoch`. + strict : bool + If `True` than in addition to being overlapping the `Intervals` must + also contain the same data. + """ + name: str covers: tuple[Interval] strict: bool @@ -127,7 +169,7 @@ class Epoch: def __post_init__(self): self._internal = cast( - Interval, accumulate(self.covers, mul if self.strict else add) + Interval, accumulate(self.covers, mul if self.strict else or_) ) def __setattr__(self, name, value): @@ -138,6 +180,21 @@ def __setattr__(self, name, value): @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`. + strict : bool + If `True` than in addition to being non-overlapping the `Epochs` must + also contain the same data. + """ + name: str epochs: tuple[Epoch] strict: bool @@ -146,7 +203,9 @@ class Era: def __post_init__(self): self._internal = cast( Interval, - accumulate([e._internal for e in self.epochs], add if self.strict else or_), + accumulate( + [e._internal for e in self.epochs], add if self.strict else and_ + ), ) def __setattr__(self, name, value): @@ -198,7 +257,8 @@ def load(cls, fpath: str): # Load epochs for ename, era in eras.items(): - strict = era.get("strict", True) + strict_era = era.get("strict_era", False) + strict_epoch = era.get("strict_epochs", True) epochs = [] for name, ec in era.items(): covers = [] @@ -213,7 +273,7 @@ def load(cls, fpath: str): ) ) covers += [ival[slc]] - epochs[name] = Epoch(name, tuple(covers), strict) - eras[ename] = Era(ename, tuple(epochs), strict) + epochs[name] = Epoch(name, tuple(covers), strict_epoch) + eras[ename] = Era(ename, tuple(epochs), strict_era) return Calendar(interval_dict, eras, data) From ca89a2c1d7b276036f7230cd7d76b34028afde63 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Fri, 3 Apr 2026 16:28:39 -0400 Subject: [PATCH 048/132] feat: add tools in calendar to modify eras and epochs and check membership of an interval --- sotodlib/utils/epochs.py | 203 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 194 insertions(+), 9 deletions(-) diff --git a/sotodlib/utils/epochs.py b/sotodlib/utils/epochs.py index 11c73da2b..f53a2f3ba 100644 --- a/sotodlib/utils/epochs.py +++ b/sotodlib/utils/epochs.py @@ -1,15 +1,15 @@ +import re from copy import deepcopy from dataclasses import dataclass, field from itertools import accumulate from operator import add, and_, mul, or_ -from typing import Any, Self, cast +from typing import Any, Optional, Self, cast import yaml from deepdiff import DeepDiff # TODO: Add check for a specific piece of data -> existance and strictness # TODO: Add method to search via tags -# TODO: Make Invtervals aware of what Epochs they are members of and make Epochs aware of what Eras they are members of @dataclass @@ -41,6 +41,9 @@ class Interval: 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): @@ -59,6 +62,14 @@ def __getitem__(self: Self, val) -> Self: 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, @@ -87,13 +98,15 @@ def combine( raise ValueError("Can't combine without identical tags with same_tag=False") combined.tags = self.tags.union(tocombine.tags) - diff = DeepDiff(self.data, self.data) + diff = DeepDiff(self.data, tocombine.data) if not same_data and len(diff) != 0: raise ValueError( "Can't combine without identical data with same_data=False" ) combined.data.update(tocombine.data) + combined.name = self.name + "+" + tocombine.name + return combined def __or__(self, tocombine) -> Self: @@ -155,6 +168,8 @@ class Epoch: ---------- 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`. strict : bool @@ -163,7 +178,8 @@ class Epoch: """ name: str - covers: tuple[Interval] + era_name: str + covers: tuple[Interval, ...] strict: bool _internal: Interval = field(init=False) @@ -172,11 +188,25 @@ def __post_init__(self): Interval, accumulate(self.covers, mul if self.strict else or_) ) + def __repr__(self) -> str: + return ( + self.name + + "(" + + ",".join([str(ival) for ival in self.covers]) + + ")" + + ("*" * self.strict) + ) + def __setattr__(self, name, value): if name == "covers" or name == "strict": self.__post_init__() return super().__setattr__(name, value) + def __eq__(self, other): + if not isinstance(other, Epoch): + return False + return str(self) == str(other) + @dataclass class Era: @@ -196,7 +226,7 @@ class Era: """ name: str - epochs: tuple[Epoch] + epochs: tuple[Epoch, ...] strict: bool _internal: Interval = field(init=False) @@ -216,12 +246,162 @@ def __setattr__(self, name, value): @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] + + 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 and era set `epoch` to `None`. + """ + 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): + def load(cls, fpath: str) -> Self: with open(fpath, "r") as f: cfg = yaml.safe_load(f) if "intervals" not in cfg: @@ -247,15 +427,17 @@ def load(cls, fpath: str): if len(val) != 2: raise ValueError("Data must have format X.Y") interval_data[key] = data[val[0]][val[1]] - interval_dict[name] = Interval( + ival = Interval( name, interval.get("start", 0), interval.get("stop", 20000000000), interval.get("tags", []), interval_data, ) + interval_dict[str(ival)] = ival # Load epochs + epoch_dict = {} for ename, era in eras.items(): strict_era = era.get("strict_era", False) strict_epoch = era.get("strict_epochs", True) @@ -266,6 +448,7 @@ def load(cls, fpath: str): iname, slstr = cname.split("[") slstr = slstr[:-1] ival = intervals[iname] + interval_dict[str(ival)] = ival slc = slice( *map( lambda x: float(x.strip()) if x.strip() else None, @@ -273,7 +456,9 @@ def load(cls, fpath: str): ) ) covers += [ival[slc]] - epochs[name] = Epoch(name, tuple(covers), strict_epoch) + epoch = Epoch(name, ename, tuple(covers), strict_epoch) + epochs += [epoch] + epoch_dict[f"{ename}.{name}"] = epoch eras[ename] = Era(ename, tuple(epochs), strict_era) - return Calendar(interval_dict, eras, data) + return cls(interval_dict, epoch_dict, eras, data, []) From 58875d66cd3154202f42201de922825a42c62e10 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Mon, 6 Apr 2026 13:16:43 -0400 Subject: [PATCH 049/132] feat: add functions to check on data presence --- sotodlib/utils/epochs.py | 109 +++++++++++++++++++++++++++++++++++---- 1 file changed, 100 insertions(+), 9 deletions(-) diff --git a/sotodlib/utils/epochs.py b/sotodlib/utils/epochs.py index f53a2f3ba..11d9c7a79 100644 --- a/sotodlib/utils/epochs.py +++ b/sotodlib/utils/epochs.py @@ -3,12 +3,11 @@ from dataclasses import dataclass, field from itertools import accumulate from operator import add, and_, mul, or_ -from typing import Any, Optional, Self, cast +from typing import Any, Literal, Optional, Self, cast, overload import yaml from deepdiff import DeepDiff -# TODO: Add check for a specific piece of data -> existance and strictness # TODO: Add method to search via tags @@ -22,12 +21,12 @@ class Interval: Two `Interval` instances can be combined with the following operators, all operators are functionally addition but with differing checks: - * `|`: Allow gaps between intervals, but data and tags can differ - * `&`: Intervals must be overlapping, but data and tags can differ - * `*`: Allow gaps between intervals, data must be the same but tags can differ - * `+`: Invervals must be overlapping, data must be the same but tags can differ - * `/`: Allow gaps between intervals, data can differ but tags must be the same - * `-`: Invervals must be overlapping, data can differ but tags must be the same + * `|`: Intervals must be overlapping, but data and tags can differ + * `&`: Allow gaps between intervals, but data and tags can differ + * `*`: Invervals must be overlapping, data must be the same but tags can differ + * `+`: Allow gaps between intervals, data must be the same but tags can differ + * `/`: Invervals must be overlapping, data can differ but tags must be the same + * `-`: Allow gaps between intervals, data can differ but tags must be the same * `**`: Allow gaps between invervals, data and tags must be the same * `@`: Allow gaps between intervals, data and tags must be the same @@ -207,6 +206,33 @@ def __eq__(self, other): 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 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 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 = self if self.strict else deepcopy(self) + try: + tester.strict = True + except ValueError: + return False + return True + return cast( + bool, accumulate([field in ival.data for ival in self.covers], and_) + ) + @dataclass class Era: @@ -243,6 +269,24 @@ def __setattr__(self, name, value): 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, accumulate([e.check_data(field, strict) for e in self.epochs], and_) + ) + @dataclass class Calendar: @@ -258,6 +302,52 @@ class Calendar: data: dict[str, dict[str, Any]] orphan_epochs: list[Epoch] + @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 ): @@ -272,7 +362,8 @@ def change_strictness( The name of the era to modify. epoch : Optional, default: None The name of epoch to modify. - To modify and era set `epoch` to `None`. + 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 From bc34b53dc713640a488891b9fba8f0a9a3f462fa Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Mon, 6 Apr 2026 14:47:18 -0400 Subject: [PATCH 050/132] feat: add tag search --- sotodlib/utils/epochs.py | 48 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 45 insertions(+), 3 deletions(-) diff --git a/sotodlib/utils/epochs.py b/sotodlib/utils/epochs.py index 11d9c7a79..4ea0590b7 100644 --- a/sotodlib/utils/epochs.py +++ b/sotodlib/utils/epochs.py @@ -8,9 +8,6 @@ import yaml from deepdiff import DeepDiff -# TODO: Add method to search via tags - - @dataclass class Interval: """ @@ -302,6 +299,51 @@ class Calendar: 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 field in ival.tags] + elif search_in == "epochs": + return [ + epoch for epoch in self.epochs.values() if field in epoch._internal.tags + ] + elif search_in == "eras": + return [era for era in self.eras.values() if field 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]: ... From a77a99b725280248767f146ec8bcde3e0a781ed3 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Fri, 10 Apr 2026 15:48:14 -0400 Subject: [PATCH 051/132] fix: switch to reduce --- sotodlib/utils/epochs.py | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/sotodlib/utils/epochs.py b/sotodlib/utils/epochs.py index 4ea0590b7..0d3771f7f 100644 --- a/sotodlib/utils/epochs.py +++ b/sotodlib/utils/epochs.py @@ -1,13 +1,14 @@ import re from copy import deepcopy from dataclasses import dataclass, field -from itertools import accumulate +from functools import reduce from operator import add, and_, mul, or_ from typing import Any, Literal, Optional, Self, cast, overload import yaml from deepdiff import DeepDiff + @dataclass class Interval: """ @@ -181,7 +182,7 @@ class Epoch: def __post_init__(self): self._internal = cast( - Interval, accumulate(self.covers, mul if self.strict else or_) + Interval, reduce(mul if self.strict else or_, self.covers) ) def __repr__(self) -> str: @@ -226,9 +227,7 @@ def check_data(self, field: str, strict: bool = True) -> bool: except ValueError: return False return True - return cast( - bool, accumulate([field in ival.data for ival in self.covers], and_) - ) + return cast(bool, reduce(and_, [field in ival.data for ival in self.covers])) @dataclass @@ -256,9 +255,7 @@ class Era: def __post_init__(self): self._internal = cast( Interval, - accumulate( - [e._internal for e in self.epochs], add if self.strict else and_ - ), + reduce(add if self.strict else and_, [e._internal for e in self.epochs]), ) def __setattr__(self, name, value): @@ -281,7 +278,7 @@ def check_data(self, field: str, strict: bool = True) -> bool: """ return cast( - bool, accumulate([e.check_data(field, strict) for e in self.epochs], and_) + bool, reduce(and_, [e.check_data(field, strict) for e in self.epochs]) ) @@ -308,9 +305,7 @@ 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"]) -> list[Interval]: ... def find_tagged( From c6f3612c62e90eb4281888e7e3bb0fd604f96c67 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Tue, 14 Apr 2026 13:45:40 -0400 Subject: [PATCH 052/132] Lat pmchanges (#1605) * feat: lat v2 pointing model * Update sotodlib/coords/pointing_model.py Co-authored-by: Matthew Hasselfield * Update sotodlib/coords/pointing_model.py Co-authored-by: Matthew Hasselfield * feat: quiver plot * fix: use correct roll * fix: remove unused lines * feat: add option for optics tubes to float and moved some fitter options to config file * fix: dont run second iteration if there are no cut points and fix missing comma * fix: apply ot offsets when plotting * fix: use same xieta_mode when making final plots and save ot offsets seperately --------- Co-authored-by: Matthew Hasselfield --- .../site_pipeline/solve_pointing_model.py | 168 +++++++++++++++--- 1 file changed, 144 insertions(+), 24 deletions(-) diff --git a/sotodlib/site_pipeline/solve_pointing_model.py b/sotodlib/site_pipeline/solve_pointing_model.py index 946ceb5ab..378c64041 100644 --- a/sotodlib/site_pipeline/solve_pointing_model.py +++ b/sotodlib/site_pipeline/solve_pointing_model.py @@ -66,6 +66,7 @@ def load_per_obs_data(config, t0, tf): 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] @@ -73,16 +74,18 @@ def load_per_obs_data(config, t0, tf): 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) - obs_index.append(np.repeat(i, 7)) + 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.concatenate(obs_index) + obs_index = np.array(obs_index) + ot_list = np.array(ot_list) #obs_index[initial_weights_mask] = np.nan - return filelist, obs_ufm_centers, weights_ufm, obs_index + return filelist, obs_ufm_centers, weights_ufm, obs_index, ot_list def load_nom_focal_plane_full(config, ufm): which_template = config.get("use_as_template", "ffp") @@ -161,7 +164,7 @@ def load_per_detector_data(config, t0, tf, no_downsample_set=False, return_all_d if config.get("use_these_files") is not None: filelist = [filelist[i] for i in config.get("use_these_files")] - weights_dets, obs_dets_fits, stream_id_list, obs_index = [], [], [], [] + weights_dets, obs_dets_fits, stream_id_list, ot_list, obs_index = [], [], [], [], [] #which_ufm = config.get("which_ufm", None) which_data = config.get("use_as_data") which_weights = config.get("use_as_weights", None) @@ -177,12 +180,14 @@ def load_per_detector_data(config, t0, tf, no_downsample_set=False, return_all_d weights_dets.append(weights) obs_dets_fits.append(data) obs_index.append(np.repeat(i, len(ufm.weights))) + ot_list.append([this_OT.name] * len(data)) nom_data = [load_nom_focal_plane_full(config, s) for s in stream_id_list] all_det_ids, all_nom_det_array = map(np.concatenate, zip(*nom_data)) weights_dets = np.concatenate(weights_dets) obs_dets_fits = np.concatenate(obs_dets_fits, axis=0) obs_index = np.concatenate(obs_index) + ot_list = np.concatenate(ot_list) weights_dets[weights_dets < config.get("weight_cutoff")] = 0.0 obs_dets_fits[np.where(weights_dets == 0)] = np.nan @@ -197,6 +202,7 @@ def load_per_detector_data(config, t0, tf, no_downsample_set=False, return_all_d all_nom_det_array[mask], all_det_ids[mask], obs_index[mask], + ot_list[mask], ) else: @@ -209,6 +215,7 @@ def load_per_detector_data(config, t0, tf, no_downsample_set=False, return_all_d all_nom_det_array = all_nom_det_array[mask] all_det_ids = all_det_ids[mask] obs_index = obs_index[mask] + ot_list = ot_list[mask] if even_obs_size: mask = create_size_mask(obs_index) obs_dets_fits = obs_dets_fits[mask] @@ -216,6 +223,7 @@ def load_per_detector_data(config, t0, tf, no_downsample_set=False, return_all_d all_nom_det_array = all_nom_det_array[mask] all_det_ids = all_det_ids[mask] obs_index = obs_index[mask] + ot_list = ot_list[mask] if cull_dets is not None: for _ in range(2 if cull_twice else 1): mask = create_culling_mask(obs_index, cull_dets) @@ -224,13 +232,15 @@ def load_per_detector_data(config, t0, tf, no_downsample_set=False, return_all_d all_nom_det_array = all_nom_det_array[mask] all_det_ids = all_det_ids[mask] obs_index = obs_index[mask] + ot_list = ot_list[mask] return ( filelist, obs_dets_fits, weights_dets, all_nom_det_array, all_det_ids, - obs_index + obs_index, + ot_list, ) def load_obs_boresight(config, filelist): @@ -286,14 +296,26 @@ 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) # Add independant params orig_pars = np.array(list(init_params.keys())) par_list = orig_pars.copy() + added_ots = [] for epoch in epochs: indep_list = epoch["indep_list"] + if float_ots: + for ot in np.unique(epoch["solver_aman"].ot_list): + ot_float_pars = [f"{n}_{ot}" for n in ["xioff", "etaoff", "rot", "xiscale", "etascale"]] + indep_list += ot_float_pars + if ot not in added_ots: + orig_pars = np.concatenate((orig_pars, ot_float_pars)) + par_list = np.concatenate((par_list, ot_float_pars)) + for p, d in zip(ot_float_pars, [0, 0, 0, 1, 1]): + init_params[p] = d + added_ots += [ot] 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] @@ -324,6 +346,32 @@ def _init_fit_params(config, epochs): 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 + # We are recomputing information that should just be cached here... + # TODO: Fix that + ot_float_pars = ["xioff", "etaoff", "rot", "xiscale", "etascale"] + ot_float_defaults = np.array([0, 0, 0, 1, 1]) + for ot in np.unique(solver_aman.ot_list): + ot_pars = [params.get(f"{n}_{ot}", d) for n, d in zip(ot_float_pars, ot_float_defaults)] + if np.array_equal(ot_pars, ot_float_defaults): + continue + msk = (solver_aman.ot_list == ot) + 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.mean(xi_mod[msk]) + eta_cent = np.mean(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 ): @@ -333,6 +381,9 @@ def objective_model_func_lmfit( 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 + + 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) #print(np.nansum(dist)) weights_array = solver_aman.weights if weights else np.ones(len(dist)) @@ -343,6 +394,7 @@ def objective_model_func_lmfit_joint( ): params = params.valuesdict() chisq = 0 + t1 = time.time() for epoch in epochs: chisq += objective_model_func_lmfit({par.split(f"_{epoch['name']}")[0]:params[par] for par in epoch["params"]}, pm_version, epoch["solver_aman"], xieta_model, weights) return chisq @@ -429,7 +481,8 @@ def apply_model_params(xieta_model, pointing_model, pm_version, aman, use_inds=N 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 @@ -446,7 +499,7 @@ def analyze_PM_with_all_dets(config, t0, tf, params): (filelist, obs_dets_fits, weights_dets, all_nom_det_array, - all_det_ids, obs_index, + all_det_ids, obs_index, ot_list ) = load_per_detector_data(config, t0, tf, return_all_dets=True) ancil, roll_c = load_obs_boresight_per_detector(config, filelist, obs_index) @@ -469,6 +522,7 @@ def analyze_PM_with_all_dets(config, t0, tf, params): ) full_aman.wrap("weights", weights_dets, [(0, "samps")]) full_aman.wrap("obs_index", obs_index) + full_aman.wrap("ot_list", ot_list) full_aman.wrap("roll_c", roll_c, [(0, "samps")]) full_aman.wrap("det_ids", all_det_ids, [(0, "samps")]) full_aman.wrap("radial", @@ -482,15 +536,25 @@ def analyze_PM_with_all_dets(config, t0, tf, params): np.array([ufm_list.index(d) for d in full_aman.det_ufm]), [(0, "samps")]) # Apply model to data. + xieta_model = config.get("xieta_model", "measured") (full_modeled, full_residuals, rms, _ - ) = apply_model_params("template", + ) = apply_model_params(xieta_model, params, config.get("pm_version"), full_aman) + 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) del(full_modeled) del(full_residuals) @@ -508,13 +572,13 @@ def analyze_PM_with_all_dets(config, t0, tf, params): obs_roll.append(np.nanmedian(full_aman.roll_c[inds])) obs_resid.append(np.nanmean(full_aman.fit_residuals[inds])) obs_dxi.append(np.nanmean((full_aman.full_modeled[0] - - full_aman.nominal_xieta_locs[0])[inds]/DEG*60)) + full_aman[to_comp][0])[inds]/DEG*60)) obs_deta.append(np.nanmean((full_aman.full_modeled[1] - - full_aman.nominal_xieta_locs[1])[inds]/DEG*60)) + full_aman[to_comp][1])[inds]/DEG*60)) obs_std_xi.append(np.nanstd((full_aman.full_modeled[0] - - full_aman.nominal_xieta_locs[0])[inds]/DEG*60)) + full_aman[to_comp][0])[inds]/DEG*60)) obs_std_eta.append(np.nanstd((full_aman.full_modeled[1] - - full_aman.nominal_xieta_locs[1])[inds]/DEG*60)) + full_aman[to_comp][1])[inds]/DEG*60)) (ufm_az, ufm_el, ufm_roll, ufm_resid, ufm_dxi, ufm_deta, ufm_std_xi, ufm_std_eta, ufm_wafer_num @@ -526,16 +590,16 @@ def analyze_PM_with_all_dets(config, t0, tf, params): ufm_roll.append(np.nanmedian(full_aman.roll_c[inds][ufm_inds])) ufm_resid.append(np.nanmean(full_aman.fit_residuals[inds][ufm_inds])) ufm_dxi.append(np.nanmean((full_aman.full_modeled[0] - - full_aman.nominal_xieta_locs[0])[inds][ufm_inds]/DEG*60)) + full_aman[to_comp][0])[inds][ufm_inds]/DEG*60)) ufm_deta.append(np.nanmean( (full_aman.full_modeled[1] - - full_aman.nominal_xieta_locs[1])[inds][ufm_inds]/DEG*60)) + full_aman[to_comp][1])[inds][ufm_inds]/DEG*60)) ufm_std_xi.append(np.nanstd( (full_aman.full_modeled[0] - - full_aman.nominal_xieta_locs[0])[inds][ufm_inds]/DEG*60)) + full_aman[to_comp][0])[inds][ufm_inds]/DEG*60)) ufm_std_eta.append(np.nanstd( (full_aman.full_modeled[1] - - full_aman.nominal_xieta_locs[1])[inds][ufm_inds]/DEG*60)) + full_aman[to_comp][1])[inds][ufm_inds]/DEG*60)) ufm_wafer_num.append(np.nanmedian(full_aman.det_wafer[inds][ufm_inds])) all_ufm_az.append(ufm_az) all_ufm_el.append(ufm_el) @@ -583,11 +647,11 @@ def analyze_PM_with_all_dets(config, t0, tf, params): full_aman.wrap("dxi", (full_aman.full_modeled[0] - - full_aman.nominal_xieta_locs[0])/DEG*60, + full_aman[to_comp][0])/DEG*60, [(0, "samps")]) full_aman.wrap("deta", (full_aman.full_modeled[1] - - full_aman.nominal_xieta_locs[1])/DEG*60, + full_aman[to_comp][1])/DEG*60, [(0, "samps")]) obsids=np.array([int(D.split('_')[1]) for D in full_aman.obs_info.obs_ids]) per_obs_stats.wrap("obsids", obsids) @@ -716,6 +780,7 @@ def main(config_path: str): 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") @@ -752,6 +817,7 @@ def main(config_path: str): all_nom_det_array, all_det_ids, obs_index, + ot_list, ) = load_per_detector_data(config, t0, tf, no_downsample_set=True) ancil, roll_c = load_obs_boresight_per_detector(config, filelist, obs_index) @@ -768,6 +834,7 @@ def main(config_path: str): ) fitcheck_aman.wrap("weights", weights_dets, [(0, "samps")]) fitcheck_aman.wrap("obs_index", obs_index, [(0, "samps")]) + fitcheck_aman.wrap("ot_list", ot_list, [(0, "samps")]) logger.info("Loaded %s fit check data points", len(weights_dets)) #Now make axis manager that has down sampled data for computation @@ -779,6 +846,7 @@ def main(config_path: str): all_nom_det_array, all_det_ids, obs_index, + ot_list, ) = load_per_detector_data(config, t0, tf) logger.info("Loaded %s data points", len(weights_dets)) ancil, roll_c = load_obs_boresight_per_detector(config, filelist, obs_index) @@ -803,6 +871,7 @@ def main(config_path: str): ) solver_aman.wrap("weights", weights_dets, [(0, "samps")]) solver_aman.wrap("obs_index", obs_index) + solver_aman.wrap("ot_list", ot_list) epoch["solver_aman"] = solver_aman epoch["fitcheck_aman"] = fitcheck_aman logger.info("Built axis manager for epoch %s", epoch["name"]) @@ -817,7 +886,7 @@ def main(config_path: str): for epoch in epochs: t0, tf = epoch["begin_timerange"], epoch["end_timerange"] - filelist, obs_ufm_centers, weights_ufm, obs_index = load_per_obs_data(config, t0, tf) + filelist, obs_ufm_centers, weights_ufm, obs_index, ot_list = load_per_obs_data(config, t0, tf) logger.info("Loaded per-obs FFP data from %s: ", config.get("per_obs_fps")) logger.info("Including data from these obs:") logger.info(filelist) @@ -849,6 +918,7 @@ def main(config_path: str): ) solver_aman.wrap("weights", weights_ufm.reshape(-1), [(0, "samps")]) solver_aman.wrap("obs_index", obs_index) + solver_aman.wrap("ot_list", ot_list) # Make weights/data cuts epoch["solver_aman"] = solver_aman logger.info("Built axis manager for epoch %s", epoch["name"]) @@ -866,9 +936,10 @@ def main(config_path: str): model_solved_params = minimize( objective_model_func_lmfit_joint, fit_params, - method="nelder", + method=config.get("fit_method", "nelder"), nan_policy="omit", args=(pm_version, epochs, xieta_model, use_weights), + **config.get("fit_options", {}), ) logger.info("Ran 1st Minimization") @@ -942,6 +1013,7 @@ def main(config_path: str): plotter.plot_residuals_histograms() plotter.plot_dets_in_these_obs() + tot_bad = 0 if iterate_cutoff is not None: logger.info("Iterating parameter solution") logger.info(f"Using {iterate_cutoff} as cutoff") @@ -960,6 +1032,7 @@ def main(config_path: str): len(bad_fit_inds), cutoff, ) + tot_bad += len(bad_fit_inds) if len(bad_fit_inds) != 0: if fit_type == "ufm_center": @@ -977,7 +1050,7 @@ def main(config_path: str): # 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, + _, _, masked_rms, _ = apply_model_params(xieta_model, epoch["solver_aman"].pointing_model, pm_version, epoch["solver_aman"], @@ -987,12 +1060,16 @@ def main(config_path: str): epoch["solver_aman"].weights[bad_fit_inds] = 0.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, - fit_params, - method="nelder", + model_solved_params, + method=config.get("fit_method", "nelder"), nan_policy="omit", args=(pm_version, epochs, xieta_model, use_weights), + **config.get("fit_options", {}), ) test_params = _round_params(model_solved_params.params.valuesdict(), 8) @@ -1091,6 +1168,20 @@ def main(config_path: str): dbfile = "db.sqlite" db = _create_db(dbfile, save_dir) for epoch in epochs: + solver_aman = epoch["solver_aman"] + # Remove OT float parameters + if config["float_ots"]: + ot_float_aman = core.AxisManager() + for ot in np.unique(solver_aman.ot_list): + 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"}, @@ -1108,6 +1199,8 @@ def main(config_path: str): 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"]}") @@ -1121,6 +1214,7 @@ def main(config_path: str): 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() @@ -1271,7 +1365,6 @@ def plot_full_unmodeled_residuals(self): plt.savefig(f"{plot_dir}/{platform}_full_2D_Residuals_Az{tag}.png", dpi=350) plt.close() - def plot_full_residuals_across_focalplane(self): platform = self.platform plot_dir = self.plot_dir @@ -1300,6 +1393,33 @@ def plot_full_residuals_across_focalplane(self): if self.save_figure: plt.savefig(f"{plot_dir}/{platform}_full_FocalPlane_colored_FitResiduals{tag}.png", dpi=350) + 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=np.deg2rad(24), scale_units='xy', alpha=.8) + 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", dpi=350) + def plot_full_histogram(self): platform = self.platform plotlims = self.plotlims From 3cd40d84d4a8437ea4ca2c43c0305cc00c1ee1eb Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Tue, 14 Apr 2026 15:04:01 -0400 Subject: [PATCH 053/132] fix: many small bugfixes in loading and initialization --- sotodlib/utils/epochs.py | 47 ++++++++++++++++++++++++---------------- 1 file changed, 28 insertions(+), 19 deletions(-) diff --git a/sotodlib/utils/epochs.py b/sotodlib/utils/epochs.py index 0d3771f7f..012ea2005 100644 --- a/sotodlib/utils/epochs.py +++ b/sotodlib/utils/epochs.py @@ -46,13 +46,13 @@ def __getitem__(self: Self, val) -> Self: if not isinstance(val, slice): val = slice(val) if val.start is not None: - if self.start < val.start: + 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: + 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}!" ) @@ -91,15 +91,13 @@ def combine( combined.start = min(self.start, tocombine.start) combined.stop = max(self.stop, tocombine.stop) - if not same_tag and self.tags != tocombine.tags: - raise ValueError("Can't combine without identical tags with same_tag=False") + 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 not same_data and len(diff) != 0: - raise ValueError( - "Can't combine without identical data with same_data=False" - ) + 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 @@ -195,7 +193,7 @@ def __repr__(self) -> str: ) def __setattr__(self, name, value): - if name == "covers" or name == "strict": + if (name == "covers" or name == "strict") and "_internal" in self.__dict__: self.__post_init__() return super().__setattr__(name, value) @@ -207,7 +205,7 @@ def __eq__(self, 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 also contain the same value for the field. + Optinally check that they each contain the same value for the field across all intervals. Parameters ---------- @@ -259,7 +257,7 @@ def __post_init__(self): ) def __setattr__(self, name, value): - if name == "epochs" or name == "strict": + if (name == "epochs" or name == "strict") and "_internal" in self.__dict__: self.__post_init__() return super().__setattr__(name, value) @@ -329,13 +327,13 @@ def find_tagged( A list of obects of type `search_in` containing this tag. """ if search_in == "intervals": - return [ival for ival in self.intervals.values() if field in ival.tags] + 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 field in epoch._internal.tags + 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 field in era._internal.tags] + return [era for era in self.eras.values() if tag in era._internal.tags] else: raise ValueError(f"Invalid search_in: {search_in}") @@ -539,11 +537,12 @@ def load(cls, fpath: str) -> Self: intervals = cfg["intervals"] eras = {} data = {} - for key, val in cfg: + for key, val in cfg.items(): if key == "intervals": continue if key[0] == "_": data[key[1:]] = val + continue eras[key] = val # Load intervals @@ -559,10 +558,11 @@ def load(cls, fpath: str) -> Self: name, interval.get("start", 0), interval.get("stop", 20000000000), - interval.get("tags", []), + set(interval.get("tags", [])), interval_data, ) interval_dict[str(ival)] = ival + intervals[name] = ival # Load epochs epoch_dict = {} @@ -571,10 +571,19 @@ def load(cls, fpath: str) -> Self: strict_epoch = era.get("strict_epochs", True) epochs = [] for name, ec in era.items(): + if name in ["strict_era", "strict_epochs"]: + continue covers = [] for cname in ec.get("covers", []): - iname, slstr = cname.split("[") - slstr = slstr[:-1] + 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}") ival = intervals[iname] interval_dict[str(ival)] = ival slc = slice( @@ -584,7 +593,7 @@ def load(cls, fpath: str) -> Self: ) ) covers += [ival[slc]] - epoch = Epoch(name, ename, tuple(covers), strict_epoch) + epoch = Epoch(name, ename, tuple(covers), strict=strict_epoch) epochs += [epoch] epoch_dict[f"{ename}.{name}"] = epoch eras[ename] = Era(ename, tuple(epochs), strict_era) From 9838573382209bbbf14a3f7adc4160e9269ddb22 Mon Sep 17 00:00:00 2001 From: Elle Shaw Date: Mon, 20 Apr 2026 16:38:23 -0700 Subject: [PATCH 054/132] Refactoring of code to handle per-detector azimuth data. Implements saving of lmfit parameter errors and correlations matrix. Simplifies loading of data into axis managers. --- .../site_pipeline/solve_pointing_model.py | 759 ++++++++---------- 1 file changed, 357 insertions(+), 402 deletions(-) diff --git a/sotodlib/site_pipeline/solve_pointing_model.py b/sotodlib/site_pipeline/solve_pointing_model.py index 378c64041..9b486693b 100644 --- a/sotodlib/site_pipeline/solve_pointing_model.py +++ b/sotodlib/site_pipeline/solve_pointing_model.py @@ -7,8 +7,7 @@ import logging import numpy as np import so3g.proj.quat as quat -import pdb -# import lmfit + import lmfit from lmfit import minimize, Parameters, fit_report import time @@ -33,10 +32,15 @@ plt.rcParams["grid.alpha"] = 0.5 -def load_nom_ufm_centers(config): - # Load Nominal UFM Center Locations from centered focal_plane +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] @@ -45,24 +49,15 @@ def load_nom_ufm_centers(config): 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) + index = temp_ufms.index(OT.focal_planes[ufm].stream_id) nom_ufm_centers[index, :3] = OT.focal_planes[ufm].center - return nom_ufm_centers - -def load_per_obs_data(config, t0, tf): - # Load per-observation UFM center data points and weights # The per obs .h5 file a dict with obs_id for keys - per_obs_fps = config.get("per_obs_fps") - ufms = config.get("ufms") - skip_tags = config.get("skip_tags", []) 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 = [] @@ -76,19 +71,35 @@ def load_per_obs_data(config, t0, tf): 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) - #obs_index[initial_weights_mask] = np.nan - return filelist, obs_ufm_centers, weights_ufm, obs_index, 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, ufm): +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: @@ -101,7 +112,7 @@ def load_nom_focal_plane_full(config, ufm): elif which_template == "ffp": ffp_path = config.get("ffp_path") with h5py.File(ffp_path, "r") as template_fp: - OT = template_fp["0/st1"] + OT = template_fp[t0]["st1"] fpf = np.array(OT[ufm]["focal_plane_full"][:]) # Extracting specific columns using structured arrays det_ids = fpf[ @@ -113,8 +124,9 @@ def load_nom_focal_plane_full(config, ufm): nom_det_array = np.stack((xi, eta, gamma), axis=1) return det_ids, nom_det_array + -def create_size_mask(obs_index): +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) @@ -124,8 +136,9 @@ def create_size_mask(obs_index): 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): +def _create_culling_mask(obs_index, cull_dets): # Remove a random fraction 1/cull_dets of each dataset unique, counts = np.unique(obs_index, return_counts=True) #min_count = min(counts) @@ -135,12 +148,15 @@ def create_culling_mask(obs_index, cull_dets): 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_set=False, return_all_dets=False): +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"]) if return_all_dets: band = None @@ -164,132 +180,145 @@ def load_per_detector_data(config, t0, tf, no_downsample_set=False, return_all_d if config.get("use_these_files") is not None: filelist = [filelist[i] for i in config.get("use_these_files")] - weights_dets, obs_dets_fits, stream_id_list, ot_list, obs_index = [], [], [], [], [] - #which_ufm = config.get("which_ufm", None) - which_data = config.get("use_as_data") - which_weights = config.get("use_as_weights", None) - + obs_dets_fits, det_boresight, weights_dets, stream_id_list, ot_list, obs_index = [], [], [], [], [], [] 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 which_ufm is not None and ufm.stream_id not in which_ufm: continue stream_id_list.append(ufm.stream_id) weights = ufm.weights[:, 1] if which_weights == "r2" else ufm.weights[:, 0] - data = ufm.avg_fp if which_data == "raw" else ufm.transformed weights_dets.append(weights) + data = ufm.avg_fp if which_data == "raw" else ufm.transformed obs_dets_fits.append(data) obs_index.append(np.repeat(i, len(ufm.weights))) ot_list.append([this_OT.name] * len(data)) + 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) - nom_data = [load_nom_focal_plane_full(config, s) for s in stream_id_list] + nom_data = [load_nom_focal_plane_full(config, t0, s) for s in stream_id_list] all_det_ids, all_nom_det_array = map(np.concatenate, zip(*nom_data)) 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] + weights_dets[weights_dets < config.get("weight_cutoff")] = 0.0 obs_dets_fits[np.where(weights_dets == 0)] = np.nan mask = ~np.isnan(weights_dets) - - if no_downsample_set: - #plotting use-case to compare subset fits with the entire dataset. - return ( - filelist, - obs_dets_fits[mask], - weights_dets[mask], - all_nom_det_array[mask], - all_det_ids[mask], - obs_index[mask], - ot_list[mask], - ) - - else: + 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]) - #apply weights and band mask - obs_dets_fits = obs_dets_fits[mask] - weights_dets = weights_dets[mask] - all_nom_det_array = all_nom_det_array[mask] - all_det_ids = all_det_ids[mask] - obs_index = obs_index[mask] - ot_list = ot_list[mask] + data_group = [arr[mask] for arr in data_group] + if even_obs_size: - mask = create_size_mask(obs_index) - obs_dets_fits = obs_dets_fits[mask] - weights_dets = weights_dets[mask] - all_nom_det_array = all_nom_det_array[mask] - all_det_ids = all_det_ids[mask] - obs_index = obs_index[mask] - ot_list = ot_list[mask] + 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): - mask = create_culling_mask(obs_index, cull_dets) - obs_dets_fits = obs_dets_fits[mask] - weights_dets = weights_dets[mask] - all_nom_det_array = all_nom_det_array[mask] - all_det_ids = all_det_ids[mask] - obs_index = obs_index[mask] - ot_list = ot_list[mask] - return ( - filelist, + 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_fm_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")]) -def load_obs_boresight(config, filelist): - # Load boresight elevation information from each observation - # Put into an axis manager - pm_version = config.get("pm_version") - 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]) - #az_c = np.round(np.array(az_c), 4) - #el_c = np.round(np.array(el_c), 4) - #roll_c = np.round(np.array(roll_c), 4) - #roll_c[np.where(roll_c == 0)[0]] = 0 # rounding gives negative 0 sometimes. - - 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")]) - if "lat" in pm_version: - ancil.wrap("corotator_enc", np.repeat((el_c - 60. - roll_c), 7), [(0, "samps")]) - if "sat" in pm_version: - ancil.wrap("boresight_enc", np.repeat(-1 * roll_c, 7), [(0, "samps")]) - return ancil, roll_c - - -def load_obs_boresight_per_detector(config, filelist, obs_ind): - # Load boresight elevation information from each observation - # Put into an axis manager - platform = config.get("platform") - 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")) - if platform == 'lat': - roll_c = np.array([roll_c[i] for i in obs_ind]) - ancil.wrap("az_enc", np.array([az_c[i] for i in obs_ind]), [(0, "samps")]) - ancil.wrap("el_enc", np.array([el_c[i] for i in obs_ind]), [(0, "samps")]) - ancil.wrap("corotator_enc", ancil.el_enc - 60. - roll_c, [(0, "samps")]) - else: - roll_c = np.array([roll_c[i] for i in obs_ind]) - ancil.wrap("az_enc", np.array([az_c[i] for i in obs_ind]), [(0, "samps")]) - ancil.wrap("el_enc", np.array([el_c[i] for i in obs_ind]), [(0, "samps")]) - ancil.wrap("boresight_enc", -1 * roll_c, [(0, "samps")]) - - return ancil, roll_c + return aman def _init_fit_params(config, epochs): @@ -372,6 +401,39 @@ def _apply_ot_float(xi_mod, eta_mod, solver_aman, params): eta_mod[msk] *= ot_pars[4] return xi_mod, eta_mod +#test Elle Apr 10 +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 + + 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) + if weights: + return dist * np.sqrt(solver_aman.weights) + else: + return dist + #weights_array = solver_aman.weights if weights else np.ones(len(dist)) + #return chi_sq(weights_array, dist) + +def objective_model_func_lmfit_joint( + params, pm_version, epochs, xieta_model, weights=True +): + params = params.valuesdict() + 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) + all_residuals.append(res) + return np.concatenate(all_residuals) + +""" def objective_model_func_lmfit( params, pm_version, solver_aman, xieta_model, weights=True ): @@ -405,6 +467,7 @@ def chi_sq(weights, dist): #chi2 = dist.T @ N @ dist chi2 = np.nansum(dist ** 2 * weights) return chi2 +""" def model_template_xieta(params, pm_version, aman): """ @@ -419,6 +482,7 @@ def model_template_xieta(params, pm_version, aman): 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) @@ -494,51 +558,35 @@ def _round_params(param_dict, decimal): return P -def analyze_PM_with_all_dets(config, t0, tf, params): - platform = config.get("platform") - - (filelist, obs_dets_fits, - weights_dets, all_nom_det_array, - all_det_ids, obs_index, ot_list - ) = load_per_detector_data(config, t0, tf, return_all_dets=True) +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 + - ancil, roll_c = load_obs_boresight_per_detector(config, filelist, obs_index) +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')] - - obs_info = core.AxisManager() - obs_info.wrap("obs_ids", np.array(filelist)) - full_aman = core.AxisManager(core.IndexAxis("samps")) - full_aman.wrap("obs_info", obs_info) - full_aman.wrap("ancil", ancil) - full_aman.wrap( - "nominal_xieta_locs", all_nom_det_array.T, - [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], - [(1, "samps")], - ) - full_aman.wrap( - "measured_xieta_data", obs_dets_fits.T, - [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], - [(1, "samps")], - ) - full_aman.wrap("weights", weights_dets, [(0, "samps")]) - full_aman.wrap("obs_index", obs_index) - full_aman.wrap("ot_list", ot_list) - full_aman.wrap("roll_c", roll_c, [(0, "samps")]) - full_aman.wrap("det_ids", all_det_ids, [(0, "samps")]) - full_aman.wrap("radial", - np.sqrt(full_aman.nominal_xieta_locs[0]**2 + - full_aman.nominal_xieta_locs[1]**2)/DEG, - [(0, "samps")]) - full_aman.wrap("det_ufm", - np.array([detid.decode('utf-8').split('_')[0].lower() for detid in full_aman.det_ids]) - , [(0, "samps")]) + 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 full_aman.det_ufm]), + np.array([ufm_list.index(d) for d in det_ufms]), [(0, "samps")]) - # Apply model to data. + # Apply model to data. xieta_model = config.get("xieta_model", "measured") (full_modeled, full_residuals, rms, _ - ) = apply_model_params(xieta_model, + ) = apply_model_params(xieta_model, #"template", params, config.get("pm_version"), full_aman) @@ -546,137 +594,74 @@ def analyze_PM_with_all_dets(config, t0, tf, params): 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")]) + [(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) - del(full_modeled) - del(full_residuals) - - (obs_az, obs_el, obs_roll, obs_resid, - obs_dxi, obs_deta, obs_std_xi, obs_std_eta - ) = [], [], [], [], [], [], [], [] - (all_ufm_az, all_ufm_el, all_ufm_roll, all_ufm_resid, - all_ufm_dxi, all_ufm_deta, all_ufm_std_xi, - all_ufm_std_eta, all_ufm_wafer_num - ) = [], [], [], [], [], [], [], [], [] - for ob in np.unique(full_aman.obs_index): - inds = np.where(full_aman.obs_index == ob)[0] - obs_az.append(np.nanmedian(full_aman.ancil.az_enc[inds])) - obs_el.append(np.nanmedian(full_aman.ancil.el_enc[inds])) - obs_roll.append(np.nanmedian(full_aman.roll_c[inds])) - obs_resid.append(np.nanmean(full_aman.fit_residuals[inds])) - obs_dxi.append(np.nanmean((full_aman.full_modeled[0] - - full_aman[to_comp][0])[inds]/DEG*60)) - obs_deta.append(np.nanmean((full_aman.full_modeled[1] - - full_aman[to_comp][1])[inds]/DEG*60)) - obs_std_xi.append(np.nanstd((full_aman.full_modeled[0] - - full_aman[to_comp][0])[inds]/DEG*60)) - obs_std_eta.append(np.nanstd((full_aman.full_modeled[1] - - full_aman[to_comp][1])[inds]/DEG*60)) - (ufm_az, ufm_el, ufm_roll, ufm_resid, - ufm_dxi, ufm_deta, ufm_std_xi, - ufm_std_eta, ufm_wafer_num - )= [], [], [], [], [], [], [], [], [] + + dxi_all = (full_aman.full_modeled[0] - xi_nom) / DEG * 60 #modeled - nominal + deta_all = (full_aman.full_modeled[1] - eta_nom) / 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: - ufm_inds = np.where(full_aman.det_ufm[inds] == ufm)[0] - ufm_az.append(np.nanmedian(full_aman.ancil.az_enc[inds][ufm_inds])) - ufm_el.append(np.nanmedian(full_aman.ancil.el_enc[inds][ufm_inds])) - ufm_roll.append(np.nanmedian(full_aman.roll_c[inds][ufm_inds])) - ufm_resid.append(np.nanmean(full_aman.fit_residuals[inds][ufm_inds])) - ufm_dxi.append(np.nanmean((full_aman.full_modeled[0] - - full_aman[to_comp][0])[inds][ufm_inds]/DEG*60)) - ufm_deta.append(np.nanmean( - (full_aman.full_modeled[1] - - full_aman[to_comp][1])[inds][ufm_inds]/DEG*60)) - ufm_std_xi.append(np.nanstd( - (full_aman.full_modeled[0] - - full_aman[to_comp][0])[inds][ufm_inds]/DEG*60)) - ufm_std_eta.append(np.nanstd( - (full_aman.full_modeled[1] - - full_aman[to_comp][1])[inds][ufm_inds]/DEG*60)) - ufm_wafer_num.append(np.nanmedian(full_aman.det_wafer[inds][ufm_inds])) - all_ufm_az.append(ufm_az) - all_ufm_el.append(ufm_el) - all_ufm_roll.append(ufm_roll) - all_ufm_resid.append(ufm_resid) - all_ufm_deta.append(ufm_deta) - all_ufm_dxi.append(ufm_dxi) - all_ufm_std_xi.append(ufm_std_xi) - all_ufm_std_eta.append(ufm_std_eta) - all_ufm_wafer_num.append(ufm_wafer_num) - + 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() - per_obs_stats.wrap("el", np.array(obs_el)) - per_obs_stats.wrap("roll", np.array(obs_roll)) - per_obs_stats.wrap("az", np.array(obs_az)) - per_obs_stats.wrap("resid", np.array(obs_resid)) - per_obs_stats.wrap("dxi", np.array(obs_dxi)) - per_obs_stats.wrap("deta", np.array(obs_deta)) - per_obs_stats.wrap("std_xi", np.array(obs_std_xi)) - per_obs_stats.wrap("std_eta", np.array(obs_std_eta)) - per_ufm_stats.wrap("az", np.array(all_ufm_az)) - per_ufm_stats.wrap("el", np.array(all_ufm_el)) - per_ufm_stats.wrap("roll", np.array(all_ufm_roll)) - per_ufm_stats.wrap("resid", np.array(all_ufm_resid)) - per_ufm_stats.wrap("dxi", np.array(all_ufm_dxi)) - per_ufm_stats.wrap("deta", np.array(all_ufm_deta)) - per_ufm_stats.wrap("std_xi", np.array(all_ufm_std_xi)) - per_ufm_stats.wrap("std_eta", np.array(all_ufm_std_eta)) - per_ufm_stats.wrap("wafer_num", np.array(all_ufm_wafer_num)) - - if platform == "lat": - obs_cr = [] - all_ufm_cr = [] - for ob in np.unique(full_aman.obs_index): - inds = np.where(full_aman.obs_index == ob)[0] - obs_cr.append(np.nanmedian(full_aman.ancil.corotator_enc[inds])) - ufm_cr = [] - for ufm in ufm_list: - ufm_inds = np.where(full_aman.det_ufm[inds] == ufm)[0] - ufm_cr.append(np.nanmedian(full_aman.ancil.corotator_enc[inds][ufm_inds])) - all_ufm_cr.append(ufm_cr) - per_obs_stats.wrap("cr", np.array(obs_cr)) - per_ufm_stats.wrap("cr", np.array(all_ufm_cr)) - - full_aman.wrap("dxi", - (full_aman.full_modeled[0] - - full_aman[to_comp][0])/DEG*60, - [(0, "samps")]) - full_aman.wrap("deta", - (full_aman.full_modeled[1] - - full_aman[to_comp][1])/DEG*60, - [(0, "samps")]) + 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]) + full_aman.wrap("obsids", obsids[full_aman.obs_index], [(0, "samps")]) #Calculate RMSs - per_obs_stats.wrap("rms", - np.sqrt(np.nanmean(per_obs_stats["dxi"]**2 + - per_obs_stats["deta"]**2)) - ) - per_ufm_stats.wrap("rms", - np.sqrt(np.nanmean(per_ufm_stats["dxi"]**2 + - per_ufm_stats["deta"]**2)) - ) - full_aman.wrap("rms", - np.sqrt(np.nanmean(full_aman["dxi"]**2 + - full_aman["deta"]**2)) - ) + 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): @@ -764,7 +749,7 @@ def main(config_path: str): t0, tf = epoch["begin_timerange"], epoch["end_timerange"] test_params, epochs = _init_fit_params(config, epochs) - logger.info("Using these paramters to test pointing: ") + 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) @@ -776,6 +761,8 @@ def main(config_path: str): 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) @@ -784,6 +771,7 @@ def main(config_path: str): 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 @@ -805,73 +793,18 @@ def main(config_path: str): which_data = config.get("use_as_data") use_weights = config.get("use_weights", True) - #Make axis manager with full detector set. - # Keep wafer/band/obs cuts but do not further downsample. + for epoch in epochs: t0, tf = epoch["begin_timerange"], epoch["end_timerange"] - fitcheck_aman = core.AxisManager(core.IndexAxis("samps")) - ( - filelist, - obs_dets_fits, - weights_dets, - all_nom_det_array, - all_det_ids, - obs_index, - ot_list, - ) = load_per_detector_data(config, t0, tf, no_downsample_set=True) - ancil, roll_c = load_obs_boresight_per_detector(config, filelist, obs_index) - - fitcheck_aman.wrap("ancil", ancil) - fitcheck_aman.wrap( - "nominal_xieta_locs", all_nom_det_array.T, - [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], - [(1, "samps")], - ) - fitcheck_aman.wrap( - "measured_xieta_data", obs_dets_fits.T, - [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], - [(1, "samps")], - ) - fitcheck_aman.wrap("weights", weights_dets, [(0, "samps")]) - fitcheck_aman.wrap("obs_index", obs_index, [(0, "samps")]) - fitcheck_aman.wrap("ot_list", ot_list, [(0, "samps")]) - logger.info("Loaded %s fit check data points", len(weights_dets)) + # 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 = core.AxisManager(core.IndexAxis("samps")) - ( - filelist, - obs_dets_fits, - weights_dets, - all_nom_det_array, - all_det_ids, - obs_index, - ot_list, - ) = load_per_detector_data(config, t0, tf) - logger.info("Loaded %s data points", len(weights_dets)) - ancil, roll_c = load_obs_boresight_per_detector(config, filelist, obs_index) - - # Build Axis Managers - solver_aman.wrap("ancil", ancil) - obs_info = core.AxisManager() - obs_info.wrap("obs_ids", np.array(filelist)) - solver_aman.wrap("obs_info", obs_info) - solver_aman.wrap("roll_c", roll_c, [(0, "samps")]) - solver_aman.wrap( - "nominal_xieta_locs", - all_nom_det_array.T, - [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], - [(1, "samps")], - ) - solver_aman.wrap( - "measured_xieta_data", - obs_dets_fits.T, - [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], - [(1, "samps")], - ) - solver_aman.wrap("weights", weights_dets, [(0, "samps")]) - solver_aman.wrap("obs_index", obs_index) - solver_aman.wrap("ot_list", ot_list) + 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"]) @@ -880,46 +813,13 @@ def main(config_path: str): elif fit_type == "ufm_center": use_weights = config.get("use_weights", True) # Load in focal_plane and boresight data - nom_ufm_centers = load_nom_ufm_centers(config) - logger.info("Loaded nominal UFM centers from %s: ", config.get("ffp_path")) - logger.info(nom_ufm_centers) - for epoch in epochs: t0, tf = epoch["begin_timerange"], epoch["end_timerange"] - filelist, obs_ufm_centers, weights_ufm, obs_index, ot_list = load_per_obs_data(config, t0, tf) + 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(filelist) + logger.info(solver_aman.obs_info.obs_ids) - ancil, roll_c = load_obs_boresight(config, filelist) - logger.info("Loaded boresight data from obs ids.") - - # Build Axis Managers - obs_info = core.AxisManager() - obs_info.wrap("obs_ids", np.array(filelist)) - - solver_aman = core.AxisManager(core.IndexAxis("samps")) - solver_aman.wrap("ancil", ancil) - solver_aman.wrap("obs_info", obs_info) - solver_aman.wrap("roll_c", np.repeat(roll_c, 7), [(0, "samps")]) - solver_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")], - ) - solver_aman.wrap( - "measured_xieta_data", - obs_ufm_centers.reshape(len(filelist) * 7, 3).T, - [(0, core.LabelAxis("xietagamma", ["xi", "eta", "gamma"]))], - [(1, "samps")], - ) - solver_aman.wrap("weights", weights_ufm.reshape(-1), [(0, "samps")]) - solver_aman.wrap("obs_index", obs_index) - solver_aman.wrap("ot_list", ot_list) - # Make weights/data cuts epoch["solver_aman"] = solver_aman logger.info("Built axis manager for epoch %s", epoch["name"]) @@ -953,7 +853,6 @@ def main(config_path: str): # save pointing model parameters to axis manager for epoch in epochs: - logger.info("Calculating RMS and cutoff for %s", epoch["name"]) 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()): @@ -961,17 +860,33 @@ def main(config_path: str): param_aman.wrap("version", pm_version) epoch["solver_aman"].wrap("pointing_model", param_aman) - # save errors to axis manager - error_aman = core.AxisManager() + #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"]: - error_aman.wrap(par_mapping[k.name], k.stderr) - epoch["solver_aman"].wrap("pointing_model_errors", error_aman) - - # parameter_fit_stats = build_param_fit_stat_aman(model_solved_params) - # solver_aman.wrap("parameter_fit_stats", parameter_fit_stats) + 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", "nelder") == "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) @@ -997,6 +912,8 @@ def main(config_path: str): 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) @@ -1013,7 +930,7 @@ def main(config_path: str): plotter.plot_residuals_histograms() plotter.plot_dets_in_these_obs() - tot_bad = 0 + tot_bad=0 if iterate_cutoff is not None: logger.info("Iterating parameter solution") logger.info(f"Using {iterate_cutoff} as cutoff") @@ -1050,7 +967,7 @@ def main(config_path: str): # 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, + _, _, masked_rms, _ = apply_model_params(xieta_model, epoch["solver_aman"].pointing_model, pm_version, epoch["solver_aman"], @@ -1059,17 +976,18 @@ def main(config_path: str): logger.info("RMS on initial fit without outliers: %f arcmin", masked_rms) epoch["solver_aman"].weights[bad_fit_inds] = 0.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, - method=config.get("fit_method", "nelder"), + fit_params, + method=config.get("fit_method", "leastsq"), nan_policy="omit", args=(pm_version, epochs, xieta_model, use_weights), - **config.get("fit_options", {}), + **config.get("fit_options", {}) ) test_params = _round_params(model_solved_params.params.valuesdict(), 8) @@ -1084,7 +1002,6 @@ def main(config_path: str): # save pointing model parameters to axis manager for epoch in epochs: - logger.info("Calculating RMS for %s", epoch["name"]) 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() @@ -1094,17 +1011,33 @@ def main(config_path: str): epoch["solver_aman"].wrap("pointing_model", param_aman) # save errors to axis manager - epoch["solver_aman"].move("pointing_model_errors", "pointing_model_errors_i1") - error_aman = core.AxisManager() + 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"]: - error_aman.wrap(par_mapping[k.name], k.stderr) - epoch["solver_aman"].wrap("pointing_model_errors", error_aman) + 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", "nelder") == "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) - # parameter_fit_stats = build_param_fit_stat_aman(model_solved_params) - # epoch["solver_aman"].wrap("parameter_fit_stats", parameter_fit_stats, overwrite=True) + 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, @@ -1135,6 +1068,8 @@ def main(config_path: str): 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) @@ -1156,6 +1091,8 @@ def main(config_path: str): 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) @@ -1180,8 +1117,6 @@ def main(config_path: str): 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"}, @@ -1200,8 +1135,8 @@ def main(config_path: str): 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) - + test_params = test_params.merge(epoch["solver_aman"].o +t_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) ") @@ -1210,9 +1145,12 @@ def main(config_path: str): 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) + plotlims=plotlims, + ) plotter.plot_full_residuals_across_focalplane() plotter.plot_full_deltas_across_focalplane() plotter.plot_full_histogram() @@ -1227,7 +1165,7 @@ def main(config_path: str): #################### class ModelFitsPlotter: - def __init__(self, solver_aman, config, save_dir, iteration_tag="", save_figure=True, plotlims=None): + def __init__(self, solver_aman, config, save_dir, t0, tf, iteration_tag="", save_figure=True, plotlims=None): self.aman = solver_aman self.config = config @@ -1240,7 +1178,8 @@ def __init__(self, solver_aman, config, save_dir, iteration_tag="", save_figure= 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") @@ -1264,7 +1203,7 @@ def plot_full_unmodeled_residuals(self): full_dxi_av = np.nanmean(self.aman.dxi) full_deta_av = np.nanmean(self.aman.deta) if "sat" in platform: - elmin, elmax = 45, 65 + elmin, elmax = 40, 65 rollmin, rollmax = -45, 45 azmin, azmax = 0, 360 if platform=="satp2": @@ -1365,6 +1304,7 @@ def plot_full_unmodeled_residuals(self): plt.savefig(f"{plot_dir}/{platform}_full_2D_Residuals_Az{tag}.png", dpi=350) plt.close() + def plot_full_residuals_across_focalplane(self): platform = self.platform plot_dir = self.plot_dir @@ -1419,7 +1359,7 @@ def plot_full_deltas_across_focalplane(self): plt.xlim(-.31, .31);plt.ylim(-.31, .31) if self.save_figure: plt.savefig(f"{plot_dir}/{platform}_full_FocalPlane_colored_FitDeltas{tag}.png", dpi=350) - + def plot_full_histogram(self): platform = self.platform plotlims = self.plotlims @@ -1431,6 +1371,7 @@ def plot_full_histogram(self): 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)) @@ -1440,12 +1381,16 @@ def plot_full_histogram(self): 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", dpi=350) + plt.savefig(f"{plot_dir}/{platform}_full_Hist_Residuals{tag}.png", dpi=350) def plot_dets_in_these_obs(self): platform = self.platform @@ -1458,7 +1403,7 @@ def plot_dets_in_these_obs(self): if platform == 'lat': elmin=10; elmax=90 else: - elmin=45; elmax=65 + elmin=40; elmax=65 plt.figure() fig, ax = plt.subplots(2,2,figsize=(11,10)) @@ -1504,7 +1449,7 @@ def plot_modeled_fits(self): ufm_list = self.ufms plotmask = np.where(weights) nom_array = np.concatenate( - [load_nom_focal_plane_full(self.config, ufm)[1] for ufm in ufm_list], + [load_nom_focal_plane_full(self.config, self.t0, ufm)[1] for ufm in ufm_list], axis=0, ) rms = np.round(fit_rms, 4) @@ -1803,30 +1748,40 @@ def plot_template_space_fits_per_detector(self): pm_version, self.aman ) + + fig, ax = plt.subplots(2, 1, figsize=(8,5)) + ax[0].hist(xi_unmod / ARCMIN - nominal_xieta_locs[0] / ARCMIN, + range=(-1 * plotlims, plotlims), bins = 30) + ax[1].hist(eta_unmod / ARCMIN - nominal_xieta_locs[1] / ARCMIN, + range=(-1 * plotlims, plotlims), bins = 30) + if self.save_figure: + plt.savefig(f"{plot_dir}/{platform}_xi_and_eta_residuals_hist.png", dpi=350) + plt.close() + #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=weights, + c=ancil.az_enc, s=scale_weights * 5, edgecolor="gray", lw=0.3, marker="o", alpha=0.2, cmap="viridis", - vmin=self.config.get("weight_cutoff"), - vmax=1 + 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 fit weight") + 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_weights{tag}.png", dpi=350) + plt.savefig(f"{plot_dir}/{platform}_unmodeled_fits_WS_azimuth{tag}.png", dpi=350) plt.close() fig, ax = plt.subplots(figsize=(9, 6)) ax.plot(0, 0, "kx", label="Nominal Center") From 5b8780f39321fcc998d1971d90426a2357829e7d Mon Sep 17 00:00:00 2001 From: Elle Shaw Date: Wed, 22 Apr 2026 09:08:06 -0700 Subject: [PATCH 055/132] Fix bugs and typos. Handle measured vs template options in calculation of differential xi and eta in analyze_PM_with_all_dets function. Feature plot of correlation matrix. --- .../site_pipeline/solve_pointing_model.py | 172 +++++++++--------- 1 file changed, 86 insertions(+), 86 deletions(-) diff --git a/sotodlib/site_pipeline/solve_pointing_model.py b/sotodlib/site_pipeline/solve_pointing_model.py index 9b486693b..f18d8b1fa 100644 --- a/sotodlib/site_pipeline/solve_pointing_model.py +++ b/sotodlib/site_pipeline/solve_pointing_model.py @@ -401,41 +401,9 @@ def _apply_ot_float(xi_mod, eta_mod, solver_aman, params): eta_mod[msk] *= ot_pars[4] return xi_mod, eta_mod -#test Elle Apr 10 -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 - - 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) - if weights: - return dist * np.sqrt(solver_aman.weights) - else: - return dist - #weights_array = solver_aman.weights if weights else np.ones(len(dist)) - #return chi_sq(weights_array, dist) -def objective_model_func_lmfit_joint( - params, pm_version, epochs, xieta_model, weights=True -): - params = params.valuesdict() - 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) - all_residuals.append(res) - return np.concatenate(all_residuals) - -""" def objective_model_func_lmfit( - params, pm_version, solver_aman, xieta_model, weights=True + params, pm_version, solver_aman, xieta_model, fit_method, weights=True ): if xieta_model == "measured": xi_mod, eta_mod = model_measured_xieta(params, pm_version, solver_aman) @@ -447,27 +415,31 @@ def objective_model_func_lmfit( 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) - #print(np.nansum(dist)) weights_array = solver_aman.weights if weights else np.ones(len(dist)) - return chi_sq(weights_array, dist) -def objective_model_func_lmfit_joint( - params, pm_version, epochs, xieta_model, weights=True -): - params = params.valuesdict() - chisq = 0 - t1 = time.time() - for epoch in epochs: - chisq += objective_model_func_lmfit({par.split(f"_{epoch['name']}")[0]:params[par] for par in epoch["params"]}, pm_version, epoch["solver_aman"], xieta_model, weights) - return chisq + return (dist * np.sqrt(weights_array)) -def chi_sq(weights, dist): - #N = np.identity(len(dist)) * weights - #chi2 = dist.T @ N @ dist - chi2 = np.nansum(dist ** 2 * weights) - return chi2 -""" +def objective_model_func_lmfit_joint( + params, pm_version, epochs, xieta_model, fit_method, weights=True): + params = params.valuesdict() + if fit_method == "leastsq" or fit_method == "least_squares": + 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, fit_method, weights) + all_residuals.append(res) + return np.concatenate(all_residuals) + + else: + chisq = 0 + 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, fit_method, weights) + chisq += np.nansum(res**2) + + return chisq + def model_template_xieta(params, pm_version, aman): """ @@ -586,11 +558,12 @@ def analyze_PM_with_all_dets(config, t0, tf, params): # Apply model to data. xieta_model = config.get("xieta_model", "measured") (full_modeled, full_residuals, rms, _ - ) = apply_model_params(xieta_model, #"template", + ) = apply_model_params(xieta_model, params, config.get("pm_version"), full_aman) - to_comp = "nominal_xieta_locs" + 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), @@ -603,8 +576,9 @@ def analyze_PM_with_all_dets(config, t0, tf, params): 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] - xi_nom) / DEG * 60 #modeled - nominal - deta_all = (full_aman.full_modeled[1] - eta_nom) / DEG * 60 + 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")]) @@ -693,6 +667,7 @@ def main(config_path: str): 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) @@ -833,12 +808,13 @@ def main(config_path: str): # Solve for Model Parameters # use chosen xieta_model to solve for parameters + breakpoint() model_solved_params = minimize( objective_model_func_lmfit_joint, fit_params, - method=config.get("fit_method", "nelder"), + method=fit_method, nan_policy="omit", - args=(pm_version, epochs, xieta_model, use_weights), + args=(pm_version, epochs, xieta_model, fit_method, use_weights), **config.get("fit_options", {}), ) logger.info("Ran 1st Minimization") @@ -877,12 +853,12 @@ def main(config_path: str): str(model_solved_params.message)) model_fit_stats_aman.wrap('fit_report', fitreport_aman) - if config.get("fit_method", "nelder") == "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) + #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 @@ -923,12 +899,14 @@ def main(config_path: str): 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: @@ -968,7 +946,7 @@ def main(config_path: str): # 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, + epoch["solver_aman"].pointing_model, pm_version, epoch["solver_aman"], use_inds=good_fit_inds) @@ -979,14 +957,13 @@ def main(config_path: str): 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, fit_params, - method=config.get("fit_method", "leastsq"), + method=fit_method, nan_policy="omit", - args=(pm_version, epochs, xieta_model, use_weights), + args=(pm_version, epochs, xieta_model, fit_method, use_weights), **config.get("fit_options", {}) ) @@ -1027,12 +1004,12 @@ def main(config_path: str): fitreport_aman.wrap('message', str(model_solved_params.message)) model_fit_stats_aman.wrap('fit_report', fitreport_aman) - if config.get("fit_method", "nelder") == "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) + #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) @@ -1080,11 +1057,13 @@ def main(config_path: str): 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: @@ -1107,7 +1086,7 @@ def main(config_path: str): for epoch in epochs: solver_aman = epoch["solver_aman"] # Remove OT float parameters - if config["float_ots"]: + if config.get("float_ots", False): ot_float_aman = core.AxisManager() for ot in np.unique(solver_aman.ot_list): for par in [f"{n}_{ot}" for n in ["xioff", "etaoff", "rot", "xiscale", "etascale"]]: @@ -1135,8 +1114,7 @@ def main(config_path: str): 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"].o -t_float_aman) + 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) ") @@ -1749,15 +1727,6 @@ def plot_template_space_fits_per_detector(self): self.aman ) - fig, ax = plt.subplots(2, 1, figsize=(8,5)) - ax[0].hist(xi_unmod / ARCMIN - nominal_xieta_locs[0] / ARCMIN, - range=(-1 * plotlims, plotlims), bins = 30) - ax[1].hist(eta_unmod / ARCMIN - nominal_xieta_locs[1] / ARCMIN, - range=(-1 * plotlims, plotlims), bins = 30) - if self.save_figure: - plt.savefig(f"{plot_dir}/{platform}_xi_and_eta_residuals_hist.png", dpi=350) - plt.close() - #plot with weights as colorbar fig, ax = plt.subplots(figsize=(9, 6)) ax.plot(0, 0, "kx", label="Nominal Center") @@ -1859,7 +1828,6 @@ def plot_template_space_fits_per_detector(self): plt.savefig(f"{plot_dir}/{platform}_unmodeled_fits_WS_corotator{tag}.png", dpi=350) plt.close() - def plot_residuals_vs_ancil(self): platform = self.platform plot_dir = self.plot_dir @@ -2226,7 +2194,39 @@ def plot_xieta_cross_residuals(self): plt.savefig(f"{plot_dir}/{platform}_xieta_cross_residuals{tag}.png", dpi=350) 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", dpi=350) + plt.close() ############ if __name__ == "__main__": From 0288873fe1aebafc709d2c5c9f5572d4370f76c0 Mon Sep 17 00:00:00 2001 From: Elle Shaw Date: Wed, 22 Apr 2026 09:10:49 -0700 Subject: [PATCH 056/132] Remove breakpoint(). Error remains on float_ots == True --- sotodlib/site_pipeline/solve_pointing_model.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sotodlib/site_pipeline/solve_pointing_model.py b/sotodlib/site_pipeline/solve_pointing_model.py index f18d8b1fa..9ef587cdf 100644 --- a/sotodlib/site_pipeline/solve_pointing_model.py +++ b/sotodlib/site_pipeline/solve_pointing_model.py @@ -421,7 +421,8 @@ def objective_model_func_lmfit( def objective_model_func_lmfit_joint( - params, pm_version, epochs, xieta_model, fit_method, weights=True): + params, pm_version, epochs, xieta_model, fit_method, weights=True +): params = params.valuesdict() if fit_method == "leastsq" or fit_method == "least_squares": all_residuals=[] @@ -808,7 +809,6 @@ def main(config_path: str): # Solve for Model Parameters # use chosen xieta_model to solve for parameters - breakpoint() model_solved_params = minimize( objective_model_func_lmfit_joint, fit_params, From 51b1ba7e14438529a0412ad32834aec1231b1594 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Wed, 22 Apr 2026 23:23:18 -0700 Subject: [PATCH 057/132] fix: handle nans in OT float and catch some edge cases --- .../site_pipeline/solve_pointing_model.py | 27 +++++++++++++------ 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/sotodlib/site_pipeline/solve_pointing_model.py b/sotodlib/site_pipeline/solve_pointing_model.py index 9ef587cdf..8d3a6e72a 100644 --- a/sotodlib/site_pipeline/solve_pointing_model.py +++ b/sotodlib/site_pipeline/solve_pointing_model.py @@ -139,6 +139,8 @@ def _create_size_mask(obs_index): 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) @@ -392,8 +394,8 @@ def _apply_ot_float(xi_mod, eta_mod, solver_aman, params): theta = ot_pars[2] R = np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]) - xi_cent = np.mean(xi_mod[msk]) - eta_cent = np.mean(eta_mod[msk]) + 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 @@ -403,7 +405,7 @@ def _apply_ot_float(xi_mod, eta_mod, solver_aman, params): def objective_model_func_lmfit( - params, pm_version, solver_aman, xieta_model, fit_method, weights=True + 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) @@ -411,6 +413,8 @@ def objective_model_func_lmfit( 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) @@ -428,7 +432,7 @@ def objective_model_func_lmfit_joint( 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, fit_method, weights) + res = objective_model_func_lmfit(epoch_params, pm_version, epoch["solver_aman"], xieta_model, weights) all_residuals.append(res) return np.concatenate(all_residuals) @@ -436,7 +440,7 @@ def objective_model_func_lmfit_joint( chisq = 0 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, fit_method, weights) + res = objective_model_func_lmfit(epoch_params, pm_version, epoch["solver_aman"], xieta_model, weights) chisq += np.nansum(res**2) return chisq @@ -482,9 +486,11 @@ def model_measured_xieta(params, pm_version, aman): 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: + 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 @@ -798,6 +804,8 @@ def main(config_path: str): 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 @@ -885,6 +893,7 @@ def main(config_path: str): 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, @@ -1042,6 +1051,7 @@ def main(config_path: str): 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, @@ -1067,6 +1077,7 @@ def main(config_path: str): 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, @@ -1109,7 +1120,7 @@ def main(config_path: str): #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 solver_aman: + if "pointing_model_i1" in epoch["solver_aman"]: test_params = epoch["solver_aman"].pointing_model_i1 else: test_params = epoch["solver_aman"].pointing_model @@ -1324,7 +1335,7 @@ def plot_full_deltas_across_focalplane(self): roll_c = self.aman.roll_c fig, ax = plt.subplots() - im = ax.quiver(xi, eta, dxi, deta, roll_c, angles='xy', scale=np.deg2rad(24), scale_units='xy', alpha=.8) + 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') From 4eb0d488e6d56053b311833c4044b83e88f595da Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Thu, 23 Apr 2026 08:26:08 -0700 Subject: [PATCH 058/132] fix: minor plotting stuff --- sotodlib/site_pipeline/solve_pointing_model.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/sotodlib/site_pipeline/solve_pointing_model.py b/sotodlib/site_pipeline/solve_pointing_model.py index 8d3a6e72a..3bf8e55a7 100644 --- a/sotodlib/site_pipeline/solve_pointing_model.py +++ b/sotodlib/site_pipeline/solve_pointing_model.py @@ -1863,6 +1863,8 @@ def plot_residuals_vs_ancil(self): 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() @@ -1870,9 +1872,11 @@ def plot_residuals_vs_ancil(self): 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}") + 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 @@ -1882,12 +1886,16 @@ def plot_residuals_vs_ancil(self): 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, @@ -1905,12 +1913,12 @@ def plot_residuals_vs_ancil(self): w=scale_weights[plotmask], ) xrange = np.arange(np.nanmin(x), np.nanmax(x)) - ax[i, j].plot( + ax[i, j].errorbar( xrange, mxb[0] * xrange + mxb[1], - "r", + color="r", lw=1, - label=f"Slope {np.round(mxb[0],4)}\n [arcmin/deg]", + label=f"Slope {np.round(mxb[0],4)} \n [arcmin/deg]", ) ax[i, j].legend(fontsize="small") ax[0, 0].set_ylabel("dXi [arcmin]") From f473780d7ea0f72add7c536f11d9db75a3a3d61a Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Fri, 24 Apr 2026 12:34:29 -0700 Subject: [PATCH 059/132] fix: dont allow OT offsets to be common mode across OTs and remove unused pars --- sotodlib/site_pipeline/solve_pointing_model.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/sotodlib/site_pipeline/solve_pointing_model.py b/sotodlib/site_pipeline/solve_pointing_model.py index 3bf8e55a7..1622cc263 100644 --- a/sotodlib/site_pipeline/solve_pointing_model.py +++ b/sotodlib/site_pipeline/solve_pointing_model.py @@ -354,8 +354,10 @@ def _init_fit_params(config, epochs): for ipar, par in zip(indep_list, epoch["indep_list"]): init_params[ipar] = init_params[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 @@ -365,10 +367,13 @@ def _init_fit_params(config, epochs): 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) # Turn off various parameters depending on platform for fix in fixed_params: @@ -383,9 +388,12 @@ def _apply_ot_float(xi_mod, eta_mod, solver_aman, params): # We are recomputing information that should just be cached here... # TODO: Fix that ot_float_pars = ["xioff", "etaoff", "rot", "xiscale", "etascale"] - ot_float_defaults = np.array([0, 0, 0, 1, 1]) - for ot in np.unique(solver_aman.ot_list): - ot_pars = [params.get(f"{n}_{ot}", d) for n, d in zip(ot_float_pars, ot_float_defaults)] + 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 np.unique(solver_aman.ot_list)]) + # 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(np.unique(solver_aman.ot_list)): + ot_pars = ot_pars_full[i] if np.array_equal(ot_pars, ot_float_defaults): continue msk = (solver_aman.ot_list == ot) From 620b4f567621a8c8f8a6175e1416cca0e36c8de3 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Fri, 24 Apr 2026 18:48:08 -0700 Subject: [PATCH 060/132] feat: better ffp plots --- sotodlib/coords/fp_containers.py | 85 +++++++++++++++++++++----------- 1 file changed, 57 insertions(+), 28 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 3e8a4ab92..f27eccd7c 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -1,3 +1,4 @@ +import re import logging import os from dataclasses import InitVar, dataclass, field @@ -792,76 +793,104 @@ def plot_by_gamma(focal_plane, plot_dir): ) plt.close() +def _convert_ids(ids, bp_groups): + # Collapse the high and low bandpasses + ids = np.array(ids) + + # This should probably just be dict comp + rep = {} + for group in bp_groups: + if len(group) == 0: + continue + bp_str = "/".join(group) + for bp in group: + rep[bp] = bp_str + + # https://stackoverflow.com/questions/6116978/how-to-replace-multiple-substrings-of-a-string + rep = dict((re.escape(k), v) for k, v in rep.items()) + pattern = re.compile("|".join(rep.keys())) + ids = np.array([pattern.sub(lambda m: rep[re.escape(m.group(0))], i) for i in ids]) + + return ids + 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 + all_diffs = np.vstack([fp.diff for fp in receiver.focal_planes]) + max_diff = np.nanpercentile(np.abs(all_diffs), 99) max_diff *= 180 * 60 * 60 / np.pi xlims, ylims = receiver.lims - + xlims = np.array(xlims)*1.1 + ylims = np.array(ylims)*1.1 + have_gamma = np.prod([fp.have_gamma for fp in receiver.focal_planes]) + nax = 2 + int(have_gamma) + + bp_groups = [('f030', 'f090', 'f220'), ('f040', 'f150', 'f280')] + bp_groups = [tuple(bp for bp in group if np.any(np.strings.find(valid_ids, bp) >= 0)) for group in bp_groups] + valid_ids = np.unique(_convert_ids(valid_ids, bp_groups)) + fig, axs_all = plt.subplots( - len(valid_ids), 3, sharex="col", sharey="row", constrained_layout=True + len(valid_ids), nax, sharex="col", sharey="row", constrained_layout=False, figsize=(50*np.ptp(xlims)*nax, 50*np.ptp(ylims)*len(valid_ids)), gridspec_kw = {'wspace':0, 'hspace':0}, ) axs = axs_all.flat axs[0].set_title("Xi") axs[1].set_title("Eta") - axs[2].set_title("Gamma") + if have_gamma: + 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 j in range(nax): + axs[nax * i + j].set_aspect("equal") + axs[nax * i + j].set_xlim(xlims) + axs[nax * 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 + msk = (_convert_ids(fp.id_strs, bp_groups) == 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( + cf = axs[nax * i + 0].scatter( fp.transformed[msk, 0], fp.transformed[msk, 1], - diff[msk, 0], - levels=20, + c = diff[msk, 0], + marker=".", vmin=-1 * max_diff, vmax=max_diff, cmap="coolwarm", + alpha=.5 ) - cf = axs[3 * i + 1].tricontourf( + cf = axs[nax * i + 1].scatter( fp.transformed[msk, 0], fp.transformed[msk, 1], - diff[msk, 1], - levels=20, + c = diff[msk, 1], + marker=".", vmin=-1 * max_diff, vmax=max_diff, cmap="coolwarm", + alpha=.5 ) if fp.have_gamma: - cf = axs[3 * i + 2].tricontourf( + cf = axs[nax * i + 2].scatter( fp.transformed[msk, 0], fp.transformed[msk, 1], - diff[msk, 2], - levels=20, + c = diff[msk, 2], + marker=".", vmin=-1 * max_diff, vmax=max_diff, cmap="coolwarm", + alpha=.5 ) - axs[3 * i + 0].set_ylabel(f"{valid_ids[i]}\nEta (rad)") + axs[nax * 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)") + for i in range(nax, 0, -1): + axs[-i].set_xlabel("Xi (rad)") fig.suptitle("Full Receiver Residuals") - fig.set_size_inches(2 * fig.get_size_inches()) + # 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.savefig(os.path.join(plot_dir, f"receiver.png"), bbox_inches="tight", dpi=100) plt.close() From 8eaad8ddf2767db3bc579b3300b579f921f530b1 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Fri, 8 May 2026 21:12:18 -0700 Subject: [PATCH 061/132] fix: more plotting improvements --- sotodlib/coords/fp_containers.py | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index e44fb70d2..35cc515f9 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -18,7 +18,7 @@ logger = logging.getLogger("finalize_focal_plane") plt.style.use("tableau-colorblind10") - +plt.rcParams['font.size'] = 20 def _add_attrs(dset, attrs): for k, v in attrs.items(): @@ -639,10 +639,10 @@ def ot_dict(self): @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]) + xmax = np.max([np.nanmax(fp.template.fp[:, 0]) for fp in self.focal_planes]) + xmin = np.min([np.nanmin(fp.template.fp[:, 0]) for fp in self.focal_planes]) + ymax = np.max([np.nanmax(fp.template.fp[:, 1]) for fp in self.focal_planes]) + ymin = np.min([np.nanmin(fp.template.fp[:, 1]) for fp in self.focal_planes]) return (xmin, xmax), (ymin, ymax) @property @@ -820,8 +820,8 @@ def plot_receiver(receiver, plot_dir): max_diff = np.nanpercentile(np.abs(all_diffs), 99) max_diff *= 180 * 60 * 60 / np.pi xlims, ylims = receiver.lims - xlims = np.array(xlims)*1.1 - ylims = np.array(ylims)*1.1 + xlims = np.array(xlims)*1.05 + ylims = np.array(ylims)*1.05 have_gamma = np.prod([fp.have_gamma for fp in receiver.focal_planes]) nax = 2 + int(have_gamma) @@ -830,7 +830,7 @@ def plot_receiver(receiver, plot_dir): valid_ids = np.unique(_convert_ids(valid_ids, bp_groups)) fig, axs_all = plt.subplots( - len(valid_ids), nax, sharex="col", sharey="row", constrained_layout=False, figsize=(50*np.ptp(xlims)*nax, 50*np.ptp(ylims)*len(valid_ids)), gridspec_kw = {'wspace':0, 'hspace':0}, + len(valid_ids), nax, sharex="col", sharey="row", constrained_layout=False, figsize=(120*np.ptp(xlims)*nax, 80*np.ptp(ylims)*len(valid_ids)), gridspec_kw = {'wspace':0, 'hspace':0}, ) axs = axs_all.flat axs[0].set_title("Xi") @@ -851,8 +851,8 @@ def plot_receiver(receiver, plot_dir): continue diff = fp.diff * 180 * 60 * 60 / np.pi cf = axs[nax * i + 0].scatter( - fp.transformed[msk, 0], - fp.transformed[msk, 1], + fp.template.fp[msk, 0], + fp.template.fp[msk, 1], c = diff[msk, 0], marker=".", vmin=-1 * max_diff, @@ -861,8 +861,8 @@ def plot_receiver(receiver, plot_dir): alpha=.5 ) cf = axs[nax * i + 1].scatter( - fp.transformed[msk, 0], - fp.transformed[msk, 1], + fp.template.fp[msk, 0], + fp.template.fp[msk, 1], c = diff[msk, 1], marker=".", vmin=-1 * max_diff, @@ -872,8 +872,8 @@ def plot_receiver(receiver, plot_dir): ) if fp.have_gamma: cf = axs[nax * i + 2].scatter( - fp.transformed[msk, 0], - fp.transformed[msk, 1], + fp.template.fp[msk, 0], + fp.template.fp[msk, 1], c = diff[msk, 2], marker=".", vmin=-1 * max_diff, From 6ada85f77743c706175d18bc5e04bd29d8e6898a Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Thu, 14 May 2026 16:24:34 -0400 Subject: [PATCH 062/132] feat: add ability to refer to previously defined eras during epoch construction --- sotodlib/utils/epochs.py | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/sotodlib/utils/epochs.py b/sotodlib/utils/epochs.py index 012ea2005..b8a3070e8 100644 --- a/sotodlib/utils/epochs.py +++ b/sotodlib/utils/epochs.py @@ -584,15 +584,25 @@ def load(cls, fpath: str) -> Self: slstr = slstr[:-1] else: raise ValueError(f"Invalid cover string {cname}") - ival = intervals[iname] - interval_dict[str(ival)] = ival slc = slice( *map( lambda x: float(x.strip()) if x.strip() else None, slstr.split(":"), ) ) - covers += [ival[slc]] + # 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, ival.start), min(slc.stop, ival.stop)) + covers += [ival[islc]] epoch = Epoch(name, ename, tuple(covers), strict=strict_epoch) epochs += [epoch] epoch_dict[f"{ename}.{name}"] = epoch From f6114b1f414b1f6f13c052c523fbd99368c34527 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Mon, 1 Jun 2026 16:49:05 -0400 Subject: [PATCH 063/132] fix: sanatize scalars before saving --- sotodlib/core/axisman_io.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sotodlib/core/axisman_io.py b/sotodlib/core/axisman_io.py index 94135d7a3..ce5c5a177 100644 --- a/sotodlib/core/axisman_io.py +++ b/sotodlib/core/axisman_io.py @@ -283,7 +283,7 @@ def _save_axisman(axisman, dest, group=None, overwrite=False, compression=None, print(f'Unhandled {item["name"]}->{item["encoding"]}') if len(scalars): - dest.attrs['_scalars'] = json.dumps(scalars) + dest.attrs['_scalars'] = json.dumps(_safe_scalars(scalars)) if len(units): dest.attrs['_units'] = json.dumps(units) From 0412e73321fd25292fdebeedd11ee1cb1cb84269 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Sun, 7 Jun 2026 18:09:58 -0400 Subject: [PATCH 064/132] feat: switch from strictness bool to operator input and fix some operators --- sotodlib/utils/epochs.py | 105 ++++++++++++++++++++++++--------------- 1 file changed, 66 insertions(+), 39 deletions(-) diff --git a/sotodlib/utils/epochs.py b/sotodlib/utils/epochs.py index b8a3070e8..6139397f7 100644 --- a/sotodlib/utils/epochs.py +++ b/sotodlib/utils/epochs.py @@ -2,12 +2,24 @@ from copy import deepcopy from dataclasses import dataclass, field from functools import reduce -from operator import add, and_, mul, or_ +import operator from typing import Any, Literal, Optional, Self, cast, overload +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, +} + @dataclass class Interval: @@ -19,14 +31,14 @@ class Interval: Two `Interval` instances can be combined with the following operators, all operators are functionally addition but with differing checks: - * `|`: Intervals must be overlapping, but data and tags can differ - * `&`: Allow gaps between intervals, but data and tags can differ - * `*`: Invervals must be overlapping, data must be the same but tags can differ - * `+`: Allow gaps between intervals, data must be the same but tags can differ - * `/`: Invervals must be overlapping, data can differ but tags must be the same - * `-`: Allow gaps between intervals, data can differ but tags must be the same - * `**`: Allow gaps between invervals, data and tags must be the same - * `@`: Allow gaps between intervals, data and tags must be the same + * `|`: 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. @@ -128,10 +140,10 @@ def __add__(self, tocombine) -> Self: def __iadd__(self, tocombine) -> Self: return self.combine(tocombine, True, True, True, False) - def __div__(self, tocombine) -> Self: + def __truediv__(self, tocombine) -> Self: return self.combine(tocombine, False, False, False, True) - def __idiv__(self, tocombine) -> Self: + def __itruediv__(self, tocombine) -> Self: return self.combine(tocombine, True, False, False, True) def __sub__(self, tocombine) -> Self: @@ -141,10 +153,10 @@ def __isub__(self, tocombine) -> Self: return self.combine(tocombine, True, True, False, True) def __pow__(self, tocombine) -> Self: - return self.combine(tocombine, False, False, False, True) + return self.combine(tocombine, False, False, True, True) def __ipow__(self, tocombine) -> Self: - return self.combine(tocombine, True, False, False, True) + return self.combine(tocombine, True, False, True, True) def __matmul__(self, tocombine) -> Self: return self.combine(tocombine, False, True, True, True) @@ -165,23 +177,24 @@ class Epoch: Name for this epoch. era_name : str Name of the era that this epoch belongs to. - covers: tuple[Interval] + covers : tuple[Interval] Collections of overlapping `Invervals` that make up an `Epoch`. - strict : bool - If `True` than in addition to being overlapping the `Intervals` must - also contain the same data. + 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, ...] - strict: bool + operator: str _internal: Interval = field(init=False) def __post_init__(self): - self._internal = cast( - Interval, reduce(mul if self.strict else or_, self.covers) - ) + 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 ( @@ -189,7 +202,7 @@ def __repr__(self) -> str: + "(" + ",".join([str(ival) for ival in self.covers]) + ")" - + ("*" * self.strict) + + (self.operator) ) def __setattr__(self, name, value): @@ -219,13 +232,15 @@ def check_data(self, field: str, strict: bool = True) -> bool: if field not in self._internal.data: return False if strict: - tester = self if self.strict else deepcopy(self) + tester = deepcopy(self) try: - tester.strict = True + tester.operator = "+" except ValueError: return False return True - return cast(bool, reduce(and_, [field in ival.data for ival in self.covers])) + return cast( + bool, reduce(OP_MAP["&"], [field in ival.data for ival in self.covers]) + ) @dataclass @@ -240,20 +255,22 @@ class Era: Name for this era. epochs : tuple[Epoch] Collections of non-overlapping `Epochs` that make up an `Era`. - strict : bool - If `True` than in addition to being non-overlapping the `Epochs` must - also contain the same data. + 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, ...] - strict: bool + 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(add if self.strict else and_, [e._internal for e in self.epochs]), + Interval, reduce(OP_MAP[self.operator], [e._internal for e in self.epochs]) ) def __setattr__(self, name, value): @@ -276,7 +293,8 @@ def check_data(self, field: str, strict: bool = True) -> bool: """ return cast( - bool, reduce(and_, [e.check_data(field, strict) for e in self.epochs]) + bool, + reduce(OP_MAP["&"], [e.check_data(field, strict) for e in self.epochs]), ) @@ -567,11 +585,11 @@ def load(cls, fpath: str) -> Self: # Load epochs epoch_dict = {} for ename, era in eras.items(): - strict_era = era.get("strict_era", False) - strict_epoch = era.get("strict_epochs", True) + era_op = era.get("era_op", "&") + epoch_op = era.get("epoch_op", "&") epochs = [] for name, ec in era.items(): - if name in ["strict_era", "strict_epochs"]: + if name in ["epoch_op", "era_op"]: continue covers = [] for cname in ec.get("covers", []): @@ -597,15 +615,24 @@ def load(cls, fpath: str) -> Self: interval_dict[str(ival)] = ival covers += [ival[slc]] # Case 2: we are refering to a previously defined epoch - if iname in epoch_dict: + 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, ival.start), min(slc.stop, ival.stop)) + 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), strict=strict_epoch) + epoch = Epoch(name, ename, tuple(covers), operator=epoch_op) epochs += [epoch] epoch_dict[f"{ename}.{name}"] = epoch - eras[ename] = Era(ename, tuple(epochs), strict_era) + eras[ename] = Era(ename, tuple(epochs), era_op) return cls(interval_dict, epoch_dict, eras, data, []) From 568809a2921435b2736dc9c076961edca40804b8 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Sun, 7 Jun 2026 15:35:28 -0700 Subject: [PATCH 065/132] fix: pass in OT config properly --- sotodlib/site_pipeline/finalize_focal_plane.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/sotodlib/site_pipeline/finalize_focal_plane.py b/sotodlib/site_pipeline/finalize_focal_plane.py index d43f2e05c..f9645027f 100644 --- a/sotodlib/site_pipeline/finalize_focal_plane.py +++ b/sotodlib/site_pipeline/finalize_focal_plane.py @@ -249,6 +249,8 @@ def _load_ctx(config): continue if aman.obs_info.tube_slot == "stp1": aman.obs_info.tube_slot = "st1" + if aman.obs_info.tube_slot == "o6": + continue if "det_info" not in aman: raise ValueError(f"No det_info in {obs_id}") if "wafer" not in aman.det_info and dm_name in aman: @@ -399,7 +401,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, } @@ -622,6 +624,7 @@ def main(): 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) From 44890281ca2706a2f63bf11346c541697a5c6938 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Thu, 11 Jun 2026 22:26:08 -0400 Subject: [PATCH 066/132] feat: First pass of containers for joint focal plane + pointing model + epochs aware system --- sotodlib/coords/fp_containers.py | 1692 ++++++++++++++++------------- sotodlib/coords/fpc_old.py | 840 ++++++++++++++ sotodlib/coords/pointing_model.py | 7 +- 3 files changed, 1781 insertions(+), 758 deletions(-) create mode 100644 sotodlib/coords/fpc_old.py diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index fb089c631..1119a4e50 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -1,42 +1,217 @@ -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 +""" +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: Function to update pointing model pars that is aware of joint fits +# TODO: Serialization + ManifestDb +# TODO: Reprs + +from __future__ import annotations +from typing import Optional, Any, cast +from dataclasses import dataclass, field +from jaxtyping import Float, Shaped +import numpy as np 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 +from functools import cached_property +from copy import deepcopy +from scipy.optimize import minimize +from sotodlib.coords.pointing_model import apply_pointing_model +from so3g.proj import quat +from sotodlib.core import AxisManager, IndexAxis +from sotodlib.utils import epochs +from sotodlib.io.metadata import SuperLoader +from sotodlib.core.metadata import MetadataSpec +from sotodlib.core.metadata import ManifestDb + +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): + to_ret = deepcopy(self.template) + to_ret.xyz = mt.apply_transform(self.template.xyz, self.transform.affine, self.transform.shift) + to_ret.center = mt.apply_transform(self.template.center, self.transform.affine, self.transform.shift) + if self.autofreeze: + setattr(self, attr_name, to_ret) + return to_ret + +def _get_aff(self : FocalPlane | FocalPlaneCollection, data_name : str, attr_name : str): + affine, shift = mt.get_affine_two_stage( + self.template.xyz[:, :2], + getattr(self, data_name).xyz[:, :2], + self.weights[:, 0], + ) + to_ret = Transform.identity() + 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( + self.template.xyz[:, 2], getattr(self, data_name).xyz[:, 2] + ) + if self.autofreeze: + setattr(self, attr_name, to_ret) + return to_ret + +class StaticOrCached(): + """ + 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 -logger = logging.getLogger("finalize_focal_plane") -plt.style.use("tableau-colorblind10") + def __set_name__(self, owner, attr_name): + self.attr_name = attr_name + def __get__(self, obj, owner): + if obj is None: + return self -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 + if obj.static: + return getattr(obj, f"_{self.name}_stat") + 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 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 + ---------- + 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. + """ + parameters : dict + force_zero_roll : bool + + def apply_det( + self, + det_off: DetectorOffsets, + det_enc: DetectorOffsets, + fake_gamma: bool, + ) -> DetectorOffsets: + """ + Apply the 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 are corrected for the boresight pointing + model specified by this instance. + + If the pointing model contains no parameters, the input detector + offsets are returned unchanged. + + When `force_zero_roll=True`, the encoder roll angle is ignored during + the correction and a zero-roll boresight solution is assumed. + + Parameters + ---------- + det_off : DetectorOffsets + Detector offsets in the `xieta` coordinate system. These are the + detector positions to which the pointing correction will be + applied. + det_enc : DetectorOffsets + Telescope encoder values in the `horizon` coordinate system. + These provide the boresight azimuth, elevation, and roll used to + evaluate the pointing model. + fake_gamma : bool + If True, ignore detector polarization angles and propagate only + detector position (`xi`, `eta`). If False, propagate the full + (`xi`, `eta`, `gamma`) coordinate set. + + Returns + ------- + det_pm : DetectorOffsets + A copy of `det_off` with the pointing-model correction applied. + The returned object has the same metadata and detector ordering + as the input but contains corrected detector coordinates. + + Raises + ------ + ValueError + If `det_off` and `det_enc` do not contain the same number of + detectors. + """ + if len(self.parameters) == 0: + return det_off + if len(det_enc.xyz) != len(det_off.xyz): + raise ValueError("Detector offsets and encoder values must have same shape!") + bs = apply_pointing_model(None, self.parameters, det_off.ancil, False) + if fake_gamma: + q_fp = quat.rotation_xieta(det_off.xi, det_off.eta) + else: + q_fp = quat.rotation_xieta(det_off.xi, det_off.eta, det_off.gamma) # type: ignore + to_ret = deepcopy(det_off) + xi, eta, gamma = quat.decompose_xieta( + ~quat.euler(2, bs.roll) + * ~quat.rotation_lonlat(-1*bs.az, bs.el) # type: ignore + * quat.rotation_lonlat(-1 * det_enc.az, det_enc.el) + * quat.euler(2, (not self.force_zero_roll) * det_enc.roll) + * q_fp + ) + to_ret.xyz = np.column_stack((xi, eta, gamma)) + return to_ret - def __post_init__(self): - self.decompose() +@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. + """ + 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,791 +225,798 @@ 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] - - 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}"] + scale = np.array((*scale, gamma_scale)) + shear = shear.item() + rot = mt.decompose_rotation(rot)[-1] - 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] + return scale, shear, rot - @cached_property - def id_strs(self): - return np.array([bp + "_" + pol for bp, pol in zip(self.bandpass, self.pol)]) + @property + def scale(self): + return self.decompose[0] - @cached_property - def valid_ids(self): - ids = np.unique(self.id_strs) - valid = ~(np.char.startswith(ids, "_") * np.char.endswith(ids, "_")) - return ids[valid] + @property + def shear(self): + return self.decompose[1] + @property + def rot(self): + return self.decompose[2] @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,) +class DetectorOffsets: + """ + Class for storing detector offsets in either `xieta` or `horizon` coordinates. + `xi`, `eta`, `gamma`, `az`, `el`, and `roll` are included as properties for convenience. + They will raise a `ValueError` if called with the wrong coordsys set. + + Attributes + ---------- + xyz : Float[np.ndarray, "3 ndet"] + The `x` axis of the detector offsets. + For `xieta` this is `xi`. + For `horizon` this is `az`. + The `y` axis of the detector offsets. + For `xieta` this is `eta`. + For `horizon` this is `el`. + The `z` axis of the detector offsets. + For `xieta` this is `gamma`. + For `horizon` this is `roll`. + det_id : Shaped[np.ndarray, "ndet"] + The detector id for each element in `xyz`. + split : Shaped[np.ndarray, "ndet"] + A string used to split up detectors when plotting. + Nominally this should be to seperate the four detectors + behind the same feedhorn. + center : Optional[Float[np.ndarray, "3"]] + The center of the detector offsets. + Can be `None` if unknown. + coordsys : str + The coordinate system that these are in. + Should be `xieta` or `horizon`. + """ + 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"): + raise ValueError(f"Invalid coordsys {self.coordsys}") + + def __setattr__(self, name: str, value: Any, /) -> None: + if name in ("xyz"): + self.__dict__.pop("ancil", None) + return super().__setattr__(name, value) + @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)) - 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 + @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 - 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, - ) +@dataclass +class FocalPlane: + """ + Container for a single focalplane 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 properties: + + - Pointing model corrected detector positions (`data_pm`). + - 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`). + + 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. + + Attributes + ---------- + name : str + Human-readable identifier for the focal plane (ie. 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. + template : DetectorOffsets + Reference detector layout used as the transform source. + 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. + data_pm : DetectorOffsets + Measured detector offsets after application of the pointing model. + 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 `data_pm`. + pm_transformed : DetectorOffsets + Template detector offsets after applying `pm_transform`. + resid : Float[np.ndarray, "ndet 3"] + Residuals between `data` and `transformed`. + pm_resid : Float[np.ndarray, "ndet 3"] + Residuals between `data_pm` and `pm_transformed`. + """ + name : str + meas_id : str + data : DetectorOffsets + enc : DetectorOffsets + weights : Float[np.ndarray, "ndet"] + template : DetectorOffsets + pointing_model : PointingModel + static : bool + autofreeze : bool + fake_gamma : bool + data_pm : DetectorOffsets = cast(DetectorOffsets,StaticOrCached("data_pm")) + transform : Transform = cast(Transform, StaticOrCached("transform")) + transformed : DetectorOffsets = cast(DetectorOffsets,StaticOrCached("transformed")) + pm_transform : Transform = cast(Transform, StaticOrCached("pm_transform")) + pm_transformed : DetectorOffsets = cast(DetectorOffsets, StaticOrCached("pm_transformed")) + _data_pm_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) - 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 from_aman(cls, name : str, meas_id : str, aman : AxisManager, template : DetectorOffsets, pointing_model : PointingModel, autofreeze: bool=False, fake_gamma: bool = True, weight_factor: float = 1000.) -> 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. + template : DetectorOffsets + Template focal plane. + 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 + _, msk, template_msk = np.intersect1d( + np.array(aman.det_info.det_id), template.det_id, return_indices=True ) + mapping = np.argsort(np.argsort(template.det_id[template_msk])) + srt = np.argsort(np.array(aman.det_info.det_id[msk])) + + # 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_msk] = np.column_stack((xi, eta, gamma))[msk][srt][mapping] + 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_msk] = np.column_stack((az, el, roll))[msk][srt][mapping] + enc.xyz[~template_msk] = np.nan + + # Compute weights + aff, sft = mt.get_rigid( + data.xyz[:, :2], template.xyz[template_msk, :2] + ) + aligned = mt.apply_transform(data.xyz[:, :2], aff, sft) + xieta_spacing = mu.estimate_spacing(template.xyz[:, :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(template.xyz[:, 2])), 99.9) + spacing = np.array([xieta_spacing, xieta_spacing, gamma_spacing]) - @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"]), + if not fake_gamma: + gscale, gsft = gamma_fit( + data.xyz[:, 2], template.xyz[template_msk, 2] ) - ) - # 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"]), + weights = mu.gen_weights( + np.column_stack((aligned, gscale * data.xyz[:, 2] + gsft)), + template.xyz[template_msk], + spacing.ravel() / weight_factor, ) - ) - 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!" + weights = mu.gen_weights( + aligned, + template.xyz[template_msk, :2], + spacing[:2].ravel() / weight_factor, ) - 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 + # ~1 sigma cut + weights[weights < 0.61] = np.nan + return cls(name, meas_id, data, enc, weights, template, pointing_model, False, autofreeze, fake_gamma) -@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 freeze(self, static : bool): + """ + Save the current dynamic properties to the static fields. - def __setattr__(self, name, val): - self.__dict__[name] = val - if name == "focal_planes": - self.__dict__.pop("fp_dict", None) + Parameters + ---------- + static : bool + What to set `self.static` to after freezing. + """ + self._data_pm_stat = self._data_pm_dyn + 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 @property - def num_fps(self): - fps = [fp for fp in self.focal_planes if fp.tot_weight is not None] - return len(fps) + def _data_pm_dyn(self) -> DetectorOffsets: + to_ret = self.pointing_model.apply_det(self.data, self.enc, self.fake_gamma) + if self.autofreeze: + self._data_pm_stat = to_ret + return to_ret - @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)) + @property + def _transform_dyn(self) -> Transform: + return _get_aff(self, "data", "_transform_stat") - return OpticsTube(name, center) + @property + def _transformed_dyn(self) -> DetectorOffsets: + return _transformed(self, "_transformed_stat") - def delete_fp(self, stream_id): - self.focal_planes = [ - fp for fp in self.focal_planes if fp.stream_id != stream_id - ] + @property + def _pm_transform_dyn(self) -> Transform: + return _get_aff(self, "pm_data", "_pm_transform_stat") - @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) - ) + @property + def _pm_transformed_dyn(self) -> DetectorOffsets: + return _transformed(self, "_pm_transformed_stat") - @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 - ] + @property + def resid(self): + return self.data.xyz - self.transformed.xyz - return OpticsTube(name, center, transform, transform_fullcm, fps) + @property + def pm_resid(self): + return self.data_pm.xyz - self.pm_transformed.xyz @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) +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.data_pm`) from each measurement. + Detector locations and weights are combined on a per-detector + basis, missing values should be filled with `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. + 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. + data : DetectorOffsets + Weighted-average detector offsets constructed from the + pointing-model-corrected measurements in `focal_planes`. + 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`. + """ + name : str + focal_planes : list[FocalPlane] + template : DetectorOffsets + static : bool + autofreeze : bool + pad : bool + fake_gamma : bool + data : DetectorOffsets = cast(DetectorOffsets, StaticOrCached("data")) + weights : Float[np.ndarray, "ndet"] = cast(Float[np.ndarray, "ndet"], StaticOrCached("weights")) + transform : Transform = cast(Transform, StaticOrCached("transform")) + transformed : DetectorOffsets = cast(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) + + 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. + """ + 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 __post_init__(self): - self.center_transformed = mt.apply_transform( - self.center, self.transform.affine, self.transform.shift - ) + @property + def _data_dyn(self) -> DetectorOffsets: + to_ret = deepcopy(self.template) + dat_full = np.array([fp.data_pm.xyz * fp.weights[..., None] for fp in self. focal_planes]) + to_ret.xyz = np.nansum(dat_full, axis=-1)/self.weights[..., None] + to_ret.center = None + if self.autofreeze: + self._data_stat = to_ret + return to_ret - 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) + @property + def _weights_dyn(self) -> Float[np.ndarray, "ndet"]: + weights_full = np.array([fp.weights for fp in self. focal_planes]) + to_ret = np.nansum(weights_full, axis=-1) + if self.autofreeze: + self._weights_stat = to_ret + return to_ret - @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) + @property + def _transform_dyn(self) -> Transform: + return _get_aff(self, "data", "_transform_stat") - @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 _transformed_dyn(self) -> DetectorOffsets: + return _transformed(self, "_transformed_stat") @property - def focal_planes(self): - fps = [] - for ot in self.optics_tubes: - fps += ot.focal_planes - return fps + def resid(self): + return self.data.xyz - self.transformed.xyz - @cached_property - def ot_dict(self): - return {ot.name: ot for ot in self.optics_tubes} +@dataclass +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. + allpad : bool + Flag indicating whether all focal-plane collections in the optics + tube are padded and should therefore be excluded from common-mode + calculations. + 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. This quantity is not computed dynamically and + is updated only through `remove_rx`. + """ + name : str + focal_planes : list[FocalPlaneCollection] + wafer_slots : list[str] + static : bool + autofreeze : bool + allpad : bool + cm_transform : Transform = cast(Transform, StaticOrCached("cm_transform")) + cm_transform_norx : Transform = field(init=False) + _cm_transform_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. + """ + self._cm_transform_stat = self._cm_transform_dyn + self.static = static @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 _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] + allpad = False + if len(transforms) == 0: + allpad = True + 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) + to_ret = Transform(cm_shift, cm_aff) + if self.autofreeze: + self._cm_transform_stat = to_ret + self.allpad = allpad + return to_ret + + def remove_rx(self, rx_cm : Transform): + """ + Remove the receiver common-mode transform from the optics tube + common-mode transform. + + Unlike `cm_transform`, the receiver-corrected transform is not a + dynamic property and is updated only when this method is called. + + If `allpad=True`, no valid focal-plane collections are available for + this optics tube and `cm_transform_norx` is set to the identity + transform. + + Parameters + ---------- + rx_cm : Transform + Receiver common-mode transform to remove from the current + optics tube common mode. + """ + if self.allpad: + self.cm_transform_norx = Transform.identity() + aff, sft = mt.decompose_transform( + self.cm_transform.affine, + self.cm_transform.shift, + rx_cm.affine, + rx_cm.shift, + ) + self.cm_transform_norx = Transform(sft, aff) + +@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. + 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. + """ + name : str + optics_tubes : list[OpticsTube] + static : bool + autofreeze : bool + cm_transform : Transform = cast(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 freeze(self, static : bool): + """ + Save the current dynamic properties to the static fields. + + Parameters + ---------- + static : bool + What to set `self.static` to after freezing. + """ + self._cm_transform_stat = self._cm_transform_dyn + self.static = static @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 _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) + 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) + +@dataclass +class PointingSystem: + """ + Collection of epoch-dependent pointing models and receiver data. + + A `PointingSystem` maintains a one-to-one correspondence between the + epochs in an `epochs.Era`, a set of `PointingModel` + instances, and a set of `Receiver` instances. The ordering of these + must be the same. + + Attributes + ---------- + era : epochs.Era + Collection of observing epochs represented by the system. + pointing_models : tuple[PointingModel, ...] + Pointing model associated with each epoch. + receivers : tuple[Receiver, ...] + Receiver and focal-plane data associated with each epoch. + chisq : float + The chisq of the current system. + This computes the chisq from the residuals for each `FocalPlaneCollection`, + not the individual `FocalPlane` measurements. + """ + era : epochs.Era + pointing_models : tuple[PointingModel, ...] + receivers : tuple[Receiver, ...] -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 + def __post_init__(self): + if len(self.era.epochs) != len(self.pointing_models) or len(self.era.epochs) != len(self.receivers): + raise ValueError("Should have one pointing model and receiver per epoch!") - 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() + @property + def chisq(self) -> float: + chisq = 0. + for rx in self.receivers: + for ot in rx.optics_tubes: + for fp in ot.focal_planes: + chisq += np.nansum((fp.weights * fp.resid)**2).item() + return chisq + + 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. + + 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 i, epoch in enumerate(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}, []) + pm_dict = {key : pm_aman[key] for key in pm_aman.keys()} + self.pointing_models[i].parameters = pm_dict 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 b19f1dc91..e653af5c5 100644 --- a/sotodlib/coords/pointing_model.py +++ b/sotodlib/coords/pointing_model.py @@ -80,8 +80,9 @@ def apply_pointing_model(tod, pointing_model=None, ancil=None, ), "When using naive pointing model, wrap=... not supported" return apply_basic_pointing_model(tod) - 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) # Encoder values, to radians. if pointing_model is None: @@ -99,7 +100,7 @@ def apply_pointing_model(tod, pointing_model=None, ancil=None, if wrap is None: wrap = "boresight" - if wrap is not False: + if wrap is not False and tod is not None: if wrap in tod._fields: del tod[wrap] tod.wrap(wrap, boresight) From 3cfd91369d73a8bd095a44f7829111254c274bc8 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Wed, 5 Aug 2026 13:28:31 -0700 Subject: [PATCH 067/132] feat: lf fixes --- sotodlib/coords/fp_containers.py | 9 +- .../site_pipeline/finalize_focal_plane.py | 162 +++++------------- 2 files changed, 48 insertions(+), 123 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 2974ba572..e22994d06 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -99,7 +99,7 @@ def __post_init__(self, pointing_cfg): 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) + 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) @@ -110,7 +110,7 @@ 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())) + np.isin(["bandpass", "pol"], list(aman.det_info.wafer.keys())) ): logger.warning( "det_info.wafer seems to be missing metadata? Safe to ignore in rset mode." @@ -120,7 +120,8 @@ def add_wafer_info(self, aman, 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] + if "rhombus" in aman.det_info.wafer: + self.rhombus[template_msk] = aman.det_info.wafer.rhombus[srt][mapping] @cached_property def id_strs(self): @@ -322,7 +323,7 @@ def save(self, f, db_info, group): 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 = {"dets:wafer.array": 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) diff --git a/sotodlib/site_pipeline/finalize_focal_plane.py b/sotodlib/site_pipeline/finalize_focal_plane.py index f9645027f..6dd1eddde 100644 --- a/sotodlib/site_pipeline/finalize_focal_plane.py +++ b/sotodlib/site_pipeline/finalize_focal_plane.py @@ -33,7 +33,7 @@ ) 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: ") @@ -54,7 +54,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 +65,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)) > 5: + msk = (dists - np.nanmedian(dists)) > 3 * np.nanstd(dists) + 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 +135,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"]), @@ -249,8 +258,6 @@ def _load_ctx(config): continue if aman.obs_info.tube_slot == "stp1": aman.obs_info.tube_slot = "st1" - if aman.obs_info.tube_slot == "o6": - continue if "det_info" not in aman: raise ValueError(f"No det_info in {obs_id}") if "wafer" not in aman.det_info and dm_name in aman: @@ -285,111 +292,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") @@ -447,10 +365,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] @@ -614,12 +533,7 @@ 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) if len(ot_sids) == 0: raise ValueError("No stream_ids found!") if np.any(ot_sids[:, 0] != ot_sids[0][0]): @@ -682,7 +596,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) @@ -709,7 +623,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 @@ -735,19 +649,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: @@ -828,6 +743,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 ( @@ -835,7 +751,7 @@ 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) @@ -1089,6 +1005,14 @@ 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) if __name__ == "__main__": main() From f470651e945acff6e65251ccc8af09574693ffb0 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Mon, 24 Aug 2026 14:58:33 -0700 Subject: [PATCH 068/132] feat: dont rerun existing per-obs and some small qol features --- .../site_pipeline/finalize_focal_plane.py | 25 +++++++++++++++---- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/sotodlib/site_pipeline/finalize_focal_plane.py b/sotodlib/site_pipeline/finalize_focal_plane.py index 6dd1eddde..6ae759ef1 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') @@ -37,6 +38,7 @@ 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): @@ -218,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], @@ -243,12 +247,19 @@ 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) + + for obs_id in tqdm(obs_ids): + if obs_id in run: + logger.debug("%s has already been run", obs_id) + continue 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) @@ -275,7 +286,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() @@ -510,6 +521,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: @@ -522,6 +534,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) @@ -533,7 +546,7 @@ def main(): ) # Load data - amans, obs_ids, ot_sids = _load_ctx(config) + 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]): @@ -1013,6 +1026,8 @@ def main(): 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() From fd0b41ea2d08a3b42f67e7b40a063fe88a54e943 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Tue, 25 Aug 2026 17:46:16 -0400 Subject: [PATCH 069/132] chore: pep8 --- sotodlib/coords/fp_containers.py | 368 ++++++++++++++++++++----------- 1 file changed, 237 insertions(+), 131 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 1119a4e50..601e120df 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -4,6 +4,7 @@ Calculated transforms can either be treated at properties for ease of calculations or as static attributes for loading saved results. """ + # TODO: Function to update pointing model pars that is aware of joint fits # TODO: Serialization + ManifestDb # TODO: Reprs @@ -20,12 +21,13 @@ from scipy.optimize import minimize from sotodlib.coords.pointing_model import apply_pointing_model from so3g.proj import quat -from sotodlib.core import AxisManager, IndexAxis +from sotodlib.core import AxisManager, IndexAxis from sotodlib.utils import epochs from sotodlib.io.metadata import SuperLoader from sotodlib.core.metadata import MetadataSpec from sotodlib.core.metadata import ManifestDb + def gamma_fit(src, dst): """ Fit the transformation for gamma. @@ -54,15 +56,21 @@ def _gamma_min(pars, src, dst): res = minimize(_gamma_min, (1.0, 0.0), (src, dst)) return res.x -def _transformed(self : FocalPlane | FocalPlaneCollection, attr_name : str): + +def _transformed(self: FocalPlane | FocalPlaneCollection, attr_name: str): to_ret = deepcopy(self.template) - to_ret.xyz = mt.apply_transform(self.template.xyz, self.transform.affine, self.transform.shift) - to_ret.center = mt.apply_transform(self.template.center, self.transform.affine, self.transform.shift) + to_ret.xyz = mt.apply_transform( + self.template.xyz, self.transform.affine, self.transform.shift + ) + to_ret.center = mt.apply_transform( + self.template.center, self.transform.affine, self.transform.shift + ) if self.autofreeze: setattr(self, attr_name, to_ret) return to_ret -def _get_aff(self : FocalPlane | FocalPlaneCollection, data_name : str, attr_name : str): + +def _get_aff(self: FocalPlane | FocalPlaneCollection, data_name: str, attr_name: str): affine, shift = mt.get_affine_two_stage( self.template.xyz[:, :2], getattr(self, data_name).xyz[:, :2], @@ -73,13 +81,14 @@ def _get_aff(self : FocalPlane | FocalPlaneCollection, data_name : str, attr_nam to_ret.affine[:2, :2] = affine if not self.fake_gamma: to_ret.affine[-1, -1], to_ret.shift[-1] = gamma_fit( - self.template.xyz[:, 2], getattr(self, data_name).xyz[:, 2] - ) + self.template.xyz[:, 2], getattr(self, data_name).xyz[:, 2] + ) if self.autofreeze: setattr(self, attr_name, to_ret) return to_ret -class StaticOrCached(): + +class StaticOrCached: """ Wrapper that will get either: @@ -111,7 +120,7 @@ class PointingModel: detector offsets. In the future this should also be able to handle measurements from things like the starcamera. - Attributes + Attributes ---------- parameters : dict Dictionary of pointing-model parameters accepted by @@ -121,8 +130,9 @@ class PointingModel: If True, ignore the encoder roll angle when applying the pointing model and assume a zero-roll boresight solution. """ - parameters : dict - force_zero_roll : bool + + parameters: dict + force_zero_roll: bool def apply_det( self, @@ -132,7 +142,7 @@ def apply_det( ) -> DetectorOffsets: """ Apply the 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 @@ -141,10 +151,10 @@ def apply_det( If the pointing model contains no parameters, the input detector offsets are returned unchanged. - + When `force_zero_roll=True`, the encoder roll angle is ignored during the correction and a zero-roll boresight solution is assumed. - + Parameters ---------- det_off : DetectorOffsets @@ -159,14 +169,14 @@ def apply_det( If True, ignore detector polarization angles and propagate only detector position (`xi`, `eta`). If False, propagate the full (`xi`, `eta`, `gamma`) coordinate set. - + Returns ------- det_pm : DetectorOffsets A copy of `det_off` with the pointing-model correction applied. The returned object has the same metadata and detector ordering as the input but contains corrected detector coordinates. - + Raises ------ ValueError @@ -176,16 +186,18 @@ def apply_det( if len(self.parameters) == 0: return det_off if len(det_enc.xyz) != len(det_off.xyz): - raise ValueError("Detector offsets and encoder values must have same shape!") + raise ValueError( + "Detector offsets and encoder values must have same shape!" + ) bs = apply_pointing_model(None, self.parameters, det_off.ancil, False) if fake_gamma: q_fp = quat.rotation_xieta(det_off.xi, det_off.eta) else: - q_fp = quat.rotation_xieta(det_off.xi, det_off.eta, det_off.gamma) # type: ignore + q_fp = quat.rotation_xieta(det_off.xi, det_off.eta, det_off.gamma) # type: ignore to_ret = deepcopy(det_off) xi, eta, gamma = quat.decompose_xieta( ~quat.euler(2, bs.roll) - * ~quat.rotation_lonlat(-1*bs.az, bs.el) # type: ignore + * ~quat.rotation_lonlat(-1 * bs.az, bs.el) # type: ignore * quat.rotation_lonlat(-1 * det_enc.az, det_enc.el) * quat.euler(2, (not self.force_zero_roll) * det_enc.roll) * q_fp @@ -193,6 +205,7 @@ def apply_det( to_ret.xyz = np.column_stack((xi, eta, gamma)) return to_ret + @dataclass class Transform: """ @@ -205,8 +218,9 @@ class Transform: affine : Float[np.ndarray, "ndim ndim"] The affine transformation matrix. """ - shift : Float[np.ndarray, "ndim"] - affine : Float[np.ndarray, "ndim ndim"] + + shift: Float[np.ndarray, "ndim"] + affine: Float[np.ndarray, "ndim ndim"] def __setattr__(self, name: str, value: Any, /) -> None: if name in ("shift", "affine"): @@ -260,6 +274,7 @@ def shear(self): def rot(self): return self.decompose[2] + @dataclass class DetectorOffsets: """ @@ -292,11 +307,12 @@ class DetectorOffsets: The coordinate system that these are in. Should be `xieta` or `horizon`. """ - 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 + + 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.coordsys not in ("xieta", "horizon"): @@ -307,7 +323,6 @@ def __setattr__(self, name: str, value: Any, /) -> None: self.__dict__.pop("ancil", None) return super().__setattr__(name, value) - @property def xi(self): if self.coordsys != "xieta": @@ -350,7 +365,7 @@ def ancil(self): 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 + ancil.wrap("boresight_enc", -1 * np.rad2deg(self.roll)) # for SATs return ancil @@ -424,29 +439,42 @@ class FocalPlane: pm_resid : Float[np.ndarray, "ndet 3"] Residuals between `data_pm` and `pm_transformed`. """ - name : str - meas_id : str - data : DetectorOffsets - enc : DetectorOffsets - weights : Float[np.ndarray, "ndet"] - template : DetectorOffsets - pointing_model : PointingModel - static : bool - autofreeze : bool - fake_gamma : bool - data_pm : DetectorOffsets = cast(DetectorOffsets,StaticOrCached("data_pm")) - transform : Transform = cast(Transform, StaticOrCached("transform")) - transformed : DetectorOffsets = cast(DetectorOffsets,StaticOrCached("transformed")) - pm_transform : Transform = cast(Transform, StaticOrCached("pm_transform")) - pm_transformed : DetectorOffsets = cast(DetectorOffsets, StaticOrCached("pm_transformed")) + + name: str + meas_id: str + data: DetectorOffsets + enc: DetectorOffsets + weights: Float[np.ndarray, "ndet"] + template: DetectorOffsets + pointing_model: PointingModel + static: bool + autofreeze: bool + fake_gamma: bool + data_pm: DetectorOffsets = cast(DetectorOffsets, StaticOrCached("data_pm")) + transform: Transform = cast(Transform, StaticOrCached("transform")) + transformed: DetectorOffsets = cast(DetectorOffsets, StaticOrCached("transformed")) + pm_transform: Transform = cast(Transform, StaticOrCached("pm_transform")) + pm_transformed: DetectorOffsets = cast( + DetectorOffsets, StaticOrCached("pm_transformed") + ) _data_pm_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) + _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) @classmethod - def from_aman(cls, name : str, meas_id : str, aman : AxisManager, template : DetectorOffsets, pointing_model : PointingModel, autofreeze: bool=False, fake_gamma: bool = True, weight_factor: float = 1000.) -> FocalPlane: + def from_aman( + cls, + name: str, + meas_id: str, + aman: AxisManager, + template: DetectorOffsets, + 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: @@ -474,9 +502,9 @@ def from_aman(cls, name : str, meas_id : str, aman : AxisManager, template : Det fake_gamma : bool, default: True See class docstring. If True will also set `gamma` to `nan`. - weight_factor : float, default: 1000 + weight_factor : float, default: 1000 Scaling factor applied to spacing when computing weights. - + Returns ------- focal_plane : FocalPlane @@ -494,23 +522,37 @@ def from_aman(cls, name : str, meas_id : str, aman : AxisManager, template : Det 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) + gamma = ( + np.array(aman.focal_plane.gamma) + if not fake_gamma + else np.nan * np.ones_like(xi) + ) data.xyz[template_msk] = np.column_stack((xi, eta, gamma))[msk][srt][mapping] 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) + 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_msk] = np.column_stack((az, el, roll))[msk][srt][mapping] enc.xyz[~template_msk] = np.nan # Compute weights - aff, sft = mt.get_rigid( - data.xyz[:, :2], template.xyz[template_msk, :2] - ) + aff, sft = mt.get_rigid(data.xyz[:, :2], template.xyz[template_msk, :2]) aligned = mt.apply_transform(data.xyz[:, :2], aff, sft) xieta_spacing = mu.estimate_spacing(template.xyz[:, :2]) # For gamma rather than the spacing in real space we want the difference between bins @@ -519,9 +561,7 @@ def from_aman(cls, name : str, meas_id : str, aman : AxisManager, template : Det spacing = np.array([xieta_spacing, xieta_spacing, gamma_spacing]) if not fake_gamma: - gscale, gsft = gamma_fit( - data.xyz[:, 2], template.xyz[template_msk, 2] - ) + gscale, gsft = gamma_fit(data.xyz[:, 2], template.xyz[template_msk, 2]) weights = mu.gen_weights( np.column_stack((aligned, gscale * data.xyz[:, 2] + gsft)), template.xyz[template_msk], @@ -537,10 +577,20 @@ def from_aman(cls, name : str, meas_id : str, aman : AxisManager, template : Det # ~1 sigma cut weights[weights < 0.61] = np.nan - return cls(name, meas_id, data, enc, weights, template, pointing_model, False, autofreeze, fake_gamma) - + return cls( + name, + meas_id, + data, + enc, + weights, + template, + pointing_model, + False, + autofreeze, + fake_gamma, + ) - def freeze(self, static : bool): + def freeze(self, static: bool): """ Save the current dynamic properties to the static fields. @@ -549,7 +599,7 @@ def freeze(self, static : bool): static : bool What to set `self.static` to after freezing. """ - self._data_pm_stat = self._data_pm_dyn + self._data_pm_stat = self._data_pm_dyn self._transform_stat = self._transform_dyn self._transformed_stat = self._transformed_dyn self._pm_transform_stat = self._pm_transform_dyn @@ -592,28 +642,28 @@ def pm_resid(self): 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.data_pm`) from each measurement. Detector locations and weights are combined on a per-detector basis, missing values should be filled with `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 @@ -650,23 +700,26 @@ class FocalPlaneCollection: resid : Float[np.ndarray, "ndet 3"] Residuals between `data` and `transformed`. """ - name : str - focal_planes : list[FocalPlane] - template : DetectorOffsets - static : bool - autofreeze : bool - pad : bool - fake_gamma : bool - data : DetectorOffsets = cast(DetectorOffsets, StaticOrCached("data")) - weights : Float[np.ndarray, "ndet"] = cast(Float[np.ndarray, "ndet"], StaticOrCached("weights")) - transform : Transform = cast(Transform, StaticOrCached("transform")) - transformed : DetectorOffsets = cast(DetectorOffsets, StaticOrCached("transformed")) + + name: str + focal_planes: list[FocalPlane] + template: DetectorOffsets + static: bool + autofreeze: bool + pad: bool + fake_gamma: bool + data: DetectorOffsets = cast(DetectorOffsets, StaticOrCached("data")) + weights: Float[np.ndarray, "ndet"] = cast( + Float[np.ndarray, "ndet"], StaticOrCached("weights") + ) + transform: Transform = cast(Transform, StaticOrCached("transform")) + transformed: DetectorOffsets = cast(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) + _weights_stat: Float[np.ndarray, "ndet"] = field(init=False) + _transform_stat: Transform = field(init=False) + _transformed_stat: DetectorOffsets = field(init=False) - def freeze(self, static : bool): + def freeze(self, static: bool): """ Save the current dynamic properties to the static fields. @@ -675,7 +728,7 @@ def freeze(self, static : bool): static : bool What to set `self.static` to after freezing. """ - self._data_stat = self._data_dyn + self._data_stat = self._data_dyn self._weights_stat = self._weights_dyn self._transform_stat = self._transform_dyn self._transformed_stat = self._transformed_dyn @@ -684,8 +737,10 @@ def freeze(self, static : bool): @property def _data_dyn(self) -> DetectorOffsets: to_ret = deepcopy(self.template) - dat_full = np.array([fp.data_pm.xyz * fp.weights[..., None] for fp in self. focal_planes]) - to_ret.xyz = np.nansum(dat_full, axis=-1)/self.weights[..., None] + dat_full = np.array( + [fp.data_pm.xyz * fp.weights[..., None] for fp in self.focal_planes] + ) + to_ret.xyz = np.nansum(dat_full, axis=-1) / self.weights[..., None] to_ret.center = None if self.autofreeze: self._data_stat = to_ret @@ -693,7 +748,7 @@ def _data_dyn(self) -> DetectorOffsets: @property def _weights_dyn(self) -> Float[np.ndarray, "ndet"]: - weights_full = np.array([fp.weights for fp in self. focal_planes]) + weights_full = np.array([fp.weights for fp in self.focal_planes]) to_ret = np.nansum(weights_full, axis=-1) if self.autofreeze: self._weights_stat = to_ret @@ -711,11 +766,12 @@ def _transformed_dyn(self) -> DetectorOffsets: def resid(self): return self.data.xyz - self.transformed.xyz + @dataclass class OpticsTube: """ An `OpticsTube` groups one or more `FocalPlaneCollection` instances - associated with the same optics tube and + 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 @@ -759,15 +815,16 @@ class OpticsTube: common mode removed. This quantity is not computed dynamically and is updated only through `remove_rx`. """ - name : str - focal_planes : list[FocalPlaneCollection] - wafer_slots : list[str] - static : bool - autofreeze : bool - allpad : bool - cm_transform : Transform = cast(Transform, StaticOrCached("cm_transform")) - cm_transform_norx : Transform = field(init=False) - _cm_transform_stat : Transform = field(init=False) + + name: str + focal_planes: list[FocalPlaneCollection] + wafer_slots: list[str] + static: bool + autofreeze: bool + allpad: bool + cm_transform: Transform = cast(Transform, StaticOrCached("cm_transform")) + cm_transform_norx: Transform = field(init=False) + _cm_transform_stat: Transform = field(init=False) def __getitem__(self, key): if key in self.wafer_slots: @@ -777,7 +834,7 @@ def __getitem__(self, key): return self.focal_planes[fp_names.index(key)] raise IndexError(f"Invalid key: {key}") - def freeze(self, static : bool): + def freeze(self, static: bool): """ Save the current dynamic properties to the static fields. @@ -791,7 +848,9 @@ def freeze(self, static : bool): @property def _cm_transform_dyn(self) -> Transform: - transforms = [fp.transform.affine for fp in self.focal_planes if fp.pad is False] + 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] allpad = False if len(transforms) == 0: @@ -808,18 +867,18 @@ def _cm_transform_dyn(self) -> Transform: self.allpad = allpad return to_ret - def remove_rx(self, rx_cm : Transform): + def remove_rx(self, rx_cm: Transform): """ Remove the receiver common-mode transform from the optics tube common-mode transform. - + Unlike `cm_transform`, the receiver-corrected transform is not a dynamic property and is updated only when this method is called. If `allpad=True`, no valid focal-plane collections are available for this optics tube and `cm_transform_norx` is set to the identity transform. - + Parameters ---------- rx_cm : Transform @@ -829,13 +888,14 @@ def remove_rx(self, rx_cm : Transform): if self.allpad: self.cm_transform_norx = Transform.identity() aff, sft = mt.decompose_transform( - self.cm_transform.affine, - self.cm_transform.shift, - rx_cm.affine, - rx_cm.shift, - ) + self.cm_transform.affine, + self.cm_transform.shift, + rx_cm.affine, + rx_cm.shift, + ) self.cm_transform_norx = Transform(sft, aff) + @dataclass class Receiver: """ @@ -879,12 +939,13 @@ class Receiver: Receiver-level common-mode transform derived from the common-mode transforms of all optics tubes containing valid data. """ - name : str - optics_tubes : list[OpticsTube] - static : bool - autofreeze : bool - cm_transform : Transform = cast(Transform, StaticOrCached("cm_transform")) - _cm_transform_stat : Transform = field(init=False) + + name: str + optics_tubes: list[OpticsTube] + static: bool + autofreeze: bool + cm_transform: Transform = cast(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] @@ -892,7 +953,7 @@ def __getitem__(self, key): return self.optics_tubes[ot_names.index(key)] raise IndexError(f"Invalid key: {key}") - def freeze(self, static : bool): + def freeze(self, static: bool): """ Save the current dynamic properties to the static fields. @@ -906,8 +967,12 @@ def freeze(self, static : bool): @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] + 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 @@ -923,7 +988,7 @@ def _cm_transform_dyn(self) -> Transform: 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 @@ -956,24 +1021,58 @@ class PointingSystem: This computes the chisq from the residuals for each `FocalPlaneCollection`, not the individual `FocalPlane` measurements. """ - era : epochs.Era - pointing_models : tuple[PointingModel, ...] - receivers : tuple[Receiver, ...] + + era: epochs.Era + pointing_models: tuple[PointingModel, ...] + receivers: tuple[Receiver, ...] def __post_init__(self): - if len(self.era.epochs) != len(self.pointing_models) or len(self.era.epochs) != len(self.receivers): + if len(self.era.epochs) != len(self.pointing_models) or len( + self.era.epochs + ) != len(self.receivers): raise ValueError("Should have one pointing model and receiver per epoch!") @property def chisq(self) -> float: - chisq = 0. + chisq = 0.0 for rx in self.receivers: for ot in rx.optics_tubes: for fp in ot.focal_planes: - chisq += np.nansum((fp.weights * fp.resid)**2).item() + chisq += np.nansum((fp.weights * fp.resid) ** 2).item() return chisq - def load_pm_from_mdb(self, mdb : ManifestDb): + def chisq_cm_prior( + self, sft_tol: float, rot_tol: float, scl_tol: float, shr_tol: float + ) -> float: + """ + Compute the chisq of the full pointing system but with strong priors on to reject + any common mode transformations across the receiver. + These are rectangular priors defined by a tolerance against the null space of the affine transform. + Any common mode out of tolerance will return a chisq of infinity. + + Parameters + ---------- + sft_tol : float + Tolerance in shift away from 0. + rot_tol : float + Tolerance in rotation away from 0. + scl_tol : float + Tolerance in scale away from 1. + shr_tol : float + Tolerance in shear away from 0. + """ + for rx in self.receivers: + if np.any(rx.cm_transform.shift > sft_tol): + return np.inf + if np.any(rx.cm_transform.rot > rot_tol): + return np.inf + if np.any(np.abs(rx.cm_transform.scale - 1) > scl_tol): + return np.inf + if np.any(rx.cm_transform.shear > shr_tol): + return np.inf + return self.chisq + + def load_pm_from_mdb(self, mdb: ManifestDb): """ Load pointing model parameters from a ManifestDb into the current era. @@ -1006,17 +1105,24 @@ def load_pm_from_mdb(self, mdb : ManifestDb): 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']: + 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 i, epoch in enumerate(self.era.epochs): matches = [] for interval in epoch.covers: - matches += [mdb.match({"obs:timestamp":interval.start}), mdb.match({"obs:timestamp":interval.stop-1})] + 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}, []) - pm_dict = {key : pm_aman[key] for key in pm_aman.keys()} + 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}, [] + ) + pm_dict = {key: pm_aman[key] for key in pm_aman.keys()} self.pointing_models[i].parameters = pm_dict From adf3c36a38807664c8214b2e8cb14f6b91b34303 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Tue, 25 Aug 2026 16:21:53 -0700 Subject: [PATCH 070/132] perf: cache load --- sotodlib/coords/fp_containers.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index ddae6b3f5..d3e867469 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -2,7 +2,7 @@ import logging import os from dataclasses import InitVar, dataclass, field -from functools import cached_property, partial +from functools import cached_property, partial, lru_cache from typing import Dict, List, Optional import h5py @@ -620,12 +620,13 @@ def load(cls, f, group="/"): return Receiver(ots, center, include_cm, list(valid_ids), transform) @classmethod + @lru_cache 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()} + return {grp: cls.load(f, grp) for grp in f.keys() if grp != "fake"} @property def focal_planes(self): From 52e59b0df808e110d9e4283dc9bb5ffaf6c2bb67 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Tue, 25 Aug 2026 16:22:09 -0700 Subject: [PATCH 071/132] fix: a bunch of random LF fixes --- .../site_pipeline/solve_pointing_model.py | 158 ++++++++++-------- 1 file changed, 91 insertions(+), 67 deletions(-) diff --git a/sotodlib/site_pipeline/solve_pointing_model.py b/sotodlib/site_pipeline/solve_pointing_model.py index 1622cc263..20aedbeb9 100644 --- a/sotodlib/site_pipeline/solve_pointing_model.py +++ b/sotodlib/site_pipeline/solve_pointing_model.py @@ -25,11 +25,15 @@ 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): @@ -159,6 +163,8 @@ def load_per_detector_data(config, t0, tf, no_downsample=False, return_all_dets= 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 @@ -182,20 +188,33 @@ def load_per_detector_data(config, t0, tf, no_downsample=False, return_all_dets= 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 = [], [], [], [], [], [] + 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) - weights = ufm.weights[:, 1] if which_weights == "r2" else ufm.weights[:, 0] - weights_dets.append(weights) + 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) - obs_index.append(np.repeat(i, len(ufm.weights))) - ot_list.append([this_OT.name] * len(data)) + 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) @@ -206,10 +225,10 @@ def load_per_detector_data(config, t0, tf, no_downsample=False, return_all_dets= 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) + det_boresight.append(det_pointing[wmsk]) - nom_data = [load_nom_focal_plane_full(config, t0, s) for s in stream_id_list] - all_det_ids, all_nom_det_array = map(np.concatenate, zip(*nom_data)) + 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) @@ -219,8 +238,6 @@ def load_per_detector_data(config, t0, tf, no_downsample=False, return_all_dets= #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] - weights_dets[weights_dets < config.get("weight_cutoff")] = 0.0 - obs_dets_fits[np.where(weights_dets == 0)] = np.nan mask = ~np.isnan(weights_dets) if not no_downsample: # Reduce detector counts for computation @@ -253,7 +270,7 @@ def build_data_aman(config, t0, tf, per_det = True, no_downsample=False, return_ filelist, obs_ufm_centers, weights_ufm, - nom_fm_centers, + nom_ufm_centers, obs_index, ot_list, ancil, @@ -334,19 +351,20 @@ def _init_fit_params(config, epochs): # Add independant params orig_pars = np.array(list(init_params.keys())) par_list = orig_pars.copy() - added_ots = [] + 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 in zip(ot_float_pars, [0, 0, 0, 1, 1]): + init_params[p] = d for epoch in epochs: indep_list = epoch["indep_list"] if float_ots: - for ot in np.unique(epoch["solver_aman"].ot_list): + 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 added_ots: - orig_pars = np.concatenate((orig_pars, ot_float_pars)) - par_list = np.concatenate((par_list, ot_float_pars)) - for p, d in zip(ot_float_pars, [0, 0, 0, 1, 1]): - init_params[p] = d - added_ots += [ot] 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] @@ -363,6 +381,7 @@ def _init_fit_params(config, epochs): 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): + import ipdb; ipdb.set_trace() raise ValueError(f"Epoch {epoch['name']} somehow has the wrong number of parameters!") par_count[pmsk] += 1 epoch["params"] = par_list[pmsk] @@ -397,6 +416,9 @@ def _apply_ot_float(xi_mod, eta_mod, solver_aman, params): 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] @@ -1239,7 +1261,7 @@ def plot_full_unmodeled_residuals(self): 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", dpi=350) + plt.savefig(f"{plot_dir}/{platform}_full_2D_Residuals_Roll{tag}.png") plt.close() @@ -1269,7 +1291,7 @@ def plot_full_unmodeled_residuals(self): 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", dpi=350) + plt.savefig(f"{plot_dir}/{platform}_full_2D_Residuals_El{tag}.png") plt.close() plt.figure(figsize=(7,5)) @@ -1298,7 +1320,7 @@ def plot_full_unmodeled_residuals(self): 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", dpi=350) + plt.savefig(f"{plot_dir}/{platform}_full_2D_Residuals_Az{tag}.png") plt.close() @@ -1328,7 +1350,7 @@ def plot_full_residuals_across_focalplane(self): 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", dpi=350) + plt.savefig(f"{plot_dir}/{platform}_full_FocalPlane_colored_FitResiduals{tag}.png") def plot_full_deltas_across_focalplane(self): platform = self.platform @@ -1355,7 +1377,7 @@ def plot_full_deltas_across_focalplane(self): 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", dpi=350) + plt.savefig(f"{plot_dir}/{platform}_full_FocalPlane_colored_FitDeltas{tag}.png") def plot_full_histogram(self): platform = self.platform @@ -1387,7 +1409,7 @@ def plot_full_histogram(self): plt.xlabel('arcmin') if self.save_figure: - plt.savefig(f"{plot_dir}/{platform}_full_Hist_Residuals{tag}.png", dpi=350) + plt.savefig(f"{plot_dir}/{platform}_full_Hist_Residuals{tag}.png") def plot_dets_in_these_obs(self): platform = self.platform @@ -1424,7 +1446,7 @@ def plot_dets_in_these_obs(self): plt.suptitle('Detectors hit in these observations') if self.save_figure: - plt.savefig(f"{plot_dir}/{platform}_dets_in_these_obs.png", dpi=350) + plt.savefig(f"{plot_dir}/{platform}_dets_in_these_obs.png") plt.close() def plot_modeled_fits(self): @@ -1445,10 +1467,11 @@ def plot_modeled_fits(self): else: ufm_list = self.ufms plotmask = np.where(weights) - nom_array = np.concatenate( - [load_nom_focal_plane_full(self.config, self.t0, ufm)[1] for ufm in ufm_list], - axis=0, - ) + 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 @@ -1492,14 +1515,15 @@ def plot_modeled_fits(self): label=f"Model, RMS = {rms}", vmax=65, ) - ax.scatter( - nom_array[:, 0] / DEG, - nom_array[:, 1] / DEG, - marker=".", - color="r", - alpha=0.2, - label="Nominal Center", - ) + 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) @@ -1518,9 +1542,9 @@ def plot_modeled_fits(self): etatoeta[:, 0] = eta_ref / DEG etatoeta[:, 1] = eta_model_fit / DEG ax.plot(xitoxi.T, etatoeta.T, "k", lw=0.4) - plt.tight_layout() + # plt.tight_layout() if self.save_figure: - plt.savefig(f"{plot_dir}/{platform}_model_fits{tag}.png", dpi=350) + plt.savefig(f"{plot_dir}/{platform}_model_fits{tag}.png") plt.close() @@ -1606,9 +1630,9 @@ def plot_ws0_modeled_fits(self): 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() + # plt.tight_layout() if self.save_figure: - plt.savefig(f"{plot_dir}/{platform}_ws0_model_fits{tag}.png", dpi=350) + plt.savefig(f"{plot_dir}/{platform}_ws0_model_fits{tag}.png") plt.close() @@ -1658,9 +1682,9 @@ def plot_template_space_fits_per_wafer(self): 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() + # plt.tight_layout() if self.save_figure: - plt.savefig(f"{plot_dir}/{platform}_unmodeled_fits_WS_elevation{tag}.png", dpi=350) + 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)) @@ -1688,8 +1712,8 @@ def plot_template_space_fits_per_wafer(self): 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", dpi=350) + # 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() @@ -1713,9 +1737,9 @@ def plot_template_space_fits_per_wafer(self): 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() + # plt.tight_layout() if self.save_figure: - plt.savefig(f"{plot_dir}/{platform}_unmodeled_fits_WS_corotator{tag}.png", dpi=350) + plt.savefig(f"{plot_dir}/{platform}_unmodeled_fits_WS_corotator{tag}.png") plt.close() @@ -1767,9 +1791,9 @@ def plot_template_space_fits_per_detector(self): 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() + # plt.tight_layout() if self.save_figure: - plt.savefig(f"{plot_dir}/{platform}_unmodeled_fits_WS_azimuth{tag}.png", dpi=350) + 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") @@ -1789,9 +1813,9 @@ def plot_template_space_fits_per_detector(self): 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() + # plt.tight_layout() if self.save_figure: - plt.savefig(f"{plot_dir}/{platform}_unmodeled_fits_WS_elevation{tag}.png", dpi=350) + plt.savefig(f"{plot_dir}/{platform}_unmodeled_fits_WS_elevation{tag}.png") plt.close() fig, ax = plt.subplots(figsize=(9, 6)) @@ -1817,9 +1841,9 @@ def plot_template_space_fits_per_detector(self): 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() + # plt.tight_layout() if self.save_figure: - plt.savefig(f"{plot_dir}/{platform}_unmodeled_fits_WS_roll{tag}.png", dpi=350) + plt.savefig(f"{plot_dir}/{platform}_unmodeled_fits_WS_roll{tag}.png") plt.close() if "lat" in pm_version: @@ -1842,9 +1866,9 @@ def plot_template_space_fits_per_detector(self): 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() + # plt.tight_layout() if self.save_figure: - plt.savefig(f"{plot_dir}/{platform}_unmodeled_fits_WS_corotator{tag}.png", dpi=350) + plt.savefig(f"{plot_dir}/{platform}_unmodeled_fits_WS_corotator{tag}.png") plt.close() def plot_residuals_vs_ancil(self): @@ -1934,9 +1958,9 @@ def plot_residuals_vs_ancil(self): 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() + # plt.tight_layout() if self.save_figure: - plt.savefig(f"{plot_dir}/{platform}_residuals_vs_ancillary{tag}.png", dpi=350) + plt.savefig(f"{plot_dir}/{platform}_residuals_vs_ancillary{tag}.png") plt.close() def plot_total_residuals(self): @@ -2038,7 +2062,7 @@ def plot_total_residuals(self): 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", dpi=350) + plt.savefig(f"{plot_dir}/{platform}_total_residuals{tag}.png") plt.close() else: # Plot first fit iteration residuals only @@ -2063,7 +2087,7 @@ def plot_total_residuals(self): plt.title("Fit Residuals") plt.legend(loc=2) if self.save_figure: - plt.savefig(f"{plot_dir}/{platform}_total_residuals{tag}.png", dpi=350) + plt.savefig(f"{plot_dir}/{platform}_total_residuals{tag}.png") plt.close() @@ -2103,7 +2127,7 @@ def plot_residuals_histograms(self): plt.title(append) plt.legend() if self.save_figure: - plt.savefig(f"{plot_dir}/{platform}_residuals_hists{tag}.png", dpi=350) + plt.savefig(f"{plot_dir}/{platform}_residuals_hists{tag}.png") plt.close() def plot_xieta_residuals(self): @@ -2158,9 +2182,9 @@ def plot_xieta_residuals(self): 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() + # plt.tight_layout() if self.save_figure: - plt.savefig(f"{plot_dir}/{platform}_xieta_residuals{tag}.png", dpi=350) + plt.savefig(f"{plot_dir}/{platform}_xieta_residuals{tag}.png") plt.close() @@ -2216,9 +2240,9 @@ def plot_xieta_cross_residuals(self): 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() + # plt.tight_layout() if self.save_figure: - plt.savefig(f"{plot_dir}/{platform}_xieta_cross_residuals{tag}.png", dpi=350) + plt.savefig(f"{plot_dir}/{platform}_xieta_cross_residuals{tag}.png") plt.close() def plot_fit_correlation_matrix(self): @@ -2252,7 +2276,7 @@ def plot_fit_correlation_matrix(self): 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", dpi=350) + plt.savefig(f"{plot_dir}/{platform}_correlation_matrix{tag}.png") plt.close() ############ From 5eb0e29f341237eeb50aab49114069016eb98577 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Thu, 27 Aug 2026 21:45:09 -0700 Subject: [PATCH 072/132] fix: load robust template --- sotodlib/coords/fp_containers.py | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index d3e867469..d59549a0d 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -641,10 +641,10 @@ def ot_dict(self): @property def lims(self): - xmax = np.max([np.nanmax(fp.template.fp[:, 0]) for fp in self.focal_planes]) - xmin = np.min([np.nanmin(fp.template.fp[:, 0]) for fp in self.focal_planes]) - ymax = np.max([np.nanmax(fp.template.fp[:, 1]) for fp in self.focal_planes]) - ymin = np.min([np.nanmin(fp.template.fp[:, 1]) for fp in self.focal_planes]) + xmax = np.max([np.nanmax(fp.template_fp[:, 0]) for fp in self.focal_planes]) + xmin = np.min([np.nanmin(fp.template_fp[:, 0]) for fp in self.focal_planes]) + ymax = np.max([np.nanmax(fp.template_fp[:, 1]) for fp in self.focal_planes]) + ymin = np.min([np.nanmin(fp.template_fp[:, 1]) for fp in self.focal_planes]) return (xmin, xmax), (ymin, ymax) @property @@ -764,7 +764,7 @@ def plot_by_gamma(focal_plane, plot_dir): 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 + 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 @@ -853,8 +853,8 @@ def plot_receiver(receiver, plot_dir): continue diff = fp.diff * 180 * 60 * 60 / np.pi cf = axs[nax * i + 0].scatter( - fp.template.fp[msk, 0], - fp.template.fp[msk, 1], + fp.template_fp[msk, 0], + fp.template_fp[msk, 1], c = diff[msk, 0], marker=".", vmin=-1 * max_diff, @@ -863,8 +863,8 @@ def plot_receiver(receiver, plot_dir): alpha=.5 ) cf = axs[nax * i + 1].scatter( - fp.template.fp[msk, 0], - fp.template.fp[msk, 1], + fp.template_fp[msk, 0], + fp.template_fp[msk, 1], c = diff[msk, 1], marker=".", vmin=-1 * max_diff, @@ -874,8 +874,8 @@ def plot_receiver(receiver, plot_dir): ) if fp.have_gamma: cf = axs[nax * i + 2].scatter( - fp.template.fp[msk, 0], - fp.template.fp[msk, 1], + fp.template_fp[msk, 0], + fp.template_fp[msk, 1], c = diff[msk, 2], marker=".", vmin=-1 * max_diff, From d3d90556bb7f97a8623a985bd6327b1f80e4cfc4 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Thu, 27 Aug 2026 21:45:26 -0700 Subject: [PATCH 073/132] fix: some padding fixes --- sotodlib/site_pipeline/finalize_focal_plane.py | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/sotodlib/site_pipeline/finalize_focal_plane.py b/sotodlib/site_pipeline/finalize_focal_plane.py index 6ae759ef1..71523ede5 100644 --- a/sotodlib/site_pipeline/finalize_focal_plane.py +++ b/sotodlib/site_pipeline/finalize_focal_plane.py @@ -68,8 +68,8 @@ def _create_db(filename, per_obs, obs_ids, start_time, stop_time): def _avg_focalplane(full_fp, tot_weight, dists): - if np.sum(np.isfinite(dists)) > 5: - msk = (dists - np.nanmedian(dists)) > 3 * np.nanstd(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 @@ -249,12 +249,10 @@ def _load_ctx(config, obsfile): failed = [] run = [] if per_obs and not config.get("overwrite", False): - run = np.genfromtxt(obsfile) + run = np.genfromtxt(obsfile, dtype=str) + obs_ids = np.setdiff1d(obs_ids, run) for obs_id in tqdm(obs_ids): - if obs_id in run: - logger.debug("%s has already been run", obs_id) - continue roll = ctx.obsdb.get(obs_id)["roll_center"] if roll is None: continue @@ -770,7 +768,7 @@ def main(): 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 From 04e5159fcb4cafb9c2c197bbdfbe2db8aa12bdbf Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Thu, 27 Aug 2026 21:46:09 -0700 Subject: [PATCH 074/132] fix: some minor fitting improvements --- .../site_pipeline/solve_pointing_model.py | 81 ++++++++++++------- 1 file changed, 51 insertions(+), 30 deletions(-) diff --git a/sotodlib/site_pipeline/solve_pointing_model.py b/sotodlib/site_pipeline/solve_pointing_model.py index 20aedbeb9..4303eb670 100644 --- a/sotodlib/site_pipeline/solve_pointing_model.py +++ b/sotodlib/site_pipeline/solve_pointing_model.py @@ -1,6 +1,5 @@ import os -import pickle -import math +import sys import h5py import argparse import yaml @@ -10,7 +9,6 @@ import lmfit from lmfit import minimize, Parameters, fit_report -import time import shutil import matplotlib @@ -336,6 +334,7 @@ def build_data_aman(config, t0, tf, per_det = True, no_downsample=False, return_ 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 @@ -347,6 +346,8 @@ def _init_fit_params(config, epochs): 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())) @@ -357,20 +358,26 @@ def _init_fit_params(config, epochs): 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 in zip(ot_float_pars, [0, 0, 0, 1, 1]): + 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: @@ -381,7 +388,6 @@ def _init_fit_params(config, epochs): 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): - import ipdb; ipdb.set_trace() raise ValueError(f"Epoch {epoch['name']} somehow has the wrong number of parameters!") par_count[pmsk] += 1 epoch["params"] = par_list[pmsk] @@ -393,7 +399,7 @@ def _init_fit_params(config, epochs): 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) + 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: @@ -404,14 +410,16 @@ def _init_fit_params(config, epochs): def _apply_ot_float(xi_mod, eta_mod, solver_aman, params): # For simplicity we do the floating of OTs to just the model - # We are recomputing information that should just be cached here... - # TODO: Fix that 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 np.unique(solver_aman.ot_list)]) + 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(np.unique(solver_aman.ot_list)): + 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 @@ -451,29 +459,26 @@ def objective_model_func_lmfit( 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 (dist * np.sqrt(weights_array)) + 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": - 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) - all_residuals.append(res) return np.concatenate(all_residuals) - - else: - chisq = 0 - 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) - chisq += np.nansum(res**2) - - return chisq + return chisq def model_template_xieta(params, pm_version, aman): @@ -539,6 +544,7 @@ def calc_RMS_and_residuals(modeled_fits, model_reference, weights, use_inds=None 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 @@ -744,7 +750,7 @@ def main(config_path: str): 'Not recognized xieta_model. \ Only "measured" or "template" accepted' ) - exit + sys.exit() epochs = config.get("epochs") for epoch in epochs: @@ -754,7 +760,7 @@ def main(config_path: str): 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: @@ -844,6 +850,20 @@ def main(config_path: str): # 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 @@ -991,7 +1011,7 @@ def main(config_path: str): 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.0 + epoch["solver_aman"].weights[bad_fit_inds] = 0 epoch["solver_aman"].wrap('bad_fit_inds', bad_fit_inds) if tot_bad == 0: @@ -999,7 +1019,7 @@ def main(config_path: str): if tot_bad > 0: model_solved_params = minimize( objective_model_func_lmfit_joint, - fit_params, + model_solved_params.params, method=fit_method, nan_policy="omit", args=(pm_version, epochs, xieta_model, fit_method, use_weights), @@ -1124,12 +1144,13 @@ def main(config_path: str): 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 np.unique(solver_aman.ot_list): + 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 From 1ea23296d9addbedbd5946c007de87adbf6d13f1 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Fri, 28 Aug 2026 23:01:30 -0700 Subject: [PATCH 075/132] fix: skip missing entried --- sotodlib/coords/fp_containers.py | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index d59549a0d..c1135f44a 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -172,7 +172,7 @@ def __post_init__(self): def template_fp(self): if self.template is not None: return self.template.fp - logger.warning( + logger.debug( "No template in focal plane %s, reconstructing from transformed. This will be wrong with_cm is set wrong!", self.stream_id, ) @@ -556,11 +556,16 @@ def load(cls, group, include_cm=None): 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 - ] + fps = [] + for grp in group.keys(): + if "transform" in grp: + continue + try: + fp = FocalPlane.load(group[grp], include_cm) + except: + logger.warning("Couldn't load focal plane from %s", grp) + continue + fps += [fp] return OpticsTube(name, center, transform, transform_fullcm, fps) From d503178965ad001618bf4e53e703a6015b9e5fa4 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Fri, 4 Sep 2026 17:14:13 -0400 Subject: [PATCH 076/132] feat: add epoch lookup --- sotodlib/utils/epochs.py | 60 ++++++++++++++++++++++++++++++---------- 1 file changed, 45 insertions(+), 15 deletions(-) diff --git a/sotodlib/utils/epochs.py b/sotodlib/utils/epochs.py index 6139397f7..6beb92bb5 100644 --- a/sotodlib/utils/epochs.py +++ b/sotodlib/utils/epochs.py @@ -1,11 +1,12 @@ +import operator import re +from bisect import bisect_right from copy import deepcopy from dataclasses import dataclass, field from functools import reduce -import operator from typing import Any, Literal, Optional, Self, cast, overload -import numpy as np +import numpy as np import yaml from deepdiff import DeepDiff @@ -265,6 +266,7 @@ class Era: 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: @@ -272,9 +274,16 @@ def __post_init__(self): 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__: + if (name == "epochs" or name == "strict") and ( + "_internal" in self.__dict__ or "_lookup" in self.__dict__ + ): self.__post_init__() return super().__setattr__(name, value) @@ -297,6 +306,29 @@ def check_data(self, field: str, strict: bool = True) -> 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._lookup[j][2] + return None + @dataclass class Calendar: @@ -313,16 +345,15 @@ class Calendar: orphan_epochs: list[Epoch] @overload - def find_tagged(self, tag: str, search_in: Literal["eras"]) -> list[Era]: - ... + 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]: - ... + 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"] + ) -> list[Interval]: ... def find_tagged( self, tag: str, search_in: Literal["intervals", "epochs", "eras"] @@ -356,18 +387,17 @@ def find_tagged( raise ValueError(f"Invalid search_in: {search_in}") @overload - def find_data_field(self, field: str, search_in: Literal["eras"]) -> list[Era]: - ... + 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]: - ... + 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]: - ... + ) -> list[Interval]: ... def find_data_field( self, field: str, search_in: Literal["intervals", "epochs", "eras"] From b92b46328c361fde72ef8deb8dc0c02cfaff1618 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Fri, 4 Sep 2026 17:14:56 -0400 Subject: [PATCH 077/132] feat: add init function and lookup --- sotodlib/coords/fp_containers.py | 164 +++++++++++++++++++++++++++++-- 1 file changed, 154 insertions(+), 10 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 601e120df..ed5a253b1 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -10,22 +10,24 @@ # TODO: Reprs from __future__ import annotations -from typing import Optional, Any, cast + +from argparse import Namespace +from copy import deepcopy from dataclasses import dataclass, field -from jaxtyping import Float, Shaped -import numpy as np +from functools import cached_property +from typing import Any, Optional, Self, cast + import megham.transform as mt import megham.utils as mu -from functools import cached_property -from copy import deepcopy +import numpy as np +from jaxtyping import Float, Shaped from scipy.optimize import minimize -from sotodlib.coords.pointing_model import apply_pointing_model from so3g.proj import quat +from sotodlib.coords.pointing_model import apply_pointing_model, param_defaults from sotodlib.core import AxisManager, IndexAxis -from sotodlib.utils import epochs +from sotodlib.core.metadata import ManifestDb, MetadataSpec from sotodlib.io.metadata import SuperLoader -from sotodlib.core.metadata import MetadataSpec -from sotodlib.core.metadata import ManifestDb +from sotodlib.utils import epochs def gamma_fit(src, dst): @@ -122,6 +124,9 @@ class PointingModel: 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 @@ -131,6 +136,7 @@ class PointingModel: model and assume a zero-roll boresight solution. """ + epoch: str parameters: dict force_zero_roll: bool @@ -323,6 +329,14 @@ def __setattr__(self, name: str, value: Any, /) -> None: self.__dict__.pop("ancil", None) return super().__setattr__(name, value) + @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 xi(self): if self.coordsys != "xieta": @@ -821,7 +835,6 @@ class OpticsTube: wafer_slots: list[str] static: bool autofreeze: bool - allpad: bool cm_transform: Transform = cast(Transform, StaticOrCached("cm_transform")) cm_transform_norx: Transform = field(init=False) _cm_transform_stat: Transform = field(init=False) @@ -846,6 +859,12 @@ def freeze(self, static: bool): self._cm_transform_stat = self._cm_transform_dyn self.static = static + @property + def allpad(self): + if len(fps) == 0: + return True + return np.all([fp.pad for fp in self.focal_planes]) + @property def _cm_transform_dyn(self) -> Transform: transforms = [ @@ -927,6 +946,9 @@ class Receiver: 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 @@ -941,6 +963,7 @@ class Receiver: """ name: str + epoch: str optics_tubes: list[OpticsTube] static: bool autofreeze: bool @@ -1072,6 +1095,37 @@ def chisq_cm_prior( return np.inf return self.chisq + def search( + self, field: str, timestamp: float + ) -> Optional[PointingModel | Receiver]: + """ + Get the first object associated with a specifc timestamp. + + Parameters + ---------- + field: str + 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 = 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 load_pm_from_mdb(self, mdb: ManifestDb): """ Load pointing model parameters from a ManifestDb into the current era. @@ -1126,3 +1180,93 @@ def load_pm_from_mdb(self, mdb: ManifestDb): ) pm_dict = {key: pm_aman[key] for key in pm_aman.keys()} self.pointing_models[i].parameters = pm_dict + + @classmethod + def empty(cls, era: epochs.Era, cfg: Namespace) -> 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. + + 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 receiver or pointing model groups contain overlapping epochs. + If a receiver or pointing model group contains an unknown epoch. + """ + if not era.check_data("ws_mapping", True): + raise ValueError( + "Era is either missing or has inconsistent values for ws_mapping" + ) + rxs = [] + pms = [] + for epoch in era.epochs: + pms += [PointingModel(epoch.name, {}, cfg.force_zero_roll)] + 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"), + 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): + 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 + 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") + pms = _group_epochs(pms, cfg.pm_group, "pointing model") + + for pm in pms: + pm_ver = cfg.pm_ver_override.get(pm.epoch, cfg.pm_ver) + pars = deepcopy(param_defaults[pm_ver]) + pars["version"] = pm_ver + pm.pars = pars + + return cls(era, tuple(pms), tuple(rxs)) From 6b24f98681f4c1d0807c485b7af8a870156e4e06 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Fri, 4 Sep 2026 18:42:23 -0400 Subject: [PATCH 078/132] feat: expose joint pm parameters --- sotodlib/coords/fp_containers.py | 103 +++++++++++++++++++++++++------ sotodlib/utils/epochs.py | 2 +- 2 files changed, 85 insertions(+), 20 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index ed5a253b1..7101e68f7 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -15,12 +15,12 @@ from copy import deepcopy from dataclasses import dataclass, field from functools import cached_property -from typing import Any, Optional, Self, cast +from typing import Any, Literal, Optional, Self, cast, overload import megham.transform as mt import megham.utils as mu import numpy as np -from jaxtyping import Float, Shaped +from jaxtyping import Float, Integer, Shaped from scipy.optimize import minimize from so3g.proj import quat from sotodlib.coords.pointing_model import apply_pointing_model, param_defaults @@ -861,7 +861,7 @@ def freeze(self, static: bool): @property def allpad(self): - if len(fps) == 0: + if len(self.focal_planes) == 0: return True return np.all([fp.pad for fp in self.focal_planes]) @@ -871,9 +871,7 @@ def _cm_transform_dyn(self) -> Transform: 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] - allpad = False if len(transforms) == 0: - allpad = True iden = Transform.identity() cm_shift, cm_aff = iden.shift, iden.affine elif len(transforms) == 1: @@ -883,7 +881,6 @@ def _cm_transform_dyn(self) -> Transform: to_ret = Transform(cm_shift, cm_aff) if self.autofreeze: self._cm_transform_stat = to_ret - self.allpad = allpad return to_ret def remove_rx(self, rx_cm: Transform): @@ -1039,6 +1036,14 @@ class PointingSystem: Pointing model associated with each epoch. receivers : tuple[Receiver, ...] Receiver and focal-plane data associated with each epoch. + parameter_names : tuple[str, ...] + The names of all pointing model parameters. + Names with parenthesis apply only to the epochs within the parenthesis. + Names without parenthesis apply to all other epochs. + parameter_map : tuple[Integer[np.ndarray, "?npar_mapped"], ...] + Mapping between parameters and what pointing models to apply them to. + parameters : Float[np.ndarray, "npar"] + The current values of the parameters. chisq : float The chisq of the current system. This computes the chisq from the residuals for each `FocalPlaneCollection`, @@ -1048,12 +1053,29 @@ class PointingSystem: era: epochs.Era pointing_models: tuple[PointingModel, ...] receivers: tuple[Receiver, ...] + parameter_names: tuple[str, ...] + parameter_map: tuple[Integer[np.ndarray, "?npar"], ...] def __post_init__(self): - if len(self.era.epochs) != len(self.pointing_models) or len( - self.era.epochs - ) != len(self.receivers): - raise ValueError("Should have one pointing model and receiver per epoch!") + # Force consistancy + self.update_parameters(self.parameters) + + @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"]): + for val, par, par_map in zip( + new_pars, self.parameter_names, self.parameter_map + ): + name = par.split("(")[0] + for idx in par_map: + self.pointing_models[idx].parameters[name] = val @property def chisq(self) -> float: @@ -1095,15 +1117,25 @@ def chisq_cm_prior( return np.inf return self.chisq + @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: str, timestamp: float + self, field: Literal["pointing_models", "receivers"], timestamp: float ) -> Optional[PointingModel | Receiver]: """ Get the first object associated with a specifc timestamp. Parameters ---------- - field: str + field: Literal["pointing_models", "receivers"] The field to search in. Valid options are: "receivers" and "pointing_models". timestamp : float @@ -1118,7 +1150,7 @@ def search( if field not in ["pointing_models", "receivers"]: raise ValueError(f"Invalud field to search in: {field}.") dat = getattr(self, field) - epoch = era.find_epoch(timestamp) + epoch = self.era.find_epoch(timestamp) if epoch is None: return None hits = [d for d in dat if epoch.name in d.epoch] @@ -1144,6 +1176,8 @@ def load_pm_from_mdb(self, mdb: ManifestDb): 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 ---------- @@ -1162,7 +1196,7 @@ def load_pm_from_mdb(self, mdb: ManifestDb): 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 i, epoch in enumerate(self.era.epochs): + for epoch in self.era.epochs: matches = [] for interval in epoch.covers: matches += [ @@ -1179,7 +1213,14 @@ def load_pm_from_mdb(self, mdb: ManifestDb): mspec, {"obs:timestamp": epoch.covers[0].start}, [] ) pm_dict = {key: pm_aman[key] for key in pm_aman.keys()} - self.pointing_models[i].parameters = pm_dict + 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) -> Self: @@ -1210,8 +1251,9 @@ def empty(cls, era: epochs.Era, cfg: Namespace) -> Self: ------ ValueError If `era` has missing or inconsistent `ws_mapping` data. - If receiver or pointing model groups contain overlapping epochs. - If a receiver or pointing model group contains an unknown epoch. + 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( @@ -1263,10 +1305,33 @@ def _group_epochs(dat, groups, desc): rxs = _group_epochs(rxs, cfg.rx_groups, "receiver") pms = _group_epochs(pms, cfg.pm_group, "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]) + par_names += list(pars.keys()) pars["version"] = pm_ver pm.pars = pars - - return cls(era, tuple(pms), tuple(rxs)) + par_names = np.unique(par_names).tolist() + par_map = [np.arange(len(pms), dtype=int).tolist()] * len(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), par_names, par_map) diff --git a/sotodlib/utils/epochs.py b/sotodlib/utils/epochs.py index 6beb92bb5..b5edf3000 100644 --- a/sotodlib/utils/epochs.py +++ b/sotodlib/utils/epochs.py @@ -325,7 +325,7 @@ def find_epoch(self, timestamp: float) -> Optional[Epoch]: """ starts = [x[0] for x in self._lookup] j = bisect_right(starts, timestamp) - 1 - if j >= 0 and timestamp <= self._lookup[j][1]: + if j >= 0 and timestamp < self._lookup[j][1]: return self._lookup[j][2] return None From 9ee2a6421298043432b6eac82aa0d92827f2e31a Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Sat, 12 Sep 2026 21:26:35 -0700 Subject: [PATCH 079/132] feat: add fast batch update func --- sotodlib/site_pipeline/jobdb.py | 39 +++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) 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 From f8b1a1ccdd3e0e407aec9b70428baed4f88d5a47 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Wed, 16 Sep 2026 18:28:21 -0400 Subject: [PATCH 080/132] feat: allow passing in a loaded file string --- sotodlib/utils/epochs.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/sotodlib/utils/epochs.py b/sotodlib/utils/epochs.py index b5edf3000..088123a0b 100644 --- a/sotodlib/utils/epochs.py +++ b/sotodlib/utils/epochs.py @@ -1,3 +1,4 @@ +import os import operator import re from bisect import bisect_right @@ -576,8 +577,11 @@ def get_membership(self, interval: str) -> list[tuple[Era, Epoch]]: @classmethod def load(cls, fpath: str) -> Self: - with open(fpath, "r") as f: - cfg = yaml.safe_load(f) + if os.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") From dc66c4143627d3cfa2b4b62cd880c243b99dfabb Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Wed, 16 Sep 2026 18:29:34 -0400 Subject: [PATCH 081/132] feat: first IO pass --- sotodlib/coords/fp_containers.py | 757 ++++++++++++++++++++++++++++++- 1 file changed, 751 insertions(+), 6 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 7101e68f7..c41db7868 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -11,12 +11,14 @@ from __future__ import annotations +import logging from argparse import Namespace from copy import deepcopy from dataclasses import dataclass, field from functools import cached_property -from typing import Any, Literal, Optional, Self, cast, overload +from typing import Any, Iterable, Literal, Optional, Self, cast, overload +import h5py import megham.transform as mt import megham.utils as mu import numpy as np @@ -24,11 +26,34 @@ 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 +from sotodlib.core import AxisManager, IndexAxis, metadata from sotodlib.core.metadata import ManifestDb, MetadataSpec -from sotodlib.io.metadata import SuperLoader +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"), +} + +logger = logging.getLogger("finalize_staic_pointing") + + +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 + + +def _create_group(f, path, overwrite=True): + if path in f: + if not overwrite: + raise ValueError(f"HDF5 path already exists: {path}") + del f[path] + return f.create_group(path) + def gamma_fit(src, dst): """ @@ -211,6 +236,56 @@ def apply_det( to_ret.xyz = np.column_stack((xi, eta, gamma)) return to_ret + 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} + ) + + 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) -> 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. + + Returns + ------- + PointingModel + The loaded pointing model. + """ + group = f[path] + parameters = AxisManager.load(f, f"{path}/parameters") + parameters = {name: parameters[name] for name in parameters._fields} + + return cls( + epoch=cast(str, group.attrs["epoch"]), + parameters=parameters, + force_zero_roll=cast(bool, group.attrs["force_zero_roll"]), + ) + @dataclass class Transform: @@ -280,6 +355,48 @@ def shear(self): 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 = f.create_group(path) + group.create_dataset("shift", data=self.shift) + group.create_dataset("affine", data=self.affine) + + @classmethod + def load(cls, f: h5py.File, path: str) -> Self: + """ + Load a transform from an HDF5 group. + + Parameters + ---------- + f : h5py.File + Open HDF5 file. + path : str + Path within the HDF5 file containing the transform. + + 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 DetectorOffsets: @@ -290,7 +407,7 @@ class DetectorOffsets: Attributes ---------- - xyz : Float[np.ndarray, "3 ndet"] + xyz : Float[np.ndarray, "ndet 3"] The `x` axis of the detector offsets. For `xieta` this is `xi`. For `horizon` this is `az`. @@ -382,6 +499,91 @@ def ancil(self): ancil.wrap("boresight_enc", -1 * np.rad2deg(self.roll)) # for SATs return ancil + 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), + ] + + 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(data), + f, + path, + overwrite=overwrite, + ) + _add_attrs( + f[path], + { + "coordsys": self.coordsys, + "center": self.center, + }, + ) + + @classmethod + 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: @@ -651,6 +853,130 @@ def resid(self): def pm_resid(self): return self.data_pm.xyz - self.pm_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, + }, + ) + + 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) + + if "_data_pm_stat" in self.__dict__: + self._data_pm_stat.save(f, f"{path}/data_pm", 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 + ) + + @classmethod + def load( + cls, + f: h5py.File, + path: str, + template: DetectorOffsets, + 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. + 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"]) + + 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, + template=template, + 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 "data_pm" in group: + fp._data_pm_stat = DetectorOffsets.load(f, f"{path}/data_pm") + 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") + + return fp + @dataclass class FocalPlaneCollection: @@ -780,6 +1106,132 @@ def _transformed_dyn(self) -> DetectorOffsets: def resid(self): return self.data.xyz - self.transformed.xyz + 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( + 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) + for fp in self.focal_planes: + fp.save( + f, + f"{path}/{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, f: h5py.File, path: str, pointing_models: tuple[PointingModel, ...] + ) -> 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. + + Returns + ------- + FocalPlaneCollection + The loaded focal plane collection. + """ + template = DetectorOffsets.load( + f, + f"{path}/template", + ) + group = cast(h5py.Group, f[path]) + + focal_planes = [] + for name in group: + if name in {"template", "data", "weights", "transform", "transformed"}: + continue + focal_planes.append( + FocalPlane.load( + f, + f"{path}/{name}", + template=template, + pointing_models=pointing_models, + ) + ) + + collection = cls( + name=cast(str, group.attrs["name"]), + focal_planes=focal_planes, + template=template, + 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"]), + ) + + 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 "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", + ) + + return collection + @dataclass class OpticsTube: @@ -911,6 +1363,90 @@ def remove_rx(self, rx_cm: Transform): ) self.cm_transform_norx = Transform(sft, aff) + 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": np.asarray(self.wafer_slots), + "static": self.static, + "autofreeze": self.autofreeze, + }, + ) + for fp in self.focal_planes: + fp.save(f, f"{path}/{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" in self.__dict__: + self.cm_transform_norx.save(f, f"{path}/cm_transform_norx") + + @classmethod + def load( + cls, f: h5py.File, path: str, pointing_models: tuple[PointingModel, ...] + ) -> 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. + """ + 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 + ) + ) + tube = cls( + name=cast(str, group.attrs["name"]), + focal_planes=focal_planes, + wafer_slots=list(np.asarray(group.attrs["wafer_slots"])), + static=cast(bool, group.attrs["static"]), + autofreeze=cast(bool, group.attrs["autofreeze"]), + ) + + group = cast(h5py.Group, f[path]) + if "cm_transform" in group: + tube._cm_transform_stat = Transform.load(f, f"{path}/cm_transform") + tube.cm_transform_norx = Transform.load(f, f"{path}/cm_transform_norx") + + return tube + @dataclass class Receiver: @@ -1017,6 +1553,88 @@ def remove_rx_all(self): 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( + group, + { + "name": self.name, + "epoch": self.epoch, + "static": self.static, + "autofreeze": self.autofreeze, + }, + ) + 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, f"{path}/{ot.name}", pointing_models, overwrite=overwrite) + + @classmethod + 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"]) + optics_tubes = [ + OpticsTube.load(f, f"{path}/{ot_name}", pointing_models) + for ot_name in group.keys() + if ot_name != "cm_transform" + ] + + receiver = cls( + name=name, + epoch=epoch, + optics_tubes=optics_tubes, + static=static, + autofreeze=autofreeze, + ) + + if "cm_transform" in group: + receiver._cm_transform_stat = Transform.load(f, f"{path}/cm_transform") + return receiver + @dataclass class PointingSystem: @@ -1042,6 +1660,10 @@ class PointingSystem: Names without parenthesis apply to all other epochs. parameter_map : tuple[Integer[np.ndarray, "?npar_mapped"], ...] Mapping between parameters and what pointing models to apply them to. + config_str : str + A serialized configuration yaml string. + calender_str : str + A serialized calendar yaml string. parameters : Float[np.ndarray, "npar"] The current values of the parameters. chisq : float @@ -1055,6 +1677,8 @@ class PointingSystem: receivers: tuple[Receiver, ...] parameter_names: tuple[str, ...] parameter_map: tuple[Integer[np.ndarray, "?npar"], ...] + config_str: str + calender_str: str def __post_init__(self): # Force consistancy @@ -1223,7 +1847,9 @@ def load_pm_from_mdb(self, mdb: ManifestDb): self.update_parameters(self.parameters) @classmethod - def empty(cls, era: epochs.Era, cfg: Namespace) -> Self: + def empty( + cls, era: epochs.Era, cfg: Namespace, config_str: str, calender_str: str + ) -> Self: """ Create an empty pointing system from an observing era. @@ -1240,6 +1866,10 @@ def empty(cls, era: epochs.Era, cfg: Namespace) -> Self: cfg : Namespace Configuration containing the receiver name, epoch groups, pointing model settings, and focal plane options. + config_str : str + A serialized configuration yaml string. + calender_str : str + A serialized calendar yaml string. Returns ------- @@ -1334,4 +1964,119 @@ def _group_epochs(dat, groups, desc): 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), par_names, par_map) + return cls( + era, tuple(pms), tuple(rxs), par_names, par_map, config_str, calender_str + ) + + 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, + { + "config_str": self.config_str, + "calender_str": self.calender_str, + "era": self.era.name, + }, + ) + _ = _create_group(f, f"{path}/pointing_models", 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 = _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] + config_str = cast(str, group.attrs["config_str"]) + calender_str = cast(str, group.attrs["config_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"]) + ) + + 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()) + ) + + pm_group = cast(h5py.Group, f[f"{path}/pointing_models"]) + pointing_models = tuple( + PointingModel.load(f, f"{path}/pointing_models/{name}") + for name in sorted(pm_group.keys()) + ) + + rx_group = cast(h5py.Group, f[f"{path}/receivers"]) + receivers = tuple( + Receiver.load(f, name, pointing_models) for name in sorted(rx_group.keys()) + ) + + return cls( + era=era, + pointing_models=pointing_models, + receivers=receivers, + parameter_names=parameter_names, + parameter_map=parameter_map, + config_str=config_str, + calender_str=calender_str, + ) From 93012686fb93d9b7d724d9e5050eb8d01f70fb21 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Thu, 17 Sep 2026 11:24:18 -0400 Subject: [PATCH 082/132] feat: add recursive config utils --- sotodlib/utils/config.py | 160 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 160 insertions(+) create mode 100644 sotodlib/utils/config.py 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 + From 143551ca43b3d3b84625900e530b42ad1b630e35 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Thu, 17 Sep 2026 17:03:24 -0400 Subject: [PATCH 083/132] fix: path.isfile --- sotodlib/utils/epochs.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sotodlib/utils/epochs.py b/sotodlib/utils/epochs.py index 088123a0b..bff29f83b 100644 --- a/sotodlib/utils/epochs.py +++ b/sotodlib/utils/epochs.py @@ -577,7 +577,7 @@ def get_membership(self, interval: str) -> list[tuple[Era, Epoch]]: @classmethod def load(cls, fpath: str) -> Self: - if os.isfile(fpath): + if os.path.isfile(fpath): with open(fpath, "r") as f: cfg = yaml.safe_load(f) else: From cf0a0f8a8dd3f56d97eefb905b93be98f42b0f41 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Thu, 17 Sep 2026 17:21:11 -0400 Subject: [PATCH 084/132] feat: rough pass of new pointing script and first pass of template system --- sotodlib/coords/fp_containers.py | 118 +++++-- .../site_pipeline/solve_static_pointing.py | 296 ++++++++++++++++++ 2 files changed, 387 insertions(+), 27 deletions(-) create mode 100644 sotodlib/site_pipeline/solve_static_pointing.py diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index c41db7868..5787606f4 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -5,8 +5,6 @@ calculations or as static attributes for loading saved results. """ -# TODO: Function to update pointing model pars that is aware of joint fits -# TODO: Serialization + ManifestDb # TODO: Reprs from __future__ import annotations @@ -15,7 +13,7 @@ from argparse import Namespace from copy import deepcopy from dataclasses import dataclass, field -from functools import cached_property +from functools import cached_property, reduce from typing import Any, Iterable, Literal, Optional, Self, cast, overload import h5py @@ -34,9 +32,11 @@ _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("finalize_staic_pointing") +logger = logging.getLogger("solve_static_pointing") def _add_attrs(dset, attrs): @@ -401,7 +401,7 @@ def load(cls, f: h5py.File, path: str) -> Self: @dataclass class DetectorOffsets: """ - Class for storing detector offsets in either `xieta` or `horizon` coordinates. + Class for storing detector offsets in either `xieta`, `horizon`, 'fp', or 'ot' coordinates. `xi`, `eta`, `gamma`, `az`, `el`, and `roll` are included as properties for convenience. They will raise a `ValueError` if called with the wrong coordsys set. @@ -438,7 +438,7 @@ class DetectorOffsets: coordsys: str def __post_init__(self): - if self.coordsys not in ("xieta", "horizon"): + if self.coordsys not in ("xieta", "horizon", "fp", "ot"): raise ValueError(f"Invalid coordsys {self.coordsys}") def __setattr__(self, name: str, value: Any, /) -> None: @@ -628,7 +628,11 @@ class FocalPlane: Per-detector weights used when fitting transforms and combining measurements. template : DetectorOffsets - Reference detector layout used as the transform source. + Reference detector layout used as the transform source on sky. + 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_model : PointingModel Pointing model to apply before computing corrected transforms. static : bool @@ -662,6 +666,8 @@ class FocalPlane: enc: DetectorOffsets weights: Float[np.ndarray, "ndet"] template: DetectorOffsets + template_fp: DetectorOffsets + template_ot: DetectorOffsets pointing_model: PointingModel static: bool autofreeze: bool @@ -686,6 +692,8 @@ def from_aman( meas_id: str, aman: AxisManager, template: DetectorOffsets, + template_fp: DetectorOffsets, + template_ot: DetectorOffsets, pointing_model: PointingModel, autofreeze: bool = False, fake_gamma: bool = True, @@ -711,6 +719,10 @@ def from_aman( See above for details on assumptions. template : DetectorOffsets Template focal plane. + 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_model : PointingModel Pointing model associated with the observation. autofreeze : bool, default: False @@ -800,6 +812,8 @@ def from_aman( enc, weights, template, + template_fp, + template_ot, pointing_model, False, autofreeze, @@ -923,6 +937,8 @@ def load( f: h5py.File, path: str, template: DetectorOffsets, + template_fp: DetectorOffsets, + template_ot: DetectorOffsets, pointing_models: tuple[PointingModel, ...], ) -> Self: """ @@ -936,6 +952,10 @@ def load( 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. @@ -958,6 +978,8 @@ def load( enc=enc, weights=weights, template=template, + template_fp=template_fp, + template_ot=template_ot, pointing_model=pointing_models[pm_idx], static=cast(bool, group.attrs["static"]), autofreeze=cast(bool, group.attrs["autofreeze"]), @@ -1014,6 +1036,10 @@ class FocalPlaneCollection: 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 coords. + template_ot : DetectorOffsets + Reference detector layout used as the transform source in OT coords. static : bool If True, return values from the frozen static fields instead of recomputing them. @@ -1044,6 +1070,8 @@ class FocalPlaneCollection: name: str focal_planes: list[FocalPlane] template: DetectorOffsets + template_fp: DetectorOffsets + template_ot: DetectorOffsets static: bool autofreeze: bool pad: bool @@ -1143,6 +1171,8 @@ def save( }, ) 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, @@ -1190,17 +1220,35 @@ def 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]) focal_planes = [] for name in group: - if name in {"template", "data", "weights", "transform", "transformed"}: + if name in { + "template", + "template_fp", + "template_ot", + "data", + "weights", + "transform", + "transformed", + }: continue focal_planes.append( FocalPlane.load( f, f"{path}/{name}", template=template, + template_fp=template_fp, + template_ot=template_ot, pointing_models=pointing_models, ) ) @@ -1209,6 +1257,8 @@ def load( name=cast(str, group.attrs["name"]), focal_planes=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"]), @@ -1660,10 +1710,10 @@ class PointingSystem: Names without parenthesis apply to all other epochs. parameter_map : tuple[Integer[np.ndarray, "?npar_mapped"], ...] Mapping between parameters and what pointing models to apply them to. - config_str : str - A serialized configuration yaml string. calender_str : str A serialized calendar yaml string. + state_meta : dict[str, str] + String based metadata used for later forensics. parameters : Float[np.ndarray, "npar"] The current values of the parameters. chisq : float @@ -1677,8 +1727,8 @@ class PointingSystem: receivers: tuple[Receiver, ...] parameter_names: tuple[str, ...] parameter_map: tuple[Integer[np.ndarray, "?npar"], ...] - config_str: str calender_str: str + state_meta: dict[str, str] def __post_init__(self): # Force consistancy @@ -1707,6 +1757,8 @@ def chisq(self) -> float: for rx in self.receivers: for ot in rx.optics_tubes: for fp in ot.focal_planes: + if fp.pad: + continue chisq += np.nansum((fp.weights * fp.resid) ** 2).item() return chisq @@ -1847,9 +1899,7 @@ def load_pm_from_mdb(self, mdb: ManifestDb): self.update_parameters(self.parameters) @classmethod - def empty( - cls, era: epochs.Era, cfg: Namespace, config_str: str, calender_str: str - ) -> Self: + def empty(cls, era: epochs.Era, cfg: Namespace, calender_str: str) -> Self: """ Create an empty pointing system from an observing era. @@ -1866,8 +1916,6 @@ def empty( cfg : Namespace Configuration containing the receiver name, epoch groups, pointing model settings, and focal plane options. - config_str : str - A serialized configuration yaml string. calender_str : str A serialized calendar yaml string. @@ -1897,12 +1945,14 @@ def empty( ots = [] for ot, arrays in ws_map.items(): fps = [] - for ufm in arrays.items(): + for _, (_, ufm) in arrays.items(): fps += [ FocalPlaneCollection( ufm, [], DetectorOffsets.empty("xieta"), + DetectorOffsets.empty("fp"), + DetectorOffsets.empty("ot"), False, False, True, @@ -1912,7 +1962,7 @@ def empty( ots += [OpticsTube(ot, fps, list(arrays.keys()), False, False)] rxs += [Receiver(cfg.tel, epoch.name, ots, False, False)] - def _group_epochs(dat, groups, desc): + def _group_epochs(dat, groups, desc, check_fields): u, c = np.unique(np.concatenate(groups), return_counts=True) ng = [d for d in dat if d.epoch not in u] @@ -1923,6 +1973,20 @@ def _group_epochs(dat, groups, desc): 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) 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}") @@ -1932,8 +1996,8 @@ def _group_epochs(dat, groups, desc): return ng + ga - rxs = _group_epochs(rxs, cfg.rx_groups, "receiver") - pms = _group_epochs(pms, cfg.pm_group, "pointing model") + 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: @@ -1964,9 +2028,7 @@ def _group_epochs(dat, groups, desc): 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), par_names, par_map, config_str, calender_str - ) + return cls(era, tuple(pms), tuple(rxs), par_names, par_map, calender_str, {}) def save(self, f: h5py.File, path: str, overwrite: bool = True): """ @@ -1996,11 +2058,12 @@ def save(self, f: h5py.File, path: str, overwrite: bool = True): _add_attrs( group, { - "config_str": self.config_str, "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) for idx, pointing_model in enumerate(self.pointing_models): pointing_model.save( @@ -2045,14 +2108,15 @@ def load(cls, f: h5py.File, path: str) -> Self: The reconstructed pointing system. """ group = f[path] - config_str = cast(str, group.attrs["config_str"]) - calender_str = cast(str, group.attrs["config_str"]) + 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( @@ -2077,6 +2141,6 @@ def load(cls, f: h5py.File, path: str) -> Self: receivers=receivers, parameter_names=parameter_names, parameter_map=parameter_map, - config_str=config_str, calender_str=calender_str, + state_meta=state_meta, ) diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py new file mode 100644 index 000000000..e4a9a7913 --- /dev/null +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -0,0 +1,296 @@ +""" +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 + +import git +import h5py +import numpy as np +import pyinstrument +import sotodlib.coords.fp_containers as fpc +import yaml +from sotodlib.coords import optics +from sotodlib.core import Context, metadata +from sotodlib.io.metadata import read_dataset +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": [], + "pm_ver_override": {}, + "par_groups": {}, + "root_dir": "~", + "project_dir": "solve_static_pointing", + "append": "", +} + + +def _setup_paths(root_dir, project, tel, append=""): + plot_dir = os.path.join(root_dir, "plots", project, tel, append) + data_dir = os.path.join(root_dir, "data", project, tel, append) + os.makedirs(os.path.expanduser(plot_dir), exist_ok=True) + os.makedirs(os.path.expanduser(data_dir), exist_ok=True) + + return plot_dir, data_dir + + +def _compute_templates_and_copy_old(system, cfg, old_system, old_cfg, ctx): + 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_cfg: + system.state_meta["zemax_hash"] = hashlib.md5( + open(cfg.optics_cfg["zemax_path"], "rb").read() + ).hexdigest() + + check_old = old_system is not None and old_cfg is not None + if check_old: + check_old = { + key: val for key, val in cfg.optics_config if key != "zemax_path" + } == {key: val for key, val in old_cfg.optics_config if key != "zemax_path"} + if "zemax_path" in cfg.optics_cfg: + 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: + 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: + 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"{oot.name}" + ] + if len(matches) == 1: + old_ot = matches[0] + for i, (fp, ws) in enumerate(zip(ot.focal_planes, ot.wafer_slot)): + 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"{ofp.name}" and ows == ws + ] + if len(matches) == 1: + old_ot = 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 = ( + None, + 0, + cfg.tel[:3].upper(), + ot.name, + ws, + cfg.optics_cfg["ufm_to_fp"], + None, + cfg.optics_cfg["fp_to_ot"], + None, + cfg.optics_cfg.get("zemax_path"), + None, + True, + ) + + coords = optics.get_focal_plane(det_x, det_y, det_pol, *focal_plane_args) # type: ignore + centers = optics.get_focal_plane(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 + ( + 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 + + 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, + ), + ) + + +def _get_old(outfile, overwrite): + old_system = None + old_cfg = None + if not os.path.isfile(outfile): + return old_system, old_cfg + logger.info("Existing file found at %s") + 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) + return old_system, old_cfg + shutil.copyfile(outfile, new_path) + 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 run(config_path: str, overwrite: 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.cal) + ctx = Context(cfg.context_path) + + # Figure out paths + plot_dir, data_dir = _setup_paths( + cfg.root_dir, cfg.project_dir, cfg.tel, cfg.append + ) + outfile = os.path.join(data_dir, "static_pointing.h5") + + # Setup output + old_system, old_cfg = _get_old(outfile, overwrite) + system = fpc.PointingSystem.empty( + cal.eras[cfg.era], cfg, yaml.dump(yaml.safe_load(cfg.cal)) + ) + system.state_meta["timestamp"] = timestamp + system.state_meta["config"] = cfg_str + system.state_meta["context"] = yaml.dump(yaml.safe_load(cfg.context_path)) + 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()}" + ) + + # Make templates and load old data if we can + _compute_templates_and_copy_old(system, cfg, old_system, old_cfg, ctx) + + # TODO: Mark pad epochs as pad + + # TODO: Load in all obs and populate in per-obs mode, probably want some sort of parallelism here + + # TODO: Fit for pointing model and focal planes + + # Save + # TODO: Setup databases! + with h5py.File(outfile, "a") as f: + system.save(f, "/", True) + + +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" + ) + 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, 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() From d9a63d4e01757cc6e45bc07032618f777dbf97c4 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Mon, 21 Sep 2026 18:47:07 -0700 Subject: [PATCH 085/132] fix: lots of small bugfixes --- sotodlib/coords/fp_containers.py | 4 +++- .../site_pipeline/solve_static_pointing.py | 22 +++++++++---------- sotodlib/utils/epochs.py | 4 ++-- 3 files changed, 16 insertions(+), 14 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 5787606f4..0950fe883 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -1963,6 +1963,8 @@ def empty(cls, era: epochs.Era, cfg: Namespace, calender_str: str) -> Self: 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] @@ -2005,7 +2007,7 @@ def _group_epochs(dat, groups, desc, check_fields): pars = deepcopy(param_defaults[pm_ver]) par_names += list(pars.keys()) pars["version"] = pm_ver - pm.pars = pars + pm.parameters = pars par_names = np.unique(par_names).tolist() par_map = [np.arange(len(pms), dtype=int).tolist()] * len(par_names) pm_epochs = [pm.epoch for pm in pms] diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index e4a9a7913..3bdfbcd10 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -66,9 +66,9 @@ def _compute_templates_and_copy_old(system, cfg, old_system, old_cfg, ctx): "wafer_info has unexpected ManifestScheme! Please annoy one of the usual suspects to modify this code!" ) - if "zemax_path" in cfg.optics_cfg: + if "zemax_path" in cfg.optics_config: system.state_meta["zemax_hash"] = hashlib.md5( - open(cfg.optics_cfg["zemax_path"], "rb").read() + open(cfg.optics_config["zemax_path"], "rb").read() ).hexdigest() check_old = old_system is not None and old_cfg is not None @@ -76,7 +76,7 @@ def _compute_templates_and_copy_old(system, cfg, old_system, old_cfg, ctx): check_old = { key: val for key, val in cfg.optics_config if key != "zemax_path" } == {key: val for key, val in old_cfg.optics_config if key != "zemax_path"} - if "zemax_path" in cfg.optics_cfg: + if "zemax_path" in cfg.optics_config: if "zemax_hash" not in old_system.state_meta: check_old = False else: @@ -108,7 +108,7 @@ def _compute_templates_and_copy_old(system, cfg, old_system, old_cfg, ctx): ] if len(matches) == 1: old_ot = matches[0] - for i, (fp, ws) in enumerate(zip(ot.focal_planes, ot.wafer_slot)): + 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: @@ -150,11 +150,11 @@ def _compute_templates_and_copy_old(system, cfg, old_system, old_cfg, ctx): cfg.tel[:3].upper(), ot.name, ws, - cfg.optics_cfg["ufm_to_fp"], + cfg.optics_config["ufm_to_fp"], None, - cfg.optics_cfg["fp_to_ot"], + cfg.optics_config["fp_to_ot"], None, - cfg.optics_cfg.get("zemax_path"), + cfg.optics_config.get("zemax_path"), None, True, ) @@ -225,8 +225,8 @@ def run(config_path: str, overwrite: bool, timestamp: str): "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.cal) - ctx = Context(cfg.context_path) + cal = epochs.Calendar.load(cfg.calendar) + ctx = Context(cfg.context) # Figure out paths plot_dir, data_dir = _setup_paths( @@ -237,11 +237,11 @@ def run(config_path: str, overwrite: bool, timestamp: str): # Setup output old_system, old_cfg = _get_old(outfile, overwrite) system = fpc.PointingSystem.empty( - cal.eras[cfg.era], cfg, yaml.dump(yaml.safe_load(cfg.cal)) + cal.eras[cfg.era], cfg, yaml.dump(yaml.safe_load(cfg.calendar)) ) system.state_meta["timestamp"] = timestamp system.state_meta["config"] = cfg_str - system.state_meta["context"] = yaml.dump(yaml.safe_load(cfg.context_path)) + system.state_meta["context"] = yaml.dump(yaml.safe_load(cfg.context)) repo = git.Repo( os.path.abspath(os.path.dirname(__file__)), search_parent_directories=True ) diff --git a/sotodlib/utils/epochs.py b/sotodlib/utils/epochs.py index bff29f83b..8e97ada29 100644 --- a/sotodlib/utils/epochs.py +++ b/sotodlib/utils/epochs.py @@ -267,7 +267,7 @@ class Era: epochs: tuple[Epoch, ...] operator: str _internal: Interval = field(init=False) - _lookup: tuple[tuple(float, float, int), ...] = field(init=False) + _lookup: tuple[tuple[float, float, int], ...] = field(init=False) def __post_init__(self): if self.operator not in OP_MAP: @@ -275,7 +275,7 @@ def __post_init__(self): self._internal = cast( Interval, reduce(OP_MAP[self.operator], [e._internal for e in self.epochs]) ) - self.lookup = sorted( + self._lookup = sorted( (ival.start, ival.stop, i) for i, epoch in enumerate(self.epochs) for ival in epoch.covers From b8b560778f721ce17c1e412ac090c86f9ce63f03 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Mon, 21 Sep 2026 20:19:42 -0700 Subject: [PATCH 086/132] fix: more bugs --- sotodlib/coords/fp_containers.py | 17 ++++---- .../site_pipeline/solve_static_pointing.py | 41 +++++++++++-------- 2 files changed, 33 insertions(+), 25 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 0950fe883..d1863202b 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -49,6 +49,8 @@ def _add_attrs(dset, attrs): def _create_group(f, path, overwrite=True): if path in f: + if path == "/": + return f[path] if not overwrite: raise ValueError(f"HDF5 path already exists: {path}") del f[path] @@ -276,8 +278,8 @@ def load(cls, f: h5py.File, path: str) -> Self: PointingModel The loaded pointing model. """ - group = f[path] - parameters = AxisManager.load(f, f"{path}/parameters") + group = cast(h5py.Group, f[path]) + parameters = AxisManager.load(group["parameters"]) parameters = {name: parameters[name] for name in parameters._fields} return cls( @@ -1439,13 +1441,13 @@ def save( group, { "name": self.name, - "wafer_slots": np.asarray(self.wafer_slots), + "wafer_slots": self.wafer_slots, "static": self.static, "autofreeze": self.autofreeze, }, ) - for fp in self.focal_planes: - fp.save(f, f"{path}/{fp.name}", pointing_models, overwrite=overwrite) + 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" in self.__dict__: @@ -1493,7 +1495,8 @@ def load( group = cast(h5py.Group, f[path]) if "cm_transform" in group: tube._cm_transform_stat = Transform.load(f, f"{path}/cm_transform") - tube.cm_transform_norx = Transform.load(f, f"{path}/cm_transform_norx") + if "cm_transform_norx" in group: + tube.cm_transform_norx = Transform.load(f, f"{path}/cm_transform_norx") return tube @@ -2134,7 +2137,7 @@ def load(cls, f: h5py.File, path: str) -> Self: rx_group = cast(h5py.Group, f[f"{path}/receivers"]) receivers = tuple( - Receiver.load(f, name, pointing_models) for name in sorted(rx_group.keys()) + Receiver.load(f, f"{path}/receivers/{name}", pointing_models) for name in sorted(rx_group.keys()) ) return cls( diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index 3bdfbcd10..7c6bf18e5 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -34,16 +34,18 @@ "pm_ver_override": {}, "par_groups": {}, "root_dir": "~", - "project_dir": "solve_static_pointing", + "project_dir": "pointing", "append": "", } def _setup_paths(root_dir, project, tel, append=""): - plot_dir = os.path.join(root_dir, "plots", project, tel, append) - data_dir = os.path.join(root_dir, "data", project, tel, append) - os.makedirs(os.path.expanduser(plot_dir), exist_ok=True) - os.makedirs(os.path.expanduser(data_dir), exist_ok=True) + 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 @@ -74,8 +76,8 @@ def _compute_templates_and_copy_old(system, cfg, old_system, old_cfg, ctx): check_old = old_system is not None and old_cfg is not None if check_old: check_old = { - key: val for key, val in cfg.optics_config if key != "zemax_path" - } == {key: val for key, val in old_cfg.optics_config if key != "zemax_path"} + 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: if "zemax_hash" not in old_system.state_meta: check_old = False @@ -104,7 +106,7 @@ def _compute_templates_and_copy_old(system, cfg, old_system, old_cfg, ctx): old_ot = None if old_rx is not None: matches = [ - oot for oot in old_rx.optics_tubes if f"{oot.name}" == f"{oot.name}" + oot for oot in old_rx.optics_tubes if f"{oot.name}" == f"{ot.name}" ] if len(matches) == 1: old_ot = matches[0] @@ -115,10 +117,10 @@ def _compute_templates_and_copy_old(system, cfg, old_system, old_cfg, ctx): matches = [ ofp for ofp, ows in zip(old_ot.focal_planes, old_ot.wafer_slots) - if f"{ofp.name}" == f"{ofp.name}" and ows == ws + if f"{ofp.name}" == f"{fp.name}" and ows == ws ] if len(matches) == 1: - old_ot = matches[0] + old_fp = matches[0] if old_fp is not None: logger.info( "%s: Matching focal plane found in old data! Copying template and data.", @@ -145,7 +147,6 @@ def _compute_templates_and_copy_old(system, cfg, old_system, old_cfg, ctx): 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 = ( - None, 0, cfg.tel[:3].upper(), ot.name, @@ -159,8 +160,8 @@ def _compute_templates_and_copy_old(system, cfg, old_system, old_cfg, ctx): True, ) - coords = optics.get_focal_plane(det_x, det_y, det_pol, *focal_plane_args) # type: ignore - centers = optics.get_focal_plane(np.zeros(1), np.zeros(1), np.zeros(1), *focal_plane_args) # type: ignore + 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 ( @@ -198,7 +199,7 @@ def _get_old(outfile, overwrite): old_cfg = None if not os.path.isfile(outfile): return old_system, old_cfg - logger.info("Existing file found at %s") + logger.info("Existing file found at %s", outfile) with h5py.File(outfile) as f: ts = f["state"].attrs["timestamp"] new_path = f"{outfile}.{ts}" @@ -227,21 +228,25 @@ def run(config_path: str, overwrite: bool, timestamp: str): 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) - system = fpc.PointingSystem.empty( - cal.eras[cfg.era], cfg, yaml.dump(yaml.safe_load(cfg.calendar)) - ) + 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"] = yaml.dump(yaml.safe_load(cfg.context)) + system.state_meta["context"] = ctx_str repo = git.Repo( os.path.abspath(os.path.dirname(__file__)), search_parent_directories=True ) From 3b02672bb7e35c5b2c64704c48764bf156513573 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Wed, 23 Sep 2026 10:43:06 -0700 Subject: [PATCH 087/132] feat: template fitting --- sotodlib/coords/fp_plots.py | 188 ++++++++++++++++++ .../site_pipeline/solve_static_pointing.py | 51 ++--- 2 files changed, 216 insertions(+), 23 deletions(-) create mode 100644 sotodlib/coords/fp_plots.py diff --git a/sotodlib/coords/fp_plots.py b/sotodlib/coords/fp_plots.py new file mode 100644 index 000000000..a89ad2729 --- /dev/null +++ b/sotodlib/coords/fp_plots.py @@ -0,0 +1,188 @@ +import os +from copy import deepcopy +from typing import Optional + +import matplotlib as mpl +import matplotlib.pyplot as plt +import numpy as np + +from .fp_containers import DetectorOffsets, Receiver + + +def plot_detector_offsets( + ax: mpl.axes._axes.Axes, + 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") diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index 7c6bf18e5..1bacde8f4 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -16,6 +16,7 @@ import numpy as np import pyinstrument import sotodlib.coords.fp_containers as fpc +import sotodlib.coords.fp_plots as fpp import yaml from sotodlib.coords import optics from sotodlib.core import Context, metadata @@ -40,9 +41,13 @@ 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) + 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) @@ -50,7 +55,7 @@ def _setup_paths(root_dir, project, tel, append=""): return plot_dir, data_dir -def _compute_templates_and_copy_old(system, cfg, old_system, old_cfg, ctx): +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"])) @@ -73,12 +78,19 @@ def _compute_templates_and_copy_old(system, cfg, old_system, old_cfg, ctx): 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: + 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: + } == { + 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: @@ -94,7 +106,7 @@ def _compute_templates_and_copy_old(system, cfg, old_system, old_cfg, ctx): 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: + if check_old and old_system is not None: matches = [ orx for orx in old_system.receivers @@ -160,21 +172,12 @@ def _compute_templates_and_copy_old(system, cfg, old_system, old_cfg, ctx): 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 - ( - 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 + 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)), @@ -192,6 +195,8 @@ def _compute_templates_and_copy_old(system, cfg, old_system, old_cfg, ctx): name, ), ) + logger.info("Plotting %s", f"{rx.name}_{rx.epoch}") + fpp.plot_receiver_templates(rx, ot_locs, plot_dir) def _get_old(outfile, overwrite): @@ -231,7 +236,7 @@ def run(config_path: str, overwrite: bool, timestamp: str): with open(cfg.calendar) as f: cal_str = f.read() with open(cfg.context) as f: - ctx_str = f.read() + ctx_str = f.read() # Figure out paths plot_dir, data_dir = _setup_paths( @@ -255,7 +260,7 @@ def run(config_path: str, overwrite: bool, timestamp: str): ) # Make templates and load old data if we can - _compute_templates_and_copy_old(system, cfg, old_system, old_cfg, ctx) + _compute_templates_and_copy_old(system, cfg, old_system, old_cfg, ctx, plot_dir) # TODO: Mark pad epochs as pad From b5bac265f9f862769ff02416f1dd16526f5b1f0a Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Wed, 23 Sep 2026 10:47:42 -0700 Subject: [PATCH 088/132] feat: add backup mode --- .../site_pipeline/solve_static_pointing.py | 26 ++++++++++++------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index 1bacde8f4..d687305ee 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -199,20 +199,23 @@ def _compute_templates_and_copy_old(system, cfg, old_system, old_cfg, ctx, plot_ fpp.plot_receiver_templates(rx, ot_locs, plot_dir) -def _get_old(outfile, overwrite): +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) - 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 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: - shutil.move(outfile, new_path) return old_system, old_cfg - shutil.copyfile(outfile, new_path) with h5py.File(outfile) as f: old_system = fpc.PointingSystem.load(f, "/") old_cfg, _ = load_config_namespace(old_system.state_meta["config"]) @@ -222,7 +225,7 @@ def _get_old(outfile, overwrite): return old_system, old_cfg -def run(config_path: str, overwrite: bool, timestamp: str): +def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): # Load config require = ( "optics_config", @@ -247,7 +250,7 @@ def run(config_path: str, overwrite: bool, timestamp: str): outfile = os.path.join(data_dir, "static_pointing.h5") # Setup output - old_system, old_cfg = _get_old(outfile, overwrite) + 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 @@ -282,6 +285,9 @@ def main(): 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 @@ -293,7 +299,7 @@ def main(): profiler.start() try: - run(args.config_path, args.overwrite, timestamp) + 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" From 6042ae65a818df71a297c8cbbd067cc0dbfa5943 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Tue, 20 Oct 2026 17:15:58 -0700 Subject: [PATCH 089/132] feat: added some utilities for jobdb management --- sotodlib/utils/jdb_utils.py | 492 ++++++++++++++++++++++++++++++++++++ 1 file changed, 492 insertions(+) create mode 100644 sotodlib/utils/jdb_utils.py 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) From 2698fe15835fae0ed7ba9e3664a0dc9f963c381d Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Mon, 2 Nov 2026 14:54:32 -0800 Subject: [PATCH 090/132] feat: add obslist generation --- .../site_pipeline/solve_static_pointing.py | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index d687305ee..39a76b65c 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -37,6 +37,9 @@ "root_dir": "~", "project_dir": "pointing", "append": "", + "point_meta": "focal_plane", + "obs_whitelist": [], + "obs_blacklist": [], } @@ -225,6 +228,51 @@ def _get_old(outfile, overwrite, backup): 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()])) + + # 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("receiver", obs["timestamp"]) is not None + ] + + return obslist + + def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): # Load config require = ( @@ -269,6 +317,9 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): # TODO: Load in all obs and populate in per-obs mode, probably want some sort of parallelism here + # Get obs list + obslist = _get_obslist(ctx, cfg, system) + # TODO: Fit for pointing model and focal planes # Save From 39b975b5595cd259b6d60865f68f6885a09bbe5a Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Mon, 2 Nov 2026 15:32:56 -0800 Subject: [PATCH 091/132] feat: add obsloader --- sotodlib/coords/fp_containers.py | 24 ++++++++++- .../site_pipeline/solve_static_pointing.py | 41 ++++++++++++++++++- 2 files changed, 62 insertions(+), 3 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index d1863202b..33681cf15 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -1562,6 +1562,27 @@ def __getitem__(self, key): 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. @@ -2137,7 +2158,8 @@ def load(cls, f: h5py.File, path: str) -> Self: 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()) + Receiver.load(f, f"{path}/receivers/{name}", pointing_models) + for name in sorted(rx_group.keys()) ) return cls( diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index 39a76b65c..6c85f579b 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -40,6 +40,7 @@ "point_meta": "focal_plane", "obs_whitelist": [], "obs_blacklist": [], + "weight_factor": 1000, } @@ -273,6 +274,40 @@ def _get_obslist(ctx, cfg, system): return obslist +def _load_obs(obs, ctx, system, cfg): + aman_full = ctx.get_meta(obs) + rx = system.search("receiver", obs["timestamp"]) + pm = system.search("pointing_model", obs["timestamp"]) + loaded = [] + for array in np.unique(aman_full.wafer.array): + aman = aman_full.restrict( + "dets", aman_full.wafer.array == array, in_place=False + ) + fp = rx.find_fpc(obs["tube_slot"], array) + if fp is None: + raise ValueError("Array {array} not found in {rx.name} {rx.epoch}") + loaded += [ + ( + obs["tube_slot"], + fpc.FocalPlane.from_aman( + fp.name, + obs["obs_id"], + aman, + fp.template, + fp.template_fp, + fp.template_ot, + 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 + + def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): # Load config require = ( @@ -315,11 +350,13 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): # TODO: Mark pad epochs as pad - # TODO: Load in all obs and populate in per-obs mode, probably want some sort of parallelism here - # Get obs list obslist = _get_obslist(ctx, cfg, system) + # TODO: Set up per-obs jobs + + # TODO: Load in all obs and populate in per-obs mode, probably want some sort of parallelism here + # TODO: Fit for pointing model and focal planes # Save From ff702465c42ce71b8439eb43c81a8476dc06e4a5 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Mon, 2 Nov 2026 19:17:25 -0800 Subject: [PATCH 092/132] feat: add per obs job setup --- sotodlib/coords/fp_containers.py | 6 + .../site_pipeline/solve_static_pointing.py | 130 ++++++++++++++---- 2 files changed, 110 insertions(+), 26 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 33681cf15..6884181bc 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -1089,6 +1089,12 @@ class FocalPlaneCollection: _transform_stat: Transform = field(init=False) _transformed_stat: DetectorOffsets = 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. diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index 6c85f579b..6a1b30d05 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -10,6 +10,9 @@ import hashlib import os import shutil +from enum import Enum +from functools import partial +from typing import cast import git import h5py @@ -17,6 +20,7 @@ import pyinstrument import sotodlib.coords.fp_containers as fpc import sotodlib.coords.fp_plots as fpp +import sotodlib.utils.jdb_utils as ju import yaml from sotodlib.coords import optics from sotodlib.core import Context, metadata @@ -24,6 +28,8 @@ from sotodlib.site_pipeline.utils.logging import init_logger from sotodlib.utils import epochs from sotodlib.utils.config import load_config_namespace +from sotodlib.site_pipeline import jobdb +import sqlalchemy as sqy logger = init_logger(__name__, "solve_static_pointing: ") default_config = { @@ -43,6 +49,39 @@ "weight_factor": 1000, } +class ErrCode(Enum): + NO_ERR = 0 + +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, ctx): + _ = jdb + jobit = [] + for obs in obslist: + det_info = ctx.get_det_info(obs["obs_id"]) + ws = det_info["wafer_slot"] + if "wafer.wafer_slot" in det_info.keys: + ws = np.array( + [ + ws1 if ws1 != "ws." else ws2 + for ws1, ws2 in zip( + det_info["wafer_slot"], det_info["wafer.wafer_slot"] + ) + ] + ) + wsufms= np.unique( np.column_stack([ws, det_info["wafer.array"]]), axis=0) + for ws, arr in wsufms: + jobit += [(obs, ws, arr)] + return jobit + +def _get_jobstr_po(info): + obs, wafer_slot, array = info + return f"{obs['obs_id']}_{wafer_slot}_{array}" + +def _get_tags_po(obs): + return {"obs_id" : obs["obs_id"], "ot" : obs["tube_slot"], "timestamp" : obs["timestamp"], "array": "", "wafer_slot" : "", "errcode" : 0, "message" : ""} + def _setup_paths(root_dir, project, tel, append=""): plot_dir = os.path.join( @@ -274,39 +313,74 @@ def _get_obslist(ctx, cfg, system): return obslist -def _load_obs(obs, ctx, system, cfg): - aman_full = ctx.get_meta(obs) +def _load_obs(obs, array, ctx, system, cfg): rx = system.search("receiver", obs["timestamp"]) pm = system.search("pointing_model", obs["timestamp"]) loaded = [] - for array in np.unique(aman_full.wafer.array): - aman = aman_full.restrict( - "dets", aman_full.wafer.array == array, in_place=False + aman = ctx.get_meta(obs, dets = {"wafer.array" : array}) + fp = rx.find_fpc(obs["tube_slot"], array) + if fp is None: + raise ValueError("Array {array} not found in {rx.name} {rx.epoch}") + loaded += [ + ( + obs["tube_slot"], + fpc.FocalPlane.from_aman( + fp.name, + obs["obs_id"], + aman, + fp.template, + fp.template_fp, + fp.template_ot, + pm, + fp.autofreeze, + fp.fake_gamma, + cfg.weight_factor, + ), ) - fp = rx.find_fpc(obs["tube_slot"], array) - if fp is None: - raise ValueError("Array {array} not found in {rx.name} {rx.epoch}") - loaded += [ - ( - obs["tube_slot"], - fpc.FocalPlane.from_aman( - fp.name, - obs["obs_id"], - aman, - fp.template, - fp.template_fp, - fp.template_ot, - 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 +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) + + # 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 if f"{meas.meas_id}_{meas.name}" not in open_ids] + + return open_jobs def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): # Load config @@ -353,7 +427,11 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): # Get obs list obslist = _get_obslist(ctx, cfg, system) - # TODO: Set up per-obs jobs + # Set 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, ctx=ctx), _get_jobstr_po, _get_tags_po, [], overwrite, False, None, 0, False, logger) + done_jobs = jdb.get_jobs(jclass="per_obs", jstate="done") + open_jobs = _check_jobs(system, jdb, done_jobs, open_jobs) # TODO: Load in all obs and populate in per-obs mode, probably want some sort of parallelism here From aaa3b0db87579240141c905b6a0aa38b2564ca39 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Tue, 3 Nov 2026 14:29:28 -0800 Subject: [PATCH 093/132] feat: add per obs loop --- sotodlib/coords/fp_containers.py | 18 +++ .../site_pipeline/solve_static_pointing.py | 110 ++++++++++++++++-- 2 files changed, 116 insertions(+), 12 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 6884181bc..733042861 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -1764,6 +1764,24 @@ def __post_init__(self): # Force consistancy self.update_parameters(self.parameters) + 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 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 + @property def parameters(self) -> Float[np.ndarray, "npar"]: return np.array( diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index 6a1b30d05..bc14e2e25 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -47,13 +47,21 @@ "obs_whitelist": [], "obs_blacklist": [], "weight_factor": 1000, + "min_frac_dets": .25, + "max_dscale": .1, + "max_shear": .05, } -class ErrCode(Enum): +class ErrCode(Enum): NO_ERR = 0 + LOADER = 1 + MIN_DETS = 2 + AFF_ERR = 3 + HIGH_SCALE = 4 + HIGH_SHEAR = 5 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")} + 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, ctx): _ = jdb @@ -77,7 +85,7 @@ def _get_jobit_po(jdb, obslist, ctx): def _get_jobstr_po(info): obs, wafer_slot, array = info - return f"{obs['obs_id']}_{wafer_slot}_{array}" + return f"{obs['obs_id']}+{wafer_slot}+{array}" def _get_tags_po(obs): return {"obs_id" : obs["obs_id"], "ot" : obs["tube_slot"], "timestamp" : obs["timestamp"], "array": "", "wafer_slot" : "", "errcode" : 0, "message" : ""} @@ -348,9 +356,9 @@ def _check_jobs(system, jdb, done_jobs, open_jobs): 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] + 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 @@ -372,15 +380,16 @@ def _check_jobs(system, jdb, done_jobs, open_jobs): 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] + 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 if f"{meas.meas_id}_{meas.name}" not in open_ids] + fp.focal_planes= [meas for meas in fp if f"{meas.meas_id}+{meas.name}" not in open_ids] - return open_jobs + return open_jobs, done_jobs def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): # Load config @@ -422,6 +431,10 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): # 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 + with h5py.File(outfile, "a") as f: + system.save(f, "/", True) + # TODO: Mark pad epochs as pad # Get obs list @@ -431,11 +444,84 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): 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, ctx=ctx), _get_jobstr_po, _get_tags_po, [], overwrite, False, None, 0, False, logger) done_jobs = jdb.get_jobs(jclass="per_obs", jstate="done") - open_jobs = _check_jobs(system, jdb, done_jobs, open_jobs) - - # TODO: Load in all obs and populate in per-obs mode, probably want some sort of parallelism here + 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 + job = None + njobs = len(open_jobs) + logger.info("Starting per-obs mode with %d open jobs and %d already done", njobs, len(done_jobs)) + 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: + ot, meas = _load_obs(obs_id, array, ctx, system, cfg) + except Exception as e: + msg = f"Failed to load with error: {e}" + ju.fail(job, ErrCode.LOADER, msg, logger) + 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 + + # 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 + + # TODO: Plot + + # Add to system + rx = system.search("receivers", job.tags["timestamp"]) + if rx is None: + raise ValueError(f"Somehow found no receiver for {jstr}") + fp = rx.find_fpc(ot, array) + if fp is None: + raise ValueError(f"Somehow found no focal plane for {jstr}") + fp.focal_planes += [meas] + job.jstate = cast(sqy.Column[str], jobdb.JState.done) + logger.info("Done with per-obs mode!") + + # Save our per-obs results + system.set_static(True) + with h5py.File(outfile, "a") as f: + system.save(f, "/", True) + # TODO: Fit for pointing model and focal planes + system.set_static(False) # Save # TODO: Setup databases! From f09ed87284c7a0fa1302d0a3367f09fb1323022e Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Tue, 3 Nov 2026 14:53:07 -0800 Subject: [PATCH 094/132] feat: add plotting for ufms --- sotodlib/coords/fp_plots.py | 74 +++++++++++++++- .../site_pipeline/solve_static_pointing.py | 86 +++++++++++++++---- 2 files changed, 142 insertions(+), 18 deletions(-) diff --git a/sotodlib/coords/fp_plots.py b/sotodlib/coords/fp_plots.py index a89ad2729..832f6e63a 100644 --- a/sotodlib/coords/fp_plots.py +++ b/sotodlib/coords/fp_plots.py @@ -6,7 +6,7 @@ import matplotlib.pyplot as plt import numpy as np -from .fp_containers import DetectorOffsets, Receiver +from .fp_containers import DetectorOffsets, FocalPlane, FocalPlaneCollection, Receiver def plot_detector_offsets( @@ -186,3 +186,75 @@ def save_and_finish(fig, name): 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), +): + """ + 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. + """ + fig, (ax1, ax2) = plt.subplots(1, 2, figsize=figsize, constrained_layout=True) + + # Plot focal-plane pointing. + plot_detector_offsets( + ax1, + focal_plane.template, + color="blue", + alpha=0.4, + label="template", + marker="P", + ) + plot_detector_offsets( + ax1, + focal_plane.transformed, + color="black", + alpha=0.4, + label="transformed", + marker="X", + ) + plot_detector_offsets( + ax1, + focal_plane.data, + 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.rad2deg( + (focal_plane.transformed.xyz - focal_plane.template.xyz)[ + np.isnan(focal_plane.weights) + ] + ) + 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) diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index bc14e2e25..520b8b3ee 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -47,11 +47,12 @@ "obs_whitelist": [], "obs_blacklist": [], "weight_factor": 1000, - "min_frac_dets": .25, - "max_dscale": .1, - "max_shear": .05, + "min_frac_dets": 0.25, + "max_dscale": 0.1, + "max_shear": 0.05, } + class ErrCode(Enum): NO_ERR = 0 LOADER = 1 @@ -59,9 +60,15 @@ class ErrCode(Enum): AFF_ERR = 3 HIGH_SCALE = 4 HIGH_SHEAR = 5 + PLOT = 6 + 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")} + 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, ctx): _ = jdb @@ -78,17 +85,27 @@ def _get_jobit_po(jdb, obslist, ctx): ) ] ) - wsufms= np.unique( np.column_stack([ws, det_info["wafer.array"]]), axis=0) + wsufms = np.unique(np.column_stack([ws, det_info["wafer.array"]]), axis=0) for ws, arr in wsufms: jobit += [(obs, ws, arr)] return jobit + def _get_jobstr_po(info): obs, wafer_slot, array = info return f"{obs['obs_id']}+{wafer_slot}+{array}" + def _get_tags_po(obs): - return {"obs_id" : obs["obs_id"], "ot" : obs["tube_slot"], "timestamp" : obs["timestamp"], "array": "", "wafer_slot" : "", "errcode" : 0, "message" : ""} + return { + "obs_id": obs["obs_id"], + "ot": obs["tube_slot"], + "timestamp": obs["timestamp"], + "array": "", + "wafer_slot": "", + "errcode": 0, + "message": "", + } def _setup_paths(root_dir, project, tel, append=""): @@ -325,7 +342,7 @@ def _load_obs(obs, array, ctx, system, cfg): rx = system.search("receiver", obs["timestamp"]) pm = system.search("pointing_model", obs["timestamp"]) loaded = [] - aman = ctx.get_meta(obs, dets = {"wafer.array" : array}) + aman = ctx.get_meta(obs, dets={"wafer.array": array}) fp = rx.find_fpc(obs["tube_slot"], array) if fp is None: raise ValueError("Array {array} not found in {rx.name} {rx.epoch}") @@ -350,6 +367,7 @@ def _load_obs(obs, array, ctx, system, cfg): # Not adding to the system so that we can leave ourselves open to parallelism return loaded + def _check_jobs(system, jdb, done_jobs, open_jobs): to_open = [] in_system = [] @@ -364,7 +382,9 @@ def _check_jobs(system, jdb, done_jobs, open_jobs): # 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}") + 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) @@ -387,10 +407,13 @@ def _check_jobs(system, jdb, done_jobs, open_jobs): 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 if f"{meas.meas_id}+{meas.name}" not in open_ids] + fp.focal_planes = [ + meas for meas in fp if f"{meas.meas_id}+{meas.name}" not in open_ids + ] return open_jobs, done_jobs + def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): # Load config require = ( @@ -442,14 +465,33 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): # Set 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, ctx=ctx), _get_jobstr_po, _get_tags_po, [], overwrite, False, None, 0, False, logger) + jdb, open_jobs = ju.setup_jobs( + None, + jdb_path, + "per_obs", + _get_jobdict_po, + partial(_get_jobit_po, obslist=obslist, ctx=ctx), + _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 job = None njobs = len(open_jobs) - logger.info("Starting per-obs mode with %d open jobs and %d already done", njobs, len(done_jobs)) + logger.info( + "Starting per-obs mode with %d open jobs and %d already done", + njobs, + len(done_jobs), + ) for i, j in enumerate(open_jobs): if job is not None: logger.debug("Writing to db") @@ -468,7 +510,7 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): 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) + logger.info("Loading and processing %s (%d/%d)", jstr, i + 1, njobs) # Load try: @@ -479,7 +521,7 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): continue # Check min dets - dfrac = np.nansum(meas.weights)/len(meas.weights) + 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) @@ -501,15 +543,26 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): ju.fail(job, ErrCode.HIGH_SHEAR, msg, logger) continue - # TODO: Plot - - # Add to system + # Locate + # TODO: I must be able to cache/hash somehow for this rx = system.search("receivers", job.tags["timestamp"]) if rx is None: raise ValueError(f"Somehow found no receiver for {jstr}") fp = rx.find_fpc(ot, array) if fp is None: raise ValueError(f"Somehow found no focal plane for {jstr}") + + # Plot + pdir = os.path.join(plot_dir, rx.epoch, "per-obs") + 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) logger.info("Done with per-obs mode!") @@ -518,7 +571,6 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): system.set_static(True) with h5py.File(outfile, "a") as f: system.save(f, "/", True) - # TODO: Fit for pointing model and focal planes system.set_static(False) From 1e9d5525edfc79807113940d2839a46c0f85dd1d Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Wed, 4 Nov 2026 21:02:54 -0800 Subject: [PATCH 095/132] fix: actually index when searching --- sotodlib/utils/epochs.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sotodlib/utils/epochs.py b/sotodlib/utils/epochs.py index 8e97ada29..c7e0fda81 100644 --- a/sotodlib/utils/epochs.py +++ b/sotodlib/utils/epochs.py @@ -327,7 +327,7 @@ def find_epoch(self, timestamp: float) -> Optional[Epoch]: 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._lookup[j][2] + return self.epochs[self._lookup[j][2]] return None From eceb9f63941177928e16c0b8af29b08682d33c50 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Wed, 4 Nov 2026 21:03:30 -0800 Subject: [PATCH 096/132] fix: many fixes: * ClassVar * Proper cutr * many typos and small fixes --- sotodlib/coords/fp_containers.py | 121 ++++++++++++------ sotodlib/coords/fp_plots.py | 6 +- .../site_pipeline/solve_static_pointing.py | 115 +++++++++-------- 3 files changed, 141 insertions(+), 101 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 733042861..a45a72a04 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -14,7 +14,7 @@ from copy import deepcopy from dataclasses import dataclass, field from functools import cached_property, reduce -from typing import Any, Iterable, Literal, Optional, Self, cast, overload +from typing import Any, Iterable, Literal, Optional, Self, cast, overload, ClassVar, TypeVar, Generic import h5py import megham.transform as mt @@ -22,6 +22,7 @@ import numpy as np from jaxtyping import Float, Integer, Shaped from scipy.optimize import minimize +from scipy.cluster import vq from so3g.proj import quat from sotodlib.coords.pointing_model import apply_pointing_model, param_defaults from sotodlib.core import AxisManager, IndexAxis, metadata @@ -38,6 +39,8 @@ logger = logging.getLogger("solve_static_pointing") +T = TypeVar("T") + def _add_attrs(dset, attrs): for k, v in attrs.items(): @@ -91,9 +94,11 @@ def _transformed(self: FocalPlane | FocalPlaneCollection, attr_name: str): to_ret.xyz = mt.apply_transform( self.template.xyz, self.transform.affine, self.transform.shift ) - to_ret.center = mt.apply_transform( - self.template.center, self.transform.affine, self.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), self.transform.affine, self.transform.shift + ).ravel() if self.autofreeze: setattr(self, attr_name, to_ret) return to_ret @@ -103,7 +108,7 @@ def _get_aff(self: FocalPlane | FocalPlaneCollection, data_name: str, attr_name: affine, shift = mt.get_affine_two_stage( self.template.xyz[:, :2], getattr(self, data_name).xyz[:, :2], - self.weights[:, 0], + self.weights, ) to_ret = Transform.identity() to_ret.shift[:2] = shift @@ -117,7 +122,7 @@ def _get_aff(self: FocalPlane | FocalPlaneCollection, data_name: str, attr_name: return to_ret -class StaticOrCached: +class StaticOrCached(Generic[T]): """ Wrapper that will get either: @@ -133,7 +138,13 @@ def __init__(self, name: str): def __set_name__(self, owner, attr_name): self.attr_name = attr_name - def __get__(self, obj, owner): + @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 @@ -674,13 +685,11 @@ class FocalPlane: static: bool autofreeze: bool fake_gamma: bool - data_pm: DetectorOffsets = cast(DetectorOffsets, StaticOrCached("data_pm")) - transform: Transform = cast(Transform, StaticOrCached("transform")) - transformed: DetectorOffsets = cast(DetectorOffsets, StaticOrCached("transformed")) - pm_transform: Transform = cast(Transform, StaticOrCached("pm_transform")) - pm_transformed: DetectorOffsets = cast( - DetectorOffsets, StaticOrCached("pm_transformed") - ) + data_pm: ClassVar[StaticOrCached[DetectorOffsets]] = StaticOrCached("data_pm") + 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") _data_pm_stat: DetectorOffsets = field(init=False) _transform_stat: Transform = field(init=False) _transformed_stat: DetectorOffsets = field(init=False) @@ -742,11 +751,16 @@ def from_aman( Note that this will have `static = False`. """ # Figure out mapping - _, msk, template_msk = np.intersect1d( - np.array(aman.det_info.det_id), template.det_id, return_indices=True - ) - mapping = np.argsort(np.argsort(template.det_id[template_msk])) - srt = np.argsort(np.array(aman.det_info.det_id[msk])) + 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) @@ -757,7 +771,7 @@ def from_aman( if not fake_gamma else np.nan * np.ones_like(xi) ) - data.xyz[template_msk] = np.column_stack((xi, eta, gamma))[msk][srt][mapping] + data.xyz[template_idx] = np.column_stack((xi, eta, gamma))[aman_idx] data.xyz[~template_msk] = np.nan # Setup enc @@ -778,34 +792,61 @@ def from_aman( if "roll" in aman.focal_plane else np.deg2rad(np.array(aman.obs_info.roll_center)) * np.ones_like(xi) ) - enc.xyz[template_msk] = np.column_stack((az, el, roll))[msk][srt][mapping] + 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: + 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[:, :2], template.xyz[template_msk, :2]) + 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[:, :2]) + 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_spacing = np.percentile(np.diff(np.sort(template.xyz[:, 2])), 99.9) + 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[template_msk, 2]) - weights = mu.gen_weights( - np.column_stack((aligned, gscale * data.xyz[:, 2] + gsft)), - template.xyz[template_msk], + 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 = mu.gen_weights( - aligned, - template.xyz[template_msk, :2], + 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] = np.nan + weights[weights < 0.61] = 0 return cls( name, @@ -1078,12 +1119,10 @@ class FocalPlaneCollection: autofreeze: bool pad: bool fake_gamma: bool - data: DetectorOffsets = cast(DetectorOffsets, StaticOrCached("data")) - weights: Float[np.ndarray, "ndet"] = cast( - Float[np.ndarray, "ndet"], StaticOrCached("weights") - ) - transform: Transform = cast(Transform, StaticOrCached("transform")) - transformed: DetectorOffsets = cast(DetectorOffsets, StaticOrCached("transformed")) + 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) @@ -1345,7 +1384,7 @@ class OpticsTube: wafer_slots: list[str] static: bool autofreeze: bool - cm_transform: Transform = cast(Transform, StaticOrCached("cm_transform")) + cm_transform: ClassVar[StaticOrCached[Transform]] = StaticOrCached("cm_transform") cm_transform_norx: Transform = field(init=False) _cm_transform_stat: Transform = field(init=False) @@ -1559,7 +1598,7 @@ class Receiver: optics_tubes: list[OpticsTube] static: bool autofreeze: bool - cm_transform: Transform = cast(Transform, StaticOrCached("cm_transform")) + cm_transform: ClassVar[StaticOrCached[Transform]] = StaticOrCached("cm_transform") _cm_transform_stat: Transform = field(init=False) def __getitem__(self, key): @@ -1773,7 +1812,7 @@ def set_static(self, static : bool): static : bool The value to set `static` to for all relevent children. """ - for rx in receivers: + for rx in self.receivers: rx.static = static for ot in rx.optics_tubes: ot.static = static diff --git a/sotodlib/coords/fp_plots.py b/sotodlib/coords/fp_plots.py index 832f6e63a..c1bf305c3 100644 --- a/sotodlib/coords/fp_plots.py +++ b/sotodlib/coords/fp_plots.py @@ -237,11 +237,7 @@ def plot_ufm( ax1.legend() # Plot histogram of residuals. - dist = 3600 * np.rad2deg( - (focal_plane.transformed.xyz - focal_plane.template.xyz)[ - np.isnan(focal_plane.weights) - ] - ) + dist = 3600 * np.linalg.norm(np.rad2deg( (focal_plane.transformed.xyz - focal_plane.data.xyz)[np.isfinite(focal_plane.weights) * (focal_plane.weights > 0), :2]), axis=1) if len(dist) > 0: dist_thresh = np.percentile(dist, 97) bins = max(int(len(dist) / 20), 10) diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index 520b8b3ee..8369e9abd 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -47,9 +47,11 @@ "obs_whitelist": [], "obs_blacklist": [], "weight_factor": 1000, - "min_frac_dets": 0.25, + "min_frac_dets": 0.1, "max_dscale": 0.1, "max_shear": 0.05, + "min_hits": 3, + "min_r2": .3, } @@ -61,6 +63,7 @@ class ErrCode(Enum): HIGH_SCALE = 4 HIGH_SHEAR = 5 PLOT = 6 + FPINIT = 7 def _get_jobdict_po(jdb): @@ -70,24 +73,19 @@ def _get_jobdict_po(jdb): } -def _get_jobit_po(jdb, obslist, ctx): +def _get_jobit_po(jdb, obslist, system): _ = jdb jobit = [] for obs in obslist: - det_info = ctx.get_det_info(obs["obs_id"]) - ws = det_info["wafer_slot"] - if "wafer.wafer_slot" in det_info.keys: - ws = np.array( - [ - ws1 if ws1 != "ws." else ws2 - for ws1, ws2 in zip( - det_info["wafer_slot"], det_info["wafer.wafer_slot"] - ) - ] - ) - wsufms = np.unique(np.column_stack([ws, det_info["wafer.array"]]), axis=0) - for ws, arr in wsufms: - jobit += [(obs, ws, arr)] + 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 @@ -96,13 +94,14 @@ def _get_jobstr_po(info): return f"{obs['obs_id']}+{wafer_slot}+{array}" -def _get_tags_po(obs): +def _get_tags_po(info): + obs, wafer_slot, array = info return { "obs_id": obs["obs_id"], "ot": obs["tube_slot"], "timestamp": obs["timestamp"], - "array": "", - "wafer_slot": "", + "array": array, + "wafer_slot": wafer_slot, "errcode": 0, "message": "", } @@ -166,7 +165,7 @@ def _compute_templates_and_copy_old(system, cfg, old_system, old_cfg, ctx, plot_ system.state_meta["zemax_hash"] == old_system.state_meta["zemax_hash"] ) - if check_old: + 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: @@ -320,6 +319,7 @@ def _get_obslist(ctx, cfg, system): 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"] # Validate against black and whitelist if len(cfg.obs_whitelist) > 0: @@ -332,37 +332,20 @@ def _get_obslist(ctx, cfg, system): obslist = [ obs for obs in obslist - if system.search("receiver", obs["timestamp"]) is not None + if system.search("receivers", obs["timestamp"]) is not None ] return obslist -def _load_obs(obs, array, ctx, system, cfg): - rx = system.search("receiver", obs["timestamp"]) - pm = system.search("pointing_model", obs["timestamp"]) - loaded = [] - aman = ctx.get_meta(obs, dets={"wafer.array": array}) +def _load_obs(aman, obs_id, array, ctx, system, cfg): + 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}") - loaded += [ - ( - obs["tube_slot"], - fpc.FocalPlane.from_aman( - fp.name, - obs["obs_id"], - aman, - fp.template, - fp.template_fp, - fp.template_ot, - pm, - fp.autofreeze, - fp.fake_gamma, - cfg.weight_factor, - ), - ) - ] + loaded = fpc.FocalPlane.from_aman( fp.name, obs["obs_id"], aman, fp.template, fp.template_fp, fp.template_ot, 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 @@ -470,7 +453,7 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): jdb_path, "per_obs", _get_jobdict_po, - partial(_get_jobit_po, obslist=obslist, ctx=ctx), + partial(_get_jobit_po, obslist=obslist, system=system), _get_jobstr_po, _get_tags_po, [], @@ -492,6 +475,7 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): njobs, len(done_jobs), ) + open_jobs += [None] for i, j in enumerate(open_jobs): if job is not None: logger.debug("Writing to db") @@ -514,12 +498,42 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): # Load try: - ot, meas = _load_obs(obs_id, array, ctx, system, cfg) + 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 + # Locate + # TODO: I must be able to cache/hash somehow for this + rx = system.search("receivers", float(job.tags["timestamp"])) + if rx is None: + raise ValueError(f"Somehow found no receiver for {jstr}") + fp = rx.find_fpc(job.tags["ot"], array) + if fp is None: + raise ValueError(f"Somehow found no focal plane for {jstr}") + + + # 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) + continue + + # Init the fp + meas = _load_obs(aman, obs_id, array, ctx, system, cfg) + try: + meas = _load_obs(aman, obs_id, array, ctx, system, cfg) + except Exception as e: + msg = f"Failed to build focal plane with error: {e}" + ju.fail(job, ErrCode.FPINIT, msg, logger) + continue + # Check min dets dfrac = np.nansum(meas.weights) / len(meas.weights) if dfrac < cfg.min_frac_dets: @@ -543,17 +557,8 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): ju.fail(job, ErrCode.HIGH_SHEAR, msg, logger) continue - # Locate - # TODO: I must be able to cache/hash somehow for this - rx = system.search("receivers", job.tags["timestamp"]) - if rx is None: - raise ValueError(f"Somehow found no receiver for {jstr}") - fp = rx.find_fpc(ot, array) - if fp is None: - raise ValueError(f"Somehow found no focal plane for {jstr}") - # Plot - pdir = os.path.join(plot_dir, rx.epoch, "per-obs") + 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) From fe28969a6bf73397d4f5399a0649e3f2af4f5cb6 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Thu, 5 Nov 2026 15:09:07 -0800 Subject: [PATCH 097/132] fix: plot the correct fp fields --- sotodlib/coords/fp_plots.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/sotodlib/coords/fp_plots.py b/sotodlib/coords/fp_plots.py index c1bf305c3..ed82eca91 100644 --- a/sotodlib/coords/fp_plots.py +++ b/sotodlib/coords/fp_plots.py @@ -192,6 +192,7 @@ 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. @@ -202,10 +203,18 @@ def plot_ufm( Focal-plane object for a specefic observation. output_dir : str Directory in which to save the plot. - figsize : tuple[float, float], default=(12, 6) + figsize : tuple[float, float], default: (12, 6) Figure dimensions in inches. + with_pm : bool, default: True + If True then use `data_pm` if `False` use `data`. + Only matters for `FocalPlane`. """ 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.data_pm + transformed = focal_plane.pm_transformed # Plot focal-plane pointing. plot_detector_offsets( @@ -218,7 +227,7 @@ def plot_ufm( ) plot_detector_offsets( ax1, - focal_plane.transformed, + transformed, color="black", alpha=0.4, label="transformed", @@ -226,7 +235,7 @@ def plot_ufm( ) plot_detector_offsets( ax1, - focal_plane.data, + data, color="orange", alpha=0.4, label="measured", @@ -237,7 +246,7 @@ def plot_ufm( ax1.legend() # Plot histogram of residuals. - dist = 3600 * np.linalg.norm(np.rad2deg( (focal_plane.transformed.xyz - focal_plane.data.xyz)[np.isfinite(focal_plane.weights) * (focal_plane.weights > 0), :2]), axis=1) + dist = 3600 * np.linalg.norm(np.rad2deg( (transformed.xyz - data.xyz)[np.isfinite(focal_plane.weights) * (focal_plane.weights > 0), :2]), axis=1) if len(dist) > 0: dist_thresh = np.percentile(dist, 97) bins = max(int(len(dist) / 20), 10) From 7cc6f1ba187afb089c594643fc68a737179dbeb7 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Thu, 5 Nov 2026 15:09:36 -0800 Subject: [PATCH 098/132] feat: add more padding infra --- sotodlib/coords/fp_containers.py | 47 +++++++++++++++++-- .../site_pipeline/solve_static_pointing.py | 9 +++- 2 files changed, 51 insertions(+), 5 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index a45a72a04..ac0cb000c 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -6,6 +6,7 @@ """ # TODO: Reprs +# TODO: Implement roll dep stuff, need to be careful about the correct direction. Should be REMOVING it from the data I think from __future__ import annotations @@ -172,11 +173,14 @@ class PointingModel: 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 force_zero_roll: bool + pad: bool = False def apply_det( self, @@ -264,7 +268,7 @@ def save(self, f: h5py.File, path: str, overwrite: bool = True): """ group = _create_group(f, path, overwrite) _add_attrs( - group, {"epoch": self.epoch, "force_zero_roll": self.force_zero_roll} + group, {"epoch": self.epoch, "force_zero_roll": self.force_zero_roll, "pad": self.pad} ) parameters = AxisManager() @@ -297,6 +301,7 @@ def load(cls, f: h5py.File, path: str) -> Self: epoch=cast(str, group.attrs["epoch"]), parameters=parameters, force_zero_roll=cast(bool, group.attrs["force_zero_roll"]), + pad=cast(bool, group.attrs["pad"]), ) @@ -1409,10 +1414,10 @@ def freeze(self, static: bool): self.static = static @property - def allpad(self): + def allpad(self) -> bool: if len(self.focal_planes) == 0: return True - return np.all([fp.pad for fp in self.focal_planes]) + return bool(np.all([fp.pad for fp in self.focal_planes])) @property def _cm_transform_dyn(self) -> Transform: @@ -1588,6 +1593,9 @@ class Receiver: autofreeze : bool If True, cache dynamically computed quantities into their corresponding static fields. + allpad : bool + Flag indicating whether all optics tube are padded + and should therefore be excluded from fitting. cm_transform : Transform Receiver-level common-mode transform derived from the common-mode transforms of all optics tubes containing valid data. @@ -1640,6 +1648,12 @@ def freeze(self, static: bool): self._cm_transform_stat = self._cm_transform_dyn self.static = static + @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 = [ @@ -1921,6 +1935,31 @@ def search( 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 = bool(pad + bool(pad_empty * (len(fp.focal_planes) == 0))) + def load_pm_from_mdb(self, mdb: ManifestDb): """ Load pointing model parameters from a ManifestDb into the current era. @@ -2027,7 +2066,7 @@ def empty(cls, era: epochs.Era, cfg: Namespace, calender_str: str) -> Self: rxs = [] pms = [] for epoch in era.epochs: - pms += [PointingModel(epoch.name, {}, cfg.force_zero_roll)] + pms += [PointingModel(epoch.name, {}, cfg.force_zero_roll, False)] ws_map = epoch.covers[0].data["ws_mapping"] ots = [] for ot, arrays in ws_map.items(): diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index 8369e9abd..44c638fef 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -38,6 +38,7 @@ "force_zero_roll": False, "rx_groups": [], "pm_groups": [], + "pad_epochs": [], "pm_ver_override": {}, "par_groups": {}, "root_dir": "~", @@ -52,6 +53,7 @@ "max_shear": 0.05, "min_hits": 3, "min_r2": .3, + "pad_empty": True, } @@ -441,7 +443,8 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): with h5py.File(outfile, "a") as f: system.save(f, "/", True) - # TODO: Mark pad epochs as pad + # Mark pad epochs as pad + system.set_pad(cfg.pad_epochs, False) # Get obs list obslist = _get_obslist(ctx, cfg, system) @@ -572,6 +575,10 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): job.jstate = cast(sqy.Column[str], jobdb.JState.done) logger.info("Done with per-obs mode!") + # Pad empty if needed + if cfg.pad_empty: + system.set_pad(cfg.pad_epochs, True) + # Save our per-obs results system.set_static(True) with h5py.File(outfile, "a") as f: From da6b17f5bafa6457788eb228106435bbc5ee4a8a Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Fri, 6 Nov 2026 14:42:48 -0800 Subject: [PATCH 099/132] fix: pm inversion now supports distortion and actually use pm transform when requensted --- sotodlib/coords/fp_containers.py | 150 +++++++++++++++++++++---------- 1 file changed, 105 insertions(+), 45 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index ac0cb000c..96b25295e 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -90,15 +90,15 @@ def _gamma_min(pars, src, dst): return res.x -def _transformed(self: FocalPlane | FocalPlaneCollection, attr_name: str): +def _transformed(self: FocalPlane | FocalPlaneCollection, attr_name: str, transform: Transform): to_ret = deepcopy(self.template) to_ret.xyz = mt.apply_transform( - self.template.xyz, self.transform.affine, self.transform.shift + 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), self.transform.affine, self.transform.shift + np.atleast_2d(self.template.center), transform.affine, transform.shift ).ravel() if self.autofreeze: setattr(self, attr_name, to_ret) @@ -186,29 +186,35 @@ def apply_det( self, det_off: DetectorOffsets, det_enc: DetectorOffsets, + weights: Float[np.ndarray, "ndet"], fake_gamma: bool, + tol: float = 1e-6, + max_iter: int = 5, ) -> DetectorOffsets: """ - Apply the pointing model correction to a set of detector offsets. - + 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 are corrected for the boresight pointing - model specified by this instance. - + `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. + If the pointing model contains no parameters, the input detector offsets are returned unchanged. - + When `force_zero_roll=True`, the encoder roll angle is ignored during the correction and a zero-roll boresight solution is assumed. - + Parameters ---------- det_off : DetectorOffsets Detector offsets in the `xieta` coordinate system. These are the - detector positions to which the pointing correction will be - applied. + detector positions from which the pointing correction will be removed. det_enc : DetectorOffsets Telescope encoder values in the `horizon` coordinate system. These provide the boresight azimuth, elevation, and roll used to @@ -217,41 +223,92 @@ def apply_det( If True, ignore detector polarization angles and propagate only detector position (`xi`, `eta`). If False, propagate the full (`xi`, `eta`, `gamma`) coordinate set. - + tol : float, default: 1e-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 ------- det_pm : DetectorOffsets - A copy of `det_off` with the pointing-model correction applied. + A copy of `det_off` 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 ------ ValueError If `det_off` and `det_enc` do not contain the same number of detectors. + RuntimeError + If the iterative distortion removal does not converge. """ if len(self.parameters) == 0: return det_off + if len(det_enc.xyz) != len(det_off.xyz): - raise ValueError( - "Detector offsets and encoder values must have same shape!" - ) - bs = apply_pointing_model(None, self.parameters, det_off.ancil, False) + raise ValueError( "Detector offsets and encoder values must have same shape!") + + # Start with the input detector coordinates + msk = np.isfinite(weights) * (weights > 0) + estimate = det_off.xyz.copy()[msk] + fp_target = det_off.xyz[msk] if fake_gamma: - q_fp = quat.rotation_xieta(det_off.xi, det_off.eta) - else: - q_fp = quat.rotation_xieta(det_off.xi, det_off.eta, det_off.gamma) # type: ignore + estimate = estimate[:, :2] to_ret = deepcopy(det_off) - xi, eta, gamma = quat.decompose_xieta( - ~quat.euler(2, bs.roll) - * ~quat.rotation_lonlat(-1 * bs.az, bs.el) # type: ignore - * quat.rotation_lonlat(-1 * det_enc.az, det_enc.el) - * quat.euler(2, (not self.force_zero_roll) * det_enc.roll) - * q_fp - ) - to_ret.xyz = np.column_stack((xi, eta, gamma)) - return to_ret + tmp = deepcopy(det_off) + tmp.xyz = tmp.xyz[msk] + fp = tmp.fp + det_enc_msk = deepcopy(det_enc) + det_enc_msk.xyz = det_enc_msk.xyz[msk] + ancil = det_enc_msk.ancil + + err = np.inf + for _ in range(max_iter): + fp.xi = estimate[:, 0] + fp.eta = estimate[:, 1] + if fake_gamma: + q_fp = quat.rotation_xieta(estimate[:, 0], estimate[:, 1]) + else: + q_fp = quat.rotation_xieta(estimate[:, 0], estimate[:, 1], estimate[:, 2]) # type: ignore[arg-type] + fp.gamma = estimate[:, 2] + + # Apply the pointing model + bs, fp_corrected = apply_pointing_model( None, self.parameters, 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) + * quat.rotation_lonlat(-1 * det_enc_msk.az, det_enc_msk.el) + * quat.euler( + 2, (not self.force_zero_roll) * det_enc_msk.roll + ) + * q_fp + ) + + if fp_corrected is None: + to_ret.xyz = np.column_stack((xi, eta, gamma)) + return to_ret + + # Estimate and remove focalplane distortion + if fake_gamma: + distortion = np.column_stack((fp_corrected.xi - fp.xi, fp_corrected.eta - fp.eta)) + resid = np.column_stack((fp_corrected.xi - fp_target[:, 0], fp_corrected.eta - fp_target[:, 1])) + else: + distortion = np.column_stack((fp_corrected.xi - fp.xi, fp_corrected.eta - fp.eta, fp_corrected.gamma - fp.gamma)) + resid = np.column_stack((fp_corrected.xi - fp_target[:, 0], fp_corrected.eta - fp_target[:, 1], fp_corrected.gamma - fp_target[:, 2])) + err = np.sqrt(np.nanmean(np.linalg.norm(resid, axis=1)**2)) + + if err < tol: + to_ret = deepcopy(det_off) + to_ret.xyz[msk] = np.column_stack((xi, eta, gamma)) + return to_ret + + # Update estimate of the undistorted fp + estimate -= 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): """ @@ -301,7 +358,7 @@ def load(cls, f: h5py.File, path: str) -> Self: epoch=cast(str, group.attrs["epoch"]), parameters=parameters, force_zero_roll=cast(bool, group.attrs["force_zero_roll"]), - pad=cast(bool, group.attrs["pad"]), + pad=cast(bool, group.attrs.get("pad", False)), ) @@ -517,6 +574,14 @@ def ancil(self): 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 save(self, f: h5py.File, path: str, overwrite: bool = True): """Save detector offsets to an HDF5 ResultSet. @@ -886,7 +951,7 @@ def freeze(self, static: bool): @property def _data_pm_dyn(self) -> DetectorOffsets: - to_ret = self.pointing_model.apply_det(self.data, self.enc, self.fake_gamma) + to_ret = self.pointing_model.apply_det(self.data, self.enc, self.weights, self.fake_gamma) if self.autofreeze: self._data_pm_stat = to_ret return to_ret @@ -897,15 +962,15 @@ def _transform_dyn(self) -> Transform: @property def _transformed_dyn(self) -> DetectorOffsets: - return _transformed(self, "_transformed_stat") + return _transformed(self, "_transformed_stat", self.transform) @property def _pm_transform_dyn(self) -> Transform: - return _get_aff(self, "pm_data", "_pm_transform_stat") + return _get_aff(self, "data_pm", "_pm_transform_stat") @property def _pm_transformed_dyn(self) -> DetectorOffsets: - return _transformed(self, "_pm_transformed_stat") + return _transformed(self, "_pm_transformed_stat", self.pm_transform) @property def resid(self): @@ -1180,7 +1245,7 @@ def _transform_dyn(self) -> Transform: @property def _transformed_dyn(self) -> DetectorOffsets: - return _transformed(self, "_transformed_stat") + return _transformed(self, "_transformed_stat", self.transform) @property def resid(self): @@ -1836,15 +1901,10 @@ def set_static(self, static : bool): meas.static = static @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 parameters(self) -> list: + return [ 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"]): + def update_parameters(self, new_pars: list): for val, par, par_map in zip( new_pars, self.parameter_names, self.parameter_map ): From 3cc416981f0fc7e63e0f5cd56e6911862332c8fb Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Fri, 6 Nov 2026 15:08:23 -0800 Subject: [PATCH 100/132] fix: take in default overrides and reduce copies --- sotodlib/coords/fp_containers.py | 33 ++++++++++++------- .../site_pipeline/solve_static_pointing.py | 1 + 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 96b25295e..33452b5b3 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -219,6 +219,9 @@ def apply_det( Telescope encoder values in the `horizon` coordinate system. These provide the boresight azimuth, elevation, and roll used to evaluate the pointing model. + weights : Float[np.ndarray, "ndet"] + Detector weights. Only used to mask out nan of 0 weight detectors during + the inversion calculation. The output will still include all dets. fake_gamma : bool If True, ignore detector polarization angles and propagate only detector position (`xi`, `eta`). If False, propagate the full @@ -251,16 +254,15 @@ def apply_det( # Start with the input detector coordinates msk = np.isfinite(weights) * (weights > 0) - estimate = det_off.xyz.copy()[msk] - fp_target = det_off.xyz[msk] + if not np.any(msk): + return deepcopy(det_off) + estimate = det_off.xyz[msk].copy() if fake_gamma: estimate = estimate[:, :2] + fp_target = det_off[msk] to_ret = deepcopy(det_off) - tmp = deepcopy(det_off) - tmp.xyz = tmp.xyz[msk] - fp = tmp.fp - det_enc_msk = deepcopy(det_enc) - det_enc_msk.xyz = det_enc_msk.xyz[msk] + fp = to_ret[msk].fp + det_enc_msk = det_enc[msk] ancil = det_enc_msk.ancil err = np.inf @@ -287,20 +289,19 @@ def apply_det( ) if fp_corrected is None: - to_ret.xyz = np.column_stack((xi, eta, gamma)) + to_ret.xyz[msk] = np.column_stack((xi, eta, gamma)) return to_ret # Estimate and remove focalplane distortion if fake_gamma: distortion = np.column_stack((fp_corrected.xi - fp.xi, fp_corrected.eta - fp.eta)) - resid = np.column_stack((fp_corrected.xi - fp_target[:, 0], fp_corrected.eta - fp_target[:, 1])) + resid = np.column_stack((fp_corrected.xi - fp_target.xi, fp_corrected.eta - fp_target.eta)) else: distortion = np.column_stack((fp_corrected.xi - fp.xi, fp_corrected.eta - fp.eta, fp_corrected.gamma - fp.gamma)) - resid = np.column_stack((fp_corrected.xi - fp_target[:, 0], fp_corrected.eta - fp_target[:, 1], fp_corrected.gamma - fp_target[:, 2])) + 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.linalg.norm(resid, axis=1)**2)) if err < tol: - to_ret = deepcopy(det_off) to_ret.xyz[msk] = np.column_stack((xi, eta, gamma)) return to_ret @@ -521,6 +522,15 @@ def __setattr__(self, name: str, value: Any, /) -> None: self.__dict__.pop("ancil", 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)) @@ -2191,6 +2201,7 @@ def _group_epochs(dat, groups, desc, check_fields): 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 += list(pars.keys()) pars["version"] = pm_ver pm.parameters = pars diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index 44c638fef..2d21ae1c4 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -40,6 +40,7 @@ "pm_groups": [], "pad_epochs": [], "pm_ver_override": {}, + "pm_defaults_overrides": {}, "par_groups": {}, "root_dir": "~", "project_dir": "pointing", From ae8e70cb2591076d23c212dc6e4282ce5d1b436e Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Fri, 6 Nov 2026 15:27:05 -0800 Subject: [PATCH 101/132] fix: only include numeric params in the top level parameter list --- sotodlib/coords/fp_containers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 33452b5b3..37e984776 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -2202,7 +2202,7 @@ def _group_epochs(dat, groups, desc, check_fields): 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 += list(pars.keys()) + 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() From c7882e1625ab07fefb10ddeb2fe1d168f769c0d5 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Fri, 6 Nov 2026 15:40:24 -0800 Subject: [PATCH 102/132] feat: move per obs to a dedicated func --- .../site_pipeline/solve_static_pointing.py | 211 +++++++++--------- 1 file changed, 108 insertions(+), 103 deletions(-) diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index 2d21ae1c4..6d3f36c17 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -354,6 +354,112 @@ def _load_obs(aman, obs_id, array, ctx, system, cfg): return loaded +def _run_per_obs(open_jobs, done_jobs, jdb, ctx, system, cfg, plot_dir): + job = None + njobs = len(open_jobs) + logger.info( + "Starting per-obs mode with %d open jobs and %d already done", + njobs, + len(done_jobs), + ) + open_jobs += [None] + 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 + + # Locate + # TODO: I must be able to cache/hash somehow for this + rx = system.search("receivers", float(job.tags["timestamp"])) + if rx is None: + raise ValueError(f"Somehow found no receiver for {jstr}") + fp = rx.find_fpc(job.tags["ot"], array) + if fp is None: + raise ValueError(f"Somehow found no focal plane for {jstr}") + + + # 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) + continue + + # Init the fp + meas = _load_obs(aman, obs_id, array, ctx, system, cfg) + try: + meas = _load_obs(aman, obs_id, array, ctx, system, cfg) + except Exception as e: + msg = f"Failed to build focal plane with error: {e}" + ju.fail(job, ErrCode.FPINIT, msg, logger) + 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 + + # 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) + logger.info("Done with per-obs mode!") + + def _check_jobs(system, jdb, done_jobs, open_jobs): to_open = [] in_system = [] @@ -451,6 +557,7 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): 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, @@ -472,109 +579,7 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): 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 - job = None - njobs = len(open_jobs) - logger.info( - "Starting per-obs mode with %d open jobs and %d already done", - njobs, - len(done_jobs), - ) - open_jobs += [None] - 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 - - # Locate - # TODO: I must be able to cache/hash somehow for this - rx = system.search("receivers", float(job.tags["timestamp"])) - if rx is None: - raise ValueError(f"Somehow found no receiver for {jstr}") - fp = rx.find_fpc(job.tags["ot"], array) - if fp is None: - raise ValueError(f"Somehow found no focal plane for {jstr}") - - - # 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) - continue - - # Init the fp - meas = _load_obs(aman, obs_id, array, ctx, system, cfg) - try: - meas = _load_obs(aman, obs_id, array, ctx, system, cfg) - except Exception as e: - msg = f"Failed to build focal plane with error: {e}" - ju.fail(job, ErrCode.FPINIT, msg, logger) - 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 - - # 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) - logger.info("Done with per-obs mode!") + _run_per_obs(open_jobs, done_jobs, jdb, ctx, system, cfg, plot_dir) # Pad empty if needed if cfg.pad_empty: From e5f1ed6ae98b219a10dd74d8f8c337e2afd8491f Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Fri, 6 Nov 2026 15:50:48 -0800 Subject: [PATCH 103/132] feat: add infra for init pars and bounds --- sotodlib/coords/fp_containers.py | 6 +++--- .../site_pipeline/solve_static_pointing.py | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 37e984776..991fb26c1 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -1911,10 +1911,10 @@ def set_static(self, static : bool): meas.static = static @property - def parameters(self) -> list: - return [ self.pointing_models[par_map[0]].parameters[par.split("(")[0]] for par, par_map in zip(self.parameter_names, self.parameter_map) ] + 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: list): + def update_parameters(self, new_pars: Float[np.ndarray, "npar"]): for val, par, par_map in zip( new_pars, self.parameter_names, self.parameter_map ): diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index 6d3f36c17..ca4f6f1ce 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -55,6 +55,7 @@ "min_hits": 3, "min_r2": .3, "pad_empty": True, + "parameters": {}, } @@ -586,15 +587,32 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): system.set_pad(cfg.pad_epochs, True) # Save our per-obs results + # TODO: Setup databases! system.set_static(True) with h5py.File(outfile, "a") as f: system.save(f, "/", True) + # Setup fit params + params = system.parameters.copy() + bounds = [(-np.inf, np.inf)]*len(params) + for name, par in cfg.parameters: + if name not in system.parameter_names: + logger.warning("Unknown paramter %s", name) + continue + idx = system.parameter_names.index(name) + params[idx] = par.get("init", params[idx]) + if par.get("static", False): + bounds[idx] = (params[idx], params[idx]) + continue + bounds[idx] = tuple(par.get("bounds", bounds[idx])[:2]) + system.update_parameters(params) + # TODO: Fit for pointing model and focal planes system.set_static(False) # Save # TODO: Setup databases! + system.set_static(True) with h5py.File(outfile, "a") as f: system.save(f, "/", True) From ed8de5ea11750967fdb990af1f6a0af3d907826a Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Sun, 8 Nov 2026 17:35:06 -0800 Subject: [PATCH 104/132] feat: fit loop --- sotodlib/coords/fp_containers.py | 14 ++++-- .../site_pipeline/solve_static_pointing.py | 45 ++++++++++++++++++- 2 files changed, 55 insertions(+), 4 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 991fb26c1..65ed186a4 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -106,9 +106,10 @@ def _transformed(self: FocalPlane | FocalPlaneCollection, attr_name: str, transf def _get_aff(self: FocalPlane | FocalPlaneCollection, data_name: str, attr_name: str): + wmsk = (self.weights > 0) * np.isfinite(self.weights) affine, shift = mt.get_affine_two_stage( - self.template.xyz[:, :2], - getattr(self, data_name).xyz[:, :2], + self.template.xyz[wmsk, :2], + getattr(self, data_name).xyz[wmsk, :2], self.weights, ) to_ret = Transform.identity() @@ -116,7 +117,7 @@ def _get_aff(self: FocalPlane | FocalPlaneCollection, data_name: str, attr_name: to_ret.affine[:2, :2] = affine if not self.fake_gamma: to_ret.affine[-1, -1], to_ret.shift[-1] = gamma_fit( - self.template.xyz[:, 2], getattr(self, data_name).xyz[:, 2] + self.template.xyz[wmsk, 2], getattr(self, data_name).xyz[wmsk, 2] ) if self.autofreeze: setattr(self, attr_name, to_ret) @@ -1964,6 +1965,13 @@ def chisq_cm_prior( return np.inf return self.chisq + def objective(self, params, cm_priors): + self.update_parameters(params) + return self.chisq_cm_prior(**cm_priors) + + def log_prob(self, params, cm_priors): + return -.5*self.objective(params, cm_priors) + @overload def search( self, field: Literal["pointing_models"], timestamp: float diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index ca4f6f1ce..3fa80ff6b 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -30,6 +30,8 @@ from sotodlib.utils.config import load_config_namespace from sotodlib.site_pipeline import jobdb import sqlalchemy as sqy +from scipy.optimize import minimize +import emcee logger = init_logger(__name__, "solve_static_pointing: ") default_config = { @@ -56,6 +58,11 @@ "min_r2": .3, "pad_empty": True, "parameters": {}, + "n_rounds": 3, + "cm_priors": {"sft_tol":1e-5, "rot_tol":1e4, "scl_tol":.1, "shr_tol":.01}, + "outlier_sigma": 3, + "mcmc_steps": 0, + "nwalkers": 32, } @@ -607,8 +614,44 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): bounds[idx] = tuple(par.get("bounds", bounds[idx])[:2]) system.update_parameters(params) - # TODO: Fit for pointing model and focal planes + # Fit for pointing model and focal planes system.set_static(False) + for i in range(cfg.n_rounds): + logger.info("Starting fit round %d", i+1) + res = minimize(system.objective, system.parameters, bounds=bounds, args=(cfg.cm_priors,), method="Nelder-Mead") + system.update_parameters(res.x) + + # Cut outliers + tot_cut = 0 + for rx in system.receivers: + for ot in rx.optics_tubes: + for fp in ot.focal_planes: + for meas in fp.focal_planes: + resid = meas.data_pm.xyz - meas.pm_transformed.xyz + wmsk = np.isfinite(meas.weights) * (meas.weights > 0) + if meas.fake_gamma: + err = np.linalg.norm(resid[:, :2], axis=1) + else: + err = np.linalg.norm(resid, axis=1) + mrmsk = err > cfg.outlier_sigma*np.std(err[wmsk]) + meas.weights[mrmsk] = 0 + tot_cut += np.sum(mrmsk[wmsk]) + if tot_cut == 0: + break + + # Run MCMC if we want + if cfg.mcmc_steps > 0: + ndim = len(system.parameters) + sampler = emcee.EnsembleSampler(cfg.nwalkers, ndim, system.log_prob, args=(cfg.cm_priors,)) + sampler.run_mcmc(system.parameters, cfg.mcmc_steps) + samples = np.array(sampler.get_chain(discard=int(.1*cfg.mcmc_steps), flat=True)) + system.update_parameters(np.median(samples, axis=0)) + lower = np.percentile(samples, 16, axis=0) + upper = np.percentile(samples, 84, axis=0) + _ = lower, upper + # TODO: Save the chain somewhere + # TODO: MCMC plots + # TODO: plots # Save # TODO: Setup databases! From de72dbb13dd88cf66ab1e7326930de7a59eed50c Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Sun, 8 Nov 2026 20:51:20 -0800 Subject: [PATCH 105/132] feat: make focal plaes aware of their parents --- sotodlib/coords/fp_containers.py | 122 ++++++++++-------- .../site_pipeline/solve_static_pointing.py | 50 +++---- 2 files changed, 87 insertions(+), 85 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 65ed186a4..68ad2d298 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -721,12 +721,8 @@ class FocalPlane: weights : Float[np.ndarray, "ndet"] Per-detector weights used when fitting transforms and combining measurements. - template : DetectorOffsets - Reference detector layout used as the transform source on sky. - 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. + parent : FocalPlaneCollection + The collection that this measurement belongs to. pointing_model : PointingModel Pointing model to apply before computing corrected transforms. static : bool @@ -752,6 +748,12 @@ class FocalPlane: Residuals between `data` and `transformed`. pm_resid : Float[np.ndarray, "ndet 3"] Residuals between `data_pm` and `pm_transformed`. + template : DetectorOffsets + Reference detector layout used as the transform source on sky. + 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. """ name: str @@ -759,10 +761,8 @@ class FocalPlane: data: DetectorOffsets enc: DetectorOffsets weights: Float[np.ndarray, "ndet"] - template: DetectorOffsets - template_fp: DetectorOffsets - template_ot: DetectorOffsets - pointing_model: PointingModel + parent: FocalPlaneCollection + pointing_model : PointingModel static: bool autofreeze: bool fake_gamma: bool @@ -771,11 +771,25 @@ class FocalPlane: 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") _data_pm_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) + + @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 @classmethod def from_aman( @@ -783,10 +797,8 @@ def from_aman( name: str, meas_id: str, aman: AxisManager, - template: DetectorOffsets, - template_fp: DetectorOffsets, - template_ot: DetectorOffsets, - pointing_model: PointingModel, + parent: FocalPlaneCollection, + pointing_model : PointingModel, autofreeze: bool = False, fake_gamma: bool = True, weight_factor: float = 1000.0, @@ -809,12 +821,8 @@ def from_aman( aman : AxisManager Input data container holding focal plane and detector metadata. See above for details on assumptions. - template : DetectorOffsets - Template focal plane. - 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. + parent : FocalPlaneCollection + The collection that this measurement belongs to. pointing_model : PointingModel Pointing model associated with the observation. autofreeze : bool, default: False @@ -832,6 +840,7 @@ def from_aman( 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) @@ -935,9 +944,7 @@ def from_aman( data, enc, weights, - template, - template_fp, - template_ot, + parent, pointing_model, False, autofreeze, @@ -983,6 +990,10 @@ def _pm_transform_dyn(self) -> Transform: 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 @@ -991,6 +1002,10 @@ def resid(self): def pm_resid(self): return self.data_pm.xyz - self.pm_transformed.xyz + @property + def fpc_resid(self): + return self.data_pm.xyz - self.fpc_transformed.xyz + def save( self, f: h5py.File, @@ -1051,18 +1066,16 @@ def save( 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 - ) + 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, - template: DetectorOffsets, - template_fp: DetectorOffsets, - template_ot: DetectorOffsets, + parent: FocalPlaneCollection, pointing_models: tuple[PointingModel, ...], ) -> Self: """ @@ -1101,9 +1114,7 @@ def load( data=data, enc=enc, weights=weights, - template=template, - template_fp=template_fp, - template_ot=template_ot, + parent=parent, pointing_model=pointing_models[pm_idx], static=cast(bool, group.attrs["static"]), autofreeze=cast(bool, group.attrs["autofreeze"]), @@ -1120,6 +1131,8 @@ def load( 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") return fp @@ -1358,32 +1371,9 @@ def load( ) group = cast(h5py.Group, f[path]) - focal_planes = [] - for name in group: - if name in { - "template", - "template_fp", - "template_ot", - "data", - "weights", - "transform", - "transformed", - }: - continue - focal_planes.append( - FocalPlane.load( - f, - f"{path}/{name}", - template=template, - template_fp=template_fp, - template_ot=template_ot, - pointing_models=pointing_models, - ) - ) - collection = cls( name=cast(str, group.attrs["name"]), - focal_planes=focal_planes, + focal_planes=[], template=template, template_fp=template_fp, template_ot=template_ot, @@ -1408,6 +1398,26 @@ def load( f"{path}/transformed", ) + for name in group: + if name in { + "template", + "template_fp", + "template_ot", + "data", + "weights", + "transform", + "transformed", + }: + continue + collection.focal_planes.append( + FocalPlane.load( + f, + f"{path}/{name}", + parent=collection, + pointing_models=pointing_models, + ) + ) + return collection diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index 3fa80ff6b..fbfa6c556 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -33,6 +33,9 @@ from scipy.optimize import minimize import emcee +# TODO: Calculate a weighted per-det scatter +# TODO: Include per-det scatter in chisq + logger = init_logger(__name__, "solve_static_pointing: ") default_config = { "tel": "LAT", @@ -349,17 +352,27 @@ def _get_obslist(ctx, cfg, system): return obslist -def _load_obs(aman, obs_id, array, ctx, system, cfg): +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}") - loaded = fpc.FocalPlane.from_aman( fp.name, obs["obs_id"], aman, fp.template, fp.template_fp, fp.template_ot, pm, fp.autofreeze, fp.fake_gamma, cfg.weight_factor) + # 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 + return loaded, rx, fp def _run_per_obs(open_jobs, done_jobs, jdb, ctx, system, cfg, plot_dir): @@ -399,35 +412,15 @@ def _run_per_obs(open_jobs, done_jobs, jdb, ctx, system, cfg, plot_dir): ju.fail(job, ErrCode.LOADER, msg, logger) continue - # Locate - # TODO: I must be able to cache/hash somehow for this - rx = system.search("receivers", float(job.tags["timestamp"])) - if rx is None: - raise ValueError(f"Somehow found no receiver for {jstr}") - fp = rx.find_fpc(job.tags["ot"], array) - if fp is None: - raise ValueError(f"Somehow found no focal plane for {jstr}") - - - # 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) - continue - # Init the fp - meas = _load_obs(aman, obs_id, array, ctx, system, cfg) try: - meas = _load_obs(aman, obs_id, array, ctx, system, cfg) + 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) @@ -627,12 +620,11 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): for ot in rx.optics_tubes: for fp in ot.focal_planes: for meas in fp.focal_planes: - resid = meas.data_pm.xyz - meas.pm_transformed.xyz wmsk = np.isfinite(meas.weights) * (meas.weights > 0) if meas.fake_gamma: - err = np.linalg.norm(resid[:, :2], axis=1) + err = np.linalg.norm(meas.fpc_resid[:, :2], axis=1) else: - err = np.linalg.norm(resid, axis=1) + err = np.linalg.norm(meas.fpc_resid, axis=1) mrmsk = err > cfg.outlier_sigma*np.std(err[wmsk]) meas.weights[mrmsk] = 0 tot_cut += np.sum(mrmsk[wmsk]) From a41118eff7365fef921048e211b965201e93cce0 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Sun, 8 Nov 2026 21:06:45 -0800 Subject: [PATCH 106/132] feat: punish per-det scatter --- sotodlib/coords/fp_containers.py | 26 +++++++++++++++++-- .../site_pipeline/solve_static_pointing.py | 3 --- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 68ad2d298..17f90e6e3 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -6,7 +6,6 @@ """ # TODO: Reprs -# TODO: Implement roll dep stuff, need to be careful about the correct direction. Should be REMOVING it from the data I think from __future__ import annotations @@ -1215,10 +1214,12 @@ class FocalPlaneCollection: fake_gamma: bool data: ClassVar[StaticOrCached[DetectorOffsets]] = StaticOrCached("data") weights: ClassVar[StaticOrCached[Float[np.ndarray, "ndet"]]] = StaticOrCached("weights") + scatter: ClassVar[StaticOrCached[Float[np.ndarray, "ndet"]]] = StaticOrCached("scatter") 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) + _scatter_stat: Float[np.ndarray, "ndet"] = field(init=False) _transform_stat: Transform = field(init=False) _transformed_stat: DetectorOffsets = field(init=False) @@ -1239,6 +1240,7 @@ def freeze(self, static: bool): """ self._data_stat = self._data_dyn self._weights_stat = self._weights_dyn + self._scatter_stat = self._scatter_dyn self._transform_stat = self._transform_dyn self._transformed_stat = self._transformed_dyn self.static = static @@ -1263,6 +1265,16 @@ def _weights_dyn(self) -> Float[np.ndarray, "ndet"]: self._weights_stat = to_ret return to_ret + @property + def _scatter_dyn(self) -> Float[np.ndarray, "ndet"]: + dat_full = np.array( [fp.data_pm.xyz for fp in self.focal_planes]) + weights_full = np.array( [fp.weights for fp in self.focal_planes]) + mean = self.data.xyz + var = np.nansum( weights_full[..., None] * (dat_full - mean[None, ...])**2, axis=0,) / self.weights[..., None] + std = np.sqrt(var) + to_ret = np.sqrt(np.nanmean(std**2, axis=0)) + return to_ret + @property def _transform_dyn(self) -> Transform: return _get_aff(self, "data", "_transform_stat") @@ -1331,6 +1343,13 @@ def save( else: raise ValueError(f"{path}/weights already exists") f.create_dataset(f"{path}/weights", data=self._weights_stat) + if "_scatter_stat" in self.__dict__: + if f"{path}/scatter" in f: + if overwrite: + del f[f"{path}/scatter"] + else: + raise ValueError(f"{path}/scatter already exists") + f.create_dataset(f"{path}/scatter", data=self._scatter_stat) if "_transform_stat" in self.__dict__: self._transform_stat.save(f, f"{path}/transform") if "_transformed_stat" in self.__dict__: @@ -1390,6 +1409,8 @@ def load( ) 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: @@ -1405,6 +1426,7 @@ def load( "template_ot", "data", "weights", + "scatter", "transform", "transformed", }: @@ -1941,7 +1963,7 @@ def chisq(self) -> float: for fp in ot.focal_planes: if fp.pad: continue - chisq += np.nansum((fp.weights * fp.resid) ** 2).item() + chisq += np.nansum(((fp.weights * fp.resid) ** 2)*fp.scatter).item() return chisq def chisq_cm_prior( diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index fbfa6c556..020eeb9d7 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -33,9 +33,6 @@ from scipy.optimize import minimize import emcee -# TODO: Calculate a weighted per-det scatter -# TODO: Include per-det scatter in chisq - logger = init_logger(__name__, "solve_static_pointing: ") default_config = { "tel": "LAT", From 37383507da9405482814989a361555e09a5bf0e4 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Sun, 8 Nov 2026 21:07:36 -0800 Subject: [PATCH 107/132] chore: pep8 --- sotodlib/coords/fp_containers.py | 186 ++++++++++++------ sotodlib/coords/fp_plots.py | 11 +- .../site_pipeline/solve_static_pointing.py | 59 ++++-- 3 files changed, 180 insertions(+), 76 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 17f90e6e3..0a8a9d67c 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -14,15 +14,26 @@ from copy import deepcopy from dataclasses import dataclass, field from functools import cached_property, reduce -from typing import Any, Iterable, Literal, Optional, Self, cast, overload, ClassVar, TypeVar, Generic +from typing import ( + Any, + ClassVar, + Generic, + Iterable, + Literal, + Optional, + Self, + TypeVar, + cast, + overload, +) import h5py import megham.transform as mt import megham.utils as mu import numpy as np from jaxtyping import Float, Integer, Shaped -from scipy.optimize import minimize 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 @@ -89,7 +100,9 @@ def _gamma_min(pars, src, dst): return res.x -def _transformed(self: FocalPlane | FocalPlaneCollection, attr_name: str, transform: Transform): +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 @@ -140,12 +153,12 @@ def __set_name__(self, owner, attr_name): self.attr_name = attr_name @overload - def __get__( self, obj: None, owner: type) -> "StaticOrCached[T]": ... + 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: ... - def __get__( self, obj: Any, owner: type | None = None) -> T | "StaticOrCached[T]": + def __get__(self, obj: Any, owner: type | None = None) -> T | "StaticOrCached[T]": if obj is None: return self @@ -193,23 +206,23 @@ def apply_det( ) -> 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. - + If the pointing model contains no parameters, the input detector offsets are returned unchanged. - + When `force_zero_roll=True`, the encoder roll angle is ignored during the correction and a zero-roll boresight solution is assumed. - + Parameters ---------- det_off : DetectorOffsets @@ -230,14 +243,14 @@ def apply_det( RMS convergence tolerance for the iterative distortion removal, in radians. max_iter : int, default: 5 Maximum number of iterations for the distortion removal. - + Returns ------- det_pm : DetectorOffsets A copy of `det_off` 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 ------ ValueError @@ -248,10 +261,12 @@ def apply_det( """ if len(self.parameters) == 0: return det_off - + if len(det_enc.xyz) != len(det_off.xyz): - raise ValueError( "Detector offsets and encoder values must have same shape!") - + raise ValueError( + "Detector offsets and encoder values must have same shape!" + ) + # Start with the input detector coordinates msk = np.isfinite(weights) * (weights > 0) if not np.any(msk): @@ -267,24 +282,22 @@ def apply_det( err = np.inf for _ in range(max_iter): - fp.xi = estimate[:, 0] - fp.eta = estimate[:, 1] + fp.xi = estimate[:, 0] + fp.eta = estimate[:, 1] if fake_gamma: q_fp = quat.rotation_xieta(estimate[:, 0], estimate[:, 1]) else: - q_fp = quat.rotation_xieta(estimate[:, 0], estimate[:, 1], estimate[:, 2]) # type: ignore[arg-type] - fp.gamma = estimate[:, 2] + q_fp = quat.rotation_xieta(estimate[:, 0], estimate[:, 1], estimate[:, 2]) # type: ignore[arg-type] + fp.gamma = estimate[:, 2] # Apply the pointing model - bs, fp_corrected = apply_pointing_model( None, self.parameters, ancil, fp) + bs, fp_corrected = apply_pointing_model(None, self.parameters, 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) * quat.rotation_lonlat(-1 * det_enc_msk.az, det_enc_msk.el) - * quat.euler( - 2, (not self.force_zero_roll) * det_enc_msk.roll - ) + * quat.euler(2, (not self.force_zero_roll) * det_enc_msk.roll) * q_fp ) @@ -294,12 +307,28 @@ def apply_det( # Estimate and remove focalplane distortion if fake_gamma: - distortion = np.column_stack((fp_corrected.xi - fp.xi, fp_corrected.eta - fp.eta)) - resid = np.column_stack((fp_corrected.xi - fp_target.xi, fp_corrected.eta - fp_target.eta)) + distortion = np.column_stack( + (fp_corrected.xi - fp.xi, fp_corrected.eta - fp.eta) + ) + resid = np.column_stack( + (fp_corrected.xi - fp_target.xi, fp_corrected.eta - fp_target.eta) + ) else: - distortion = np.column_stack((fp_corrected.xi - fp.xi, fp_corrected.eta - fp.eta, fp_corrected.gamma - fp.gamma)) - 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.linalg.norm(resid, axis=1)**2)) + distortion = np.column_stack( + ( + fp_corrected.xi - fp.xi, + fp_corrected.eta - fp.eta, + fp_corrected.gamma - fp.gamma, + ) + ) + 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.linalg.norm(resid, axis=1) ** 2)) if err < tol: to_ret.xyz[msk] = np.column_stack((xi, eta, gamma)) @@ -308,8 +337,9 @@ def apply_det( # Update estimate of the undistorted fp estimate -= distortion - raise RuntimeError(f"Pointing-model inversion did not converge after {max_iter} iterations (error={err:.3e} rad).") - + 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): """ @@ -326,7 +356,12 @@ def save(self, f: h5py.File, path: str, overwrite: bool = True): """ group = _create_group(f, path, overwrite) _add_attrs( - group, {"epoch": self.epoch, "force_zero_roll": self.force_zero_roll, "pad": self.pad} + group, + { + "epoch": self.epoch, + "force_zero_roll": self.force_zero_roll, + "pad": self.pad, + }, ) parameters = AxisManager() @@ -761,16 +796,22 @@ class FocalPlane: enc: DetectorOffsets weights: Float[np.ndarray, "ndet"] parent: FocalPlaneCollection - pointing_model : PointingModel + pointing_model: PointingModel static: bool autofreeze: bool fake_gamma: bool data_pm: ClassVar[StaticOrCached[DetectorOffsets]] = StaticOrCached("data_pm") transform: ClassVar[StaticOrCached[Transform]] = StaticOrCached("transform") - transformed: ClassVar[StaticOrCached[DetectorOffsets]] = StaticOrCached("transformed") + 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_transformed: ClassVar[StaticOrCached[DetectorOffsets]] = StaticOrCached( + "pm_transformed" + ) + fpc_transformed: ClassVar[StaticOrCached[DetectorOffsets]] = StaticOrCached( + "fpc_transformed" + ) _data_pm_stat: DetectorOffsets = field(init=False) _transform_stat: Transform = field(init=False) _transformed_stat: DetectorOffsets = field(init=False) @@ -797,7 +838,7 @@ def from_aman( meas_id: str, aman: AxisManager, parent: FocalPlaneCollection, - pointing_model : PointingModel, + pointing_model: PointingModel, autofreeze: bool = False, fake_gamma: bool = True, weight_factor: float = 1000.0, @@ -842,7 +883,9 @@ def from_aman( 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) + _, 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] @@ -897,7 +940,9 @@ def from_aman( 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)) + 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): @@ -968,7 +1013,9 @@ def freeze(self, static: bool): @property def _data_pm_dyn(self) -> DetectorOffsets: - to_ret = self.pointing_model.apply_det(self.data, self.enc, self.weights, self.fake_gamma) + to_ret = self.pointing_model.apply_det( + self.data, self.enc, self.weights, self.fake_gamma + ) if self.autofreeze: self._data_pm_stat = to_ret return to_ret @@ -1065,9 +1112,13 @@ def save( 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) + 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) + self._fpc_transformed_stat.save( + f, f"{path}/fpc_transformed", overwrite=overwrite + ) @classmethod def load( @@ -1131,7 +1182,9 @@ def load( 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") + fp._fpc_transformed_stat = DetectorOffsets.load( + f, f"{path}/fpc_transformed" + ) return fp @@ -1213,10 +1266,16 @@ class FocalPlaneCollection: pad: bool fake_gamma: bool data: ClassVar[StaticOrCached[DetectorOffsets]] = StaticOrCached("data") - weights: ClassVar[StaticOrCached[Float[np.ndarray, "ndet"]]] = StaticOrCached("weights") - scatter: ClassVar[StaticOrCached[Float[np.ndarray, "ndet"]]] = StaticOrCached("scatter") + weights: ClassVar[StaticOrCached[Float[np.ndarray, "ndet"]]] = StaticOrCached( + "weights" + ) + scatter: ClassVar[StaticOrCached[Float[np.ndarray, "ndet"]]] = StaticOrCached( + "scatter" + ) transform: ClassVar[StaticOrCached[Transform]] = StaticOrCached("transform") - transformed: ClassVar[StaticOrCached[DetectorOffsets]] = StaticOrCached("transformed") + transformed: ClassVar[StaticOrCached[DetectorOffsets]] = StaticOrCached( + "transformed" + ) _data_stat: DetectorOffsets = field(init=False) _weights_stat: Float[np.ndarray, "ndet"] = field(init=False) _scatter_stat: Float[np.ndarray, "ndet"] = field(init=False) @@ -1267,10 +1326,16 @@ def _weights_dyn(self) -> Float[np.ndarray, "ndet"]: @property def _scatter_dyn(self) -> Float[np.ndarray, "ndet"]: - dat_full = np.array( [fp.data_pm.xyz for fp in self.focal_planes]) - weights_full = np.array( [fp.weights for fp in self.focal_planes]) + dat_full = np.array([fp.data_pm.xyz for fp in self.focal_planes]) + weights_full = np.array([fp.weights for fp in self.focal_planes]) mean = self.data.xyz - var = np.nansum( weights_full[..., None] * (dat_full - mean[None, ...])**2, axis=0,) / self.weights[..., None] + var = ( + np.nansum( + weights_full[..., None] * (dat_full - mean[None, ...]) ** 2, + axis=0, + ) + / self.weights[..., None] + ) std = np.sqrt(var) to_ret = np.sqrt(np.nanmean(std**2, axis=0)) return to_ret @@ -1703,7 +1768,7 @@ class Receiver: corresponding static fields. allpad : bool Flag indicating whether all optics tube are padded - and should therefore be excluded from fitting. + and should therefore be excluded from fitting. cm_transform : Transform Receiver-level common-mode transform derived from the common-mode transforms of all optics tubes containing valid data. @@ -1925,7 +1990,7 @@ def __post_init__(self): # Force consistancy self.update_parameters(self.parameters) - def set_static(self, static : bool): + def set_static(self, static: bool): """ Set `static` for all relevent childen. @@ -1945,7 +2010,12 @@ def set_static(self, static : bool): @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)]) + 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"]): for val, par, par_map in zip( @@ -1963,7 +2033,9 @@ def chisq(self) -> float: for fp in ot.focal_planes: if fp.pad: continue - chisq += np.nansum(((fp.weights * fp.resid) ** 2)*fp.scatter).item() + chisq += np.nansum( + ((fp.weights * fp.resid) ** 2) * fp.scatter + ).item() return chisq def chisq_cm_prior( @@ -2002,7 +2074,7 @@ def objective(self, params, cm_priors): return self.chisq_cm_prior(**cm_priors) def log_prob(self, params, cm_priors): - return -.5*self.objective(params, cm_priors) + return -0.5 * self.objective(params, cm_priors) @overload def search( @@ -2242,7 +2314,11 @@ def _group_epochs(dat, groups, desc, check_fields): 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))] + 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() diff --git a/sotodlib/coords/fp_plots.py b/sotodlib/coords/fp_plots.py index ed82eca91..f83ffc842 100644 --- a/sotodlib/coords/fp_plots.py +++ b/sotodlib/coords/fp_plots.py @@ -192,7 +192,7 @@ def plot_ufm( focal_plane: FocalPlane | FocalPlaneCollection, output_dir: str, figsize: tuple[float, float] = (12, 6), - with_pm: bool = True + with_pm: bool = True, ): """ Plot the UFM focal-plane fit and residual distribution. @@ -246,7 +246,14 @@ def plot_ufm( ax1.legend() # Plot histogram of residuals. - dist = 3600 * np.linalg.norm(np.rad2deg( (transformed.xyz - data.xyz)[np.isfinite(focal_plane.weights) * (focal_plane.weights > 0), :2]), axis=1) + dist = 3600 * np.linalg.norm( + np.rad2deg( + (transformed.xyz - data.xyz)[ + np.isfinite(focal_plane.weights) * (focal_plane.weights > 0), :2 + ] + ), + axis=1, + ) if len(dist) > 0: dist_thresh = np.percentile(dist, 97) bins = max(int(len(dist) / 20), 10) diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index 020eeb9d7..e25f0d166 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -14,6 +14,7 @@ from functools import partial from typing import cast +import emcee import git import h5py import numpy as np @@ -21,17 +22,16 @@ 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 minimize 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 -from sotodlib.site_pipeline import jobdb -import sqlalchemy as sqy -from scipy.optimize import minimize -import emcee logger = init_logger(__name__, "solve_static_pointing: ") default_config = { @@ -55,11 +55,11 @@ "max_dscale": 0.1, "max_shear": 0.05, "min_hits": 3, - "min_r2": .3, + "min_r2": 0.3, "pad_empty": True, "parameters": {}, "n_rounds": 3, - "cm_priors": {"sft_tol":1e-5, "rot_tol":1e4, "scl_tol":.1, "shr_tol":.01}, + "cm_priors": {"sft_tol": 1e-5, "rot_tol": 1e4, "scl_tol": 0.1, "shr_tol": 0.01}, "outlier_sigma": 3, "mcmc_steps": 0, "nwalkers": 32, @@ -111,7 +111,7 @@ def _get_tags_po(info): "obs_id": obs["obs_id"], "ot": obs["tube_slot"], "timestamp": obs["timestamp"], - "array": array, + "array": array, "wafer_slot": wafer_slot, "errcode": 0, "message": "", @@ -358,7 +358,7 @@ def _load_obs(aman, obs_id, array, ctx, system, cfg, job): 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 ) + 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) @@ -366,7 +366,16 @@ def _load_obs(aman, obs_id, array, ctx, system, cfg, job): 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) + 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 @@ -443,7 +452,9 @@ def _run_per_obs(open_jobs, done_jobs, jdb, ctx, system, cfg, plot_dir): continue # Plot - pdir = os.path.join(plot_dir, rx.epoch, "per-obs", str(job.tags["timestamp"])[:5]) + 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) @@ -579,7 +590,7 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): # 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) - # Pad empty if needed + # Pad empty if needed if cfg.pad_empty: system.set_pad(cfg.pad_epochs, True) @@ -591,7 +602,7 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): # Setup fit params params = system.parameters.copy() - bounds = [(-np.inf, np.inf)]*len(params) + bounds = [(-np.inf, np.inf)] * len(params) for name, par in cfg.parameters: if name not in system.parameter_names: logger.warning("Unknown paramter %s", name) @@ -607,8 +618,14 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): # Fit for pointing model and focal planes system.set_static(False) for i in range(cfg.n_rounds): - logger.info("Starting fit round %d", i+1) - res = minimize(system.objective, system.parameters, bounds=bounds, args=(cfg.cm_priors,), method="Nelder-Mead") + logger.info("Starting fit round %d", i + 1) + res = minimize( + system.objective, + system.parameters, + bounds=bounds, + args=(cfg.cm_priors,), + method="Nelder-Mead", + ) system.update_parameters(res.x) # Cut outliers @@ -619,10 +636,10 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): 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) + err = np.linalg.norm(meas.fpc_resid[:, :2], axis=1) else: - err = np.linalg.norm(meas.fpc_resid, axis=1) - mrmsk = err > cfg.outlier_sigma*np.std(err[wmsk]) + err = np.linalg.norm(meas.fpc_resid, axis=1) + mrmsk = err > cfg.outlier_sigma * np.std(err[wmsk]) meas.weights[mrmsk] = 0 tot_cut += np.sum(mrmsk[wmsk]) if tot_cut == 0: @@ -631,9 +648,13 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): # Run MCMC if we want if cfg.mcmc_steps > 0: ndim = len(system.parameters) - sampler = emcee.EnsembleSampler(cfg.nwalkers, ndim, system.log_prob, args=(cfg.cm_priors,)) + sampler = emcee.EnsembleSampler( + cfg.nwalkers, ndim, system.log_prob, args=(cfg.cm_priors,) + ) sampler.run_mcmc(system.parameters, cfg.mcmc_steps) - samples = np.array(sampler.get_chain(discard=int(.1*cfg.mcmc_steps), flat=True)) + samples = np.array( + sampler.get_chain(discard=int(0.1 * cfg.mcmc_steps), flat=True) + ) system.update_parameters(np.median(samples, axis=0)) lower = np.percentile(samples, 16, axis=0) upper = np.percentile(samples, 84, axis=0) From d8cdf88e60bda575c3ccc734420295521762051c Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Sun, 8 Nov 2026 21:13:21 -0800 Subject: [PATCH 108/132] fix: avoid single point scatter from zeroing out chisq --- sotodlib/coords/fp_containers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 0a8a9d67c..723fbce9c 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -2034,7 +2034,7 @@ def chisq(self) -> float: if fp.pad: continue chisq += np.nansum( - ((fp.weights * fp.resid) ** 2) * fp.scatter + ((fp.weights * fp.resid) ** 2) * (1 + fp.scatter) ).item() return chisq From 149ce68263dd0f4603cb48eea790dc27e5aa1a7f Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Sun, 8 Nov 2026 21:17:32 -0800 Subject: [PATCH 109/132] fix: bad fstring --- sotodlib/site_pipeline/solve_pointing_model.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sotodlib/site_pipeline/solve_pointing_model.py b/sotodlib/site_pipeline/solve_pointing_model.py index 4303eb670..aabf8c108 100644 --- a/sotodlib/site_pipeline/solve_pointing_model.py +++ b/sotodlib/site_pipeline/solve_pointing_model.py @@ -772,7 +772,7 @@ def main(config_path: str): 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"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) ") From 05a04b52bafe6f1c24487cbc573095f27ec1bc58 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Sun, 8 Nov 2026 21:50:48 -0800 Subject: [PATCH 110/132] fix: more consistant naming --- sotodlib/coords/fp_containers.py | 38 ++++++++++++++++---------------- sotodlib/coords/fp_plots.py | 6 ++--- 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 723fbce9c..80b515e47 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -724,7 +724,7 @@ class FocalPlane: positions, encoder values, detector weights, and an optional pointing model. From these inputs it can derive several useful properties: - - Pointing model corrected detector positions (`data_pm`). + - Pointing model corrected detector positions (`pm_data`). - The affine transform mapping the template onto the measured data (`transform`). - The transformed template (`transformed`). @@ -768,20 +768,20 @@ class FocalPlane: fake_gamma : bool If True, ignore gamma when fitting and applying transforms, effectively treating the focal plane as two-dimensional. - data_pm : DetectorOffsets + pm_data : DetectorOffsets Measured detector offsets after application of the pointing model. 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 `data_pm`. + Best-fit affine transform mapping `template` to `pm_data`. pm_transformed : DetectorOffsets Template detector offsets after applying `pm_transform`. resid : Float[np.ndarray, "ndet 3"] Residuals between `data` and `transformed`. pm_resid : Float[np.ndarray, "ndet 3"] - Residuals between `data_pm` and `pm_transformed`. + Residuals between `pm_data` and `pm_transformed`. template : DetectorOffsets Reference detector layout used as the transform source on sky. template_fp : DetectorOffsets @@ -800,7 +800,7 @@ class FocalPlane: static: bool autofreeze: bool fake_gamma: bool - data_pm: ClassVar[StaticOrCached[DetectorOffsets]] = StaticOrCached("data_pm") + pm_data: ClassVar[StaticOrCached[DetectorOffsets]] = StaticOrCached("pm_data") transform: ClassVar[StaticOrCached[Transform]] = StaticOrCached("transform") transformed: ClassVar[StaticOrCached[DetectorOffsets]] = StaticOrCached( "transformed" @@ -812,7 +812,7 @@ class FocalPlane: fpc_transformed: ClassVar[StaticOrCached[DetectorOffsets]] = StaticOrCached( "fpc_transformed" ) - _data_pm_stat: DetectorOffsets = field(init=False) + _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) @@ -1004,7 +1004,7 @@ def freeze(self, static: bool): static : bool What to set `self.static` to after freezing. """ - self._data_pm_stat = self._data_pm_dyn + self._pm_data_stat = self._pm_data_dyn self._transform_stat = self._transform_dyn self._transformed_stat = self._transformed_dyn self._pm_transform_stat = self._pm_transform_dyn @@ -1012,12 +1012,12 @@ def freeze(self, static: bool): self.static = static @property - def _data_pm_dyn(self) -> DetectorOffsets: + def _pm_data_dyn(self) -> DetectorOffsets: to_ret = self.pointing_model.apply_det( self.data, self.enc, self.weights, self.fake_gamma ) if self.autofreeze: - self._data_pm_stat = to_ret + self._pm_data_stat = to_ret return to_ret @property @@ -1030,7 +1030,7 @@ def _transformed_dyn(self) -> DetectorOffsets: @property def _pm_transform_dyn(self) -> Transform: - return _get_aff(self, "data_pm", "_pm_transform_stat") + return _get_aff(self, "pm_data", "_pm_transform_stat") @property def _pm_transformed_dyn(self) -> DetectorOffsets: @@ -1046,11 +1046,11 @@ def resid(self): @property def pm_resid(self): - return self.data_pm.xyz - self.pm_transformed.xyz + return self.pm_data.xyz - self.pm_transformed.xyz @property def fpc_resid(self): - return self.data_pm.xyz - self.fpc_transformed.xyz + return self.pm_data.xyz - self.fpc_transformed.xyz def save( self, @@ -1103,8 +1103,8 @@ def save( raise ValueError(f"{path}/weights already exists") f.create_dataset(f"{path}/weights", data=self.weights) - if "_data_pm_stat" in self.__dict__: - self._data_pm_stat.save(f, f"{path}/data_pm", overwrite=overwrite) + 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__: @@ -1171,8 +1171,8 @@ def load( fake_gamma=cast(bool, group.attrs["fake_gamma"]), ) - if "data_pm" in group: - fp._data_pm_stat = DetectorOffsets.load(f, f"{path}/data_pm") + 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: @@ -1204,7 +1204,7 @@ class FocalPlaneCollection: against the reference template through a single affine transform. The collection operates on the pointing model corrected detector - positions (`FocalPlane.data_pm`) from each measurement. + positions (`FocalPlane.pm_data`) from each measurement. Detector locations and weights are combined on a per-detector basis, missing values should be filled with `nan`s. @@ -1308,7 +1308,7 @@ def freeze(self, static: bool): def _data_dyn(self) -> DetectorOffsets: to_ret = deepcopy(self.template) dat_full = np.array( - [fp.data_pm.xyz * fp.weights[..., None] for fp in self.focal_planes] + [fp.pm_data.xyz * fp.weights[..., None] for fp in self.focal_planes] ) to_ret.xyz = np.nansum(dat_full, axis=-1) / self.weights[..., None] to_ret.center = None @@ -1326,7 +1326,7 @@ def _weights_dyn(self) -> Float[np.ndarray, "ndet"]: @property def _scatter_dyn(self) -> Float[np.ndarray, "ndet"]: - dat_full = np.array([fp.data_pm.xyz for fp in self.focal_planes]) + dat_full = np.array([fp.pm_data.xyz for fp in self.focal_planes]) weights_full = np.array([fp.weights for fp in self.focal_planes]) mean = self.data.xyz var = ( diff --git a/sotodlib/coords/fp_plots.py b/sotodlib/coords/fp_plots.py index f83ffc842..ef073bf08 100644 --- a/sotodlib/coords/fp_plots.py +++ b/sotodlib/coords/fp_plots.py @@ -10,7 +10,7 @@ def plot_detector_offsets( - ax: mpl.axes._axes.Axes, + ax: mpl.axes._axes.Axes, # type: ignore offsets: DetectorOffsets, text: Optional[str] = None, fontsize: int = 16, @@ -206,14 +206,14 @@ def plot_ufm( figsize : tuple[float, float], default: (12, 6) Figure dimensions in inches. with_pm : bool, default: True - If True then use `data_pm` if `False` use `data`. + If True then use `pm_data` if `False` use `data`. Only matters for `FocalPlane`. """ 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.data_pm + data = focal_plane.pm_data transformed = focal_plane.pm_transformed # Plot focal-plane pointing. From fdd20f967f8b46e4da259b8b34430a729125c798 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Mon, 9 Nov 2026 15:06:12 -0800 Subject: [PATCH 111/132] feat: add mdb and some small io fixes --- sotodlib/coords/fp_containers.py | 141 +++++++++++++++++- sotodlib/coords/fp_plots.py | 2 +- .../site_pipeline/solve_static_pointing.py | 19 ++- 3 files changed, 153 insertions(+), 9 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 80b515e47..85ad02dfe 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -10,6 +10,7 @@ from __future__ import annotations import logging +import os from argparse import Namespace from copy import deepcopy from dataclasses import dataclass, field @@ -53,6 +54,136 @@ 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): for k, v in attrs.items(): if v is None: @@ -61,7 +192,7 @@ def _add_attrs(dset, attrs): dset.attrs[k] = v -def _create_group(f, path, overwrite=True): +def _create_group(f, path, overwrite=True) -> h5py.Group: if path in f: if path == "/": return f[path] @@ -122,7 +253,7 @@ def _get_aff(self: FocalPlane | FocalPlaneCollection, data_name: str, attr_name: affine, shift = mt.get_affine_two_stage( self.template.xyz[wmsk, :2], getattr(self, data_name).xyz[wmsk, :2], - self.weights, + self.weights[wmsk], ) to_ret = Transform.identity() to_ret.shift[:2] = shift @@ -480,8 +611,6 @@ def save(self, f: h5py.File, path: str, overwrite: bool = True): If True overwrite any existing h5groups. """ group = _create_group(f, path, overwrite=overwrite) - - group = f.create_group(path) group.create_dataset("shift", data=self.shift) group.create_dataset("affine", data=self.affine) @@ -2397,8 +2526,8 @@ def save(self, f: h5py.File, path: str, overwrite: bool = True): group.attrs["parameter_names"] = np.asarray( self.parameter_names, dtype=h5py.string_dtype() ) - parameter_map_group = _create_group( - f, f"{path}/parameter_map", overwrite=overwrite + 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( diff --git a/sotodlib/coords/fp_plots.py b/sotodlib/coords/fp_plots.py index ef073bf08..6d630bc27 100644 --- a/sotodlib/coords/fp_plots.py +++ b/sotodlib/coords/fp_plots.py @@ -10,7 +10,7 @@ def plot_detector_offsets( - ax: mpl.axes._axes.Axes, # type: ignore + ax: mpl.axes._axes.Axes, # type: ignore offsets: DetectorOffsets, text: Optional[str] = None, fontsize: int = 16, diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index e25f0d166..23a11af0c 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -435,6 +435,9 @@ def _run_per_obs(open_jobs, done_jobs, jdb, ctx, system, cfg, plot_dir): ju.fail(job, ErrCode.MIN_DETS, msg, logger) continue + # Lets make sure transformed is initid + meas.freeze(True) + # Cut on scale and shear try: scale, shear, _ = meas.transform.decompose @@ -556,13 +559,19 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): _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 @@ -592,13 +601,17 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): # Pad empty if needed if cfg.pad_empty: + logger.info("Padding empty") system.set_pad(cfg.pad_epochs, True) # Save our per-obs results - # TODO: Setup databases! + 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 = system.parameters.copy() @@ -664,10 +677,12 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): # TODO: plots # Save - # TODO: Setup databases! 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 + ) def main(): From d4f7ec2927b7f6e00a2dc91ffd67a9088ca9fc9c Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Mon, 9 Nov 2026 15:14:58 -0800 Subject: [PATCH 112/132] feat: save per-obs every n obs --- sotodlib/site_pipeline/solve_static_pointing.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index 23a11af0c..545907674 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -63,6 +63,7 @@ "outlier_sigma": 3, "mcmc_steps": 0, "nwalkers": 32, + "save_every": 10, } @@ -381,7 +382,7 @@ def _load_obs(aman, obs_id, array, ctx, system, cfg, job): return loaded, rx, fp -def _run_per_obs(open_jobs, done_jobs, jdb, ctx, system, cfg, plot_dir): +def _run_per_obs(open_jobs, done_jobs, jdb, ctx, system, cfg, plot_dir, outfile): job = None njobs = len(open_jobs) logger.info( @@ -469,6 +470,10 @@ def _run_per_obs(open_jobs, done_jobs, jdb, ctx, system, cfg, plot_dir): # 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) logger.info("Done with per-obs mode!") @@ -597,7 +602,7 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): 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) + _run_per_obs(open_jobs, done_jobs, jdb, ctx, system, cfg, plot_dir, outfile) # Pad empty if needed if cfg.pad_empty: From 6e27948c2e8d2b23bd8d8365612d4f404a4f78fe Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Mon, 9 Nov 2026 17:16:48 -0800 Subject: [PATCH 113/132] feat: add plotting for fits --- sotodlib/coords/fp_plots.py | 592 +++++++++++++++++- .../site_pipeline/solve_static_pointing.py | 21 +- 2 files changed, 611 insertions(+), 2 deletions(-) diff --git a/sotodlib/coords/fp_plots.py b/sotodlib/coords/fp_plots.py index 6d630bc27..6fe19adda 100644 --- a/sotodlib/coords/fp_plots.py +++ b/sotodlib/coords/fp_plots.py @@ -5,8 +5,17 @@ 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, Receiver +from .fp_containers import ( + DetectorOffsets, + FocalPlane, + FocalPlaneCollection, + OpticsTube, + Receiver, +) def plot_detector_offsets( @@ -270,3 +279,584 @@ def plot_ufm( 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: + 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: + try: + cf = ax2.tricontourf( + xi, + eta, + dist, + levels=np.linspace(-color_limit, color_limit, 21), + vmin=-color_limit, + vmax=color_limit, + cmap="coolwarm", + extend="both", + ) + except (ValueError, RuntimeError): + 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: + splits = sorted(np.unique(np.asarray(fp.template.split)), 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: + 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_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. + """ + os.makedirs(output_dir, exist_ok=True) + + 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.template.center is None: + continue + xc = fp.template.center[0] + yc = fp.template.center[1] + 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.fpc_transformed.xyz[msk, 0] - fp.transformed.xyz[msk, 0] + ) + disp_y = np.nanmedian( + meas.fpc_transformed.xyz[msk, 1] - fp.transformed.xyz[msk, 1] + ) + x0.append(xc) + y0.append(yc) + dx.append(disp_x) + dy.append(disp_y) + x0 = np.asarray(x0) + y0 = np.asarray(y0) + 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"{receiver.name} Observation Displacements" + fname = f"{receiver.name}_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"{receiver.name} Observation Displacements by {name}\n{scale_str}" + fname = f"{receiver.name}_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_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) diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index 545907674..1c5011ae1 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -523,6 +523,20 @@ def _check_jobs(system, jdb, done_jobs, open_jobs): return open_jobs, done_jobs +def _plot_fit(system, plot_dir, i): + logger.info("Plotting fitted focal-plane collections for round %s", i) + for rx in system.receivers: + pdir = os.path.join(plot_dir, f"fit_{i}", rx.epoch) + os.makedirs(pdir, exist_ok=True) + fpp.plot_receiver(rx, pdir) + fpp.plot_receiver_displacements(rx, [(None, None)], pdir) + fpp.plot_receiver_resid_vs_enc(rx, pdir) + for ot in rx.optics_tubes: + fpp.plot_optics_tube(ot, pdir) + for fp in ot.focal_planes: + fpp.plot_ufm(fp, pdir) + + def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): # Load config require = ( @@ -634,9 +648,9 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): system.update_parameters(params) # Fit for pointing model and focal planes - system.set_static(False) for i in range(cfg.n_rounds): logger.info("Starting fit round %d", i + 1) + system.set_static(False) res = minimize( system.objective, system.parameters, @@ -651,6 +665,7 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): for rx in system.receivers: for ot in rx.optics_tubes: for fp in ot.focal_planes: + fp.freeze(True) for meas in fp.focal_planes: wmsk = np.isfinite(meas.weights) * (meas.weights > 0) if meas.fake_gamma: @@ -660,11 +675,14 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): mrmsk = err > cfg.outlier_sigma * np.std(err[wmsk]) meas.weights[mrmsk] = 0 tot_cut += np.sum(mrmsk[wmsk]) + meas.freeze(True) + _plot_fit(system, plot_dir, i) if tot_cut == 0: break # Run MCMC if we want if cfg.mcmc_steps > 0: + system.set_static(False) ndim = len(system.parameters) sampler = emcee.EnsembleSampler( cfg.nwalkers, ndim, system.log_prob, args=(cfg.cm_priors,) @@ -677,6 +695,7 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): lower = np.percentile(samples, 16, axis=0) upper = np.percentile(samples, 84, axis=0) _ = lower, upper + _plot_fit(system, plot_dir, "mcmc") # TODO: Save the chain somewhere # TODO: MCMC plots # TODO: plots From 3ec0cec5b94db9194035cb2df943ac0504710296 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Tue, 10 Nov 2026 08:08:31 -0800 Subject: [PATCH 114/132] fix: many small fixes and perf improvements --- sotodlib/coords/fp_containers.py | 114 +++++++++++++----- sotodlib/coords/fp_plots.py | 12 +- .../site_pipeline/solve_static_pointing.py | 28 +++-- 3 files changed, 108 insertions(+), 46 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 85ad02dfe..43281bd63 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -294,7 +294,11 @@ def __get__(self, obj: Any, owner: type | None = None) -> T | "StaticOrCached[T] return self if obj.static: - return getattr(obj, f"_{self.name}_stat") + if f"_{self.name}_stat" in obj.__dict__: + return getattr(obj, f"_{self.name}_stat") + res = getattr(obj, f"_{self.name}_dyn") + setattr(obj, f"_{self.name}_stat", res) + return res return getattr(obj, f"_{self.name}_dyn") @@ -332,7 +336,7 @@ def apply_det( det_enc: DetectorOffsets, weights: Float[np.ndarray, "ndet"], fake_gamma: bool, - tol: float = 1e-6, + tol: float = 2.42e-6, max_iter: int = 5, ) -> DetectorOffsets: """ @@ -370,7 +374,7 @@ def apply_det( If True, ignore detector polarization angles and propagate only detector position (`xi`, `eta`). If False, propagate the full (`xi`, `eta`, `gamma`) coordinate set. - tol : float, default: 1e-6 + 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. @@ -412,6 +416,9 @@ def apply_det( ancil = det_enc_msk.ancil err = np.inf + alpha = 1.0 + prev_err = np.inf + prev_distortion = np.zeros_like(estimate) for _ in range(max_iter): fp.xi = estimate[:, 0] fp.eta = estimate[:, 1] @@ -460,13 +467,19 @@ def apply_det( ) ) err = np.sqrt(np.nanmean(np.linalg.norm(resid, axis=1) ** 2)) - + if err > prev_err: + alpha *= 0.5 + distortion = prev_distortion + else: + alpha = min(1.0, alpha * 1.2) + prev_distortion = distortion + prev_err = err if err < tol: to_ret.xyz[msk] = np.column_stack((xi, eta, gamma)) return to_ret # Update estimate of the undistorted fp - estimate -= distortion + estimate -= alpha * distortion raise RuntimeError( f"Pointing-model inversion did not converge after {max_iter} iterations (error={err:.3e} rad)." @@ -1133,6 +1146,7 @@ def freeze(self, static: bool): static : bool What to set `self.static` to after freezing. """ + self.static = True self._pm_data_stat = self._pm_data_dyn self._transform_stat = self._transform_dyn self._transformed_stat = self._transformed_dyn @@ -1426,6 +1440,9 @@ def freeze(self, static: bool): 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._scatter_stat = self._scatter_dyn @@ -1439,7 +1456,10 @@ def _data_dyn(self) -> DetectorOffsets: dat_full = np.array( [fp.pm_data.xyz * fp.weights[..., None] for fp in self.focal_planes] ) - to_ret.xyz = np.nansum(dat_full, axis=-1) / self.weights[..., None] + weights = self.weights + wmsk = np.isfinite(weights) * (weights > 0) + to_ret.xyz[wmsk] = np.nansum(dat_full[:, wmsk], axis=0) / weights[wmsk, None] + to_ret.xyz[~wmsk] = np.nan to_ret.center = None if self.autofreeze: self._data_stat = to_ret @@ -1447,8 +1467,8 @@ def _data_dyn(self) -> DetectorOffsets: @property def _weights_dyn(self) -> Float[np.ndarray, "ndet"]: - weights_full = np.array([fp.weights for fp in self.focal_planes]) - to_ret = np.nansum(weights_full, axis=-1) + 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 @@ -1458,15 +1478,19 @@ def _scatter_dyn(self) -> Float[np.ndarray, "ndet"]: dat_full = np.array([fp.pm_data.xyz for fp in self.focal_planes]) weights_full = np.array([fp.weights for fp in self.focal_planes]) mean = self.data.xyz - var = ( + weights = self.weights + wmsk = np.isfinite(weights) * (weights > 0) + var = np.zeros_like(weights) + var[wmsk] = ( np.nansum( - weights_full[..., None] * (dat_full - mean[None, ...]) ** 2, + weights_full[:, wmsk, None] * (dat_full - mean[None, wmsk, :])** 2, axis=0, ) - / self.weights[..., None] + / weights[wmsk, None] ) - std = np.sqrt(var) - to_ret = np.sqrt(np.nanmean(std**2, axis=0)) + to_ret = np.sqrt(np.nanmean(var, axis=0)) + if self.autofreeze: + self._scatter_stat= to_ret return to_ret @property @@ -1523,7 +1547,7 @@ def save( for fp in self.focal_planes: fp.save( f, - f"{path}/{fp.meas_id}", + f"{path}/focal_planes/{fp.meas_id}", pointing_models=pointing_models, overwrite=overwrite, ) @@ -1613,22 +1637,13 @@ def load( f"{path}/transformed", ) - for name in group: - if name in { - "template", - "template_fp", - "template_ot", - "data", - "weights", - "scatter", - "transform", - "transformed", - }: - continue + 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}/{name}", + f"{path}/focal_planes/{name}", parent=collection, pointing_models=pointing_models, ) @@ -1712,6 +1727,9 @@ def freeze(self, static: bool): 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 @@ -1733,7 +1751,7 @@ def _cm_transform_dyn(self) -> Transform: 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) + 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 @@ -1947,6 +1965,9 @@ def freeze(self, static: bool): 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 @@ -1970,7 +1991,7 @@ def _cm_transform_dyn(self) -> Transform: 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) + 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 @@ -2137,6 +2158,24 @@ def set_static(self, static: bool): for meas in fp.focal_planes: meas.static = static + def set_freeze(self, static: bool): + """ + Run freeze for all relevent childen. + + Parameters + ---------- + static : bool + The value to set `static` to for all relevent children. + """ + for rx in self.receivers: + rx.freeze(static) + for ot in rx.optics_tubes: + ot.freeze(static) + for fp in ot.focal_planes: + fp.freeze(static) + for meas in fp.focal_planes: + meas.freeze(static) + @property def parameters(self) -> Float[np.ndarray, "npar"]: return np.array( @@ -2269,7 +2308,7 @@ def set_pad(self, pad_epochs: list[str], pad_empty: bool): pad = rx.epoch in pad_epochs for ot in rx.optics_tubes: for fp in ot.focal_planes: - fp.pad = bool(pad + bool(pad_empty * (len(fp.focal_planes) == 0))) + fp.pad = pad or (pad_empty and (len(fp.focal_planes) == 0)) def load_pm_from_mdb(self, mdb: ManifestDb): """ @@ -2474,6 +2513,21 @@ def _group_epochs(dat, groups, desc, check_fields): return cls(era, tuple(pms), tuple(rxs), 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 = [] + 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. diff --git a/sotodlib/coords/fp_plots.py b/sotodlib/coords/fp_plots.py index 6fe19adda..207841b00 100644 --- a/sotodlib/coords/fp_plots.py +++ b/sotodlib/coords/fp_plots.py @@ -218,6 +218,7 @@ def plot_ufm( 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 @@ -244,7 +245,7 @@ def plot_ufm( ) plot_detector_offsets( ax1, - data, + data[wmsk], color="orange", alpha=0.4, label="measured", @@ -255,14 +256,7 @@ def plot_ufm( ax1.legend() # Plot histogram of residuals. - dist = 3600 * np.linalg.norm( - np.rad2deg( - (transformed.xyz - data.xyz)[ - np.isfinite(focal_plane.weights) * (focal_plane.weights > 0), :2 - ] - ), - axis=1, - ) + 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) diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index 1c5011ae1..41a02f839 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -13,6 +13,7 @@ from enum import Enum from functools import partial from typing import cast +from copy import deepcopy import emcee import git @@ -331,7 +332,8 @@ def _get_obslist(ctx, cfg, system): 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_1782128967_lati1_111"] + # obsids = ["obs_1777500417_lati6_111"] # Validate against black and whitelist if len(cfg.obs_whitelist) > 0: @@ -385,12 +387,17 @@ def _load_obs(aman, obs_id, array, ctx, system, cfg, job): 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") @@ -437,7 +444,12 @@ def _run_per_obs(open_jobs, done_jobs, jdb, ctx, system, cfg, plot_dir, outfile) continue # Lets make sure transformed is initid - meas.freeze(True) + try: + meas.freeze(True) + 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: @@ -474,6 +486,7 @@ def _run_per_obs(open_jobs, done_jobs, jdb, ctx, system, cfg, plot_dir, outfile) 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!") @@ -517,7 +530,7 @@ def _check_jobs(system, jdb, done_jobs, open_jobs): for ot in rx.optics_tubes: for fp in ot.focal_planes: fp.focal_planes = [ - meas for meas in fp if f"{meas.meas_id}+{meas.name}" not in open_ids + meas for meas in fp.focal_planes if f"{meas.meas_id}+{meas.name}" not in open_ids ] return open_jobs, done_jobs @@ -635,7 +648,7 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): # Setup fit params params = system.parameters.copy() bounds = [(-np.inf, np.inf)] * len(params) - for name, par in cfg.parameters: + for name, par in cfg.parameters.items(): if name not in system.parameter_names: logger.warning("Unknown paramter %s", name) continue @@ -646,6 +659,7 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): continue bounds[idx] = tuple(par.get("bounds", bounds[idx])[:2]) system.update_parameters(params) + logger.info(params) # Fit for pointing model and focal planes for i in range(cfg.n_rounds): @@ -659,13 +673,14 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): method="Nelder-Mead", ) system.update_parameters(res.x) + logger.info(params) + system.set_freeze(True) # Cut outliers tot_cut = 0 for rx in system.receivers: for ot in rx.optics_tubes: for fp in ot.focal_planes: - fp.freeze(True) for meas in fp.focal_planes: wmsk = np.isfinite(meas.weights) * (meas.weights > 0) if meas.fake_gamma: @@ -675,7 +690,6 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): mrmsk = err > cfg.outlier_sigma * np.std(err[wmsk]) meas.weights[mrmsk] = 0 tot_cut += np.sum(mrmsk[wmsk]) - meas.freeze(True) _plot_fit(system, plot_dir, i) if tot_cut == 0: break @@ -695,10 +709,10 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): lower = np.percentile(samples, 16, axis=0) upper = np.percentile(samples, 84, axis=0) _ = lower, upper + system.set_freeze(True) _plot_fit(system, plot_dir, "mcmc") # TODO: Save the chain somewhere # TODO: MCMC plots - # TODO: plots # Save system.set_static(True) From 89eabc931ddc24d464baa6840416c410946571cf Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Sat, 14 Nov 2026 00:02:30 -0800 Subject: [PATCH 115/132] fix: clear cache on every iter and many speedups --- sotodlib/coords/fp_containers.py | 70 +++++++--- sotodlib/coords/fp_plots.py | 35 ++--- sotodlib/coords/pointing_model.py | 31 ++++- .../site_pipeline/solve_static_pointing.py | 120 ++++++++++++++---- 4 files changed, 182 insertions(+), 74 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 43281bd63..dd0a17898 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -249,13 +249,15 @@ def _transformed( def _get_aff(self: FocalPlane | FocalPlaneCollection, data_name: str, attr_name: str): + to_ret = Transform.identity() wmsk = (self.weights > 0) * np.isfinite(self.weights) + if np.sum(wmsk) < 5: + return to_ret affine, shift = mt.get_affine_two_stage( self.template.xyz[wmsk, :2], getattr(self, data_name).xyz[wmsk, :2], self.weights[wmsk], ) - to_ret = Transform.identity() to_ret.shift[:2] = shift to_ret.affine[:2, :2] = affine if not self.fake_gamma: @@ -414,6 +416,7 @@ def apply_det( fp = to_ret[msk].fp det_enc_msk = det_enc[msk] ancil = det_enc_msk.ancil + # xi, eta, gamma = to_ret.xyz[msk].T err = np.inf alpha = 1.0 @@ -481,9 +484,14 @@ def apply_det( # Update estimate of the undistorted fp estimate -= alpha * distortion + # logger.error( + # f"Pointing-model inversion did not converge after {max_iter} iterations (error={err:.3e} rad)." + # ) raise RuntimeError( - f"Pointing-model inversion did not converge after {max_iter} iterations (error={err:.3e} rad)." - ) + f"Pointing-model inversion did not converge after {max_iter} iterations (error={err:.3e} rad)." + ) + # to_ret.xyz[msk] = np.column_stack((xi, eta, gamma)) + # return to_ret def save(self, f: h5py.File, path: str, overwrite: bool = True): """ @@ -1137,7 +1145,7 @@ def from_aman( fake_gamma, ) - def freeze(self, static: bool): + def freeze(self, static: bool, optimizer: bool): """ Save the current dynamic properties to the static fields. @@ -1148,10 +1156,12 @@ def freeze(self, static: bool): """ self.static = True self._pm_data_stat = self._pm_data_dyn - 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._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 @property @@ -1450,6 +1460,13 @@ def freeze(self, static: bool): self._transformed_stat = self._transformed_dyn self.static = static + @property + def chisq(self) -> float: + chisq = 0 + for meas in self.focal_planes: + chisq += np.nansum((np.linalg.norm(meas.fpc_resid, axis=1)*meas.weights)**2) + return chisq + @property def _data_dyn(self) -> DetectorOffsets: to_ret = deepcopy(self.template) @@ -1480,15 +1497,15 @@ def _scatter_dyn(self) -> Float[np.ndarray, "ndet"]: mean = self.data.xyz weights = self.weights wmsk = np.isfinite(weights) * (weights > 0) - var = np.zeros_like(weights) + var = np.zeros_like(mean) var[wmsk] = ( np.nansum( - weights_full[:, wmsk, None] * (dat_full - mean[None, wmsk, :])** 2, + weights_full[:, wmsk, None] * (dat_full[:, wmsk, :] - mean[None, wmsk, :])** 2, axis=0, ) / weights[wmsk, None] ) - to_ret = np.sqrt(np.nanmean(var, axis=0)) + to_ret = np.sqrt(np.nanmean(var, axis=1)) if self.autofreeze: self._scatter_stat= to_ret return to_ret @@ -2158,7 +2175,7 @@ def set_static(self, static: bool): for meas in fp.focal_planes: meas.static = static - def set_freeze(self, static: bool): + def set_freeze(self, static: bool, optimizer: bool = False): """ Run freeze for all relevent childen. @@ -2168,13 +2185,14 @@ def set_freeze(self, static: bool): The value to set `static` to for all relevent children. """ for rx in self.receivers: - rx.freeze(static) for ot in rx.optics_tubes: - ot.freeze(static) for fp in ot.focal_planes: - fp.freeze(static) for meas in fp.focal_planes: - meas.freeze(static) + meas.freeze(True, optimizer) + fp.freeze(True) + ot.freeze(True) + rx.freeze(True) + self.set_static(static) @property def parameters(self) -> Float[np.ndarray, "npar"]: @@ -2201,9 +2219,10 @@ def chisq(self) -> float: for fp in ot.focal_planes: if fp.pad: continue - chisq += np.nansum( - ((fp.weights * fp.resid) ** 2) * (1 + fp.scatter) - ).item() + chisq += fp.chisq + # chisq += np.nansum( + # ((fp.weights * np.linalg.norm(fp.resid, axis=1)) ** 2) * (1 + fp.scatter) + # ).item() return chisq def chisq_cm_prior( @@ -2238,8 +2257,17 @@ def chisq_cm_prior( return self.chisq def objective(self, params, cm_priors): + # orig_pars = self.parameters.copy() self.update_parameters(params) - return self.chisq_cm_prior(**cm_priors) + print(params) + self.set_static(False) + try: + self.set_freeze(True, True) + if cm_priors is None: + return self.chisq + return self.chisq_cm_prior(**cm_priors) + except RuntimeError: + return np.inf #1000*self.objective(orig_pars, cm_priors) def log_prob(self, params, cm_priors): return -0.5 * self.objective(params, cm_priors) @@ -2520,7 +2548,7 @@ def set_pm_to_defaults(self, cfg): 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 = [] + 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] diff --git a/sotodlib/coords/fp_plots.py b/sotodlib/coords/fp_plots.py index 207841b00..2b765cacf 100644 --- a/sotodlib/coords/fp_plots.py +++ b/sotodlib/coords/fp_plots.py @@ -302,6 +302,8 @@ def plot_optics_tube( 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] @@ -359,27 +361,7 @@ def plot_optics_tube( color_limit = np.nanpercentile(np.abs(dist), 99) cf = None if len(dist) >= 3 and np.isfinite(color_limit) and color_limit > 0: - try: - cf = ax2.tricontourf( - xi, - eta, - dist, - levels=np.linspace(-color_limit, color_limit, 21), - vmin=-color_limit, - vmax=color_limit, - cmap="coolwarm", - extend="both", - ) - except (ValueError, RuntimeError): - cf = ax2.scatter( - xi, - eta, - c=dist, - s=10, - vmin=-color_limit, - vmax=color_limit, - cmap="coolwarm", - ) + 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") @@ -448,7 +430,8 @@ def plot_receiver( all_splits = set() neighbors = {} for fp in focal_planes: - splits = sorted(np.unique(np.asarray(fp.template.split)), key=str) + 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()) @@ -480,6 +463,8 @@ def plot_receiver( 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) @@ -673,6 +658,8 @@ def plot_receiver_displacements( dy = [] for ot in receiver.optics_tubes: for fp in ot.focal_planes: + if fp.pad: + continue if fp.template.center is None: continue xc = fp.template.center[0] @@ -682,10 +669,10 @@ def plot_receiver_displacements( if np.sum(msk) == 0: continue disp_x = np.nanmedian( - meas.fpc_transformed.xyz[msk, 0] - fp.transformed.xyz[msk, 0] + meas.pm_transformed.xyz[msk, 0] - fp.transformed.xyz[msk, 0] ) disp_y = np.nanmedian( - meas.fpc_transformed.xyz[msk, 1] - fp.transformed.xyz[msk, 1] + meas.pm_transformed.xyz[msk, 1] - fp.transformed.xyz[msk, 1] ) x0.append(xc) y0.append(yc) diff --git a/sotodlib/coords/pointing_model.py b/sotodlib/coords/pointing_model.py index 9ef7f5133..47789e5b5 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__) @@ -388,8 +392,9 @@ def apply_lat_distortion_model(params, az, el, roll, focal_plane): * 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( @@ -684,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/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index 41a02f839..a16b85eb0 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -11,9 +11,11 @@ import os import shutil from enum import Enum -from functools import partial from typing import cast from copy import deepcopy +import corner +import matplotlib.pyplot as plt +from functools import partial import emcee import git @@ -445,7 +447,7 @@ def _run_per_obs(open_jobs, done_jobs, jdb, ctx, system, cfg, plot_dir, outfile) # Lets make sure transformed is initid try: - meas.freeze(True) + 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) @@ -539,14 +541,20 @@ def _check_jobs(system, jdb, done_jobs, open_jobs): def _plot_fit(system, plot_dir, i): logger.info("Plotting fitted focal-plane collections for round %s", i) for rx in system.receivers: - pdir = os.path.join(plot_dir, f"fit_{i}", rx.epoch) + 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_resid_vs_enc(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) @@ -591,12 +599,12 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): _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 - ) + # 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") @@ -636,14 +644,28 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): 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] + # 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 - ) + # 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 = system.parameters.copy() @@ -661,6 +683,11 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): system.update_parameters(params) logger.info(params) + system.set_static(False) + system.set_freeze(True) + logger.info("Initial chisq is %.5f", system.chisq) + _plot_fit(system, plot_dir, 0) + # Fit for pointing model and focal planes for i in range(cfg.n_rounds): logger.info("Starting fit round %d", i + 1) @@ -669,50 +696,89 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): system.objective, system.parameters, bounds=bounds, - args=(cfg.cm_priors,), - method="Nelder-Mead", + # args=(cfg.cm_priors,), + args=(None,), + # method="powell", + # method="Nelder-Mead", ) system.update_parameters(res.x) - logger.info(params) + logger.info(res.x) + system.set_static(False) system.set_freeze(True) + _plot_fit(system, plot_dir, i+1) # 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) - mrmsk = err > cfg.outlier_sigma * np.std(err[wmsk]) + err[~wmsk] = np.nan + all_errs += [err] + wmsks += [wmsk] + errs_full = np.hstack(all_errs) + err_cuttoff = np.nanmean(errs_full) + cfg.outlier_sigma*np.nanstd(errs_full) + for meas, err, wmsk in zip(fp.focal_planes, all_errs, wmsks): + mrmsk = err > err_cuttoff meas.weights[mrmsk] = 0 tot_cut += np.sum(mrmsk[wmsk]) - _plot_fit(system, plot_dir, i) if tot_cut == 0: + logger.info("None cut! Stopping optimization.") break # Run MCMC if we want if cfg.mcmc_steps > 0: system.set_static(False) ndim = len(system.parameters) + + # Create HDF5 backend + chain_file = os.path.join(data_dir, "mcmc_chain.h5") + backend = emcee.backends.HDFBackend(chain_file) + + # Run a fresh chain + backend.reset(cfg.nwalkers, ndim) sampler = emcee.EnsembleSampler( - cfg.nwalkers, ndim, system.log_prob, args=(cfg.cm_priors,) + cfg.nwalkers, + ndim, + system.log_prob, + args=(cfg.cm_priors,), + backend=backend, ) sampler.run_mcmc(system.parameters, cfg.mcmc_steps) - samples = np.array( - sampler.get_chain(discard=int(0.1 * cfg.mcmc_steps), flat=True) - ) + samples = sampler.get_chain( discard=int(0.1 * cfg.mcmc_steps), flat=True) + assert samples is not None + + # Update params system.update_parameters(np.median(samples, axis=0)) lower = np.percentile(samples, 16, axis=0) upper = np.percentile(samples, 84, axis=0) _ = lower, upper system.set_freeze(True) + + # Plot _plot_fit(system, plot_dir, "mcmc") - # TODO: Save the chain somewhere - # TODO: MCMC plots + labels = list(system.parameter_names) + fig = corner.corner( + samples, + labels=labels, + quantiles=[0.16, 0.50, 0.84], + show_titles=True, + title_fmt=".4f", + title_kwargs={"fontsize": 10}, + label_kwargs={"fontsize": 10}, + truths=np.median(samples, axis=0), + ) + fig.savefig( os.path.join(plot_dir, "mcmc_corner.png"), dpi=200, bbox_inches="tight") + plt.close(fig) # Save system.set_static(True) From f8a49921f9b4d672be124e84c7ec15024c633f91 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Sat, 14 Nov 2026 12:47:07 -0800 Subject: [PATCH 116/132] feat: fit scaled pars --- sotodlib/coords/fp_containers.py | 161 ++++++++++++------ .../site_pipeline/solve_static_pointing.py | 107 +++++++----- 2 files changed, 172 insertions(+), 96 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index dd0a17898..fa51ac3dc 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -32,7 +32,7 @@ import megham.transform as mt import megham.utils as mu import numpy as np -from jaxtyping import Float, Integer, Shaped +from jaxtyping import Float, Integer, Shaped, Bool from scipy.cluster import vq from scipy.optimize import minimize from so3g.proj import quat @@ -250,9 +250,9 @@ def _transformed( def _get_aff(self: FocalPlane | FocalPlaneCollection, data_name: str, attr_name: str): to_ret = Transform.identity() - wmsk = (self.weights > 0) * np.isfinite(self.weights) - if np.sum(wmsk) < 5: - return to_ret + wmsk = self.wmsk + if np.sum(wmsk) < 4: + return to_ret affine, shift = mt.get_affine_two_stage( self.template.xyz[wmsk, :2], getattr(self, data_name).xyz[wmsk, :2], @@ -297,7 +297,9 @@ def __get__(self, obj: Any, owner: type | None = None) -> T | "StaticOrCached[T] if obj.static: if f"_{self.name}_stat" in obj.__dict__: - return getattr(obj, f"_{self.name}_stat") + 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 @@ -336,7 +338,7 @@ def apply_det( self, det_off: DetectorOffsets, det_enc: DetectorOffsets, - weights: Float[np.ndarray, "ndet"], + msk: Bool[np.ndarray, "ndet"], fake_gamma: bool, tol: float = 2.42e-6, max_iter: int = 5, @@ -405,7 +407,6 @@ def apply_det( ) # Start with the input detector coordinates - msk = np.isfinite(weights) * (weights > 0) if not np.any(msk): return deepcopy(det_off) estimate = det_off.xyz[msk].copy() @@ -945,6 +946,7 @@ class FocalPlane: data: DetectorOffsets enc: DetectorOffsets weights: Float[np.ndarray, "ndet"] + wmsk: Bool[np.ndarray, "ndet"] parent: FocalPlaneCollection pointing_model: PointingModel static: bool @@ -1131,6 +1133,7 @@ def from_aman( # ~1 sigma cut weights[weights < 0.61] = 0 + valid_msk *= (weights == 0) return cls( name, @@ -1138,6 +1141,7 @@ def from_aman( data, enc, weights, + valid_msk, parent, pointing_model, False, @@ -1164,10 +1168,27 @@ def freeze(self, static: bool, optimizer: bool): 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.data, self.enc, self.weights, self.fake_gamma + self.data, self.enc, self.wmsk, self.fake_gamma ) if self.autofreeze: self._pm_data_stat = to_ret @@ -1255,6 +1276,7 @@ def save( 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) @@ -1309,6 +1331,11 @@ def load( 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: + wmsk = np.isfinite(weights) * (weights > 0) + wmsk = np.isfinite(weights) * (weights > 0) pm_idx = cast(int, group.attrs["pm_idx"]) fp = cls( @@ -1317,6 +1344,7 @@ def load( data=data, enc=enc, weights=weights, + wmsk=wmsk, parent=parent, pointing_model=pointing_models[pm_idx], static=cast(bool, group.attrs["static"]), @@ -1422,16 +1450,12 @@ class FocalPlaneCollection: weights: ClassVar[StaticOrCached[Float[np.ndarray, "ndet"]]] = StaticOrCached( "weights" ) - scatter: ClassVar[StaticOrCached[Float[np.ndarray, "ndet"]]] = StaticOrCached( - "scatter" - ) 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) - _scatter_stat: Float[np.ndarray, "ndet"] = field(init=False) _transform_stat: Transform = field(init=False) _transformed_stat: DetectorOffsets = field(init=False) @@ -1455,11 +1479,25 @@ def freeze(self, static: bool): self.static = True self._data_stat = self._data_dyn self._weights_stat = self._weights_dyn - self._scatter_stat = self._scatter_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 + @property def chisq(self) -> float: chisq = 0 @@ -1470,13 +1508,13 @@ def chisq(self) -> float: @property def _data_dyn(self) -> DetectorOffsets: to_ret = deepcopy(self.template) - dat_full = np.array( - [fp.pm_data.xyz * fp.weights[..., None] for fp in self.focal_planes] - ) - weights = self.weights - wmsk = np.isfinite(weights) * (weights > 0) - to_ret.xyz[wmsk] = np.nansum(dat_full[:, wmsk], axis=0) / weights[wmsk, None] - to_ret.xyz[~wmsk] = np.nan + to_ret.xyz[:] = 0 + fmsk = np.zeros(len(to_ret.xyz), dtype=bool) + for meas in self.focal_planes: + fmsk += meas.wmsk + to_ret.xyz[meas.wmsk] += meas.pm_data.xyz[meas.wmsk] * meas.weights[meas.wmsk, None] + to_ret.xyz[~fmsk] = np.nan + to_ret.xyz[fmsk] /= self.weights[fmsk, None] to_ret.center = None if self.autofreeze: self._data_stat = to_ret @@ -1490,26 +1528,6 @@ def _weights_dyn(self) -> Float[np.ndarray, "ndet"]: self._weights_stat = to_ret return to_ret - @property - def _scatter_dyn(self) -> Float[np.ndarray, "ndet"]: - dat_full = np.array([fp.pm_data.xyz for fp in self.focal_planes]) - weights_full = np.array([fp.weights for fp in self.focal_planes]) - mean = self.data.xyz - weights = self.weights - wmsk = np.isfinite(weights) * (weights > 0) - var = np.zeros_like(mean) - var[wmsk] = ( - np.nansum( - weights_full[:, wmsk, None] * (dat_full[:, wmsk, :] - mean[None, wmsk, :])** 2, - axis=0, - ) - / weights[wmsk, None] - ) - to_ret = np.sqrt(np.nanmean(var, axis=1)) - if self.autofreeze: - self._scatter_stat= to_ret - return to_ret - @property def _transform_dyn(self) -> Transform: return _get_aff(self, "data", "_transform_stat") @@ -1522,6 +1540,11 @@ def _transformed_dyn(self) -> DetectorOffsets: def resid(self): return self.data.xyz - self.transformed.xyz + @property + def wmsk(self): + weights = self.weights + return np.isfinite(weights) * (weights > 0) + def save( self, f: h5py.File, @@ -1578,13 +1601,6 @@ def save( else: raise ValueError(f"{path}/weights already exists") f.create_dataset(f"{path}/weights", data=self._weights_stat) - if "_scatter_stat" in self.__dict__: - if f"{path}/scatter" in f: - if overwrite: - del f[f"{path}/scatter"] - else: - raise ValueError(f"{path}/scatter already exists") - f.create_dataset(f"{path}/scatter", data=self._scatter_stat) if "_transform_stat" in self.__dict__: self._transform_stat.save(f, f"{path}/transform") if "_transformed_stat" in self.__dict__: @@ -1644,8 +1660,8 @@ def load( ) 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 "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: @@ -1750,6 +1766,18 @@ def freeze(self, static: bool): 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 + @property def allpad(self) -> bool: if len(self.focal_planes) == 0: @@ -1988,6 +2016,18 @@ def freeze(self, static: bool): 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 + @property def allpad(self) -> bool: if len(self.optics_tubes) == 0: @@ -2194,6 +2234,24 @@ def set_freeze(self, static: bool, optimizer: bool = False): rx.freeze(True) self.set_static(static) + def set_thaw(self, static: bool): + """ + 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: + meas.thaw(static) + fp.thaw(static) + ot.thaw(static) + rx.thaw(static) + @property def parameters(self) -> Float[np.ndarray, "npar"]: return np.array( @@ -2260,13 +2318,12 @@ def objective(self, params, cm_priors): # orig_pars = self.parameters.copy() self.update_parameters(params) print(params) - self.set_static(False) + self.set_thaw(True) try: - self.set_freeze(True, True) if cm_priors is None: return self.chisq return self.chisq_cm_prior(**cm_priors) - except RuntimeError: + except (RuntimeError, AssertionError): return np.inf #1000*self.objective(orig_pars, cm_priors) def log_prob(self, params, cm_priors): diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index a16b85eb0..c3ecdfb36 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -611,33 +611,33 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): 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) + # 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: @@ -667,46 +667,62 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): # system, "transformed", os.path.join(data_dir, "per_obs.sqlite"), outfile # ) + # Setup fit params 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 paramter %s", name) + logger.warning("Unknown parameter %s", name) continue idx = system.parameter_names.index(name) - params[idx] = par.get("init", params[idx]) + params[idx] = float(par.get("init", params[idx])) if par.get("static", False): bounds[idx] = (params[idx], params[idx]) continue - bounds[idx] = tuple(par.get("bounds", bounds[idx])[:2]) + 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 + system.update_parameters(params) logger.info(params) - - system.set_static(False) + logger.info(scales) + + system.set_thaw(True) system.set_freeze(True) logger.info("Initial chisq is %.5f", system.chisq) _plot_fit(system, plot_dir, 0) - + # Fit for pointing model and focal planes + def scaled_objective(z, args): + return system.objective(z * scales, args) + scaled_bounds = [(lo / scale, hi / scale,) for scale, (lo, hi) in zip(scales, bounds)] + for i in range(cfg.n_rounds): logger.info("Starting fit round %d", i + 1) - system.set_static(False) + system.set_thaw(True) + x0 = system.parameters.copy()/scales res = minimize( - system.objective, - system.parameters, - bounds=bounds, - # args=(cfg.cm_priors,), + scaled_objective, + x0, args=(None,), - # method="powell", - # method="Nelder-Mead", + method="L-BFGS-B", + bounds=scaled_bounds, + # options={ + # # "eps": 1e-7, + # "maxiter": 5000, + # "ftol": 1e-12, + # "gtol": 1e-8, + # } ) - system.update_parameters(res.x) - logger.info(res.x) - system.set_static(False) + system.update_parameters(res.x * scales) + logger.info(res.x * scales) + system.set_thaw(True) system.set_freeze(True) - _plot_fit(system, plot_dir, i+1) + # Cut outliers tot_cut = 0 for rx in system.receivers: @@ -730,6 +746,7 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): for meas, err, wmsk in zip(fp.focal_planes, all_errs, wmsks): mrmsk = err > err_cuttoff meas.weights[mrmsk] = 0 + meas.wmsk[mrmsk] = False tot_cut += np.sum(mrmsk[wmsk]) if tot_cut == 0: logger.info("None cut! Stopping optimization.") @@ -745,6 +762,7 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): backend = emcee.backends.HDFBackend(chain_file) # Run a fresh chain + system.set_thaw(True) backend.reset(cfg.nwalkers, ndim) sampler = emcee.EnsembleSampler( cfg.nwalkers, @@ -762,6 +780,7 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): lower = np.percentile(samples, 16, axis=0) upper = np.percentile(samples, 84, axis=0) _ = lower, upper + system.set_thaw(True) system.set_freeze(True) # Plot From 43ac23a2cfd8b83b4fb8484fb02ccb99ec82fcaa Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Mon, 16 Nov 2026 16:25:23 -0800 Subject: [PATCH 117/132] feat: nuisance fit --- sotodlib/coords/fp_containers.py | 296 +++++++++++- sotodlib/coords/fp_plots.py | 97 ++++ .../site_pipeline/solve_static_pointing.py | 428 ++++++++++++------ sotodlib/utils/epochs.py | 32 ++ 4 files changed, 696 insertions(+), 157 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index fa51ac3dc..b73cd038c 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -268,6 +268,72 @@ def _get_aff(self: FocalPlane | FocalPlaneCollection, data_name: str, attr_name: setattr(self, attr_name, to_ret) return to_ret +def setup_fit_params( system: PointingSystem, cfg: Namespace, nuisance_params: NuisanceParams) -> 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. + nuisance_params : NuisanceParams + Per-observation nuisance parameters. + + 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. + """ + # 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 + + # Setup nuisance fit parameters + nuisance_values = [] + nuisance_bounds = [] + nuisance_scales = [] + for par_dict in nuisance_params.par_list: + 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.append(value) + nuisance_bounds.append((-np.inf, np.inf)) + nuisance_scales.append(1.0) + continue + idx = system.parameter_names.index(name) + nuisance_values.append(value) + lo, hi = bounds[idx] + nuisance_bounds.append((value - (value - lo)/cfg.nuisance_scale, value + (hi - value)/cfg.nuisance_scale)) + nuisance_scales.append(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)]) + + return params, bounds, scales + class StaticOrCached(Generic[T]): """ @@ -305,6 +371,132 @@ def __get__(self, obj: Any, owner: type | None = None) -> T | "StaticOrCached[T] return res return getattr(obj, f"_{self.name}_dyn") +@dataclass +class NuisanceParams: + """ + Map and store of per observation nuicance parameters. + 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. + """ + obs_mapping : dict[str, int] + par_list : list[dict[str, float]] + + def __getitem__(self, key) -> dict[str, float]: + if key not in self.obs_mapping: + return {} + return self.par_list[self.obs_mapping[key]] + + @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 + + @classmethod + def from_system(cls, system : PointingSystem, nuisance_pars: dict[str, float], threshold: float) -> NuisanceParams: + 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))] + return cls(obs_mapping, par_list) + + + 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) + + @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"]) + + return cls(obs_mapping, par_list) @dataclass class PointingModel: @@ -331,6 +523,7 @@ class PointingModel: epoch: str parameters: dict + nuisance_params: NuisanceParams force_zero_roll: bool pad: bool = False @@ -339,6 +532,7 @@ def apply_det( det_off: DetectorOffsets, det_enc: DetectorOffsets, msk: Bool[np.ndarray, "ndet"], + meas_id: str, fake_gamma: bool, tol: float = 2.42e-6, max_iter: int = 5, @@ -406,6 +600,12 @@ def apply_det( "Detector offsets and encoder values must have same shape!" ) + # Apply nuisance + params_use = deepcopy(self.parameters) + nuisance = self.nuisance_params[meas_id] + for key, val in nuisance.items(): + params_use[key] += val + # Start with the input detector coordinates if not np.any(msk): return deepcopy(det_off) @@ -417,7 +617,6 @@ def apply_det( fp = to_ret[msk].fp det_enc_msk = det_enc[msk] ancil = det_enc_msk.ancil - # xi, eta, gamma = to_ret.xyz[msk].T err = np.inf alpha = 1.0 @@ -433,7 +632,7 @@ def apply_det( fp.gamma = estimate[:, 2] # Apply the pointing model - bs, fp_corrected = apply_pointing_model(None, self.parameters, ancil, fp) + 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) @@ -523,7 +722,7 @@ def save(self, f: h5py.File, path: str, overwrite: bool = True): parameters.save(f, f"{path}/parameters") @classmethod - def load(cls, f: h5py.File, path: str) -> Self: + def load(cls, f: h5py.File, path: str, nuisance_params: NuisanceParams) -> Self: """ Load a pointing model from an HDF5 file. @@ -546,6 +745,7 @@ def load(cls, f: h5py.File, path: str) -> Self: 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)), ) @@ -1188,7 +1388,7 @@ def thaw(self, static: bool): @property def _pm_data_dyn(self) -> DetectorOffsets: to_ret = self.pointing_model.apply_det( - self.data, self.enc, self.wmsk, self.fake_gamma + self.data, self.enc, self.wmsk, self.meas_id, self.fake_gamma ) if self.autofreeze: self._pm_data_stat = to_ret @@ -1499,11 +1699,23 @@ def thaw(self, static: bool): self.static = static @property - def chisq(self) -> float: - chisq = 0 + def residuals(self) -> Float[np.ndarray, "ndet*nobs"]: + residuals = [] for meas in self.focal_planes: - chisq += np.nansum((np.linalg.norm(meas.fpc_resid, axis=1)*meas.weights)**2) - return chisq + ndim = 3 - int(meas.fake_gamma) + r = np.linalg.norm(meas.fpc_resid[:, :ndim], axis=1) * meas.weights + r[~meas.wmsk] = 0 + residuals.append(r) + if not residuals: + return np.empty(0) + to_ret = np.nan_to_num(np.concatenate(residuals), 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: @@ -2188,6 +2400,7 @@ class PointingSystem: 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 @@ -2197,6 +2410,10 @@ def __post_init__(self): # Force consistancy self.update_parameters(self.parameters) + @property + 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. @@ -2262,13 +2479,28 @@ def parameters(self) -> Float[np.ndarray, "npar"]: ) def update_parameters(self, new_pars: Float[np.ndarray, "npar"]): + npar = len(self.parameters) for val, par, par_map in zip( - new_pars, self.parameter_names, self.parameter_map + 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 residuals(self) -> Float[np.ndarray, "n_data"]: + residuals = [] + for rx in self.receivers: + for ot in rx.optics_tubes: + for fp in ot.focal_planes: + if fp.pad: + continue + residuals.append(fp.residuals) + return np.concatenate(residuals) + @property def chisq(self) -> float: chisq = 0.0 @@ -2278,9 +2510,6 @@ def chisq(self) -> float: if fp.pad: continue chisq += fp.chisq - # chisq += np.nansum( - # ((fp.weights * np.linalg.norm(fp.resid, axis=1)) ** 2) * (1 + fp.scatter) - # ).item() return chisq def chisq_cm_prior( @@ -2314,20 +2543,34 @@ def chisq_cm_prior( return np.inf return self.chisq - def objective(self, params, cm_priors): - # orig_pars = self.parameters.copy() + def objective(self, params, cm_priors, nresid): self.update_parameters(params) - print(params) self.set_thaw(True) try: if cm_priors is None: - return self.chisq - return self.chisq_cm_prior(**cm_priors) + chisq = self.chisq + else: + chisq = self.chisq_cm_prior(**cm_priors) + if np.isfinite(chisq): + for rx in self.receivers: + chisq += np.sum((nresid*rx.cm_transform.shift)**2) + (nresid*rx.cm_transform.rot)**2 + return chisq + except (RuntimeError, AssertionError): + return 1e6 + + def objective_resid(self, params, nresid): + self.update_parameters(params) + self.set_thaw(True) + try: + resid = [self.residuals,] + for rx in self.receivers: + resid += [nresid*rx.cm_transform.shift.tolist(), nresid*rx.cm_transform.rot] + return np.hstack(resid) except (RuntimeError, AssertionError): - return np.inf #1000*self.objective(orig_pars, cm_priors) + return np.full(nresid, 1e3) - def log_prob(self, params, cm_priors): - return -0.5 * self.objective(params, cm_priors) + def log_prob(self, params, cm_priors, nresid): + return -0.5 * self.objective(params, cm_priors, nresid) @overload def search( @@ -2498,10 +2741,11 @@ def empty(cls, era: epochs.Era, cfg: Namespace, calender_str: str) -> Self: raise ValueError( "Era is either missing or has inconsistent values for ws_mapping" ) + nuisance_params = NuisanceParams({}, []) rxs = [] pms = [] for epoch in era.epochs: - pms += [PointingModel(epoch.name, {}, cfg.force_zero_roll, False)] + pms += [PointingModel(epoch.name, {}, nuisance_params, cfg.force_zero_roll, False)] ws_map = epoch.covers[0].data["ws_mapping"] ots = [] for ot, arrays in ws_map.items(): @@ -2596,7 +2840,7 @@ def _group_epochs(dat, groups, desc, check_fields): 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), par_names, par_map, calender_str, {}) + 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() @@ -2648,6 +2892,7 @@ def save(self, f: h5py.File, path: str, overwrite: bool = True): 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, @@ -2707,9 +2952,13 @@ def load(cls, f: h5py.File, path: str) -> Self: 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}") + PointingModel.load(f, f"{path}/pointing_models/{name}", nuisance_params) for name in sorted(pm_group.keys()) ) @@ -2723,6 +2972,7 @@ def load(cls, f: h5py.File, path: str) -> Self: era=era, pointing_models=pointing_models, receivers=receivers, + nuisance_params=nuisance_params, parameter_names=parameter_names, parameter_map=parameter_map, calender_str=calender_str, diff --git a/sotodlib/coords/fp_plots.py b/sotodlib/coords/fp_plots.py index 2b765cacf..94a71798a 100644 --- a/sotodlib/coords/fp_plots.py +++ b/sotodlib/coords/fp_plots.py @@ -15,6 +15,7 @@ FocalPlaneCollection, OpticsTube, Receiver, + PointingSystem, ) @@ -841,3 +842,99 @@ def plot_receiver_resid_vs_enc( 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/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index c3ecdfb36..71bd0e1bf 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -28,6 +28,7 @@ import sqlalchemy as sqy import yaml from scipy.optimize import minimize +from scipy.optimize import least_squares from sotodlib.coords import optics from sotodlib.core import Context, metadata from sotodlib.io.metadata import read_dataset @@ -64,9 +65,14 @@ "n_rounds": 3, "cm_priors": {"sft_tol": 1e-5, "rot_tol": 1e4, "scl_tol": 0.1, "shr_tol": 0.01}, "outlier_sigma": 3, - "mcmc_steps": 0, + "mcmc_steps": 300, "nwalkers": 32, "save_every": 10, + "nuisance_params": {}, + "obs_time_thresh": 180, + "nuisance_scale": 10, + "activate_nuisance": 1, + "least_squares": True, } @@ -81,6 +87,210 @@ class ErrCode(Enum): FPINIT = 7 + +def least_squares_fixed(fun, x0, bounds, x_scale, 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] + + 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], + **kwargs, + ) + + x_full = x_fixed.copy() + x_full[free_mask] = result.x + result.x = x_full + result.fixed_mask = fixed_mask + + return result + +def _fit_round(system, x0, bounds, scales, nresid, use_least_squares): + 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, + args=(nresid,), + method="trf", + loss="linear", #"soft_l1", + tr_solver="lsmr", + verbose=2, + ) + + 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, None, nresid) + + res = minimize( + scaled_objective, + x0 / scales, + method="L-BFGS-B", + bounds=scaled_bounds, + ) + + return res, res.x * scales + + +def _run_mcmc(system, nresid, cfg, bounds, scales, data_dir, plot_dir): + system.set_static(False) + system.set_thaw(True) + + x0 = system.parameters_full.copy() + ndim = len(x0) + npar = len(system.parameters) + 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) + + fixed_mask = lb == ub + free_mask = ~fixed_mask + nfixed = np.sum(fixed_mask) + nfree = np.sum(free_mask) + x_fixed = x0.copy() + x_fixed[fixed_mask] = lb[fixed_mask] + nwalkers = 2*nfree + + if nfree == 0: + raise ValueError("All parameters are fixed; nothing to sample.") + + logger.info("MCMC parameters: %d total, %d free, %d fixed (%d physical, %d nuisance)", ndim, nfree, nfixed, npar, ndim - npar) + + # Log probability with bounds and stuff + def log_prob(x_free): + x = x_fixed.copy() + x[free_mask] = x_free + if np.any(x_free < lb[free_mask]) or np.any(x_free > ub[free_mask]): + return -np.inf + try: + value = system.log_prob(x, None, nresid) + except (RuntimeError, AssertionError, ValueError, FloatingPointError): + return -np.inf + if not np.isfinite(value): + return -np.inf + return value + + # Initialize walkers + rng = np.random.default_rng() + init_scale = 1e-2 + x0_free = x_fixed[free_mask] + scales_free = scales[free_mask] + lb_free = lb[free_mask] + ub_free = ub[free_mask] + p0 = np.empty((nwalkers, nfree)) + for i in range(nwalkers): + failed = True + for _ in range(1000): + trial = x0_free + rng.normal(size=nfree) * scales_free * init_scale + if np.any(trial < lb_free) or np.any(trial > ub_free): + continue + if np.isfinite(log_prob(trial)): + p0[i] = trial + failed = False + break + if failed: + raise RuntimeError( f"Could not initialize walker {i}") + + # Run sampler + chain_file = os.path.join(data_dir, "mcmc_chain.h5") + backend = emcee.backends.HDFBackend(chain_file) + backend.reset(nwalkers, ndim) + sampler = emcee.EnsembleSampler( nwalkers, nfree, log_prob) + logger.info("Starting MCMC for %d steps", cfg.mcmc_steps) + sampler.run_mcmc(p0, cfg.mcmc_steps, progress=True) + + # Diagnostics + logger.info( "Mean acceptance fraction: %.3f", np.mean(sampler.acceptance_fraction)) + try: + tau = sampler.get_autocorr_time() + logger.info("Autocorrelation times: %s", tau) + logger.info( "Estimated effective sample sizes: %s", np.round(nwalkers * cfg.mcmc_steps / tau).astype(int)) + discard = int(2 * np.max(tau)) + except emcee.autocorr.AutocorrError: + logger.warning("Chain too short to estimate autocorrelation time.") + 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 steps", discard) + + # Reconstruct full-dimensional chain + free_samples = np.asarray(sampler.get_chain(discard=discard, flat=True)) + if len(free_samples) == 0: + raise RuntimeError("No samples remaining after burn-in.") + samples = np.tile(x_fixed, (len(free_samples), 1)) + samples[:, free_mask] = free_samples + + # Save full chain to HDF5. + with h5py.File(chain_file, "w") as f: + f.create_dataset( "samples", data=samples, compression="gzip") + f.create_dataset("fixed_mask", data=fixed_mask) + f.attrs["nwalkers"] = nwalkers + f.attrs["ndim"] = ndim + f.attrs["nfree"] = nfree + f.attrs["discard"] = discard + + # Posterior summaries + median = np.median(samples, axis=0) + lower = np.percentile(samples, 16, axis=0) + upper = np.percentile(samples, 84, axis=0) + system.update_parameters(median) + system.set_thaw(True) + system.set_freeze(True) + + # Log parameter estimates + header = ( + f"{'Parameter Name':<35}" + f"{'Median':>18}" + f"{'Lower':>18}" + f"{'Upper':>18}" + ) + logger.info("MCMC 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}{med:>18.8g}{lo:>18.8g}{hi:>18.8g}") + + # Plot + plot_mask = np.zeros(ndim, dtype=bool) + plot_mask[:npar] = True + plot_mask *= free_mask + physical_samples = 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") + logger.info("MCMC complete.") + + return sampler, samples + + def _get_jobdict_po(jdb): return { f"{job.tags['obs_id']}+{job.tags['wafer_slot']}+{job.tags['array']}": job @@ -548,6 +758,7 @@ def _plot_fit(system, plot_dir, i): fpp.plot_receiver(rx, pdir) fpp.plot_receiver_displacements(rx, [(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 @@ -599,45 +810,45 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): _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 - # ) + 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) + 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: @@ -658,37 +869,25 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): ) meas.pointing_model = system.pointing_models[pm_idx] - # 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 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 = 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 - + params, bounds, scales = fpc.setup_fit_params(system, cfg, system.nuisance_params) system.update_parameters(params) - logger.info(params) - logger.info(scales) + logger.info(params[:len(system.parameters)]) system.set_thaw(True) system.set_freeze(True) @@ -696,33 +895,36 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): _plot_fit(system, plot_dir, 0) # Fit for pointing model and focal planes - def scaled_objective(z, args): - return system.objective(z * scales, args) - scaled_bounds = [(lo / scale, hi / scale,) for scale, (lo, hi) in zip(scales, bounds)] - + nresid = len(system.residuals) for i in range(cfg.n_rounds): logger.info("Starting fit round %d", i + 1) system.set_thaw(True) - x0 = system.parameters.copy()/scales - res = minimize( - scaled_objective, - x0, - args=(None,), - method="L-BFGS-B", - bounds=scaled_bounds, - # options={ - # # "eps": 1e-7, - # "maxiter": 5000, - # "ftol": 1e-12, - # "gtol": 1e-8, - # } - ) - system.update_parameters(res.x * scales) - logger.info(res.x * scales) + npar = len(system.parameters) + x0 = system.parameters_full.copy() + scales_use = scales + bounds_use = bounds + if i < cfg.activate_nuisance: + 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) + system.update_parameters(params_fit) + 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) + 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}") system.set_thaw(True) system.set_freeze(True) - _plot_fit(system, plot_dir, i+1) - + _plot_fit(system, plot_dir, i + 1) + # Cut outliers tot_cut = 0 for rx in system.receivers: @@ -739,65 +941,23 @@ def scaled_objective(z, args): else: err = np.linalg.norm(meas.fpc_resid, axis=1) err[~wmsk] = np.nan - all_errs += [err] - wmsks += [wmsk] - errs_full = np.hstack(all_errs) - err_cuttoff = np.nanmean(errs_full) + cfg.outlier_sigma*np.nanstd(errs_full) + 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) for meas, err, wmsk in zip(fp.focal_planes, all_errs, wmsks): - mrmsk = err > err_cuttoff - meas.weights[mrmsk] = 0 + mrmsk = err > err_cutoff + # meas.weights[mrmsk] = 0 meas.wmsk[mrmsk] = False tot_cut += np.sum(mrmsk[wmsk]) - if tot_cut == 0: + + if tot_cut == 0 and i >= cfg.activate_nuisance: logger.info("None cut! Stopping optimization.") break # Run MCMC if we want if cfg.mcmc_steps > 0: - system.set_static(False) - ndim = len(system.parameters) - - # Create HDF5 backend - chain_file = os.path.join(data_dir, "mcmc_chain.h5") - backend = emcee.backends.HDFBackend(chain_file) - - # Run a fresh chain - system.set_thaw(True) - backend.reset(cfg.nwalkers, ndim) - sampler = emcee.EnsembleSampler( - cfg.nwalkers, - ndim, - system.log_prob, - args=(cfg.cm_priors,), - backend=backend, - ) - sampler.run_mcmc(system.parameters, cfg.mcmc_steps) - samples = sampler.get_chain( discard=int(0.1 * cfg.mcmc_steps), flat=True) - assert samples is not None - - # Update params - system.update_parameters(np.median(samples, axis=0)) - lower = np.percentile(samples, 16, axis=0) - upper = np.percentile(samples, 84, axis=0) - _ = lower, upper - system.set_thaw(True) - system.set_freeze(True) - - # Plot - _plot_fit(system, plot_dir, "mcmc") - labels = list(system.parameter_names) - fig = corner.corner( - samples, - labels=labels, - quantiles=[0.16, 0.50, 0.84], - show_titles=True, - title_fmt=".4f", - title_kwargs={"fontsize": 10}, - label_kwargs={"fontsize": 10}, - truths=np.median(samples, axis=0), - ) - fig.savefig( os.path.join(plot_dir, "mcmc_corner.png"), dpi=200, bbox_inches="tight") - plt.close(fig) + _ = _run_mcmc(system, nresid, cfg, bounds, scales, data_dir, plot_dir) # Save system.set_static(True) diff --git a/sotodlib/utils/epochs.py b/sotodlib/utils/epochs.py index c7e0fda81..0f64c379a 100644 --- a/sotodlib/utils/epochs.py +++ b/sotodlib/utils/epochs.py @@ -6,6 +6,7 @@ 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 @@ -23,6 +24,37 @@ } +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: """ From f5f4ead6e3a668f8aedb50ddfe585ba62a0ba05b Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Wed, 18 Nov 2026 06:45:23 -0800 Subject: [PATCH 118/132] fix!: remove roll check --- sotodlib/coords/pointing_model.py | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/sotodlib/coords/pointing_model.py b/sotodlib/coords/pointing_model.py index 47789e5b5..f64ff2345 100644 --- a/sotodlib/coords/pointing_model.py +++ b/sotodlib/coords/pointing_model.py @@ -373,22 +373,22 @@ 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 @@ -398,7 +398,7 @@ def apply_lat_distortion_model(params, az, el, roll, focal_plane): # 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 From 478cf5c5c99d6ea7c71c936ada4dc6be40b5fd80 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Wed, 18 Nov 2026 06:45:49 -0800 Subject: [PATCH 119/132] feat: lots of caching and allow rescaling of cm prior --- sotodlib/coords/fp_containers.py | 181 ++++++++++++++++++++----------- 1 file changed, 120 insertions(+), 61 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index b73cd038c..67d8c3a97 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -248,21 +248,25 @@ def _transformed( return to_ret -def _get_aff(self: FocalPlane | FocalPlaneCollection, data_name: str, attr_name: str): +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( - self.template.xyz[wmsk, :2], - getattr(self, data_name).xyz[wmsk, :2], - self.weights[wmsk], + 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( - self.template.xyz[wmsk, 2], getattr(self, data_name).xyz[wmsk, 2] + getattr(self, template_name).xyz[msk, 2], getattr(self, data_name).xyz[msk, 2] ) if self.autofreeze: setattr(self, attr_name, to_ret) @@ -529,11 +533,7 @@ class PointingModel: def apply_det( self, - det_off: DetectorOffsets, - det_enc: DetectorOffsets, - msk: Bool[np.ndarray, "ndet"], - meas_id: str, - fake_gamma: bool, + meas, tol: float = 2.42e-6, max_iter: int = 5, ) -> DetectorOffsets: @@ -592,31 +592,30 @@ def apply_det( RuntimeError If the iterative distortion removal does not converge. """ + to_ret = deepcopy(meas.data) if len(self.parameters) == 0: - return det_off - - if len(det_enc.xyz) != len(det_off.xyz): - raise ValueError( - "Detector offsets and encoder values must have same shape!" - ) + return to_ret # Apply nuisance params_use = deepcopy(self.parameters) - nuisance = self.nuisance_params[meas_id] + nuisance = self.nuisance_params[meas.meas_id] for key, val in nuisance.items(): params_use[key] += val # Start with the input detector coordinates - if not np.any(msk): - return deepcopy(det_off) - estimate = det_off.xyz[msk].copy() - if fake_gamma: + if not np.any(meas.wmsk): + return to_ret + estimate = meas.data_msk.xyz.copy() + if meas.fake_gamma: estimate = estimate[:, :2] - fp_target = det_off[msk] - to_ret = deepcopy(det_off) - fp = to_ret[msk].fp - det_enc_msk = det_enc[msk] + 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 alpha = 1.0 @@ -625,7 +624,7 @@ def apply_det( for _ in range(max_iter): fp.xi = estimate[:, 0] fp.eta = estimate[:, 1] - if fake_gamma: + if meas.fake_gamma: q_fp = quat.rotation_xieta(estimate[:, 0], estimate[:, 1]) else: q_fp = quat.rotation_xieta(estimate[:, 0], estimate[:, 1], estimate[:, 2]) # type: ignore[arg-type] @@ -634,20 +633,14 @@ def apply_det( # Apply the pointing model 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) - * quat.rotation_lonlat(-1 * det_enc_msk.az, det_enc_msk.el) - * quat.euler(2, (not self.force_zero_roll) * det_enc_msk.roll) - * q_fp - ) + 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[msk] = np.column_stack((xi, eta, gamma)) + to_ret.xyz[meas.wmsk] = np.column_stack((xi, eta, gamma)) return to_ret # Estimate and remove focalplane distortion - if fake_gamma: + if meas.fake_gamma: distortion = np.column_stack( (fp_corrected.xi - fp.xi, fp_corrected.eta - fp.eta) ) @@ -678,20 +671,15 @@ def apply_det( prev_distortion = distortion prev_err = err if err < tol: - to_ret.xyz[msk] = np.column_stack((xi, eta, gamma)) + to_ret.xyz[meas.wmsk] = np.column_stack((xi, eta, gamma)) return to_ret # Update estimate of the undistorted fp estimate -= alpha * distortion - # logger.error( - # f"Pointing-model inversion did not converge after {max_iter} iterations (error={err:.3e} rad)." - # ) raise RuntimeError( f"Pointing-model inversion did not converge after {max_iter} iterations (error={err:.3e} rad)." ) - # to_ret.xyz[msk] = np.column_stack((xi, eta, gamma)) - # return to_ret def save(self, f: h5py.File, path: str, overwrite: bool = True): """ @@ -906,6 +894,7 @@ def __post_init__(self): def __setattr__(self, name: str, value: Any, /) -> None: if name in ("xyz"): self.__dict__.pop("ancil", None) + self.__dict__.pop("fp", None) return super().__setattr__(name, value) def __getitem__(self, key) -> DetectorOffsets: @@ -978,6 +967,14 @@ def fp(self): fp.wrap("gamma", self.gamma) return fp + @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) + def save(self, f: h5py.File, path: str, overwrite: bool = True): """Save detector offsets to an HDF5 ResultSet. @@ -1171,6 +1168,14 @@ class FocalPlane: _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 @@ -1183,6 +1188,26 @@ def template_fp(self) -> DetectorOffsets: 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, @@ -1387,16 +1412,14 @@ def thaw(self, static: bool): @property def _pm_data_dyn(self) -> DetectorOffsets: - to_ret = self.pointing_model.apply_det( - self.data, self.enc, self.wmsk, self.meas_id, self.fake_gamma - ) + 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", "_transform_stat") + return _get_aff(self, "data_msk", "template_msk", "weights_msk", "_transform_stat", False) @property def _transformed_dyn(self) -> DetectorOffsets: @@ -1404,7 +1427,7 @@ def _transformed_dyn(self) -> DetectorOffsets: @property def _pm_transform_dyn(self) -> Transform: - return _get_aff(self, "pm_data", "_pm_transform_stat") + return _get_aff(self, "pm_data_msk", "template_msk", "weights_msk", "_pm_transform_stat", False) @property def _pm_transformed_dyn(self) -> DetectorOffsets: @@ -1658,6 +1681,7 @@ class FocalPlaneCollection: _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] @@ -1698,17 +1722,32 @@ def thaw(self, static: bool): self.__dict__.pop("_transformed_stat", None) self.static = static + @property + def ndet(self) -> int: + return len(self.template.xyz) + + @property + def nobs(self) -> int: + return len(self.focal_planes) + @property def residuals(self) -> Float[np.ndarray, "ndet*nobs"]: - residuals = [] + 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: + 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 - residuals.append(r) - if not residuals: - return np.empty(0) - to_ret = np.nan_to_num(np.concatenate(residuals), copy=False, nan=0.0, posinf=np.inf, neginf=-np.inf) + 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 @@ -1742,7 +1781,7 @@ def _weights_dyn(self) -> Float[np.ndarray, "ndet"]: @property def _transform_dyn(self) -> Transform: - return _get_aff(self, "data", "_transform_stat") + return _get_aff(self, "data", "template", "weights", "_transform_stat", True) @property def _transformed_dyn(self) -> DetectorOffsets: @@ -2405,6 +2444,7 @@ class PointingSystem: 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 @@ -2490,16 +2530,35 @@ def update_parameters(self, new_pars: Float[np.ndarray, "npar"]): if npar < len(new_pars): self.nuisance_params.update(new_pars[npar:]) + @property + 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 residuals(self) -> Float[np.ndarray, "n_data"]: - residuals = [] + 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 - residuals.append(fp.residuals) - return np.concatenate(residuals) + fpr = fp.residuals + resid[i:(i+len(fpr))] = fpr + i += len(fpr) + return resid @property def chisq(self) -> float: @@ -2543,7 +2602,7 @@ def chisq_cm_prior( return np.inf return self.chisq - def objective(self, params, cm_priors, nresid): + def objective(self, params, cm_priors, nresid, cm_fac): self.update_parameters(params) self.set_thaw(True) try: @@ -2553,24 +2612,24 @@ def objective(self, params, cm_priors, nresid): chisq = self.chisq_cm_prior(**cm_priors) if np.isfinite(chisq): for rx in self.receivers: - chisq += np.sum((nresid*rx.cm_transform.shift)**2) + (nresid*rx.cm_transform.rot)**2 + 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, nresid): + def objective_resid(self, params, nresid, cm_fac): self.update_parameters(params) self.set_thaw(True) try: resid = [self.residuals,] for rx in self.receivers: - resid += [nresid*rx.cm_transform.shift.tolist(), nresid*rx.cm_transform.rot] + 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, cm_priors, nresid): - return -0.5 * self.objective(params, cm_priors, nresid) + def log_prob(self, params, cm_priors, nresid, cm_fac): + return -0.5 * self.objective(params, cm_priors, nresid, cm_fac) @overload def search( From 9e7c2e1f234684615709d9b237e672c57572f2c4 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Wed, 18 Nov 2026 06:46:27 -0800 Subject: [PATCH 120/132] feat: cleaner logging, jac_sparsity, and gibbs sampling --- .../site_pipeline/solve_static_pointing.py | 446 +++++++++++++----- 1 file changed, 327 insertions(+), 119 deletions(-) diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index 71bd0e1bf..dc67bb043 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -64,8 +64,8 @@ "parameters": {}, "n_rounds": 3, "cm_priors": {"sft_tol": 1e-5, "rot_tol": 1e4, "scl_tol": 0.1, "shr_tol": 0.01}, - "outlier_sigma": 3, - "mcmc_steps": 300, + "outlier_sigma": 20, + "mcmc_steps": 0, "nwalkers": 32, "save_every": 10, "nuisance_params": {}, @@ -73,6 +73,8 @@ "nuisance_scale": 10, "activate_nuisance": 1, "least_squares": True, + "cm_fac": 1e-3, + "proposal_factor": 1e-2, } @@ -88,7 +90,7 @@ class ErrCode(Enum): -def least_squares_fixed(fun, x0, bounds, x_scale, args=(), **kwargs): +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) @@ -96,6 +98,8 @@ def least_squares_fixed(fun, x0, bounds, x_scale, args=(), **kwargs): 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() @@ -108,6 +112,7 @@ def wrapped_fun(x_free, *args): args=args, bounds=(lb[free_mask], ub[free_mask]), x_scale=x_scale[free_mask], + jac_sparsity=jac_sparsity, **kwargs, ) @@ -118,7 +123,35 @@ def wrapped_fun(x_free, *args): return result -def _fit_round(system, x0, bounds, scales, nresid, use_least_squares): + +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): if use_least_squares: lb = np.array([b[0] for b in bounds]) ub = np.array([b[1] for b in bounds]) @@ -127,18 +160,20 @@ def _fit_round(system, x0, bounds, scales, nresid, use_least_squares): x0, bounds=(lb, ub), x_scale=scales, - args=(nresid,), + jac_sparsity=jac_sparsity, + args=(nresid, cm_fac), method="trf", loss="linear", #"soft_l1", tr_solver="lsmr", verbose=2, + # xtol=1e-8, ) 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, None, nresid) + return system.objective(z * scales, None, nresid, cm_fac) res = minimize( scaled_objective, @@ -157,122 +192,275 @@ def _run_mcmc(system, nresid, cfg, bounds, scales, data_dir, plot_dir): 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 - nfixed = np.sum(fixed_mask) - nfree = np.sum(free_mask) - x_fixed = x0.copy() - x_fixed[fixed_mask] = lb[fixed_mask] - nwalkers = 2*nfree - if nfree == 0: + # 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.") - logger.info("MCMC parameters: %d total, %d free, %d fixed (%d physical, %d nuisance)", ndim, nfree, nfixed, npar, ndim - npar) + # Enforce fixed parameter values + x = x0.copy() + x[fixed_mask] = lb[fixed_mask] - # Log probability with bounds and stuff - def log_prob(x_free): - x = x_fixed.copy() - x[free_mask] = x_free - if np.any(x_free < lb[free_mask]) or np.any(x_free > ub[free_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, None, nresid) - except (RuntimeError, AssertionError, ValueError, FloatingPointError): + value = system.log_prob(x, None, nresid, cfg.cm_fac) + 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 - # Initialize walkers rng = np.random.default_rng() - init_scale = 1e-2 - x0_free = x_fixed[free_mask] - scales_free = scales[free_mask] - lb_free = lb[free_mask] - ub_free = ub[free_mask] - p0 = np.empty((nwalkers, nfree)) - for i in range(nwalkers): - failed = True - for _ in range(1000): - trial = x0_free + rng.normal(size=nfree) * scales_free * init_scale - if np.any(trial < lb_free) or np.any(trial > ub_free): - continue - if np.isfinite(log_prob(trial)): - p0[i] = trial - failed = False - break - if failed: - raise RuntimeError( f"Could not initialize walker {i}") - - # Run sampler - chain_file = os.path.join(data_dir, "mcmc_chain.h5") - backend = emcee.backends.HDFBackend(chain_file) - backend.reset(nwalkers, ndim) - sampler = emcee.EnsembleSampler( nwalkers, nfree, log_prob) - logger.info("Starting MCMC for %d steps", cfg.mcmc_steps) - sampler.run_mcmc(p0, cfg.mcmc_steps, progress=True) - - # Diagnostics - logger.info( "Mean acceptance fraction: %.3f", np.mean(sampler.acceptance_fraction)) - try: - tau = sampler.get_autocorr_time() - logger.info("Autocorrelation times: %s", tau) - logger.info( "Estimated effective sample sizes: %s", np.round(nwalkers * cfg.mcmc_steps / tau).astype(int)) - discard = int(2 * np.max(tau)) - except emcee.autocorr.AutocorrError: - logger.warning("Chain too short to estimate autocorrelation time.") - discard = int(0.1 * cfg.mcmc_steps) + + # 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) + + # Estimate autocorrelation time + # 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)) + # if np.isnan(discard): + # logger.warning("Estimated autocorrelation time is nan") + # discard = int(0.1 * cfg.mcmc_steps) + # except emcee.autocorr.AutocorrError: + # logger.warning( "Chain too short to estimate autocorrelation time.") + 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 steps", discard) + raise RuntimeError( "MCMC chain too short relative to autocorrelation time.") + logger.info("Discarding %d burn-in iterations", discard) + + posterior_samples = samples[discard:] - # Reconstruct full-dimensional chain - free_samples = np.asarray(sampler.get_chain(discard=discard, flat=True)) - if len(free_samples) == 0: + if len(posterior_samples) == 0: raise RuntimeError("No samples remaining after burn-in.") - samples = np.tile(x_fixed, (len(free_samples), 1)) - samples[:, free_mask] = free_samples - # Save full chain to HDF5. + # Save the chain. + chain_file = os.path.join(data_dir, "mcmc_chain.h5") + with h5py.File(chain_file, "w") as f: f.create_dataset( "samples", data=samples, compression="gzip") + f.create_dataset( "posterior_samples", data=posterior_samples, compression="gzip") f.create_dataset("fixed_mask", data=fixed_mask) - f.attrs["nwalkers"] = nwalkers f.attrs["ndim"] = ndim - f.attrs["nfree"] = nfree + f.attrs["npar"] = npar + f.attrs["nuisance_params"] = nnuisance f.attrs["discard"] = discard + f.attrs["physical_acceptance"] = physical_fraction + f.attrs["nuisance_acceptance"] = nuisance_fraction # Posterior summaries - median = np.median(samples, axis=0) - lower = np.percentile(samples, 16, axis=0) - upper = np.percentile(samples, 84, axis=0) + 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 parameter estimates + # Log physical parameter estimates. header = ( f"{'Parameter Name':<35}" f"{'Median':>18}" f"{'Lower':>18}" f"{'Upper':>18}" ) - logger.info("MCMC parameter estimates:\n%s", header) + + 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])): + + 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}{med:>18.8g}{lo:>18.8g}{hi:>18.8g}") - # Plot - plot_mask = np.zeros(ndim, dtype=bool) - plot_mask[:npar] = True - plot_mask *= free_mask - physical_samples = samples[:, plot_mask] + 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( @@ -283,12 +471,13 @@ def log_prob(x_free): title_fmt=".4g", truths=median[plot_mask], ) - fig.savefig( os.path.join(plot_dir, "mcmc_corner.png"), dpi=200, bbox_inches="tight",) + + fig.savefig( os.path.join(plot_dir, "mcmc_corner.png"), dpi=200, bbox_inches="tight") plt.close(fig) _plot_fit(system, plot_dir, "mcmc") - logger.info("MCMC complete.") + logger.info("Gibbs MCMC complete") - return sampler, samples + return samples, posterior_samples def _get_jobdict_po(jdb): @@ -810,12 +999,12 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): _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 - ) + # 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") @@ -876,52 +1065,69 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): 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 - ) + # 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, system.nuisance_params) system.update_parameters(params) 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)) + 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)] = 1 + n += ndet + jac_sparsity[npar:,nresid:] = 1 + jac_sparsity = jac_sparsity.T system.set_thaw(True) system.set_freeze(True) logger.info("Initial chisq is %.5f", system.chisq) - _plot_fit(system, plot_dir, 0) + # _plot_fit(system, plot_dir, 0) # Fit for pointing model and focal planes - nresid = len(system.residuals) for i in range(cfg.n_rounds): logger.info("Starting fit round %d", i + 1) system.set_thaw(True) - npar = len(system.parameters) x0 = system.parameters_full.copy() - scales_use = scales - bounds_use = bounds - if i < cfg.activate_nuisance: - 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) + + # Just static + logger.info("Fitting static for round %d", i + 1) + 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) system.update_parameters(params_fit) - 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) - 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}") + _report_fit(res, cfg, system, npar, x0, True, False) system.set_thaw(True) + + # Now nuisance + if len(cfg.nuisance_params) > 0 and i+1 >= cfg.activate_nuisance: + logger.info("Fitting nuisance for round %d", i + 1) + x0 = system.parameters_full.copy() + bounds_fixed = [(val, val) for val in x0[:npar]] + bounds_use = bounds_fixed + bounds[npar:] + scales_use = scales + res, params_fit = _fit_round(system, x0, bounds_use, scales_use, nresid, cfg.least_squares, jac_sparsity, cfg.cm__fac) + system.update_parameters(params_fit) + _report_fit(res, cfg, system, npar, x0, False, True) + system.set_thaw(True) system.set_freeze(True) _plot_fit(system, plot_dir, i + 1) @@ -945,12 +1151,14 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): 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 From 8efca2c428b3d496fd5d63f7941f674a86793023 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Wed, 18 Nov 2026 06:57:16 -0800 Subject: [PATCH 121/132] feat: save mcmc to seperate file --- .../site_pipeline/solve_static_pointing.py | 67 ++++++++++--------- 1 file changed, 34 insertions(+), 33 deletions(-) diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index dc67bb043..a6c621574 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -368,18 +368,17 @@ def metropolis_step(x, current_logp, mask, block_name): logger.info("Physical acceptance fraction: %.3f", physical_fraction) logger.info("Nuisance acceptance fraction: %.3f", nuisance_fraction) - # Estimate autocorrelation time - # 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)) - # if np.isnan(discard): - # logger.warning("Estimated autocorrelation time is nan") - # discard = int(0.1 * cfg.mcmc_steps) - # except emcee.autocorr.AutocorrError: - # logger.warning( "Chain too short to estimate autocorrelation time.") - discard = int(0.1 * cfg.mcmc_steps) + 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.") @@ -390,20 +389,6 @@ def metropolis_step(x, current_logp, mask, block_name): if len(posterior_samples) == 0: raise RuntimeError("No samples remaining after burn-in.") - # Save the chain. - chain_file = os.path.join(data_dir, "mcmc_chain.h5") - - with h5py.File(chain_file, "w") as f: - f.create_dataset( "samples", data=samples, compression="gzip") - f.create_dataset( "posterior_samples", data=posterior_samples, compression="gzip") - f.create_dataset("fixed_mask", data=fixed_mask) - f.attrs["ndim"] = ndim - f.attrs["npar"] = npar - f.attrs["nuisance_params"] = nnuisance - f.attrs["discard"] = discard - f.attrs["physical_acceptance"] = physical_fraction - f.attrs["nuisance_acceptance"] = nuisance_fraction - # Posterior summaries median = np.median(posterior_samples, axis=0) lower = np.percentile(posterior_samples, 16, axis=0) @@ -477,6 +462,23 @@ def metropolis_step(x, current_logp, mask, block_name): _plot_fit(system, plot_dir, "mcmc") 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 @@ -1162,19 +1164,18 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): if tot_cut == 0 and i >= cfg.activate_nuisance: logger.info("None cut! Stopping optimization.") break - - # Run MCMC if we want - if cfg.mcmc_steps > 0: - _ = _run_mcmc(system, nresid, cfg, bounds, scales, data_dir, plot_dir) + 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 - ) + 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) def main(): # Load arguments From 0fe7289d7fcca9d858095f1e5d3d5990742689c5 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Wed, 18 Nov 2026 12:11:34 -0800 Subject: [PATCH 122/132] feat: add nuisance plots --- sotodlib/coords/fp_plots.py | 233 +++++++++++++----- .../site_pipeline/solve_static_pointing.py | 3 +- 2 files changed, 179 insertions(+), 57 deletions(-) diff --git a/sotodlib/coords/fp_plots.py b/sotodlib/coords/fp_plots.py index 94a71798a..c8d8d6ce1 100644 --- a/sotodlib/coords/fp_plots.py +++ b/sotodlib/coords/fp_plots.py @@ -15,7 +15,7 @@ FocalPlaneCollection, OpticsTube, Receiver, - PointingSystem, + NuisanceParams, ) @@ -619,6 +619,75 @@ def plot_receiver( 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]]], @@ -640,87 +709,139 @@ def plot_receiver_displacements( 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. + 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. """ - os.makedirs(output_dir, exist_ok=True) - 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: + if fp.pad or fp.template.center is None: continue - if fp.template.center is None: - continue - xc = fp.template.center[0] - yc = fp.template.center[1] + xc, yc = fp.template.center[:2] for meas in fp.focal_planes: - msk = np.isfinite(meas.weights) * (meas.weights > 0) + 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] - ) + 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) - 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( + 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, - constrained_layout=True, ) - if name is None: - ax.quiver(x0, y0, dx, dy, angles="xy", scale_units="xy") - title = f"{receiver.name} Observation Displacements" - fname = f"{receiver.name}_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"{receiver.name} Observation Displacements by {name}\n{scale_str}" - fname = f"{receiver.name}_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_resid_vs_enc( receiver: Receiver, diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index a6c621574..f93f47b7b 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -948,6 +948,7 @@ def _plot_fit(system, plot_dir, 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.nuisanse_plot, [(None, None)], pdir) fpp.plot_receiver_resid_vs_enc(rx, pdir) fpp.plot_receiver_residuals(rx, pdir) for ot in rx.optics_tubes: @@ -1126,7 +1127,7 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): bounds_fixed = [(val, val) for val in x0[:npar]] bounds_use = bounds_fixed + bounds[npar:] scales_use = scales - res, params_fit = _fit_round(system, x0, bounds_use, scales_use, nresid, cfg.least_squares, jac_sparsity, cfg.cm__fac) + res, params_fit = _fit_round(system, x0, bounds_use, scales_use, nresid, cfg.least_squares, jac_sparsity, cfg.cm_fac) system.update_parameters(params_fit) _report_fit(res, cfg, system, npar, x0, False, True) system.set_thaw(True) From 697c0187397b37ab284d9777e09e1ae5c02dcf9e Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Wed, 18 Nov 2026 13:13:42 -0800 Subject: [PATCH 123/132] feat: remove hard cm priors and switch to csr --- sotodlib/coords/fp_containers.py | 43 +++---------------- .../site_pipeline/solve_static_pointing.py | 18 ++++---- 2 files changed, 14 insertions(+), 47 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 67d8c3a97..749086c04 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -2571,45 +2571,11 @@ def chisq(self) -> float: chisq += fp.chisq return chisq - def chisq_cm_prior( - self, sft_tol: float, rot_tol: float, scl_tol: float, shr_tol: float - ) -> float: - """ - Compute the chisq of the full pointing system but with strong priors on to reject - any common mode transformations across the receiver. - These are rectangular priors defined by a tolerance against the null space of the affine transform. - Any common mode out of tolerance will return a chisq of infinity. - - Parameters - ---------- - sft_tol : float - Tolerance in shift away from 0. - rot_tol : float - Tolerance in rotation away from 0. - scl_tol : float - Tolerance in scale away from 1. - shr_tol : float - Tolerance in shear away from 0. - """ - for rx in self.receivers: - if np.any(rx.cm_transform.shift > sft_tol): - return np.inf - if np.any(rx.cm_transform.rot > rot_tol): - return np.inf - if np.any(np.abs(rx.cm_transform.scale - 1) > scl_tol): - return np.inf - if np.any(rx.cm_transform.shear > shr_tol): - return np.inf - return self.chisq - - def objective(self, params, cm_priors, nresid, cm_fac): + def objective(self, params, nresid, cm_fac): self.update_parameters(params) self.set_thaw(True) try: - if cm_priors is None: - chisq = self.chisq - else: - chisq = self.chisq_cm_prior(**cm_priors) + 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 @@ -2618,6 +2584,7 @@ def objective(self, params, cm_priors, nresid, cm_fac): return 1e6 def objective_resid(self, params, nresid, cm_fac): + print("obj") self.update_parameters(params) self.set_thaw(True) try: @@ -2628,8 +2595,8 @@ def objective_resid(self, params, nresid, cm_fac): except (RuntimeError, AssertionError): return np.full(nresid, 1e3) - def log_prob(self, params, cm_priors, nresid, cm_fac): - return -0.5 * self.objective(params, cm_priors, nresid, cm_fac) + def log_prob(self, params, nresid, cm_fac): + return -0.5 * self.objective(params, nresid, cm_fac) @overload def search( diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index f93f47b7b..718dde768 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -29,6 +29,7 @@ import yaml from scipy.optimize import minimize from scipy.optimize import least_squares +from scipy.sparse import csr_array from sotodlib.coords import optics from sotodlib.core import Context, metadata from sotodlib.io.metadata import read_dataset @@ -63,7 +64,6 @@ "pad_empty": True, "parameters": {}, "n_rounds": 3, - "cm_priors": {"sft_tol": 1e-5, "rot_tol": 1e4, "scl_tol": 0.1, "shr_tol": 0.01}, "outlier_sigma": 20, "mcmc_steps": 0, "nwalkers": 32, @@ -151,7 +151,7 @@ def _report_fit(res, cfg, system, npar, x0, report_static, report_nuisance): 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): +def _fit_round(system, x0, bounds, scales, nresid, use_least_squares, jac_sparsity, cm_fac, **kwargs): if use_least_squares: lb = np.array([b[0] for b in bounds]) ub = np.array([b[1] for b in bounds]) @@ -166,20 +166,21 @@ def _fit_round(system, x0, bounds, scales, nresid, use_least_squares, jac_sparsi loss="linear", #"soft_l1", tr_solver="lsmr", verbose=2, - # xtol=1e-8, + **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, None, nresid, cm_fac) + return system.objective(z * scales, nresid, cm_fac) res = minimize( scaled_objective, x0 / scales, method="L-BFGS-B", bounds=scaled_bounds, + **kwargs, ) return res, res.x * scales @@ -234,7 +235,7 @@ def log_prob(x): if np.any(x < lb) or np.any(x > ub): return -np.inf try: - value = system.log_prob(x, None, nresid, cfg.cm_fac) + value = system.log_prob(x, nresid, cfg.cm_fac) except ( RuntimeError, AssertionError, @@ -249,7 +250,6 @@ def log_prob(x): if not np.isfinite(current_logp): raise RuntimeError("Initial parameter vector has invalid log probability.") - diagnostics = { "physical": { "bounds": 0, @@ -1094,10 +1094,10 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): 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)] = 1 + jac_n[idx, :, n:(n+ndet)] = meas.wmsk.astype(int) n += ndet jac_sparsity[npar:,nresid:] = 1 - jac_sparsity = jac_sparsity.T + jac_sparsity = csr_array(jac_sparsity.T, dtype=bool) system.set_thaw(True) system.set_freeze(True) @@ -1127,7 +1127,7 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): bounds_fixed = [(val, val) for val in x0[:npar]] bounds_use = bounds_fixed + bounds[npar:] scales_use = scales - res, params_fit = _fit_round(system, x0, bounds_use, scales_use, nresid, cfg.least_squares, jac_sparsity, cfg.cm_fac) + res, params_fit = _fit_round(system, x0, bounds_use, scales_use, nresid, cfg.least_squares, jac_sparsity, cfg.cm_fac, max_nfev=25, xtol=1e-6, ftol=1e-4) system.update_parameters(params_fit) _report_fit(res, cfg, system, npar, x0, False, True) system.set_thaw(True) From 11d0c5cdbfd8e5179a25481e3207c9e2a39512e6 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Wed, 18 Nov 2026 17:17:02 -0500 Subject: [PATCH 124/132] feat: first pass at nuisance transforms --- sotodlib/coords/fp_containers.py | 86 +++++++++++++++++-- sotodlib/coords/fp_plots.py | 78 +++++++++++++++++ .../site_pipeline/solve_static_pointing.py | 14 ++- 3 files changed, 166 insertions(+), 12 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 749086c04..a976fe058 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -378,7 +378,7 @@ def __get__(self, obj: Any, owner: type | None = None) -> T | "StaticOrCached[T] @dataclass class NuisanceParams: """ - Map and store of per observation nuicance parameters. + Map and store of per observation nuisance parameters and transforms. Can be indexed directly by `obs_id`. Attributes @@ -391,14 +391,19 @@ class NuisanceParams: 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. """ obs_mapping : dict[str, int] par_list : list[dict[str, float]] + transform_list : list[Transform] - def __getitem__(self, key) -> dict[str, float]: + def __getitem__(self, key) -> tuple[dict[str, float], Transform]: if key not in self.obs_mapping: - return {} - return self.par_list[self.obs_mapping[key]] + return {}, Transform.identity() + idx = self.obs_mapping[key] + return self.par_list[idx], self.transform_list[idx] @property def params_flat(self) -> Float[np.ndarray, "npar"]: @@ -435,7 +440,59 @@ def from_system(cls, system : PointingSystem, nuisance_pars: dict[str, float], t 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))] - return cls(obs_mapping, par_list) + transform_list = [Transform.identity() for _ in range(len(obs_ids_split))] + return cls(obs_mapping, par_list, transform_list) + + def compute_transforms(self, system): + """ + 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 `nuisance_transform = ~(obs_transform * ~ cm_transform)` if we have some existing `nuisance_transform` then it was already + included in `pm_data = nuisance_transform_old(pointing_model(data))` so the new nuisance_transform should chain them as + `nuisance_transform = nuisance_transform_new * nuisance_transform_old` giving us: + `pm_data = nuisance_transform(pointing_model(data)) = (nuisance_transform_new * nuisance_transform_old)(pointing_model(data)) = nuisance_transform_new(pm_data_old)` + + 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. + """ + rev_mapping = [[] for _ in range(len(self.transform_list))] + for meas_id, idx in self.obs_mapping.items(): + rev_mapping[idx] += [meas_id] + 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, False, fast=True) + n_aff, n_sft = mt.invert_transform(mt.compose_transforms(cm_aff, cm_shift, rx_aff_inv, rx_sft_inv)) + trf_old = self.transform_list[i] + n_aff, n_sft = mt.compose_transforms(trf_old.affine, trf_old.shift, n_aff, n_sft) + self.transform_list[i] = Transform(n_aff, n_sft) + 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): @@ -470,6 +527,10 @@ def save(self, f: h5py.File, path: str, overwrite: bool = True): 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: """ @@ -499,8 +560,13 @@ def load(cls, f: h5py.File, path: str) -> Self: 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) + return cls(obs_mapping, par_list, transform_list) @dataclass class PointingModel: @@ -598,8 +664,8 @@ def apply_det( # Apply nuisance params_use = deepcopy(self.parameters) - nuisance = self.nuisance_params[meas.meas_id] - for key, val in nuisance.items(): + npars, ntrf = self.nuisance_params[meas.meas_id] + for key, val in npars.items(): params_use[key] += val # Start with the input detector coordinates @@ -637,6 +703,7 @@ def apply_det( 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 # Estimate and remove focalplane distortion @@ -672,6 +739,7 @@ def apply_det( 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 # Update estimate of the undistorted fp @@ -2767,7 +2835,7 @@ def empty(cls, era: epochs.Era, cfg: Namespace, calender_str: str) -> Self: raise ValueError( "Era is either missing or has inconsistent values for ws_mapping" ) - nuisance_params = NuisanceParams({}, []) + nuisance_params = NuisanceParams({}, [], []) rxs = [] pms = [] for epoch in era.epochs: diff --git a/sotodlib/coords/fp_plots.py b/sotodlib/coords/fp_plots.py index c8d8d6ce1..f7ecf2627 100644 --- a/sotodlib/coords/fp_plots.py +++ b/sotodlib/coords/fp_plots.py @@ -843,6 +843,84 @@ def plot_receiver_nuisance_displacements( 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, diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index 718dde768..ca7fdeeca 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -72,6 +72,7 @@ "obs_time_thresh": 180, "nuisance_scale": 10, "activate_nuisance": 1, + "activate_nuisance_transforms": 1, "least_squares": True, "cm_fac": 1e-3, "proposal_factor": 1e-2, @@ -459,7 +460,7 @@ def metropolis_step(x, current_logp, mask, block_name): fig.savefig( os.path.join(plot_dir, "mcmc_corner.png"), dpi=200, bbox_inches="tight") plt.close(fig) - _plot_fit(system, plot_dir, "mcmc") + _plot_fit(system, plot_dir, "mcmc", cfg) logger.info("Gibbs MCMC complete") # Save the chain. @@ -939,7 +940,7 @@ def _check_jobs(system, jdb, done_jobs, open_jobs): return open_jobs, done_jobs -def _plot_fit(system, plot_dir, i): +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: @@ -949,6 +950,7 @@ def _plot_fit(system, plot_dir, i): fpp.plot_receiver(rx, pdir) fpp.plot_receiver_displacements(rx, [(None, None)], pdir) fpp.plot_receiver_nuisance_displacements(rx, system.nuisance_params, cfg.nuisanse_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: @@ -1131,8 +1133,14 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): system.update_parameters(params_fit) _report_fit(res, cfg, system, npar, x0, False, True) system.set_thaw(True) + + # Now do the fp nuisance transforms + if i+1 >= cfg.activate_nuisance_transforms: + system.nuisance_params.compute_transforms(system) + + # Freeze and plot system.set_freeze(True) - _plot_fit(system, plot_dir, i + 1) + _plot_fit(system, plot_dir, "i + 1", cfg) # Cut outliers tot_cut = 0 From 43da4fcb41a1c0b7cb8f337287a5cee057a36826 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Wed, 18 Nov 2026 18:24:18 -0500 Subject: [PATCH 125/132] fix: update docstrings and a bunch of small fixes --- sotodlib/coords/fp_containers.py | 539 ++++++++++++++++++++++++------- 1 file changed, 421 insertions(+), 118 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index a976fe058..1a59e3475 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -394,6 +394,9 @@ class NuisanceParams: 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]] @@ -427,6 +430,30 @@ def update(self, params: Float[np.ndarray, "npar"]): @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 measurement 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 observation 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: @@ -443,8 +470,8 @@ def from_system(cls, system : PointingSystem, nuisance_pars: dict[str, float], t transform_list = [Transform.identity() for _ in range(len(obs_ids_split))] return cls(obs_mapping, par_list, transform_list) - def compute_transforms(self, system): - """ + 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. @@ -452,14 +479,53 @@ def compute_transforms(self, system): 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 `nuisance_transform = ~(obs_transform * ~ cm_transform)` if we have some existing `nuisance_transform` then it was already - included in `pm_data = nuisance_transform_old(pointing_model(data))` so the new nuisance_transform should chain them as - `nuisance_transform = nuisance_transform_new * nuisance_transform_old` giving us: - `pm_data = nuisance_transform(pointing_model(data)) = (nuisance_transform_new * nuisance_transform_old)(pointing_model(data)) = nuisance_transform_new(pm_data_old)` + 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 = [[] for _ in range(len(self.transform_list))] for meas_id, idx in self.obs_mapping.items(): @@ -597,9 +663,10 @@ class PointingModel: force_zero_roll: bool pad: bool = False + def apply_det( self, - meas, + meas: FocalPlane, tol: float = 2.42e-6, max_iter: int = 5, ) -> DetectorOffsets: @@ -609,54 +676,52 @@ def apply_det( 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. + `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. - If the pointing model contains no parameters, the input detector - offsets are returned unchanged. + 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. - When `force_zero_roll=True`, the encoder roll angle is ignored during - the correction and a zero-roll boresight solution is assumed. + 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 ---------- - det_off : DetectorOffsets - Detector offsets in the `xieta` coordinate system. These are the - detector positions from which the pointing correction will be removed. - det_enc : DetectorOffsets - Telescope encoder values in the `horizon` coordinate system. - These provide the boresight azimuth, elevation, and roll used to - evaluate the pointing model. - weights : Float[np.ndarray, "ndet"] - Detector weights. Only used to mask out nan of 0 weight detectors during - the inversion calculation. The output will still include all dets. - fake_gamma : bool - If True, ignore detector polarization angles and propagate only - detector position (`xi`, `eta`). If False, propagate the full - (`xi`, `eta`, `gamma`) coordinate set. + 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. + RMS convergence tolerance for the iterative distortion removal, + in radians. max_iter : int, default: 5 Maximum number of iterations for the distortion removal. Returns ------- - det_pm : DetectorOffsets - A copy of `det_off` with the pointing-model correction removed. + 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 ------ - ValueError - If `det_off` and `det_enc` do not contain the same number of - detectors. RuntimeError - If the iterative distortion removal does not converge. + If the iterative distortion removal does not converge within + `max_iter` iterations. """ to_ret = deepcopy(meas.data) if len(self.parameters) == 0: @@ -788,6 +853,9 @@ def load(cls, f: h5py.File, path: str, nuisance_params: NuisanceParams) -> Self: 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 ------- @@ -818,6 +886,17 @@ class Transform: 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"] @@ -919,34 +998,57 @@ def load(cls, f: h5py.File, path: str) -> Self: @dataclass class DetectorOffsets: """ - Class for storing detector offsets in either `xieta`, `horizon`, 'fp', or 'ot' coordinates. - `xi`, `eta`, `gamma`, `az`, `el`, and `roll` are included as properties for convenience. - They will raise a `ValueError` if called with the wrong coordsys set. + 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"] - The `x` axis of the detector offsets. - For `xieta` this is `xi`. - For `horizon` this is `az`. - The `y` axis of the detector offsets. - For `xieta` this is `eta`. - For `horizon` this is `el`. - The `z` axis of the detector offsets. - For `xieta` this is `gamma`. - For `horizon` this is `roll`. + 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"] - The detector id for each element in `xyz`. + Detector ID associated with each row of `xyz`. split : Shaped[np.ndarray, "ndet"] - A string used to split up detectors when plotting. - Nominally this should be to seperate the four detectors - behind the same feedhorn. + String used to group detectors when plotting. Nominally, this + separates the four detectors behind the same feedhorn. center : Optional[Float[np.ndarray, "3"]] - The center of the detector offsets. - Can be `None` if unknown. + Center of the detector offsets, or `None` if unknown. coordsys : str - The coordinate system that these are in. - Should be `xieta` or `horizon`. + 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"] @@ -963,6 +1065,8 @@ 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: @@ -1132,38 +1236,41 @@ def load(cls, f: h5py.File, path: str) -> Self: @dataclass class FocalPlane: """ - Container for a single focalplane measurement and its derived transforms. + 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 + 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 properties: + 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 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 + 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 (ie. UFM name). + 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. + 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 @@ -1171,6 +1278,9 @@ class FocalPlane: 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 @@ -1185,7 +1295,9 @@ class FocalPlane: If True, ignore gamma when fitting and applying transforms, effectively treating the focal plane as two-dimensional. pm_data : DetectorOffsets - Measured detector offsets after application of the pointing model. + 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 @@ -1194,18 +1306,35 @@ class FocalPlane: 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 coords. + 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 coords. + 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 @@ -1678,7 +1807,7 @@ class FocalPlaneCollection: 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, missing values should be filled with `nan`s. + 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 @@ -1698,9 +1827,11 @@ class FocalPlaneCollection: template : DetectorOffsets Reference detector layout used as the transform source. template_fp : DetectorOffsets - Reference detector layout used as the transform source in focal plane coords. + 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 coords. + 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. @@ -1717,6 +1848,7 @@ class FocalPlaneCollection: 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. @@ -1726,6 +1858,22 @@ class FocalPlaneCollection: 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`. """ name: str @@ -2040,10 +2188,6 @@ class OpticsTube: autofreeze : bool If True, cache dynamically computed quantities into their corresponding static fields. - allpad : bool - Flag indicating whether all focal-plane collections in the optics - tube are padded and should therefore be excluded from common-mode - calculations. cm_transform : Transform Common-mode transform derived from the transforms of all non-padded focal-plane collections. @@ -2051,8 +2195,11 @@ class OpticsTube: Copy of the optics-tube common-mode transform with a receiver common mode removed. This quantity is not computed dynamically and is updated only through `remove_rx`. + 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] @@ -2277,12 +2424,12 @@ class Receiver: autofreeze : bool If True, cache dynamically computed quantities into their corresponding static fields. - allpad : bool - Flag indicating whether all optics tube are padded - and should therefore be excluded from fitting. 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 @@ -2472,36 +2619,76 @@ def load( class PointingSystem: """ Collection of epoch-dependent pointing models and receiver data. - - A `PointingSystem` maintains a one-to-one correspondence between the - epochs in an `epochs.Era`, a set of `PointingModel` - instances, and a set of `Receiver` instances. The ordering of these - must be the same. - + + 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. + 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. + 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, ...] - The names of all pointing model parameters. - Names with parenthesis apply only to the epochs within the parenthesis. - Names without parenthesis apply to all other epochs. - parameter_map : tuple[Integer[np.ndarray, "?npar_mapped"], ...] - Mapping between parameters and what pointing models to apply them to. + 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 - A serialized calendar yaml string. + Serialized calendar YAML string used to reconstruct the observing + calendar and associated era. state_meta : dict[str, str] - String based metadata used for later forensics. + String-based metadata associated with the current system state. + Used to preserve provenance and support subsequent data forensics. parameters : Float[np.ndarray, "npar"] - The current values of the parameters. + (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 - The chisq of the current system. - This computes the chisq from the residuals for each `FocalPlaneCollection`, - not the individual `FocalPlane` measurements. + (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 @@ -2587,14 +2774,38 @@ def parameters(self) -> Float[np.ndarray, "npar"]: ) def update_parameters(self, new_pars: Float[np.ndarray, "npar"]): - npar = len(self.parameters) - for val, par, par_map in zip( - new_pars[:npar], self.parameter_names, self.parameter_map - ): + """ + 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:]) @@ -2626,6 +2837,8 @@ def residuals(self) -> Float[np.ndarray, "n_data"]: 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 @@ -2639,7 +2852,41 @@ def chisq(self) -> float: chisq += fp.chisq return chisq - def objective(self, params, nresid, cm_fac): + def objective( self, params: Float[np.ndarray, "npar"], nresid: int, cm_fac: float) -> 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. + + Returns + ------- + float + Total objective value, consisting of the focal-plane chi-squared + and the receiver common-mode regularization penalty. + """ self.update_parameters(params) self.set_thaw(True) try: @@ -2651,19 +2898,73 @@ def objective(self, params, nresid, cm_fac): except (RuntimeError, AssertionError): return 1e6 - def objective_resid(self, params, nresid, cm_fac): - print("obj") - self.update_parameters(params) - self.set_thaw(True) - 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 objective_resid( self, params: Float[np.ndarray, "npar"], nresid: int, cm_fac: float) -> 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. - def log_prob(self, params, nresid, cm_fac): + Returns + ------- + Float[np.ndarray, "nresid"] + Concatenated residual vector containing the focal-plane + residuals followed by the receiver common-mode shift and + rotation regularization terms. + """ + print("obj") + self.update_parameters(params) + self.set_thaw(True) + 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) -> 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. + + Returns + ------- + log_prob : float + Log probability of the supplied parameter values. + """ return -0.5 * self.objective(params, nresid, cm_fac) @overload @@ -2888,6 +3189,8 @@ def _group_epochs(dat, groups, desc, check_fields): 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}") @@ -2913,7 +3216,7 @@ def _group_epochs(dat, groups, desc, check_fields): pars["version"] = pm_ver pm.parameters = pars par_names = np.unique(par_names).tolist() - par_map = [np.arange(len(pms), dtype=int).tolist()] * len(par_names) + 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(): @@ -3049,7 +3352,7 @@ def load(cls, f: h5py.File, path: str) -> Self: if f"{path}/nuisance" in f: nuisance_params = NuisanceParams.load(f, f"{path}/nuisance") else: - nuisance_params = NuisanceParams({}, []) + 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) From c81fdd57a19d4c9ab4bd410c34c14fe7b8fa0bb2 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Thu, 19 Nov 2026 16:25:36 -0800 Subject: [PATCH 126/132] fix: lots of formatting and typos --- sotodlib/coords/fp_containers.py | 381 ++++++++++++------ sotodlib/coords/fp_plots.py | 91 ++++- .../site_pipeline/solve_static_pointing.py | 205 +++++++--- 3 files changed, 460 insertions(+), 217 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 1a59e3475..3cd98e252 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -248,7 +248,14 @@ def _transformed( 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): +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: @@ -266,13 +273,17 @@ def _get_aff(self: FocalPlane | FocalPlaneCollection, data_name: str, template_n 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] + 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, nuisance_params: NuisanceParams) -> tuple[np.ndarray, list[tuple[float, float]], np.ndarray]: + +def setup_fit_params( + system: PointingSystem, cfg: Namespace, nuisance_params: NuisanceParams +) -> tuple[np.ndarray, list[tuple[float, float]], np.ndarray]: """ Set up fit parameters, including nuisance parameters. @@ -280,7 +291,7 @@ def setup_fit_params( system: PointingSystem, cfg: Namespace, nuisance_params: N ---------- system : PointingSystem Pointing system containing the non-nuisance parameters. - cfg : Namespace + cfg : Namespace Configuration containing parameter initial values, bounds and static flags. nuisance_params : NuisanceParams Per-observation nuisance parameters. @@ -308,7 +319,7 @@ def setup_fit_params( system: PointingSystem, cfg: Namespace, nuisance_params: N 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 + 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 @@ -320,7 +331,10 @@ def setup_fit_params( system: PointingSystem, cfg: Namespace, nuisance_params: N for par_dict in nuisance_params.par_list: 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) + logger.warning( + "No equivalent non-nuisance parameter found for nuisance parameter %s", + name, + ) nuisance_values.append(value) nuisance_bounds.append((-np.inf, np.inf)) nuisance_scales.append(1.0) @@ -328,7 +342,12 @@ def setup_fit_params( system: PointingSystem, cfg: Namespace, nuisance_params: N idx = system.parameter_names.index(name) nuisance_values.append(value) lo, hi = bounds[idx] - nuisance_bounds.append((value - (value - lo)/cfg.nuisance_scale, value + (hi - value)/cfg.nuisance_scale)) + nuisance_bounds.append( + ( + value - (value - lo) / cfg.nuisance_scale, + value + (hi - value) / cfg.nuisance_scale, + ) + ) nuisance_scales.append(scales[idx]) # Append nuisance parameters @@ -375,6 +394,7 @@ def __get__(self, obj: Any, owner: type | None = None) -> T | "StaticOrCached[T] return res return getattr(obj, f"_{self.name}_dyn") + @dataclass class NuisanceParams: """ @@ -398,9 +418,10 @@ class NuisanceParams: (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] + + 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: @@ -410,8 +431,11 @@ def __getitem__(self, key) -> tuple[dict[str, float], Transform]: @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) - + 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. @@ -429,7 +453,9 @@ def update(self, params: Float[np.ndarray, "npar"]): idx += 1 @classmethod - def from_system(cls, system : PointingSystem, nuisance_pars: dict[str, float], threshold: float) -> NuisanceParams: + def from_system( + cls, system: PointingSystem, nuisance_pars: dict[str, float], threshold: float + ) -> NuisanceParams: """ Construct nuisance parameters and transforms from a pointing system. @@ -461,11 +487,13 @@ def from_system(cls, system : PointingSystem, nuisance_pars: dict[str, float], t 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) + 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}) + 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) @@ -532,7 +560,9 @@ def compute_transforms(self, system: PointingSystem): rev_mapping[idx] += [meas_id] 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) + rx_aff_inv, rx_sft_inv = mt.invert_transform( + rx.cm_transform.affine, rx.cm_transform.shift + ) affs = {} sfts = {} rx_ids = [] @@ -549,18 +579,29 @@ def compute_transforms(self, system: PointingSystem): 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!") + 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, False, fast=True) - n_aff, n_sft = mt.invert_transform(mt.compose_transforms(cm_aff, cm_shift, rx_aff_inv, rx_sft_inv)) + cm_aff, cm_shift = mt.get_common_mode( + [affs[mid] for mid in meas_ids], + [sfts[mid] for mid in meas_ids], + -2, + False, + fast=True, + ) + n_aff, n_sft = mt.invert_transform( + *mt.compose_transform(cm_aff, cm_shift, rx_aff_inv, rx_sft_inv) + ) trf_old = self.transform_list[i] - n_aff, n_sft = mt.compose_transforms(trf_old.affine, trf_old.shift, n_aff, n_sft) + n_aff, n_sft = mt.compose_transform( + trf_old.affine, trf_old.shift, n_aff, n_sft + ) self.transform_list[i] = Transform(n_aff, n_sft) 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. @@ -580,18 +621,34 @@ def save(self, f: h5py.File, path: str, overwrite: bool = True): 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) + 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)] + 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) + 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): @@ -616,8 +673,7 @@ def load(cls, f: h5py.File, path: str) -> Self: """ 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 + str(row["obs:obs_id"]): int(row["par_idx"]) for row in data } data = read_dataset(f, os.path.join(path, "par_list")).asarray() @@ -626,14 +682,18 @@ def load(cls, f: h5py.File, path: str) -> Self: 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))] + 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: """ @@ -663,7 +723,6 @@ class PointingModel: force_zero_roll: bool pad: bool = False - def apply_det( self, meas: FocalPlane, @@ -725,7 +784,7 @@ def apply_det( """ to_ret = deepcopy(meas.data) if len(self.parameters) == 0: - return to_ret + return to_ret # Apply nuisance params_use = deepcopy(self.parameters) @@ -735,13 +794,13 @@ def apply_det( # Start with the input detector coordinates if not np.any(meas.wmsk): - return to_ret + return to_ret estimate = meas.data_msk.xyz.copy() if meas.fake_gamma: estimate = estimate[:, :2] - fp_target = meas.data_msk + fp_target = meas.data_msk fp = meas.data_msk.fp - det_enc_msk = meas.enc_msk + 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 @@ -764,7 +823,12 @@ def apply_det( # Apply the pointing model 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) + 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)) @@ -811,8 +875,8 @@ def apply_det( estimate -= alpha * distortion raise RuntimeError( - f"Pointing-model inversion did not converge after {max_iter} iterations (error={err:.3e} rad)." - ) + 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): """ @@ -1002,8 +1066,8 @@ class DetectorOffsets: 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. + + Cached properties are cleared when `xyz` is assigned to. Attributes ---------- @@ -1145,7 +1209,9 @@ def q_enc(self): @cached_property def q_enc_zero_roll(self): - return quat.rotation_lonlat(-1 * self.az, self.el) * quat.euler(2, 0*self.roll) + return quat.rotation_lonlat(-1 * self.az, self.el) * quat.euler( + 2, 0 * self.roll + ) def save(self, f: h5py.File, path: str, overwrite: bool = True): """Save detector offsets to an HDF5 ResultSet. @@ -1335,6 +1401,7 @@ class FocalPlane: pm_data_msk : DetectorOffsets (Property) Pointing model corrected detector offsets selected by `wmsk`. """ + name: str meas_id: str data: DetectorOffsets @@ -1555,7 +1622,7 @@ def from_aman( # ~1 sigma cut weights[weights < 0.61] = 0 - valid_msk *= (weights == 0) + valid_msk *= weights == 0 return cls( name, @@ -1599,7 +1666,7 @@ def thaw(self, static: bool): static : bool What to set `self.static` to after thawing. """ - self.__dict__.pop("_pm_data_stat", None) + 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) @@ -1609,14 +1676,16 @@ def thaw(self, static: bool): @property def _pm_data_dyn(self) -> DetectorOffsets: - to_ret = self.pointing_model.apply_det( self) + 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) + return _get_aff( + self, "data_msk", "template_msk", "weights_msk", "_transform_stat", False + ) @property def _transformed_dyn(self) -> DetectorOffsets: @@ -1624,7 +1693,14 @@ def _transformed_dyn(self) -> DetectorOffsets: @property def _pm_transform_dyn(self) -> Transform: - return _get_aff(self, "pm_data_msk", "template_msk", "weights_msk", "_pm_transform_stat", False) + return _get_aff( + self, + "pm_data_msk", + "template_msk", + "weights_msk", + "_pm_transform_stat", + False, + ) @property def _pm_transformed_dyn(self) -> DetectorOffsets: @@ -1932,8 +2008,8 @@ def thaw(self, static: bool): 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("_weights_stat", None) + self.__dict__.pop("_data_stat", None) self.__dict__.pop("_transform_stat", None) self.__dict__.pop("_transformed_stat", None) self.static = static @@ -1948,7 +2024,7 @@ def nobs(self) -> int: @property def residuals(self) -> Float[np.ndarray, "ndet*nobs"]: - n_data = self.ndet*self.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: @@ -1961,9 +2037,11 @@ def residuals(self) -> Float[np.ndarray, "ndet*nobs"]: 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 + 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) + 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 @@ -1979,7 +2057,9 @@ def _data_dyn(self) -> DetectorOffsets: fmsk = np.zeros(len(to_ret.xyz), dtype=bool) for meas in self.focal_planes: fmsk += meas.wmsk - to_ret.xyz[meas.wmsk] += meas.pm_data.xyz[meas.wmsk] * meas.weights[meas.wmsk, None] + to_ret.xyz[meas.wmsk] += ( + meas.pm_data.xyz[meas.wmsk] * meas.weights[meas.wmsk, None] + ) to_ret.xyz[~fmsk] = np.nan to_ret.xyz[fmsk] /= self.weights[fmsk, None] to_ret.center = None @@ -1989,7 +2069,7 @@ def _data_dyn(self) -> DetectorOffsets: @property def _weights_dyn(self) -> Float[np.ndarray, "ndet"]: - weights_full = np.asarray( [fp.weights for fp in self.focal_planes]) + 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 @@ -2200,6 +2280,7 @@ class OpticsTube: 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] @@ -2262,7 +2343,9 @@ def _cm_transform_dyn(self) -> Transform: 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) + 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 @@ -2514,7 +2597,9 @@ def _cm_transform_dyn(self) -> Transform: 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) + 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 @@ -2619,30 +2704,30 @@ def load( 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 @@ -2774,35 +2859,39 @@ def parameters(self) -> Float[np.ndarray, "npar"]: ) 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. - """ + """ + 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)}") + 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): + 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 @@ -2817,7 +2906,7 @@ def n_data(self) -> int: for fp in ot.focal_planes: if fp.pad: continue - n += fp.ndet*fp.nobs + n += fp.ndet * fp.nobs return n @property @@ -2835,11 +2924,11 @@ def residuals(self) -> Float[np.ndarray, "n_data"]: if fp.pad: continue fpr = fp.residuals - resid[i:(i+len(fpr))] = fpr + 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 + raise RuntimeError(f"Residual size mismatch: expected {n_data}, got {i}") + return resid @property def chisq(self) -> float: @@ -2852,7 +2941,9 @@ def chisq(self) -> float: chisq += fp.chisq return chisq - def objective( self, params: Float[np.ndarray, "npar"], nresid: int, cm_fac: float) -> float: + def objective( + self, params: Float[np.ndarray, "npar"], nresid: int, cm_fac: float + ) -> float: """ Evaluate the total chi-squared objective function. @@ -2893,12 +2984,17 @@ def objective( self, params: Float[np.ndarray, "npar"], nresid: int, cm_fac: flo 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 + 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) -> Float[np.ndarray, "nresid_full"]: + def objective_resid( + self, params: Float[np.ndarray, "npar"], nresid: int, cm_fac: float + ) -> Float[np.ndarray, "nresid_full"]: """ Evaluate the residual vector used by least-squares optimization. @@ -2933,38 +3029,45 @@ def objective_resid( self, params: Float[np.ndarray, "npar"], nresid: int, cm_fa residuals followed by the receiver common-mode shift and rotation regularization terms. """ - print("obj") - self.update_parameters(params) - self.set_thaw(True) - 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) -> 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. - - Returns - ------- - log_prob : float - Log probability of the supplied parameter values. - """ + print('.', end='', flush=True) + self.update_parameters(params) + self.set_thaw(True) + 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 + ) -> 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. + + Returns + ------- + log_prob : float + Log probability of the supplied parameter values. + """ return -0.5 * self.objective(params, nresid, cm_fac) @overload @@ -3140,7 +3243,11 @@ def empty(cls, era: epochs.Era, cfg: Namespace, calender_str: str) -> Self: rxs = [] pms = [] for epoch in era.epochs: - pms += [PointingModel(epoch.name, {}, nuisance_params, cfg.force_zero_roll, False)] + pms += [ + PointingModel( + epoch.name, {}, nuisance_params, cfg.force_zero_roll, False + ) + ] ws_map = epoch.covers[0].data["ws_mapping"] ots = [] for ot, arrays in ws_map.items(): @@ -3190,7 +3297,9 @@ def _group_epochs(dat, groups, desc, check_fields): ] good = all(x == allf[0] for x in allf) if not good: - raise ValueError(f"Inconsistent {field} values in {desc} group {grp}") + 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}") @@ -3237,7 +3346,16 @@ def _group_epochs(dat, groups, desc, check_fields): 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, {}) + 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() @@ -3246,14 +3364,15 @@ def set_pm_to_defaults(self, cfg): 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)): + 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. diff --git a/sotodlib/coords/fp_plots.py b/sotodlib/coords/fp_plots.py index f7ecf2627..40bff75f8 100644 --- a/sotodlib/coords/fp_plots.py +++ b/sotodlib/coords/fp_plots.py @@ -257,7 +257,9 @@ def plot_ufm( ax1.legend() # Plot histogram of residuals. - dist = 3600 * np.linalg.norm( np.rad2deg( (transformed.xyz - data.xyz)[wmsk, :2]), axis=1) + 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) @@ -362,7 +364,9 @@ def plot_optics_tube( 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") + 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") @@ -661,33 +665,53 @@ def plot_displacements( dy = np.asarray(dy) * plot_scale nobs = len(dx) for name, color_data in colorbys: - fig, ax = plt.subplots( figsize=figsize, constrained_layout=True) + fig, ax = plt.subplots(figsize=figsize, constrained_layout=True) if name is None: - ax.quiver( x0, y0, dx, dy, angles="xy", scale_units="xy",) + 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") + 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}" + 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",) + 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]]], @@ -732,8 +756,12 @@ def plot_receiver_displacements( 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]) + 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) @@ -811,18 +839,25 @@ def plot_receiver_nuisance_displacements( dx = [] dy = [] for obs_id in obs_ids: - pars = nuisance_params[obs_id] + 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}") + 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}") + 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) + 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}" @@ -901,7 +936,10 @@ def plot_receiver_nuisance_transform_displacements( 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) + 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) @@ -921,6 +959,7 @@ def plot_receiver_nuisance_transform_displacements( figsize=figsize, ) + def plot_receiver_resid_vs_enc( receiver: Receiver, output_dir: str, @@ -1111,7 +1150,9 @@ def plot_receiver_residuals( 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) + 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: @@ -1128,12 +1169,22 @@ def plot_receiver_residuals( 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.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") + fig.savefig( + os.path.join(output_dir, f"{receiver.name}_residuals.png"), + dpi=dpi, + bbox_inches="tight", + ) plt.close(fig) diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index ca7fdeeca..1d9ae2713 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -90,7 +90,6 @@ class ErrCode(Enum): 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) @@ -136,7 +135,9 @@ def _report_fit(res, cfg, system, npar, x0, report_static, report_nuisance): 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): + 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) @@ -149,10 +150,23 @@ def _report_fit(res, cfg, system, npar, x0, report_static, report_nuisance): 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): + 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, **kwargs): + +def _fit_round( + system, + x0, + bounds, + scales, + nresid, + use_least_squares, + jac_sparsity, + cm_fac, + **kwargs, +): if use_least_squares: lb = np.array([b[0] for b in bounds]) ub = np.array([b[1] for b in bounds]) @@ -164,7 +178,7 @@ def _fit_round(system, x0, bounds, scales, nresid, use_least_squares, jac_sparsi jac_sparsity=jac_sparsity, args=(nresid, cm_fac), method="trf", - loss="linear", #"soft_l1", + loss="linear", # "soft_l1", tr_solver="lsmr", verbose=2, **kwargs, @@ -172,7 +186,10 @@ def _fit_round(system, x0, bounds, scales, nresid, use_least_squares, jac_sparsi return res, res.x - scaled_bounds = [(lo / scale, hi / scale) for (lo, hi), scale in zip(bounds, scales)] + 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) @@ -228,8 +245,13 @@ def _run_mcmc(system, nresid, cfg, bounds, scales, data_dir, plot_dir): 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) + 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): @@ -247,28 +269,30 @@ def log_prob(x): 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": [], - }, - } + "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] @@ -277,10 +301,7 @@ def metropolis_step(x, current_logp, mask, block_name): proposal = x.copy() - proposal[indices] += ( - rng.normal(size=len(indices)) - * proposal_scales[indices] - ) + proposal[indices] += rng.normal(size=len(indices)) * proposal_scales[indices] if np.any(proposal[indices] < lb[indices]) or np.any( proposal[indices] > ub[indices] @@ -319,11 +340,15 @@ def metropolis_step(x, current_logp, mask, block_name): # 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") + 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") + x, current_logp, accepted = metropolis_step( + x, current_logp, nuisance_free, "nuisance" + ) nuisance_accept += accepted samples[i] = x @@ -373,16 +398,19 @@ def metropolis_step(x, current_logp, mask, block_name): 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)) + 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.") + 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.") + raise RuntimeError("MCMC chain too short relative to autocorrelation time.") logger.info("Discarding %d burn-in iterations", discard) posterior_samples = samples[discard:] @@ -401,10 +429,7 @@ def metropolis_step(x, current_logp, mask, block_name): # Log physical parameter estimates. header = ( - f"{'Parameter Name':<35}" - f"{'Median':>18}" - f"{'Lower':>18}" - f"{'Upper':>18}" + f"{'Parameter Name':<35}" f"{'Median':>18}" f"{'Lower':>18}" f"{'Upper':>18}" ) logger.info("Physical parameter estimates:\n%s", header) @@ -421,10 +446,7 @@ def metropolis_step(x, current_logp, mask, block_name): 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}" + f"{name + suffix:<35}" f"{med:>18.8g}" f"{lo:>18.8g}" f"{hi:>18.8g}" ) # Log nuisance parameter estimates @@ -447,7 +469,11 @@ def metropolis_step(x, current_logp, mask, block_name): # 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] + 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, @@ -458,7 +484,9 @@ def metropolis_step(x, current_logp, mask, block_name): truths=median[plot_mask], ) - fig.savefig( os.path.join(plot_dir, "mcmc_corner.png"), dpi=200, bbox_inches="tight") + 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") @@ -470,8 +498,10 @@ def metropolis_step(x, current_logp, mask, block_name): 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("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 @@ -800,7 +830,7 @@ def _run_per_obs(open_jobs, done_jobs, jdb, ctx, system, cfg, plot_dir, outfile) len(done_jobs), ) open_jobs += [None] - pm_pars = deepcopy(system.parameters) # Cache a copy of the pars + 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: @@ -934,7 +964,9 @@ def _check_jobs(system, jdb, done_jobs, open_jobs): 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 + meas + for meas in fp.focal_planes + if f"{meas.meas_id}+{meas.name}" not in open_ids ] return open_jobs, done_jobs @@ -949,8 +981,12 @@ def _plot_fit(system, plot_dir, i, cfg): 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.nuisanse_plot, [(None, None)], pdir) - fpp.plot_receiver_nuisance_transform_displacements(rx, system.nuisance_params, [(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: @@ -1064,7 +1100,9 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): meas.pointing_model = system.pointing_models[pm_idx] # Setup nuisance - nuisance_params = fpc.NuisanceParams.from_system(system, cfg.nuisance_params, cfg.obs_time_thresh) + 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 @@ -1081,10 +1119,12 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): # Setup fit params params, bounds, scales = fpc.setup_fit_params(system, cfg, system.nuisance_params) system.update_parameters(params) - logger.info(params[:len(system.parameters)]) + 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)) + nresid_full = len( + system.objective_resid(system.parameters_full, nresid, cfg.cm_fac) + ) 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) @@ -1096,16 +1136,16 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): 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) + jac_n[idx, :, n : (n + ndet)] = meas.wmsk.astype(int) n += ndet - jac_sparsity[npar:,nresid:] = 1 + 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) - + # Fit for pointing model and focal planes for i in range(cfg.n_rounds): logger.info("Starting fit round %d", i + 1) @@ -1117,31 +1157,59 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): 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) + res, params_fit = _fit_round( + system, + x0, + bounds_use, + scales_use, + nresid, + cfg.least_squares, + None, + cfg.cm_fac, + ) 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) + # Now nuisance - if len(cfg.nuisance_params) > 0 and i+1 >= cfg.activate_nuisance: + if len(cfg.nuisance_params) > 0 and i + 1 >= cfg.activate_nuisance: logger.info("Fitting nuisance for round %d", i + 1) x0 = system.parameters_full.copy() bounds_fixed = [(val, val) for val in x0[:npar]] bounds_use = bounds_fixed + bounds[npar:] scales_use = scales - res, params_fit = _fit_round(system, x0, bounds_use, scales_use, nresid, cfg.least_squares, jac_sparsity, cfg.cm_fac, max_nfev=25, xtol=1e-6, ftol=1e-4) + res, params_fit = _fit_round( + system, + x0, + bounds_use, + scales_use, + nresid, + cfg.least_squares, + jac_sparsity, + cfg.cm_fac, + max_nfev=25, + xtol=1e-6, + ftol=1e-4, + ) system.update_parameters(params_fit) _report_fit(res, cfg, system, npar, x0, False, True) system.set_thaw(True) + system.set_freeze(True) + _plot_fit(system, plot_dir, f"{i + 1}_np", cfg) + system.set_thaw(True) + # Now do the fp nuisance transforms - if i+1 >= cfg.activate_nuisance_transforms: + if i + 1 >= cfg.activate_nuisance_transforms: system.nuisance_params.compute_transforms(system) # Freeze and plot system.set_freeze(True) - _plot_fit(system, plot_dir, "i + 1", cfg) - + _plot_fit(system, plot_dir, f"{i + 1}_fp", cfg) + # Cut outliers tot_cut = 0 for rx in system.receivers: @@ -1161,13 +1229,15 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): 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) + 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 + meas.wmsk = meas.wmsk.copy() # reset cache tot_cut += np.sum(mrmsk[wmsk]) if tot_cut == 0 and i >= cfg.activate_nuisance: @@ -1180,12 +1250,15 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): 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) + 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) + def main(): # Load arguments parser = ap.ArgumentParser() From 1774c89ab00a855cb9f9b8456c1793ecfe3204b9 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Thu, 19 Nov 2026 16:26:09 -0800 Subject: [PATCH 127/132] feat: start from results of last fit if desired --- sotodlib/coords/fp_containers.py | 38 ++++++++++++++++--- .../site_pipeline/solve_static_pointing.py | 6 ++- 2 files changed, 37 insertions(+), 7 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 3cd98e252..34b299e87 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -282,7 +282,7 @@ def _get_aff( def setup_fit_params( - system: PointingSystem, cfg: Namespace, nuisance_params: NuisanceParams + system: PointingSystem, cfg: Namespace, old_system: Optional[PointingSystem] ) -> tuple[np.ndarray, list[tuple[float, float]], np.ndarray]: """ Set up fit parameters, including nuisance parameters. @@ -293,8 +293,12 @@ def setup_fit_params( Pointing system containing the non-nuisance parameters. cfg : Namespace Configuration containing parameter initial values, bounds and static flags. - nuisance_params : NuisanceParams - Per-observation nuisance parameters. + 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 ------- @@ -305,6 +309,10 @@ def setup_fit_params( 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) @@ -323,12 +331,30 @@ def setup_fit_params( 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 nuisance_values = [] nuisance_bounds = [] nuisance_scales = [] - for par_dict in nuisance_params.par_list: + 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( @@ -355,6 +381,8 @@ def setup_fit_params( bounds.extend(nuisance_bounds) scales = np.concatenate([scales, np.asarray(nuisance_scales)]) + system.update_parameters(params) + return params, bounds, scales @@ -3029,7 +3057,7 @@ def objective_resid( residuals followed by the receiver common-mode shift and rotation regularization terms. """ - print('.', end='', flush=True) + print(".", end="", flush=True) self.update_parameters(params) self.set_thaw(True) try: diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index 1d9ae2713..21d26afd8 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -76,6 +76,9 @@ "least_squares": True, "cm_fac": 1e-3, "proposal_factor": 1e-2, + "pars_from_old": True, + "nuisance_from_old": True, + "nuisance_transform_from_old": False, } @@ -1117,8 +1120,7 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): # ) # Setup fit params - params, bounds, scales = fpc.setup_fit_params(system, cfg, system.nuisance_params) - system.update_parameters(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) From 926d06a80e056c0416ad121235652a057f25f2f2 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Tue, 24 Nov 2026 08:10:56 -0800 Subject: [PATCH 128/132] perf: switch to block nuisance opt, add pool option, add selective thaw --- sotodlib/coords/fp_containers.py | 184 ++++++++++++------ .../site_pipeline/solve_static_pointing.py | 109 +++++++---- 2 files changed, 195 insertions(+), 98 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 34b299e87..1c41912cf 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -15,6 +15,7 @@ from copy import deepcopy from dataclasses import dataclass, field from functools import cached_property, reduce +from concurrent.futures import Executor from typing import ( Any, ClassVar, @@ -340,9 +341,10 @@ def setup_fit_params( par[idx] = old_system.parameters[old_names.index(name)] # Setup nuisance fit parameters - nuisance_values = [] - nuisance_bounds = [] - nuisance_scales = [] + 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] @@ -361,20 +363,15 @@ def setup_fit_params( "No equivalent non-nuisance parameter found for nuisance parameter %s", name, ) - nuisance_values.append(value) - nuisance_bounds.append((-np.inf, np.inf)) - nuisance_scales.append(1.0) + 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.append(value) + nuisance_values[nidx] = value lo, hi = bounds[idx] - nuisance_bounds.append( - ( - value - (value - lo) / cfg.nuisance_scale, - value + (hi - value) / cfg.nuisance_scale, - ) - ) - nuisance_scales.append(scales[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)]) @@ -385,6 +382,8 @@ def setup_fit_params( return params, bounds, scales +def _get_pm(meas): + return meas._pm_data_dyn class StaticOrCached(Generic[T]): """ @@ -526,6 +525,13 @@ def from_system( 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 @@ -583,9 +589,7 @@ def compute_transforms(self, system: PointingSystem): 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 = [[] for _ in range(len(self.transform_list))] - for meas_id, idx in self.obs_mapping.items(): - rev_mapping[idx] += [meas_id] + rev_mapping = self.rev_mapping done_idx = set() for rx in system.receivers: rx_aff_inv, rx_sft_inv = mt.invert_transform( @@ -615,17 +619,17 @@ def compute_transforms(self, system: PointingSystem): [affs[mid] for mid in meas_ids], [sfts[mid] for mid in meas_ids], -2, - False, - fast=True, + True, + fast=False, #True, ) - n_aff, n_sft = mt.invert_transform( - *mt.compose_transform(cm_aff, cm_shift, rx_aff_inv, rx_sft_inv) + 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_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!") @@ -836,21 +840,25 @@ def apply_det( q_enc = det_enc_msk.q_enc err = np.inf - alpha = 1.0 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: - q_fp = quat.rotation_xieta(estimate[:, 0], estimate[:, 1], estimate[:, 2]) # type: ignore[arg-type] fp.gamma = estimate[:, 2] - - # Apply the pointing model - bs, fp_corrected = apply_pointing_model(None, params_use, ancil, fp) + 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) @@ -860,46 +868,40 @@ def apply_det( 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) + to_ret.xyz = mt.apply_transform( to_ret.xyz, ntrf.affine, ntrf.shift) return to_ret - - # Estimate and remove focalplane distortion + if meas.fake_gamma: - distortion = np.column_stack( - (fp_corrected.xi - fp.xi, fp_corrected.eta - fp.eta) - ) - resid = np.column_stack( - (fp_corrected.xi - fp_target.xi, fp_corrected.eta - fp_target.eta) - ) + 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: - distortion = np.column_stack( - ( - fp_corrected.xi - fp.xi, - fp_corrected.eta - fp.eta, - fp_corrected.gamma - fp.gamma, - ) - ) - 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.linalg.norm(resid, axis=1) ** 2)) + 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 + 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) + to_ret.xyz = mt.apply_transform( + to_ret.xyz, ntrf.affine, ntrf.shift + ) return to_ret - - # Update estimate of the undistorted fp + estimate -= alpha * distortion raise RuntimeError( @@ -2859,7 +2861,7 @@ def set_freeze(self, static: bool, optimizer: bool = False): rx.freeze(True) self.set_static(static) - def set_thaw(self, static: bool): + def set_thaw(self, static: bool, thaw_meas: Optional[list[str]] = None): """ Run thaw for all relevent childen. @@ -2872,11 +2874,53 @@ def set_thaw(self, static: bool): 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 + ] + + # 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( @@ -2970,7 +3014,7 @@ def chisq(self) -> float: return chisq def objective( - self, params: Float[np.ndarray, "npar"], nresid: int, cm_fac: float + self, params: Float[np.ndarray, "npar"], nresid: int, cm_fac: float, executor : Executor, thaw_meas = None ) -> float: """ Evaluate the total chi-squared objective function. @@ -2999,15 +3043,20 @@ def objective( 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 ------- - float + 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) + self.set_thaw(True, thaw_meas) + self.warm_pm_data(executor) try: chisq = self.chisq if np.isfinite(chisq): @@ -3021,7 +3070,7 @@ def objective( return 1e6 def objective_resid( - self, params: Float[np.ndarray, "npar"], nresid: int, cm_fac: float + 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. @@ -3049,17 +3098,21 @@ def objective_resid( 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 ------- - Float[np.ndarray, "nresid"] + 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) + self.set_thaw(True, thaw_meas) + self.warm_pm_data(executor) try: resid = [ self.residuals, @@ -3074,7 +3127,7 @@ def objective_resid( return np.full(nresid, 1e3) def log_prob( - self, params: Float[np.ndarray, "npar"], nresid: int, cm_fac: float + self, params: Float[np.ndarray, "npar"], nresid: int, cm_fac: float, executor : Executor ) -> float: """ Calculate the log probability of the current parameter values. @@ -3090,13 +3143,16 @@ def log_prob( 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) + return -0.5 * self.objective(params, nresid, cm_fac, executor, None) @overload def search( diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index 21d26afd8..dde0b4cf3 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -16,6 +16,7 @@ import corner import matplotlib.pyplot as plt from functools import partial +from concurrent.futures import Executor import emcee import git @@ -74,11 +75,13 @@ "activate_nuisance": 1, "activate_nuisance_transforms": 1, "least_squares": True, - "cm_fac": 1e-3, + "cm_fac": 1e-4, "proposal_factor": 1e-2, - "pars_from_old": True, - "nuisance_from_old": True, + "pars_from_old": False, + "nuisance_from_old": False, "nuisance_transform_from_old": False, + "pool_type": "thread", + "pool_size": 1, } @@ -168,6 +171,8 @@ def _fit_round( use_least_squares, jac_sparsity, cm_fac, + executor, + thaw_meas=None, **kwargs, ): if use_least_squares: @@ -179,7 +184,7 @@ def _fit_round( bounds=(lb, ub), x_scale=scales, jac_sparsity=jac_sparsity, - args=(nresid, cm_fac), + args=(nresid, cm_fac, executor, thaw_meas), method="trf", loss="linear", # "soft_l1", tr_solver="lsmr", @@ -194,12 +199,13 @@ def _fit_round( ] def scaled_objective(z): - return system.objective(z * scales, nresid, cm_fac) + return system.objective(z * scales, nresid, cm_fac, executor, thaw_meas) res = minimize( scaled_objective, x0 / scales, - method="L-BFGS-B", + # method="L-BFGS-B", + method="powell", bounds=scaled_bounds, **kwargs, ) @@ -207,7 +213,7 @@ def scaled_objective(z): return res, res.x * scales -def _run_mcmc(system, nresid, cfg, bounds, scales, data_dir, plot_dir): +def _run_mcmc(system, nresid, cfg, bounds, scales, data_dir, plot_dir, executor): system.set_static(False) system.set_thaw(True) @@ -261,7 +267,7 @@ 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) + value = system.log_prob(x, nresid, cfg.cm_fac, executor) except ( RuntimeError, AssertionError, @@ -1002,6 +1008,21 @@ def _plot_fit(system, plot_dir, i, cfg): 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 = ( @@ -1039,16 +1060,21 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): 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 - # ) + 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 + ) + import sys + sys.exit() # Mark pad epochs as pad logger.info("Padding epochs") @@ -1118,6 +1144,7 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): # 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) @@ -1125,7 +1152,7 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): npar = len(system.parameters) nresid = len(system.residuals) nresid_full = len( - system.objective_resid(system.parameters_full, nresid, cfg.cm_fac) + 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: @@ -1146,7 +1173,7 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): system.set_thaw(True) system.set_freeze(True) logger.info("Initial chisq is %.5f", system.chisq) - # _plot_fit(system, plot_dir, 0) + _plot_fit(system, plot_dir, 0, cfg) # Fit for pointing model and focal planes for i in range(cfg.n_rounds): @@ -1168,6 +1195,7 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): cfg.least_squares, None, cfg.cm_fac, + executor, ) system.update_parameters(params_fit) _report_fit(res, cfg, system, npar, x0, True, False) @@ -1178,26 +1206,34 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): # Now nuisance if len(cfg.nuisance_params) > 0 and i + 1 >= cfg.activate_nuisance: + rev_mapping = system.nuisance_params.rev_mapping logger.info("Fitting nuisance for round %d", i + 1) x0 = system.parameters_full.copy() - bounds_fixed = [(val, val) for val in x0[:npar]] - bounds_use = bounds_fixed + bounds[npar:] + nn = len(cfg.nuisance_params) + # _bounds_use = bounds_fixed + bounds[npar:] scales_use = scales - res, params_fit = _fit_round( - system, - x0, - bounds_use, - scales_use, - nresid, - cfg.least_squares, - jac_sparsity, - cfg.cm_fac, - max_nfev=25, - xtol=1e-6, - ftol=1e-4, - ) - system.update_parameters(params_fit) - _report_fit(res, cfg, system, npar, x0, False, True) + 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.set_thaw(True) system.set_freeze(True) @@ -1206,7 +1242,9 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): # Now do the fp nuisance transforms if i + 1 >= cfg.activate_nuisance_transforms: + logger.info("Fitting nuisance transforms for round %d", i + 1) system.nuisance_params.compute_transforms(system) + system.set_thaw(True) # Freeze and plot system.set_freeze(True) @@ -1258,7 +1296,10 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): # Run MCMC if we want if cfg.mcmc_steps > 0: - _ = _run_mcmc(system, nresid, cfg, bounds, scales, data_dir, plot_dir) + _ = _run_mcmc(system, nresid, cfg, bounds, scales, data_dir, plot_dir, executor) + + # Shutdown executor + executor.shutdown() def main(): From bffbc849e683889109dad0f3381c3a128f7b64d5 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Tue, 24 Nov 2026 09:06:45 -0800 Subject: [PATCH 129/132] fix: ensure that fake gamma fps dont compute a gamma form floating point errors --- sotodlib/coords/fp_containers.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 1c41912cf..9f635fe06 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -2085,13 +2085,18 @@ 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 - to_ret.xyz[meas.wmsk] += ( - meas.pm_data.xyz[meas.wmsk] * meas.weights[meas.wmsk, None] + 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] ) 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 From bc63c03eedc7f42f5236f19c6b29486684e1484b Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Tue, 24 Nov 2026 10:25:27 -0800 Subject: [PATCH 130/132] feat: automatically compute pad transforms and make receiver hierarchy bijective --- sotodlib/coords/fp_containers.py | 106 ++++++++++++++++--------------- 1 file changed, 54 insertions(+), 52 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 9f635fe06..280dbdeeb 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -1951,6 +1951,8 @@ class FocalPlaneCollection: 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`. @@ -1991,6 +1993,7 @@ class FocalPlaneCollection: autofreeze: bool pad: bool fake_gamma: bool + parent: OpticsTube data: ClassVar[StaticOrCached[DetectorOffsets]] = StaticOrCached("data") weights: ClassVar[StaticOrCached[Float[np.ndarray, "ndet"]]] = StaticOrCached( "weights" @@ -2112,6 +2115,8 @@ def _weights_dyn(self) -> Float[np.ndarray, "ndet"]: @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) @property @@ -2190,7 +2195,7 @@ def save( @classmethod def load( - cls, f: h5py.File, path: str, pointing_models: tuple[PointingModel, ...] + cls, f: h5py.File, path: str, pointing_models: tuple[PointingModel, ...], parent: OpticsTube, ) -> Self: """ Load a focal plane collection from an HDF5 file. @@ -2203,6 +2208,8 @@ def load( 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 ------- @@ -2233,6 +2240,7 @@ def load( 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: @@ -2303,13 +2311,13 @@ class OpticsTube: 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. This quantity is not computed dynamically and - is updated only through `remove_rx`. + 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 @@ -2321,9 +2329,11 @@ class OpticsTube: wafer_slots: list[str] static: bool autofreeze: bool + parent: Receiver cm_transform: ClassVar[StaticOrCached[Transform]] = StaticOrCached("cm_transform") - cm_transform_norx: Transform = field(init=False) + cm_transform_norx: ClassVar[StaticOrCached[Transform]] = StaticOrCached("cm_transform_norx") _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: @@ -2386,33 +2396,22 @@ def _cm_transform_dyn(self) -> Transform: self._cm_transform_stat = to_ret return to_ret - def remove_rx(self, rx_cm: Transform): - """ - Remove the receiver common-mode transform from the optics tube - common-mode transform. - - Unlike `cm_transform`, the receiver-corrected transform is not a - dynamic property and is updated only when this method is called. - - If `allpad=True`, no valid focal-plane collections are available for - this optics tube and `cm_transform_norx` is set to the identity - transform. - - Parameters - ---------- - rx_cm : Transform - Receiver common-mode transform to remove from the current - optics tube common mode. - """ + @property + def _cm_transform_norx_dyn(self) -> Transform: if self.allpad: - self.cm_transform_norx = Transform.identity() - aff, sft = mt.decompose_transform( - self.cm_transform.affine, - self.cm_transform.shift, - rx_cm.affine, - rx_cm.shift, - ) - self.cm_transform_norx = Transform(sft, aff) + 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, @@ -2449,12 +2448,12 @@ def save( 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" in self.__dict__: + if "_cm_transform_norx_stat" in self.__dict__: self.cm_transform_norx.save(f, f"{path}/cm_transform_norx") @classmethod def load( - cls, f: h5py.File, path: str, pointing_models: tuple[PointingModel, ...] + cls, f: h5py.File, path: str, pointing_models: tuple[PointingModel, ...], parent: Receiver ) -> Self: """ Load an optics tube from an HDF5 file. @@ -2473,29 +2472,31 @@ def load( OpticsTube The loaded optics tube. """ - 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 - ) - ) tube = cls( name=cast(str, group.attrs["name"]), - focal_planes=focal_planes, + 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, ) - group = cast(h5py.Group, f[path]) 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 = Transform.load(f, f"{path}/cm_transform_norx") + 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 @@ -2716,22 +2717,23 @@ def load( epoch = cast(str, group.attrs["epoch"]) static = cast(bool, group.attrs["static"]) autofreeze = cast(bool, group.attrs["autofreeze"]) - optics_tubes = [ - OpticsTube.load(f, f"{path}/{ot_name}", pointing_models) - for ot_name in group.keys() - if ot_name != "cm_transform" - ] - receiver = cls( name=name, epoch=epoch, - optics_tubes=optics_tubes, + 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 From c30b96ba99886b11886481d38dfdcafcd02dadbe Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Tue, 24 Nov 2026 13:11:09 -0800 Subject: [PATCH 131/132] feat: force mean zeor nuisance --- sotodlib/coords/fp_containers.py | 33 +++++++++++- .../site_pipeline/solve_static_pointing.py | 51 +++++++++++-------- 2 files changed, 62 insertions(+), 22 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 280dbdeeb..3d534c40a 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -479,6 +479,35 @@ def update(self, params: Float[np.ndarray, "npar"]): 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 @@ -486,7 +515,7 @@ def from_system( """ Construct nuisance parameters and transforms from a pointing system. - Observations are grouped into epochs using their measurement IDs + 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. @@ -494,7 +523,7 @@ def from_system( Parameters ---------- system : PointingSystem - Pointing system from which to collect observation IDs. + Pointing system from which to collect obs_ids. nuisance_pars : dict[str, float] Initial nuisance parameter values assigned to each epoch. threshold : float diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index dde0b4cf3..8362c0f1c 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -82,6 +82,7 @@ "nuisance_transform_from_old": False, "pool_type": "thread", "pool_size": 1, + "zero_nuisance": False, } @@ -1073,8 +1074,6 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): fpc.make_manifestdb( system, "template", os.path.join(data_dir, "template.sqlite"), outfile ) - import sys - sys.exit() # Mark pad epochs as pad logger.info("Padding epochs") @@ -1137,14 +1136,13 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): 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 - # ) - + 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) @@ -1179,10 +1177,20 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): for i in range(cfg.n_rounds): logger.info("Starting fit round %d", i + 1) system.set_thaw(True) - x0 = system.parameters_full.copy() + + 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] @@ -1200,17 +1208,19 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): 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) - # _bounds_use = bounds_fixed + bounds[npar:] 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)) @@ -1234,21 +1244,22 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): 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) - 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) - # Freeze and plot - 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 From bfa48247cb6cb29c2bce8b9b08fdc0cc4c5c2095 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Tue, 24 Nov 2026 13:11:36 -0800 Subject: [PATCH 132/132] fix: pep8 --- sotodlib/coords/fp_containers.py | 130 ++++++++++++------ sotodlib/coords/fp_plots.py | 2 +- .../site_pipeline/solve_static_pointing.py | 38 +++-- 3 files changed, 114 insertions(+), 56 deletions(-) diff --git a/sotodlib/coords/fp_containers.py b/sotodlib/coords/fp_containers.py index 3d534c40a..516e2f8bf 100644 --- a/sotodlib/coords/fp_containers.py +++ b/sotodlib/coords/fp_containers.py @@ -12,10 +12,10 @@ import logging import os 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 concurrent.futures import Executor from typing import ( Any, ClassVar, @@ -33,7 +33,7 @@ import megham.transform as mt import megham.utils as mu import numpy as np -from jaxtyping import Float, Integer, Shaped, Bool +from jaxtyping import Bool, Float, Integer, Shaped from scipy.cluster import vq from scipy.optimize import minimize from so3g.proj import quat @@ -370,7 +370,10 @@ def setup_fit_params( 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_bounds[nidx] = ( + value - (value - lo) / cfg.nuisance_scale, + value + (hi - value) / cfg.nuisance_scale, + ) nuisance_scales[nidx] = scales[idx] # Append nuisance parameters @@ -382,9 +385,11 @@ def setup_fit_params( return params, bounds, scales + def _get_pm(meas): return meas._pm_data_dyn + class StaticOrCached(Generic[T]): """ Wrapper that will get either: @@ -479,7 +484,6 @@ def update(self, params: Float[np.ndarray, "npar"]): par_dict[name] = float(params[idx]) idx += 1 - def mean_zero(self, system: PointingSystem): """ Make all nuisance parameter distributions mean zero by @@ -490,16 +494,23 @@ def mean_zero(self, system: PointingSystem): system : PointingSystem Pointing system whose pointing models will be modified. """ - pm_mapping = {pm.epoch : [] for pm in system.pointing_models} + 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]] + 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]))) + 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 @@ -649,9 +660,9 @@ def compute_transforms(self, system: PointingSystem): [sfts[mid] for mid in meas_ids], -2, True, - fast=False, #True, + fast=False, # True, ) - n_aff, n_sft = mt.invert_transform( # cm_aff, cm_shift) + 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] @@ -872,22 +883,22 @@ def apply_det( 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 + estimate[:, 0], estimate[:, 1], estimate[:, 2] # type: ignore ) - - bs, fp_corrected = apply_pointing_model( None, params_use, ancil, fp) + + 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) @@ -897,25 +908,36 @@ def apply_det( 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) + 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,)) + 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,)) - + 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 @@ -923,14 +945,12 @@ def apply_det( 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 - ) + to_ret.xyz = mt.apply_transform(to_ret.xyz, ntrf.affine, ntrf.shift) return to_ret - + estimate -= alpha * distortion raise RuntimeError( @@ -1980,7 +2000,7 @@ class FocalPlaneCollection: fake_gamma : bool If True, ignore gamma when fitting transforms, effectively treating the focal plane as two-dimensional. - parent : OpticsTube + parent : OpticsTube The OT that this FocalPlane belongs to. data : DetectorOffsets Weighted-average detector offsets constructed from the @@ -2123,7 +2143,7 @@ def _data_dyn(self) -> DetectorOffsets: 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] + meas.pm_data.xyz[meas.wmsk, :ndim] * meas.weights[meas.wmsk, None] ) to_ret.xyz[~fmsk] = np.nan to_ret.xyz[fmsk] /= self.weights[fmsk, None] @@ -2224,7 +2244,11 @@ def save( @classmethod def load( - cls, f: h5py.File, path: str, pointing_models: tuple[PointingModel, ...], parent: OpticsTube, + cls, + f: h5py.File, + path: str, + pointing_models: tuple[PointingModel, ...], + parent: OpticsTube, ) -> Self: """ Load a focal plane collection from an HDF5 file. @@ -2237,7 +2261,7 @@ def load( 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 + parent : OpticsTube The OT that this FocalPlane belongs to. Returns @@ -2360,7 +2384,9 @@ class OpticsTube: autofreeze: bool parent: Receiver cm_transform: ClassVar[StaticOrCached[Transform]] = StaticOrCached("cm_transform") - cm_transform_norx: ClassVar[StaticOrCached[Transform]] = StaticOrCached("cm_transform_norx") + cm_transform_norx: ClassVar[StaticOrCached[Transform]] = StaticOrCached( + "cm_transform_norx" + ) _cm_transform_stat: Transform = field(init=False) _cm_transform_norx_stat: Transform = field(init=False) @@ -2441,7 +2467,6 @@ def _cm_transform_norx_dyn(self) -> Transform: self._cm_transform_norx_stat = to_ret return to_ret - def save( self, f: h5py.File, @@ -2482,7 +2507,11 @@ def save( @classmethod def load( - cls, f: h5py.File, path: str, pointing_models: tuple[PointingModel, ...], parent: Receiver + cls, + f: h5py.File, + path: str, + pointing_models: tuple[PointingModel, ...], + parent: Receiver, ) -> Self: """ Load an optics tube from an HDF5 file. @@ -2514,7 +2543,9 @@ def load( 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") + 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: @@ -2917,8 +2948,7 @@ def set_thaw(self, static: bool, thaw_meas: Optional[list[str]] = None): ot.thaw(static) rx.thaw(static) - - def warm_pm_data(self, executor : Executor): + 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` @@ -2942,13 +2972,13 @@ def warm_pm_data(self, executor : Executor): for fp in ot.focal_planes for meas in fp.focal_planes ] - + # 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() @@ -3050,7 +3080,12 @@ def chisq(self) -> float: return chisq def objective( - self, params: Float[np.ndarray, "npar"], nresid: int, cm_fac: float, executor : Executor, thaw_meas = None + self, + params: Float[np.ndarray, "npar"], + nresid: int, + cm_fac: float, + executor: Executor, + thaw_meas=None, ) -> float: """ Evaluate the total chi-squared objective function. @@ -3106,7 +3141,12 @@ def objective( return 1e6 def objective_resid( - self, params: Float[np.ndarray, "npar"], nresid: int, cm_fac: float, executor : Executor, thaw_meas = None + 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. @@ -3163,7 +3203,11 @@ def objective_resid( return np.full(nresid, 1e3) def log_prob( - self, params: Float[np.ndarray, "npar"], nresid: int, cm_fac: float, executor : Executor + self, + params: Float[np.ndarray, "npar"], + nresid: int, + cm_fac: float, + executor: Executor, ) -> float: """ Calculate the log probability of the current parameter values. diff --git a/sotodlib/coords/fp_plots.py b/sotodlib/coords/fp_plots.py index 40bff75f8..42a969681 100644 --- a/sotodlib/coords/fp_plots.py +++ b/sotodlib/coords/fp_plots.py @@ -13,9 +13,9 @@ DetectorOffsets, FocalPlane, FocalPlaneCollection, + NuisanceParams, OpticsTube, Receiver, - NuisanceParams, ) diff --git a/sotodlib/site_pipeline/solve_static_pointing.py b/sotodlib/site_pipeline/solve_static_pointing.py index 8362c0f1c..e5030dccd 100644 --- a/sotodlib/site_pipeline/solve_static_pointing.py +++ b/sotodlib/site_pipeline/solve_static_pointing.py @@ -10,17 +10,17 @@ import hashlib import os import shutil -from enum import Enum -from typing import cast +from concurrent.futures import Executor from copy import deepcopy -import corner -import matplotlib.pyplot as plt +from enum import Enum from functools import partial -from concurrent.futures import Executor +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 @@ -28,8 +28,7 @@ import sotodlib.utils.jdb_utils as ju import sqlalchemy as sqy import yaml -from scipy.optimize import minimize -from scipy.optimize import least_squares +from scipy.optimize import least_squares, minimize from scipy.sparse import csr_array from sotodlib.coords import optics from sotodlib.core import Context, metadata @@ -1012,18 +1011,25 @@ def _plot_fit(system, plot_dir, i, cfg): 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] + 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 = ( @@ -1186,7 +1192,9 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): 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))] + 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) @@ -1223,10 +1231,16 @@ def run(config_path: str, overwrite: bool, backup: bool, timestamp: str): 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)) + 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:] + 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,