fastlisaresponse 1.1.4__cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.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.

Potentially problematic release.


This version of fastlisaresponse might be problematic. Click here for more details.

@@ -0,0 +1,796 @@
1
+ from multiprocessing.sharedctypes import Value
2
+ import numpy as np
3
+ from typing import Optional, List
4
+ import warnings
5
+ from typing import Tuple
6
+ from copy import deepcopy
7
+
8
+ import time
9
+ import h5py
10
+
11
+ from scipy.interpolate import CubicSpline
12
+
13
+ from lisatools.detector import EqualArmlengthOrbits, Orbits
14
+ from lisatools.utils.utility import AET
15
+
16
+ from .utils.parallelbase import FastLISAResponseParallelModule
17
+
18
+
19
+ # TODO: need to update constants setup
20
+ YRSID_SI = 31558149.763545603
21
+
22
+
23
+ def get_factorial(n):
24
+ fact = 1
25
+
26
+ for i in range(1, n + 1):
27
+ fact = fact * i
28
+
29
+ return fact
30
+
31
+
32
+ from math import factorial
33
+
34
+ factorials = np.array([factorial(i) for i in range(30)])
35
+
36
+ C_inv = 3.3356409519815204e-09
37
+
38
+
39
+ class pyResponseTDI(FastLISAResponseParallelModule):
40
+ """Class container for fast LISA response function generation.
41
+
42
+ The class computes the generic time-domain response function for LISA.
43
+ It takes LISA constellation orbital information as input and properly determines
44
+ the response for these orbits numerically. This includes both the projection
45
+ of the gravitational waves onto the LISA constellation arms and combinations \
46
+ of projections into TDI observables. The methods and maths used can be found
47
+ [here](https://arxiv.org/abs/2204.06633).
48
+
49
+ This class is also GPU-accelerated, which is very helpful for Bayesian inference
50
+ methods.
51
+
52
+ Args:
53
+ sampling_frequency (double): The sampling rate in Hz.
54
+ num_pts (int): Number of points to produce for the final output template.
55
+ order (int, optional): Order of Lagrangian interpolation technique. Lower orders
56
+ will be faster. The user must make sure the order is sufficient for the
57
+ waveform being used. (default: 25)
58
+ tdi (str or list, optional): TDI setup. Currently, the stock options are
59
+ :code:`'1st generation'` and :code:`'2nd generation'`. Or the user can provide
60
+ a list of tdi_combinations of the form
61
+ :code:`{"link": 12, "links_for_delay": [21, 13, 31], "sign": 1, "type": "delay"}`.
62
+ :code:`'link'` (`int`) the link index (12, 21, 13, 31, 23, 32) for the projection (:math:`y_{ij}`).
63
+ :code:`'links_for_delay'` (`list`) are the link indexes as a list used for delays
64
+ applied to the link projections.
65
+ ``'sign'`` is the sign in front of the contribution to the TDI observable. It takes the value of `+1` or `-1`.
66
+ ``type`` is either ``"delay"`` or ``"advance"``. It is optional and defaults to ``"delay"``.
67
+ (default: ``"1st generation"``)
68
+ orbits (:class:`Orbits`, optional): Orbits class from LISA Analysis Tools. Works with LISA Orbits
69
+ outputs: `lisa-simulation.pages.in2p3.fr/orbits/ <https://lisa-simulation.pages.in2p3.fr/orbits/latest/>`_.
70
+ (default: :class:`EqualArmlengthOrbits`)
71
+ tdi_chan (str, optional): Which TDI channel combination to return. Choices are :code:`'XYZ'`,
72
+ :code:`AET`, or :code:`AE`. (default: :code:`'XYZ'`)
73
+ tdi_orbits (:class:`Orbits`, optional): Set if different orbits from projection.
74
+ Orbits class from LISA Analysis Tools. Works with LISA Orbits
75
+ outputs: `lisa-simulation.pages.in2p3.fr/orbits/ <https://lisa-simulation.pages.in2p3.fr/orbits/latest/>`_.
76
+ (default: :class:`EqualArmlengthOrbits`)
77
+ force_backend (str, optional): If given, run this class on the requested backend.
78
+ Options are ``"cpu"``, ``"cuda11x"``, ``"cuda12x"``. (default: ``None``)
79
+
80
+ Attributes:
81
+ A_in (xp.ndarray): Array containing y values for linear spline of A
82
+ during Lagrangian interpolation.
83
+ buffer_integer (int): Self-determined buffer necesary for the given
84
+ value for :code:`order`.
85
+ channels_no_delays (2D np.ndarray): Carrier of link index and sign information
86
+ for arms that do not get delayed during TDI computation.
87
+ deps (double): The spacing between Epsilon values in the interpolant
88
+ for the A quantity in Lagrangian interpolation. Hard coded to
89
+ 1/(:code:`num_A` - 1).
90
+ dt (double): Inverse of the sampling_frequency.
91
+ E_in (xp.ndarray): Array containing y values for linear spline of E
92
+ during Lagrangian interpolation.
93
+ half_order (int): Half of :code:`order` adjusted to be :code:`int`.
94
+ link_inds (xp.ndarray): Link indexes for delays in TDI.
95
+ link_space_craft_0_in (xp.ndarray): Link indexes for receiver on each
96
+ arm of the LISA constellation.
97
+ link_space_craft_1_in (xp.ndarray): Link indexes for emitter on each
98
+ arm of the LISA constellation.
99
+ nlinks (int): The number of links in the constellation. Typically 6.
100
+ num_A (int): Number of points to use for A spline values used in the Lagrangian
101
+ interpolation. This is hard coded to 1001.
102
+ num_channels (int): 3.
103
+ num_pts (int): Number of points to produce for the final output template.
104
+ order (int): Order of Lagrangian interpolation technique.
105
+ sampling_frequency (double): The sampling rate in Hz.
106
+ tdi (str or list): TDI setup.
107
+ tdi_buffer (int): The buffer necessary for all information needed at early times
108
+ for the TDI computation. This is set to 200.
109
+ xp (obj): Either Numpy or Cupy.
110
+
111
+ """
112
+
113
+ def __init__(
114
+ self,
115
+ sampling_frequency,
116
+ num_pts,
117
+ order=25,
118
+ tdi="1st generation",
119
+ orbits: Optional[Orbits] = EqualArmlengthOrbits,
120
+ tdi_orbits: Optional[Orbits] = None,
121
+ tdi_chan="XYZ",
122
+ force_backend=None,
123
+ ):
124
+
125
+ # setup all quantities
126
+ self.sampling_frequency = sampling_frequency
127
+ self.dt = 1 / sampling_frequency
128
+ self.tdi_buffer = 200
129
+
130
+ self.num_pts = num_pts
131
+
132
+ # Lagrangian interpolation setup
133
+ self.order = order
134
+ self.buffer_integer = self.order * 2 + 1
135
+ self.half_order = int((order + 1) / 2)
136
+
137
+ # setup TDI information
138
+ self.tdi = tdi
139
+ self.tdi_chan = tdi_chan
140
+
141
+ super().__init__(force_backend=force_backend)
142
+
143
+ # prepare the interpolation of A and E in the Lagrangian interpolation
144
+ self._fill_A_E()
145
+
146
+ # setup orbits
147
+ self.response_orbits = orbits
148
+
149
+ if tdi_orbits is None:
150
+ tdi_orbits = self.response_orbits
151
+
152
+ self.tdi_orbits = tdi_orbits
153
+
154
+ if self.num_pts * self.dt > self.response_orbits.t_base.max():
155
+ warnings.warn(
156
+ "Input number of points is longer in time than available orbital information. Trimming to fit orbital information."
157
+ )
158
+ self.num_pts = int(self.response_orbits.t_base.max() / self.dt)
159
+
160
+ # setup spacecraft links indexes
161
+
162
+ # setup TDI info
163
+ self._init_TDI_delays()
164
+
165
+ @property
166
+ def response_gen(self) -> callable:
167
+ """CPU/GPU function for generating the projections."""
168
+ return self.backend.get_response_wrap
169
+
170
+ @property
171
+ def tdi_gen(self) -> callable:
172
+ """CPU/GPU function for generating tdi."""
173
+ return self.backend.get_tdi_delays_wrap
174
+
175
+ @property
176
+ def xp(self) -> object:
177
+ return self.backend.xp
178
+
179
+ @property
180
+ def response_orbits(self) -> Orbits:
181
+ """Response function orbits."""
182
+ return self._response_orbits
183
+
184
+ @response_orbits.setter
185
+ def response_orbits(self, orbits: Orbits) -> None:
186
+ """Set response orbits."""
187
+
188
+ if orbits is None:
189
+ orbits = EqualArmlengthOrbits()
190
+
191
+ assert isinstance(orbits, Orbits)
192
+
193
+ self._response_orbits = deepcopy(orbits)
194
+
195
+ if not self._response_orbits.configured:
196
+ self._response_orbits.configure(linear_interp_setup=True)
197
+
198
+ @property
199
+ def tdi_orbits(self) -> Orbits:
200
+ """TDI function orbits."""
201
+ return self._tdi_orbits
202
+
203
+ @tdi_orbits.setter
204
+ def tdi_orbits(self, orbits: Orbits) -> None:
205
+ """Set TDI orbits."""
206
+
207
+ if orbits is None:
208
+ orbits = EqualArmlengthOrbits()
209
+
210
+ assert isinstance(orbits, Orbits)
211
+ assert orbits.use_gpu == self.backend.uses_gpu
212
+
213
+ self._tdi_orbits = deepcopy(orbits)
214
+
215
+ if not self._tdi_orbits.configured:
216
+ self._tdi_orbits.configure(linear_interp_setup=True)
217
+
218
+ @property
219
+ def citation(self):
220
+ """Get citations for use of this code"""
221
+
222
+ return """
223
+ # TODO add
224
+ """
225
+
226
+ def _fill_A_E(self):
227
+ """Set up A and E terms inside the Lagrangian interpolant"""
228
+
229
+ factorials = np.asarray([float(get_factorial(n)) for n in range(40)])
230
+
231
+ # base quantities for linear interpolant over A
232
+ self.num_A = 1001
233
+ self.deps = 1.0 / (self.num_A - 1)
234
+
235
+ eps = np.arange(self.num_A) * self.deps
236
+
237
+ h = self.half_order
238
+
239
+ denominator = factorials[h - 1] * factorials[h]
240
+
241
+ # prepare A
242
+ A_in = np.zeros_like(eps)
243
+ for j, eps_i in enumerate(eps):
244
+ A = 1.0
245
+ for i in range(1, h):
246
+ A *= (i + eps_i) * (i + 1 - eps_i)
247
+
248
+ A /= denominator
249
+ A_in[j] = A
250
+
251
+ self.A_in = self.xp.asarray(A_in)
252
+
253
+ # prepare E
254
+ E_in = self.xp.zeros((self.half_order,))
255
+
256
+ for j in range(1, self.half_order):
257
+ first_term = factorials[h - 1] / factorials[h - 1 - j]
258
+ second_term = factorials[h] / factorials[h + j]
259
+ value = first_term * second_term
260
+ value = value * (-1.0) ** j
261
+ E_in[j - 1] = value
262
+
263
+ self.E_in = self.xp.asarray(E_in)
264
+
265
+ def _init_TDI_delays(self):
266
+ """Initialize TDI specific information"""
267
+
268
+ # setup the actual TDI combination
269
+ if self.tdi in ["1st generation", "2nd generation"]:
270
+ # tdi 1.0
271
+ tdi_combinations = [
272
+ {"link": 13, "links_for_delay": [], "sign": +1},
273
+ {"link": 31, "links_for_delay": [13], "sign": +1},
274
+ {"link": 12, "links_for_delay": [13, 31], "sign": +1},
275
+ {"link": 21, "links_for_delay": [13, 31, 12], "sign": +1},
276
+ {"link": 12, "links_for_delay": [], "sign": -1},
277
+ {"link": 21, "links_for_delay": [12], "sign": -1},
278
+ {"link": 13, "links_for_delay": [12, 21], "sign": -1},
279
+ {"link": 31, "links_for_delay": [12, 21, 13], "sign": -1},
280
+ ]
281
+
282
+ if self.tdi == "2nd generation":
283
+ # tdi 2.0 is tdi 1.0 + additional terms
284
+ tdi_combinations += [
285
+ {"link": 12, "links_for_delay": [13, 31, 12, 21], "sign": +1},
286
+ {"link": 21, "links_for_delay": [13, 31, 12, 21, 12], "sign": +1},
287
+ {
288
+ "link": 13,
289
+ "links_for_delay": [13, 31, 12, 21, 12, 21],
290
+ "sign": +1,
291
+ },
292
+ {
293
+ "link": 31,
294
+ "links_for_delay": [13, 31, 12, 21, 12, 21, 13],
295
+ "sign": +1,
296
+ },
297
+ {"link": 13, "links_for_delay": [12, 21, 13, 31], "sign": -1},
298
+ {"link": 31, "links_for_delay": [12, 21, 13, 31, 13], "sign": -1},
299
+ {
300
+ "link": 12,
301
+ "links_for_delay": [12, 21, 13, 31, 13, 31],
302
+ "sign": -1,
303
+ },
304
+ {
305
+ "link": 21,
306
+ "links_for_delay": [12, 21, 13, 31, 13, 31, 12],
307
+ "sign": -1,
308
+ },
309
+ ]
310
+
311
+ elif isinstance(self.tdi, list):
312
+ tdi_combinations = self.tdi
313
+
314
+ else:
315
+ raise ValueError(
316
+ "tdi kwarg should be '1st generation', '2nd generation', or a list with a specific tdi combination."
317
+ )
318
+ self.tdi_combinations = tdi_combinations
319
+
320
+ @property
321
+ def tdi_combinations(self) -> List:
322
+ """TDI Combination setup"""
323
+ return self._tdi_combinations
324
+
325
+ @tdi_combinations.setter
326
+ def tdi_combinations(self, tdi_combinations: List) -> None:
327
+ """Set TDI combinations and fill out setup."""
328
+ tdi_base_links = []
329
+ tdi_link_combinations = []
330
+ tdi_signs = []
331
+ tdi_operation_index = []
332
+ channels = []
333
+
334
+ tdi_index = 0
335
+ for permutation_number in range(3):
336
+ for tmp in tdi_combinations:
337
+ tdi_base_links.append(
338
+ self._cyclic_permutation(tmp["link"], permutation_number)
339
+ )
340
+ tdi_signs.append(tmp["sign"])
341
+ channels.append(permutation_number)
342
+ if len(tmp["links_for_delay"]) == 0:
343
+ tdi_link_combinations.append(-11)
344
+ tdi_operation_index.append(tdi_index)
345
+
346
+ else:
347
+ for link_delay in tmp["links_for_delay"]:
348
+
349
+ tdi_link_combinations.append(
350
+ self._cyclic_permutation(link_delay, permutation_number)
351
+ )
352
+ tdi_operation_index.append(tdi_index)
353
+
354
+ tdi_index += 1
355
+
356
+ self.tdi_operation_index = self.xp.asarray(tdi_operation_index).astype(
357
+ self.xp.int32
358
+ )
359
+ self.tdi_base_links = self.xp.asarray(tdi_base_links).astype(self.xp.int32)
360
+ self.tdi_link_combinations = self.xp.asarray(tdi_link_combinations).astype(
361
+ self.xp.int32
362
+ )
363
+ self.tdi_signs = self.xp.asarray(tdi_signs).astype(self.xp.int32)
364
+ self.channels = self.xp.asarray(channels).astype(self.xp.int32)
365
+ assert len(self.tdi_link_combinations) == len(self.tdi_operation_index)
366
+
367
+ assert (
368
+ len(self.tdi_base_links)
369
+ == len(np.unique(self.tdi_operation_index))
370
+ == len(self.tdi_signs)
371
+ == len(self.channels)
372
+ )
373
+
374
+ def _cyclic_permutation(self, link, permutation):
375
+ """permute indexes by cyclic permutation"""
376
+ link_str = str(link)
377
+
378
+ out = ""
379
+ for i in range(2):
380
+ sc = int(link_str[i])
381
+ temp = sc + permutation
382
+ if temp > 3:
383
+ temp = temp % 3
384
+ out += str(temp)
385
+
386
+ return int(out)
387
+
388
+ @property
389
+ def y_gw(self):
390
+ """Projections along the arms"""
391
+ return self.y_gw_flat.reshape(self.nlinks, -1)
392
+
393
+ def _data_time_check(
394
+ self, t_data: np.ndarray, input_in: np.ndarray
395
+ ) -> Tuple[np.ndarray, np.ndarray]:
396
+ # remove input data that goes beyond orbital information
397
+ if t_data.max() > self.response_orbits.t.max():
398
+ warnings.warn(
399
+ "Input waveform is longer than available orbital information. Trimming to fit orbital information."
400
+ )
401
+
402
+ max_ind = np.where(t_data <= self.response_orbits.t.max())[0][-1]
403
+
404
+ t_data = t_data[:max_ind]
405
+ input_in = input_in[:max_ind]
406
+ return (t_data, input_in)
407
+
408
+ def get_projections(self, input_in, lam, beta, t0=10000.0):
409
+ """Compute projections of GW signal on to LISA constellation
410
+
411
+ Args:
412
+ input_in (xp.ndarray): Input complex time-domain signal. It should be of the form:
413
+ :math:`h_+ + ih_x`. If using the GPU for the response, this should be a CuPy array.
414
+ lam (double): Ecliptic Longitude in radians.
415
+ beta (double): Ecliptic Latitude in radians.
416
+ t0 (double, optional): Time at which to the waveform. Because of the delays
417
+ and interpolation towards earlier times, the beginning of the waveform
418
+ is garbage. ``t0`` tells the waveform generator where to start the waveform
419
+ compraed to ``t=0``.
420
+
421
+ Raises:
422
+ ValueError: If ``t0`` is not large enough.
423
+
424
+
425
+ """
426
+ self.tdi_start_ind = int(t0 / self.dt)
427
+ # get necessary buffer for TDI
428
+ self.check_tdi_buffer = int(100.0 * self.sampling_frequency) + 4 * self.order
429
+
430
+ from copy import deepcopy
431
+
432
+ tmp_orbits = deepcopy(self.response_orbits.x_base)
433
+ self.projection_buffer = (
434
+ int(
435
+ (
436
+ np.sum(
437
+ tmp_orbits.copy() * tmp_orbits.copy(),
438
+ axis=-1,
439
+ )
440
+ ** (1 / 2)
441
+ ).max()
442
+ * C_inv
443
+ )
444
+ + 4 * self.order
445
+ )
446
+ self.projections_start_ind = self.tdi_start_ind - 2 * self.check_tdi_buffer
447
+
448
+ if self.projections_start_ind < self.projection_buffer:
449
+ raise ValueError(
450
+ "Need to increase t0. The initial buffer is not large enough."
451
+ )
452
+
453
+ # determine sky vectors
454
+ k = np.zeros(3, dtype=np.float64)
455
+ u = np.zeros(3, dtype=np.float64)
456
+ v = np.zeros(3, dtype=np.float64)
457
+
458
+ self.num_total_points = len(input_in)
459
+
460
+ cosbeta = np.cos(beta)
461
+ sinbeta = np.sin(beta)
462
+
463
+ coslam = np.cos(lam)
464
+ sinlam = np.sin(lam)
465
+
466
+ v[0] = -sinbeta * coslam
467
+ v[1] = -sinbeta * sinlam
468
+ v[2] = cosbeta
469
+ u[0] = sinlam
470
+ u[1] = -coslam
471
+ u[2] = 0.0
472
+ k[0] = -cosbeta * coslam
473
+ k[1] = -cosbeta * sinlam
474
+ k[2] = -sinbeta
475
+
476
+ self.nlinks = 6
477
+ k_in = self.xp.asarray(k)
478
+ u_in = self.xp.asarray(u)
479
+ v_in = self.xp.asarray(v)
480
+
481
+ input_in = self.xp.asarray(input_in)
482
+
483
+ t_data = self.xp.arange(len(input_in)) * self.dt
484
+
485
+ t_data, input_in = self._data_time_check(t_data, input_in)
486
+
487
+ assert len(input_in) >= self.num_pts
488
+ y_gw = self.xp.zeros((self.nlinks * self.num_pts,), dtype=self.xp.float64)
489
+
490
+ self.response_gen(
491
+ y_gw,
492
+ t_data,
493
+ k_in,
494
+ u_in,
495
+ v_in,
496
+ self.dt,
497
+ len(input_in),
498
+ input_in,
499
+ len(input_in),
500
+ self.order,
501
+ self.sampling_frequency,
502
+ self.buffer_integer,
503
+ self.A_in,
504
+ self.deps,
505
+ len(self.A_in),
506
+ self.E_in,
507
+ self.projections_start_ind,
508
+ self.response_orbits,
509
+ )
510
+
511
+ self.y_gw_flat = y_gw
512
+ self.y_gw_length = self.num_pts
513
+
514
+ @property
515
+ def XYZ(self):
516
+ """Return links as an array"""
517
+ return self.delayed_links_flat.reshape(3, -1)
518
+
519
+ def get_tdi_delays(self, y_gw=None):
520
+ """Get TDI combinations from projections.
521
+
522
+ This functions generates the TDI combinations from the projections
523
+ computed with ``get_projections``. It can return XYZ, AET, or AE depending
524
+ on what was input for ``tdi_chan`` into ``__init__``.
525
+
526
+ Args:
527
+ y_gw (xp.ndarray, optional): Projections along each link. Must be
528
+ a 2D ``numpy`` or ``cupy`` array with shape: ``(nlinks, num_pts)``.
529
+ The links must be entered in the proper order in the code:
530
+ 21, 12, 31, 13, 32, 23. (Default: None)
531
+
532
+ Returns:
533
+ tuple: (X,Y,Z) or (A,E,T) or (A,E)
534
+
535
+ Raises:
536
+ ValueError: If ``tdi_chan`` is not one of the options.
537
+
538
+
539
+ """
540
+ self.delayed_links_flat = self.xp.zeros(
541
+ (3, self.num_pts), dtype=self.xp.float64
542
+ )
543
+
544
+ # y_gw entered directly
545
+ if y_gw is not None:
546
+ assert y_gw.shape == (len(self.link_space_craft_0_in), self.num_pts)
547
+ self.y_gw_flat = y_gw.flatten().copy()
548
+ self.y_gw_length = self.num_pts
549
+
550
+ elif self.y_gw_flat is None:
551
+ raise ValueError(
552
+ "Need to either enter projection array or have this code determine projections."
553
+ )
554
+
555
+ self.delayed_links_flat = self.delayed_links_flat.flatten()
556
+
557
+ t_data = self.xp.arange(self.y_gw_length) * self.dt
558
+
559
+ num_units = int(self.tdi_operation_index.max() + 1)
560
+
561
+ assert np.all(
562
+ (np.diff(self.tdi_operation_index) == 0)
563
+ | (np.diff(self.tdi_operation_index) == 1)
564
+ )
565
+
566
+ _, unit_starts, unit_lengths = np.unique(
567
+ self.tdi_operation_index,
568
+ return_index=True,
569
+ return_counts=True,
570
+ )
571
+
572
+ unit_starts = unit_starts.astype(np.int32)
573
+ unit_lengths = unit_lengths.astype(np.int32)
574
+
575
+ self.tdi_gen(
576
+ self.delayed_links_flat,
577
+ self.y_gw_flat,
578
+ self.y_gw_length,
579
+ self.num_pts,
580
+ t_data,
581
+ unit_starts,
582
+ unit_lengths,
583
+ self.tdi_base_links,
584
+ self.tdi_link_combinations,
585
+ self.tdi_signs,
586
+ self.channels,
587
+ num_units,
588
+ 3, # num channels
589
+ self.order,
590
+ self.sampling_frequency,
591
+ self.buffer_integer,
592
+ self.A_in,
593
+ self.deps,
594
+ len(self.A_in),
595
+ self.E_in,
596
+ self.tdi_start_ind,
597
+ self.tdi_orbits,
598
+ )
599
+
600
+ if self.tdi_chan == "XYZ":
601
+ X, Y, Z = self.XYZ
602
+ return X, Y, Z
603
+
604
+ elif self.tdi_chan == "AET" or self.tdi_chan == "AE":
605
+ X, Y, Z = self.XYZ
606
+ A, E, T = AET(X, Y, Z)
607
+ if self.tdi_chan == "AET":
608
+ return A, E, T
609
+
610
+ else:
611
+ return A, E
612
+
613
+ else:
614
+ raise ValueError("tdi_chan must be 'XYZ', 'AET' or 'AE'.")
615
+
616
+
617
+ class ResponseWrapper(FastLISAResponseParallelModule):
618
+ """Wrapper to produce LISA TDI from TD waveforms
619
+
620
+ This class takes a waveform generator that produces :math:`h_+ \pm ih_x`.
621
+ (:code:`flip_hx` is used if the waveform produces :math:`h_+ - ih_x`).
622
+ It takes the complex waveform in the SSB frame and produces the TDI channels
623
+ according to settings chosen for :class:`pyResponseTDI`.
624
+
625
+ The waveform generator must have :code:`kwargs` with :code:`T` for the observation
626
+ time in years and :code:`dt` for the time step in seconds.
627
+
628
+ Args:
629
+ waveform_gen (obj): Function or class (with a :code:`__call__` function) that takes parameters and produces
630
+ :math:`h_+ \pm h_x`.
631
+ Tobs (double): Observation time in years.
632
+ dt (double): Time between time samples in seconds. The inverse of the sampling frequency.
633
+ index_lambda (int): The user will input parameters. The code will read these in
634
+ with the :code:`*args` formalism producing a list. :code:`index_lambda`
635
+ tells the class the index of the ecliptic longitude within this list of
636
+ parameters.
637
+ index_beta (int): The user will input parameters. The code will read these in
638
+ with the :code:`*args` formalism producing a list. :code:`index_beta`
639
+ tells the class the index of the ecliptic latitude (or ecliptic polar angle)
640
+ within this list of parameters.
641
+ t0 (double, optional): Start of returned waveform in seconds leaving ample time for garbage at
642
+ the beginning of the waveform. It also removed the same amount from the end. (Default: 10000.0)
643
+ flip_hx (bool, optional): If True, :code:`waveform_gen` produces :math:`h_+ - ih_x`.
644
+ :class:`pyResponseTDI` takes :math:`h_+ + ih_x`, so this setting will
645
+ multiply the cross polarization term out of the waveform generator by -1.
646
+ (Default: :code:`False`)
647
+ remove_sky_coords (bool, optional): If True, remove the sky coordinates from
648
+ the :code:`*args` list. This should be set to True if the waveform
649
+ generator does not take in the sky information. (Default: :code:`False`)
650
+ is_ecliptic_latitude (bool, optional): If True, the latitudinal sky
651
+ coordinate is the ecliptic latitude. If False, thes latitudinal sky
652
+ coordinate is the polar angle. In this case, the code will
653
+ convert it with :math:`\beta=\pi / 2 - \Theta`. (Default: :code:`True`)
654
+ force_backend (str, optional): If given, run this class on the requested backend.
655
+ Options are ``"cpu"``, ``"cuda11x"``, ``"cuda12x"``. (default: ``None``)
656
+ remove_garbage (bool or str, optional): If True, it removes everything before ``t0``
657
+ and after the end time - ``t0``. If ``str``, it must be ``"zero"``. If ``"zero"``,
658
+ it will not remove the points, but set them to zero. This is ideal for PE. (Default: ``True``)
659
+ n_overide (int, optional): If not ``None``, this will override the determination of
660
+ the number of points, ``n``, from ``int(T/dt)`` to the ``n_overide``. This is used
661
+ if there is an issue matching points between the waveform generator and the response
662
+ model.
663
+ orbits (:class:`Orbits`, optional): Orbits class from LISA Analysis Tools. Works with LISA Orbits
664
+ outputs: `lisa-simulation.pages.in2p3.fr/orbits/ <https://lisa-simulation.pages.in2p3.fr/orbits/latest/>`_.
665
+ (default: :class:`EqualArmlengthOrbits`)
666
+ **kwargs (dict, optional): Keyword arguments passed to :class:`pyResponseTDI`.
667
+
668
+ """
669
+
670
+ def __init__(
671
+ self,
672
+ waveform_gen,
673
+ Tobs,
674
+ dt,
675
+ index_lambda,
676
+ index_beta,
677
+ t0=10000.0,
678
+ flip_hx=False,
679
+ remove_sky_coords=False,
680
+ is_ecliptic_latitude=True,
681
+ force_backend=None,
682
+ remove_garbage=True,
683
+ n_overide=None,
684
+ orbits: Optional[Orbits] = EqualArmlengthOrbits,
685
+ **kwargs,
686
+ ):
687
+
688
+ # store all necessary information
689
+ self.waveform_gen = waveform_gen
690
+ self.index_lambda = index_lambda
691
+ self.index_beta = index_beta
692
+ self.dt = dt
693
+ self.t0 = t0
694
+ self.sampling_frequency = 1.0 / dt
695
+ super().__init__(force_backend=force_backend)
696
+
697
+ if orbits is None:
698
+ orbits = EqualArmlengthOrbits()
699
+
700
+ assert isinstance(orbits, Orbits)
701
+
702
+ if Tobs * YRSID_SI > orbits.t_base.max():
703
+ warnings.warn(
704
+ f"Tobs is larger than available orbital information time array. Reducing Tobs to {orbits.t_base.max()}"
705
+ )
706
+ Tobs = orbits.t_base.max() / YRSID_SI
707
+
708
+ if n_overide is not None:
709
+ if not isinstance(n_overide, int):
710
+ raise ValueError("n_overide must be an integer if not None.")
711
+ self.n = n_overide
712
+
713
+ else:
714
+ self.n = int(Tobs * YRSID_SI / dt)
715
+
716
+ self.Tobs = self.n * dt
717
+ self.is_ecliptic_latitude = is_ecliptic_latitude
718
+ self.remove_sky_coords = remove_sky_coords
719
+ self.flip_hx = flip_hx
720
+ self.remove_garbage = remove_garbage
721
+
722
+ # initialize response function class
723
+ self.response_model = pyResponseTDI(
724
+ self.sampling_frequency, self.n, orbits=orbits, force_backend=force_backend, **kwargs
725
+ )
726
+
727
+ self.Tobs = (self.n * self.response_model.dt) / YRSID_SI
728
+
729
+ @property
730
+ def xp(self) -> object:
731
+ return self.backend.xp
732
+
733
+ @property
734
+ def citation(self):
735
+ """Get citations for use of this code"""
736
+
737
+ return """
738
+ # TODO add
739
+ """
740
+
741
+ def __call__(self, *args, **kwargs):
742
+ """Run the waveform and response generation
743
+
744
+ Args:
745
+ *args (list): Arguments to the waveform generator. This must include
746
+ the sky coordinates.
747
+ **kwargs (dict): kwargs necessary for the waveform generator.
748
+
749
+ Return:
750
+ list: TDI Channels.
751
+
752
+ """
753
+
754
+ args = list(args)
755
+
756
+ # get sky coords
757
+ beta = args[self.index_beta]
758
+ lam = args[self.index_lambda]
759
+
760
+ # remove them from the list if waveform generator does not take them
761
+ if self.remove_sky_coords:
762
+ args.pop(self.index_beta)
763
+ args.pop(self.index_lambda)
764
+
765
+ # transform polar angle
766
+ if not self.is_ecliptic_latitude:
767
+ beta = np.pi / 2.0 - beta
768
+
769
+ # add the new Tobs and dt info to the waveform generator kwargs
770
+ kwargs["T"] = self.Tobs
771
+ kwargs["dt"] = self.dt
772
+
773
+ # get the waveform
774
+ h = self.waveform_gen(*args, **kwargs)
775
+
776
+ if self.flip_hx:
777
+ h = h.real - 1j * h.imag
778
+
779
+ self.response_model.get_projections(h, lam, beta, t0=self.t0)
780
+ tdi_out = self.response_model.get_tdi_delays()
781
+
782
+ out = list(tdi_out)
783
+ if self.remove_garbage is True: # bool
784
+ for i in range(len(out)):
785
+ out[i] = out[i][
786
+ self.response_model.tdi_start_ind : -self.response_model.tdi_start_ind
787
+ ]
788
+
789
+ elif isinstance(self.remove_garbage, str): # bool
790
+ if self.remove_garbage != "zero":
791
+ raise ValueError("remove_garbage must be True, False, or 'zero'.")
792
+ for i in range(len(out)):
793
+ out[i][: self.response_model.tdi_start_ind] = 0.0
794
+ out[i][-self.response_model.tdi_start_ind :] = 0.0
795
+
796
+ return out