lalinference_pipe_utils.py 138 KB
Newer Older
1

2
#flow DAG Class definitions for LALInference Pipeline
3
# (C) 2012 John Veitch, Vivien Raymond, Kiersten Ruisard, Kan Wang
4

John Douglas Veitch's avatar
John Douglas Veitch committed
5
import itertools
6
import glue
7
8
9
from glue import pipeline
from ligo import segments
from ligo.segments import utils as segmentsUtils
10
11
from glue.ligolw import ligolw, lsctables
from glue.ligolw import utils as ligolw_utils
12
import os
13
import socket
14
15
import uuid
import ast
16
import pdb
John Douglas Veitch's avatar
John Douglas Veitch committed
17
import string
18
from math import floor,ceil,log,pow
19
import sys
20
import random
21
from itertools import permutations
22
import shutil
23
import numpy as np
24
import math
25
from six.moves import range
26
from six import next
27
from functools import reduce
28
29
30
31
32

# We use the GLUE pipeline utilities to construct classes for each
# type of job. Each class has inputs and outputs, which are used to
# join together types of jobs into a DAG.

33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def findSegmentsToAnalyze(flag, gpsstart, gpsend, url=None):
    """
    Return segments with given DQ flag
    Parameters
    ----
    flag : string
        name of DQ flag
    gpsstart, gpsend : float
        GPS period to analyse
    """
    try:
        from gwpy.segments import DataQualityFlag
    except ImportError:
        print('Unable to import gwpy. Querying science segments not possible. Please try installing gwpy')
        raise
    if url is None:
49
        return DataQualityFlag.query_dqsegdb(flag, gpsstart, gpsend).active
50
    else:
51
        return DataQualityFlag.query_dqsegdb(flag, gpsstart, gpsend, url=url).active
52

53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
def guess_url(fslocation):
    """
    Try to work out the web address of a given path
    """
    SERVER="localhost"
    USER=os.environ['USER']
    HOST=socket.getfqdn()
    if 'public_html' in fslocation:
        k='public_html/'
    elif 'WWW' in fslocation:
        k='WWW/'
    elif 'www_html' in fslocation:
        k='www_html/'
    else:
        k=None
    if k is not None:
        (a,b)=fslocation.split(k)
        webpath=os.path.join('~%s'%(USER),b)
        onweb=True
    else:
73
        (c,d)=fslocation.split(USER,1)
74
75
76
77
        for k in ['public_html','WWW','www_html']:
            trypath=c+os.environ['USER']+'/'+k+d
            #Follow symlinks
            if os.path.realpath(trypath)==os.path.normpath(fslocation):
78
79
                #(a,b)=trypath.split(k)
                webpath=os.path.join('~%s'%(USER),d)
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
                onweb=True
                break
            else:
                webpath=fslocation
                onweb=False
    if 'atlas' in HOST:
        url="https://atlas1.atlas.aei.uni-hannover.de/"
    elif 'cit' in HOST or 'caltech' in HOST:
        url="https://ldas-jobs.ligo.caltech.edu/"
    elif 'ligo-wa' in HOST:
        url="https://ldas-jobs.ligo-wa.caltech.edu/"
    elif 'ligo-la' in HOST:
        url="https://ldas-jobs.ligo-la.caltech.edu/"
    elif 'uwm' in HOST or 'nemo' in HOST:
        url="https://ldas-jobs.phys.uwm.edu/"
    elif 'phy.syr.edu' in HOST:
        url="https://sugar-jobs.phy.syr.edu/"
    elif 'arcca.cf.ac.uk' in HOST:
        url="https://geo2.arcca.cf.ac.uk/"
    elif 'vulcan' in HOST:
        url="https://galahad.aei.mpg.de/"
    else:
        if onweb:
103
            url="http://%s/"%(HOST)
104
        else:
105
            url=HOST+':'
106
107
108
    url=url+webpath
    return(url)

John Douglas Veitch's avatar
John Douglas Veitch committed
109
class Event():
110
    """
111
    Represents a unique event to run on
112
    """
113
    new_id=itertools.count()
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
    def __init__(self,trig_time=None,SimInspiral=None,SimBurst=None,SnglInspiral=None,CoincInspiral=None,event_id=None,timeslide_dict=None,GID=None,ifos=None, duration=None,srate=None,trigSNR=None,fhigh=None,horizon_distance=None):
        self.trig_time=trig_time
        self.injection=SimInspiral
        self.burstinjection=SimBurst
        self.sngltrigger=SnglInspiral
        if timeslide_dict is None:
            self.timeslides={}
        else:
            self.timeslides=timeslide_dict
        self.GID=GID
        self.coinctrigger=CoincInspiral
        if ifos is None:
            self.ifos = []
        else:
            self.ifos = ifos
        self.duration = duration
        self.srate = srate
        self.trigSNR = trigSNR
        self.fhigh = fhigh
        self.horizon_distance = horizon_distance
        if event_id is not None:
            self.event_id=event_id
        else:
137
            self.event_id=next(Event.new_id)
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
        if self.injection is not None:
            self.trig_time=self.injection.get_end()
            if event_id is None: self.event_id=int(str(self.injection.simulation_id).split(':')[2])
        if self.burstinjection is not None:
            self.trig_time=self.burstinjection.get_end()
            if event_id is None: self.event_id=int(str(self.burstinjection.simulation_id).split(':')[2])
        if self.sngltrigger is not None:
            self.trig_time=self.sngltrigger.get_end()
            self.event_id=int(str(self.sngltrigger.event_id).split(':')[2])
        if self.coinctrigger is not None:
            self.trig_time=self.coinctrigger.end_time + 1.0e-9 * self.coinctrigger.end_time_ns
        if self.GID is not None:
            self.event_id=int(''.join(i for i in self.GID if i.isdigit()))
        self.engine_opts={}
    def set_engine_option(self,opt,val):
        """
        Can set event-specific options for the engine nodes
        using this option, e.g. ev.set_engine_option('time-min','1083759273')
        """
        self.engine_opts[opt]=val
John Douglas Veitch's avatar
John Douglas Veitch committed
158
159

dummyCacheNames=['LALLIGO','LALVirgo','LALAdLIGO','LALAdVirgo']
John Douglas Veitch's avatar
John Douglas Veitch committed
160

161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
def create_events_from_coinc_and_psd(
    coinc_xml_obj, psd_dict, gid=None, threshold_snr=None, flow=20.0, roq=False
):
    """This function calculates seglen, fhigh, srate and horizon distance from
    coinc.xml and psd.xml.gz from GraceDB and create list of Events as input of
    pipeline. This function is based on Chris Pankow's script.

    Parameters
    ----------
    coinc_xml_obj: glue.ligolw.ligolw.Document
        file object of coinc.xml
    psd_dict: dictionary of REAL8FrequencySeries
        PSDs of all the ifos
    threshold_snr: float
        snr threshold for detection
    flow: float
        lower frequecy cutoff for overlap calculation
    roq: bool
        Whether the run uses ROQ or not
180
181
182
183
184
185
    """
    output=[]
    from lal import series as lalseries
    import lal
    from lalsimulation import SimInspiralChirpTimeBound, GetApproximantFromString, IMRPhenomDGetPeakFreq
    from ligo.gracedb.rest import GraceDb, HTTPError
186
    try:
187
188
189
        from gstlal import reference_psd
    except ImportError:
        reference_psd = None
190
191
    coinc_events = lsctables.CoincInspiralTable.get_table(coinc_xml_obj)
    sngl_event_idx = dict((row.event_id, row) for row in lsctables.SnglInspiralTable.get_table(coinc_xml_obj))
192
193
194
195
196
    ifos = sorted(coinc_events[0].instruments)
    trigSNR = coinc_events[0].snr
    # Parse PSD
    srate_psdfile=16384
    fhigh=None
197
198
199
200
201
202
    if psd_dict is not None:
        psd = list(psd_dict.values())[0]
        srate_psdfile = pow(
            2.0, ceil(log(psd.f0 + psd.deltaF * (psd.data.length - 1), 2))
        ) * 2
    coinc_map = lsctables.CoincMapTable.get_table(coinc_xml_obj)
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
    for coinc in coinc_events:
        these_sngls = [sngl_event_idx[c.event_id] for c in coinc_map if c.coinc_event_id == coinc.coinc_event_id]
        dur=[]
        srate=[]
        horizon_distance=[]
        for e in these_sngls:
            if roq==False:
                chirplen = SimInspiralChirpTimeBound(flow, e.mass1 * lal.MSUN_SI, e.mass2 * lal.MSUN_SI, 0.0, 0.0)
                fstop = IMRPhenomDGetPeakFreq(e.mass1, e.mass2, 0.0, 0.0)
                dur.append(pow(2.0, ceil( log(max(8.0, chirplen + 2.0), 2) ) ) )
                srate.append(pow(2.0, ceil( log(fstop, 2) ) ) * 2)
            # determine horizon distance
            if threshold_snr is not None:
                if e.eff_distance is not None and not math.isnan(e.eff_distance):
                    if e.snr > threshold_snr:
                        horizon_distance.append(e.eff_distance * e.snr / threshold_snr)
                    else:
                        horizon_distance.append(2 * e.eff_distance)
                else:
222
                    if reference_psd is not None and psd_dict is not None:
223
224
225
                        if not roq==False:
                            fstop = IMRPhenomDGetPeakFreq(e.mass1, e.mass2, 0.0, 0.0)
                        HorizonDistanceObj = reference_psd.HorizonDistance(f_min = flow, f_max = fstop, delta_f = 1.0 / 32.0, m1 = e.mass1, m2 = e.mass2)
226
                        horizon_distance.append(HorizonDistanceObj(psd_dict[e.ifo], snr = threshold_snr)[0])
227
228
229
230
231
        if srate:
            if max(srate)<srate_psdfile:
                srate = max(srate)
            else:
                srate = srate_psdfile
232
                if psd_dict is not None:
233
234
235
236
237
238
239
240
241
242
243
                    fhigh = srate_psdfile/2.0 * 0.95 # Because of the drop-off near Nyquist of the PSD from gstlal
        else:
            srate = None
        if dur:
            duration = max(dur)
        else:
            duration = None
        horizon_distance = max(horizon_distance) if len(horizon_distance) > 0 else None
        ev=Event(CoincInspiral=coinc, GID=gid, ifos = ifos, duration = duration, srate = srate,
                 trigSNR = trigSNR, fhigh = fhigh, horizon_distance=horizon_distance)
        output.append(ev)
244

245
246
    print("Found %d coinc events in table." % len(coinc_events))
    return output
247

248
249
250
251
252
def open_pipedown_database(database_filename,tmp_space):
    """
    Open the connection to the pipedown database
    """
    if not os.access(database_filename,os.R_OK):
253
        raise Exception('Unable to open input file: %s'%(database_filename))
254
    from glue.ligolw import dbtables
255
    import sqlite3
256
257
258
    working_filename=dbtables.get_connection_filename(database_filename,tmp_path=tmp_space)
    connection = sqlite3.connect(working_filename)
    if tmp_space:
259
        dbtables.set_temp_store_directory(connection,tmp_space)
260
    #dbtables.DBTable_set_connection(connection)
261
    return (connection,working_filename)
262

263
def get_zerolag_lloid(database_connection, dumpfile=None, gpsstart=None, gpsend=None, max_cfar=-1, min_cfar=-1):
264
265
266
267
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
293
294
295
296
297
298
299
300
301
302
303
304
    """
    Returns a list of Event objects
    from pipedown data base. Can dump some stats to dumpfile if given,
    and filter by gpsstart and gpsend to reduce the nunmber or specify
    max_cfar to select by combined FAR
    """
    output={}
    if gpsstart is not None: gpsstart=float(gpsstart)
    if gpsend is not None: gpsend=float(gpsend)
    # Get coincs
    get_coincs = "SELECT sngl_inspiral.end_time+sngl_inspiral.end_time_ns*1e-9,sngl_inspiral.ifo,coinc_event.coinc_event_id,sngl_inspiral.snr,sngl_inspiral.chisq,coinc_inspiral.combined_far \
            FROM sngl_inspiral join coinc_event_map on (coinc_event_map.table_name=='sngl_inspiral' and coinc_event_map.event_id ==\
            sngl_inspiral.event_id) join coinc_event on (coinc_event.coinc_event_id==coinc_event_map.coinc_event_id) \
            join coinc_inspiral on (coinc_event.coinc_event_id==coinc_inspiral.coinc_event_id) \
    WHERE coinc_event.time_slide_id=='time_slide:time_slide_id:1'\
            "
    if gpsstart is not None:
        get_coincs=get_coincs+' and coinc_inspiral.end_time+coinc_inspiral.end_time_ns*1.0e-9 > %f'%(gpsstart)
    if gpsend is not None:
        get_coincs=get_coincs+' and coinc_inspiral.end_time+coinc_inspiral.end_time_ns*1.0e-9 < %f'%(gpsend)
    if max_cfar !=-1:
        get_coincs=get_coincs+' and coinc_inspiral.combined_far < %f'%(max_cfar)
    if min_cfar != -1:
        get_coincs=get_coincs+' and coinc_inspiral.combined_far > %f'%(min_cfar)
    db_out=database_connection.cursor().execute(get_coincs)
    extra={}
    for (sngl_time, ifo, coinc_id, snr, chisq, cfar) in db_out:
        coinc_id=int(coinc_id.split(":")[-1])
        if not coinc_id in output.keys():
            output[coinc_id]=Event(trig_time=sngl_time,timeslide_dict={},event_id=int(coinc_id))
            extra[coinc_id]={}
        output[coinc_id].timeslides[ifo]=0
        output[coinc_id].ifos.append(ifo)
        extra[coinc_id][ifo]={'snr':snr,'chisq':chisq,'cfar':cfar}
    if dumpfile is not None:
        fh=open(dumpfile,'w')
        for co in output.keys():
            for ifo in output[co].ifos:
                fh.write('%s %s %s %s %s %s %s\n'%(str(co),ifo,str(output[co].trig_time),str(output[co].timeslides[ifo]),str(extra[co][ifo]['snr']),str(extra[co][ifo]['chisq']),str(extra[co][ifo]['cfar'])))
        fh.close()
    return output.values()
305

306
def get_zerolag_pipedown(database_connection, dumpfile=None, gpsstart=None, gpsend=None, max_cfar=-1, min_cfar=-1):
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
    """
    Returns a list of Event objects
    from pipedown data base. Can dump some stats to dumpfile if given,
    and filter by gpsstart and gpsend to reduce the nunmber or specify
    max_cfar to select by combined FAR
    """
    output={}
    if gpsstart is not None: gpsstart=float(gpsstart)
    if gpsend is not None: gpsend=float(gpsend)
    # Get coincs
    get_coincs = "SELECT sngl_inspiral.end_time+sngl_inspiral.end_time_ns*1e-9,sngl_inspiral.ifo,coinc_event.coinc_event_id,sngl_inspiral.snr,sngl_inspiral.chisq,coinc_inspiral.combined_far \
            FROM sngl_inspiral join coinc_event_map on (coinc_event_map.table_name=='sngl_inspiral' and coinc_event_map.event_id ==\
            sngl_inspiral.event_id) join coinc_event on (coinc_event.coinc_event_id==coinc_event_map.coinc_event_id) \
            join coinc_inspiral on (coinc_event.coinc_event_id==coinc_inspiral.coinc_event_id) \
            WHERE coinc_event.time_slide_id=='time_slide:time_slide_id:10049'\
            "
    if gpsstart is not None:
        get_coincs=get_coincs+' and coinc_inspiral.end_time+coinc_inspiral.end_time_ns*1.0e-9 > %f'%(gpsstart)
    if gpsend is not None:
        get_coincs=get_coincs+' and coinc_inspiral.end_time+coinc_inspiral.end_time_ns*1.0e-9 < %f'%(gpsend)
    if max_cfar !=-1:
        get_coincs=get_coincs+' and coinc_inspiral.combined_far < %f'%(max_cfar)
    if min_cfar != -1:
        get_coincs=get_coincs+' and coinc_inspiral.combined_far > %f'%(min_cfar)
    db_out=database_connection.cursor().execute(get_coincs)
    extra={}
    for (sngl_time, ifo, coinc_id, snr, chisq, cfar) in db_out:
        coinc_id=int(coinc_id.split(":")[-1])
        if not coinc_id in output.keys():
            output[coinc_id]=Event(trig_time=sngl_time,timeslide_dict={},event_id=int(coinc_id))
            extra[coinc_id]={}
        output[coinc_id].timeslides[ifo]=0
        output[coinc_id].ifos.append(ifo)
        extra[coinc_id][ifo]={'snr':snr,'chisq':chisq,'cfar':cfar}
    if dumpfile is not None:
        fh=open(dumpfile,'w')
        for co in output.keys():
            for ifo in output[co].ifos:
                fh.write('%s %s %s %s %s %s %s\n'%(str(co),ifo,str(output[co].trig_time),str(output[co].timeslides[ifo]),str(extra[co][ifo]['snr']),str(extra[co][ifo]['chisq']),str(extra[co][ifo]['cfar'])))
        fh.close()
    return output.values()
348

349
def get_timeslides_pipedown(database_connection, dumpfile=None, gpsstart=None, gpsend=None, max_cfar=-1):
350
351
352
353
354
355
356
357
358
359
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
    """
    Returns a list of Event objects
    with times and timeslide offsets
    """
    output={}
    if gpsstart is not None: gpsstart=float(gpsstart)
    if gpsend is not None: gpsend=float(gpsend)
    db_segments=[]
    sql_seg_query="SELECT search_summary.out_start_time, search_summary.out_end_time from search_summary join process on process.process_id==search_summary.process_id where process.program=='thinca'"
    db_out = database_connection.cursor().execute(sql_seg_query)
    for d in db_out:
        if d not in db_segments:
            db_segments.append(d)
    seglist=segments.segmentlist([segments.segment(d[0],d[1]) for d in db_segments])
    db_out_saved=[]
    # Get coincidences
    get_coincs="SELECT sngl_inspiral.end_time+sngl_inspiral.end_time_ns*1e-9,time_slide.offset,sngl_inspiral.ifo,coinc_event.coinc_event_id,sngl_inspiral.snr,sngl_inspiral.chisq,coinc_inspiral.combined_far \
                FROM sngl_inspiral join coinc_event_map on (coinc_event_map.table_name == 'sngl_inspiral' and coinc_event_map.event_id \
                == sngl_inspiral.event_id) join coinc_event on (coinc_event.coinc_event_id==coinc_event_map.coinc_event_id) join time_slide\
                on (time_slide.time_slide_id == coinc_event.time_slide_id and time_slide.instrument==sngl_inspiral.ifo)\
                join coinc_inspiral on (coinc_inspiral.coinc_event_id==coinc_event.coinc_event_id) where coinc_event.time_slide_id!='time_slide:time_slide_id:10049'"
    joinstr = ' and '
    if gpsstart is not None:
        get_coincs=get_coincs+ joinstr + ' coinc_inspiral.end_time+coinc_inspiral.end_time_ns*1e-9 > %f'%(gpsstart)
    if gpsend is not None:
        get_coincs=get_coincs+ joinstr+' coinc_inspiral.end_time+coinc_inspiral.end_time_ns*1e-9 <%f'%(gpsend)
    if max_cfar!=-1:
        get_coincs=get_coincs+joinstr+' coinc_inspiral.combined_far < %f'%(max_cfar)
    db_out=database_connection.cursor().execute(get_coincs)
    # Timeslide functionality requires obsolete pylal - will be removed
    import pylal
    from pylal import SnglInspiralUtils
    extra={}
    for (sngl_time, slide, ifo, coinc_id, snr, chisq, cfar) in db_out:
        coinc_id=int(coinc_id.split(":")[-1])
385
        seg=list(filter(lambda seg:sngl_time in seg,seglist))[0]
386
387
388
389
390
391
392
393
394
395
396
397
398
399
        slid_time = SnglInspiralUtils.slideTimeOnRing(sngl_time,slide,seg)
        if not coinc_id in output.keys():
            output[coinc_id]=Event(trig_time=slid_time,timeslide_dict={},event_id=int(coinc_id))
            extra[coinc_id]={}
        output[coinc_id].timeslides[ifo]=slid_time-sngl_time
        output[coinc_id].ifos.append(ifo)
        extra[coinc_id][ifo]={'snr':snr,'chisq':chisq,'cfar':cfar}
    if dumpfile is not None:
        fh=open(dumpfile,'w')
        for co in output.keys():
            for ifo in output[co].ifos:
                fh.write('%s %s %s %s %s %s %s\n'%(str(co),ifo,str(output[co].trig_time),str(output[co].timeslides[ifo]),str(extra[co][ifo]['snr']),str(extra[co][ifo]['chisq']),str(extra[co][ifo]['cfar'])))
        fh.close()
    return output.values()
400

401
def mkdirs(path):
402
403
404
405
406
407
    """
    Helper function. Make the given directory, creating intermediate
    dirs if necessary, and don't complain about it already existing.
    """
    if os.access(path,os.W_OK) and os.path.isdir(path): return
    else: os.makedirs(path)
408

John Douglas Veitch's avatar
John Douglas Veitch committed
409
def chooseEngineNode(name):
410
411
412
413
414
415
416
417
418
419
420
    if name=='lalinferencenest':
        return LALInferenceNestNode
    if name=='lalinferenceburst':
        return LALInferenceBurstNode
    if name=='lalinferencemcmc':
        return LALInferenceMCMCNode
    if name=='lalinferencedatadump':
        return LALInferenceDataDumpNode
    if name=='bayeswavepsd':
        return BayesWavePSDNode
    return EngineNode
John Douglas Veitch's avatar
John Douglas Veitch committed
421

422
423
424
def get_engine_name(cp):
    name=cp.get('analysis','engine')
    if name=='random':
425
        engine_list=['lalinferencenest','lalinferencemcmc']
426
427
428
429
430
431
432
433
434
        if cp.has_option('input','gid'):
            gid=cp.get('input','gid')
            engine_number=int(''.join(i for i in gid if i.isdigit())) % 2
        else:
            engine_number=random.randint(0,1)
        return engine_list[engine_number]
    else:
        return name

435
def scan_timefile(timefile):
436
437
438
439
440
    import re
    p=re.compile('[\d.]+')
    times=[]
    timefilehandle=open(timefile,'r')
    for time in timefilehandle:
441
442
443
444
445
446
447
        if not p.match(time):
            continue
        if float(time) in times:
            print('Skipping duplicate time %s'%(time))
            continue
        print('Read time %s'%(time))
        times.append(float(time))
448
449
    timefilehandle.close()
    return times
450

451
def get_xml_psds(psdxml,ifos,outpath,end_time=None):
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
    """
    Get a psd.xml.gz file and:
    1) Reads it
    2) Checks the psd file contains all the IFO we want to analyze
    3) Writes down the PSDs into an ascii file for each IFO in psd.xml.gz. The name of the file contains the trigtime (if given) and the IFO name.
    Input:
      psdxml: psd.xml.gz file
      ifos: list of ifos used for the analysis
      outpath: path where the ascii PSD will be written to
      (end_time): trigtime for this event. Will be used a part of the PSD file name
    """
    try:
        from lal import series as lalseries
    except ImportError:
        print("ERROR, cannot import lal.series in bppu/get_xml_psds()\n")
        raise

    out={}
    if not os.path.isdir(outpath):
        os.makedirs(outpath)
    if end_time is not None:
        time=repr(float(end_time))
474
    else:
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
        time=''
    #check we don't already have ALL the psd files #
    got_all=1
    for ifo in ifos:
        path_to_ascii_psd=os.path.join(outpath,ifo+'_psd_'+time+'.txt')
        # Check we don't already have that ascii (e.g. because we are running parallel runs of the save event
        if os.path.isfile(path_to_ascii_psd):
            got_all*=1
        else:
            got_all*=0
    if got_all==1:
        #print "Already have PSD files. Nothing to do...\n"
        for ifo in ifos:
            out[ifo]=os.path.join(outpath,ifo+'_psd_'+time+'.txt')
        return out

    # We need to convert the PSD for one or more IFOS. Open the file
    if not os.path.isfile(psdxml):
        print("ERROR: impossible to open the psd file %s. Exiting...\n"%psdxml)
        sys.exit(1)
    xmlpsd =  lalseries.read_psd_xmldoc(ligolw_utils.load_filename(psdxml,contenthandler = lalseries.PSDContentHandler))
    # Check the psd file contains all the IFOs we want to analize
497
    for ifo in ifos:
498
        if not ifo in xmlpsd:
499
500
501
502
503
            print("ERROR. The PSD for the ifo %s does not seem to be contained in %s\n"%(ifo,psdxml))
            sys.exit(1)
    #loop over ifos in psd xml file
    for instrument in xmlpsd.keys():
        #name of the ascii file we are going to write the PSD into
504
        path_to_ascii_psd=os.path.join(outpath,instrument+'_psd_'+time+'.txt')
505
506
507
508
509
510
511
512
        # Check we don't already have that ascii (e.g. because we are running parallel runs of the save event
        if os.path.isfile(path_to_ascii_psd):
            continue
        # get data for the IFO
        ifodata=xmlpsd[instrument]
        #check data is not empty
        if ifodata is None:
            continue
513
514
        # write down PSD into an ascii file
        combine = np.c_[ifodata.f0 + np.arange(ifodata.data.length) * ifodata.deltaF, ifodata.data.data]
515
516
        np.savetxt(path_to_ascii_psd,combine)
        # set node.psds dictionary with the path to the ascii files
517
        ifo=instrument
518
        out[ifo]=os.path.join(outpath,ifo+'_psd_'+time+'.txt')
519
    return out
520

521
522
523
524
def get_trigger_chirpmass(coinc_xml_obj):
    coinc_events = lsctables.CoincInspiralTable.get_table(coinc_xml_obj)
    sngl_event_idx = dict((row.event_id, row) for row in lsctables.SnglInspiralTable.get_table(coinc_xml_obj))
    coinc_map = lsctables.CoincMapTable.get_table(coinc_xml_obj)
525
526
527
528
529
530
531
532
533
534
535
536
537
538
    mass1 = []
    mass2 = []
    for coinc in coinc_events:
        these_sngls = [sngl_event_idx[c.event_id] for c in coinc_map if c.coinc_event_id == coinc.coinc_event_id]
        for e in these_sngls:
            mass1.append(e.mass1)
            mass2.append(e.mass2)
    # check that trigger masses are identical in each IFO
    assert len(set(mass1)) == 1
    assert len(set(mass2)) == 1

    mchirp = (mass1[0]*mass2[0])**(3./5.) / ( (mass1[0] + mass2[0])**(1./5.) )

    return mchirp
539

540
def get_roq_mchirp_priors(path, roq_paths, roq_params, key, coinc_xml_obj=None, sim_inspiral=None):
541

542
543
544
545
    ## XML and GID cannot be given at the same time
    ## sim_inspiral must already point at the right row
    mc_priors = {}

546
547
    if coinc_xml_obj is not None and sim_inspiral is not None:
        print("Error in get_roq_mchirp_priors, cannot use both coinc.xml and sim_inspiral\n")
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
        sys.exit(1)

    for roq in roq_paths:
        params=os.path.join(path,roq,'params.dat')
        roq_params[roq]=np.genfromtxt(params,names=True)
        mc_priors[roq]=[float(roq_params[roq]['chirpmassmin']),float(roq_params[roq]['chirpmassmax'])]
    ordered_roq_paths=[item[0] for item in sorted(roq_params.items(), key=key)][::-1]
    # below is to construct non-overlapping mc priors for multiple roq mass-bin runs
    '''i=0
    for roq in ordered_roq_paths:
      if i>0:
        # change min, just set to the max of the previous one since we have already aligned it in the previous iteration of this loop
        #mc_priors[roq][0]+= (mc_priors[roq_lengths[i-1]][1]-mc_priors[roq][0])/2.
        mc_priors[roq][0]=mc_priors[ordered_roq_paths[i-1]][1]
      if i<len(roq_paths)-1:
        mc_priors[roq][1]-= (mc_priors[roq][1]- mc_priors[ordered_roq_paths[i+1]][0])/2.
      i+=1'''
565
566
    if coinc_xml_obj is not None:
        trigger_mchirp = get_trigger_chirpmass(coinc_xml_obj)
567
    elif sim_inspiral is not None:
568
        trigger_mchirp = sim_inspiral.mchirp
569
570
    else:
        trigger_mchirp = None
571

572
    return mc_priors, trigger_mchirp
573

574
def get_roq_component_mass_priors(path, roq_paths, roq_params, key, coinc_xml_obj=None, sim_inspiral=None):
Vivien Raymond's avatar
Vivien Raymond committed
575

576
    ## coinc_xml_obj and sim_inspiral cannot be given at the same time
577
578
579
    ## sim_inspiral must already point at the right row
    m1_priors = {}
    m2_priors = {}
Vivien Raymond's avatar
Vivien Raymond committed
580

581
582
    if coinc_xml_obj is not None and sim_inspiral is not None:
        print("Error in get_roq_mchirp_priors, cannot use both coinc.xml and sim_inspiral\n")
583
        sys.exit(1)
Vivien Raymond's avatar
Vivien Raymond committed
584

585
586
587
588
589
    for roq in roq_paths:
        params=os.path.join(path,roq,'params.dat')
        roq_params[roq]=np.genfromtxt(params,names=True)
        m1_priors[roq]=[float(roq_params[roq]['mass1min']),float(roq_params[roq]['mass1max'])]
        m2_priors[roq]=[float(roq_params[roq]['mass2min']),float(roq_params[roq]['mass2max'])]
Vivien Raymond's avatar
Vivien Raymond committed
590

591
592
    if coinc_xml_obj is not None:
        trigger_mchirp = get_trigger_chirpmass(coinc_xml_obj)
593
594
595
596
    elif sim_inspiral is not None:
        trigger_mchirp = sim_inspiral.mchirp
    else:
        trigger_mchirp = None
Vivien Raymond's avatar
Vivien Raymond committed
597

598
    return m1_priors, m2_priors, trigger_mchirp
Vivien Raymond's avatar
Vivien Raymond committed
599

600
def get_roq_mass_freq_scale_factor(mc_priors, trigger_mchirp, force_flow=None):
601
602
603
604
    mc_priors_keys_list = list(mc_priors.keys())
    mc_priors_keys_int = [int(seglen[:-1]) for seglen in mc_priors_keys_list]
    roq_min = mc_priors_keys_list[np.argmin(mc_priors_keys_int)]
    roq_max = mc_priors_keys_list[np.argmax(mc_priors_keys_int)]
605
606
607
608
609
610
611
612
613
614
615
    mc_max = mc_priors[roq_min][1]
    mc_min = mc_priors[roq_max][0]
    scale_factor = 1.
    if force_flow == None and trigger_mchirp != None:
        if trigger_mchirp >= mc_max:
            scale_factor = 2.**(floor(trigger_mchirp/mc_max))
        if trigger_mchirp <= mc_min:
            scale_factor = (2./3.2)**(ceil(trigger_mchirp/mc_min))
    elif force_flow != None:
        scale_factor = 20./force_flow
    return scale_factor
616

617
618
def create_pfn_tuple(filename,protocol='file://',site='local'):
    return( (os.path.basename(filename),protocol+os.path.abspath(filename),site) )
619

Vivien Raymond's avatar
Vivien Raymond committed
620
def mchirp_from_components(m1, m2):
621
    return (m1*m2)**(3.0/5.0) / (m1+m2)**(1.0/5.0)
Vivien Raymond's avatar
Vivien Raymond committed
622
623

def Query_ROQ_Bounds_Type(path, roq_paths):
624
625
626
627
628
629
630
631
632
633
634
635
    # Assume that parametrization of ROQ bounds is independent of seglen; just look at first one
    import numpy as np
    roq = roq_paths[0]
    params = os.path.join(path,roq,'params.dat')
    roq_params0 = np.genfromtxt(params,names=True)
    roq_names_set = set(roq_params0.dtype.names)
    component_mass_bounds_set = set(['mass1min', 'mass1max', 'mass2min', 'mass2max'])
    chirp_mass_q_bounds_set = set(['chirpmassmin', 'chirpmassmax', 'qmin', 'qmax'])
    if roq_names_set.issuperset(component_mass_bounds_set):
        roq_bounds = 'component_mass'
    elif roq_names_set.issuperset(chirp_mass_q_bounds_set):
        roq_bounds = 'chirp_mass_q'
636
    else:
637
638
639
        print('Invalid bounds for ROQ. Ether (m1,m2) or (mc,q) bounds are supported.')
        sys.exit(1)
    return roq_bounds
640

641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
class LALInferencePipelineDAG(pipeline.CondorDAG):
    def __init__(self,cp,dax=False,site='local'):
        self.subfiles=[]
        self.config=cp
        self.engine=get_engine_name(cp)
        self.EngineNode=chooseEngineNode(self.engine)
        self.site=site
        if cp.has_option('paths','basedir'):
            self.basepath=cp.get('paths','basedir')
        else:
            self.basepath=os.getcwd()
            print('No basepath specified, using current directory: %s'%(self.basepath))
        mkdirs(self.basepath)
        print("Generating LALInference DAG in {0}".format(self.basepath))
        if dax:
            os.chdir(self.basepath)
        self.posteriorpath=os.path.join(self.basepath,'posterior_samples')
        mkdirs(self.posteriorpath)
        daglogdir=cp.get('paths','daglogdir')
        mkdirs(daglogdir)
        self.daglogfile=os.path.join(daglogdir,'lalinference_pipeline-'+str(uuid.uuid1())+'.log')
        super(LALInferencePipelineDAG,self).__init__(self.daglogfile,dax=dax)
        if cp.has_option('paths','cachedir'):
            self.cachepath=cp.get('paths','cachedir')
        else:
            self.cachepath=os.path.join(self.basepath,'caches')
        mkdirs(self.cachepath)
        if cp.has_option('paths','logdir'):
            self.logpath=cp.get('paths','logdir')
        else:
            self.logpath=os.path.join(self.basepath,'log')
        mkdirs(self.logpath)
        if cp.has_option('analysis','ifos'):
            self.ifos=ast.literal_eval(cp.get('analysis','ifos'))
        else:
            self.ifos=['H1','L1','V1']
        self.segments={}
        if cp.has_option('datafind','veto-categories'):
            self.veto_categories=cp.get('datafind','veto-categories')
        else: self.veto_categories=[]
        for ifo in self.ifos:
            self.segments[ifo]=[]
        self.computeroqweightsnode={}
        self.bayeslinenode={}
        self.bayeswavepsdnode={}
        self.dq={}
        self.frtypes=ast.literal_eval(cp.get('datafind','types'))
        self.channels=ast.literal_eval(cp.get('data','channels'))
        self.use_available_data=False
        self.webdir=cp.get('paths','webdir')
        if cp.has_option('analysis','dataseed'):
            self.dataseed=cp.getint('analysis','dataseed')
        else:
            self.dataseed=None
        # Set up necessary job files.
        self.prenodes={}
        self.datafind_job = pipeline.LSCDataFindJob(self.cachepath,self.logpath,self.config,dax=self.is_dax())
        self.datafind_job.add_opt('url-type','file')
        # If running on OSG use its datafind server
        if cp.has_option('analysis','osg') and cp.getboolean('analysis','osg'):
            self.datafind_job.add_opt('server','datafind.ligo.org')
        if cp.has_option('condor','accounting_group'):
            self.datafind_job.add_condor_cmd('accounting_group',cp.get('condor','accounting_group'))
        if cp.has_option('condor','accounting_group_user'):
            self.datafind_job.add_condor_cmd('accounting_group_user',cp.get('condor','accounting_group_user'))
        self.datafind_job.set_sub_file(os.path.abspath(os.path.join(self.basepath,'datafind.sub')))
        self.preengine_job = EngineJob(self.config, os.path.join(self.basepath,'prelalinference.sub'),self.logpath,engine='lalinferencedatadump',ispreengine=True,dax=self.is_dax())
        self.preengine_job.set_grid_site('local')
        self.preengine_job.set_universe('vanilla')
        if self.config.getboolean('analysis','roq'):
            self.computeroqweights_job = ROMJob(self.config,os.path.join(self.basepath,'computeroqweights.sub'),self.logpath,dax=self.is_dax())
            self.computeroqweights_job.set_grid_site('local')
        if self.config.has_option('condor','bayesline'):
            self.bayesline_job = BayesLineJob(self.config,os.path.join(self.basepath,'bayesline.sub'),self.logpath,dax=self.is_dax())
            self.bayesline_job.set_grid_site('local')
        self.bayeswavepsd_job={}
717
        if self.config.has_option('condor','bayeswave'):
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
            for ifo in self.ifos:
                self.bayeswavepsd_job[ifo] = BayesWavePSDJob(self.config,os.path.join(self.basepath,'bayeswavepsd_%s.sub'%(ifo)),self.logpath,dax=self.is_dax())
                self.bayeswavepsd_job[ifo].set_grid_site('local')
        # Need to create a job file for each IFO combination
        self.engine_jobs={}
        ifocombos=[]
        for N in range(1,len(self.ifos)+1):
            for a in permutations(self.ifos,N):
                ifocombos.append(a)
        for ifos in ifocombos:
            self.engine_jobs[ifos] = EngineJob(self.config, os.path.join(self.basepath,'engine_%s.sub'%(reduce(lambda x,y:x+y, map(str,ifos)))),self.logpath,engine=self.engine,dax=self.is_dax(), site=site)
        self.results_page_job = ResultsPageJob(self.config,os.path.join(self.basepath,'resultspage.sub'),self.logpath,dax=self.is_dax())
        self.results_page_job.set_grid_site('local')
        self.cotest_results_page_job = ResultsPageJob(self.config,os.path.join(self.basepath,'resultspagecoherent.sub'),self.logpath,dax=self.is_dax())
        self.cotest_results_page_job.set_grid_site('local')
        if self.engine=='lalinferencemcmc':
            self.combine_job = CombineMCMCJob(self.config,os.path.join(self.basepath,'combine_files.sub'),self.logpath,dax=self.is_dax())
            self.combine_job.set_grid_site('local')
            self.merge_job = MergeJob(self.config,os.path.join(self.basepath,'merge_runs.sub'),self.logpath,dax=self.is_dax(),engine='mcmc')
            self.merge_job.set_grid_site('local')
738
        else:
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
            self.merge_job = MergeJob(self.config,os.path.join(self.basepath,'merge_runs.sub'),self.logpath,dax=self.is_dax(),engine='nest')
            self.merge_job.set_grid_site('local')
        self.coherence_test_job = CoherenceTestJob(self.config,os.path.join(self.basepath,'coherence_test.sub'),self.logpath,dax=self.is_dax())
        self.coherence_test_job.set_grid_site('local')
        self.gracedbjob = GraceDBJob(self.config,os.path.join(self.basepath,'gracedb.sub'),self.logpath,dax=self.is_dax())
        self.gracedbjob.set_grid_site('local')
        self.mapjob = SkyMapJob(cp, os.path.join(self.basepath,'skymap.sub'), self.logpath)
        self.plotmapjob = PlotSkyMapJob(cp, os.path.join(self.basepath,'plotskymap.sub'),self.logpath)
        # Process the input to build list of analyses to do
        self.events=self.setup_from_inputs()

        # Sanity checking
        if len(self.events)==0:
            print('No input events found, please check your config if you expect some events')
        self.times=[e.trig_time for e in self.events]

        # Set up the segments
        if not (self.config.has_option('input','gps-start-time') and self.config.has_option('input','gps-end-time')) and len(self.times)>0:
            (mintime,maxtime)=self.get_required_data(self.times)
            if not self.config.has_option('input','gps-start-time'):
                self.config.set('input','gps-start-time',str(int(floor(mintime))))
            if not self.config.has_option('input','gps-end-time'):
                self.config.set('input','gps-end-time',str(int(ceil(maxtime))))
        self.add_science_segments()

        # Save the final configuration that is being used
        # first to the run dir
        conffilename=os.path.join(self.basepath,'config.ini')
767
        with open(conffilename,'w') as conffile:
768
769
770
            self.config.write(conffile)
        if self.config.has_option('paths','webdir'):
            mkdirs(self.config.get('paths','webdir'))
771
            with open(os.path.join(self.config.get('paths','webdir'),'config.ini'),'w') as conffile:
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
                self.config.write(conffile)

        # Generate the DAG according to the config given
        for event in self.events: self.add_full_analysis(event)
        if self.config.has_option('analysis','upload-to-gracedb'):
            if self.config.getboolean('analysis','upload-to-gracedb'):
                self.add_gracedb_FITSskymap_upload(self.events[0],engine=self.engine)
        self.dagfilename="lalinference_%s-%s"%(self.config.get('input','gps-start-time'),self.config.get('input','gps-end-time'))
        self.set_dag_file(os.path.join(self.basepath,self.dagfilename))
        if self.is_dax():
            self.set_dax_file(self.dagfilename)

    def add_full_analysis(self,event):
        if self.engine=='lalinferencenest' or  self.engine=='lalinferenceburst':
            result=self.add_full_analysis_lalinferencenest(event)
        elif self.engine=='lalinferencemcmc':
            result=self.add_full_analysis_lalinferencemcmc(event)
        else:
            raise Exception('Unknown engine {0}'.format(self.engine))
        return result
792

793
794
795
796
    def create_frame_pfn_file(self):
        """
        Create a pegasus cache file name, uses inspiralutils
        """
797
        from lalapps import inspiralutils as iu
798
799
800
801
        gpsstart=self.config.get('input','gps-start-time')
        gpsend=self.config.get('input','gps-end-time')
        pfnfile=iu.create_frame_pfn_file(self.frtypes,gpsstart,gpsend)
        return pfnfile
802

803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
    def get_required_data(self,times):
        """
        Calculate the data that will be needed to process all events
        """
        #psdlength = self.config.getint('input','max-psd-length')
        padding=self.config.getint('input','padding')
        if self.config.has_option('engine','seglen') or self.config.has_option('lalinference','seglen'):
            if self.config.has_option('engine','seglen'):
                seglen = int(np.ceil(self.config.getfloat('engine','seglen')))
            if self.config.has_option('lalinference','seglen'):
                seglen = self.config.getint('lalinference','seglen')

            if os.path.isfile(os.path.join(self.basepath,'psd.xml.gz')) or self.config.has_option('condor','bayesline') or self.config.has_option('condor','bayeswave'):
                psdlength = 0
                padding = 0
                self.config.set('input','padding',str(padding))
                if self.config.has_option('condor','bayeswave'):
                    if (np.log2(seglen)%1):
                        seglen = np.power(2., np.ceil(np.log2(seglen)))
822

823
824
            else:
                psdlength = 32*seglen
825
        else:
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
            seglen = max(e.duration for e in self.events)
            if os.path.isfile(os.path.join(self.basepath,'psd.xml.gz')) or self.config.has_option('condor','bayesline') or self.config.has_option('condor','bayeswave'):
                psdlength = 0
                padding = 0
                self.config.set('input','padding',str(padding))
                if self.config.has_option('condor','bayeswave'):
                    if (np.log2(seglen)%1):
                        seglen = np.power(2., np.ceil(np.log2(seglen)))
            else:
                psdlength = 32*seglen
        # Assume that the data interval is (end_time - seglen -padding , end_time + psdlength +padding )
        # -> change to (trig_time - seglen - padding - psdlength + 2 , trig_time + padding + 2) to estimate the psd before the trigger for online follow-up.
        # Also require padding before start time
        return (min(times)-padding-seglen-psdlength+2,max(times)+padding+2)

    def setup_from_times(self,times):
        """
        Generate a DAG from a list of times
        """
        for time in self.times:
            self.add_full_analysis(Event(trig_time=time))

    def select_events(self):
        """
        Read events from the config parser. Understands both ranges and comma separated events, or combinations
        eg. events=[0,1,5:10,21] adds to the analysis the events: 0,1,5,6,7,8,9,10 and 21
        """
853
        events=[]
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
        times=[]
        raw_events=self.config.get('input','events').replace('[','').replace(']','').split(',')
        for raw_event in raw_events:
            if ':' in raw_event:
                limits=raw_event.split(':')
                if len(limits) != 2:
                    print("Error: in event config option; ':' must separate two numbers.")
                    exit(0)
                low=int(limits[0])
                high=int(limits[1])
                if low>high:
                    events.extend(range(int(high),int(low)+1))
                elif high>low:
                    events.extend(range(int(low),int(high)+1))
            else:
                events.append(int(raw_event))
870
        return events
871

872
873
874
875
876
877
878
879
880
881
882
883
884
885
    def setup_from_inputs(self):
        """
        Scan the list of inputs, i.e.
        gps-time-file, injection-file, sngl-inspiral-file, coinc-inspiral-file, pipedown-database
        in the [input] section of the ini file.
        And process the events found therein
        """
        events=[]
        gpsstart=None
        gpsend=None
        if self.config.has_option('input','gps-start-time'):
            gpsstart=self.config.getfloat('input','gps-start-time')
        if self.config.has_option('input','gps-end-time'):
            gpsend=self.config.getfloat('input','gps-end-time')
886
        inputnames=['gps-time-file','burst-injection-file','injection-file','coinc-xml','pipedown-db','gid','gstlal-db']
887
888
889
890
891
892
893
894
895
896
897
898
899
        ReadInputFromList=sum([ 1 if self.config.has_option('input',name) else 0 for name in inputnames])
        # If no input events given, just return an empty list (e.g. for PP pipeline)
        if ReadInputFromList!=1 and (gpsstart is None or gpsend is None):
            return []
        # Review: Clean up this section
        if self.config.has_option('input','events'):
            selected_events=self.config.get('input','events')
            print('Selected events %s'%(str(selected_events)))

            if selected_events=='all':
                selected_events=None
            else:
                selected_events=self.select_events()
900
        else:
901
902
903
904
905
906
            selected_events=None

        if(self.config.has_option('engine','correlatedGaussianLikelihood') or
           self.config.has_option('engine','bimodalGaussianLikelihood') or
           self.config.has_option('engine','rosenbrockLikelihood')):
            analytic_test = True
907
        else:
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
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
            analytic_test = False

        # No input file given, analyse the entire time stretch between gpsstart and gpsend
        if self.config.has_option('input','analyse-all-time') and self.config.getboolean('input','analyse-all-time')==True:
            print('Setting up for analysis of continuous time stretch %f - %f'%(gpsstart,gpsend))
            if self.config.has_option('engine','seglen'):
                seglen=self.config.getfloat('engine','seglen')
            else:
                print('ERROR: seglen must be specified in [engine] section when running without input file')
                sys.exit(1)
            if(self.config.has_option('input','segment-overlap')):
                overlap=self.config.getfloat('input','segment-overlap')
            else:
                overlap=32.;
            if(overlap>seglen):
                print('ERROR: segment-overlap is greater than seglen')
                sys.exit(1)
            # Now divide gpsstart - gpsend into jobs of seglen - overlap length
            t=gpsstart
            events=[]
            while(t<gpsend):
                ev=Event(trig_time=t+seglen-2)
                ev.set_engine_option('segment-start',str(t-overlap))
                if not analytic_test:
                    ev.set_engine_option('time-min',str(t))
                tMax=t + seglen - overlap
                if tMax>=gpsend:
                    tMax=gpsend
                if not analytic_test:
                    ev.set_engine_option('time-max',str(tMax))
                events.append(ev)
                t=tMax
            return events

        # ASCII list of GPS times
        if self.config.has_option('input','gps-time-file'):
            times=scan_timefile(self.config.get('input','gps-time-file'))
            if self.config.has_option('input','timeslides-ascii'):
            # The timeslides-ascii files contains one row per trigtime, and a column per IFO
            # Note: the IFO order is the same given in the ifos section of the [analysis] tag
                print("Reading timeslides from ascii file. Columns order is understood as follow:")
                for this_ifo,ifo in enumerate(self.ifos):
                    print("Column %d"%this_ifo + "= %s "%(ifo))
                dest=self.config.get('input','timeslides-ascii')
                if not os.path.isfile(dest):
                    print("ERROR the ascii file %s containing the timeslides does not exist\n"%dest)
                    exit(1)
                else:
                    from numpy import loadtxt
                    data=loadtxt(dest).reshape(-1,len(self.ifos))
                    if len(self.ifos)!= len(data[0,:]):
                        print("ERROR: ascii timeslide file must contain a column for each IFO used in the analysis!\n")
                        exit(1)
                    if len(times)!=len(data[:,0]):
                        print('ERROR: ascii timeslide must contain a row for each trigtime. Exiting...\n')
                        exit(1)
                    timeslides={}
                    for this_time,time in enumerate(times):
                        timeslides[this_time]={}
                        for this_ifo,ifo in enumerate(self.ifos):
                            timeslides[this_time][ifo]=data[this_time,this_ifo]
                events=[Event(trig_time=time,timeslide_dict=timeslides[i_time]) for i_time,time in enumerate(times)]
            else:
                events=[Event(trig_time=time) for time in times]
        # Siminspiral Table
        if self.config.has_option('input','injection-file'):
            injTable = lsctables.SimInspiralTable.get_table(
975
                              ligolw_utils.load_filename(self.config.get('input','injection-file'),
976
977
978
979
980
981
                                                  contenthandler=lsctables.use_in(ligolw.LIGOLWContentHandler)) )
            events=[Event(SimInspiral=inj) for inj in injTable]
            self.add_pfn_cache([create_pfn_tuple(self.config.get('input','injection-file'))])
        # SimBurst Table
        if self.config.has_option('input','burst-injection-file'):
            injfile=self.config.get('input','burst-injection-file')
982
            injTable=lsctables.SimBurstTable.get_table(ligolw_utils.load_filename(injfile,contenthandler = lsctables.use_in(LIGOLWContentHandler)))
983
984
985
            events=[Event(SimBurst=inj) for inj in injTable]
            self.add_pfn_cache([create_pfn_tuple(self.config.get('input','burst-injection-file'))])
        # LVAlert CoincInspiral Table
986
987
        gid = None
        if self.config.has_option('input','gid') or self.config.has_option('input', 'coinc-xml'):
988
989
990
991
992
993
            flow=20.0
            if self.config.has_option('lalinference','flow'):
                flow=min(ast.literal_eval(self.config.get('lalinference','flow')).values())
            threshold_snr = None
            if not self.config.has_option('engine','distance-max') and self.config.has_option('input','threshold-snr'):
                threshold_snr=self.config.getfloat('input','threshold-snr')
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
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
1051
1052
1053
1054
1055
1056
1057
1058
1059

            # get coinc object and psd object
            from lal import series as lalseries
            psd_file_obj = None
            if self.config.has_option('input', 'gid'):
                from ligo.gracedb.rest import GraceDb, HTTPError
                gid = self.config.get('input', 'gid')
                if self.config.has_option('analysis','service-url'):
                    client = GraceDb(
                        service_url=self.config.get('analysis', 'service-url')
                    )
                else:
                    client = GraceDb()
                print("Download %s coinc.xml" % gid)
                coinc_file_obj = client.files(gid, "coinc.xml")
                try:
                    downloadpsd = (not self.config.getboolean('input','ignore-gracedb-psd'))
                except:
                    downloadpsd = True
                if downloadpsd:
                    print("Download %s psd.xml.gz" % gid)
                    try:
                        psd_file_obj = client.files(gid, "psd.xml.gz")
                    except HTTPError:
                        print("Failed to download %s psd.xml.gz. lalinference will estimate the psd itself." % gid)
            else:
                coinc_file_obj = open(self.config.get('input', 'coinc-xml'), "rb")
                try:
                    psd_file_obj =  open(self.config.get('input', 'psd-xml-gz'), "rb")
                except:
                    print("lalinference will estimate the psd itself.")

            # write down the objects to files
            coinc_xml_obj = ligolw_utils.load_fileobj(
                coinc_file_obj,
                contenthandler = lsctables.use_in(ligolw.LIGOLWContentHandler)
            )[0]
            ligolw_utils.write_filename(
                coinc_xml_obj, os.path.join(self.basepath, "coinc.xml")
            )
            if psd_file_obj is not None:
                path_to_psd = os.path.join(self.basepath, "psd.xml.gz")
                psd_xml_obj = ligolw_utils.load_fileobj(
                    psd_file_obj,
                    contenthandler = lalseries.PSDContentHandler
                )[0]
                psd_dict = lalseries.read_psd_xmldoc(psd_xml_obj)
                ligolw_utils.write_filename(psd_xml_obj, path_to_psd, gz = True)
                ifos = sorted(
                    lsctables.CoincInspiralTable.get_table(
                        coinc_xml_obj
                    )[0].instruments
                )
                get_xml_psds(
                    os.path.realpath(path_to_psd), ifos,
                    os.path.realpath(os.path.join(self.basepath, "PSDs")),
                    end_time=None
                )
            else:
                psd_dict = None

            events = create_events_from_coinc_and_psd(
                         coinc_xml_obj, psd_dict, gid, threshold_snr=None, flow=flow,
                         roq=self.config.getboolean('analysis','roq')
                     )

1060
1061
        # pipedown-database
        if self.config.has_option('input','gstlal-db'):
1062
1063
            queryfunc=get_zerolag_lloid
            dbname=self.config.get('input','gstlal-db')
1064
        elif self.config.has_option('input','pipedown-db'):
1065
1066
            queryfunc=get_zerolag_pipedown
            dbname=self.config.get('input','pipedown-db')
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
        else: dbname=None
        if dbname:
            db_connection = open_pipedown_database(dbname,None)[0]
            # Timeslides
            if self.config.has_option('input','time-slide-dump'):
                timeslidedump=self.config.get('input','time-slide-dump')
            else:
                timeslidedump=None
            if self.config.has_option('input','min-cfar'):
                mincfar=self.config.getfloat('input','min-cfar')
            else:
                mincfar=-1
            if self.config.has_option('input','max-cfar'):
                maxcfar=self.config.getfloat('input','max-cfar')
            else:
                maxcfar=-1
            if self.config.get('input','timeslides').lower()=='true':
                events=get_timeslides_pipedown(db_connection, gpsstart=gpsstart, gpsend=gpsend,dumpfile=timeslidedump,max_cfar=maxcfar)
            else:
                events=queryfunc(db_connection, gpsstart=gpsstart, gpsend=gpsend, dumpfile=timeslidedump,max_cfar=maxcfar,min_cfar=mincfar)
        if(selected_events is not None):
            used_events=[]
            for i in selected_events:
                e=events[i]
                e.event_id=i
                used_events.append(e)
            events=used_events
        if gpsstart is not None:
1095
            events = list(filter(lambda e: not e.trig_time<gpsstart, events))
1096
        if gpsend is not None:
1097
            events = list(filter(lambda e: not e.trig_time>gpsend, events))
1098
        return events
John Douglas Veitch's avatar
Working    
John Douglas Veitch committed
1099

1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
    def add_full_analysis_lalinferencenest(self,event):
        """
        Generate an end-to-end analysis of a given event (Event class)
        For LALinferenceNest code. Uses parallel runs if specified
        """
        evstring=str(event.event_id)
        if event.trig_time is not None:
            evstring=str(event.trig_time)+'-'+str(event.event_id)
        if self.config.has_option('analysis','nparallel'):
            Npar=self.config.getint('analysis','nparallel')
1110
        else:
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
            Npar=4
        # Set up the parallel engine nodes
        enginenodes=[]
        bwpsdnodes={}
        for i in range(Npar):
            n,bwpsdnodes=self.add_engine_node(event,bwpsdnodes)
            if n is not None:
                if i>0:
                    n.add_var_arg('--dont-dump-extras')
                enginenodes.append(n)
        if len(enginenodes)==0:
            return False
        myifos=enginenodes[0].get_ifos()
        # Merge the results together
        pagedir=os.path.join(self.webdir,evstring,myifos)
        #pagedir=os.path.join(self.basepath,evstring,myifos)
        mkdirs(pagedir)
        mergenode=MergeNode(self.merge_job,parents=enginenodes,engine='nest')
        mergenode.set_pos_output_file(os.path.join(self.posteriorpath,'posterior_%s_%s.hdf5'%(myifos,evstring)))
        self.add_node(mergenode)
        # Call finalize to build final list of available data
        enginenodes[0].finalize()
        enginenodes[0].set_psd_files()
        enginenodes[0].set_snr_file()
        if self.config.getboolean('analysis','coherence-test') and len(enginenodes[0].ifos)>1:
1136
            if self.site!='local':
1137
                zipfilename='postproc_'+evstring+'.tar.gz'
1138
            else:
1139
1140
1141
1142
                zipfilename=None
            respagenode=self.add_results_page_node(resjob=self.cotest_results_page_job,outdir=pagedir,parent=mergenode,gzip_output=zipfilename,ifos=enginenodes[0].ifos)
            respagenode.set_psd_files(enginenodes[0].get_psd_files())
            respagenode.set_snr_file(enginenodes[0].get_snr_file())
1143
            if os.path.exists(self.basepath+'/coinc.xml'):
1144
1145
1146
1147
1148
                try:
                    gid = self.config.get('input','gid')
                except:
                    gid = None
                respagenode.set_coinc_file(os.path.join(self.basepath, 'coinc.xml'), gid)
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
            mkdirs(os.path.join(self.basepath,'coherence_test'))
            par_mergenodes=[]
            for ifo in enginenodes[0].ifos:
                co_merge_job = MergeJob(self.config,os.path.join(self.basepath,'merge_runs_%s.sub'%(ifo)),self.logpath,dax=self.is_dax(),engine='nest')
                co_merge_job.set_grid_site('local')
                cotest_nodes=[]
                for i in range(Npar):
                    cot_node,bwpsdnodes=self.add_engine_node(event,bwpsdnodes,ifos=[ifo],co_test=True)
                    if cot_node is not None:
                        if i>0:
                            cot_node.add_var_arg('--dont-dump-extras')
                        cotest_nodes.append(cot_node)
                if len(cotest_nodes)==0:
                    return False
                for co in cotest_nodes:
                    co.set_psdstart(enginenodes[0].GPSstart)
                    co.set_psdlength(enginenodes[0].psdlength)
                    if co!=cotest_nodes[0]:
                        co.add_var_arg('--dont-dump-extras')
                    else:
                        co.set_psd_files()
                        co.set_snr_file()
                pmergenode=MergeNode(co_merge_job,parents=cotest_nodes,engine='nest')
                pmergenode.set_pos_output_file(os.path.join(self.posteriorpath,'posterior_%s_%s.hdf5'%(ifo,evstring)))
                self.add_node(pmergenode)
                par_mergenodes.append(pmergenode)
                presultsdir=os.path.join(pagedir,ifo)
                mkdirs(presultsdir)
                if self.site!='local':
                    pzipfilename='postproc_'+evstring+'_'+ifo+'.tar.gz'
                else:
                    pzipfilename=None
                subresnode=self.add_results_page_node(outdir=presultsdir,parent=pmergenode, gzip_output=pzipfilename,ifos=ifo)
                subresnode.set_psd_files(cotest_nodes[0].get_psd_files())
                subresnode.set_snr_file(cotest_nodes[0].get_snr_file())
                if os.path.exists(self.basepath+'/coinc.xml'):
1185
1186
1187
1188
1189
                    try:
                        gid = self.config.get('input','gid')
                    except:
                        gid = None
                    subresnode.set_coinc_file(os.path.join(self.basepath, 'coinc.xml'), gid)
1190
1191
1192
1193
1194
1195
                if self.config.has_option('input','injection-file') and event.event_id is not None:
                    subresnode.set_injection(self.config.get('input','injection-file'),event.event_id)
                elif self.config.has_option('input','burst-injection-file') and event.event_id is not None:
                    subresnode.set_injection(self.config.get('input','burst-injection-file'),event.event_id)
            coherence_node=CoherenceTestNode(self.coherence_test_job,outfile=os.path.join(self.basepath,'coherence_test','coherence_test_%s_%s.dat'%(myifos,evstring)))
            coherence_node.add_coherent_parent(mergenode)
Matthew David Pitkin's avatar
Matthew David Pitkin committed
1196
1197
            for parmergenode in par_mergenodes:
                coherence_node.add_incoherent_parent(parmergenode)
1198
1199
1200
            self.add_node(coherence_node)
            respagenode.add_parent(coherence_node)
            respagenode.set_bayes_coherent_incoherent(coherence_node.get_output_files()[0])
1201
        else:
1202
1203
1204
1205
1206
1207
1208
1209
1210
            if self.site!='local':
                zipfilename='postproc_'+evstring+'.tar.gz'
            else:
                zipfilename=None
            # Note: Disabled gzip_output for now. Possibly need it for future Pegasus use
            respagenode=self.add_results_page_node(outdir=pagedir,parent=mergenode,gzip_output=None,ifos=enginenodes[0].ifos)
            respagenode.set_psd_files(enginenodes[0].get_psd_files())
            respagenode.set_snr_file(enginenodes[0].get_snr_file())
            if os.path.exists(self.basepath+'/coinc.xml'):
1211
1212
1213
1214
1215
                try:
                    gid = self.config.get('input','gid')
                except:
                    gid = None
                respagenode.set_coinc_file(os.path.join(self.basepath, 'coinc.xml'), gid)
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
        if self.config.has_option('input','injection-file') and event.event_id is not None:
            respagenode.set_injection(self.config.get('input','injection-file'),event.event_id)
        elif self.config.has_option('input','burst-injection-file') and event.event_id is not None:
            respagenode.set_injection(self.config.get('input','burst-injection-file'),event.event_id)

        if self.config.has_option('analysis','upload-to-gracedb'):
            if self.config.getboolean('analysis','upload-to-gracedb') and event.GID is not None:
                self.add_gracedb_start_node(event.GID,'LALInference',[sciseg.get_df_node() for sciseg in enginenodes[0].scisegs.values()])
                self.add_gracedb_log_node(respagenode,event.GID)
            elif self.config.has_option('analysis','ugid'):
                # LIB will want to upload info to gracedb but if we pass the gid in the usual way the pipeline
                # will try to pull inspiral-only XML tables from the gdb page, failing.
                # To avoid that, LIB will read the gracedDB id to upload info to as an ugid=ID option
                # in the analysis section.
                ugid=self.config.get('analysis','ugid')
                self.add_gracedb_start_node(ugid,'LIB',[sciseg.get_df_node() for sciseg in enginenodes[0].scisegs.values()])
                self.add_gracedb_log_node(respagenode,ugid)
        if self.config.has_option('condor','ligo-skymap-plot') and self.config.has_option('condor','ligo-skymap-from-samples'):
            if self.engine=='lalinferenceburst': prefix='LIB'
            else: prefix='LALInference'
            mapnode = SkyMapNode(self.mapjob, posfile = mergenode.get_pos_file(), parent=mergenode,
                    prefix= prefix, outdir=pagedir)
            plotmapnode = PlotSkyMapNode(self.plotmapjob, parent=mapnode, inputfits = mapnode.outfits, output=os.path.join(pagedir,'skymap.png'))
            self.add_node(mapnode)
            self.add_node(plotmapnode)
        return True

    def add_full_analysis_lalinferencemcmc(self,event):
        """
        Generate an end-to-end analysis of a given event
        For LALInferenceMCMC.
        """
        evstring=str(event.event_id)
        if event.trig_time is not None:
            evstring=str(event.trig_time)+'-'+str(event.event_id)
        if self.config.has_option('analysis','nparallel'):
            Npar=self.config.getint('analysis','nparallel')
1253
        else:
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
            Npar=2
        enginenodes=[]
        bwpsdnodes={}
        for i in range(Npar):
            n,bwpsdnodes=self.add_engine_node(event,bwpsdnodes)
            if n is not None:
                if i>0:
                    n.add_var_arg('--dont-dump-extras')
                enginenodes.append(n)
        if len(enginenodes)==0:
            return False
        myifos=enginenodes[0].get_ifos()
        enginenodes[0].set_psd_files()
        enginenodes[0].set_snr_file()
        pagedir=os.path.join(self.webdir,evstring,myifos)
        mkdirs(pagedir)
        combinenodes=[]
        for i in range(Npar):
            combinenodes.append(CombineMCMCNode(self.combine_job,parents=[enginenodes[i]]))
            input_file = combinenodes[i].get_parent_posfile(enginenodes[i])
            input_file_split_index = input_file.find('lalinferencemcmc-')
            combinenodes[i].set_pos_output_file(input_file[:input_file_split_index]+'combine_'+input_file[input_file_split_index:])
            combinenodes[i].add_var_arg(input_file)
            number_of_mpi_jobs = self.config.getint('mpi','mpi_task_count')
            for j in range(1,number_of_mpi_jobs):
                combinenodes[i].add_var_arg(input_file+".%02d" % j)
            self.add_node(combinenodes[i])
        mergenode=MergeNode(self.merge_job,parents=combinenodes,engine='mcmc')
        mergenode.set_pos_output_file(os.path.join(self.posteriorpath,'posterior_%s_%s.hdf5'%(myifos,evstring)))
        if self.config.has_option('resultspage','deltaLogP'):
            mergenode.add_var_arg('--deltaLogP '+str(self.config.getfloat('resultspage','deltaLogP')))
        if self.config.has_option('resultspage','downsample'):
            mergenode.add_var_arg('--downsample '+str(self.config.getint('resultspage','downsample')))
        if self.config.has_option('resultspage','fixedBurnin'):
            mergenode.add_var_arg('--fixedBurnin '+str(self.config.getint('resultspage','fixedBurnin')))
        self.add_node(mergenode)
1290
        respagenode=self.add_results_page_node(outdir=pagedir,parent=mergenode,gzip_output=None,ifos=enginenodes[0].ifos)
1291
1292
        respagenode.set_psd_files(enginenodes[0].get_psd_files())
        respagenode.set_snr_file(enginenodes[0].get_snr_file())
1293
        if os.path.exists(self.basepath+'/coinc.xml'):
1294
1295
1296
1297
1298
            try:
                gid = self.config.get('input','gid')
            except:
                gid = None
            respagenode.set_coinc_file(os.path.join(self.basepath, 'coinc.xml'), gid)
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
        if self.config.has_option('input','injection-file') and event.event_id is not None:
            respagenode.set_injection(self.config.get('input','injection-file'),event.event_id)
        if self.config.has_option('input','burst-injection-file') and event.event_id is not None:
            respagenode.set_injection(self.config.get('input','burst-injection-file'),event.event_id)
        if event.GID is not None:
            if self.config.has_option('analysis','upload-to-gracedb'):
                if self.config.getboolean('analysis','upload-to-gracedb'):
                    self.add_gracedb_start_node(event.GID,'LALInference',[sciseg.get_df_node() for sciseg in enginenodes[0].scisegs.values()])
                    self.add_gracedb_log_node(respagenode,event.GID)
        if self.config.has_option('condor','ligo-skymap-plot') and self.config.has_option('condor','ligo-skymap-from-samples'):
            mapnode = SkyMapNode(self.mapjob, posfile = mergenode.get_pos_file(), parent=mergenode,
                    prefix= 'LALInference', outdir=pagedir)
            plotmapnode = PlotSkyMapNode(self.plotmapjob, parent=mapnode, inputfits = mapnode.outfits, output=os.path.join(pagedir,'skymap.png'))
            self.add_node(mapnode)
            self.add_node(plotmapnode)

    def add_science_segments(self):
        # Query the segment database for science segments and
        # add them to the pool of segments
John Douglas Veitch's avatar
John Douglas Veitch committed
1318
1319
        start=self.config.getfloat('input','gps-start-time')
        end=self.config.getfloat('input','gps-end-time')
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
        if self.config.has_option('input','ignore-science-segments'):
            if self.config.getboolean('input','ignore-science-segments'):
                i=0
                for ifo in self.ifos:
                    sciseg=pipeline.ScienceSegment((i,start,end,end-start))
                    df_node=self.get_datafind_node(ifo,self.frtypes[ifo],int(sciseg.start()),int(sciseg.end()))
                    sciseg.set_df_node(df_node)
                    self.segments[ifo].append(sciseg)
                    i+=1
                return
        # Look up science segments as required
1331
1332
1333
        segurl = None # No segment URL will default to $DEFAULT_SEGMENT_SERVER from env
        if self.config.has_option('segfind','segment-url'):
            segurl = self.config.get('segfind','segment-url')
John Douglas Veitch's avatar
John Douglas Veitch committed
1334
        for ifo in self.ifos:
1335
            print('Querying segment database for {0} data between {1} and {2}'.format(ifo,start,end))
1336
1337
            segs = findSegmentsToAnalyze(self.config.get('segments',ifo.lower()+'-analyze'),
                start, end, url=segurl)
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
            segs.coalesce()
            for seg in segs:
                sciseg=pipeline.ScienceSegment((segs.index(seg),seg[0],seg[1],seg[1]-seg[0]))
                df_node=self.get_datafind_node(ifo,self.frtypes[ifo],int(sciseg.start()),int(sciseg.end()))
                sciseg.set_df_node(df_node)
                self.segments[ifo].append(sciseg)

    def get_datafind_node(self,ifo,frtype,gpsstart,gpsend):
        node=pipeline.LSCDataFindNode(self.datafind_job)
        node.set_observatory(ifo[0])
        node.set_type(frtype)
        node.set_start(gpsstart)
        node.set_end(gpsend)
        #self.add_node(node)
        return node

    def add_engine_node(self,event,bwpsd={},ifos=None,co_test=False,extra_options=None):
        """
        Add an engine node to the dag. Will find the appropriate cache files automatically.
        Will determine the data to be read and the output file.
        Will use all IFOs known to the DAG, unless otherwise specified as a list of strings
        """
        if ifos is None and len(event.ifos)>0:
            ifos=event.ifos
        if ifos is None:
            ifos=self.ifos
        end_time=event.trig_time
        if self.config.has_option('lalinference','seglen'):
            seglen=self.config.getfloat('lalinference','seglen')
        elif self.config.has_option('engine','seglen'):
            seglen=self.config.getfloat('engine','seglen')
        else:
            seglen=event.duration
        segstart=end_time+2-seglen
        segend=segstart+seglen
        myifos=set([])
        for ifo in ifos:
            for seg in self.segments[ifo]:
                if segstart >= seg.start() and segend <= seg.end():
                    myifos.add(ifo)
        ifos=myifos
        if len(ifos)==0:
            print('No data found for time %f - %f, skipping'%(segstart,segend))
            return

        computeroqweightsnode={}
        bayeslinenode={}
        bayeswavepsdnode=bwpsd
        prenode=LALInferenceDataDumpNode(self.preengine_job)
        node=self.EngineNode(self.engine_jobs[tuple(ifos)])
        roqeventpath=os.path.join(self.preengine_job.roqpath,str(event.event_id)+'/')
        if self.config.has_option('condor','bayesline') or self.config.has_option('condor','bayeswave') or self.config.getboolean('analysis','roq'):
            mkdirs(roqeventpath)
        node.set_trig_time(end_time)
        prenode.set_trig_time(end_time)
        randomseed=random.randint(1,2**31)
        node.set_seed(randomseed)
        prenode.set_seed(randomseed)
        original_srate=0
        srate=0
        if event.srate:
            original_srate=event.srate
        if self.config.has_option('lalinference','srate'):
            original_srate=self.config.getfloat('lalinference','srate')
        elif self.config.has_option('engine','srate'):
            original_srate=self.config.getfloat('engine','srate')
        if (np.log2(original_srate)%1):
            print('The srate given,'+str(original_srate)+' Hz, is not a power of 2.')
            print('For data handling purposes, the srate used will be '+str(np.power(2., np.ceil(np.log2(original_srate))))+' Hz')
            print('The inner products will still however be integrated up to '+str(original_srate/2.)+' Hz')
            srate = np.power(2., np.ceil(np.log2(original_srate)))
        else:
            srate = original_srate
        if srate is not 0:
            node.set_srate(