grid_based_searches.py 26.8 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
8
9
10
11
12

import os
import logging
import itertools
from collections import OrderedDict

import numpy as np
import matplotlib
import matplotlib.pyplot as plt

13
14
15
import pyfstat.helper_functions as helper_functions
from pyfstat.core import (BaseSearchClass, ComputeFstat,
                          SemiCoherentGlitchSearch, SemiCoherentSearch, tqdm,
16
                          args, read_par)
Gregory Ashton's avatar
Gregory Ashton committed
17
18
import lalpulsar
import lal
Gregory Ashton's avatar
Gregory Ashton committed
19
20
21
22


class GridSearch(BaseSearchClass):
    """ Gridded search using ComputeFstat """
Gregory Ashton's avatar
Gregory Ashton committed
23
24
25
    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$',
26
                   'Alpha': r'$-\alpha_0$', 'Delta': r'$-\delta_0$'}
Gregory Ashton's avatar
Gregory Ashton committed
27

Gregory Ashton's avatar
Gregory Ashton committed
28
    @helper_functions.initializer
Gregory Ashton's avatar
Gregory Ashton committed
29
30
31
32
33
    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):
Gregory Ashton's avatar
Gregory Ashton committed
34
35
36
37
38
        """
        Parameters
        ----------
        label, outdir: str
            A label and directory to read/write data from/to
39
40
41
        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
42
43
        F0s, F1s, F2s, delta_F0s, delta_F1s, tglitchs, Alphas, Deltas: tuple
            Length 3 tuple describing the grid for each parameter, e.g
44
45
            [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
46
47
        tref, minStartTime, maxStartTime: int
            GPS seconds of the reference time, start time and end time
48
49
        input_arrays: bool
            if true, use the F0s, F1s, etc as is
Gregory Ashton's avatar
Gregory Ashton committed
50
51
52
53
54
55

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

        if os.path.isdir(outdir) is False:
            os.mkdir(outdir)
56
        self.set_out_file()
Gregory Ashton's avatar
Gregory Ashton committed
57
        self.keys = ['_', '_', 'F0', 'F1', 'F2', 'Alpha', 'Delta']
Gregory Ashton's avatar
Gregory Ashton committed
58
59
60
        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
61
62
63

    def inititate_search_object(self):
        logging.info('Setting up search object')
64
65
        if self.nsegs == 1:
            self.search = ComputeFstat(
66
                tref=self.tref, sftfilepattern=self.sftfilepattern,
67
68
69
                minCoverFreq=self.minCoverFreq, maxCoverFreq=self.maxCoverFreq,
                detectors=self.detectors, transient=False,
                minStartTime=self.minStartTime, maxStartTime=self.maxStartTime,
70
                BSGL=self.BSGL, SSBprec=self.SSBprec,
71
72
                injectSources=self.injectSources,
                assumeSqrtSX=self.assumeSqrtSX)
73
            self.search.get_det_stat = self.search.get_fullycoherent_twoF
74
75
76
        else:
            self.search = SemiCoherentSearch(
                label=self.label, outdir=self.outdir, tref=self.tref,
77
                nsegs=self.nsegs, sftfilepattern=self.sftfilepattern,
78
79
80
                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
81
                injectSources=self.injectSources)
82
83

            def cut_out_tstart_tend(*vals):
84
                return self.search.get_semicoherent_twoF(*vals[2:])
85
            self.search.get_det_stat = cut_out_tstart_tend
Gregory Ashton's avatar
Gregory Ashton committed
86
87
88
89

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

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

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

    def check_old_data_is_okay_to_use(self):
        if args.clean:
            return False
        if os.path.isfile(self.out_file) is False:
            logging.info('No old data found, continuing with grid search')
            return False
115
        if self.sftfilepattern is not None:
116
117
118
119
120
121
            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
122

123
124
125
126
127
128
129
130
131
        data = np.atleast_2d(np.genfromtxt(self.out_file, delimiter=' '))
        if np.all(data[:, 0:-1] == self.input_data):
            logging.info(
                'Old data found with matching input, no search performed')
            return data
        else:
            logging.info(
                'Old data found, input differs, continuing with grid search')
            return False
132
        return False
Gregory Ashton's avatar
Gregory Ashton committed
133
134
135
136
137
138
139
140

    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
141
142
        if hasattr(self, 'search') is False:
            self.inititate_search_object()
Gregory Ashton's avatar
Gregory Ashton committed
143
144

        data = []
145
        for vals in tqdm(self.input_data):
146
            FS = self.search.get_det_stat(*vals)
Gregory Ashton's avatar
Gregory Ashton committed
147
148
            data.append(list(vals) + [FS])

149
        data = np.array(data, dtype=np.float)
Gregory Ashton's avatar
Gregory Ashton committed
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
        if return_data:
            return data
        else:
            logging.info('Saving data to {}'.format(self.out_file))
            np.savetxt(self.out_file, data, delimiter=' ')
            self.data = data

    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
183
184
185
    def plot_1D(self, xkey, ax=None, x0=None, savefig=True):
        if ax is None:
            fig, ax = plt.subplots()
Gregory Ashton's avatar
Gregory Ashton committed
186
187
        xidx = self.keys.index(xkey)
        x = np.unique(self.data[:, xidx])
188
189
        if x0:
            x = x - x0
Gregory Ashton's avatar
Gregory Ashton committed
190
        z = self.data[:, -1]
Gregory Ashton's avatar
Gregory Ashton committed
191
192
193
194
195
196
197
198
199
        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])
        if savefig:
            fig.savefig('{}/{}_1D.png'.format(self.outdir, self.label))
        else:
            return ax
Gregory Ashton's avatar
Gregory Ashton committed
200
201
202

    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
203
                rel_flat_idxs=[], flatten_method=np.max, title=None,
Gregory Ashton's avatar
Gregory Ashton committed
204
205
                predicted_twoF=None, cm=None, cbarkwargs={}, x0=None, y0=None,
                colorbar=False):
Gregory Ashton's avatar
Gregory Ashton committed
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
        """ 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])
223
224
        if x0:
            x = x-x0
Gregory Ashton's avatar
Gregory Ashton committed
225
        y = np.unique(self.data[:, yidx])
226
227
        if y0:
            y = y-y0
Gregory Ashton's avatar
Gregory Ashton committed
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
        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
247
248
249
        if colorbar:
            cb = plt.colorbar(pax, ax=ax, **cbarkwargs)
            cb.set_label('$2\mathcal{F}$')
Gregory Ashton's avatar
Gregory Ashton committed
250
251
252
253
254
255

        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])
256
        if x0:
Gregory Ashton's avatar
Gregory Ashton committed
257
            ax.set_xlabel(self.tex_labels[xkey]+self.tex_labels0[xkey])
258
        else:
Gregory Ashton's avatar
Gregory Ashton committed
259
            ax.set_xlabel(self.tex_labels[xkey])
260
        if y0:
Gregory Ashton's avatar
Gregory Ashton committed
261
            ax.set_ylabel(self.tex_labels[ykey]+self.tex_labels0[ykey])
262
        else:
Gregory Ashton's avatar
Gregory Ashton committed
263
            ax.set_ylabel(self.tex_labels[ykey])
Gregory Ashton's avatar
Gregory Ashton committed
264

Gregory Ashton's avatar
Gregory Ashton committed
265
266
267
        if title:
            ax.set_title(title)

Gregory Ashton's avatar
Gregory Ashton committed
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
        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):
        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))

293
    def set_out_file(self, extra_label=None):
294
295
296
297
        if self.detectors:
            dets = self.detectors.replace(',', '')
        else:
            dets = 'NA'
298
299
300
301
302
303
304
305
        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
306

Gregory Ashton's avatar
Gregory Ashton committed
307
308
309
class SliceGridSearch(GridSearch):
    """ Slice gridded search using ComputeFstat """
    @helper_functions.initializer
Gregory Ashton's avatar
Gregory Ashton committed
310
311
312
313
314
    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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
        """
        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
339
340
341
        self.ndim = 0
        self.thetas = [F0s, F1s, Alphas, Deltas]
        self.ndim = 4
Gregory Ashton's avatar
Gregory Ashton committed
342

Gregory Ashton's avatar
Gregory Ashton committed
343
        self.search_keys = ['F0', 'F1', 'Alpha', 'Delta']
Gregory Ashton's avatar
Gregory Ashton committed
344
        self.Lambda0 = np.array(Lambda0)
Gregory Ashton's avatar
Gregory Ashton committed
345
        if len(self.Lambda0) != len(self.search_keys):
Gregory Ashton's avatar
Gregory Ashton committed
346
            raise ValueError(
Gregory Ashton's avatar
Gregory Ashton committed
347
348
                'Lambda0 must be of length {}'.format(len(self.search_keys)))

349
350
    def run(self, factor=2, max_n_ticks=4, whspace=0.07, save=True,
            **kwargs):
Gregory Ashton's avatar
Gregory Ashton committed
351
        lbdim = 0.5 * factor   # size of left/bottom margin
352
        trdim = 0.4 * factor   # size of top/right margin
Gregory Ashton's avatar
Gregory Ashton committed
353
354
355
356
357
358
359
360
361
362
363
364
365
366
        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],
367
368
            Alphas=self.Lambda0[2], Deltas=self.Lambda0[3], tref=self.tref,
            minStartTime=self.minStartTime, maxStartTime=self.maxStartTime)
Gregory Ashton's avatar
Gregory Ashton committed
369
370
371

        for i, ikey in enumerate(self.search_keys):
            setattr(search, ikey+'s', self.thetas[i])
372
373
            search.label = '{}_{}'.format(self.label, ikey)
            search.set_out_file()
Gregory Ashton's avatar
Gregory Ashton committed
374
            search.run()
375
376
377
            axes[i, i] = search.plot_1D(ikey, ax=axes[i, i], savefig=False,
                                        x0=self.Lambda0[i]
                                        )
Gregory Ashton's avatar
Gregory Ashton committed
378
            setattr(search, ikey+'s', [self.Lambda0[i]])
379
380
381
            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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408

            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])
409
410
                search.label = '{}_{}'.format(self.label, ikey+jkey)
                search.set_out_file()
Gregory Ashton's avatar
Gregory Ashton committed
411
                search.run()
412
                ax = search.plot_2D(jkey, ikey, ax=ax, save=False,
413
414
                                    y0=self.Lambda0[i], x0=self.Lambda0[j],
                                    **kwargs)
Gregory Ashton's avatar
Gregory Ashton committed
415
416
417
                setattr(search, ikey+'s', [self.Lambda0[i]])
                setattr(search, jkey+'s', [self.Lambda0[j]])

418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
                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
435
436


Gregory Ashton's avatar
Gregory Ashton committed
437
class GridUniformPriorSearch():
438
    @helper_functions.initializer
439
    def __init__(self, theta_prior, NF0, NF1, label, outdir, sftfilepattern,
440
                 tref, minStartTime, maxStartTime, minCoverFreq=None,
441
                 maxCoverFreq=None, BSGL=False, detectors=None, nsegs=1,
442
                 SSBprec=None, injectSources=None):
Gregory Ashton's avatar
Gregory Ashton committed
443
444
445
446
        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]
447
        self.search = GridSearch(
448
            label, outdir, sftfilepattern, F0s=F0s, F1s=F1s, tref=tref,
Gregory Ashton's avatar
Gregory Ashton committed
449
450
            Alphas=[theta_prior['Alpha']], Deltas=[theta_prior['Delta']],
            minStartTime=minStartTime, maxStartTime=maxStartTime, BSGL=BSGL,
451
            detectors=detectors, minCoverFreq=minCoverFreq,
452
453
            injectSources=injectSources, maxCoverFreq=maxCoverFreq,
            nsegs=nsegs, SSBprec=SSBprec)
454

455
    def run(self):
456
        self.search.run()
457
458

    def get_2D_plot(self, **kwargs):
459
        return self.search.plot_2D('F0', 'F1', **kwargs)
Gregory Ashton's avatar
Gregory Ashton committed
460
461


Gregory Ashton's avatar
Gregory Ashton committed
462
463
464
class GridGlitchSearch(GridSearch):
    """ Grid search using the SemiCoherentGlitchSearch """
    @helper_functions.initializer
465
    def __init__(self, label, outdir, sftfilepattern=None, F0s=[0],
Gregory Ashton's avatar
Gregory Ashton committed
466
467
468
                 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,
469
                 write_after=1000):
Gregory Ashton's avatar
Gregory Ashton committed
470
471
472
473
474
475

        """
        Parameters
        ----------
        label, outdir: str
            A label and directory to read/write data from/to
476
477
478
        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
479
480
481
482
483
484
485
486
487
488
489
490
        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].
        tref, minStartTime, maxStartTime: int
            GPS seconds of the reference time, start time and end time

        For all other parameters, see pyfstat.ComputeFStat.
        """
        if tglitchs is None:
            self.tglitchs = [self.maxStartTime]

        self.search = SemiCoherentGlitchSearch(
491
            label=label, outdir=outdir, sftfilepattern=self.sftfilepattern,
Gregory Ashton's avatar
Gregory Ashton committed
492
493
494
495
496
497
            tref=tref, minStartTime=minStartTime, maxStartTime=maxStartTime,
            minCoverFreq=minCoverFreq, maxCoverFreq=maxCoverFreq,
            BSGL=self.BSGL)

        if os.path.isdir(outdir) is False:
            os.mkdir(outdir)
498
        self.set_out_file()
Gregory Ashton's avatar
Gregory Ashton committed
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
        self.keys = ['F0', 'F1', 'F2', 'Alpha', 'Delta', 'delta_F0',
                     'delta_F1', 'tglitch']

    def get_input_data_array(self):
        arrays = []
        for tup in (self.F0s, self.F1s, self.F2s, self.Alphas, self.Deltas,
                    self.delta_F0s, self.delta_F1s, self.tglitchs):
            arrays.append(self.get_array_from_tuple(tup))

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

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


Gregory Ashton's avatar
Gregory Ashton committed
516
517
518
class FrequencySlidingWindow(GridSearch):
    """ A sliding-window search over the Frequency """
    @helper_functions.initializer
519
    def __init__(self, label, outdir, sftfilepattern, F0s, F1, F2,
Gregory Ashton's avatar
Gregory Ashton committed
520
521
522
                 Alpha, Delta, tref, minStartTime=None,
                 maxStartTime=None, window_size=10*86400, window_delta=86400,
                 BSGL=False, minCoverFreq=None, maxCoverFreq=None,
523
                 detectors=None, SSBprec=None, injectSources=None):
Gregory Ashton's avatar
Gregory Ashton committed
524
525
526
527
528
        """
        Parameters
        ----------
        label, outdir: str
            A label and directory to read/write data from/to
529
530
531
        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
532
533
534
535
536
537
538
539
540
541
542
543
        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
        """

        if os.path.isdir(outdir) is False:
            os.mkdir(outdir)
544
        self.set_out_file()
Gregory Ashton's avatar
Gregory Ashton committed
545
546
547
548
549
        self.nsegs = 1
        self.F1s = [F1]
        self.F2s = [F2]
        self.Alphas = [Alpha]
        self.Deltas = [Delta]
550
        self.input_arrays = False
Gregory Ashton's avatar
Gregory Ashton committed
551

Gregory Ashton's avatar
Gregory Ashton committed
552
553
554
    def inititate_search_object(self):
        logging.info('Setting up search object')
        self.search = ComputeFstat(
555
            tref=self.tref, sftfilepattern=self.sftfilepattern,
Gregory Ashton's avatar
Gregory Ashton committed
556
557
558
            minCoverFreq=self.minCoverFreq, maxCoverFreq=self.maxCoverFreq,
            detectors=self.detectors, transient=True,
            minStartTime=self.minStartTime, maxStartTime=self.maxStartTime,
Gregory Ashton's avatar
Gregory Ashton committed
559
560
            BSGL=self.BSGL, SSBprec=self.SSBprec,
            injectSources=self.injectSources)
Gregory Ashton's avatar
Gregory Ashton committed
561
        self.search.get_det_stat = (
562
            self.search.get_fullycoherent_twoF)
Gregory Ashton's avatar
Gregory Ashton committed
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585

    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,
586
                            colorbar=True, timestamps=False):
Gregory Ashton's avatar
Gregory Ashton committed
587
588
589
590
591
592
593
594
595
596
597
        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
598
            ax.set_ylabel('Frequency - $f_0$ [Hz] \n $f_0={:0.2f}$'.format(F0))
Gregory Ashton's avatar
Gregory Ashton committed
599
600
601
602
603
604
605
606
607
        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(
608
609
            r'Mid-point (days after $t_\mathrm{{start}}$={})'.format(
                self.minStartTime))
Gregory Ashton's avatar
Gregory Ashton committed
610
611
        ax.set_title(
            'Sliding window length = {} days in increments of {} days'
612
613
614
615
616
617
618
            .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
619
620
621
622
623
624
        if savefig:
            plt.tight_layout()
            plt.savefig(
                '{}/{}_sliding_window.png'.format(self.outdir, self.label))
        else:
            return ax
625
626
627
628
629


class DMoff_NO_SPIN(GridSearch):
    """ DMoff test using SSBPREC_NO_SPIN """
    @helper_functions.initializer
630
    def __init__(self, par, label, outdir, sftfilepattern, minStartTime=None,
631
                 maxStartTime=None, minCoverFreq=None, maxCoverFreq=None,
632
                 detectors=None, injectSources=None, assumeSqrtSX=None):
633
634
635
        """
        Parameters
        ----------
636
637
638
        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
639
640
        label, outdir: str
            A label and directory to read/write data from/to
641
642
643
        sftfilepattern: str
            Pattern to match SFTs using wildcards (*?) and ranges [0-9];
            mutiple patterns can be given separated by colons.
644
645
646
647
648
649
650
651
652
        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)

653
654
655
656
        if type(par) == dict:
            self.par = par
        elif type(par) == str and os.path.isfile(par):
            self.par = read_par(filename=par)
657
658
659
660
661
662
663
664
665
666
667
668
669
        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
670
        a0 = self.Re/self.c  # *np.cos(self.par['Delta'])
671
        self.m0 = np.max([4, int(np.ceil(2*np.pi*self.par['F0']*a0))])
672
673
        logging.info(
            'Setting up DMoff_NO_SPIN search with m0 = {}'.format(self.m0))
674
675
676
677
678
679
680
681
682

    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
683
684
685
        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)]
686
687
688
        self.run()
        twoF_SUM = np.sum(self.data[:, -1])

Gregory Ashton's avatar
Gregory Ashton committed
689
690
691
        self.SSBprec = lalpulsar.SSBPREC_NO_SPIN
        self.set_out_file('SSBPREC_NO_SPIN')
        self.F0s = [self.par['F0']+j/lal.DAYSID_SI
692
693
694
695
                    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
696
697
        self.set_out_file('SSBPREC_NO_SPIN_TERRESTRIAL')
        self.F0s = [self.par['F0']+j/lal.DAYJUL_SI
698
699
700
701
702
                    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