Skip to content

Continuous waves

gwmock_signal.continuous

Continuous-wave (isolated pulsar) signal generation.

ContinuousWaveSimulator

Bases: GWSimulator

Generate detector strain for continuous waves from isolated pulsars.

Parameters:

Name Type Description Default
earth_ephemeris str

Path to a LALPulsar earth* ephemeris file.

required
sun_ephemeris str

Path to the matching sun* ephemeris file.

required
reference_time_ssb float

SSB reference epoch for the spin parameters, in seconds. Required, and constant for a whole run. See the module docstring: deriving it per segment is what silently breaks phase coherence, so there is no default to fall into.

required
spindowns Sequence[float]

Spindown terms (f1, f2, ...) in Hz/s, Hz/s^2, ... applied at reference_time_ssb.

()

Raises:

Type Description
ValueError

If reference_time_ssb is not finite.

Source code in src/gwmock_signal/continuous/simulator.py
 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
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
198
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
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
class ContinuousWaveSimulator(GWSimulator):
    """Generate detector strain for continuous waves from isolated pulsars.

    Args:
        earth_ephemeris: Path to a LALPulsar ``earth*`` ephemeris file.
        sun_ephemeris: Path to the matching ``sun*`` ephemeris file.
        reference_time_ssb: SSB reference epoch for the spin parameters, in seconds. **Required,
            and constant for a whole run.** See the module docstring: deriving it per segment is
            what silently breaks phase coherence, so there is no default to fall into.
        spindowns: Spindown terms ``(f1, f2, ...)`` in Hz/s, Hz/s^2, ... applied at
            ``reference_time_ssb``.

    Raises:
        ValueError: If ``reference_time_ssb`` is not finite.
    """

    def __init__(
        self,
        *,
        earth_ephemeris: str,
        sun_ephemeris: str,
        reference_time_ssb: float,
        spindowns: Sequence[float] = (),
        projection_backend: str = "jax",
    ) -> None:
        """Initialize the continuous-wave simulator.

        Args:
            earth_ephemeris: Path to the Earth ephemeris table.
            sun_ephemeris: Path to the Sun ephemeris table.
            reference_time_ssb: Epoch the source parameters refer to, at the solar-system
                barycentre. Required; see the class docstring for why it has no default.
            spindowns: Spindown terms ``f1, f2, ...`` in Hz/s, Hz/s^2, ...
            projection_backend: Which projection implementation to use, ``"jax"`` (the default)
                or ``"numpy"``. The device path is the default because the projection is ~99% of
                a segment's cost here. It is an argument rather than a constant because "JAX imports" and
                "JAX runs" are different claims: device memory can be exhausted, a driver can be
                misconfigured, or a backend can have a defect, and in any of those the host path
                still works and the caller needs to be able to reach it.

                One limit comes with the default. The device path refuses a span over 86400 s, the
                longest its sidereal-time model has been checked over, which is a
                *single* segment and needs ``"numpy"`` to go beyond. The span it measures is the
                padded one, not the nominal segment. ``edge_padding`` adds samples at each end,
                about 0.05 s to 4.13 s per end depending on sample rate, so the usable segment --
                and therefore the longest nominal segment this backend accepts -- is that much
                shorter than 86400 s. A run of any length made of ordinary segments is unaffected,
                since each re-anchors.

        Raises:
            ValueError: If ``reference_time_ssb`` or any spindown term is not finite, or
                ``projection_backend`` is not one of the two names.
        """
        self.projection_backend = use_projection_backend(projection_backend)
        if not np.isfinite(reference_time_ssb):
            raise ValueError("reference_time_ssb must be a finite GPS-scale time in seconds.")
        spindown_terms = tuple(float(term) for term in spindowns)
        if not all(np.isfinite(term) for term in spindown_terms):
            raise ValueError(f"spindowns must all be finite, got {spindown_terms}.")
        self.earth_ephemeris = str(earth_ephemeris)
        self.sun_ephemeris = str(sun_ephemeris)
        self.ephemeris = SolarSystemEphemeris(self.earth_ephemeris, self.sun_ephemeris)
        self.reference_time_ssb = float(reference_time_ssb)
        self.spindowns = spindown_terms

    @property
    def required_params(self) -> frozenset[str]:
        """Return the parameter keys a continuous-wave source must supply."""
        return _REQUIRED_PARAMETERS

    def _ssb_polarizations(
        self,
        params: Mapping[str, Any],
        *,
        start_ssb: float,
        n_samples: int,
        sampling_frequency: float,
    ) -> tuple[np.ndarray, np.ndarray]:
        """Return plus and cross polarizations on an even grid of SSB times from ``start_ssb``.

        The phase is ``phi0 + 2 pi sum_k f_k tau^(k+1) / (k+1)!`` with ``tau`` the SSB time since
        :attr:`reference_time_ssb`, and the polarizations ``A+ cos(phase)`` and ``Ax sin(phase)``: the
        isolated-pulsar model of LALPulsar's ``XLALGeneratePulsarSignal`` before its barycentring, which
        projection now applies with every other source's (:mod:`~gwmock_signal.projection.solar_system`).

        Raises:
            RuntimeError: If the polarizations are not all finite, which an extreme spindown can cause
                far from the reference epoch: its term grows as a power of the time from it.
        """
        tau = (start_ssb - self.reference_time_ssb) + np.arange(n_samples, dtype=float) / sampling_frequency
        coefficients = (float(params["frequency"]), *self.spindowns)
        phase = np.zeros(n_samples)
        power, factorial = np.ones(n_samples), 1.0
        for order, coefficient in enumerate(coefficients, start=1):
            power = power * tau
            factorial *= order
            phase = phase + coefficient * power / factorial
        phase = float(params["initial_phase"]) + 2.0 * np.pi * phase
        plus = float(params["amplitude_plus"]) * np.cos(phase)
        cross = float(params["amplitude_cross"]) * np.sin(phase)
        if not (np.all(np.isfinite(plus)) and np.all(np.isfinite(cross))):
            raise RuntimeError(
                "The continuous-wave polarizations are not all finite, so nothing was written. Check the source "
                "parameters: they are required finite but not bounded, and a spindown term grows as a power of "
                "the time from reference_time_ssb, so an extreme spindown far from it overflows the phase."
            )
        return plus, cross

    def _barycentric_offset(
        self,
        effects: ProjectionEffects,
        params: Mapping[str, Any],
        start: float,
        n_samples: int,
        sampling_frequency: float,
    ) -> tuple[int, int]:
        """Return how many samples the SSB grid runs ahead of the detector grid, and how many more it needs.

        The offset is the smallest solar-system delay across the span, rounded down, less one sample; the
        extra length covers the delay's range, plus one sample. Both are zero without the delays.
        """
        if not effects.solar_system:
            return 0, 0
        end = start + (n_samples - 1) / sampling_frequency
        times = np.concatenate([np.arange(start, end, 60.0), [end]])
        delay, _ = solar_system.delay(
            times,
            float(params["right_ascension"]),
            float(params["declination"]),
            self.ephemeris,
            roemer=effects.roemer_delay,
            einstein=effects.einstein_delay,
            shapiro=effects.shapiro_delay,
        )
        offset = math.floor(float(np.min(delay)) * sampling_frequency) - 1
        return offset, math.ceil(float(np.max(delay)) * sampling_frequency) - offset + 1

    def _validate_source(self, params: Mapping[str, Any], sampling_frequency: float) -> None:
        """Reject source values that would produce a silently wrong or all-NaN signal.

        Args:
            params: Source parameters, already checked for presence by the base class.
            sampling_frequency: Sample rate in Hz, needed for the Nyquist check.

        Raises:
            ValueError: If any required value is not finite, or the frequency is non-positive or
                at/above Nyquist.
        """
        for key in sorted(_REQUIRED_PARAMETERS):
            value = float(params[key])
            if not np.isfinite(value):
                raise ValueError(f"{key} must be finite, got {value!r}.")
        frequency = float(params["frequency"])
        if frequency <= 0.0:
            raise ValueError(f"frequency must be positive, got {frequency!r} Hz.")
        if frequency >= 0.5 * sampling_frequency:
            raise ValueError(
                f"frequency {frequency!r} Hz is at or above the Nyquist frequency "
                f"{0.5 * sampling_frequency!r} Hz for this sample rate, so it would alias."
            )

    @staticmethod
    def _as_series(background: Mapping[str, Any], names: Sequence[str]) -> dict[str, TimeSeries]:
        """Return the background channels for ``names`` as the package's time series.

        Raises:
            TypeError: If a background value is not a time series.
        """
        channels = {}
        for name in names:
            try:
                channels[name] = as_timeseries(background[name])
            except TypeError as exc:
                raise TypeError(
                    f"background values must be gwmock_signal.TimeSeries or GWpy TimeSeries; {name!r} is a "
                    f"{type(background[name]).__name__}."
                ) from exc
        return channels

    @staticmethod
    def _resolve_segment(
        background: Mapping[str, TimeSeries], names: Sequence[str], sampling_frequency: float
    ) -> tuple[float, int]:
        """Return the (epoch, sample count) the background defines, checking every channel agrees.

        Args:
            background: Existing strain, one channel per detector.
            names: Detector names, in output order.
            sampling_frequency: The rate the caller asked to generate at.

        Returns:
            The segment's epoch in GPS seconds and its length in samples.

        Raises:
            TypeError: If a background value is not a time series.
            ValueError: If the channels disagree, or the caller's rate differs from theirs.
        """
        reference = background[names[0]]
        epoch = reference.t0
        n_samples = reference.n_samples
        rate = reference.sample_rate

        # The argument drives generation while the background defines the grid the result is added
        # to, so a disagreement produces a signal sampled at one rate and labelled at another --
        # added elementwise, with no complaint, and time-stretched by the ratio.
        if rate != sampling_frequency:
            raise ValueError(
                f"sampling_frequency is {sampling_frequency!r} Hz but the background is at "
                f"{rate!r} Hz. The signal would be generated on one time grid and added to "
                f"another, stretching it by a factor of {sampling_frequency / rate:.6g}."
            )

        # Every channel must describe the same stretch of time. The polarizations are generated
        # once, for one epoch and length, and added to all of them -- so a channel that disagreed
        # would silently receive a signal from the wrong interval rather than failing.
        for name in names[1:]:
            channel = background[name]
            if channel.n_samples != n_samples:
                raise ValueError(
                    f"background channels must share a length; {name!r} has {channel.n_samples} samples "
                    f"against {n_samples} for {names[0]!r}."
                )
            if channel.t0 != epoch:
                raise ValueError(
                    f"background channels must share an epoch; {name!r} starts at "
                    f"{channel.t0!r} against {epoch!r} for {names[0]!r}."
                )
            if channel.sample_rate != rate:
                raise ValueError(
                    f"background channels must share a sample rate; {name!r} is at "
                    f"{channel.sample_rate!r} Hz against {rate!r} for {names[0]!r}."
                )
        return epoch, n_samples

    def simulate(  # noqa: PLR0913
        self,
        params: Mapping[str, Any],
        detector_names: Sequence[DetectorSpec],
        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:
        """Generate continuous-wave strain for one source over the background's span.

        Args:
            params: Source parameters; see :data:`_REQUIRED_PARAMETERS`.
            detector_names: IFO codes or ``CustomDetector`` instances.
            background: Existing strain to add the signal to. **Required**, because a continuous
                wave has no duration of its own: the segment being generated is defined by the
                background's epoch and length.
            sampling_frequency: Sample rate in Hz.
            minimum_frequency: Unused. A continuous wave is monochromatic apart from its spindown
                and Doppler modulation, so there is no low-frequency cutoff to apply; accepted to
                keep the source-agnostic signature.
            effects: Which physical effects the projection includes; see
                :class:`~gwmock_signal.projection.effects.ProjectionEffects`. ``None``, the default,
                means all of them. The source's parameters are defined at the solar-system barycentre, so
                the solar-system delays enter in full; without them the signal is generated as if the
                geocentre were the barycentre. ``earth_rotation`` must stay on.
            interpolate_if_offset: Unused; the polarizations are generated on the segment's own
                grid, so there is never an offset to interpolate away.
            earth_rotation: Deprecated; ``effects=ProjectionEffects(earth_rotation=...)``.
            finite_arm_length: Deprecated; ``effects=ProjectionEffects(finite_arm_length=...)``.

        Returns:
            ``DetectorStrainStack`` with the signal added to *background*.

        Raises:
            ValueError: If ``background`` is absent or empty, or ``sampling_frequency`` is not
                positive.
            KeyError: If a detector has no background channel.
            RuntimeError: If the generated polarizations are not all finite -- an out-of-range
                source parameter. Refused rather than written; see ``_ssb_polarizations``.
        """
        del minimum_frequency, interpolate_if_offset
        effects = _resolve_effects(
            effects,
            earth_rotation=earth_rotation,
            finite_arm_length=finite_arm_length,
            caller="ContinuousWaveSimulator.simulate",
        )
        self._validate_params(params)
        if sampling_frequency <= 0.0:
            raise ValueError("sampling_frequency must be positive.")

        if not effects.earth_rotation:
            raise ValueError(
                "earth_rotation=False is not available for continuous waves. That branch holds the "
                "antenna pattern fixed at the midpoint of the span, which is an approximation for "
                "signals short enough that Earth barely turns across them -- a continuous wave runs "
                "for months. It is refused rather than warned about because the output would look "
                "entirely normal while being wrong, and because the error would depend on how the "
                "run happened to be split into segments."
            )
        self._validate_source(params, sampling_frequency)

        if not background:
            raise ValueError(
                "ContinuousWaveSimulator requires a background: a continuous wave has no duration "
                "of its own, so the segment's epoch and length come from the data it is added to."
            )

        names = [d if isinstance(d, str) else d.name for d in detector_names]
        if not names:
            raise ValueError("detector_names must not be empty.")
        for name in names:
            if name not in background:
                raise KeyError(f"Missing background for detector {name!r}.")

        # Every channel must describe the same stretch of time. The polarizations are generated
        # once, for one epoch and length, and added to all of them -- so a channel that disagreed
        # would silently receive a signal from the wrong interval rather than failing.
        background = self._as_series(background, names)
        epoch, n_samples = self._resolve_segment(background, names, sampling_frequency)

        # Generated with a margin at both ends and trimmed after projecting. The rotating
        # projection resamples at the time-dependent detector delay with a windowed sinc kernel,
        # and taps reaching past the end of the array read zero. For a transient that is right --
        # there is nothing beyond the buffer. For a continuous wave there is: the signal carries on
        # into the neighbouring segments, so zeros at the seam would make each segment disagree
        # with the same stretch generated as part of a longer run, by far more than rounding.
        margin = edge_padding(sampling_frequency)
        padded_epoch = epoch - margin / sampling_frequency
        n_padded = n_samples + 2 * margin
        # The polarizations are generated in SSB time, which runs ahead of the detector's by the
        # solar-system delay D: up to 500 s, changing by up to 1e-4 s per second. They are labelled on the
        # detector grid and offset from it by a whole number of samples, the smallest D across the segment,
        # so the projection's positions stay small; and lengthened by D's range, so every sample the kept
        # span reads exists.
        offset, extra = self._barycentric_offset(effects, params, padded_epoch, n_padded, sampling_frequency)
        plus, cross = self._ssb_polarizations(
            params,
            start_ssb=padded_epoch + offset / sampling_frequency,
            n_samples=n_padded + extra,
            sampling_frequency=sampling_frequency,
        )
        polarizations = {
            "plus": TimeSeries(plus, t0=padded_epoch, sample_rate=sampling_frequency, unit="strain"),
            "cross": TimeSeries(cross, t0=padded_epoch, sample_rate=sampling_frequency, unit="strain"),
        }
        projected = _project(
            polarizations,
            detector_names,
            right_ascension=float(params["right_ascension"]),
            declination=float(params["declination"]),
            polarization_angle=float(params.get("polarization_angle", 0.0)),
            effects=effects,
            # The device implementation of the same algorithm. Measured against the host path at
            # this class's own segment sizes, three detectors, 512 Hz: 2.0x over 256 s and 3.4x
            # over 1024 s. With every effect on, the solar-system delay in full, they agree to 1.3e-11
            # of peak at 512 Hz over 256 s and 1024 s (`test_the_device_and_host_projections_agree_with_
            # every_effect`). Not a choice about accuracy -- the two differ only by floating-point
            # reassociation -- but the projection is 99% of a
            # continuous-wave segment's cost, so it is the only part worth moving.
            #
            # Defaults to the device path; see ``projection_backend`` for why it can be changed.
            backend=self.projection_backend,
            sinc_taps=DEFAULT_SINC_TAPS,
            kaiser_beta=DEFAULT_KAISER_BETA,
            # The margin above already gives the delay somewhere to read from, and the trim below
            # assumes a series exactly as long as the polarizations. A transient's projection is
            # padded so delayed signal is not lost past the buffer; a continuous wave's signal does
            # not end at the buffer, so here that padding would only be cut off again.
            keep_delayed_samples=False,
            ephemeris=self.ephemeris,
            barycentric_offset_samples=offset,
        )

        # The projection returns dimensionless series; the trimmed signal is labelled ``strain``, as
        # it is, and added to a background that must be strain too.
        strains = {
            name: _add_strain(
                background[name], np.asarray(projected[name].data, dtype=float)[margin : margin + n_samples]
            )
            for name in names
        }
        return DetectorStrainStack.from_mapping(names, strains)

required_params property

Return the parameter keys a continuous-wave source must supply.

__init__(*, earth_ephemeris, sun_ephemeris, reference_time_ssb, spindowns=(), projection_backend='jax')

Initialize the continuous-wave simulator.

Parameters:

Name Type Description Default
earth_ephemeris str

Path to the Earth ephemeris table.

required
sun_ephemeris str

Path to the Sun ephemeris table.

required
reference_time_ssb float

Epoch the source parameters refer to, at the solar-system barycentre. Required; see the class docstring for why it has no default.

required
spindowns Sequence[float]

Spindown terms f1, f2, ... in Hz/s, Hz/s^2, ...

()
projection_backend str

Which projection implementation to use, "jax" (the default) or "numpy". The device path is the default because the projection is ~99% of a segment's cost here. It is an argument rather than a constant because "JAX imports" and "JAX runs" are different claims: device memory can be exhausted, a driver can be misconfigured, or a backend can have a defect, and in any of those the host path still works and the caller needs to be able to reach it.

One limit comes with the default. The device path refuses a span over 86400 s, the longest its sidereal-time model has been checked over, which is a single segment and needs "numpy" to go beyond. The span it measures is the padded one, not the nominal segment. edge_padding adds samples at each end, about 0.05 s to 4.13 s per end depending on sample rate, so the usable segment -- and therefore the longest nominal segment this backend accepts -- is that much shorter than 86400 s. A run of any length made of ordinary segments is unaffected, since each re-anchors.

'jax'

Raises:

Type Description
ValueError

If reference_time_ssb or any spindown term is not finite, or projection_backend is not one of the two names.

Source code in src/gwmock_signal/continuous/simulator.py
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
153
154
155
156
157
def __init__(
    self,
    *,
    earth_ephemeris: str,
    sun_ephemeris: str,
    reference_time_ssb: float,
    spindowns: Sequence[float] = (),
    projection_backend: str = "jax",
) -> None:
    """Initialize the continuous-wave simulator.

    Args:
        earth_ephemeris: Path to the Earth ephemeris table.
        sun_ephemeris: Path to the Sun ephemeris table.
        reference_time_ssb: Epoch the source parameters refer to, at the solar-system
            barycentre. Required; see the class docstring for why it has no default.
        spindowns: Spindown terms ``f1, f2, ...`` in Hz/s, Hz/s^2, ...
        projection_backend: Which projection implementation to use, ``"jax"`` (the default)
            or ``"numpy"``. The device path is the default because the projection is ~99% of
            a segment's cost here. It is an argument rather than a constant because "JAX imports" and
            "JAX runs" are different claims: device memory can be exhausted, a driver can be
            misconfigured, or a backend can have a defect, and in any of those the host path
            still works and the caller needs to be able to reach it.

            One limit comes with the default. The device path refuses a span over 86400 s, the
            longest its sidereal-time model has been checked over, which is a
            *single* segment and needs ``"numpy"`` to go beyond. The span it measures is the
            padded one, not the nominal segment. ``edge_padding`` adds samples at each end,
            about 0.05 s to 4.13 s per end depending on sample rate, so the usable segment --
            and therefore the longest nominal segment this backend accepts -- is that much
            shorter than 86400 s. A run of any length made of ordinary segments is unaffected,
            since each re-anchors.

    Raises:
        ValueError: If ``reference_time_ssb`` or any spindown term is not finite, or
            ``projection_backend`` is not one of the two names.
    """
    self.projection_backend = use_projection_backend(projection_backend)
    if not np.isfinite(reference_time_ssb):
        raise ValueError("reference_time_ssb must be a finite GPS-scale time in seconds.")
    spindown_terms = tuple(float(term) for term in spindowns)
    if not all(np.isfinite(term) for term in spindown_terms):
        raise ValueError(f"spindowns must all be finite, got {spindown_terms}.")
    self.earth_ephemeris = str(earth_ephemeris)
    self.sun_ephemeris = str(sun_ephemeris)
    self.ephemeris = SolarSystemEphemeris(self.earth_ephemeris, self.sun_ephemeris)
    self.reference_time_ssb = float(reference_time_ssb)
    self.spindowns = spindown_terms

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

Generate continuous-wave strain for one source over the background's span.

Parameters:

Name Type Description Default
params Mapping[str, Any]

Source parameters; see :data:_REQUIRED_PARAMETERS.

required
detector_names Sequence[DetectorSpec]

IFO codes or CustomDetector instances.

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

Existing strain to add the signal to. Required, because a continuous wave has no duration of its own: the segment being generated is defined by the background's epoch and length.

None
sampling_frequency float

Sample rate in Hz.

required
minimum_frequency float

Unused. A continuous wave is monochromatic apart from its spindown and Doppler modulation, so there is no low-frequency cutoff to apply; accepted to keep the source-agnostic signature.

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 source's parameters are defined at the solar-system barycentre, so the solar-system delays enter in full; without them the signal is generated as if the geocentre were the barycentre. earth_rotation must stay on.

None
interpolate_if_offset bool

Unused; the polarizations are generated on the segment's own grid, so there is never an offset to interpolate away.

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 with the signal added to background.

Raises:

Type Description
ValueError

If background is absent or empty, or sampling_frequency is not positive.

KeyError

If a detector has no background channel.

RuntimeError

If the generated polarizations are not all finite -- an out-of-range source parameter. Refused rather than written; see _ssb_polarizations.

Source code in src/gwmock_signal/continuous/simulator.py
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
def simulate(  # noqa: PLR0913
    self,
    params: Mapping[str, Any],
    detector_names: Sequence[DetectorSpec],
    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:
    """Generate continuous-wave strain for one source over the background's span.

    Args:
        params: Source parameters; see :data:`_REQUIRED_PARAMETERS`.
        detector_names: IFO codes or ``CustomDetector`` instances.
        background: Existing strain to add the signal to. **Required**, because a continuous
            wave has no duration of its own: the segment being generated is defined by the
            background's epoch and length.
        sampling_frequency: Sample rate in Hz.
        minimum_frequency: Unused. A continuous wave is monochromatic apart from its spindown
            and Doppler modulation, so there is no low-frequency cutoff to apply; accepted to
            keep the source-agnostic signature.
        effects: Which physical effects the projection includes; see
            :class:`~gwmock_signal.projection.effects.ProjectionEffects`. ``None``, the default,
            means all of them. The source's parameters are defined at the solar-system barycentre, so
            the solar-system delays enter in full; without them the signal is generated as if the
            geocentre were the barycentre. ``earth_rotation`` must stay on.
        interpolate_if_offset: Unused; the polarizations are generated on the segment's own
            grid, so there is never an offset to interpolate away.
        earth_rotation: Deprecated; ``effects=ProjectionEffects(earth_rotation=...)``.
        finite_arm_length: Deprecated; ``effects=ProjectionEffects(finite_arm_length=...)``.

    Returns:
        ``DetectorStrainStack`` with the signal added to *background*.

    Raises:
        ValueError: If ``background`` is absent or empty, or ``sampling_frequency`` is not
            positive.
        KeyError: If a detector has no background channel.
        RuntimeError: If the generated polarizations are not all finite -- an out-of-range
            source parameter. Refused rather than written; see ``_ssb_polarizations``.
    """
    del minimum_frequency, interpolate_if_offset
    effects = _resolve_effects(
        effects,
        earth_rotation=earth_rotation,
        finite_arm_length=finite_arm_length,
        caller="ContinuousWaveSimulator.simulate",
    )
    self._validate_params(params)
    if sampling_frequency <= 0.0:
        raise ValueError("sampling_frequency must be positive.")

    if not effects.earth_rotation:
        raise ValueError(
            "earth_rotation=False is not available for continuous waves. That branch holds the "
            "antenna pattern fixed at the midpoint of the span, which is an approximation for "
            "signals short enough that Earth barely turns across them -- a continuous wave runs "
            "for months. It is refused rather than warned about because the output would look "
            "entirely normal while being wrong, and because the error would depend on how the "
            "run happened to be split into segments."
        )
    self._validate_source(params, sampling_frequency)

    if not background:
        raise ValueError(
            "ContinuousWaveSimulator requires a background: a continuous wave has no duration "
            "of its own, so the segment's epoch and length come from the data it is added to."
        )

    names = [d if isinstance(d, str) else d.name for d in detector_names]
    if not names:
        raise ValueError("detector_names must not be empty.")
    for name in names:
        if name not in background:
            raise KeyError(f"Missing background for detector {name!r}.")

    # Every channel must describe the same stretch of time. The polarizations are generated
    # once, for one epoch and length, and added to all of them -- so a channel that disagreed
    # would silently receive a signal from the wrong interval rather than failing.
    background = self._as_series(background, names)
    epoch, n_samples = self._resolve_segment(background, names, sampling_frequency)

    # Generated with a margin at both ends and trimmed after projecting. The rotating
    # projection resamples at the time-dependent detector delay with a windowed sinc kernel,
    # and taps reaching past the end of the array read zero. For a transient that is right --
    # there is nothing beyond the buffer. For a continuous wave there is: the signal carries on
    # into the neighbouring segments, so zeros at the seam would make each segment disagree
    # with the same stretch generated as part of a longer run, by far more than rounding.
    margin = edge_padding(sampling_frequency)
    padded_epoch = epoch - margin / sampling_frequency
    n_padded = n_samples + 2 * margin
    # The polarizations are generated in SSB time, which runs ahead of the detector's by the
    # solar-system delay D: up to 500 s, changing by up to 1e-4 s per second. They are labelled on the
    # detector grid and offset from it by a whole number of samples, the smallest D across the segment,
    # so the projection's positions stay small; and lengthened by D's range, so every sample the kept
    # span reads exists.
    offset, extra = self._barycentric_offset(effects, params, padded_epoch, n_padded, sampling_frequency)
    plus, cross = self._ssb_polarizations(
        params,
        start_ssb=padded_epoch + offset / sampling_frequency,
        n_samples=n_padded + extra,
        sampling_frequency=sampling_frequency,
    )
    polarizations = {
        "plus": TimeSeries(plus, t0=padded_epoch, sample_rate=sampling_frequency, unit="strain"),
        "cross": TimeSeries(cross, t0=padded_epoch, sample_rate=sampling_frequency, unit="strain"),
    }
    projected = _project(
        polarizations,
        detector_names,
        right_ascension=float(params["right_ascension"]),
        declination=float(params["declination"]),
        polarization_angle=float(params.get("polarization_angle", 0.0)),
        effects=effects,
        # The device implementation of the same algorithm. Measured against the host path at
        # this class's own segment sizes, three detectors, 512 Hz: 2.0x over 256 s and 3.4x
        # over 1024 s. With every effect on, the solar-system delay in full, they agree to 1.3e-11
        # of peak at 512 Hz over 256 s and 1024 s (`test_the_device_and_host_projections_agree_with_
        # every_effect`). Not a choice about accuracy -- the two differ only by floating-point
        # reassociation -- but the projection is 99% of a
        # continuous-wave segment's cost, so it is the only part worth moving.
        #
        # Defaults to the device path; see ``projection_backend`` for why it can be changed.
        backend=self.projection_backend,
        sinc_taps=DEFAULT_SINC_TAPS,
        kaiser_beta=DEFAULT_KAISER_BETA,
        # The margin above already gives the delay somewhere to read from, and the trim below
        # assumes a series exactly as long as the polarizations. A transient's projection is
        # padded so delayed signal is not lost past the buffer; a continuous wave's signal does
        # not end at the buffer, so here that padding would only be cut off again.
        keep_delayed_samples=False,
        ephemeris=self.ephemeris,
        barycentric_offset_samples=offset,
    )

    # The projection returns dimensionless series; the trimmed signal is labelled ``strain``, as
    # it is, and added to a background that must be strain too.
    strains = {
        name: _add_strain(
            background[name], np.asarray(projected[name].data, dtype=float)[margin : margin + n_samples]
        )
        for name in names
    }
    return DetectorStrainStack.from_mapping(names, strains)

ContinuousWaveSimulator is a direct GWSimulator subclass, not a TransientSimulator as a continuous wave is not a transient placed at a coalescence time but a signal that is on for the whole observation, which is typically months. Therefore, the simulation does not fit the transient injection pipeline: waveforms → projection → injection used for CBC signals. It is generated as one analysis segment at a time, against a fixed SSB reference epoch, so consecutive segments join up into a single phase-coherent signal rather than independent ones.

It requires the JAX optional dependency (pip install 'gwmock-signal[jax]') as its polarizations come from rippleGW (and JAX)'s pulsar-signal generator.

For usage examples, see the User guide — Continuous waves examples.