core.py 46.2 KB
Newer Older
Gregory Ashton's avatar
Gregory Ashton committed
1
""" The core tools used in pyfstat """
2
3
from __future__ import division, absolute_import, print_function

Gregory Ashton's avatar
Gregory Ashton committed
4
5
6
7
import os
import logging
import copy

8
import glob
Gregory Ashton's avatar
Gregory Ashton committed
9
import numpy as np
10
11
12
13
14
import scipy.special
import scipy.optimize

import lal
import lalpulsar
15
import pyfstat.helper_functions as helper_functions
16
17

# workaround for matplotlib on X-less remote logins
18
if 'DISPLAY' in os.environ:
19
20
    import matplotlib.pyplot as plt
else:
21
22
    logging.info('No $DISPLAY environment variable found, so importing \
                  matplotlib.pyplot with non-interactive "Agg" backend.')
23
24
25
26
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt

Gregory Ashton's avatar
Gregory Ashton committed
27
helper_functions.set_up_matplotlib_defaults()
28
args, tqdm = helper_functions.set_up_command_line_arguments()
29
detector_colors = {'h1': 'C0', 'l1': 'C1'}
Gregory Ashton's avatar
Gregory Ashton committed
30
31


Gregory Ashton's avatar
Gregory Ashton committed
32
class Bunch(object):
33
34
    """ Turns dictionary into object with attribute-style access

35
36
    Parameters
    ----------
37
38
39
40
41
42
43
44
45
46
47
48
49
50
    dict
        Input dictionary

    Examples
    --------
    >>> data = Bunch(dict(x=1, y=[1, 2, 3], z=True))
    >>> print(data.x)
    1
    >>> print(data.y)
    [1, 2, 3]
    >>> print(data.z)
    True

    """
Gregory Ashton's avatar
Gregory Ashton committed
51
52
53
54
55
    def __init__(self, dictionary):
        self.__dict__.update(dictionary)


def read_par(filename=None, label=None, outdir=None, suffix='par',
56
57
             return_type='dict', comments=['%', '#'], raise_error=False):
    """ Read in a .par or .loudest file, returns a dict or Bunch of the data
58

Gregory Ashton's avatar
Gregory Ashton committed
59
60
    Parameters
    ----------
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
    filename : str
        Filename (path) containing rows of `key=val` data to read in.
    label, outdir, suffix : str, optional
        If filename is None, form the file to read as `outdir/label.suffix`.
    return_type : {'dict', 'bunch'}, optional
        If `dict`, return a dictionary, if 'bunch' return a Bunch
    comments : str or list of strings, optional
        Characters denoting that a row is a comment.
    raise_error : bool, optional
        If True, raise an error for lines which are not comments, but cannot
        be read.

    Notes
    -----
    This can also be used to read in .loudest files, or any file which has
    rows of `key=val` data (in which the val can be understood using eval(val)
Gregory Ashton's avatar
Gregory Ashton committed
77
78
79
80
81

    Returns
    -------
    d: Bunch or dict
        The par values as either a `Bunch` or dict type
82

83
84
85
86
    """
    if filename is None:
        filename = '{}/{}.{}'.format(outdir, label, suffix)
    if os.path.isfile(filename) is False:
87
        raise ValueError("No file {} found".format(filename))
Gregory Ashton's avatar
Gregory Ashton committed
88
89
    d = {}
    with open(filename, 'r') as f:
90
        d = _get_dictionary_from_lines(f, comments, raise_error)
Gregory Ashton's avatar
Gregory Ashton committed
91
92
93
94
95
96
    if return_type in ['bunch', 'Bunch']:
        return Bunch(d)
    elif return_type in ['dict', 'dictionary']:
        return d
    else:
        raise ValueError('return_type {} not understood'.format(return_type))
Gregory Ashton's avatar
Gregory Ashton committed
97
98


99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def _get_dictionary_from_lines(lines, comments, raise_error):
    """ Return dictionary of key=val pairs for each line in lines

    Parameters
    ----------
    comments : str or list of strings
        Characters denoting that a row is a comment.
    raise_error : bool
        If True, raise an error for lines which are not comments, but cannot
        be read.

    Returns
    -------
    d: Bunch or dict
        The par values as either a `Bunch` or dict type

    """
116
117
    d = {}
    for line in lines:
118
        if line[0] not in comments and len(line.split('=')) == 2:
119
120
121
            try:
                key, val = line.rstrip('\n').split('=')
                key = key.strip()
Gregory Ashton's avatar
Gregory Ashton committed
122
123
124
125
                try:
                    d[key] = np.float64(eval(val.rstrip('; ')))
                except NameError:
                    d[key] = val.rstrip('; ')
126
            except SyntaxError:
127
128
                if raise_error:
                    raise IOError('Line {} not understood'.format(line))
129
130
131
132
133
                pass
    return d


def predict_fstat(h0, cosi, psi, Alpha, Delta, Freq, sftfilepattern,
Gregory Ashton's avatar
Gregory Ashton committed
134
135
                  minStartTime, maxStartTime, IFO=None, assumeSqrtSX=None,
                  **kwargs):
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
    """ Wrapper to lalapps_PredictFstat

    Parameters
    ----------
    h0, cosi, psi, Alpha, Delta, Freq : float
        Signal properties, see `lalapps_PredictFstat --help` for more info.
    sftfilepattern : str
        Pattern matching the sftfiles to use.
    minStartTime, maxStartTime : int
    IFO : str
        See `lalapps_PredictFstat --help`
    assumeSqrtSX : float or None
        See `lalapps_PredictFstat --help`, if None this option is not used

    Returns
    -------
    twoF_expected, twoF_sigma : float
        The expectation and standard deviation of 2F

    """
156
157
    tempory_filename = 'fs.tmp'

158
159
160
161
162
163
164
165
166
167
    cl_pfs = []
    cl_pfs.append("lalapps_PredictFstat")
    cl_pfs.append("--h0={}".format(h0))
    cl_pfs.append("--cosi={}".format(cosi))
    cl_pfs.append("--psi={}".format(psi))
    cl_pfs.append("--Alpha={}".format(Alpha))
    cl_pfs.append("--Delta={}".format(Delta))
    cl_pfs.append("--Freq={}".format(Freq))

    cl_pfs.append("--DataFiles='{}'".format(sftfilepattern))
168
    if assumeSqrtSX:
169
        cl_pfs.append("--assumeSqrtSX={}".format(assumeSqrtSX))
170
    if IFO:
171
172
173
174
175
        if ',' in IFO:
            logging.warning('Multiple detector selection not available, using'
                            ' all available data')
        else:
            cl_pfs.append("--IFO={}".format(IFO))
176

177
178
    cl_pfs.append("--minStartTime={}".format(int(minStartTime)))
    cl_pfs.append("--maxStartTime={}".format(int(maxStartTime)))
179
    cl_pfs.append("--outputFstat={}".format(tempory_filename))
180

181
182
    cl_pfs = " ".join(cl_pfs)
    helper_functions.run_commandline(cl_pfs)
183
184
    d = read_par(filename=tempory_filename)
    os.remove(tempory_filename)
185
186
187
    return float(d['twoF_expected']), float(d['twoF_sigma'])


Gregory Ashton's avatar
Gregory Ashton committed
188
class BaseSearchClass(object):
189
    """ The base search class providing parent methods to other searches """
Gregory Ashton's avatar
Gregory Ashton committed
190

191
    def _add_log_file(self):
Gregory Ashton's avatar
Gregory Ashton committed
192
193
194
195
196
197
198
199
200
        """ Log output to a file, requires class to have outdir and label """
        logfilename = '{}/{}.log'.format(self.outdir, self.label)
        fh = logging.FileHandler(logfilename)
        fh.setLevel(logging.INFO)
        fh.setFormatter(logging.Formatter(
            '%(asctime)s %(levelname)-8s: %(message)s',
            datefmt='%y-%m-%d %H:%M'))
        logging.getLogger().addHandler(fh)

201
    def _shift_matrix(self, n, dT):
Gregory Ashton's avatar
Gregory Ashton committed
202
203
204
205
        """ Generate the shift matrix

        Parameters
        ----------
206
        n : int
Gregory Ashton's avatar
Gregory Ashton committed
207
            The dimension of the shift-matrix to generate
208
        dT : float
Gregory Ashton's avatar
Gregory Ashton committed
209
210
211
212
            The time delta of the shift matrix

        Returns
        -------
213
214
        m : ndarray, shape (n,)
            The shift matrix.
Gregory Ashton's avatar
Gregory Ashton committed
215

216
        """
Gregory Ashton's avatar
Gregory Ashton committed
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
        m = np.zeros((n, n))
        factorial = np.math.factorial
        for i in range(n):
            for j in range(n):
                if i == j:
                    m[i, j] = 1.0
                elif i > j:
                    m[i, j] = 0.0
                else:
                    if i == 0:
                        m[i, j] = 2*np.pi*float(dT)**(j-i) / factorial(j-i)
                    else:
                        m[i, j] = float(dT)**(j-i) / factorial(j-i)
        return m

232
    def _shift_coefficients(self, theta, dT):
Gregory Ashton's avatar
Gregory Ashton committed
233
234
235
236
        """ Shift a set of coefficients by dT

        Parameters
        ----------
237
238
        theta : array-like, shape (n,)
            Vector of the expansion coefficients to transform starting from the
Gregory Ashton's avatar
Gregory Ashton committed
239
            lowest degree e.g [phi, F0, F1,...].
240
241
        dT : float
            Difference between the two reference times as tref_new - tref_old.
Gregory Ashton's avatar
Gregory Ashton committed
242
243
244

        Returns
        -------
245
246
        theta_new : ndarray, shape (n,)
            Vector of the coefficients as evaluated as the new reference time.
Gregory Ashton's avatar
Gregory Ashton committed
247
248
        """
        n = len(theta)
249
        m = self._shift_matrix(n, dT)
Gregory Ashton's avatar
Gregory Ashton committed
250
251
        return np.dot(m, theta)

252
    def _calculate_thetas(self, theta, delta_thetas, tbounds, theta0_idx=0):
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
        """ Calculates the set of thetas given delta_thetas, the jumps

        This is used when generating data containing glitches or timing noise.
        Specifically, the source parameters of the signal are not constant in
        time, but jump by `delta_theta` at `tbounds`.

        Parameters
        ----------
        theta : array_like
            The source parameters of size (n,).
        delta_thetas : array_like
            The jumps in the source parameters of size (m, n) where m is the
            number of jumps.
        tbounds : array_like
            Time boundaries of the jumps of size (m+2,).
        theta0_idx : int
            Index of the segment for which the theta are defined.

        Returns
        -------
        ndarray
            The set of thetas, shape (m+1, n).

        """
Gregory Ashton's avatar
Gregory Ashton committed
277
278
279
        thetas = [theta]
        for i, dt in enumerate(delta_thetas):
            if i < theta0_idx:
280
                pre_theta_at_ith_glitch = self._shift_coefficients(
Gregory Ashton's avatar
Gregory Ashton committed
281
282
                    thetas[0], tbounds[i+1] - self.tref)
                post_theta_at_ith_glitch = pre_theta_at_ith_glitch - dt
283
                thetas.insert(0, self._shift_coefficients(
Gregory Ashton's avatar
Gregory Ashton committed
284
285
286
                    post_theta_at_ith_glitch, self.tref - tbounds[i+1]))

            elif i >= theta0_idx:
287
                pre_theta_at_ith_glitch = self._shift_coefficients(
Gregory Ashton's avatar
Gregory Ashton committed
288
289
                    thetas[i], tbounds[i+1] - self.tref)
                post_theta_at_ith_glitch = pre_theta_at_ith_glitch + dt
290
                thetas.append(self._shift_coefficients(
Gregory Ashton's avatar
Gregory Ashton committed
291
                    post_theta_at_ith_glitch, self.tref - tbounds[i+1]))
292
        self.thetas_at_tref = thetas
Gregory Ashton's avatar
Gregory Ashton committed
293
294
        return thetas

295
    def _get_list_of_matching_sfts(self):
296
        """ Returns a list of sfts matching the attribute sftfilepattern """
297
298
        sftfilepatternlist = np.atleast_1d(self.sftfilepattern.split(';'))
        matches = [glob.glob(p) for p in sftfilepatternlist]
299
        matches = [item for sublist in matches for item in sublist]
300
301
302
303
        if len(matches) > 0:
            return matches
        else:
            raise IOError('No sfts found matching {}'.format(
304
                self.sftfilepattern))
305

306
307
    def set_ephemeris_files(self, earth_ephem=None, sun_ephem=None):
        """ Set the ephemeris files to use for the Earth and Sun
Gregory Ashton's avatar
Gregory Ashton committed
308

309
310
311
312
313
        Parameters
        ----------
        earth_ephem, sun_ephem: str
            Paths of the two files containing positions of Earth and Sun,
            respectively at evenly spaced times, as passed to CreateFstatInput
Gregory Ashton's avatar
Gregory Ashton committed
314

315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
        Note: If not manually set, default values in ~/.pyfstat are used

        """

        earth_ephem_default, sun_ephem_default = (
                helper_functions.get_ephemeris_files())

        if earth_ephem is None:
            self.earth_ephem = earth_ephem_default
        if sun_ephem is None:
            self.sun_ephem = sun_ephem_default


class ComputeFstat(BaseSearchClass):
    """ Base class providing interface to `lalpulsar.ComputeFstat` """
Gregory Ashton's avatar
Gregory Ashton committed
330
331

    @helper_functions.initializer
332
    def __init__(self, tref, sftfilepattern=None, minStartTime=None,
David Keitel's avatar
David Keitel committed
333
334
                 maxStartTime=None, binary=False, BSGL=False,
                 transientWindowType=None, t0Band=None, tauBand=None,
335
                 dt0=None, dtau=None,
336
                 detectors=None, minCoverFreq=None, maxCoverFreq=None,
337
338
                 injectSources=None, injectSqrtSX=None, assumeSqrtSX=None,
                 SSBprec=None):
Gregory Ashton's avatar
Gregory Ashton committed
339
340
341
        """
        Parameters
        ----------
342
        tref : int
Gregory Ashton's avatar
Gregory Ashton committed
343
            GPS seconds of the reference time.
344
        sftfilepattern : str
345
346
            Pattern to match SFTs using wildcards (*?) and ranges [0-9];
            mutiple patterns can be given separated by colons.
347
        minStartTime, maxStartTime : float GPStime
Gregory Ashton's avatar
Gregory Ashton committed
348
349
            Only use SFTs with timestemps starting from (including, excluding)
            this epoch
350
        binary : bool
Gregory Ashton's avatar
Gregory Ashton committed
351
            If true, search of binary parameters.
Gregory Ashton's avatar
Gregory Ashton committed
352
353
        BSGL : bool
            If true, compute the BSGL rather than the twoF value.
David Keitel's avatar
David Keitel committed
354
355
356
        transientWindowType: str
            If 'rect' or 'exp',
            allow for the Fstat to be computed over a transient range.
Gregory Ashton's avatar
Gregory Ashton committed
357
358
            ('none' instead of None explicitly calls the transient-window
            function, but with the full range, for debugging)
359
360
361
362
363
        t0Band, tauBand: int
            if >0, search t0 in (minStartTime,minStartTime+t0Band)
                   and tau in (2*Tsft,2*Tsft+tauBand).
            if =0, only compute CW Fstat with t0=minStartTime,
                   tau=maxStartTime-minStartTime.
364
365
366
        dt0, dtau: int
            grid resolutions in transient start-time and duration,
            both default to Tsft
367
        detectors : str
Gregory Ashton's avatar
Gregory Ashton committed
368
            Two character reference to the data to use, specify None for no
369
            contraint. If multiple-separate by comma.
370
        minCoverFreq, maxCoverFreq : float
Gregory Ashton's avatar
Gregory Ashton committed
371
372
373
            The min and max cover frequency passed to CreateFstatInput, if
            either is None the range of frequencies in the SFT less 1Hz is
            used.
374
        injectSources : dict or str
375
376
            Either a dictionary of the values to inject, or a string pointing
            to the .cff file to inject
377
        injectSqrtSX :
378
            Not yet implemented
379
        assumeSqrtSX : float
380
381
382
            Don't estimate noise-floors but assume (stationary) per-IFO
            sqrt{SX} (if single value: use for all IFOs). If signal only,
            set sqrtSX=1
383
        SSBprec : int
384
385
            Flag to set the SSB calculation: 0=Newtonian, 1=relativistic,
            2=relativisitic optimised, 3=DMoff, 4=NO_SPIN
Gregory Ashton's avatar
Gregory Ashton committed
386
387
388

        """

389
        self.set_ephemeris_files()
Gregory Ashton's avatar
Gregory Ashton committed
390
391
        self.init_computefstatistic_single_point()

392
393
394
395
396
397
398
399
400
401
402
    def _get_SFTCatalog(self):
        """ Load the SFTCatalog

        If sftfilepattern is specified, load the data. If not, attempt to
        create data on the fly.

        Returns
        -------
        SFTCatalog: lalpulsar.SFTCatalog

        """
Gregory Ashton's avatar
Gregory Ashton committed
403
404
        if hasattr(self, 'SFTCatalog'):
            return
405
        if self.sftfilepattern is None:
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
            for k in ['minStartTime', 'maxStartTime', 'detectors']:
                if getattr(self, k) is None:
                    raise ValueError('You must provide "{}" to injectSources'
                                     .format(k))
            C1 = getattr(self, 'injectSources', None) is None
            C2 = getattr(self, 'injectSqrtSX', None) is None
            if C1 and C2:
                raise ValueError('You must specify either one of injectSources'
                                 ' or injectSqrtSX')
            SFTCatalog = lalpulsar.SFTCatalog()
            Tsft = 1800
            Toverlap = 0
            Tspan = self.maxStartTime - self.minStartTime
            detNames = lal.CreateStringVector(
                *[d for d in self.detectors.split(',')])
            multiTimestamps = lalpulsar.MakeMultiTimestamps(
                self.minStartTime, Tspan, Tsft, Toverlap, detNames.length)
            SFTCatalog = lalpulsar.MultiAddToFakeSFTCatalog(
                SFTCatalog, detNames, multiTimestamps)
            return SFTCatalog

Gregory Ashton's avatar
Gregory Ashton committed
427
428
        logging.info('Initialising SFTCatalog')
        constraints = lalpulsar.SFTConstraints()
429
        if self.detectors:
430
            if ',' in self.detectors:
431
432
                logging.warning('Multiple detector selection not available,'
                                ' using all available data')
433
434
            else:
                constraints.detector = self.detectors
Gregory Ashton's avatar
Gregory Ashton committed
435
436
437
438
439
        if self.minStartTime:
            constraints.minStartTime = lal.LIGOTimeGPS(self.minStartTime)
        if self.maxStartTime:
            constraints.maxStartTime = lal.LIGOTimeGPS(self.maxStartTime)
        logging.info('Loading data matching pattern {}'.format(
440
441
                     self.sftfilepattern))
        SFTCatalog = lalpulsar.SFTdataFind(self.sftfilepattern, constraints)
442

Gregory Ashton's avatar
Gregory Ashton committed
443
        SFT_timestamps = [d.header.epoch for d in SFTCatalog.data]
Gregory Ashton's avatar
Gregory Ashton committed
444
        self.SFT_timestamps = [float(s) for s in SFT_timestamps]
445
446
        if len(SFT_timestamps) == 0:
            raise ValueError('Failed to load any data')
Gregory Ashton's avatar
Gregory Ashton committed
447
448
449
450
451
        if args.quite is False and args.no_interactive is False:
            try:
                from bashplotlib.histogram import plot_hist
                print('Data timestamps histogram:')
                plot_hist(SFT_timestamps, height=5, bincount=50)
Gregory Ashton's avatar
Gregory Ashton committed
452
            except ImportError:
Gregory Ashton's avatar
Gregory Ashton committed
453
                pass
454

455
        cl_tconv1 = 'lalapps_tconvert {}'.format(int(SFT_timestamps[0]))
456
457
        output = helper_functions.run_commandline(cl_tconv1,
                                                  log_level=logging.DEBUG)
458
459
        tconvert1 = output.rstrip('\n')
        cl_tconv2 = 'lalapps_tconvert {}'.format(int(SFT_timestamps[-1]))
460
461
        output = helper_functions.run_commandline(cl_tconv2,
                                                  log_level=logging.DEBUG)
462
        tconvert2 = output.rstrip('\n')
Gregory Ashton's avatar
Gregory Ashton committed
463
464
        logging.info('Data spans from {} ({}) to {} ({})'.format(
            int(SFT_timestamps[0]),
465
            tconvert1,
Gregory Ashton's avatar
Gregory Ashton committed
466
            int(SFT_timestamps[-1]),
467
            tconvert2))
468
469
470
471
472
473
474
475
476
477
478
479
480

        if self.minStartTime is None:
            self.minStartTime = int(SFT_timestamps[0])
        if self.maxStartTime is None:
            self.maxStartTime = int(SFT_timestamps[-1])

        detector_names = list(set([d.header.name for d in SFTCatalog.data]))
        self.detector_names = detector_names
        if len(detector_names) == 0:
            raise ValueError('No data loaded.')
        logging.info('Loaded {} data files from detectors {}'.format(
            len(SFT_timestamps), detector_names))

481
        return SFTCatalog
Gregory Ashton's avatar
Gregory Ashton committed
482
483
484
485

    def init_computefstatistic_single_point(self):
        """ Initilisation step of run_computefstatistic for a single point """

486
        SFTCatalog = self._get_SFTCatalog()
Gregory Ashton's avatar
Gregory Ashton committed
487
488
489
490
491
492

        logging.info('Initialising ephems')
        ephems = lalpulsar.InitBarycenter(self.earth_ephem, self.sun_ephem)

        logging.info('Initialising FstatInput')
        dFreq = 0
David Keitel's avatar
David Keitel committed
493
        if self.transientWindowType:
Gregory Ashton's avatar
Gregory Ashton committed
494
495
496
497
498
499
            self.whatToCompute = lalpulsar.FSTATQ_ATOMS_PER_DET
        else:
            self.whatToCompute = lalpulsar.FSTATQ_2F

        FstatOAs = lalpulsar.FstatOptionalArgs()
        FstatOAs.randSeed = lalpulsar.FstatOptionalArgsDefaults.randSeed
500
501
502
503
504
        if self.SSBprec:
            logging.info('Using SSBprec={}'.format(self.SSBprec))
            FstatOAs.SSBprec = self.SSBprec
        else:
            FstatOAs.SSBprec = lalpulsar.FstatOptionalArgsDefaults.SSBprec
Gregory Ashton's avatar
Gregory Ashton committed
505
506
507
        FstatOAs.Dterms = lalpulsar.FstatOptionalArgsDefaults.Dterms
        FstatOAs.runningMedianWindow = lalpulsar.FstatOptionalArgsDefaults.runningMedianWindow
        FstatOAs.FstatMethod = lalpulsar.FstatOptionalArgsDefaults.FstatMethod
508
509
510
511
512
513
514
515
        if self.assumeSqrtSX is None:
            FstatOAs.assumeSqrtSX = lalpulsar.FstatOptionalArgsDefaults.assumeSqrtSX
        else:
            mnf = lalpulsar.MultiNoiseFloor()
            assumeSqrtSX = np.atleast_1d(self.assumeSqrtSX)
            mnf.sqrtSn[:len(assumeSqrtSX)] = assumeSqrtSX
            mnf.length = len(assumeSqrtSX)
            FstatOAs.assumeSqrtSX = mnf
Gregory Ashton's avatar
Gregory Ashton committed
516
517
518
        FstatOAs.prevInput = lalpulsar.FstatOptionalArgsDefaults.prevInput
        FstatOAs.collectTiming = lalpulsar.FstatOptionalArgsDefaults.collectTiming

Gregory Ashton's avatar
Gregory Ashton committed
519
        if hasattr(self, 'injectSources') and type(self.injectSources) == dict:
Gregory Ashton's avatar
Gregory Ashton committed
520
521
522
523
524
525
526
527
528
529
            logging.info('Injecting source with params: {}'.format(
                self.injectSources))
            PPV = lalpulsar.CreatePulsarParamsVector(1)
            PP = PPV.data[0]
            PP.Amp.h0 = self.injectSources['h0']
            PP.Amp.cosi = self.injectSources['cosi']
            PP.Amp.phi0 = self.injectSources['phi0']
            PP.Amp.psi = self.injectSources['psi']
            PP.Doppler.Alpha = self.injectSources['Alpha']
            PP.Doppler.Delta = self.injectSources['Delta']
Gregory Ashton's avatar
Gregory Ashton committed
530
531
532
533
534
535
            if 'fkdot' in self.injectSources:
                PP.Doppler.fkdot = np.array(self.injectSources['fkdot'])
            else:
                PP.Doppler.fkdot = np.zeros(lalpulsar.PULSAR_MAX_SPINS)
                for i, key in enumerate(['F0', 'F1', 'F2']):
                    PP.Doppler.fkdot[i] = self.injectSources[key]
Gregory Ashton's avatar
Gregory Ashton committed
536
537
538
539
            PP.Doppler.refTime = self.tref
            if 't0' not in self.injectSources:
                PP.Transient.type = lalpulsar.TRANSIENT_NONE
            FstatOAs.injectSources = PPV
Gregory Ashton's avatar
Gregory Ashton committed
540
        elif hasattr(self, 'injectSources') and type(self.injectSources) == str:
541
542
543
544
            logging.info('Injecting source from param file: {}'.format(
                self.injectSources))
            PPV = lalpulsar.PulsarParamsFromFile(self.injectSources, self.tref)
            FstatOAs.injectSources = PPV
Gregory Ashton's avatar
Gregory Ashton committed
545
546
        else:
            FstatOAs.injectSources = lalpulsar.FstatOptionalArgsDefaults.injectSources
547
548
549
550
        if hasattr(self, 'injectSqrtSX') and self.injectSqrtSX is not None:
            raise ValueError('injectSqrtSX not implemented')
        else:
            FstatOAs.InjectSqrtSX = lalpulsar.FstatOptionalArgsDefaults.injectSqrtSX
Gregory Ashton's avatar
Gregory Ashton committed
551
        if self.minCoverFreq is None or self.maxCoverFreq is None:
552
            fAs = [d.header.f0 for d in SFTCatalog.data]
Gregory Ashton's avatar
Gregory Ashton committed
553
            fBs = [d.header.f0 + (d.numBins-1)*d.header.deltaF
554
                   for d in SFTCatalog.data]
Gregory Ashton's avatar
Gregory Ashton committed
555
556
557
558
559
560
            self.minCoverFreq = np.min(fAs) + 0.5
            self.maxCoverFreq = np.max(fBs) - 0.5
            logging.info('Min/max cover freqs not provided, using '
                         '{} and {}, est. from SFTs'.format(
                             self.minCoverFreq, self.maxCoverFreq))

561
        self.FstatInput = lalpulsar.CreateFstatInput(SFTCatalog,
Gregory Ashton's avatar
Gregory Ashton committed
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
                                                     self.minCoverFreq,
                                                     self.maxCoverFreq,
                                                     dFreq,
                                                     ephems,
                                                     FstatOAs
                                                     )

        logging.info('Initialising PulsarDoplerParams')
        PulsarDopplerParams = lalpulsar.PulsarDopplerParams()
        PulsarDopplerParams.refTime = self.tref
        PulsarDopplerParams.Alpha = 1
        PulsarDopplerParams.Delta = 1
        PulsarDopplerParams.fkdot = np.array([0, 0, 0, 0, 0, 0, 0])
        self.PulsarDopplerParams = PulsarDopplerParams

        logging.info('Initialising FstatResults')
        self.FstatResults = lalpulsar.FstatResults()

        if self.BSGL:
            if len(self.detector_names) < 2:
582
                raise ValueError("Can't use BSGL with single detectors data")
Gregory Ashton's avatar
Gregory Ashton committed
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
            else:
                logging.info('Initialising BSGL')

            # Tuning parameters - to be reviewed
            numDetectors = 2
            if hasattr(self, 'nsegs'):
                p_val_threshold = 1e-6
                Fstar0s = np.linspace(0, 1000, 10000)
                p_vals = scipy.special.gammaincc(2*self.nsegs, Fstar0s)
                Fstar0 = Fstar0s[np.argmin(np.abs(p_vals - p_val_threshold))]
                if Fstar0 == Fstar0s[-1]:
                    raise ValueError('Max Fstar0 exceeded')
            else:
                Fstar0 = 15.
            logging.info('Using Fstar0 of {:1.2f}'.format(Fstar0))
            oLGX = np.zeros(10)
            oLGX[:numDetectors] = 1./numDetectors
            self.BSGLSetup = lalpulsar.CreateBSGLSetup(numDetectors,
                                                       Fstar0,
                                                       oLGX,
                                                       True,
                                                       1)
            self.twoFX = np.zeros(10)
            self.whatToCompute = (self.whatToCompute +
                                  lalpulsar.FSTATQ_2F_PER_DET)

David Keitel's avatar
David Keitel committed
609
        if self.transientWindowType:
Gregory Ashton's avatar
Gregory Ashton committed
610
611
            logging.info('Initialising transient parameters')
            self.windowRange = lalpulsar.transientWindowRange_t()
David Keitel's avatar
David Keitel committed
612
613
614
615
616
617
            transientWindowTypes = {'none': lalpulsar.TRANSIENT_NONE,
                                    'rect': lalpulsar.TRANSIENT_RECTANGULAR,
                                    'exp':  lalpulsar.TRANSIENT_EXPONENTIAL}
            if self.transientWindowType in transientWindowTypes:
                self.windowRange.type = transientWindowTypes[self.transientWindowType]
            else:
Gregory Ashton's avatar
Gregory Ashton committed
618
619
620
621
                raise ValueError(
                    'Unknown window-type ({}) passed as input, [{}] allows.'
                    .format(self.transientWindowType,
                            ', '.join(transientWindowTypes)))
David Keitel's avatar
David Keitel committed
622

623
            # default spacing
David Keitel's avatar
David Keitel committed
624
            self.Tsft = int(1.0/SFTCatalog.data[0].header.deltaF)
625
626
627
628
629
630
            self.windowRange.dt0 = self.Tsft
            self.windowRange.dtau = self.Tsft

            # special treatment of window_type = none ==> replace by rectangular window spanning all the data
            if self.windowRange.type == lalpulsar.TRANSIENT_NONE:
                self.windowRange.t0 = int(self.minStartTime)
Gregory Ashton's avatar
Gregory Ashton committed
631
                self.windowRange.t0Band = 0
632
                self.windowRange.tau = int(self.maxStartTime-self.minStartTime)
David Keitel's avatar
David Keitel committed
633
                self.windowRange.tauBand = 0
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
            else: # user-set bands and spacings
                if self.t0Band is None:
                    self.windowRange.t0Band = 0
                else:
                    if not isinstance(self.t0Band, int):
                        logging.warn('Casting non-integer t0Band={} to int...'
                                     .format(self.t0Band))
                        self.t0Band = int(self.t0Band)
                    self.windowRange.t0Band = self.t0Band
                    if self.dt0:
                        self.windowRange.dt0 = self.dt0
                if self.tauBand is None:
                    self.windowRange.tauBand = 0
                else:
                    if not isinstance(self.tauBand, int):
                        logging.warn('Casting non-integer tauBand={} to int...'
                                     .format(self.tauBand))
                        self.tauBand = int(self.tauBand)
                    self.windowRange.tauBand = self.tauBand
                    if self.dtau:
                        self.windowRange.dtau = self.dtau
Gregory Ashton's avatar
Gregory Ashton committed
655

656
657
658
    def get_fullycoherent_twoF(self, tstart, tend, F0, F1, F2, Alpha, Delta,
                               asini=None, period=None, ecc=None, tp=None,
                               argp=None):
Gregory Ashton's avatar
Gregory Ashton committed
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
        """ Returns twoF or ln(BSGL) fully-coherently at a single point """
        self.PulsarDopplerParams.fkdot = np.array([F0, F1, F2, 0, 0, 0, 0])
        self.PulsarDopplerParams.Alpha = Alpha
        self.PulsarDopplerParams.Delta = Delta
        if self.binary:
            self.PulsarDopplerParams.asini = asini
            self.PulsarDopplerParams.period = period
            self.PulsarDopplerParams.ecc = ecc
            self.PulsarDopplerParams.tp = tp
            self.PulsarDopplerParams.argp = argp

        lalpulsar.ComputeFstat(self.FstatResults,
                               self.FstatInput,
                               self.PulsarDopplerParams,
                               1,
                               self.whatToCompute
                               )

David Keitel's avatar
David Keitel committed
677
        if not self.transientWindowType:
Gregory Ashton's avatar
Gregory Ashton committed
678
679
680
681
682
683
684
685
686
687
688
            if self.BSGL is False:
                return self.FstatResults.twoF[0]

            twoF = np.float(self.FstatResults.twoF[0])
            self.twoFX[0] = self.FstatResults.twoFPerDet(0)
            self.twoFX[1] = self.FstatResults.twoFPerDet(1)
            log10_BSGL = lalpulsar.ComputeBSGL(twoF, self.twoFX,
                                               self.BSGLSetup)
            return log10_BSGL/np.log10(np.exp(1))

        self.windowRange.t0 = int(tstart)  # TYPE UINT4
David Keitel's avatar
David Keitel committed
689
690
691
692
693
        if self.windowRange.tauBand == 0:
            # true single-template search also in transient params:
            # actual (t0,tau) window was set with tstart, tend before
            self.windowRange.tau = int(tend - tstart)  # TYPE UINT4
        else:
Gregory Ashton's avatar
Gregory Ashton committed
694
695
            # grid search: start at minimum tau required for nondegenerate
            # F-stat computation
David Keitel's avatar
David Keitel committed
696
            self.windowRange.tau = int(2*self.Tsft)
Gregory Ashton's avatar
Gregory Ashton committed
697

698
        self.FstatMap = lalpulsar.ComputeTransientFstatMap(
Gregory Ashton's avatar
Gregory Ashton committed
699
            self.FstatResults.multiFatoms[0], self.windowRange, False)
700
        F_mn = self.FstatMap.F_mn.data
Gregory Ashton's avatar
Gregory Ashton committed
701

702
        twoF = 2*np.max(F_mn)
Gregory Ashton's avatar
Gregory Ashton committed
703
        if self.BSGL is False:
704
705
706
707
            if np.isnan(twoF):
                return 0
            else:
                return twoF
Gregory Ashton's avatar
Gregory Ashton committed
708
709
710
711
712
713
714
715
716
717

        FstatResults_single = copy.copy(self.FstatResults)
        FstatResults_single.lenth = 1
        FstatResults_single.data = self.FstatResults.multiFatoms[0].data[0]
        FS0 = lalpulsar.ComputeTransientFstatMap(
            FstatResults_single.multiFatoms[0], self.windowRange, False)
        FstatResults_single.data = self.FstatResults.multiFatoms[0].data[1]
        FS1 = lalpulsar.ComputeTransientFstatMap(
            FstatResults_single.multiFatoms[0], self.windowRange, False)

718
719
720
721
722
        # for now, use the Doppler parameter with
        # multi-detector F maximised over t0,tau
        # to return BSGL
        # FIXME: should we instead compute BSGL over the whole F_mn
        # and return the maximum of that?
723
        idx_maxTwoF = np.argmax(F_mn)
724
725
726

        self.twoFX[0] = 2*FS0.F_mn.data[idx_maxTwoF]
        self.twoFX[1] = 2*FS1.F_mn.data[idx_maxTwoF]
Gregory Ashton's avatar
Gregory Ashton committed
727
        log10_BSGL = lalpulsar.ComputeBSGL(
728
                twoF, self.twoFX, self.BSGLSetup)
Gregory Ashton's avatar
Gregory Ashton committed
729
730
731
732
733
734

        return log10_BSGL/np.log10(np.exp(1))

    def calculate_twoF_cumulative(self, F0, F1, F2, Alpha, Delta, asini=None,
                                  period=None, ecc=None, tp=None, argp=None,
                                  tstart=None, tend=None, npoints=1000,
735
736
                                  ):
        """ Calculate the cumulative twoF along the obseration span
737
738
739

        Parameters
        ----------
740
741
        F0, F1, F2, Alpha, Delta: float
            Parameters at which to compute the cumulative twoF
742
743
        asini, period, ecc, tp, argp: float, optional
            Binary parameters at which to compute the cumulative 2F
744
745
746
747
748
749
        tstart, tend: int
            GPS times to restrict the range of data used - automatically
            truncated to the span of data available
        npoints: int
            Number of points to compute twoF along the span

750
751
752
        Notes
        -----
        The minimum cumulatibe twoF is hard-coded to be computed over
753
754
755
756
757
758
        the first 6 hours from either the first timestampe in the data (if
        tstart is smaller than it) or tstart.

        """
        SFTminStartTime = self.SFT_timestamps[0]
        SFTmaxStartTime = self.SFT_timestamps[-1]
Gregory Ashton's avatar
Gregory Ashton committed
759
        tstart = np.max([SFTminStartTime, tstart])
760
761
762
        min_tau = np.max([SFTminStartTime - tstart, 0]) + 3600*6
        max_tau = SFTmaxStartTime - tstart
        taus = np.linspace(min_tau, max_tau, npoints)
Gregory Ashton's avatar
Gregory Ashton committed
763
        twoFs = []
David Keitel's avatar
David Keitel committed
764
765
766
        if not self.transientWindowType:
            # still call the transient-Fstat-map function, but using the full range
            self.transientWindowType = 'none'
Gregory Ashton's avatar
Gregory Ashton committed
767
768
            self.init_computefstatistic_single_point()
        for tau in taus:
769
            detstat = self.get_fullycoherent_twoF(
Gregory Ashton's avatar
Gregory Ashton committed
770
771
                tstart=tstart, tend=tstart+tau, F0=F0, F1=F1, F2=F2,
                Alpha=Alpha, Delta=Delta, asini=asini, period=period, ecc=ecc,
772
773
                tp=tp, argp=argp)
            twoFs.append(detstat)
Gregory Ashton's avatar
Gregory Ashton committed
774
775
776

        return taus, np.array(twoFs)

777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
    def _calculate_predict_fstat_cumulative(self, N, label=None, outdir=None,
                                            IFO=None, pfs_input=None):
        """ Calculates the predicted 2F and standard deviation cumulatively

        Parameters
        ----------
        N : int
            Number of timesteps to use between minStartTime and maxStartTime.
        label, outdir : str, optional
            The label and directory to read in the .loudest file from
        IFO : str
        pfs_input : dict, optional
            Input kwargs to predict_fstat (alternative to giving label and
            outdir).

        Returns
        -------
        times, pfs, pfs_sigma : ndarray, size (N,)

        """
Gregory Ashton's avatar
Gregory Ashton committed
797
798
799
800
801

        if pfs_input is None:
            if os.path.isfile('{}/{}.loudest'.format(outdir, label)) is False:
                raise ValueError(
                    'Need a loudest file to add the predicted Fstat')
802
            loudest = read_par(label=label, outdir=outdir, suffix='loudest')
Gregory Ashton's avatar
Gregory Ashton committed
803
804
            pfs_input = {key: loudest[key] for key in
                         ['h0', 'cosi', 'psi', 'Alpha', 'Delta', 'Freq']}
805
806
807
        times = np.linspace(self.minStartTime, self.maxStartTime, N+1)[1:]
        times = np.insert(times, 0, self.minStartTime + 86400/2.)
        out = [predict_fstat(minStartTime=self.minStartTime, maxStartTime=t,
808
                             sftfilepattern=self.sftfilepattern, IFO=IFO,
809
810
811
812
                             **pfs_input) for t in times]
        pfs, pfs_sigma = np.array(out).T
        return times, pfs, pfs_sigma

813
814
    def plot_twoF_cumulative(self, label, outdir, add_pfs=False, N=15,
                             injectSources=None, ax=None, c='k', savefig=True,
815
                             title=None, plt_label=None, **kwargs):
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
        """ Plot the twoF value cumulatively

        Parameters
        ----------
        label, outdir : str
        add_pfs : bool
            If true, plot the predicted 2F and standard deviation
        N : int
            Number of points to use
        injectSources : dict
            See `ComputeFstat`
        ax : matplotlib.axes._subplots_AxesSubplot, optional
            Axis to add the plot to.
        c : str
            Colour
        savefig : bool
            If true, save the figure in outdir
833
834
        title, plt_label: str
            Figure title and label
835
836
837
838
839
840
841
842
843

        Returns
        -------
        tauS, tauF : ndarray shape (N,)
            If savefig, the times and twoF (cumulative) values
        ax : matplotlib.axes._subplots_AxesSubplot, optional
            If savefig is False

        """
Gregory Ashton's avatar
Gregory Ashton committed
844
845
        if ax is None:
            fig, ax = plt.subplots()
Gregory Ashton's avatar
Gregory Ashton committed
846
847
848
849
850
851
852
        if injectSources:
            pfs_input = dict(
                h0=injectSources['h0'], cosi=injectSources['cosi'],
                psi=injectSources['psi'], Alpha=injectSources['Alpha'],
                Delta=injectSources['Delta'], Freq=injectSources['fkdot'][0])
        else:
            pfs_input = None
853
854

        taus, twoFs = self.calculate_twoF_cumulative(**kwargs)
855
        ax.plot(taus/86400., twoFs, label=plt_label, color=c)
856
        if len(self.detector_names) > 1:
857
858
            detector_names = self.detector_names
            detectors = self.detectors
859
860
861
862
            for d in self.detector_names:
                self.detectors = d
                self.init_computefstatistic_single_point()
                taus, twoFs = self.calculate_twoF_cumulative(**kwargs)
863
864
865
866
867
868
                ax.plot(taus/86400., twoFs, label='{}'.format(d),
                        color=detector_colors[d.lower()])
            self.detectors = detectors
            self.detector_names = detector_names

        if add_pfs:
869
870
            times, pfs, pfs_sigma = self._calculate_predict_fstat_cumulative(
                N=N, label=label, outdir=outdir, pfs_input=pfs_input)
871
872
            ax.fill_between(
                (times-self.minStartTime)/86400., pfs-pfs_sigma, pfs+pfs_sigma,
Gregory Ashton's avatar
Gregory Ashton committed
873
                color=c,
874
875
                label=(r'Predicted $\langle 2\mathcal{F} '
                       r'\rangle\pm $ 1-$\sigma$ band'),
876
877
878
                zorder=-10, alpha=0.2)
            if len(self.detector_names) > 1:
                for d in self.detector_names:
879
880
881
882
                    out = self._calculate_predict_fstat_cumulative(
                        N=N, label=label, outdir=outdir, IFO=d.upper(),
                        pfs_input=pfs_input)
                    times, pfs, pfs_sigma = out
883
884
885
886
887
888
889
890
                    ax.fill_between(
                        (times-self.minStartTime)/86400., pfs-pfs_sigma,
                        pfs+pfs_sigma, color=detector_colors[d.lower()],
                        alpha=0.5,
                        label=(
                            'Predicted $2\mathcal{{F}}$ 1-$\sigma$ band ({})'
                            .format(d.upper())),
                        zorder=-10)
891

Gregory Ashton's avatar
Gregory Ashton committed
892
893
894
895
896
897
898
        ax.set_xlabel(r'Days from $t_{{\rm start}}={:.0f}$'.format(
            kwargs['tstart']))
        if self.BSGL:
            ax.set_ylabel(r'$\log_{10}(\mathrm{BSGL})_{\rm cumulative}$')
        else:
            ax.set_ylabel(r'$\widetilde{2\mathcal{F}}_{\rm cumulative}$')
        ax.set_xlim(0, taus[-1]/86400)
899
900
        if plt_label:
            ax.legend(frameon=False, loc=2, fontsize=6)
Gregory Ashton's avatar
Gregory Ashton committed
901
902
903
904
905
906
907
908
909
        if title:
            ax.set_title(title)
        if savefig:
            plt.tight_layout()
            plt.savefig('{}/{}_twoFcumulative.png'.format(outdir, label))
            return taus, twoFs
        else:
            return ax

910
911
912
913
914
915
916
917
918
919
920
921
    def write_atoms_to_file(self, fnamebase=''):
        multiFatoms = getattr(self.FstatResults, 'multiFatoms', None)
        if multiFatoms and multiFatoms[0]:
            dopplerName = lalpulsar.PulsarDopplerParams2String ( self.PulsarDopplerParams )
            #fnameAtoms = os.path.join(self.outdir,'Fstatatoms_%s.dat' % dopplerName)
            fnameAtoms = fnamebase + '_Fstatatoms_%s.dat' % dopplerName
            fo = lal.FileOpen(fnameAtoms, 'w')
            lalpulsar.write_MultiFstatAtoms_to_fp ( fo, multiFatoms[0] )
            del fo # instead of lal.FileClose() which is not SWIG-exported
        else:
            raise RuntimeError('Cannot print atoms vector to file: no FstatResults.multiFatoms, or it is None!')

Gregory Ashton's avatar
Gregory Ashton committed
922

923
class SemiCoherentSearch(ComputeFstat):
Gregory Ashton's avatar
Gregory Ashton committed
924
925
926
    """ A semi-coherent search """

    @helper_functions.initializer
927
    def __init__(self, label, outdir, tref, nsegs=None, sftfilepattern=None,
Gregory Ashton's avatar
Gregory Ashton committed
928
929
                 binary=False, BSGL=False, minStartTime=None,
                 maxStartTime=None, minCoverFreq=None, maxCoverFreq=None,
930
931
                 detectors=None, injectSources=None, assumeSqrtSX=None,
                 SSBprec=None):
Gregory Ashton's avatar
Gregory Ashton committed
932
933
934
935
936
937
938
939
940
        """
        Parameters
        ----------
        label, outdir: str
            A label and directory to read/write data from/to.
        tref, minStartTime, maxStartTime: int
            GPS seconds of the reference time, and start and end of the data.
        nsegs: int
            The (fixed) number of segments
941
942
943
        sftfilepattern: str
            Pattern to match SFTs using wildcards (*?) and ranges [0-9];
            mutiple patterns can be given separated by colons.
Gregory Ashton's avatar
Gregory Ashton committed
944
945
946
947
948

        For all other parameters, see pyfstat.ComputeFStat.
        """

        self.fs_file_name = "{}/{}_FS.dat".format(self.outdir, self.label)
949
        self.set_ephemeris_files()
David Keitel's avatar
David Keitel committed
950
951
952
        self.transientWindowType = 'rect'
        self.t0Band  = None
        self.tauBand = None
Gregory Ashton's avatar
Gregory Ashton committed
953
954
955
956
957
958
959
        self.init_computefstatistic_single_point()
        self.init_semicoherent_parameters()

    def init_semicoherent_parameters(self):
        logging.info(('Initialising semicoherent parameters from {} to {} in'
                      ' {} segments').format(
            self.minStartTime, self.maxStartTime, self.nsegs))
David Keitel's avatar
David Keitel committed
960
        self.transientWindowType = 'rect'
Gregory Ashton's avatar
Gregory Ashton committed
961
962
963
        self.whatToCompute = lalpulsar.FSTATQ_2F+lalpulsar.FSTATQ_ATOMS_PER_DET
        self.tboundaries = np.linspace(self.minStartTime, self.maxStartTime,
                                       self.nsegs+1)
964
        self.Tcoh = self.tboundaries[1] - self.tboundaries[0]
Gregory Ashton's avatar
Gregory Ashton committed
965

966
967
968
969
970
971
972
973
974
        if hasattr(self, 'SFT_timestamps'):
            if self.tboundaries[0] < self.SFT_timestamps[0]:
                logging.debug(
                    'Semi-coherent start time {} before first SFT timestamp {}'
                    .format(self.tboundaries[0], self.SFT_timestamps[0]))
            if self.tboundaries[-1] > self.SFT_timestamps[-1]:
                logging.debug(
                    'Semi-coherent end time {} after last SFT timestamp {}'
                    .format(self.tboundaries[-1], self.SFT_timestamps[-1]))
Gregory Ashton's avatar
Gregory Ashton committed
975

976
    def get_semicoherent_twoF(
977
978
979
980
981
            self, F0, F1, F2, Alpha, Delta, asini=None,
            period=None, ecc=None, tp=None, argp=None,
            record_segments=False):
        """ Returns twoF or ln(BSGL) semi-coherently at a single point """

Gregory Ashton's avatar
Gregory Ashton committed
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
        self.PulsarDopplerParams.fkdot = np.array([F0, F1, F2, 0, 0, 0, 0])
        self.PulsarDopplerParams.Alpha = Alpha
        self.PulsarDopplerParams.Delta = Delta
        if self.binary:
            self.PulsarDopplerParams.asini = asini
            self.PulsarDopplerParams.period = period
            self.PulsarDopplerParams.ecc = ecc
            self.PulsarDopplerParams.tp = tp
            self.PulsarDopplerParams.argp = argp

        lalpulsar.ComputeFstat(self.FstatResults,
                               self.FstatInput,
                               self.PulsarDopplerParams,
                               1,
                               self.whatToCompute
                               )

David Keitel's avatar
David Keitel committed
999
        #if not self.transientWindowType:
1000
1001
1002
1003
1004
1005
1006
1007
        #    if self.BSGL is False:
        #        return self.FstatResults.twoF[0]
        #    twoF = np.float(self.FstatResults.twoF[0])
        #    self.twoFX[0] = self.FstatResults.twoFPerDet(0)
        #    self.twoFX[1] = self.FstatResults.twoFPerDet(1)
        #    log10_BSGL = lalpulsar.ComputeBSGL(twoF, self.twoFX,
        #                                       self.BSGLSetup)
        #    return log10_BSGL/np.log10(np.exp(1))
Gregory Ashton's avatar
Gregory Ashton committed
1008
1009

        detStat = 0
1010
1011
        if record_segments:
            self.detStat_per_segment = []
Gregory Ashton's avatar
Gregory Ashton committed
1012

1013
1014
1015
        self.windowRange.tau = int(self.Tcoh)  # TYPE UINT4
        for tstart in self.tboundaries[:-1]:
            d_detStat = self._get_per_segment_det_stat(tstart)
1016
1017
1018
            detStat += d_detStat
            if record_segments:
                self.detStat_per_segment.append(d_detStat)
Gregory Ashton's avatar
Gregory Ashton committed
1019
1020
1021

        return detStat

1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
    def _get_per_segment_det_stat(self, tstart):
        self.windowRange.t0 = int(tstart)  # TYPE UINT4

        FS = lalpulsar.ComputeTransientFstatMap(
            self.FstatResults.multiFatoms[0], self.windowRange, False)

        if self.BSGL is False:
            d_detStat = 2*FS.F_mn.data[0][0]
        else:
            FstatResults_single = copy.copy(self.FstatResults)
            FstatResults_single.lenth = 1
            FstatResults_single.data = self.FstatResults.multiFatoms[0].data[0]
            FS0 = lalpulsar.ComputeTransientFstatMap(
                FstatResults_single.multiFatoms[0], self.windowRange, False)
            FstatResults_single.data = self.FstatResults.multiFatoms[0].data[1]
            FS1 = lalpulsar.ComputeTransientFstatMap(
                FstatResults_single.multiFatoms[0], self.windowRange, False)

            self.twoFX[0] = 2*FS0.F_mn.data[0][0]
            self.twoFX[1] = 2*FS1.F_mn.data[0][0]
            log10_BSGL = lalpulsar.ComputeBSGL(
                    2*FS.F_mn.data[0][0], self.twoFX, self.BSGLSetup)
            d_detStat = log10_BSGL/np.log10(np.exp(1))
        if np.isnan(d_detStat):
            logging.debug('NaNs in semi-coherent twoF treated as zero')
            d_detStat = 0

        return d_detStat

Gregory Ashton's avatar
Gregory Ashton committed
1051

1052
class SemiCoherentGlitchSearch(ComputeFstat):
Gregory Ashton's avatar
Gregory Ashton committed
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
    """ A semi-coherent glitch search

    This implements a basic `semi-coherent glitch F-stat in which the data
    is divided into segments either side of the proposed glitches and the
    fully-coherent F-stat in each segment is summed to give the semi-coherent
    F-stat
    """

    @helper_functions.initializer
    def __init__(self, label, outdir, tref, minStartTime, maxStartTime,
1063
                 nglitch=1, sftfilepattern=None, theta0_idx=0, BSGL=False,
1064
                 minCoverFreq=None, maxCoverFreq=None, assumeSqrtSX=None,
1065
                 detectors=None, SSBprec=None, injectSources=None):
Gregory Ashton's avatar
Gregory Ashton committed
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
        """
        Parameters
        ----------
        label, outdir: str
            A label and directory to read/write data from/to.
        tref, minStartTime, maxStartTime: int
            GPS seconds of the reference time, and start and end of the data.
        nglitch: int
            The (fixed) number of glitches; this can zero, but occasionally
            this causes issue (in which case just use ComputeFstat).
1076
1077
1078
        sftfilepattern: str
            Pattern to match SFTs using wildcards (*?) and ranges [0-9];
            mutiple patterns can be given separated by colons.
Gregory Ashton's avatar
Gregory Ashton committed
1079
1080
1081
1082
1083
1084
1085
1086
1087
        theta0_idx, int
            Index (zero-based) of which segment the theta refers to - uyseful
            if providing a tight prior on theta to allow the signal to jump
            too theta (and not just from)

        For all other parameters, see pyfstat.ComputeFStat.
        """

        self.fs_file_name = "{}/{}_FS.dat".format(self.outdir, self.label)
1088
        self.set_ephemeris_files()
David Keitel's avatar
David Keitel committed
1089
1090
1091
1092
        self.transientWindowType = 'rect'
        self.t0Band  = None
        self.tauBand = None
        self.binary  = False
Gregory Ashton's avatar
Gregory Ashton committed
1093
1094
        self.init_computefstatistic_single_point()

1095
    def get_semicoherent_nglitch_twoF(self, F0, F1, F2, Alpha, Delta, *args):
Gregory Ashton's avatar
Gregory Ashton committed
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
        """ Returns the semi-coherent glitch summed twoF """

        args = list(args)
        tboundaries = ([self.minStartTime] + args[-self.nglitch:]
                       + [self.maxStartTime])
        delta_F0s = args[-3*self.nglitch:-2*self.nglitch]
        delta_F1s = args[-2*self.nglitch:-self.nglitch]
        delta_F2 = np.zeros(len(delta_F0s))
        delta_phi = np.zeros(len(delta_F0s))
        theta = [0, F0, F1, F2]
        delta_thetas = np.atleast_2d(
                np.array([delta_phi, delta_F0s, delta_F1s, delta_F2]).T)

1109
        thetas = self._calculate_thetas(theta, delta_thetas, tboundaries,
1110
                                        theta0_idx=self.theta0_idx)
Gregory Ashton's avatar
Gregory Ashton committed
1111
1112
1113
1114

        twoFSum = 0
        for i, theta_i_at_tref in enumerate(thetas):
            ts, te = tboundaries[i], tboundaries[i+1]
1115
            if te - ts > 1800:
1116
1117
1118
1119
                twoFVal = self.get_fullycoherent_twoF(
                    ts, te, theta_i_at_tref[1], theta_i_at_tref[2],
                    theta_i_at_tref[3], Alpha, Delta)
                twoFSum += twoFVal
Gregory Ashton's avatar
Gregory Ashton committed
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136

        if np.isfinite(twoFSum):
            return twoFSum
        else:
            return -np.inf

    def compute_glitch_fstat_single(self, F0, F1, F2, Alpha, Delta, delta_F0,
                                    delta_F1, tglitch):
        """ Returns the semi-coherent glitch summed twoF for nglitch=1

        Note: OBSOLETE, used only for testing
        """

        theta = [F0, F1, F2]
        delta_theta = [delta_F0, delta_F1, 0]
        tref = self.tref

1137
        theta_at_glitch = self._shift_coefficients(theta, tglitch - tref)
Gregory Ashton's avatar
Gregory Ashton committed
1138
        theta_post_glitch_at_glitch = theta_at_glitch + delta_theta
1139
        theta_post_glitch = self._shift_coefficients(
Gregory Ashton's avatar
Gregory Ashton committed
1140
1141
            theta_post_glitch_at_glitch, tref - tglitch)

1142
        twoFsegA = self.get_fullycoherent_twoF(
Gregory Ashton's avatar
Gregory Ashton committed
1143
1144
1145
1146
1147
1148
            self.minStartTime, tglitch, theta[0], theta[1], theta[2], Alpha,
            Delta)

        if tglitch == self.maxStartTime:
            return twoFsegA

1149
        twoFsegB = self.get_fullycoherent_twoF(
Gregory Ashton's avatar
Gregory Ashton committed
1150
1151
1152
1153
1154
            tglitch, self.maxStartTime, theta_post_glitch[0],
            theta_post_glitch[1], theta_post_glitch[2], Alpha,
            Delta)

        return twoFsegA + twoFsegB