Skip to content

Simulator

gwmock_signal.simulator

Abstract base class and CBC concrete implementation for GW signal simulation.

CBCSimulator

Bases: TransientSimulator

Compact binary coalescence simulator backed by WaveformFactory.

Generates time-domain polarizations via a pluggable waveform backend, projects them onto the requested detectors, and injects them into background strain. waveform_model is a CBC concern and is supplied at construction time, keeping the base-class simulate interface source-agnostic.

The public interface accepts gwmock-pop canonical parameter names (e.g. detector_frame_mass_1, coa_time, polarization_angle). Backend-specific translation is handled internally and is invisible to callers.

Parameters:

Name Type Description Default
waveform_model str

Time-domain approximant name or any model registered with WaveformFactory (e.g. 'IMRPhenomD').

required
waveform_backend WaveformBackend | None

Optional waveform backend instance. Defaults to LALSimulationBackend through WaveformFactory.

None
projection_backend str

Which implementation projects the polarizations onto the network, "numpy" (the default) or "jax".

'numpy'
Source code in src/gwmock_signal/simulator.py
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
class CBCSimulator(TransientSimulator):
    """Compact binary coalescence simulator backed by ``WaveformFactory``.

    Generates time-domain polarizations via a pluggable waveform backend,
    projects them onto the requested detectors, and injects them into background
    strain. ``waveform_model`` is a CBC concern and is supplied at construction
    time, keeping the base-class ``simulate`` interface source-agnostic.

    The public interface accepts **gwmock-pop canonical parameter names**
    (e.g. ``detector_frame_mass_1``, ``coa_time``, ``polarization_angle``).
    Backend-specific translation is handled internally and is invisible to callers.

    Args:
        waveform_model: Time-domain approximant name or any model
            registered with ``WaveformFactory`` (e.g. ``'IMRPhenomD'``).
        waveform_backend: Optional waveform backend instance. Defaults to
            ``LALSimulationBackend`` through ``WaveformFactory``.
        projection_backend: Which implementation projects the polarizations onto the network,
            ``"numpy"`` (the default) or ``"jax"``.
    """

    #: Minimum parameter keys required by the CBC pipeline (gwmock-pop canonical names).
    _REQUIRED: frozenset[str] = frozenset(
        {
            "detector_frame_mass_1",
            "detector_frame_mass_2",
            "coa_time",
            "distance",
            "inclination",
            "right_ascension",
            "declination",
            "polarization_angle",
        }
    )

    def __init__(
        self,
        waveform_model: str,
        waveform_backend: WaveformBackend | None = None,
        *,
        projection_backend: str = "numpy",
        ephemeris: SolarSystemEphemeris | None = None,
    ) -> None:
        """Initialise with the waveform model name.

        Args:
            waveform_model: Time-domain approximant name or any model
                registered with ``WaveformFactory``.
            waveform_backend: Optional waveform backend instance.
            projection_backend: Which implementation evaluates the ``earth_rotation=True``
                projection, ``"numpy"`` (the default) or ``"jax"``. The host path stays the
                default here, unlike on the continuous-wave simulator: a compact binary can be
                generated with LAL alone, so defaulting to the device path would make JAX a
                requirement of the ordinary configuration. ``"jax"`` needs JAX installed and is
                worth asking for on long segments, where projection is almost the whole cost --
                measured at 97% of a single 1024 s event at 8192 Hz across five detectors, and
                2.7x faster on the same CPU. It is refused with ``earth_rotation=False``, which
                has no device implementation, and for a span beyond
                :data:`~gwmock_signal.projection.network.MAX_LINEAR_SIDEREAL_SPAN_SECONDS`.
            ephemeris: The Earth and Sun tables for the solar-system delays; the LALPulsar DE405
                tables by default.

        Raises:
            ValueError: If *projection_backend* is not ``"numpy"`` or ``"jax"``.
        """
        # Checked before the factory is built, not after. `WaveformFactory` enumerates its
        # backend's approximants at construction, which imports the waveform library and can fail
        # on its own -- and then a run whose actual mistake is the name below would be told about
        # the waveform stack instead, with the documented ValueError never raised.
        self.projection_backend = use_projection_backend(projection_backend)
        self._waveform_model = waveform_model
        self._waveform_factory = WaveformFactory(backend=waveform_backend)
        if ephemeris is not None:
            self.ephemeris = ephemeris

    @property
    def waveform_model(self) -> str:
        """PyCBC approximant or custom model name."""
        return self._waveform_model

    def polarizations_tapered(self, params: Mapping[str, Any], sampling_frequency: float) -> bool:
        """Whether this model's buffers, with the options in *params* and at this rate, fall smoothly to zero at both ends.

        True where the backend's conditioning guarantees it for this approximant and these
        ``waveform_arguments`` (the LALSimulation backend, except IMRPhenomXPHM with its precession-angle
        multibanding on), and never for a custom registered model, which bypasses that conditioning.
        """
        return self._waveform_factory.tapers_polarizations(
            self._waveform_model, params.get("waveform_arguments"), sampling_frequency=sampling_frequency
        )

    @property
    def required_params(self) -> frozenset[str]:
        """Return the fixed set of required CBC parameter keys."""
        return self._REQUIRED

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

        Answered before generating, which is the point: a caller placing signals into segmented
        data needs to know that a compact binary's buffer begins well before its coalescence, so a
        ``coa_time`` just past a segment boundary belongs to an *earlier* segment. Choosing the
        claiming segment from ``coa_time`` alone crops the start away, and the loss is not marginal.

        **The size of that loss is not a single number** -- it moves by orders of magnitude with the
        low-frequency cutoff, the offset past the boundary, the backend, the approximant and the
        component spins, so no bare percentage is quoted here. The measured tables are in the user
        guide, under *How much signal a segment boundary costs*, together with what they are a proxy
        for and what they are not anchored against.

        Exposed here rather than left to callers to reach the backend through
        ``_waveform_factory``. Two private attributes across a package boundary would break
        silently on any internal rename, and a caller does not reliably own the backend instance --
        this class constructs one when none is supplied.

        Mirrors :meth:`generate_polarizations`, so the parameters, sample rate and cutoff are the
        same ones generation will be given and the answer describes the buffer it will produce.

        Args:
            params: Source parameters, as :meth:`generate_polarizations` takes them.
            sampling_frequency: Sample rate in Hz.
            minimum_frequency: Low-frequency cutoff in Hz.

        Returns:
            Seconds between the first sample and coalescence, always positive; or ``None`` when the
            backend cannot say. Treat ``None`` as *unknown*, never as zero -- see
            :meth:`~gwmock_signal.waveform.backends.base.WaveformBackend.pre_coalescence_duration`.
            Note the value is where the buffer starts, not where audible signal begins, which makes
            it safe for placement: a segment chosen from it never crops real signal. It includes
            the projection's padding (see :func:`_projected_duration`), because :meth:`simulate`
            returns the projected strain, which starts that much before the polarizations.
        """
        return _projected_duration(
            self._waveform_factory.pre_coalescence_duration(
                self._waveform_model,
                sampling_frequency,
                minimum_frequency,
                **_waveform_parameters(params),
            ),
            sampling_frequency,
        )

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

        The complement of :meth:`pre_coalescence_duration`, and the half that answers a different
        question: the pre side tells a caller an event *begins* before a segment, this one tells
        it an event has *finished* before one. Without it, a run whose population starts earlier
        than the run itself cannot distinguish an event whose content is entirely in the past from
        one whose tail lands in the segment being written, and must generate both to find out.

        **This is what the backend keeps after coalescence, not a physical ringdown time.** It
        depends on the backend's conditioning -- a fraction of the buffer on ripple, the remnant's
        merger and ringdown bounds plus a taper's time response on LAL -- and ranges from a fraction
        of a second to tens of seconds. A caller substituting a constant is not approximating it.

        Exposed here for the same reason as the pre side: reaching the backend through
        ``_waveform_factory`` means two private attributes across a package boundary, and a caller
        does not reliably own the backend instance.

        Args:
            params: Source parameters, as :meth:`generate_polarizations` takes them.
            sampling_frequency: Sample rate in Hz.
            minimum_frequency: Low-frequency cutoff in Hz.

        Returns:
            Seconds from coalescence to one sample past the buffer's end, always positive; or
            ``None`` when the backend cannot say. Treat ``None`` as *unknown*, never as zero --
            zero asserts the content stops at coalescence, which would discard exactly the events
            whose tail reaches into the segment being written. Includes the projection's padding,
            as :meth:`pre_coalescence_duration` does and for the same reason.
        """
        return _projected_duration(
            self._waveform_factory.post_coalescence_duration(
                self._waveform_model,
                sampling_frequency,
                minimum_frequency,
                **_waveform_parameters(params),
            ),
            sampling_frequency,
        )

    def generate_polarizations(
        self,
        params: Mapping[str, Any],
        sampling_frequency: float,
        minimum_frequency: float,
    ) -> tuple[TimeSeries | gwpy.timeseries.TimeSeries, TimeSeries | gwpy.timeseries.TimeSeries]:
        """Delegate waveform generation to ``WaveformFactory``.

        Projection-specific keys are excluded because they are consumed by
        ``TransientSimulator.simulate`` rather than by waveform generation.

        Args:
            params: CBC source parameters using gwmock-pop canonical names
                (e.g. ``detector_frame_mass_1``, ``coa_time``).
            sampling_frequency: Sample rate in Hz.
            minimum_frequency: Low-frequency cutoff in Hz.

        Returns:
            Tuple of ``(hp, hc)`` as the waveform model returns them: the package's
            ``TimeSeries`` from a backend, or either kind from a registered model.
        """
        waveform_params = _waveform_parameters(params)

        result = self._waveform_factory.generate(
            self._waveform_model,
            waveform_params,
            tc=params["coa_time"],
            sampling_frequency=sampling_frequency,
            minimum_frequency=minimum_frequency,
        )
        return result["plus"], result["cross"]

    def write(  # noqa: PLR0913
        self,
        path: str | Path,
        params: Mapping[str, Any],
        detector_names: Sequence[str | CustomDetector],
        background: Mapping[str, TimeSeries | gwpy.timeseries.TimeSeries],
        *,
        sampling_frequency: float,
        minimum_frequency: float,
        format: Literal["gwf", "hdf5", "npy", "txt"] = "hdf5",  # noqa: A002
        effects: ProjectionEffects | None = None,
        interpolate_if_offset: bool = True,
        earth_rotation: bool | None = None,
        finite_arm_length: bool | None = None,
    ) -> DetectorStrainStack:
        """Simulate a CBC injection, write the result, and save the parameter dict.

        Calls :meth:`simulate`, writes the returned ``DetectorStrainStack`` to
        *path* via :meth:`DetectorStrainStack.write`, and saves *params* as a
        JSON sidecar at ``<stem>_params.json`` next to *path*.

        Args:
            path: Output file path.
            params: CBC source parameters (same as :meth:`simulate`).
            detector_names: IFO codes for the target network.
            background: Mapping of detector name to background ``TimeSeries``.
            sampling_frequency: Sample rate in Hz.
            minimum_frequency: Low-frequency cutoff in Hz.
            format: Output format for the strain data — one of ``'gwf'``,
                ``'hdf5'``, ``'npy'``, or ``'txt'``.  Defaults to ``'hdf5'``.
            effects: Passed through to :meth:`simulate`.
            interpolate_if_offset: Passed through to :meth:`simulate`.
            earth_rotation: Deprecated; passed through to :meth:`simulate`.
            finite_arm_length: Deprecated; passed through to :meth:`simulate`.

        Returns:
            The ``DetectorStrainStack`` that was written to disk.
        """
        result = self.simulate(
            params,
            detector_names,
            background,
            sampling_frequency=sampling_frequency,
            minimum_frequency=minimum_frequency,
            effects=effects,
            interpolate_if_offset=interpolate_if_offset,
            earth_rotation=earth_rotation,
            finite_arm_length=finite_arm_length,
        )
        result.write(path, format=format)

        params_path = Path(path).with_name(Path(path).stem + "_params.json")
        params_path.write_text(json.dumps(dict(params), default=_json_default, indent=4))

        return result

required_params property

Return the fixed set of required CBC parameter keys.

waveform_model property

PyCBC approximant or custom model name.

__init__(waveform_model, waveform_backend=None, *, projection_backend='numpy', ephemeris=None)

Initialise with the waveform model name.

Parameters:

Name Type Description Default
waveform_model str

Time-domain approximant name or any model registered with WaveformFactory.

required
waveform_backend WaveformBackend | None

Optional waveform backend instance.

None
projection_backend str

Which implementation evaluates the earth_rotation=True projection, "numpy" (the default) or "jax". The host path stays the default here, unlike on the continuous-wave simulator: a compact binary can be generated with LAL alone, so defaulting to the device path would make JAX a requirement of the ordinary configuration. "jax" needs JAX installed and is worth asking for on long segments, where projection is almost the whole cost -- measured at 97% of a single 1024 s event at 8192 Hz across five detectors, and 2.7x faster on the same CPU. It is refused with earth_rotation=False, which has no device implementation, and for a span beyond :data:~gwmock_signal.projection.network.MAX_LINEAR_SIDEREAL_SPAN_SECONDS.

'numpy'
ephemeris SolarSystemEphemeris | None

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

None

Raises:

Type Description
ValueError

If projection_backend is not "numpy" or "jax".

Source code in src/gwmock_signal/simulator.py
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
def __init__(
    self,
    waveform_model: str,
    waveform_backend: WaveformBackend | None = None,
    *,
    projection_backend: str = "numpy",
    ephemeris: SolarSystemEphemeris | None = None,
) -> None:
    """Initialise with the waveform model name.

    Args:
        waveform_model: Time-domain approximant name or any model
            registered with ``WaveformFactory``.
        waveform_backend: Optional waveform backend instance.
        projection_backend: Which implementation evaluates the ``earth_rotation=True``
            projection, ``"numpy"`` (the default) or ``"jax"``. The host path stays the
            default here, unlike on the continuous-wave simulator: a compact binary can be
            generated with LAL alone, so defaulting to the device path would make JAX a
            requirement of the ordinary configuration. ``"jax"`` needs JAX installed and is
            worth asking for on long segments, where projection is almost the whole cost --
            measured at 97% of a single 1024 s event at 8192 Hz across five detectors, and
            2.7x faster on the same CPU. It is refused with ``earth_rotation=False``, which
            has no device implementation, and for a span beyond
            :data:`~gwmock_signal.projection.network.MAX_LINEAR_SIDEREAL_SPAN_SECONDS`.
        ephemeris: The Earth and Sun tables for the solar-system delays; the LALPulsar DE405
            tables by default.

    Raises:
        ValueError: If *projection_backend* is not ``"numpy"`` or ``"jax"``.
    """
    # Checked before the factory is built, not after. `WaveformFactory` enumerates its
    # backend's approximants at construction, which imports the waveform library and can fail
    # on its own -- and then a run whose actual mistake is the name below would be told about
    # the waveform stack instead, with the documented ValueError never raised.
    self.projection_backend = use_projection_backend(projection_backend)
    self._waveform_model = waveform_model
    self._waveform_factory = WaveformFactory(backend=waveform_backend)
    if ephemeris is not None:
        self.ephemeris = ephemeris

generate_polarizations(params, sampling_frequency, minimum_frequency)

Delegate waveform generation to WaveformFactory.

Projection-specific keys are excluded because they are consumed by TransientSimulator.simulate rather than by waveform generation.

Parameters:

Name Type Description Default
params Mapping[str, Any]

CBC source parameters using gwmock-pop canonical names (e.g. detector_frame_mass_1, coa_time).

required
sampling_frequency float

Sample rate in Hz.

required
minimum_frequency float

Low-frequency cutoff in Hz.

required

Returns:

Type Description
TimeSeries | TimeSeries

Tuple of (hp, hc) as the waveform model returns them: the package's

TimeSeries | TimeSeries

TimeSeries from a backend, or either kind from a registered model.

Source code in src/gwmock_signal/simulator.py
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
def generate_polarizations(
    self,
    params: Mapping[str, Any],
    sampling_frequency: float,
    minimum_frequency: float,
) -> tuple[TimeSeries | gwpy.timeseries.TimeSeries, TimeSeries | gwpy.timeseries.TimeSeries]:
    """Delegate waveform generation to ``WaveformFactory``.

    Projection-specific keys are excluded because they are consumed by
    ``TransientSimulator.simulate`` rather than by waveform generation.

    Args:
        params: CBC source parameters using gwmock-pop canonical names
            (e.g. ``detector_frame_mass_1``, ``coa_time``).
        sampling_frequency: Sample rate in Hz.
        minimum_frequency: Low-frequency cutoff in Hz.

    Returns:
        Tuple of ``(hp, hc)`` as the waveform model returns them: the package's
        ``TimeSeries`` from a backend, or either kind from a registered model.
    """
    waveform_params = _waveform_parameters(params)

    result = self._waveform_factory.generate(
        self._waveform_model,
        waveform_params,
        tc=params["coa_time"],
        sampling_frequency=sampling_frequency,
        minimum_frequency=minimum_frequency,
    )
    return result["plus"], result["cross"]

polarizations_tapered(params, sampling_frequency)

Whether this model's buffers, with the options in params and at this rate, fall smoothly to zero at both ends.

True where the backend's conditioning guarantees it for this approximant and these waveform_arguments (the LALSimulation backend, except IMRPhenomXPHM with its precession-angle multibanding on), and never for a custom registered model, which bypasses that conditioning.

Source code in src/gwmock_signal/simulator.py
545
546
547
548
549
550
551
552
553
554
def polarizations_tapered(self, params: Mapping[str, Any], sampling_frequency: float) -> bool:
    """Whether this model's buffers, with the options in *params* and at this rate, fall smoothly to zero at both ends.

    True where the backend's conditioning guarantees it for this approximant and these
    ``waveform_arguments`` (the LALSimulation backend, except IMRPhenomXPHM with its precession-angle
    multibanding on), and never for a custom registered model, which bypasses that conditioning.
    """
    return self._waveform_factory.tapers_polarizations(
        self._waveform_model, params.get("waveform_arguments"), sampling_frequency=sampling_frequency
    )

post_coalescence_duration(params, sampling_frequency, minimum_frequency)

Return how long after coa_time this simulator's output runs, in seconds.

The complement of :meth:pre_coalescence_duration, and the half that answers a different question: the pre side tells a caller an event begins before a segment, this one tells it an event has finished before one. Without it, a run whose population starts earlier than the run itself cannot distinguish an event whose content is entirely in the past from one whose tail lands in the segment being written, and must generate both to find out.

This is what the backend keeps after coalescence, not a physical ringdown time. It depends on the backend's conditioning -- a fraction of the buffer on ripple, the remnant's merger and ringdown bounds plus a taper's time response on LAL -- and ranges from a fraction of a second to tens of seconds. A caller substituting a constant is not approximating it.

Exposed here for the same reason as the pre side: reaching the backend through _waveform_factory means two private attributes across a package boundary, and a caller does not reliably own the backend instance.

Parameters:

Name Type Description Default
params Mapping[str, Any]

Source parameters, as :meth:generate_polarizations takes them.

required
sampling_frequency float

Sample rate in Hz.

required
minimum_frequency float

Low-frequency cutoff in Hz.

required

Returns:

Name Type Description
float | None

Seconds from coalescence to one sample past the buffer's end, always positive; or

float | None

None when the backend cannot say. Treat None as unknown, never as zero --

float | None

zero asserts the content stops at coalescence, which would discard exactly the events

float | None

whose tail reaches into the segment being written. Includes the projection's padding,

as float | None

meth:pre_coalescence_duration does and for the same reason.

Source code in src/gwmock_signal/simulator.py
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
def post_coalescence_duration(
    self,
    params: Mapping[str, Any],
    sampling_frequency: float,
    minimum_frequency: float,
) -> float | None:
    """Return how long after ``coa_time`` this simulator's output runs, in seconds.

    The complement of :meth:`pre_coalescence_duration`, and the half that answers a different
    question: the pre side tells a caller an event *begins* before a segment, this one tells
    it an event has *finished* before one. Without it, a run whose population starts earlier
    than the run itself cannot distinguish an event whose content is entirely in the past from
    one whose tail lands in the segment being written, and must generate both to find out.

    **This is what the backend keeps after coalescence, not a physical ringdown time.** It
    depends on the backend's conditioning -- a fraction of the buffer on ripple, the remnant's
    merger and ringdown bounds plus a taper's time response on LAL -- and ranges from a fraction
    of a second to tens of seconds. A caller substituting a constant is not approximating it.

    Exposed here for the same reason as the pre side: reaching the backend through
    ``_waveform_factory`` means two private attributes across a package boundary, and a caller
    does not reliably own the backend instance.

    Args:
        params: Source parameters, as :meth:`generate_polarizations` takes them.
        sampling_frequency: Sample rate in Hz.
        minimum_frequency: Low-frequency cutoff in Hz.

    Returns:
        Seconds from coalescence to one sample past the buffer's end, always positive; or
        ``None`` when the backend cannot say. Treat ``None`` as *unknown*, never as zero --
        zero asserts the content stops at coalescence, which would discard exactly the events
        whose tail reaches into the segment being written. Includes the projection's padding,
        as :meth:`pre_coalescence_duration` does and for the same reason.
    """
    return _projected_duration(
        self._waveform_factory.post_coalescence_duration(
            self._waveform_model,
            sampling_frequency,
            minimum_frequency,
            **_waveform_parameters(params),
        ),
        sampling_frequency,
    )

pre_coalescence_duration(params, sampling_frequency, minimum_frequency)

Return how long before coa_time this simulator's output starts, in seconds.

Answered before generating, which is the point: a caller placing signals into segmented data needs to know that a compact binary's buffer begins well before its coalescence, so a coa_time just past a segment boundary belongs to an earlier segment. Choosing the claiming segment from coa_time alone crops the start away, and the loss is not marginal.

The size of that loss is not a single number -- it moves by orders of magnitude with the low-frequency cutoff, the offset past the boundary, the backend, the approximant and the component spins, so no bare percentage is quoted here. The measured tables are in the user guide, under How much signal a segment boundary costs, together with what they are a proxy for and what they are not anchored against.

Exposed here rather than left to callers to reach the backend through _waveform_factory. Two private attributes across a package boundary would break silently on any internal rename, and a caller does not reliably own the backend instance -- this class constructs one when none is supplied.

Mirrors :meth:generate_polarizations, so the parameters, sample rate and cutoff are the same ones generation will be given and the answer describes the buffer it will produce.

Parameters:

Name Type Description Default
params Mapping[str, Any]

Source parameters, as :meth:generate_polarizations takes them.

required
sampling_frequency float

Sample rate in Hz.

required
minimum_frequency float

Low-frequency cutoff in Hz.

required

Returns:

Type Description
float | None

Seconds between the first sample and coalescence, always positive; or None when the

float | None

backend cannot say. Treat None as unknown, never as zero -- see

float | None

meth:~gwmock_signal.waveform.backends.base.WaveformBackend.pre_coalescence_duration.

float | None

Note the value is where the buffer starts, not where audible signal begins, which makes

float | None

it safe for placement: a segment chosen from it never crops real signal. It includes

float | None

the projection's padding (see :func:_projected_duration), because :meth:simulate

float | None

returns the projected strain, which starts that much before the polarizations.

Source code in src/gwmock_signal/simulator.py
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
def pre_coalescence_duration(
    self,
    params: Mapping[str, Any],
    sampling_frequency: float,
    minimum_frequency: float,
) -> float | None:
    """Return how long before ``coa_time`` this simulator's output starts, in seconds.

    Answered before generating, which is the point: a caller placing signals into segmented
    data needs to know that a compact binary's buffer begins well before its coalescence, so a
    ``coa_time`` just past a segment boundary belongs to an *earlier* segment. Choosing the
    claiming segment from ``coa_time`` alone crops the start away, and the loss is not marginal.

    **The size of that loss is not a single number** -- it moves by orders of magnitude with the
    low-frequency cutoff, the offset past the boundary, the backend, the approximant and the
    component spins, so no bare percentage is quoted here. The measured tables are in the user
    guide, under *How much signal a segment boundary costs*, together with what they are a proxy
    for and what they are not anchored against.

    Exposed here rather than left to callers to reach the backend through
    ``_waveform_factory``. Two private attributes across a package boundary would break
    silently on any internal rename, and a caller does not reliably own the backend instance --
    this class constructs one when none is supplied.

    Mirrors :meth:`generate_polarizations`, so the parameters, sample rate and cutoff are the
    same ones generation will be given and the answer describes the buffer it will produce.

    Args:
        params: Source parameters, as :meth:`generate_polarizations` takes them.
        sampling_frequency: Sample rate in Hz.
        minimum_frequency: Low-frequency cutoff in Hz.

    Returns:
        Seconds between the first sample and coalescence, always positive; or ``None`` when the
        backend cannot say. Treat ``None`` as *unknown*, never as zero -- see
        :meth:`~gwmock_signal.waveform.backends.base.WaveformBackend.pre_coalescence_duration`.
        Note the value is where the buffer starts, not where audible signal begins, which makes
        it safe for placement: a segment chosen from it never crops real signal. It includes
        the projection's padding (see :func:`_projected_duration`), because :meth:`simulate`
        returns the projected strain, which starts that much before the polarizations.
    """
    return _projected_duration(
        self._waveform_factory.pre_coalescence_duration(
            self._waveform_model,
            sampling_frequency,
            minimum_frequency,
            **_waveform_parameters(params),
        ),
        sampling_frequency,
    )

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 the GPS time at which this source's solar-system delay is absorbed.

The delay's value and rate there are taken out, so this time keeps its meaning at the geocentre: a compact binary's coalescence, coa_time. A subclass whose signal is placed by another time overrides this.

Source code in src/gwmock_signal/simulator.py
247
248
249
250
251
252
253
254
def timing_reference(self, params: Mapping[str, Any]) -> float:
    """Return the GPS time at which this source's solar-system delay is absorbed.

    The delay's value and rate there are taken out, so this time keeps its meaning at the geocentre:
    a compact binary's coalescence, ``coa_time``. A subclass whose signal is placed by another time
    overrides this.
    """
    return float(params["coa_time"])

write(path, params, detector_names, background, *, sampling_frequency, minimum_frequency, format='hdf5', effects=None, interpolate_if_offset=True, earth_rotation=None, finite_arm_length=None)

Simulate a CBC injection, write the result, and save the parameter dict.

Calls :meth:simulate, writes the returned DetectorStrainStack to path via :meth:DetectorStrainStack.write, and saves params as a JSON sidecar at <stem>_params.json next to path.

Parameters:

Name Type Description Default
path str | Path

Output file path.

required
params Mapping[str, Any]

CBC source parameters (same as :meth:simulate).

required
detector_names Sequence[str | CustomDetector]

IFO codes for the target network.

required
background Mapping[str, TimeSeries | TimeSeries]

Mapping of detector name to background TimeSeries.

required
sampling_frequency float

Sample rate in Hz.

required
minimum_frequency float

Low-frequency cutoff in Hz.

required
format Literal['gwf', 'hdf5', 'npy', 'txt']

Output format for the strain data — one of 'gwf', 'hdf5', 'npy', or 'txt'. Defaults to 'hdf5'.

'hdf5'
effects ProjectionEffects | None

Passed through to :meth:simulate.

None
interpolate_if_offset bool

Passed through to :meth:simulate.

True
earth_rotation bool | None

Deprecated; passed through to :meth:simulate.

None
finite_arm_length bool | None

Deprecated; passed through to :meth:simulate.

None

Returns:

Type Description
DetectorStrainStack

The DetectorStrainStack that was written to disk.

Source code in src/gwmock_signal/simulator.py
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
def write(  # noqa: PLR0913
    self,
    path: str | Path,
    params: Mapping[str, Any],
    detector_names: Sequence[str | CustomDetector],
    background: Mapping[str, TimeSeries | gwpy.timeseries.TimeSeries],
    *,
    sampling_frequency: float,
    minimum_frequency: float,
    format: Literal["gwf", "hdf5", "npy", "txt"] = "hdf5",  # noqa: A002
    effects: ProjectionEffects | None = None,
    interpolate_if_offset: bool = True,
    earth_rotation: bool | None = None,
    finite_arm_length: bool | None = None,
) -> DetectorStrainStack:
    """Simulate a CBC injection, write the result, and save the parameter dict.

    Calls :meth:`simulate`, writes the returned ``DetectorStrainStack`` to
    *path* via :meth:`DetectorStrainStack.write`, and saves *params* as a
    JSON sidecar at ``<stem>_params.json`` next to *path*.

    Args:
        path: Output file path.
        params: CBC source parameters (same as :meth:`simulate`).
        detector_names: IFO codes for the target network.
        background: Mapping of detector name to background ``TimeSeries``.
        sampling_frequency: Sample rate in Hz.
        minimum_frequency: Low-frequency cutoff in Hz.
        format: Output format for the strain data — one of ``'gwf'``,
            ``'hdf5'``, ``'npy'``, or ``'txt'``.  Defaults to ``'hdf5'``.
        effects: Passed through to :meth:`simulate`.
        interpolate_if_offset: Passed through to :meth:`simulate`.
        earth_rotation: Deprecated; passed through to :meth:`simulate`.
        finite_arm_length: Deprecated; passed through to :meth:`simulate`.

    Returns:
        The ``DetectorStrainStack`` that was written to disk.
    """
    result = self.simulate(
        params,
        detector_names,
        background,
        sampling_frequency=sampling_frequency,
        minimum_frequency=minimum_frequency,
        effects=effects,
        interpolate_if_offset=interpolate_if_offset,
        earth_rotation=earth_rotation,
        finite_arm_length=finite_arm_length,
    )
    result.write(path, format=format)

    params_path = Path(path).with_name(Path(path).stem + "_params.json")
    params_path.write_text(json.dumps(dict(params), default=_json_default, indent=4))

    return result

GWSimulator

Bases: ABC

Abstract base class for gravitational-wave signal simulators.

Defines the stable, source-agnostic contract used across packages: subclasses must implement required_params and simulate and must return a DetectorStrainStack. _validate_params is provided as a concrete helper.

See docs/api/simulator/index.md for the API reference.

Source code in src/gwmock_signal/simulator.py
132
133
134
135
136
137
138
139
140
141
142
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
class GWSimulator(ABC):
    """Abstract base class for gravitational-wave signal simulators.

    Defines the stable, source-agnostic contract used across packages:
    subclasses must implement ``required_params`` and ``simulate`` and must
    return a ``DetectorStrainStack``. ``_validate_params`` is provided as a
    concrete helper.

    See ``docs/api/simulator/index.md`` for the API reference.
    """

    @property
    @abstractmethod
    def required_params(self) -> frozenset[str]:
        """Parameter keys that must be present in the params dict passed to ``simulate``."""

    def _validate_params(self, params: Mapping[str, Any]) -> None:
        """Raise ``ValueError`` naming any key in ``required_params`` missing from ``params``.

        Args:
            params: Source parameters to validate.

        Raises:
            ValueError: If any required key is absent, naming each missing key.
        """
        missing = self.required_params - set(params)
        if missing:
            raise ValueError(f"Missing required parameters: {sorted(missing)}")

    @abstractmethod
    def simulate(  # noqa: PLR0913
        self,
        params: Mapping[str, Any],
        detector_names: Sequence[str],
        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,
    ) -> DetectorStrainStack:
        """Return detector strain for one source realization as a ``DetectorStrainStack``.

        Args:
            params: Source parameters.
            detector_names: IFO codes (e.g. ``'H1'``, ``'L1'``, ``'V1'``).
            background: Optional mapping of detector name to existing background
                strain. Non-transient subclasses may use this to inject into
                pre-existing data; transient subclasses may ignore it and return
                signal-only strain directly.
            sampling_frequency: Sample rate in Hz.
            minimum_frequency: Low-frequency cutoff in Hz.
            effects: Which physical effects the projection includes, for a source projected onto
                detectors; see :class:`~gwmock_signal.projection.effects.ProjectionEffects`. ``None``
                means all of them.
            interpolate_if_offset: Optional backend-specific flag controlling
                how off-grid injections should be handled.
            earth_rotation: Deprecated; ``effects=ProjectionEffects(earth_rotation=...)``.
            finite_arm_length: Deprecated; ``effects=ProjectionEffects(finite_arm_length=...)``.

        Returns:
            ``DetectorStrainStack`` containing one aligned strain channel per
            detector in ``detector_names`` order.
        """

required_params abstractmethod property

Parameter keys that must be present in the params dict passed to simulate.

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

Return detector strain for one source realization as a DetectorStrainStack.

Parameters:

Name Type Description Default
params Mapping[str, Any]

Source parameters.

required
detector_names Sequence[str]

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

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

Optional mapping of detector name to existing background strain. Non-transient subclasses may use this to inject into pre-existing data; transient subclasses may ignore it and return signal-only strain directly.

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, for a source projected onto detectors; see :class:~gwmock_signal.projection.effects.ProjectionEffects. None means all of them.

None
interpolate_if_offset bool

Optional backend-specific flag controlling how off-grid injections should be handled.

True
earth_rotation bool | None

Deprecated; effects=ProjectionEffects(earth_rotation=...).

None
finite_arm_length bool | None

Deprecated; effects=ProjectionEffects(finite_arm_length=...).

None

Returns:

Type Description
DetectorStrainStack

DetectorStrainStack containing one aligned strain channel per

DetectorStrainStack

detector in detector_names order.

Source code in src/gwmock_signal/simulator.py
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
@abstractmethod
def simulate(  # noqa: PLR0913
    self,
    params: Mapping[str, Any],
    detector_names: Sequence[str],
    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,
) -> DetectorStrainStack:
    """Return detector strain for one source realization as a ``DetectorStrainStack``.

    Args:
        params: Source parameters.
        detector_names: IFO codes (e.g. ``'H1'``, ``'L1'``, ``'V1'``).
        background: Optional mapping of detector name to existing background
            strain. Non-transient subclasses may use this to inject into
            pre-existing data; transient subclasses may ignore it and return
            signal-only strain directly.
        sampling_frequency: Sample rate in Hz.
        minimum_frequency: Low-frequency cutoff in Hz.
        effects: Which physical effects the projection includes, for a source projected onto
            detectors; see :class:`~gwmock_signal.projection.effects.ProjectionEffects`. ``None``
            means all of them.
        interpolate_if_offset: Optional backend-specific flag controlling
            how off-grid injections should be handled.
        earth_rotation: Deprecated; ``effects=ProjectionEffects(earth_rotation=...)``.
        finite_arm_length: Deprecated; ``effects=ProjectionEffects(finite_arm_length=...)``.

    Returns:
        ``DetectorStrainStack`` containing one aligned strain channel per
        detector in ``detector_names`` order.
    """

TransientSimulator

Bases: GWSimulator

Intermediate base class for transient GW source simulators.

Provides the concrete simulate method that orchestrates the full transient injection pipeline: validation → polarizations → detector projection → strain injection → stacking. It also exposes register_waveform_model so each simulator instance can add custom waveform generators without poking private WaveformFactory attributes. Subclasses must implement generate_polarizations and required_params.

Source code in src/gwmock_signal/simulator.py
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
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
class TransientSimulator(GWSimulator):
    """Intermediate base class for transient GW source simulators.

    Provides the concrete ``simulate`` method that orchestrates the full
    transient injection pipeline: validation → polarizations → detector
    projection → strain injection → stacking. It also exposes
    ``register_waveform_model`` so each simulator instance can add custom
    waveform generators without poking private ``WaveformFactory`` attributes.
    Subclasses must implement ``generate_polarizations`` and ``required_params``.
    """

    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

    #: Which implementation evaluates the ``earth_rotation=True`` projection, ``"numpy"`` or
    #: ``"jax"``.
    #:
    #: A class attribute rather than a ``simulate`` argument, and defaulting to the host path.
    #: Projection dominates the cost of a long transient -- measured at 97% of a single event at
    #: 1024 s and 8192 Hz across five detectors, where the device path is 2.7x faster on the same
    #: CPU -- so it is worth choosing, but it is a property of how a run is set up rather than of
    #: one call. The two agree to ~1e-10 of peak, so this is a substitution and not a different
    #: answer; see ``backend`` on
    #: :func:`~gwmock_signal.projection.network.project_polarizations_to_network`.
    #:
    #: Subclasses that accept it from their caller set the instance attribute in ``__init__`` from
    #: :func:`~gwmock_signal.projection.network.use_projection_backend`; one that does not inherits
    #: the host path, which needs no optional dependency.
    projection_backend: str = "numpy"

    #: Whether the device projection is compiled only for a few fixed lengths, the polarizations padded
    #: with zeros to the next one; see ``fixed_lengths`` on :func:`~gwmock_signal.projection.network._project`.
    #: For a simulator whose events come in many lengths, each of which would otherwise compile its own
    #: kernel. Off unless a subclass turns it on: it pads every event, and a source whose events share a
    #: length gains nothing for that.
    fixed_device_lengths: bool = False

    #: The Earth and Sun tables the solar-system delays are computed from; the LALPulsar DE405 tables
    #: unless a subclass is given others.
    ephemeris: SolarSystemEphemeris = SolarSystemEphemeris()

    def timing_reference(self, params: Mapping[str, Any]) -> float:
        """Return the GPS time at which this source's solar-system delay is absorbed.

        The delay's value and rate there are taken out, so this time keeps its meaning at the geocentre:
        a compact binary's coalescence, ``coa_time``. A subclass whose signal is placed by another time
        overrides this.
        """
        return float(params["coa_time"])

    @abstractmethod
    def generate_polarizations(
        self,
        params: Mapping[str, Any],
        sampling_frequency: float,
        minimum_frequency: float,
    ) -> tuple[TimeSeries | gwpy.timeseries.TimeSeries, TimeSeries | gwpy.timeseries.TimeSeries]:
        """Generate plus and cross polarization time series.

        Args:
            params: Source parameters.
            sampling_frequency: Sample rate in Hz.
            minimum_frequency: Low-frequency cutoff in Hz.

        Returns:
            Tuple of ``(hp, hc)`` time series, each the package's or GWpy's.
        """

    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

    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)

required_params abstractmethod property

Parameter keys that must be present in the params dict passed to simulate.

generate_polarizations(params, sampling_frequency, minimum_frequency) abstractmethod

Generate plus and cross polarization time series.

Parameters:

Name Type Description Default
params Mapping[str, Any]

Source parameters.

required
sampling_frequency float

Sample rate in Hz.

required
minimum_frequency float

Low-frequency cutoff in Hz.

required

Returns:

Type Description
tuple[TimeSeries | TimeSeries, TimeSeries | TimeSeries]

Tuple of (hp, hc) time series, each the package's or GWpy's.

Source code in src/gwmock_signal/simulator.py
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
@abstractmethod
def generate_polarizations(
    self,
    params: Mapping[str, Any],
    sampling_frequency: float,
    minimum_frequency: float,
) -> tuple[TimeSeries | gwpy.timeseries.TimeSeries, TimeSeries | gwpy.timeseries.TimeSeries]:
    """Generate plus and cross polarization time series.

    Args:
        params: Source parameters.
        sampling_frequency: Sample rate in Hz.
        minimum_frequency: Low-frequency cutoff in Hz.

    Returns:
        Tuple of ``(hp, hc)`` time series, each the package's or GWpy's.
    """

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

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 the GPS time at which this source's solar-system delay is absorbed.

The delay's value and rate there are taken out, so this time keeps its meaning at the geocentre: a compact binary's coalescence, coa_time. A subclass whose signal is placed by another time overrides this.

Source code in src/gwmock_signal/simulator.py
247
248
249
250
251
252
253
254
def timing_reference(self, params: Mapping[str, Any]) -> float:
    """Return the GPS time at which this source's solar-system delay is absorbed.

    The delay's value and rate there are taken out, so this time keeps its meaning at the geocentre:
    a compact binary's coalescence, ``coa_time``. A subclass whose signal is placed by another time
    overrides this.
    """
    return float(params["coa_time"])

GWSimulator.simulate(...) is the stable cross-package boundary. Custom backends should accept the documented keyword arguments, may use background=None or inject into a provided background, and must return a DetectorStrainStack.

For registry-based construction (gwmock-pop source_type strings), see Registry. For one-shot CBC injection without instantiating a simulator, see Pipeline (inject_cbc_signal).

TransientSimulator also exposes register_waveform_model(name, factory) for per-instance waveform registration. Use this when downstream orchestration needs to inject a custom callable waveform without reaching into private _waveform_factory state.

For narrative examples (waveforms → projection → injection), see the user guide overview. For an extensibility-oriented walkthrough, see Custom backends.