pycwb.modules.online package

Submodules

pycwb.modules.online.background module

Background estimation manager (placeholder).

The initial online release uses pre-trained XGBoost + IFAR files for significance assignment. This module reserves the interface for future automatic background job management (Condor/Slurm batch submission, result harvesting, and model retraining).

class pycwb.modules.online.background.BackgroundManager[source]

Bases: object

Placeholder for background job management.

check_job_status(job_id) → str[source]

Poll job status. Returns ‘running’, ‘completed’, or ‘failed’.

collect_results(job_id)[source]

Harvest background triggers from a completed job.

submit_background_job(data_range, config)[source]

Submit a batch job to process background lags.

pycwb.modules.online.data_acquisition module

Data acquisition manager — daemon thread that polls a DataSource, fills per-IFO RingBuffer instances, and produces OnlineSegment objects on a shared queue.

Implements sliding-window segment production: each segment covers duration seconds of data, emitted every stride seconds.

class pycwb.modules.online.data_acquisition.DataAcquisitionManager(config, data_source: DataSource, segment_queue: Queue, stop_event: Event, initial_gps: float = None)[source]

Bases: Thread

Daemon thread that acquires data and enqueues analysis segments.

Parameters:
  • config (Config) – PyCWB configuration (with online extension attributes).

  • data_source (DataSource) – Connected data source adapter.

  • segment_queue (queue.Queue) – Queue into which OnlineSegment objects are placed.

  • stop_event (threading.Event) – Set to signal graceful shutdown.

  • initial_gps (float or None) – GPS time to start from. If None, starts from current GPS.

run()[source]

Main acquisition loop.

stop()[source]

Signal the thread to shut down.

pycwb.modules.online.data_source module

Data source adapters for online data acquisition.

Each adapter implements the DataSource interface, providing connect(), read_chunk(), is_alive(), and close() methods. A factory function create_data_source() selects the adapter from the online_data_source config block.

class pycwb.modules.online.data_source.DataSource[source]

Bases: ABC

Abstract interface for live data streams.

abstractmethod close() → None[source]

Release resources and close the connection.

abstractmethod connect() → None[source]

Establish the connection to the data stream.

abstractmethod is_alive() → bool[source]

Return True if the connection is healthy.

abstractmethod read_chunk(channels: list, start_gps: float, duration: float) → Dict[str, object][source]

Read duration seconds of data starting at start_gps.

Returns a dict mapping channel name to a TimeSeries-like object.

read_dq_chunk(dq_channels: list, start_gps: float, duration: float) → Dict[str, object | None][source]

Read data-quality channels; returns None per channel on failure.

Unlike read_chunk() this method never raises — missing or unreadable DQ channels silently return None so the acquisition loop can continue without the DQ check.

class pycwb.modules.online.data_source.KafkaDataSource(bootstrap_servers: str, topics: dict, group_id: str = 'pycwb-online', buffer_seconds: int = 300, timeout: float = 60)[source]

Bases: DataSource

IGWN Kafka low-latency strain data consumer.

Consumes 1-second GWF binary blobs from per-IFO Kafka topics. A background daemon thread continuously polls the broker and stores decoded TimeSeries frames in a sliding in-memory buffer. read_chunk() assembles the requested window from the buffer, blocking until all required seconds have arrived or timeout elapses.

Parameters:
  • bootstrap_servers (str) – Kafka broker address, e.g. "kafka.scimma.org:9092".

  • topics (dict) – Mapping {ifo: topic_name}, e.g. {"H1": "igwn.ligo.h1.raw", "L1": "igwn.ligo.l1.raw"}.

  • group_id (str) – Kafka consumer group ID.

  • buffer_seconds (int) – How many seconds of data to retain in the in-memory buffer.

  • timeout (float) – Seconds to wait for a required frame before raising TimeoutError.

close() → None[source]

Release resources and close the connection.

connect() → None[source]

Establish the connection to the data stream.

is_alive() → bool[source]

Return True if the connection is healthy.

read_chunk(channels: list, start_gps: float, duration: float) → Dict[str, object][source]

Block until all required 1-second frames are buffered, then return.

class pycwb.modules.online.data_source.NDS2DataSource(host: str = '', port: int = 0)[source]

Bases: DataSource

NDS2 adapter using gwpy.timeseries.TimeSeriesDict.get.

close() → None[source]

Release resources and close the connection.

connect() → None[source]

Establish the connection to the data stream.

is_alive() → bool[source]

Return True if the connection is healthy.

read_chunk(channels, start_gps, duration)[source]

Read duration seconds of data starting at start_gps.

Returns a dict mapping channel name to a TimeSeries-like object.

class pycwb.modules.online.data_source.SharedMemoryDataSource(base_path: str = '/dev/shm/kafka', timeout: float = 30, poll_interval: float = 0.1)[source]

Bases: DataSource

Read 1-second GWF files from a low-latency shared-memory directory tree.

Expects files under {base_path}/{ifo}/ following the standard LIGO low-latency naming convention:

{site}-{ifo}_{stream}-{gps_start}-{duration}.gwf

Example: /dev/shm/kafka/H1/H-H1_llhoft-1257894000-1.gwf

The IFO name is extracted from each channel’s prefix ("H1:GDS-..." → "H1"). read_chunk() reads one file per required GPS second, polling until each file appears or timeout elapses.

Parameters:
  • base_path (str) – Root directory containing per-IFO sub-directories, e.g. "/dev/shm/kafka".

  • timeout (float) – Seconds to wait for a file to appear before raising TimeoutError.

  • poll_interval (float) – Polling interval (seconds) while waiting for new files.

close() → None[source]

Release resources and close the connection.

connect() → None[source]

Establish the connection to the data stream.

is_alive() → bool[source]

Return True if the connection is healthy.

read_chunk(channels: list, start_gps: float, duration: float) → Dict[str, object][source]

Read all required 1-second GWF files, waiting for each to appear.

read_dq_chunk(dq_channels: list, start_gps: float, duration: float) → Dict[str, object | None][source]

Read DQ channels from per-IFO GWF files; returns None per channel when the channel is absent or the file cannot be read.

scan_earliest_gps(ifos) → float | None[source]

Scan all IFO sub-directories and return the earliest GPS second present across all IFOs, or None if no files are found yet.

pycwb.modules.online.data_source.create_data_source(config) → DataSource[source]

Factory: create a DataSource from config.

The adapter type is selected from getattr(config, 'online_data_source', {}).get('type', 'nds2').

pycwb.modules.online.deduplication module

Sliding-window trigger deduplication.

With overlapping segments (stride < duration), the same astrophysical signal may be detected in multiple consecutive segments. This module buffers recent triggers and keeps only the best-ranked instance of each physical event before forwarding it downstream.

class pycwb.modules.online.deduplication.TriggerDeduplicator(gps_window: float = 0.5, sky_tolerance: float = 5.0, flush_delay: float = None)[source]

Bases: object

Buffer triggers and merge duplicates from overlapping segments.

Parameters:
  • gps_window (float) – GPS time coincidence window (seconds).

  • sky_tolerance (float) – Sky position coincidence tolerance (degrees).

  • flush_delay (float or None) – Seconds after wall_time_done before a trigger is considered final. If None, defaults to duration + 2 * stride (set externally by the caller).

flush_all() → List[OnlineTrigger][source]

Flush all pending triggers (e.g. at shutdown).

ingest(trigger: OnlineTrigger) → List[OnlineTrigger][source]

Add a trigger; return any finalized (flushed) triggers.

If trigger matches a pending trigger within the GPS/sky window, the one with the higher rho (effective correlated SNR, i.e. rho[0]) is kept.

pycwb.modules.online.latency_monitor module

Latency and health monitoring daemon thread.

Periodically logs queue depth, processing latency, data staleness, and worker utilisation. Raises warnings when metrics exceed thresholds.

class pycwb.modules.online.latency_monitor.LatencyMonitor(config, segment_queue, ring_buffers, stop_event, n_workers=4)[source]

Bases: Thread

Health monitor for the online search pipeline.

Parameters:
  • config (Config) – PyCWB configuration.

  • segment_queue (queue.Queue) – The segment submission queue (used for depth monitoring).

  • ring_buffers (dict) – {ifo: RingBuffer} — for data staleness checks.

  • stop_event (threading.Event) – Shutdown signal.

  • n_workers (int) – Total analysis worker count (for utilisation logging).

record_latency(latency_seconds: float)[source]

Called by the orchestrator after each segment completes.

run()[source]

Method representing the thread’s activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

stop()[source]

pycwb.modules.online.ring_buffer module

Thread-safe per-IFO ring buffer for online data acquisition.

Stores a contiguous window of data in memory. The data acquisition thread calls append() to add new data; the orchestrator calls snapshot() to extract analysis-ready windows.

class pycwb.modules.online.ring_buffer.RingBuffer(capacity_seconds: float, sample_rate: float)[source]

Bases: object

Fixed-capacity ring buffer for a single IFO channel.

Parameters:
  • capacity_seconds (float) – Maximum duration (seconds) of data retained.

  • sample_rate (float) – Sample rate of incoming data.

append(chunk_data: ndarray, chunk_start_gps: float) → None[source]

Append a contiguous chunk of data.

Parameters:
  • chunk_data (np.ndarray) – 1-D array of samples to append.

  • chunk_start_gps (float) – GPS time of the first sample in chunk_data.

available_new_duration() → float[source]

Seconds of data appended since the last snapshot trigger.

check_and_clear_gap()[source]

Check if a gap was detected and clear the flag.

Returns:

(gap_detected, pre_gap_gps) — the GPS time just before the gap, or None if no gap.

Return type:

tuple (bool, float or None)

property last_gps

GPS time up to which data is available (exclusive boundary).

mark_snapshot() → None[source]

Mark current time as the snapshot reference for stride tracking.

snapshot(start_gps: float, end_gps: float) → ndarray[source]

Return a copy of data in [start_gps, end_gps).

Parameters:
  • start_gps (float) – GPS bounds (end exclusive).

  • end_gps (float) – GPS bounds (end exclusive).

Returns:

Copy of the requested data window.

Return type:

np.ndarray

Raises:

ValueError – If the requested range is outside the buffered window.

pycwb.modules.online.significance module

Real-time significance assignment for online triggers.

Loads a pre-trained XGBoost model and an IFAR lookup table at startup, then maps each trigger’s event features to a ranking statistic and inverse false-alarm rate (IFAR).

pycwb.modules.online.significance.assign_significance(event, model, ifar_table, feature_columns=None)[source]

Assign ranking statistic and IFAR to an event in-place.

Parameters:
  • event (Event) – PyCWB event object. ranking_statistic and ifar attributes are set on the object.

  • model (xgboost.Booster or None) – Pre-trained classifier. If None, significance is not assigned.

  • ifar_table (dict or None) – Mapping from ranking statistic to IFAR.

  • feature_columns (list[str] or None) – Ordered attribute names to extract from event as model input. Defaults to ['rho', 'netcc', 'penalty', 'ecor', 'qveto', 'qfactor'].

pycwb.modules.online.significance.load_significance_model(model_path: str, ifar_file: str)[source]

Load the pre-trained model and IFAR table.

Parameters:
  • model_path (str) – Path to a saved XGBoost model (.json or .ubj). If empty, returns (None, None) and significance assignment becomes a no-op.

  • ifar_file (str) – Path to the IFAR lookup table (NumPy .npz with keys stat and ifar, or CSV with those columns).

Returns:

(model, ifar_table) — model is an xgboost.Booster (or None), ifar_table is a dict with stat and ifar arrays (or None).

Return type:

tuple

pycwb.modules.online.trigger_handler module

Trigger handler — daemon thread that consumes triggers from a queue, applies deduplication and significance, saves locally, and dispatches alerts (GraceDB, webhooks).

Errors in alerting are logged but never crash the pipeline.

class pycwb.modules.online.trigger_handler.TriggerHandler(config, trigger_queue: Queue, stop_event: Event, working_dir: str = '.')[source]

Bases: Thread

Daemon thread that processes triggers from the analysis workers.

Parameters:
  • config (Config) – PyCWB configuration (with online extension attributes).

  • trigger_queue (queue.Queue) – Queue of OnlineTrigger objects (or None sentinel).

  • stop_event (threading.Event) – Shared shutdown flag. The handler keeps consuming worker results after it is set and stops only on the None sentinel.

  • working_dir (str) – Directory for local trigger output.

run()[source]

Method representing the thread’s activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

Module contents

pycwb.modules.online — Streaming GW search pipeline.

Full online/streaming analysis pipeline for real-time GW burst detection. Components include: DataSource (abstract data adapter), DataAcquisitionManager (polling daemon), RingBuffer (thread-safe per-IFO buffer), TriggerHandler (deduplication + significance + GraceDB alerts), BackgroundManager, and LatencyMonitor.