Exemplo n.º 1
0
    def testExceptions(self):
        """
        Test to make sure that methods complain when incorrect data types are passed.
        """
        obs = utils.ObservationMetaData(pointingRA=55.0, pointingDec=-72.0, mjd=53467.8)

        raFloat = 1.1
        raList = np.array([0.2, 0.3])

        decFloat = 1.1
        decList = np.array([0.2, 0.3])

        self.assertRaises(RuntimeError, utils._altAzPaFromRaDec, raList, decFloat, obs)
        self.assertRaises(RuntimeError, utils._altAzPaFromRaDec, raFloat, decList, obs)
        utils._altAzPaFromRaDec(raFloat, decFloat, obs)
        utils._altAzPaFromRaDec(raList, decList, obs)

        self.assertRaises(RuntimeError, utils._raDecFromAltAz, raList, decFloat, obs)
        self.assertRaises(RuntimeError, utils._raDecFromAltAz, raFloat, decList, obs)
        utils._raDecFromAltAz(raFloat, decFloat, obs)
        utils._raDecFromAltAz(raList, decList, obs)

        self.assertRaises(RuntimeError, utils.altAzPaFromRaDec, raList, decFloat, obs)
        self.assertRaises(RuntimeError, utils.altAzPaFromRaDec, raFloat, decList, obs)
        utils.altAzPaFromRaDec(raFloat, decFloat, obs)
        utils.altAzPaFromRaDec(raList, decList, obs)

        self.assertRaises(RuntimeError, utils.raDecFromAltAz, raList, decFloat, obs)
        self.assertRaises(RuntimeError, utils.raDecFromAltAz, raFloat, decList, obs)
        utils.raDecFromAltAz(raFloat, decFloat, obs)
        utils.raDecFromAltAz(raList, decList, obs)
Exemplo n.º 2
0
    def testPAStacker(self):
        """ Test the parallacticAngleStacker"""
        data = np.zeros(100,
                        dtype=list(
                            zip([
                                'observationStartMJD', 'fieldDec', 'fieldRA',
                                'observationStartLST'
                            ], [float] * 4)))
        data['observationStartMJD'] = np.arange(100) * .2 + 50000
        site = Site(name='LSST')
        data['observationStartLST'], last = calcLmstLast(
            data['observationStartMJD'], site.longitude_rad)
        data['observationStartLST'] = data['observationStartLST'] * 180. / 12.
        stacker = stackers.ParallacticAngleStacker(degrees=True)
        data = stacker.run(data)
        # Check values are in good range
        assert (data['PA'].max() <= 180)
        assert (data['PA'].min() >= -180)

        # Check compared to the util
        check_pa = []
        ras = np.radians(data['fieldRA'])
        decs = np.radians(data['fieldDec'])
        for ra, dec, mjd in zip(ras, decs, data['observationStartMJD']):
            alt, az, pa = _altAzPaFromRaDec(
                ra, dec, ObservationMetaData(mjd=mjd, site=site))

            check_pa.append(pa)
        check_pa = np.degrees(check_pa)
        np.testing.assert_array_almost_equal(data['PA'], check_pa, decimal=0)
Exemplo n.º 3
0
    def testPAStacker(self):
        """ Test the parallacticAngleStacker"""
        data = np.zeros(100, dtype=list(zip(
            ['observationStartMJD', 'fieldDec', 'fieldRA', 'observationStartLST'], [float] * 4)))
        data['observationStartMJD'] = np.arange(100) * .2 + 50000
        site = Site(name='LSST')
        data['observationStartLST'], last = calcLmstLast(data['observationStartMJD'], site.longitude_rad)
        data['observationStartLST'] = data['observationStartLST']*180./12.
        stacker = stackers.ParallacticAngleStacker(degrees=True)
        data = stacker.run(data)
        # Check values are in good range
        assert(data['PA'].max() <= 180)
        assert(data['PA'].min() >= -180)

        # Check compared to the util
        check_pa = []
        ras = np.radians(data['fieldRA'])
        decs = np.radians(data['fieldDec'])
        for ra, dec, mjd in zip(ras, decs, data['observationStartMJD']):
            alt, az, pa = _altAzPaFromRaDec(ra, dec,
                                            ObservationMetaData(mjd=mjd, site=site))

            check_pa.append(pa)
        check_pa = np.degrees(check_pa)
        np.testing.assert_array_almost_equal(data['PA'], check_pa, decimal=0)
Exemplo n.º 4
0
    def test_rad(self):
        nside = 64
        hpids = np.arange(hp.nside2npix(nside))
        ra, dec = utils._hpid2RaDec(nside, hpids)
        mjd = 59852.
        obs = utils.ObservationMetaData(mjd=mjd)

        alt1, az1, pa1 = utils._altAzPaFromRaDec(ra, dec, obs)

        alt2, az2 = utils._approx_RaDec2AltAz(ra, dec, obs.site.latitude_rad,
                                              obs.site.longitude_rad, mjd)

        # Check that the fast is similar to the more precice transform
        tol = np.radians(2)
        tol_mean = np.radians(1.)
        separations = utils._angularSeparation(az1, alt1, az2, alt2)

        self.assertLess(np.max(separations), tol)
        self.assertLess(np.mean(separations), tol_mean)

        # Check that the fast can nearly round-trip
        ra_back, dec_back = utils._approx_altAz2RaDec(alt2, az2, obs.site.latitude_rad,
                                                      obs.site.longitude_rad, mjd)
        separations = utils._angularSeparation(ra, dec, ra_back, dec_back)
        self.assertLess(np.max(separations), tol)
        self.assertLess(np.mean(separations), tol_mean)
Exemplo n.º 5
0
    def test_raDecAltAz_noRefraction_degVsRadians(self):
        """
        Check that raDecFromAltAz and altAzPaFromRaDec are consistent in a degrees-versus-radians
        sense when refraction is turned off
        """

        rng = np.random.RandomState(34)
        n_samples = 10
        ra_in = rng.random_sample(n_samples)*360.0
        dec_in = rng.random_sample(n_samples)*180.0 - 90.0
        mjd = 43000.0
        obs = utils.ObservationMetaData(mjd=mjd)
        alt, az, pa = utils.altAzPaFromRaDec(ra_in, dec_in, obs, includeRefraction=False)
        alt_rad, az_rad, pa_rad = utils._altAzPaFromRaDec(np.radians(ra_in),
                                                          np.radians(dec_in),
                                                          obs, includeRefraction=False)

        distance = utils.haversine(az_rad, alt_rad,
                                   np.radians(az), np.radians(alt))
        self.assertLess(utils.arcsecFromRadians(distance).min(), 0.001)
        np.testing.assert_array_almost_equal(pa, np.degrees(pa_rad), decimal=12)

        ra, dec = utils.raDecFromAltAz(alt, az, obs, includeRefraction=False)
        ra_rad, dec_rad = utils._raDecFromAltAz(alt_rad, az_rad, obs, includeRefraction=False)
        distance = utils.haversine(ra_rad, dec_rad, np.radians(ra), np.radians(dec))
        self.assertLess(utils.arcsecFromRadians(distance).min(), 0.001)
    def setRaDecMjd(self, lon, lat, mjd, degrees=False, azAlt=False, solarFlux=130.):
        """
        Set the sky parameters by computing the sky conditions on a given MJD and sky location.

        lon: Longitude-like (RA or Azimuth). Can be single number, list, or numpy array
        lat: Latitude-like (Dec or Altitude)
        mjd: Modified Julian Date for the calculation. Must be single number.
        degrees: (False) Assumes lon and lat are radians unless degrees=True
        azAlt: (False) Assume lon, lat are RA, Dec unless azAlt=True
        solarFlux: solar flux in SFU Between 50 and 310. Default=130. 1 SFU=10^4 Jy.
        """
        # Wrap in array just in case single points were passed
        if not type(lon).__module__ == np.__name__:
            if np.size(lon) == 1:
                lon = np.array([lon]).ravel()
                lat = np.array([lat]).ravel()
            else:
                lon = np.array(lon)
                lat = np.array(lat)
        if degrees:
            self.ra = np.radians(lon)
            self.dec = np.radians(lat)
        else:
            self.ra = lon
            self.dec = lat
        if np.size(mjd) > 1:
            raise ValueError('mjd must be single value.')
        self.mjd = mjd
        if azAlt:
            self.azs = self.ra.copy()
            self.alts = self.dec.copy()
            if self.preciseAltAz:
                self.ra, self.dec = _raDecFromAltAz(self.alts, self.azs,
                                                    ObservationMetaData(mjd=self.mjd, site=self.telescope))
            else:
                self.ra, self.dec = stupidFast_altAz2RaDec(self.alts, self.azs,
                                                           self.telescope.latitude_rad,
                                                           self.telescope.longitude_rad, mjd)
        else:
            if self.preciseAltAz:
                self.alts, self.azs, pa = _altAzPaFromRaDec(self.ra, self.dec,
                                                            ObservationMetaData(mjd=self.mjd,
                                                                                site=self.telescope))
            else:
                self.alts, self.azs = stupidFast_RaDec2AltAz(self.ra, self.dec,
                                                             self.telescope.latitude_rad,
                                                             self.telescope.longitude_rad, mjd)

        self.npts = self.ra.size
        self._initPoints()

        self.solarFlux = solarFlux
        self.points['solarFlux'] = self.solarFlux

        self._setupPointGrid()

        self.paramsSet = True

        # Interpolate the templates to the set paramters
        self.interpSky()
Exemplo n.º 7
0
    def test_rad(self):
        nside = 64
        hpids = np.arange(hp.nside2npix(nside))
        ra, dec = utils._hpid2RaDec(nside, hpids)
        mjd = 59852.
        obs = utils.ObservationMetaData(mjd=mjd)

        alt1, az1, pa1 = utils._altAzPaFromRaDec(ra, dec, obs)

        alt2, az2 = utils._approx_RaDec2AltAz(ra, dec, obs.site.latitude_rad,
                                              obs.site.longitude_rad, mjd)

        # Check that the fast is similar to the more precice transform
        tol = np.radians(2)
        tol_mean = np.radians(1.)
        separations = utils._angularSeparation(az1, alt1, az2, alt2)

        self.assertLess(np.max(separations), tol)
        self.assertLess(np.mean(separations), tol_mean)

        # Check that the fast can nearly round-trip
        ra_back, dec_back = utils._approx_altAz2RaDec(alt2, az2,
                                                      obs.site.latitude_rad,
                                                      obs.site.longitude_rad,
                                                      mjd)
        separations = utils._angularSeparation(ra, dec, ra_back, dec_back)
        self.assertLess(np.max(separations), tol)
        self.assertLess(np.mean(separations), tol_mean)
Exemplo n.º 8
0
    def testAltAzFromRaDec(self):
        """
        Test conversion from RA, Dec to Alt, Az
        """

        nSamples = 100
        ra = self.rng.random_sample(nSamples)*2.0*np.pi
        dec = (self.rng.random_sample(nSamples)-0.5)*np.pi
        lon_rad = 1.467
        lat_rad = -0.234
        controlAlt, controlAz = controlAltAzFromRaDec(ra, dec,
                                                      lon_rad, lat_rad,
                                                      self.mjd)

        obs = utils.ObservationMetaData(mjd=utils.ModifiedJulianDate(UTC=self.mjd),
                                        site=utils.Site(longitude=np.degrees(lon_rad),
                                                        latitude=np.degrees(lat_rad),
                                                        name='LSST'))

        # verify parallactic angle against an expression from
        # http://www.astro.washington.edu/groups/APO/Mirror.Motions/Feb.2000.Image.Jumps/report.html#Image%20motion%20directions
        #
        ra_obs, dec_obs = utils._observedFromICRS(ra, dec, obs_metadata=obs, epoch=2000.0,
                                                  includeRefraction=True)

        lmst, last = utils.calcLmstLast(obs.mjd.UT1, lon_rad)
        hourAngle = np.radians(last * 15.0) - ra_obs
        controlSinPa = np.sin(hourAngle) * np.cos(lat_rad) / np.cos(controlAlt)

        testAlt, testAz, testPa = utils._altAzPaFromRaDec(ra, dec, obs)

        distance = utils.arcsecFromRadians(utils.haversine(controlAz, controlAlt, testAz, testAlt))
        self.assertLess(distance.max(), 0.0001)
        self.assertLess(np.abs(np.sin(testPa) - controlSinPa).max(), self.tolerance)

        # test non-vectorized version
        for r, d in zip(ra, dec):
            controlAlt, controlAz = controlAltAzFromRaDec(r, d, lon_rad, lat_rad, self.mjd)
            testAlt, testAz, testPa = utils._altAzPaFromRaDec(r, d, obs)
            lmst, last = utils.calcLmstLast(obs.mjd.UT1, lon_rad)
            r_obs, dec_obs = utils._observedFromICRS(r, d, obs_metadata=obs,
                                                     epoch=2000.0, includeRefraction=True)
            hourAngle = np.radians(last * 15.0) - r_obs
            controlSinPa = np.sin(hourAngle) * np.cos(lat_rad) / np.cos(controlAlt)
            distance = utils.arcsecFromRadians(utils.haversine(controlAz, controlAlt, testAz, testAlt))
            self.assertLess(distance, 0.0001)
            self.assertLess(np.abs(np.sin(testPa) - controlSinPa), self.tolerance)
Exemplo n.º 9
0
    def _run(self, simData):
        pa_arr = []
        for ra, dec, mjd in zip(simData[self.raCol], simData[self.decCol], simData[self.mjdCol]):
            alt, az, pa = _altAzPaFromRaDec(ra, dec,
                                            ObservationMetaData(mjd=mjd,site=self.site))

            pa_arr.append(pa)

        simData['PA'] = np.array(pa_arr)
        return simData
    def testAltAzPaFromRaDec(self):
        mjd = 57432.7
        obs = ObservationMetaData(mjd=mjd, site=Site(longitude=self.lon, latitude=self.lat, name='LSST'))

        altRad, azRad, paRad = utils._altAzPaFromRaDec(self.raList, self.decList, obs)

        altDeg, azDeg, paDeg = utils.altAzPaFromRaDec(np.degrees(self.raList),
                                                      np.degrees(self.decList),
                                                      obs)


        np.testing.assert_array_almost_equal(altRad, np.radians(altDeg), 10)
        np.testing.assert_array_almost_equal(azRad, np.radians(azDeg), 10)
        np.testing.assert_array_almost_equal(paRad, np.radians(paDeg), 10)


        altRad, azRad, paRad = utils._altAzPaFromRaDec(self.raList, self.decList, obs)

        altDeg, azDeg, paDeg = utils.altAzPaFromRaDec(np.degrees(self.raList),
                                                      np.degrees(self.decList),
                                                      obs)


        np.testing.assert_array_almost_equal(altRad, np.radians(altDeg), 10)
        np.testing.assert_array_almost_equal(azRad, np.radians(azDeg), 10)
        np.testing.assert_array_almost_equal(paRad, np.radians(paDeg), 10)


        for ra, dec, in zip(self.raList, self.decList):
            altRad, azRad, paRad = utils._altAzPaFromRaDec(ra, dec, obs)
            altDeg, azDeg, paDeg = utils.altAzPaFromRaDec(np.degrees(ra),
                                                          np.degrees(dec),
                                                          obs)

            self.assertAlmostEqual(altRad, np.radians(altDeg), 10)
            self.assertAlmostEqual(azRad, np.radians(azDeg), 10)
            self.assertAlmostEqual(paRad, np.radians(paDeg), 10)
Exemplo n.º 11
0
    def testAltAzPaFromRaDec(self):
        mjd = 57432.7
        obs = ObservationMetaData(mjd=mjd,
                                  site=Site(longitude=self.lon,
                                            latitude=self.lat,
                                            name='LSST'))

        altRad, azRad, paRad = utils._altAzPaFromRaDec(self.raList,
                                                       self.decList, obs)

        altDeg, azDeg, paDeg = utils.altAzPaFromRaDec(np.degrees(self.raList),
                                                      np.degrees(self.decList),
                                                      obs)

        np.testing.assert_array_almost_equal(altRad, np.radians(altDeg), 10)
        np.testing.assert_array_almost_equal(azRad, np.radians(azDeg), 10)
        np.testing.assert_array_almost_equal(paRad, np.radians(paDeg), 10)

        altRad, azRad, paRad = utils._altAzPaFromRaDec(self.raList,
                                                       self.decList, obs)

        altDeg, azDeg, paDeg = utils.altAzPaFromRaDec(np.degrees(self.raList),
                                                      np.degrees(self.decList),
                                                      obs)

        np.testing.assert_array_almost_equal(altRad, np.radians(altDeg), 10)
        np.testing.assert_array_almost_equal(azRad, np.radians(azDeg), 10)
        np.testing.assert_array_almost_equal(paRad, np.radians(paDeg), 10)

        for ra, dec, in zip(self.raList, self.decList):
            altRad, azRad, paRad = utils._altAzPaFromRaDec(ra, dec, obs)
            altDeg, azDeg, paDeg = utils.altAzPaFromRaDec(
                np.degrees(ra), np.degrees(dec), obs)

            self.assertAlmostEqual(altRad, np.radians(altDeg), 10)
            self.assertAlmostEqual(azRad, np.radians(azDeg), 10)
            self.assertAlmostEqual(paRad, np.radians(paDeg), 10)
    def testradec2altaz(self):
        np.random.seed(42)
        ra = np.random.rand(100)*np.pi*2
        dec = np.random.rand(100)*np.pi-np.pi/2
        site = Site('LSST')
        mjd = 55000
        omd = ObservationMetaData(mjd=mjd,site=site)

        trueAlt,trueAz,pa = _altAzPaFromRaDec(ra,dec,omd)
        fastAlt,fastAz = sb.stupidFast_RaDec2AltAz(ra,dec,
                                                   site.latitude_rad,
                                                   site.longitude_rad,mjd)
        distanceDiff = haversine(trueAz,trueAlt, fastAz,fastAlt)

        degreeTol =2.  # 2-degree tolerance on the fast transform
        assert(np.degrees(distanceDiff.max()) < degreeTol)
Exemplo n.º 13
0
    def testradec2altaz(self):
        np.random.seed(42)
        ra = np.random.rand(100) * np.pi * 2
        dec = np.random.rand(100) * np.pi - np.pi / 2
        site = Site('LSST')
        mjd = 55000
        omd = ObservationMetaData(mjd=mjd, site=site)

        trueAlt, trueAz, pa = _altAzPaFromRaDec(ra, dec, omd)
        fastAlt, fastAz = sb.stupidFast_RaDec2AltAz(ra, dec, site.latitude_rad,
                                                    site.longitude_rad, mjd)
        distanceDiff = haversine(trueAz, trueAlt, fastAz, fastAlt)

        degreeTol = 2.  # 2-degree tolerance on the fast transform
        assert (np.degrees(distanceDiff.max()) < degreeTol)

        # make sure we don't have nans
        alt, az = sb.stupidFast_RaDec2AltAz(np.radians(np.array([0.])),
                                            np.radians(np.array([-90.])),
                                            np.radians(-30.2444),
                                            np.radians(-70.7494), 59582.05125)
        assert (~np.isnan(alt))
        assert (~np.isnan(az))
Exemplo n.º 14
0
    def setRaDecMjd(self,
                    lon,
                    lat,
                    mjd,
                    degrees=False,
                    azAlt=False,
                    solarFlux=130.):
        """
        Set the sky parameters by computing the sky conditions on a given MJD and sky location.

        Ra and Dec in raidans or degrees.
        input ra, dec or az,alt w/ altAz=True
        solarFlux: solar flux in s.f.u. Between 50 and 310.
        """
        # Wrap in array just in case single points were passed
        if not type(lon).__module__ == np.__name__:
            if np.size(lon) == 1:
                lon = np.array([lon])
                lat = np.array([lat])
            else:
                lon = np.array(lon)
                lat = np.array(lat)
        if degrees:
            self.ra = np.radians(lon)
            self.dec = np.radians(lat)
        else:
            self.ra = lon
            self.dec = lat
        self.mjd = mjd
        if azAlt:
            self.azs = self.ra.copy()
            self.alts = self.dec.copy()
            self.ra, self.dec = _raDecFromAltAz(self.alts, self.azs,
                                                self.Observatory.lon,
                                                self.Observatory.lat, self.mjd)
        else:
            self.alts, self.azs, pa = _altAzPaFromRaDec(
                self.ra, self.dec, self.Observatory.lon, self.Observatory.lat,
                self.mjd)

        self.npts = self.ra.size
        self._initPoints()

        self.solarFlux = solarFlux
        self.points['solarFlux'] = self.solarFlux

        # Switch to Dublin Julian Date for pyephem
        self.Observatory.date = mjd2djd(self.mjd)

        sun = ephem.Sun()
        sun.compute(self.Observatory)
        self.sunAlt = sun.alt
        self.sunAz = sun.az

        # Compute airmass the same way as ESO model
        self.airmass = 1. / np.cos(np.pi / 2. - self.alts)

        self.points['airmass'] = self.airmass
        self.points['nightTimes'] = 2
        self.points['alt'] = self.alts
        self.points['az'] = self.azs

        if self.twilight:
            self.points['sunAlt'] = self.sunAlt
            self.points['azRelSun'] = wrapRA(self.azs - self.sunAz)

        if self.moon:
            moon = ephem.Moon()
            moon.compute(self.Observatory)
            self.moonPhase = moon.phase
            self.moonAlt = moon.alt
            self.moonAz = moon.az
            # Calc azimuth relative to moon
            self.azRelMoon = wrapRA(self.azs - self.moonAz)
            over = np.where(self.azRelMoon > np.pi)
            self.azRelMoon[over] = 2. * np.pi - self.azRelMoon[over]
            self.points['moonAltitude'] += np.degrees(self.moonAlt)
            self.points['azRelMoon'] += self.azRelMoon
            self.points['moonSunSep'] += self.moonPhase / 100. * 180.

        if self.zodiacal:
            self.eclipLon = np.zeros(self.npts)
            self.eclipLat = np.zeros(self.npts)

            for i, temp in enumerate(self.ra):
                eclip = ephem.Ecliptic(
                    ephem.Equatorial(self.ra[i], self.dec[i], epoch='2000'))
                self.eclipLon[i] += eclip.lon
                self.eclipLat[i] += eclip.lat
            # Subtract off the sun ecliptic longitude
            sunEclip = ephem.Ecliptic(sun)
            self.sunEclipLon = sunEclip.lon
            self.points['altEclip'] += self.eclipLat
            self.points['azEclipRelSun'] += wrapRA(self.eclipLon -
                                                   self.sunEclipLon)
maxID = np.max(maxID)

# Crop off some of the early junky observations
minMJD = 56900
minID,mjd = sb.allSkyDB(0,'select min(ID) from dates where mjd > %i;' % minMJD, dtypes='int')

altLimit = 10. # Degrees
sunAltLimit = np.radians(-20.)

maxID = 3000
step = 5

for dateID in np.arange(minID.max(),minID.max()+maxID+1, step):
    sqlQ = 'select stars.ra, stars.dec, stars.ID, obs.starMag_inst, obs.starMag_err,obs.sky, obs.filter from obs, stars, dates where obs.starID = stars.ID and obs.dateID = dates.ID and obs.filter = "%s" and obs.dateID = %i and obs.starMag_err != 0 and dates.sunAlt < %f and obs.starMag_inst > %f;' % (filt,dateID,sunAltLimit, starBrightLimit)

    # Note that RA,Dec are in degrees
    data,mjd = sb.allSkyDB(dateID, sqlQ=sqlQ, dtypes=dtypes)
    if data.size > nStarLimit:
        alt,az,pa = _altAzPaFromRaDec(np.radians(data['ra']), np.radians(data['dec']),
                                      telescope.lon, telescope.lat, mjd)
        for i,nside in enumerate(nsides):
            tempMap = healbin(az,alt, az*0+1, nside=nside, reduceFunc=np.size)[hpIndices[i]]
            ratio = np.size(np.where(tempMap > 0)[0])/float(np.size(tempMap))
            mapFractions[i].append(ratio)


print 'nside, resolution (deg), fraction of healpixes populated'
for mf,nside in zip(mapFractions,nsides):
    resol = hp.nside2resol(nside, arcmin=True)/60.
    print ' %i,  %f, %f' % (nside, resol,np.median(mf))
Exemplo n.º 16
0
    def setRaDecMjd(self,
                    lon,
                    lat,
                    mjd,
                    degrees=False,
                    azAlt=False,
                    solarFlux=130.,
                    filterNames=['u', 'g', 'r', 'i', 'z', 'y']):
        """
        Set the sky parameters by computing the sky conditions on a given MJD and sky location.



        lon: Longitude-like (RA or Azimuth). Can be single number, list, or numpy array
        lat: Latitude-like (Dec or Altitude)
        mjd: Modified Julian Date for the calculation. Must be single number.
        degrees: (False) Assumes lon and lat are radians unless degrees=True
        azAlt: (False) Assume lon, lat are RA, Dec unless azAlt=True
        solarFlux: solar flux in SFU Between 50 and 310. Default=130. 1 SFU=10^4 Jy.
        filterNames: list of fitlers to return magnitudes for (if initialized with mags=True).
        """
        self.filterNames = filterNames
        if self.mags:
            self.npix = len(self.filterNames)
        # Wrap in array just in case single points were passed
        if np.size(lon) == 1:
            lon = np.array([lon]).ravel()
            lat = np.array([lat]).ravel()
        else:
            lon = np.array(lon)
            lat = np.array(lat)
        if degrees:
            self.ra = np.radians(lon)
            self.dec = np.radians(lat)
        else:
            self.ra = lon
            self.dec = lat
        if np.size(mjd) > 1:
            raise ValueError('mjd must be single value.')
        self.mjd = mjd
        if azAlt:
            self.azs = self.ra.copy()
            self.alts = self.dec.copy()
            if self.preciseAltAz:
                self.ra, self.dec = _raDecFromAltAz(
                    self.alts, self.azs,
                    ObservationMetaData(mjd=self.mjd, site=self.telescope))
            else:
                self.ra, self.dec = stupidFast_altAz2RaDec(
                    self.alts, self.azs, self.telescope.latitude_rad,
                    self.telescope.longitude_rad, mjd)
        else:
            if self.preciseAltAz:
                self.alts, self.azs, pa = _altAzPaFromRaDec(
                    self.ra, self.dec,
                    ObservationMetaData(mjd=self.mjd, site=self.telescope))
            else:
                self.alts, self.azs = stupidFast_RaDec2AltAz(
                    self.ra, self.dec, self.telescope.latitude_rad,
                    self.telescope.longitude_rad, mjd)

        self.npts = self.ra.size
        self._initPoints()

        self.solarFlux = solarFlux
        self.points['solarFlux'] = self.solarFlux

        self._setupPointGrid()

        self.paramsSet = True

        # Assume large airmasses are the same as airmass=2.5
        to_fudge = np.where((self.points['airmass'] > 2.5)
                            & (self.points['airmass'] < self.airmassLimit))
        self.points['airmass'][to_fudge] = 2.499
        self.points['alt'][to_fudge] = np.pi / 2 - np.arccos(
            1. / self.airmassLimit)

        # Interpolate the templates to the set paramters
        self._interpSky()
Exemplo n.º 17
0
#maxID= 300
maxID = 9000

totalIDs = 0
IDsWithStars = 0

for dateID in np.arange(minID.max(), minID.max() + maxID + 1):
    sqlQ = 'select stars.ra, stars.dec, stars.ID, obs.starMag_inst, obs.starMag_err,obs.sky, obs.filter from obs, stars, dates where obs.starID = stars.ID and obs.dateID = dates.ID and obs.filter = "%s" and obs.dateID = %i and obs.starMag_err != 0 and dates.sunAlt < %f and obs.starMag_inst > %f;' % (
        filt, dateID, sunAltLimit, starBrightLimit)
    totalIDs += 1
    # Note that RA,Dec are in degrees
    data, mjd = sb.allSkyDB(dateID, sqlQ=sqlQ, dtypes=dtypes)
    if data.size > nStarLimit:
        IDsWithStars += 1
        alt, az, pa = _altAzPaFromRaDec(
            np.radians(data['ra']), np.radians(data['dec']),
            ObservationMetaData(mjd=mjd, site=telescope))

        # Let's trim off any overly high airmass values
        good = np.where(alt > np.radians(altLimit))
        data = data[good]
        hpids = hp.ang2pix(nside, np.pi / 2. - alt[good], az[good])
        # Extend the lists
        starIDs.extend(data['starID'].tolist())
        dateIDs.extend([dateID] * np.size(data))
        hpIDs.extend(hpids.tolist())
        starMags.extend(data['starMag'].tolist())
        starMags_err.extend(data['starMag_err'].tolist())
        mjds.extend([mjd] * np.size(data))
        airmasses.extend((1. / np.cos(np.pi / 2 - alt[good])).tolist())
        left = np.searchsorted(data['mjd'], umjd)
        right = np.searchsorted(data['mjd'], umjd, side='right')

        altaz = np.zeros(data.size, dtype=zip(['alt','az'], [float]*2))
        moonAlt = np.zeros(data.size, dtype=float)

        print 'computing alts and azs'

        for j, (le, ri, mjd) in enumerate(zip(left,right,umjd)):
            Observatory.date = mjd2djd(mjd)
            sun.compute(Observatory)
            obs_metadata = ObservationMetaData(pointingRA=np.degrees(sun.ra),
                                                   pointingDec=np.degrees(sun.dec),
                                                   rotSkyPos=np.degrees(0),
                                                   mjd=mjd)
            alt, az, pa = _altAzPaFromRaDec(data['ra'][le:ri], data['dec'][le:ri], obs_metadata)
            az = wrapRA(az - sun.az)
            altaz['alt'][le:ri] += alt
            altaz['az'][le:ri] += az
            moon.compute(Observatory)
            moonAlt[le:ri] += moon.alt

        print 'making maps'
        good = np.where(moonAlt < 0)
        magMap[:,i] = _healbin(altaz['az'][good],altaz['alt'][good], data['sky'][good],
                               nside=nside, reduceFunc=np.median)
        rmsMap[:,i] = _healbin(altaz['az'][good],altaz['alt'][good],data['sky'][good],
                               nside=nside, reduceFunc=robustRMS)

    print 'saving maps'
    np.savez('TwilightMaps/twiMaps_%s.npz' % filterName, magMap=magMap, rmsMap=rmsMap, sunAlts=sunAlts)
altLimit = 10.  # Degrees
sunAltLimit = np.radians(-20.)

maxID = 3000
step = 5

for dateID in np.arange(minID.max(), minID.max() + maxID + 1, step):
    sqlQ = 'select stars.ra, stars.dec, stars.ID, obs.starMag_inst, obs.starMag_err,obs.sky, obs.filter from obs, stars, dates where obs.starID = stars.ID and obs.dateID = dates.ID and obs.filter = "%s" and obs.dateID = %i and obs.starMag_err != 0 and dates.sunAlt < %f and obs.starMag_inst > %f;' % (
        filt, dateID, sunAltLimit, starBrightLimit)

    # Note that RA,Dec are in degrees
    data, mjd = sb.allSkyDB(dateID, sqlQ=sqlQ, dtypes=dtypes)
    if data.size > nStarLimit:
        alt, az, pa = _altAzPaFromRaDec(np.radians(data['ra']),
                                        np.radians(data['dec']), telescope.lon,
                                        telescope.lat, mjd)
        for i, nside in enumerate(nsides):
            tempMap = healbin(az,
                              alt,
                              az * 0 + 1,
                              nside=nside,
                              reduceFunc=np.size)[hpIndices[i]]
            ratio = np.size(np.where(tempMap > 0)[0]) / float(np.size(tempMap))
            mapFractions[i].append(ratio)

print 'nside, resolution (deg), fraction of healpixes populated'
for mf, nside in zip(mapFractions, nsides):
    resol = hp.nside2resol(nside, arcmin=True) / 60.
    print ' %i,  %f, %f' % (nside, resol, np.median(mf))
Exemplo n.º 20
0
    def setRaDecMjd(self, lon, lat, mjd, degrees=False, azAlt=False, solarFlux=130.,
                    filterNames=['u', 'g', 'r', 'i', 'z', 'y']):
        """
        Set the sky parameters by computing the sky conditions on a given MJD and sky location.



        lon: Longitude-like (RA or Azimuth). Can be single number, list, or numpy array
        lat: Latitude-like (Dec or Altitude)
        mjd: Modified Julian Date for the calculation. Must be single number.
        degrees: (False) Assumes lon and lat are radians unless degrees=True
        azAlt: (False) Assume lon, lat are RA, Dec unless azAlt=True
        solarFlux: solar flux in SFU Between 50 and 310. Default=130. 1 SFU=10^4 Jy.
        filterNames: list of fitlers to return magnitudes for (if initialized with mags=True).
        """
        self.filterNames = filterNames
        if self.mags:
            self.npix = len(self.filterNames)
        # Wrap in array just in case single points were passed
        if np.size(lon) == 1:
            lon = np.array([lon]).ravel()
            lat = np.array([lat]).ravel()
        else:
            lon = np.array(lon)
            lat = np.array(lat)
        if degrees:
            self.ra = np.radians(lon)
            self.dec = np.radians(lat)
        else:
            self.ra = lon
            self.dec = lat
        if np.size(mjd) > 1:
            raise ValueError('mjd must be single value.')
        self.mjd = mjd
        if azAlt:
            self.azs = self.ra.copy()
            self.alts = self.dec.copy()
            if self.preciseAltAz:
                self.ra, self.dec = _raDecFromAltAz(self.alts, self.azs,
                                                    ObservationMetaData(mjd=self.mjd, site=self.telescope))
            else:
                self.ra, self.dec = _approx_altAz2RaDec(self.alts, self.azs,
                                                        self.telescope.latitude_rad,
                                                        self.telescope.longitude_rad, mjd)
        else:
            if self.preciseAltAz:
                self.alts, self.azs, pa = _altAzPaFromRaDec(self.ra, self.dec,
                                                            ObservationMetaData(mjd=self.mjd,
                                                                                site=self.telescope))
            else:
                self.alts, self.azs = _approx_RaDec2AltAz(self.ra, self.dec,
                                                          self.telescope.latitude_rad,
                                                          self.telescope.longitude_rad, mjd)

        self.npts = self.ra.size
        self._initPoints()

        self.solarFlux = solarFlux
        self.points['solarFlux'] = self.solarFlux

        self._setupPointGrid()

        self.paramsSet = True

        # Assume large airmasses are the same as airmass=2.5
        to_fudge = np.where((self.points['airmass'] > 2.5) & (self.points['airmass'] < self.airmassLimit))
        self.points['airmass'][to_fudge] = 2.499
        self.points['alt'][to_fudge] = np.pi/2-np.arccos(1./self.airmassLimit)

        # Interpolate the templates to the set paramters
        self.goodPix = np.where((self.airmass <= self.airmassLimit) & (self.airmass >= 1.))[0]
        if self.goodPix.size > 0:
            self._interpSky()
        else:
            warnings.warn('No valid points to interpolate')
Exemplo n.º 21
0
telescope = Site('LSST')
nside = 32
lat, ra = hp.pix2ang(nside, np.arange(hp.nside2npix(nside)))
dec = np.pi/2-lat

kwargs = dict(twilight=False, zodiacal=False, moon=True, scatteredStar=False, mergedSpec=False)

sm = sb.SkyModel(observatory='LSST', mags=True)  # , **kwargs)
mjd = 49353.177645
sm.setRaDecMjd(ra, dec, mjd)
mag = sm.returnMags()
lmst, last = calcLmstLast(mjd, telescope.longitude_rad)

moonRA, moonDec = _raDecFromAltAz(sm.moonAlt, sm.moonAz, ObservationMetaData(mjd=mjd, site=telescope))

alt, az, pa = _altAzPaFromRaDec(ra, dec, ObservationMetaData(mjd=mjd, site=telescope))
angDist2Moon = np.degrees(haversine(az, alt, sm.moonAz, sm.moonAlt))
ang2 = np.degrees(haversine(ra, dec, moonRA, moonDec))
alt = np.degrees(alt)

mags = -0.5*(np.nanmin(mag['u'])-mag['u'])


#extent = (0,130, 0,90)
extent = (20, 120, 20, 90)

xs, ys = np.mgrid[extent[0]:extent[1], extent[2]:extent[3]]
resampled = griddata((angDist2Moon, alt), mags, (xs, ys))
notInf = np.where((resampled != np.inf) & (~np.isnan(resampled)))

resampled[notInf] = resampled[notInf]-resampled[notInf].max()
Exemplo n.º 22
0
# Temp to speed things up
#maxID = 30000
#maxID= 300
maxID = 9000

totalIDs = 0
IDsWithStars = 0

for dateID in np.arange(minID.max(),minID.max()+maxID+1):
    sqlQ = 'select stars.ra, stars.dec, stars.ID, obs.starMag_inst, obs.starMag_err,obs.sky, obs.filter from obs, stars, dates where obs.starID = stars.ID and obs.dateID = dates.ID and obs.filter = "%s" and obs.dateID = %i and obs.starMag_err != 0 and dates.sunAlt < %f and obs.starMag_inst > %f;' % (filt,dateID,sunAltLimit, starBrightLimit)
    totalIDs += 1
    # Note that RA,Dec are in degrees
    data,mjd = sb.allSkyDB(dateID, sqlQ=sqlQ, dtypes=dtypes)
    if data.size > nStarLimit:
        IDsWithStars += 1
        alt,az,pa = _altAzPaFromRaDec(np.radians(data['ra']), np.radians(data['dec']),
                                      ObservationMetaData(mjd=mjd,site=telescope))

        # Let's trim off any overly high airmass values
        good = np.where(alt > np.radians(altLimit))
        data = data[good]
        hpids = hp.ang2pix(nside, np.pi/2.-alt[good], az[good])
        # Extend the lists
        starIDs.extend(data['starID'].tolist())
        dateIDs.extend([dateID]*np.size(data))
        hpIDs.extend(hpids.tolist())
        starMags.extend(data['starMag'].tolist() )
        starMags_err.extend( data['starMag_err'].tolist())
        mjds.extend([mjd]* np.size(data))
        airmasses.extend((1./np.cos(np.pi/2-alt[good])).tolist() )

print 'Finished reading data'
Exemplo n.º 23
0
    def setRaDecMjd(self,lon,lat,mjd,degrees=False,azAlt=False,solarFlux=130.):
        """
        Set the sky parameters by computing the sky conditions on a given MJD and sky location.

        Ra and Dec in raidans or degrees.
        input ra, dec or az,alt w/ altAz=True
        solarFlux: solar flux in s.f.u. Between 50 and 310.
        """
        # Wrap in array just in case single points were passed
        if not type(lon).__module__ == np.__name__ :
            if np.size(lon) == 1:
                lon = np.array([lon])
                lat = np.array([lat])
            else:
                lon = np.array(lon)
                lat = np.array(lat)
        if degrees:
            self.ra = np.radians(lon)
            self.dec = np.radians(lat)
        else:
            self.ra = lon
            self.dec = lat
        self.mjd = mjd
        if azAlt:
            self.azs = self.ra.copy()
            self.alts = self.dec.copy()
            self.ra,self.dec = _raDecFromAltAz(self.alts,self.azs, self.Observatory.lon,
                                               self.Observatory.lat, self.mjd)
        else:
            self.alts,self.azs,pa = _altAzPaFromRaDec(self.ra, self.dec, self.Observatory.lon,
                                                      self.Observatory.lat, self.mjd)

        self.npts = self.ra.size
        self._initPoints()

        self.solarFlux = solarFlux
        self.points['solarFlux'] = self.solarFlux

        # Switch to Dublin Julian Date for pyephem
        self.Observatory.date = mjd2djd(self.mjd)

        sun = ephem.Sun()
        sun.compute(self.Observatory)
        self.sunAlt = sun.alt
        self.sunAz = sun.az

        # Compute airmass the same way as ESO model
        self.airmass = 1./np.cos(np.pi/2.-self.alts)

        self.points['airmass'] = self.airmass
        self.points['nightTimes'] = 2
        self.points['alt'] = self.alts
        self.points['az'] = self.azs

        if self.twilight:
            self.points['sunAlt'] = self.sunAlt
            self.points['azRelSun'] = wrapRA(self.azs - self.sunAz)

        if self.moon:
            moon = ephem.Moon()
            moon.compute(self.Observatory)
            self.moonPhase = moon.phase
            self.moonAlt = moon.alt
            self.moonAz = moon.az
            # Calc azimuth relative to moon
            self.azRelMoon = wrapRA(self.azs - self.moonAz)
            over = np.where(self.azRelMoon > np.pi)
            self.azRelMoon[over] = 2.*np.pi - self.azRelMoon[over]
            self.points['moonAltitude'] += np.degrees(self.moonAlt)
            self.points['azRelMoon'] += self.azRelMoon
            self.points['moonSunSep'] += self.moonPhase/100.*180.


        if self.zodiacal:
            self.eclipLon = np.zeros(self.npts)
            self.eclipLat = np.zeros(self.npts)

            for i,temp in enumerate(self.ra):
                eclip = ephem.Ecliptic(ephem.Equatorial(self.ra[i],self.dec[i], epoch='2000'))
                self.eclipLon[i] += eclip.lon
                self.eclipLat[i] += eclip.lat
            # Subtract off the sun ecliptic longitude
            sunEclip = ephem.Ecliptic(sun)
            self.sunEclipLon = sunEclip.lon
            self.points['altEclip'] += self.eclipLat
            self.points['azEclipRelSun'] += wrapRA(self.eclipLon - self.sunEclipLon)
Exemplo n.º 24
0
kwargs = dict(twilight=False,
              zodiacal=False,
              moon=True,
              scatteredStar=False,
              mergedSpec=False)

sm = sb.SkyModel(observatory='LSST', mags=True)  # , **kwargs)
mjd = 49353.177645
sm.setRaDecMjd(ra, dec, mjd)
mag = sm.returnMags()
lmst, last = calcLmstLast(mjd, telescope.longitude_rad)

moonRA, moonDec = _raDecFromAltAz(sm.moonAlt, sm.moonAz,
                                  ObservationMetaData(mjd=mjd, site=telescope))

alt, az, pa = _altAzPaFromRaDec(ra, dec,
                                ObservationMetaData(mjd=mjd, site=telescope))
angDist2Moon = np.degrees(haversine(az, alt, sm.moonAz, sm.moonAlt))
ang2 = np.degrees(haversine(ra, dec, moonRA, moonDec))
alt = np.degrees(alt)

mags = -0.5 * (np.nanmin(mag['u']) - mag['u'])

#extent = (0,130, 0,90)
extent = (20, 120, 20, 90)

xs, ys = np.mgrid[extent[0]:extent[1], extent[2]:extent[3]]
resampled = griddata((angDist2Moon, alt), mags, (xs, ys))
notInf = np.where((resampled != np.inf) & (~np.isnan(resampled)))

resampled[notInf] = resampled[notInf] - resampled[notInf].max()
Exemplo n.º 25
0
        left = np.searchsorted(data['mjd'], umjd)
        right = np.searchsorted(data['mjd'], umjd, side='right')

        altaz = np.zeros(data.size, dtype=list(zip(['alt', 'az'], [float]*2)))
        moonAlt = np.zeros(data.size, dtype=float)

        print('computing alts and azs')

        for j, (le, ri, mjd) in enumerate(zip(left, right, umjd)):
            Observatory.date = mjd2djd(mjd)
            sun.compute(Observatory)
            obs_metadata = ObservationMetaData(pointingRA=np.degrees(sun.ra),
                                               pointingDec=np.degrees(sun.dec),
                                               rotSkyPos=np.degrees(0),
                                               mjd=mjd)
            alt, az, pa = _altAzPaFromRaDec(data['ra'][le:ri], data['dec'][le:ri], obs_metadata)
            az = wrapRA(az - sun.az)
            altaz['alt'][le:ri] += alt
            altaz['az'][le:ri] += az
            moon.compute(Observatory)
            moonAlt[le:ri] += moon.alt

        print('making maps')
        good = np.where(moonAlt < 0)
        magMap[:, i] = _healbin(altaz['az'][good], altaz['alt'][good], data['sky'][good],
                                nside=nside, reduceFunc=np.median)
        rmsMap[:, i] = _healbin(altaz['az'][good], altaz['alt'][good], data['sky'][good],
                                nside=nside, reduceFunc=robustRMS)

    print('saving maps')
    np.savez('TwilightMaps/twiMaps_%s.npz' % filterName, magMap=magMap, rmsMap=rmsMap, sunAlts=sunAlts)