LSST Applications g0265f82a02+0e5473021a,g02d81e74bb+0dd8ce4237,g1470d8bcf6+3ea6592b6f,g2079a07aa2+86d27d4dc4,g2305ad1205+5ca4c0b359,g295015adf3+d10818ec9d,g2a9a014e59+6f9be1b9cd,g2bbee38e9b+0e5473021a,g337abbeb29+0e5473021a,g3ddfee87b4+703ba97ebf,g487adcacf7+4fa16da234,g50ff169b8f+96c6868917,g52b1c1532d+585e252eca,g591dd9f2cf+ffa42b374e,g5a732f18d5+53520f316c,g64a986408d+0dd8ce4237,g858d7b2824+0dd8ce4237,g8a8a8dda67+585e252eca,g99cad8db69+d39438377f,g9ddcbc5298+9a081db1e4,ga1e77700b3+15fc3df1f7,ga8c6da7877+f1d96605c8,gb0e22166c9+60f28cb32d,gb6a65358fc+0e5473021a,gba4ed39666+c2a2e4ac27,gbb8dafda3b+e5339d463f,gc120e1dc64+da31e9920e,gc28159a63d+0e5473021a,gcf0d15dbbd+703ba97ebf,gdaeeff99f8+f9a426f77a,ge6526c86ff+889fc9d533,ge79ae78c31+0e5473021a,gee10cc3b42+585e252eca,gf18bd8381d+7268b93478,gff1a9f87cc+0dd8ce4237,w.2024.16
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 : `lsst.log.log.log.Log` or `logging.Logger`, optional
    Logger.

Definition at line 44 of file insertFakes.py.

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

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

◆ 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 1224 of file insertFakes.py.

1224 def addFakeSources(self, image, fakeImages, sourceType):
1225 """Add the fake sources to the given image
1226
1227 Parameters
1228 ----------
1229 image : `lsst.afw.image.exposure.exposure.ExposureF`
1230 The image into which the fake sources should be added
1231 fakeImages : `typing.Iterator` [`tuple` ['lsst.afw.image.ImageF`, `lsst.geom.Point2d`]]
1232 An iterator of tuples that contains (or generates) images of fake sources,
1233 and the locations they are to be inserted at.
1234 sourceType : `str`
1235 The type (star/galaxy) of fake sources input
1236
1237 Returns
1238 -------
1239 image : `lsst.afw.image.exposure.exposure.ExposureF`
1240
1241 Notes
1242 -----
1243 Uses the x, y information in the ``fakeCat`` to position an image of the fake interpolated onto the
1244 pixel grid of the image. Sets the ``FAKE`` mask plane for the pixels added with the fake source.
1245 """
1246
1247 imageBBox = image.getBBox()
1248 imageMI = image.maskedImage
1249
1250 for (fakeImage, xy) in fakeImages:
1251 X0 = xy.getX() - fakeImage.getWidth()/2 + 0.5
1252 Y0 = xy.getY() - fakeImage.getHeight()/2 + 0.5
1253 self.log.debug("Adding fake source at %d, %d", xy.getX(), xy.getY())
1254 if sourceType == "galaxy":
1255 interpFakeImage = afwMath.offsetImage(fakeImage, X0, Y0, "lanczos3")
1256 else:
1257 interpFakeImage = fakeImage
1258
1259 interpFakeImBBox = interpFakeImage.getBBox()
1260 interpFakeImBBox.clip(imageBBox)
1261
1262 if interpFakeImBBox.getArea() > 0:
1263 imageMIView = imageMI[interpFakeImBBox]
1264 clippedFakeImage = interpFakeImage[interpFakeImBBox]
1265 clippedFakeImageMI = afwImage.MaskedImageF(clippedFakeImage)
1266 clippedFakeImageMI.mask.set(self.bitmask)
1267 imageMIView += clippedFakeImageMI
1268
1269 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 991 of file insertFakes.py.

991 def addPixCoords(self, fakeCat, image):
992
993 """Add pixel coordinates to the catalog of fakes.
994
995 Parameters
996 ----------
997 fakeCat : `pandas.core.frame.DataFrame`
998 The catalog of fake sources to be input
999 image : `lsst.afw.image.exposure.exposure.ExposureF`
1000 The image into which the fake sources should be added
1001
1002 Returns
1003 -------
1004 fakeCat : `pandas.core.frame.DataFrame`
1005 """
1006 wcs = image.getWcs()
1007 ras = fakeCat['ra'].values
1008 decs = fakeCat['dec'].values
1009 xs, ys = wcs.skyToPixelArray(ras, decs)
1010 fakeCat["x"] = xs
1011 fakeCat["y"] = ys
1012
1013 return fakeCat
1014

◆ 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 1183 of file insertFakes.py.

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

◆ 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 1052 of file insertFakes.py.

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

◆ 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 1128 of file insertFakes.py.

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

◆ 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 904 of file insertFakes.py.

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

◆ 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 1015 of file insertFakes.py.

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

Variable Documentation

◆ bitmask

lsst.pipe.tasks.insertFakes.bitmask

Definition at line 1266 of file insertFakes.py.

◆ linWcs

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

Definition at line 890 of file insertFakes.py.

◆ mat

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

Definition at line 891 of file insertFakes.py.

◆ obj

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

Definition at line 900 of file insertFakes.py.

◆ wcs

lsst.pipe.tasks.insertFakes.wcs

Definition at line 892 of file insertFakes.py.