From be75bcfe3d6ccd189572cc3527e8264a20ebf11e Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Fri, 10 Apr 2026 07:56:28 -0700 Subject: [PATCH 01/20] feat: add support for ASO tubes --- sotodlib/coords/optics.py | 156 +++++++++++++++++++++++++++++++++----- 1 file changed, 136 insertions(+), 20 deletions(-) diff --git a/sotodlib/coords/optics.py b/sotodlib/coords/optics.py index 161e70919..31c19eaf3 100644 --- a/sotodlib/coords/optics.py +++ b/sotodlib/coords/optics.py @@ -4,6 +4,7 @@ LAT code adapted from code provided by Simon Dicker. """ + import logging from functools import lru_cache, partial import numpy as np @@ -47,6 +48,7 @@ SAT_R_SKY = (0.0, 0.0523597, 0.10471958, 0.15707946, 0.20943951, 0.26179764, 0.27925093, 0.30543087) # fmt: on + def _interp_func(x, y, spline): xr = np.atleast_1d(x).ravel() xa = np.argsort(xr) @@ -119,8 +121,8 @@ def get_gamma(pol_xi, pol_eta): xi = pol_xi.reshape((-1, 2)) eta = pol_eta.reshape((-1, 2)) - q0 = quat.rotation_xieta(xi[:,0], eta[:,0]) - q1 = quat.rotation_xieta(xi[:,1], eta[:,1]) + q0 = quat.rotation_xieta(xi[:, 0], eta[:, 0]) + q1 = quat.rotation_xieta(xi[:, 1], eta[:, 1]) dq = ~q0 * q1 d_xi, d_eta, _ = quat.decompose_xieta(dq) @@ -129,9 +131,10 @@ def get_gamma(pol_xi, pol_eta): @lru_cache(maxsize=None) -def load_ufm_to_fp_config(config_path): +def load_config(config_path): """ - Load and cache config file with the parameters to transform from UFM to focal_plane coordinates. + Load and cache config file with the parameters to transform from UFM to focal_plane coordinates + or focal_plane to OT coordinates. Arguments: @@ -164,7 +167,7 @@ def get_ufm_to_fp_pars(telescope_flavor, wafer_slot, config_path): transform_pars: Dict of transformation parameters that can be passed to ufm_to_fp. """ - config = load_ufm_to_fp_config(config_path) + config = load_config(config_path) return config[telescope_flavor][wafer_slot] @@ -228,6 +231,86 @@ def ufm_to_fp(aman, x=None, y=None, pol=None, theta=0, dx=0, dy=0): return x_fp, y_fp, pol_fp +@lru_cache(maxsize=None) +def get_fp_to_ot_pars(ot, config_path): + """ + Get (and cache) the parameters to transform from focal_plane to OT coordinates + for a specific slot of a given telescope's focal plane. + + Arguments: + + ot: The OT(ie. i6, st1, etc). + + config_path: Path to the yaml with the parameters. + + Returns: + + transform_pars: Dict of transformation parameters that can be passed to fp_to_ot. + """ + config = load_config(config_path) + return config[ot] + + +def fp_to_ot(aman, x=None, y=None, pol=None, phi=0, dx=0, dy=0): + """ + Transform from coords internal to focal plane to OT coordinates. + + Arguments: + + aman: AxisManager assumed to contain aman.focal_plane. + If provided outputs will be wrapped into aman.focal_plane. + + x: X position in focal_plane's internal coordinate system in mm. + If provided overrides the value from aman. + + y: Y position in focal_plane's internal coordinate system in mm. + If provided overrides the value from aman. + + pol: Polarization angle in focal_plane's internal coordinate system in deg. + If provided overrides the value from aman. + + phi: Internal rotation of the focal_plane in degrees. + + dx: X offset in mm. + + dy: Y offset in mm. + + Returns: + + x_fp: X position on focal plane. + + y_fp: Y position on focal plane. + + pol_fp: Pol angle on focal plane. + """ + if x is None: + x = aman.focal_plane.x_fp + if y is None: + y = aman.focal_plane.y_fp + if pol is None: + pol = aman.focal_plane.pol_fp + xy = np.column_stack((x, y, np.zeros_like(x))) + + rot = R.from_euler("z", phi, degrees=True) + xy = rot.apply(xy) + + x_ot = xy[:, 0] + dx + y_ot = xy[:, 1] + dy + pol_ot = pol + phi + + if aman is not None: + focal_plane = core.AxisManager(aman.dets) + focal_plane.wrap("x_ot", x_ot, [(0, focal_plane.dets)]) + focal_plane.wrap("y_ot", y_ot, [(0, focal_plane.dets)]) + focal_plane.wrap("pol_ot", pol_ot, [(0, focal_plane.dets)]) + if "focal_plane" in aman: + aman.focal_plane.merge(focal_plane) + else: + aman.wrap("focal_plane", focal_plane) + + return x_ot, y_ot, pol_ot + + def LAT_pix2sky(x, y, sec2el, sec2xel, array2secx, array2secy, rot=0, opt2cryo=30.0): """ Routine to map pixels from arrays to sky. @@ -238,7 +321,7 @@ def LAT_pix2sky(x, y, sec2el, sec2xel, array2secx, array2secy, rot=0, opt2cryo=3 y: Y position on focal plane (currently zemax coord). - sec2el: Function that maps positions on secondary to on sky elevation. + sec2el: Function that maps positions on secondary to on sky elevation. sex2xel: Function that maps positions on secondary to on sky cross-elevation. @@ -423,23 +506,27 @@ def LAT_focal_plane(aman, zemax_path, x=None, y=None, pol=None, roll=0, tube_slo If aman is provided then will be wrapped as aman.focal_plane.eta. """ if x is None: - x = aman.focal_plane.x_fp + x = aman.focal_plane.x_ot if y is None: - y = aman.focal_plane.y_fp + y = aman.focal_plane.y_ot if pol is None: - pol = aman.focal_plane.pol_fp + pol = aman.focal_plane.pol_ot sec2el, sec2xel = LAT_optics(zemax_path) array2secx, array2secy = LATR_optics(zemax_path, tube_slot) el, xel = LAT_pix2sky(x, y, sec2el, sec2xel, array2secx, array2secy, roll) - xi, eta, _ = quat.decompose_xieta(quat.euler(1, np.deg2rad(90)) * quat.rotation_lonlat(-xel, el)) + xi, eta, _ = quat.decompose_xieta( + quat.euler(1, np.deg2rad(90)) * quat.rotation_lonlat(-xel, el) + ) pol_x, pol_y = gen_pol_endpoints(x, y, pol) pol_el, pol_xel = LAT_pix2sky( pol_x, pol_y, sec2el, sec2xel, array2secx, array2secy, roll ) - pol_xi, pol_eta, _ = quat.decompose_xieta(quat.euler(1, np.deg2rad(90)) * quat.rotation_lonlat(-pol_xel, pol_el)) + pol_xi, pol_eta, _ = quat.decompose_xieta( + quat.euler(1, np.deg2rad(90)) * quat.rotation_lonlat(-pol_xel, pol_el) + ) gamma = get_gamma(pol_xi, pol_eta) if np.isscalar(xi): gamma = gamma[0] @@ -519,13 +606,13 @@ def SAT_focal_plane(aman, x=None, y=None, pol=None, roll=0, mapping_data=None): mapping_data = (tuple(val) for val in mapping_data) fp_to_sky = sat_to_sky(*mapping_data) - # Get things in polor coords - r_fp = (x**2 + y**2)**.5 + # Get things in polor coords + r_fp = (x**2 + y**2) ** 0.5 phi_fp = np.arctan2(y, x) # Now to the sky theta_iso = -fp_to_sky(r_fp) - phi_iso = np.pi/2 - phi_fp + phi_iso = np.pi / 2 - phi_fp # Flip about the origin for optics (180 deg rotation) phi_iso += np.pi @@ -539,10 +626,10 @@ def SAT_focal_plane(aman, x=None, y=None, pol=None, roll=0, mapping_data=None): # Lets do gamma as a set of endpoints pol_x, pol_y = gen_pol_endpoints(x, y, pol) - pol_r = (pol_x**2 + pol_y**2)**.5 + pol_r = (pol_x**2 + pol_y**2) ** 0.5 pol_phi = np.arctan2(pol_y, pol_x) pol_theta_iso = -fp_to_sky(pol_r) - pol_phi_iso = np.pi/2 - pol_phi + np.pi + pol_phi_iso = np.pi / 2 - pol_phi + np.pi _xi, _eta, _ = quat.decompose_xieta(quat.rotation_iso(pol_theta_iso, pol_phi_iso)) pol_xi = _xi * np.cos(np.deg2rad(roll)) - _eta * np.sin(np.deg2rad(roll)) pol_eta = _eta * np.cos(np.deg2rad(roll)) + _xi * np.sin(np.deg2rad(roll)) @@ -574,6 +661,8 @@ def get_focal_plane( wafer_slot="ws0", config_path=None, ufm_to_fp_pars=None, + ot_config_path=None, + fp_to_ot_pars=None, zemax_path=None, mapping_data=None, return_fp=False, @@ -608,9 +697,14 @@ def get_focal_plane( config_path: Path to the ufm_to_fp config file. - ufm_to_fp_pars: Loaded ufm_to_fp_parsm to focalplane params. + ufm_to_fp_pars: Loaded ufm_to_fp_pars to focalplane params. If provided config_path is is ignored. + ot_config_path: Path to the optics_tubes config file. + + fp_to_ot_pars: Loaded optics_tubes params. + If provided ot_config_path is is ignored. + zemax_path: Path to the data file from Zemax. Only used by the LAT. @@ -639,6 +733,15 @@ def get_focal_plane( pol_fp: Pol angle on focal plane. Only returned if return_fp is True. + + x_ot: X position in the OT. + Only returned if return_fp is True. + + y_ot: Y position in the OT. + Only returned if return_fp is True. + + pol_ot: Pol angle in the OT. + Only returned if return_fp is True. """ if aman is not None and "obs_info" in aman: if telescope_flavor is None: @@ -654,19 +757,32 @@ def get_focal_plane( if ufm_to_fp_pars is None: ufm_to_fp_pars = get_ufm_to_fp_pars(telescope_flavor, wafer_slot, config_path) x_fp, y_fp, pol_fp = ufm_to_fp(aman, x=x, y=y, pol=pol, **ufm_to_fp_pars) + if fp_to_ot_pars is None: + fp_to_ot_pars = get_fp_to_ot_pars(tube_slot, ot_config_path) + x_ot, y_ot, pol_ot = fp_to_ot(aman, x=x_fp, y=y_fp, pol=pol_fp, **fp_to_ot_pars) + # We dont want to use the shift of the OT when computing on sky locations + x_use, y_use, pol_use = fp_to_ot( + aman, x=x_fp, y=y_fp, pol=pol_fp, phi=fp_to_ot_pars["phi"] + ) if telescope_flavor == "LAT": if zemax_path is None: raise ValueError("Must provide zemax_path for LAT") xi, eta, gamma = LAT_focal_plane( - aman, zemax_path, x=x_fp, y=y_fp, pol=pol_fp, roll=roll, tube_slot=tube_slot + aman, + zemax_path, + x=x_use, + y=y_use, + pol=pol_use, + roll=roll, + tube_slot=tube_slot, ) else: xi, eta, gamma = SAT_focal_plane( - aman, x=x_fp, y=y_fp, pol=pol_fp, roll=roll, mapping_data=mapping_data + aman, x=x_use, y=y_use, pol=pol_use, roll=roll, mapping_data=mapping_data ) if return_fp: - return xi, eta, gamma, x_fp, y_fp, pol_fp + return xi, eta, gamma, x_fp, y_fp, pol_fp, x_ot, y_ot, pol_ot return xi, eta, gamma From 3edbc66ed055c3a8e31635a5e64bd3085dd67f43 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Fri, 10 Apr 2026 07:59:31 -0700 Subject: [PATCH 02/20] fix: supple ot path to gen_template --- sotodlib/site_pipeline/finalize_focal_plane.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sotodlib/site_pipeline/finalize_focal_plane.py b/sotodlib/site_pipeline/finalize_focal_plane.py index 02a31faf5..c45f262a9 100644 --- a/sotodlib/site_pipeline/finalize_focal_plane.py +++ b/sotodlib/site_pipeline/finalize_focal_plane.py @@ -387,6 +387,7 @@ def _load_rset(config): 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") + ot_config_path = os.path.join(config_dir, "shared/focalplane/optics_tubes.yaml") zemax_path = config.get("zemax_path", None) pointing_cfg = { @@ -394,6 +395,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, "zemax_path": zemax_path, "return_fp": False, } From e493b1b1937179479fe3240e8fc2c158bed1a042 Mon Sep 17 00:00:00 2001 From: Saianeesh Keshav Haridas Date: Fri, 10 Apr 2026 08:07:38 -0700 Subject: [PATCH 03/20] fix: update test --- tests/test_coords.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_coords.py b/tests/test_coords.py index e5e1ab032..d917be7fe 100644 --- a/tests/test_coords.py +++ b/tests/test_coords.py @@ -258,7 +258,7 @@ def test_sat_fp(self): y = x.copy() pol = x.copy() - xi, eta, gamma = co.get_focal_plane(None, x, y, pol, 0, "SAT", "ws1", ufm_to_fp_pars={'theta': 60.0, 'dx': 0.0, 'dy': 128.5}) + xi, eta, gamma = co.get_focal_plane(None, x, y, pol, 0, "SAT", "ws1", ufm_to_fp_pars={'theta': 60.0, 'dx': 0.0, 'dy': 128.5}, fp_to_ot_pars={'phi': 0.0, 'dx': 0.0, 'dy': 0}) self.assertTrue(np.all(np.isclose(xi, np.array([-6.4406e-02, 0, 5.58489e-02])))) self.assertTrue(np.all(np.isclose(eta, np.array([0.01425728, -0.2207397, -0.404499])))) self.assertTrue(np.all(np.isclose(gamma, np.array([5.409, 3.6846, 1.8156])))) From 410671a2f907a3f3083b9d4a92e597c35699f00e Mon Sep 17 00:00:00 2001 From: Michael McCrackan Date: Fri, 1 May 2026 13:13:02 -0700 Subject: [PATCH 04/20] add tube orientation --- sotodlib/coords/det_match.py | 21 +++++++++++++++------ sotodlib/coords/det_match_solutions.py | 5 +++++ 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/sotodlib/coords/det_match.py b/sotodlib/coords/det_match.py index ea9bc7806..0b4e2b73d 100644 --- a/sotodlib/coords/det_match.py +++ b/sotodlib/coords/det_match.py @@ -80,6 +80,7 @@ class PointingConfig: Either the tube name as a string or the tube number as an int. """ fp_file: str + ot_file: str wafer_slot: str tel_type: str zemax_path: Optional[str] = None @@ -109,17 +110,25 @@ def __post_init__(self): self.theta = np.deg2rad(self.fp_pars['theta']) def get_pointing(self, x, y, pol=0): - xp = x * np.cos(self.theta) - y * np.sin(self.theta) + self.dx - yp = x * np.sin(self.theta) + y * np.cos(self.theta) + self.dy - if self.tel_type.upper() == 'SAT': + xp = x * np.cos(self.theta) - y * np.sin(self.theta) + self.dx + yp = x * np.sin(self.theta) + y * np.cos(self.theta) + self.dy xi, eta, gamma = optics.SAT_focal_plane( None, x=xp, y=yp, pol=pol, roll=self.roll ) elif self.tel_type.upper() == 'LAT': - xi, eta, gamma = optics.LAT_focal_plane( - None, self.zemax_path, x=xp, y=yp, pol=pol, - roll=self.roll, tube_slot=self.tube_slot + xi, eta, gamma = optics.get_focal_plane( + None, + x=x, + y=y, + pol=pol, + roll=self.roll, + telescope_flavor="LAT", + tube_slot=self.tube_slot, + wafer_slot=self.wafer_slot, + ufm_to_fp_pars=self.fp_pars, + ot_config_path=self.ot_file, + zemax_path=self.zemax_path, ) return xi, eta, gamma diff --git a/sotodlib/coords/det_match_solutions.py b/sotodlib/coords/det_match_solutions.py index 2399e04f4..f140d28a1 100644 --- a/sotodlib/coords/det_match_solutions.py +++ b/sotodlib/coords/det_match_solutions.py @@ -109,6 +109,7 @@ class SolutionsCfg: initial_pointing_offset: Tuple[float, float] = (0, 0) ufm_to_fp_path: Optional[str] = None + fp_to_ot_path: Optional[str] = None freq_correct_by_muxband: bool = True ctx: Context = field(init=False) @@ -146,6 +147,10 @@ def __post_init__(self): self.ufm_to_fp_path = os.path.join( self.site_pipeline_cfg_dir, "shared/focalplane/ufm_to_fp.yaml" ) + if self.fp_to_ot_path is None: + self.fp_to_ot_path = os.path.join( + self.site_pipeline_cfg_dir, "shared/focalplane/optics_tubes.yaml" + ) @dataclass From 8eaf7cc798a091a4d1b4c69d9572a91b15f1bb51 Mon Sep 17 00:00:00 2001 From: Michael McCrackan Date: Fri, 1 May 2026 13:33:29 -0700 Subject: [PATCH 05/20] make sat and lat consistent --- sotodlib/coords/det_match.py | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/sotodlib/coords/det_match.py b/sotodlib/coords/det_match.py index 0b4e2b73d..23a70f3ff 100644 --- a/sotodlib/coords/det_match.py +++ b/sotodlib/coords/det_match.py @@ -105,16 +105,23 @@ def __post_init__(self): self.fp_pars = optics.get_ufm_to_fp_pars( self.tel_type, self.wafer_slot, self.fp_file ) - self.dx = self.fp_pars['dx'] - self.dy = self.fp_pars['dy'] - self.theta = np.deg2rad(self.fp_pars['theta']) + + self.ot_pars = optics.get_fp_to_ot_pars( + self.tube_slot, self.ot_file) def get_pointing(self, x, y, pol=0): if self.tel_type.upper() == 'SAT': - xp = x * np.cos(self.theta) - y * np.sin(self.theta) + self.dx - yp = x * np.sin(self.theta) + y * np.cos(self.theta) + self.dy - xi, eta, gamma = optics.SAT_focal_plane( - None, x=xp, y=yp, pol=pol, roll=self.roll + xi, eta, gamma = optics.get_focal_plane( + None, + x=x, + y=y, + pol=pol, + roll=self.roll, + telescope_flavor="SAT", + tube_slot=self.tube_slot, + wafer_slot=self.wafer_slot, + ufm_to_fp_pars=self.fp_pars, + fp_to_ot_pars=self.ot_pars, ) elif self.tel_type.upper() == 'LAT': xi, eta, gamma = optics.get_focal_plane( @@ -127,7 +134,7 @@ def get_pointing(self, x, y, pol=0): tube_slot=self.tube_slot, wafer_slot=self.wafer_slot, ufm_to_fp_pars=self.fp_pars, - ot_config_path=self.ot_file, + fp_to_ot_pars=self.ot_pars, zemax_path=self.zemax_path, ) return xi, eta, gamma From ea72c58e1a17259afabc79a0f45cba485a43c412 Mon Sep 17 00:00:00 2001 From: Michael McCrackan Date: Sat, 2 May 2026 10:32:20 -0700 Subject: [PATCH 06/20] LF support --- sotodlib/coords/det_match.py | 51 +++++++--- sotodlib/coords/det_match_solutions.py | 110 ++++++++++++++++----- sotodlib/site_pipeline/update_det_match.py | 7 +- 3 files changed, 131 insertions(+), 37 deletions(-) diff --git a/sotodlib/coords/det_match.py b/sotodlib/coords/det_match.py index 23a70f3ff..aefa7ce2f 100644 --- a/sotodlib/coords/det_match.py +++ b/sotodlib/coords/det_match.py @@ -67,22 +67,22 @@ class PointingConfig: Path to focal-plane file that is used by the optics module. wafer_slot: str Wafer slot of the UFM. For example: "ws0" - tel_type: str - Tel type for the optics model. Either "SAT" or "LAT" + platform: str + Which platform to use for the optics model. zemax_path: str - If running for a "LAT" tel_type, the path to the zemax file must be specified. + If running for the lat platform, the path to the zemax file must be specified. roll: float Rotation about the line of sight. For the LAT this is elev - 60 - corotator. For the SAT this is -1*boresight. tube_slot: str/int - If running for a "LAT" tel_type, the tube slot must be specified. + If running for the lat platform, the tube slot must be specified. Either the tube name as a string or the tube number as an int. """ fp_file: str ot_file: str wafer_slot: str - tel_type: str + platform: str zemax_path: Optional[str] = None roll: Optional[float] = 0 tube_slot: Optional[Union[str, int]] = None @@ -93,6 +93,10 @@ class PointingConfig: fp_pars: dict = field(init=False) def __post_init__(self): + if self.platform.lower() in ["satp1", "satp2", "satp3"]: + self.tel_type = "SAT" + elif self.platform.lower() == "lat": + self.tel_type = "LAT" if self.tel_type == 'LAT': if self.zemax_path is None: raise ValueError("zemax path must be set for 'LAT' tel_type") @@ -301,7 +305,8 @@ def as_array(self): return np.array(data, dtype=dtype) @classmethod - def from_aman(cls, aman, stream_id, det_cal=None, name=None, pointing: Optional[AxisManager]=None): + def from_aman(cls, aman, stream_id, det_cal=None, name=None, pointing: Optional[AxisManager]=None, + ignore_north_south=False): """ Load a resonator set from a Context object based on an obs_id @@ -331,7 +336,10 @@ def from_aman(cls, aman, stream_id, det_cal=None, name=None, pointing: Optional[ resonators = [] for i, ri in enumerate(np.where(m)[0]): band, channel = aman.det_info.smurf.band[ri], aman.det_info.smurf.channel[ri] - is_north = north_is_highband ^ (band < 4) + if not ignore_north_south: + is_north = north_is_highband ^ (band < 4) + else: + is_north = 1 readout_id = aman.det_info.readout_id[ri] bg = det_cal.bg[ri] res_freq=aman.det_info.smurf.frequency[ri] @@ -352,7 +360,7 @@ def from_aman(cls, aman, stream_id, det_cal=None, name=None, pointing: Optional[ @classmethod def from_tunefile(cls, tunefile, name=None, north_is_highband=True, - resfit_file=None, bgmap_file=None): + resfit_file=None, bgmap_file=None, ignore_north_south=False): """ Creates an instance based on a smurf-tune file. If a resfit or bgmap file is included, that data will be added to the Resonance objects as @@ -379,7 +387,10 @@ def from_tunefile(cls, tunefile, name=None, north_is_highband=True, continue for res_idx, d in _v['resonances'].items(): - is_north = north_is_highband ^ (band < 4) + if not ignore_north_south: + is_north = north_is_highband ^ (band < 4) + else: + is_north = 1 res = Resonator( idx=idx, smurf_res_idx=res_idx, res_freq=d['freq'], smurf_band=band, is_north=is_north @@ -401,7 +412,8 @@ def from_tunefile(cls, tunefile, name=None, north_is_highband=True, @classmethod def from_wafer_info_file(cls, wafer_info_file, array_name, name=None, - pt_cfg: Optional[PointingConfig]=None): + pt_cfg: Optional[PointingConfig]=None, + ignore_north_south=False): """ Initialize a ResSet from a wafer info file. This is a file that contains detector design information. @@ -431,7 +443,11 @@ def from_wafer_info_file(cls, wafer_info_file, array_name, name=None, resonators = [] idx = 0 for r in wafer_array: - is_north = r['dets:wafer.coax'] == b'N' + # always true for LF + if not ignore_north_south: + is_north = r['dets:wafer.coax'] == b'N' + else: + is_north = 1 kwargs = dict( idx=idx, det_id=r['dets:det_id'].decode(), @@ -473,7 +489,8 @@ def from_wafer_info_file(cls, wafer_info_file, array_name, name=None, @classmethod def from_solutions(cls, sol_file, north_is_highband=True, name=None, - fp_pars=None, platform='SAT', zemax_path=None): + fp_pars=None, platform='SAT', zemax_path=None, + ignore_north_south=False): """ Creates an instance from an input-solution file. This will include both design data, along with smurf-band and smurf-channel info. Resonance frequencies used here are the VNA @@ -521,7 +538,10 @@ def _int(val, null_val=None): continue # is_north = north_is_highband ^ (_int(d['smurf_band']) < 4) # is_north = d['is_north'].lower().strip() == 'true' - is_north = _int(d['bias_line']) < 6 + if not ignore_north_south: + is_north = _int(d['bias_line']) < 6 + else: + is_north = 1 is_optical = (d['is_optical'].lower() == 'true') kwargs = dict( @@ -761,7 +781,7 @@ def _get_biadjacency_matrix(self) -> np.ndarray: mat = np.zeros((len(self.src), len(self.dst)), dtype=float) - # N/S mismatch + # N/S mismatch (all N for LF) m = src_arr['is_north'][:, None] != dst_arr['is_north'][None, :] mat[m] = np.inf @@ -954,7 +974,10 @@ def get_stats(self) -> MatchingStats: stats.unmatched_src = np.sum(~src_arr['matched'].astype(bool)) stats.unmatched_dst = np.sum(~dst_arr['matched'].astype(bool)) + # print(stats.unmatched_src, stats.unmatched_dst) + has_pt = ~np.isnan(src_arr['xi']) + # print(has_pt) stats.unmatched_src_with_pointing = np.sum( (~src_arr['matched'].astype(bool)) & has_pt ) diff --git a/sotodlib/coords/det_match_solutions.py b/sotodlib/coords/det_match_solutions.py index f140d28a1..305d54b06 100644 --- a/sotodlib/coords/det_match_solutions.py +++ b/sotodlib/coords/det_match_solutions.py @@ -32,14 +32,14 @@ class SolutionsCfg: Directory where results should be stored. wafer_info_path: str Path to the wafer_info h5 file. - tel_type: str - Tel type for the optics model. Either "SAT" or "LAT" + platform: str + Telescope platform. base_obs_id: str Obs_id to use as a base for matching when merging multiple pointing obs_ids for a wafer. Will default to the pointing obs_id with the greatest number of detectors above the min_R2 threshold. zemax_path: str - If running for a "LAT" tel_type, the path to the zemax file must be specified. + If running for the LAT, the path to the zemax file must be specified. apply_roll: bool Whether or not to apply the obs_id roll angle. Some pointing sets may already be corrected for roll angle. @@ -91,7 +91,7 @@ class SolutionsCfg: pointing_results_dir: str results_dir: str wafer_info_path: str - tel_type: str + platform: str base_obs_id: Optional[str] = None zemax_path: Optional[str] = None apply_roll: bool = True @@ -110,6 +110,7 @@ class SolutionsCfg: initial_pointing_offset: Tuple[float, float] = (0, 0) ufm_to_fp_path: Optional[str] = None fp_to_ot_path: Optional[str] = None + imprinter_path: Optional[str] = None freq_correct_by_muxband: bool = True ctx: Context = field(init=False) @@ -151,6 +152,10 @@ def __post_init__(self): self.fp_to_ot_path = os.path.join( self.site_pipeline_cfg_dir, "shared/focalplane/optics_tubes.yaml" ) + if self.imprinter_path is None: + self.imprinter_path = os.path.join( + self.site_pipeline_cfg_dir, f"{self.platform}/imprinter.yaml" + ) @dataclass @@ -235,7 +240,7 @@ def pointing_preprocess(cfg: SolutionsCfg, pinfo: PointingInfo): return meta -def merge_pointing_info(cfg: SolutionsCfg, pinfos: List[PointingInfo], base_idx=0): +def merge_pointing_info(cfg: SolutionsCfg, pinfos: List[PointingInfo], base_idx=0, ignore_north_south=False): """ Combine all pointing measurements into a single resonator set, with the median pointing info from all. This requires a base_idx to be specified, @@ -251,7 +256,13 @@ def merge_pointing_info(cfg: SolutionsCfg, pinfos: List[PointingInfo], base_idx= meta = pinfos[base_idx].meta stream_id = meta.det_info.stream_id[0] wafer_slot = meta.det_info.wafer_slot[0] - base_resset = dm.ResSet.from_aman(meta, stream_id=stream_id, pointing=meta.tod_pointing) + + base_resset = dm.ResSet.from_aman( + meta, + stream_id=stream_id, + pointing=meta.tod_pointing, + ignore_north_south=ignore_north_south + ) pointing_map = { r.idx: [(r.xi, r.eta)] for r in base_resset @@ -259,14 +270,19 @@ def merge_pointing_info(cfg: SolutionsCfg, pinfos: List[PointingInfo], base_idx= match_pars = dm.MatchParams( freq_width=cfg.match_pars["pointing"]["freq_width"], - dist_width=np.deg2rad(cfg.match_pars["pointing"]["dist_width"]) + dist_width=np.deg2rad(cfg.match_pars["pointing"]["dist_width"]), ) for i in range(len(pinfos)): if i == base_idx: continue meta = pinfos[i].meta - src = dm.ResSet.from_aman(meta, stream_id=stream_id, pointing=meta.tod_pointing) + src = dm.ResSet.from_aman( + meta, + stream_id=stream_id, + pointing=meta.tod_pointing, + ignore_north_south=ignore_north_south + ) dst = base_resset match = dm.Match(src, dst, match_pars=match_pars) for rsrc, rdst in match.get_match_iter(include_unmatched=False): @@ -395,7 +411,8 @@ def match_wafer( cfg: SolutionsCfg, am: AxisManager, stream_id: str, - meas_rset: Optional[dm.ResSet] + meas_rset: Optional[dm.ResSet], + ignore_north_south: bool = False ) -> MatchSolution: """ Create a match solution for a given wafer slot. @@ -414,19 +431,58 @@ def match_wafer( m = am.det_info.stream_id == stream_id wafer_slot = am.det_info.wafer_slot[m][0] + tube_slot = am.obs_info.tube_slot if meas_rset is None: - src = dm.ResSet.from_aman(am, stream_id, pointing=am[cfg.pointing_field]) + src = dm.ResSet.from_aman( + am, + stream_id, + pointing=am[cfg.pointing_field], + ignore_north_south=ignore_north_south + ) else: src = meas_rset - pt_cfg = dm.PointingConfig( - fp_file=cfg.ufm_to_fp_path, wafer_slot=wafer_slot, tel_type=cfg.tel_type, - zemax_path=cfg.zemax_path, - roll=np.deg2rad(am.obs_info.roll_center) if cfg.apply_roll else 0.0, - tube_slot = am.obs_info.tube_slot - ) - dst = dm.ResSet.from_wafer_info_file(cfg.wafer_info_path, stream_id, pt_cfg=pt_cfg) + if ignore_north_south: + wafer_slot = [] + wafer_dict = {} + + # get wafer and wafer_slot entry from imprinter + with open(cfg.imprinter_path, "r") as f: + imprinter = yaml.safe_load(f) + + for k, v in imprinter['tel_tubes'].items(): + if v['tube_slot'] == tube_slot: + for ws in v['wafer_slots']: + if 'wafer' in ws.keys(): + wafer_dict[ws['wafer_slot']] = (ws['wafer'].split('_')[-1].capitalize()) + wafer_slot.append(ws['wafer_slot']) + else: + wafer_slot = [wafer_slot] + wafer_dict = None + + dst = [] + for ws in wafer_slot: + pt_cfg = dm.PointingConfig( + fp_file=cfg.ufm_to_fp_path, ot_file=cfg.fp_to_ot_path, + wafer_slot=ws, platform=cfg.platform, + zemax_path=cfg.zemax_path, + roll=np.deg2rad(am.obs_info.roll_center) if cfg.apply_roll else 0.0, + tube_slot = am.obs_info.tube_slot + ) + dst_wafer = dm.ResSet.from_wafer_info_file( + cfg.wafer_info_path, + stream_id, + pt_cfg=pt_cfg, + ignore_north_south=ignore_north_south, + ).as_array() + + if wafer_dict is not None: + mask = [wafer_dict[ws] in d["det_id"].astype(str) for d in dst_wafer] + dst_wafer = dst_wafer[mask] + + dst.append(dst_wafer) + dst = dm.ResSet.from_array(np.concatenate(dst)) # first match match_pars = dm.MatchParams( @@ -434,7 +490,7 @@ def match_wafer( dist_width=np.deg2rad(cfg.match_pars["match0"]["dist_width"]), enforce_pointing_reqs=True, allow_unassigned_to_assigned=False, - unassigned_slots=cfg.unassigned_slots + unassigned_slots=cfg.unassigned_slots, ) match = dm.Match(src, dst, match_pars=match_pars, apply_dst_pointing=False) @@ -560,13 +616,23 @@ def get_wafer_solution( else: base_idx = 0 - meas_rset, pointing_map = merge_pointing_info(cfg, pointing_results, base_idx=base_idx) - # tod_pointing = get_best_tod_pointing(cfg, pointing_results) + if wafer_slot == "ws.": + ignore_north_south = True + else: + ignore_north_south = False + + meas_rset, pointing_map = merge_pointing_info( + cfg, pointing_results, base_idx=base_idx, + ignore_north_south=ignore_north_south + ) meta = pointing_results[0].meta stream_id = meta.det_info.stream_id[0] - match_solution = match_wafer(cfg, meta, stream_id, meas_rset=meas_rset) + match_solution = match_wafer( + cfg, meta, stream_id, meas_rset=meas_rset, + ignore_north_south=ignore_north_south + ) solution = FullWaferSolution( pointing_results=pointing_results, @@ -582,7 +648,7 @@ def get_wafer_solution( def solve_all(cfg) -> Dict[str, Optional[FullWaferSolution]]: - wafer_slots = ["ws0", "ws1", "ws2", "ws3", "ws4", "ws5", "ws6"] + wafer_slots = ["ws.", "ws0", "ws1", "ws2", "ws3", "ws4", "ws5", "ws6"] results = {ws: get_wafer_solution(cfg, ws, save=True) for ws in wafer_slots} return results diff --git a/sotodlib/site_pipeline/update_det_match.py b/sotodlib/site_pipeline/update_det_match.py index 3cf74ca2c..fb40bb8bb 100644 --- a/sotodlib/site_pipeline/update_det_match.py +++ b/sotodlib/site_pipeline/update_det_match.py @@ -245,7 +245,12 @@ def get_failed_detsets(cache_file): def run_match_aman(runner: Runner, aman, detset, wafer_slot=None): stream_id = aman.det_info.stream_id[aman.det_info.detset == detset][0] - rs0 = det_match.ResSet.from_aman(aman, stream_id) + if wafer_slot == "ws.": + ignore_north_south = True + else: + ignore_north_south = False + + rs0 = det_match.ResSet.from_aman(aman, stream_id, ignore_north_south=ignore_north_south) rs0.name = 'meas' rs1 = load_solution_set(runner, stream_id, wafer_slot=wafer_slot) From 6ea0c5701a6b2aaff6a8c909192ffc3e849dc97f Mon Sep 17 00:00:00 2001 From: Michael McCrackan Date: Mon, 18 May 2026 13:58:41 -0700 Subject: [PATCH 07/20] updates and fixes --- sotodlib/coords/det_match.py | 5 ++-- sotodlib/coords/det_match_solutions.py | 33 ++++++++++++---------- sotodlib/coords/optics.py | 7 ++++- sotodlib/site_pipeline/update_det_match.py | 22 ++------------- 4 files changed, 28 insertions(+), 39 deletions(-) diff --git a/sotodlib/coords/det_match.py b/sotodlib/coords/det_match.py index aefa7ce2f..44eef149c 100644 --- a/sotodlib/coords/det_match.py +++ b/sotodlib/coords/det_match.py @@ -443,7 +443,6 @@ def from_wafer_info_file(cls, wafer_info_file, array_name, name=None, resonators = [] idx = 0 for r in wafer_array: - # always true for LF if not ignore_north_south: is_north = r['dets:wafer.coax'] == b'N' else: @@ -489,7 +488,7 @@ def from_wafer_info_file(cls, wafer_info_file, array_name, name=None, @classmethod def from_solutions(cls, sol_file, north_is_highband=True, name=None, - fp_pars=None, platform='SAT', zemax_path=None, + fp_pars=None, platform='LAT', zemax_path=None, ignore_north_south=False): """ Creates an instance from an input-solution file. This will include both design data, along with smurf-band @@ -508,7 +507,7 @@ def from_solutions(cls, sol_file, north_is_highband=True, name=None, Result of the function ``sotododlib.coords.optics.get_ufm_to_fp_pars``. If this is None, detector positions will not be mapped to pointing angles. platform (str): - 'SAT' or 'LAT'. Used to determine which focal plane function to + Which platform. Used to determine which focal plane function to use for pointing zemax_path (str): zemax path, required to get pointing for LAT optics diff --git a/sotodlib/coords/det_match_solutions.py b/sotodlib/coords/det_match_solutions.py index 305d54b06..b51583fca 100644 --- a/sotodlib/coords/det_match_solutions.py +++ b/sotodlib/coords/det_match_solutions.py @@ -34,6 +34,8 @@ class SolutionsCfg: Path to the wafer_info h5 file. platform: str Telescope platform. + wafer_slots: list + Optional list of wafer slots to make solutions for. base_obs_id: str Obs_id to use as a base for matching when merging multiple pointing obs_ids for a wafer. Will default to the pointing obs_id with the @@ -92,6 +94,7 @@ class SolutionsCfg: results_dir: str wafer_info_path: str platform: str + wafer_slots: Optional[list[str]] = None base_obs_id: Optional[str] = None zemax_path: Optional[str] = None apply_roll: bool = True @@ -128,6 +131,9 @@ def from_yaml(cls, path: str) -> "SolutionsCfg": def __post_init__(self): self.ctx = Context(self.ctx_path) + if self.wafer_slots is None: + self.wafer_slots = ["ws.", "ws0", "ws1", "ws2", "ws3", "ws4", "ws5", "ws6"] + if not os.path.exists(self.results_dir): if os.path.exists(os.path.split(self.results_dir)[0]): os.makedirs(self.results_dir) @@ -444,8 +450,8 @@ def match_wafer( src = meas_rset if ignore_north_south: - wafer_slot = [] - wafer_dict = {} + wafer_slots = [] + wafers_dict = {} # get wafer and wafer_slot entry from imprinter with open(cfg.imprinter_path, "r") as f: @@ -455,14 +461,14 @@ def match_wafer( if v['tube_slot'] == tube_slot: for ws in v['wafer_slots']: if 'wafer' in ws.keys(): - wafer_dict[ws['wafer_slot']] = (ws['wafer'].split('_')[-1].capitalize()) - wafer_slot.append(ws['wafer_slot']) + wafers_dict[ws['wafer_slot']] = (ws['wafer'].split('_')[-1].capitalize()) + wafer_slots.append(ws['wafer_slot']) else: - wafer_slot = [wafer_slot] - wafer_dict = None + wafer_slots = [wafer_slot] + wafers_dict = None dst = [] - for ws in wafer_slot: + for ws in wafer_slots: pt_cfg = dm.PointingConfig( fp_file=cfg.ufm_to_fp_path, ot_file=cfg.fp_to_ot_path, wafer_slot=ws, platform=cfg.platform, @@ -477,8 +483,8 @@ def match_wafer( ignore_north_south=ignore_north_south, ).as_array() - if wafer_dict is not None: - mask = [wafer_dict[ws] in d["det_id"].astype(str) for d in dst_wafer] + if wafers_dict is not None: + mask = [wafers_dict[ws] in d["det_id"].astype(str) for d in dst_wafer] dst_wafer = dst_wafer[mask] dst.append(dst_wafer) @@ -616,10 +622,8 @@ def get_wafer_solution( else: base_idx = 0 - if wafer_slot == "ws.": - ignore_north_south = True - else: - ignore_north_south = False + # Whether or not to use North/South in match + ignore_north_south = (wafer_slot == "ws.") meas_rset, pointing_map = merge_pointing_info( cfg, pointing_results, base_idx=base_idx, @@ -648,8 +652,7 @@ def get_wafer_solution( def solve_all(cfg) -> Dict[str, Optional[FullWaferSolution]]: - wafer_slots = ["ws.", "ws0", "ws1", "ws2", "ws3", "ws4", "ws5", "ws6"] - results = {ws: get_wafer_solution(cfg, ws, save=True) for ws in wafer_slots} + results = {ws: get_wafer_solution(cfg, ws, save=True) for ws in cfg.wafer_slots} return results diff --git a/sotodlib/coords/optics.py b/sotodlib/coords/optics.py index 31c19eaf3..d11d49995 100644 --- a/sotodlib/coords/optics.py +++ b/sotodlib/coords/optics.py @@ -373,7 +373,7 @@ def load_zemax(path): zemax_dat: Dictionairy with data from zemax """ try: - zemax_dat = np.load(path, allow_pickle=True) + zemax_dat = np.load(path, allow_pickle=True, encoding='bytes').items() except Exception as e: logger.error("Can't load data from " + path) raise e @@ -398,6 +398,7 @@ def LAT_optics(zemax_path): zemax_dat = load_zemax(zemax_path) try: LAT = zemax_dat["LAT"][()] + LAT = {k.decode(): v for k, v in zemax_dat["LAT"][()].items()} except Exception as e: logger.error("LAT key missing from dictionary") raise e @@ -436,6 +437,10 @@ def LATR_optics(zemax_path, tube_slot): zemax_dat = load_zemax(zemax_path) try: LATR = zemax_dat["LATR"][()] + LATR = np.array([ + {k.decode(): v for k, v in d.items()} + for d in LATR + ], dtype=object) except Exception as e: logger.error("LATR key missing from dictionary") raise e diff --git a/sotodlib/site_pipeline/update_det_match.py b/sotodlib/site_pipeline/update_det_match.py index fb40bb8bb..e3f9f1d70 100644 --- a/sotodlib/site_pipeline/update_det_match.py +++ b/sotodlib/site_pipeline/update_det_match.py @@ -245,10 +245,7 @@ def get_failed_detsets(cache_file): def run_match_aman(runner: Runner, aman, detset, wafer_slot=None): stream_id = aman.det_info.stream_id[aman.det_info.detset == detset][0] - if wafer_slot == "ws.": - ignore_north_south = True - else: - ignore_north_south = False + ignore_north_south = True if wafer_slot == "ws." else False rs0 = det_match.ResSet.from_aman(aman, stream_id, ignore_north_south=ignore_north_south) rs0.name = 'meas' @@ -319,23 +316,8 @@ def run_match(runner: Runner, detset: str) -> bool: logger.info(f" - {ds}") for ds in new_detsets: - stream_id = aman.det_info.stream_id[aman.det_info.detset == ds][0] - # Try to get wafer slot info from book idx - if 'wafer_slots' in book_idx: - for ws in book_idx['wafer_slots']: - if ws['stream_id'] == stream_id: - wafer_slot = ws['wafer_slot'] - break - else: - logger.error( - f"Could not find wafer_slot from book index for ds={detset}, " - f"obs_id={obs_id}" - ) - raise Exception("Could not find wafer-slot") - else: - wafer_slot = None - + wafer_slot = aman.det_info.wafer_slot[aman.det_info.detset == ds][0] match = run_match_aman(runner, aman, ds, wafer_slot=wafer_slot) fpath = os.path.join(runner.match_dir, f"{ds}.h5") match.save(fpath) From 426c83d9c944bc8e387d6e01151205646080d7f6 Mon Sep 17 00:00:00 2001 From: Michael McCrackan Date: Tue, 19 May 2026 22:02:53 -0700 Subject: [PATCH 08/20] updates --- sotodlib/coords/det_match.py | 7 +++-- sotodlib/coords/det_match_solutions.py | 27 ++++++++++++++++--- sotodlib/site_pipeline/update_det_match.py | 30 +++++++++++++++++++++- 3 files changed, 56 insertions(+), 8 deletions(-) diff --git a/sotodlib/coords/det_match.py b/sotodlib/coords/det_match.py index 44eef149c..2d97d0d31 100644 --- a/sotodlib/coords/det_match.py +++ b/sotodlib/coords/det_match.py @@ -160,6 +160,8 @@ class Resonator: smurf_subband: int = -1 readout_id: str = '' + wafer_slot: str = 'ws.' + xi: float = np.nan eta: float = np.nan gamma: float = np.nan @@ -214,7 +216,7 @@ def apply_design_properties(smurf_res, design_res, in_place=False, apply_pointin 'det_pol', 'det_freq', 'det_bandpass', 'det_angle_raw_deg', 'det_angle_actual_deg', 'det_type', 'det_id', 'is_optical', 'mux_bondpad', 'mux_subband', 'mux_band', 'mux_channel', - 'mux_layout_pos' + 'mux_layout_pos', 'wafer_slot' ] # for LF @@ -973,10 +975,7 @@ def get_stats(self) -> MatchingStats: stats.unmatched_src = np.sum(~src_arr['matched'].astype(bool)) stats.unmatched_dst = np.sum(~dst_arr['matched'].astype(bool)) - # print(stats.unmatched_src, stats.unmatched_dst) - has_pt = ~np.isnan(src_arr['xi']) - # print(has_pt) stats.unmatched_src_with_pointing = np.sum( (~src_arr['matched'].astype(bool)) & has_pt ) diff --git a/sotodlib/coords/det_match_solutions.py b/sotodlib/coords/det_match_solutions.py index b51583fca..1ce14e342 100644 --- a/sotodlib/coords/det_match_solutions.py +++ b/sotodlib/coords/det_match_solutions.py @@ -467,7 +467,8 @@ def match_wafer( wafer_slots = [wafer_slot] wafers_dict = None - dst = [] + dst_merged = [] + # loop through and get pointing information for all wafers for ws in wafer_slots: pt_cfg = dm.PointingConfig( fp_file=cfg.ufm_to_fp_path, ot_file=cfg.fp_to_ot_path, @@ -483,12 +484,32 @@ def match_wafer( ignore_north_south=ignore_north_south, ).as_array() + # extract current wafer if wafers_dict is not None: mask = [wafers_dict[ws] in d["det_id"].astype(str) for d in dst_wafer] dst_wafer = dst_wafer[mask] + dst_wafer['wafer_slot'][:] = ws - dst.append(dst_wafer) - dst = dm.ResSet.from_array(np.concatenate(dst)) + dst_merged.append(dst_wafer) + dst_merged = np.concatenate(dst_merged) + + # get full wafer info and populate pointing and wafer_slot information + # from merged dst (not necesary if matching a single wafer) + if ignore_north_south: + dst = dm.ResSet.from_wafer_info_file( + cfg.wafer_info_path, + stream_id, + pt_cfg=None, + ignore_north_south=ignore_north_south, + ).as_array() + + merge_fields = ["xi", "eta", "wafer_slot"] + for i, d in enumerate(dst_all): + idx = np.where(dst_merged['det_id'] == d['det_id'])[0][0] + if idx: + for field in merge_fields: + dst[i][field] = dst_merged[idx][field] + dst = dm.ResSet.from_array(dst) # first match match_pars = dm.MatchParams( diff --git a/sotodlib/site_pipeline/update_det_match.py b/sotodlib/site_pipeline/update_det_match.py index e3f9f1d70..d33c53c04 100644 --- a/sotodlib/site_pipeline/update_det_match.py +++ b/sotodlib/site_pipeline/update_det_match.py @@ -154,6 +154,7 @@ def __init__(self, cfg: UpdateDetMatchesConfig): self.cfg = cfg self.ctx = core.Context(cfg.context_path) self.detset_db = None + self.detset_db_path = None self.detcal_db = None with open(self.cfg.wafer_map_path, 'r') as f: self.wafer_map = yaml.safe_load(f) @@ -169,7 +170,8 @@ def __init__(self, cfg: UpdateDetMatchesConfig): else: continue if entry_name == cfg.detset_meta_name: - self.detset_db = core.metadata.ManifestDb(d['db']) + self.detset_db_path = d['db'] + self.detset_db = core.metadata.ManifestDb(self.detset_db_path) elif entry_name == cfg.detcal_meta_name: self.detcal_db = core.metadata.ManifestDb(d['db']) @@ -242,6 +244,29 @@ def get_failed_detsets(cache_file): return list(x.keys()) +def update_detset_wafer_slot(runner: Runner, ds, match): + """ + Update a deset with the wafer_slot field from a match. + """ + ds_base_path = os.path.dirname(detset_db_path) + db = self.detset_db.inspect() + entry = [d for d in db if d['dataset'] == ds][0] + + h5_path = "os.path.join(ds_base_path, entry['filename'])" + with h5py.File(os.path.join(ds_base_path, entry['filename'])) as h5f: + dataset = h5f[entry['dets:detset']][:] + + # replace wafer_slot + merged = match.merged.as_array() + for i, row in enumerate(dataset): + idx = np.where(merged['readout_id'] == row['dets:readout_id'].astype(str))[0] + if idx.size != 0: + row[i]['dets:wafer_slot'] = merged[idx[0]]['wafer_slot'] + + # write entry back out to detset + write_dataset(core.metadata.ResultSet.from_friend(dataset), h5_path, ds, overwrite=True) + + def run_match_aman(runner: Runner, aman, detset, wafer_slot=None): stream_id = aman.det_info.stream_id[aman.det_info.detset == detset][0] @@ -263,6 +288,7 @@ def run_match_aman(runner: Runner, aman, detset, wafer_slot=None): match_pars.freq_offset_mhz = opt_freq match = det_match.Match(rs0, rs1, match_pars=match_pars, apply_dst_pointing=runner.cfg.apply_solution_pointing) + return match def run_match(runner: Runner, detset: str) -> bool: @@ -321,6 +347,8 @@ def run_match(runner: Runner, detset: str) -> bool: match = run_match_aman(runner, aman, ds, wafer_slot=wafer_slot) fpath = os.path.join(runner.match_dir, f"{ds}.h5") match.save(fpath) + if wafer_slot == "ws.": + update_detset_wafer_slot(runner, ds, match) logger.info(f"Saved match to file: {fpath}") return True From f768e43e83e3c7f35899023398a4019cd268232d Mon Sep 17 00:00:00 2001 From: Michael McCrackan Date: Mon, 1 Jun 2026 07:32:54 -0700 Subject: [PATCH 09/20] remove detset function --- sotodlib/site_pipeline/update_det_match.py | 25 ---------------------- 1 file changed, 25 deletions(-) diff --git a/sotodlib/site_pipeline/update_det_match.py b/sotodlib/site_pipeline/update_det_match.py index d33c53c04..ca1876049 100644 --- a/sotodlib/site_pipeline/update_det_match.py +++ b/sotodlib/site_pipeline/update_det_match.py @@ -244,29 +244,6 @@ def get_failed_detsets(cache_file): return list(x.keys()) -def update_detset_wafer_slot(runner: Runner, ds, match): - """ - Update a deset with the wafer_slot field from a match. - """ - ds_base_path = os.path.dirname(detset_db_path) - db = self.detset_db.inspect() - entry = [d for d in db if d['dataset'] == ds][0] - - h5_path = "os.path.join(ds_base_path, entry['filename'])" - with h5py.File(os.path.join(ds_base_path, entry['filename'])) as h5f: - dataset = h5f[entry['dets:detset']][:] - - # replace wafer_slot - merged = match.merged.as_array() - for i, row in enumerate(dataset): - idx = np.where(merged['readout_id'] == row['dets:readout_id'].astype(str))[0] - if idx.size != 0: - row[i]['dets:wafer_slot'] = merged[idx[0]]['wafer_slot'] - - # write entry back out to detset - write_dataset(core.metadata.ResultSet.from_friend(dataset), h5_path, ds, overwrite=True) - - def run_match_aman(runner: Runner, aman, detset, wafer_slot=None): stream_id = aman.det_info.stream_id[aman.det_info.detset == detset][0] @@ -347,8 +324,6 @@ def run_match(runner: Runner, detset: str) -> bool: match = run_match_aman(runner, aman, ds, wafer_slot=wafer_slot) fpath = os.path.join(runner.match_dir, f"{ds}.h5") match.save(fpath) - if wafer_slot == "ws.": - update_detset_wafer_slot(runner, ds, match) logger.info(f"Saved match to file: {fpath}") return True From 7ceae83ac2001c6fc6ef8f65d5a6ac720ce0b4c2 Mon Sep 17 00:00:00 2001 From: Michael McCrackan Date: Mon, 1 Jun 2026 07:56:32 -0700 Subject: [PATCH 10/20] fixes, rename ot to rx --- sotodlib/coords/det_match.py | 12 +++++++----- sotodlib/coords/det_match_solutions.py | 12 ++++++++---- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/sotodlib/coords/det_match.py b/sotodlib/coords/det_match.py index 2d97d0d31..aa4075e9e 100644 --- a/sotodlib/coords/det_match.py +++ b/sotodlib/coords/det_match.py @@ -65,6 +65,8 @@ class PointingConfig: ----- fp_file: str Path to focal-plane file that is used by the optics module. + rx_file: str + Path to optics tube YAML file that is used by the optics module. wafer_slot: str Wafer slot of the UFM. For example: "ws0" platform: str @@ -80,7 +82,7 @@ class PointingConfig: Either the tube name as a string or the tube number as an int. """ fp_file: str - ot_file: str + rx_file: str wafer_slot: str platform: str zemax_path: Optional[str] = None @@ -110,8 +112,8 @@ def __post_init__(self): self.tel_type, self.wafer_slot, self.fp_file ) - self.ot_pars = optics.get_fp_to_ot_pars( - self.tube_slot, self.ot_file) + self.rx_pars = optics.get_fp_to_rx_pars( + self.tube_slot, self.rx_file) def get_pointing(self, x, y, pol=0): if self.tel_type.upper() == 'SAT': @@ -125,7 +127,7 @@ def get_pointing(self, x, y, pol=0): tube_slot=self.tube_slot, wafer_slot=self.wafer_slot, ufm_to_fp_pars=self.fp_pars, - fp_to_ot_pars=self.ot_pars, + fp_to_rx_pars=self.rx_pars, ) elif self.tel_type.upper() == 'LAT': xi, eta, gamma = optics.get_focal_plane( @@ -138,7 +140,7 @@ def get_pointing(self, x, y, pol=0): tube_slot=self.tube_slot, wafer_slot=self.wafer_slot, ufm_to_fp_pars=self.fp_pars, - fp_to_ot_pars=self.ot_pars, + fp_to_rx_pars=self.rx_pars, zemax_path=self.zemax_path, ) return xi, eta, gamma diff --git a/sotodlib/coords/det_match_solutions.py b/sotodlib/coords/det_match_solutions.py index 1ce14e342..b7715578d 100644 --- a/sotodlib/coords/det_match_solutions.py +++ b/sotodlib/coords/det_match_solutions.py @@ -85,6 +85,8 @@ class SolutionsCfg: (xi_offset, eta_offset) where both are in radians. ufm_to_fp_path: str Path to file that maps wafer_slot to position on focal plane. + fp_to_rx_path: str + Path to file that maps tube slot to position on focal plane. freq_correct_by_muxband: bool If true, apply the same freq offset correction to all resonators in a mux-band. """ @@ -112,7 +114,7 @@ class SolutionsCfg: initial_pointing_offset: Tuple[float, float] = (0, 0) ufm_to_fp_path: Optional[str] = None - fp_to_ot_path: Optional[str] = None + fp_to_rx_path: Optional[str] = None imprinter_path: Optional[str] = None freq_correct_by_muxband: bool = True @@ -154,8 +156,8 @@ def __post_init__(self): self.ufm_to_fp_path = os.path.join( self.site_pipeline_cfg_dir, "shared/focalplane/ufm_to_fp.yaml" ) - if self.fp_to_ot_path is None: - self.fp_to_ot_path = os.path.join( + if self.fp_to_rx_path is None: + self.fp_to_rx_path = os.path.join( self.site_pipeline_cfg_dir, "shared/focalplane/optics_tubes.yaml" ) if self.imprinter_path is None: @@ -471,7 +473,7 @@ def match_wafer( # loop through and get pointing information for all wafers for ws in wafer_slots: pt_cfg = dm.PointingConfig( - fp_file=cfg.ufm_to_fp_path, ot_file=cfg.fp_to_ot_path, + fp_file=cfg.ufm_to_fp_path, rx_file=cfg.fp_to_rx_path, wafer_slot=ws, platform=cfg.platform, zemax_path=cfg.zemax_path, roll=np.deg2rad(am.obs_info.roll_center) if cfg.apply_roll else 0.0, @@ -510,6 +512,8 @@ def match_wafer( for field in merge_fields: dst[i][field] = dst_merged[idx][field] dst = dm.ResSet.from_array(dst) + else: + dst = dm.ResSet.from_array(dst_merged) # first match match_pars = dm.MatchParams( From e0300bd2ee65b225723370d6cce97ef6e2bbfa46 Mon Sep 17 00:00:00 2001 From: Michael McCrackan Date: Mon, 1 Jun 2026 08:00:24 -0700 Subject: [PATCH 11/20] remove variable --- sotodlib/site_pipeline/update_det_match.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/sotodlib/site_pipeline/update_det_match.py b/sotodlib/site_pipeline/update_det_match.py index ca1876049..f1560f5dd 100644 --- a/sotodlib/site_pipeline/update_det_match.py +++ b/sotodlib/site_pipeline/update_det_match.py @@ -154,7 +154,6 @@ def __init__(self, cfg: UpdateDetMatchesConfig): self.cfg = cfg self.ctx = core.Context(cfg.context_path) self.detset_db = None - self.detset_db_path = None self.detcal_db = None with open(self.cfg.wafer_map_path, 'r') as f: self.wafer_map = yaml.safe_load(f) @@ -170,8 +169,7 @@ def __init__(self, cfg: UpdateDetMatchesConfig): else: continue if entry_name == cfg.detset_meta_name: - self.detset_db_path = d['db'] - self.detset_db = core.metadata.ManifestDb(self.detset_db_path) + self.detset_db = core.metadata.ManifestDb(d['db']) elif entry_name == cfg.detcal_meta_name: self.detcal_db = core.metadata.ManifestDb(d['db']) From 9cdf337f6d8f2c85b549c0dbea20da423208bd50 Mon Sep 17 00:00:00 2001 From: Michael McCrackan Date: Mon, 1 Jun 2026 08:11:52 -0700 Subject: [PATCH 12/20] fix optics file diffs --- sotodlib/coords/optics.py | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/sotodlib/coords/optics.py b/sotodlib/coords/optics.py index f88596b5f..dc5c51844 100644 --- a/sotodlib/coords/optics.py +++ b/sotodlib/coords/optics.py @@ -254,7 +254,6 @@ def get_fp_to_rx_pars(ot, config_path): return config[ot] - def fp_to_rx(aman, x=None, y=None, pol=None, phi=0, dx=0, dy=0): """ Transform from coords internal to focal plane to receiver coordinates. @@ -515,11 +514,11 @@ def LAT_focal_plane(aman, zemax_path, x=None, y=None, pol=None, roll=0, tube_slo If aman is provided then will be wrapped as aman.focal_plane.eta. """ if x is None: - x = aman.focal_plane.x_ot + x = aman.focal_plane.x_fp if y is None: - y = aman.focal_plane.y_ot + y = aman.focal_plane.y_fp if pol is None: - pol = aman.focal_plane.pol_ot + pol = aman.focal_plane.pol_fp sec2el, sec2xel = LAT_optics(zemax_path) array2secx, array2secy = LATR_optics(zemax_path, tube_slot) @@ -718,11 +717,6 @@ def get_focal_plane( Should be a dict where each key is an OT pointing to a dict with keys dx, dy, and phi. - ot_config_path: Path to the optics_tubes config file. - - fp_to_ot_pars: Loaded optics_tubes params. - If provided ot_config_path is is ignored. - zemax_path: Path to the data file from Zemax. Only used by the LAT. From 8546c2634ce4587e891750337faaa389f4eb1d7e Mon Sep 17 00:00:00 2001 From: Michael McCrackan Date: Mon, 1 Jun 2026 08:50:57 -0700 Subject: [PATCH 13/20] fix typo --- sotodlib/coords/det_match_solutions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sotodlib/coords/det_match_solutions.py b/sotodlib/coords/det_match_solutions.py index b7715578d..3af549d2f 100644 --- a/sotodlib/coords/det_match_solutions.py +++ b/sotodlib/coords/det_match_solutions.py @@ -506,7 +506,7 @@ def match_wafer( ).as_array() merge_fields = ["xi", "eta", "wafer_slot"] - for i, d in enumerate(dst_all): + for i, d in enumerate(dst_merged): idx = np.where(dst_merged['det_id'] == d['det_id'])[0][0] if idx: for field in merge_fields: From 8201b09dc1db4c83ed60ab1cb63db77b6c10ce44 Mon Sep 17 00:00:00 2001 From: Michael McCrackan Date: Mon, 1 Jun 2026 08:52:21 -0700 Subject: [PATCH 14/20] duplicate import --- sotodlib/coords/det_match_solutions.py | 1 - 1 file changed, 1 deletion(-) diff --git a/sotodlib/coords/det_match_solutions.py b/sotodlib/coords/det_match_solutions.py index 3af549d2f..71c29552a 100644 --- a/sotodlib/coords/det_match_solutions.py +++ b/sotodlib/coords/det_match_solutions.py @@ -6,7 +6,6 @@ import os import numpy as np import yaml -from copy import deepcopy from scipy import interpolate from tqdm.auto import tqdm, trange from copy import deepcopy From e1f749a17960464e8e1ffb89c8feb76ae5414cd6 Mon Sep 17 00:00:00 2001 From: Michael McCrackan Date: Mon, 1 Jun 2026 11:20:19 -0700 Subject: [PATCH 15/20] fix indexing --- sotodlib/coords/det_match_solutions.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/sotodlib/coords/det_match_solutions.py b/sotodlib/coords/det_match_solutions.py index 71c29552a..b28061366 100644 --- a/sotodlib/coords/det_match_solutions.py +++ b/sotodlib/coords/det_match_solutions.py @@ -506,10 +506,10 @@ def match_wafer( merge_fields = ["xi", "eta", "wafer_slot"] for i, d in enumerate(dst_merged): - idx = np.where(dst_merged['det_id'] == d['det_id'])[0][0] + idx = np.where(dst['det_id'] == d['det_id'])[0][0] if idx: for field in merge_fields: - dst[i][field] = dst_merged[idx][field] + dst[idx][field] = dst_merged[i][field] dst = dm.ResSet.from_array(dst) else: dst = dm.ResSet.from_array(dst_merged) @@ -588,7 +588,6 @@ def match_wafer( match.match_pars.dist_width = np.deg2rad(cfg.match_pars["match2"]["dist_width"]) match._match() - match_iterations.append(deepcopy(match)) return MatchSolution( From 3dc82fba0983cf45ee0daeb6057d6f44e5423b7b Mon Sep 17 00:00:00 2001 From: Michael McCrackan Date: Mon, 16 Nov 2026 10:21:22 -0800 Subject: [PATCH 16/20] use highest det_cal bandpass yield for obs_id --- sotodlib/site_pipeline/update_det_match.py | 167 +++++++++++++++------ 1 file changed, 124 insertions(+), 43 deletions(-) diff --git a/sotodlib/site_pipeline/update_det_match.py b/sotodlib/site_pipeline/update_det_match.py index f1560f5dd..a99d86298 100644 --- a/sotodlib/site_pipeline/update_det_match.py +++ b/sotodlib/site_pipeline/update_det_match.py @@ -268,61 +268,142 @@ def run_match_aman(runner: Runner, aman, detset, wafer_slot=None): def run_match(runner: Runner, detset: str) -> bool: """ - Creates match files for specified detset, along with any other unmatched - detsets in the loaded observation. If match fails for a known reason, this - will add it to the failed_detset_cache so that it is not re-attempted. + Find the observation with the highest number of non-NC detectors + for the requested detset and run detector matching. Returns ------- success: bool True if match was successful """ - # Find obs-id with cal info - obs_all = set(runner.ctx.obsdb.query("type=='obs'")['obs_id']) - cur = runner.ctx.obsfiledb.conn.execute(f""" - select distinct obs_id from files where detset=='{detset}' - """) - obsids_with_cal = set(runner.detcal_db.get_entries(['dataset'])['dataset']) + + fpath = os.path.join(runner.match_dir, f"{detset}.h5") + + if os.path.exists(fpath): + logger.info(f"Match already exists for {detset}") + return True + + obs_all = set( + runner.ctx.obsdb.query("type=='obs'")["obs_id"] + ) + + cur = runner.ctx.obsfiledb.conn.execute( + "SELECT DISTINCT obs_id FROM files WHERE detset = ?", + (detset,), + ) + obs_dset = {r[0] for r in cur} - obs_ids = sorted(list( - obs_all.intersection(obs_dset).intersection(obsids_with_cal)), - key=lambda s:s.split('_')[1])[::-1] - if len(obs_ids) == 0: + + obsids_with_cal = set( + runner.detcal_db.get_entries(["dataset"])["dataset"] + ) + + obs_ids = sorted( + obs_all.intersection(obs_dset).intersection(obsids_with_cal), + key=lambda s: int(s.split("_")[1]), + reverse=True, + ) + + if not obs_ids: add_to_failed_cache( - runner.failed_detset_cache_path, detset, "NO_OBSID_WITH_CAL", runner.cfg + runner.failed_detset_cache_path, + detset, + "NO_OBSID_WITH_CAL", + runner.cfg, ) logger.error(f"Cannot find obsid for detset {detset}") return False - obs_id = obs_ids[0] - - book_dir = os.path.dirname(runner.ctx.obsfiledb.get_files(obs_id)[detset][0][0]) - book_idx_file = os.path.join(book_dir, 'M_index.yaml') - with open(book_idx_file, 'r') as f: - book_idx = yaml.safe_load(f) - - aman = runner.ctx.get_meta(obs_id, ignore_missing=True) - finished_detsets = set([os.path.splitext(f)[0] for f in os.listdir(runner.match_dir)]) - new_detsets = [] - for detset in np.unique(aman.det_info.detset): - if ( - detset not in finished_detsets and - get_detset_time(detset) > runner.cfg.start_time and - get_detset_time(detset) < runner.cfg.stop_time - ): - new_detsets.append(detset) - - logger.info(f"Loaded obs_id {obs_id}. Running matches for detsets:") - for ds in new_detsets: - logger.info(f" - {ds}") - - for ds in new_detsets: - stream_id = aman.det_info.stream_id[aman.det_info.detset == ds][0] - wafer_slot = aman.det_info.wafer_slot[aman.det_info.detset == ds][0] - match = run_match_aman(runner, aman, ds, wafer_slot=wafer_slot) - fpath = os.path.join(runner.match_dir, f"{ds}.h5") - match.save(fpath) - logger.info(f"Saved match to file: {fpath}") + logger.info( + f"Searching {len(obs_ids)} observations for detset {detset}" + ) + + best_obs_id = None + best_aman = None + best_n_good = -1 + best_n_total = 0 + + for obs_id in tqdm( + obs_ids, + desc=f"Searching {detset}", + disable=not runner.cfg.show_pb, + ): + try: + aman = runner.ctx.get_meta( + obs_id, + dets={"detset": detset}, + ignore_missing=True, + ) + + bandpass = np.asarray( + aman.det_cal.bandpass + ).astype(str) + + good = (bandpass != "NC") + + n_good = int(np.count_nonzero(good)) + n_total = int(np.count_nonzero(aman.dets.count)) + + if n_total == 0: + continue + + logger.debug( + f"{obs_id} | {detset} | " + f"{n_good}/{n_total} non-NC detectors" + ) + + if n_good > best_n_good: + best_obs_id = obs_id + best_aman = aman + best_n_good = n_good + best_n_total = n_total + + logger.info( + f"New best obs_id: {best_obs_id} | " + f"{best_n_good}/{best_n_total} non-NC detectors" + ) + + except Exception as e: + logger.warning( + f"Failed to load metadata for {obs_id} " + f"and {detset}: {e}" + ) + continue + + if best_aman is None: + logger.error( + f"No usable detector calibration metadata found for {detset}" + ) + return False + + logger.info( + f"Selected obs_id {best_obs_id} for {detset}: " + f"{best_n_good}/{best_n_total} non-NC detectors " + f"({100 * best_n_good / best_n_total:.2f}%)" + ) + + stream_id = str( + best_aman.det_info.stream_id[0] + ) + + wafer_slot = str( + best_aman.det_info.wafer_slot[0] + ) + + logger.info( + f"Running match for {detset} | " + f"{stream_id} | {wafer_slot} | {best_obs_id}" + ) + + match = run_match_aman( + runner, + best_aman, + detset, + wafer_slot=wafer_slot, + ) + + match.save(fpath) + logger.info(f"Saved match to file: {fpath}") return True From 10ad874208e1e0361893705c038a77f3a160fb00 Mon Sep 17 00:00:00 2001 From: Michael McCrackan Date: Mon, 16 Nov 2026 10:54:20 -0800 Subject: [PATCH 17/20] skip if bandpass yield is higher than design --- sotodlib/site_pipeline/update_det_match.py | 51 +++++++++++++++++----- 1 file changed, 39 insertions(+), 12 deletions(-) diff --git a/sotodlib/site_pipeline/update_det_match.py b/sotodlib/site_pipeline/update_det_match.py index a99d86298..373179ae1 100644 --- a/sotodlib/site_pipeline/update_det_match.py +++ b/sotodlib/site_pipeline/update_det_match.py @@ -3,7 +3,8 @@ import os import yaml from copy import deepcopy -from typing import Optional, Dict, List +from typing import Optional, Dict, List, Any +from collections import defaultdict from dataclasses import dataclass from tqdm.auto import tqdm import logging @@ -46,6 +47,8 @@ class UpdateDetMatchesConfig: h5 files will be stored. context_path: str Path to context file. This must contain detset and det_cal metadata. + wafer_info_path: str + Path to wafer info metadata file. site_pipeline_root: str Path to root of site-pipeline-configs. If ``$SITE_PIPELINE_CONFIG_DIR`` is set in the environment, that will be used as the default. @@ -92,7 +95,7 @@ class UpdateDetMatchesConfig: Time in seconds before a failed detset will be added to the cache. This is to prevent new detsets still acquiring data from being added right away. - + Attributes ------------- freq_offsets : Optional[np.ndarray] @@ -101,6 +104,7 @@ class UpdateDetMatchesConfig: """ results_path: str context_path: str + wafer_info_path: str site_pipeline_root:str = os.environ.get('SITE_PIPELINE_CONFIG_DIR') wafer_map_path: Optional[str] = None freq_offset_range_args: Optional[tuple[float, float, float]] = (-4, 4, 0.3) @@ -124,7 +128,7 @@ def __post_init__(self): if self.wafer_map_path is None: self.wafer_map_path = os.path.join( self.site_pipeline_root, 'shared/detmapping/wafer_map.yaml') - + if self.freq_offset_range_args is not None: self.freq_offsets = np.arange(*self.freq_offset_range_args) else: @@ -135,12 +139,12 @@ def __post_init__(self): if not os.path.exists(self.results_path): raise FileNotFoundError(f"Results dir does not exist: {self.results_path}") - + allowed_solution_types = ['kaiwen_handmade', 'resonator_set'] if self.solution_type not in allowed_solution_types: raise ValueError( f"Solution type ({self.solution_type}) must be a member of: {allowed_solution_types}") - + if self.solution_type == 'resonator_set': if self.resonator_set_dir is None: raise ValueError("Must specify resonator_set_dir for solution_type='resonator_set'") @@ -155,9 +159,10 @@ def __init__(self, cfg: UpdateDetMatchesConfig): self.ctx = core.Context(cfg.context_path) self.detset_db = None self.detcal_db = None + self.wafer_info_dataset: defaultdict[str, Any] = defaultdict(lambda: None) with open(self.cfg.wafer_map_path, 'r') as f: self.wafer_map = yaml.safe_load(f) - + self.ufm_to_fp_file = os.path.join( cfg.site_pipeline_root, 'shared/focalplane/ufm_to_fp.yaml') @@ -179,7 +184,11 @@ def __init__(self, cfg: UpdateDetMatchesConfig): if self.detcal_db is None: raise Exception( f"Could not find detcal metadata entry with name: {cfg.detcal_meta_name}") - + + with h5py.File(cfg.wafer_info_path) as h5f: + for ufm in list(h5f.keys()): + self.wafer_info_dataset[ufm] = h5f[ufm][:] + self.failed_detset_cache_path = os.path.join(cfg.results_path, 'failed_detsets.yaml') self.match_dir = os.path.join(cfg.results_path, 'matches') if not os.path.exists(self.match_dir): @@ -227,7 +236,7 @@ def add_to_failed_cache(cache_file, detset, msg, cfg: UpdateDetMatchesConfig): with open(cache_file, 'r') as f: x = yaml.safe_load(f) else: - x = {} + x = {} x[str(detset)] = str(msg) with open(cache_file, 'w') as f: @@ -261,7 +270,7 @@ def run_match_aman(runner: Runner, aman, detset, wafer_slot=None): match_pars=match_pars, ) match_pars.freq_offset_mhz = opt_freq - match = det_match.Match(rs0, rs1, match_pars=match_pars, + match = det_match.Match(rs0, rs1, match_pars=match_pars, apply_dst_pointing=runner.cfg.apply_solution_pointing) return match @@ -335,12 +344,28 @@ def run_match(runner: Runner, detset: str) -> bool: ignore_missing=True, ) + stream_id = aman.det_info.stream_id[0] + bandpass = np.asarray( aman.det_cal.bandpass ).astype(str) good = (bandpass != "NC") + # Some bg files give yields higher than design. Skip those since + # there will be many spurious entries with wrong bgs. + bad_bg = False + for bp in np.unique(bandpass[good]): + design_yield = np.count_nonzero(wafer_info_dataset[stream_id]['dets:wafer.bandpass'] == bp) + det_cal_yield = np.count_nonzero(bandpass[good] == bp) + if det_cal_yield > design_yield: + bad_bg = True + break + + if bad_bg: + logger.warnining(f"{obs_id} and {detset} yield surpasses design yield. skipping.") + continue + n_good = int(np.count_nonzero(good)) n_total = int(np.count_nonzero(aman.dets.count)) @@ -426,8 +451,8 @@ def scan_for_freq_offset(rs0, rs1, freq_offsets, match_pars=None, show_pb=True): else: match_pars = deepcopy(match_pars) freq_offsets = np.array(freq_offsets) - - rs0 = deepcopy(rs0) + + rs0 = deepcopy(rs0) rs1 = deepcopy(rs1) costs = np.full_like(freq_offsets, np.nan) @@ -477,7 +502,7 @@ def add_to_db(arr, db_path, h5_path, detset, write_relpath=True): }, h5_path) else: logger.warning(f"Dataset {detset} already exists in db: {db_path}") - + write_relpath = runner.cfg.write_relpath add_to_db(ra, det_match_idx, det_match_h5, detset, write_relpath=write_relpath) @@ -506,6 +531,7 @@ def update_manifests_all(runner): logger.info(f"Adding {ds} to manifests") update_manifests(runner, ds) + def get_parser(parser=None): if parser is None: parser = argparse.ArgumentParser() @@ -515,6 +541,7 @@ def get_parser(parser=None): help='create a det_match solution set') return parser + def main(config_file: str, run_all: bool=False, solutions_mode: bool=False): """ Site-pipeline script to peform detector matching of tunesets to a solution From 6c093524266963dd703d0c13be28262002d36cfa Mon Sep 17 00:00:00 2001 From: Michael McCrackan Date: Tue, 17 Nov 2026 11:05:33 -0800 Subject: [PATCH 18/20] mostly remove ignore_north_south --- sotodlib/coords/det_match.py | 75 ++++++++++++++-------- sotodlib/coords/det_match_solutions.py | 17 +---- sotodlib/site_pipeline/update_det_match.py | 4 +- 3 files changed, 53 insertions(+), 43 deletions(-) diff --git a/sotodlib/coords/det_match.py b/sotodlib/coords/det_match.py index 499757ac1..16e2c06ec 100644 --- a/sotodlib/coords/det_match.py +++ b/sotodlib/coords/det_match.py @@ -44,16 +44,35 @@ def map_band_chans(b1, c1, b2, c2, chans_per_band=512): return mapping -def get_north_is_highband(bands, bgs): +def get_north_is_highband(bands, bgs, min_fraction=0.5): """ - Checks if north is highband based on bgmapping. This will tell you if - the majority of dets on the north side of the ufm (bgs 0-5) belong to - highband (bands 4-7). + Determine the UFM coax orientation by requiring both SMuRF + band populations to agree on the north/south assignment. """ - highband = (bands > 3).astype(int) * 2 - 1 # 1 if highband, -1 if not - north = (bgs < 6).astype(int) * 2 - 1 # 1 if north, -1 if not - north[bgs == -1] = 0 - return np.mean(highband * north) > 0 + bands, bgs = np.asarray(bands), np.asarray(bgs) + + valid = (bands >= 0) & (bands < 8) & (bgs >= 0) & (bgs < 12) + + low = valid & (bands < 4) + high = valid & (bands >= 4) + + if not np.any(low) or not np.any(high): + raise ValueError("Missing lowband or highband population") + + f_low_north = np.mean(bgs[low] < 6) + f_high_north = np.mean(bgs[high] < 6) + + if f_high_north > min_fraction and f_low_north < 1 - min_fraction: + return True + + if f_low_north > min_fraction and f_high_north < 1 - min_fraction: + return False + + raise ValueError( + f"Ambiguous north/south orientation: " + f"lowband north={f_low_north:.1%}, " + f"highband north={f_high_north:.1%}" + ) @dataclass @@ -309,8 +328,8 @@ def as_array(self): return np.array(data, dtype=dtype) @classmethod - def from_aman(cls, aman, stream_id, det_cal=None, name=None, pointing: Optional[AxisManager]=None, - ignore_north_south=False): + def from_aman(cls, aman, stream_id, det_cal=None, name=None, + pointing: Optional[AxisManager]=None): """ Load a resonator set from a Context object based on an obs_id @@ -331,17 +350,20 @@ def from_aman(cls, aman, stream_id, det_cal=None, name=None, pointing: Optional[ m = aman.det_info.stream_id == stream_id if not np.any(m): raise ValueError(f"No channels with stream_id {stream_id} in obs") - + if det_cal is None: det_cal = aman.det_cal - north_is_highband = get_north_is_highband( - aman.det_info.smurf.band[m], det_cal.bg[m] - ) + if aman.det_info.wafer_slot[0] != "ws.": + north_is_highband = get_north_is_highband( + aman.det_info.smurf.band[m], det_cal.bg[m] + ) + is_norths = [] resonators = [] for i, ri in enumerate(np.where(m)[0]): band, channel = aman.det_info.smurf.band[ri], aman.det_info.smurf.channel[ri] - if not ignore_north_south: + if aman.det_info.wafer_slot[ri] != "ws.": is_north = north_is_highband ^ (band < 4) + is_norths.append(int(is_north)) else: is_north = 1 readout_id = aman.det_info.readout_id[ri] @@ -382,6 +404,9 @@ def from_tunefile(cls, tunefile, name=None, north_is_highband=True, Path to file containing resonance fit data bgmap_file (str): Path to file containing bgmap data + ignore_north_south (str): + Do not infer North/South orientation and just set all to North. + Used for LF. """ tune = np.load(tunefile, allow_pickle=True).item() resonances = [] @@ -416,8 +441,7 @@ def from_tunefile(cls, tunefile, name=None, north_is_highband=True, @classmethod def from_wafer_info_file(cls, wafer_info_file, array_name, name=None, - pt_cfg: Optional[PointingConfig]=None, - ignore_north_south=False): + pt_cfg: Optional[PointingConfig]=None): """ Initialize a ResSet from a wafer info file. This is a file that contains detector design information. @@ -447,10 +471,7 @@ def from_wafer_info_file(cls, wafer_info_file, array_name, name=None, resonators = [] idx = 0 for r in wafer_array: - if not ignore_north_south: - is_north = r['dets:wafer.coax'] == b'N' - else: - is_north = 1 + is_north = r['dets:wafer.coax'] == b'N' kwargs = dict( idx=idx, det_id=r['dets:det_id'].decode(), @@ -505,16 +526,18 @@ def from_solutions(cls, sol_file, north_is_highband=True, name=None, name (str): Name to label this ResSet north_is_highband (bool): - True if the north-side of the array corresponds to bands - 4-8 + True if the north-side of the array corresponds to bands 4-8 fp_pars (dict): - Result of the function ``sotododlib.coords.optics.get_ufm_to_fp_pars``. If this is None, detector positions will - not be mapped to pointing angles. + Result of the function ``sotododlib.coords.optics.get_ufm_to_fp_pars``. + If this is None, detector positions will not be mapped to pointing angles. platform (str): Which platform. Used to determine which focal plane function to use for pointing zemax_path (str): zemax path, required to get pointing for LAT optics + ignore_north_south (str): + Do not infer North/South orientation and just set all to North. + Used for LF. """ resonances = [] @@ -528,7 +551,7 @@ def from_solutions(cls, sol_file, north_is_highband=True, name=None, labels[i] = labels[i].strip() # Helper needed for when sol file has saved ints as floats - def _int(val, null_val=None): + def _int(val, null_val=None): is_null = (val == 'null' or val == '') if is_null and null_val is not None: return null_val diff --git a/sotodlib/coords/det_match_solutions.py b/sotodlib/coords/det_match_solutions.py index 2089a4ca4..43536d7dd 100644 --- a/sotodlib/coords/det_match_solutions.py +++ b/sotodlib/coords/det_match_solutions.py @@ -247,7 +247,7 @@ def pointing_preprocess(cfg: SolutionsCfg, pinfo: PointingInfo): return meta -def merge_pointing_info(cfg: SolutionsCfg, pinfos: List[PointingInfo], base_idx=0, ignore_north_south=False): +def merge_pointing_info(cfg: SolutionsCfg, pinfos: List[PointingInfo], base_idx=0): """ Combine all pointing measurements into a single resonator set, with the median pointing info from all. This requires a base_idx to be specified, @@ -268,7 +268,6 @@ def merge_pointing_info(cfg: SolutionsCfg, pinfos: List[PointingInfo], base_idx= meta, stream_id=stream_id, pointing=meta.tod_pointing, - ignore_north_south=ignore_north_south ) pointing_map = { @@ -288,7 +287,6 @@ def merge_pointing_info(cfg: SolutionsCfg, pinfos: List[PointingInfo], base_idx= meta, stream_id=stream_id, pointing=meta.tod_pointing, - ignore_north_south=ignore_north_south ) dst = base_resset match = dm.Match(src, dst, match_pars=match_pars) @@ -419,7 +417,6 @@ def match_wafer( am: AxisManager, stream_id: str, meas_rset: Optional[dm.ResSet], - ignore_north_south: bool = False ) -> MatchSolution: """ Create a match solution for a given wafer slot. @@ -445,12 +442,11 @@ def match_wafer( am, stream_id, pointing=am[cfg.pointing_field], - ignore_north_south=ignore_north_south ) else: src = meas_rset - if ignore_north_south: + if wafer_slot == "ws.": wafer_slots = [] wafers_dict = {} @@ -482,7 +478,6 @@ def match_wafer( cfg.wafer_info_path, stream_id, pt_cfg=pt_cfg, - ignore_north_south=ignore_north_south, ).as_array() # extract current wafer @@ -496,12 +491,11 @@ def match_wafer( # get full wafer info and populate pointing and wafer_slot information # from merged dst (not necesary if matching a single wafer) - if ignore_north_south: + if wafer_slot == "ws.": dst = dm.ResSet.from_wafer_info_file( cfg.wafer_info_path, stream_id, pt_cfg=None, - ignore_north_south=ignore_north_south, ).as_array() merge_fields = ["xi", "eta", "wafer_slot"] @@ -645,12 +639,8 @@ def get_wafer_solution( else: base_idx = 0 - # Whether or not to use North/South in match - ignore_north_south = (wafer_slot == "ws.") - meas_rset, pointing_map = merge_pointing_info( cfg, pointing_results, base_idx=base_idx, - ignore_north_south=ignore_north_south ) meta = pointing_results[0].meta @@ -658,7 +648,6 @@ def get_wafer_solution( match_solution = match_wafer( cfg, meta, stream_id, meas_rset=meas_rset, - ignore_north_south=ignore_north_south ) solution = FullWaferSolution( diff --git a/sotodlib/site_pipeline/update_det_match.py b/sotodlib/site_pipeline/update_det_match.py index 373179ae1..8372c374e 100644 --- a/sotodlib/site_pipeline/update_det_match.py +++ b/sotodlib/site_pipeline/update_det_match.py @@ -254,9 +254,7 @@ def get_failed_detsets(cache_file): def run_match_aman(runner: Runner, aman, detset, wafer_slot=None): stream_id = aman.det_info.stream_id[aman.det_info.detset == detset][0] - ignore_north_south = True if wafer_slot == "ws." else False - - rs0 = det_match.ResSet.from_aman(aman, stream_id, ignore_north_south=ignore_north_south) + rs0 = det_match.ResSet.from_aman(aman, stream_id) rs0.name = 'meas' rs1 = load_solution_set(runner, stream_id, wafer_slot=wafer_slot) From 5244de64deb092dc0753563eeb76a26656e47018 Mon Sep 17 00:00:00 2001 From: Michael McCrackan Date: Mon, 23 Nov 2026 11:44:42 -0800 Subject: [PATCH 19/20] parallelize update_det_match --- sotodlib/coords/det_match.py | 17 +- sotodlib/site_pipeline/update_det_match.py | 253 +++++++++++++++------ 2 files changed, 193 insertions(+), 77 deletions(-) diff --git a/sotodlib/coords/det_match.py b/sotodlib/coords/det_match.py index 16e2c06ec..75d784407 100644 --- a/sotodlib/coords/det_match.py +++ b/sotodlib/coords/det_match.py @@ -357,13 +357,11 @@ def from_aman(cls, aman, stream_id, det_cal=None, name=None, north_is_highband = get_north_is_highband( aman.det_info.smurf.band[m], det_cal.bg[m] ) - is_norths = [] resonators = [] for i, ri in enumerate(np.where(m)[0]): band, channel = aman.det_info.smurf.band[ri], aman.det_info.smurf.channel[ri] if aman.det_info.wafer_slot[ri] != "ws.": is_north = north_is_highband ^ (band < 4) - is_norths.append(int(is_north)) else: is_north = 1 readout_id = aman.det_info.readout_id[ri] @@ -494,12 +492,12 @@ def from_wafer_info_file(cls, wafer_info_file, array_name, name=None, optional_fields = { "det_row": (has_det_row, 'dets:wafer.det_row'), "det_col": (has_det_col, 'dets:wafer.det_col'), - "rhombus": (has_rhomb, 'dets:wafer.rhombus'), + "det_rhomb": (has_rhomb, 'dets:wafer.rhombus'), } for key, (found, val) in optional_fields.items(): - if found and field in r.dtype.names: - kwargs[key] = val + if found and val in r.dtype.names: + kwargs[key] = r[val] res = Resonator(**kwargs) @@ -516,9 +514,9 @@ def from_solutions(cls, sol_file, north_is_highband=True, name=None, fp_pars=None, platform='LAT', zemax_path=None, ignore_north_south=False): """ - Creates an instance from an input-solution file. This will include both design data, along with smurf-band - and smurf-channel info. Resonance frequencies used here are the VNA - freqs measured by Kaiwen. + Creates an instance from an input-solution file. This will include + both design data, along with smurf-band and smurf-channel info. + Resonance frequencies used here are the VNA freqs measured by Kaiwen. Args: sol_file (str): @@ -722,7 +720,7 @@ class MatchParams: unmatched_good_res_pen: float = 10. good_res_qi_thresh: float = 100e3 enforce_pointing_reqs: bool = False - allow_unassigned_to_assigned: bool = True + allow_unassigned_to_assigned: bool = False assigned_bg_unmatched_pen: float = 100000 unassigned_bg_unmatched_pen: float = 10000 @@ -812,6 +810,7 @@ def _get_biadjacency_matrix(self) -> np.ndarray: m = src_arr['is_north'][:, None] != dst_arr['is_north'][None, :] mat[m] = np.inf + # Don't match NC det type (placeholder row in wafer_info files) src_no_match = np.isin(src_arr['det_type'], ['NC']) dst_no_match = np.isin(dst_arr['det_type'], ['NC']) mat[src_no_match, :] = np.inf diff --git a/sotodlib/site_pipeline/update_det_match.py b/sotodlib/site_pipeline/update_det_match.py index 8372c374e..a3e48a6e9 100644 --- a/sotodlib/site_pipeline/update_det_match.py +++ b/sotodlib/site_pipeline/update_det_match.py @@ -10,21 +10,18 @@ import logging import argparse import time +import uuid from sotodlib.coords import det_match, optics from sotodlib.coords.det_match_solutions import SolutionsCfg, solve_all from sotodlib import core from sotodlib.core.metadata import ManifestDb from sotodlib.io.metadata import write_dataset +from sotodlib.site_pipeline.utils.logging import init_logger +from sotodlib.utils.procs_pool import get_exec_env -logger = logging.getLogger("update_det_match") -if len(logger.handlers) == 0: - fmt = logging.Formatter("%(asctime)s %(levelname)s %(name)s : %(message)s") - handler = logging.StreamHandler() - handler.setFormatter(fmt) - logger.addHandler(handler) -logger.setLevel(logging.INFO) +logger = init_logger("update_det_match", "update-det-match: ") def get_detset_time(detset: str) -> float: @@ -202,7 +199,7 @@ def get_remaining_detsets(self) -> List[str]: detsets_all = set([d for t, d in zip(ts, detsets_all) if t > self.cfg.start_time and t < self.cfg.stop_time]) failed_detsets = set(get_failed_detsets(self.failed_detset_cache_path)) finished_detsets = set([os.path.splitext(f)[0] for f in os.listdir(self.match_dir)]) - remaining_detsets = list(detsets_all - failed_detsets - finished_detsets) + remaining_detsets = np.sort(list(detsets_all - failed_detsets - finished_detsets)) return remaining_detsets def load_solution_set(runner: Runner, stream_id: str, wafer_slot=None): @@ -234,7 +231,7 @@ def add_to_failed_cache(cache_file, detset, msg, cfg: UpdateDetMatchesConfig): if os.path.exists(cache_file): with open(cache_file, 'r') as f: - x = yaml.safe_load(f) + x = yaml.safe_load(f) or {} else: x = {} @@ -273,22 +270,23 @@ def run_match_aman(runner: Runner, aman, detset, wafer_slot=None): return match -def run_match(runner: Runner, detset: str) -> bool: +def _run_match_core(runner: Runner, detset: str): """ Find the observation with the highest number of non-NC detectors for the requested detset and run detector matching. Returns ------- - success: bool - True if match was successful + success, failure_reason : tuple[bool, str or None] + Failure reason is only set when the old code would add the detset + to failed_detsets.yaml. The caller owns cache updates. """ fpath = os.path.join(runner.match_dir, f"{detset}.h5") if os.path.exists(fpath): logger.info(f"Match already exists for {detset}") - return True + return True, None obs_all = set( runner.ctx.obsdb.query("type=='obs'")["obs_id"] @@ -312,14 +310,8 @@ def run_match(runner: Runner, detset: str) -> bool: ) if not obs_ids: - add_to_failed_cache( - runner.failed_detset_cache_path, - detset, - "NO_OBSID_WITH_CAL", - runner.cfg, - ) logger.error(f"Cannot find obsid for detset {detset}") - return False + return False, "NO_OBSID_WITH_CAL" logger.info( f"Searching {len(obs_ids)} observations for detset {detset}" @@ -354,18 +346,22 @@ def run_match(runner: Runner, detset: str) -> bool: # there will be many spurious entries with wrong bgs. bad_bg = False for bp in np.unique(bandpass[good]): - design_yield = np.count_nonzero(wafer_info_dataset[stream_id]['dets:wafer.bandpass'] == bp) + design_yield = np.count_nonzero(runner.wafer_info_dataset[stream_id]['dets:wafer.bandpass'].astype(str) == bp) det_cal_yield = np.count_nonzero(bandpass[good] == bp) + logger.info(f"{obs_id} {bp} yields: {det_cal_yield} / {design_yield}") if det_cal_yield > design_yield: bad_bg = True break if bad_bg: - logger.warnining(f"{obs_id} and {detset} yield surpasses design yield. skipping.") + logger.warning( + f"{obs_id} and {detset} yield surpasses design yield; " + "skipping." + ) continue n_good = int(np.count_nonzero(good)) - n_total = int(np.count_nonzero(aman.dets.count)) + n_total = aman.dets.count if n_total == 0: continue @@ -397,7 +393,7 @@ def run_match(runner: Runner, detset: str) -> bool: logger.error( f"No usable detector calibration metadata found for {detset}" ) - return False + return False, None logger.info( f"Selected obs_id {best_obs_id} for {detset}: " @@ -418,17 +414,67 @@ def run_match(runner: Runner, detset: str) -> bool: f"{stream_id} | {wafer_slot} | {best_obs_id}" ) - match = run_match_aman( - runner, - best_aman, - detset, - wafer_slot=wafer_slot, - ) + try: + match = run_match_aman( + runner, + best_aman, + detset, + wafer_slot=wafer_slot, + ) + + # Publish only complete files. This prevents the parent process + # from indexing an HDF5 file still being written by a worker. + pending_dir = os.path.join(runner.cfg.results_path, ".pending_matches") + os.makedirs(pending_dir, exist_ok=True) + pending_file = os.path.join( + pending_dir, f"{detset}.{uuid.uuid4().hex}.h5" + ) + try: + match.save(pending_file) + os.replace(pending_file, fpath) + finally: + if os.path.exists(pending_file): + os.remove(pending_file) + + logger.info(f"Saved match to file: {fpath}") + except Exception as e: + logger.warning( + f"run_match_aman failed for {detset}: {e}" + ) + return False, None + + return True, None + - match.save(fpath) - logger.info(f"Saved match to file: {fpath}") +def run_match(runner: Runner, detset: str) -> bool: + """Run a single detset serially, retaining the original bool API.""" + success, failure_reason = _run_match_core(runner, detset) + if failure_reason is not None: + add_to_failed_cache( + runner.failed_detset_cache_path, detset, failure_reason, runner.cfg + ) + return success + + +# Worker processes keep their own Context / SQLite connections; never pass +# a parent Runner into a process pool. Reuse the Runner across detsets that +# land on the same worker, rather than reloading wafer data for each task. +_WORKER_RUNNER = None +_WORKER_CONFIG_FILE = None + + +def _run_match_worker(config_file: str, detset: str): + """Execute one detset without writing any shared manifests or cache.""" + global _WORKER_RUNNER, _WORKER_CONFIG_FILE - return True + if _WORKER_RUNNER is None or _WORKER_CONFIG_FILE != config_file: + with open(config_file) as f: + cfg = UpdateDetMatchesConfig(**yaml.safe_load(f)) + _WORKER_RUNNER = Runner(cfg) + _WORKER_CONFIG_FILE = config_file + + success, reason = _run_match_core(_WORKER_RUNNER, detset) + return detset, success, reason def scan_for_freq_offset(rs0, rs1, freq_offsets, match_pars=None, show_pb=True): @@ -523,7 +569,10 @@ def update_manifests_all(runner): assignment_detsets = [] indexed_detsets = set(det_match_detsets).intersection(set(assignment_detsets)) - completed_detsets = set([os.path.splitext(f)[0] for f in os.listdir(runner.match_dir)]) + completed_detsets = { + os.path.splitext(f)[0] for f in os.listdir(runner.match_dir) + if f.endswith(".h5") and os.path.isfile(os.path.join(runner.match_dir, f)) + } for ds in (completed_detsets - indexed_detsets): logger.info(f"Adding {ds} to manifests") @@ -535,52 +584,120 @@ def get_parser(parser=None): parser = argparse.ArgumentParser() parser.add_argument('config_file', type=str, help='path to config file') parser.add_argument('--run-all', action='store_true', help='run all detsets') + parser.add_argument('--nproc', type=int, default=4, + help='number of worker processes for --run-all (default: 4)') parser.add_argument('--solutions-mode', action='store_true', help='create a det_match solution set') return parser -def main(config_file: str, run_all: bool=False, solutions_mode: bool=False): - """ - Site-pipeline script to peform detector matching of tunesets to a solution - set. +def _main_detsets(config_file: str, run_all: bool, executor=None, + as_completed_callable=None): + """Parent process owns shared manifests and failed-detset cache updates.""" + with open(config_file) as f: + cfg = UpdateDetMatchesConfig(**yaml.safe_load(f)) - ------ - config_file: str - Yaml configuration file for tuneset matching (or solution set matching - if solutions_mode is True). - run_all: bool - Run all detsets if True, otherwise exit after first successful match. - solutions_mode: bool - Create a det_match solution instead of matching a solution to a tuneset. - Requires a solutions configuration file. - """ + runner = Runner(cfg) + remaining_detsets = [str(d) for d in runner.get_remaining_detsets()] + logger.info(f"{len(remaining_detsets)} detsets to match") + + # Complete any indexing left from prior runs before starting workers. + if run_all: + update_manifests_all(runner) + + # Preserve the prior run_all=False behavior: stop at first success. + if not run_all: + for detset in remaining_detsets: + success = run_match(runner, detset) + update_manifests_all(runner) + if success: + break + return + + futures = { + executor.submit(_run_match_worker, config_file, detset): detset + for detset in remaining_detsets + } + n_success = 0 + n_failed = 0 + n_manifest_failed = 0 + + for future in tqdm( + as_completed_callable(futures), total=len(futures), + desc="Matching detsets", disable=not bool(futures), + ): + detset = futures[future] + try: + returned_detset, success, failure_reason = future.result() + if returned_detset != detset: + raise RuntimeError( + f"Worker returned detset {returned_detset} for {detset}" + ) + except Exception: + n_failed += 1 + logger.exception(f"Worker failed for {detset}") + continue + + # Workers only write matches/.h5. The parent alone edits + # failed_detsets.yaml, det_match.h5, assignment.h5 and their SQLite DBs. + if failure_reason is not None: + add_to_failed_cache( + runner.failed_detset_cache_path, detset, failure_reason, cfg + ) + + if success: + n_success += 1 + try: + # Index only this COMPLETED match, not other workers' + # still-open files that may be visible in matches/. + update_manifests(runner, detset) + except Exception: + n_manifest_failed += 1 + logger.exception(f"Manifest update failed for {detset}") + else: + n_failed += 1 + + # Index any successfully written results whose manifest updates failed, + # and catch up on pre-existing finished outputs. All tasks are complete. + update_manifests_all(runner) + logger.info( + f"Detset matching finished: {n_success} succeeded, " + f"{n_failed} failed, {n_manifest_failed} manifest update errors" + ) + + +def main(config_file: str, run_all: bool = False, + solutions_mode: bool = False, nproc: int = 4): + """Match detsets, parallelizing --run-all using sotodlib's executor.""" if solutions_mode: - with open(config_file, "r") as f: + # Unchanged: solutions mode is not parallelized here. + with open(config_file) as f: cfg = SolutionsCfg(**yaml.safe_load(f)) solve_all(cfg) - else: - with open(config_file, 'r') as f: - cfg = UpdateDetMatchesConfig(**yaml.safe_load(f)) + return - runner = Runner(cfg) + config_file = os.path.abspath(config_file) + + if not run_all: + _main_detsets(config_file, run_all=False) + return + + rank, executor, as_completed_callable = get_exec_env(nproc) + if rank == 0: + try: + _main_detsets( + config_file, run_all=True, executor=executor, + as_completed_callable=as_completed_callable, + ) + finally: + if executor is not None: + executor.shutdown(wait=True) - remaining_detsets = runner.get_remaining_detsets() - logger.info(f"{len(remaining_detsets)} detsets to match") - if run_all: - update_manifests_all(runner) - for detset in remaining_detsets: - logger.info(f"running: {detset}") - run_match(runner, detset) - update_manifests_all(runner) - else: - for detset in remaining_detsets: - success = run_match(runner, detset) - update_manifests_all(runner) - if success: - break if __name__ == '__main__': parser = get_parser() args = parser.parse_args() - main(args.config_file, run_all=args.run_all, solutions_mode=args.solutions_mode) + main( + args.config_file, run_all=args.run_all, + solutions_mode=args.solutions_mode, nproc=args.nproc, + ) From 6b5629f7ce359d866937f96b72296811d699d116 Mon Sep 17 00:00:00 2001 From: Michael McCrackan Date: Mon, 23 Nov 2026 21:46:19 -0800 Subject: [PATCH 20/20] search for init pointing offset, remove linear fit from mux band freqs, only use OPTC matches for offsets --- sotodlib/coords/det_match.py | 58 +- sotodlib/coords/det_match_solutions.py | 960 +++++++++++++++++++++++-- sotodlib/coords/optics.py | 4 +- 3 files changed, 950 insertions(+), 72 deletions(-) diff --git a/sotodlib/coords/det_match.py b/sotodlib/coords/det_match.py index 75d784407..14dabcd40 100644 --- a/sotodlib/coords/det_match.py +++ b/sotodlib/coords/det_match.py @@ -39,7 +39,7 @@ def map_band_chans(b1, c1, b2, c2, chans_per_band=512): mapping = np.full_like(acs1, -1, dtype=int) for i, ac in enumerate(acs1): x = np.where(acs2 == ac)[0] - if len(x > 0): + if x.size > 0: mapping[i] = x[0] return mapping @@ -569,7 +569,7 @@ def _int(val, null_val=None): is_optical = (d['is_optical'].lower() == 'true') kwargs = dict( - i=i, + idx=i, res_freq=float(d['freq_mhz']), smurf_band=_int(d['smurf_band']), bg=_int(d['bias_line']), @@ -820,7 +820,6 @@ def _get_biadjacency_matrix(self) -> np.ndarray: # Det types of DARK and SLOT are allowed to may or may not have # pointing data. For these types of detectors, the cost is left # untouched. - src_has_pointing = np.isfinite(src_arr['xi']) & np.isfinite(src_arr['eta']) dst_has_pointing = np.isfinite(dst_arr['xi']) & np.isfinite(dst_arr['eta']) @@ -852,11 +851,6 @@ def _get_biadjacency_matrix(self) -> np.ndarray: m = dst_unassigned_type[None, :] & (src_arr['bg'][:, None] !=-1) mat[m] = np.inf - # Frequency offset - df = src_arr['res_freq'][:, None] - dst_arr['res_freq'][None, :] - df -= self.match_pars.freq_offset_mhz - mat += np.exp((np.abs(df / self.match_pars.freq_width)) ** 2) - # Design or pointing unassigned dst_unassigned = (dst_arr['bg'][None, :] == -1) # pointing or tune unassigned @@ -879,6 +873,11 @@ def _get_biadjacency_matrix(self) -> np.ndarray: m = bgs_mismatch & (~dst_unassigned) & (~src_unassigned) mat[m] = np.inf + # Frequency offset + df = src_arr['res_freq'][:, None] - dst_arr['res_freq'][None, :] + df -= self.match_pars.freq_offset_mhz + mat += np.exp((np.abs(df / self.match_pars.freq_width)) ** 2) + # If pointing, add cost if assigned too far dd = np.sqrt( (src_arr['xi'][:, None] - dst_arr['xi'][None, :])**2 \ @@ -909,7 +908,7 @@ def _get_unassigned_costs(self, rs): def _match(self): - nside = max(len(self.src), len(self.dst)) + self.match_pars.unassigned_slots + nside = len(self.src) + len(self.dst) # Keep this square so all resonators are included in final matching mat_full = np.zeros((nside, nside), dtype=float) @@ -1022,11 +1021,16 @@ def get_stats(self) -> MatchingStats: if (~np.isnan(dangs)).any(): stats.pointing_err_avg = np.nanmean(dangs) - stats.freq_diff_avg /= stats.matched_chans - stats.freq_diff_avg = float(stats.freq_diff_avg) - - stats.freq_err_avg /= stats.matched_chans - stats.freq_err_avg = float(stats.freq_err_avg) + if stats.matched_chans: + stats.freq_diff_avg = float( + stats.freq_diff_avg / stats.matched_chans + ) + stats.freq_err_avg = float( + stats.freq_err_avg / stats.matched_chans + ) + else: + stats.freq_diff_avg = np.nan + stats.freq_err_avg = np.nan return stats @@ -1035,6 +1039,8 @@ def save(self, path): with h5py.File(path, 'w') as fout: fout.create_group('meta') fout.create_group('meta/match_pars') + fout['meta/matching_cost'] = self.matching_cost + fout['meta/apply_dst_pointing'] = self.apply_dst_pointing for k, v in asdict(self.match_pars).items(): fout['meta/match_pars'][k] = v if self.src.name is not None: @@ -1070,7 +1076,27 @@ def load(cls, path): else: match_pars[k] = f['meta/match_pars'][k][()] match_pars = MatchParams(**match_pars) - match = cls(src, dst, match_pars=match_pars) + matching = np.asarray(f['matching'], dtype=int) + merged = ResSet.from_array(np.array(f['merged']), name='merged') + matching_cost = ( + float(f['meta/matching_cost'][()]) + if 'meta/matching_cost' in f else np.nan + ) + apply_dst_pointing = ( + bool(f['meta/apply_dst_pointing'][()]) + if 'meta/apply_dst_pointing' in f else True + ) + + # Restore the saved solution without rerunning the assignment. + match = cls.__new__(cls) + match.src = src + match.dst = dst + match.match_pars = match_pars + match.apply_dst_pointing = apply_dst_pointing + match.matching = matching + match.matching_cost = matching_cost + match.merged = merged + match.stats = match.get_stats() return match @@ -1087,7 +1113,7 @@ def plot_match_freqs(m: Match, is_north=True, show_offset=False, xlim=None): else: offset = 0 - yw= 0.4 + yw = 0.4 def plot_res(ax, r: Resonator, y=0, offset=0): if r is None: return diff --git a/sotodlib/coords/det_match_solutions.py b/sotodlib/coords/det_match_solutions.py index 43536d7dd..2022ac017 100644 --- a/sotodlib/coords/det_match_solutions.py +++ b/sotodlib/coords/det_match_solutions.py @@ -5,8 +5,13 @@ from collections import defaultdict import os import numpy as np +import matplotlib.pyplot as plt +from matplotlib.collections import LineCollection +from matplotlib.lines import Line2D +import matplotlib.patheffects as pe import yaml from scipy import interpolate +from scipy.stats import theilslopes from tqdm.auto import tqdm, trange from copy import deepcopy @@ -81,13 +86,22 @@ class SolutionsCfg: initial_pointing_offset : Tuple[float, float] Estimated pointing offset for the boresight. This should be - (xi_offset, eta_offset) where both are in radians. + (xi_offset, eta_offset) where both are in degrees. ufm_to_fp_path : str Path to file that maps wafer_slot to position on focal plane. fp_to_rx_path: str Path to file that maps tube slot to position on focal plane. freq_correct_by_muxband: bool If true, apply the same freq offset correction to all resonators in a mux-band. + match_plot_color_by: str + Color the residual scatter plots by "north_south" or "det_type". + initial_offset_search_x_range_args, initial_offset_search_y_range_args: tuple + Arguments passed to np.arange to establish the allowed xi/eta ranges. + Offsets are additional shifts in degrees relative to the configured + initial_pointing_offset. + initial_offset_search_levels: int + Number of 2D interval-halving steps. Each step tests at most 9 points. + Search minimizes Match 0 matching_cost with frequency effectively disabled. """ ctx_path: str @@ -116,6 +130,26 @@ class SolutionsCfg: fp_to_rx_path: Optional[str] = None imprinter_path: Optional[str] = None freq_correct_by_muxband: bool = True + # Correction to DESIGN frequencies, fitted from matched OPTC only. + # "linear" fits a per-N/S, per-mux-band offset and slope. + # "median" retains a constant per-band correction for comparison. + freq_correction_model: str = "linear" # "linear" or "median" + freq_fit_min_matches: int = 20 + freq_fit_min_span_mhz: float = 20.0 + freq_fit_clip_sigma: float = 3.0 + freq_fit_clip_floor_mhz: float = 2.0 + freq_fit_max_iterations: int = 6 + freq_fit_max_abs_slope: float = 0.25 + show_match_plots: bool = True # Display interactive diagnostics after each match + match_plot_color_by: str = "north_south" # "north_south" or "det_type" + + # Search xi/eta before Match 0 using progressively halved 2D intervals. + # np.arange args establish the bounds; the step is not used as the search + # spacing. Frequency is effectively ignored during the search. + search_initial_pointing_offset: bool = True + initial_offset_search_x_range_args: Tuple[float, float, float] = (-0.06, 0.061, 0.01) + initial_offset_search_y_range_args: Tuple[float, float, float] = (-0.06, 0.061, 0.01) + initial_offset_search_levels: int = 6 ctx: Context = field(init=False) wafer_map: Dict[str, dict] = field(init=False) @@ -130,6 +164,37 @@ def from_yaml(cls, path: str) -> "SolutionsCfg": return cls.from_dict(yaml.safe_load(f)) def __post_init__(self): + if self.match_plot_color_by not in ("north_south", "det_type"): + raise ValueError( + "match_plot_color_by must be 'north_south' or 'det_type'" + ) + if self.freq_correction_model not in ("linear", "median"): + raise ValueError("freq_correction_model must be 'linear' or 'median'") + if self.freq_fit_min_matches < 2: + raise ValueError("freq_fit_min_matches must be >= 2") + if self.freq_fit_min_span_mhz <= 0: + raise ValueError("freq_fit_min_span_mhz must be positive") + if self.freq_fit_clip_sigma <= 0 or self.freq_fit_clip_floor_mhz < 0: + raise ValueError("frequency fit clipping settings must be nonnegative") + if self.freq_fit_max_iterations < 1: + raise ValueError("freq_fit_max_iterations must be >= 1") + if not 0 < self.freq_fit_max_abs_slope < 1: + raise ValueError("freq_fit_max_abs_slope must be between 0 and 1") + if self.search_initial_pointing_offset: + if self.initial_offset_search_levels < 1: + raise ValueError("initial_offset_search_levels must be >= 1") + for name, args in ( + ("initial_offset_search_x_range_args", self.initial_offset_search_x_range_args), + ("initial_offset_search_y_range_args", self.initial_offset_search_y_range_args), + ): + if not 1 <= len(args) <= 3: + raise ValueError(f"{name} must contain 1 to 3 np.arange arguments") + try: + values = np.arange(*args) + except (TypeError, ValueError, ZeroDivisionError) as exc: + raise ValueError(f"Invalid {name}: {args}") from exc + if not values.size or not np.isfinite(values).all(): + raise ValueError(f"{name} must produce a nonempty, finite array") self.ctx = Context(self.ctx_path) if self.wafer_slots is None: @@ -229,8 +294,8 @@ def pointing_preprocess(cfg: SolutionsCfg, pinfo: PointingInfo): theta = 0 offset = cfg.initial_pointing_offset - _xi += offset[0] - _eta += offset[1] + _xi += np.radians(offset[0]) + _eta += np.radians(offset[1]) xi = _xi * np.cos(theta) - _eta * np.sin(theta) eta = _xi * np.sin(theta) + _eta * np.cos(theta) @@ -343,32 +408,74 @@ class MatchSolution: match: dm.Match am: AxisManager match_iterations: List[dm.Match] = field(default_factory=list) + # Effective starting offset in degrees, including the grid-search adjustment. + best_initial_pointing_offset: Optional[Tuple[float, float]] = None + initial_offset_search: Optional[dict] = None + + +def _optical_pointing_pairs(match): + """Yield matched OPTC design detectors with finite pointing on both sides. + + Only these pairs are permitted to determine pointing corrections. + The resulting corrections are still applied to all measured resonators. + """ + for rsrc, rdst in match.get_match_iter(include_unmatched=False): + if _det_type_label(rdst.det_type) != "OPTC": + continue + if not np.isfinite([rsrc.xi, rsrc.eta, rdst.xi, rdst.eta]).all(): + continue + yield rsrc, rdst def get_pt_offset_interp(match, sel_rad=np.deg2rad(2)) -> Tuple[Any, Any]: - _xis, _etas, _dxis, _detas = [], [], [], [] - for r1, r2 in match.get_match_iter(include_unmatched=False): - _xis.append(r1.xi) - _etas.append(r1.eta) - _dxis.append(r1.xi - r2.xi) - _detas.append(r1.eta - r2.eta) - xis = np.array(_xis) - etas = np.array(_etas) - dxis = np.array(_dxis) - detas = np.array(_detas) - - xi_list = np.arange(np.nanmin(xis), np.nanmax(xis), sel_rad / 2) - eta_list = np.arange(np.nanmin(etas), np.nanmax(etas), sel_rad / 2) + """Interpolate measured minus design pointing offsets using OPTC pairs only. + + Other detector types never contribute to the interpolation, but the + returned interpolators can be evaluated for any measured resonator with + finite xi/eta. Empty local neighborhoods fall back to the median optical + offset, so they do not propagate NaNs into other detectors' pointing. + """ + if not np.isfinite(sel_rad) or sel_rad <= 0: + raise ValueError("sel_rad must be finite and positive") + + pairs = list(_optical_pointing_pairs(match)) + if not pairs: + raise ValueError( + "Cannot estimate spatial pointing offsets: no matched OPTC " + "detectors have finite measured and design xi/eta" + ) + + xis = np.array([rsrc.xi for rsrc, _ in pairs], dtype=float) + etas = np.array([rsrc.eta for rsrc, _ in pairs], dtype=float) + dxis = np.array([rsrc.xi - rdst.xi for rsrc, rdst in pairs], dtype=float) + detas = np.array([rsrc.eta - rdst.eta for rsrc, rdst in pairs], dtype=float) + + step = sel_rad / 2 + xi_list = np.arange(np.min(xis), np.max(xis) + step, step) + eta_list = np.arange(np.min(etas), np.max(etas) + step, step) + if xi_list.size < 2: + xi_list = np.array([xis[0] - step / 2, xis[0] + step / 2]) + if eta_list.size < 2: + eta_list = np.array([etas[0] - step / 2, etas[0] + step / 2]) + xi_grid, eta_grid = np.meshgrid(xi_list, eta_list) - dxi_data = np.full_like(xi_grid, np.nan) - deta_data = np.full_like(eta_grid, np.nan) + dxi_data = np.empty_like(xi_grid) + deta_data = np.empty_like(eta_grid) + default_dxi = np.median(dxis) + default_deta = np.median(detas) + n_fallback = 0 + for i, j in np.ndindex(xi_grid.shape): - sel = ( - np.sqrt((xis - xi_grid[i, j]) ** 2 + (etas - eta_grid[i, j]) ** 2) < sel_rad - ) - sel &= np.isfinite(dxis) & np.isfinite(detas) - dxi_data[i, j] = np.nanmedian(dxis[sel]) - deta_data[i, j] = np.nanmedian(detas[sel]) + select = np.hypot( + xis - xi_grid[i, j], etas - eta_grid[i, j] + ) < sel_rad + if np.any(select): + dxi_data[i, j] = np.median(dxis[select]) + deta_data[i, j] = np.median(detas[select]) + else: + dxi_data[i, j] = default_dxi + deta_data[i, j] = default_deta + n_fallback += 1 dxi_interp = interpolate.RegularGridInterpolator( (xi_list, eta_list), dxi_data.T, bounds_error=False, fill_value=None @@ -412,6 +519,714 @@ class MatchSolutionResult: traceback: Optional[str] = None +# Consistent colors across iterations and across the two diagnostic figures. +MATCH_PLOT_COLORS = { + "north_south": { + "South": "tab:blue", + "North": "tab:orange", + }, + "det_type": { + "OPTC": "tab:blue", + "DARK": "tab:orange", + "SQID": "tab:green", + "BARE": "tab:red", + "UNRT": "tab:purple", + "SLOT": "tab:brown", + "NC": "tab:gray", + "UNMATCHED": "0.7", + "UNKNOWN": "tab:pink", + }, +} + + +def _det_type_label(value): + """Normalize detector-type labels, including bytes from HDF5.""" + if isinstance(value, bytes): + value = value.decode("utf-8", errors="replace") + return str(value).strip().upper() or "UNKNOWN" + + +def _plot_label(resonator, color_by): + if color_by == "north_south": + return "North" if resonator.is_north else "South" + if color_by == "det_type": + return _det_type_label(resonator.det_type) + raise ValueError(f"Invalid color_by: {color_by}") + + +def _plot_color(label, color_by): + return MATCH_PLOT_COLORS[color_by].get(label, "tab:cyan") + + +def _plot_groups(ax, xs, ys, labels, valid, color_by, **scatter_kwargs): + """Scatter finite values by category, retaining a category legend.""" + labels = np.asarray(labels) + for label in sorted(set(labels[valid])): + sel = valid & (labels == label) + ax.scatter( + xs[sel], ys[sel], + color=_plot_color(label, color_by), + label=label, + **scatter_kwargs, + ) + + + +def _fit_mux_frequency_offset(measured, design, cfg): + """Fit design - measured = offset + slope*(measured - f0). + + Uses an initial Theil-Sen fit and iteratively sigma-clipped least squares + on matched OPTC pairs. Returns None for sparse or unreliable groups. + """ + measured = np.asarray(measured, dtype=float) + design = np.asarray(design, dtype=float) + valid = np.isfinite(measured) & np.isfinite(design) + if valid.sum() < cfg.freq_fit_min_matches: + return None + + f_meas = measured[valid] + residual = (design - measured)[valid] + span = np.ptp(f_meas) + if cfg.freq_correction_model == "linear" and span < cfg.freq_fit_min_span_mhz: + return None + + f0 = float(np.median(f_meas)) + x = f_meas - f0 + + if cfg.freq_correction_model == "median": + offset = float(np.median(residual)) + return dict(f0=f0, offset=offset, slope=0.0, + inliers=np.ones(len(x), dtype=bool)) + + try: + slope, offset, _, _ = theilslopes(residual, x) + except (ValueError, FloatingPointError) as exc: + return None + if not np.isfinite([slope, offset]).all(): + return None + + inliers = np.ones(len(x), dtype=bool) + for _ in range(cfg.freq_fit_max_iterations): + fit_residual = residual - (offset + slope * x) + center = np.median(fit_residual[inliers]) + mad = np.median(np.abs(fit_residual[inliers] - center)) + sigma = 1.4826 * mad + threshold = max(cfg.freq_fit_clip_floor_mhz, + cfg.freq_fit_clip_sigma * sigma) + new_inliers = np.abs(fit_residual - center) <= threshold + if new_inliers.sum() < cfg.freq_fit_min_matches: + return None + if np.ptp(x[new_inliers]) < cfg.freq_fit_min_span_mhz: + return None + new_slope, new_offset = np.polyfit(x[new_inliers], residual[new_inliers], 1) + converged = np.array_equal(new_inliers, inliers) + inliers = new_inliers + slope, offset = float(new_slope), float(new_offset) + if converged: + break + + if not np.isfinite([offset, slope]).all(): + return None + if abs(slope) > cfg.freq_fit_max_abs_slope: + return None + if 1 + slope <= 0: + return None + + return dict(f0=f0, offset=offset, slope=slope, inliers=inliers) + + +def _correct_design_frequency(f_design, fit): + """Invert the fitted design(measured) relation to find measured frequency. + + design = measured + offset + slope*(measured - f0) + => measured = f0 + (design - f0 - offset)/(1 + slope). + This exact inversion matters when fitting a nonzero slope. + """ + return fit["f0"] + ( + np.asarray(f_design) - fit["f0"] - fit["offset"] + ) / (1.0 + fit["slope"]) + + +def apply_muxband_frequency_correction(match, cfg, wafer_slot=""): + """Fit on matched OPTC only; correct ALL design detector types per group. + + Does not rematch, so before/after diagnostics refer to the exact same + original pairs. ``match._match()`` is called separately in Match 1. + """ + groups = defaultdict(list) + for src, dst in match.get_match_iter(include_unmatched=False): + if _det_type_label(dst.det_type) != "OPTC": + continue + if dst.mux_band is None or int(dst.mux_band) < 0: + continue + if np.isfinite([src.res_freq, dst.res_freq]).all(): + groups[(bool(dst.is_north), int(dst.mux_band))].append( + (float(src.res_freq), float(dst.res_freq)) + ) + + # Include groups with no valid OPTC pair in the report, but don't alter them. + dst_groups = defaultdict(list) + for dst in match.dst: + if dst.mux_band is None or int(dst.mux_band) < 0: + continue + dst_groups[(bool(dst.is_north), int(dst.mux_band))].append(dst) + + diagnostics = [] + for (north, mb), dests in sorted(dst_groups.items()): + pairs = groups.get((north, mb), []) + f_meas = np.array([x for x, _ in pairs], dtype=float) + f_design = np.array([y for _, y in pairs], dtype=float) + fit = _fit_mux_frequency_offset(f_meas, f_design, cfg) + if fit is None: + if len(pairs): + diagnostics.append(dict(north=north, mux_band=mb, + measured=f_meas, before=f_design - f_meas, + after=f_design - f_meas, fit=None)) + continue + + # Apply to ALL detector types, not just OPTC. + for dst in dests: + if np.isfinite(dst.res_freq): + dst.res_freq = float(_correct_design_frequency(dst.res_freq, fit)) + + after = _correct_design_frequency(f_design, fit) - f_meas + before = f_design - f_meas + n_inliers = int(fit["inliers"].sum()) + + diagnostics.append(dict(north=north, mux_band=mb, + measured=f_meas, before=before, after=after, + fit=fit)) + + return diagnostics + + +def plot_muxband_frequency_correction( + diagnostics, + wafer_slot="", + zoom_percentile=98.0, +): + """Show same matched OPTC pairs before/after frequency correction. + + The BEFORE panel overlays conspicuous, outlined fitted lines on muted + scatter points. Lines are drawn *after* all points so they cannot be + obscured. Colors encode mux band; line style/markers encode N/S. + + Parameters + ---------- + zoom_percentile : float or None + If a float between 50 and 100, use the central percentile range of + residuals for BOTH panels' y limits, clipping extreme outliers only + in the display. Use None to show all residuals. This does not affect + fitting or the frequency correction. + """ + if not diagnostics: + return + + fig, axs = plt.subplots( + 1, 2, figsize=(17, 6.5), sharex=True, sharey=True, + constrained_layout=True, + ) + cmap = plt.get_cmap("tab20") + n_fits = 0 + all_residuals = [] + + # Draw scatter points first; intentionally subtle so the lines stand out. + for record in diagnostics: + x = np.asarray(record["measured"], dtype=float) + mb = record["mux_band"] + north = record["north"] + color = cmap(mb % 20) + marker = "^" if north else "o" + + for ax, name in zip(axs, ("before", "after")): + y = np.asarray(record[name], dtype=float) + valid = np.isfinite(x) & np.isfinite(y) + if np.any(valid): + all_residuals.append(y[valid]) + ax.scatter( + x[valid], y[valid], color=color, s=10, alpha=0.23, + marker=marker, linewidths=0, rasterized=True, zorder=2, + ) + + # Draw ALL fit lines last, with a thick contrasting outline above points. + for record in diagnostics: + fit = record["fit"] + x = np.asarray(record["measured"], dtype=float) + if fit is None or x.size < 2: + continue + + # Show line only where optical inliers constrain the fit. + inliers = np.asarray(fit["inliers"], dtype=bool) + valid = np.isfinite(x) & inliers + if valid.sum() < 2: + continue + xx = np.linspace(np.min(x[valid]), np.max(x[valid]), 200) + yy = fit["offset"] + fit["slope"] * (xx - fit["f0"]) + + color = cmap(record["mux_band"] % 20) + north = record["north"] + line, = axs[0].plot( + xx, yy, color=color, lw=3.2, + ls="-" if north else "--", alpha=1.0, zorder=20, + ) + line.set_path_effects([ + pe.Stroke(linewidth=6.5, foreground="white"), + pe.Normal(), + ]) + n_fits += 1 + + if all_residuals and zoom_percentile is not None: + if not 50 < zoom_percentile < 100: + raise ValueError("zoom_percentile must be between 50 and 100, or None") + residuals = np.concatenate(all_residuals) + lo, hi = np.percentile(residuals, [100 - zoom_percentile, zoom_percentile]) + lo, hi = min(lo, 0), max(hi, 0) + if hi > lo: + pad = 0.12 * (hi - lo) + axs[0].set_ylim(lo - pad, hi + pad) + + for ax, label in zip(axs, ("Before", "After")): + ax.axhline(0, color="0.45", lw=1, zorder=1) + ax.set_xlabel("Measured resonance frequency (MHz)") + ax.set_title(label) + ax.grid(alpha=0.2, zorder=0) + axs[0].set_ylabel("Design - measured (MHz)") + + # Small style legend: line colors are the corresponding mux-band colors. + fit_handles = [ + Line2D([0], [0], color="0.2", lw=3, ls="-", label="North"), + Line2D([0], [0], color="0.2", lw=3, ls="--", label="South"), + ] + axs[0].legend(handles=fit_handles, loc="upper left", fontsize=9) + + fig.suptitle(f"{wafer_slot} | Frequency fit | {n_fits} groups") + if n_fits == 0: + axs[0].text( + 0.5, 0.95, "No accepted fits", + transform=axs[0].transAxes, ha="center", va="top", fontsize=10, + bbox=dict(facecolor="white", alpha=0.85, edgecolor="0.7"), + ) + plt.show() + +def summarize_optical_frequency_slopes(match, stage, min_matches=20): + """Report per-group frequency residual slopes AFTER assignments are recomputed.""" + groups = defaultdict(list) + for src, dst in match.get_match_iter(include_unmatched=False): + if _det_type_label(dst.det_type) != "OPTC" or dst.mux_band < 0: + continue + if np.isfinite([src.res_freq, dst.res_freq]).all(): + groups[(bool(dst.is_north), int(dst.mux_band))].append( + (float(src.res_freq), float(dst.res_freq - src.res_freq)) + ) + for (north, mb), pairs in sorted(groups.items()): + if len(pairs) < min_matches: + continue + xy = np.asarray(pairs) + f, df = xy[:, 0], xy[:, 1] + slope = np.polyfit(f - np.median(f), df, 1)[0] + + +def plot_match_offsets( + match: dm.Match, + stage: str, + wafer_slot: str, + bins: int = 50, + color_by: str = "north_south", +): + """Display pointing and frequency residuals, design minus measured. + + Scatter colors indicate N/S or the matched *design* detector type. + Histograms remain combined across categories. + """ + pairs = list(match.get_match_iter(include_unmatched=False)) + if not pairs: + print(f"{wafer_slot} {stage}: no matched resonators to plot", flush=True) + return + + dxi = np.rad2deg(np.array([r2.xi - r1.xi for r1, r2 in pairs])) * 3600 + deta = np.rad2deg(np.array([r2.eta - r1.eta for r1, r2 in pairs])) * 3600 + df = np.array([r2.res_freq - r1.res_freq for r1, r2 in pairs], dtype=float) + fsrc = np.array([r1.res_freq for r1, _ in pairs], dtype=float) + labels = np.array([ + _plot_label(r1 if color_by == "north_south" else r2, color_by) + for r1, r2 in pairs + ]) + + valid_xy = np.isfinite(dxi) & np.isfinite(deta) + valid_f = np.isfinite(fsrc) & np.isfinite(df) + legend_title = "N/S" if color_by == "north_south" else "Detector type" + + fig, axs = plt.subplots(2, 2, figsize=(12, 9), constrained_layout=True) + + ax = axs[0, 0] + _plot_groups( + ax, dxi, deta, labels, valid_xy, color_by, + s=9, alpha=0.45, rasterized=True, + ) + ax.axvline(0, color="0.5", lw=1) + ax.axhline(0, color="0.5", lw=1) + ax.set_xlabel(r"$\Delta\xi$ (design - measured) [arcsec]") + ax.set_ylabel(r"$\Delta\eta$ (design - measured) [arcsec]") + if valid_xy.any(): + ax.set_title(f"Pointing (N={valid_xy.sum()})") + ax.legend(title=legend_title, fontsize=8) + else: + ax.set_title("Pointing") + + ax = axs[0, 1] + for values, label, color in ( + (dxi, r"$\Delta\xi$", "tab:blue"), + (deta, r"$\Delta\eta$", "tab:orange"), + ): + selected = values[np.isfinite(values)] + if selected.size: + ax.hist( + selected, bins=bins, histtype="step", lw=1.5, + color=color, label=label, + ) + ax.axvline(0, color="0.5", lw=1) + ax.set_xlabel("Pointing offset (arcsec)") + ax.set_ylabel("Matched detectors") + if valid_xy.any(): + ax.legend() + ax.set_title("Pointing histogram") + + ax = axs[1, 0] + _plot_groups( + ax, fsrc, df, labels, valid_f, color_by, + s=9, alpha=0.45, rasterized=True, + ) + ax.axhline(0, color="0.5", lw=1) + ax.set_xlabel("Measured resonance frequency (MHz)") + ax.set_ylabel(r"$\Delta f$ (design - measured) [MHz]") + if valid_f.any(): + ax.legend(title=legend_title, fontsize=8) + ax.set_title(f"Frequency (N={valid_f.sum()})") + else: + ax.set_title("Frequency") + + ax = axs[1, 1] + if valid_f.any(): + ax.hist( + df[valid_f], bins=bins, histtype="stepfilled", + alpha=0.55, color="tab:green", + ) + ax.set_title(f"Frequency histogram (median {np.median(df[valid_f]):+.1f} MHz)") + else: + ax.set_title("Frequency histogram") + ax.axvline(0, color="0.5", lw=1) + ax.set_xlabel(r"$\Delta f$ (design - measured) [MHz]") + ax.set_ylabel("Matched detectors") + + for ax in axs.flat: + ax.grid(alpha=0.2) + + fig.suptitle(f"{wafer_slot} | {stage}") + plt.show() + + +def _design_band(resonator): + """Optical frequency band of a design resonator (e.g. f090, f150).""" + band = getattr(resonator, "det_bandpass", "") + if isinstance(band, bytes): + band = band.decode("utf-8", errors="replace") + band = str(band).strip() + if band and band.upper() not in {"NC", "NONE", "NAN", "UNKNOWN"}: + return band + + # Older wafer-info records may have det_freq but no bandpass. + freq = getattr(resonator, "det_freq", 0) + try: + freq = float(freq) + except (ValueError, TypeError): + return None + if not np.isfinite(freq) or freq <= 0: + return None + return f"f{int(round(freq)):03d}" + + +def plot_match_xieta( + match: dm.Match, + stage: str, + wafer_slot: str, + color_by: str = "north_south", +): + """Side-by-side xi/eta matching plots, one panel per design band. + + Matched measured positions are labeled Pointing and shown in blue; + design positions are orange. All bands use the same colors. The + color_by argument is retained for compatibility with existing calls. + """ + bands = sorted({ + band for r in match.dst + if (band := _design_band(r)) is not None + }) + if not bands: + return + + matched_by_band = defaultdict(list) + for rsrc, rdst in match.get_match_iter(include_unmatched=False): + band = _design_band(rdst) + if band is not None: + matched_by_band[band].append((rsrc, rdst)) + + pointing_color = "tab:blue" + design_color = "tab:orange" + link_color = "0.2" + + nband = len(bands) + fig, axs = plt.subplots( + 1, nband, + figsize=(max(5.5 * nband, 8.0), 5.0), + constrained_layout=True, + ) + axs = np.atleast_1d(axs) + + for ax, band in zip(axs, bands): + design = [r for r in match.dst if _design_band(r) == band] + pairs = matched_by_band[band] + measured = [rsrc for rsrc, _ in pairs] + + src_xy = np.rad2deg(np.array( + [(r.xi, r.eta) for r in measured], dtype=float + ).reshape(-1, 2)) + dst_xy = np.rad2deg(np.array( + [(r.xi, r.eta) for r in design], dtype=float + ).reshape(-1, 2)) + src_valid = np.isfinite(src_xy).all(axis=1) + dst_valid = np.isfinite(dst_xy).all(axis=1) + + segments = [] + for rsrc, rdst in pairs: + xy = np.rad2deg(np.array( + [[rdst.xi, rdst.eta], [rsrc.xi, rsrc.eta]], dtype=float + )) + if np.isfinite(xy).all(): + segments.append(xy) + + if segments: + lines = LineCollection( + segments, colors=link_color, linewidths=1.8, + alpha=0.8, zorder=3, rasterized=True, + ) + lines.set_path_effects([ + pe.Stroke(linewidth=3.6, foreground="white"), + pe.Normal(), + ]) + ax.add_collection(lines) + + ax.scatter( + src_xy[src_valid, 0], src_xy[src_valid, 1], + s=16, marker="o", alpha=0.85, linewidths=0, + color=pointing_color, rasterized=True, zorder=5, + ) + ax.scatter( + dst_xy[dst_valid, 0], dst_xy[dst_valid, 1], + s=28, marker="+", alpha=0.95, linewidths=1.4, + color=design_color, rasterized=True, zorder=6, + ) + + ax.legend( + handles=[ + Line2D([0], [0], linestyle="None", marker="o", + color=pointing_color, markersize=4.5, + label=f"Pointing ({src_valid.sum()})"), + Line2D([0], [0], linestyle="None", marker="+", + color=design_color, markersize=6.5, + label=f"Design ({dst_valid.sum()})"), + ], + loc="upper right", fontsize=8, + ) + + ax.set_title(band) + ax.set_xlabel("xi (deg)") + if ax is axs[0]: + ax.set_ylabel("eta (deg)") + ax.set_aspect("equal", adjustable="datalim") + ax.grid(alpha=0.2) + + fig.suptitle(f"{wafer_slot} | {stage}") + plt.show() + + + +def search_best_initial_pointing_offset(src, dst, match_pars, cfg, wafer_slot=""): + """Search for the best initial xi/eta shift by 2D interval halving. + + Evaluate a 3x3 stencil at each level, recenter on the lowest matching + cost, and halve the stencil spacing. Frequencies are effectively ignored + in the search (very large freq_width), but the final match uses the + original match_pars. All trials use the same unshifted src coordinates. + + This is a local, coarse-to-fine optimizer, not a strict binary search: + matching cost need not be monotonic or unimodal. + """ + x_range = np.asarray(np.arange(*cfg.initial_offset_search_x_range_args), dtype=float) + y_range = np.asarray(np.arange(*cfg.initial_offset_search_y_range_args), dtype=float) + xmin, xmax = float(x_range.min()), float(x_range.max()) + ymin, ymax = float(y_range.min()), float(y_range.max()) + + search_pars = deepcopy(match_pars) + search_pars.freq_width = 1e12 # MHz: neutralize frequency cost during scan + match = dm.Match( + deepcopy(src), deepcopy(dst), match_pars=search_pars, + apply_dst_pointing=False, + ) + + original_xy = np.asarray([(r.xi, r.eta) for r in match.src], dtype=float) + valid_xy = np.isfinite(original_xy).all(axis=1) + valid_indices = np.flatnonzero(valid_xy) + + def set_shift(dx_deg, dy_deg): + dxi, deta = np.deg2rad([dx_deg, dy_deg]) + for i in valid_indices: + match.src[i].xi = original_xy[i, 0] + dxi + match.src[i].eta = original_xy[i, 1] + deta + + cache = {} + + def evaluate(dx_deg, dy_deg): + # Cache duplicate samples between levels, including the zero baseline. + key = (round(float(dx_deg), 12), round(float(dy_deg), 12)) + if key not in cache: + set_shift(*key) + match._match() + cache[key] = float(match.matching_cost) + return cache[key] + + def better(cost, dx, dy, best_cost, best_dx, best_dy): + if not np.isfinite(cost): + return False + if not np.isfinite(best_cost): + return True + if np.isclose(cost, best_cost, rtol=1e-12, atol=1e-9): + return np.hypot(dx, dy) < np.hypot(best_dx, best_dy) + return cost < best_cost + + baseline_cost = evaluate(0.0, 0.0) + best_cost = baseline_cost + best_dx, best_dy = 0.0, 0.0 + + # Start at the middle of the allowed rectangle. Retain the zero-offset + # baseline as a separate candidate, including when outside the rectangle. + cx, cy = (xmin + xmax) / 2, (ymin + ymax) / 2 + sx, sy = (xmax - xmin) / 2, (ymax - ymin) / 2 + levels = [] + + for level in range(cfg.initial_offset_search_levels): + xs = np.unique(np.clip([cx - sx, cx, cx + sx], xmin, xmax)) + ys = np.unique(np.clip([cy - sy, cy, cy + sy], ymin, ymax)) + costs = np.empty((len(ys), len(xs)), dtype=float) + + for iy, dy in enumerate(ys): + for ix, dx in enumerate(xs): + cost = evaluate(dx, dy) + costs[iy, ix] = cost + if better(cost, dx, dy, best_cost, best_dx, best_dy): + best_dx, best_dy = float(dx), float(dy) + best_cost = cost + + if not np.isfinite(best_cost): + raise ValueError(f"{wafer_slot}: no finite pointing matching cost") + + levels.append({ + "x": xs.copy(), "y": ys.copy(), "costs": costs.copy(), + "best_delta_deg": (best_dx, best_dy), + "best_cost": best_cost, + "step_deg": (sx, sy), + }) + print( + f"{wafer_slot} pointing search {level + 1}/{cfg.initial_offset_search_levels}: " + f"best=({best_dx:+.6f}, {best_dy:+.6f}) deg, " + f"cost={best_cost:.2f}, step=({sx:.6f}, {sy:.6f}) deg, " + f"evaluated={len(cache)}", + flush=True, + ) + + # If zero wins and is outside the configured range, project the center + # onto the allowed box. Otherwise refine around the best offset. + cx = float(np.clip(best_dx, xmin, xmax)) + cy = float(np.clip(best_dy, ymin, ymax)) + sx *= 0.5 + sy *= 0.5 + + # Run Match 0 with its original frequency width and every other parameter. + set_shift(best_dx, best_dy) + match.match_pars = deepcopy(match_pars) + match._match() + + base_x, base_y = cfg.initial_pointing_offset + last = levels[-1] + result = { + "best_delta_deg": (best_dx, best_dy), + "best_offset_deg": (float(base_x + best_dx), float(base_y + best_dy)), + "baseline_cost": baseline_cost, + "best_cost": best_cost, + "x": last["x"], + "y": last["y"], + "costs": last["costs"], + "levels": levels, + "n_evaluations": len(cache), + "search_freq_width_mhz": search_pars.freq_width, + "baseline_metrics": {"matching_cost": baseline_cost}, + "best_metrics": {"matching_cost": best_cost}, + } + print( + f"{wafer_slot} pointing search: cost {baseline_cost:.2f} -> {best_cost:.2f}; " + f"delta=({best_dx:+.6f}, {best_dy:+.6f}) deg; " + f"initial offset=({result['best_offset_deg'][0]:+.6f}, " + f"{result['best_offset_deg'][1]:+.6f}) deg; " + f"{len(cache)} assignments", + flush=True, + ) + return match, result + + +def plot_initial_offset_search(search, wafer_slot=""): + """Compare the first and final xi/eta search stencils.""" + levels = search["levels"] + samples = [levels[0], levels[-1]] if len(levels) > 1 else [levels[0]] + fig, axs = plt.subplots( + 1, len(samples), figsize=(5.2 * len(samples), 4.6), + constrained_layout=True, + ) + axs = np.atleast_1d(axs) + + def edges(values): + values = np.asarray(values, dtype=float) + if len(values) == 1: + return values + np.array([-0.001, 0.001]) + mids = (values[:-1] + values[1:]) / 2 + return np.r_[values[0] - (mids[0] - values[0]), mids, + values[-1] + (values[-1] - mids[-1])] + + for i, (ax, level) in enumerate(zip(axs, samples)): + xs, ys, costs = level["x"], level["y"], level["costs"] + values = np.asarray(costs, dtype=float) + positive = values[np.isfinite(values) & (values > 0)] + log_cost = (len(positive) > 0 and + positive.max() / positive.min() > 100) + if log_cost: + values = np.log10(np.where(values > 0, values, np.nan)) + im = ax.pcolormesh(edges(xs), edges(ys), values, + cmap="viridis_r", shading="auto") + # Mark the lowest-cost evaluated trial in this stencil. + if np.isfinite(costs).any(): + iy, ix = np.unravel_index(np.nanargmin(costs), costs.shape) + ax.plot(xs[ix], ys[iy], "rx", ms=10, mew=2.5) + ax.set_title("First" if i == 0 else "Final") + ax.set_xlabel("delta xi (deg)") + ax.set_ylabel("delta eta (deg)") + fig.colorbar(im, ax=ax, label="log10 cost" if log_cost else "Cost") + + bx, by = search["best_delta_deg"] + fig.suptitle( + f"{wafer_slot} | M0 offset search | " + f"best ({bx:+.5f}, {by:+.5f}) deg" + ) + plt.show() + + def match_wafer( cfg: SolutionsCfg, am: AxisManager, @@ -516,40 +1331,49 @@ def match_wafer( allow_unassigned_to_assigned=False, unassigned_slots=cfg.unassigned_slots, ) - match = dm.Match(src, dst, match_pars=match_pars, apply_dst_pointing=False) + offset_search = None + if cfg.search_initial_pointing_offset: + match, offset_search = search_best_initial_pointing_offset( + src, dst, match_pars, cfg, wafer_slot=wafer_slot, + ) + if cfg.show_match_plots: + plot_initial_offset_search(offset_search, wafer_slot=wafer_slot) + else: + match = dm.Match(src, dst, match_pars=match_pars, apply_dst_pointing=False) match_iterations.append(deepcopy(match)) - dxis, detas = [], [] - dfs = [] - is_north = [] - for r1, r2 in match.get_match_iter(include_unmatched=False): - dxis.append(r2.xi - r1.xi) - detas.append(r2.eta - r1.eta) - dfs.append(r2.res_freq - r1.res_freq) - is_north.append(r2.is_north) - dxi = np.nanmedian(dxis) - deta = np.nanmedian(detas) + if cfg.show_match_plots: + plot_match_offsets(match, "M0 initial", wafer_slot, color_by=cfg.match_plot_color_by) + plot_match_xieta(match, "M0 initial", wafer_slot, color_by=cfg.match_plot_color_by) + + # Determine the global shift from matched optical detectors only. + optical_pairs = list(_optical_pointing_pairs(match)) + if not optical_pairs: + raise ValueError( + f"{wafer_slot}: cannot estimate global pointing shift: " + "no matched OPTC pairs with finite xi/eta" + ) + + dxi = np.median([r2.xi - r1.xi for r1, r2 in optical_pairs]) + deta = np.median([r2.eta - r1.eta for r1, r2 in optical_pairs]) for r in match.src: - r.xi += dxi - r.eta += deta + if np.isfinite([r.xi, r.eta]).all(): + r.xi += dxi + r.eta += deta match._match() match_iterations.append(deepcopy(match)) + if cfg.show_match_plots: + plot_match_offsets(match, "M0 shifted", wafer_slot, color_by=cfg.match_plot_color_by) + plot_match_xieta(match, "M0 shifted", wafer_slot, color_by=cfg.match_plot_color_by) if cfg.freq_correct_by_muxband: - da = match.dst.as_array() - df_arr = np.full(len(da), np.nan) - for i, r in enumerate(match.dst): - if r.matched: - df_arr[i] = r.res_freq - match.src[r.match_idx].res_freq - - for is_north in [0, 1]: - for mb in np.unique(da["mux_band"]): - mask = (da["mux_band"] == mb) & (da["is_north"] == is_north) - df_med = np.nanmedian(df_arr[mask]) - for res_idx in np.where(mask)[0]: - match.dst[res_idx].res_freq -= df_med + freq_diagnostics = apply_muxband_frequency_correction( + match, cfg, wafer_slot=wafer_slot + ) + if cfg.show_match_plots: + plot_muxband_frequency_correction(freq_diagnostics, wafer_slot) else: # Correct freq offset by box median interpolation foffset_north = get_foffset_interp(match, True) @@ -569,13 +1393,32 @@ def match_wafer( unassigned_slots=cfg.unassigned_slots ) match._match() - - dxi_interp, deta_interp = get_pt_offset_interp(match, sel_rad=np.deg2rad(cfg.sel_rad)) + if cfg.show_match_plots: + summarize_optical_frequency_slopes(match, "Match 1", cfg.freq_fit_min_matches) + plot_match_offsets(match, "M1 frequency", wafer_slot, color_by=cfg.match_plot_color_by) + plot_match_xieta(match, "M1 frequency", wafer_slot, color_by=cfg.match_plot_color_by) + + # Interpolators were estimated from matched OPTC detectors only. + # Apply the spatial correction to ALL measured resonators with finite xi/eta. + dxi_interp, deta_interp = get_pt_offset_interp( + match, sel_rad=np.deg2rad(cfg.sel_rad) + ) + n_corrected = 0 for r in match.src: - if np.isnan(r.xi): + if not np.isfinite([r.xi, r.eta]).all(): continue - r.xi -= dxi_interp((r.xi, r.eta)).item() - r.eta -= deta_interp((r.xi, r.eta)).item() + + # Evaluate both offsets at the SAME original position. + xy = (r.xi, r.eta) + dxi = float(dxi_interp(xy).item()) + deta = float(deta_interp(xy).item()) + if not np.isfinite([dxi, deta]).all(): + raise ValueError( + f"{wafer_slot}: non-finite spatial correction at xi/eta={xy}" + ) + r.xi -= dxi + r.eta -= deta + n_corrected += 1 # Third match match.match_pars.freq_width = cfg.match_pars["match2"]["freq_width"] @@ -583,11 +1426,20 @@ def match_wafer( match._match() match_iterations.append(deepcopy(match)) + if cfg.show_match_plots: + summarize_optical_frequency_slopes(match, "Match 2", cfg.freq_fit_min_matches) + plot_match_offsets(match, "M2 spatial", wafer_slot, color_by=cfg.match_plot_color_by) + plot_match_xieta(match, "M2 spatial", wafer_slot, color_by=cfg.match_plot_color_by) return MatchSolution( match=match, match_iterations=match_iterations, am=am, + best_initial_pointing_offset=( + offset_search["best_offset_deg"] if offset_search is not None + else tuple(cfg.initial_pointing_offset) + ), + initial_offset_search=offset_search, ) diff --git a/sotodlib/coords/optics.py b/sotodlib/coords/optics.py index dc5c51844..083d75d0c 100644 --- a/sotodlib/coords/optics.py +++ b/sotodlib/coords/optics.py @@ -401,7 +401,7 @@ def LAT_optics(zemax_path): zemax_dat = load_zemax(zemax_path) try: LAT = zemax_dat["LAT"][()] - LAT = {k.decode(): v for k, v in zemax_dat["LAT"][()].items()} + LAT = {k: v for k, v in zemax_dat["LAT"][()].items()} except Exception as e: logger.error("LAT key missing from dictionary") raise e @@ -441,7 +441,7 @@ def LATR_optics(zemax_path, tube_slot): try: LATR = zemax_dat["LATR"][()] LATR = np.array([ - {k.decode(): v for k, v in d.items()} + {k: v for k, v in d.items()} for d in LATR ], dtype=object) except Exception as e: