Skip to content

plots

figure

figure(**kwargs)

A matplotlib figure context.

Source code in gvt/plots.py
482
483
484
485
486
487
488
489
@contextmanager
def figure(**kwargs) -> Generator[Figure, None, None]:
    """A matplotlib figure context."""
    fig = Figure(**kwargs)
    try:
        yield fig
    finally:
        plt.close(fig)

injected_vs_detected_frequency

injected_vs_detected_frequency(path, events)

Generate a frequency recovery plot for a set of events.

Parameters:

Name Type Description Default
path Path

The directory to write this plot to.

required
events EventTable

The events to plot.

required
Source code in gvt/plots.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
def injected_vs_detected_frequency(path: Path, events: EventTable):
    """Generate a frequency recovery plot for a set of events.

    Parameters
    ----------
    path : Path
        The directory to write this plot to.
    events : EventTable
        The events to plot.

    """
    min_f = 10
    max_f = 1.1 * max(events["frequency_target"])
    with figure(dpi=300, figsize=[10, 10]) as fig:
        ax = fig.add_subplot()

        # plot middle dotted line
        line = [1, 2, 100000]
        ax.plot(line, line, "--", color="blue")

        # injected vs. detected events
        ax.scatter(
            events["frequency_ref"],
            events["frequency_target"],
            marker="o",
            color="#5e3c99",
            alpha=0.4,
        )

        # plot confidence bounds
        error = 0.2
        x_bound = numpy.arange(min_f, max_f)
        ax.plot(x_bound, x_bound - x_bound * error, "--", color="gray")
        ax.plot(x_bound, x_bound + x_bound * error, "--", color="gray")

        # plot settings
        ax.set_xlim(min_f, max_f)
        ax.set_ylim(min_f, max_f)
        ax.set_xscale("log")
        ax.set_yscale("log")
        ax.grid(True)
        ax.set_xlabel("Injected Frequency")
        ax.set_ylabel("Detected Frequency")
        ax.set_title("Injected vs. Detected Frequency")

        # write to disk
        filename = "injected_vs_detected_frequency.png"
        fig.savefig(path / filename)

injected_vs_detected_snr

injected_vs_detected_snr(path, events, threshold=constants.SNR_THRESHOLD)

Generate an SNR recovery plot for a set of events.

Parameters:

Name Type Description Default
path Path

The directory to write this plot to.

required
events EventTable

The events to plot.

required
threshold float

The SNR threshold. Default is 5.5.

constants.SNR_THRESHOLD
Source code in gvt/plots.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
def injected_vs_detected_snr(
    path: Path, events: EventTable, threshold: float = constants.SNR_THRESHOLD
):
    """Generate an SNR recovery plot for a set of events.

    Parameters
    ----------
    path : Path
        The directory to write this plot to.
    events : EventTable
        The events to plot.
    threshold : float
        The SNR threshold. Default is 5.5.

    """
    min_snr = math.floor(0.9 * threshold)
    max_snr = 1.1 * max(events["snr_target"])
    with figure(dpi=300, figsize=[10, 10]) as fig:
        ax = fig.add_subplot()

        # plot middle dotted line
        line = [1, 2, 100000]
        ax.plot(line, line, "--", color="blue")

        # injected vs. detected events
        ax.scatter(
            events["snr_ref"],
            events["snr_target"],
            marker="o",
            color="#5e3c99",
            alpha=0.4,
        )

        # plot confidence bounds
        x_bound = numpy.arange(min_snr, max_snr)
        ax.plot(x_bound, x_bound * numpy.sqrt(2), "--", color="gray")
        ax.plot(x_bound, x_bound / numpy.sqrt(2), "--", color="gray")

        # SNR cutoff
        ax.plot([min_snr, max_snr], [threshold, threshold], "-", color="red")

        # plot settings
        ax.set_xlim(min_snr, max_snr)
        ax.set_ylim(min_snr, max_snr)
        ax.set_xscale("log")
        ax.set_yscale("log")
        ax.grid(True)
        ax.set_xlabel("Injected SNR")
        ax.set_ylabel("Detected SNR")
        ax.set_title("Injected vs. Detected SNR")

        # write to disk
        filename = "injected_vs_detected_snr.png"
        fig.savefig(path / filename)

injection_frequency_mismatch

injection_frequency_mismatch(path, events)

Generate a frequency mismatch plot for a set of events.

Parameters:

Name Type Description Default
path Path

The directory to write this plot to.

required
events EventTable

The events to plot.

required
Source code in gvt/plots.py
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
def injection_frequency_mismatch(path: Path, events: EventTable):
    """Generate a frequency mismatch plot for a set of events.

    Parameters
    ----------
    path : Path
        The directory to write this plot to.
    events : EventTable
        The events to plot.

    """
    min_f = 10
    max_f = 1.1 * max(events["frequency_target"])
    ref_f = events["frequency_ref"]
    difference = 100 * (events["frequency_target"] - ref_f) / ref_f

    with figure(dpi=300, figsize=[10, 10 / golden_ratio]) as fig:
        ax = fig.add_subplot()

        # plot mismatch
        ax.scatter(ref_f, difference, marker="x", color="#5e3c99")

        # plot bounds
        ax.plot([min_f, max_f], [-20, -20], "--", color="gray")
        ax.plot([min_f, max_f], [20, 20], "--", color="gray")

        # plot settings
        ylim = 1.1 * numpy.max(numpy.abs(difference))
        ax.set_ylim(-ylim, ylim)
        ax.set_xscale("log")
        ax.grid(True)
        ax.set_xlabel("Injection Frequency")
        ax.set_ylabel("Frequency Mismatch (% error)")
        ax.set_title("Injection Frequency Mismatch")

        # write to disk
        filename = "injection_frequency_mismatch.png"
        fig.savefig(path / filename)

injection_snr_mismatch

injection_snr_mismatch(path, events, threshold=constants.SNR_THRESHOLD)

Generate an SNR mismatch plot for a set of events.

Parameters:

Name Type Description Default
path Path

The directory to write this plot to.

required
events EventTable

The events to plot.

required
threshold float

The SNR threshold. Default is 5.5.

constants.SNR_THRESHOLD
Source code in gvt/plots.py
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
def injection_snr_mismatch(
    path: Path, events: EventTable, threshold: float = constants.SNR_THRESHOLD
):
    """Generate an SNR mismatch plot for a set of events.

    Parameters
    ----------
    path : Path
        The directory to write this plot to.
    events : EventTable
        The events to plot.
    threshold : float
        The SNR threshold. Default is 5.5.

    """
    min_snr = math.floor(0.9 * threshold)
    max_snr = 1.1 * max(events["snr_target"])
    difference = 100 * (events["snr_target"] - events["snr_ref"]) / events["snr_ref"]
    ylim = 1.1 * numpy.max(numpy.abs(difference))

    with figure(dpi=300, figsize=[10, 10 / golden_ratio]) as fig:
        ax = fig.add_subplot()

        # plot mismatch
        ax.scatter(events["snr_ref"], difference, marker="x", color="#5e3c99")

        # plot bounds
        ax.plot([min_snr, max_snr], [-20, -20], "--", color="gray")
        ax.plot([min_snr, max_snr], [20, 20], "--", color="gray")

        # SNR cutoff
        ax.plot([threshold, threshold], [-ylim, ylim], "-", color="red")

        # plot settings
        ax.set_ylim(-ylim, ylim)
        ax.set_xscale("log")
        ax.grid(True)
        ax.set_xlabel("Injection SNR")
        ax.set_ylabel("SNR Mismatch (% error)")
        ax.set_title("Injection SNR Mismatch")

        # write to disk
        filename = "injection_snr_mismatch.png"
        fig.savefig(path / filename)

missed_found_by_label

missed_found_by_label(path, summary)

Generate a categorical missed/found plot.

Parameters:

Name Type Description Default
path Path

The directory to write this plot to.

required
summary EventTable

The event summary on a per-label basis.

required
Source code in gvt/plots.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def missed_found_by_label(path: Path, summary: EventTable):
    """Generate a categorical missed/found plot.

    Parameters
    ----------
    path : Path
        The directory to write this plot to.
    summary : EventTable
        The event summary on a per-label basis.

    """
    labels = [label.replace("_", " ") for label in summary["label"]]
    with figure(dpi=300, figsize=[10, 10 / golden_ratio]) as fig:
        ax = fig.add_subplot()

        # plot missed / found bars
        ax.bar(
            labels,
            summary["total"],
            edgecolor="k",
            color="#D55E00",
            label="missed",
        )
        ax.bar(
            labels,
            summary["found"],
            edgecolor="k",
            color="#0072B2",
            label="found",
        )

        # plot settings
        plt.setp(ax.get_xticklabels(), rotation=45, ha="right")
        ax.set_yscale("log")
        ax.set_ylabel("Count")
        ax.set_title("Missed / Found by Glitch Type")
        ax.legend(loc="upper right")
        fig.tight_layout()

        # write to disk
        filename = "missed_found_by_label.png"
        fig.savefig(path / filename)

missed_found_injections

missed_found_injections(path, found, missed)

Generate a missed/found plot for a set of events.

Parameters:

Name Type Description Default
path Path

The directory to write this plot to.

required
found EventTable

The events that were found.

required
missed EventTable

The events that were missed.

required
Source code in gvt/plots.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
def missed_found_injections(path: Path, found: EventTable, missed: EventTable):
    """Generate a missed/found plot for a set of events.

    Parameters
    ----------
    path : Path
        The directory to write this plot to.
    found : EventTable
        The events that were found.
    missed : EventTable
        The events that were missed.

    """
    with figure(dpi=300, figsize=[10, 10]) as fig:
        ax = fig.add_subplot()

        # plot missed and found events
        ax.scatter(
            found["snr_ref"], found["frequency_ref"], marker="o", color="#5e3c99"
        )
        ax.scatter(missed["snr"], missed["frequency"], marker="x", color="red", s=70)

        # plot settings
        ax.set_xscale("log")
        ax.set_yscale("log")
        ax.axis([5, 100, 10, 4000])
        ax.grid(True)
        ax.set_xlabel("Injected SNR")
        ax.set_ylabel("Injected frequency [Hz]")
        ax.set_title("Missed / Found Events")
        ax.legend(
            (f"Found: N={len(found)}", f"Missed: N={len(missed)}"),
            loc="lower right",
        )

        # write to disk
        filename = "missed_found_events.png"
        fig.savefig(path / filename)

qscan_timeseries

qscan_timeseries(path, t0, duration, series, target)

Plot an omega scan and timeseries plot for an event.

Parameters:

Name Type Description Default
path Path

The directory to write this plot to.

required
t0 float

The center time to plot.

required
duration float

The duration in seconds to plot around the event.

required
series TimeSeries

The timeseries to plot around the event.

required
target EventTable

The set of events, sorted by time.

required
Source code in gvt/plots.py
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def qscan_timeseries(
    path: Path, t0: float, duration: float, series: TimeSeries, target: EventTable
):
    """Plot an omega scan and timeseries plot for an event.

    Parameters
    ----------
    path : Path
        The directory to write this plot to.
    t0 : float
        The center time to plot.
    duration : float
        The duration in seconds to plot around the event.
    series : TimeSeries
        The timeseries to plot around the event.
    target : EventTable
        The set of events, sorted by time.

    """
    dt = duration / 2
    qscan = series.q_transform(
        qrange=(4, 64),
        frange=(10, 2048),
        gps=t0,
        outseg=(t0 - dt, t0 + dt),
        tres=0.000208,  # type: ignore
        logf=True,
    )
    qscan.shift(-qscan.t0 - dt * qscan.t0.unit)

    events = target.filter(f"{t0 - dt} <= time <= {t0 + dt}")

    with figure(dpi=300, figsize=[10 / golden_ratio, 10]) as fig:
        # generate omega scan plot
        ax = fig.add_subplot(2, 1, 1)
        ax.pcolormesh(qscan, vmin=0, vmax=25)
        ax.set_yscale("log")
        ax.set_xlim(-duration, duration)
        ax.set_ylabel("Frequency [Hz]")
        ax.colorbar(label="Normalized energy", clim=(0, 25), location="top")

        # generate timeseries plot below omega scan
        ax = fig.add_subplot(2, 1, 2, sharex=ax)
        ax.plot(
            events["time"] - t0,
            events["snr"],
            color="#0072B2",
            alpha=0.7,
            lw=1.5,
        )
        ax.set_xlim(-dt, dt)
        ax.set_ylim(min(1, 0.9 * min(events["snr"])), 1.1 * max(events["snr"]))
        ax.set_yscale("symlog")
        ax.set_ylabel("SNR")
        ax.set_xlabel(f"Time [seconds] from {t0}")

        # set ticks for y-axis to avoid missing ticks
        locmin = SymmetricalLogLocator(
            linthresh=1, base=10, subs=(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
        )
        ax.yaxis.set_minor_locator(locmin)
        ax.yaxis.set_minor_formatter(NullFormatter())

        fig.suptitle("Omega Scan and Event Timeseries")
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", UserWarning)
            fig.tight_layout(rect=[0, 0, 1, 0.92])

        # write to disk
        filename = f"series_qscan_{t0}.png"
        fig.savefig(path / filename)

roc_curve

roc_curve(path, found, summary)

Generate a ROC curve for a set of events.

Parameters:

Name Type Description Default
path Path

The directory to write this plot to.

required
found EventTable

The events that were found.

required
summary EventTable

The event summary on a per-label basis.

required
Source code in gvt/plots.py
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
def roc_curve(path: Path, found: EventTable, summary: EventTable):
    """Generate a ROC curve for a set of events.

    Parameters
    ----------
    path : Path
        The directory to write this plot to.
    found : EventTable
        The events that were found.
    summary : EventTable
        The event summary on a per-label basis.

    """
    # separate into glitch/clean classes
    clean = found["ml_label"] == "No_Glitch"
    not_clean = found["ml_label"] != "No_Glitch"
    not_none = found["ml_label"] == "None_of_the_Above"

    cleans = found[clean]
    glitches = found[not_clean | not_none]

    clean = summary["label"] == "No_Glitch"
    not_clean = summary["label"] != "No_Glitch"
    not_none = summary["label"] == "None_of_the_Above"

    total_clean = numpy.sum(summary[clean]["total"])
    total_glitch = numpy.sum(summary[not_clean | not_none]["total"])

    # calculate efficiency / false positive rate
    significances = unique(found, keys="snr_target")["snr_target"]
    tprs = []
    fprs = []

    for significance in significances:
        num_glitch = len(glitches[glitches["snr_target"] >= significance])
        num_clean = len(cleans[cleans["snr_target"] >= significance])
        tprs.append(num_glitch / total_glitch)
        fprs.append(num_clean / total_clean)

    # plot ROC curve
    with figure(dpi=300, figsize=[10, 10]) as fig:
        ax = fig.gca()
        ax.grid(which="both", linewidth=0.2)

        # plot 'random coin flip' line
        xmin = min(1e-3, 0.1 / (total_glitch + total_clean))
        line = numpy.logspace(numpy.log10(xmin), 0, 1001)
        ax.plot(line, line, color="k", linestyle="dashed", alpha=0.5)

        # plot ROC curve
        ax.plot(fprs, tprs, drawstyle="steps", color="#0072B2")

        # plot settings
        ax.set_xscale("log")
        ax.set_xlim(xmin=xmin, xmax=1.01)
        ax.set_ylim(ymin=-0.01, ymax=1.01)
        ax.set_xlabel("False Positive Rate")
        ax.set_ylabel("Efficiency")
        ax.set_title("ROC Curve")
        fig.tight_layout()

        # write to disk
        filename = "roc_curve.png"
        fig.savefig(path / filename)

time_difference_histogram

time_difference_histogram(path, events, dt)

Generate a time difference histogram for a set of events.

Parameters:

Name Type Description Default
path Path

The directory to write this plot to.

required
events EventTable

The events to plot.

required
dt float

The maximum time difference to plot.

required
Source code in gvt/plots.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
def time_difference_histogram(path: Path, events: EventTable, dt: float):
    """Generate a time difference histogram for a set of events.

    Parameters
    ----------
    path : Path
        The directory to write this plot to.
    events : EventTable
        The events to plot.
    dt : float
        The maximum time difference to plot.

    """
    n_bins = 100
    with figure(dpi=300, figsize=[10, 10 / golden_ratio]) as fig:
        ax = fig.add_subplot()

        # plot histogram
        ax.hist(
            events["time_target"] - events["time_ref"],
            bins=n_bins,
            alpha=0.7,
            color="#5e3c99",
            log=True,
            range=(-dt, dt),
        )

        # plot settings
        ax.set_title("Time Difference Histogram")
        ax.set_xlabel("Event time - Injection time [s]")
        ax.set_ylabel("Number of Events")
        ax.set_xlim(-dt, dt)
        ax.set_ylim(0.1, 10000)

        # write to disk
        filename = "time_difference_histogram.png"
        fig.savefig(path / filename)