grid_based_searches.py 41.7 KB
Newer Older
Gregory Ashton's avatar
Gregory Ashton committed
1
""" Searches using grid-based methods """
2
from __future__ import division, absolute_import, print_function
Gregory Ashton's avatar
Gregory Ashton committed
3
4
5
6
7

import os
import logging
import itertools
from collections import OrderedDict
Gregory Ashton's avatar
Gregory Ashton committed
8
9
10
import datetime
import getpass
import socket
Gregory Ashton's avatar
Gregory Ashton committed
11
12
13
14

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
15
from scipy.misc import logsumexp
Gregory Ashton's avatar
Gregory Ashton committed
16

17
18
19
import pyfstat.helper_functions as helper_functions
from pyfstat.core import (BaseSearchClass, ComputeFstat,
                          SemiCoherentGlitchSearch, SemiCoherentSearch, tqdm,
20
                          args, read_par)
Gregory Ashton's avatar
Gregory Ashton committed
21
22
import lalpulsar
import lal
Gregory Ashton's avatar
Gregory Ashton committed
23
24
25
26


class GridSearch(BaseSearchClass):
    """ Gridded search using ComputeFstat """
Gregory Ashton's avatar
Gregory Ashton committed
27
28
29
    tex_labels = {'F0': '$f$', 'F1': '$\dot{f}$', 'F2': '$\ddot{f}$',
                  'Alpha': r'$\alpha$', 'Delta': r'$\delta$'}
    tex_labels0 = {'F0': '$-f_0$', 'F1': '$-\dot{f}_0$', 'F2': '$-\ddot{f}_0$',
30
                   'Alpha': r'$-\alpha_0$', 'Delta': r'$-\delta_0$'}
Gregory Ashton's avatar
Gregory Ashton committed
31

Gregory Ashton's avatar
Gregory Ashton committed
32
    @helper_functions.initializer
Gregory Ashton's avatar
Gregory Ashton committed
33
34
35
36
    def __init__(self, label, outdir, sftfilepattern, F0s, F1s, F2s, Alphas,
                 Deltas, tref=None, minStartTime=None, maxStartTime=None,
                 nsegs=1, BSGL=False, minCoverFreq=None, maxCoverFreq=None,
                 detectors=None, SSBprec=None, injectSources=None,
37
                 input_arrays=False, assumeSqrtSX=None):
Gregory Ashton's avatar
Gregory Ashton committed
38
39
40
41
42
        """
        Parameters
        ----------
        label, outdir: str
            A label and directory to read/write data from/to
43
44
45
        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
46
47
        F0s, F1s, F2s, delta_F0s, delta_F1s, tglitchs, Alphas, Deltas: tuple
            Length 3 tuple describing the grid for each parameter, e.g
48
49
            [F0min, F0max, dF0], for a fixed value simply give [F0]. Unless
            input_arrays == True, then these are the values to search at.
Gregory Ashton's avatar
Gregory Ashton committed
50
51
        tref, minStartTime, maxStartTime: int
            GPS seconds of the reference time, start time and end time
52
53
        input_arrays: bool
            if true, use the F0s, F1s, etc as is
Gregory Ashton's avatar
Gregory Ashton committed
54
55
56
57
58
59

        For all other parameters, see `pyfstat.ComputeFStat` for details
        """

        if os.path.isdir(outdir) is False:
            os.mkdir(outdir)
60
        self.set_out_file()
Gregory Ashton's avatar
Gregory Ashton committed
61
        self.keys = ['_', '_', 'F0', 'F1', 'F2', 'Alpha', 'Delta']
Gregory Ashton's avatar
Gregory Ashton committed
62
63
64
        self.search_keys = [x+'s' for x in self.keys[2:]]
        for k in self.search_keys:
            setattr(self, k, np.atleast_1d(getattr(self, k)))
Gregory Ashton's avatar
Gregory Ashton committed
65
66
67

    def inititate_search_object(self):
        logging.info('Setting up search object')
68
69
        if self.nsegs == 1:
            self.search = ComputeFstat(
70
                tref=self.tref, sftfilepattern=self.sftfilepattern,
71
                minCoverFreq=self.minCoverFreq, maxCoverFreq=self.maxCoverFreq,
David Keitel's avatar
David Keitel committed
72
                detectors=self.detectors,
73
                minStartTime=self.minStartTime, maxStartTime=self.maxStartTime,
74
                BSGL=self.BSGL, SSBprec=self.SSBprec,
75
76
                injectSources=self.injectSources,
                assumeSqrtSX=self.assumeSqrtSX)
77
            self.search.get_det_stat = self.search.get_fullycoherent_twoF
78
79
80
        else:
            self.search = SemiCoherentSearch(
                label=self.label, outdir=self.outdir, tref=self.tref,
81
                nsegs=self.nsegs, sftfilepattern=self.sftfilepattern,
82
83
84
                BSGL=self.BSGL, minStartTime=self.minStartTime,
                maxStartTime=self.maxStartTime, minCoverFreq=self.minCoverFreq,
                maxCoverFreq=self.maxCoverFreq, detectors=self.detectors,
Gregory Ashton's avatar
Gregory Ashton committed
85
                injectSources=self.injectSources)
86
87

            def cut_out_tstart_tend(*vals):
88
                return self.search.get_semicoherent_twoF(*vals[2:])
89
            self.search.get_det_stat = cut_out_tstart_tend
Gregory Ashton's avatar
Gregory Ashton committed
90
91
92
93

    def get_array_from_tuple(self, x):
        if len(x) == 1:
            return np.array(x)
94
        elif len(x) == 3 and self.input_arrays is False:
Gregory Ashton's avatar
Gregory Ashton committed
95
            return np.arange(x[0], x[1], x[2])
Gregory Ashton's avatar
Gregory Ashton committed
96
        else:
Gregory Ashton's avatar
Gregory Ashton committed
97
98
            logging.info('Using tuple as is')
            return np.array(x)
Gregory Ashton's avatar
Gregory Ashton committed
99
100

    def get_input_data_array(self):
Gregory Ashton's avatar
Gregory Ashton committed
101
        logging.info("Generating input data array")
102
        coord_arrays = []
Gregory Ashton's avatar
Gregory Ashton committed
103
104
        for tup in ([self.minStartTime], [self.maxStartTime], self.F0s,
                    self.F1s, self.F2s, self.Alphas, self.Deltas):
105
            coord_arrays.append(self.get_array_from_tuple(tup))
Gregory Ashton's avatar
Gregory Ashton committed
106

107
108
109
110
        input_data = []
        for vals in itertools.product(*coord_arrays):
                input_data.append(vals)
        self.input_data = np.array(input_data)
111
        self.coord_arrays = coord_arrays
Gregory Ashton's avatar
Gregory Ashton committed
112
113
114
115
116

    def check_old_data_is_okay_to_use(self):
        if args.clean:
            return False
        if os.path.isfile(self.out_file) is False:
117
118
119
            logging.info(
                'No old data found in "{:s}", continuing with grid search'
                .format(self.out_file))
Gregory Ashton's avatar
Gregory Ashton committed
120
            return False
121
        if self.sftfilepattern is not None:
122
123
124
125
126
127
            oldest_sft = min([os.path.getmtime(f) for f in
                              self._get_list_of_matching_sfts()])
            if os.path.getmtime(self.out_file) < oldest_sft:
                logging.info('Search output data outdates sft files,'
                             + ' continuing with grid search')
                return False
128

129
        data = np.atleast_2d(np.genfromtxt(self.out_file, delimiter=' '))
130
131
        if np.all(data[:, 0: len(self.coord_arrays)] ==
                  self.input_data[:, 0:len(self.coord_arrays)]):
132
            logging.info(
133
134
                'Old data found in "{:s}" with matching input, no search '
                'performed'.format(self.out_file))
135
136
137
            return data
        else:
            logging.info(
138
139
                'Old data found in "{:s}", input differs, continuing with '
                'grid search'.format(self.out_file))
140
            return False
141
        return False
Gregory Ashton's avatar
Gregory Ashton committed
142
143
144
145
146
147
148
149

    def run(self, return_data=False):
        self.get_input_data_array()
        old_data = self.check_old_data_is_okay_to_use()
        if old_data is not False:
            self.data = old_data
            return

Gregory Ashton's avatar
Gregory Ashton committed
150
151
        if hasattr(self, 'search') is False:
            self.inititate_search_object()
Gregory Ashton's avatar
Gregory Ashton committed
152
153

        data = []
154
        for vals in tqdm(self.input_data):
155
            detstat = self.search.get_det_stat(*vals)
156
157
            thisCand = list(vals) + [detstat]
            data.append(thisCand)
Gregory Ashton's avatar
Gregory Ashton committed
158

159
        data = np.array(data, dtype=np.float)
Gregory Ashton's avatar
Gregory Ashton committed
160
161
162
        if return_data:
            return data
        else:
163
            self.save_array_to_disk(data)
Gregory Ashton's avatar
Gregory Ashton committed
164
165
            self.data = data

166
167
168
169
170
171
172
173
174
175
176
177
    def get_header(self):
        header = ';'.join(['date:{}'.format(str(datetime.datetime.now())),
                           'user:{}'.format(getpass.getuser()),
                           'hostname:{}'.format(socket.gethostname())])
        header += '\n' + ' '.join(self.keys)
        return header

    def save_array_to_disk(self, data):
        logging.info('Saving data to {}'.format(self.out_file))
        header = self.get_header()
        np.savetxt(self.out_file, data, delimiter=' ', header=header)

Gregory Ashton's avatar
Gregory Ashton committed
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
    def convert_F0_to_mismatch(self, F0, F0hat, Tseg):
        DeltaF0 = F0[1] - F0[0]
        m_spacing = (np.pi*Tseg*DeltaF0)**2 / 12.
        N = len(F0)
        return np.arange(-N*m_spacing/2., N*m_spacing/2., m_spacing)

    def convert_F1_to_mismatch(self, F1, F1hat, Tseg):
        DeltaF1 = F1[1] - F1[0]
        m_spacing = (np.pi*Tseg**2*DeltaF1)**2 / 720.
        N = len(F1)
        return np.arange(-N*m_spacing/2., N*m_spacing/2., m_spacing)

    def add_mismatch_to_ax(self, ax, x, y, xkey, ykey, xhat, yhat, Tseg):
        axX = ax.twiny()
        axX.zorder = -10
        axY = ax.twinx()
        axY.zorder = -10

        if xkey == 'F0':
            m = self.convert_F0_to_mismatch(x, xhat, Tseg)
            axX.set_xlim(m[0], m[-1])

        if ykey == 'F1':
            m = self.convert_F1_to_mismatch(y, yhat, Tseg)
            axY.set_ylim(m[0], m[-1])

Gregory Ashton's avatar
Gregory Ashton committed
204
205
    def plot_1D(self, xkey, ax=None, x0=None, xrescale=1, savefig=True,
                xlabel=None, ylabel='$\widetilde{2\mathcal{F}}$'):
Gregory Ashton's avatar
Gregory Ashton committed
206
207
        if ax is None:
            fig, ax = plt.subplots()
Gregory Ashton's avatar
Gregory Ashton committed
208
209
        xidx = self.keys.index(xkey)
        x = np.unique(self.data[:, xidx])
210
211
        if x0:
            x = x - x0
Gregory Ashton's avatar
Gregory Ashton committed
212
        x = x * xrescale
Gregory Ashton's avatar
Gregory Ashton committed
213
        z = self.data[:, -1]
Gregory Ashton's avatar
Gregory Ashton committed
214
215
216
217
218
        ax.plot(x, z)
        if x0:
            ax.set_xlabel(self.tex_labels[xkey]+self.tex_labels0[xkey])
        else:
            ax.set_xlabel(self.tex_labels[xkey])
Gregory Ashton's avatar
Gregory Ashton committed
219
220
221
222
223

        if xlabel:
            ax.set_xlabel(xlabel)

        ax.set_ylabel(ylabel)
Gregory Ashton's avatar
Gregory Ashton committed
224
        if savefig:
Gregory Ashton's avatar
Gregory Ashton committed
225
            fig.tight_layout()
Gregory Ashton's avatar
Gregory Ashton committed
226
227
            fig.savefig('{}/{}_1D.png'.format(self.outdir, self.label))
        else:
228
            return ax
Gregory Ashton's avatar
Gregory Ashton committed
229
230
231

    def plot_2D(self, xkey, ykey, ax=None, save=True, vmin=None, vmax=None,
                add_mismatch=None, xN=None, yN=None, flat_keys=[],
Gregory Ashton's avatar
Gregory Ashton committed
232
                rel_flat_idxs=[], flatten_method=np.max, title=None,
Gregory Ashton's avatar
Gregory Ashton committed
233
234
                predicted_twoF=None, cm=None, cbarkwargs={}, x0=None, y0=None,
                colorbar=False):
Gregory Ashton's avatar
Gregory Ashton committed
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
        """ Plots a 2D grid of 2F values

        Parameters
        ----------
        add_mismatch: tuple (xhat, yhat, Tseg)
            If not None, add a secondary axis with the metric mismatch from the
            point xhat, yhat with duration Tseg
        flatten_method: np.max
            Function to use in flattening the flat_keys
        """
        if ax is None:
            fig, ax = plt.subplots()
        xidx = self.keys.index(xkey)
        yidx = self.keys.index(ykey)
        flat_idxs = [self.keys.index(k) for k in flat_keys]

        x = np.unique(self.data[:, xidx])
252
253
        if x0:
            x = x-x0
Gregory Ashton's avatar
Gregory Ashton committed
254
        y = np.unique(self.data[:, yidx])
255
256
        if y0:
            y = y-y0
Gregory Ashton's avatar
Gregory Ashton committed
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
        flat_vals = [np.unique(self.data[:, j]) for j in flat_idxs]
        z = self.data[:, -1]

        Y, X = np.meshgrid(y, x)
        shape = [len(x), len(y)] + [len(v) for v in flat_vals]
        Z = z.reshape(shape)

        if len(rel_flat_idxs) > 0:
            Z = flatten_method(Z, axis=tuple(rel_flat_idxs))

        if predicted_twoF:
            Z = (predicted_twoF - Z) / (predicted_twoF + 4)
            if cm is None:
                cm = plt.cm.viridis_r
        else:
            if cm is None:
                cm = plt.cm.viridis

        pax = ax.pcolormesh(X, Y, Z, cmap=cm, vmin=vmin, vmax=vmax)
Gregory Ashton's avatar
Gregory Ashton committed
276
277
278
        if colorbar:
            cb = plt.colorbar(pax, ax=ax, **cbarkwargs)
            cb.set_label('$2\mathcal{F}$')
Gregory Ashton's avatar
Gregory Ashton committed
279
280
281
282
283
284

        if add_mismatch:
            self.add_mismatch_to_ax(ax, x, y, xkey, ykey, *add_mismatch)

        ax.set_xlim(x[0], x[-1])
        ax.set_ylim(y[0], y[-1])
285
        if x0:
Gregory Ashton's avatar
Gregory Ashton committed
286
            ax.set_xlabel(self.tex_labels[xkey]+self.tex_labels0[xkey])
287
        else:
Gregory Ashton's avatar
Gregory Ashton committed
288
            ax.set_xlabel(self.tex_labels[xkey])
289
        if y0:
Gregory Ashton's avatar
Gregory Ashton committed
290
            ax.set_ylabel(self.tex_labels[ykey]+self.tex_labels0[ykey])
291
        else:
Gregory Ashton's avatar
Gregory Ashton committed
292
            ax.set_ylabel(self.tex_labels[ykey])
Gregory Ashton's avatar
Gregory Ashton committed
293

Gregory Ashton's avatar
Gregory Ashton committed
294
295
296
        if title:
            ax.set_title(title)

Gregory Ashton's avatar
Gregory Ashton committed
297
298
299
300
301
302
303
304
305
306
307
308
        if xN:
            ax.xaxis.set_major_locator(matplotlib.ticker.MaxNLocator(xN))
        if yN:
            ax.yaxis.set_major_locator(matplotlib.ticker.MaxNLocator(yN))

        if save:
            fig.tight_layout()
            fig.savefig('{}/{}_2D.png'.format(self.outdir, self.label))
        else:
            return ax

    def get_max_twoF(self):
Gregory Ashton's avatar
Gregory Ashton committed
309
310
311
312
313
314
315
316
317
318
        """ Get the maximum twoF over the grid

        Returns
        -------
        d: dict
            Dictionary containing, 'minStartTime', 'maxStartTime', 'F0', 'F1',
            'F2', 'Alpha', 'Delta' and 'twoF' of maximum

        """

Gregory Ashton's avatar
Gregory Ashton committed
319
320
321
322
323
324
325
326
327
328
329
330
331
        twoF = self.data[:, -1]
        idx = np.argmax(twoF)
        v = self.data[idx, :]
        d = OrderedDict(minStartTime=v[0], maxStartTime=v[1], F0=v[2], F1=v[3],
                        F2=v[4], Alpha=v[5], Delta=v[6], twoF=v[7])
        return d

    def print_max_twoF(self):
        d = self.get_max_twoF()
        print('Max twoF values for {}:'.format(self.label))
        for k, v in d.iteritems():
            print('  {}={}'.format(k, v))

332
    def set_out_file(self, extra_label=None):
333
334
335
336
        if self.detectors:
            dets = self.detectors.replace(',', '')
        else:
            dets = 'NA'
337
338
339
340
341
342
343
344
        if extra_label:
            self.out_file = '{}/{}_{}_{}_{}.txt'.format(
                self.outdir, self.label, dets, type(self).__name__,
                extra_label)
        else:
            self.out_file = '{}/{}_{}_{}.txt'.format(
                self.outdir, self.label, dets, type(self).__name__)

Gregory Ashton's avatar
Gregory Ashton committed
345

346
347
348
349
350
351
352
353
354
355
class TransientGridSearch(GridSearch):
    """ Gridded transient-continous search using ComputeFstat """

    @helper_functions.initializer
    def __init__(self, label, outdir, sftfilepattern, F0s, F1s, F2s, Alphas,
                 Deltas, tref=None, minStartTime=None, maxStartTime=None,
                 BSGL=False, minCoverFreq=None, maxCoverFreq=None,
                 detectors=None, SSBprec=None, injectSources=None,
                 input_arrays=False, assumeSqrtSX=None,
                 transientWindowType=None, t0Band=None, tauBand=None,
356
                 dt0=None, dtau=None,
357
                 outputTransientFstatMap=False,
358
359
                 outputAtoms=False,
                 tCWFstatMapVersion='lal'):
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
        """
        Parameters
        ----------
        label, outdir: str
            A label and directory to read/write data from/to
        sftfilepattern: str
            Pattern to match SFTs using wildcards (*?) and ranges [0-9];
            mutiple patterns can be given separated by colons.
        F0s, F1s, F2s, delta_F0s, delta_F1s, tglitchs, Alphas, Deltas: tuple
            Length 3 tuple describing the grid for each parameter, e.g
            [F0min, F0max, dF0], for a fixed value simply give [F0]. Unless
            input_arrays == True, then these are the values to search at.
        tref, minStartTime, maxStartTime: int
            GPS seconds of the reference time, start time and end time
        input_arrays: bool
            if true, use the F0s, F1s, etc as is
        transientWindowType: str
            If 'rect' or 'exp', compute atoms so that a transient (t0,tau) map
            can later be computed.  ('none' instead of None explicitly calls
            the transient-window function, but with the full range, for
            debugging). Currently only supported for nsegs=1.
        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.
386
387
388
        dt0, dtau: int
            grid resolutions in transient start-time and duration,
            both default to Tsft
389
390
391
        outputTransientFstatMap: bool
            if true, write output files for (t0,tau) Fstat maps
            (one file for each doppler grid point!)
392
393
394
        tCWFstatMapVersion: str
            Choose between standard 'lal' implementation,
            'pycuda' for gpu, and some others for devel/debug.
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415

        For all other parameters, see `pyfstat.ComputeFStat` for details
        """

        self.nsegs = 1
        if os.path.isdir(outdir) is False:
            os.mkdir(outdir)
        self.set_out_file()
        self.keys = ['_', '_', 'F0', 'F1', 'F2', 'Alpha', 'Delta']
        self.search_keys = [x+'s' for x in self.keys[2:]]
        for k in self.search_keys:
            setattr(self, k, np.atleast_1d(getattr(self, k)))

    def inititate_search_object(self):
        logging.info('Setting up search object')
        self.search = ComputeFstat(
            tref=self.tref, sftfilepattern=self.sftfilepattern,
            minCoverFreq=self.minCoverFreq, maxCoverFreq=self.maxCoverFreq,
            detectors=self.detectors,
            transientWindowType=self.transientWindowType,
            t0Band=self.t0Band, tauBand=self.tauBand,
416
            dt0=self.dt0, dtau=self.dtau,
417
418
419
            minStartTime=self.minStartTime, maxStartTime=self.maxStartTime,
            BSGL=self.BSGL, SSBprec=self.SSBprec,
            injectSources=self.injectSources,
420
421
            assumeSqrtSX=self.assumeSqrtSX,
            tCWFstatMapVersion=self.tCWFstatMapVersion)
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
        self.search.get_det_stat = self.search.get_fullycoherent_twoF

    def run(self, return_data=False):
        self.get_input_data_array()
        old_data = self.check_old_data_is_okay_to_use()
        if old_data is not False:
            self.data = old_data
            return

        if hasattr(self, 'search') is False:
            self.inititate_search_object()

        data = []
        for vals in tqdm(self.input_data):
            detstat = self.search.get_det_stat(*vals)
            windowRange = getattr(self.search, 'windowRange', None)
            FstatMap = getattr(self.search, 'FstatMap', None)
            thisCand = list(vals) + [detstat]
            if getattr(self, 'transientWindowType', None):
441
442
443
444
                if self.tCWFstatMapVersion == 'lal':
                    F_mn = FstatMap.F_mn.data
                else:
                    F_mn = FstatMap.F_mn
445
446
                if self.outputTransientFstatMap:
                    tCWfile = os.path.splitext(self.out_file)[0]+'_tCW_%.16f_%.16f_%.16f_%.16g_%.16g.dat' % (vals[2],vals[5],vals[6],vals[3],vals[4]) # freq alpha delta f1dot f2dot
447
448
449
450
451
                    if self.tCWFstatMapVersion == 'lal':
                        fo = lal.FileOpen(tCWfile, 'w')
                        lalpulsar.write_transientFstatMap_to_fp ( fo, FstatMap, windowRange, None )
                        del fo # instead of lal.FileClose() which is not SWIG-exported
                    else:
452
453
                        np.savetxt(tCWfile, 2.0*F_mn, delimiter=' ')
                maxidx = np.unravel_index(F_mn.argmax(), F_mn.shape)
454
455
456
                thisCand += [windowRange.t0+maxidx[0]*windowRange.dt0,
                             windowRange.tau+maxidx[1]*windowRange.dtau]
            data.append(thisCand)
457
458
            if self.outputAtoms:
                self.search.write_atoms_to_file(os.path.splitext(self.out_file)[0])
459
460
461
462
463
464
465
466
467

        data = np.array(data, dtype=np.float)
        if return_data:
            return data
        else:
            self.save_array_to_disk(data)
            self.data = data


Gregory Ashton's avatar
Gregory Ashton committed
468
469
470
class SliceGridSearch(GridSearch):
    """ Slice gridded search using ComputeFstat """
    @helper_functions.initializer
Gregory Ashton's avatar
Gregory Ashton committed
471
472
473
474
475
    def __init__(self, label, outdir, sftfilepattern, F0s, F1s, F2s, Alphas,
                 Deltas, tref=None, minStartTime=None, maxStartTime=None,
                 nsegs=1, BSGL=False, minCoverFreq=None, maxCoverFreq=None,
                 detectors=None, SSBprec=None, injectSources=None,
                 input_arrays=False, assumeSqrtSX=None, Lambda0=None):
Gregory Ashton's avatar
Gregory Ashton committed
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
        """
        Parameters
        ----------
        label, outdir: str
            A label and directory to read/write data from/to
        sftfilepattern: str
            Pattern to match SFTs using wildcards (*?) and ranges [0-9];
            mutiple patterns can be given separated by colons.
        F0s, F1s, F2s, delta_F0s, delta_F1s, tglitchs, Alphas, Deltas: tuple
            Length 3 tuple describing the grid for each parameter, e.g
            [F0min, F0max, dF0], for a fixed value simply give [F0]. Unless
            input_arrays == True, then these are the values to search at.
        tref, minStartTime, maxStartTime: int
            GPS seconds of the reference time, start time and end time
        input_arrays: bool
            if true, use the F0s, F1s, etc as is

        For all other parameters, see `pyfstat.ComputeFStat` for details
        """

        if os.path.isdir(outdir) is False:
            os.mkdir(outdir)
        self.set_out_file()
        self.keys = ['_', '_', 'F0', 'F1', 'F2', 'Alpha', 'Delta']
Gregory Ashton's avatar
Gregory Ashton committed
500
501
502
        self.ndim = 0
        self.thetas = [F0s, F1s, Alphas, Deltas]
        self.ndim = 4
Gregory Ashton's avatar
Gregory Ashton committed
503

Gregory Ashton's avatar
Gregory Ashton committed
504
        self.search_keys = ['F0', 'F1', 'Alpha', 'Delta']
505
506
        if self.Lambda0 is None:
            raise ValueError('Lambda0 undefined')
Gregory Ashton's avatar
Gregory Ashton committed
507
        if len(self.Lambda0) != len(self.search_keys):
Gregory Ashton's avatar
Gregory Ashton committed
508
            raise ValueError(
Gregory Ashton's avatar
Gregory Ashton committed
509
                'Lambda0 must be of length {}'.format(len(self.search_keys)))
510
        self.Lambda0 = np.array(Lambda0)
Gregory Ashton's avatar
Gregory Ashton committed
511

512
513
    def run(self, factor=2, max_n_ticks=4, whspace=0.07, save=True,
            **kwargs):
Gregory Ashton's avatar
Gregory Ashton committed
514
        lbdim = 0.5 * factor   # size of left/bottom margin
515
        trdim = 0.4 * factor   # size of top/right margin
Gregory Ashton's avatar
Gregory Ashton committed
516
517
518
519
520
521
522
523
524
525
526
527
528
529
        plotdim = factor * self.ndim + factor * (self.ndim - 1.) * whspace
        dim = lbdim + plotdim + trdim

        fig, axes = plt.subplots(self.ndim, self.ndim, figsize=(dim, dim))

        # Format the figure.
        lb = lbdim / dim
        tr = (lbdim + plotdim) / dim
        fig.subplots_adjust(left=lb, bottom=lb, right=tr, top=tr,
                            wspace=whspace, hspace=whspace)

        search = GridSearch(
            self.label, self.outdir, self.sftfilepattern,
            F0s=self.Lambda0[0], F1s=self.Lambda0[1], F2s=self.F2s[0],
530
531
            Alphas=self.Lambda0[2], Deltas=self.Lambda0[3], tref=self.tref,
            minStartTime=self.minStartTime, maxStartTime=self.maxStartTime)
Gregory Ashton's avatar
Gregory Ashton committed
532
533
534

        for i, ikey in enumerate(self.search_keys):
            setattr(search, ikey+'s', self.thetas[i])
535
536
            search.label = '{}_{}'.format(self.label, ikey)
            search.set_out_file()
Gregory Ashton's avatar
Gregory Ashton committed
537
            search.run()
538
539
540
            axes[i, i] = search.plot_1D(ikey, ax=axes[i, i], savefig=False,
                                        x0=self.Lambda0[i]
                                        )
Gregory Ashton's avatar
Gregory Ashton committed
541
            setattr(search, ikey+'s', [self.Lambda0[i]])
542
543
544
            axes[i, i].yaxis.tick_right()
            axes[i, i].yaxis.set_label_position("right")
            axes[i, i].set_xlabel('')
Gregory Ashton's avatar
Gregory Ashton committed
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571

            for j, jkey in enumerate(self.search_keys):
                ax = axes[i, j]

                if j > i:
                    ax.set_frame_on(False)
                    ax.set_xticks([])
                    ax.set_yticks([])
                    continue

                ax.get_shared_x_axes().join(axes[self.ndim-1, j], ax)
                if i < self.ndim - 1:
                    ax.set_xticklabels([])
                if j < i:
                    ax.get_shared_y_axes().join(axes[i, i-1], ax)
                    if j > 0:
                        ax.set_yticklabels([])
                if j == i:
                    continue

                ax.xaxis.set_major_locator(
                    matplotlib.ticker.MaxNLocator(max_n_ticks, prune="upper"))
                ax.yaxis.set_major_locator(
                    matplotlib.ticker.MaxNLocator(max_n_ticks, prune="upper"))

                setattr(search, ikey+'s', self.thetas[i])
                setattr(search, jkey+'s', self.thetas[j])
572
573
                search.label = '{}_{}'.format(self.label, ikey+jkey)
                search.set_out_file()
Gregory Ashton's avatar
Gregory Ashton committed
574
                search.run()
575
                ax = search.plot_2D(jkey, ikey, ax=ax, save=False,
576
577
                                    y0=self.Lambda0[i], x0=self.Lambda0[j],
                                    **kwargs)
Gregory Ashton's avatar
Gregory Ashton committed
578
579
580
                setattr(search, ikey+'s', [self.Lambda0[i]])
                setattr(search, jkey+'s', [self.Lambda0[j]])

581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
                ax.grid(lw=0.2, ls='--', zorder=10)
                ax.set_xlabel('')
                ax.set_ylabel('')

        for i, ikey in enumerate(self.search_keys):
            axes[-1, i].set_xlabel(
                self.tex_labels[ikey]+self.tex_labels0[ikey])
            if i > 0:
                axes[i, 0].set_ylabel(
                    self.tex_labels[ikey]+self.tex_labels0[ikey])
            axes[i, i].set_ylabel("$2\mathcal{F}$")

        if save:
            fig.savefig(
                '{}/{}_slice_projection.png'.format(self.outdir, self.label))
        else:
            return fig, axes
Gregory Ashton's avatar
Gregory Ashton committed
598
599


Gregory Ashton's avatar
Gregory Ashton committed
600
class GridUniformPriorSearch():
601
    @helper_functions.initializer
602
    def __init__(self, theta_prior, NF0, NF1, label, outdir, sftfilepattern,
603
                 tref, minStartTime, maxStartTime, minCoverFreq=None,
604
                 maxCoverFreq=None, BSGL=False, detectors=None, nsegs=1,
605
                 SSBprec=None, injectSources=None):
Gregory Ashton's avatar
Gregory Ashton committed
606
607
608
609
        dF0 = (theta_prior['F0']['upper'] - theta_prior['F0']['lower'])/NF0
        dF1 = (theta_prior['F1']['upper'] - theta_prior['F1']['lower'])/NF1
        F0s = [theta_prior['F0']['lower'], theta_prior['F0']['upper'], dF0]
        F1s = [theta_prior['F1']['lower'], theta_prior['F1']['upper'], dF1]
610
        self.search = GridSearch(
611
            label, outdir, sftfilepattern, F0s=F0s, F1s=F1s, tref=tref,
Gregory Ashton's avatar
Gregory Ashton committed
612
613
            Alphas=[theta_prior['Alpha']], Deltas=[theta_prior['Delta']],
            minStartTime=minStartTime, maxStartTime=maxStartTime, BSGL=BSGL,
614
            detectors=detectors, minCoverFreq=minCoverFreq,
615
616
            injectSources=injectSources, maxCoverFreq=maxCoverFreq,
            nsegs=nsegs, SSBprec=SSBprec)
617

618
    def run(self):
619
        self.search.run()
620
621

    def get_2D_plot(self, **kwargs):
622
        return self.search.plot_2D('F0', 'F1', **kwargs)
Gregory Ashton's avatar
Gregory Ashton committed
623
624


Gregory Ashton's avatar
Gregory Ashton committed
625
626
627
class GridGlitchSearch(GridSearch):
    """ Grid search using the SemiCoherentGlitchSearch """
    @helper_functions.initializer
628
    def __init__(self, label, outdir='data', sftfilepattern=None, F0s=[0],
Gregory Ashton's avatar
Gregory Ashton committed
629
630
631
                 F1s=[0], F2s=[0], delta_F0s=[0], delta_F1s=[0], tglitchs=None,
                 Alphas=[0], Deltas=[0], tref=None, minStartTime=None,
                 maxStartTime=None, minCoverFreq=None, maxCoverFreq=None,
632
                 detectors=None):
Gregory Ashton's avatar
Gregory Ashton committed
633
        """
634
635
        Run a single-glitch grid search

Gregory Ashton's avatar
Gregory Ashton committed
636
637
638
639
        Parameters
        ----------
        label, outdir: str
            A label and directory to read/write data from/to
640
641
642
        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
643
644
        F0s, F1s, F2s, delta_F0s, delta_F1s, tglitchs, Alphas, Deltas: tuple
            Length 3 tuple describing the grid for each parameter, e.g
645
646
            [F0min, F0max, dF0], for a fixed value simply give [F0]. Note that
            tglitchs is referenced to zero at minStartTime.
Gregory Ashton's avatar
Gregory Ashton committed
647
648
649
650
651
        tref, minStartTime, maxStartTime: int
            GPS seconds of the reference time, start time and end time

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

        self.BSGL = False
654
        self.input_arrays = False
Gregory Ashton's avatar
Gregory Ashton committed
655
        if tglitchs is None:
656
            raise ValueError('You must specify `tglitchs`')
Gregory Ashton's avatar
Gregory Ashton committed
657
658

        self.search = SemiCoherentGlitchSearch(
659
            label=label, outdir=outdir, sftfilepattern=self.sftfilepattern,
Gregory Ashton's avatar
Gregory Ashton committed
660
661
662
            tref=tref, minStartTime=minStartTime, maxStartTime=maxStartTime,
            minCoverFreq=minCoverFreq, maxCoverFreq=maxCoverFreq,
            BSGL=self.BSGL)
663
        self.search.get_det_stat = self.search.get_semicoherent_nglitch_twoF
Gregory Ashton's avatar
Gregory Ashton committed
664
665
666

        if os.path.isdir(outdir) is False:
            os.mkdir(outdir)
667
        self.set_out_file()
Gregory Ashton's avatar
Gregory Ashton committed
668
669
670
671
        self.keys = ['F0', 'F1', 'F2', 'Alpha', 'Delta', 'delta_F0',
                     'delta_F1', 'tglitch']

    def get_input_data_array(self):
672
673
        logging.info("Generating input data array")
        coord_arrays = []
Gregory Ashton's avatar
Gregory Ashton committed
674
675
        for tup in (self.F0s, self.F1s, self.F2s, self.Alphas, self.Deltas,
                    self.delta_F0s, self.delta_F1s, self.tglitchs):
676
            coord_arrays.append(self.get_array_from_tuple(tup))
Gregory Ashton's avatar
Gregory Ashton committed
677
678

        input_data = []
679
        for vals in itertools.product(*coord_arrays):
Gregory Ashton's avatar
Gregory Ashton committed
680
681
            input_data.append(vals)
        self.input_data = np.array(input_data)
682
        self.coord_arrays = coord_arrays
Gregory Ashton's avatar
Gregory Ashton committed
683
684


Gregory Ashton's avatar
Gregory Ashton committed
685
686
687
class FrequencySlidingWindow(GridSearch):
    """ A sliding-window search over the Frequency """
    @helper_functions.initializer
688
    def __init__(self, label, outdir, sftfilepattern, F0s, F1, F2,
Gregory Ashton's avatar
Gregory Ashton committed
689
690
691
                 Alpha, Delta, tref, minStartTime=None,
                 maxStartTime=None, window_size=10*86400, window_delta=86400,
                 BSGL=False, minCoverFreq=None, maxCoverFreq=None,
692
                 detectors=None, SSBprec=None, injectSources=None):
Gregory Ashton's avatar
Gregory Ashton committed
693
694
695
696
697
        """
        Parameters
        ----------
        label, outdir: str
            A label and directory to read/write data from/to
698
699
700
        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
701
702
703
704
705
706
707
708
709
710
        F0s: array
            Frequency range
        F1, F2, Alpha, Delta: float
            Fixed values to compute twoF(F) over
        tref, minStartTime, maxStartTime: int
            GPS seconds of the reference time, start time and end time

        For all other parameters, see `pyfstat.ComputeFStat` for details
        """

711
712
713
714
        self.transientWindowType = None
        self.t0Band = None
        self.tauBand = None

Gregory Ashton's avatar
Gregory Ashton committed
715
716
        if os.path.isdir(outdir) is False:
            os.mkdir(outdir)
717
        self.set_out_file()
Gregory Ashton's avatar
Gregory Ashton committed
718
719
720
721
722
        self.nsegs = 1
        self.F1s = [F1]
        self.F2s = [F2]
        self.Alphas = [Alpha]
        self.Deltas = [Delta]
723
        self.input_arrays = False
724
        self.keys = ['_', '_', 'F0', 'F1', 'F2', 'Alpha', 'Delta']
Gregory Ashton's avatar
Gregory Ashton committed
725

Gregory Ashton's avatar
Gregory Ashton committed
726
727
728
    def inititate_search_object(self):
        logging.info('Setting up search object')
        self.search = ComputeFstat(
729
            tref=self.tref, sftfilepattern=self.sftfilepattern,
Gregory Ashton's avatar
Gregory Ashton committed
730
            minCoverFreq=self.minCoverFreq, maxCoverFreq=self.maxCoverFreq,
David Keitel's avatar
David Keitel committed
731
            detectors=self.detectors, transientWindowType=self.transientWindowType,
Gregory Ashton's avatar
Gregory Ashton committed
732
            minStartTime=self.minStartTime, maxStartTime=self.maxStartTime,
Gregory Ashton's avatar
Gregory Ashton committed
733
734
            BSGL=self.BSGL, SSBprec=self.SSBprec,
            injectSources=self.injectSources)
Gregory Ashton's avatar
Gregory Ashton committed
735
        self.search.get_det_stat = (
736
            self.search.get_fullycoherent_twoF)
Gregory Ashton's avatar
Gregory Ashton committed
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759

    def get_input_data_array(self):
        arrays = []
        tstarts = [self.minStartTime]
        while tstarts[-1] + self.window_size < self.maxStartTime:
            tstarts.append(tstarts[-1]+self.window_delta)
        arrays = [tstarts]
        for tup in (self.F0s, self.F1s, self.F2s,
                    self.Alphas, self.Deltas):
            arrays.append(self.get_array_from_tuple(tup))

        input_data = []
        for vals in itertools.product(*arrays):
            input_data.append(vals)

        input_data = np.array(input_data)
        input_data = np.insert(
            input_data, 1, input_data[:, 0] + self.window_size, axis=1)

        self.arrays = arrays
        self.input_data = np.array(input_data)

    def plot_sliding_window(self, F0=None, ax=None, savefig=True,
760
                            colorbar=True, timestamps=False):
Gregory Ashton's avatar
Gregory Ashton committed
761
762
763
764
765
766
767
768
769
770
771
        data = self.data
        if ax is None:
            ax = plt.subplot()
        tstarts = np.unique(data[:, 0])
        tends = np.unique(data[:, 1])
        frequencies = np.unique(data[:, 2])
        twoF = data[:, -1]
        tmids = (tstarts + tends) / 2.0
        dts = (tmids - self.minStartTime) / 86400.
        if F0:
            frequencies = frequencies - F0
772
            ax.set_ylabel('Frequency - $f_0$ [Hz] \n $f_0={:0.2f}$'.format(F0))
Gregory Ashton's avatar
Gregory Ashton committed
773
774
775
776
777
778
779
780
781
        else:
            ax.set_ylabel('Frequency [Hz]')
        twoF = twoF.reshape((len(tmids), len(frequencies)))
        Y, X = np.meshgrid(frequencies, dts)
        pax = ax.pcolormesh(X, Y, twoF)
        if colorbar:
            cb = plt.colorbar(pax, ax=ax)
            cb.set_label('$2\mathcal{F}$')
        ax.set_xlabel(
782
783
            r'Mid-point (days after $t_\mathrm{{start}}$={})'.format(
                self.minStartTime))
Gregory Ashton's avatar
Gregory Ashton committed
784
785
        ax.set_title(
            'Sliding window length = {} days in increments of {} days'
786
787
788
789
790
791
792
            .format(self.window_size/86400, self.window_delta/86400),
            )
        if timestamps:
            axT = ax.twiny()
            axT.set_xlim(tmids[0]*1e-9, tmids[-1]*1e-9)
            axT.set_xlabel('Mid-point timestamp [GPS $10^{9}$ s]')
            ax.set_title(ax.get_title(), y=1.18)
Gregory Ashton's avatar
Gregory Ashton committed
793
794
795
796
797
798
        if savefig:
            plt.tight_layout()
            plt.savefig(
                '{}/{}_sliding_window.png'.format(self.outdir, self.label))
        else:
            return ax
799
800


Gregory Ashton's avatar
Gregory Ashton committed
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
class EarthTest(GridSearch):
    """ """
    tex_labels = {'deltaRadius': '$\Delta R$ [m]',
                  'phaseOffset': 'phase-offset [rad]',
                  'deltaPspin': '$\Delta P_\mathrm{spin}$ [s]'}

    @helper_functions.initializer
    def __init__(self, label, outdir, sftfilepattern, deltaRadius,
                 phaseOffset, deltaPspin, F0, F1, F2, Alpha,
                 Delta, tref=None, minStartTime=None, maxStartTime=None,
                 BSGL=False, minCoverFreq=None, maxCoverFreq=None,
                 detectors=None, injectSources=None,
                 assumeSqrtSX=None):
        """
        Parameters
        ----------
        label, outdir: str
            A label and directory to read/write data from/to
        sftfilepattern: str
            Pattern to match SFTs using wildcards (*?) and ranges [0-9];
            mutiple patterns can be given separated by colons.
        F0, F1, F2, Alpha, Delta: float
        tref, minStartTime, maxStartTime: int
            GPS seconds of the reference time, start time and end time

        For all other parameters, see `pyfstat.ComputeFStat` for details
        """
828
829
830
831
        self.transientWindowType = None
        self.t0Band = None
        self.tauBand = None

832
833
        if os.path.isdir(outdir) is False:
            os.mkdir(outdir)
Gregory Ashton's avatar
Gregory Ashton committed
834
835
836
837
838
839
        self.nsegs = 1
        self.F0s = [F0]
        self.F1s = [F1]
        self.F2s = [F2]
        self.Alphas = [Alpha]
        self.Deltas = [Delta]
840
        self.duration = maxStartTime - minStartTime
Gregory Ashton's avatar
Gregory Ashton committed
841
842
        self.deltaRadius = np.atleast_1d(deltaRadius)
        self.phaseOffset = np.atleast_1d(phaseOffset)
843
        self.phaseOffset = self.phaseOffset + 1e-12  # Hack to stop cached data being used
Gregory Ashton's avatar
Gregory Ashton committed
844
845
846
847
848
        self.deltaPspin = np.atleast_1d(deltaPspin)
        self.set_out_file()
        self.SSBprec = lalpulsar.SSBPREC_RELATIVISTIC
        self.keys = ['deltaRadius', 'phaseOffset', 'deltaPspin']

849
850
851
852
853
854
855
856
        self.prior_widths = [
            np.max(self.deltaRadius)-np.min(self.deltaRadius),
            np.max(self.phaseOffset)-np.min(self.phaseOffset),
            np.max(self.deltaPspin)-np.min(self.deltaPspin)]

        if hasattr(self, 'search') is False:
            self.inititate_search_object()

Gregory Ashton's avatar
Gregory Ashton committed
857
858
859
860
861
862
863
864
865
    def get_input_data_array(self):
        logging.info("Generating input data array")
        coord_arrays = [self.deltaRadius, self.phaseOffset, self.deltaPspin]
        input_data = []
        for vals in itertools.product(*coord_arrays):
                input_data.append(vals)
        self.input_data = np.array(input_data)
        self.coord_arrays = coord_arrays

866
867
868
869
870
871
872
873
874
875
876
877
    def run_special(self):
        vals = [self.minStartTime, self.maxStartTime, self.F0, self.F1,
                self.F2, self.Alpha, self.Delta]
        self.special_data = {'zero': [0, 0, 0]}
        for key, (dR, dphi, dP) in self.special_data.iteritems():
            rescaleRadius = (1 + dR / lal.REARTH_SI)
            rescalePeriod = (1 + dP / lal.DAYSID_SI)
            lalpulsar.BarycenterModifyEarthRotation(
                rescaleRadius, dphi, rescalePeriod, self.tref)
            FS = self.search.get_det_stat(*vals)
            self.special_data[key] = list([dR, dphi, dP]) + [FS]

Gregory Ashton's avatar
Gregory Ashton committed
878
    def run(self):
879
        self.run_special()
Gregory Ashton's avatar
Gregory Ashton committed
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
        self.get_input_data_array()
        old_data = self.check_old_data_is_okay_to_use()
        if old_data is not False:
            self.data = old_data
            return

        data = []
        vals = [self.minStartTime, self.maxStartTime, self.F0, self.F1,
                self.F2, self.Alpha, self.Delta]
        for (dR, dphi, dP) in tqdm(self.input_data):
            rescaleRadius = (1 + dR / lal.REARTH_SI)
            rescalePeriod = (1 + dP / lal.DAYSID_SI)
            lalpulsar.BarycenterModifyEarthRotation(
                rescaleRadius, dphi, rescalePeriod, self.tref)
            FS = self.search.get_det_stat(*vals)
            data.append(list([dR, dphi, dP]) + [FS])

        data = np.array(data, dtype=np.float)
        logging.info('Saving data to {}'.format(self.out_file))
        np.savetxt(self.out_file, data, delimiter=' ')
        self.data = data

902
903
904
905
    def marginalised_bayes_factor(self, prior_widths=None):
        if prior_widths is None:
            prior_widths = self.prior_widths

906
        ndims = self.data.shape[1] - 1
907
        params = np.array([np.unique(self.data[:, j]) for j in range(ndims)])
908
909
910
911
912
        twoF = self.data[:, -1].reshape(tuple([len(p) for p in params]))
        F = twoF / 2.0
        for i, x in enumerate(params[::-1]):
            if len(x) > 1:
                dx = x[1] - x[0]
913
                F = logsumexp(F, axis=-1)+np.log(dx)-np.log(prior_widths[-1-i])
914
915
            else:
                F = np.squeeze(F, axis=-1)
916
917
918
919
920
921
922
923
924
925
926
        marginalised_F = np.atleast_1d(F)[0]
        F_at_zero = self.special_data['zero'][-1]/2.0

        max_idx = np.argmax(self.data[:, -1])
        max_F = self.data[max_idx, -1]/2.0
        max_F_params = self.data[max_idx, :-1]
        logging.info('F at zero = {:.1f}, marginalised_F = {:.1f},'
                     ' max_F = {:.1f} ({})'.format(
                         F_at_zero, marginalised_F, max_F, max_F_params))
        return F_at_zero - marginalised_F, (F_at_zero - max_F) / F_at_zero

927
928
    def plot_corner(self, prior_widths=None, fig=None, axes=None,
                    projection='log_mean'):
929
930
931
932
933
934
935
936
937
938
939
940
        Bsa, FmaxMismatch = self.marginalised_bayes_factor(prior_widths)

        data = self.data[:, -1].reshape(
            (len(self.deltaRadius), len(self.phaseOffset),
             len(self.deltaPspin)))
        xyz = [self.deltaRadius/lal.REARTH_SI, self.phaseOffset/(np.pi),
               self.deltaPspin/60.]
        labels = [r'$\frac{\Delta R}{R_\mathrm{Earth}}$',
                  r'$\frac{\Delta \phi}{\pi}$',
                  r'$\Delta P_\mathrm{spin}$ [min]',
                  r'$2\mathcal{F}$']

941
942
943
944
945
946
        try:
            from gridcorner import gridcorner
        except ImportError:
            raise ImportError(
                "Python module 'gridcorner' not found, please install from "
                "https://gitlab.aei.uni-hannover.de/GregAshton/gridcorner")
947

948
949
        fig, axes = gridcorner(data, xyz, projection=projection, factor=1.6,
                               labels=labels)
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
        axes[-1][-1].axvline((lal.DAYJUL_SI - lal.DAYSID_SI)/60.0, color='C3')
        plt.suptitle(
            'T={:.1f} days, $f$={:.2f} Hz, $\log\mathcal{{B}}_{{S/A}}$={:.1f},'
            r' $\frac{{\mathcal{{F}}_0-\mathcal{{F}}_\mathrm{{max}}}}'
            r'{{\mathcal{{F}}_0}}={:.1e}$'
            .format(self.duration/86400, self.F0, Bsa, FmaxMismatch), y=0.99,
            size=14)
        fig.savefig('{}/{}_projection_matrix.png'.format(
            self.outdir, self.label))

    def plot(self, key, prior_widths=None):
        Bsa, FmaxMismatch = self.marginalised_bayes_factor(prior_widths)

        rescales_defaults = {'deltaRadius': 1/lal.REARTH_SI,
                             'phaseOffset': 1/np.pi,
                             'deltaPspin': 1}
        labels = {'deltaRadius': r'$\frac{\Delta R}{R_\mathrm{Earth}}$',
                  'phaseOffset': r'$\frac{\Delta \phi}{\pi}$',
                  'deltaPspin': r'$\Delta P_\mathrm{spin}$ [s]'
                  }

        fig, ax = self.plot_1D(key, xrescale=rescales_defaults[key],
                               xlabel=labels[key], savefig=False)
        ax.set_title(
            'T={} days, $f$={} Hz, $\log\mathcal{{B}}_{{S/A}}$={:.1f}'
            .format(self.duration/86400, self.F0, Bsa))
        fig.tight_layout()
        fig.savefig('{}/{}_1D.png'.format(self.outdir, self.label))
978

Gregory Ashton's avatar
Gregory Ashton committed
979

980
981
982
class DMoff_NO_SPIN(GridSearch):
    """ DMoff test using SSBPREC_NO_SPIN """
    @helper_functions.initializer
983
    def __init__(self, par, label, outdir, sftfilepattern, minStartTime=None,
984
                 maxStartTime=None, minCoverFreq=None, maxCoverFreq=None,
985
                 detectors=None, injectSources=None, assumeSqrtSX=None):
986
987
988
        """
        Parameters
        ----------
989
990
991
        par: dict, str
            Either a par dictionary (containing 'F0', 'F1', 'Alpha', 'Delta'
            and 'tref') or a path to a .par file to read in the F0, F1 etc
992
993
        label, outdir: str
            A label and directory to read/write data from/to
994
995
996
        sftfilepattern: str
            Pattern to match SFTs using wildcards (*?) and ranges [0-9];
            mutiple patterns can be given separated by colons.
997
998
999
1000
1001
1002
1003
1004
1005
        minStartTime, maxStartTime: int
            GPS seconds of the start time and end time

        For all other parameters, see `pyfstat.ComputeFStat` for details
        """

        if os.path.isdir(outdir) is False:
            os.mkdir(outdir)

1006
1007
1008
1009
        if type(par) == dict:
            self.par = par
        elif type(par) == str and os.path.isfile(par):
            self.par = read_par(filename=par)
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
        else:
            raise ValueError('The .par file does not exist')

        self.nsegs = 1
        self.BSGL = False

        self.tref = self.par['tref']
        self.F1s = [self.par.get('F1', 0)]
        self.F2s = [self.par.get('F2', 0)]
        self.Alphas = [self.par['Alpha']]
        self.Deltas = [self.par['Delta']]
        self.Re = 6.371e6
        self.c = 2.998e8
1023
        a0 = self.Re/self.c  # *np.cos(self.par['Delta'])
1024
        self.m0 = np.max([4, int(np.ceil(2*np.pi*self.par['F0']*a0))])
1025
1026
        logging.info(
            'Setting up DMoff_NO_SPIN search with m0 = {}'.format(self.m0))
1027
1028
1029
1030
1031
1032
1033
1034
1035

    def get_results(self):
        """ Compute the three summed detection statistics

        Returns
        -------
            m0, twoF_SUM, twoFstar_SUM_SIDEREAL, twoFstar_SUM_TERRESTRIAL

        """
Gregory Ashton's avatar
Gregory Ashton committed
1036
1037
1038
        self.SSBprec = lalpulsar.SSBPREC_RELATIVISTIC
        self.set_out_file('SSBPREC_RELATIVISTIC')
        self.F0s = [self.par['F0']+j/lal.DAYSID_SI for j in range(-4, 5)]
1039
1040
1041
        self.run()
        twoF_SUM = np.sum(self.data[:, -1])

Gregory Ashton's avatar
Gregory Ashton committed
1042
1043
1044
        self.SSBprec = lalpulsar.SSBPREC_NO_SPIN
        self.set_out_file('SSBPREC_NO_SPIN')
        self.F0s = [self.par['F0']+j/lal.DAYSID_SI
1045
1046
1047
1048
                    for j in range(-self.m0, self.m0+1)]
        self.run()
        twoFstar_SUM = np.sum(self.data[:, -1])

Gregory Ashton's avatar
Gregory Ashton committed
1049
1050
        self.set_out_file('SSBPREC_NO_SPIN_TERRESTRIAL')
        self.F0s = [self.par['F0']+j/lal.DAYJUL_SI
1051
1052
1053
1054
1055
                    for j in range(-self.m0, self.m0+1)]
        self.run()
        twoFstar_SUM_terrestrial = np.sum(self.data[:, -1])

        return self.m0, twoF_SUM, twoFstar_SUM, twoFstar_SUM_terrestrial