gstlal-inspiral  1.9.3
 All Classes Namespaces Files Functions
gstlal_inspiral_merge_and_reduce
1 #!/usr/bin/env python3
2 #
3 # Copyright (C) 2007--2014,2016,2017 Kipp Cannon
4 #
5 # This program is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the
7 # Free Software Foundation; either version 3 of the License, or (at your
8 # option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
13 # Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 
19 
20 #
21 # =============================================================================
22 #
23 # Preamble
24 #
25 # =============================================================================
26 #
27 
28 
29 """
30 Transfer table data between LIGO Light Weight XML files and SQLite
31 databases.
32 """
33 
34 
35 from __future__ import print_function
36 from optparse import OptionParser
37 import os
38 import sqlite3
39 import sys
40 
41 
42 from lal.utils.cache import CacheEntry
43 from ligo.lw import __date__, __version__
44 from ligo.lw import ligolw
45 from ligo.lw import dbtables
46 from ligo.lw.utils import local_path_from_url
47 from ligo.lw.utils import ligolw_sqlite
48 import six
49 
50 
51 # so they can be inserted into a database
52 dbtables.ligolwtypes.ToPyType["ilwd:char"] = six.text_type
53 
54 
55 __author__ = "Kipp Cannon <kipp.cannon@ligo.org>"
56 
57 
58 #
59 # =============================================================================
60 #
61 # Command Line
62 #
63 # =============================================================================
64 #
65 
66 
67 def parse_command_line():
68  """
69  Parse the command line, return an options object and a list of file
70  names.
71  """
72  parser = OptionParser(
73  version = "Name: %%prog\n%s" % __version__,
74  usage = "%prog -d|--database filename [options] [url ...]",
75  description = "merge database files applying the sql in --sql-file as you go"
76  )
77  parser.add_option("-d", "--database", metavar = "filename", help = "Set the name of the SQLite3 database file (required).")
78  parser.add_option("--ilwdchar-compat", action = "store_true", help = "Use obsolete ilwd:char based table definitions and ID reassignment algorithm (default = use new int_8s based table definitions and ID reassignment algorithm).")
79  parser.add_option("-i", "--input-cache", metavar = "filename", action = "append", default = [], help = "Get the names of XML documents to insert into the database from this LAL cache. This option can be given multiple times, and all files from all caches will be loaded.")
80  parser.add_option("-p", "--preserve-ids", action = "store_true", help = "Preserve row IDs from the XML in the database. The default is to assign new IDs to prevent collisisions. Inserts will fail if collisions occur.")
81  parser.add_option("-r", "--replace", action = "store_true", help = "If the database file already exists, over-write it instead of inserting into it.")
82  parser.add_option("-t", "--tmp-space", metavar = "path", help = "Path to a directory suitable for use as a work area while manipulating the database file. The database file will be worked on in this directory, and then moved to the final location when complete. This option is intended to improve performance when running in a networked environment, where there might be a local disk with higher bandwidth than is available to the filesystem on which the final output will reside.")
83  parser.add_option("-s", "--sql-file", metavar = "filename", help = "Execute this SQL file (required).")
84  parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose.")
85  options, urls = parser.parse_args()
86 
87  urls = [CacheEntry(line).url for cache in options.input_cache for line in open(cache)] + urls
88 
89  if not options.database:
90  raise ValueError("missing required argument --database")
91 
92  return options, (urls or [None])
93 
94 
95 #
96 # =============================================================================
97 #
98 # Main
99 #
100 # =============================================================================
101 #
102 
103 
104 #
105 # Command line
106 #
107 
108 
109 options, urls = parse_command_line()
110 
111 will_replace_file = options.replace
112 will_use_tmp_space = options.tmp_space is not None
113 
114 if options.ilwdchar_compat:
115  from glue.ligolw import ligolw
116  from glue.ligolw import dbtables
117  from glue.ligolw.utils import local_path_from_url
118  from glue.ligolw.utils import ligolw_sqlite
119 
120 #
121 # Setup sql
122 #
123 
124 # Parse the sql file into something that can be executed in sequence
125 sql = [line.strip() for line in open(options.sql_file)]
126 # Remove comments and pragmas
127 sql = [s for s in sql if not s.startswith("--") and not s.startswith("PRAGMA")]
128 sql = "\n".join(sql)
129 sql = [statement.strip() for statement in sql.split(";\n")]
130 sql = [statement for statement in sql if statement]
131 
132 
133 #
134 # Open database
135 #
136 
137 
138 @dbtables.use_in
139 class ContentHandler(ligolw.LIGOLWContentHandler):
140  pass
141 
142 
143 with dbtables.workingcopy(options.database, tmp_path = options.tmp_space if will_use_tmp_space else None, replace_file = will_replace_file, verbose = options.verbose) as target:
144  ContentHandler.connection = sqlite3.connect(str(target))
145  cursor = ContentHandler.connection.cursor()
146 
147 
148  #
149  # Insert files
150  #
151 
152 
153  for n, url in enumerate(urls, 1):
154  if options.verbose:
155  print("%d/%d:" % (n, len(urls)), end=' ', file=sys.stderr)
156  if url.endswith(".sqlite"):
157  with dbtables.workingcopy(local_path_from_url(url), tmp_path = options.tmp_space, discard = True, verbose = options.verbose) as source_filename:
158  if options.verbose:
159  print("reading '%s' ..." % source_filename, file=sys.stderr)
160  xmldoc = dbtables.get_xml(sqlite3.connect(str(source_filename)))
161  ligolw_sqlite.insert_from_xmldoc(ContentHandler.connection, xmldoc, preserve_ids = options.preserve_ids, verbose = options.verbose)
162  xmldoc.unlink()
163  else:
164  ligolw_sqlite.insert_from_url(url, contenthandler = ContentHandler, preserve_ids = options.preserve_ids, verbose = options.verbose)
165 
166  if options.verbose:
167  print("Executing SQL ...", file=sys.stderr)
168 
169  for statement in sql:
170  if options.verbose:
171  print(statement, file=sys.stderr)
172  cursor.execute(statement)
173  ContentHandler.connection.commit()
174 
175  if options.verbose:
176  print("... Done.", file=sys.stderr)
177 
178 
179  dbtables.build_indexes(ContentHandler.connection, options.verbose)
180 
181 
182  #
183  # Close database, and move to final location
184  #
185 
186 
187  ContentHandler.connection.close()
188 
189 
190 #
191 # Done
192 #
193 
194 
195 if options.verbose:
196  print("done.", file=sys.stderr)