Coverage for python/lsst/summit/utils/utils.py: 17%
330 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-07-10 12:26 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-07-10 12:26 +0000
1# This file is part of summit_utils.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (https://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 <https://www.gnu.org/licenses/>.
22import os
23from typing import Iterable
24import numpy as np
25import logging
26from scipy.ndimage import gaussian_filter
27import lsst.afw.image as afwImage
28import lsst.afw.detection as afwDetect
29from lsst.afw.detection import Footprint, FootprintSet
30import lsst.afw.math as afwMath
31import lsst.daf.base as dafBase
32import lsst.geom as geom
33import lsst.pipe.base as pipeBase
34import lsst.utils.packages as packageUtils
35from lsst.daf.butler.cli.cliLog import CliLog
36import datetime
37from dateutil.tz import gettz
39from lsst.obs.lsst.translators.lsst import FILTER_DELIMITER
40from lsst.obs.lsst.translators.latiss import AUXTEL_LOCATION
42from astro_metadata_translator import ObservationInfo
43from astropy.coordinates import SkyCoord, AltAz
44from astropy.coordinates.earth import EarthLocation
45import astropy.units as u
46from astropy.time import Time
48from .astrometry.utils import genericCameraHeaderToWcs
50__all__ = ["SIGMATOFWHM",
51 "FWHMTOSIGMA",
52 "EFD_CLIENT_MISSING_MSG",
53 "GOOGLE_CLOUD_MISSING_MSG",
54 "AUXTEL_LOCATION",
55 "countPixels",
56 "quickSmooth",
57 "argMax2d",
58 "getImageStats",
59 "detectObjectsInExp",
60 "humanNameForCelestialObject",
61 "getFocusFromHeader",
62 "dayObsIntToString",
63 "dayObsSeqNumToVisitId",
64 "setupLogging",
65 "getCurrentDayObs_datetime",
66 "getCurrentDayObs_int",
67 "getCurrentDayObs_humanStr",
68 "getSite",
69 "getExpPositionOffset",
70 "starTrackerFileToExposure",
71 "getAirmassSeeingCorrection",
72 "getFilterSeeingCorrection",
73 "getCdf",
74 "getQuantiles",
75 "digitizeData",
76 ]
79SIGMATOFWHM = 2.0*np.sqrt(2.0*np.log(2.0))
80FWHMTOSIGMA = 1/SIGMATOFWHM
82EFD_CLIENT_MISSING_MSG = ('ImportError: lsst_efd_client not found. Please install with:\n'
83 ' pip install lsst-efd-client')
85GOOGLE_CLOUD_MISSING_MSG = ('ImportError: Google cloud storage not found. Please install with:\n'
86 ' pip install google-cloud-storage')
89def countPixels(maskedImage, maskPlane):
90 """Count the number of pixels in an image with a given mask bit set.
92 Parameters
93 ----------
94 maskedImage : `lsst.afw.image.MaskedImage`
95 The masked image,
96 maskPlane : `str`
97 The name of the bitmask.
99 Returns
100 -------
101 count : `int``
102 The number of pixels in with the selected mask bit
103 """
104 bit = maskedImage.mask.getPlaneBitMask(maskPlane)
105 return len(np.where(np.bitwise_and(maskedImage.mask.array, bit))[0])
108def quickSmooth(data, sigma=2):
109 """Perform a quick smoothing of the image.
111 Not to be used for scientific purposes, but improves the stretch and
112 visual rendering of low SNR against the sky background in cutouts.
114 Parameters
115 ----------
116 data : `np.array`
117 The image data to smooth
118 sigma : `float`, optional
119 The size of the smoothing kernel.
121 Returns
122 -------
123 smoothData : `np.array`
124 The smoothed data
125 """
126 kernel = [sigma, sigma]
127 smoothData = gaussian_filter(data, kernel, mode='constant')
128 return smoothData
131def argMax2d(array):
132 """Get the index of the max value of an array and whether it's unique.
134 If its not unique, returns a list of the other locations containing the
135 maximum value, e.g. returns
137 (12, 34), False, [(56,78), (910, 1112)]
139 Parameters
140 ----------
141 array : `np.array`
142 The data
144 Returns
145 -------
146 maxLocation : `tuple`
147 The coords of the first instance of the max value
148 unique : `bool`
149 Whether it's the only location
150 otherLocations : `list` of `tuple`
151 List of the other max values' locations, empty if False
152 """
153 uniqueMaximum = False
154 maxCoords = np.where(array == np.max(array))
155 maxCoords = [coord for coord in zip(*maxCoords)] # list of coords as tuples
156 if len(maxCoords) == 1: # single unambiguous value
157 uniqueMaximum = True
159 return maxCoords[0], uniqueMaximum, maxCoords[1:]
162def dayObsIntToString(dayObs):
163 """Convert an integer dayObs to a dash-delimited string.
165 e.g. convert the hard to read 20210101 to 2021-01-01
167 Parameters
168 ----------
169 dayObs : `int`
170 The dayObs.
172 Returns
173 -------
174 dayObs : `str`
175 The dayObs as a string.
176 """
177 assert isinstance(dayObs, int)
178 dStr = str(dayObs)
179 assert len(dStr) == 8
180 return '-'.join([dStr[0:4], dStr[4:6], dStr[6:8]])
183def dayObsSeqNumToVisitId(dayObs, seqNum):
184 """Get the visit id for a given dayObs/seqNum.
186 Parameters
187 ----------
188 dayObs : `int`
189 The dayObs.
190 seqNum : `int`
191 The seqNum.
193 Returns
194 -------
195 visitId : `int`
196 The visitId.
198 Notes
199 -----
200 TODO: Remove this horrible hack once DM-30948 makes this possible
201 programatically/via the butler.
202 """
203 if dayObs < 19700101 or dayObs > 35000101:
204 raise ValueError(f'dayObs value {dayObs} outside plausible range')
205 return int(f"{dayObs}{seqNum:05}")
208def getImageStats(exp):
209 """Calculate a grab-bag of stats for an image. Must remain fast.
211 Parameters
212 ----------
213 exp : `lsst.afw.image.Exposure`
214 The input exposure.
216 Returns
217 -------
218 stats : `lsst.pipe.base.Struct`
219 A container with attributes containing measurements and statistics
220 for the image.
221 """
222 result = pipeBase.Struct()
224 vi = exp.visitInfo
225 expTime = vi.exposureTime
226 md = exp.getMetadata()
228 obj = vi.object
229 mjd = vi.getDate().get()
230 result.object = obj
231 result.mjd = mjd
233 fullFilterString = exp.filter.physicalLabel
234 filt = fullFilterString.split(FILTER_DELIMITER)[0]
235 grating = fullFilterString.split(FILTER_DELIMITER)[1]
237 airmass = vi.getBoresightAirmass()
238 rotangle = vi.getBoresightRotAngle().asDegrees()
240 azAlt = vi.getBoresightAzAlt()
241 az = azAlt[0].asDegrees()
242 el = azAlt[1].asDegrees()
244 result.expTime = expTime
245 result.filter = filt
246 result.grating = grating
247 result.airmass = airmass
248 result.rotangle = rotangle
249 result.az = az
250 result.el = el
251 result.focus = md.get('FOCUSZ')
253 data = exp.image.array
254 result.maxValue = np.max(data)
256 peak, uniquePeak, otherPeaks = argMax2d(data)
257 result.maxPixelLocation = peak
258 result.multipleMaxPixels = uniquePeak
260 result.nBadPixels = countPixels(exp.maskedImage, 'BAD')
261 result.nSatPixels = countPixels(exp.maskedImage, 'SAT')
262 result.percentile99 = np.percentile(data, 99)
263 result.percentile9999 = np.percentile(data, 99.99)
265 sctrl = afwMath.StatisticsControl()
266 sctrl.setNumSigmaClip(5)
267 sctrl.setNumIter(2)
268 statTypes = afwMath.MEANCLIP | afwMath.STDEVCLIP
269 stats = afwMath.makeStatistics(exp.maskedImage, statTypes, sctrl)
270 std, stderr = stats.getResult(afwMath.STDEVCLIP)
271 mean, meanerr = stats.getResult(afwMath.MEANCLIP)
273 result.clippedMean = mean
274 result.clippedStddev = std
276 return result
279def detectObjectsInExp(exp, nSigma=10, nPixMin=10, grow=0):
280 """Quick and dirty object detection for an expsure.
282 Return the footPrintSet for the objects in a preferably-postISR exposure.
284 Parameters
285 ----------
286 exp : `lsst.afw.image.Exposure`
287 The exposure to detect objects in.
288 nSigma : `float`
289 The number of sigma for detection.
290 nPixMin : `int`
291 The minimum number of pixels in an object for detection.
292 grow : `int`
293 The number of pixels to grow the footprint by after detection.
295 Returns
296 -------
297 footPrintSet : `lsst.afw.detection.FootprintSet`
298 The set of footprints in the image.
299 """
300 median = np.nanmedian(exp.image.array)
301 exp.image -= median
303 threshold = afwDetect.Threshold(nSigma, afwDetect.Threshold.STDEV)
304 footPrintSet = afwDetect.FootprintSet(exp.getMaskedImage(), threshold, "DETECTED", nPixMin)
305 if grow > 0:
306 isotropic = True
307 footPrintSet = afwDetect.FootprintSet(footPrintSet, grow, isotropic)
309 exp.image += median # add back in to leave background unchanged
310 return footPrintSet
313def fluxesFromFootprints(footprints, parentImage, subtractImageMedian=False):
314 """Calculate the flux from a set of footprints, given the parent image,
315 optionally subtracting the whole-image median from each pixel as a very
316 rough background subtraction.
318 Parameters
319 ----------
320 footprints : `lsst.afw.detection.FootprintSet` or
321 `lsst.afw.detection.Footprint` or
322 `iterable` of `lsst.afw.detection.Footprint`
323 The footprints to measure.
324 parentImage : `lsst.afw.image.Image`
325 The parent image.
326 subtractImageMedian : `bool`, optional
327 Subtract a whole-image median from each pixel in the footprint when
328 summing as a very crude background subtraction. Does not change the
329 original image.
331 Returns
332 -------
333 fluxes : `list` of `float`
334 The fluxes for each footprint.
336 Raises
337 ------
338 TypeError : raise for unsupported types.
339 """
340 median = 0
341 if subtractImageMedian:
342 median = np.nanmedian(parentImage.array)
344 # poor person's single dispatch
345 badTypeMsg = ("This function works with FootprintSets, single Footprints, and iterables of Footprints. "
346 f"Got {type(footprints)}: {footprints}")
347 if isinstance(footprints, FootprintSet):
348 footprints = footprints.getFootprints()
349 elif isinstance(footprints, Iterable):
350 if not isinstance(footprints[0], Footprint):
351 raise TypeError(badTypeMsg)
352 elif isinstance(footprints, Footprint):
353 footprints = [footprints]
354 else:
355 raise TypeError(badTypeMsg)
357 return np.array([fluxFromFootprint(fp, parentImage, backgroundValue=median) for fp in footprints])
360def fluxFromFootprint(footprint, parentImage, backgroundValue=0):
361 """Calculate the flux from a footprint, given the parent image, optionally
362 subtracting a single value from each pixel as a very rough background
363 subtraction, e.g. the image median.
365 Parameters
366 ----------
367 footprint : `lsst.afw.detection.Footprint`
368 The footprint to measure.
369 parentImage : `lsst.afw.image.Image`
370 Image containing the footprint.
371 backgroundValue : `bool`, optional
372 The value to subtract from each pixel in the footprint when summing
373 as a very crude background subtraction. Does not change the original
374 image.
376 Returns
377 -------
378 flux : `float`
379 The flux in the footprint
380 """
381 if backgroundValue: # only do the subtraction if non-zero for speed
382 xy0 = parentImage.getBBox().getMin()
383 return footprint.computeFluxFromArray(parentImage.array - backgroundValue, xy0)
384 return footprint.computeFluxFromImage(parentImage)
387def humanNameForCelestialObject(objName):
388 """Returns a list of all human names for obj, or [] if none are found.
390 Parameters
391 ----------
392 objName : `str`
393 The/a name of the object.
395 Returns
396 -------
397 names : `list` of `str`
398 The names found for the object
399 """
400 from astroquery.simbad import Simbad
401 results = []
402 try:
403 simbadResult = Simbad.query_objectids(objName)
404 for row in simbadResult:
405 if row['ID'].startswith('NAME'):
406 results.append(row['ID'].replace('NAME ', ''))
407 return results
408 except Exception:
409 return [] # same behavior as for found but un-named objects
412def _getAltAzZenithsFromSeqNum(butler, dayObs, seqNumList):
413 """Get the alt, az and zenith angle for the seqNums of a given dayObs.
415 Parameters
416 ----------
417 butler : `lsst.daf.butler.Butler`
418 The butler to query.
419 dayObs : `int`
420 The dayObs.
421 seqNumList : `list` of `int`
422 The seqNums for which to return the alt, az and zenith
424 Returns
425 -------
426 azimuths : `list` of `float`
427 List of the azimuths for each seqNum
428 elevations : `list` of `float`
429 List of the elevations for each seqNum
430 zeniths : `list` of `float`
431 List of the zenith angles for each seqNum
432 """
433 azimuths, elevations, zeniths = [], [], []
434 for seqNum in seqNumList:
435 md = butler.get('raw.metadata', day_obs=dayObs, seq_num=seqNum, detector=0)
436 obsInfo = ObservationInfo(md)
437 alt = obsInfo.altaz_begin.alt.value
438 az = obsInfo.altaz_begin.az.value
439 elevations.append(alt)
440 zeniths.append(90-alt)
441 azimuths.append(az)
442 return azimuths, elevations, zeniths
445def getFocusFromHeader(exp):
446 """Get the raw focus value from the header.
448 Parameters
449 ----------
450 exp : `lsst.afw.image.exposure`
451 The exposure.
453 Returns
454 -------
455 focus : `float` or `None`
456 The focus value if found, else ``None``.
457 """
458 md = exp.getMetadata()
459 if 'FOCUSZ' in md:
460 return md['FOCUSZ']
461 return None
464def checkStackSetup():
465 """Check which weekly tag is being used and which local packages are setup.
467 Designed primarily for use in notbooks/observing, this prints the weekly
468 tag(s) are setup for lsst_distrib, and lists any locally setup packages and
469 the path to each.
471 Notes
472 -----
473 Uses print() instead of logger messages as this should simply print them
474 without being vulnerable to any log messages potentially being diverted.
475 """
476 packages = packageUtils.getEnvironmentPackages(include_all=True)
478 lsstDistribHashAndTags = packages['lsst_distrib'] # looks something like 'g4eae7cb9+1418867f (w_2022_13)'
479 lsstDistribTags = lsstDistribHashAndTags.split()[1]
480 if len(lsstDistribTags.split()) == 1:
481 tag = lsstDistribTags.replace('(', '')
482 tag = tag.replace(')', '')
483 print(f"You are running {tag} of lsst_distrib")
484 else: # multiple weekly tags found for lsst_distrib!
485 print(f'The version of lsst_distrib you have is compatible with: {lsstDistribTags}')
487 localPackages = []
488 localPaths = []
489 for package, tags in packages.items():
490 if tags.startswith('LOCAL:'):
491 path = tags.split('LOCAL:')[1]
492 path = path.split('@')[0] # don't need the git SHA etc
493 localPaths.append(path)
494 localPackages.append(package)
496 if localPackages:
497 print("\nLocally setup packages:")
498 print("-----------------------")
499 maxLen = max(len(package) for package in localPackages)
500 for package, path in zip(localPackages, localPaths):
501 print(f"{package:<{maxLen}s} at {path}")
502 else:
503 print("\nNo locally setup packages (using a vanilla stack)")
506def setupLogging(longlog=False):
507 """Setup logging in the same way as one would get from pipetask run.
509 Code that isn't run through the butler CLI defaults to WARNING level
510 messages and no logger names. This sets the behaviour to follow whatever
511 the pipeline default is, currently
512 <logger_name> <level>: <message> e.g.
513 lsst.isr INFO: Masking defects.
514 """
515 CliLog.initLog(longlog=longlog)
518def getCurrentDayObs_datetime():
519 """Get the current day_obs - the observatory rolls the date over at UTC-12
521 Returned as datetime.date(2022, 4, 28)
522 """
523 utc = gettz("UTC")
524 nowUtc = datetime.datetime.now().astimezone(utc)
525 offset = datetime.timedelta(hours=-12)
526 dayObs = (nowUtc + offset).date()
527 return dayObs
530def getCurrentDayObs_int():
531 """Return the current dayObs as an int in the form 20220428
532 """
533 return int(getCurrentDayObs_datetime().strftime("%Y%m%d"))
536def getCurrentDayObs_humanStr():
537 """Return the current dayObs as a string in the form '2022-04-28'
538 """
539 return dayObsIntToString(getCurrentDayObs_int())
542def getExpRecordAge(expRecord):
543 """Get the time, in seconds, since the end of exposure.
545 Parameters
546 ----------
547 expRecord : `lsst.daf.butler.DimensionRecord`
548 The exposure record.
550 Returns
551 -------
552 age : `float`
553 The age of the exposure, in seconds.
554 """
555 return -1 * (expRecord.timespan.end - Time.now()).sec
558def getSite():
559 """Returns where the code is running.
561 Returns
562 -------
563 location : `str`
564 One of ['tucson', 'summit', 'base', 'staff-rsp', 'rubin-devl']
566 Raises
567 ------
568 ValueError
569 Raised if location cannot be determined.
570 """
571 # All nublado instances guarantee that EXTERNAL_URL is set and uniquely
572 # identifies it.
573 location = os.getenv('EXTERNAL_INSTANCE_URL', "")
574 if location == "https://tucson-teststand.lsst.codes": 574 ↛ 575line 574 didn't jump to line 575, because the condition on line 574 was never true
575 return 'tucson'
576 elif location == "https://summit-lsp.lsst.codes": 576 ↛ 577line 576 didn't jump to line 577, because the condition on line 576 was never true
577 return 'summit'
578 elif location == "https://base-lsp.lsst.codes": 578 ↛ 579line 578 didn't jump to line 579, because the condition on line 578 was never true
579 return 'base'
580 elif location == "https://usdf-rsp.slac.stanford.edu": 580 ↛ 581line 580 didn't jump to line 581, because the condition on line 580 was never true
581 return 'staff-rsp'
583 # if no EXTERNAL_URL, try HOSTNAME to see if we're on the dev nodes
584 # it is expected that this will be extensible to SLAC
585 hostname = os.getenv('HOSTNAME', "")
586 if hostname.startswith('sdfrome'): 586 ↛ 587line 586 didn't jump to line 587, because the condition on line 586 was never true
587 return 'rubin-devl'
589 # we have failed
590 raise ValueError('Location could not be determined')
593def getAltAzFromSkyPosition(skyPos, visitInfo, doCorrectRefraction=False,
594 wavelength=500.0,
595 pressureOverride=None,
596 temperatureOverride=None,
597 relativeHumidityOverride=None,
598 ):
599 """Get the alt/az from the position on the sky and the time and location
600 of the observation.
602 The temperature, pressure and relative humidity are taken from the
603 visitInfo by default, but can be individually overridden as needed. It
604 should be noted that the visitInfo never contains a nominal wavelength, and
605 so this takes a default value of 500nm.
607 Parameters
608 ----------
609 skyPos : `lsst.geom.SpherePoint`
610 The position on the sky.
611 visitInfo : `lsst.afw.image.VisitInfo`
612 The visit info containing the time of the observation.
613 doCorrectRefraction : `bool`, optional
614 Correct for the atmospheric refraction?
615 wavelength : `float`, optional
616 The nominal wavelength in nanometers (e.g. 500.0), as a float.
617 pressureOverride : `float`, optional
618 The pressure, in bars (e.g. 0.770), to override the value supplied in
619 the visitInfo, as a float.
620 temperatureOverride : `float`, optional
621 The temperature, in Celsius (e.g. 10.0), to override the value supplied
622 in the visitInfo, as a float.
623 relativeHumidityOverride : `float`, optional
624 The relativeHumidity in the range 0..1 (i.e. not as a percentage), to
625 override the value supplied in the visitInfo, as a float.
627 Returns
628 -------
629 alt : `lsst.geom.Angle`
630 The altitude.
631 az : `lsst.geom.Angle`
632 The azimuth.
633 """
634 skyLocation = SkyCoord(skyPos.getRa().asRadians(), skyPos.getDec().asRadians(), unit=u.rad)
635 long = visitInfo.observatory.getLongitude()
636 lat = visitInfo.observatory.getLatitude()
637 ele = visitInfo.observatory.getElevation()
638 earthLocation = EarthLocation.from_geodetic(long.asDegrees(), lat.asDegrees(), ele)
640 refractionKwargs = {}
641 if doCorrectRefraction:
642 # wavelength is never supplied in the visitInfo so always take this
643 wavelength = wavelength * u.nm
645 if pressureOverride:
646 pressure = pressureOverride
647 else:
648 pressure = visitInfo.weather.getAirPressure()
649 # ObservationInfos (which are the "source of truth" use pascals) so
650 # convert from pascals to bars
651 pressure /= 100000.0
652 pressure = pressure*u.bar
654 if temperatureOverride:
655 temperature = temperatureOverride
656 else:
657 temperature = visitInfo.weather.getAirTemperature()
658 temperature = temperature*u.deg_C
660 if relativeHumidityOverride:
661 relativeHumidity = relativeHumidityOverride
662 else:
663 relativeHumidity = visitInfo.weather.getHumidity() / 100.0 # this is in percent
664 relativeHumidity = relativeHumidity*u.deg_C
666 refractionKwargs = dict(pressure=pressure,
667 temperature=temperature,
668 relative_humidity=relativeHumidity,
669 obswl=wavelength)
671 # must go via astropy.Time because dafBase.dateTime.DateTime contains
672 # the timezone, but going straight to visitInfo.date.toPython() loses this.
673 obsTime = Time(visitInfo.date.toPython(), scale='tai')
674 altAz = AltAz(obstime=obsTime,
675 location=earthLocation,
676 **refractionKwargs)
678 obsAltAz = skyLocation.transform_to(altAz)
679 alt = geom.Angle(obsAltAz.alt.degree, geom.degrees)
680 az = geom.Angle(obsAltAz.az.degree, geom.degrees)
682 return alt, az
685def getExpPositionOffset(exp1, exp2, useWcs=True, allowDifferentPlateScales=False):
686 """Get the change in sky position between two exposures.
688 Given two exposures, calculate the offset on the sky between the images.
689 If useWcs then use the (fitted or unfitted) skyOrigin from their WCSs, and
690 calculate the alt/az from the observation times, otherwise use the nominal
691 values in the exposures' visitInfos. Note that if using the visitInfo
692 values that for a given pointing the ra/dec will be ~identical, regardless
693 of whether astrometric fitting has been performed.
695 Values are given as exp1-exp2.
697 Parameters
698 ----------
699 exp1 : `lsst.afw.image.Exposure`
700 The first exposure.
701 exp2 : `lsst.afw.image.Exposure`
702 The second exposure.
703 useWcs : `bool`
704 Use the WCS for the ra/dec and alt/az if True, else use the nominal/
705 boresight values from the exposures' visitInfos.
706 allowDifferentPlateScales : `bool`, optional
707 Use to disable checking that plate scales are the same. Generally,
708 differing plate scales would indicate an error, but where blind-solving
709 has been undertaken during commissioning plate scales can be different
710 enough to warrant setting this to ``True``.
712 Returns
713 -------
714 offsets : `lsst.pipe.base.Struct`
715 A struct containing the offsets:
716 ``deltaRa``
717 The diference in ra (`lsst.geom.Angle`)
718 ``deltaDec``
719 The diference in dec (`lsst.geom.Angle`)
720 ``deltaAlt``
721 The diference in alt (`lsst.geom.Angle`)
722 ``deltaAz``
723 The diference in az (`lsst.geom.Angle`)
724 ``deltaPixels``
725 The diference in pixels (`float`)
726 """
728 wcs1 = exp1.getWcs()
729 wcs2 = exp2.getWcs()
730 pixScaleArcSec = wcs1.getPixelScale().asArcseconds()
731 if not allowDifferentPlateScales:
732 assert np.isclose(pixScaleArcSec, wcs2.getPixelScale().asArcseconds()), \
733 "Pixel scales in the exposures differ."
735 if useWcs:
736 p1 = wcs1.getSkyOrigin()
737 p2 = wcs2.getSkyOrigin()
738 alt1, az1 = getAltAzFromSkyPosition(p1, exp1.getInfo().getVisitInfo())
739 alt2, az2 = getAltAzFromSkyPosition(p2, exp2.getInfo().getVisitInfo())
740 ra1 = p1[0]
741 ra2 = p2[0]
742 dec1 = p1[1]
743 dec2 = p2[1]
744 else:
745 az1 = exp1.visitInfo.boresightAzAlt[0]
746 az2 = exp2.visitInfo.boresightAzAlt[0]
747 alt1 = exp1.visitInfo.boresightAzAlt[1]
748 alt2 = exp2.visitInfo.boresightAzAlt[1]
750 ra1 = exp1.visitInfo.boresightRaDec[0]
751 ra2 = exp2.visitInfo.boresightRaDec[0]
752 dec1 = exp1.visitInfo.boresightRaDec[1]
753 dec2 = exp2.visitInfo.boresightRaDec[1]
755 p1 = exp1.visitInfo.boresightRaDec
756 p2 = exp2.visitInfo.boresightRaDec
758 angular_offset = p1.separation(p2).asArcseconds()
759 deltaPixels = angular_offset / pixScaleArcSec
761 ret = pipeBase.Struct(deltaRa=(ra1-ra2).wrapNear(geom.Angle(0.0)),
762 deltaDec=dec1-dec2,
763 deltaAlt=alt1-alt2,
764 deltaAz=(az1-az2).wrapNear(geom.Angle(0.0)),
765 deltaPixels=deltaPixels
766 )
768 return ret
771def starTrackerFileToExposure(filename, logger=None):
772 """Read the exposure from the file and set the wcs from the header.
774 Parameters
775 ----------
776 filename : `str`
777 The full path to the file.
778 logger : `logging.Logger`, optional
779 The logger to use for errors, created if not supplied.
781 Returns
782 -------
783 exp : `lsst.afw.image.Exposure`
784 The exposure.
785 """
786 if not logger:
787 logger = logging.getLogger(__name__)
788 exp = afwImage.ExposureF(filename)
789 try:
790 wcs = genericCameraHeaderToWcs(exp)
791 exp.setWcs(wcs)
792 except Exception as e:
793 logger.warning(f"Failed to set wcs from header: {e}")
795 # for some reason the date isn't being set correctly
796 # DATE-OBS is present in the original header, but it's being
797 # stripped out and somehow not set (plus it doesn't give the midpoint
798 # of the exposure), so set it manually from the midpoint here
799 try:
800 md = exp.getMetadata()
801 begin = datetime.datetime.fromisoformat(md['DATE-BEG'])
802 end = datetime.datetime.fromisoformat(md['DATE-END'])
803 duration = end - begin
804 mid = begin + duration/2
805 newTime = dafBase.DateTime(mid.isoformat(), dafBase.DateTime.Timescale.TAI)
806 newVi = exp.visitInfo.copyWith(date=newTime)
807 exp.info.setVisitInfo(newVi)
808 except Exception as e:
809 logger.warning(f"Failed to set date from header: {e}")
811 return exp
814def obsInfoToDict(obsInfo):
815 """Convert an ObservationInfo to a dict.
817 Parameters
818 ----------
819 obsInfo : `astro_metadata_translator.ObservationInfo`
820 The ObservationInfo to convert.
822 Returns
823 -------
824 obsInfoDict : `dict`
825 The ObservationInfo as a dict.
826 """
827 return {prop: getattr(obsInfo, prop) for prop in obsInfo.all_properties.keys()}
830def getFieldNameAndTileNumber(field, warn=True, logger=None):
831 """Get the tile name and number of an observed field.
833 It is assumed to always be appended, with an underscore, to the rest of the
834 field name. Returns the name and number as a tuple, or the name unchanged
835 if no tile number is found.
837 Parameters
838 ----------
839 field : `str`
840 The name of the field
842 Returns
843 -------
844 fieldName : `str`
845 The name of the field without the trailing tile number, if present.
846 tileNum : `int`
847 The number of the tile, as an integer, or ``None`` if not found.
848 """
849 if warn and not logger:
850 logger = logging.getLogger('lsst.summit.utils.utils.getFieldNameAndTileNumber')
852 if '_' not in field:
853 if warn:
854 logger.warning(f"Field {field} does not contain an underscore,"
855 " so cannot determine the tile number.")
856 return field, None
858 try:
859 fieldParts = field.split("_")
860 fieldNum = int(fieldParts[-1])
861 except ValueError:
862 if warn:
863 logger.warning(f"Field {field} does not contain only an integer after the final underscore"
864 " so cannot determine the tile number.")
865 return field, None
867 return "_".join(fieldParts[:-1]), fieldNum
870def getAirmassSeeingCorrection(airmass):
871 """Get the correction factor for seeing due to airmass.
873 Parameters
874 ----------
875 airmass : `float`
876 The airmass, greater than or equal to 1.
878 Returns
879 -------
880 correctionFactor : `float`
881 The correction factor to apply to the seeing.
883 Raises
884 ------
885 ValueError raised for unphysical airmasses.
886 """
887 if airmass < 1:
888 raise ValueError(f"Invalid airmass: {airmass}")
889 return airmass**(-0.6)
892def getFilterSeeingCorrection(filterName):
893 """Get the correction factor for seeing due to a filter.
895 Parameters
896 ----------
897 filterName : `str`
898 The name of the filter, e.g. 'SDSSg_65mm'.
900 Returns
901 -------
902 correctionFactor : `float`
903 The correction factor to apply to the seeing.
905 Raises
906 ------
907 ValueError raised for unknown filters.
908 """
909 match filterName:
910 case 'SDSSg_65mm':
911 return (477./500.)**0.2
912 case 'SDSSr_65mm':
913 return (623./500.)**0.2
914 case 'SDSSi_65mm':
915 return (762./500.)**0.2
916 case _:
917 raise ValueError(f"Unknown filter name: {filterName}")
920def getCdf(data, scale):
921 """Return an approximate cumulative distribution function scaled to
922 the [0, scale] range.
924 Parameters
925 ----------
926 data : `np.array`
927 The input data.
928 scale : `int`
929 The scaling range of the output.
931 Returns
932 -------
933 cdf : `np.array` of `int`
934 A monotonically increasing sequence that represents a scaled
935 cumulative distribution function, starting with the value at
936 minVal, then at (minVal + 1), and so on.
937 minVal : `float`
938 An integer smaller than the minimum value in the input data.
939 maxVal : `float`
940 An integer larger than the maximum value in the input data.
941 """
942 flatData = data.ravel()
943 size = flatData.size - np.count_nonzero(np.isnan(flatData))
945 minVal = np.floor(np.nanmin(flatData))
946 maxVal = np.ceil(np.nanmax(flatData)) + 1.0
948 hist, binEdges = np.histogram(
949 flatData, bins=int(maxVal - minVal), range=(minVal, maxVal)
950 )
952 cdf = (scale*np.cumsum(hist)/size).astype(np.int64)
953 return cdf, minVal, maxVal
956def getQuantiles(data, nColors):
957 """Get a set of boundaries that equally distribute data into
958 nColors intervals. The output can be used to make a colormap
959 of nColors colors.
961 This is equivalent to using the numpy function:
962 np.quantile(data, np.linspace(0, 1, nColors + 1))
963 but with a coarser precision, yet sufficient for our use case.
964 This implementation gives a speed-up.
966 Parameters
967 ----------
968 data : `np.array`
969 The input image data.
970 nColors : `int`
971 The number of intervals to distribute data into.
973 Returns
974 -------
975 boundaries: `list` of `float`
976 A monotonically increasing sequence of size (nColors + 1).
977 These are the edges of nColors intervals.
978 """
979 cdf, minVal, maxVal = getCdf(data, nColors)
980 boundaries = np.asarray(
981 [np.argmax(cdf >= i) + minVal for i in range(nColors)] + [maxVal]
982 )
983 return boundaries
986def digitizeData(data, nColors=256):
987 """
988 Scale data into nColors using its cumulative distribution function.
990 Parameters
991 ----------
992 data : `np.array`
993 The input image data.
994 nColors : `int`
995 The number of intervals to distribute data into.
997 Returns
998 -------
999 data: `np.array` of `int`
1000 Scaled data in the [0, nColors - 1] range.
1001 """
1002 cdf, minVal, maxVal = getCdf(data, nColors - 1)
1003 bins = np.floor((data - minVal)).astype(np.int64)
1004 return cdf[bins]