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)
353 """This is the python wrapper that reads lsst tables
356 if prefs.getVerboseType() != prefs.QUIET:
357 print(
"----- %d input catalogues:" % prefs.getNcat())
362 fields = psfexLib.vectorField()
363 for cat
in prefs.getCatalogs():
364 field = psfexLib.Field(cat)
366 wcssList.append(wcss)
371 md = readMetadata(calexpFile)
375 cdMatrix = np.array([1.0, 0.0, 0.0, 1.0])
376 cdMatrix.shape = (2, 2)
381 naxis1, naxis2 = md.getScalar(
"NAXIS1"), md.getScalar(
"NAXIS2")
383 md = readMetadata(cat)
385 field.addExt(wcs, naxis1, naxis2, md.getScalar(
"NAXIS2"))
387 wcss.append((wcs, naxis1, naxis2))
396 sets = psfexLib.vectorSet()
400 psfexLib.makeit(fields, sets)
402 ret = [[f.getPsfs()
for f
in fields], sets]
409def read_samplesLsst(prefs, set, filename, frmin, frmax, ext, next, catindex, context, pcval, nobj,
410 plot=dict(showFlags=
False, showRejection=
False)):
413 set = psfexLib.Set(context)
415 cmin, cmax =
None,
None
416 if set.getNcontext():
417 cmin = np.empty(set.getNcontext())
418 cmax = np.empty(set.getNcontext())
419 for i
in range(set.getNcontext()):
421 cmin[i] = set.getContextOffset(i) - set.getContextScale(i)/2.0
422 cmax[i] = cmin[i] + set.getContextScale(i)
424 cmin[i] = psfexLib.BIG
425 cmax[i] = -psfexLib.BIG
429 tab = afwTable.SourceCatalog.readFits(filename)
431 centroid = tab.getCentroidDefinition()
432 xm = tab.get(
"%s.x" % centroid)
433 ym = tab.get(
"%s.y" % centroid)
435 shape = tab.getShapeDefinition()
436 ixx = tab.get(
"%s.xx" % shape)
437 iyy = tab.get(
"%s.yy" % shape)
439 rmsSize = np.sqrt(0.5*(ixx + iyy))
440 elong = 0.5*(ixx - iyy)/(ixx + iyy)
442 flux = tab.get(prefs.getPhotfluxRkey())
443 fluxErr = tab.get(prefs.getPhotfluxerrRkey())
451 set.setVigSize(vigw, vigh)
453 vignet = np.empty(nobj*vigw*vigh,
"float32").reshape(nobj, vigw, vigh)
457 mi = afwImage.MaskedImageF(calexpFile)
458 backnoise2 = np.median(mi.getVariance().getArray())
461 edgeBit = [k
for k, v
in getFlags().
items()
if v ==
"edge"][0]
463 for i, xc, yc
in zip(range(nobj), xm, ym):
465 x, y = int(xc), int(yc)
470 pstamp = mi[x - vigw//2:x + vigw//2 + 1, y - vigh//2:y + vigh//2 + 1]
471 vignet[i] = pstamp.getImage().getArray().transpose()
478 for i, key
in enumerate(context.getName()):
479 if context.getPcflag(i):
480 contextvalp.append(pcval[pc])
484 contextvalp.append(tab.header[key[1:]])
486 raise RuntimeError(
"*Error*: %s parameter not found in the header of %s" %
490 contextvalp.append(tab.get(key))
492 raise RuntimeError(
"*Error*: %s parameter not found in the header of %s" %
494 set.setContextname(i, key)
498 flags, flux, fluxErr, rmsSize, elong, vignet,
499 plot=plot, title=
"%s[%d]" % (filename, ext + 1)
if next > 1
else filename)
503 if not vignet.dtype.isnative:
506 vignet = vignet.byteswap()
508 for i
in np.where(good)[0]:
509 sample = set.newSample()
510 sample.setCatindex(catindex)
511 sample.setExtindex(ext)
513 sample.setVig(vignet[i])
514 sample.setNorm(float(flux[i]))
515 sample.setBacknoise2(backnoise2)
517 sample.setX(float(xm[i]))
518 sample.setY(float(ym[i]))
519 sample.setFluxrad(float(rmsSize[i]))
521 for j
in range(set.getNcontext()):
522 sample.setContext(j, float(contextvalp[j][i]))
524 set.finiSample(sample, prefs.getProfAccuracy())
527 for j
in range(set.getNcontext()):
528 cmin[j] = contextvalp[j][good].
min()
529 cmax[j] = contextvalp[j][good].
max()
533 for i
in range(set.getNcontext()):
534 set.setContextScale(i, cmax[i] - cmin[i])
535 set.setContextOffset(i, (cmin[i] + cmax[i])/2.0)
543def load_samplesLsst(prefs, context, ext=psfexLib.Prefs.ALL_EXTENSIONS, next=1, plot=dict()):
544 minsn = prefs.getMinsn()
545 maxelong = (prefs.getMaxellip() + 1.0)/(1.0 - prefs.getMaxellip())
if prefs.getMaxellip() < 1.0
else 100
546 min = prefs.getFwhmrange()[0]
547 max = prefs.getFwhmrange()[1]
549 filenames = prefs.getCatalogs()
551 ncat = len(filenames)
552 fwhmmin = np.empty(ncat)
553 fwhmmax = np.empty(ncat)
555 if not prefs.getAutoselectFlag():
556 fwhmmin = np.zeros(ncat) + prefs.getFwhmrange()[0]
557 fwhmmax = np.zeros(ncat) + prefs.getFwhmrange()[1]
558 fwhmmode = (fwhmmin + fwhmmax)/2.0
565 for i, fileName
in enumerate(filenames):
568 if prefs.getVerboseType() != prefs.QUIET:
569 print(
"Examining Catalog #%d" % (i+1))
572 tab = afwTable.SourceCatalog.readFits(fileName)
575 shape = tab.getShapeDefinition()
576 ixx = tab.get(
"%s.xx" % shape)
577 iyy = tab.get(
"%s.yy" % shape)
579 rmsSize = np.sqrt(0.5*(ixx + iyy))
580 elong = 0.5*(ixx - iyy)/(ixx + iyy)
582 flux = tab.get(prefs.getPhotfluxRkey())
583 fluxErr = tab.get(prefs.getPhotfluxerrRkey())
587 good = np.logical_and(flux/fluxErr > minsn,
588 np.logical_not(flags & prefs.getFlagMask()))
589 good = np.logical_and(good, elong < maxelong)
591 good = np.logical_and(good, fwhm >= min)
592 good = np.logical_and(good, fwhm < max)
593 fwhms[i] = fwhm[good]
595 if prefs.getVarType() == prefs.VAR_NONE:
597 fwhms_all = np.empty(sum([len(f)
for f
in fwhms.values()]))
599 for f
in fwhms.values():
600 fwhms_all[i:len(f)] = f
602 mode, min, max = compute_fwhmrange(fwhms_all, prefs.getMaxvar(),
603 prefs.getFwhmrange()[0], prefs.getFwhmrange()[1],
606 raise RuntimeError(
"No source with appropriate FWHM found!!")
607 mode = min = max = 2.35/(1.0 - 1.0/psfexLib.cvar.INTERPFAC)
609 fwhmmin = np.zeros(ncat) + min
610 fwhmmax = np.zeros(ncat) + max
611 fwhmmode = np.zeros(ncat) + mode
613 fwhmmode = np.empty(ncat)
614 fwhmmin = np.empty(ncat)
615 fwhmmax = np.empty(ncat)
617 for i
in range(ncat):
620 fwhmmode[i], fwhmmin[i], fwhmmax[i] = \
621 compute_fwhmrange(fwhms[i], prefs.getMaxvar(),
622 prefs.getFwhmrange()[0], prefs.getFwhmrange()[1], plot=plot)
624 raise RuntimeError(
"No source with appropriate FWHM found!!")
625 fwhmmode[i] = fwhmmin[i] = fwhmmax[i] = 2.35/(1.0 - 1.0/psfexLib.cvar.INTERPFAC)
631 for i, fileName
in enumerate(filenames):
633 for ext
in range(next):
634 set =
read_samplesLsst(prefs, set, fileName, fwhmmin[i]/2.0, fwhmmax[i]/2.0,
635 ext, next, i, context,
636 context.getPc(i)
if context.getNpc()
else None, nobj, plot=plot)
638 if fwhmmode[i] < mode:
643 if prefs.getVerboseType() != prefs.QUIET:
645 print(
"%d samples loaded." % set.getNsample())
647 raise RuntimeError(
"No appropriate source found!!")