make_sfts.py 23.1 KB
Newer Older
Gregory Ashton's avatar
Gregory Ashton committed
1
""" pyfstat tools to generate sfts """
2

Gregory Ashton's avatar
Gregory Ashton committed
3
4
5
6

import numpy as np
import logging
import os
7
import glob
8
import pkgutil
Gregory Ashton's avatar
Gregory Ashton committed
9

Gregory Ashton's avatar
Gregory Ashton committed
10
import lal
Gregory Ashton's avatar
Gregory Ashton committed
11
12
import lalpulsar

Gregory Ashton's avatar
Gregory Ashton committed
13
from pyfstat.core import BaseSearchClass, tqdm, args, predict_fstat
14
import pyfstat.helper_functions as helper_functions
Gregory Ashton's avatar
Gregory Ashton committed
15
16


17
18
19
20
class KeyboardInterruptError(Exception):
    pass


Gregory Ashton's avatar
Gregory Ashton committed
21
class Writer(BaseSearchClass):
22
    """ Instance object for generating SFTs """
23

Gregory Ashton's avatar
Gregory Ashton committed
24
    @helper_functions.initializer
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
    def __init__(
        self,
        label="Test",
        tstart=700000000,
        duration=100 * 86400,
        tref=None,
        F0=30,
        F1=1e-10,
        F2=0,
        Alpha=5e-3,
        Delta=6e-2,
        h0=0.1,
        cosi=0.0,
        psi=0.0,
        phi=0,
        Tsft=1800,
        outdir=".",
        sqrtSX=1,
        Band=4,
        detectors="H1",
        minStartTime=None,
        maxStartTime=None,
        add_noise=True,
        transientWindowType="none",
    ):
Gregory Ashton's avatar
Gregory Ashton committed
50
51
52
53
54
        """
        Parameters
        ----------
        label: string
            a human-readable label to be used in naming the output files
55
56
        tstart, duration : int
            start and duration (in gps seconds) of the total observation span
Gregory Ashton's avatar
Gregory Ashton committed
57
58
59
60
61
62
63
64
65
66
67
68
69
70
        tref: float or None
            reference time (default is None, which sets the reference time to
            tstart)
        F0, F1, F2, Alpha, Delta, h0, cosi, psi, phi: float
            frequency, sky-position, and amplitude parameters
        Tsft: float
            the sft duration
        minStartTime, maxStartTime: float
            if not None, the total span of data, this can be used to generate
            transient signals

        see `lalapps_Makefakedata_v5 --help` for help with the other paramaters
        """

71
        self.set_ephemeris_files()
Gregory Ashton's avatar
Gregory Ashton committed
72
73
74
75
        self.basic_setup()
        self.calculate_fmin_Band()

        self.tbounds = [self.tstart, self.tend]
76
        logging.info("Using segment boundaries {}".format(self.tbounds))
77

Gregory Ashton's avatar
Gregory Ashton committed
78
79
80
    def basic_setup(self):
        self.tstart = int(self.tstart)
        self.duration = int(self.duration)
Gregory Ashton's avatar
Gregory Ashton committed
81
82
83
84
85
        self.tend = self.tstart + self.duration
        if self.minStartTime is None:
            self.minStartTime = self.tstart
        if self.maxStartTime is None:
            self.maxStartTime = self.tend
Gregory Ashton's avatar
Gregory Ashton committed
86
87
        self.minStartTime = int(self.minStartTime)
        self.maxStartTime = int(self.maxStartTime)
88
        self.duration_days = (self.tend - self.tstart) / 86400
Gregory Ashton's avatar
Gregory Ashton committed
89
90
91

        self.data_duration = self.maxStartTime - self.minStartTime
        numSFTs = int(float(self.data_duration) / self.Tsft)
Gregory Ashton's avatar
Gregory Ashton committed
92

Gregory Ashton's avatar
Gregory Ashton committed
93
        self.theta = np.array([self.phi, self.F0, self.F1, self.F2])
Gregory Ashton's avatar
Gregory Ashton committed
94
95
96
97
98

        if os.path.isdir(self.outdir) is False:
            os.makedirs(self.outdir)
        if self.tref is None:
            self.tref = self.tstart
Gregory Ashton's avatar
Gregory Ashton committed
99
        self.config_file_name = "{}/{}.cff".format(self.outdir, self.label)
Gregory Ashton's avatar
Gregory Ashton committed
100
101
        self.sftfilenames = [
            lalpulsar.OfficialSFTFilename(
102
103
104
105
106
107
108
109
110
111
112
113
114
115
                dets[0],
                dets[1],
                numSFTs,
                self.Tsft,
                self.minStartTime,
                self.data_duration,
                self.label,
            )
            for dets in self.detectors.split(",")
        ]
        self.sftfilepath = ";".join(
            ["{}/{}".format(self.outdir, fn) for fn in self.sftfilenames]
        )
        self.IFOs = ",".join(['"{}"'.format(d) for d in self.detectors.split(",")])
Gregory Ashton's avatar
Gregory Ashton committed
116
117

    def make_data(self):
118
        """ A convienience wrapper to generate a cff file then sfts """
Gregory Ashton's avatar
Gregory Ashton committed
119
120
121
        self.make_cff()
        self.run_makefakedata()

122
123
    def get_base_template(self, i, Alpha, Delta, h0, cosi, psi, phi, F0, F1, F2, tref):
        return """[TS{}]
Gregory Ashton's avatar
Gregory Ashton committed
124
125
126
127
128
129
130
131
132
Alpha = {:1.18e}
Delta = {:1.18e}
h0 = {:1.18e}
cosi = {:1.18e}
psi = {:1.18e}
phi0 = {:1.18e}
Freq = {:1.18e}
f1dot = {:1.18e}
f2dot = {:1.18e}
133
refTime = {:10.6f}"""
134

Gregory Ashton's avatar
Gregory Ashton committed
135
    def get_single_config_line_cw(
136
137
138
139
140
141
142
143
144
        self, i, Alpha, Delta, h0, cosi, psi, phi, F0, F1, F2, tref
    ):
        template = (
            self.get_base_template(
                i, Alpha, Delta, h0, cosi, psi, phi, F0, F1, F2, tref
            )
            + """\n"""
        )
        return template.format(i, Alpha, Delta, h0, cosi, psi, phi, F0, F1, F2, tref)
Gregory Ashton's avatar
Gregory Ashton committed
145
146

    def get_single_config_line_tcw(
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
        self,
        i,
        Alpha,
        Delta,
        h0,
        cosi,
        psi,
        phi,
        F0,
        F1,
        F2,
        tref,
        window,
        tstart,
        duration_days,
    ):
        template = (
            self.get_base_template(
                i, Alpha, Delta, h0, cosi, psi, phi, F0, F1, F2, tref
            )
            + """
David Keitel's avatar
David Keitel committed
168
transientWindowType = {:s}
169
transientStartTime = {:10.0f}
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
transientTau = {:10.0f}\n"""
        )
        return template.format(
            i,
            Alpha,
            Delta,
            h0,
            cosi,
            psi,
            phi,
            F0,
            F1,
            F2,
            tref,
            window,
            tstart,
            duration_days * 86400,
        )

    def get_single_config_line(
        self,
        i,
        Alpha,
        Delta,
        h0,
        cosi,
        psi,
        phi,
        F0,
        F1,
        F2,
        tref,
        window,
        tstart,
        duration_days,
    ):
        if window == "none":
Gregory Ashton's avatar
Gregory Ashton committed
207
            return self.get_single_config_line_cw(
208
209
                i, Alpha, Delta, h0, cosi, psi, phi, F0, F1, F2, tref
            )
210
        else:
Gregory Ashton's avatar
Gregory Ashton committed
211
            return self.get_single_config_line_tcw(
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
                i,
                Alpha,
                Delta,
                h0,
                cosi,
                psi,
                phi,
                F0,
                F1,
                F2,
                tref,
                window,
                tstart,
                duration_days,
            )
227

Gregory Ashton's avatar
Gregory Ashton committed
228
229
    def make_cff(self):
        """
230
        Generates a .cff file
Gregory Ashton's avatar
Gregory Ashton committed
231
232
233

        """

234
        content = self.get_single_config_line(
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
            0,
            self.Alpha,
            self.Delta,
            self.h0,
            self.cosi,
            self.psi,
            self.phi,
            self.F0,
            self.F1,
            self.F2,
            self.tref,
            self.transientWindowType,
            self.tstart,
            self.duration_days,
        )
Gregory Ashton's avatar
Gregory Ashton committed
250
251
252
253
254
255
256

        if self.check_if_cff_file_needs_rewritting(content):
            config_file = open(self.config_file_name, "w+")
            config_file.write(content)
            config_file.close()

    def calculate_fmin_Band(self):
257
        self.fmin = self.F0 - 0.5 * self.Band
Gregory Ashton's avatar
Gregory Ashton committed
258
259
260
261
262
263
264

    def check_cached_data_okay_to_use(self, cl_mfd):
        """ Check if cached data exists and, if it does, if it can be used """

        getmtime = os.path.getmtime

        if os.path.isfile(self.sftfilepath) is False:
265
            logging.info("No SFT file matching {} found".format(self.sftfilepath))
Gregory Ashton's avatar
Gregory Ashton committed
266
267
            return False
        else:
268
            logging.info("Matching SFT file found")
Gregory Ashton's avatar
Gregory Ashton committed
269
270
271

        if getmtime(self.sftfilepath) < getmtime(self.config_file_name):
            logging.info(
272
273
274
275
276
                (
                    "The config file {} has been modified since the sft file {} "
                    + "was created"
                ).format(self.config_file_name, self.sftfilepath)
            )
Gregory Ashton's avatar
Gregory Ashton committed
277
278
279
            return False

        logging.info(
280
281
282
283
284
285
            "The config file {} is older than the sft file {}".format(
                self.config_file_name, self.sftfilepath
            )
        )
        logging.info("Checking contents of cff file")
        cl_dump = "lalapps_SFTdumpheader {} | head -n 20".format(self.sftfilepath)
Gregory Ashton's avatar
Gregory Ashton committed
286
        output = helper_functions.run_commandline(cl_dump)
287
        calls = [line for line in output.split("\n") if line[:3] == "lal"]
Gregory Ashton's avatar
Gregory Ashton committed
288
        if calls[0] == cl_mfd:
289
            logging.info("Contents matched, use old sft file")
Gregory Ashton's avatar
Gregory Ashton committed
290
291
            return True
        else:
292
            logging.info("Contents unmatched, create new sft file")
Gregory Ashton's avatar
Gregory Ashton committed
293
294
295
296
297
298
299
300
301
            return False

    def check_if_cff_file_needs_rewritting(self, content):
        """ Check if the .cff file has changed

        Returns True if the file should be overwritten - where possible avoid
        overwriting to allow cached data to be used
        """
        if os.path.isfile(self.config_file_name) is False:
302
            logging.info("No config file {} found".format(self.config_file_name))
Gregory Ashton's avatar
Gregory Ashton committed
303
304
            return True
        else:
305
            logging.info("Config file {} already exists".format(self.config_file_name))
Gregory Ashton's avatar
Gregory Ashton committed
306

307
        with open(self.config_file_name, "r") as f:
Gregory Ashton's avatar
Gregory Ashton committed
308
309
310
            file_content = f.read()
            if file_content == content:
                logging.info(
311
312
313
314
                    "File contents match, no update of {} required".format(
                        self.config_file_name
                    )
                )
Gregory Ashton's avatar
Gregory Ashton committed
315
316
317
                return False
            else:
                logging.info(
318
319
                    "File contents unmatched, updating {}".format(self.config_file_name)
                )
Gregory Ashton's avatar
Gregory Ashton committed
320
321
322
323
324
325
326
327
328
329
330
331
                return True

    def run_makefakedata(self):
        """ Generate the sft data from the configuration file """

        # Remove old data:
        try:
            os.unlink("{}/*{}*.sft".format(self.outdir, self.label))
        except OSError:
            pass

        cl_mfd = []
332
333
        cl_mfd.append("lalapps_Makefakedata_v5")
        cl_mfd.append("--outSingleSFT=TRUE")
Gregory Ashton's avatar
Gregory Ashton committed
334
335
        cl_mfd.append('--outSFTdir="{}"'.format(self.outdir))
        cl_mfd.append('--outLabel="{}"'.format(self.label))
336
        cl_mfd.append("--IFOs={}".format(self.IFOs))
Gregory Ashton's avatar
Gregory Ashton committed
337
338
339
        if self.add_noise:
            cl_mfd.append('--sqrtSX="{}"'.format(self.sqrtSX))
        if self.minStartTime is None:
340
            cl_mfd.append("--startTime={:0.0f}".format(float(self.tstart)))
Gregory Ashton's avatar
Gregory Ashton committed
341
        else:
342
            cl_mfd.append("--startTime={:0.0f}".format(float(self.minStartTime)))
Gregory Ashton's avatar
Gregory Ashton committed
343
        if self.maxStartTime is None:
344
            cl_mfd.append("--duration={}".format(int(self.duration)))
Gregory Ashton's avatar
Gregory Ashton committed
345
346
        else:
            data_duration = self.maxStartTime - self.minStartTime
347
348
349
350
            cl_mfd.append("--duration={}".format(int(data_duration)))
        cl_mfd.append("--fmin={:.16g}".format(self.fmin))
        cl_mfd.append("--Band={:.16g}".format(self.Band))
        cl_mfd.append("--Tsft={}".format(self.Tsft))
Gregory Ashton's avatar
Gregory Ashton committed
351
        if self.h0 != 0:
352
            cl_mfd.append('--injectionSources="{}"'.format(self.config_file_name))
Gregory Ashton's avatar
Gregory Ashton committed
353
354
355
356
357
358
359
360

        cl_mfd = " ".join(cl_mfd)

        if self.check_cached_data_okay_to_use(cl_mfd) is False:
            helper_functions.run_commandline(cl_mfd)

    def predict_fstat(self):
        """ Wrapper to lalapps_PredictFstat """
Gregory Ashton's avatar
Gregory Ashton committed
361
        twoF_expected, twoF_sigma = predict_fstat(
362
363
364
365
366
367
368
369
370
371
372
373
374
            self.h0,
            self.cosi,
            self.psi,
            self.Alpha,
            self.Delta,
            self.F0,
            self.sftfilepath,
            self.minStartTime,
            self.maxStartTime,
            self.detectors,
            self.sqrtSX,
            tempory_filename="{}.tmp".format(self.label),
        )  # detectors OR IFO?
Gregory Ashton's avatar
Gregory Ashton committed
375
        return twoF_expected
376
377
378
379


class GlitchWriter(Writer):
    """ Instance object for generating SFTs containing glitch signals """
380

381
    @helper_functions.initializer
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
    def __init__(
        self,
        label="Test",
        tstart=700000000,
        duration=100 * 86400,
        dtglitch=None,
        delta_phi=0,
        delta_F0=0,
        delta_F1=0,
        delta_F2=0,
        tref=None,
        F0=30,
        F1=1e-10,
        F2=0,
        Alpha=5e-3,
        Delta=6e-2,
        h0=0.1,
        cosi=0.0,
        psi=0.0,
        phi=0,
        Tsft=1800,
        outdir=".",
        sqrtSX=1,
        Band=4,
        detectors="H1",
        minStartTime=None,
        maxStartTime=None,
        add_noise=True,
        transientWindowType="rect",
    ):
412
413
414
415
416
        """
        Parameters
        ----------
        label: string
            a human-readable label to be used in naming the output files
417
418
        tstart, duration : float
            start and duration (in gps seconds) of the total observation span
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
        dtglitch: float
            time (in gps seconds) of the glitch after tstart. To create data
            without a glitch, set dtglitch=None
        delta_phi, delta_F0, delta_F1: float
            instanteneous glitch magnitudes in rad, Hz, and Hz/s respectively
        tref: float or None
            reference time (default is None, which sets the reference time to
            tstart)
        F0, F1, F2, Alpha, Delta, h0, cosi, psi, phi: float
            frequency, sky-position, and amplitude parameters
        Tsft: float
            the sft duration
        minStartTime, maxStartTime: float
            if not None, the total span of data, this can be used to generate
            transient signals

        see `lalapps_Makefakedata_v5 --help` for help with the other paramaters
        """

Gregory Ashton's avatar
Gregory Ashton committed
438
439
440
        self.basic_setup()
        self.calculate_fmin_Band()

441
442
443
444
445
446
        shapes = np.array(
            [
                np.shape(x)
                for x in [self.delta_phi, self.delta_F0, self.delta_F1, self.delta_F2]
            ]
        )
Gregory Ashton's avatar
Gregory Ashton committed
447
        if not np.all(shapes == shapes[0]):
448
            raise ValueError("all delta_* must be the same shape: {}".format(shapes))
449

450
451
452
        for d in self.delta_phi, self.delta_F0, self.delta_F1, self.delta_F2:
            if np.size(d) == 1:
                d = np.atleast_1d(d)
Gregory Ashton's avatar
Gregory Ashton committed
453

454
455
456
457
458
        if self.dtglitch is None:
            self.tbounds = [self.tstart, self.tend]
        else:
            self.dtglitch = np.atleast_1d(self.dtglitch)
            self.tglitch = self.tstart + self.dtglitch
459
460
            self.tbounds = np.concatenate(([self.tstart], self.tglitch, [self.tend]))
        logging.info("Using segment boundaries {}".format(self.tbounds))
461
462
463
464
465

        tbs = np.array(self.tbounds)
        self.durations_days = (tbs[1:] - tbs[:-1]) / 86400

        self.delta_thetas = np.atleast_2d(
466
467
            np.array([delta_phi, delta_F0, delta_F1, delta_F2]).T
        )
468
469
470
471
472
473
474

    def make_cff(self):
        """
        Generates an .cff file for a 'glitching' signal

        """

475
        thetas = self._calculate_thetas(self.theta, self.delta_thetas, self.tbounds)
476

477
478
479
480
        content = ""
        for i, (t, d, ts) in enumerate(
            zip(thetas, self.durations_days, self.tbounds[:-1])
        ):
481
            line = self.get_single_config_line(
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
                i,
                self.Alpha,
                self.Delta,
                self.h0,
                self.cosi,
                self.psi,
                t[0],
                t[1],
                t[2],
                t[3],
                self.tref,
                self.transientWindowType,
                ts,
                d,
            )
497
498
499
500
501
502
503

            content += line

        if self.check_if_cff_file_needs_rewritting(content):
            config_file = open(self.config_file_name, "w+")
            config_file.write(content)
            config_file.close()
Gregory Ashton's avatar
Gregory Ashton committed
504
505
506
507
508
509


class FrequencyModulatedArtifactWriter(Writer):
    """ Instance object for generating SFTs containing artifacts """

    @helper_functions.initializer
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
    def __init__(
        self,
        label,
        outdir=".",
        tstart=700000000,
        duration=86400,
        F0=30,
        F1=0,
        tref=None,
        h0=10,
        Tsft=1800,
        sqrtSX=1,
        Band=4,
        Pmod=lal.DAYSID_SI,
        Pmod_phi=0,
        Pmod_amp=1,
        Alpha=None,
        Delta=None,
        IFO="H1",
        minStartTime=None,
        maxStartTime=None,
        detectors="H1",
    ):
Gregory Ashton's avatar
Gregory Ashton committed
533
534
535
        """
        Parameters
        ----------
Gregory Ashton's avatar
Gregory Ashton committed
536
        tstart, duration : int
Gregory Ashton's avatar
Gregory Ashton committed
537
            start and duration times (in gps seconds) of the total observation
538
539
540
541
542
        Pmod, F0, F1 h0: float
            Modulation period, freq, freq-drift, and h0 of the artifact
        Alpha, Delta: float
            Sky position, in radians, of a signal of which to add the orbital
            modulation to the artifact, if not `None`.
Gregory Ashton's avatar
Gregory Ashton committed
543
544
545
546
547
548
549
        Tsft: float
            the sft duration
        sqrtSX: float
            Background IFO noise

        see `lalapps_Makefakedata_v4 --help` for help with the other paramaters
        """
Gregory Ashton's avatar
Gregory Ashton committed
550
551
        self.phi = 0
        self.F2 = 0
Gregory Ashton's avatar
Gregory Ashton committed
552

Gregory Ashton's avatar
Gregory Ashton committed
553
        self.basic_setup()
554
        self.set_ephemeris_files()
555
        self.tstart = int(tstart)
Gregory Ashton's avatar
Gregory Ashton committed
556
        self.duration = int(duration)
557

Gregory Ashton's avatar
Gregory Ashton committed
558
559
560
        if os.path.isdir(self.outdir) is False:
            os.makedirs(self.outdir)
        if tref is None:
561
            raise ValueError("Input `tref` not specified")
Gregory Ashton's avatar
Gregory Ashton committed
562

Gregory Ashton's avatar
Gregory Ashton committed
563
        self.nsfts = int(np.ceil(self.duration / self.Tsft))
564
        self.duration = self.duration / 86400.0
Gregory Ashton's avatar
Gregory Ashton committed
565
566
567
568
569
        self.calculate_fmin_Band()

        self.cosi = 0
        self.Fmax = F0

570
        if Alpha is not None and Delta is not None:
571
572
573
574
575
576
577
            self.n = np.array(
                [
                    np.cos(Alpha) * np.cos(Delta),
                    np.sin(Alpha) * np.cos(Delta),
                    np.sin(Delta),
                ]
            )
Gregory Ashton's avatar
Gregory Ashton committed
578
579

    def get_frequency(self, t):
580
581
        DeltaFDrift = self.F1 * (t - self.tref)

582
        phir = 2 * np.pi * t / self.Pmod + self.Pmod_phi
583
584

        if self.Alpha is not None and self.Delta is not None:
585
586
587
588
589
            spin_posvel = lalpulsar.PosVel3D_t()
            orbit_posvel = lalpulsar.PosVel3D_t()
            det = lal.CachedDetectors[4]
            ephems = lalpulsar.InitBarycenter(self.earth_ephem, self.sun_ephem)
            lalpulsar.DetectorPosVel(
590
591
592
593
594
595
596
                spin_posvel,
                orbit_posvel,
                lal.LIGOTimeGPS(t),
                det,
                ephems,
                lalpulsar.DETMOTION_ORBIT,
            )
597
            # Pos and vel returned in units of c
598
            DeltaFOrbital = np.dot(self.n, orbit_posvel.vel) * self.Fmax
Gregory Ashton's avatar
Gregory Ashton committed
599

600
            if self.IFO == "H1":
601
                Lambda = lal.LHO_4K_DETECTOR_LATITUDE_RAD
602
            elif self.IFO == "L1":
603
                Lambda = lal.LLO_4K_DETECTOR_LATITUDE_RAD
604

605
            DeltaFSpin = (
606
607
608
609
610
611
612
613
614
                self.Pmod_amp
                * lal.REARTH_SI
                / lal.C_SI
                * 2
                * np.pi
                / self.Pmod
                * (np.cos(self.Delta) * np.cos(Lambda) * np.sin(self.Alpha - phir))
                * self.Fmax
            )
615
616
        else:
            DeltaFOrbital = 0
617
            DeltaFSpin = 2 * np.pi * self.Pmod_amp / self.Pmod * np.cos(phir)
618
619

        f = self.F0 + DeltaFDrift + DeltaFOrbital + DeltaFSpin
Gregory Ashton's avatar
Gregory Ashton committed
620
621
622
623
624
        return f

    def get_h0(self, t):
        return self.h0

625
    def concatenate_sft_files(self):
626
        SFTFilename = lalpulsar.OfficialSFTFilename(
627
628
629
630
631
632
633
634
            self.IFO[0],
            self.IFO[1],
            self.nsfts,
            self.Tsft,
            int(self.tstart),
            int(self.duration),
            self.label,
        )
635

636
637
        # If the file already exists, simply remove it for now (no caching
        # implemented)
638
        helper_functions.run_commandline(
639
640
641
642
643
644
645
646
647
648
649
            "rm {}/{}".format(self.outdir, SFTFilename), raise_error=False, log_level=10
        )

        cl_splitSFTS = "lalapps_splitSFTs -fs {} -fb {} -fe {} -o {}/{} -i {}/*sft".format(
            self.fmin,
            self.Band,
            self.fmin + self.Band,
            self.outdir,
            SFTFilename,
            self.tmp_outdir,
        )
650
        helper_functions.run_commandline(cl_splitSFTS)
651
652
        helper_functions.run_commandline("rm {} -r".format(self.tmp_outdir))
        files = glob.glob("{}/{}*".format(self.outdir, SFTFilename))
653
654
        if len(files) == 1:
            fn = files[0]
655
656
            fn_new = fn.split(".")[0] + ".sft"
            helper_functions.run_commandline("mv {} {}".format(fn, fn_new))
657
658
        else:
            raise IOError(
659
660
                "Attempted to rename file, but multiple files found: {}".format(files)
            )
661

662
    def pre_compute_evolution(self):
663
        logging.info("Precomputing evolution parameters")
664
665
666
667
668
669
670
        self.lineFreqs = []
        self.linePhis = []
        self.lineh0s = []
        self.mid_times = []

        linePhi = 0
        lineFreq_old = 0
671
        for i in tqdm(list(range(self.nsfts))):
672
            mid_time = self.tstart + (i + 0.5) * self.Tsft
673
674
675
676
            lineFreq = self.get_frequency(mid_time)

            self.mid_times.append(mid_time)
            self.lineFreqs.append(lineFreq)
677
678
679
            self.linePhis.append(
                linePhi + np.pi * self.Tsft * (lineFreq_old + lineFreq)
            )
680
681
682
683
684
685
            self.lineh0s.append(self.get_h0(mid_time))

            lineFreq_old = lineFreq

    def make_ith_sft(self, i):
        try:
686
687
688
689
690
691
692
            self.run_makefakedata_v4(
                self.mid_times[i],
                self.lineFreqs[i],
                self.linePhis[i],
                self.lineh0s[i],
                self.tmp_outdir,
            )
693
694
695
        except KeyboardInterrupt:
            raise KeyboardInterruptError()

Gregory Ashton's avatar
Gregory Ashton committed
696
697
698
    def make_data(self):
        self.maxStartTime = None
        self.duration = self.Tsft
699

700
        self.tmp_outdir = "{}/{}_tmp".format(self.outdir, self.label)
701
        if os.path.isdir(self.tmp_outdir) is True:
702
            raise ValueError(
703
704
705
706
                "Temporary directory {} already exists, please rename".format(
                    self.tmp_outdir
                )
            )
707
        else:
708
            os.makedirs(self.tmp_outdir)
709

710
711
        self.pre_compute_evolution()

712
        logging.info("Generating SFTs")
713

714
        if args.N > 1 and pkgutil.find_loader("pathos") is not None:
715
            import pathos.pools
716
717

            logging.info("Using {} threads".format(args.N))
718
719
            try:
                with pathos.pools.ProcessPool(args.N) as p:
720
721
722
723
724
725
                    list(
                        tqdm(
                            p.imap(self.make_ith_sft, list(range(self.nsfts))),
                            total=self.nsfts,
                        )
                    )
726
727
728
729
730
            except KeyboardInterrupt:
                p.terminate()
        else:
            logging.info(
                "No multiprocessing requested or `pathos` not install, cont."
731
732
                " without multiprocessing"
            )
733
            for i in tqdm(list(range(self.nsfts))):
734
                self.make_ith_sft(i)
Gregory Ashton's avatar
Gregory Ashton committed
735

736
        self.concatenate_sft_files()
737
738

    def run_makefakedata_v4(self, mid_time, lineFreq, linePhi, h0, tmp_outdir):
Gregory Ashton's avatar
Gregory Ashton committed
739
740
        """ Generate the sft data using the --lineFeature option """
        cl_mfd = []
741
742
        cl_mfd.append("lalapps_Makefakedata_v4")
        cl_mfd.append("--outSingleSFT=FALSE")
743
        cl_mfd.append('--outSFTbname="{}"'.format(tmp_outdir))
744
        cl_mfd.append("--IFO={}".format(self.IFO))
Gregory Ashton's avatar
Gregory Ashton committed
745
        cl_mfd.append('--noiseSqrtSh="{}"'.format(self.sqrtSX))
746
747
748
749
750
751
752
753
754
755
756
        cl_mfd.append("--startTime={:0.0f}".format(mid_time - self.Tsft / 2.0))
        cl_mfd.append("--refTime={:0.0f}".format(mid_time))
        cl_mfd.append("--duration={}".format(int(self.duration)))
        cl_mfd.append("--fmin={:.16g}".format(self.fmin))
        cl_mfd.append("--Band={:.16g}".format(self.Band))
        cl_mfd.append("--Tsft={}".format(self.Tsft))
        cl_mfd.append("--Freq={}".format(lineFreq))
        cl_mfd.append("--phi0={}".format(linePhi))
        cl_mfd.append("--h0={}".format(h0))
        cl_mfd.append("--cosi={}".format(self.cosi))
        cl_mfd.append("--lineFeature=TRUE")
Gregory Ashton's avatar
Gregory Ashton committed
757
758
759
760
761
762
        cl_mfd = " ".join(cl_mfd)
        helper_functions.run_commandline(cl_mfd, log_level=10)


class FrequencyAmplitudeModulatedArtifactWriter(FrequencyModulatedArtifactWriter):
    """ Instance object for generating SFTs containing artifacts """
763

Gregory Ashton's avatar
Gregory Ashton committed
764
    def get_h0(self, t):
765
        return self.h0 * np.sin(2 * np.pi * t / self.Pmod + self.Pmod_phi)