SendInjStream

SendInjStream(instruments, tag, kafka_server, analysis, psd, injection_file, stream=None, f_max=1600.0, offset=0, coinc_output='output_files', fake_injection_rate=20.0, fake_far_threshold=2.315e-05, verbose=False)

Bases: SegmentsTracker

Source code in gw/lts/send_inj_stream.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
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
183
184
185
186
def __init__(self, instruments, tag, kafka_server, analysis, psd,
             injection_file, stream=None, f_max=1600., offset=0,
             coinc_output="output_files", fake_injection_rate=20.0,
             fake_far_threshold=2.315e-5, verbose=False):
    logging.info("Setting up injection stream...")
    self.tag = tag
    self.kafka_server = kafka_server
    self.analysis = analysis
    self.ifos = instruments
    self.psd = psd
    self.f_max = f_max
    self.coinc_output = coinc_output
    self.fake_inj_rate = fake_injection_rate
    self.fake_far_threshold = fake_far_threshold
    self.offset = offset
    self.verbose = verbose

    # init kafka client
    self.producer = kafka.Client(f"kafka://{self.tag}@{self.kafka_server}")

    # load and sort sim inspiral table
    xmldoc = ligolw_utils.load_filename(
        injection_file, contenthandler=LIGOLWContentHandler
    )
    self.simtable = lsctables.SimInspiralTable.get_table(xmldoc)
    self.simtable.sort(
        key=lambda row: row.geocent_end_time
        + 10.0**-9.0 * row.geocent_end_time_ns
    )

    # if streaming data, set up the segments tracker
    # and find the nearest injection to start from
    if stream:
        self.lock = threading.Lock()
        LLOIDSegmentsTracker.__init__(
            self,
            stream,
            instruments,
            verbose=verbose
        )

        # init dict to store IFO segments
        self.state_history = {
            ifo: deque(maxlen=1000) for ifo in instruments
        }
        self.time_of_last_state = None

        # skip any old injections first
        t = now()
        for row in list(self.simtable):
            injection_time = row.geocent_end_time + self.offset
            # skip injections which have already passed
            if t - injection_time > 0:
                logging.debug(
                    f"Skipping old injection (t = {injection_time})"
                )
                self.simtable.pop(0)
            else:
                break
        assert len(self.simtable), "No remaining injections left in " \
                                   "simtable after skipping ones in " \
                                   "the past. Check your --time-offset."

    # otherwise, do additional setup required for
    # simulating coinc events in the fake-data scheme
    else:
        self.fake_injection_stream_setup()

calc_inj_snrs

calc_inj_snrs(inj)

Estimate injected SNRs given injection time, waveform, intrinsic and extrinsic parameters.

Parameters:
  • inj

    SimInspiral table row object corresponding to a single injection.

Returns:
  • snr(dict)

    Dictionary, keyed by ifo, of estimated injected SNRs.

Source code in gw/lts/send_inj_stream.py
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
def calc_inj_snrs(self, inj):
    """
    Estimate injected SNRs given injection time,
    waveform, intrinsic and extrinsic parameters.

    Parameters
    ----------
    inj (ligolw table row)
        SimInspiral table row object corresponding to
        a single injection.

    Returns
    ----------
    snr (dict)
        Dictionary, keyed by ifo, of estimated injected
        SNRs.
    """
    snr = dict.fromkeys(self.ifos, 0.0)

    injtime = inj.geocent_end_time
    f_min = inj.f_lower
    approximant = lalsimulation.GetApproximantFromString(str(inj.waveform))
    sample_rate = 16384.0
    f_max = self.f_max

    h_plus, h_cross = lalsimulation.SimInspiralTD(
        m1=inj.mass1 * lal.MSUN_SI,
        m2=inj.mass2 * lal.MSUN_SI,
        S1x=inj.spin1x,
        S1y=inj.spin1y,
        S1z=inj.spin1z,
        S2x=inj.spin2x,
        S2y=inj.spin2y,
        S2z=inj.spin2z,
        distance=inj.distance * 1e6 * lal.PC_SI,
        inclination=inj.inclination,
        phiRef=inj.coa_phase,
        longAscNodes=0.0,
        eccentricity=0.0,
        meanPerAno=0.0,
        deltaT=1.0 / sample_rate,
        f_min=f_min,
        f_ref=0.0,
        LALparams=None,
        approximant=approximant,
    )

    h_plus.epoch += injtime
    h_cross.epoch += injtime

    # Compute strain in each detector. If one detector wasn't on,
    # snr will be set to zero.
    for instrument in snr:
        if instrument not in self.psd.keys():
            continue
        h = lalsimulation.SimDetectorStrainREAL8TimeSeries(
            h_plus,
            h_cross,
            inj.longitude,
            inj.latitude,
            inj.polarization,
            lalsimulation.DetectorPrefixToLALDetector(instrument),
        )
        snr[instrument] = lalsimulation.MeasureSNR(
            h, self.psd[instrument], f_min, f_max
        )

    return snr

mc_eta_from_m1_m2 staticmethod

mc_eta_from_m1_m2(m1, m2)

Compute chirp mass and mass ratio from component masses.

Source code in gw/lts/send_inj_stream.py
798
799
800
801
802
803
804
805
806
@staticmethod
def mc_eta_from_m1_m2(m1, m2):
    """
    Compute chirp mass and mass ratio from component masses.
    """
    mc = (m1 * m2) ** (3.0 / 5.0) / (m1 + m2) ** (1.0 / 5.0)
    eta = (m1 * m2) / (m1 + m2) ** 2.0

    return mc, eta

produce_coinc_message

produce_coinc_message(trigger, coincfar)

Send output messages of simulated coinc events to output inj_events topic.

Parameters:
  • trigger

    Row corresponding to a single injection in the SimInspiral table.

  • coincfar

    FAR value for simulated recovered event associated with this injection.

Source code in gw/lts/send_inj_stream.py
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
def produce_coinc_message(self, trigger, coincfar):
    """
    Send output messages of simulated coinc events to output
    `inj_events` topic.

    Parameters
    ----------
    trigger (ligowl table row)
        Row corresponding to a single injection in the SimInspiral
        table.
    coincfar (float)
        FAR value for simulated recovered event associated with
        this injection.
    """
    # build coinc xml doc, calculate p_astro, and produce message
    newxmldoc = self.produce_output_coinc(trigger, coincfar)
    if not newxmldoc:
        return

    coinctable = lsctables.CoincInspiralTable.get_table(newxmldoc)
    coincrow = coinctable[0]

    time = coincrow.end_time
    coincsnr = coincrow.snr
    mchirp = coincrow.mchirp
    p_astro = pastro_utils.p_astro(mchirp, coincsnr, self.p_x_c, self.p_c)

    # write coinc file to disk
    filename = f"fake_coinc-{int(time)}.xml"
    ligolw_utils.write_filename(
        newxmldoc,
        os.path.join(self.coinc_output, filename),
        verbose=self.verbose
    )

    coinc_msg = io.BytesIO()
    ligolw_utils.write_fileobj(newxmldoc, coinc_msg)

    # create json packet
    output = {
        "time": time,
        "time_ns": coincrow.end_time_ns,
        "snr": coincsnr,
        "far": coincrow.combined_far,
        "p_astro": json.dumps(p_astro),
        "coinc": coinc_msg.getvalue().decode(),
    }

    # send coinc message to events topic
    logging.info(f"network SNR: {output['snr']} | FAR: {output['far']}")

    topic = f"fake-data.{self.tag}.testsuite.inj_events"
    self.producer.write(topic, output)
    logging.info(f"Sent msg to: {topic}")

    newxmldoc.unlink()

    return

produce_output_coinc

produce_output_coinc(row, coincfar)

Construct a full ligolw file object to represent a simulated recovered event.

Parameters:
  • row

    A single SimInspiral row corresponding to the injection.

  • coincfar

    FAR value for simulated recovered event associated with this injection.

Returns:
  • newxmldoc (ligolw file object)

    ligo-lw coinc file object with all required tables.

Source code in gw/lts/send_inj_stream.py
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
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
767
768
769
770
771
772
773
774
775
776
777
778
def produce_output_coinc(self, row, coincfar):
    """
    Construct a full ligolw file object to represent a simulated
    recovered event.

    Parameters
    ----------
    row (ligolw table row)
        A single SimInspiral row corresponding to the injection.
    coincfar (float)
        FAR value for simulated recovered event associated with
        this injection.

    Returns
    ----------
    newxmldoc (ligolw file object)
        ligo-lw coinc file object with all required tables.
    """
    # instantiate relevant lsctables objects
    newxmldoc = ligolw.Document()
    ligolw_elem = newxmldoc.appendChild(ligolw.LIGO_LW())
    new_process_table = ligolw_elem.appendChild(
        lsctables.New(lsctables.ProcessTable,
                      columns=utils.all_process_rows)
    )
    new_sngl_inspiral_table = ligolw_elem.appendChild(
        lsctables.New(lsctables.SnglInspiralTable,
                      columns=utils.all_sngl_rows)
    )
    new_coinc_inspiral_table = ligolw_elem.appendChild(
        lsctables.New(lsctables.CoincInspiralTable,
                      columns=utils.all_coinc_rows)
    )
    new_coinc_event_table = ligolw_elem.appendChild(
        lsctables.New(lsctables.CoincTable)
    )
    new_coinc_map_table = ligolw_elem.appendChild(
        lsctables.New(lsctables.CoincMapTable)
    )

    # simulate SNR time series using interpolated psd object
    # measurement_error is set as gaussian but one can switch
    # to no noise by measurement_error="zero-noise"
    bayestar_sim_list = bayestar_realize_coincs.simulate(
        seed=None,
        sim_inspiral=row,
        psds=self.psds_interp,
        responses=self.responses,
        locations=self.locations,
        measurement_error="gaussian-noise",
        f_low=20,
        f_high=2048,
    )

    # get mass parameters
    mass1 = max(numpy.random.normal(loc=row.mass1, scale=1.0), 1.1)
    mass2 = max(numpy.random.normal(loc=row.mass2, scale=1.0), mass1)
    mchirp, eta = self.mc_eta_from_m1_m2(mass1, mass2)

    snrs = defaultdict(lambda: 0)
    coincsnr = None

    # populate process table
    process_row_dict = {k: 0 for k in utils.all_process_rows}
    process_row_dict.update(
        {"process_id": 0, "program": "gstlal_inspiral", "comment": ""}
    )
    new_process_table.extend([
        lsctables.ProcessTable.RowType(**process_row_dict)
    ])

    # populate sngl table, coinc map table, and SNR timeseriess
    for event_id, (
        ifo, (horizon, abs_snr, arg_snr, toa, snr_series)
    ) in enumerate(zip(self.ifos, bayestar_sim_list)):
        sngl_row_dict = {k: 0 for k in utils.all_sngl_rows}

        sngl_row_dict.update(
            {
                "process_id": 0,
                "event_id": event_id,
                "end": toa,
                "mchirp": mchirp,
                "mass1": mass1,
                "mass2": mass2,
                "eta": eta,
                "ifo": ifo,
                "snr": abs_snr,
                "coa_phase": arg_snr,
            }
        )

        # add to the sngl inspiral table
        new_sngl_inspiral_table.extend(
            [lsctables.SnglInspiralTable.RowType(**sngl_row_dict)]
        )
        snrs[ifo] = abs_snr

        coinc_map_row_dict = {
            "coinc_event_id": 0,
            "event_id": event_id,
            "table_name": "sngl_inspiral",
        }

        # add to the coinc map table
        new_coinc_map_table.extend(
            [lsctables.CoincMapTable.RowType(**coinc_map_row_dict)]
        )

        # add SNR time series as array objects
        elem = lal.series.build_COMPLEX8TimeSeries(snr_series)
        elem.appendChild(Param.from_pyvalue("event_id", event_id))
        ligolw_elem.appendChild(elem)

    # calculate coinc SNR, only proceed if above 4
    coincsnr = numpy.linalg.norm([snr for snr in snrs.values() if snr > 4])
    if not coincsnr:
        logging.debug(f"Coinc SNR {coincsnr} too low to send a message.")
        return None

    # populate coinc inspiral table
    coinc_row_dict = {col: 0 for col in utils.all_coinc_rows}
    coincendtime = row.geocent_end_time
    coincendtimens = row.geocent_end_time_ns
    coinc_row_dict.update(
        {
            "coinc_event_id": 0,
            "snr": coincsnr,
            "mass": row.mass1 + row.mass2,
            "mchirp": row.mchirp,
            "end_time": coincendtime,
            "end_time_ns": coincendtimens,
            "combined_far": coincfar,
        }
    )
    new_coinc_inspiral_table.extend(
        [lsctables.CoincInspiralTable.RowType(**coinc_row_dict)]
    )

    # populate coinc event table
    coinc_event_row_dict = {col: 0 for col in utils.all_coinc_event_rows}
    coinc_event_row_dict.update(
        {
            "coinc_def_id": 0,
            "process_id": 0,
            "time_slide_id": 0,
            "instruments": "H1,L1,V1",
            "numevents": len(new_sngl_inspiral_table),
        }
    )
    new_coinc_event_table.extend(
        [lsctables.CoincTable.RowType(**coinc_event_row_dict)]
    )

    # add psd frequeny series
    lal.series.make_psd_xmldoc(self.psd, ligolw_elem)

    return newxmldoc

shift_times

shift_times(row, time_offset)

fix RA and GPS times according to the time offset

Parameters:
  • row

    SimInspiral table row object corresponding to a single injection.

  • time_offset

    Offset to shift injection times by.

Returns:
  • row (ligolw table row)

    SimInspiral table row with shifted times and corrected right ascension

Source code in gw/lts/send_inj_stream.py
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
def shift_times(self, row, time_offset):
    """
    fix RA and GPS times according to the time offset

    Parameters
    ----------
    row (ligolw table row)
        SimInspiral table row object corresponding to
        a single injection.
    time_offset (int)
        Offset to shift injection times by.

    Returns
    ----------
    row (ligolw table row)
        SimInspiral table row with shifted times and
        corrected right ascension
    """
    end_time = row.geocent_end_time + row.geocent_end_time_ns * 10.0**-9.0
    gmst0 = GreenwichMeanSiderealTime(LIGOTimeGPS(end_time))
    gmst = GreenwichMeanSiderealTime(LIGOTimeGPS(end_time + time_offset))
    dgmst = gmst - gmst0
    row.longitude = row.longitude + dgmst

    row.geocent_end_time = int(row.geocent_end_time + time_offset)
    row.h_end_time = row.h_end_time + time_offset
    row.l_end_time = row.l_end_time + time_offset
    row.v_end_time = row.v_end_time + time_offset

    return row