Loading [MathJax]/extensions/TeX/AMSsymbols.js
LALInference 4.1.9.1-5e288d3
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Modules Pages
cbcBayesPosToSimBurst.py
Go to the documentation of this file.
1##python
2# -*- coding: utf-8 -*-
3# cbcBayesPosToSimBurst.py
4# C2014 Salvatore Vitale <salvatore.vitale@ligo.org>
5#
6# based on
7#
8# cbcBayesPosToSimInspiral.py
9#
10# Copyright 2013
11# Benjamin Farr <bfarr@u.northwestern.edu>,
12# Will M. Farr <will.farr@ligo.org>,
13# John Veitch <john.veitch@ligo.org>
14#
15#
16# This program is free software; you can redistribute it and/or modify
17# it under the terms of the GNU General Public License as published by
18# the Free Software Foundation; either version 2 of the License, or
19# (at your option) any later version.
20#
21# This program is distributed in the hope that it will be useful,
22# but WITHOUT ANY WARRANTY; without even the implied warranty of
23# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24# GNU General Public License for more details.
25#
26# You should have received a copy of the GNU General Public License
27# along with this program; if not, write to the Free Software
28# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
29# MA 02110-1301, USA.
30"""
31Populate a sim_inspiral table with random draws from an ASCII table.
32"""
33from optparse import Option, OptionParser
34import numpy as np
35from igwn_ligolw import ligolw
36from igwn_ligolw import lsctables
37import igwn_ligolw.utils.process
38
39# Create a datatype for all relavent fields to be filled in the sim_inspiral table
40sim_inspiral_dt = [
41 ('waveform','|S64'),
42 ('frequency', 'f8'),
43 ('q', 'f8'),
44 ('bandwidth', 'f8'),
45 ('duration', 'f8'),
46 ('hrss', 'f8'),
47 ('time_geocent_gps', 'i4'),
48 ('time_geocent_gps_ns', 'i4'),
49 ('ra','f8'),
50 ('dec', 'f8'),
51 ('pol_ellipse_angle', 'f8'),
52 ('pol_ellipse_e', 'f8'),
53 ('psi', 'f8'),
54 ('amplitude', 'f8'),
55 ('egw_over_rsquared', 'f8'),
56 ('waveform_number', 'i8'),
57]
58
59def get_input_filename(parser, args):
60 """Determine name of input: either the sole positional command line argument,
61 or /dev/stdin."""
62 if len(args) == 0:
63 infilename = '/dev/stdin'
64 elif len(args) == 1:
65 infilename = args[0]
66 else:
67 parser.error("Too many command line arguments.")
68 return infilename
69
70def standardize_param_name(params, possible_names, desired_name):
71 for name in possible_names:
72 if name in params: params[params.index(name)] = desired_name
73
75 standardize_param_name(params, ['frequency','freq',], 'frequency')
76 standardize_param_name(params, ['q','Q','quality'], 'q')
77 standardize_param_name(params, ['duration', 'tau'], 'duration')
78 standardize_param_name(params, ['ra','longitude','rightascension'],'ra')
79 standardize_param_name(params, ['dec','latitude','declination'],'dec')
80 standardize_param_name(params, ['alpha','polar_angle','pol_ellipse_angle'], 'pol_ellipse_angle')
81 standardize_param_name(params, ['polar_eccentricity','eccentricity','pol_ellipse_e'], 'pol_ellipse_e')
82 standardize_param_name(params, ['psi', 'polarisation','polarization'],'psi')
83
84
86 from math import sqrt
87 params = samples.dtype.names
88 has_q = 'q' in params
89 has_dur='duration' in params
90 has_frequency = 'frequency' in params
91 if has_q:
92 q = samples['q']
93 if has_frequency:
94 duration=[i/sqrt(2)/np.pi/j for (i,j) in zip(q,samples['frequency'])]
95 else:
96 duration=np.nan
97 elif has_dur:
98 duration = samples['duration']
99 if has_frequency:
100 q=[sqrt(2)*np.pi*i*j for (i,j) in zip(duration,samples['frequency'])]
101 else:
102 q=np.nan
103 return q,duration
104
105
106if __name__ == "__main__":
107 parser = OptionParser(
108 description = __doc__,
109 usage = "%prog [options] [INPUT]",
110 option_list = [
111 Option("-o", "--output", metavar="FILE.xml",
112 help="name of output XML file"),
113 Option("--num-of-injs", metavar="NUM", type=int, default=200,
114 help="number of injections"),
115 Option("--approx", metavar="APPROX", default="SineGaussianF",
116 help="approximant to be injected"),
117 Option("--taper", metavar="TAPER", default="TAPER_NONE",
118 help="Taper methods for injections"),
119 Option("--flow", metavar="FLOW", type=float, default=None,
120 help="Taper methods for injections"),
121 ]
122 )
123
124 opts, args = parser.parse_args()
125 infilename = get_input_filename(parser, args)
126
127 # Read in ASCII table, assuming column names are the first line
128 with open(infilename, 'r') as inp:
129 params = inp.readline().split()
131 samples = np.loadtxt(inp, dtype=[(p, np.float) for p in params])
132
133 # Choose subset for sim_inspiral_table
134 N = opts.num_of_injs
135 selection = np.arange(N)
136 np.random.shuffle(selection)
137 samples = samples[selection]
138
139 # Create an empty structured array with names indentical to sim_inspiral fields
140 injections = np.zeros((N,), dtype=sim_inspiral_dt)
141
142 # Determine all mass parameterizations
144
145 # Get cycle numbers as simulation_ids
146 ids = range(N)
147
148 # Compute polar parameters from alpha if given
149 if 'alpha' in params:
150 # LIB may use use the convention that pol_ellipse_angle=alpha).
151 injections['pol_ellipse_angle'] = samples['alpha']
152 elif 'pol_ellipse_angle' in params:
153 injections['pol_ellipse_angle'] = samples['pol_ellipse_angle']
154 else:
155 injections['pol_ellipse_angle'] = None
156
157 if 'polar_eccentricity' in params:
158 injections['pol_ellipse_e']= samples['polar_eccentricity']
159 elif 'pol_ellipse_e' in params:
160 injections['pol_ellipse_e']= samples['pol_ellipse_e']
161 else:
162 injections['pol_ellipse_e']=None
163 print(params)
164 print(samples['pol_ellipse_e'])
165 print(injections['pol_ellipse_e'])
166 if 'bandwidth' in params:
167 injections['bandwidth'] = samples['bandwidth']
168 else:
169 injections['bandwidth'] = np.nan
170 if 'time' in params:
171 injections['time_geocent_gps'] = np.modf(samples['time'])[1]
172 injections['time_geocent_gps_ns'] = np.modf(samples['time'])[0] * 10**9
173 elif 'time_min' in params and 'time_max' in params:
174 est_time=samples['time_min']+0.5*(samples['time_max']-samples['time_min'])
175 injections['time_geocent_gps'] = np.modf(est_time)[1]
176 injections['time_geocent_gps_ns'] = np.modf(est_time)[0] * 10**9
177
178 # Populate structured array
179 injections['waveform'] = [opts.approx for i in range(N)]
180 try:
181 injections['frequency'] = samples['frequency']
182 except:
183 injections['frequency']=[np.nan for i in samples['ra']]
184 injections['duration'] = dur
185 injections['q'] = q
186 try:
187 injections['hrss'] = samples['hrss']
188 except:
189 injections['hrss'] = np.exp(samples['loghrss'])
190 injections['ra'] = samples['ra']
191 injections['dec'] = samples['dec']
192 injections['psi'] = samples['psi']
193
194 # Create a new XML document
195 xmldoc = ligolw.Document()
196 xmldoc.appendChild(ligolw.LIGO_LW())
197 proc = igwn_ligolw.utils.process.register_to_xmldoc(doc, sys.argv[0], {})
198
199 #create timeslide table and set offsets to 0
200 timeslide_table = lsctables.New(lsctables.TimeSlideTable)
201 timeslide_id = timeslide_table.append_offsetvector(
202 {'H1':0,'V1':0,'L1':0,'H2':0}, proc)
203
204 sim_table = lsctables.New(lsctables.SimBurstTable)
205 xmldoc.childNodes[0].appendChild(timeslide_table)
206 xmldoc.childNodes[0].appendChild(sim_table)
207
208 # Add empty rows to the sim_inspiral table
209 for inj in range(N):
210 row = sim_table.RowType()
211 for slot in row.__slots__: setattr(row, slot, 0)
212 sim_table.append(row)
213
214 # Fill in IDs
215 for i,row in enumerate(sim_table):
216 row.process_id = proc.process_id
217 row.simulation_id = sim_table.get_next_id()
218 row.time_slide_id = timeslide_id
219 # Fill rows
220 for field in injections.dtype.names:
221 vals = injections[field]
222 for row, val in zip(sim_table, vals): setattr(row, field, val)
223
224 # Write file
225 output_file = open(opts.output, 'w')
226 xmldoc.write(output_file)
227 output_file.close()
def compute_duration_parameterizations(samples)
def standardize_param_name(params, possible_names, desired_name)
def get_input_filename(parser, args)
Determine name of input: either the sole positional command line argument, or /dev/stdin.