Skip to content

Commit

Permalink
Only import matplotlib when needed
Browse files Browse the repository at this point in the history
Some tests and one bit of library code were importing matplotlib
even if plotting was not requested. This could cause needless failures
(not to mention unwanted rebuilds of the font cache).
I standardized on only importing when plotting is specifically requested,
and the library code prints an error message and continues
(whereas the unit tests fail, a safe thing to do because they
do not normally plot anyway).
  • Loading branch information
r-owen committed Dec 14, 2016
1 parent b143333 commit 781f0c4
Show file tree
Hide file tree
Showing 6 changed files with 43 additions and 45 deletions.
13 changes: 6 additions & 7 deletions python/lsst/meas/astrom/anetBasicAstrometry.py
Expand Up @@ -726,9 +726,8 @@ def plotSolution(self, matches, wcs, imageSize):

try:
import matplotlib.pyplot as plt
import numpy
except ImportError:
print("Unable to import matplotlib", file=sys.stderr)
except ImportError as e:
self.log.warning("Unable to import matplotlib: %s", e)
return

fig = plt.figure(1)
Expand All @@ -739,10 +738,10 @@ def plotSolution(self, matches, wcs, imageSize):
pass

num = len(matches)
x = numpy.zeros(num)
y = numpy.zeros(num)
dx = numpy.zeros(num)
dy = numpy.zeros(num)
x = np.zeros(num)
y = np.zeros(num)
dx = np.zeros(num)
dy = np.zeros(num)
for i, m in enumerate(matches):
x[i] = m.second.getX()
y[i] = m.second.getY()
Expand Down
6 changes: 5 additions & 1 deletion python/lsst/meas/astrom/fitTanSipWcs.py
Expand Up @@ -239,7 +239,11 @@ def plotFit(self, matches, wcs, rejected):
We create four plots, for all combinations of (dx, dy) against
(x, y). Good points are black, while rejected points are red.
"""
import matplotlib.pyplot as plt
try:
import matplotlib.pyplot as plt
except ImportError as e:
self.log.warn("Unable to import matplotlib: %s", e)
return

fit = [wcs.skyToPixel(m.first.getCoord()) for m in matches]
x1 = np.array([ff.getX() for ff in fit])
Expand Down
16 changes: 8 additions & 8 deletions python/lsst/meas/astrom/sip/cleanBadPoints.py
Expand Up @@ -89,14 +89,14 @@ def indicesOfGoodPoints(x, y, s, order=1, nsigma=3, maxiter=100):
newidx = np.flatnonzero(deviance < nsigma)

if False:
import matplotlib.pyplot as mpl
mpl.plot(x, y, 'ks')
mpl.plot(rx, ry, 'b-')
mpl.plot(rx, ry, 'bs')
mpl.plot(rx, fit, 'ms')
mpl.plot(rx, fit, 'm-')
#mpl.plot(x[newidx], y[newidx], 'rs')
mpl.show()
import matplotlib.pyplot as plt
plt.plot(x, y, 'ks')
plt.plot(rx, ry, 'b-')
plt.plot(rx, ry, 'bs')
plt.plot(rx, fit, 'ms')
plt.plot(rx, fit, 'm-')
#plt.plot(x[newidx], y[newidx], 'rs')
plt.show()

# If we haven't culled any points we're finished cleaning
if len(newidx) == len(idx):
Expand Down
6 changes: 3 additions & 3 deletions tests/testFitTanSipWcsHighOrder.py
Expand Up @@ -2,7 +2,6 @@
import unittest

import numpy as np
import matplotlib.pylab as pylab

import lsst.utils.tests
import lsst.daf.base as dafBase
Expand Down Expand Up @@ -80,6 +79,7 @@ def doTest(self, name, xyTransform, order=3, doPlot=False):
maxDiffSky=0.001*afwGeom.arcseconds, maxDiffPix=0.02, msg=msg)

def plotWcs(self, wcs0, wcs1, bbox, xyTransform):
import matplotlib.pyplot as plt
bboxd = afwGeom.Box2D(bbox)
x0Arr = []
y0Arr = []
Expand All @@ -99,9 +99,9 @@ def plotWcs(self, wcs0, wcs1, bbox, xyTransform):
y1Arr.append(pixelPos1[1])
x2Arr.append(distortedPos[0])
y2Arr.append(distortedPos[1])
pylab.plot(x0Arr, y0Arr, 'b+', x1Arr, y1Arr, 'rx', x2Arr, y2Arr, 'g.')
plt.plot(x0Arr, y0Arr, 'b+', x1Arr, y1Arr, 'rx', x2Arr, y2Arr, 'g.')

pylab.show()
plt.show()


class MemoryTester(lsst.utils.tests.MemoryTestCase):
Expand Down
39 changes: 17 additions & 22 deletions tests/testFitTanSipWcsTask.py
Expand Up @@ -38,12 +38,6 @@
import unittest

import numpy as np
try:
import matplotlib
matplotlib.use("Agg")
import pylab
except ImportError:
pass

import lsst.pipe.base
import lsst.utils.tests
Expand Down Expand Up @@ -237,6 +231,7 @@ def doTest(self, name, func, order=3, numIter=4, specifyBBox=False, doPlot=False
self.checkResults(fitRes, catsUpdated=True)

def plotWcs(self, tanSipWcs, name=""):
import matplotlib.pyplot as plt
fileNamePrefix = "testCreateWcsWithSip_%s_%s" % (self.MatchClass.__name__, name)
pnum = 1

Expand All @@ -258,32 +253,32 @@ def plotWcs(self, tanSipWcs, name=""):
xc = np.array(xc)
yc = np.array(yc)

pylab.clf()
pylab.plot(xs, ys, "r.")
pylab.plot(xc, yc, "bx")
plt.clf()
plt.plot(xs, ys, "r.")
plt.plot(xc, yc, "bx")
fileName = "%s_%i.png" % (fileNamePrefix, pnum)
pylab.savefig(fileName)
plt.savefig(fileName)
print("Wrote", fileName)
pnum += 1

pylab.clf()
pylab.plot(xs, xc-xs, "b.")
plt.clf()
plt.plot(xs, xc-xs, "b.")
fileName = "%s_%i.png" % (fileNamePrefix, pnum)
pylab.xlabel("x(source)")
pylab.ylabel("x(ref - src)")
pylab.savefig(fileName)
plt.xlabel("x(source)")
plt.ylabel("x(ref - src)")
plt.savefig(fileName)
print("Wrote", fileName)
pnum += 1

pylab.clf()
pylab.plot(rs, ds, "r.")
pylab.plot(rc, dc, "bx")
plt.clf()
plt.plot(rs, ds, "r.")
plt.plot(rc, dc, "bx")
fileName = "%s_%i.png" % (fileNamePrefix, pnum)
pylab.savefig(fileName)
plt.savefig(fileName)
print("Wrote", fileName)
pnum += 1

pylab.clf()
plt.clf()
for y in np.linspace(0, 4000, 5):
x0, y0 = [], []
x1, y1 = [], []
Expand All @@ -296,9 +291,9 @@ def plotWcs(self, tanSipWcs, name=""):
y1.append(xy[1])
x0 = np.array(x0)
x1 = np.array(x1)
pylab.plot(x0, x1-x0, "b-")
plt.plot(x0, x1-x0, "b-")
fileName = "%s_%i.png" % (fileNamePrefix, pnum)
pylab.savefig(fileName)
plt.savefig(fileName)
print("Wrote", fileName)
pnum += 1

Expand Down
8 changes: 4 additions & 4 deletions tests/testLoadAstrometryNetObjects.py
Expand Up @@ -189,18 +189,18 @@ def assertObjInBBox(self, refCat, bbox, wcs):
def plotStars(self, refCat, bbox=None):
"""Plot the centroids of reference objects, and the bounding box (if specified)
"""
import matplotlib.pyplot as pyplot
import matplotlib.pyplot as plt
if bbox is not None:
cornerList = list(afwGeom.Box2D(bbox).getCorners())
cornerList.append(cornerList[0]) # show 4 sides of the box by going back to the beginning
xc, yc = list(zip(*cornerList))
pyplot.plot(xc, yc, '-')
plt.plot(xc, yc, '-')

centroidKey = refCat.schema["centroid"].asKey()
centroidList = [rec.get(centroidKey) for rec in refCat]
xp, yp = list(zip(*centroidList))
pyplot.plot(xp, yp, '.')
pyplot.show()
plt.plot(xp, yp, '.')
plt.show()


class MemoryTester(lsst.utils.tests.MemoryTestCase):
Expand Down

0 comments on commit 781f0c4

Please sign in to comment.