lsst.jointcal  16.0-5-g82b7855
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.obs.lsstSim
32 import lsst.pipe.base
33 
34 import lsst.jointcal.star
35 
36 
37 def createTwoFakeCcdImages(num1=4, num2=4, seed=100, fakeCcdId=12):
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 
58  Returns
59  -------
60  struct : `lsst.pipe.base.Struct`
61  Result struct with components:
62 
63  - `camera` : Camera representing these catalogs
64  (`lsst.afw.cameraGeom.Camera`).
65  - `catalogs` : Catalogs containing fake sources
66  (`list` of `lsst.afw.table.SourceCatalog`).
67  - `ccdImageList` : CcdImages containing the metadata and fake sources
68  (`list` of `lsst.jointcal.CcdImage`).
69  - `bbox` : Bounding Box of the image (`lsst.afw.geom.Box2I`).
70  """
71  np.random.seed(seed)
72 
73  visit1 = 849375
74  visit2 = 850587
75  instFluxKeyName = "SomeFlux"
76 
77  # Load or fake the necessary metadata for each CcdImage
78  dataDir = lsst.utils.getPackageDir('jointcal')
79  inputDir = os.path.join(dataDir, 'tests/data/cfht_minimal')
80  butler = lsst.daf.persistence.Butler(inputDir)
81 
82  # so we can access parts of the camera later (e.g. focal plane)
83  camera = butler.get('camera', visit=visit1)
84 
85  struct1 = createFakeCcdImage(butler, visit1, num1, instFluxKeyName,
86  photoCalibMean=100.0, photoCalibErr=1.0, fakeCcdId=fakeCcdId)
87  struct2 = createFakeCcdImage(butler, visit2, num2, instFluxKeyName,
88  photoCalibMean=120.0, photoCalibErr=5.0, fakeCcdId=fakeCcdId)
89 
90  return lsst.pipe.base.Struct(camera=camera,
91  catalogs=[struct1.catalog, struct2.catalog],
92  ccdImageList=[struct1.ccdImage, struct2.ccdImage],
93  bbox=struct1.bbox)
94 
95 
96 def createFakeCcdImage(butler, visit, num, instFluxKeyName,
97  photoCalibMean=100.0, photoCalibErr=1.0, fakeCcdId=12):
98  """Create a fake CcdImage by making a fake catalog.
99 
100  Parameters
101  ----------
102  butler : `lsst.daf.persistence.Butler`
103  Butler to load metadata from.
104  visit : `int`
105  Visit identifier to build a butler dataId.
106  num : `int`
107  Number of sources to put in the catalogs. Should be
108  a square, to have sqrt(num) centroids on a grid.
109  instFluxKeyName : `str`
110  Name of the instFluxKey to populate in the catalog.
111  photoCalibMean : `float`, optional
112  Value to set for calibrationMean in the created PhotoCalib.
113  photoCalibErr : `float`, optional
114  Value to set for calibrationErr in the created PhotoCalib.
115  fakeCcdId : `int`, optional
116  Use this as the ccdId in the returned CcdImage.
117 
118  Returns
119  -------
120  struct : `lsst.pipe.base.Struct`
121  Result struct with components:
122 
123  - `catalog` : Catalogs containing fake sources
124  (`lsst.afw.table.SourceCatalog`).
125  - `ccdImage` : CcdImage containing the metadata and fake sources
126  (`lsst.jointcal.CcdImage`).
127  - `bbox` : Bounding Box of the image (`lsst.afw.geom.Box2I`).
128  """
129  ccdId = 12 # we only have data for ccd=12
130 
131  dataId = dict(visit=visit, ccd=ccdId)
132  skyWcs = butler.get('calexp_wcs', dataId=dataId)
133  visitInfo = butler.get('calexp_visitInfo', dataId=dataId)
134  bbox = butler.get('calexp_bbox', dataId=dataId)
135  detector = butler.get('calexp_detector', dataId=dataId)
136  filt = butler.get("calexp_filter", dataId=dataId).getName()
137  photoCalib = lsst.afw.image.PhotoCalib(photoCalibMean, photoCalibErr)
138 
139  catalog = createFakeCatalog(num, bbox, instFluxKeyName, skyWcs=skyWcs)
140  ccdImage = lsst.jointcal.ccdImage.CcdImage(catalog, skyWcs, visitInfo, bbox, filt, photoCalib,
141  detector, visit, fakeCcdId, instFluxKeyName)
142 
143  return lsst.pipe.base.Struct(catalog=catalog, ccdImage=ccdImage, bbox=bbox)
144 
145 
146 def createFakeCatalog(num, bbox, instFluxKeyName, skyWcs=None, refCat=False):
147  """Return a fake minimally-useful catalog for jointcal.
148 
149  Parameters
150  ----------
151  num : `int`
152  Number of sources to put in the catalogs. Should be
153  a square, to have sqrt(num) centroids on a grid.
154  bbox : `lsst.afw.geom.Box2I`
155  Bounding Box of the detector to populate.
156  instFluxKeyName : `str`
157  Name of the instFluxKey to populate in the catalog.
158  skyWcs : `lsst.afw.geom.SkyWcs` or None, optional
159  If supplied, use this to fill in coordinates from centroids.
160  refCat : `bool`, optional
161  Return a ``SimpleCatalog`` so that it behaves like a reference catalog?
162 
163  Returns
164  -------
165  catalog : `lsst.afw.table.SourceCatalog`
166  A populated source catalog.
167  """
169  # centroid
170  centroidKey = lsst.afw.table.Point2DKey.addFields(schema, "centroid", "centroid", "pixels")
171  xErrKey = schema.addField("centroid_xSigma", type="F")
172  yErrKey = schema.addField("centroid_ySigma", type="F")
173  # shape
174  shapeKey = lsst.afw.table.QuadrupoleKey.addFields(schema, "shape", "",
175  lsst.afw.table.CoordinateType.PIXEL)
176  # Put the fake sources in the minimal catalog.
177  schema.addField(instFluxKeyName+"_flux", type="D", doc="post-ISR instFlux")
178  schema.addField(instFluxKeyName+"_fluxSigma", type="D", doc="post-ISR instFlux stddev")
179  schema.addField(instFluxKeyName+"_calFlux", type="D", doc="maggies")
180  schema.addField(instFluxKeyName+"_calFluxErr", type="D", doc="maggies stddev")
181  schema.addField(instFluxKeyName+"_mag", type="D", doc="magnitude")
182  schema.addField(instFluxKeyName+"_magErr", type="D", doc="magnitude stddev")
183  return fillCatalog(schema, num, bbox,
184  centroidKey, xErrKey, yErrKey, shapeKey, instFluxKeyName,
185  skyWcs=skyWcs, refCat=refCat)
186 
187 
188 def fillCatalog(schema, num, bbox,
189  centroidKey, xErrKey, yErrKey, shapeKey, instFluxKeyName,
190  skyWcs=None, fluxErrFraction=0.05, refCat=False):
191  """Return a catalog populated with fake, but reasonable, sources.
192 
193  Centroids are placed on a uniform grid, errors are normally distributed.
194 
195  Parameters
196  ----------
197  schema : `lsst.afw.table.Schema`
198  Pre-built schema to make the catalog from.
199  num : `int`
200  Number of sources to put in the catalog.
201  bbox : `lsst.afw.geom.Box2I`
202  Bounding box of the ccd to put sources in.
203  centroidKey : `lsst.afw.table.Key`
204  Key for the centroid field to populate.
205  xErrKey : `lsst.afw.table.Key`
206  Key for the xErr field to populate.
207  yErrKey : `lsst.afw.table.Key`
208  Key for the yErr field to populate.
209  shapeKey : `lsst.afw.table.Key`
210  Key for the shape field to populate.
211  instFluxKeyName : `str`
212  Name of instFlux field to populate (i.e. instFluxKeyName+'_flux')
213  skyWcs : `lsst.afw.geom.SkyWcs` or None, optional
214  If supplied, use this to fill in coordinates from centroids.
215  fluxErrFraction : `float`, optional
216  Fraction of instFlux to use for the instFluxErr.
217  refCat : `bool`, optional
218  Return a ``SimpleCatalog`` so that it behaves like a reference catalog?
219 
220  Returns
221  -------
222  catalog : `lsst.afw.table.SourceCatalog`
223  The filled catalog.
224  """
225  table = lsst.afw.table.SourceTable.make(schema)
226  table.defineCentroid('centroid')
227  table.defineShape('shape')
228  table.defineInstFlux(instFluxKeyName)
229  if refCat:
230  catalog = lsst.afw.table.SimpleCatalog(table)
231  else:
232  catalog = lsst.afw.table.SourceCatalog(table)
233 
234  instFlux = np.random.random(num)
235  instFluxErr = instFlux * fluxErrFraction
236  xx = np.linspace(bbox.getMinX(), bbox.getMaxX(), int(np.sqrt(num)))
237  yy = np.linspace(bbox.getMinY(), bbox.getMaxY(), int(np.sqrt(num)))
238  xv, yv = np.meshgrid(xx, yy)
239  vx = np.random.normal(scale=0.1, size=num)
240  vy = np.random.normal(scale=0.1, size=num)
241 
242  # make all the sources perfectly spherical, for simplicity.
243  mxx = 1
244  myy = 1
245  mxy = 0
246 
247  for i, (x, y) in enumerate(zip(xv.ravel(), yv.ravel())):
248  record = catalog.addNew()
249  record.set('id', i)
250  record.set(centroidKey, lsst.afw.geom.Point2D(x, y))
251  record.set(shapeKey, lsst.afw.geom.ellipses.Quadrupole(mxx, myy, mxy))
252 
253  if skyWcs is not None:
254  lsst.afw.table.updateSourceCoords(skyWcs, catalog)
255 
256  catalog[xErrKey] = vx
257  catalog[yErrKey] = vy
258  catalog[instFluxKeyName + '_flux'] = instFlux
259  catalog[instFluxKeyName + '_fluxSigma'] = instFluxErr
260 
261  return catalog
262 
263 
264 def getMeasuredStarsFromCatalog(catalog, pixToFocal):
265  """Return a list of measuredStars built from a catalog.
266 
267  Parameters
268  ----------
269  catalog : `lsst.afw.table.SourceCatalog`
270  The table to get sources from.
271  pixToFocal : `lsst.afw.geom.TransformPoint2ToPoint2`
272  Transform that goes from pixel to focal plane coordinates, to set the
273  MeasuredStar x/y focal points.
274 
275  Returns
276  -------
277  stars : `list` of `lsst.jointcal.MeasuredStar`
278  MeasuredStars built from the catalog sources.
279  """
280  stars = []
281  for record in catalog:
282  star = lsst.jointcal.star.MeasuredStar()
283  star.x = record.getX()
284  star.y = record.getY()
285  star.setInstFlux(record.getInstFlux())
286  star.setInstFluxErr(record.getInstFluxErr())
287  # TODO: cleanup after DM-4044
288  point = lsst.afw.geom.Point2D(star.x, star.y)
289  pointFocal = pixToFocal.applyForward(point)
290  star.setXFocal(pointFocal.getX())
291  star.setYFocal(pointFocal.getY())
292  stars.append(star)
293 
294  return stars
def createFakeCatalog(num, bbox, instFluxKeyName, skyWcs=None, refCat=False)
Definition: testUtils.py:146
def fillCatalog(schema, num, bbox, centroidKey, xErrKey, yErrKey, shapeKey, instFluxKeyName, skyWcs=None, fluxErrFraction=0.05, refCat=False)
Definition: testUtils.py:190
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)
def createTwoFakeCcdImages(num1=4, num2=4, seed=100, fakeCcdId=12)
Definition: testUtils.py:37
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:264
def createFakeCcdImage(butler, visit, num, instFluxKeyName, photoCalibMean=100.0, photoCalibErr=1.0, fakeCcdId=12)
Definition: testUtils.py:97