Skip to content

Commit

Permalink
Modernize Python 2
Browse files Browse the repository at this point in the history
* print_function
* absolute_import
* .next method to next() function
* exception catching "as e"
  • Loading branch information
timj committed Aug 7, 2016
1 parent c2ee24a commit 83fd184
Show file tree
Hide file tree
Showing 70 changed files with 425 additions and 353 deletions.
7 changes: 4 additions & 3 deletions bin.src/showCamera.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
# the GNU General Public License along with this program. If not,
# see <http://www.lsstcorp.org/LegalNotices/>.
#
from __future__ import print_function
import sys
import matplotlib.pyplot as plt

Expand Down Expand Up @@ -48,7 +49,7 @@
try:
__import__(obsPackageName)
except:
print >> sys.stderr, "Unable to import %s -- is it setup?" % (obsPackageName,)
print("Unable to import %s -- is it setup?" % (obsPackageName,), file=sys.stderr)
sys.exit(1)

obsPackage = sys.modules[obsPackageName] # __import__ returns the top-level module, so look ours up
Expand All @@ -57,7 +58,7 @@
try:
mapper = getattr(obsPackage, mapperName)
except AttributeError:
print >> sys.stderr, "Unable to find mapper %s in %s" % (mapperName, obsPackageName)
print("Unable to find mapper %s in %s" % (mapperName, obsPackageName), file=sys.stderr)
sys.exit(1)
#
# Control verbosity from butler
Expand All @@ -76,6 +77,6 @@
showFig=not args.outputFile, savePath=args.outputFile)

if not args.outputFile:
print "Hit any key to exit",; raw_input()
print("Hit any key to exit", end=' '); raw_input()

sys.exit(0)
6 changes: 4 additions & 2 deletions examples/catTables.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
#!/usr/bin/env python

from __future__ import print_function
import sys
import lsst.afw.table as afwTable
from functools import reduce


def concatenate(catalogList):
Expand All @@ -26,8 +28,8 @@ def concatenate(catalogList):

if __name__ == "__main__":
if len(sys.argv) < 4:
print "catTables.py: Concatenate multiple FITS tables (catalogs) from lsst.afw.table"
print "Usage: catTables.py OUT IN1 IN2 [IN3...]"
print("catTables.py: Concatenate multiple FITS tables (catalogs) from lsst.afw.table")
print("Usage: catTables.py OUT IN1 IN2 [IN3...]")
sys.exit(1)

outName = sys.argv[1]
Expand Down
5 changes: 3 additions & 2 deletions examples/coordOffset.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
#

#
from __future__ import print_function
import lsst.afw.coord as afwCoord

def main():
Expand All @@ -45,14 +46,14 @@ def main():
arc = i*dArc*afwCoord.degToRad
c = afwCoord.Fk5Coord(long0, lat0)
c.offset(phi*afwCoord.degToRad, arc)
print c.getLongitude(afwCoord.DEGREES), c.getLatitude(afwCoord.DEGREES),
print(c.getLongitude(afwCoord.DEGREES), c.getLatitude(afwCoord.DEGREES), end=' ')

# try the rotate() method
c = afwCoord.Fk5Coord(long0, lat0)
ax = afwCoord.Fk5Coord(axLon, axLat)

c.rotate(ax, arc)
print c.getLongitude(afwCoord.DEGREES), c.getLatitude(afwCoord.DEGREES)
print(c.getLongitude(afwCoord.DEGREES), c.getLatitude(afwCoord.DEGREES))

if __name__ == '__main__':
main()
19 changes: 10 additions & 9 deletions examples/countMaskBits.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
Usage:
./countMaskBits.py path-to-masked-image
"""
from __future__ import print_function
import sys
import os

Expand Down Expand Up @@ -77,21 +78,21 @@ def countNotFinite(maskedImage):
maskBitNameDict = getMaskBitNameDict(mask)
maskArr = maskedImage.getMask().getArray()
bitIndList = sorted(maskBitNameDict.keys())
print "Bit Mask Plane Name # Pixels"
print("Bit Mask Plane Name # Pixels")
for bitInd in bitIndList:
planeName = maskBitNameDict[bitInd]
bitMask = 1 << bitInd
count = numpy.sum(maskArr & bitMask > 0)
print "%3d %-18s %d" % (bitInd, planeName, count)
print("%3d %-18s %d" % (bitInd, planeName, count))

print
print "Interpolation: \"bad\" pixels have any of these bits set: %s" % (BadPixelList,)
print()
print("Interpolation: \"bad\" pixels have any of these bits set: %s" % (BadPixelList,))
numBad, numInterp, numBadAndInterp = countInterp(maskedImage)
print "%d bad; %d interp; %d bad & interp; %d bad and not interp; %d good but interp" % \
(numBad, numInterp, numBadAndInterp, numBad - numBadAndInterp, numInterp - numBadAndInterp)
print("%d bad; %d interp; %d bad & interp; %d bad and not interp; %d good but interp" % \
(numBad, numInterp, numBadAndInterp, numBad - numBadAndInterp, numInterp - numBadAndInterp))

print
print()
numImNotFinite, numVarNotFinite, numImNotEdgeOrFinite, numVarNotEdgeOrFinite = countNotFinite(maskedImage)
print "%d non-finite image pixels; of these %d are not EDGE" % (numImNotFinite, numImNotEdgeOrFinite)
print "%d non-finite variance pixels; of these %d are not EDGE" % (numVarNotFinite, numVarNotEdgeOrFinite)
print("%d non-finite image pixels; of these %d are not EDGE" % (numImNotFinite, numImNotEdgeOrFinite))
print("%d non-finite variance pixels; of these %d are not EDGE" % (numVarNotFinite, numVarNotEdgeOrFinite))

3 changes: 2 additions & 1 deletion examples/footprintSet.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"""
Examples of using Footprints
"""
from __future__ import print_function

import sys
import lsst.afw.image as afwImage
Expand Down Expand Up @@ -75,7 +76,7 @@ def run(frame=6):
polarity = False # look for objects below background
threshold = afwDetect.Threshold(level, afwDetect.Threshold.VALUE, polarity)
fs2 = afwDetect.FootprintSet(im, threshold, "DETECTED_NEGATIVE")
print "Detected %d objects below background" % len(fs2.getFootprints())
print("Detected %d objects below background" % len(fs2.getFootprints()))
#
# Search in S/N (n.b. the peak's -10sigma)
#
Expand Down
3 changes: 2 additions & 1 deletion examples/imageAddSegFault.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,12 @@

"""Demonstrate a segmentation fault
"""
from __future__ import print_function
import lsst.afw.image as afwImage
import lsst.afw.geom as afwGeom

testMaskedImage = afwImage.MaskedImageD(afwGeom.Extent2I(100, 100))
testImage = testMaskedImage.getImage().get() # no segfault if .get() omitted
addImage = afwImage.ImageD(testMaskedImage.getCols(), testMaskedImage.getRows())
testImage += addImage # no segfault if this step omitted
print "Done"
print("Done")
5 changes: 3 additions & 2 deletions examples/showCamera.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
# see <http://www.lsstcorp.org/LegalNotices/>.
#

from __future__ import print_function
import math
import numpy
import matplotlib.pyplot as plt
Expand Down Expand Up @@ -117,10 +118,10 @@ def main(camera, sample=20, showDistortion=True):
elif args.camera.lower() == "lsstsim":
from lsst.obs.lsstSim import LsstSimMapper as Mapper
else:
print >> sys.stderr, "Unknown camera %s" % args.camera
print("Unknown camera %s" % args.camera, file=sys.stderr)
sys.exit(1)

camera = Mapper().camera

main(camera, showDistortion=args.showDistortion, sample=2)
print "Hit any key to exit",; raw_input()
print("Hit any key to exit", end=' '); raw_input()
3 changes: 2 additions & 1 deletion examples/simpleStacker.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
# Steve Bickerton
# An example executible which calls the example 'stack' code
#
from __future__ import print_function
import lsst.afw.math as afwMath
import lsst.afw.image as afwImage
import lsst.afw.geom as afwGeom
Expand All @@ -46,7 +47,7 @@ def main():

imgStack = afwMath.statisticsStack(imgList, afwMath.MEAN)

print imgStack.get(nX/2, nY/2)
print(imgStack.get(nX/2, nY/2))


#######################################
Expand Down
13 changes: 7 additions & 6 deletions examples/spatialCellExample.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
python
>>> import SpatialCellExample; SpatialCellExample.run()
"""
from __future__ import print_function

import os
import sys
Expand Down Expand Up @@ -81,8 +82,8 @@ def readImage(filename=None):
im = mi.getImage()
try:
backobj = afwMath.makeBackground(im, bctrl)
except Exception, e:
print >> sys.stderr, e,
except Exception as e:
print(e, end=' ', file=sys.stderr)

bctrl.setInterpStyle(afwMath.Interpolate.CONSTANT)
backobj = afwMath.makeBackground(im, bctrl)
Expand Down Expand Up @@ -142,7 +143,7 @@ def SpatialCellSetDemo(filename=None):
visitor = testSpatialCellLib.ExampleCandidateVisitor()

cellSet.visitCandidates(visitor)
print "There are %d candidates" % (visitor.getN())
print("There are %d candidates" % (visitor.getN()))

ctypes = ["red", "yellow", "cyan", ]
for i in range(cellSet.getCellList().size()):
Expand Down Expand Up @@ -181,13 +182,13 @@ def SpatialCellSetDemo(filename=None):
cell.visitCandidates(visitor)

cell.setIgnoreBad(False) # include BAD in cell.size()
print "%s nobj=%d N_good=%d NPix_good=%d" % \
(cell.getLabel(), cell.size(), visitor.getN(), visitor.getNPix())
print("%s nobj=%d N_good=%d NPix_good=%d" % \
(cell.getLabel(), cell.size(), visitor.getN(), visitor.getNPix()))


cellSet.setIgnoreBad(True) # don't visit BAD candidates
cellSet.visitCandidates(visitor)
print "There are %d good candidates" % (visitor.getN())
print("There are %d good candidates" % (visitor.getN()))

#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

Expand Down
21 changes: 11 additions & 10 deletions examples/statisticsConstructor.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
#

#
from __future__ import print_function
import lsst.afw.math as afwMath
import lsst.afw.image as afwImage
import lsst.afw.geom as afwGeom
Expand All @@ -38,25 +39,25 @@ def main():

# call with the factory function ... should get stats on the image plane
fmt = "%-40s %-16s %3.1f\n"
print fmt % ("Using makeStatistics:", "(should be " + str(mimValue[0]) + ")",
afwMath.makeStatistics(mimg, afwMath.MEAN).getValue()),
print(fmt % ("Using makeStatistics:", "(should be " + str(mimValue[0]) + ")",
afwMath.makeStatistics(mimg, afwMath.MEAN).getValue()), end=' ')

# call the constructor directly ... once for image plane, then for variance
# - make sure we're not using weighted stats for this
sctrl = afwMath.StatisticsControl()
sctrl.setWeighted(False)
print fmt % ("Using Statistics on getImage():", "(should be " + str(mimValue[0]) + ")",
print(fmt % ("Using Statistics on getImage():", "(should be " + str(mimValue[0]) + ")",
afwMath.StatisticsF(mimg.getImage(), mimg.getMask(), mimg.getVariance(),
afwMath.MEAN, sctrl).getValue()),
print fmt % ("Using Statistics on getVariance():", "(should be " + str(mimValue[2]) + ")",
afwMath.MEAN, sctrl).getValue()), end=' ')
print(fmt % ("Using Statistics on getVariance():", "(should be " + str(mimValue[2]) + ")",
afwMath.StatisticsF(mimg.getVariance(), mimg.getMask(), mimg.getVariance(),
afwMath.MEAN, sctrl).getValue()),
afwMath.MEAN, sctrl).getValue()), end=' ')

# call makeStatistics as a front-end for the constructor
print fmt % ("Using makeStatistics on getImage():", "(should be " + str(mimValue[0]) + ")",
afwMath.makeStatistics(mimg.getImage(), mimg.getMask(), afwMath.MEAN).getValue()),
print fmt % ("Using makeStatistics on getVariance():", "(should be " + str(mimValue[2]) + ")",
afwMath.makeStatistics(mimg.getVariance(), mimg.getMask(), afwMath.MEAN).getValue()),
print(fmt % ("Using makeStatistics on getImage():", "(should be " + str(mimValue[0]) + ")",
afwMath.makeStatistics(mimg.getImage(), mimg.getMask(), afwMath.MEAN).getValue()), end=' ')
print(fmt % ("Using makeStatistics on getVariance():", "(should be " + str(mimValue[2]) + ")",
afwMath.makeStatistics(mimg.getVariance(), mimg.getMask(), afwMath.MEAN).getValue()), end=' ')


if __name__ == '__main__':
Expand Down
3 changes: 2 additions & 1 deletion examples/statisticsMaskedImage.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
#

#
from __future__ import print_function
import lsst.afw.math as afwMath
import lsst.afw.image as afwImage
import lsst.afw.geom as afwGeom
Expand Down Expand Up @@ -71,7 +72,7 @@ def showSetAndMask():
sctrl.setAndMask(masks[i])
stat = afwMath.makeStatistics(mimg, afwMath.MEAN, sctrl)
answer = stat.getValue(afwMath.MEAN)
print explanations[i], " (got %.1f)" % (answer)
print(explanations[i], " (got %.1f)" % (answer))



Expand Down
9 changes: 5 additions & 4 deletions examples/statisticsNaN.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
#

#
from __future__ import print_function
import lsst.afw.math as afwMath
import lsst.afw.image as afwImage
import lsst.afw.geom as afwGeom
Expand All @@ -47,16 +48,16 @@ def main():
afwMath.convolve(outImage, inImage, gaussKernel, False, True)
if disp:
ds9.mtv(outImage, frame = 1)
print "Should be a number: ", afwMath.makeStatistics(outImage, afwMath.MEAN).getValue()
print "Should be a number: ", afwMath.makeStatistics(outImage, afwMath.STDEV).getValue()
print("Should be a number: ", afwMath.makeStatistics(outImage, afwMath.MEAN).getValue())
print("Should be a number: ", afwMath.makeStatistics(outImage, afwMath.STDEV).getValue())

# not works ... now does work
outImage = afwImage.ImageF(afwGeom.Extent2I(100, 100))
afwMath.convolve(outImage, inImage, gaussKernel, False, False)
if disp:
ds9.mtv(outImage, frame = 2)
print "Should be a number: ", afwMath.makeStatistics(outImage, afwMath.MEAN).getValue()
print "Should be a number: ", afwMath.makeStatistics(outImage, afwMath.STDEV).getValue()
print("Should be a number: ", afwMath.makeStatistics(outImage, afwMath.MEAN).getValue())
print("Should be a number: ", afwMath.makeStatistics(outImage, afwMath.STDEV).getValue())

# This will print nan
sctrl = afwMath.StatisticsControl()
Expand Down
13 changes: 7 additions & 6 deletions examples/timeSpatiallyVaryingConvolve.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
# see <http://www.lsstcorp.org/LegalNotices/>.
#

from __future__ import print_function
import math
import sys
import os
Expand Down Expand Up @@ -178,27 +179,27 @@ def timeSet(outImage, inImage, kernelFunction, kernelDescr, convControl, spOrder
)
for methodDescr, maxInterpolationDistance in methodDescrInterpDistList:
convControl.setMaxInterpolationDistance(maxInterpolationDistance)
print "%s using %s" % (kernelDescr, methodDescr)
print "ImWid\tImHt\tKerWid\tKerHt\tSec/Cnv"
print("%s using %s" % (kernelDescr, methodDescr))
print("ImWid\tImHt\tKerWid\tKerHt\tSec/Cnv")
for kSize in (5, 11, 19):
kernel = kernelFunction(kSize, imSize, spOrder)
dur, nIter = timeConvolution(outImage, inImage, kernel, convControl)
print "%d\t%d\t%d\t%d\t%0.2f" % (imSize[0], imSize[1], kSize, kSize, dur/float(nIter))
print
print("%d\t%d\t%d\t%d\t%0.2f" % (imSize[0], imSize[1], kSize, kSize, dur/float(nIter)))
print()

def run():
convControl = afwMath.ConvolutionControl()
convControl.setDoNormalize(True)
spOrder = 3
print "All kernels use a spatial model of a Polynomial2 of order %s" % (spOrder,)
print("All kernels use a spatial model of a Polynomial2 of order %s" % (spOrder,))

for imageClass in (
afwImage.ImageF,
afwImage.ImageD,
afwImage.MaskedImageF,
afwImage.MaskedImageD,
):
print "\n*** Test convolution with %s ***\n" % (imageClass.__name__,)
print("\n*** Test convolution with %s ***\n" % (imageClass.__name__,))
if len(sys.argv) < 2:
inImage = imageClass(InputMaskedImagePath)
# to get original behavior change True to False:
Expand Down

0 comments on commit 83fd184

Please sign in to comment.