gstlal-inspiral  1.9.3
 All Classes Namespaces Files Functions
hoftcache.py
Go to the documentation of this file.
1 # Copyright (C) 2013 Kipp Cannon, Chad Hanna, Drew Keppel
2 #
3 # This program is free software; you can redistribute it and/or modify it
4 # under the terms of the GNU General Public License as published by the
5 # Free Software Foundation; either version 2 of the License, or (at your
6 # option) any later version.
7 #
8 # This program is distributed in the hope that it will be useful, but
9 # WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
11 # Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License along
14 # with this program; if not, write to the Free Software Foundation, Inc.,
15 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 
17 ## @file
18 
19 ## @package hoftcache
20 
21 #
22 # =============================================================================
23 #
24 # Preamble
25 #
26 # =============================================================================
27 #
28 
29 
30 import os
31 import sys
32 import tempfile
33 import uuid
34 
35 
36 import gi
37 gi.require_version('Gst', '1.0')
38 from gi.repository import GObject, Gst
39 GObject.threads_init()
40 Gst.init(None)
41 
42 
43 from gstlal import datasource
44 from gstlal import pipeparts
45 from gstlal import simplehandler
46 
47 
48 #
49 # =============================================================================
50 #
51 # File Clean-Up Machinery
52 #
53 # =============================================================================
54 #
55 
56 
57 class tempcache(list):
58  """
59  List-like object to hold CacheEntry objects, and run os.unlink() on
60  the .path of each as they are removed from the list or when the
61  list is garbage collected. All errors during file removal are
62  ignored.
63 
64  Note that there is no way to remove a CacheEntry from this list
65  without the file it represents being deleted. If, after adding a
66  CacheEntry to this list it is decided the file must not be deleted,
67  then instead of removing it from the list it must be replaced with
68  something else, e.g. None, and that item can then be removed from
69  the list.
70 
71  Example:
72 
73  >>> from lal.utils import CacheEntry
74  >>> # create a cache, and add an entry
75  >>> cache = tempcache()
76  >>> cache.append(CacheEntry("- - - - file://localhost/tmp/blah.txt"))
77  >>> # now remove it without the file being deleted
78  >>> cache[-1] = None
79  >>> del cache[-1]
80  """
81  def __delitem__(self, i):
82  try:
83  os.unlink(self[i].path)
84  except:
85  pass
86  super(tempcache, self).__delitem__(i)
87 
88  def __delslice__(self, i, j):
89  try:
90  for entry in self[i:j]:
91  try:
92  os.unlink(entry.path)
93  except:
94  pass
95  except:
96  pass
97  super(tempcache, self).__delslice__(i, j)
98 
99  def __del__(self):
100  del self[:]
101 
102 
103 #
104 # =============================================================================
105 #
106 # Handler
107 #
108 # =============================================================================
109 #
110 
111 
112 class Handler(simplehandler.Handler):
113  def __init__(self, *args, **kwargs):
114  super(Handler, self).__init__(*args, **kwargs)
115  self.cache = tempcache()
116 
117  def do_on_message(self, bus, message):
118  if message.type == Gst.MessageType.ELEMENT and message.get_structure().get_name() == "GstMultiFileSink":
119  self.cache.append(pipeparts.framecpp_filesink_cache_entry_from_mfs_message(message))
120  return True
121  return False
122 
123 
124 #
125 # =============================================================================
126 #
127 # Modified Version of mkbasicsrc from datasource.py
128 #
129 # =============================================================================
130 #
131 
132 
133 def mkbasicsrc(pipeline, gw_data_source_info, instrument, verbose = False):
134  if gw_data_source_info.data_source == "frames":
135  if instrument == "V1":
136  #FIXME Hack because virgo often just uses "V" in the file names rather than "V1". We need to sieve on "V"
137  src = pipeparts.mklalcachesrc(pipeline, blocksize = 1048576, use_mmap = False, location = gw_data_source_info.frame_cache, cache_src_regex = "V")
138  else:
139  src = pipeparts.mklalcachesrc(pipeline, blocksize = 1048576, use_mmap = False, location = gw_data_source_info.frame_cache, cache_src_regex = instrument[0], cache_dsc_regex = instrument)
140  demux = pipeparts.mkframecppchanneldemux(pipeline, src, do_file_checksum = False, channel_list = list(map("%s:%s".__mod__, gw_data_source_info.channel_dict.items())))
141  pipeparts.framecpp_channeldemux_set_units(demux, dict.fromkeys(demux.get_property("channel-list"), "strain"))
142  # allow frame reading and decoding to occur in a diffrent thread
143  src = pipeparts.mkqueue(pipeline, None, max_size_buffers = 0, max_size_bytes = 0, max_size_time = 8 * Gst.SECOND)
144  pipeparts.src_deferred_link(demux, "%s:%s" % (instrument, gw_data_source_info.channel_dict[instrument]), src.get_static_pad("sink"))
145  # FIXME: remove this when pipeline can handle disconts
146  src = pipeparts.mkaudiorate(pipeline, src, skip_to_first = True, silent = False)
147  else:
148  raise ValueError("invalid data_source: %s" % gw_data_source_info.data_source)
149 
150  # provide an audioconvert element to allow Virgo data (which is single-precision) to be adapted into the pipeline
151  src = pipeparts.mkaudioconvert(pipeline, src)
152 
153  # progress report
154  if verbose:
155  src = pipeparts.mkprogressreport(pipeline, src, "progress_src_%s" % instrument)
156 
157  # optional injections
158  if gw_data_source_info.injection_filename is not None:
159  src = pipeparts.mkinjections(pipeline, src, gw_data_source_info.injection_filename)
160  # let the injection code run in a different thread than the whitener, etc.,
161  src = pipeparts.mkqueue(pipeline, src, max_size_bytes = 0, max_size_buffers = 0, max_size_time = Gst.SECOND * 64)
162 
163 
164  return src
165 
166 
167 #
168 # =============================================================================
169 #
170 # Pipeline
171 #
172 # =============================================================================
173 #
174 
175 
176 def build_pipeline(pipeline, data_source_info, output_path = tempfile.gettempdir(), sample_rate = None, description = "TMPFILE_DELETE_ME_%s" % uuid.uuid4().hex, channel_comment = None, frame_duration = 1, frames_per_file = 1024, verbose = False):
177  #
178  # get instrument and channel name (requires exactly one
179  # instrument+channel)
180  #
181 
182  channelmux_input_dict = {}
183 
184  for instrument, channel_name in data_source_info.channel_dict.items():
185  #
186  # retrieve h(t)
187  #
188 
189  src = mkbasicsrc(pipeline, data_source_info, instrument, verbose = verbose)
190 
191  #
192  # optionally resample
193  #
194 
195  if sample_rate is not None:
196  # make sure we're *down*sampling
197  src = pipeparts.mkcapsfilter(pipeline, src, "audio/x-raw, rate=[%d,MAX]" % sample_rate)
198  src = pipeparts.mkresample(pipeline, src, quality = 9)
199  src = pipeparts.mkcapsfilter(pipeline, src, "audio/x-raw, rate=%d" % sample_rate)
200 
201  #
202  # pack into frame files for output
203  #
204 
205  src = pipeparts.mkframecppchannelmux(pipeline, {"%s:%s" % (instrument, channel_name): src}, frame_duration = frame_duration, frames_per_file = frames_per_file)
206  for pad in src.sinkpads:
207  if channel_comment is not None:
208  pad.set_property("comment", channel_comment)
209  pad.set_property("pad-type", "FrProcData")
210  pipeparts.mkframecppfilesink(pipeline, src, frame_type = "%s_%s" % (instrument, description), path = output_path)
211 
212 
213 #
214 # =============================================================================
215 #
216 # Collect and Cache h(t)
217 #
218 # =============================================================================
219 #
220 
221 
222 def cache_hoft(data_source_info, channel_comment = "cached h(t) for inspiral search", verbose = False, **kwargs):
223  #
224  # build pipeline
225  #
226 
227 
228  mainloop = GObject.MainLoop()
229  pipeline = Gst.Pipeline(name="pipeline")
230  handler = Handler(mainloop, pipeline)
231 
232 
233  if verbose:
234  print("assembling pipeline ...", file=sys.stderr)
235  build_pipeline(pipeline, data_source_info, channel_comment = channel_comment, verbose = verbose, **kwargs)
236  if verbose:
237  print("done", file=sys.stderr)
238 
239 
240  #
241  # seek and run pipeline
242  #
243 
244  if pipeline.set_state(Gst.State.READY) != Gst.StateChangeReturn.SUCCESS:
245  raise RuntimeError("pipeline did not enter ready state")
246  datasource.pipeline_seek_for_gps(pipeline, *data_source_info.seg)
247  if verbose:
248  print("setting pipeline state to playing ...", file=sys.stderr)
249  if pipeline.set_state(Gst.State.PLAYING) != Gst.StateChangeReturn.SUCCESS:
250  raise RuntimeError("pipeline did not enter playing state")
251 
252  if verbose:
253  print("running pipeline ...", file=sys.stderr)
254  mainloop.run()
255 
256 
257  #
258  # return tempcache object. when this object is garbage collected
259  # the frame files will be deleted. keep a reference alive as long
260  # as you wish to preserve the files.
261  #
262 
263 
264  return handler.cache