diff --git a/sotodlib/coords/det_match.py b/sotodlib/coords/det_match.py index 222e4ccd3..14dabcd40 100644 --- a/sotodlib/coords/det_match.py +++ b/sotodlib/coords/det_match.py @@ -39,21 +39,40 @@ 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 -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 @@ -65,23 +84,26 @@ 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" - 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 + rx_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 @@ -92,6 +114,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") @@ -104,22 +130,37 @@ 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']) - 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 + 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': - 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_rx_pars=self.rx_pars, ) 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, + fp_to_rx_pars=self.rx_pars, + zemax_path=self.zemax_path, ) return xi, eta, gamma @@ -140,6 +181,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 @@ -194,7 +237,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 @@ -285,7 +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): + 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 @@ -306,16 +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] + ) 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 aman.det_info.wafer_slot[ri] != "ws.": + 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] @@ -336,7 +384,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 @@ -354,6 +402,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 = [] @@ -363,7 +414,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 @@ -438,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) @@ -457,11 +511,12 @@ 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 - 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): @@ -469,16 +524,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): - '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 + ignore_north_south (str): + Do not infer North/South orientation and just set all to North. + Used for LF. """ resonances = [] @@ -492,7 +549,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 @@ -505,11 +562,14 @@ 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( - i=i, + idx=i, res_freq=float(d['freq_mhz']), smurf_band=_int(d['smurf_band']), bg=_int(d['bias_line']), @@ -660,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 @@ -746,10 +806,11 @@ 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 + # 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 @@ -759,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']) @@ -791,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 @@ -818,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 \ @@ -848,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) @@ -961,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 @@ -974,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: @@ -1009,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 @@ -1026,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 16c3cc0dc..2022ac017 100644 --- a/sotodlib/coords/det_match_solutions.py +++ b/sotodlib/coords/det_match_solutions.py @@ -5,9 +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 copy import deepcopy from scipy import interpolate +from scipy.stats import theilslopes from tqdm.auto import tqdm, trange from copy import deepcopy @@ -32,15 +36,17 @@ 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" - base_obs_id : str + 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 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. - apply_roll : bool + zemax_path: str + 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. pointing_field : str @@ -80,18 +86,30 @@ 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. - freq_correct_by_muxband : bool + 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 pointing_results_dir: str results_dir: str wafer_info_path: str - tel_type: str + platform: str + wafer_slots: Optional[list[str]] = None base_obs_id: Optional[str] = None zemax_path: Optional[str] = None apply_roll: bool = True @@ -109,7 +127,29 @@ class SolutionsCfg: initial_pointing_offset: Tuple[float, float] = (0, 0) ufm_to_fp_path: Optional[str] = None + 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) @@ -124,8 +164,42 @@ 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: + 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) @@ -146,6 +220,14 @@ 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_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: + self.imprinter_path = os.path.join( + self.site_pipeline_cfg_dir, f"{self.platform}/imprinter.yaml" + ) @dataclass @@ -212,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) @@ -246,7 +328,12 @@ 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, + ) pointing_map = { r.idx: [(r.xi, r.eta)] for r in base_resset @@ -254,14 +341,18 @@ 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, + ) dst = base_resset match = dm.Match(src, dst, match_pars=match_pars) for rsrc, rdst in match.get_match_iter(include_unmatched=False): @@ -317,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 @@ -386,11 +519,719 @@ 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, stream_id: str, - meas_rset: Optional[dm.ResSet] + meas_rset: Optional[dm.ResSet], ) -> MatchSolution: """ Create a match solution for a given wafer slot. @@ -409,19 +1250,78 @@ 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], + ) 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 wafer_slot == "ws.": + wafer_slots = [] + wafers_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(): + wafers_dict[ws['wafer_slot']] = (ws['wafer'].split('_')[-1].capitalize()) + wafer_slots.append(ws['wafer_slot']) + else: + wafer_slots = [wafer_slot] + wafers_dict = None + + 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, 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, + 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, + ).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_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 wafer_slot == "ws.": + dst = dm.ResSet.from_wafer_info_file( + cfg.wafer_info_path, + stream_id, + pt_cfg=None, + ).as_array() + + merge_fields = ["xi", "eta", "wafer_slot"] + for i, d in enumerate(dst_merged): + idx = np.where(dst['det_id'] == d['det_id'])[0][0] + if idx: + for field in merge_fields: + dst[idx][field] = dst_merged[i][field] + dst = dm.ResSet.from_array(dst) + else: + dst = dm.ResSet.from_array(dst_merged) # first match match_pars = dm.MatchParams( @@ -429,42 +1329,51 @@ 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) + 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) @@ -484,26 +1393,53 @@ 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"] match.match_pars.dist_width = np.deg2rad(cfg.match_pars["match2"]["dist_width"]) 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, ) @@ -555,13 +1491,16 @@ 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) + meas_rset, pointing_map = merge_pointing_info( + cfg, pointing_results, base_idx=base_idx, + ) 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, + ) solution = FullWaferSolution( pointing_results=pointing_results, @@ -577,8 +1516,7 @@ def get_wafer_solution( def solve_all(cfg) -> Dict[str, Optional[FullWaferSolution]]: - wafer_slots = ["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 01e1ce6c1..083d75d0c 100644 --- a/sotodlib/coords/optics.py +++ b/sotodlib/coords/optics.py @@ -376,7 +376,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 @@ -401,6 +401,7 @@ def LAT_optics(zemax_path): zemax_dat = load_zemax(zemax_path) try: LAT = zemax_dat["LAT"][()] + LAT = {k: v for k, v in zemax_dat["LAT"][()].items()} except Exception as e: logger.error("LAT key missing from dictionary") raise e @@ -439,6 +440,10 @@ def LATR_optics(zemax_path, tube_slot): zemax_dat = load_zemax(zemax_path) try: LATR = zemax_dat["LATR"][()] + LATR = np.array([ + {k: 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 80dd7f7ae..8a67d69bd 100644 --- a/sotodlib/site_pipeline/update_det_match.py +++ b/sotodlib/site_pipeline/update_det_match.py @@ -3,23 +3,27 @@ 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 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 from sotodlib.site_pipeline.utils.logging import init_logger -logger = init_logger('update_det_match', 'update-det-match: ') +logger = init_logger("update_det_match", "update-det-match: ") def get_detset_time(detset: str) -> float: @@ -42,6 +46,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. @@ -88,7 +94,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] @@ -97,6 +103,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) @@ -120,7 +127,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: @@ -131,12 +138,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'") @@ -151,9 +158,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') @@ -175,7 +183,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): @@ -189,7 +201,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): @@ -221,9 +233,9 @@ 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 = {} + x = {} x[str(detset)] = str(msg) with open(cache_file, 'w') as f: @@ -255,84 +267,216 @@ 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 -def run_match(runner: Runner, detset: str) -> bool: +def _run_match_core(runner: Runner, detset: str): """ - 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 + 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. """ - # 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, None + + 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: - add_to_failed_cache( - runner.failed_detset_cache_path, detset, "NO_OBSID_WITH_CAL", runner.cfg - ) + + 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: 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] - # 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'] + return False, "NO_OBSID_WITH_CAL" + + 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, + ) + + 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(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 - else: - logger.error( - f"Could not find wafer_slot from book index for ds={detset}, " - f"obs_id={obs_id}" + + if bad_bg: + logger.warning( + f"{obs_id} and {detset} yield surpasses design yield; " + "skipping." ) - raise Exception("Could not find wafer-slot") - else: - wafer_slot = None + continue + + n_good = int(np.count_nonzero(good)) + n_total = 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, None + + 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}" + ) + + 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) - 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}") + except Exception as e: + logger.warning( + f"run_match_aman failed for {detset}: {e}" + ) + return False, None - return True + return True, None + + +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 + + 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): @@ -353,8 +497,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) @@ -404,7 +548,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) @@ -427,62 +571,135 @@ 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") update_manifests(runner, ds) + def get_parser(parser=None): if parser is 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. - ------ - 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. - """ +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)) + + 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, + )