From 7799b43ce63576e63ce51d890f7c0f5810db9ead Mon Sep 17 00:00:00 2001
From: Jameson Graef Rollins <jrollins@finestructure.net>
Date: Tue, 28 Aug 2018 23:49:51 -0700
Subject: [PATCH] CLI support systems with no display

matplotlib.pyplot throws a RuntimeError when no display is present.  One
way around that is to set the backend to AGG.  But we don't want AGG when
we do have a display.  So we only want to set it opportunistically.  But
it also has to be set before anything else is imported.  Kind of convoluted.

So we really just import pyplot as opportunistically as possible, and then
rely on setting AGG backend when we're sure we don't need it in main().
---
 gwinc/__main__.py | 13 ++++++++++++-
 gwinc/plot.py     |  4 +---
 2 files changed, 13 insertions(+), 4 deletions(-)

diff --git a/gwinc/__main__.py b/gwinc/__main__.py
index 3b87cf88..5650137b 100644
--- a/gwinc/__main__.py
+++ b/gwinc/__main__.py
@@ -3,7 +3,6 @@ import os
 import signal
 import argparse
 import numpy as np
-from matplotlib import pyplot as plt
 from IPython.terminal.embed import InteractiveShellEmbed
 
 import logging
@@ -136,6 +135,18 @@ def main():
                 v = float(v)
             range_params[p] = v
 
+    if args.save:
+        # FIXME: this silliness seems to be the only way to have
+        # matplotlib usable on systems without a display.  There must
+        # be a better way.  'AGG' is a backend that works without
+        # displays.  but it has to be set before any other matplotlib
+        # stuff is imported.  and we *don't* want it set if we do want
+        # to show an interactive plot.  there doesn't seem a way to
+        # set this opportunistically.
+        import matplotlib
+        matplotlib.use('AGG')
+    from matplotlib import pyplot as plt
+
     ##########
     # main calculations
 
diff --git a/gwinc/plot.py b/gwinc/plot.py
index 3194705a..6381918f 100644
--- a/gwinc/plot.py
+++ b/gwinc/plot.py
@@ -1,7 +1,4 @@
 from numpy import sqrt
-import matplotlib.pyplot as plt
-
-import logging
 
 PRIORITY_MAP = {
     'Quantum Vacuum': 0,
@@ -80,6 +77,7 @@ def plot_noise(
     f = noises['Freq']
 
     if ax is None:
+        import matplotlib.pyplot as plt
         fig = plt.figure()
         ax = fig.add_subplot(1, 1, 1)
 
-- 
GitLab