Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add NullLinearityType to cameraGeom #71

Merged
merged 4 commits into from
Jun 7, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions python/lsst/afw/cameraGeom/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,4 @@
from .makePixelToTanPixel import *
from .assembleImage import *
from .rotateBBoxBy90 import *
NullLinearityType = "None" # linearity type indicating no linearity correction wanted
87 changes: 87 additions & 0 deletions python/lsst/afw/geom/testUtils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
from __future__ import absolute_import, division
#
# LSST Data Management System
# Copyright 2016 LSST Corporation.
#
# This product includes software developed by the
# LSST Project (http://www.lsst.org/).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the LSST License Statement and
# the GNU General Public License along with this program. If not,
# see <http://www.lsstcorp.org/LegalNotices/>.
#
import numpy as np

from .geomLib import Box2I, Box2D

__all__ = ["BoxGrid"]

class BoxGrid(object):
"""!Divide a box into nx by ny sub-boxes that tile the region
"""
def __init__(self, box, numColRow):
"""!Construct a BoxGrid

The sub-boxes will be of the same type as `box` and will exactly tile `box`;
they will also all be the same size, to the extent possible (some variation
is inevitable for integer boxes that cannot be evenly divided.

@param[in] box box (an lsst.afw.geom.Box2I or Box2D);
the boxes in the grid will be of the same type
@param[in] numColRow number of columns and rows (a pair of ints)
"""
if len(numColRow) != 2:
raise RuntimeError("numColRow=%r; must be a sequence of two integers" % (numColRow,))
self._numColRow = tuple(int(val) for val in numColRow)

if isinstance(box, Box2I):
stopDelta = 1
elif isinstance(box, Box2D):
stopDelta = 0
else:
raise RuntimeError("Unknown class %s of box %s" % (type(box), box))
self.boxClass = type(box)
self.stopDelta = stopDelta

minPoint = box.getMin()
self.pointClass = type(minPoint)
dtype = np.array(minPoint).dtype

self._divList = [np.linspace(start=box.getMin()[i],
stop=box.getMax()[i] + self.stopDelta,
num=self._numColRow[i] + 1,
endpoint=True,
dtype=dtype) for i in range(2)]

@property
def numColRow(self):
return self._numColRow
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this present? Just rename self._numColRow as self.numColRow.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To make it read only. This class looks a bit like a numpy array, which you can reshape on the fly. I wanted to avoid anyone attempting that.


def __getitem__(self, indXY):
"""!Return the box at the specified x,y index (a pair of ints)
"""
beg = self.pointClass(*[self._divList[i][indXY[i]] for i in range(2)])
end = self.pointClass(*[self._divList[i][indXY[i] + 1] - self.stopDelta for i in range(2)])
return self.boxClass(beg, end)

def __len__(self):
return self.shape[0]*self.shape[1]

def __iter__(self):
"""!Return an iterator over all boxes, where column varies most quickly
"""
for row in xrange(self.numColRow[1]):
for col in xrange(self.numColRow[0]):
yield self[col, row]


24 changes: 13 additions & 11 deletions python/lsst/afw/image/basicUtils.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
from __future__ import absolute_import, division
#
#
# LSST Data Management System
# Copyright 2008, 2009, 2010 LSST Corporation.
#
# Copyright 2008-2016 LSST Corporation.
#
# This product includes software developed by the
# LSST Project (http://www.lsst.org/).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the LSST License Statement and
# the GNU General Public License along with this program. If not,
#
# You should have received a copy of the LSST License Statement and
# the GNU General Public License along with this program. If not,
# see <http://www.lsstcorp.org/LegalNotices/>.
#

Expand All @@ -41,15 +41,17 @@ def makeImageFromArray(array):
"""Construct an Image from a NumPy array, inferring the Image type from the NumPy type.
Return None if input is None.
"""
if array is None: return None
if array is None:
return None
cls = getattr(imageLib, "Image%s" % (suffixes[str(array.dtype.type)],))
return cls(array)

def makeMaskFromArray(array):
"""Construct an Mask from a NumPy array, inferring the Mask type from the NumPy type.
Return None if input is None.
"""
if array is None: return None
if array is None:
return None
cls = getattr(imageLib, "Mask%s" % (suffixes[str(array.dtype.type)],))
return cls(array)

Expand Down Expand Up @@ -145,8 +147,8 @@ def wcsNearlyEqualOverBBox(wcs0, wcs1, bbox, maxDiffSky=0.01*afwGeom.arcseconds,
))

@lsst.utils.tests.inTestCase
def assertWcsNearlyEqualOverBBox(testCase, wcs0, wcs1, bbox, maxDiffSky=0.01*afwGeom.arcseconds, maxDiffPix=0.01,
nx=5, ny=5, msg="WCSs differ"):
def assertWcsNearlyEqualOverBBox(testCase, wcs0, wcs1, bbox, maxDiffSky=0.01*afwGeom.arcseconds,
maxDiffPix=0.01, nx=5, ny=5, msg="WCSs differ"):
"""!Compare pixelToSky and skyToPixel for two WCS over a rectangular grid of pixel positions

If the WCS are too divergent, call testCase.fail; the message describes the largest error measured
Expand Down
42 changes: 31 additions & 11 deletions python/lsst/afw/image/testUtils.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,32 @@
from __future__ import absolute_import, division
#
#
# LSST Data Management System
# Copyright 2008, 2009, 2010 LSST Corporation.
#
# Copyright 2008-2016 LSST Corporation.
#
# This product includes software developed by the
# LSST Project (http://www.lsst.org/).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the LSST License Statement and
# the GNU General Public License along with this program. If not,
#
# You should have received a copy of the LSST License Statement and
# the GNU General Public License along with this program. If not,
# see <http://www.lsstcorp.org/LegalNotices/>.
#

##\file
## \brief Utilities to help write tests, mostly using numpy
## \brief Utilities to help write tests, mostly using numpy
import numpy as np

import lsst.utils.tests
from .imageLib import ImageF
from .basicUtils import makeMaskedImageFromArrays

# the asserts are automatically imported so unit tests can find them without special imports;
Expand All @@ -34,7 +35,7 @@

def makeGaussianNoiseMaskedImage(dimensions, sigma, variance=1.0):
"""Make a gaussian noise MaskedImageF

Inputs:
- dimensions: dimensions of output array (cols, rows)
- sigma; sigma of image plane's noise distribution
Expand All @@ -44,9 +45,28 @@ def makeGaussianNoiseMaskedImage(dimensions, sigma, variance=1.0):
image = np.random.normal(loc=0.0, scale=sigma, size=npSize).astype(np.float32)
mask = np.zeros(npSize, dtype=np.uint16)
variance = np.zeros(npSize, dtype=np.float32) + variance

return makeMaskedImageFromArrays(image, mask, variance)

def makeRampImage(bbox, start=0, stop=None, imageClass=ImageF):
"""!Make an image whose values are a linear ramp

@param[in] bbox bounding box of image (an lsst.afw.geom.Box2I)
@param[in] start starting ramp value, inclusive
@param[in] stop ending ramp value, inclusive; if None, increase by integer values
@param[in] imageClass type of image (e.g. lsst.afw.image.ImageF)
"""
im = imageClass(bbox)
imDim = im.getDimensions()
numPix = imDim[0]*imDim[1]
imArr = im.getArray()
if stop is None:
# increase by integer values
stop = start + numPix - 1
rampArr = np.linspace(start=start, stop=stop, endpoint=True, num=numPix, dtype=imArr.dtype)
imArr[:] = np.reshape(rampArr, (imDim[1], imDim[0])) # numpy arrays are transposed w.r.t. afwImage
return im

@lsst.utils.tests.inTestCase
def assertImagesNearlyEqual(testCase, image0, image1, skipMask=None,
rtol=1.0e-05, atol=1e-08, msg="Images differ"):
Expand Down Expand Up @@ -121,7 +141,7 @@ def assertMaskedImagesNearlyEqual(testCase, maskedImage0, maskedImage1,
doImage=True, doMask=True, doVariance=True, skipMask=None,
rtol=1.0e-05, atol=1e-08, msg="Masked images differ"):
"""!Assert that two masked images are nearly equal, including non-finite values

@param[in] testCase unittest.TestCase instance the test is part of;
an object supporting one method: fail(self, msgStr)
@param[in] maskedImage0 masked image 0 (an lsst.afw.image.MaskedImage or
Expand Down
16 changes: 8 additions & 8 deletions python/lsst/afw/image/utils.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
from __future__ import absolute_import, division
#
#
# LSST Data Management System
# Copyright 2008, 2009, 2010 LSST Corporation.
#
# Copyright 2008-2016 LSST Corporation.
#
# This product includes software developed by the
# LSST Project (http://www.lsst.org/).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the LSST License Statement and
# the GNU General Public License along with this program. If not,
#
# You should have received a copy of the LSST License Statement and
# the GNU General Public License along with this program. If not,
# see <http://www.lsstcorp.org/LegalNotices/>.
#

Expand Down Expand Up @@ -112,7 +112,7 @@ def defineFiltersFromPolicy(filterPolicy, reset=False):
if p.exists("alias"):
for a in p.getArray("alias"):
afwImage.Filter.defineAlias(p.get("name"), a)

class CalibNoThrow(object):
"""A class intended to be used with python's with statement, to return NaNs for negative fluxes
instead of raising exceptions (exceptions may be raised for other purposes).
Expand Down
67 changes: 67 additions & 0 deletions tests/testGeomTestUtils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import unittest

import lsst.utils.tests
import lsst.afw.geom as afwGeom
from lsst.afw.geom.testUtils import BoxGrid

class BoxGridTestCase(lsst.utils.tests.TestCase):
"""!Unit tests for BoxGrid"""
def test3By4(self):
"""!Test a 3x4 box divided into a 3x2 grid, such that each sub-box is 1x2
"""
for boxClass in (afwGeom.Box2I, afwGeom.Box2D):
pointClass = type(boxClass().getMin())
extentClass = type(boxClass().getDimensions())

minPt = pointClass(-1, 3)
extent = extentClass(3, 4)
numColRow = (3, 2)
outerBox = boxClass(minPt, extent)
boxGrid = BoxGrid(box=outerBox, numColRow=numColRow)
for box in boxGrid:
self.assertEqual(box.getDimensions(), extentClass(1, 2))
for row in range(numColRow[1]):
for col in range(numColRow[0]):
box = boxGrid[col, row]
predMin = outerBox.getMin() + extentClass(col*1, row*2)
self.assertEqual(box.getMin(), predMin)

def testIntUneven(self):
"""!Test dividing an integer box into an uneven grid

Divide a 5x4 box into 2x3 regions
"""
minPt = afwGeom.Point2I(0, 0)
extent = afwGeom.Extent2I(5, 7)
numColRow = (2, 3)
outerBox = afwGeom.Box2I(minPt, extent)
boxGrid = BoxGrid(box=outerBox, numColRow=numColRow)
desColStarts = (0, 2)
desWidths = (2, 3)
desRowStarts = (0, 2, 4)
desHeights = (2, 2, 3)
for row in range(numColRow[1]):
desRowStart = desRowStarts[row]
desHeight = desHeights[row]
for col in range(numColRow[0]):
desColStart = desColStarts[col]
desWidth = desWidths[col]
box = boxGrid[col, row]
self.assertEqual(tuple(box.getMin()), (desColStart, desRowStart))
self.assertEqual(tuple(box.getDimensions()), (desWidth, desHeight))

def suite():
"""!Returns a suite containing all the test cases in this module."""
lsst.utils.tests.init()

suites = []
suites += unittest.makeSuite(BoxGridTestCase)
suites += unittest.makeSuite(lsst.utils.tests.MemoryTestCase)
return unittest.TestSuite(suites)

def run(exit=False):
"""!Run the tests"""
lsst.utils.tests.run(suite(), exit)

if __name__ == "__main__":
run(True)