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