def testRaDecFromAltAz(self):
        azList = self.raList
        altList = self.decList
        mjd = 47895.6
        obs = ObservationMetaData(mjd=mjd, site=Site(longitude=self.lon, latitude=self.lat, name='LSST'))

        raRad, decRad = utils._raDecFromAltAz(altList, azList, obs)

        raDeg, decDeg = utils.raDecFromAltAz(np.degrees(altList),
                                             np.degrees(azList), obs)


        np.testing.assert_array_almost_equal(raRad, np.radians(raDeg), 10)
        np.testing.assert_array_almost_equal(decRad, np.radians(decDeg), 10)

        raRad, decRad = utils._raDecFromAltAz(altList, azList, obs)

        raDeg, decDeg = utils.raDecFromAltAz(np.degrees(altList),
                                             np.degrees(azList), obs)


        np.testing.assert_array_almost_equal(raRad, np.radians(raDeg), 10)
        np.testing.assert_array_almost_equal(decRad, np.radians(decDeg), 10)


        for alt, az in zip(altList, azList):
            raRad, decRad = utils._raDecFromAltAz(alt, az, obs)
            raDeg, decDeg = utils.raDecFromAltAz(np.degrees(alt),
                                                 np.degrees(az), obs)

            self.assertAlmostEqual(raRad, np.radians(raDeg), 10)
            self.assertAlmostEqual(decRad, np.radians(decDeg), 10)
Beispiel #2
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)
    def testRaDecFromAltAz(self):
        azList = self.raList
        altList = self.decList
        mjd = 47895.6
        obs = ObservationMetaData(mjd=mjd,
                                  site=Site(longitude=self.lon,
                                            latitude=self.lat,
                                            name='LSST'))

        raRad, decRad = utils._raDecFromAltAz(altList, azList, obs)

        raDeg, decDeg = utils.raDecFromAltAz(np.degrees(altList),
                                             np.degrees(azList), obs)

        np.testing.assert_array_almost_equal(raRad, np.radians(raDeg), 10)
        np.testing.assert_array_almost_equal(decRad, np.radians(decDeg), 10)

        raRad, decRad = utils._raDecFromAltAz(altList, azList, obs)

        raDeg, decDeg = utils.raDecFromAltAz(np.degrees(altList),
                                             np.degrees(azList), obs)

        np.testing.assert_array_almost_equal(raRad, np.radians(raDeg), 10)
        np.testing.assert_array_almost_equal(decRad, np.radians(decDeg), 10)

        for alt, az in zip(altList, azList):
            raRad, decRad = utils._raDecFromAltAz(alt, az, obs)
            raDeg, decDeg = utils.raDecFromAltAz(np.degrees(alt),
                                                 np.degrees(az), obs)

            self.assertAlmostEqual(raRad, np.radians(raDeg), 10)
            self.assertAlmostEqual(decRad, np.radians(decDeg), 10)
def makeObservationMetaData():
    #create a cartoon ObservationMetaData object
    mjd = 52000.0
    alt = numpy.pi/2.0
    az = 0.0
    band = 'r'
    testSite = Site(latitude=numpy.degrees(0.5), longitude=numpy.degrees(1.1), height=3000,
                    temperature=260.0, pressure=725.0, lapseRate=0.005, humidity=0.4)
    obsTemp = ObservationMetaData(site=testSite, mjd=mjd)
    centerRA, centerDec = _raDecFromAltAz(alt, az, obsTemp)
    rotTel = _getRotTelPos(centerRA, centerDec, obsTemp, 0.0)

    obsDict = calcObsDefaults(centerRA, centerDec, alt, az, rotTel, mjd, band,
                 testSite.longitude_rad, testSite.latitude_rad)

    obsDict['Opsim_expmjd'] = mjd
    radius = 0.1
    phoSimMetaData = OrderedDict([
                      (k, (obsDict[k],numpy.dtype(type(obsDict[k])))) for k in obsDict])

    obs_metadata = ObservationMetaData(boundType='circle', boundLength=2.0*radius,
                                       phoSimMetaData=phoSimMetaData, site=testSite)



    return obs_metadata
    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()
Beispiel #6
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 testaltaz2radec(self):
        np.random.seed(42)
        az = np.random.rand(100)*np.pi*2
        alt = np.random.rand(100)*np.pi-np.pi/2
        site = Site('LSST')
        mjd = 55000
        omd = ObservationMetaData(mjd=mjd,site=site)

        trueRA,trueDec = _raDecFromAltAz(alt,az, omd)
        fastRA,fastDec = sb.stupidFast_altAz2RaDec(alt,az,site.latitude_rad,
                                                   site.longitude_rad,mjd)
        distanceDiff = haversine(trueRA,trueDec, fastRA,fastDec)
        degreeTol =2.  # 2-degree tolerance on the fast transform
        assert(np.degrees(distanceDiff.max()) < degreeTol)
    def testaltaz2radec(self):
        np.random.seed(42)
        az = np.random.rand(100) * np.pi * 2
        alt = np.random.rand(100) * np.pi - np.pi / 2
        site = Site('LSST')
        mjd = 55000
        omd = ObservationMetaData(mjd=mjd, site=site)

        trueRA, trueDec = _raDecFromAltAz(alt, az, omd)
        fastRA, fastDec = sb.stupidFast_altAz2RaDec(alt, az, site.latitude_rad,
                                                    site.longitude_rad, mjd)
        distanceDiff = haversine(trueRA, trueDec, fastRA, fastDec)
        degreeTol = 2.  # 2-degree tolerance on the fast transform
        assert (np.degrees(distanceDiff.max()) < degreeTol)
    def test_icrsFromObserved(self):
        """
        Test that _icrsFromObserved really inverts _observedFromAppGeo.

        In this case, the method is only reliable at distances of more than
        45 degrees from the sun and at zenith distances less than 70 degrees.
        """

        numpy.random.seed(412)
        nSamples = 100

        mjd2000 = pal.epb(2000.0) # convert epoch to mjd

        site = Site(name='LSST')

        for mjd in (53000.0, 53241.6, 58504.6):
            for includeRefraction in (True, False):
                for raPointing in (23.5, 256.9, 100.0):
                    for decPointing in (-12.0, 45.0, 66.8):

                        obs = ObservationMetaData(mjd=mjd, site=site)

                        raZenith, decZenith = _raDecFromAltAz(0.5*numpy.pi, 0.0, obs)

                        obs = ObservationMetaData(pointingRA=raPointing, pointingDec=decPointing,
                                                  mjd=mjd, site=site)

                        rr = numpy.random.random_sample(nSamples)*numpy.radians(50.0)
                        theta = numpy.random.random_sample(nSamples)*2.0*numpy.pi

                        ra_in = raZenith + rr*numpy.cos(theta)
                        dec_in = decZenith + rr*numpy.sin(theta)

                        # test a round-trip between observedFromICRS and icrsFromObserved
                        ra_obs, dec_obs = _observedFromICRS(ra_in, dec_in, obs_metadata=obs,
                                                            includeRefraction=includeRefraction,
                                                            epoch=2000.0)

                        ra_icrs, dec_icrs = _icrsFromObserved(ra_obs, dec_obs, obs_metadata=obs,
                                                              includeRefraction=includeRefraction,
                                                              epoch=2000.0)

                        valid_pts = numpy.where(_distanceToSun(ra_in, dec_in, mjd)>0.25*numpy.pi)[0]

                        self.assertGreater(len(valid_pts), 0)

                        distance = arcsecFromRadians(pal.dsepVector(ra_in[valid_pts], dec_in[valid_pts],
                                                     ra_icrs[valid_pts], dec_icrs[valid_pts]))

                        self.assertLess(distance.max(), 0.01)


                        # test a round-trip between observedFromAppGeo and appGeoFromObserved
                        ra_obs, dec_obs = _observedFromAppGeo(ra_in, dec_in, obs_metadata=obs,
                                                              includeRefraction=includeRefraction)
                        ra_app, dec_app = _appGeoFromObserved(ra_obs, dec_obs, obs_metadata=obs,
                                                                includeRefraction=includeRefraction)

                        distance = arcsecFromRadians(pal.dsepVector(ra_in[valid_pts], dec_in[valid_pts],
                                                     ra_app[valid_pts], dec_app[valid_pts]))

                        self.assertLess(distance.max(), 0.01)
Beispiel #10
0
def makePhoSimTestDB(filename='PhoSimTestDatabase.db',
                     size=1000,
                     seedVal=32,
                     radius=0.1,
                     deltaRA=None,
                     deltaDec=None,
                     bandpass='******',
                     m5=None,
                     seeing=None,
                     magnorm_min=17.0,
                     delta_magnorm=4.0,
                     **kwargs):
    """
    Make a test database to storing cartoon information for the test phoSim input
    catalog to use.

    The method will return an ObservationMetaData object guaranteed to encompass the
    objects in this database.

    @param [in] filename is a string indicating the name of the DB file to be created

    @param [in] size is the number of objects int he database

    @param [in] seedVal is the seed passed to the random number generator

    @param [in] radius is the radius (in degrees) of the field of view to be returned

    @param [in] bandpass is the bandpas(es) of the observation to be passed to
    ObservationMetaData (optional)

    @param [in] m5 is the m5 value(s) to be passed to ObservationMetaData
    (optional)

    @param [in] seeing is the seeing value(s) in arcseconds to be passed to
    ObservationMetaData (optional)

    @param [in] deltaRA/Dec are numpy arrays that indicate where (in relation to the center
    of the field of view) objects should be placed.  These coordinates are in degrees.  Specifying
    either of these paramters will overwrite size.  If you only specify one of these parameters, the other
    will be set randomly.  These parameters are optional.

    @param [in] magnorm_min is the min magnorm (magNorms for sources in the database will be
    distributed according to a random deviate drawn from magnorm_min + random*delta_magnorm)

    @param [in] delta_magnorm (see documentation for magnorm_min)
    """

    if os.path.exists(filename):
        os.unlink(filename)

    # just an example of some valid SED file names
    galaxy_seds = [
        'Const.80E07.02Z.spec', 'Inst.80E07.002Z.spec',
        'Burst.19E07.0005Z.spec'
    ]
    agn_sed = 'agn.spec'
    star_seds = [
        'km20_5750.fits_g40_5790', 'm2.0Full.dat', 'bergeron_6500_85.dat_6700'
    ]

    rng = np.random.RandomState(seedVal)

    if deltaRA is not None and deltaDec is not None:
        if len(deltaRA) != len(deltaDec):
            raise RuntimeError("WARNING in makePhoSimTestDB deltaRA and "
                               "deltaDec have different lengths")

    if deltaRA is not None:
        size = len(deltaRA)
    elif deltaDec is not None:
        size = len(deltaDec)

    # create the ObservationMetaData object
    mjd = 52000.0
    alt = np.pi / 2.0
    az = 0.0

    testSite = Site(name='LSST')
    obsTemp = ObservationMetaData(mjd=mjd, site=testSite)
    centerRA, centerDec = _raDecFromAltAz(alt, az, obsTemp)
    rotTel = _getRotTelPos(centerRA, centerDec, obsTemp, 0.0)
    rotSkyPos = _getRotSkyPos(centerRA, centerDec, obsTemp, rotTel)

    obs_metadata = ObservationMetaData(pointingRA=np.degrees(centerRA),
                                       pointingDec=np.degrees(centerDec),
                                       rotSkyPos=np.degrees(rotSkyPos),
                                       bandpassName=bandpass,
                                       mjd=mjd,
                                       boundType='circle',
                                       boundLength=2.0 * radius,
                                       site=testSite,
                                       m5=m5,
                                       seeing=seeing)

    moon_alt = -90.0
    sun_alt = -90.0

    moon_ra, moon_dec = raDecFromAltAz(moon_alt, 0.0, obs_metadata)
    dist2moon = haversine(np.radians(moon_ra), np.radians(moon_dec),
                          obs_metadata._pointingRA, obs_metadata._pointingDec)

    obs_metadata.OpsimMetaData = {
        'moonra': moon_ra,
        'moondec': moon_dec,
        'moonalt': moon_alt,
        'sunalt': sun_alt,
        'dist2moon': dist2moon,
        'rottelpos': np.degrees(rotTel)
    }

    # Now begin building the database.
    # First create the tables.
    conn = sqlite3.connect(filename)
    c = conn.cursor()
    try:
        c.execute('''CREATE TABLE galaxy_bulge
                 (galtileid int, galid int, bra real, bdec real, ra real, dec real, magnorm_bulge real,
                 sedname_bulge text, a_b real, b_b real, pa_bulge real, bulge_n int,
                 ext_model_b text, av_b real, rv_b real, u_ab real, g_ab real, r_ab real, i_ab real,
                 z_ab real, y_ab real, redshift real, BulgeHalfLightRadius real)'''
                  )
        conn.commit()
    except:
        raise RuntimeError("Error creating galaxy_bulge table.")

    try:
        c.execute('''CREATE TABLE galaxy
                     (galtileid int, galid int, ra real, dec real,
                      bra real, bdec real, dra real, ddec real,
                      agnra real, agndec real,
                      magnorm_bulge, magnorm_disk, magnorm_agn,
                      sedname_bulge text, sedname_disk text, sedname_agn text,
                      varParamStr text,
                      a_b real, b_b real, pa_bulge real, bulge_n int,
                      a_d real, b_d real, pa_disk real, disk_n int,
                      ext_model_b text, av_b real, rv_b real,
                      ext_model_d text, av_d real, rv_d real,
                      u_ab real, g_ab real, r_ab real, i_ab real,
                      z_ab real, y_ab real,
                      redshift real, BulgeHalfLightRadius real, DiskHalfLightRadius real)'''
                  )

        conn.commit()
    except:
        raise RuntimeError("Error creating galaxy table.")

    try:
        c.execute('''CREATE TABLE galaxy_agn
                  (galtileid int, galid int, agnra real, agndec real, ra real, dec real,
                  magnorm_agn real, sedname_agn text, varParamStr text, u_ab real,
                  g_ab real, r_ab real, i_ab real, z_ab real, y_ab real, redshift real)'''
                  )
    except:
        raise RuntimeError("Error creating galaxy_agn table.")

    try:
        c.execute('''CREATE TABLE StarAllForceseek
                  (simobjid int, ra real, decl real, magNorm real,
                  mudecl real, mura real, galacticAv real, vrad real, varParamStr text,
                  sedFilename text, parallax real, ebv real)''')
    except:
        raise RuntimeError("Error creating StarAllForceseek table.")

    # Now generate the data to be stored in the tables.

    rr = rng.random_sample(size) * np.radians(radius)
    theta = rng.random_sample(size) * 2.0 * np.pi

    if deltaRA is None:
        ra = np.degrees(centerRA + rr * np.cos(theta))
    else:
        ra = np.degrees(centerRA) + deltaRA

    if deltaDec is None:
        dec = np.degrees(centerDec + rr * np.sin(theta))
    else:
        dec = np.degrees(centerDec) + deltaDec

    bra = np.radians(ra + rng.random_sample(size) * 0.01 * radius)
    bdec = np.radians(dec + rng.random_sample(size) * 0.01 * radius)
    dra = np.radians(ra + rng.random_sample(size) * 0.01 * radius)
    ddec = np.radians(dec + rng.random_sample(size) * 0.01 * radius)
    agnra = np.radians(ra + rng.random_sample(size) * 0.01 * radius)
    agndec = np.radians(dec + rng.random_sample(size) * 0.01 * radius)

    magnorm_bulge = rng.random_sample(size) * delta_magnorm + magnorm_min
    magnorm_disk = rng.random_sample(size) * delta_magnorm + magnorm_min
    magnorm_agn = rng.random_sample(size) * delta_magnorm + magnorm_min
    b_b = rng.random_sample(size) * 0.2
    a_b = b_b + rng.random_sample(size) * 0.05
    b_d = rng.random_sample(size) * 0.5
    a_d = b_d + rng.random_sample(size) * 0.1

    BulgeHalfLightRadius = rng.random_sample(size) * 0.2
    DiskHalfLightRadius = rng.random_sample(size) * 0.5

    pa_bulge = rng.random_sample(size) * 360.0
    pa_disk = rng.random_sample(size) * 360.0

    av_b = rng.random_sample(size) * 0.3
    av_d = rng.random_sample(size) * 0.3
    rv_b = rng.random_sample(size) * 0.1 + 2.0
    rv_d = rng.random_sample(size) * 0.1 + 2.0

    u_ab = rng.random_sample(size) * 4.0 + 17.0
    g_ab = rng.random_sample(size) * 4.0 + 17.0
    r_ab = rng.random_sample(size) * 4.0 + 17.0
    i_ab = rng.random_sample(size) * 4.0 + 17.0
    z_ab = rng.random_sample(size) * 4.0 + 17.0
    y_ab = rng.random_sample(size) * 4.0 + 17.0
    redshift = rng.random_sample(size) * 2.0

    t0_mjd = mjd - rng.random_sample(size) * 1000.0
    agn_tau = rng.random_sample(size) * 1000.0 + 1000.0
    agnSeed = rng.randint(2, 4001, size=size)
    agn_sfu = rng.random_sample(size)
    agn_sfg = rng.random_sample(size)
    agn_sfr = rng.random_sample(size)
    agn_sfi = rng.random_sample(size)
    agn_sfz = rng.random_sample(size)
    agn_sfy = rng.random_sample(size)

    rrStar = rng.random_sample(size) * np.radians(radius)
    thetaStar = rng.random_sample(size) * 2.0 * np.pi

    if deltaRA is None:
        raStar = centerRA + rrStar * np.cos(thetaStar)
    else:
        raStar = centerRA + np.radians(deltaRA)

    if deltaDec is None:
        decStar = centerDec + rrStar * np.sin(thetaStar)
    else:
        decStar = centerDec + np.radians(deltaDec)

    raStar = np.degrees(raStar)
    decStar = np.degrees(decStar)

    magnormStar = rng.random_sample(size) * delta_magnorm + magnorm_min
    mudecl = rng.random_sample(size) * 0.0001
    mura = rng.random_sample(size) * 0.0001
    galacticAv = rng.random_sample(size) * 0.05 * 3.1
    vrad = rng.random_sample(size) * 1.0
    parallax = 0.00045 + rng.random_sample(size) * 0.00001
    period = rng.random_sample(size) * 20.0
    amp = rng.random_sample(size) * 5.0

    # write the data to the tables.
    for i in range(size):

        cmd = '''INSERT INTO galaxy_bulge VALUES (%i, %i, %f, %f, %f, %f, %f,
              '%s', %f, %f, %f, %i, '%s', %f, %f, %f, %f, %f, %f, %f, %f, %f, %f)''' % \
              (i, i, bra[i], bdec[i], ra[i], dec[i], magnorm_bulge[i], galaxy_seds[i%len(galaxy_seds)],
               a_b[i], b_b[i], pa_bulge[i], 4, 'CCM', av_b[i], rv_b[i], u_ab[i], g_ab[i],
               r_ab[i], i_ab[i], z_ab[i], y_ab[i], redshift[i], BulgeHalfLightRadius[i])

        c.execute(cmd)

        varParam = {
            'varMethodName': 'applyAgn',
            'pars': {
                'agn_tau': round(agn_tau[i], 4),
                't0_mjd': round(t0_mjd[i], 4),
                'agn_sfu': round(agn_sfu[i], 4),
                'agn_sfg': round(agn_sfg[i], 4),
                'agn_sfr': round(agn_sfr[i], 4),
                'agn_sfi': round(agn_sfi[i], 4),
                'agn_sfz': round(agn_sfz[i], 4),
                'agn_sfy': round(agn_sfy[i], 4),
                'seed': int(agnSeed[i])
            }
        }

        paramStr = json.dumps(varParam)

        cmd = '''INSERT INTO galaxy VALUES (%i, %i, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f,
                                            '%s', '%s', '%s', '%s',
                                            %f, %f, %f, %i,
                                            %f, %f, %f, %i,
                                            '%s', %f, %f,
                                            '%s', %f, %f,
                                            %f, %f, %f, %f, %f, %f,
                                            %f, %f, %f)''' % \
              (i, i, ra[i], dec[i], bra[i], bdec[i], dra[i], ddec[i], agnra[i], agndec[i],
               magnorm_bulge[i], magnorm_disk[i], magnorm_agn[i],
               galaxy_seds[i%len(galaxy_seds)], galaxy_seds[i%len(galaxy_seds)], agn_sed,
               paramStr,
               a_b[i], b_b[i], pa_bulge[i], 4,
               a_d[i], b_d[i], pa_disk[i], 1,
               'CCM', av_b[i], rv_b[i],
               'CCM', av_d[i], rv_d[i],
               u_ab[i], g_ab[i], r_ab[i], i_ab[i], z_ab[i], y_ab[i], redshift[i],
               BulgeHalfLightRadius[i], DiskHalfLightRadius[i])
        c.execute(cmd)

        cmd = '''INSERT INTO galaxy_agn VALUES (%i, %i, %f, %f, %f, %f, %f, '%s', '%s',
              %f, %f, %f, %f, %f, %f, %f)''' % \
              (i, i, agnra[i], agndec[i], ra[i], dec[i],
               magnorm_agn[i], agn_sed, paramStr,
               u_ab[i], g_ab[i], r_ab[i], i_ab[i],
               z_ab[i], y_ab[i], redshift[i])

        c.execute(cmd)

        varParam = {
            'varMethodName': 'testVar',
            'pars': {
                'period': period[i],
                'amplitude': amp[i]
            }
        }
        paramStr = json.dumps(varParam)
        cmd = '''INSERT INTO StarAllForceseek VALUES (%i, %f, %f, %f, %f, %f, %f, %f, '%s', '%s', %f, %f)''' %\
              (i, raStar[i], decStar[i], magnormStar[i], mudecl[i], mura[i],
               galacticAv[i], vrad[i], paramStr, star_seds[i%len(star_seds)], parallax[i],
               galacticAv[i]/3.1)

        c.execute(cmd)

    conn.commit()
    conn.close()
    return obs_metadata
Beispiel #11
0
# Let's recreate the delta m_5 plot from figure 3 in:
# http://xxx.lanl.gov/pdf/1510.07574.pdf
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)))
Beispiel #12
0
                                                np.radians(skydata['dec']),
                                                telescope.lon, telescope.lat,
                                                mjd)
                skyhp = healbin(az, alt, skydata['sky'], nside=nside)
                skyhp[np.isnan(skyhp)] = hp.UNSEEN

                good = np.where(skyhp != hp.UNSEEN)
                sm.setRaDecMjd(hpra[good],
                               hpdec[good],
                               mjd,
                               degrees=False,
                               azAlt=True)

                # switch moon to ra dec
                moonRA, moonDec = _raDecFromAltAz(sm.moonAlt, sm.moonAz,
                                                  telescope.lon, telescope.lat,
                                                  mjd)
                # compute distances
                moonDistances = haversine(hpra[good], hpdec[good], moonRA,
                                          moonDec)
                closeToMoon = np.where(moonDistances < np.radians(moonLimit))

                modelhp = np.zeros(npix, dtype=float) + hp.UNSEEN
                modelhp[good] = sm.returnMags(canonDict[filterName])
                modelhp[good][closeToMoon] = hp.UNSEEN
                good = np.where(modelhp != hp.UNSEEN)
                validationArr['frameZP'][i] = np.median(modelhp[good] -
                                                        skyhp[good])

                notnan = np.where(skyhp != hp.UNSEEN)
                validationArr['obsDarkestHP'][i] = np.where(
Beispiel #13
0
    def test_raDecFromAltAz(self):
        """
        Test conversion of Alt, Az to Ra, Dec using data on the Sun

        This site gives the altitude and azimuth of the Sun as a function
        of time and position on the earth

        http://aa.usno.navy.mil/data/docs/AltAz.php

        This site gives the apparent geocentric RA, Dec of major celestial objects
        as a function of time

        http://aa.usno.navy.mil/data/docs/geocentric.php

        This site converts calendar dates into Julian Dates

        http://aa.usno.navy.mil/data/docs/JulianDate.php
        """

        hours = np.radians(360.0 / 24.0)
        minutes = hours / 60.0
        seconds = minutes / 60.0

        longitude_list = []
        latitude_list = []
        mjd_list = []
        alt_list = []
        az_list = []
        ra_app_list = []
        dec_app_list = []

        longitude_list.append(np.radians(-22.0 - 33.0 / 60.0))
        latitude_list.append(np.radians(11.0 + 45.0 / 60.0))
        mjd_list.append(2457364.958333 - 2400000.5)  # 8 December 2015 11:00 UTC
        alt_list.append(np.radians(41.1))
        az_list.append(np.radians(134.7))
        ra_app_list.append(16.0 * hours + 59.0 * minutes + 16.665 * seconds)
        dec_app_list.append(np.radians(-22.0 - 42.0 / 60.0 - 2.94 / 3600.0))

        longitude_list.append(np.radians(-22.0 - 33.0 / 60.0))
        latitude_list.append(np.radians(11.0 + 45.0 / 60.0))
        mjd_list.append(2457368.958333 - 2400000.5)  # 12 December 2015 11:00 UTC
        alt_list.append(np.radians(40.5))
        az_list.append(np.radians(134.7))
        ra_app_list.append(17.0 * hours + 16.0 * minutes + 51.649 * seconds)
        dec_app_list.append(np.radians(-23.0 - 3 / 60.0 - 50.35 / 3600.0))

        longitude_list.append(np.radians(145.0 + 23.0 / 60.0))
        latitude_list.append(np.radians(-64.0 - 5.0 / 60.0))
        mjd_list.append(2456727.583333 - 2400000.5)  # 11 March 2014, 02:00 UTC
        alt_list.append(np.radians(29.5))
        az_list.append(np.radians(8.2))
        ra_app_list.append(23.0 * hours + 24.0 * minutes + 46.634 * seconds)
        dec_app_list.append(np.radians(-3.0 - 47.0 / 60.0 - 47.81 / 3600.0))

        longitude_list.append(np.radians(145.0 + 23.0 / 60.0))
        latitude_list.append(np.radians(-64.0 - 5.0 / 60.0))
        mjd_list.append(2456731.583333 - 2400000.5)  # 15 March 2014, 02:00 UTC
        alt_list.append(np.radians(28.0))
        az_list.append(np.radians(7.8))
        ra_app_list.append(23.0 * hours + 39.0 * minutes + 27.695 * seconds)
        dec_app_list.append(np.radians(-2.0 - 13.0 / 60.0 - 18.32 / 3600.0))

        for longitude, latitude, mjd, alt, az, ra_app, dec_app in \
            zip(longitude_list, latitude_list, mjd_list, alt_list, az_list,
                ra_app_list, dec_app_list):

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

            ra_icrs, dec_icrs = utils._raDecFromAltAz(alt, az, obs)
            ra_test, dec_test = utils._appGeoFromICRS(ra_icrs, dec_icrs, mjd=obs.mjd)

            distance = np.degrees(utils.haversine(ra_app, dec_app, ra_test, dec_test))
            # this is all the precision we have in the alt,az data taken from the USNO
            self.assertLess(distance, 0.1)

            correction = np.degrees(utils.haversine(ra_test, dec_test, ra_icrs, dec_icrs))
            self.assertLess(distance, correction)
Beispiel #14
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')
    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)
Beispiel #16
0
def makePhoSimTestDB(filename='PhoSimTestDatabase.db', size=1000, seedVal=32, radius=0.1,
                     deltaRA=None, deltaDec=None,
                     bandpass='******', m5=None, seeing=None,
                     magnorm_min=17.0, delta_magnorm=4.0, **kwargs):
    """
    Make a test database to storing cartoon information for the test phoSim input
    catalog to use.

    The method will return an ObservationMetaData object guaranteed to encompass the
    objects in this database.

    @param [in] filename is a string indicating the name of the DB file to be created

    @param [in] size is the number of objects int he database

    @param [in] seedVal is the seed passed to the random number generator

    @param [in] radius is the radius (in degrees) of the field of view to be returned

    @param [in] bandpass is the bandpas(es) of the observation to be passed to
    ObservationMetaData (optional)

    @param [in] m5 is the m5 value(s) to be passed to ObservationMetaData
    (optional)

    @param [in] seeing is the seeing value(s) in arcseconds to be passed to
    ObservationMetaData (optional)

    @param [in] deltaRA/Dec are numpy arrays that indicate where (in relation to the center
    of the field of view) objects should be placed.  These coordinates are in degrees.  Specifying
    either of these paramters will overwrite size.  If you only specify one of these parameters, the other
    will be set randomly.  These parameters are optional.

    @param [in] magnorm_min is the min magnorm (magNorms for sources in the database will be
    distributed according to a random deviate drawn from magnorm_min + random*delta_magnorm)

    @param [in] delta_magnorm (see documentation for magnorm_min)
    """

    if os.path.exists(filename):
        os.unlink(filename)

    # just an example of some valid SED file names
    galaxy_seds = ['Const.80E07.02Z.spec', 'Inst.80E07.002Z.spec', 'Burst.19E07.0005Z.spec']
    agn_sed = 'agn.spec'
    star_seds = ['km20_5750.fits_g40_5790', 'm2.0Full.dat', 'bergeron_6500_85.dat_6700']

    rng = np.random.RandomState(seedVal)

    if deltaRA is not None and deltaDec is not None:
        if len(deltaRA) != len(deltaDec):
            raise RuntimeError("WARNING in makePhoSimTestDB deltaRA and "
                               "deltaDec have different lengths")

    if deltaRA is not None:
        size = len(deltaRA)
    elif deltaDec is not None:
        size = len(deltaDec)

    # create the ObservationMetaData object
    mjd = 52000.0
    alt = np.pi/2.0
    az = 0.0

    testSite = Site(name='LSST')
    obsTemp = ObservationMetaData(mjd=mjd, site=testSite)
    centerRA, centerDec = _raDecFromAltAz(alt, az, obsTemp)
    rotTel = _getRotTelPos(centerRA, centerDec, obsTemp, 0.0)
    rotSkyPos = _getRotSkyPos(centerRA, centerDec, obsTemp, rotTel)

    obs_metadata = ObservationMetaData(pointingRA=np.degrees(centerRA),
                                       pointingDec=np.degrees(centerDec),
                                       rotSkyPos=np.degrees(rotSkyPos),
                                       bandpassName=bandpass,
                                       mjd=mjd,
                                       boundType = 'circle', boundLength = 2.0*radius,
                                       site=testSite,
                                       m5=m5, seeing=seeing)

    moon_alt = -90.0
    sun_alt = -90.0

    moon_ra, moon_dec = raDecFromAltAz(moon_alt, 0.0, obs_metadata)
    dist2moon = haversine(np.radians(moon_ra), np.radians(moon_dec),
                          obs_metadata._pointingRA, obs_metadata._pointingDec)

    obs_metadata.OpsimMetaData = {'moonra': moon_ra,
                                  'moondec': moon_dec,
                                  'moonalt': moon_alt,
                                  'sunalt': sun_alt,
                                  'dist2moon': dist2moon,
                                  'rottelpos': np.degrees(rotTel)}

    # Now begin building the database.
    # First create the tables.
    conn = sqlite3.connect(filename)
    c = conn.cursor()
    try:
        c.execute('''CREATE TABLE galaxy_bulge
                 (galtileid int, galid int, bra real, bdec real, ra real, dec real, magnorm_bulge real,
                 sedname_bulge text, a_b real, b_b real, pa_bulge real, bulge_n int,
                 ext_model_b text, av_b real, rv_b real, u_ab real, g_ab real, r_ab real, i_ab real,
                 z_ab real, y_ab real, redshift real, BulgeHalfLightRadius real)''')
        conn.commit()
    except:
        raise RuntimeError("Error creating galaxy_bulge table.")

    try:
        c.execute('''CREATE TABLE galaxy
                     (galtileid int, galid int, ra real, dec real,
                      bra real, bdec real, dra real, ddec real,
                      agnra real, agndec real,
                      magnorm_bulge, magnorm_disk, magnorm_agn,
                      sedname_bulge text, sedname_disk text, sedname_agn text,
                      varParamStr text,
                      a_b real, b_b real, pa_bulge real, bulge_n int,
                      a_d real, b_d real, pa_disk real, disk_n int,
                      ext_model_b text, av_b real, rv_b real,
                      ext_model_d text, av_d real, rv_d real,
                      u_ab real, g_ab real, r_ab real, i_ab real,
                      z_ab real, y_ab real,
                      redshift real, BulgeHalfLightRadius real, DiskHalfLightRadius real)''')

        conn.commit()
    except:
        raise RuntimeError("Error creating galaxy table.")

    try:
        c.execute('''CREATE TABLE galaxy_agn
                  (galtileid int, galid int, agnra real, agndec real, ra real, dec real,
                  magnorm_agn real, sedname_agn text, varParamStr text, u_ab real,
                  g_ab real, r_ab real, i_ab real, z_ab real, y_ab real, redshift real)''')
    except:
        raise RuntimeError("Error creating galaxy_agn table.")

    try:
        c.execute('''CREATE TABLE StarAllForceseek
                  (simobjid int, ra real, decl real, magNorm real,
                  mudecl real, mura real, galacticAv real, vrad real, varParamStr text,
                  sedFilename text, parallax real, ebv real)''')
    except:
        raise RuntimeError("Error creating StarAllForceseek table.")

    # Now generate the data to be stored in the tables.

    rr = rng.random_sample(size)*np.radians(radius)
    theta = rng.random_sample(size)*2.0*np.pi

    if deltaRA is None:
        ra = np.degrees(centerRA + rr*np.cos(theta))
    else:
        ra = np.degrees(centerRA) + deltaRA

    if deltaDec is None:
        dec = np.degrees(centerDec + rr*np.sin(theta))
    else:
        dec = np.degrees(centerDec) + deltaDec

    bra = np.radians(ra+rng.random_sample(size)*0.01*radius)
    bdec = np.radians(dec+rng.random_sample(size)*0.01*radius)
    dra = np.radians(ra + rng.random_sample(size)*0.01*radius)
    ddec = np.radians(dec + rng.random_sample(size)*0.01*radius)
    agnra = np.radians(ra + rng.random_sample(size)*0.01*radius)
    agndec = np.radians(dec + rng.random_sample(size)*0.01*radius)

    magnorm_bulge = rng.random_sample(size)*delta_magnorm + magnorm_min
    magnorm_disk = rng.random_sample(size)*delta_magnorm + magnorm_min
    magnorm_agn = rng.random_sample(size)*delta_magnorm + magnorm_min
    b_b = rng.random_sample(size)*0.2
    a_b = b_b+rng.random_sample(size)*0.05
    b_d = rng.random_sample(size)*0.5
    a_d = b_d+rng.random_sample(size)*0.1

    BulgeHalfLightRadius = rng.random_sample(size)*0.2
    DiskHalfLightRadius = rng.random_sample(size)*0.5

    pa_bulge = rng.random_sample(size)*360.0
    pa_disk = rng.random_sample(size)*360.0

    av_b = rng.random_sample(size)*0.3
    av_d = rng.random_sample(size)*0.3
    rv_b = rng.random_sample(size)*0.1 + 2.0
    rv_d = rng.random_sample(size)*0.1 + 2.0

    u_ab = rng.random_sample(size)*4.0 + 17.0
    g_ab = rng.random_sample(size)*4.0 + 17.0
    r_ab = rng.random_sample(size)*4.0 + 17.0
    i_ab = rng.random_sample(size)*4.0 + 17.0
    z_ab = rng.random_sample(size)*4.0 + 17.0
    y_ab = rng.random_sample(size)*4.0 + 17.0
    redshift = rng.random_sample(size)*2.0

    t0_mjd = mjd - rng.random_sample(size)*1000.0
    agn_tau = rng.random_sample(size)*1000.0 + 1000.0
    agnSeed = rng.randint(2, 4001, size=size)
    agn_sfu = rng.random_sample(size)
    agn_sfg = rng.random_sample(size)
    agn_sfr = rng.random_sample(size)
    agn_sfi = rng.random_sample(size)
    agn_sfz = rng.random_sample(size)
    agn_sfy = rng.random_sample(size)

    rrStar = rng.random_sample(size)*np.radians(radius)
    thetaStar = rng.random_sample(size)*2.0*np.pi

    if deltaRA is None:
        raStar = centerRA + rrStar*np.cos(thetaStar)
    else:
        raStar = centerRA + np.radians(deltaRA)

    if deltaDec is None:
        decStar = centerDec + rrStar*np.sin(thetaStar)
    else:
        decStar = centerDec + np.radians(deltaDec)

    raStar = np.degrees(raStar)
    decStar = np.degrees(decStar)

    magnormStar = rng.random_sample(size)*delta_magnorm + magnorm_min
    mudecl = rng.random_sample(size)*0.0001
    mura = rng.random_sample(size)*0.0001
    galacticAv = rng.random_sample(size)*0.05*3.1
    vrad = rng.random_sample(size)*1.0
    parallax = 0.00045+rng.random_sample(size)*0.00001
    period = rng.random_sample(size)*20.0
    amp = rng.random_sample(size)*5.0

    # write the data to the tables.
    for i in range(size):

        cmd = '''INSERT INTO galaxy_bulge VALUES (%i, %i, %f, %f, %f, %f, %f,
              '%s', %f, %f, %f, %i, '%s', %f, %f, %f, %f, %f, %f, %f, %f, %f, %f)''' % \
              (i, i, bra[i], bdec[i], ra[i], dec[i], magnorm_bulge[i], galaxy_seds[i%len(galaxy_seds)],
               a_b[i], b_b[i], pa_bulge[i], 4, 'CCM', av_b[i], rv_b[i], u_ab[i], g_ab[i],
               r_ab[i], i_ab[i], z_ab[i], y_ab[i], redshift[i], BulgeHalfLightRadius[i])

        c.execute(cmd)

        varParam = {'varMethodName': 'applyAgn',
                    'pars': {'agn_tau': round(agn_tau[i], 4), 't0_mjd': round(t0_mjd[i], 4),
                             'agn_sfu': round(agn_sfu[i], 4), 'agn_sfg': round(agn_sfg[i], 4),
                             'agn_sfr': round(agn_sfr[i], 4), 'agn_sfi': round(agn_sfi[i], 4),
                             'agn_sfz': round(agn_sfz[i], 4), 'agn_sfy': round(agn_sfy[i], 4),
                             'seed': int(agnSeed[i])}}

        paramStr = json.dumps(varParam)

        cmd = '''INSERT INTO galaxy VALUES (%i, %i, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f,
                                            '%s', '%s', '%s', '%s',
                                            %f, %f, %f, %i,
                                            %f, %f, %f, %i,
                                            '%s', %f, %f,
                                            '%s', %f, %f,
                                            %f, %f, %f, %f, %f, %f,
                                            %f, %f, %f)''' % \
              (i, i, ra[i], dec[i], bra[i], bdec[i], dra[i], ddec[i], agnra[i], agndec[i],
               magnorm_bulge[i], magnorm_disk[i], magnorm_agn[i],
               galaxy_seds[i%len(galaxy_seds)], galaxy_seds[i%len(galaxy_seds)], agn_sed,
               paramStr,
               a_b[i], b_b[i], pa_bulge[i], 4,
               a_d[i], b_d[i], pa_disk[i], 1,
               'CCM', av_b[i], rv_b[i],
               'CCM', av_d[i], rv_d[i],
               u_ab[i], g_ab[i], r_ab[i], i_ab[i], z_ab[i], y_ab[i], redshift[i],
               BulgeHalfLightRadius[i], DiskHalfLightRadius[i])
        c.execute(cmd)

        cmd = '''INSERT INTO galaxy_agn VALUES (%i, %i, %f, %f, %f, %f, %f, '%s', '%s',
              %f, %f, %f, %f, %f, %f, %f)''' % \
              (i, i, agnra[i], agndec[i], ra[i], dec[i],
               magnorm_agn[i], agn_sed, paramStr,
               u_ab[i], g_ab[i], r_ab[i], i_ab[i],
               z_ab[i], y_ab[i], redshift[i])

        c.execute(cmd)

        varParam = {'varMethodName': 'testVar', 'pars': {'period': period[i], 'amplitude': amp[i]}}
        paramStr = json.dumps(varParam)
        cmd = '''INSERT INTO StarAllForceseek VALUES (%i, %f, %f, %f, %f, %f, %f, %f, '%s', '%s', %f, %f)''' %\
              (i, raStar[i], decStar[i], magnormStar[i], mudecl[i], mura[i],
               galacticAv[i], vrad[i], paramStr, star_seds[i%len(star_seds)], parallax[i],
               galacticAv[i]/3.1)

        c.execute(cmd)

    conn.commit()
    conn.close()
    return obs_metadata
Beispiel #17
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()
Beispiel #18
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)
Beispiel #19
0
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)))
        darkTimeMaps = []
        for i,indx in enumerate(indices):
            skydata,mjd = sb.allSkyDB(dateData[indx]['dateID'], filt=filterName)
            if skydata.size > starLimit:
                airmass = 1./np.cos(np.radians(90.-skydata['alt']))
                skydata = skydata[np.where((airmass < amMax) & (airmass >= 1.))]
                alt,az,pa =  _altAzPaFromRaDec(np.radians(skydata['ra']), np.radians(skydata['dec']),
                                               telescope.lon, telescope.lat, mjd)
                skyhp = healplots.healbin(az,alt, skydata['sky'], nside=nside)
                skyhp[np.isnan(skyhp)] = hp.UNSEEN

                good = np.where(skyhp != hp.UNSEEN)
                sm.setRaDecMjd(hpra[good], hpdec[good], mjd, degrees=False, azAlt=True)

                # switch moon to ra dec
                moonRA,moonDec = _raDecFromAltAz(sm.moonAlt,sm.moonAz, telescope.lon, telescope.lat, mjd)
                # compute distances
                moonDistances = haversine(hpra[good], hpdec[good], moonRA,moonDec)
                closeToMoon = np.where( moonDistances < np.radians(moonLimit) )

                modelhp = np.zeros(npix,dtype=float)+hp.UNSEEN
                modelhp[good] = sm.returnMags(canonDict[filterName])
                modelhp[good][closeToMoon] = hp.UNSEEN
                good = np.where(modelhp != hp.UNSEEN )
                validationArr['frameZP'][i] = np.median(modelhp[good]-skyhp[good] )

                notnan = np.where(skyhp != hp.UNSEEN)
                validationArr['obsDarkestHP'][i] = np.where(skyhp == skyhp[notnan].max() )[0].min()
                validationArr['obsBrightestHP'][i] = np.where(skyhp == skyhp[notnan].min() )[0].min()
                notnan =np.where(modelhp != hp.UNSEEN)[0]
                if notnan.size >=1: