lsst.jointcal  16.0-15-g8e16a51+3
testUtils.py
Go to the documentation of this file.
1 # This file is part of jointcal.
2 
3 # Developed for the LSST Data Management System.
4 # This product includes software developed by the LSST Project
5 # (http://www.lsst.org).
6 # See the COPYRIGHT file at the top-level directory of this distribution
7 # for details of code ownership.
8 
9 # This program is free software: you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation, either version 3 of the License, or
12 # (at your option) any later version.
13 
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 
19 # You should have received a copy of the GNU General Public License
20 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 """Functions to help create jointcal tests by generating fake data."""
22 
23 __all__ = ['createFakeCatalog', 'createTwoFakeCcdImages', 'getMeasuredStarsFromCatalog']
24 
25 import os
26 import numpy as np
27 
28 import lsst.afw.geom
29 import lsst.afw.table
31 import lsst.pipe.base
32 
33 import lsst.jointcal.star
34 
35 
36 def createTwoFakeCcdImages(num1=4, num2=4, seed=100, fakeCcdId=12,
37  photoCalibMean1=100.0, photoCalibMean2=120.0):
38  """Return two fake ccdImages built on CFHT Megacam metadata.
39 
40  If ``num1 == num2``, the catalogs will align on-sky so each source will
41  have a match in the other catalog.
42 
43  This uses the butler dataset stored in `tests/data/cfht_minimal` to
44  bootstrap the metadata.
45 
46  Parameters
47  ----------
48  num1, num2 : `int`, optional
49  Number of sources to put in the first and second catalogs. Should be
50  a square, to have sqrt(num) centroids on a grid.
51  seed : `int`, optional
52  Seed value for np.random.
53  fakeCcdId : `int`, optional
54  Sensor identifier to use for both CcdImages. The wcs, bbox, calib, etc.
55  will still be drawn from the CFHT ccd=12 files, as that is the only
56  testdata that is included in this simple test dataset.
57  photoCalibMean1, photoCalibMean2: `float`, optional
58  The mean photometric calibration to pass to each ccdImage construction.
59 
60  Returns
61  -------
62  struct : `lsst.pipe.base.Struct`
63  Result struct with components:
64 
65  - `camera` : Camera representing these catalogs
66  (`lsst.afw.cameraGeom.Camera`).
67  - `catalogs` : Catalogs containing fake sources
68  (`list` of `lsst.afw.table.SourceCatalog`).
69  - `ccdImageList` : CcdImages containing the metadata and fake sources
70  (`list` of `lsst.jointcal.CcdImage`).
71  - `bbox` : Bounding Box of the image (`lsst.afw.geom.Box2I`).
72  - 'instFluxKeyName' : name of the instFlux field in the catalogs ('str').
73  """
74  np.random.seed(seed)
75 
76  visit1 = 849375
77  visit2 = 850587
78  instFluxKeyName = "SomeFlux"
79 
80  # Load or fake the necessary metadata for each CcdImage
81  dataDir = lsst.utils.getPackageDir('jointcal')
82  inputDir = os.path.join(dataDir, 'tests/data/cfht_minimal')
83  butler = lsst.daf.persistence.Butler(inputDir)
84 
85  # so we can access parts of the camera later (e.g. focal plane)
86  camera = butler.get('camera', visit=visit1)
87 
88  struct1 = createFakeCcdImage(butler, visit1, num1, instFluxKeyName,
89  photoCalibMean=photoCalibMean1, photoCalibErr=1.0, fakeCcdId=fakeCcdId)
90  struct2 = createFakeCcdImage(butler, visit2, num2, instFluxKeyName,
91  photoCalibMean=photoCalibMean2, photoCalibErr=5.0, fakeCcdId=fakeCcdId)
92 
93  return lsst.pipe.base.Struct(camera=camera,
94  catalogs=[struct1.catalog, struct2.catalog],
95  ccdImageList=[struct1.ccdImage, struct2.ccdImage],
96  bbox=struct1.bbox,
97  instFluxKeyName=instFluxKeyName)
98 
99 
100 def createFakeCcdImage(butler, visit, num, instFluxKeyName,
101  photoCalibMean=100.0, photoCalibErr=1.0, fakeCcdId=12):
102  """Create a fake CcdImage by making a fake catalog.
103 
104  Parameters
105  ----------
106  butler : `lsst.daf.persistence.Butler`
107  Butler to load metadata from.
108  visit : `int`
109  Visit identifier to build a butler dataId.
110  num : `int`
111  Number of sources to put in the catalogs. Should be
112  a square, to have sqrt(num) centroids on a grid.
113  instFluxKeyName : `str`
114  Name of the instFluxKey to populate in the catalog.
115  photoCalibMean : `float`, optional
116  Value to set for calibrationMean in the created PhotoCalib.
117  photoCalibErr : `float`, optional
118  Value to set for calibrationErr in the created PhotoCalib.
119  fakeCcdId : `int`, optional
120  Use this as the ccdId in the returned CcdImage.
121 
122  Returns
123  -------
124  struct : `lsst.pipe.base.Struct`
125  Result struct with components:
126 
127  - `catalog` : Catalogs containing fake sources
128  (`lsst.afw.table.SourceCatalog`).
129  - `ccdImage` : CcdImage containing the metadata and fake sources
130  (`lsst.jointcal.CcdImage`).
131  - `bbox` : Bounding Box of the image (`lsst.afw.geom.Box2I`).
132  """
133  ccdId = 12 # we only have data for ccd=12
134 
135  dataId = dict(visit=visit, ccd=ccdId)
136  skyWcs = butler.get('calexp_wcs', dataId=dataId)
137  visitInfo = butler.get('calexp_visitInfo', dataId=dataId)
138  bbox = butler.get('calexp_bbox', dataId=dataId)
139  detector = butler.get('calexp_detector', dataId=dataId)
140  filt = butler.get("calexp_filter", dataId=dataId).getName()
141  photoCalib = lsst.afw.image.PhotoCalib(photoCalibMean, photoCalibErr)
142 
143  catalog = createFakeCatalog(num, bbox, instFluxKeyName, skyWcs=skyWcs)
144  ccdImage = lsst.jointcal.ccdImage.CcdImage(catalog, skyWcs, visitInfo, bbox, filt, photoCalib,
145  detector, visit, fakeCcdId, instFluxKeyName)
146 
147  return lsst.pipe.base.Struct(catalog=catalog, ccdImage=ccdImage, bbox=bbox)
148 
149 
150 def createFakeCatalog(num, bbox, instFluxKeyName, skyWcs=None, refCat=False):
151  """Return a fake minimally-useful catalog for jointcal.
152 
153  Parameters
154  ----------
155  num : `int`
156  Number of sources to put in the catalogs. Should be
157  a square, to have sqrt(num) centroids on a grid.
158  bbox : `lsst.afw.geom.Box2I`
159  Bounding Box of the detector to populate.
160  instFluxKeyName : `str`
161  Name of the instFluxKey to populate in the catalog.
162  skyWcs : `lsst.afw.geom.SkyWcs` or None, optional
163  If supplied, use this to fill in coordinates from centroids.
164  refCat : `bool`, optional
165  Return a ``SimpleCatalog`` so that it behaves like a reference catalog?
166 
167  Returns
168  -------
169  catalog : `lsst.afw.table.SourceCatalog`
170  A populated source catalog.
171  """
173  # centroid
174  centroidKey = lsst.afw.table.Point2DKey.addFields(schema, "centroid", "centroid", "pixels")
175  xErrKey = schema.addField("centroid_xErr", type="F")
176  yErrKey = schema.addField("centroid_yErr", type="F")
177  # shape
178  shapeKey = lsst.afw.table.QuadrupoleKey.addFields(schema, "shape", "",
179  lsst.afw.table.CoordinateType.PIXEL)
180  # Put the fake sources in the minimal catalog.
181  schema.addField(instFluxKeyName+"_flux", type="D", doc="post-ISR instFlux")
182  schema.addField(instFluxKeyName+"_fluxErr", type="D", doc="post-ISR instFlux stddev")
183  schema.addField(instFluxKeyName+"_calFlux", type="D", doc="maggies")
184  schema.addField(instFluxKeyName+"_calFluxErr", type="D", doc="maggies stddev")
185  schema.addField(instFluxKeyName+"_mag", type="D", doc="magnitude")
186  schema.addField(instFluxKeyName+"_magErr", type="D", doc="magnitude stddev")
187  return fillCatalog(schema, num, bbox,
188  centroidKey, xErrKey, yErrKey, shapeKey, instFluxKeyName,
189  skyWcs=skyWcs, refCat=refCat)
190 
191 
192 def fillCatalog(schema, num, bbox,
193  centroidKey, xErrKey, yErrKey, shapeKey, instFluxKeyName,
194  skyWcs=None, fluxErrFraction=0.05, refCat=False):
195  """Return a catalog populated with fake, but reasonable, sources.
196 
197  Centroids are placed on a uniform grid, errors are normally distributed.
198 
199  Parameters
200  ----------
201  schema : `lsst.afw.table.Schema`
202  Pre-built schema to make the catalog from.
203  num : `int`
204  Number of sources to put in the catalog.
205  bbox : `lsst.afw.geom.Box2I`
206  Bounding box of the ccd to put sources in.
207  centroidKey : `lsst.afw.table.Key`
208  Key for the centroid field to populate.
209  xErrKey : `lsst.afw.table.Key`
210  Key for the xErr field to populate.
211  yErrKey : `lsst.afw.table.Key`
212  Key for the yErr field to populate.
213  shapeKey : `lsst.afw.table.Key`
214  Key for the shape field to populate.
215  instFluxKeyName : `str`
216  Name of instFlux field to populate (i.e. instFluxKeyName+'_flux')
217  skyWcs : `lsst.afw.geom.SkyWcs` or None, optional
218  If supplied, use this to fill in coordinates from centroids.
219  fluxErrFraction : `float`, optional
220  Fraction of instFlux to use for the instFluxErr.
221  refCat : `bool`, optional
222  Return a ``SimpleCatalog`` so that it behaves like a reference catalog?
223 
224  Returns
225  -------
226  catalog : `lsst.afw.table.SourceCatalog`
227  The filled catalog.
228  """
229  table = lsst.afw.table.SourceTable.make(schema)
230  table.defineCentroid('centroid')
231  table.defineShape('shape')
232  table.defineInstFlux(instFluxKeyName)
233  if refCat:
234  catalog = lsst.afw.table.SimpleCatalog(table)
235  else:
236  catalog = lsst.afw.table.SourceCatalog(table)
237 
238  instFlux = np.random.random(num)*10000
239  instFluxErr = np.abs(instFlux * np.random.normal(fluxErrFraction, scale=0.1, size=num))
240  xx = np.linspace(bbox.getMinX(), bbox.getMaxX(), int(np.sqrt(num)))
241  yy = np.linspace(bbox.getMinY(), bbox.getMaxY(), int(np.sqrt(num)))
242  xv, yv = np.meshgrid(xx, yy)
243  vx = np.random.normal(scale=0.1, size=num)
244  vy = np.random.normal(scale=0.1, size=num)
245 
246  # make all the sources perfectly spherical, for simplicity.
247  mxx = 1
248  myy = 1
249  mxy = 0
250 
251  for i, (x, y) in enumerate(zip(xv.ravel(), yv.ravel())):
252  record = catalog.addNew()
253  record.set('id', i)
254  record.set(centroidKey, lsst.afw.geom.Point2D(x, y))
255  record.set(shapeKey, lsst.afw.geom.ellipses.Quadrupole(mxx, myy, mxy))
256 
257  if skyWcs is not None:
258  lsst.afw.table.updateSourceCoords(skyWcs, catalog)
259 
260  catalog[xErrKey] = vx
261  catalog[yErrKey] = vy
262  catalog[instFluxKeyName + '_flux'] = instFlux
263  catalog[instFluxKeyName + '_fluxErr'] = instFluxErr
264 
265  return catalog
266 
267 
268 def getMeasuredStarsFromCatalog(catalog, pixToFocal):
269  """Return a list of measuredStars built from a catalog.
270 
271  Parameters
272  ----------
273  catalog : `lsst.afw.table.SourceCatalog`
274  The table to get sources from.
275  pixToFocal : `lsst.afw.geom.TransformPoint2ToPoint2`
276  Transform that goes from pixel to focal plane coordinates, to set the
277  MeasuredStar x/y focal points.
278 
279  Returns
280  -------
281  stars : `list` of `lsst.jointcal.MeasuredStar`
282  MeasuredStars built from the catalog sources.
283  """
284  stars = []
285  for record in catalog:
286  star = lsst.jointcal.star.MeasuredStar()
287  star.x = record.getX()
288  star.y = record.getY()
289  star.setInstFluxAndErr(record.getInstFlux(), record.getInstFluxErr())
290  # TODO: cleanup after DM-4044
291  point = lsst.afw.geom.Point2D(star.x, star.y)
292  pointFocal = pixToFocal.applyForward(point)
293  star.setXFocal(pointFocal.getX())
294  star.setYFocal(pointFocal.getY())
295  stars.append(star)
296 
297  return stars
def createFakeCatalog(num, bbox, instFluxKeyName, skyWcs=None, refCat=False)
Definition: testUtils.py:150
def fillCatalog(schema, num, bbox, centroidKey, xErrKey, yErrKey, shapeKey, instFluxKeyName, skyWcs=None, fluxErrFraction=0.05, refCat=False)
Definition: testUtils.py:194
void updateSourceCoords(geom::SkyWcs const &wcs, SourceCollection &sourceList)
std::string getPackageDir(std::string const &packageName)
static QuadrupoleKey addFields(Schema &schema, std::string const &name, std::string const &doc, CoordinateType coordType=CoordinateType::PIXEL)
static Schema makeMinimalSchema()
static std::shared_ptr< SourceTable > make(Schema const &schema, std::shared_ptr< IdFactory > const &idFactory)
def getMeasuredStarsFromCatalog(catalog, pixToFocal)
Definition: testUtils.py:268
def createFakeCcdImage(butler, visit, num, instFluxKeyName, photoCalibMean=100.0, photoCalibErr=1.0, fakeCcdId=12)
Definition: testUtils.py:101
def createTwoFakeCcdImages(num1=4, num2=4, seed=100, fakeCcdId=12, photoCalibMean1=100.0, photoCalibMean2=120.0)
Definition: testUtils.py:37