gstlal-inspiral  1.9.3
 All Classes Namespaces Files Functions
gstlal_ll_inspiral_trigger_counter
1 #!/usr/bin/env python3
2 #
3 # Copyright (C) 2016 Kipp Cannon, Chad Hanna
4 # Copyright (C) 2019 Patrick Godwin
5 #
6 # This program is free software; you can redistribute it and/or modify it
7 # under the terms of the GNU General Public License as published by the
8 # Free Software Foundation; either version 2 of the License, or (at your
9 # option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
14 # Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with this program; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 
20 
21 import argparse
22 import logging
23 import sys, os
24 import time
25 import timeit
26 import io
27 import threading
28 from gstlal import bottle
29 import socket
30 import base64
31 import uuid
32 import shutil
33 
34 from gstlal import far
35 from gstlal import httpinterface
36 from gstlal import servicediscovery
37 from ligo import lw
38 from ligo.lw import utils as ligolw_utils
39 from ligo.lw.utils import process as ligolw_process
40 from ligo.scald import aggregator
41 from ligo.scald.io import kafka
42 
43 
44 def service_domain(gracedb_search, gracedb_pipeline):
45  return "%s_%s.%s" % (gracedb_pipeline.lower(), gracedb_search.lower(), servicediscovery.DEFAULT_SERVICE_DOMAIN)
46 
47 #
48 # =============================================================================
49 #
50 # Command Line
51 #
52 # =============================================================================
53 #
54 
55 class ZeroLagCounts(object):
56  """
57  A Class to keep track of zero lag counts clustered over 10s fixed windows
58  """
59 
60  def __init__(self, fname, verbose = False):
61  """
62  fname is the name of the zerolag file read from disk to start the counting
63  """
64  self.lock = threading.Lock()
65  self.fname = fname
66  _, self.zerolag_rankingstatpdf = far.parse_likelihood_control_doc(ligolw_utils.load_url(fname, verbose = verbose, contenthandler = far.RankingStat.LIGOLWContentHandler))
67  self.counts_dict = {}
68 
69  def add_coincs(self, coincs):
70  """
71  Iterate over a list of coincs to extract their gps time and
72  likelihood ratio value. GPS times are rounded to the nearest 10s in order to
73  cluster events. The max likelihood is tracked in the dictionary over the 10s
74  window. Nothing is added to the zerolag histograms. The counts are purely
75  internal. Only when a new zerolag histogram is requested will the zerolag
76  histogram be updated. That makes it easier to manage late buffers. No
77  additional logic required. The number of coincs added is returned for
78  logging purposes
79  """
80  cnt = 0
81  for c in coincs:
82  # avoid trigs before LR assigned
83  if "likelihood" in c:
84  # equiv to 10s clustering
85  key = round(c["end"], -1)
86  lr = c["likelihood"]
87  self.counts_dict[key] = max(self.counts_dict.setdefault(key, lr), lr)
88  cnt += 1
89  return cnt
90 
91  def __get_zerolag_rankingstatpdf_xmldoc(self, zlpdf):
92  """
93  generate an in memory XML document
94  """
95  xmldoc = lw.ligolw.Document()
96  xmldoc.appendChild(lw.ligolw.LIGO_LW())
97  process = ligolw_process.register_to_xmldoc(xmldoc, u"gstlal_inspiral", paramdict = {})
98  far.gen_likelihood_control_doc(xmldoc, None, zlpdf)
99  ligolw_process.set_process_end_time(process)
100  return xmldoc
101 
102  def __add_counts_to_zerolag_pdf(self, zlpdf):
103  """
104  Add the internal counts to a zerolag histogram. NOTE!!!! This
105  should never be called on the internal zerolag histogram, only on a copy. That
106  is why this method is not invoked unless someone is requesting an updated file
107  """
108  for lr in self.counts_dict.values():
109  zlpdf.zero_lag_lr_lnpdf.count[lr,] += 1
110 
111  def web_get_zerolag_rankingstatpdf(self):
112  """
113  offer up a new XML doc with the internal counts added to the
114  counts that this program was seeded with. Suitable as a bottle route.
115  """
116  with self.lock:
117  # always make a copy of the *original* pdf that was
118  # loaded at start, never modify it. Just update a copy.
119  # Avoids annoying logic for late buffers. The idea is
120  # that you always get the most up to date.
121  zlpdf = self.zerolag_rankingstatpdf.copy()
122  self.__add_counts_to_zerolag_pdf(zlpdf)
123  output = io.BytesIO()
124  ligolw_utils.write_fileobj(self.__get_zerolag_rankingstatpdf_xmldoc(zlpdf), output)
125  outstr = output.getvalue()
126  output.close()
127  return outstr
128 
129  def snapshot_output_url(self, fname, verbose = False):
130  """
131  Write a new XML doc with the internal counts added to disk with fname
132  """
133  with self.lock:
134  zlpdf = self.zerolag_rankingstatpdf.copy()
135  self.__add_counts_to_zerolag_pdf(zlpdf)
136  ligolw_utils.write_url(self.__get_zerolag_rankingstatpdf_xmldoc(zlpdf), fname, verbose = verbose, trap_signals = None)
137 
138 
139 # Read command line options
140 def parse_command_line():
141 
142  parser = argparse.ArgumentParser(description="Online trigger counter")
143 
144  # directory to put everything in
145  parser.add_argument("--topic", default="triggers", help="Specify the topic where triggers are located.")
146  parser.add_argument("--output-period", type = float, default = 3600., help = "Wait this many seconds between writing the output file (default = 3600)")
147  parser.add_argument("-u", "--uri", default="kafka://localhost:9092", help="specify Kafka URI to read metrics from. default = kafka://localhost:9092.")
148  parser.add_argument("--output", default="zerolag_rankingstatpdf.xml.gz", help = "Choose the output file. Default zerolag_rankingstatpdf.xml.gz")
149  parser.add_argument("--gracedb-pipeline", default = "gstlal", help = "Name of pipeline to provide in GracedB uploads (default is gstlal).")
150  parser.add_argument("--gracedb-search", default = "LowMass", help = "Name of search to provide in GracedB uploads (default is LowMass).")
151  parser.add_argument("-v", "--verbose", default=False, action="store_true", help = "Be verbose.")
152 
153  args = parser.parse_args()
154 
155  return args
156 
157 
158 #
159 # =============================================================================
160 #
161 # Main
162 #
163 # =============================================================================
164 #
165 
166 if __name__ == '__main__':
167 
168  time_since_last = time.time()
169  options = parse_command_line()
170  ZLC = ZeroLagCounts(options.output)
171 
172  #
173  # Stuff to handle bottle route to retrieve xml doc with new counts
174  #
175 
176  bottle.default_app.push()
177  bottle.route('/zerolag_rankingstatpdf.xml')(ZLC.web_get_zerolag_rankingstatpdf)
178  httpservers = httpinterface.HTTPServers(
179  service_name = "%s.gstlal_ll_inspiral_trigger_counter" % (base64.urlsafe_b64encode(uuid.uuid4().bytes)),
180  service_domain = service_domain(options.gracedb_search, options.gracedb_pipeline),
181  service_properties = {
182  "cwd": os.getcwd(),
183  "pid": str(os.getpid()),
184  },
185  service_discovery = False,#FIXME
186  verbose = options.verbose
187  )
188  open("gstlal_ll_inspiral_trigger_counter_registry.txt", "w").write("http://%s:%s/\n" % (socket.gethostname(), httpservers[0][0].port))
189 
190 
191  # set up logging
192  log_level = logging.DEBUG if options.verbose else logging.INFO
193  logging.basicConfig(format = '%(asctime)s | gstlal_ll_inspiral_trigger_counter : %(levelname)s : %(message)s')
194  logging.getLogger().setLevel(log_level)
195 
196  # instantiate a consumer to subscribe to all of our topics, i.e., jobs
197  client = kafka.Client(options.uri)
198  client.subscribe(options.topic)
199 
200  # start an infinite loop to keep updating and aggregating data
201  logging.info("starting up...")
202  while True:
203 
204  logging.debug("retrieving data from kafka")
205  start = timeit.default_timer()
206  msgs = [msg for msg in client.query(max_messages=2000)]
207  triggers = aggregator.parse_triggers(msgs)
208  elapsed = timeit.default_timer() - start
209  logging.debug("time to retrieve data: %.1f s" % elapsed)
210 
211  # store and reduce data for each job
212  if triggers:
213  start = timeit.default_timer()
214  logging.debug("adding triggers")
215 
216  num = ZLC.add_coincs(triggers)
217 
218  elapsed = timeit.default_timer() - start
219  logging.debug("time to add %d triggers: %.1f s" % (num, elapsed))
220  else:
221  logging.debug("no triggers to process")
222 
223  if (time.time() - time_since_last) > options.output_period:
224  shutil.move(options.output, options.output + ".bk")
225  ZLC.snapshot_output_url(options.output, verbose = True)
226  time_since_last = time.time()
227 
228  # close connection to client
229  logging.info("shutting down client...")
230  client.close()
231 
232  #
233  # always end on an error so that condor won't think we're done and will
234  # restart us
235  #
236 
237  sys.exit(1)