pycwb.modules.coherence_native package

Submodules

pycwb.modules.coherence_native.callbacks module

Callable contracts for optional replacements within this scientific module.

These describe individual operations, not a required workflow or stage order. Prepared inputs are shared read-only; cluster mutations stay job-owned.

class pycwb.modules.coherence_native.callbacks.PixelSelector(*args, **kwargs)[source]

Bases: Protocol

Return the native candidate dictionary without mutating prepared maps.

pycwb.modules.coherence_native.clustering module

Connected-component clustering for selected coherence pixels.

pycwb.modules.coherence_native.clustering.cluster_pixels(pixel_candidates: dict, kt: int = 1, kf: int = 1, select_subrho: float | None = None, select_subnet: float | None = None, profile=ExecutionProfile(scalar_dpf=False, sky_delay_reuse=True, coherence_early_cuts=False, preindex_shifts=False, cluster_runs=False, compact_coherence=False, tiled_wdm=False, compact_td_cache=False, staged_td=False, bounded_jax_max_energy=False, numba_max_energy_mode='parallel', regression_engine='numba', gc_full_interval=1, perf_diagnostics=False, require_gpu=False, wdm_bounded_jax_forward=False, wdm_bounded_jax_inverse=False, wdm_deterministic_jax_inverse=False, wdm_bounded_numba=False, wdm_compact_complex=False)) → FragmentCluster[source]

Cluster selected pixels using connected-component analysis.

Parameters:
  • pixel_candidates (dict) – Candidate payload from select_network_pixels().

  • kt (int) – Time-connectivity radius in bins (adjacency tolerance |Δtime| ≤ kt).

  • kf (int) – Frequency-connectivity radius in bins (adjacency tolerance |Δfreq| ≤ kf).

  • select_subrho (float or None) – Optional rejection thresholds applied before constructing objects. Uses the same strict-less-than rejection as FragmentCluster.select. Omit when rejected clusters must remain available.

  • select_subnet (float or None) – Optional rejection thresholds applied before constructing objects. Uses the same strict-less-than rejection as FragmentCluster.select. Omit when rejected clusters must remain available.

Returns:

Clustered pixels with selected and rejected flags based on size.

Return type:

FragmentCluster

pycwb.modules.coherence_native.coherence module

Native coherence orchestration and public entry points.

Numerical implementations live in focused sibling modules; their entry points remain available here for workflow and notebook compatibility.

pycwb.modules.coherence_native.coherence.coherence(config: Config, strains: list[TimeSeries], return_rejected: bool = False, job_seg: WaveSegment | None = None, nRMS: list | None = None) → list[list[FragmentCluster]][source]

Select the significant pixels for all resolution levels and all lags.

This is the interactive convenience wrapper. Internally it calls setup_coherence() once (expensive: WDM decomposition + TF maps) and then coherence_single_lag() for every lag (cheap: pixel selection + clustering only).

Parameters:
  • config (Config) – Configuration object.

  • strains (list[TimeSeries]) – List of whitened strain time series.

  • return_rejected (bool) – If True, keep rejected clusters in the output.

  • job_seg (WaveSegment, optional) – Job segment supplying lag count and per-lag time shifts. When None a single zero-lag pass is performed.

  • nRMS (list[NoiseRMSMap] or None, optional) – Noise anchors returned by native conditioning. Supply these for detector-weighted subnet cuts; omission retains legacy unit weights.

Returns:

result[res][lag] — one FragmentCluster per resolution per lag.

Return type:

list[list[FragmentCluster]]

pycwb.modules.coherence_native.coherence.coherence_single_lag(coherence_setups: list[dict], lag_idx: int, return_rejected: bool = False, veto_windows: list[tuple[float, float]] | None = None, *, select_pixels: PixelSelector | None = None) → list[FragmentCluster][source]

Compute coherence for one lag index, using pre-built per-resolution setups from setup_coherence().

This is the per-lag cheap counterpart: only pixel selection and clustering are performed here; all expensive TF/WDM work is already done.

Parameters:
  • coherence_setups (list[dict]) – Returned by setup_coherence().

  • lag_idx (int) – Zero-based lag index.

  • return_rejected (bool) – If True keep rejected clusters in the output.

  • veto_windows (list[tuple[float, float]] or None) – GPS intervals (start, end) to keep. When not None, a binary mask is built via build_veto_mask() and passed to pixel selection so that only pixels inside these windows survive.

Returns:

  • list[FragmentCluster] – One FragmentCluster per resolution for this lag.

  • Backend callbacks

  • —————–

  • select_pixels (callable, optional) – Process-owned implementations with the corresponding native signatures. None selects the native implementation. Shared prepared inputs must remain immutable; cluster/output mutation follows the native contract. These callbacks are not serialized or sent between workers.

pycwb.modules.coherence_native.kernels module

Numba kernels used by native coherence selection and clustering.

pycwb.modules.coherence_native.projection module

Max-energy projection and backend selection for native coherence.

pycwb.modules.coherence_native.projection.max_energy(tf_map: TimeFrequencyMap, max_delay: float, up_n: int, pattern: int, f_low: float | None = None, f_high: float | None = None, hist: list | None = None, backend: str = 'jax', profile=ExecutionProfile(scalar_dpf=False, sky_delay_reuse=True, coherence_early_cuts=False, preindex_shifts=False, cluster_runs=False, compact_coherence=False, tiled_wdm=False, compact_td_cache=False, staged_td=False, bounded_jax_max_energy=False, numba_max_energy_mode='parallel', regression_engine='numba', gc_full_interval=1, perf_diagnostics=False, require_gpu=False, wdm_bounded_jax_forward=False, wdm_bounded_jax_inverse=False, wdm_deterministic_jax_inverse=False, wdm_bounded_numba=False, wdm_compact_complex=False), *, delay_energy: Callable | None = None) → tuple[TimeFrequencyMap, float][source]

Compute max-energy skymap projection for a detector TF map.

Calls time_delay_max_energy() from the module-level pure-function implementation and returns a new TF map together with the Gamma-to-Gauss scaling parameter.

Parameters:
  • tf_map (TimeFrequencyMap) – Detector time-frequency map object.

  • max_delay (float) – Maximum delay for the time series.

  • up_n (int) – Upsample factor for decorrelation.

  • pattern (int) – Wave packet pattern identifier.

  • f_low (float | None, optional) – Low-frequency cutoff in Hz.

  • f_high (float | None, optional) – High-frequency cutoff in Hz.

  • hist (list | None, optional) – Optional histogram container for statistics.

  • backend ({"jax", "numba", "auto"}, optional) – Backend for the time-delay max-energy kernel. "jax" preserves the historical behavior. "numba" uses the compiled numba pattern path and delegates pattern 0 to JAX. "auto" chooses from the WDM layer count.

Returns:

  • tuple[TimeFrequencyMap, float] – Updated TF map after max-energy projection and Gamma-to-Gauss scaling factor.

  • Backend callbacks

  • —————–

  • delay_energy (callable, optional) – Process-owned implementations with the corresponding native signatures. None selects the native implementation. Shared prepared inputs must remain immutable; cluster/output mutation follows the native contract. These callbacks are not serialized or sent between workers.

pycwb.modules.coherence_native.run_clustering module

Sparse row-run connectivity with every original pixel retained.

pycwb.modules.coherence_native.run_clustering.label_components_runs(f_arr, t_arr, n_freq, n_time, kf, kt)[source]

Match grid labels using connected runs and a sweep of their boundaries.

A row run contains sorted pixels separated by at most kt bins. Its pixels are already connected. Two runs on nearby rows connect iff their closed time intervals are within kt bins: any internal gap is at most kt, so an interval overlap cannot conceal a disconnected pair. The sweep advances the run with the earlier end; later runs in that row start > kt past it. Roots and final labels follow original input order, including duplicates. Invalid coordinates remain isolated, as in the grid implementation.

Parameters:
  • f_arr (numpy.ndarray) – Integer frequency and time bins in original pixel order, shape (n_pixels,).

  • t_arr (numpy.ndarray) – Integer frequency and time bins in original pixel order, shape (n_pixels,).

  • n_freq (int) – Grid extents used to validate each coordinate.

  • n_time (int) – Grid extents used to validate each coordinate.

  • kf (int) – Inclusive frequency/time connection gaps in bins. Negative gaps use the existing grid implementation.

  • kt (int) – Inclusive frequency/time connection gaps in bins. Negative gaps use the existing grid implementation.

Returns:

One-based int64 component labels in original order, including duplicates.

Return type:

numpy.ndarray

pycwb.modules.coherence_native.selection module

Network-pixel selection for native coherence.

pycwb.modules.coherence_native.selection.select_network_pixels(tf_maps: list[TimeFrequencyMap], lag_index: int, energy_threshold: float, lag_shifts: ndarray | list | None = None, veto: ndarray | None = None, edge: float = 0.0, selection_cache: dict | None = None, preindex_shifts: bool = False) → dict[source]

Select significant pixels above energy threshold for one lag.

Parameters:
  • tf_maps (list[TimeFrequencyMap]) – Per-detector time-frequency maps.

  • lag_index (int) – Zero-based lag index for time-delay selection.

  • energy_threshold (float) – Pixel energy threshold for significance.

  • lag_shifts (np.ndarray | list[float] | None, optional) – Per-detector time shifts in seconds for this lag.

  • veto (np.ndarray | None, optional) – Binary veto array in time bins (1 keep, 0 reject).

  • edge (float, optional) – Edge margin in seconds. Default is 0.0.

  • selection_cache (dict or None, optional) – Lag-invariant numeric cache produced by _build_selection_cache(). When omitted, it is built from tf_maps for backwards-compatible direct calls.

Returns:

Candidate payload with keys:

  • mask : bool ndarray, shape (n_freq, n_time) — pixel selection mask

  • time : int64 ndarray, shape (n_pix,) — time-bin indices of selected pixels

  • frequency : int64 ndarray, shape (n_pix,) — frequency-bin indices

  • energy : float64 ndarray, shape (n_pix,) — summed energy across detectors

  • pix_det_energy : float64 ndarray, shape (n_pix, n_ifo) — per-detector pixel energy

  • pix_det_index : int64 ndarray, shape (n_pix, n_ifo) — flat TF index per detector

  • rate : float — sample rate (Hz)

  • layers : int — number of WDM frequency layers

  • start : float — segment GPS start

  • stop : float — segment GPS stop

  • f_low : float | None — low-frequency edge

  • f_high : float | None — high-frequency edge

Return type:

dict

pycwb.modules.coherence_native.setup module

Lag-independent setup for native coherence.

pycwb.modules.coherence_native.setup.setup_coherence(config: Config, strains: list[TimeSeries], job_seg: WaveSegment | None = None, nRMS: list | None = None) → list[dict][source]

Compute all lag-independent coherence data (TF maps after max_energy, threshold, selection cache) for every resolution level.

Call this once per job segment, then pass the returned list to coherence_single_lag() for each lag.

Parameters:
  • config (Config) – Configuration object.

  • strains (list[TimeSeries]) – Whitened strain time series.

  • job_seg (WaveSegment or None, optional) – Job segment (provides lag count via job_seg.n_lag).

  • nRMS (list[NoiseRMSMap] or None, optional) – Whitening-noise anchors shared across resolutions. Native workflows supply these for cWB-compatible subnet statistics.

Returns:

One setup dict per resolution, keyed by tf_maps, Eo, job_seg, pattern, level, layers, rate, select_subrho, select_subnet, segEdge.

Return type:

list[dict]

pycwb.modules.coherence_native.tf_batch_generation module

Batch time-frequency map generation for coherence using JAX vmap.

Replaces the serial per-detector loop:

tf_maps = [
    TimeFrequencyMap.from_timeseries(ts=strain, wavelet=wdm_wavelet, ...)
    for strain in strains
]

with a single vmap’d call over all detectors:

batch_t2w_detectors(strains, wdm_wavelet, config)

All detectors share the same WDM parameters and the same segment length, so vmap over the leading detector dimension compiles once and runs in parallel.

pycwb.modules.coherence_native.tf_batch_generation.batch_t2w_detectors(strains, wdm_wavelet, profile=ExecutionProfile(scalar_dpf=False, sky_delay_reuse=True, coherence_early_cuts=False, preindex_shifts=False, cluster_runs=False, compact_coherence=False, tiled_wdm=False, compact_td_cache=False, staged_td=False, bounded_jax_max_energy=False, numba_max_energy_mode='parallel', regression_engine='numba', gc_full_interval=1, perf_diagnostics=False, require_gpu=False, wdm_bounded_jax_forward=False, wdm_bounded_jax_inverse=False, wdm_deterministic_jax_inverse=False, wdm_bounded_numba=False, wdm_compact_complex=False))[source]

Compute TimeFrequencyMap data for all detectors in one batched JAX call.

Parameters:
  • strains (list of pycwb TimeSeries) – Whitened strain time series for each detector. All must have the same sample_rate and the same number of samples.

  • wdm_wavelet (WDMWavelet (wdm_wavelet.WDM instance)) – The WDM wavelet used for this resolution level. Must have JAX backend.

Returns:

  • list of np.ndarray – One complex128 array per detector, each shape (M+1, n_time). These are the raw TF map data arrays ready to populate pycwb TimeFrequencyMap.

  • tuple (dt, df) – Time and frequency resolution metadata.

pycwb.modules.coherence_native.time_delay_common module

Shared helpers for time-delay max-energy backends.

pycwb.modules.coherence_native.time_delay_common.frequency_bounds(tf_map, n_freq: int) → tuple[float, float][source]

Return low/high frequency bounds for packet-energy kernels.

pycwb.modules.coherence_native.time_delay_common.sample_rate_from_tf_map(tf_map, n_freq: int) → float[source]

Return the sample rate implied by WDM frequency spacing.

pycwb.modules.coherence_native.time_delay_common.time_series_length(tf_map) → int[source]

Return the original time-series length represented by a TF map.

pycwb.modules.coherence_native.time_delay_common.validate_time_delay_inputs(tf_map, dt, downsample, *, require_wavelet_api: bool) → None[source]

Validate backend-independent max-energy inputs.

pycwb.modules.coherence_native.time_delay_jax module

JAX implementation of WDM time-delay max-energy.

pycwb.modules.coherence_native.time_delay_jax.time_delay_max_energy(tf_map: TimeFrequencyMap, dt: float, downsample: int = 1, pattern: int = 0, hist: list | None = None, profile: ExecutionProfile = ExecutionProfile(scalar_dpf=False, sky_delay_reuse=True, coherence_early_cuts=False, preindex_shifts=False, cluster_runs=False, compact_coherence=False, tiled_wdm=False, compact_td_cache=False, staged_td=False, bounded_jax_max_energy=False, numba_max_energy_mode='parallel', regression_engine='numba', gc_full_interval=1, perf_diagnostics=False, require_gpu=False, wdm_bounded_jax_forward=False, wdm_bounded_jax_inverse=False, wdm_deterministic_jax_inverse=False, wdm_bounded_numba=False, wdm_compact_complex=False), *, pattern_maximum: Callable | None = None) → tuple[TimeFrequencyMap, float][source]

Compute the delayed max-energy map for a TF series.

Pure-function port of TimeFrequencyMap.time_delay_max_energy (now removed from the class). Updates tf_map.data in place.

Parameters:
  • tf_map (TimeFrequencyMap) – detector TF map

  • dt (float) – max time delay in seconds

  • downsample (int) – delay step in samples (cWB N)

  • pattern (int) – wave-packet pattern (cWB pattern)

  • hist (list | None) – optional list-like container to collect transformed samples

Returns:

tuple of (new_tf_map with processed data, gamma-to-Gauss scaling parameter ALP) where ALP == 1.0 when pattern == 0.

Return type:

tuple[TimeFrequencyMap, float]

pycwb.modules.coherence_native.time_delay_numba module

Numba implementation of WDM time-delay max-energy.

pycwb.modules.coherence_native.time_delay_numba.time_delay_max_energy_numba(tf_map: TimeFrequencyMap, dt, downsample=1, pattern=0, hist=None, mode=None, profile=ExecutionProfile(scalar_dpf=False, sky_delay_reuse=True, coherence_early_cuts=False, preindex_shifts=False, cluster_runs=False, compact_coherence=False, tiled_wdm=False, compact_td_cache=False, staged_td=False, bounded_jax_max_energy=False, numba_max_energy_mode='parallel', regression_engine='numba', gc_full_interval=1, perf_diagnostics=False, require_gpu=False, wdm_bounded_jax_forward=False, wdm_bounded_jax_inverse=False, wdm_deterministic_jax_inverse=False, wdm_bounded_numba=False, wdm_compact_complex=False))[source]

Numba-accelerated version of time_delay_max_energy().

Uses @numba.njit for the inner energy kernel instead of JAX JIT, which avoids XLA compilation overhead and works without a JAX install. Only the pattern path (pattern != 0) is fully supported; for pattern == 0 the function falls back to the JAX implementation when JAX is available, or raises NotImplementedError.

Parameters:
  • tf_map (TimeFrequencyMap) – detector TF map

  • dt (float) – max time delay in seconds

  • downsample (int) – delay step in samples

  • pattern (int) – wave-packet pattern (cWB pattern)

  • hist (list | None) – optional list-like container to collect transformed samples

  • mode (str | None) – numba loop strategy, "parallel", "time-major" or "streaming". Defaults to the resolved execution profile ("parallel" by default).

Returns:

(new_tf_map, alp)

Return type:

tuple[TimeFrequencyMap, float]

pycwb.modules.coherence_native.veto_threshold module

Veto-mask and threshold helpers for native coherence.

pycwb.modules.coherence_native.veto_threshold.apply_veto(tf_map: TimeFrequencyMap, tw: float, segment_list: list[tuple[float, float]] | None = None, injection_times: list[float] | None = None, edge: float | None = None, return_mask: bool = False) → float | tuple[float, ndarray][source]

Compute live time and optional veto mask from segments and injections.

Parameters:
  • tf_map (TimeFrequencyMap) – Reference TF map for timeline definition.

  • tw (float) – Injection exclusion window in seconds.

  • segment_list (list[tuple[float, float]] | None, optional) – Accepted live segments (start, stop) in GPS seconds.

  • injection_times (list[float] | None, optional) – Injection GPS times to exclude within ±tw/2 seconds.

  • edge (float | None, optional) – Edge margin in seconds excluded from live-time integration.

  • return_mask (bool, optional) – If True, return (live_time, veto_mask) instead of just live time.

Returns:

Live time in seconds. If return_mask=True, returns (live_time, veto_mask) where veto_mask is a 1-D int16 array.

Return type:

float or tuple[float, np.ndarray]

pycwb.modules.coherence_native.veto_threshold.build_veto_mask(tf_map, veto_windows: list[tuple[float, float]], edge: float | None = None) → ndarray[source]

Build a binary keep-mask from GPS time windows for a TF map timeline.

Bins inside any of veto_windows are marked 1 (keep); everything else is 0 (reject). The resulting array can be passed as the veto argument to select_network_pixels().

Parameters:
  • tf_map (object) – Reference TF map that defines the time axis (must expose data, dt, and start attributes).

  • veto_windows (list[tuple[float, float]]) – GPS intervals (start, end) to keep. Overlapping windows are handled correctly (union).

  • edge (float or None) – Ignored for mask construction but accepted for API consistency.

Returns:

1-D int16 array of length n_time (mask: 1=keep, 0=reject).

Return type:

np.ndarray

pycwb.modules.coherence_native.veto_threshold.compute_threshold(tf_maps: list[TimeFrequencyMap], bpp: float, alp: float | None = None, edge: float | None = None) → float[source]

Compute pixel energy threshold from time-frequency map statistics.

Uses a Python-native implementation inspired by cWB network::THRESHOLD logic based on the black-pixel probability (false-alarm rate).

Parameters:
  • tf_maps (list[TimeFrequencyMap]) – Per-detector time-frequency maps.

  • bpp (float) – Black-pixel probability (target false-alarm rate).

  • alp (float | None, optional) – Packet-shape scaling parameter (None for the no-shape path).

  • edge (float | None, optional) – Edge margin in seconds excluded from threshold statistics.

Returns:

Computed pixel energy threshold.

Return type:

float

Module contents

pycwb.modules.coherence_native — Native coherence engine.

Production coherence pipeline using JAX-accelerated WDM time→frequency transforms, max-energy computation, threshold-based pixel selection, veto application, and single-resolution pixel clustering. Uses lag shifts provided by the job segment.