Ejemplo n.º 1
0
    def __init__(self, root, registry=None, compress=True):
        if registry is None:
            registry = os.path.join(root, "registry.sqlite3")
        self.mapper = LsstSimMapper(root=root, registry=registry)
        bf = dafPersist.ButlerFactory(mapper=self.mapper)
        self.butler = bf.create()

        self.expFile = CsvFileWriter("Raw_Amp_Exposure.csv",
                                     compress=compress)
        self.mdFile = CsvFileWriter("Raw_Amp_Exposure_Metadata.csv",
                                    compress=compress)
        self.rToSFile = CsvFileWriter("Raw_Amp_To_Science_Ccd_Exposure.csv",
                                      compress=compress)
        self.polyFile = open("Raw_Amp_Exposure_Poly.tsv", "wb")
Ejemplo n.º 2
0
    def __init__(self, origin, rotation_angle):
        # this line prevents the camera mapper from printing harmless warnings to
        # stdout (which, as of 5 November 2015, happens every time you instantiate
        # the camera below)
        pexLog.Log.getDefaultLog().setThresholdFor("CameraMapper",
                                                   pexLog.Log.FATAL)

        # Make the camera if we haven't yet.
        if LsstCamera._camera is None:
            LsstCamera._camera = LsstSimMapper().camera

        # _pixel_system_dict will be a dictionary of chip pixel coordinate systems
        # keyed to chip names
        self._pixel_system_dict = {}

        # _tan_pixel_system_dict will be a dictionary of chip tan pixel coordinate
        # systems
        self._tan_pixel_system_dict = {}

        # _pupil_system_dict will be a dictionary of chip pupil coordinate systems
        # keyed to chip names
        self._pupil_system_dict = {}

        self._pointing = origin
        self._rotation_angle = rotation_angle
        self._cos_rot = np.cos(self._rotation_angle / galsim.radians)
        self._sin_rot = np.sin(self._rotation_angle / galsim.radians)
        self._cos_dec = np.cos(self._pointing.dec / galsim.radians)
        self._sin_dec = np.sin(self._pointing.dec / galsim.radians)
Ejemplo n.º 3
0
 def generateInputList(self):
     with open("ccdlist", "w") as inputFile:
         print >> inputFile, ">intids visit"
         import lsst.daf.persistence as dafPersist
         from lsst.obs.lsstSim import LsstSimMapper
         butler = dafPersist.ButlerFactory(mapper=LsstSimMapper(
             root=self.inputDirectory)).create()
         numInputs = 0
         for sensorRef in butler.subset("raw", "sensor"):
             numChannels = 0
             for channelRef in sensorRef.subItems():
                 if butler.datasetExists("raw", channelRef.dataId):
                     numChannels += 1
             id = "visit=%(visit)d raft=%(raft)s sensor=%(sensor)s" % \
                     sensorRef.dataId
             if numChannels == 32:
                 print >> inputFile, "raw", id
                 numInputs += 1
                 if numInputs >= self.options.ccdCount:
                     break
             else:
                 print >>sys.stderr, "Warning:", id, \
                         "has %d channel files (should be 32);" % \
                         (numChannels,), "not processing"
         for i in xrange(self.nPipelines):
             print >> inputFile, "raw visit=0 raft=0 sensor=0"
Ejemplo n.º 4
0
    def testAddStarByChipPos(self):

        # Instantiate the skySim object
        skySim = SkySim()

        # Set the ObservationMetaData
        RA = 0
        Dec = 0
        cameraRotation = 0
        cameraMJD = 59580.0
        obs = ObservationMetaData(pointingRA=RA, pointingDec=Dec, rotSkyPos=cameraRotation, 
                                    mjd=cameraMJD)

        # Set the camera
        camera = LsstSimMapper().camera

        # Add the star
        sensorName = "R22_S11"
        starId = 0
        starMag = 17
        xInpixelInCam = 2000
        yInPixelInCam = 2036
        skySim.addStarByChipPos(camera, obs, sensorName, starId, xInpixelInCam, yInPixelInCam, 
                                starMag, self.testDataDir)

        # Test the result
        self.assertAlmostEqual(skySim.ra[0], 359.99971038)
        self.assertAlmostEqual(skySim.decl[0], 0.0001889)

        # Test to get the sensor box
        cornerInRaDecList = skySim.getCornOfChipOnSky(camera, obs, sensorName, self.testDataDir)
        self.assertEqual(len(cornerInRaDecList), 4)
Ejemplo n.º 5
0
    def __init__(self):
        """Initialize the commissioning camera class."""

        # The comcam's configuration here is approximated by taking the central
        # raft of lsst camera.
        super(ComCam, self).__init__(LsstSimMapper().camera)
        self._initDetectors(DetectorType.SCIENCE)

        # Remove the ccd data that are not belong to ComCam
        detectorList = [
            "R:2,2 S:0,2",
            "R:2,2 S:1,2",
            "R:2,2 S:2,2",
            "R:2,2 S:0,1",
            "R:2,2 S:1,1",
            "R:2,2 S:2,1",
            "R:2,2 S:0,0",
            "R:2,2 S:1,0",
            "R:2,2 S:2,0",
        ]
        self.setWfsCcdList(detectorList)

        wfsCorners = dict()
        ccdDims = dict()
        for detector in detectorList:
            wfsCorners[detector] = self.getWfsCorner(detector)
            ccdDims[detector] = self.getCcdDim(detector)

        self.setWfsCorners(wfsCorners)
        self.setCcdDims(ccdDims)
def lsst_camera():
    """
    Return a copy of the LSST Camera model as stored in obs_lsstSim.
    """
    if not hasattr(lsst_camera, '_lsst_camera'):
        lsst_camera._lsst_camera = LsstSimMapper().camera

    return lsst_camera._lsst_camera
Ejemplo n.º 7
0
 def _setupCamera(self):
     """
     Initialize camera mapper, etc.
     """
     self.mapper = LsstSimMapper()
     self.camera = self.mapper.camera
     self.epoch = 2000.0
     self.cameraFov=np.radians(2.1)
Ejemplo n.º 8
0
def lsst_camera():
    """
    Return a copy of the LSST Camera model as stored in obs_lsstSim.
    """
    if not hasattr(lsst_camera, '_lsst_camera'):
        lsstLog.setLevel('CameraMapper', lsstLog.WARN)
        lsst_camera._lsst_camera = LsstSimMapper().camera

    return lsst_camera._lsst_camera
Ejemplo n.º 9
0
class ssmCatCamera(ssmCat):
    column_outputs = basic_columns + ['chipName']
    camera = LsstSimMapper().camera
    cannot_be_null = ['visibility', 'chipName']
    transformations = {
        'raJ2000': np.degrees,
        'decJ2000': np.degrees,
        'velRa': np.degrees,
        'velDec': np.degrees
    }
    default_formats = {'f': '%.13f'}
Ejemplo n.º 10
0
    def __init__(self):
        """Initialization of sky simulator class."""

        self.starId = np.array([], dtype=int)
        self.ra = np.array([])
        self.decl = np.array([])
        self.mag = np.array([])

        self._camera = LsstSimMapper().camera
        self._obs = ObservationMetaData()
        self._sourProc = SourceProcessor()
    def setUpClass(cls):

        if _USE_LSST_CAMERA:
            cls.camera = LsstSimMapper().camera
            cls.detector = cls.camera['R:1,1 S:2,2']
        else:
            baseDir = os.path.join(getPackageDir('sims_GalSimInterface'), 'tests', 'cameraData')
            cls.camera = ReturnCamera(baseDir)
            cls.detector = cls.camera[0]

        cls.obs = ObservationMetaData(pointingRA=25.0, pointingDec=-10.0,
                                      boundType='circle', boundLength=1.0,
                                      mjd=49250.0, rotSkyPos=0.0)
        cls.epoch = 2000.0
Ejemplo n.º 12
0
class LsstObservatory:
    """
    Class to encapsulate an Observatory object and compute the
    observatory location information.
    """
    def __init__(self):
        self.observatory = LsstSimMapper().MakeRawVisitInfoClass().observatory

    def getLocation(self):
        """
        The LSST observatory location in geocentric coordinates.

        Returns
        -------
        astropy.coordinates.earth.EarthLocation
        """
        return astropy.coordinates.EarthLocation.from_geodetic(
            self.observatory.getLongitude().asDegrees(),
            self.observatory.getLatitude().asDegrees(),
            self.observatory.getElevation())

    def __getattr__(self, attr):
        if hasattr(self.observatory, attr):
            return getattr(self.observatory, attr)
Ejemplo n.º 13
0
    def __init__(self, camera=None):
        """Initialize the world coordinate system (WCS) solution class.

        Parameters
        ----------
        camera : lsst.afw.cameraGeom.camera.camera.Camera, optional
            A collection of Detectors that also supports coordinate
            transformation. (the default is None.)
        """

        self._obs = ObservationMetaData()

        if camera is None:
            self._camera = LsstSimMapper().camera
        else:
            self._camera = camera
Ejemplo n.º 14
0
    def __init__(self):
        """Initialization of sky simulator class."""

        # Star ID
        self.starId = np.array([], dtype=int)

        # Star RA
        self.ra = np.array([])

        # Star Decl
        self.decl = np.array([])

        # Star magnitude
        self.mag = np.array([])

        # DM camera object contains the information to do the coordinate
        # transformation
        self._camera = LsstSimMapper().camera

        # SIMS observation metadata object
        self._obs = ObservationMetaData()

        # Source processor in ts_wep
        self._sourProc = SourceProcessor()
Ejemplo n.º 15
0
conn.execute(cmd)
conn.commit()

# fill table
cmd = "INSERT INTO defect VALUES (NULL, ?, ?, ?, ?, ?, ?)"
numEntries = 0
os.chdir(registryDir)
for filePath in glob.glob(os.path.join("rev_*", "defects*.fits")):
    m = re.search(r'rev_(\d+)/defects(\d+)[AB]*\.fits', filePath)
    if not m:
        sys.stderr.write("Skipping file with invalid name: %r\n" % (filePath,))
        continue
    print("Processing %r" % (filePath,))

    fitsTable = pyfits.open(filePath)
    ccd = fitsTable[1].header["NAME"]
    serial = LsstSimMapper.getShortCcdName(ccd)+"_"+phosimVersion
    conn.execute(cmd, (
        filePath,
        int(m.group(1)),
        ccd,
        serial,
        "1970-01-01",
        "2037-12-31",
    ))
    numEntries += 1
conn.commit()
print("Added %d entries" % (numEntries))

conn.close()
Ejemplo n.º 16
0
This script demonstrates how to use the stand-along findChipName method from astrometry
using an ObservationMetaData generated from the OpSim database
"""
from __future__ import print_function

from builtins import zip
import numpy
import os
from collections import OrderedDict
from lsst.sims.utils import arcsecFromRadians
from lsst.sims.utils import pupilCoordsFromRaDec, observedFromICRS
from lsst.sims.coordUtils import chipNameFromRaDec
from lsst.sims.catUtils.baseCatalogModels import OpSim3_61DBObject
from lsst.obs.lsstSim import LsstSimMapper

mapper = LsstSimMapper()
camera = mapper.camera

epoch = 2000.0

#generate an ObservationMetaData object based on an actual OpSim pointing

radiusDegrees = 3.0
OpSimDB = OpSim3_61DBObject()
obs_metadata_list = OpSimDB.getObservationMetaData((88.0, -40.0),
                                                   5.0,
                                                   fovRadius=radiusDegrees,
                                                   makeCircBounds=True)

obs_metadata = obs_metadata_list[0]
Ejemplo n.º 17
0
def main(file, psf, outdir):
    """
    Drive GalSim to simulate the LSST.
    """
    # Setup a parser to take command line arguments

    config = desc.imsim.read_config(None)

    logger = desc.imsim.get_logger("INFO")

    # Get the number of rows to read from the instance file.  Use
    # default if not specified.

    numRows = None
    sensor = None
    # The PhoSim instance file contains both pointing commands and
    # objects.  The parser will split them and return a both phosim
    # command dictionary and a dataframe of objects.
    commands, phosim_objects = \
        desc.imsim.parsePhoSimInstanceFile(file, numRows)

    phosim_objects = \
        desc.imsim.validate_phosim_object_list(phosim_objects).accepted

    # Build the ObservationMetaData with values taken from the
    # PhoSim commands at the top of the instance file.
    obs_md = desc.imsim.phosim_obs_metadata(commands)
    #print (commands)
    #obs_md.OpsimMetaData['altitude' ] = 20
    camera = LsstSimMapper().camera

    # Sub-divide the source dataframe into stars and galaxies.
    if sensor is not None:
        # Trim the input catalog to a single chip.
        phosim_objects['chipName'] = \
            chipNameFromRaDec(phosim_objects['raICRS'].values,
                              phosim_objects['decICRS'].values,
                              parallax=phosim_objects['parallax'].values,
                              camera=camera, obs_metadata=obs_md,
                              epoch=2000.0)

        starDataBase = \
            phosim_objects.query("galSimType=='pointSource' and chipName=='%s'"
                                 % sensor)
        galaxyDataBase = \
            phosim_objects.query("galSimType=='sersic' and chipName=='%s'"
                                 % sensor)
    else:
        starDataBase = \
            phosim_objects.query("galSimType=='pointSource'")
        galaxyDataBase = \
            phosim_objects.query("galSimType=='sersic'")

    # Simulate the objects in the Pandas Dataframes.

    # First simulate stars
    phoSimStarCatalog = desc.imsim.ImSimStars(starDataBase, obs_md)
    phoSimStarCatalog.photParams = desc.imsim.photometricParameters(commands)

    # Add noise and sky background
    # The simple code using the default lsst-GalSim interface would be:
    #
    #    PhoSimStarCatalog.noise_and_background = ExampleCCDNoise(addNoise=True,
    #                                                             addBackground=True)
    #
    # But, we need a more realistic sky model and we need to pass more than
    # this basic info to use Peter Y's ESO sky model.
    # We must pass obs_metadata, chip information etc...
    phoSimStarCatalog.noise_and_background = ESOSkyModel(obs_md,
                                                         addNoise=True,
                                                         addBackground=True)

    # Add a PSF.
    if psf.lower() == "doublegaussian":
        # This one is taken from equation 30 of
        # www.astro.washington.edu/users/ivezic/Astr511/LSST_SNRdoc.pdf .
        #
        # Set seeing from self.obs_metadata.
        phoSimStarCatalog.PSF = \
            SNRdocumentPSF(obs_md.OpsimMetaData['FWHMgeom'])
    elif psf.lower() == "kolmogorov":
        # This PSF was presented by David Kirkby at the 23 March 2017
        # Survey Simulations Working Group telecon
        #
        # https://confluence.slac.stanford.edu/pages/viewpage.action?spaceKey=LSSTDESC&title=SSim+2017-03-23

        # equation 3 of Krisciunas and Schaefer 1991
        airmass = 1.0 / np.sqrt(
            1.0 - 0.96 *
            (np.sin(0.5 * np.pi - obs_md.OpsimMetaData['altitude']))**2)

        phoSimStarCatalog.PSF = \
            Kolmogorov_and_Gaussian_PSF(airmass=airmass,
                                        rawSeeing=obs_md.OpsimMetaData['rawSeeing'],
                                        band=obs_md.bandpass)
    else:
        raise RuntimeError("Do not know what to do with psf model: "
                           "%s" % psf)

    phoSimStarCatalog.camera = camera
    phoSimStarCatalog.get_fitsFiles()

    # Now galaxies
    phoSimGalaxyCatalog = desc.imsim.ImSimGalaxies(galaxyDataBase, obs_md)
    phoSimGalaxyCatalog.copyGalSimInterpreter(phoSimStarCatalog)
    phoSimGalaxyCatalog.PSF = phoSimStarCatalog.PSF
    phoSimGalaxyCatalog.noise_and_background = phoSimStarCatalog.noise_and_background
    phoSimGalaxyCatalog.get_fitsFiles()

    # Write out the fits files
    outdir = outdir
    if not os.path.isdir(outdir):
        os.makedirs(outdir)
    prefix = config['persistence']['eimage_prefix']
    phoSimGalaxyCatalog.write_images(nameRoot=os.path.join(outdir, prefix) +
                                     str(commands['obshistid']))
Ejemplo n.º 18
0
def getInputButler(opt):
    inmapper = LsstSimMapper(root=opt.inRoot, registry=opt.registry)
    bf = dafPersist.ButlerFactory(mapper=inmapper)
    inButler = bf.create()
    return inButler
Ejemplo n.º 19
0
    cmdSettingFile = "./data/cmdFile/starDefault.cmd"
    instSettingFile = "./data/instFile/starSingleExp.inst"

    folderPath2FocalPlane = os.path.join(phosimDir, "data", "lsst")

    # Sky information
    outputFilePath = "./output/skyWfsAllInfo.txt"

    # Set the settings
    obsId = 9001000
    aFilter = "g"
    wavelengthInNm = 500
    mjdTime = 59580.0

    # Generate the camera object
    camera = LsstSimMapper().camera

    # Set the ObservationMetaData
    RA = 0
    Dec = 0

    # The unit of camera rotation angle is in degree
    cameraRotation = 0
    cameraMJD = 59580.0

    obs = ObservationMetaData(pointingRA=RA,
                              pointingDec=Dec,
                              rotSkyPos=cameraRotation,
                              mjd=mjdTime)

    # Instantiate the subsystems
 def observatory(self):
     if self._observatory is None:
         self._observatory \
             = LsstSimMapper().MakeRawVisitInfoClass().observatory
     return self._observatory
Ejemplo n.º 21
0
    def testEndToEnd(self):
        """Test ISR, CcdAssembly, CrSplit, ImgChar, SFM pipelines"""

        #Setup up astrometry_net_data
        # Note - one of datarel's dependencies causes setup of
        #        'astrometry_net_data cfhttemplate' version; 
        #        datarel needs imsim_*.
        ver = 'imsim-2010-12-17-1'
        print "Setting up astrometry_net_data", ver
        # XXX what is actually used from this setup -- a path in the env?
        ok, version, reason = eups.Eups().setup("astrometry_net_data", versionName=ver)
        if not ok:
            raise ValueError("Couldn't set up version '%s' of astrometry_net_data: %s" % (ver, reason))

        afwdataDir = lsst.utils.getPackageDir("afwdata")
        inputRoot = os.path.join(afwdataDir, "ImSim")
        if os.path.exists("endToEnd.py"):
            outputRoot = "."
        else:
            outputRoot = "tests"

        registryPath = os.path.join(inputRoot, "registry.sqlite3")

        bf = dafPersist.ButlerFactory(mapper=LsstSimMapper(root=inputRoot))
        inButler = bf.create()
        obf = dafPersist.ButlerFactory(mapper=LsstSimMapper(root=outputRoot,
            registry=registryPath))
        outButler = obf.create()

        stat = subprocess.call(["runImSim.py", "-T", "--force",
            "-i", inputRoot, "-o", outputRoot,
            "-v", "85408556", "-r", "2,3", "-s", "1,1"])
        self.assertEqual(stat, 0, "Error while running end to end test")

        fname = "psf/v85408556-fr/R23/S11.boost"
        stat = subprocess.call(["cmp",
            os.path.join(outputRoot, fname), os.path.join(inputRoot, fname)])

        psfDiffers = (stat != 0)
        if psfDiffers:
            print 'PSF differs (but carrying on and failing later...)'

        results = []
        
        for datasetType in ("icSrc", "src", "calexp"):
            msg = compare(outButler, inButler, datasetType,
                    visit=85408556, raft="2,3", sensor="1,1")
            results.append((datasetType, msg))
            if msg is not None:
                print 'Dataset type', datasetType, 'differs (but carrying on and failing later...)'
                print 'message:', msg

        for snap in (0, 1):
            msg = compare(outButler, inButler, "sdqaCcd",
                visit=85408556, snap=snap, raft="2,3", sensor="1,1")
            results.append(('sdqaCcd snap %i' % snap, msg))
            if msg is not None:
                print 'Snap', snap, 'sdqaCCD differs (but carrying on and failing later...)'
                print 'message:', msg
            for channel in inButler.queryMetadata("raw", "channel"):
                msg = compare(outButler, inButler, "sdqaAmp",
                    visit=85408556, snap=snap, raft="2,3", sensor="1,1",
                    channel=channel)
                print 'channel:', channel
                results.append(('sdqaAmp snap %i channel ' % (snap) + str(channel), msg))
                if msg is not None:
                    print 'Snap', snap, 'channel', channels, 'sdqaAmp differs (but carrying on and failing later...)'
                    print 'message:', msg

        # Deferred failure!
        self.assertFalse(psfDiffers)
        for datasetType,msg in results:
            self.assert_(msg is None, msg)
Ejemplo n.º 22
0
 class CameraCoordsCatalog(AstrometryStars, CameraCoords,
                           InstanceCatalog):
     camera = LsstSimMapper().camera
     column_outputs = ['id', 'chipName']
    camConfig.transformDict = tmc

    def makeDir(dirPath, doClobber=False):
        """Make a directory; if it exists then clobber or fail, depending on doClobber

        @param[in] dirPath: path of directory to create
        @param[in] doClobber: what to do if dirPath already exists:
            if True and dirPath is a dir, then delete it and recreate it, else raise an exception
        @throw RuntimeError if dirPath exists and doClobber False
        """
        if os.path.exists(dirPath):
            if doClobber and os.path.isdir(dirPath):
                print("Clobbering directory %r" % (dirPath, ))
                shutil.rmtree(dirPath)
            else:
                raise RuntimeError("Directory %r exists" % (dirPath, ))
        print("Creating directory %r" % (dirPath, ))
        os.makedirs(dirPath)

    # write data products
    outDir = args.OutputDir
    makeDir(dirPath=outDir, doClobber=args.clobber)

    camConfigPath = os.path.join(outDir, "camera.py")
    camConfig.save(camConfigPath)

    for detectorName, ampTable in ampTableDict.items():
        shortDetectorName = LsstSimMapper.getShortCcdName(detectorName)
        ampInfoPath = os.path.join(outDir, shortDetectorName + ".fits")
        ampTable.writeFits(ampInfoPath)
Ejemplo n.º 24
0
    def __init__(self):
        """Initialize the LSST camera class."""

        super(LsstCam, self).__init__(LsstSimMapper().camera)
        self._initDetectors(DetectorType.WAVEFRONT)
Ejemplo n.º 25
0
 def __init__(self):
     self.observatory = LsstSimMapper().MakeRawVisitInfoClass().observatory
Ejemplo n.º 26
0
class CsvGenerator(object):

    def __init__(self, root, registry=None, compress=True):
        if registry is None:
            registry = os.path.join(root, "registry.sqlite3")
        self.mapper = LsstSimMapper(root=root, registry=registry)
        bf = dafPersist.ButlerFactory(mapper=self.mapper)
        self.butler = bf.create()

        self.expFile = CsvFileWriter("Raw_Amp_Exposure.csv",
                                     compress=compress)
        self.mdFile = CsvFileWriter("Raw_Amp_Exposure_Metadata.csv",
                                    compress=compress)
        self.rToSFile = CsvFileWriter("Raw_Amp_To_Science_Ccd_Exposure.csv",
                                      compress=compress)
        self.polyFile = open("Raw_Amp_Exposure_Poly.tsv", "wb")

    def csvAll(self):
        for visit, raft, sensor in self.butler.queryMetadata("raw", "sensor",
                                                             ("visit", "raft", "sensor")):
            if self.butler.datasetExists("raw", visit=visit, snap=0,
                                         raft=raft, sensor=sensor, channel="0,0"):
                self.toCsv(visit, raft, sensor)
        self.expFile.flush()
        self.mdFile.flush()
        self.rToSFile.flush()
        self.polyFile.flush()
        self.polyFile.close()

    def getFullMetadata(self, datasetType, **keys):
        filename = self.mapper.map(datasetType, keys).getLocations()[0]
        return afwImage.readMetadata(filename)

    def toCsv(self, visit, raft, sensor):
        r1, comma, r2 = raft
        s1, comma, s2 = sensor
        raftNum = rafts.index(raft)
        raftId = int(r1) * 5 + int(r2)
        ccdNum = int(s1) * 3 + int(s2)
        sciCcdExposureId = (long(visit) << 9) + raftId * 10 + ccdNum

        for snap in xrange(2):
            rawCcdExposureId = (sciCcdExposureId << 1) + snap

            for channelY in xrange(2):
                for channelX in xrange(8):
                    channel = "%d,%d" % (channelY, channelX)
                    channelNum = (channelY << 3) + channelX
                    rawAmpExposureId = (rawCcdExposureId << 4) + channelNum

                    try:
                        md = self.getFullMetadata("raw",
                                                  visit=visit, snap=snap,
                                                  raft=raft, sensor=sensor, channel=channel)
                    except:
                        print("*** Unable to read metadata for "
                              "visit %d snap %d "
                              "raft %s sensor %s channel %s" %
                              (visit, snap, raft, sensor, channel))
                        continue

                    self.rToSFile.write(rawAmpExposureId, sciCcdExposureId,
                                        snap, channelNum)

                    width = md.get('NAXIS1')
                    height = md.get('NAXIS2')
                    wcs = afwImage.makeWcs(md.deepCopy())
                    cen = wcs.pixelToSky(0.5*width - 0.5, 0.5*height - 0.5).toIcrs()
                    corner1 = wcs.pixelToSky(-0.5, -0.5).toIcrs()
                    corner2 = wcs.pixelToSky(-0.5, height - 0.5).toIcrs()
                    corner3 = wcs.pixelToSky(width - 0.5, height - 0.5).toIcrs()
                    corner4 = wcs.pixelToSky(width - 0.5, -0.5).toIcrs()
                    mjd = md.get('MJD-OBS')
                    if mjd == 0.0:
                        mjd = 49563.270671
                    obsStart = dafBase.DateTime(mjd,
                                                dafBase.DateTime.MJD, dafBase.DateTime.UTC)
                    expTime = md.get('EXPTIME')
                    obsMidpoint = dafBase.DateTime(obsStart.nsecs() +
                                                   long(expTime * 1000000000 / 2))
                    filterName = md.get('FILTER').strip()
                    self.expFile.write(rawAmpExposureId,
                                       visit, snap, raftNum, raft, ccdNum,
                                       sensor, channelNum, channel,
                                       filterMap.index(filterName), filterName,
                                       cen.getRa().asDegrees(), cen.getDec().asDegrees(),
                                       md.get('EQUINOX'), md.get('RADESYS'),
                                       md.get('CTYPE1'), md.get('CTYPE2'),
                                       md.get('CRPIX1'), md.get('CRPIX2'),
                                       md.get('CRVAL1'), md.get('CRVAL2'),
                                       md.get('CD1_1'), md.get('CD1_2'),
                                       md.get('CD2_1'), md.get('CD2_2'),
                                       corner1.getRa().asDegrees(),
                                       corner1.getDec().asDegrees(),
                                       corner2.getRa().asDegrees(),
                                       corner2.getDec().asDegrees(),
                                       corner3.getRa().asDegrees(),
                                       corner3.getDec().asDegrees(),
                                       corner4.getRa().asDegrees(),
                                       corner4.getDec().asDegrees(),
                                       obsStart.get(dafBase.DateTime.MJD,
                                                    dafBase.DateTime.TAI),
                                       obsStart,
                                       obsMidpoint.get(dafBase.DateTime.MJD,
                                                       dafBase.DateTime.TAI),
                                       expTime,
                                       md.get('AIRMASS'), md.get('DARKTIME'),
                                       md.get('ZENITH'))
                    for name in md.paramNames():
                        if md.typeOf(name) == md.TYPE_Int:
                            self.mdFile.write(rawAmpExposureId, name, 1,
                                              md.getInt(name), None, None)
                        elif md.typeOf(name) == md.TYPE_Double:
                            self.mdFile.write(rawAmpExposureId, name, 1,
                                              None, md.getDouble(name), None)
                        else:
                            self.mdFile.write(rawAmpExposureId, name, 1,
                                              None, None, str(md.get(name)))
                    self.polyFile.write("\t".join([
                        str(rawAmpExposureId),
                        repr(corner1.getRa().asDegrees()), repr(corner1.getDec().asDegrees()),
                        repr(corner2.getRa().asDegrees()), repr(corner2.getDec().asDegrees()),
                        repr(corner3.getRa().asDegrees()), repr(corner3.getDec().asDegrees()),
                        repr(corner4.getRa().asDegrees()), repr(corner4.getDec().asDegrees())]))
                    self.polyFile.write("\n")

        print("Processed visit %d raft %s sensor %s" % (visit, raft, sensor))
 def setUpClass(cls):
     cls.camera = LsstSimMapper().camera
    camConfig.transformDict = tmc

    def makeDir(dirPath, doClobber=False):
        """Make a directory; if it exists then clobber or fail, depending on doClobber

        @param[in] dirPath: path of directory to create
        @param[in] doClobber: what to do if dirPath already exists:
            if True and dirPath is a dir, then delete it and recreate it, else raise an exception
        @throw RuntimeError if dirPath exists and doClobber False
        """
        if os.path.exists(dirPath):
            if doClobber and os.path.isdir(dirPath):
                print "Clobbering directory %r" % (dirPath,)
                shutil.rmtree(dirPath)
            else:
                raise RuntimeError("Directory %r exists" % (dirPath,))
        print "Creating directory %r" % (dirPath,)
        os.makedirs(dirPath)

    # write data products
    outDir = args.OutputDir
    makeDir(dirPath=outDir, doClobber=args.clobber)

    camConfigPath = os.path.join(outDir, "camera.py")
    camConfig.save(camConfigPath)

    for detectorName, ampTable in ampTableDict.iteritems():
        shortDetectorName = LsstSimMapper.getShortCcdName(detectorName)
        ampInfoPath = os.path.join(outDir, shortDetectorName + ".fits")
        ampTable.writeFits(ampInfoPath)
Ejemplo n.º 29
0
def getOutputButler(opt):
    outmapper = LsstSimMapper(root=opt.outRoot, registry=opt.registry)
    bf = dafPersist.ButlerFactory(mapper=outmapper)
    outButler = bf.create()
    return outButler
Ejemplo n.º 30
0
    def __init__(self):
        """Initialize the LSST full-array mode (FAM) camera class."""

        super(LsstFamCam, self).__init__(LsstSimMapper().camera)
        self._initDetectors(DetectorType.SCIENCE)
conn.execute(cmd)
conn.commit()

# fill table
cmd = "INSERT INTO defect VALUES (NULL, ?, ?, ?, ?, ?, ?)"
numEntries = 0
os.chdir(registryDir)
for filePath in glob.glob(os.path.join("rev_*", "defects*.fits")):
    m = re.search(r'rev_(\d+)/defects(\d+)[AB]*\.fits', filePath)
    if not m:
        sys.stderr.write("Skipping file with invalid name: %r\n" % (filePath,))
        continue
    print "Processing %r" % (filePath,)

    fitsTable = pyfits.open(filePath)
    ccd = fitsTable[1].header["NAME"]
    serial = LsstSimMapper.getShortCcdName(ccd)+"_"+phosimVersion
    conn.execute(cmd, (
        filePath,
        int(m.group(1)),
        ccd,
        serial,
        "1970-01-01",
        "2037-12-31",
    ))
    numEntries += 1
conn.commit()
print "Added %d entries" % (numEntries)

conn.close()
Ejemplo n.º 32
0
 def _setupLSSTCamera(self):
     """If we want to include the camera chip gaps, etc"""
     mapper = LsstSimMapper()
     self.camera = mapper.camera
     self.epoch = 2000.0