jaxtfwaves 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
tfwaves/stft.py ADDED
@@ -0,0 +1,902 @@
1
+ #! /usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ Main module for tfwaves package, providing access to STFTWaveform class.
6
+ Authors:
7
+ Quentin Baghi <quentin.baghi@protonmail.com>
8
+ Saptarshi Ghosh <saptarshi.ghosh@apc.in2p3.fr>
9
+ Gael Servignat <servignat@apc.in2p3.fr>
10
+ """
11
+
12
+ from abc import ABC
13
+ from dataclasses import dataclass
14
+
15
+ import jax
16
+ import jax.numpy as jnp
17
+ import numpy as np
18
+
19
+ from .interpolation import spline_cubic_jit, spline_hermite_jit
20
+ from .response import ResponseFromStrain, aet_mat, compute_tdi_tf
21
+ from .utils import (
22
+ dot_custom,
23
+ linearized_quadrature_vectorized,
24
+ multiple_dot_vect,
25
+ zfreq,
26
+ ztau,
27
+ )
28
+
29
+ MOSA = [12, 23, 31, 13, 32, 21]
30
+
31
+
32
+ @dataclass
33
+ class ObservationConfig:
34
+ """
35
+ This class gathers extrinsic source information: the spacecrafts orbit used,
36
+ the starting time of observation and the size of the signal.
37
+ """
38
+
39
+ orbit_path: str
40
+ t_start: float
41
+ size: int
42
+
43
+
44
+ class STFTWaveform(ABC):
45
+ """
46
+ A class representing a waveform using Short-Time Fourier Transform (STFT),
47
+ inheriting from scipy.signal.ShortTimeFFT, with additional phases and amplitudes attributes.
48
+ """
49
+
50
+ def __init__(
51
+ self,
52
+ *args,
53
+ waveform,
54
+ config: ObservationConfig,
55
+ channel: str,
56
+ ):
57
+ """
58
+ Initialize the STFTWaveform with waveform and time bins.
59
+ Parameters:
60
+ *args : tuple
61
+ Arguments for the ShorTimeFFT initialization.
62
+ waveform: waveform.Waveform instance
63
+ The waveform object that computes amplitudes and phases as a function of time
64
+ or frequency.
65
+ config: ObservationConfig
66
+ Object that contains source extrinsic information and LISA orbital information.
67
+ **kwargs : dict
68
+ Additional keyword arguments for ShotTimeFFT initialization.
69
+ """
70
+
71
+ # TODO: move instances in @property decorated methods.
72
+ w, hop, fs, mfft = args
73
+ # stft parameters
74
+ self.fs = fs
75
+ self.mfft = len(w) if mfft is None else mfft
76
+ self.delta_t = hop / fs
77
+ self.delta_f = fs / self.mfft
78
+ # Waveform instance
79
+ self._waveform = waveform
80
+ # STFT frequency bins
81
+ self.f_bins = jnp.fft.rfftfreq(self.mfft, 1 / self.fs) # Assumes one-sided FFT
82
+ # STFT window
83
+ self.w = jnp.asarray(w)
84
+ # Window sum
85
+ self.w_sum = jnp.sum(self.w)
86
+ # Time series sampling time
87
+ self.dt = jnp.asarray(1 / self.fs)
88
+ # Half of the window duration
89
+ self.half_window_time = self.delta_t / 2
90
+
91
+ self._response: ResponseFromStrain
92
+ self._response_splines: dict
93
+ self.orbit_path = config.orbit_path
94
+ self.size = config.size
95
+ self.t_start = config.t_start
96
+ # STFT time bins
97
+ m = int(self.fs * self.delta_t)
98
+ size_t_bins = config.size // m
99
+ t_max = size_t_bins * self.delta_t
100
+ self.t_bins = jnp.linspace(
101
+ self.t_start, t_max + self.t_start, num=size_t_bins + 1, endpoint=True
102
+ )
103
+
104
+ # Initialize the response
105
+ self._initialize_response(self.delta_t)
106
+
107
+ # Precompute TDI response on the response grid (minus sign to match pyTDI conventions)
108
+ if "2" in channel:
109
+ gen = "2.0"
110
+ else:
111
+ gen = "1.5"
112
+ self.tf_tdi_matrix = -compute_tdi_tf(
113
+ np.asarray(self.f_bins),
114
+ np.asarray(self._response.ltt),
115
+ np.asarray(self._response.t), # Use the response time grid
116
+ gen=gen,
117
+ use_lisagwresponse_convention=True,
118
+ )
119
+
120
+ if "AET" in channel:
121
+ self.tf_tdi_matrix = np.einsum("nijk, jl -> nilk", self.tf_tdi_matrix, aet_mat.T)
122
+ elif "XYZ" not in channel:
123
+ raise ValueError("Channel not XYZ or AET; unknown channel.")
124
+
125
+ self.tf_tdi_matrix = jnp.asarray(self.tf_tdi_matrix)
126
+
127
+ @property
128
+ def waveform(self):
129
+ """Accessor of waveform generator attribute"""
130
+ return self._waveform
131
+
132
+ @property
133
+ def response_splines(self):
134
+ """Accessor to interpolated modulation and delay functions"""
135
+ return self._response_splines
136
+
137
+ @waveform.setter
138
+ def waveform(self, wvf):
139
+ self._waveform = wvf
140
+
141
+ def _initialize_response(self, resp_dt) -> None:
142
+ """Initialize the LISA response system.
143
+ Parameters
144
+ ----------
145
+ gw_beta : float
146
+ ecliptic latitude of the source in radians.
147
+ gw_lambda : float
148
+ ecliptic longitude of the source in radians.
149
+ """
150
+ if not self.orbit_path:
151
+ raise ValueError("Orbit path must be specified for response calculation")
152
+
153
+ # Instantiate the response on a coarse grid of the same size as waveform.t
154
+ self._response = ResponseFromStrain(
155
+ orbits=self.orbit_path,
156
+ dt=resp_dt, # This is the coarse grid
157
+ # Should it be the STFT time resolution?
158
+ size=self.t_bins.size, # Size of the coarse grid
159
+ t0=self.t_start, # Your standard offset, should not be hard-coded
160
+ t=self.t_bins,
161
+ )
162
+
163
+ def _build_response(self, gw_beta, gw_lambda) -> None:
164
+ """Recompute the response modulation and delays from new sky location.
165
+ Parameters
166
+ ----------
167
+ gw_beta : float
168
+ ecliptic latitude of the source in radians.
169
+ gw_lambda : float
170
+ ecliptic longitude of the source in radians.
171
+ """
172
+
173
+ self._response.set_position(
174
+ jnp.asarray(gw_beta), # jnp.pi/2 - self._waveform.qS for EMRIs
175
+ jnp.asarray(gw_lambda), # self._waveform.phiS for EMRIs
176
+ shift_sun="no",
177
+ )
178
+
179
+ def _build_response_splines(
180
+ self,
181
+ ) -> None:
182
+ """Build splines for response pattern functions using orbit file time grid if available."""
183
+
184
+ response_time = self._response.t
185
+ xiplus = self._response.xiplus
186
+ xicross = self._response.xicross
187
+ demi = self._response.demi
188
+ drec = self._response.drec
189
+ n = self._response.n
190
+
191
+ # Compute fplus and fcross from antenna patterns
192
+ denominator = 2 * (1 - dot_custom(n, self._response.k))
193
+ fplus = jnp.squeeze(xiplus / denominator)
194
+ fcross = jnp.squeeze(xicross / denominator)
195
+
196
+ # Build splines
197
+ self._response_splines = {
198
+ "fplus": {
199
+ sc: spline_hermite_jit(response_time, jnp.asarray(fplus[:, i]))
200
+ for i, sc in enumerate(MOSA)
201
+ },
202
+ "fcross": {
203
+ sc: spline_hermite_jit(response_time, jnp.asarray(fcross[:, i]))
204
+ for i, sc in enumerate(MOSA)
205
+ },
206
+ "demi": {
207
+ sc: spline_hermite_jit(response_time, jnp.asarray(demi[:, i]))
208
+ for i, sc in enumerate(MOSA)
209
+ },
210
+ "drec": {
211
+ sc: spline_hermite_jit(response_time, jnp.asarray(drec[:, i]))
212
+ for i, sc in enumerate(MOSA)
213
+ },
214
+ }
215
+
216
+ def update_parameters(self, gw_beta, gw_lambda) -> None:
217
+ """
218
+ Update waveform parameters and rebuild splines.
219
+
220
+ Parameters
221
+ ----------
222
+ *args : tuple
223
+ Parameters in order: [M, mu, a, p0, e0, x0, dist, qS, phiS, qK, phiK] for EMRIs
224
+ [m1, m2, chi1, chi2, inc, fstart, phi, psi, dist] for SOBHB
225
+ [m1, m2, chi1, chi2, inc, fstart, Deltat, phi, psi, dist] for MBHB
226
+ **kwargs : dict
227
+ Additional parameters including:
228
+ - dt: Sampling period [s]
229
+ - orbit_path: Path to orbit file
230
+ """
231
+ # Update response parameters and re-build modulation and delay splines
232
+ self._build_response(gw_beta, gw_lambda)
233
+ self._build_response_splines()
234
+
235
+ def compute_hphc(self, **kwargs):
236
+ """
237
+ Compute h+ and hx components STFT from a time-domain or frequency-domain waveform.
238
+ Placeholder for actual implementation.
239
+ """
240
+ raise NotImplementedError("This method should be implemented by subclasses.")
241
+
242
+ def get_nonzero_indices(self, f_tau, di=5):
243
+ """
244
+ Get the indices of non-zero elements in the STFT waveform.
245
+ Parameters
246
+ ----------
247
+ f_tau : ndarray
248
+ Waveform frequencies at STFT times (number of modes x number of time bins)
249
+ di : int, optional
250
+ Number of frequency bins to consider around each frequency in the STFT, by default 5
251
+
252
+ Returns
253
+ -------
254
+ indices_f : ndarray
255
+ Array of frequency indices (number of modes x number of time bins)
256
+ Indices around f ((2*di+1) x number of modes x number of time bins)
257
+ indices_t : ndarray
258
+ Indices of time bins
259
+ """
260
+ offsets = jnp.arange(-di, di + 1)
261
+ return vmapped_get_nonzero_indices_pure(f_tau, self.delta_t, self.f_bins, offsets)
262
+
263
+ def compute_arm_response_tf(self, **kwargs):
264
+ """
265
+ Compute arm responses using time-frequency approximation approach.
266
+
267
+ Parameters:
268
+ di_resp: Frequency bin range (default: 10)
269
+ arm_index: Index of the arm to compute response for (0, 1, or 2)
270
+ **kwargs: Additional parameters
271
+
272
+ Returns:
273
+ sy_approx_tf: Sparse STFT matrix for the arm response (n_frequencies x n_times x 6)
274
+ indices_f: Frequency indices used
275
+ indices_t: Time indices used
276
+ """
277
+ # Get the undelayed hplus and hcross STFT approximations (already sparse)
278
+ h_plus, h_cross, indices_f, indices_t = self.compute_hphc(ssb=True, **kwargs)
279
+ # Get modulations
280
+ fplus, fcross = self._response.get_fplus_fcross()
281
+ # Get frequencies for phase factors
282
+ return jax.jit(single_wvf_arm_response_tf)(
283
+ self.f_bins,
284
+ fplus,
285
+ fcross,
286
+ self._response.demi,
287
+ self._response.drec,
288
+ h_plus,
289
+ h_cross,
290
+ indices_f,
291
+ indices_t,
292
+ )
293
+
294
+ def compute_tdi_tf_response(self, **kwargs):
295
+ """
296
+ Compute TDI responses STFT from the frequency-domain waveform.
297
+ """
298
+
299
+ # Get arm responses and indices
300
+ sy_approx_tf, indices_f, indices_t = self.compute_arm_response_tf(**kwargs)
301
+
302
+ return jitted_tdi_response_tf(self.tf_tdi_matrix, sy_approx_tf, indices_f, indices_t)
303
+
304
+
305
+ class TimeToTFWaveform(STFTWaveform):
306
+ """
307
+ A class representing a waveform in time-to-time-frequency domain build from phases and
308
+ amplitudes
309
+ in the time domain, inheriting from STFTWaveform.
310
+ """
311
+
312
+ def compute_stft_approx(self, tau, f, *args):
313
+ """
314
+ Compute the approximate TF waveform from flattened amplitudes and phases
315
+
316
+ Parameters
317
+ ----------
318
+ tau : ndarray
319
+ 1d array of STFT times
320
+ f : ndarray
321
+ 1d array of STFT frequencies
322
+ a_tau : ndarray
323
+ 1d array of waveform amplitudes
324
+ phi_tau : ndarray
325
+ waveform phases
326
+ dphi_tau : ndarray
327
+ waveform frequencies, and frequency derivatives
328
+ ddphi_tau : ndarray
329
+ waveform frequency derivatives
330
+ """
331
+
332
+ a_tau = args[0]
333
+ phi_tau = args[1]
334
+ f_tau = args[2]
335
+ df_tau = args[3]
336
+
337
+ # Compute and re-convert to xp arrays
338
+ z_tilde_plus = jnp.asarray(
339
+ zfreq(
340
+ f_tau + f,
341
+ df_tau,
342
+ -self.half_window_time,
343
+ self.half_window_time,
344
+ )
345
+ / self.dt
346
+ )
347
+ z_tilde_minus = jnp.asarray(
348
+ zfreq(
349
+ f_tau - f,
350
+ df_tau,
351
+ -self.half_window_time,
352
+ self.half_window_time,
353
+ )
354
+ / self.dt
355
+ )
356
+
357
+ # STFT of the complex strain
358
+ exp_phasor = jnp.exp(-2j * jnp.pi * f * tau)
359
+ exp_phitau = jnp.exp(-1j * phi_tau)
360
+ s_h = exp_phasor * a_tau * exp_phitau * z_tilde_plus
361
+ # Complex conjugate of the STFT of the complex strain evaluated at the negative frequency
362
+ s_h_conj = exp_phasor * jnp.conj(a_tau * exp_phitau * z_tilde_minus)
363
+
364
+ # Compute flattended STFT approximation
365
+ return (s_h_conj + s_h) / 2.0, (s_h_conj - s_h) / (2.0j)
366
+
367
+ def compute_hphc(self, di=5, ssb=False, **kwargs):
368
+ """Build approximate time-frequency waveform from amplitude and phase functions.
369
+ Parameters
370
+ ----------
371
+ di : int, optional
372
+ Number of frequency bins to consider around each frequency in the STFT, by default 5
373
+
374
+ Returns
375
+ -------
376
+ s_plus : ndarray
377
+ Approximate STFT of the h+ component. Has shape (number of frequency bins, number of
378
+ time bins)
379
+ s_cross : ndarray
380
+ Approximate STFT of the hx component. Has shape (number of frequency bins, number of
381
+ time bins)
382
+ indices_f : ndarray
383
+ Indices of frequency bins used in the approximation. Has shape (2*di+1, number of modes,
384
+ number of time bins)
385
+ indices_t : ndarray
386
+ Indices of time bins used in the approximation
387
+ """
388
+
389
+ # STFT time bins
390
+ t_bins = jnp.asarray(self.t_bins)
391
+
392
+ # Initialize approximate STFT
393
+ # s_plus = jnp.zeros((self.f_bins.size, self.t_bins.size), dtype=complex)
394
+ # s_cross = jnp.zeros((self.f_bins.size, self.t_bins.size), dtype=complex)
395
+
396
+ # Compute amplitude and phase derivatives vs time
397
+ waveform_vars = self.waveform.compute_amplitudes_and_phases_derivatives(t_bins)
398
+ # if waveform_vars[0].ndim == 2:
399
+ # n_modes = waveform_vars[0].shape[0]
400
+ # else:
401
+ # n_modes = 1
402
+
403
+ if ssb:
404
+ psi_ldc = self.waveform.compute_polarization_angle()
405
+ # Extract components and modify phase
406
+ amp, phi, dphi, ddphi = waveform_vars
407
+ phi = phi + 2 * psi_ldc
408
+ waveform_vars = (amp, phi, dphi, ddphi)
409
+
410
+ # Get the indices of non-zero frequency bins (size (2*di+1, n_modes, n_times))
411
+ offsets = jnp.arange(-di, di + 1)
412
+ indices_f, indices_t = get_nonzero_indices_pure(
413
+ waveform_vars[2], self.delta_t, self.f_bins, offsets
414
+ )
415
+
416
+ # Get the frequencies (2*di+1, n_modes, n_times)
417
+ f = self.f_bins[indices_f]
418
+ # Compute the approximate STFT at the selected indices
419
+ s_plus_tracks, s_cross_tracks = self.compute_stft_approx(
420
+ t_bins,
421
+ f,
422
+ *waveform_vars,
423
+ )
424
+
425
+ # Assign
426
+ s_plus = jnp.zeros((self.f_bins.size, self.t_bins.size), dtype=complex)
427
+ s_cross = jnp.zeros((self.f_bins.size, self.t_bins.size), dtype=complex)
428
+
429
+ s_plus = s_plus.at[indices_f, indices_t].add(s_plus_tracks / self.w_sum)
430
+ s_cross = s_cross.at[indices_f, indices_t].add(s_cross_tracks / self.w_sum)
431
+
432
+ return s_plus, s_cross, indices_f, indices_t
433
+
434
+ def compute_arm_responses(self, *args, **kwargs):
435
+ """
436
+ Compute arm responses from the time-to-frequency waveform.
437
+ Placeholder for actual implementation.
438
+ """
439
+
440
+ def compute_tdi_responses(self, *args, **kwargs):
441
+ """
442
+ Compute TDI responses from the time-to-frequency waveform.
443
+ Placeholder for actual implementation.
444
+ """
445
+ # Implement your logic here
446
+
447
+
448
+ class FrequencyToTFWaveform(STFTWaveform):
449
+ """
450
+ A class representing a waveform in frequency-to-time-frequency domain build from phases and
451
+ amplitudes in the time domain, inheriting from STFTWaveform.
452
+ """
453
+
454
+ def compute_stft_approx(self, tau, *args):
455
+ """
456
+ Compute the approximate TF waveform from flattened amplitudes and phases
457
+
458
+ Parameters
459
+ ----------
460
+ f : ndarray
461
+ 1d array of STFT frequencies
462
+ a_tau : ndarray
463
+ 1d array of waveform amplitudes
464
+ dphi_tau : ndarray
465
+ list of waveform phases, times, and times derivatives
466
+ """
467
+
468
+ a_freq = args[0]
469
+ phi_freq = args[1]
470
+ tau_f = args[2]
471
+ dtau_f = args[3]
472
+
473
+ # Compute and re-convert to xp arrays
474
+ z_tilde = jnp.asarray(
475
+ ztau(
476
+ tau - tau_f,
477
+ dtau_f,
478
+ -self.half_window_time,
479
+ self.half_window_time,
480
+ )
481
+ / self.dt
482
+ )
483
+
484
+ # STFT of the complex strain
485
+ exp_phif = jnp.exp(-1j * phi_freq)
486
+ s_h = a_freq * exp_phif * z_tilde
487
+
488
+ # Compute flattended STFT approximation
489
+ return s_h
490
+
491
+ def vmapped_compute_hphc(self, di=5, ssb=False):
492
+ """Build approximate time-frequency waveform from amplitude and phase functions
493
+ given in frequency domain.
494
+ Parameters
495
+ ----------
496
+ di : int, optional
497
+ Number of frequency bins to consider around each frequency in the STFT, by default 5
498
+
499
+ Returns
500
+ -------
501
+ s_plus : ndarray
502
+ Approximate STFT of the h+ component. Has shape (number of frequency bins, number of
503
+ time bins)
504
+ s_cross : ndarray
505
+ Approximate STFT of the hx component. Has shape (number of frequency bins, number of
506
+ time bins)
507
+ indices_f : ndarray
508
+ Indices of frequency bins used in the approximation. Has shape (2*di+1, number of modes,
509
+ number of time bins)
510
+ indices_t : ndarray
511
+ Indices of time bins used in the approximation
512
+ """
513
+
514
+ # Compute relevant indices
515
+ tau_f = self.waveform.vmapped_compute_times(self.waveform.freq)
516
+
517
+ f_tau = vmapped_f_of_t_from_dphi(tau_f, self.waveform.freq, self.t_bins)
518
+
519
+ indices_f, indices_t = self.get_nonzero_indices(f_tau=f_tau, di=di)
520
+
521
+ f = self.f_bins[indices_f]
522
+ t = self.t_bins[indices_t]
523
+
524
+ waveform_vars_plus = self.waveform.compute_amplitudes_and_phases_derivatives(f)
525
+ waveform_vars_minus = self.waveform.compute_amplitudes_and_phases_derivatives(-f)
526
+
527
+ # if waveform_vars_plus[0].ndim > 1:
528
+ # n_modes = waveform_vars_plus[0].shape[0]
529
+ # else:
530
+ # n_modes = 1
531
+
532
+ psi = self.waveform.compute_polarization_angle()
533
+ ssb_fact = compute_ssb_fact(psi, ssb=ssb)
534
+
535
+ s_plus_all, s_cross_all = stft_for_many_jitted(
536
+ waveform_vars_plus,
537
+ waveform_vars_minus,
538
+ t,
539
+ indices_f,
540
+ ssb_fact,
541
+ self.w_sum,
542
+ self.compute_stft_approx,
543
+ )
544
+
545
+ return s_plus_all, s_cross_all, indices_f, indices_t
546
+
547
+ def compute_hphc(self, di=5, ssb=False, **kwargs):
548
+ """Build approximate time-frequency waveform from amplitude and phase functions
549
+ given in frequency domain.
550
+ Parameters
551
+ ----------
552
+ di : int, optional
553
+ Number of frequency bins to consider around each frequency in the STFT, by default 5
554
+
555
+ Returns
556
+ -------
557
+ s_plus : ndarray
558
+ Approximate STFT of the h+ component. Has shape (number of frequency bins, number of
559
+ time bins)
560
+ s_cross : ndarray
561
+ Approximate STFT of the hx component. Has shape (number of frequency bins, number of
562
+ time bins)
563
+ indices_f : ndarray
564
+ Indices of frequency bins used in the approximation. Has shape (2*di+1, number of modes,
565
+ number of time bins)
566
+ indices_t : ndarray
567
+ Indices of time bins used in the approximation
568
+ """
569
+
570
+ # Compute relevant indices
571
+ tau_f = self.waveform.compute_times(self.waveform.freq) + self.t_start
572
+
573
+ f_tau = f_of_t_from_dphi(tau_f, self.waveform.freq, self.t_bins)
574
+
575
+ offsets = jnp.arange(-di, di + 1)
576
+ indices_f, indices_t = get_nonzero_indices_pure(f_tau, self.delta_t, self.f_bins, offsets)
577
+
578
+ f = self.f_bins[indices_f]
579
+ t = self.t_bins[indices_t] - self.t_start
580
+
581
+ waveform_vars_plus = self.waveform.compute_amplitudes_and_phases_derivatives(f)
582
+ waveform_vars_minus = self.waveform.compute_amplitudes_and_phases_derivatives(-f)
583
+
584
+ # if waveform_vars_plus[0].ndim > 1:
585
+ # n_modes = waveform_vars_plus[0].shape[0]
586
+ # else:
587
+ # n_modes = 1
588
+
589
+ psi = self.waveform.compute_polarization_angle()
590
+ ssb_fact = compute_ssb_fact(psi, ssb=ssb)
591
+
592
+ # s_plus, s_cross = jax.jit(stft_for_one_waveform, static_argnums=6)(
593
+ s_plus, s_cross = stft_for_one_waveform(
594
+ waveform_vars_plus,
595
+ waveform_vars_minus,
596
+ t,
597
+ indices_f,
598
+ ssb_fact,
599
+ self.w_sum,
600
+ self.compute_stft_approx,
601
+ )
602
+
603
+ return s_plus, s_cross, indices_f, indices_t
604
+
605
+ def compute_arm_responses(self, **kwargs):
606
+ """Not implemented for this class."""
607
+
608
+ def compute_tdi_responses(self, **kwargs):
609
+ """Not implemented for this class."""
610
+
611
+ def compute_arm_response_tf(self, di=5, **kwargs):
612
+ """Computes arm response in tf domain
613
+
614
+ Parameters
615
+ ----------
616
+ di : int, optional
617
+ Number of frequency bins to consider around each frequency in the STFT, by default 5
618
+ Returns
619
+ -------
620
+ s_cross : ndarray
621
+ Approximate STFT of the links. Has shape (number of frequency bins x number of
622
+ time bins, 6).
623
+ indices_f : ndarray
624
+ Indices of frequency bins used in the approximation. Has shape (2*di+1, number of modes,
625
+ number of time bins)
626
+ indices_t : ndarray
627
+ Indices of time bins used in the approximation.
628
+ """
629
+ # Compute relevant indices
630
+ tau_f = self.waveform.compute_times(self.waveform.freq) + self.t_start
631
+ f_tau = f_of_t_from_dphi(tau_f, self.waveform.freq, self.t_bins)
632
+
633
+ offsets = jnp.arange(-di, di + 1)
634
+ indices_f, indices_t = get_nonzero_indices_pure(f_tau, self.delta_t, self.f_bins, offsets)
635
+
636
+ f = self.f_bins[indices_f]
637
+ t = self.t_bins[indices_t] - self.t_start
638
+
639
+ waveform_vars = self.waveform.compute_pure_amplitudes_and_phases_derivatives(f)
640
+
641
+ # Build exact bin edges matching t-bins to avoid arange floating-step drift.
642
+ time_span = (
643
+ jnp.concatenate(
644
+ [
645
+ t - self.half_window_time,
646
+ jnp.asarray([t[-1] + self.half_window_time]),
647
+ ]
648
+ )
649
+ + self.t_start
650
+ )
651
+
652
+ fplus_sc = jnp.stack(
653
+ [jnp.asarray(self.response_splines["fplus"][sc](time_span)) for sc in MOSA],
654
+ axis=-1,
655
+ )
656
+ fcross_sc = jnp.stack(
657
+ [jnp.asarray(self.response_splines["fcross"][sc](time_span)) for sc in MOSA],
658
+ axis=-1,
659
+ )
660
+ demi_sc = jnp.stack(
661
+ [jnp.asarray(self.response_splines["demi"][sc](time_span)) for sc in MOSA],
662
+ axis=-1,
663
+ )
664
+ drec_sc = jnp.stack(
665
+ [jnp.asarray(self.response_splines["drec"][sc](time_span)) for sc in MOSA],
666
+ axis=-1,
667
+ )
668
+
669
+ phase_amp = (
670
+ jnp.exp(-1j * jnp.sign(waveform_vars[3]) * jnp.pi / 4.0)
671
+ * waveform_vars[0]
672
+ * jnp.exp(-1j * waveform_vars[1])
673
+ )[..., jnp.newaxis]
674
+
675
+ sc_output = linearized_quadrature_vectorized(
676
+ fplus_sc,
677
+ fcross_sc,
678
+ demi_sc,
679
+ drec_sc,
680
+ t,
681
+ f,
682
+ self.delta_t,
683
+ waveform_vars[2],
684
+ waveform_vars[3],
685
+ phase_amp,
686
+ )
687
+
688
+ y_sc = (
689
+ (
690
+ (sc_output[0] - sc_output[1]) * self.waveform.fact_amplitude_plus
691
+ + (sc_output[2] - sc_output[3]) * self.waveform.fact_amplitude_cross
692
+ )
693
+ / self.dt
694
+ / self.w_sum
695
+ / jnp.sqrt(jnp.abs(waveform_vars[3]))[..., jnp.newaxis]
696
+ )
697
+
698
+ # Flatten with time-major ordering to match returned sparse indices:
699
+ # indices_f.T.ravel() / broadcast(indices_t).T.ravel()
700
+ sy = y_sc.transpose(1, 0, 2).reshape((-1, 6))
701
+
702
+ # Safety guard; ideally unnecessary once prep is NaN-safe
703
+ sy = jnp.nan_to_num(sy)
704
+
705
+ return (
706
+ sy,
707
+ indices_f.T.ravel(),
708
+ jnp.broadcast_to(indices_t, indices_f.shape).T.ravel(),
709
+ )
710
+
711
+
712
+ # _vmapped_compute_arm_response_sc = jax.jit(
713
+ # jax.vmap(
714
+ # _compute_single_spacecraft_arm_response,
715
+ # in_axes=(0, 0, 0, 0, None, None, None, None, None, None, None),
716
+ # )
717
+ # )
718
+
719
+
720
+ @jax.jit
721
+ def f_of_t_from_dphi(tau, f_grid, t_grid):
722
+ """Computes f(t) from tau(f) using a JAX cubic spline inverse."""
723
+ # Enforce monotonic tau to keep inverse well-defined.
724
+ tau_monotonic = jnp.maximum.accumulate(tau)
725
+
726
+ # Ensure strict monotonicity to avoid zero-width intervals in searchsorted.
727
+ eps = jnp.asarray(1e-15, dtype=tau_monotonic.dtype)
728
+ tau_monotonic = tau_monotonic + eps * jnp.arange(tau_monotonic.size, dtype=tau_monotonic.dtype)
729
+
730
+ tmin = tau_monotonic[0]
731
+ tmax = tau_monotonic[-1]
732
+
733
+ # JAX-native spline inversion: f(t) directly from tau(f).
734
+ spline_f_of_t = spline_cubic_jit(tau_monotonic, f_grid)
735
+ f_t = spline_f_of_t(t_grid)
736
+
737
+ # Keep previous behavior outside support: set to zero.
738
+ mask = (t_grid >= tmin) & (t_grid <= tmax)
739
+ f_t = jnp.where(mask, f_t, 0.0)
740
+ return f_t
741
+
742
+
743
+ vmapped_f_of_t_from_dphi = jax.vmap(f_of_t_from_dphi, in_axes=(0, 0, None))
744
+
745
+
746
+ @jax.jit
747
+ def compute_ssb_fact(psi, ssb=False):
748
+ """Compute SSB factor for SSB frame conversion.
749
+
750
+ Args:
751
+ waveform (FDWaveform): waveform having psi as attribute.
752
+ ssb (bool, optional): To convert to SSB or not. Defaults to False.
753
+
754
+ Returns:
755
+ _type_: _description_
756
+ """
757
+ ssb_fact = jnp.where(
758
+ ssb,
759
+ jnp.exp(-2j * psi),
760
+ 1.0 + 0.0j,
761
+ )
762
+
763
+ return ssb_fact
764
+
765
+
766
+ @jax.jit
767
+ def get_nonzero_indices_pure(f_tau, delta_t, f_bins, offsets):
768
+ """JIT-compatible helper function to extract non zero indices.
769
+
770
+ Args:
771
+ f_tau (array): f(tau) array
772
+ delta_t (array): STFT time step.
773
+ f_bins (array): STFT freq bins
774
+ offsets (array): offset to be applied
775
+ around track.
776
+
777
+ Returns:
778
+ arrays: arrays of non zeros indices.
779
+ """
780
+
781
+ # same as: jnp.where(f_tau.ndim > 1, f_tau.shape[1], f_tau.size),but jit-safe
782
+ n_times = f_tau.shape[-1]
783
+
784
+ # Array of frequency indices (number of modes x number of time bins)
785
+ indices_f = jnp.asarray((delta_t * f_tau).astype(int))
786
+ # Indices around f ((2*di+1) x number of modes x number of time bins)
787
+ indices_f = indices_f[None, ...] + offsets[:, None, None]
788
+ # Clip indices to valid range to avoid out-of-bounds errors
789
+ indices_f = jnp.clip(indices_f, 0, f_bins.size - 1)
790
+ # Indices of time bins
791
+ indices_t = jnp.arange(n_times)
792
+ return jnp.squeeze(indices_f), indices_t
793
+
794
+
795
+ vmapped_get_nonzero_indices_pure = jax.vmap(get_nonzero_indices_pure, in_axes=(0, None, None, None))
796
+
797
+
798
+ def stft_for_one_waveform(
799
+ vars_plus_i,
800
+ vars_minus_i,
801
+ t_i,
802
+ indices_f_i,
803
+ ssb_i,
804
+ w_sum,
805
+ compute_stft_approx_fn,
806
+ ):
807
+ """
808
+ Computes approximates stft with STFTWaveform methods. Helper function to be jitted.
809
+ """
810
+
811
+ s_h_plus_approx = compute_stft_approx_fn(t_i, *vars_plus_i) * ssb_i
812
+ s_h_minus_approx = compute_stft_approx_fn(t_i, *vars_minus_i) * ssb_i
813
+
814
+ upd_plus = ((s_h_minus_approx.conj() + s_h_plus_approx) / (2.0 * w_sum)).ravel()
815
+ upd_cross = ((s_h_minus_approx.conj() - s_h_plus_approx) / (2.0j * w_sum)).ravel()
816
+
817
+ # TODO: check whether this below is necessary,
818
+ # or why we don't simply return the two arrays above?
819
+ s_plus_i = jnp.zeros(indices_f_i.size, dtype=complex)
820
+ s_cross_i = jnp.zeros(indices_f_i.size, dtype=complex)
821
+
822
+ s_plus_i = s_plus_i.at[:].add(upd_plus)
823
+ s_cross_i = s_cross_i.at[:].add(upd_cross)
824
+
825
+ return s_plus_i, s_cross_i
826
+
827
+
828
+ stft_for_many_jitted = jax.jit(
829
+ jax.vmap(
830
+ stft_for_one_waveform,
831
+ in_axes=(0, 0, 0, 0, 0, None, None),
832
+ ),
833
+ static_argnums=6,
834
+ )
835
+
836
+
837
+ def single_wvf_arm_response_tf(
838
+ f_bins,
839
+ fplus,
840
+ fcross,
841
+ response_demi,
842
+ response_drec,
843
+ h_plus,
844
+ h_cross,
845
+ indices_f,
846
+ indices_t,
847
+ ):
848
+ """Computing arm response for single waveform. Can be vmapped."""
849
+ if indices_f.ndim == 3 and indices_f.shape[1] == 1:
850
+ indices_f = indices_f.reshape(indices_f.shape[0], indices_f.shape[2])
851
+ # Convert h_plus and h_cross to dense at selected indices for multiplication
852
+ coords = jnp.vstack([indices_f.ravel(), jnp.broadcast_to(indices_t, indices_f.shape).ravel()])
853
+ f = f_bins[coords[0]][..., jnp.newaxis]
854
+
855
+ # Compute the exponential delays to apply (for d_emi and d_rec)
856
+ dephasing = jnp.exp(2j * jnp.pi * f * response_demi[coords[1], :]) - jnp.exp(
857
+ 2j * jnp.pi * f * response_drec[coords[1], :]
858
+ )
859
+
860
+ # Process all components
861
+ sy = dephasing * (
862
+ fplus[coords[1], :] * h_plus[:, jnp.newaxis]
863
+ + fcross[coords[1], :] * h_cross[:, jnp.newaxis]
864
+ )
865
+
866
+ return sy, coords[0], coords[1]
867
+
868
+
869
+ jitted_arm_response_tf = jax.jit(
870
+ jax.vmap(
871
+ single_wvf_arm_response_tf,
872
+ in_axes=(None, 2, 2, 2, 2, 0, 0, 0, 0),
873
+ )
874
+ )
875
+
876
+
877
+ def single_wvf_tdi_response_tf(
878
+ full_tdi_matrix,
879
+ sy_approx_i,
880
+ indices_f_i,
881
+ indices_t_i,
882
+ ):
883
+ """Multiplies arm response with TDI matrix on relevant indices."""
884
+ tdi_matrix = full_tdi_matrix[indices_f_i, indices_t_i, :, :]
885
+
886
+ # Compute TDI responses using einsum for efficiency
887
+ # result = jnp.zeros((indices_f_i.size, 3), dtype=complex)
888
+
889
+ result = multiple_dot_vect(jnp.asarray(tdi_matrix), sy_approx_i)
890
+
891
+ return (
892
+ jnp.squeeze(result),
893
+ indices_f_i,
894
+ indices_t_i,
895
+ ) # TODO: dig deeper and find where the extra dimension appears to fix it.
896
+
897
+
898
+ jitted_vmapped_tdi_response_tf = jax.jit(
899
+ jax.vmap(single_wvf_tdi_response_tf, in_axes=(None, 0, 0, 0))
900
+ )
901
+
902
+ jitted_tdi_response_tf = jax.jit(single_wvf_tdi_response_tf)