gstlal-inspiral  1.9.2
 All Classes Namespaces Files Functions
lloid.py
Go to the documentation of this file.
1 # Copyright (C) 2010 Leo Singer
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 lloidplots
20 """
21 
22 Plotting tools, mostly for inspiral searches.
23 
24 """
25 __author__ = "Leo Singer <leo.singer@ligo.org>"
26 __organization__ = ["LIGO", "California Institute of Technology"]
27 __copyright__ = "Copyright 2010, Leo Singer"
28 
29 
30 import itertools
31 import pylab
32 
33 
34 import gstlal.pipeutil # FIXME: needed because we have GStreamer stuff mixed in where it shouldn't be
35 
36 """Dictionary of strings for useful units."""
37 units = {
38  'msun': r"$M_\odot$",
39 }
40 
41 
42 """Dictionary of strings for useful plot labels. Keys are generallly named the
43 same as a matching ligolw column."""
44 labels = {
45  'mtotal': r"total mass, $M$ (%s)" % units['msun'],
46  'mchirp': r"chirp mass, $\mathcal{M}$ (%s)" % units['msun'],
47  'mass1': r"component mass 1, $M_1$ (%s)" % units['msun'],
48  'mass2': r"component mass 2, $M_2$ (%s)" % units['msun'],
49  'snr': r"SNR $\rho$",
50  'eff_snr': r"effective SNR $\rho_\mathrm{eff}$",
51  'combined_snr': r"combined SNR, $\sqrt{\sum\rho^2}$",
52  'combined_eff_snr': r"combined effective SNR, $\sqrt{\sum\rho_\mathrm{eff}^2}$",
53  'chisq': r"$\chi^2$",
54  'tau0': r"chirp time $\tau0$",
55  'tau3': r"chirp time $\tau3$",
56 }
57 
58 
59 def plotbank(in_filename, out_filename=None, column1='mchirp', column2='mtotal'):
60  """Plot template bank parameters from a file generated by lalapps_tmpltbank."""
61  from ligo.lw import ligolw, utils, lsctables
62  class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
63  pass
64  lsctables.use_in(LIGOLWContentHandler)
65  table = lsctables.SnglInspiralTable.get_table(
66  utils.load_filename(in_filename, contenthandler = LIGOLWContentHandler)
67  )
68  pylab.figure()
69  pylab.title('%s: placement of %d templates' % (in_filename, len(table)))
70  pylab.plot(table.get_column(column1), table.get_column(column2), ',')
71  pylab.xlabel(labels[column1])
72  pylab.ylabel(labels[column2])
73  pylab.grid()
74  if out_filename is None:
75  pylab.show()
76  else:
77  pylab.savefig(out_filename)
78  pylab.close()
79 
80 
81 def plotsvd(in_filename, out_filename=None):
82  """Plot heatmap of orthogonal template components."""
83  from gstlal.gstlal_svd_bank import read_bank
84  bank = read_bank(in_filename)
85  ntemplates = 0
86  for bf in bank.bank_fragments:
87  next_ntemplates = ntemplates + bf.orthogonal_template_bank.shape[0]
88  pylab.imshow(
89  pylab.log10(abs(bf.orthogonal_template_bank[::-1,:])),
90  extent = (bf.end, bf.start, ntemplates, next_ntemplates),
91  hold=True, aspect='auto'
92  )
93  pylab.text(bf.end + bank.filter_length / 30, ntemplates + 0.5 * bf.orthogonal_template_bank.shape[0], '%d Hz' % bf.rate, size='x-small')
94  ntemplates = next_ntemplates
95 
96  pylab.xlim(0, 1.15*bank.filter_length)
97  pylab.ylim(0, 1.05*ntemplates)
98  pylab.colorbar().set_label('$\mathrm{log}_{10} |u_{i}(t)|$')
99  pylab.xlabel(r"Time $t$ until coalescence (seconds)")
100  pylab.ylabel(r"Basis index $i$")
101  pylab.title(r"Orthonormal basis templates $u_{i}(t)$")
102  if out_filename is None:
103  pylab.show()
104  else:
105  pylab.savefig(out_filename)
106  pylab.close()
107 
108 
109 def plotskymap(fig, theta, phi, logp, gpstime, arrival_times=None, inj_lon_lat=None):
110  """Draw a skymap as produced by the lal_skymap element.
111  arrival_times should be a dictionary with keys being IFO names
112  (e.g. 'H1', 'L1', 'V1', ...) and values being double precision GPS arrival
113  at each IFO.
114 
115  If inj_lon_at is set to a celestial Dec/RA tuple in radians, then the
116  injection point of origin will be marked with a cross.
117 
118  Currently, lal_skymap generates a grid of 450x900 points, and this code
119  relies on that. It could be generalized to handle any rectangular grid,
120  but the pcolormesh method that is used here is really only finally tuned for
121  quadrilateral meshes.
122  """
123 
124 
125  # Some imports that are only useful for this function
126 
127  from math import atan2, acos, asin, degrees, sqrt, pi
128  from mpl_toolkits.basemap import Basemap, shiftgrid
129  import numpy as np
130  import lal
131  import lalsimulation
132 
133 
134  # Some useful functions
135 
136  def location_for_site(prefix):
137  """Get the Cartesian (WGS84) coordinates of a site, given its prefix
138  (H1 for Hanford, L1 for Livingston...)."""
139  return lalsimulation.DetectorPrefixToLALDetector(prefix).location
140 
141  def cart2spherical(cart):
142  """Convert a Cartesian vector to spherical polar azimuth (phi) and elevation (theta) in radians."""
143  return atan2(cart[1], cart[0]), acos(cart[2] / sqrt(np.dot(cart, cart)))
144 
145 
146  def spherical2latlon(spherical):
147  """Converts spherical polar coordinates in radians to latitude, longitude in degrees."""
148  return degrees(spherical[0]), 90 - degrees(spherical[1])
149 
150 
151  # Get figure axes.
152  ax = fig.gca()
153 
154  # Initialize map; draw gridlines and map boundary.
155  m = Basemap(projection='moll', lon_0=0, lat_0=0, ax=ax)
156  m.drawparallels(np.arange(-45,46,45), linewidth=0.5, labels=[1, 0, 0, 0], labelstyle="+/-")
157  m.drawmeridians(np.arange(-180,180,90), linewidth=0.5)
158  m.drawmapboundary()
159 
160  # lal_skymap outputs geographic coordinates; convert to celestial here.
161  sidereal_time = np.mod(lal.GreenwichMeanSiderealTime(lal.LIGOTimeGPS(gpstime)) / lal.PI_180, 360)
162  lons_grid = sidereal_time + phi.reshape(450, 900) / lal.PI_180
163  lats_grid = 90 - theta.reshape(450, 900) / lal.PI_180
164  logp_grid = logp.reshape(450, 900)
165 
166  # Rotate the coordinate grid; Basemap is too stupid to correctly handle a
167  # scalar field that must wrap around the edge of the map.
168  # FIXME: Find a mapping library that isn't a toy.
169  gridshift = round(sidereal_time / 360) * 360 + 180
170  lats_grid, dummy = shiftgrid(gridshift, lats_grid, lons_grid[0,:], start=False)
171  logp_grid, dummy = shiftgrid(gridshift, logp_grid, lons_grid[0,:], start=False)
172  lons_grid, dummy = shiftgrid(gridshift, lons_grid, lons_grid[0,:], start=False)
173 
174  # Transform from longitude/latitude to selected projection.
175  x, y = m(lons_grid, lats_grid)
176 
177  # Draw log probability distribution
178  pc = m.pcolormesh(x, y, logp_grid, vmin=logp[np.isfinite(logp)].min())
179  cb = fig.colorbar(pc, shrink=0.5)
180  cb.set_label('log relative probability')
181  cb.cmap.set_under('1.0', alpha=1.0)
182  cb.cmap.set_bad('1.0', alpha=1.0)
183 
184  # Draw mode of probability distribution
185  maxidx = logp_grid.flatten().argmax()
186  m.plot(x.flatten()[maxidx], y.flatten()[maxidx], '*', markerfacecolor='white', markersize=10)
187 
188  # Draw time delay loci, if arrival times were provided.
189  if arrival_times is not None:
190  for sites in itertools.combinations(arrival_times.keys(), 2):
191  site0_location = location_for_site(sites[0])
192  site1_location = location_for_site(sites[1])
193  site_separation = site0_location - site1_location
194  site_distance_seconds = sqrt(np.dot(site_separation, site_separation)) / lal.C_SI
195  lon, lat = spherical2latlon(cart2spherical(site_separation))
196  site0_toa = arrival_times[sites[0]]
197  site1_toa = arrival_times[sites[1]]
198  radius = acos((site1_toa - site0_toa) / site_distance_seconds) * 180 / pi
199  # Sigh. Basemap is too stupid to be able to draw circles that wrap around
200  # the dateline. We'll just grab the points it generated, and plot it as
201  # a dense scatter point series.
202  poly = m.tissot(lon + sidereal_time, lat, radius, 1000, facecolor='none')
203  poly.remove()
204  x, y = zip(*poly.xy)
205  m.plot(x, y, ',k')
206 
207  # Draw injection point, if provided
208  if inj_lon_lat is not None:
209  inj_x, inj_y = m(degrees(inj_lon_lat[0]), degrees(inj_lon_lat[1]))
210  m.plot(inj_x, inj_y, '+k', markersize=20, markeredgewidth=1)
211 
212  # Add labels
213  ax.set_title('Candidate log probability distribution')
214  ax.set_xlabel('RA/dec, J2000. White star marks the mode of the PDF.\nBlack lines represent time delay solution loci for each pair of detectors.', fontsize=10)