gstlal-inspiral  1.9.3
 All Classes Namespaces Files Functions
snr.py
1 """
2 Plotting SNR from LIGO light-weight XML file
3 """
4 import sys
5 import numpy
6 
7 import matplotlib
8 matplotlib.use("Agg")
9 matplotlib.rcParams.update({
10  "font.size": 10.0,
11  "axes.titlesize": 10.0,
12  "axes.labelsize": 10.0,
13  "xtick.labelsize": 10.0,
14  "ytick.labelsize": 10.0,
15  "legend.fontsize": 10.0,
16  "figure.dpi": 100,
17  "savefig.dpi": 100,
18  "text.usetex": True
19 })
20 from matplotlib import pyplot
21 
22 from gstlal import svd_bank_snr
23 from gstlal.plots import util as plotutil
24 
25 def plot_snr(SNR_dict, width=8, center=None, span=None, verbose=False):
26  """Plot snr time series from SNR_dicts.
27 
28  Args:
29  SNR_dict: A dictionary containing (instrument, LAL series) pairs.
30  width (int): The width of the output figure in inch.
31  center (float): The center gpstime of the plot.
32  span (float): Seconds to span around center.
33  verbose (bool, default=False): Be verbose.
34 
35  Return:
36  fig (object): Matplotlib figure.
37  """
38 
39  nrows = len(SNR_dict.keys())
40  ncols = 1
41 
42  fig, axes = pyplot.subplots(nrows = nrows, ncols = ncols, sharex = True)
43  if nrows == 1:
44  axes = [axes]
45  _axes_add_snr(axes, SNR_dict, center = center, span = span)
46  fig.set_size_inches(width, int(round(width/plotutil.golden_ratio)))
47  fig.tight_layout(pad = 0.8)
48 
49  return fig
50 
51 def plot_snr_with_ac(SNR_dict, autocorrelation_dict, width=8, ref_trigger_time=None, verbose=False):
52  """Plot real part of the snr time series together with template autocorrelation.
53 
54  Args:
55  SNR_dict (dict): A dictionary containing (instrument, LAL series) pairs.
56  autocorrelation_dict (dict): A dictionary containing (instrument, numpy.array) pairs.
57  width (int): The width of the output figure in inch.
58  ref_trigger_time (float, default=None): The reference trigger time which it used to find the actual trigger time based on the time series.
59  verbose (bool, default=False): Be verbose.
60 
61  Return:
62  fig (object): Matplotlib figure.
63  """
64 
65  all_instruments = set(SNR_dict) & set(autocorrelation_dict)
66  nrows = len(all_instruments)
67  ncols = 1
68 
69  fig, axes = pyplot.subplots(nrows = nrows, ncols = ncols, sharex = False)
70  if nrows == 1:
71  axes = [axes]
72  _axes_add_snr_with_ac(axes, SNR_dict, autocorrelation_dict, ref_trigger_time = ref_trigger_time)
73  fig.set_size_inches(width, int(round(width/plotutil.golden_ratio)))
74  fig.tight_layout(pad = 0.8)
75 
76  return fig
77 
78 def _axes_add_snr(axes, SNR_dict, center=None, span=None):
79  """Add snr time series to the plot
80 
81  Args:
82  axes (object): Matplotlib axes.
83  SNR_dict (dict): A dictionary of only one snr.
84  center (float): The center gpstime of the plot.
85  span (float): Seconds to span around center.
86  """
87  col = 0
88  for instrument, SNRs in SNR_dict.items():
89  if len(SNRs) > 1:
90  raise ValueError("Too many SNR time series in SNR_dict.")
91 
92  data, center_gps_time, relative_gps_time = _trim_by_time(SNRs[0], center = center, span = span)
93  if numpy.iscomplexobj(data):
94  axes[col].plot(relative_gps_time, data.real, color = plotutil.colour_from_instruments([instrument]), linestyle = "-", label = r"$\mathrm{Real}: \ \rho(t)$", linewidth = 1)
95  axes[col].plot(relative_gps_time, data.imag, color = plotutil.colour_from_instruments([instrument]), linestyle = "--", label = r"$\mathrm{Imaginary}: \ \rho(t)$", linewidth = 1)
96  else:
97  axes[col].plot(relative_gps_time, data, color = plotutil.colour_from_instruments([instrument]), label = r"$\|\rho(t)\|$" , linewidth = 1)
98  axes[col].set_xlabel(r"$\mathrm{GPS \ Time \ Since \ %f}$" % center_gps_time)
99  axes[col].set_ylabel(r"$\mathrm{%s} \ \rho(t)$" % instrument)
100  axes[col].legend(loc = "upper left")
101  axes[col].grid(True)
102  axes[col].tick_params(labelbottom = True)
103  col += 1
104 
105 def _axes_add_snr_with_ac(axes, SNR_dict, autocorrelation_dict, ref_trigger_time):
106  """Add snr time series and template autocorrelation to the plot
107 
108  Args:
109  axes (object): Matplotlib axes.
110  SNR_dict (dict): A dictionary of only one snr.
111  autocorrelation_dict (dict): A dictionary containing (instrument, numpy.array) pairs.
112  ref_trigger_time (float, default=None): The reference trigger time which it used to find the actual trigger time based on the time series.
113  """
114  assert len(SNR_dict) == len(autocorrelation_dict), "Number of instruments of SNRs and template autocorrelations does not match."
115 
116  all_instruments = set(SNR_dict) & set(autocorrelation_dict)
117  col = 0
118 
119  for instrument in all_instruments:
120  if len(SNR_dict[instrument]) > 1 or len(autocorrelation_dict[instrument]) > 1:
121  raise ValueError("Too many SNR time series or template autocorrelation in the dictionary.")
122 
123  complex_snr, trigger_time = _find_trigger_time(SNR_dict[instrument][0], ref_trigger_time = ref_trigger_time)
124  SNR, center_gps_time, relative_gps_time = _trim_by_samples(SNR_dict[instrument][0], center = trigger_time, samples = len(autocorrelation_dict[instrument][0]))
125  phase = numpy.angle(complex_snr)
126 
127  # pick only the real part of SNR and autocorrelation, then scale the autocorrelation
128  real_SNR = (SNR * numpy.exp(-1.j * phase)).real
129  scaled_autocorrelation = autocorrelation_dict[instrument][0].real * max(real_SNR)
130 
131  # now do ploting
132  axes[col].plot(relative_gps_time, real_SNR, color = plotutil.colour_from_instruments([instrument]), linestyle = "-", label = r"$\mathrm{Measured}:\rho(t)$" , linewidth = 1)
133  axes[col].plot(relative_gps_time, scaled_autocorrelation, color = "black", linestyle = "--", label = r"$\mathrm{Scaled \ Autocorrelation}$" , linewidth = 1)
134 
135  axes[col].set_xlabel(r"$\mathrm{GPS \ Time \ Since \ %f}$" % center_gps_time)
136  axes[col].set_ylabel(r"$\mathrm{%s} \ \rho(t)$" % instrument)
137  axes[col].legend(loc = "upper left")
138  axes[col].grid(True)
139  axes[col].tick_params(labelbottom = True)
140  col += 1
141 
142 
143 def _trim_by_time(snr_series, center, span):
144  """Trim the snr_series to the nearest center with certain span, the original time series is remained intact.
145 
146  Args:
147  snr_series (lal.series): A SNR lal.series.
148  center (float): The center gpstime of the trimmed data.
149  span (float): Seconds to span around center.
150 
151  Return:
152  data (numpy.array <type 'float'>): The snr_series.data.data[center-span, center+span].
153  gps_time (float): The nearest gps_time at center.
154  relative_gps_time (numpy.array <type 'float'>): The gpstime relative to gps_time.
155  """
156  if center and span:
157  start = _find_nearest(snr_series, center - span)[1]
158  mid = _find_nearest(snr_series, center)[1]
159  end = _find_nearest(snr_series, center + span)[1]
160  else:
161  start = None
162  mid = 0
163  end = None
164 
165  gps_time = (snr_series.epoch.gpsSeconds + snr_series.epoch.gpsNanoSeconds * 1.e-9 + (numpy.arange(snr_series.data.length) * snr_series.deltaT))
166 
167  return snr_series.data.data[start:end], gps_time[mid], (gps_time - gps_time[mid])[start:end]
168 
169 def _trim_by_samples(snr_series, center, samples=351):
170  """Trim the snr_series to the nearest center with given samples, the original time series is remained intact.
171 
172  Args:
173  snr_series (lal.series): A SNR LAL series.
174  center (float): The center gpstime of the trimmed data.
175  samples (int, default=351): The samples of the output data.
176 
177  Return:
178  data (numpy.array <type 'float'>): The snr_series.data.data[center-span, center+span].
179  gps_time (float): The nearest gps_time at center.
180  relative_gps_time (numpy.array <type 'float'>): The gpstime relative to gps_time.
181  """
182  assert samples % 2 == 1, "An odd number of samples is expected."
183 
184  left_right_samples = (samples - 1) // 2
185 
186  gps_time = (snr_series.epoch.gpsSeconds + snr_series.epoch.gpsNanoSeconds * 1.e-9 + (numpy.arange(snr_series.data.length) * snr_series.deltaT))
187 
188  mid = _find_nearest(snr_series, center)[1]
189  start = mid - left_right_samples if mid - left_right_samples > 0 else 0
190  end = mid + left_right_samples if mid + left_right_samples < len(gps_time) - 1 else len(gps_time) - 1
191 
192  return snr_series.data.data[start:end+1], gps_time[mid], (gps_time - gps_time[mid])[start:end+1]
193 
194 def _find_trigger_time(snr_series, ref_trigger_time=None):
195  """Find the nearest gps time available from the time series
196 
197  Args:
198  snr_series (lal.series): A SNR LAL series.
199  time (float): Requested gpstime.
200 
201  Return:
202  (SNR, index): A tuple of SNR and index nearest to time.
203  """
204  # FIXME: perhaps as an options?
205  span = 1.
206  search_left_right_samples = int(round(span / snr_series.deltaT))
207 
208  gps_time = (snr_series.epoch.gpsSeconds + snr_series.epoch.gpsNanoSeconds * 1.e-9 + (numpy.arange(snr_series.data.length) * snr_series.deltaT))
209  mid = _find_nearest(snr_series, ref_trigger_time)[1] if ref_trigger_time is not None else len(gps_time) // 2
210  end = len(gps_time) - 1 if mid + search_left_right_samples > len(gps_time) - 1 else mid + search_left_right_samples
211  start = 0 if mid - search_left_right_samples < 0 else mid - search_left_right_samples
212 
213  index = numpy.argmax(numpy.abs(snr_series.data.data[start:end+1]))
214 
215  return (snr_series.data.data[start:end+1][index], gps_time[start:end+1][index])
216 
217 def _find_nearest(snr_series, time):
218  """Find the nearest gps time available from the time series
219 
220  Args:
221  snr_series (lal.series): A SNR LAL series.
222  time (float): Requested gpstime.
223 
224  Return:
225  (SNR, index): A tuple of SNR and index nearest to time.
226  """
227  gps_start = snr_series.epoch.gpsSeconds + snr_series.epoch.gpsNanoSeconds * 10.**-9
228  gps = gps_start + numpy.arange(snr_series.data.length) * snr_series.deltaT
229  if time - gps[0] >= 0 and time - gps[-1] <= 0:
230  index = abs(gps - time).argmin()
231  else:
232  raise ValueError("Invalid choice of center time %f." % time)
233  return (snr_series.data.data[index], index)
def plot_snr_with_ac
Definition: snr.py:51
def plot_snr
Definition: snr.py:25