111 flags, flux, fluxerr, rmsSize, elong, vignet,
112 plot=dict(), title=
""):
113 maxbad = prefs.getBadpixNmax()
114 maxbadflag = prefs.getBadpixFlag()
115 maxelong = (prefs.getMaxellip() + 1.0)/(1.0 - prefs.getMaxellip())
if prefs.getMaxellip() < 1.0
else 100.0
116 minsn = prefs.getMinsn()
118 sn = flux/np.where(fluxerr > 0, fluxerr, 1)
119 sn[fluxerr <= 0] = -psfexLib.BIG
121 plotFlags = plot.get(
"showFlags")
if plt
else False
122 plotRejection = plot.get(
"showRejection")
if plt
else False
124 bad = flags & prefs.getFlagMask() != 0
125 set.setBadFlags(int(sum(bad != 0)))
128 selectionVectors = []
129 selectionVectors.append((bad,
"flags %d" % sum(bad != 0)))
132 set.setBadSN(int(sum(dbad)))
133 bad = np.logical_or(bad, dbad)
135 selectionVectors.append((dbad,
"S/N %d" % sum(dbad)))
137 dbad = rmsSize < frmin
138 set.setBadFrmin(int(sum(dbad)))
139 bad = np.logical_or(bad, dbad)
141 selectionVectors.append((dbad,
"frmin %d" % sum(dbad)))
143 dbad = rmsSize > frmax
144 set.setBadFrmax(int(sum(dbad)))
145 bad = np.logical_or(bad, dbad)
147 selectionVectors.append((dbad,
"frmax %d" % sum(dbad)))
149 dbad = elong > maxelong
150 set.setBadElong(int(sum(dbad)))
151 bad = np.logical_or(bad, dbad)
153 selectionVectors.append((dbad,
"elong %d" % sum(dbad)))
157 nbad = np.array([(v <= -psfexLib.BIG).sum()
for v
in vignet])
159 set.setBadPix(int(sum(dbad)))
160 bad = np.logical_or(bad, dbad)
162 selectionVectors.append((dbad,
"badpix %d" % sum(dbad)))
164 good = np.logical_not(bad)
165 if plotFlags
or plotRejection:
166 imag = -2.5*np.log10(flux)
173 isSet = np.where(flags == 0x0)[0]
174 plt.plot(imag[isSet], rmsSize[isSet],
'o', alpha=alpha, label=
"good")
178 if mask & prefs.getFlagMask():
179 isSet = np.where(np.bitwise_and(flags, mask))[0]
181 plt.plot(imag[isSet], rmsSize[isSet],
'o', alpha=alpha, label=labels[mask])
183 for bad, label
in selectionVectors:
184 plt.plot(imag[bad], rmsSize[bad],
'o', alpha=alpha, label=label)
186 plt.plot(imag[good], rmsSize[good],
'o', color=
"black", label=
"selected")
187 [plt.axhline(_, color=
'red')
for _
in [frmin, frmax]]
188 plt.xlim(np.median(imag[good]) + 5*np.array([-1, 1]))
189 plt.ylim(-0.1, 2*frmax)
191 plt.xlabel(
"Instrumental Magnitude")
192 plt.ylabel(
"rmsSize")
193 plt.title(
"%s %d selected" % (title, sum(good)))
200def showPsf(psf, set, ext=None, wcsData=None, trim=0, nspot=5,
201 diagnostics=False, outDir="", frame=None, title=None):
202 """Show a PSF on display (e.g., ds9)
210 wcsData = wcsData[ext]
211 wcs, naxis1, naxis2 = wcsData
213 wcs, naxis1, naxis2 =
None,
None,
None
215 naxis = [naxis1, naxis2]
219 cmin, cmax = [set.getContextOffset(i) + d*set.getContextScale(i)
for d
in (-0.5, 0.5)]
220 naxis[i] = cmax + cmin
222 if naxis[0] > naxis[1]:
223 nx, ny = int(nspot*naxis[0]/float(naxis[1]) + 0.5), nspot
225 nx, ny = nspot, int(nspot*naxis[1]/float(naxis[0]) + 0.5)
227 mos = afwDisplay.utils.Mosaic(gutter=2, background=0.02)
229 xpos, ypos = np.linspace(0, naxis[0], nx), np.linspace(0, naxis[1], ny)
234 im = afwImage.ImageF(*psf.getLoc().shape)
235 im.getArray()[:] = psf.getLoc()
236 im /= float(im.getArray().max())
238 if trim > im.getHeight()//2:
239 trim = im.getHeight()//2
241 im = im[trim:-trim, trim:-trim]
245 mosaic = mos.makeMosaic(mode=nx)
246 if frame
is not None:
247 afwDisplay.Display(frame=frame).mtv(mosaic, title=title)
257 delta = pos[1][1][i].asDegrees() - pos[0][1][i].asDegrees()
258 CD.append(delta/(pos[1][0][i] - pos[0][0][i]))
264 title =
"%s-%d" % (title, ext)
266 if frame
is not None:
267 afwDisplay.Display(frame=frame).mtv(mosaic, title=title, wcs=mosWcs)
270 outFile =
"%s-mod.fits" % title
272 outFile = os.path.join(outDir, outFile)
273 mosaic.writeFits(outFile, mosWcs.getFitsMetadata())
275 mos = afwDisplay.utils.Mosaic(gutter=4, background=0.002)
276 for i
in range(set.getNsample()):
278 if ext
is not None and s.getExtindex() != ext:
281 smos = afwDisplay.utils.Mosaic(gutter=2, background=-0.003)
282 for func
in [s.getVig, s.getVigResi]:
285 norm = float(arr.max())
if True else s.getNorm()
288 im = afwImage.ImageF(*arr.shape)
289 im.getArray()[:] = arr
292 mos.append(smos.makeMosaic(mode=
"x"))
294 mosaic = mos.makeMosaic(title=title)
296 if frame
is not None:
297 afwDisplay.Display(frame=frame + 1).mtv(mosaic, title=title)
300 outFile =
"%s-psfstars.fits" % title
302 outFile = os.path.join(outDir, outFile)
304 mosaic.writeFits(outFile)
354 """This is the python wrapper that reads lsst tables
357 if prefs.getVerboseType() != prefs.QUIET:
358 print(
"----- %d input catalogues:" % prefs.getNcat())
363 fields = psfexLib.vectorField()
364 for cat
in prefs.getCatalogs():
365 field = psfexLib.Field(cat)
367 wcssList.append(wcss)
372 md = readMetadata(calexpFile)
376 cdMatrix = np.array([1.0, 0.0, 0.0, 1.0])
377 cdMatrix.shape = (2, 2)
382 naxis1, naxis2 = md.getScalar(
"NAXIS1"), md.getScalar(
"NAXIS2")
384 md = readMetadata(cat)
386 field.addExt(wcs, naxis1, naxis2, md.getScalar(
"NAXIS2"))
388 wcss.append((wcs, naxis1, naxis2))
397 sets = psfexLib.vectorSet()
401 psfexLib.makeit(fields, sets)
403 ret = [[f.getPsfs()
for f
in fields], sets]
410def read_samplesLsst(prefs, set, filename, frmin, frmax, ext, next, catindex, context, pcval, nobj,
411 plot=dict(showFlags=
False, showRejection=
False)):
414 set = psfexLib.Set(context)
416 cmin, cmax =
None,
None
417 if set.getNcontext():
418 cmin = np.empty(set.getNcontext())
419 cmax = np.empty(set.getNcontext())
420 for i
in range(set.getNcontext()):
422 cmin[i] = set.getContextOffset(i) - set.getContextScale(i)/2.0
423 cmax[i] = cmin[i] + set.getContextScale(i)
425 cmin[i] = psfexLib.BIG
426 cmax[i] = -psfexLib.BIG
430 tab = afwTable.SourceCatalog.readFits(filename)
432 centroid = tab.getCentroidDefinition()
433 xm = tab.get(
"%s.x" % centroid)
434 ym = tab.get(
"%s.y" % centroid)
436 shape = tab.getShapeDefinition()
437 ixx = tab.get(
"%s.xx" % shape)
438 iyy = tab.get(
"%s.yy" % shape)
440 rmsSize = np.sqrt(0.5*(ixx + iyy))
441 elong = 0.5*(ixx - iyy)/(ixx + iyy)
443 flux = tab.get(prefs.getPhotfluxRkey())
444 fluxErr = tab.get(prefs.getPhotfluxerrRkey())
452 set.setVigSize(vigw, vigh)
454 vignet = np.empty(nobj*vigw*vigh,
"float32").reshape(nobj, vigw, vigh)
458 mi = afwImage.MaskedImageF(calexpFile)
459 backnoise2 = np.median(mi.getVariance().getArray())
462 edgeBit = [k
for k, v
in getFlags().items()
if v ==
"edge"][0]
464 for i, xc, yc
in zip(range(nobj), xm, ym):
466 x, y = int(xc), int(yc)
471 pstamp = mi[x - vigw//2:x + vigw//2 + 1, y - vigh//2:y + vigh//2 + 1]
472 vignet[i] = pstamp.getImage().getArray().transpose()
479 for i, key
in enumerate(context.getName()):
480 if context.getPcflag(i):
481 contextvalp.append(pcval[pc])
485 contextvalp.append(tab.header[key[1:]])
487 raise RuntimeError(
"*Error*: %s parameter not found in the header of %s" %
491 contextvalp.append(tab.get(key))
493 raise RuntimeError(
"*Error*: %s parameter not found in the header of %s" %
495 set.setContextname(i, key)
499 flags, flux, fluxErr, rmsSize, elong, vignet,
500 plot=plot, title=
"%s[%d]" % (filename, ext + 1)
if next > 1
else filename)
504 if not vignet.dtype.isnative:
507 vignet = vignet.byteswap()
509 for i
in np.where(good)[0]:
510 sample = set.newSample()
511 sample.setCatindex(catindex)
512 sample.setExtindex(ext)
514 sample.setVig(vignet[i])
515 sample.setNorm(float(flux[i]))
516 sample.setBacknoise2(backnoise2)
518 sample.setX(float(xm[i]))
519 sample.setY(float(ym[i]))
520 sample.setFluxrad(float(rmsSize[i]))
522 for j
in range(set.getNcontext()):
523 sample.setContext(j, float(contextvalp[j][i]))
525 set.finiSample(sample, prefs.getProfAccuracy())
528 for j
in range(set.getNcontext()):
529 cmin[j] = contextvalp[j][good].min()
530 cmax[j] = contextvalp[j][good].max()
534 for i
in range(set.getNcontext()):
535 set.setContextScale(i, cmax[i] - cmin[i])
536 set.setContextOffset(i, (cmin[i] + cmax[i])/2.0)
544def load_samplesLsst(prefs, context, ext=psfexLib.Prefs.ALL_EXTENSIONS, next=1, plot=dict()):
545 minsn = prefs.getMinsn()
546 maxelong = (prefs.getMaxellip() + 1.0)/(1.0 - prefs.getMaxellip())
if prefs.getMaxellip() < 1.0
else 100
547 min = prefs.getFwhmrange()[0]
548 max = prefs.getFwhmrange()[1]
550 filenames = prefs.getCatalogs()
552 ncat = len(filenames)
553 fwhmmin = np.empty(ncat)
554 fwhmmax = np.empty(ncat)
556 if not prefs.getAutoselectFlag():
557 fwhmmin = np.zeros(ncat) + prefs.getFwhmrange()[0]
558 fwhmmax = np.zeros(ncat) + prefs.getFwhmrange()[1]
559 fwhmmode = (fwhmmin + fwhmmax)/2.0
566 for i, fileName
in enumerate(filenames):
569 if prefs.getVerboseType() != prefs.QUIET:
570 print(
"Examining Catalog #%d" % (i+1))
573 tab = afwTable.SourceCatalog.readFits(fileName)
576 shape = tab.getShapeDefinition()
577 ixx = tab.get(
"%s.xx" % shape)
578 iyy = tab.get(
"%s.yy" % shape)
580 rmsSize = np.sqrt(0.5*(ixx + iyy))
581 elong = 0.5*(ixx - iyy)/(ixx + iyy)
583 flux = tab.get(prefs.getPhotfluxRkey())
584 fluxErr = tab.get(prefs.getPhotfluxerrRkey())
588 good = np.logical_and(flux/fluxErr > minsn,
589 np.logical_not(flags & prefs.getFlagMask()))
590 good = np.logical_and(good, elong < maxelong)
592 good = np.logical_and(good, fwhm >= min)
593 good = np.logical_and(good, fwhm < max)
594 fwhms[i] = fwhm[good]
596 if prefs.getVarType() == prefs.VAR_NONE:
598 fwhms_all = np.empty(sum([len(f)
for f
in fwhms.values()]))
600 for f
in fwhms.values():
601 fwhms_all[i:len(f)] = f
604 prefs.getFwhmrange()[0], prefs.getFwhmrange()[1],
607 raise RuntimeError(
"No source with appropriate FWHM found!!")
608 mode = min = max = 2.35/(1.0 - 1.0/psfexLib.cvar.INTERPFAC)
610 fwhmmin = np.zeros(ncat) + min
611 fwhmmax = np.zeros(ncat) + max
612 fwhmmode = np.zeros(ncat) + mode
614 fwhmmode = np.empty(ncat)
615 fwhmmin = np.empty(ncat)
616 fwhmmax = np.empty(ncat)
618 for i
in range(ncat):
621 fwhmmode[i], fwhmmin[i], fwhmmax[i] = \
623 prefs.getFwhmrange()[0], prefs.getFwhmrange()[1], plot=plot)
625 raise RuntimeError(
"No source with appropriate FWHM found!!")
626 fwhmmode[i] = fwhmmin[i] = fwhmmax[i] = 2.35/(1.0 - 1.0/psfexLib.cvar.INTERPFAC)
632 for i, fileName
in enumerate(filenames):
634 for ext
in range(next):
635 set =
read_samplesLsst(prefs, set, fileName, fwhmmin[i]/2.0, fwhmmax[i]/2.0,
636 ext, next, i, context,
637 context.getPc(i)
if context.getNpc()
else None, nobj, plot=plot)
639 if fwhmmode[i] < mode:
644 if prefs.getVerboseType() != prefs.QUIET:
646 print(
"%d samples loaded." % set.getNsample())
648 raise RuntimeError(
"No appropriate source found!!")