3 # Copyright (C) 2016 Kipp Cannon, Chad Hanna
4 # Copyright (C) 2019 Patrick Godwin
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.
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.
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.
28 from gstlal
import bottle
34 from gstlal
import far
35 from gstlal
import httpinterface
36 from gstlal
import servicediscovery
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
44 def service_domain(gracedb_search, gracedb_pipeline):
45 return
"%s_%s.%s" % (gracedb_pipeline.lower(), gracedb_search.lower(), servicediscovery.DEFAULT_SERVICE_DOMAIN)
48 # =============================================================================
52 # =============================================================================
55 class ZeroLagCounts(object):
57 A Class to keep track of zero lag counts clustered over 10s fixed windows
60 def __init__(self, fname, verbose = False):
62 fname is the name of the zerolag file read from disk to start the counting
64 self.lock = threading.Lock()
66 _, self.zerolag_rankingstatpdf = far.parse_likelihood_control_doc(ligolw_utils.load_url(fname, verbose = verbose, contenthandler = far.RankingStat.LIGOLWContentHandler))
69 def add_coincs(
self, coincs):
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
82 # avoid trigs before LR assigned
84 # equiv to 10s clustering
85 key = round(c[
"end"], -1)
87 self.counts_dict[key] = max(self.counts_dict.setdefault(key, lr), lr)
91 def __get_zerolag_rankingstatpdf_xmldoc(self, zlpdf):
93 generate an in memory XML document
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)
102 def __add_counts_to_zerolag_pdf(
self, zlpdf):
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
108 for lr in self.counts_dict.values():
109 zlpdf.zero_lag_lr_lnpdf.count[lr,] += 1
111 def web_get_zerolag_rankingstatpdf(self):
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.
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()
129 def snapshot_output_url(self, fname, verbose = False):
131 Write a new XML doc with the internal counts added to disk with fname
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)
139 # Read command line options
140 def parse_command_line():
142 parser = argparse.ArgumentParser(description=
"Online trigger counter")
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.")
153 args = parser.parse_args()
159 # =============================================================================
163 # =============================================================================
166 if __name__ ==
'__main__':
168 time_since_last = time.time()
169 options = parse_command_line()
170 ZLC = ZeroLagCounts(options.output)
173 # Stuff to handle bottle route to retrieve xml doc with new counts
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 = {
183 "pid": str(os.getpid()),
185 service_discovery = False,#FIXME
186 verbose = options.verbose
188 open("gstlal_ll_inspiral_trigger_counter_registry.txt", "w").write("http:
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)
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)
200 # start an infinite loop to keep updating and aggregating data
201 logging.info(
"starting up...")
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)
211 # store and reduce data for each job
213 start = timeit.default_timer()
214 logging.debug(
"adding triggers")
216 num = ZLC.add_coincs(triggers)
218 elapsed = timeit.default_timer() - start
219 logging.debug(
"time to add %d triggers: %.1f s" % (num, elapsed))
221 logging.debug(
"no triggers to process")
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()
228 # close connection to client
229 logging.info(
"shutting down client...")
233 # always end on an error so that condor won't think we're done and will