LSST Applications g063fba187b+cac8b7c890,g0f08755f38+6aee506743,g1653933729+a8ce1bb630,g168dd56ebc+a8ce1bb630,g1a2382251a+b4475c5878,g1dcb35cd9c+8f9bc1652e,g20f6ffc8e0+6aee506743,g217e2c1bcf+73dee94bd0,g28da252d5a+1f19c529b9,g2bbee38e9b+3f2625acfc,g2bc492864f+3f2625acfc,g3156d2b45e+6e55a43351,g32e5bea42b+1bb94961c2,g347aa1857d+3f2625acfc,g35bb328faa+a8ce1bb630,g3a166c0a6a+3f2625acfc,g3e281a1b8c+c5dd892a6c,g3e8969e208+a8ce1bb630,g414038480c+5927e1bc1e,g41af890bb2+8a9e676b2a,g7af13505b9+809c143d88,g80478fca09+6ef8b1810f,g82479be7b0+f568feb641,g858d7b2824+6aee506743,g89c8672015+f4add4ffd5,g9125e01d80+a8ce1bb630,ga5288a1d22+2903d499ea,gb58c049af0+d64f4d3760,gc28159a63d+3f2625acfc,gcab2d0539d+b12535109e,gcf0d15dbbd+46a3f46ba9,gda6a2b7d83+46a3f46ba9,gdaeeff99f8+1711a396fd,ge79ae78c31+3f2625acfc,gef2f8181fd+0a71e47438,gf0baf85859+c1f95f4921,gfa517265be+6aee506743,gfa999e8aa5+17cd334064,w.2024.51
LSST Data Management Base Package
Loading...
Searching...
No Matches
Classes | Functions | Variables
lsst.pipe.tasks.insertFakes Namespace Reference

Classes

class  InsertFakesConnections
 

Functions

 _add_fake_sources (exposure, objects, calibFluxRadius=12.0, logger=None)
 
 _isWCSGalsimDefault (wcs, hdr)
 
 processImagesForInsertion (self, fakeCat, wcs, psf, photoCalib, band, pixelScale)
 
 addPixCoords (self, fakeCat, image)
 
 trimFakeCat (self, fakeCat, image)
 
 mkFakeGalsimGalaxies (self, fakeCat, band, photoCalib, pixelScale, psf, image)
 
 mkFakeStars (self, fakeCat, band, photoCalib, psf, image)
 
 cleanCat (self, fakeCat, starCheckVal)
 
 addFakeSources (self, image, fakeImages, sourceType)
 

Variables

 linWcs = wcs.linearizePixelToSky(skyCoord, geom.arcseconds)
 
 mat = linWcs.getMatrix()
 
 wcs
 
 obj = galsim.InterpolatedImage(im, calculate_stepk=False)
 
 bitmask
 

Detailed Description

Insert fakes into deepCoadds

Function Documentation

◆ _add_fake_sources()

lsst.pipe.tasks.insertFakes._add_fake_sources ( exposure,
objects,
calibFluxRadius = 12.0,
logger = None )
protected
Add fake sources to the given exposure

Parameters
----------
exposure : `lsst.afw.image.exposure.exposure.ExposureF`
    The exposure into which the fake sources should be added
objects : `typing.Iterator` [`tuple` ['lsst.geom.SpherePoint`, `galsim.GSObject`]]
    An iterator of tuples that contains (or generates) locations and object
    surface brightness profiles to inject.
calibFluxRadius : `float`, optional
    Aperture radius (in pixels) used to define the calibration for this
    exposure+catalog.  This is used to produce the correct instrumental fluxes
    within the radius.  The value should match that of the field defined in
    slot_CalibFlux_instFlux.
logger : `logging.Logger`, optional
    Logger.

Definition at line 46 of file insertFakes.py.

46def _add_fake_sources(exposure, objects, calibFluxRadius=12.0, logger=None):
47 """Add fake sources to the given exposure
48
49 Parameters
50 ----------
51 exposure : `lsst.afw.image.exposure.exposure.ExposureF`
52 The exposure into which the fake sources should be added
53 objects : `typing.Iterator` [`tuple` ['lsst.geom.SpherePoint`, `galsim.GSObject`]]
54 An iterator of tuples that contains (or generates) locations and object
55 surface brightness profiles to inject.
56 calibFluxRadius : `float`, optional
57 Aperture radius (in pixels) used to define the calibration for this
58 exposure+catalog. This is used to produce the correct instrumental fluxes
59 within the radius. The value should match that of the field defined in
60 slot_CalibFlux_instFlux.
61 logger : `logging.Logger`, optional
62 Logger.
63 """
64 exposure.mask.addMaskPlane("FAKE")
65 bitmask = exposure.mask.getPlaneBitMask("FAKE")
66 if logger:
67 logger.info("Adding mask plane with bitmask %s", bitmask)
68
69 wcs = exposure.getWcs()
70 psf = exposure.getPsf()
71
72 bbox = exposure.getBBox()
73 fullBounds = galsim.BoundsI(bbox.minX, bbox.maxX, bbox.minY, bbox.maxY)
74 gsImg = galsim.Image(exposure.image.array, bounds=fullBounds)
75
76 pixScale = wcs.getPixelScale(bbox.getCenter()).asArcseconds()
77
78 for spt, gsObj in objects:
79 pt = wcs.skyToPixel(spt)
80 posd = galsim.PositionD(pt.x, pt.y)
81 posi = galsim.PositionI(pt.x//1, pt.y//1)
82 if logger:
83 logger.debug("Adding fake source at %s", pt)
84
85 mat = wcs.linearizePixelToSky(spt, geom.arcseconds).getMatrix()
86 gsWCS = galsim.JacobianWCS(mat[0, 0], mat[0, 1], mat[1, 0], mat[1, 1])
87
88 # This check is here because sometimes the WCS
89 # is multivalued and objects that should not be
90 # were being included.
91 gsPixScale = np.sqrt(gsWCS.pixelArea())
92 if gsPixScale < pixScale/2 or gsPixScale > pixScale*2:
93 continue
94
95 try:
96 psfArr = psf.computeKernelImage(pt).array
97 apCorr = psf.computeApertureFlux(calibFluxRadius, pt)
98 except InvalidParameterError:
99 # Try mapping to nearest point contained in bbox.
100 contained_pt = Point2D(
101 np.clip(pt.x, bbox.minX, bbox.maxX),
102 np.clip(pt.y, bbox.minY, bbox.maxY)
103 )
104 if pt == contained_pt: # no difference, so skip immediately
105 if logger:
106 logger.info("Cannot compute Psf for object at %s; skipping", pt)
107 continue
108 # otherwise, try again with new point
109 try:
110 psfArr = psf.computeKernelImage(contained_pt).array
111 apCorr = psf.computeApertureFlux(calibFluxRadius, contained_pt)
112 except InvalidParameterError:
113 if logger:
114 logger.info("Cannot compute Psf for object at %s; skipping", pt)
115 continue
116
117 psfArr /= apCorr
118 gsPSF = galsim.InterpolatedImage(galsim.Image(psfArr), wcs=gsWCS)
119
120 conv = galsim.Convolve(gsObj, gsPSF)
121 stampSize = conv.getGoodImageSize(gsWCS.minLinearScale())
122 subBounds = galsim.BoundsI(posi).withBorder(stampSize//2)
123 subBounds &= fullBounds
124
125 if subBounds.area() > 0:
126 subImg = gsImg[subBounds]
127 offset = posd - subBounds.true_center
128 # Note, for calexp injection, pixel is already part of the PSF and
129 # for coadd injection, it's incorrect to include the output pixel.
130 # So for both cases, we draw using method='no_pixel'.
131
132 conv.drawImage(
133 subImg,
134 add_to_image=True,
135 offset=offset,
136 wcs=gsWCS,
137 method='no_pixel'
138 )
139
140 subBox = geom.Box2I(
141 geom.Point2I(subBounds.xmin, subBounds.ymin),
142 geom.Point2I(subBounds.xmax, subBounds.ymax)
143 )
144 exposure[subBox].mask.array |= bitmask
145
146
An integer coordinate rectangle.
Definition Box.h:55

◆ _isWCSGalsimDefault()

lsst.pipe.tasks.insertFakes._isWCSGalsimDefault ( wcs,
hdr )
protected
Decide if wcs = galsim.PixelScale(1.0) is explicitly present in header,
or if it's just the galsim default.

Parameters
----------
wcs : galsim.BaseWCS
    Potentially default WCS.
hdr : galsim.fits.FitsHeader
    Header as read in by galsim.

Returns
-------
isDefault : bool
    True if default, False if explicitly set in header.

Definition at line 147 of file insertFakes.py.

147def _isWCSGalsimDefault(wcs, hdr):
148 """Decide if wcs = galsim.PixelScale(1.0) is explicitly present in header,
149 or if it's just the galsim default.
150
151 Parameters
152 ----------
153 wcs : galsim.BaseWCS
154 Potentially default WCS.
155 hdr : galsim.fits.FitsHeader
156 Header as read in by galsim.
157
158 Returns
159 -------
160 isDefault : bool
161 True if default, False if explicitly set in header.
162 """
163 if wcs != galsim.PixelScale(1.0):
164 return False
165 if hdr.get('GS_WCS') is not None:
166 return False
167 if hdr.get('CTYPE1', 'LINEAR') == 'LINEAR':
168 return not any(k in hdr for k in ['CD1_1', 'CDELT1'])
169 for wcs_type in galsim.fitswcs.fits_wcs_types:
170 # If one of these succeeds, then assume result is explicit
171 try:
172 wcs_type._readHeader(hdr)
173 return False
174 except Exception:
175 pass
176 else:
177 return not any(k in hdr for k in ['CD1_1', 'CDELT1'])
178
179

◆ addFakeSources()

lsst.pipe.tasks.insertFakes.addFakeSources ( self,
image,
fakeImages,
sourceType )
Add the fake sources to the given image

Parameters
----------
image : `lsst.afw.image.exposure.exposure.ExposureF`
            The image into which the fake sources should be added
fakeImages : `typing.Iterator` [`tuple` ['lsst.afw.image.ImageF`, `lsst.geom.Point2d`]]
            An iterator of tuples that contains (or generates) images of fake sources,
            and the locations they are to be inserted at.
sourceType : `str`
            The type (star/galaxy) of fake sources input

Returns
-------
image : `lsst.afw.image.exposure.exposure.ExposureF`

Notes
-----
Uses the x, y information in the ``fakeCat`` to position an image of the fake interpolated onto the
pixel grid of the image. Sets the ``FAKE`` mask plane for the pixels added with the fake source.

Definition at line 1236 of file insertFakes.py.

1236 def addFakeSources(self, image, fakeImages, sourceType):
1237 """Add the fake sources to the given image
1238
1239 Parameters
1240 ----------
1241 image : `lsst.afw.image.exposure.exposure.ExposureF`
1242 The image into which the fake sources should be added
1243 fakeImages : `typing.Iterator` [`tuple` ['lsst.afw.image.ImageF`, `lsst.geom.Point2d`]]
1244 An iterator of tuples that contains (or generates) images of fake sources,
1245 and the locations they are to be inserted at.
1246 sourceType : `str`
1247 The type (star/galaxy) of fake sources input
1248
1249 Returns
1250 -------
1251 image : `lsst.afw.image.exposure.exposure.ExposureF`
1252
1253 Notes
1254 -----
1255 Uses the x, y information in the ``fakeCat`` to position an image of the fake interpolated onto the
1256 pixel grid of the image. Sets the ``FAKE`` mask plane for the pixels added with the fake source.
1257 """
1258
1259 imageBBox = image.getBBox()
1260 imageMI = image.maskedImage
1261
1262 for (fakeImage, xy) in fakeImages:
1263 X0 = xy.getX() - fakeImage.getWidth()/2 + 0.5
1264 Y0 = xy.getY() - fakeImage.getHeight()/2 + 0.5
1265 self.log.debug("Adding fake source at %d, %d", xy.getX(), xy.getY())
1266 if sourceType == "galaxy":
1267 interpFakeImage = afwMath.offsetImage(fakeImage, X0, Y0, "lanczos3")
1268 else:
1269 interpFakeImage = fakeImage
1270
1271 interpFakeImBBox = interpFakeImage.getBBox()
1272 interpFakeImBBox.clip(imageBBox)
1273
1274 if interpFakeImBBox.getArea() > 0:
1275 imageMIView = imageMI[interpFakeImBBox]
1276 clippedFakeImage = interpFakeImage[interpFakeImBBox]
1277 clippedFakeImageMI = afwImage.MaskedImageF(clippedFakeImage)
1278 clippedFakeImageMI.mask.set(self.bitmask)
1279 imageMIView += clippedFakeImageMI
1280
1281 return image
std::shared_ptr< ImageT > offsetImage(ImageT const &image, float dx, float dy, std::string const &algorithmName="lanczos5", unsigned int buffer=0)
Return an image offset by (dx, dy) using the specified algorithm.

◆ addPixCoords()

lsst.pipe.tasks.insertFakes.addPixCoords ( self,
fakeCat,
image )
Add pixel coordinates to the catalog of fakes.

Parameters
----------
fakeCat : `pandas.core.frame.DataFrame`
            The catalog of fake sources to be input
image : `lsst.afw.image.exposure.exposure.ExposureF`
            The image into which the fake sources should be added

Returns
-------
fakeCat : `pandas.core.frame.DataFrame`

Definition at line 1003 of file insertFakes.py.

1003 def addPixCoords(self, fakeCat, image):
1004
1005 """Add pixel coordinates to the catalog of fakes.
1006
1007 Parameters
1008 ----------
1009 fakeCat : `pandas.core.frame.DataFrame`
1010 The catalog of fake sources to be input
1011 image : `lsst.afw.image.exposure.exposure.ExposureF`
1012 The image into which the fake sources should be added
1013
1014 Returns
1015 -------
1016 fakeCat : `pandas.core.frame.DataFrame`
1017 """
1018 wcs = image.getWcs()
1019 ras = fakeCat['ra'].values
1020 decs = fakeCat['dec'].values
1021 xs, ys = wcs.skyToPixelArray(ras, decs)
1022 fakeCat["x"] = xs
1023 fakeCat["y"] = ys
1024
1025 return fakeCat
1026

◆ cleanCat()

lsst.pipe.tasks.insertFakes.cleanCat ( self,
fakeCat,
starCheckVal )
Remove rows from the fakes catalog which have HLR = 0 for either the buldge or disk component,
   also remove galaxies that have Sersic index outside the galsim min and max
   allowed (0.3 <= n <= 6.2).

Parameters
----------
fakeCat : `pandas.core.frame.DataFrame`
            The catalog of fake sources to be input
starCheckVal : `str`, `bytes` or `int`
            The value that is set in the sourceType column to specifiy an object is a star.

Returns
-------
fakeCat : `pandas.core.frame.DataFrame`
            The input catalog of fake sources but with the bad objects removed

Definition at line 1195 of file insertFakes.py.

1195 def cleanCat(self, fakeCat, starCheckVal):
1196 """Remove rows from the fakes catalog which have HLR = 0 for either the buldge or disk component,
1197 also remove galaxies that have Sersic index outside the galsim min and max
1198 allowed (0.3 <= n <= 6.2).
1199
1200 Parameters
1201 ----------
1202 fakeCat : `pandas.core.frame.DataFrame`
1203 The catalog of fake sources to be input
1204 starCheckVal : `str`, `bytes` or `int`
1205 The value that is set in the sourceType column to specifiy an object is a star.
1206
1207 Returns
1208 -------
1209 fakeCat : `pandas.core.frame.DataFrame`
1210 The input catalog of fake sources but with the bad objects removed
1211 """
1212
1213 rowsToKeep = (((fakeCat['bulge_semimajor'] != 0.0) & (fakeCat['disk_semimajor'] != 0.0))
1214 | (fakeCat[self.config.sourceType] == starCheckVal))
1215 numRowsNotUsed = len(fakeCat) - len(np.where(rowsToKeep)[0])
1216 self.log.info("Removing %d rows with HLR = 0 for either the bulge or disk", numRowsNotUsed)
1217 fakeCat = fakeCat[rowsToKeep]
1218
1219 minN = galsim.Sersic._minimum_n
1220 maxN = galsim.Sersic._maximum_n
1221 rowsWithGoodSersic = (((fakeCat['bulge_n'] >= minN) & (fakeCat['bulge_n'] <= maxN)
1222 & (fakeCat['disk_n'] >= minN) & (fakeCat['disk_n'] <= maxN))
1223 | (fakeCat[self.config.sourceType] == starCheckVal))
1224 numRowsNotUsed = len(fakeCat) - len(np.where(rowsWithGoodSersic)[0])
1225 self.log.info("Removing %d rows of galaxies with nBulge or nDisk outside of %0.2f <= n <= %0.2f",
1226 numRowsNotUsed, minN, maxN)
1227 fakeCat = fakeCat[rowsWithGoodSersic]
1228
1229 if self.config.doSubSelectSources:
1230 numRowsNotUsed = len(fakeCat) - len(fakeCat['select'])
1231 self.log.info("Removing %d rows which were not designated as template sources", numRowsNotUsed)
1232 fakeCat = fakeCat[fakeCat['select']]
1233
1234 return fakeCat
1235

◆ mkFakeGalsimGalaxies()

lsst.pipe.tasks.insertFakes.mkFakeGalsimGalaxies ( self,
fakeCat,
band,
photoCalib,
pixelScale,
psf,
image )
Make images of fake galaxies using GalSim.

Parameters
----------
band : `str`
pixelScale : `float`
psf : `lsst.meas.extensions.psfex.psfexPsf.PsfexPsf`
            The PSF information to use to make the PSF images
fakeCat : `pandas.core.frame.DataFrame`
            The catalog of fake sources to be input
photoCalib : `lsst.afw.image.photoCalib.PhotoCalib`
            Photometric calibration to be used to calibrate the fake sources

Yields
------
galImages : `generator`
            A generator of tuples of `lsst.afw.image.exposure.exposure.ExposureF` and
            `lsst.geom.Point2D` of their locations.

Notes
-----

Fake galaxies are made by combining two sersic profiles, one for the bulge and one for the disk. Each
component has an individual sersic index (n), a, b and position angle (PA). The combined profile is
then convolved with the PSF at the specified x, y position on the image.

The names of the columns in the ``fakeCat`` are configurable and are the column names from the
University of Washington simulations database as default. For more information see the doc strings
attached to the config options.

See mkFakeStars doc string for an explanation of calibration to instrumental flux.

Definition at line 1064 of file insertFakes.py.

1064 def mkFakeGalsimGalaxies(self, fakeCat, band, photoCalib, pixelScale, psf, image):
1065 """Make images of fake galaxies using GalSim.
1066
1067 Parameters
1068 ----------
1069 band : `str`
1070 pixelScale : `float`
1071 psf : `lsst.meas.extensions.psfex.psfexPsf.PsfexPsf`
1072 The PSF information to use to make the PSF images
1073 fakeCat : `pandas.core.frame.DataFrame`
1074 The catalog of fake sources to be input
1075 photoCalib : `lsst.afw.image.photoCalib.PhotoCalib`
1076 Photometric calibration to be used to calibrate the fake sources
1077
1078 Yields
1079 ------
1080 galImages : `generator`
1081 A generator of tuples of `lsst.afw.image.exposure.exposure.ExposureF` and
1082 `lsst.geom.Point2D` of their locations.
1083
1084 Notes
1085 -----
1086
1087 Fake galaxies are made by combining two sersic profiles, one for the bulge and one for the disk. Each
1088 component has an individual sersic index (n), a, b and position angle (PA). The combined profile is
1089 then convolved with the PSF at the specified x, y position on the image.
1090
1091 The names of the columns in the ``fakeCat`` are configurable and are the column names from the
1092 University of Washington simulations database as default. For more information see the doc strings
1093 attached to the config options.
1094
1095 See mkFakeStars doc string for an explanation of calibration to instrumental flux.
1096 """
1097
1098 self.log.info("Making %d fake galaxy images", len(fakeCat))
1099
1100 for (index, row) in fakeCat.iterrows():
1101 xy = geom.Point2D(row["x"], row["y"])
1102
1103 # We put these two PSF calculations within this same try block so that we catch cases
1104 # where the object's position is outside of the image.
1105 try:
1106 correctedFlux = psf.computeApertureFlux(self.config.calibFluxRadius, xy)
1107 psfKernel = psf.computeKernelImage(xy).getArray()
1108 psfKernel /= correctedFlux
1109
1110 except InvalidParameterError:
1111 self.log.info("Galaxy at %0.4f, %0.4f outside of image", row["x"], row["y"])
1112 continue
1113
1114 try:
1115 flux = photoCalib.magnitudeToInstFlux(row['mag'], xy)
1116 except LogicError:
1117 flux = 0
1118
1119 # GalSim convention: HLR = sqrt(a * b) = a * sqrt(b / a)
1120 bulge_gs_HLR = row['bulge_semimajor']*np.sqrt(row['bulge_axis_ratio'])
1121 bulge = galsim.Sersic(n=row['bulge_n'], half_light_radius=bulge_gs_HLR)
1122 bulge = bulge.shear(q=row['bulge_axis_ratio'], beta=((90 - row['bulge_pa'])*galsim.degrees))
1123
1124 disk_gs_HLR = row['disk_semimajor']*np.sqrt(row['disk_axis_ratio'])
1125 disk = galsim.Sersic(n=row['disk_n'], half_light_radius=disk_gs_HLR)
1126 disk = disk.shear(q=row['disk_axis_ratio'], beta=((90 - row['disk_pa'])*galsim.degrees))
1127
1128 gal = bulge*row['bulge_disk_flux_ratio'] + disk
1129 gal = gal.withFlux(flux)
1130
1131 psfIm = galsim.InterpolatedImage(galsim.Image(psfKernel), scale=pixelScale)
1132 gal = galsim.Convolve([gal, psfIm])
1133 try:
1134 galIm = gal.drawImage(scale=pixelScale, method="real_space").array
1135 except (galsim.errors.GalSimFFTSizeError, MemoryError):
1136 continue
1137
1138 yield (afwImage.ImageF(galIm), xy)
1139

◆ mkFakeStars()

lsst.pipe.tasks.insertFakes.mkFakeStars ( self,
fakeCat,
band,
photoCalib,
psf,
image )
Make fake stars based off the properties in the fakeCat.

Parameters
----------
band : `str`
psf : `lsst.meas.extensions.psfex.psfexPsf.PsfexPsf`
            The PSF information to use to make the PSF images
fakeCat : `pandas.core.frame.DataFrame`
            The catalog of fake sources to be input
image : `lsst.afw.image.exposure.exposure.ExposureF`
            The image into which the fake sources should be added
photoCalib : `lsst.afw.image.photoCalib.PhotoCalib`
            Photometric calibration to be used to calibrate the fake sources

Yields
------
starImages : `generator`
            A generator of tuples of `lsst.afw.image.ImageF` of fake stars and
            `lsst.geom.Point2D` of their locations.

Notes
-----
To take a given magnitude and translate to the number of counts in the image
we use photoCalib.magnitudeToInstFlux, which returns the instrumental flux for the
given calibration radius used in the photometric calibration step.
Thus `calibFluxRadius` should be set to this same radius so that we can normalize
the PSF model to the correct instrumental flux within calibFluxRadius.

Definition at line 1140 of file insertFakes.py.

1140 def mkFakeStars(self, fakeCat, band, photoCalib, psf, image):
1141
1142 """Make fake stars based off the properties in the fakeCat.
1143
1144 Parameters
1145 ----------
1146 band : `str`
1147 psf : `lsst.meas.extensions.psfex.psfexPsf.PsfexPsf`
1148 The PSF information to use to make the PSF images
1149 fakeCat : `pandas.core.frame.DataFrame`
1150 The catalog of fake sources to be input
1151 image : `lsst.afw.image.exposure.exposure.ExposureF`
1152 The image into which the fake sources should be added
1153 photoCalib : `lsst.afw.image.photoCalib.PhotoCalib`
1154 Photometric calibration to be used to calibrate the fake sources
1155
1156 Yields
1157 ------
1158 starImages : `generator`
1159 A generator of tuples of `lsst.afw.image.ImageF` of fake stars and
1160 `lsst.geom.Point2D` of their locations.
1161
1162 Notes
1163 -----
1164 To take a given magnitude and translate to the number of counts in the image
1165 we use photoCalib.magnitudeToInstFlux, which returns the instrumental flux for the
1166 given calibration radius used in the photometric calibration step.
1167 Thus `calibFluxRadius` should be set to this same radius so that we can normalize
1168 the PSF model to the correct instrumental flux within calibFluxRadius.
1169 """
1170
1171 self.log.info("Making %d fake star images", len(fakeCat))
1172
1173 for (index, row) in fakeCat.iterrows():
1174 xy = geom.Point2D(row["x"], row["y"])
1175
1176 # We put these two PSF calculations within this same try block so that we catch cases
1177 # where the object's position is outside of the image.
1178 try:
1179 correctedFlux = psf.computeApertureFlux(self.config.calibFluxRadius, xy)
1180 starIm = psf.computeImage(xy)
1181 starIm /= correctedFlux
1182
1183 except InvalidParameterError:
1184 self.log.info("Star at %0.4f, %0.4f outside of image", row["x"], row["y"])
1185 continue
1186
1187 try:
1188 flux = photoCalib.magnitudeToInstFlux(row['mag'], xy)
1189 except LogicError:
1190 flux = 0
1191
1192 starIm *= flux
1193 yield ((starIm.convertF(), xy))
1194

◆ processImagesForInsertion()

lsst.pipe.tasks.insertFakes.processImagesForInsertion ( self,
fakeCat,
wcs,
psf,
photoCalib,
band,
pixelScale )
Process images from files into the format needed for insertion.

Parameters
----------
fakeCat : `pandas.core.frame.DataFrame`
            The catalog of fake sources to be input
wcs : `lsst.afw.geom.skyWcs.skyWcs.SkyWc`
            WCS to use to add fake sources
psf : `lsst.meas.algorithms.coaddPsf.coaddPsf.CoaddPsf` or
      `lsst.meas.extensions.psfex.psfexPsf.PsfexPsf`
            The PSF information to use to make the PSF images
photoCalib : `lsst.afw.image.photoCalib.PhotoCalib`
            Photometric calibration to be used to calibrate the fake sources
band : `str`
            The filter band that the observation was taken in.
pixelScale : `float`
            The pixel scale of the image the sources are to be added to.

Returns
-------
galImages : `list`
            A list of tuples of `lsst.afw.image.exposure.exposure.ExposureF` and
            `lsst.geom.Point2D` of their locations.
            For sources labelled as galaxy.
starImages : `list`
            A list of tuples of `lsst.afw.image.exposure.exposure.ExposureF` and
            `lsst.geom.Point2D` of their locations.
            For sources labelled as star.

Notes
-----
The input fakes catalog needs to contain the absolute path to the image in the
band that is being used to add images to. It also needs to have the R.A. and
declination of the fake source in radians and the sourceType of the object.

Definition at line 916 of file insertFakes.py.

916 def processImagesForInsertion(self, fakeCat, wcs, psf, photoCalib, band, pixelScale):
917 """Process images from files into the format needed for insertion.
918
919 Parameters
920 ----------
921 fakeCat : `pandas.core.frame.DataFrame`
922 The catalog of fake sources to be input
923 wcs : `lsst.afw.geom.skyWcs.skyWcs.SkyWc`
924 WCS to use to add fake sources
925 psf : `lsst.meas.algorithms.coaddPsf.coaddPsf.CoaddPsf` or
926 `lsst.meas.extensions.psfex.psfexPsf.PsfexPsf`
927 The PSF information to use to make the PSF images
928 photoCalib : `lsst.afw.image.photoCalib.PhotoCalib`
929 Photometric calibration to be used to calibrate the fake sources
930 band : `str`
931 The filter band that the observation was taken in.
932 pixelScale : `float`
933 The pixel scale of the image the sources are to be added to.
934
935 Returns
936 -------
937 galImages : `list`
938 A list of tuples of `lsst.afw.image.exposure.exposure.ExposureF` and
939 `lsst.geom.Point2D` of their locations.
940 For sources labelled as galaxy.
941 starImages : `list`
942 A list of tuples of `lsst.afw.image.exposure.exposure.ExposureF` and
943 `lsst.geom.Point2D` of their locations.
944 For sources labelled as star.
945
946 Notes
947 -----
948 The input fakes catalog needs to contain the absolute path to the image in the
949 band that is being used to add images to. It also needs to have the R.A. and
950 declination of the fake source in radians and the sourceType of the object.
951 """
952 galImages = []
953 starImages = []
954
955 self.log.info("Processing %d fake images", len(fakeCat))
956
957 for (imFile, sourceType, mag, x, y) in zip(fakeCat[band + "imFilename"].array,
958 fakeCat["sourceType"].array,
959 fakeCat['mag'].array,
960 fakeCat["x"].array, fakeCat["y"].array):
961
962 im = afwImage.ImageF.readFits(imFile)
963
964 xy = geom.Point2D(x, y)
965
966 # We put these two PSF calculations within this same try block so that we catch cases
967 # where the object's position is outside of the image.
968 try:
969 correctedFlux = psf.computeApertureFlux(self.config.calibFluxRadius, xy)
970 psfKernel = psf.computeKernelImage(xy).getArray()
971 psfKernel /= correctedFlux
972
973 except InvalidParameterError:
974 self.log.info("%s at %0.4f, %0.4f outside of image", sourceType, x, y)
975 continue
976
977 psfIm = galsim.InterpolatedImage(galsim.Image(psfKernel), scale=pixelScale)
978 galsimIm = galsim.InterpolatedImage(galsim.Image(im.array), scale=pixelScale)
979 convIm = galsim.Convolve([galsimIm, psfIm])
980
981 try:
982 outIm = convIm.drawImage(scale=pixelScale, method="real_space").array
983 except (galsim.errors.GalSimFFTSizeError, MemoryError):
984 continue
985
986 imSum = np.sum(outIm)
987 divIm = outIm/imSum
988
989 try:
990 flux = photoCalib.magnitudeToInstFlux(mag, xy)
991 except LogicError:
992 flux = 0
993
994 imWithFlux = flux*divIm
995
996 if sourceType == b"galaxy":
997 galImages.append((afwImage.ImageF(imWithFlux), xy))
998 if sourceType == b"star":
999 starImages.append((afwImage.ImageF(imWithFlux), xy))
1000
1001 return galImages, starImages
1002

◆ trimFakeCat()

lsst.pipe.tasks.insertFakes.trimFakeCat ( self,
fakeCat,
image )
Trim the fake cat to the size of the input image plus trimBuffer padding.

`fakeCat` must be processed with addPixCoords before using this method.

Parameters
----------
fakeCat : `pandas.core.frame.DataFrame`
            The catalog of fake sources to be input
image : `lsst.afw.image.exposure.exposure.ExposureF`
            The image into which the fake sources should be added

Returns
-------
fakeCat : `pandas.core.frame.DataFrame`
            The original fakeCat trimmed to the area of the image

Definition at line 1027 of file insertFakes.py.

1027 def trimFakeCat(self, fakeCat, image):
1028 """Trim the fake cat to the size of the input image plus trimBuffer padding.
1029
1030 `fakeCat` must be processed with addPixCoords before using this method.
1031
1032 Parameters
1033 ----------
1034 fakeCat : `pandas.core.frame.DataFrame`
1035 The catalog of fake sources to be input
1036 image : `lsst.afw.image.exposure.exposure.ExposureF`
1037 The image into which the fake sources should be added
1038
1039 Returns
1040 -------
1041 fakeCat : `pandas.core.frame.DataFrame`
1042 The original fakeCat trimmed to the area of the image
1043 """
1044 wideBbox = Box2D(image.getBBox()).dilatedBy(self.config.trimBuffer)
1045
1046 # prefilter in ra/dec to avoid cases where the wcs incorrectly maps
1047 # input fakes which are really off the chip onto it.
1048 ras = fakeCat[self.config.ra_col].values * u.rad
1049 decs = fakeCat[self.config.dec_col].values * u.rad
1050
1051 isContainedRaDec = image.containsSkyCoords(ras, decs, padding=self.config.trimBuffer)
1052
1053 # also filter on the image BBox in pixel space
1054 xs = fakeCat["x"].values
1055 ys = fakeCat["y"].values
1056
1057 isContainedXy = xs >= wideBbox.minX
1058 isContainedXy &= xs <= wideBbox.maxX
1059 isContainedXy &= ys >= wideBbox.minY
1060 isContainedXy &= ys <= wideBbox.maxY
1061
1062 return fakeCat[isContainedRaDec & isContainedXy]
1063

Variable Documentation

◆ bitmask

lsst.pipe.tasks.insertFakes.bitmask

Definition at line 1278 of file insertFakes.py.

◆ linWcs

lsst.pipe.tasks.insertFakes.linWcs = wcs.linearizePixelToSky(skyCoord, geom.arcseconds)

Definition at line 902 of file insertFakes.py.

◆ mat

lsst.pipe.tasks.insertFakes.mat = linWcs.getMatrix()

Definition at line 903 of file insertFakes.py.

◆ obj

lsst.pipe.tasks.insertFakes.obj = galsim.InterpolatedImage(im, calculate_stepk=False)

Definition at line 912 of file insertFakes.py.

◆ wcs

lsst.pipe.tasks.insertFakes.wcs

Definition at line 904 of file insertFakes.py.