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