Skip to content

Burst

gwmock_signal.burst

Unmodelled gravitational-wave bursts: ad hoc families, file waveforms and test injection sets.

BurstSimulator

Bases: TransientSimulator

Burst injections: the ad hoc LVK families and numerical waveforms read from file.

Each event names its morphology in burst_model, so one simulator serves a mixed injection set. The event keys follow the per-event record of established burst injection pipelines -- peak time, distance, sky position, polarization angle, inclination, model -- under this package's canonical names:

======================== ==================================================================== burst_model "sine_gaussian", "gaussian", "white_noise_burst", or a name given in waveform_files peak_time GPS time of the waveform's centre at the geocentre, s coa_time optional placement time for segmented output, s; see below right_ascension rad declination rad polarization_angle rad hrss ad hoc families: sqrt(int (h_+^2 + h_x^2) dt) at the Earth distance file waveforms: source distance, Mpc inclination rad; ad hoc families that take it, and file waveforms whose inclination_dependence is not "none" ======================== ====================================================================

plus the family's own shape parameters, listed on each function in :mod:gwmock_signal.burst.waveforms. Keys a model does not use are ignored, so an event may carry labels such as which injection set it belongs to.

A file waveform is scaled by its reference_distance / distance and by the inclination factors of its :class:WaveformFile.

Two times, two meanings. peak_time is the burst's physical reference, and it alone positions the waveform. coa_time is the key a caller writing segmented data places every transient by; it carries no physics for a burst and never moves or changes the waveform. :meth:pre_coalescence_duration and :meth:post_coalescence_duration measure from it -- from peak_time when it is absent -- so coa_time - pre and coa_time + post are where the output starts and ends. coa_time = peak_time is the simple choice; the start of the polarization buffer, or any other instant inside the output, is equally valid and gives the same strain. A coa_time that is not a finite number, or that lies outside the output -- before its first sample or after its end, padding included -- cannot place the event, and is refused with the same ValueError by the two queries, :meth:generate_polarizations and :meth:simulate, so a caller that ignores a failed query still cannot inject a cropped burst.

Projecting on the device. With projection_backend="jax" the projection compiles a kernel per length of series, and a burst injection set comes in thousands of lengths (6,947 among one stream's 53,248 bursts at 8192 Hz). Each burst is therefore projected at a fixed length -- its polarizations padded with zeros to the next length of a ladder with two per octave, and the result cut back -- so that stream compiles 16 kernels per pair of arm lengths in the network, and reuses each; see :func:~gwmock_signal.projection.network.device_length. The strain is bit-identical to an unpadded projection with the finite arms off, and differs by rounding with them on.

Parameters:

Name Type Description Default
waveform_files Mapping[str, WaveformFile] | None

Model name -> :class:WaveformFile. Each file is read once, on first use.

None
ephemeris SolarSystemEphemeris | None

The Earth and Sun tables for the solar-system delays; the LALPulsar DE405 tables by default.

None
projection_backend str

Which implementation evaluates the earth_rotation=True projection, "numpy" (the default) or "jax", as on :class:~gwmock_signal.simulator.CBCSimulator. "jax" needs JAX installed.

'numpy'

Raises:

Type Description
ValueError

If a file model reuses an ad hoc family's name, a value is not a :class:WaveformFile, or projection_backend is not "numpy" or "jax".

Source code in src/gwmock_signal/burst/simulator.py
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
class BurstSimulator(TransientSimulator):
    """Burst injections: the ad hoc LVK families and numerical waveforms read from file.

    Each event names its morphology in ``burst_model``, so one simulator serves a mixed injection
    set. The event keys follow the per-event record of established burst injection pipelines --
    peak time, distance, sky position, polarization angle, inclination, model -- under this
    package's canonical names:

    ========================  ====================================================================
    ``burst_model``           ``"sine_gaussian"``, ``"gaussian"``, ``"white_noise_burst"``, or a
                              name given in ``waveform_files``
    ``peak_time``             GPS time of the waveform's centre at the geocentre, s
    ``coa_time``              optional placement time for segmented output, s; see below
    ``right_ascension``       rad
    ``declination``           rad
    ``polarization_angle``    rad
    ``hrss``                  ad hoc families: ``sqrt(int (h_+^2 + h_x^2) dt)`` at the Earth
    ``distance``              file waveforms: source distance, Mpc
    ``inclination``           rad; ad hoc families that take it, and file waveforms whose
                              ``inclination_dependence`` is not ``"none"``
    ========================  ====================================================================

    plus the family's own shape parameters, listed on each function in
    :mod:`gwmock_signal.burst.waveforms`. Keys a model does not use are ignored, so an event may
    carry labels such as which injection set it belongs to.

    A file waveform is scaled by its ``reference_distance / distance`` and by the inclination
    factors of its :class:`WaveformFile`.

    **Two times, two meanings.** ``peak_time`` is the burst's physical reference, and it alone
    positions the waveform. ``coa_time`` is the key a caller writing segmented data places every
    transient by; it carries no physics for a burst and never moves or changes the waveform.
    :meth:`pre_coalescence_duration` and :meth:`post_coalescence_duration` measure from it -- from
    ``peak_time`` when it is absent -- so ``coa_time - pre`` and ``coa_time + post`` are where the
    output starts and ends. ``coa_time = peak_time`` is the simple choice; the start of the
    polarization buffer, or any other instant inside the output, is equally valid and gives the
    same strain. A ``coa_time`` that is not a finite number, or that lies outside the output -- before
    its first sample or after its end, padding included -- cannot place the event, and is refused
    with the same ``ValueError`` by the two queries, :meth:`generate_polarizations` and
    :meth:`simulate`, so a caller that ignores a failed query still cannot inject a cropped burst.

    **Projecting on the device.** With ``projection_backend="jax"`` the projection compiles a kernel
    per length of series, and a burst injection set comes in thousands of lengths (6,947 among one
    stream's 53,248 bursts at 8192 Hz). Each burst is therefore projected at a fixed length -- its
    polarizations padded with zeros to the next length of a ladder with two per octave, and the result
    cut back -- so that stream compiles 16 kernels per pair of arm lengths in the network, and reuses each; see
    :func:`~gwmock_signal.projection.network.device_length`. The strain is bit-identical to an unpadded
    projection with the finite arms off, and differs by rounding with them on.

    Args:
        waveform_files: Model name -> :class:`WaveformFile`. Each file is read once, on first use.
        ephemeris: The Earth and Sun tables for the solar-system delays; the LALPulsar DE405 tables by
            default.
        projection_backend: Which implementation evaluates the ``earth_rotation=True`` projection,
            ``"numpy"`` (the default) or ``"jax"``, as on
            :class:`~gwmock_signal.simulator.CBCSimulator`. ``"jax"`` needs JAX installed.

    Raises:
        ValueError: If a file model reuses an ad hoc family's name, a value is not a
            :class:`WaveformFile`, or *projection_backend* is not ``"numpy"`` or ``"jax"``.
    """

    fixed_device_lengths = True

    def __init__(
        self,
        *,
        waveform_files: Mapping[str, WaveformFile] | None = None,
        ephemeris: SolarSystemEphemeris | None = None,
        projection_backend: str = "numpy",
    ) -> None:
        """Initialise with the optional numerical waveform files, the solar-system tables and the projection backend."""
        self.projection_backend = use_projection_backend(projection_backend)
        files = dict(waveform_files or {})
        shadowed = sorted(set(files) & set(PARAMETRIC_MODELS))
        if shadowed:
            raise ValueError(f"waveform_files may not reuse the ad hoc model names {shadowed}.")
        wrong = sorted(name for name, entry in files.items() if not isinstance(entry, WaveformFile))
        if wrong:
            raise ValueError(f"waveform_files values must be WaveformFile instances; {wrong} are not.")
        self._waveform_files: dict[str, WaveformFile] = files
        self._file_cache: dict[str, tuple[np.ndarray, np.ndarray, np.ndarray]] = {}
        self._extent_cache: OrderedDict[Any, tuple[float, float, float]] = OrderedDict()
        if ephemeris is not None:
            self.ephemeris = ephemeris

    def timing_reference(self, params: Mapping[str, Any]) -> float:
        """Return ``peak_time``, the burst's physical reference, where its solar-system delay is absorbed."""
        return _finite_time(params, "peak_time")

    @property
    def required_params(self) -> frozenset[str]:
        """Return the keys every burst event must carry."""
        return _REQUIRED

    def pre_coalescence_duration(
        self,
        params: Mapping[str, Any],
        sampling_frequency: float,
        minimum_frequency: float,
    ) -> float:
        """Return how long before the placement time this simulator's output starts, in seconds.

        The burst counterpart of :meth:`CBCSimulator.pre_coalescence_duration
        <gwmock_signal.simulator.CBCSimulator.pre_coalescence_duration>`, with the same call, so a
        caller placing transients into segmented data can ask either simulator alike. For a burst
        "coalescence" is the placement time: ``coa_time`` when the event gives one, else
        ``peak_time``. A burst's buffer is centred on its peak, so a peak just past a segment
        boundary has content belonging to the segment before -- up to 5.6 s of it for a
        ``Q = 100`` sine-Gaussian at 30 Hz -- and the caller needs this answer to claim it there.

        **Measured, not modelled.** The answer is read off the polarization buffer
        :meth:`generate_polarizations` returns for this very event and sample rate, so it is exact
        by construction for every family, including the numerical ones, and cannot drift from the
        generator: no copy of LALSimulation's buffer-sizing rules is kept here. The cost is one
        generation of the polarizations -- no projection -- per distinct event. At 8192 Hz that was
        measured at about 7 ms for a draft white-noise burst, 2.8 ms for the longest buffer (a
        91,265-sample ``Q = 100`` sine-Gaussian at 30 Hz) and under 0.3 ms for every other draft
        family, small beside the projection :meth:`simulate` then pays. The extent is remembered
        for the last few events, so the start and end queries and repeats for the same event share
        one generation.

        Args:
            params: One burst event, as :meth:`simulate` takes it.
            sampling_frequency: Sample rate in Hz.
            minimum_frequency: Unused, as in :meth:`generate_polarizations`; accepted so the call
                matches the compact-binary simulator's.

        Returns:
            Seconds from the first sample :meth:`simulate` returns to the placement time,
            including the padding the projection adds before the polarizations (see
            :func:`~gwmock_signal.simulator._projected_duration`). Never ``None``: a burst's
            buffer is always known, and never negative.

        Raises:
            ValueError: As :meth:`generate_polarizations`, for an event it would refuse; if
                ``coa_time`` is given and is not a finite number; or if the placement time lies
                outside the output (before its first sample or past its end), where no segment
                claimed from it could hold the event as placed.
        """
        del minimum_frequency
        lead, _ = self._buffer_extent(params, sampling_frequency)
        return lead

    def post_coalescence_duration(
        self,
        params: Mapping[str, Any],
        sampling_frequency: float,
        minimum_frequency: float,
    ) -> float:
        """Return how long after the placement time this simulator's output runs, in seconds.

        The complement of :meth:`pre_coalescence_duration`, measured the same way from the same
        buffer and remembered with it.

        Args:
            params: One burst event, as :meth:`simulate` takes it.
            sampling_frequency: Sample rate in Hz.
            minimum_frequency: Unused; accepted so the call matches the compact-binary simulator's.

        Returns:
            Seconds from the placement time to one sample past the last sample :meth:`simulate`
            returns, including the projection's padding after the polarizations; never negative.

        Raises:
            ValueError: As :meth:`pre_coalescence_duration`.
        """
        del minimum_frequency
        _, tail = self._buffer_extent(params, sampling_frequency)
        return tail

    def _buffer_extent(self, params: Mapping[str, Any], sampling_frequency: float) -> tuple[float, float]:
        """Return ``(lead, tail)`` of the projected output around the placement time, in seconds."""
        _placement_time(params)  # Refuse unusable times before paying for a generation.
        key = _span_key(params, sampling_frequency)
        span = self._extent_cache.get(key) if key is not None else None
        if span is None:
            span = self._remember(key, *self._generate(params, sampling_frequency))
        elif key is not None:
            self._extent_cache.move_to_end(key)
        return _placement_extent(params, span)

    def _remember(self, key: Any, hp: TimeSeries, hc: TimeSeries) -> tuple[float, float, float]:
        """Return the polarization buffer's ``(start, end, sample_rate)``, remembering it under *key*.

        Remembered per event without ``coa_time``, which generation never reads, so an event asked
        about under several placement times, and then generated, is generated once per query run.
        """
        span = (
            min(hp.t0, hc.t0),
            max(hp.t0 + hp.n_samples / hp.sample_rate, hc.t0 + hc.n_samples / hc.sample_rate),
            hp.sample_rate,
        )
        if key is not None:
            self._extent_cache[key] = span
            self._extent_cache.move_to_end(key)
            if len(self._extent_cache) > _EXTENT_CACHE_SIZE:
                self._extent_cache.popitem(last=False)
        return span

    @property
    def burst_models(self) -> tuple[str, ...]:
        """Return every ``burst_model`` this instance can generate."""
        return (*PARAMETRIC_MODELS, *self._waveform_files)

    def generate_polarizations(
        self,
        params: Mapping[str, Any],
        sampling_frequency: float,
        minimum_frequency: float,
    ) -> tuple[TimeSeries, TimeSeries]:
        """Return ``(h_plus, h_cross)`` for one burst event, centred on its ``peak_time``.

        Args:
            params: One burst event; see the class docstring.
            sampling_frequency: Sample rate in Hz.
            minimum_frequency: Unused. A burst's band is set by its own parameters, and cutting
                it here would change the hrss the event records.

        Returns:
            Tuple of ``(hp, hc)`` series.

        Raises:
            ValueError: If ``burst_model`` is unknown or the event lacks one of its parameters; or
                if the event gives a ``coa_time`` the duration queries refuse -- not a finite
                number, or outside the projected output. The check is the queries' own, made on the
                buffer just generated, so it costs no second generation. Without ``coa_time`` the
                event is generated as before.
        """
        placed = params.get("coa_time") is not None
        if placed:
            _placement_time(params)  # Refuse an unusable time before paying for a generation.
        hp, hc = self._generate(params, sampling_frequency)
        if placed:
            _placement_extent(params, self._remember(_span_key(params, sampling_frequency), hp, hc))
        return hp, hc

    def _generate(self, params: Mapping[str, Any], sampling_frequency: float) -> tuple[TimeSeries, TimeSeries]:
        """Return the polarizations for *params*, centred on ``peak_time``; ``coa_time`` is not read."""
        model = params["burst_model"]
        if model in PARAMETRIC_MODELS:
            return PARAMETRIC_MODELS[model](params, sampling_frequency)
        if model in self._waveform_files:
            return self._file_polarizations(model, params, sampling_frequency)
        raise ValueError(f"Unknown burst_model {model!r}; this simulator knows {list(self.burst_models)}.")

    def _file_polarizations(
        self, model: str, params: Mapping[str, Any], sampling_frequency: float
    ) -> tuple[TimeSeries, TimeSeries]:
        """Return a file waveform placed at ``peak_time``, scaled to ``distance``, at the target rate."""
        entry = self._waveform_files[model]
        needed = ["distance"] + ([] if entry.inclination_dependence == "none" else ["inclination"])
        missing = [key for key in needed if key not in params]
        if missing:
            raise ValueError(f"burst_model {model!r} needs parameters {missing}.")
        distance = float(params["distance"])
        if not (math.isfinite(distance) and distance > 0):
            raise ValueError(f"distance must be finite and positive, got {params['distance']!r}.")
        inclination = float(params.get("inclination", 0.0))
        if not math.isfinite(inclination):
            raise ValueError(f"inclination must be finite, got {params['inclination']!r}.")
        if model not in self._file_cache:
            self._file_cache[model] = read_waveform_file(entry.path)
        times, plus, cross = self._file_cache[model]

        scale = entry.reference_distance / distance
        plus_factor, cross_factor = _INCLINATION_FACTORS[entry.inclination_dependence](inclination)
        t0 = float(params["peak_time"]) + times[0]
        file_rate = 1.0 / (times[1] - times[0])
        resample = not math.isclose(file_rate, sampling_frequency, rel_tol=1e-9)
        series = []
        for strain, factor, name in ((plus, plus_factor, "plus"), (cross, cross_factor, "cross")):
            values = scale * factor * np.asarray(strain, dtype=float)
            if resample:
                values = _resample(values, file_rate, sampling_frequency)
            rate = sampling_frequency if resample else file_rate
            series.append(TimeSeries(values, t0=t0, sample_rate=rate, name=name))
        return series[0], series[1]

burst_models property

Return every burst_model this instance can generate.

required_params property

Return the keys every burst event must carry.

__init__(*, waveform_files=None, ephemeris=None, projection_backend='numpy')

Initialise with the optional numerical waveform files, the solar-system tables and the projection backend.

Source code in src/gwmock_signal/burst/simulator.py
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
def __init__(
    self,
    *,
    waveform_files: Mapping[str, WaveformFile] | None = None,
    ephemeris: SolarSystemEphemeris | None = None,
    projection_backend: str = "numpy",
) -> None:
    """Initialise with the optional numerical waveform files, the solar-system tables and the projection backend."""
    self.projection_backend = use_projection_backend(projection_backend)
    files = dict(waveform_files or {})
    shadowed = sorted(set(files) & set(PARAMETRIC_MODELS))
    if shadowed:
        raise ValueError(f"waveform_files may not reuse the ad hoc model names {shadowed}.")
    wrong = sorted(name for name, entry in files.items() if not isinstance(entry, WaveformFile))
    if wrong:
        raise ValueError(f"waveform_files values must be WaveformFile instances; {wrong} are not.")
    self._waveform_files: dict[str, WaveformFile] = files
    self._file_cache: dict[str, tuple[np.ndarray, np.ndarray, np.ndarray]] = {}
    self._extent_cache: OrderedDict[Any, tuple[float, float, float]] = OrderedDict()
    if ephemeris is not None:
        self.ephemeris = ephemeris

generate_polarizations(params, sampling_frequency, minimum_frequency)

Return (h_plus, h_cross) for one burst event, centred on its peak_time.

Parameters:

Name Type Description Default
params Mapping[str, Any]

One burst event; see the class docstring.

required
sampling_frequency float

Sample rate in Hz.

required
minimum_frequency float

Unused. A burst's band is set by its own parameters, and cutting it here would change the hrss the event records.

required

Returns:

Type Description
tuple[TimeSeries, TimeSeries]

Tuple of (hp, hc) series.

Raises:

Type Description
ValueError

If burst_model is unknown or the event lacks one of its parameters; or if the event gives a coa_time the duration queries refuse -- not a finite number, or outside the projected output. The check is the queries' own, made on the buffer just generated, so it costs no second generation. Without coa_time the event is generated as before.

Source code in src/gwmock_signal/burst/simulator.py
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
def generate_polarizations(
    self,
    params: Mapping[str, Any],
    sampling_frequency: float,
    minimum_frequency: float,
) -> tuple[TimeSeries, TimeSeries]:
    """Return ``(h_plus, h_cross)`` for one burst event, centred on its ``peak_time``.

    Args:
        params: One burst event; see the class docstring.
        sampling_frequency: Sample rate in Hz.
        minimum_frequency: Unused. A burst's band is set by its own parameters, and cutting
            it here would change the hrss the event records.

    Returns:
        Tuple of ``(hp, hc)`` series.

    Raises:
        ValueError: If ``burst_model`` is unknown or the event lacks one of its parameters; or
            if the event gives a ``coa_time`` the duration queries refuse -- not a finite
            number, or outside the projected output. The check is the queries' own, made on the
            buffer just generated, so it costs no second generation. Without ``coa_time`` the
            event is generated as before.
    """
    placed = params.get("coa_time") is not None
    if placed:
        _placement_time(params)  # Refuse an unusable time before paying for a generation.
    hp, hc = self._generate(params, sampling_frequency)
    if placed:
        _placement_extent(params, self._remember(_span_key(params, sampling_frequency), hp, hc))
    return hp, hc

polarizations_tapered(params, sampling_frequency)

Whether the polarizations generated for params at sampling_frequency fall smoothly to zero at both ends.

If so, the projection and the injection oversample them exactly and place them accurately up to Nyquist. False unless a subclass knows better; see :meth:~gwmock_signal.waveform.backends.base.WaveformBackend.tapers_polarizations.

Source code in src/gwmock_signal/simulator.py
211
212
213
214
215
216
217
218
def polarizations_tapered(self, params: Mapping[str, Any], sampling_frequency: float) -> bool:
    """Whether the polarizations generated for *params* at *sampling_frequency* fall smoothly to zero at both ends.

    If so, the projection and the injection oversample them exactly and place them accurately up to
    Nyquist. False unless a subclass knows better; see
    :meth:`~gwmock_signal.waveform.backends.base.WaveformBackend.tapers_polarizations`.
    """
    return False

post_coalescence_duration(params, sampling_frequency, minimum_frequency)

Return how long after the placement time this simulator's output runs, in seconds.

The complement of :meth:pre_coalescence_duration, measured the same way from the same buffer and remembered with it.

Parameters:

Name Type Description Default
params Mapping[str, Any]

One burst event, as :meth:simulate takes it.

required
sampling_frequency float

Sample rate in Hz.

required
minimum_frequency float

Unused; accepted so the call matches the compact-binary simulator's.

required

Returns:

Type Description
float

Seconds from the placement time to one sample past the last sample :meth:simulate

float

returns, including the projection's padding after the polarizations; never negative.

Raises:

Type Description
ValueError

As :meth:pre_coalescence_duration.

Source code in src/gwmock_signal/burst/simulator.py
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
def post_coalescence_duration(
    self,
    params: Mapping[str, Any],
    sampling_frequency: float,
    minimum_frequency: float,
) -> float:
    """Return how long after the placement time this simulator's output runs, in seconds.

    The complement of :meth:`pre_coalescence_duration`, measured the same way from the same
    buffer and remembered with it.

    Args:
        params: One burst event, as :meth:`simulate` takes it.
        sampling_frequency: Sample rate in Hz.
        minimum_frequency: Unused; accepted so the call matches the compact-binary simulator's.

    Returns:
        Seconds from the placement time to one sample past the last sample :meth:`simulate`
        returns, including the projection's padding after the polarizations; never negative.

    Raises:
        ValueError: As :meth:`pre_coalescence_duration`.
    """
    del minimum_frequency
    _, tail = self._buffer_extent(params, sampling_frequency)
    return tail

pre_coalescence_duration(params, sampling_frequency, minimum_frequency)

Return how long before the placement time this simulator's output starts, in seconds.

The burst counterpart of :meth:CBCSimulator.pre_coalescence_duration <gwmock_signal.simulator.CBCSimulator.pre_coalescence_duration>, with the same call, so a caller placing transients into segmented data can ask either simulator alike. For a burst "coalescence" is the placement time: coa_time when the event gives one, else peak_time. A burst's buffer is centred on its peak, so a peak just past a segment boundary has content belonging to the segment before -- up to 5.6 s of it for a Q = 100 sine-Gaussian at 30 Hz -- and the caller needs this answer to claim it there.

Measured, not modelled. The answer is read off the polarization buffer :meth:generate_polarizations returns for this very event and sample rate, so it is exact by construction for every family, including the numerical ones, and cannot drift from the generator: no copy of LALSimulation's buffer-sizing rules is kept here. The cost is one generation of the polarizations -- no projection -- per distinct event. At 8192 Hz that was measured at about 7 ms for a draft white-noise burst, 2.8 ms for the longest buffer (a 91,265-sample Q = 100 sine-Gaussian at 30 Hz) and under 0.3 ms for every other draft family, small beside the projection :meth:simulate then pays. The extent is remembered for the last few events, so the start and end queries and repeats for the same event share one generation.

Parameters:

Name Type Description Default
params Mapping[str, Any]

One burst event, as :meth:simulate takes it.

required
sampling_frequency float

Sample rate in Hz.

required
minimum_frequency float

Unused, as in :meth:generate_polarizations; accepted so the call matches the compact-binary simulator's.

required

Returns:

Type Description
float

Seconds from the first sample :meth:simulate returns to the placement time,

float

including the padding the projection adds before the polarizations (see

float

func:~gwmock_signal.simulator._projected_duration). Never None: a burst's

float

buffer is always known, and never negative.

Raises:

Type Description
ValueError

As :meth:generate_polarizations, for an event it would refuse; if coa_time is given and is not a finite number; or if the placement time lies outside the output (before its first sample or past its end), where no segment claimed from it could hold the event as placed.

Source code in src/gwmock_signal/burst/simulator.py
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
def pre_coalescence_duration(
    self,
    params: Mapping[str, Any],
    sampling_frequency: float,
    minimum_frequency: float,
) -> float:
    """Return how long before the placement time this simulator's output starts, in seconds.

    The burst counterpart of :meth:`CBCSimulator.pre_coalescence_duration
    <gwmock_signal.simulator.CBCSimulator.pre_coalescence_duration>`, with the same call, so a
    caller placing transients into segmented data can ask either simulator alike. For a burst
    "coalescence" is the placement time: ``coa_time`` when the event gives one, else
    ``peak_time``. A burst's buffer is centred on its peak, so a peak just past a segment
    boundary has content belonging to the segment before -- up to 5.6 s of it for a
    ``Q = 100`` sine-Gaussian at 30 Hz -- and the caller needs this answer to claim it there.

    **Measured, not modelled.** The answer is read off the polarization buffer
    :meth:`generate_polarizations` returns for this very event and sample rate, so it is exact
    by construction for every family, including the numerical ones, and cannot drift from the
    generator: no copy of LALSimulation's buffer-sizing rules is kept here. The cost is one
    generation of the polarizations -- no projection -- per distinct event. At 8192 Hz that was
    measured at about 7 ms for a draft white-noise burst, 2.8 ms for the longest buffer (a
    91,265-sample ``Q = 100`` sine-Gaussian at 30 Hz) and under 0.3 ms for every other draft
    family, small beside the projection :meth:`simulate` then pays. The extent is remembered
    for the last few events, so the start and end queries and repeats for the same event share
    one generation.

    Args:
        params: One burst event, as :meth:`simulate` takes it.
        sampling_frequency: Sample rate in Hz.
        minimum_frequency: Unused, as in :meth:`generate_polarizations`; accepted so the call
            matches the compact-binary simulator's.

    Returns:
        Seconds from the first sample :meth:`simulate` returns to the placement time,
        including the padding the projection adds before the polarizations (see
        :func:`~gwmock_signal.simulator._projected_duration`). Never ``None``: a burst's
        buffer is always known, and never negative.

    Raises:
        ValueError: As :meth:`generate_polarizations`, for an event it would refuse; if
            ``coa_time`` is given and is not a finite number; or if the placement time lies
            outside the output (before its first sample or past its end), where no segment
            claimed from it could hold the event as placed.
    """
    del minimum_frequency
    lead, _ = self._buffer_extent(params, sampling_frequency)
    return lead

register_waveform_model(name, factory)

Register a one-shot waveform generator under name for this instance.

Re-registering the same name with an equal factory is a no-op. Reusing the name for a different factory raises ValueError.

Parameters:

Name Type Description Default
name str

Waveform model name used later as waveform_model.

required
factory RegisteredWaveformFactory

Callable returning either (plus, cross) or a {"plus": ..., "cross": ...} mapping, or a WaveformBackend whose generate_td_waveform method should serve that name.

required
Source code in src/gwmock_signal/simulator.py
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
def register_waveform_model(
    self,
    name: str,
    factory: RegisteredWaveformFactory,
) -> None:
    """Register a one-shot waveform generator under ``name`` for this instance.

    Re-registering the same name with an equal factory is a no-op. Reusing
    the name for a different factory raises ``ValueError``.

    Args:
        name: Waveform model name used later as ``waveform_model``.
        factory: Callable returning either ``(plus, cross)`` or a
            ``{"plus": ..., "cross": ...}`` mapping, or a ``WaveformBackend``
            whose ``generate_td_waveform`` method should serve that name.
    """
    if not hasattr(self, "_waveform_factory"):
        raise AttributeError(
            "TransientSimulator subclasses must initialize _waveform_factory before registering waveform models."
        )

    registered_factories = self.__dict__.setdefault("_registered_waveform_models", {})
    if name in registered_factories:
        if registered_factories[name] == factory:
            return
        raise ValueError(f"Waveform model {name!r} is already registered for this simulator instance.")

    try:
        self._waveform_factory.get_model(name)
    except ValueError:
        pass
    else:
        raise ValueError(f"Waveform model {name!r} is already registered for this simulator instance.")

    if not isinstance(factory, WaveformBackend) and not callable(factory):
        raise TypeError(f"Waveform model {name!r} must be registered with a callable or WaveformBackend.")

    wrapped_factory = (
        _wrap_registered_waveform_backend(name, factory)
        if isinstance(factory, WaveformBackend)
        else _wrap_registered_waveform_callable(factory)
    )
    self._waveform_factory.register_model(name, wrapped_factory)
    registered_factories[name] = factory

simulate(params, detector_names, background=None, *, sampling_frequency, minimum_frequency, effects=None, interpolate_if_offset=True, earth_rotation=None, finite_arm_length=None, output_grid=None)

Run the full injection pipeline and return a DetectorStrainStack.

Calls _validate_params and generate_polarizations, projects the polarizations onto the network and injects them into the background, as project_polarizations_to_network and inject_strain do, then assembles the result into a DetectorStrainStack.

Parameters:

Name Type Description Default
params Mapping[str, Any]

Source parameters; must contain all required_params keys plus right_ascension, declination, and polarization_angle for antenna-response projection.

required
detector_names Sequence[str | CustomDetector]

IFO codes (e.g. 'H1', 'L1', 'V1').

required
background Mapping[str, TimeSeries | TimeSeries] | None

Optional mapping of detector name to background TimeSeries (e.g. noise or zeros), the package's or GWpy's. If omitted, the projected detector response is returned directly on the waveform time grid, or on output_grid when that is given, extended at each end by the padding that keeps the geocentre-to-detector delay from pushing signal out of the buffer; see :func:~gwmock_signal.projection.network.project_polarizations_to_network.

None
sampling_frequency float

Sample rate in Hz.

required
minimum_frequency float

Low-frequency cutoff in Hz.

required
effects ProjectionEffects | None

Which physical effects the projection includes; see :class:~gwmock_signal.projection.effects.ProjectionEffects. None, the default, means all of them. The solar-system delays are absorbed at :meth:timing_reference, and use the tables in :attr:ephemeris.

None
interpolate_if_offset bool

If True, interpolate the injection when its start is not on a target sample boundary.

True
earth_rotation bool | None

Deprecated; effects=ProjectionEffects(earth_rotation=...). Overrides that field when given.

None
finite_arm_length bool | None

Deprecated; effects=ProjectionEffects(finite_arm_length=...). Overrides that field when given.

None
output_grid SamplingGrid | None

A lattice for the projected strain, such as the segment it will be added to; see :func:~gwmock_signal.projection.network.project_polarizations_to_network. Without background, the returned strain then starts on it, so it is added to that segment without being resampled again.

None

Returns:

Type Description
DetectorStrainStack

DetectorStrainStack containing the simulated strain for each

DetectorStrainStack

detector in detector_names order.

Note

Which implementation projects is read from :attr:projection_backend, not taken here: it is a property of how the simulator was set up, and the two implementations agree to ~1e-10 of peak, so it is not a per-call decision about the answer.

Source code in src/gwmock_signal/simulator.py
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
def simulate(  # noqa: PLR0913
    self,
    params: Mapping[str, Any],
    detector_names: Sequence[str | CustomDetector],
    background: Mapping[str, TimeSeries | gwpy.timeseries.TimeSeries] | None = None,
    *,
    sampling_frequency: float,
    minimum_frequency: float,
    effects: ProjectionEffects | None = None,
    interpolate_if_offset: bool = True,
    earth_rotation: bool | None = None,
    finite_arm_length: bool | None = None,
    output_grid: SamplingGrid | None = None,
) -> DetectorStrainStack:
    """Run the full injection pipeline and return a ``DetectorStrainStack``.

    Calls ``_validate_params`` and ``generate_polarizations``, projects the polarizations
    onto the network and injects them into the background, as
    ``project_polarizations_to_network`` and ``inject_strain`` do, then assembles the
    result into a ``DetectorStrainStack``.

    Args:
        params: Source parameters; must contain all ``required_params`` keys
            plus ``right_ascension``, ``declination``, and ``polarization_angle``
            for antenna-response projection.
        detector_names: IFO codes (e.g. ``'H1'``, ``'L1'``, ``'V1'``).
        background: Optional mapping of detector name to background
            ``TimeSeries`` (e.g. noise or zeros), the package's or GWpy's. If omitted, the projected
            detector response is returned directly on the waveform time grid, or on
            ``output_grid`` when that is given, extended at each
            end by the padding that keeps the geocentre-to-detector delay from pushing signal
            out of the buffer; see
            :func:`~gwmock_signal.projection.network.project_polarizations_to_network`.
        sampling_frequency: Sample rate in Hz.
        minimum_frequency: Low-frequency cutoff in Hz.
        effects: Which physical effects the projection includes; see
            :class:`~gwmock_signal.projection.effects.ProjectionEffects`. ``None``, the default,
            means all of them. The solar-system delays are absorbed at
            :meth:`timing_reference`, and use the tables in :attr:`ephemeris`.
        interpolate_if_offset: If ``True``, interpolate the injection
            when its start is not on a target sample boundary.
        earth_rotation: Deprecated; ``effects=ProjectionEffects(earth_rotation=...)``. Overrides
            that field when given.
        finite_arm_length: Deprecated; ``effects=ProjectionEffects(finite_arm_length=...)``. Overrides
            that field when given.
        output_grid: A lattice for the projected strain, such as the segment it will be added to;
            see :func:`~gwmock_signal.projection.network.project_polarizations_to_network`. Without
            ``background``, the returned strain then starts on it, so it is added to that segment
            without being resampled again.

    Returns:
        ``DetectorStrainStack`` containing the simulated strain for each
        detector in ``detector_names`` order.

    Note:
        Which implementation projects is read from :attr:`projection_backend`, not taken
        here: it is a property of how the simulator was set up, and the two implementations
        agree to ~1e-10 of peak, so it is not a per-call decision about the answer.
    """
    self._validate_params(params)

    # Validate projection keys before direct params[...] access.
    # _validate_params only checks subclass-defined required_params. Non-CBC subclasses can pass validation and then fail mid-pipeline with KeyError.
    projection_keys = {"right_ascension", "declination", "polarization_angle"}
    missing_projection = projection_keys - set(params)
    if missing_projection:
        raise ValueError(f"Missing required parameters: {sorted(missing_projection)}")

    # Normalise detector entries so dict lookups use plain string keys.
    str_names: list[str] = [d.name if hasattr(d, "name") and not isinstance(d, str) else d for d in detector_names]

    hp, hc = self.generate_polarizations(params, sampling_frequency, minimum_frequency)
    projected = _project(
        {"plus": hp, "cross": hc},
        detector_names,
        right_ascension=params["right_ascension"],
        declination=params["declination"],
        polarization_angle=params["polarization_angle"],
        effects=_resolve_effects(
            effects,
            earth_rotation=earth_rotation,
            finite_arm_length=finite_arm_length,
            caller=f"{type(self).__name__}.simulate",
        ),
        backend=self.projection_backend,
        sinc_taps=DEFAULT_SINC_TAPS,
        kaiser_beta=DEFAULT_KAISER_BETA,
        tapered=self.polarizations_tapered(params, sampling_frequency),
        ephemeris=self.ephemeris,
        reference_time=self.timing_reference(params),
        output_grid=output_grid,
        fixed_lengths=self.fixed_device_lengths,
    )
    if background is None:
        return DetectorStrainStack.from_mapping(str_names, projected)
    backgrounds = {name: as_timeseries(background[name]) for name in str_names}
    injected = {
        name: _inject(
            backgrounds[name],
            projected[name],
            interpolate_if_offset=interpolate_if_offset,
            tapered=self.polarizations_tapered(params, sampling_frequency),
            # Built on `output_grid`, so on a background on that same lattice any fraction in its
            # offset is the rounding of its timestamps (up to half a float64 step: at 4000 Hz, 2.4e-4 of a sample at GPS 1e9), not a
            # shift: it is added by whole samples. A background on another lattice is placed as before.
            on_grid=output_grid is not None
            and backgrounds[name].sample_rate == output_grid.sampling_frequency
            and bool(output_grid.is_on_lattice(backgrounds[name].t0)),
        )
        for name in str_names
    }
    return DetectorStrainStack.from_mapping(str_names, injected)

timing_reference(params)

Return peak_time, the burst's physical reference, where its solar-system delay is absorbed.

Source code in src/gwmock_signal/burst/simulator.py
329
330
331
def timing_reference(self, params: Mapping[str, Any]) -> float:
    """Return ``peak_time``, the burst's physical reference, where its solar-system delay is absorbed."""
    return _finite_time(params, "peak_time")

WaveformFile dataclass

A numerical burst waveform on disk and how to place it.

Attributes:

Name Type Description
path str | Path

Text file of t h_+ h_x columns (see :func:~gwmock_signal.burst.waveforms.read_waveform_file).

reference_distance float

Distance, in Mpc, at which the file's strains are given.

inclination_dependence InclinationDependence

How the strain varies with the event's inclination:

  • "none" -- used as written, whatever the inclination;
  • "axisymmetric" -- an axisymmetric (m = 0) quadrupole, given edge-on: h_+ is scaled by sin^2(iota) and h_x is zero;
  • "rotating" -- a rotating (m = +-2) quadrupole, given face-on: h_+ is scaled by (1 + cos^2 iota) / 2 and h_x by cos(iota).

Raises:

Type Description
ValueError

If reference_distance is not finite and positive, or inclination_dependence is not one of the three above.

Source code in src/gwmock_signal/burst/simulator.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
@dataclass(frozen=True)
class WaveformFile:
    """A numerical burst waveform on disk and how to place it.

    Attributes:
        path: Text file of ``t h_+ h_x`` columns (see
            :func:`~gwmock_signal.burst.waveforms.read_waveform_file`).
        reference_distance: Distance, in Mpc, at which the file's strains are given.
        inclination_dependence: How the strain varies with the event's ``inclination``:

            * ``"none"`` -- used as written, whatever the inclination;
            * ``"axisymmetric"`` -- an axisymmetric (``m = 0``) quadrupole, given edge-on:
              ``h_+`` is scaled by ``sin^2(iota)`` and ``h_x`` is zero;
            * ``"rotating"`` -- a rotating (``m = +-2``) quadrupole, given face-on: ``h_+`` is
              scaled by ``(1 + cos^2 iota) / 2`` and ``h_x`` by ``cos(iota)``.

    Raises:
        ValueError: If ``reference_distance`` is not finite and positive, or
            ``inclination_dependence`` is not one of the three above.
    """

    path: str | Path
    reference_distance: float
    inclination_dependence: InclinationDependence = "none"

    def __post_init__(self) -> None:
        """Refuse a distance or an inclination dependence the simulator could not apply."""
        if not (math.isfinite(self.reference_distance) and self.reference_distance > 0):
            raise ValueError(f"reference_distance must be finite and positive (Mpc), got {self.reference_distance!r}.")
        if self.inclination_dependence not in _INCLINATION_FACTORS:
            raise ValueError(
                f"inclination_dependence must be one of {sorted(_INCLINATION_FACTORS)}, "
                f"got {self.inclination_dependence!r}."
            )

__post_init__()

Refuse a distance or an inclination dependence the simulator could not apply.

Source code in src/gwmock_signal/burst/simulator.py
224
225
226
227
228
229
230
231
232
def __post_init__(self) -> None:
    """Refuse a distance or an inclination dependence the simulator could not apply."""
    if not (math.isfinite(self.reference_distance) and self.reference_distance > 0):
        raise ValueError(f"reference_distance must be finite and positive (Mpc), got {self.reference_distance!r}.")
    if self.inclination_dependence not in _INCLINATION_FACTORS:
        raise ValueError(
            f"inclination_dependence must be one of {sorted(_INCLINATION_FACTORS)}, "
            f"got {self.inclination_dependence!r}."
        )

draw_burst_injection_set(*, start_time, end_time, interval, hrss_range, rng, families=DRAFT_BURST_FAMILIES, sine_gaussian_frequency_range=(30.0, 1800.0))

Return one burst event every interval seconds in [start_time, end_time).

Events sit at start_time + (k + 1/2) * interval, so none straddles either end. Each event takes a family chosen uniformly from families, then draws whatever the family does not fix:

  • sky position isotropic, polarization angle uniform in [0, pi);
  • hrss log-uniform in hrss_range;
  • inclination uniform in cos(iota) for sine-Gaussians and white-noise bursts;
  • frequency log-uniform in sine_gaussian_frequency_range for sine-Gaussians;
  • seed for white-noise bursts, so each event's noise realisation is reproducible.

Nothing is drawn for a family whose burst_model names a numerical waveform file, so such a family must fix its own distance (and inclination, when its file's response depends on it); a family without a distance is refused here rather than when the event is simulated.

Parameters:

Name Type Description Default
start_time float

GPS start of the span, s.

required
end_time float

GPS end of the span, s.

required
interval float

Seconds between consecutive events; the fixed test-set rate is 1 / interval.

required
hrss_range tuple[float, float]

(low, high) bounds of the log-uniform hrss distribution. No default: the range must straddle the detection threshold of the network being tested.

required
rng Generator

Source of randomness; pass a seeded generator for a reproducible set.

required
families Sequence[Mapping[str, Any]]

Family templates, each a mapping with burst_model and any fixed parameters.

DRAFT_BURST_FAMILIES
sine_gaussian_frequency_range tuple[float, float]

(low, high) Hz for sine-Gaussian central frequencies.

(30.0, 1800.0)

Returns:

Type Description
list[dict[str, Any]]

One event mapping per injection, in time order, each ready for

list[dict[str, Any]]

meth:~gwmock_signal.burst.BurstSimulator.simulate and carrying

list[dict[str, Any]]

injection_set="test".

Raises:

Type Description
ValueError

If the span or interval is not positive, a range is not positive, or families is empty, has an entry without burst_model, or has a numerical (file) family without a fixed distance.

Source code in src/gwmock_signal/burst/injection_set.py
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def draw_burst_injection_set(  # noqa: PLR0913
    *,
    start_time: float,
    end_time: float,
    interval: float,
    hrss_range: tuple[float, float],
    rng: np.random.Generator,
    families: Sequence[Mapping[str, Any]] = DRAFT_BURST_FAMILIES,
    sine_gaussian_frequency_range: tuple[float, float] = (30.0, 1800.0),
) -> list[dict[str, Any]]:
    """Return one burst event every *interval* seconds in ``[start_time, end_time)``.

    Events sit at ``start_time + (k + 1/2) * interval``, so none straddles either end. Each event
    takes a family chosen uniformly from *families*, then draws whatever the family does not fix:

    * sky position isotropic, polarization angle uniform in ``[0, pi)``;
    * ``hrss`` log-uniform in *hrss_range*;
    * ``inclination`` uniform in ``cos(iota)`` for sine-Gaussians and white-noise bursts;
    * ``frequency`` log-uniform in *sine_gaussian_frequency_range* for sine-Gaussians;
    * ``seed`` for white-noise bursts, so each event's noise realisation is reproducible.

    Nothing is drawn for a family whose ``burst_model`` names a numerical waveform file, so such a
    family must fix its own ``distance`` (and ``inclination``, when its file's response depends on
    it); a family without a ``distance`` is refused here rather than when the event is simulated.

    Args:
        start_time: GPS start of the span, s.
        end_time: GPS end of the span, s.
        interval: Seconds between consecutive events; the fixed test-set rate is ``1 / interval``.
        hrss_range: ``(low, high)`` bounds of the log-uniform hrss distribution. No default:
            the range must straddle the detection threshold of the network being tested.
        rng: Source of randomness; pass a seeded generator for a reproducible set.
        families: Family templates, each a mapping with ``burst_model`` and any fixed parameters.
        sine_gaussian_frequency_range: ``(low, high)`` Hz for sine-Gaussian central frequencies.

    Returns:
        One event mapping per injection, in time order, each ready for
        :meth:`~gwmock_signal.burst.BurstSimulator.simulate` and carrying
        ``injection_set="test"``.

    Raises:
        ValueError: If the span or interval is not positive, a range is not positive, or
            *families* is empty, has an entry without ``burst_model``, or has a numerical
            (file) family without a fixed ``distance``.
    """
    if not (math.isfinite(start_time) and math.isfinite(end_time) and end_time > start_time):
        raise ValueError(f"end_time must be after start_time, got [{start_time}, {end_time}).")
    if not (math.isfinite(interval) and interval > 0):
        raise ValueError(f"interval must be finite and positive, got {interval!r}.")
    if not families:
        raise ValueError("families must not be empty.")
    if any("burst_model" not in family for family in families):
        raise ValueError("every family must name its burst_model.")
    undistanced = sorted(
        {str(f["burst_model"]) for f in families if f["burst_model"] not in _AD_HOC and "distance" not in f}
    )
    if undistanced:
        raise ValueError(
            f"families {undistanced} are not ad hoc ({sorted(_AD_HOC)}), so their events need a distance, "
            "which this draw does not supply: fix 'distance' (Mpc) in each such family."
        )
    log_hrss = _log_bounds(hrss_range, "hrss_range")
    log_frequency = _log_bounds(sine_gaussian_frequency_range, "sine_gaussian_frequency_range")

    count = math.floor((end_time - start_time) / interval)
    events = []
    for k in range(count):
        family = dict(families[rng.integers(len(families))])
        model = family["burst_model"]
        event: dict[str, Any] = {
            "peak_time": start_time + (k + 0.5) * interval,
            "right_ascension": rng.uniform(0.0, 2 * math.pi),
            "declination": math.asin(rng.uniform(-1.0, 1.0)),
            "polarization_angle": rng.uniform(0.0, math.pi),
            "hrss": math.exp(rng.uniform(*log_hrss)),
        }
        if model in _INCLINED:
            event["inclination"] = math.acos(rng.uniform(-1.0, 1.0))
        if model == SINE_GAUSSIAN:
            event["frequency"] = math.exp(rng.uniform(*log_frequency))
        if model == WHITE_NOISE_BURST:
            event["seed"] = int(rng.integers(_MAX_SEED + 1))
        event.update(family)
        event["injection_set"] = TEST_SET_LABEL
        events.append(event)
    return events

gwmock_signal.burst.waveforms

Burst polarizations: the ad hoc families and numerical waveforms read from file.

The ad hoc families -- sine-Gaussian, Gaussian and band-limited white-noise burst -- are generated by LALSimulation's own burst routines, the ones the LIGO-Virgo-KAGRA burst injections use, so this module encodes no second opinion about their shapes. It adds three things LALSimulation leaves to its caller:

  • Placement. LALSimulation centres every burst on t = 0; it is moved to peak_time.
  • Inclination. The sine-Gaussian and white-noise generators take a polarisation-ellipse eccentricity. A source with inclination iota has h_x / h_+ = 2 cos(iota) / (1 + cos^2 iota), which is eccentricity e = sin^2(iota) / (1 + cos^2 iota); the sign of cos(iota) (the handedness, which e cannot carry) is applied to the cross polarization.
  • Discrete hrss. Every family is scaled so that its samples carry the requested hrss = sqrt(sum (h_+^2 + h_x^2) dt). For a well-sampled sine-Gaussian or Gaussian this changes nothing measurable (about 1e-16); it corrects a pulse the samples do not resolve (a 0.1 ms Gaussian at 8192 Hz by 1.3e-3) and the white-noise burst, which LALSimulation normalises by int hdot^2 dt.

Every parameter is checked against its documented domain -- finite, positive where it must be, below the Nyquist frequency, a white-noise burst not more compact than its time-bandwidth limit -- before LAL is resolved, so an invalid argument is reported the same way whether or not lalsuite is installed. Limits that belong to LALSimulation's numerics rather than to a parameter's meaning, such as the range of the GPS epoch it places a very long burst at, are left to LALSimulation to report.

gaussian(params, sampling_frequency)

Return a linearly polarized Gaussian pulse centred on peak_time.

The cross polarization is identically zero, as in LALSimulation and the LVK injection sets.

Parameters:

Name Type Description Default
params Mapping[str, Any]

peak_time, hrss and duration (the standard deviation of h_+(t), s).

required
sampling_frequency float

Sample rate in Hz.

required

Returns:

Type Description
tuple[TimeSeries, TimeSeries]

(h_plus, h_cross).

Source code in src/gwmock_signal/burst/waveforms.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
def gaussian(params: Mapping[str, Any], sampling_frequency: float) -> tuple[TimeSeries, TimeSeries]:
    """Return a linearly polarized Gaussian pulse centred on ``peak_time``.

    The cross polarization is identically zero, as in LALSimulation and the LVK injection sets.

    Args:
        params: ``peak_time``, ``hrss`` and ``duration`` (the standard deviation of ``h_+(t)``, s).
        sampling_frequency: Sample rate in Hz.

    Returns:
        ``(h_plus, h_cross)``.
    """
    _require(params, ("peak_time", "hrss", "duration"), GAUSSIAN)
    peak_time = _finite(params, "peak_time")
    sampling_frequency = _sample_rate(sampling_frequency)
    duration = _positive(params, "duration")
    hrss = _positive(params, "hrss")
    # LALSimulation's own amplitude check: the peak h_rss / sqrt(sqrt(pi) duration) must be finite.
    if not math.isfinite(hrss / math.sqrt(math.sqrt(math.pi) * duration)):
        raise ValueError(f"hrss={hrss!r} with duration={duration!r} gives a non-finite peak amplitude.")
    lalsimulation = _lalsuite.require("lalsimulation", _LAL_FEATURE)
    hp, hc = lalsimulation.SimBurstGaussian(duration, hrss, 1.0 / sampling_frequency)
    return _at_hrss(hp, hc, hrss, peak_time)

read_waveform_file(path)

Read a numerical burst waveform: three whitespace-separated columns t h_+ h_x.

t is in seconds relative to the waveform's reference instant (placed at peak_time), and must be uniformly sampled; the strains are at the file's reference_distance.

Parameters:

Name Type Description Default
path str | Path

Text file to read.

required

Returns:

Type Description
tuple[ndarray, ndarray, ndarray]

(times, h_plus, h_cross).

Raises:

Type Description
ValueError

If the file does not have three columns, has fewer than two rows, holds a non-finite value, or is not uniformly sampled in increasing time.

Source code in src/gwmock_signal/burst/waveforms.py
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
def read_waveform_file(path: str | Path) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Read a numerical burst waveform: three whitespace-separated columns ``t h_+ h_x``.

    ``t`` is in seconds relative to the waveform's reference instant (placed at ``peak_time``), and
    must be uniformly sampled; the strains are at the file's ``reference_distance``.

    Args:
        path: Text file to read.

    Returns:
        ``(times, h_plus, h_cross)``.

    Raises:
        ValueError: If the file does not have three columns, has fewer than two rows, holds a
            non-finite value, or is not uniformly sampled in increasing time.
    """
    data = np.loadtxt(path, ndmin=2)
    if data.shape[1] != _WAVEFORM_FILE_COLUMNS or data.shape[0] < 2:  # noqa: PLR2004
        raise ValueError(f"{path}: expected at least two rows of three columns 't h_plus h_cross', got {data.shape}.")
    if not np.all(np.isfinite(data)):
        raise ValueError(f"{path}: contains non-finite values.")
    times, plus, cross = data.T
    steps = np.diff(times)
    if steps[0] <= 0 or not np.allclose(steps, steps[0], rtol=_UNIFORM_SPACING_RTOL, atol=0.0):
        raise ValueError(f"{path}: time column must be uniformly sampled and increasing.")
    return times, plus, cross

sine_gaussian(params, sampling_frequency)

Return an elliptically polarized sine-Gaussian centred on peak_time.

Parameters:

Name Type Description Default
params Mapping[str, Any]

peak_time, hrss, frequency (central frequency, Hz), quality_factor and inclination (rad; 0 is circular, pi/2 linear).

required
sampling_frequency float

Sample rate in Hz.

required

Returns:

Type Description
tuple[TimeSeries, TimeSeries]

(h_plus, h_cross).

Source code in src/gwmock_signal/burst/waveforms.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
def sine_gaussian(params: Mapping[str, Any], sampling_frequency: float) -> tuple[TimeSeries, TimeSeries]:
    """Return an elliptically polarized sine-Gaussian centred on ``peak_time``.

    Args:
        params: ``peak_time``, ``hrss``, ``frequency`` (central frequency, Hz),
            ``quality_factor`` and ``inclination`` (rad; ``0`` is circular, ``pi/2`` linear).
        sampling_frequency: Sample rate in Hz.

    Returns:
        ``(h_plus, h_cross)``.
    """
    _require(params, ("peak_time", "hrss", "frequency", "quality_factor", "inclination"), SINE_GAUSSIAN)
    peak_time = _finite(params, "peak_time")
    sampling_frequency = _sample_rate(sampling_frequency)
    frequency = _positive(params, "frequency")
    _below_nyquist(frequency, sampling_frequency, "frequency")
    eccentricity, cross_sign = _eccentricity_and_handedness(float(params["inclination"]))
    quality_factor = _positive(params, "quality_factor")
    hrss = _positive(params, "hrss")
    lalsimulation = _lalsuite.require("lalsimulation", _LAL_FEATURE)
    hp, hc = lalsimulation.SimBurstSineGaussian(
        quality_factor,
        frequency,
        hrss,
        eccentricity,
        0.0,
        1.0 / sampling_frequency,
    )
    return _at_hrss(hp, hc, hrss, peak_time, cross_sign)

white_noise_burst(params, sampling_frequency)

Return a band- and time-limited white-noise burst centred on peak_time.

The band is set by its lower edge and width. LALSimulation shapes both the band and the time envelope smoothly rather than with hard edges, so the content is concentrated in, not confined to, [low_frequency, low_frequency + bandwidth].

Parameters:

Name Type Description Default
params Mapping[str, Any]

peak_time, hrss, low_frequency (Hz), bandwidth (Hz), duration (s), inclination (rad) and seed -- an integer that fixes the noise realisation, so the same parameters always give the same waveform.

required
sampling_frequency float

Sample rate in Hz.

required

Returns:

Type Description
tuple[TimeSeries, TimeSeries]

(h_plus, h_cross).

Source code in src/gwmock_signal/burst/waveforms.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
def white_noise_burst(params: Mapping[str, Any], sampling_frequency: float) -> tuple[TimeSeries, TimeSeries]:
    """Return a band- and time-limited white-noise burst centred on ``peak_time``.

    The band is set by its lower edge and width. LALSimulation
    shapes both the band and the time envelope smoothly rather than with hard edges, so the content
    is concentrated in, not confined to, ``[low_frequency, low_frequency + bandwidth]``.

    Args:
        params: ``peak_time``, ``hrss``, ``low_frequency`` (Hz), ``bandwidth`` (Hz), ``duration``
            (s), ``inclination`` (rad) and ``seed`` -- an integer that fixes the noise realisation,
            so the same parameters always give the same waveform.
        sampling_frequency: Sample rate in Hz.

    Returns:
        ``(h_plus, h_cross)``.
    """
    _require(
        params,
        ("peak_time", "hrss", "low_frequency", "bandwidth", "duration", "inclination", "seed"),
        WHITE_NOISE_BURST,
    )
    peak_time = _finite(params, "peak_time")
    sampling_frequency = _sample_rate(sampling_frequency)
    bandwidth = _positive(params, "bandwidth")
    duration = _positive(params, "duration")
    centre = _positive(params, "low_frequency") + bandwidth / 2
    _below_nyquist(centre + bandwidth / 2, sampling_frequency, "low_frequency + bandwidth")
    # LALSimulation's own test, written in its operation order so that rounding cannot put a burst
    # on opposite sides of the boundary here and there: the envelope variance
    # duration^2 / 4 - 1 / (pi^2 bandwidth^2) must not be negative (duration * bandwidth >= 2 / pi).
    sigma_t_squared = duration * duration / 4.0 - 1.0 / (math.pi * math.pi * bandwidth * bandwidth)
    if sigma_t_squared < 0:
        raise ValueError(
            f"duration={duration!r} and bandwidth={bandwidth!r} give a negative envelope variance "
            f"({sigma_t_squared:g} s^2): a white-noise burst cannot be that compact in both time and frequency."
        )
    seed = int(params["seed"])
    if not 0 <= seed < 2**64:
        raise ValueError(f"seed must be an integer in [0, 2**64), got {params['seed']!r}.")
    hrss = _positive(params, "hrss")
    eccentricity, cross_sign = _eccentricity_and_handedness(float(params["inclination"]))
    lalsimulation = _lalsuite.require("lalsimulation", _LAL_FEATURE)
    lal = _lalsuite.require("lal", _LAL_FEATURE)
    hp, hc = lalsimulation.GenerateBandAndTimeLimitedWhiteNoiseBurst(
        duration, centre, bandwidth, eccentricity, 0.0, 1.0, 1.0 / sampling_frequency, lal.gsl_rng("ranlux", seed)
    )
    return _at_hrss(hp, hc, hrss, peak_time, cross_sign)

BurstSimulator is a TransientSimulator: each burst is generated, projected onto the network and injected like any other transient. It is registered under the source_type "burst".

For the injection specification and usage examples, see the User guide — Burst injections.