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.
@@ -0,0 +1,474 @@
1
+ #! /usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """Plugin that implements SOBHB waveform generator based on ripplegw."""
4
+
5
+ import lisaconstants
6
+
7
+ from tfwaves.interpolation import JAXCubicSpline, JAXHermiteSpline
8
+ from tfwaves.waveform import FDWaveform
9
+
10
+ from .sobhbparams import SOBHBParams
11
+
12
+ try:
13
+ from ripplegw.waveforms import IMRPhenomD
14
+ except ImportError as exc:
15
+ raise ImportError("This plugin is based on ripplegw, please install it!") from exc
16
+
17
+ try:
18
+ import jax
19
+ except ImportError:
20
+ jax = None
21
+
22
+ if jax is not None:
23
+ import jax.numpy as jnp
24
+ from jax import config
25
+
26
+ config.update("jax_enable_x64", True)
27
+ else:
28
+ jnp = None
29
+
30
+ try:
31
+ import flax
32
+ except ImportError:
33
+ flax = None
34
+
35
+
36
+ Msun_s = lisaconstants.GM_SUN / lisaconstants.c**3.0
37
+
38
+
39
+ ### Jitting spline building function!
40
+ hermite_spline_jit = jax.jit(JAXHermiteSpline.build)
41
+ cubic_spline_jit = jax.jit(JAXCubicSpline.build)
42
+
43
+
44
+ @flax.struct.dataclass
45
+ class SOBHBWaveform(FDWaveform):
46
+ """
47
+ JAX-compatible SOBHB waveform generator with LISA response capabilities, based on ripplegw.
48
+ """
49
+
50
+ t_obs: float
51
+ params: SOBHBParams
52
+ freq: jax.Array
53
+ amp_spline: JAXCubicSpline | JAXHermiteSpline
54
+ phase_spline: JAXCubicSpline | JAXHermiteSpline
55
+ fact_pos: complex
56
+ fact_neg: complex
57
+ ssb_fact: complex
58
+ fact_amplitude_plus: complex
59
+ fact_amplitude_cross: complex
60
+
61
+ # --- Constructors ---
62
+ @staticmethod
63
+ def make_from_params(theta: SOBHBParams):
64
+ """Factory method: builds waveform state from parameters."""
65
+
66
+ freq, tc = set_freq_grid_and_tc(theta, dt=theta.cadence)
67
+ amp, phase = waveform_gen(theta, freq, tc)
68
+
69
+ amp_spline = hermite_spline_jit(freq, amp)
70
+ phase_spline = hermite_spline_jit(freq, phase)
71
+
72
+ K22p = Kplus22(theta.iota, theta.phi0)
73
+ K22c = Kcross22(theta.iota, theta.phi0)
74
+ fact_pos = jnp.conj(K22p) - 1j * jnp.conj(K22c)
75
+ fact_neg = K22p - 1j * K22c
76
+ ssb_fact = jnp.exp(-2.0j * theta.psi)
77
+
78
+ return SOBHBWaveform(
79
+ t_obs=theta.t_obs,
80
+ params=theta,
81
+ freq=freq,
82
+ amp_spline=amp_spline,
83
+ phase_spline=phase_spline,
84
+ fact_pos=fact_pos,
85
+ fact_neg=fact_neg,
86
+ ssb_fact=ssb_fact,
87
+ fact_amplitude_plus=(fact_neg.conj() * ssb_fact.conj() + fact_pos * ssb_fact) / 2.0,
88
+ fact_amplitude_cross=(fact_neg.conj() * ssb_fact.conj() - fact_pos * ssb_fact) / 2.0j,
89
+ )
90
+
91
+ # --- Computation methods ---
92
+ @jax.jit
93
+ def compute_amplitudes(self, freq: jax.typing.ArrayLike) -> jax.Array:
94
+ amplitudes = self.amp_spline(jnp.abs(freq))
95
+ return jnp.where(freq < 0.0, self.fact_neg * amplitudes, self.fact_pos * amplitudes)
96
+
97
+ @jax.jit
98
+ def compute_pure_amplitudes(self, freq: jax.typing.ArrayLike) -> jax.Array:
99
+ """Computes pure amplitude without Ylm factors"""
100
+ return self.amp_spline(jnp.abs(freq))
101
+
102
+ @jax.jit
103
+ def compute_phases(self, freq: jax.typing.ArrayLike) -> jax.Array:
104
+ phase = self.phase_spline(jnp.abs(freq))
105
+ return phase * jnp.sign(freq)
106
+
107
+ @jax.jit
108
+ def compute_times(self, freq: jax.typing.ArrayLike) -> jax.Array:
109
+ """Compute times from phase derivative."""
110
+ dphi_df = self.phase_spline.derivative(order=1)(jnp.abs(freq))
111
+ return dphi_df / (2 * jnp.pi)
112
+
113
+ @jax.jit
114
+ @jax.vmap
115
+ def vmapped_compute_times(self, freq: jax.typing.ArrayLike) -> jax.Array:
116
+ """Vmapped version of compute_times."""
117
+ return self.compute_times(freq)
118
+
119
+ @jax.jit
120
+ def compute_times_derivatives(self, freq: jax.typing.ArrayLike) -> jax.Array:
121
+ """Compute time derivatives from 2nd phase derivative."""
122
+ d2phi_df2 = self.phase_spline.derivative(order=2)(jnp.abs(freq))
123
+ return d2phi_df2 / (2 * jnp.pi) * jnp.sign(freq)
124
+
125
+ @jax.jit
126
+ # @jax.vmap
127
+ def compute_amplitudes_and_phases_derivatives(self, freq: jax.typing.ArrayLike):
128
+ """
129
+ Compute amplitudes, phases, times, and times derivatives all in a row
130
+
131
+ Parameters
132
+ ----------
133
+ freq : ndarray
134
+ STFT frequencies
135
+
136
+ Returns
137
+ -------
138
+ a_tau, phi_tau, tau_f, dtau_f
139
+ phases, times, times derivatives
140
+ """
141
+
142
+ return (
143
+ self.compute_amplitudes(freq),
144
+ self.compute_phases(freq),
145
+ self.compute_times(freq),
146
+ self.compute_times_derivatives(freq),
147
+ )
148
+
149
+ def compute_pure_amplitudes_and_phases_derivatives(self, freq: jax.typing.ArrayLike):
150
+ """
151
+ Compute amplitudes, phases, times, and times derivatives all in a row
152
+
153
+ Parameters
154
+ ----------
155
+ freq : ndarray
156
+ STFT frequencies
157
+
158
+ Returns
159
+ -------
160
+ a_tau, phi_tau, tau_f, dtau_f
161
+ phases, times, times derivatives
162
+ """
163
+
164
+ return (
165
+ self.compute_pure_amplitudes(freq),
166
+ self.compute_phases(freq),
167
+ self.compute_times(freq),
168
+ self.compute_times_derivatives(freq),
169
+ )
170
+
171
+ def compute_strain(self, freq: jax.typing.ArrayLike, ssb: bool = False) -> jax.Array:
172
+ """Compute source-frame gravitational wave strain."""
173
+
174
+ amp = self.compute_amplitudes(freq)
175
+ phase = self.compute_phases(freq)
176
+
177
+ if ssb:
178
+ return amp * jnp.exp(-1j * phase) * jnp.exp(-2j * self.params["psi"])
179
+
180
+ return amp * jnp.exp(-1j * phase)
181
+
182
+ # @jax.vmap
183
+ def compute_polarization_angle(
184
+ self,
185
+ ):
186
+ """Compute polarization angle."""
187
+ return self.params.psi
188
+
189
+ def update_parameters(
190
+ self,
191
+ ):
192
+ """This method is not overridden as this class is static."""
193
+ return
194
+
195
+
196
+ ### Non-class member helper function to be jitted and vmapped.
197
+
198
+ grad_inspiral_phase = jax.grad(IMRPhenomD.get_inspiral_phase)
199
+ grad_IIb_phase = jax.grad(IMRPhenomD.get_IIb_raw_phase)
200
+
201
+
202
+ @jax.jit
203
+ def funcNewtonianfoftGeom(q, deltat):
204
+ """Computes the Newtonian estimate of f(deltat), where deltat is the time before merger,
205
+ for a binary of mass ratio q>1.
206
+
207
+ Args:
208
+ q (float): mass ratio. Greater than 1
209
+ deltat (float): Time to merger in s.
210
+
211
+ Returns:
212
+ float: estimate of f in geometric units (Mf).
213
+ """
214
+ nu = q / (1.0 + q) / (1.0 + q)
215
+ return 1.0 / jnp.pi * (256 * nu / 5.0 * deltat) ** (-3.0 / 8)
216
+
217
+
218
+ def imrphenomd_time_of_frequency(f, tref, theta):
219
+ """Return t(f) for given parameters
220
+
221
+ Args:
222
+ f (_type_): _description_
223
+ tref (_type_): _description_
224
+ theta (jax.Array): The order of the parameters is:
225
+ Mchirp (Msol), eta (symmetric mass ratio), chi1, chi2, dist (Mpc),
226
+ fstart (Hz), phi0, iota, psi, alpha, delta, t_obs (s).
227
+
228
+ Returns:
229
+ _type_: _description_
230
+ """
231
+ # This should return t(f) for the given parameters.
232
+ # tref is given in [s].
233
+ theta_intrinsic = jnp.array([theta.m1, theta.m2, theta.chi1, theta.chi2])
234
+
235
+ coeffs = IMRPhenomD.get_coeffs(theta_intrinsic)
236
+
237
+ M_s = (theta.m1 + theta.m2) * Msun_s
238
+
239
+ # Shift phase so that peak amplitude matches t = 0
240
+ t0 = grad_inspiral_phase(f * M_s, theta_intrinsic, coeffs)
241
+ return t0 * M_s / (2.0 * jnp.pi) - tref
242
+
243
+
244
+ @jax.jit
245
+ def imrphenomd_inverse_frequency_of_time(t, tpeak, tref, f_estimate, theta, t_acc, max_iter=8):
246
+ """Fast inversion of t(f) using Newton–Raphson with fallback bracketing.
247
+ Args:
248
+ t (float): total time of observation in [s].
249
+ tpeak (float): time before merger in [s].
250
+ tref (float): time at beginning of observations in [s].
251
+ f_estimate (float): initial guess for Newton-Raphson solver.
252
+ theta (SOBHBParams): parameters of the source.
253
+ t_acc (float): desired precision.
254
+ max_iter (int, optional): maximum number of iterations in Newton-Raphson solver.
255
+
256
+ Returns:
257
+ f_sol (float): frequency in Hz such that t(f_sol) = t+tpeak+tref.
258
+ """
259
+
260
+ # target time
261
+ t_target = tpeak + t + tref
262
+
263
+ def t_of_f(f):
264
+ return imrphenomd_time_of_frequency(f, tref, theta)
265
+
266
+ # Newton iterations (vectorized)
267
+ def body(state):
268
+ i, f = state
269
+ t_curr = t_of_f(f)
270
+ dt_df = jax.grad(t_of_f)(f)
271
+ f_new = f - (t_curr - t_target) / dt_df
272
+ # keep frequencies positive
273
+ f_new = jnp.clip(f_new, 1e-6, 1e5)
274
+ return (i + 1, f_new)
275
+
276
+ def cond(state):
277
+ i, f = state
278
+ return jnp.logical_and(i < max_iter, jnp.abs(t_of_f(f) - t_target) > t_acc)
279
+
280
+ i0 = jnp.array(0)
281
+ f0 = jnp.asarray(f_estimate)
282
+ _, f_sol = jax.lax.while_loop(cond, body, (i0, f0))
283
+
284
+ return f_sol
285
+
286
+
287
+ def compute_tc(f4, f_RD, f_damp, Mtot_s, theta_intrinsic, imrphenomd_coeffs):
288
+ """Computes time of merger from IMRPhenomD phase.
289
+
290
+ Args:
291
+ f4 (_type_): _description_
292
+ f_RD (_type_): _description_
293
+ f_damp (_type_): _description_
294
+ Mtot_s (_type_): _description_
295
+ theta_intrinsic (_type_): _description_
296
+ imrphenomd_coeffs (_type_): _description_
297
+
298
+ Returns:
299
+ _type_: _description_
300
+ """
301
+ return grad_IIb_phase(f4 * Mtot_s, theta_intrinsic, imrphenomd_coeffs, f_RD, f_damp)
302
+
303
+
304
+ def compute_tref(f_ref, Mtot_s, theta_intrinsic, imrphenomd_coeffs):
305
+ """Computes time at f_ref from IMRPhenomD phase.
306
+
307
+ Args:
308
+ f_ref (_type_): _description_
309
+ Mtot_s (_type_): _description_
310
+ theta_intrinsic (_type_): _description_
311
+ imrphenomd_coeffs (_type_): _description_
312
+
313
+ Returns:
314
+ _type_: _description_
315
+ """
316
+ return grad_inspiral_phase(f_ref * Mtot_s, theta_intrinsic, imrphenomd_coeffs)
317
+
318
+
319
+ # @jax.vmap
320
+ @jax.jit
321
+ def set_freq_grid_and_tc(
322
+ theta,
323
+ f_t_acc=1e-4,
324
+ length=1000,
325
+ dt=5,
326
+ ):
327
+ """Creates the frequency grids for the given parameters.
328
+
329
+ Args:
330
+ theta (jax.Array): The order of the parameters is:
331
+ m1 (Msol), m2 (Msol), chi1, chi2, dist (Mpc),
332
+ fstart (Hz), phi0, iota, psi, alpha, delta, t_obs (s).
333
+
334
+ f_t_acc (_type_, optional): _description_. Defaults to 1e-4.
335
+ length (int, optional): length of frequency grid to be returned. Defaults to 100.
336
+
337
+ Returns:
338
+ _type_: _description_
339
+ """
340
+ theta_intrinsic = jnp.array([theta.m1, theta.m2, theta.chi1, theta.chi2])
341
+
342
+ coeffs = IMRPhenomD.get_coeffs(theta_intrinsic)
343
+
344
+ M_s = (theta.m1 + theta.m2) * Msun_s
345
+
346
+ f_ref = theta.fstart
347
+ f_l = f_ref
348
+ tobs = theta.t_obs
349
+
350
+ # Shift phase so that peak amplitude matches t = 0
351
+ transition_freqs = IMRPhenomD.get_transition_frequencies(theta_intrinsic, coeffs[5], coeffs[6])
352
+ _, _, _, f4, f_RD, f_damp = transition_freqs
353
+ tc = compute_tc(f4, f_RD, f_damp, M_s, theta_intrinsic, coeffs)
354
+ t0 = compute_tref(f_ref, M_s, theta_intrinsic, coeffs)
355
+
356
+ time_before_merger_s = (tc - t0) * M_s / (2.0 * jnp.pi) # Time until merger in seconds
357
+ time_after_obs_s = (time_before_merger_s - tobs) / M_s
358
+ tref = t0 * M_s / (2 * jnp.pi)
359
+
360
+ # Handle post-merger observation case
361
+ def merger_already_happened_case(_):
362
+ """Return default safe outputs if tobs > merger time."""
363
+ f_max = 0.5 / dt
364
+ fs = jnp.linspace(f_l, f_max, num=length)
365
+ return fs, time_before_merger_s
366
+
367
+ def normal_case(_):
368
+ """Normal inspiral case (t_before_merger_s positive)."""
369
+ timer_after_obs_s = (time_before_merger_s - tobs) / M_s
370
+ f_u_guess = funcNewtonianfoftGeom(theta.q, timer_after_obs_s) / M_s
371
+ f_u = imrphenomd_inverse_frequency_of_time(
372
+ tobs, time_before_merger_s, tref, f_u_guess, theta, f_t_acc
373
+ )
374
+ fs = jnp.linspace(f_l, f_u, num=length)
375
+ return fs, time_before_merger_s
376
+
377
+ # Conditional execution using JAX primitives
378
+ fs, time_before_merger_s = jax.lax.cond(
379
+ time_after_obs_s <= 0.0,
380
+ merger_already_happened_case,
381
+ normal_case,
382
+ operand=None,
383
+ )
384
+
385
+ return fs, time_before_merger_s
386
+
387
+
388
+ def compute_f_init(theta, t_shift):
389
+ """Computes f(tc-t0-t_shift) i.e. the frequency at the start of the observations
390
+ allowing for a shift of t_shift on the time of coalescence.
391
+
392
+ Args:
393
+ theta (SOBHBParams): parameters of source.
394
+ t_shift (float): Shift of time of coalescence.
395
+
396
+ Returns:
397
+ _type_: _description_
398
+ """
399
+ theta_intrinsic = jnp.asarray([theta.m1, theta.m2, theta.chi1, theta.chi2])
400
+ imrphenomd_coeffs = IMRPhenomD.get_coeffs(theta_intrinsic)
401
+ Mtot_s = (theta.m1 + theta.m2) * Msun_s
402
+ transition_freqs = IMRPhenomD.get_transition_frequencies(
403
+ theta_intrinsic, imrphenomd_coeffs[5], imrphenomd_coeffs[6]
404
+ )
405
+ _, _, _, f4, f_RD, f_damp = transition_freqs
406
+ tc = compute_tc(f4, f_RD, f_damp, Mtot_s, theta_intrinsic, imrphenomd_coeffs)
407
+ t0 = compute_tref(theta.fstart, Mtot_s, theta_intrinsic, imrphenomd_coeffs)
408
+
409
+ time_before_merger_s = (tc - t0) * Mtot_s / (2.0 * jnp.pi) # Time until merger in seconds
410
+ tref = t0 * Mtot_s / (2 * jnp.pi)
411
+ timer_after_obs_s = (time_before_merger_s - t_shift) / Mtot_s
412
+ f_u_guess = funcNewtonianfoftGeom(theta.q, timer_after_obs_s) / Mtot_s
413
+ f_u = imrphenomd_inverse_frequency_of_time(
414
+ t_shift, time_before_merger_s, tref, f_u_guess, theta, 1e-4
415
+ )
416
+ return f_u
417
+
418
+
419
+ # @jax.vmap
420
+ @jax.jit
421
+ def waveform_gen(theta, fs, tc):
422
+ """Actual waveform generator. Generates h22 in source frame.
423
+
424
+ Args:
425
+ theta (SOBHBParams): The order of the parameters is:
426
+ Mchirp (Msol), eta (symmetric mass ratio), chi1, chi2, dist (Mpc),
427
+ fstart (Hz), phi0, iota, psi, alpha, delta, t_obs (s).
428
+
429
+ fs (jax.Array): Frequency grid on which to generate the waveform.
430
+
431
+ Returns:
432
+ _type_: _description_
433
+ """
434
+ theta_intrinsic = jnp.array([theta.m1, theta.m2, theta.chi1, theta.chi2])
435
+
436
+ coeffs = IMRPhenomD.get_coeffs(theta_intrinsic)
437
+
438
+ # Transition frequencies are needed.
439
+ transition_freqs = IMRPhenomD.get_transition_frequencies(theta_intrinsic, coeffs[5], coeffs[6])
440
+
441
+ # Lets call the amplitude and phase now
442
+ Psi = IMRPhenomD.Phase(fs, theta_intrinsic, coeffs, transition_freqs)
443
+ ext_phase_contrib = 2.0 * jnp.pi * fs * tc
444
+ Psi += ext_phase_contrib
445
+ Psi -= Psi[0]
446
+
447
+ A = IMRPhenomD.Amp(fs, theta_intrinsic, coeffs, transition_freqs, D=theta.dist) / (
448
+ 0.5 * jnp.sqrt(5 / (4 * jnp.pi))
449
+ )
450
+
451
+ return A, Psi
452
+
453
+
454
+ ### Spin-weighted spherical harmonics
455
+
456
+
457
+ def sYlm22(theta, phi):
458
+ """Computes spin-weighted spherical harmonic with s=-2, l=m=2."""
459
+ return jnp.sqrt(5.0 / (64.0 * jnp.pi)) * (1.0 + jnp.cos(theta)) ** 2 * jnp.exp(2j * phi)
460
+
461
+
462
+ def sYlm2m2(theta, phi):
463
+ """Computes spin-weighted spherical harmonic with s=-2, l=2, m=-2."""
464
+ return jnp.sqrt(5.0 / (64.0 * jnp.pi)) * (1.0 - jnp.cos(theta)) ** 2 * jnp.exp(-2j * phi)
465
+
466
+
467
+ def Kplus22(theta, phi):
468
+ """Computes K_+^22"""
469
+ return 1.0 / 2 * (sYlm22(theta, phi) + jnp.conj(sYlm2m2(theta, phi)))
470
+
471
+
472
+ def Kcross22(theta, phi):
473
+ """Computes K_x^22"""
474
+ return 1j / 2 * (sYlm22(theta, phi) - jnp.conj(sYlm2m2(theta, phi)))
tfwaves/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ """
2
+ Source code.
3
+ Authors:
4
+ Quentin Baghi <quentin.baghi@protonmail.com>
5
+ Saptarshi Ghosh <saptarshi.ghosh@apc.in2p3.fr>
6
+ Gael Servignat <servignat@apc.in2p3.fr>
7
+ """
8
+
9
+ from .stft import STFTWaveform