Beispiel #1
0
def rise_set(source, observatory, elevation_limit=None, when=None, lst=False):
    """Rise and set times for a source"""
    if isinstance(source, astroplan.FixedTarget):
        S = source
    elif isinstance(source, astropy.coordinates.SkyCoord):
        S = astroplan.FixedTarget(source)
    else:
        S = astroplan.FixedTarget.from_name(source)
    if isinstance(observatory, astroplan.Observer):
        L = observatory
    elif isinstance(observatory, astropy.coordinates.EarthLocation):
        L = astroplan.Observer(observatory)
    else:
        try:
            L = astroplan.Observer(observatory_location(observatory))
            if elevation_limit is None:
                elevation_limit = known_elevation_limits.get(
                    observatory_aliases[observatory.lower()], None)
        except ValueError:
            try:
                L = astroplan.Observer.from_site(observatory)
            except ValueError:
                raise ValueError(
                    "Observatory {!r} not found".format(observatory))
    if elevation_limit is None:
        elevation_limit = 0 * u.deg

    if when is None:
        T = astropy.time.Time.now()
    elif isinstance(when, astropy.time.Time):
        T = when
    else:
        T = astropy.time.Time(when)

    if L.target_is_up(T, S, horizon=elevation_limit):
        rise = L.target_rise_time(T,
                                  S,
                                  which="previous",
                                  horizon=elevation_limit)
    else:
        rise = L.target_rise_time(T, S, which="next", horizon=elevation_limit)
    set = L.target_set_time(rise, S, which="next", horizon=elevation_limit)
    rise.location = L.location
    set.location = L.location
    rise.format = "iso"
    set.format = "iso"
    if lst:
        return _rise_set(
            rise=format_sidereal_time(rise.sidereal_time("apparent")),
            set=format_sidereal_time(set.sidereal_time("apparent")),
        )
    else:
        return _rise_set(rise=rise, set=set)
Beispiel #2
0
    def __init__(self, star, observatory, dataset="winter"):
        super().__init__()

        self.dataset = dataset

        self.star = star
        self.observatory = observatory
        # Define target parameterss
        coords = star.coordinates
        self.target = astroplan.FixedTarget(name=star.name, coord=coords)
        self.observer = astroplan.Observer(observatory)

        # Load data
        tapas_dir = join(dirname(__file__), "../../data/tapas/")
        tellw, self.airw, self.angw = load_tellurics(join(tapas_dir, "*winter*ipac.gz"))
        tells, self.airs, self.angs = load_tellurics(join(tapas_dir, "*summer*ipac.gz"))

        # Sort wavelength axis
        # We assume here that all files use the same wavelength axis
        wavew, waves = np.squeeze(tellw[0, :, 0]), np.squeeze(tells[0, :, 0])
        iiw, iis = np.argsort(wavew), np.argsort(waves)
        self.tellw, self.tells = tellw[:, iiw, :], tells[:, iis, :]

        # Create interpolator
        self.wavew, self.waves = (
            np.squeeze(self.tellw[0, :, 0]),
            np.squeeze(self.tells[0, :, 0]),
        )
        self.fluxw, self.fluxs = (
            np.squeeze(self.tellw[:, :, 1]),
            np.squeeze(self.tells[:, :, 1]),
        )
        self.tellwi = RegularGridInterpolator((self.airw, self.wavew), self.fluxw)
        self.tellsi = RegularGridInterpolator((self.airs, self.waves), self.fluxs)
Beispiel #3
0
    def observer(self):
        """Return an `astroplan.Observer` representing an observer at this
        facility, accounting for the latitude, longitude, and elevation."""
        try:
            return self._observer
        except AttributeError:
            if (self.lon is None or self.lon == "" or np.isnan(self.lon)
                    or self.lat is None or self.lat == "" or np.isnan(self.lat)
                    or self.fixed_location is False
                    or self.fixed_location is None):
                self._observer = None
                return self._observer

        try:
            elevation = self.elevation
            # if elevation is not specified, assume it is 0
            if (self.elevation is None or self.elevation == ""
                    or np.isnan(self.elevation)):
                elevation = 0

            self._observer = astroplan.Observer(
                longitude=self.lon * u.deg,
                latitude=self.lat * u.deg,
                elevation=elevation * u.m,
            )

        except Exception as e:
            log(f'Telescope {self.id} ("{self.name}") cannot calculate an observer: {e}'
                )
            self._observer = None

        return self._observer
Beispiel #4
0
 def airmass(self):
     target = astroplan.FixedTarget(name=self.star.name,
                                    coord=self.star.coordinates)
     observer = astroplan.Observer(self.observatory_location)
     altaz = observer.altaz(self.datetime, target)
     airmass = altaz.secz.value
     return airmass
Beispiel #5
0
    def __init__(self, star, observatory, degree=2, skip_resample=False):
        self.star = star
        self.observatory = observatory

        # Define target parameterss
        coords = star.coordinates
        self.target = astroplan.FixedTarget(name=star.name, coord=coords)
        self.observer = astroplan.Observer(observatory)

        self.degree = degree
        self.skip_resample = skip_resample
Beispiel #6
0
def get_segments_tile(config_struct, observatory, radec, segmentlist):

    observer = astroplan.Observer(location=observatory)

    fxdbdy = astroplan.FixedTarget(coord=radec)

    date_start = Time(segmentlist[0][0], format='mjd', scale='utc')
    date_end = Time(segmentlist[-1][1], format='mjd', scale='utc')

    tilesegmentlist = segments.segmentlist()
    while date_start.mjd < date_end.mjd:
        date_rise = observer.target_rise_time(date_start, fxdbdy)
        date_set = observer.target_set_time(date_start, fxdbdy)

        print(date_rise.mjd, date_set.mjd)
        if (date_rise.mjd < 0) and (date_set.mjd < 0): break

        print(date_rise.mjd, date_set.mjd)

        if date_rise > date_set:
            date_rise = observer.target_rise_time(
                date_start - TimeDelta(24 * u.hour), fxdbdy)
        print(date_rise.mjd, date_set.mjd)

        segment = segments.segment(date_rise.mjd, date_set.mjd)
        tilesegmentlist = tilesegmentlist + segments.segmentlist([segment])
        tilesegmentlist.coalesce()

        date_start = date_set + TimeDelta(24 * u.hour)

    #moonsegmentlist = get_skybrightness(\
    #    config_struct,segmentlist,observer,fxdbdy,radec)

    moonsegmentlist = get_moon_segments(\
        config_struct,segmentlist,observer,fxdbdy,radec)

    tilesegmentlistdic = segments.segmentlistdict()
    tilesegmentlistdic["observations"] = segmentlist
    tilesegmentlistdic["tile"] = tilesegmentlist
    tilesegmentlistdic["moon"] = moonsegmentlist
    tilesegmentlist = tilesegmentlistdic.intersection(
        ["observations", "tile", "moon"])
    tilesegmentlist.coalesce()

    return tilesegmentlist
Beispiel #7
0
 def observer(self):
     """Return an `astroplan.Observer` representing an observer at this
     facility, accounting for the latitude, longitude, elevation, and
     local time zone of the observatory (if ground based)."""
     try:
         return self._observer
     except AttributeError:
         tf = timezonefinder.TimezoneFinder(in_memory=True)
         local_tz = tf.closest_timezone_at(
             lng=self.lon, lat=self.lat, delta_degree=5
         )
         self._observer = astroplan.Observer(
             longitude=self.lon * u.deg,
             latitude=self.lat * u.deg,
             elevation=self.elevation * u.m,
             timezone=local_tz,
         )
     return self._observer
Beispiel #8
0
def plot_table(tab):
    min_mag = 12

    lat = tab.meta['lat']
    lon = tab.meta['lon']
    height = tab.meta['height']
    timezone = tab.meta['timezone']
    location = EarthLocation(lat=lat, lon=lon, height=height)
    site = astroplan.Observer(location=location,
                              name=tab.meta['location_name'],
                              timezone=timezone)

    t1 = np.array([
        pytz.utc.localize(datetime.fromisoformat(value))
        for value in tab['time_utc']
    ])
    tval_local = np.array([tutc.astimezone(site.timezone) for tutc in t1])
    magval_local = tab['mag']

    # Filter mag values above 12
    mask_5 = magval_local > min_mag
    tval_local_f = tval_local[mask_5]
    magval_local = magval_local[mask_5]

    if len(tval_local_f) > 0:
        ref_time = tval_local_f[0]
    elif len(tval_local) > 0:
        ref_time = tval_local[0]
    else:
        # Empty file
        return None

    ref_day = datetime(year=ref_time.year,
                       month=ref_time.month,
                       day=ref_time.day,
                       hour=23,
                       minute=55,
                       second=0)
    ref_day = site.timezone.localize(ref_day)
    fig = plt.figure()
    ax = fig.add_subplot()
    gen_plot(ax, tval_local_f, magval_local, site, ref_day, tab.meta)
    return fig
Beispiel #9
0
def get_segments(params, config_struct):

    gpstime = params["gpstime"]
    event_mjd = Time(gpstime, format='gps', scale='utc').mjd

    segmentlist = segments.segmentlist()
    n_windows = len(params["Tobs"]) // 2
    start_segments = event_mjd + params["Tobs"][::2]
    end_segments = event_mjd + params["Tobs"][1::2]
    for start_segment, end_segment in zip(start_segments, end_segments):
        segmentlist.append(segments.segment(start_segment, end_segment))

    location = astropy.coordinates.EarthLocation(config_struct["longitude"],
                                                 config_struct["latitude"],
                                                 config_struct["elevation"])
    observer = astroplan.Observer(location=location)

    date_start = Time(segmentlist[0][0], format='mjd', scale='utc')
    date_end = Time(segmentlist[-1][1], format='mjd', scale='utc')

    nightsegmentlist = segments.segmentlist()
    while date_start < date_end:
        date_rise = observer.twilight_morning_astronomical(date_start)
        date_set = observer.twilight_evening_astronomical(date_start)
        if date_set.mjd > date_rise.mjd:
            date_set = observer.twilight_evening_astronomical(
                date_start - TimeDelta(24 * u.hour))

        segment = segments.segment(date_set.mjd, date_rise.mjd)
        nightsegmentlist = nightsegmentlist + segments.segmentlist([segment])
        nightsegmentlist.coalesce()

        date_start = date_rise + TimeDelta(24 * u.hour)

    segmentlistdic = segments.segmentlistdict()
    segmentlistdic["observations"] = segmentlist
    segmentlistdic["night"] = nightsegmentlist
    segmentlist = segmentlistdic.intersection(["observations", "night"])
    segmentlist.coalesce()

    return segmentlist
Beispiel #10
0
    def observer_timezone(self):
        """Return an `astroplan.Observer` representing an observer at this
        facility, accounting for the latitude, longitude, elevation, and
        local time zone of the observatory (if ground based)."""
        try:
            return self._observer_timezone
        except AttributeError:
            if (self.lon is None or self.lon == "" or np.isnan(self.lon)
                    or self.lat is None or self.lat == "" or np.isnan(self.lat)
                    or self.fixed_location is False
                    or self.fixed_location is None):
                self._observer_timezone = None
                return self._observer_timezone

        try:
            tf = timezonefinder.TimezoneFinder(in_memory=True)
            local_tz = tf.timezone_at(lng=(self.lon + 180) % 360 - 180,
                                      lat=self.lat)
            elevation = self.elevation
            # if elevation is not specified, assume it is 0
            if (self.elevation is None or self.elevation == ""
                    or np.isnan(self.elevation)):
                elevation = 0

            self._observer_timezone = astroplan.Observer(
                longitude=self.lon * u.deg,
                latitude=self.lat * u.deg,
                elevation=elevation * u.m,
                timezone=local_tz,
            )

        except Exception as e:
            log(f'Telescope {self.id} ("{self.name}") cannot calculate an observer: {e}'
                )
            self._observer_timezone = None

        return self._observer_timezone
Beispiel #11
0
def schedule(observations: List[Dict], session: Dict,
             program: Dict) -> List[ObservingBlock]:
    """ Return the next object to be imaged according to the 'general' scheduling
    algorithm, and the time that the executor must wait before imaging this observation.

    Parameters
    ----------
    observations: List[Dict]
        A list of dictionaries representing the observations to be scheduled
    program: Dict
        The Program object containing the configuration of this observational program

    Returns
    -------
    obs: Dict
        The next observation to be executed
    wait: int
         The time (in seconds) to wait before imaging this observation.

    Authors: rprechelt
    """
    # create observer
    observatory = astroplan.Observer(
        latitude=config.general.latitude * units.deg,
        longitude=config.general.longitude * units.deg,
        elevation=config.general.altitude * units.m,
        name=config.general.name,
        timezone="UTC")

    # build default constraints
    global_constraints = [
        constraints.AltitudeConstraint(min=config.telescope.min_alt *
                                       units.deg),  # set minimum altitude
        constraints.AtNightConstraint.twilight_nautical(),
        constraints.TimeConstraint(min=Time(datetime.datetime.now()),
                                   max=Time(session['end']))
    ]

    # list to store observing blocks
    blocks = []

    # create targets
    for observation in observations:

        # check whether observation has RA and Dec values
        if observation.get('RA') is None:
            continue
        if observation.get('Dec') is None:
            continue

        # target coordinates
        center = SkyCoord(observation['RA'] + ' ' + observation['Dec'],
                          unit=(units.hourangle, units.deg))

        # create and apply offset
        ra_offset = Angle(observation['options'].get('ra_offset') or 0,
                          unit=units.arcsec)
        dec_offset = Angle(observation['options'].get('dec_offset') or 0,
                           unit=units.arcsec)

        # offset coordinates
        coord = SkyCoord(center.ra + ra_offset, center.dec + dec_offset)

        # create astroplan traget
        target = FixedTarget(coord=coord, name=observation['target'])

        # priority - if the observation has a priority, otherwise 1
        priority = observation['options'].get('priority') or 1

        # if specified, restrict airmass, otherwise no airmass restriction
        max_airmass = observation['options'].get('airmass') or 38
        airmass = constraints.AirmassConstraint(
            max=max_airmass, boolean_constraint=False)  # rank by airmass

        # if specified, use observations moon separation, otherwise use 2 degrees
        moon_sep = (observation['options'].get('moon')
                    or config.queue.moon_separation) * units.deg
        moon = constraints.MoonSeparationConstraint(min=moon_sep)

        # time, airmass, moon, + altitude, and at night
        local_constraints = [moon]

        # create observing block for this target
        blocks.append(
            ObservingBlock.from_exposures(
                target,
                priority,
                observation['exposure_time'] * units.second,
                observation['exposure_count'] *
                (len(observation['filters']) + 1),
                config.telescope.readout_time * units.second,
                configuration=observation,
                constraints=local_constraints))

    # we need to create a transitioner to go between blocks
    transitioner = astroplan.Transitioner(
        1 * units.deg / units.second,
        {'filter': {
            'default': 4 * units.second
        }})

    # create priority scheduler
    priority_scheduler = scheduling.PriorityScheduler(
        constraints=global_constraints,
        observer=observatory,
        transitioner=transitioner)

    # initialize the schedule
    schedule = scheduling.Schedule(Time.now(), Time(session['end']))

    # schedule!
    schedule = priority_scheduler(blocks, schedule)

    # print(schedule.to_table())
    # print(f'observing_blocks: {schedule.observing_blocks}')
    # print(f'open_slots: {schedule.open_slots}')
    # print(f'scheduled_blocks: {schedule.scheduled_blocks}')

    # return the scheduled blocks
    return schedule
Beispiel #12
0
    def __init__(self,
                 startdate="",
                 stopdate="",
                 twilight_angle=-18.,
                 verbose=True):
        """
        EXAMPLE:
            startdate = '2018-02-25 05:00:00'
            stopdate = '2018-03-05 05:00:00' 
        """
        print("Using Twilight = {}".format(twilight_angle))
        self.hetloc = astropy.coordinates.EarthLocation.of_site(
            'McDonald Observatory')
        self.observer = astroplan.Observer(location=self.hetloc)

        #################################
        all_times = het_helper_functions.arange_time(
            startdate, stopdate, form=None)  # array of astropy.time.Time()
        self.num_nights = len(all_times)
        jd_arr = [i.jd for i in all_times]
        hori = astropy.coordinates.Angle(twilight_angle,
                                         unit=u.degree)  # have used -12
        print("Creating array of {} nights to check observability".format(
            self.num_nights))

        #################################
        print("Calculating Sunrise/Sunset Times")
        sunrise_times, sunset_times, self.times_night_all_lst = [], [], []
        for i in tqdm(all_times):
            sunrise_times.append(
                astropy.time.Time(self.observer.sun_rise_time(i,
                                                              which='nearest',
                                                              horizon=hori),
                                  location=self.hetloc))
            sunset_times.append(
                astropy.time.Time(self.observer.sun_set_time(i,
                                                             which='nearest',
                                                             horizon=hori),
                                  location=self.hetloc))
        self.df_time = pd.DataFrame({
            'jd': jd_arr,
            'time': all_times,
            'sunset_time': sunset_times,
            'sunrise_time': sunrise_times
        })

        #################################
        print("Calculating Local Sidereal Times")
        for i in tqdm(self.df_time.index):
            jd_1 = self.df_time.loc[i, 'sunset_time'].jd
            jd_2 = self.df_time.loc[i, 'sunrise_time'].jd
            jds_night = linspace(jd_1, jd_2, 100)
            self.times_night_all_lst.append([
                astropy.time.Time(
                    i, format='jd',
                    location=self.hetloc).sidereal_time('mean').degree
                for i in jds_night
            ])

        #################################
        # Setting observability limits
        decs = linspace(
            -90., 90.,
            10000)  #dindgen(1d5)/1d5*180d - 90d ;declinations to try
        decs_rad = radians(decs)  #del_rad = del * !dtor

        phi = self.hetloc.lat.radian
        alt1 = radians(het_config.HET_MAX_ALT)
        alt2 = radians(het_config.HET_MIN_ALT)

        h1 = degrees(
            arccos((sin(alt1) - sin(decs_rad) * sin(phi)) /
                   (cos(decs_rad) * cos(phi))))
        h2 = degrees(
            arccos((sin(alt2) - sin(decs_rad) * sin(phi)) /
                   (cos(decs_rad) * cos(phi))))

        # The following structure shows the observability limits for each declination value
        # where limits are degrees from zenith (hour angle), and are symmetric across zenith
        # (ie negative limits also apply)
        self.obs_limits = {
            'h1': h1,
            'h2': h2,
            'decs': decs,
            'alt1': alt1,
            'alt2': alt2
        }
        print("Finished loading observability limits for all nights")
Beispiel #13
0
import inspect
import numpy as np
from astropy.time import Time
import astropy.coordinates as coords
import astropy.units as u
import astroplan

BASE_DIR = os.path.dirname(
    os.path.abspath(inspect.getfile(inspect.currentframe()))) + '/'

P48_loc = coords.EarthLocation(lat=coords.Latitude('33d21m26.35s'),
                               lon=coords.Longitude('-116d51m32.04s'),
                               height=1707.)

# use UTC only
P48_Observer = astroplan.Observer(location=P48_loc)

# HA and Dec from http://www.oir.caltech.edu/twiki_oir/bin/view/Palomar/ZTF/TelescopeSpecifications v5
# Dome estimate from Jeff Z email, 9/21/15
# goals info from Jeff Z email, 12/12/16
# Ha/Dec from Telescope Drive Performance Assessment v1.2; dome estimate from
# Jeff Z. email, 9/27/17
P48_slew_pars = {
    'ha': {
        'coord': 'ra',
        'accel': 0.4 * u.deg * u.second**(-2.),
        'decel': 0.4 * u.deg * u.second**(-2.),
        'vmax': 2.5 * u.deg / u.second
    },
    'dec': {
        'coord': 'dec',
Beispiel #14
0
import astroplan
from astropy.coordinates import solar_system_ephemeris
solar_system_ephemeris.set('jpl') 
import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt
import datetime

# Posicion del observador (IAR)
lat = -34.8601
lon = -58.1385

h   = 20
IAR = EarthLocation(lat=lat, lon=lon, height=h*u.m)

observer = astroplan.Observer(location = IAR, timezone='America/Buenos_Aires')
localtz  =  TimezoneInfo(utc_offset=-3 * u.hour)

# Limites de la antena
EASTLIMIT  = -29
WESTLIMIT  = +29
NORTHLIMIT = -10
SOUTHLIMIT = -90


# Algunos TimeDeltas
# 1 Minuto
oneMin  = TimeDelta(val = 60, format='sec')
# 5 Minutos
fiveMins = TimeDelta(val = 300, format='sec')
# 10 Minutos
Beispiel #15
0
def params_checker(params):
    #assigns defaults to params
    do_Parameters = [
        "do3D", "doEvent", "doSuperSched", "doMovie_supersched", "doSkymap",
        "doSamples", "doCoverage", "doSchedule", "doPlots", "doDatabase",
        "doMovie", "doTiles", "doIterativeTiling", "doMinimalTiling",
        "doOverlappingScheduling", "doPerturbativeTiling",
        "doOrderByObservability", "doCatalog", "doUseCatalog",
        "doCatalogDatabase", "doObservability", "doSkybrightness",
        "doEfficiency", "doCalcTiles", "doTransients", "doSingleExposure",
        "doAlternatingFilters", "doMaxTiles", "doReferences", "doChipGaps",
        "doUsePrimary", "doSplit", "doParallel", "writeCatalog", "doFootprint",
        "doBalanceExposure"
    ]

    for parameter in do_Parameters:
        if parameter not in params.keys():
            params[parameter] = False

    if "skymap" not in params.keys():
        params["skymap"] = '../output/skymaps/G268556.fits'

    if "gpstime" not in params.keys():
        params["gpstime"] = 1167559936.0

    if "outputDir" not in params.keys():
        params["outputDir"] = "../output"

    if "tilingDir" not in params.keys():
        params["tilingDir"] = "../tiling"

    if "catalogDir" not in params.keys():
        params["catalogDir"] = "../catalogs"

    if "event" not in params.keys():
        params["event"] = "G268556"

    if "coverageFiles" not in params.keys():
        params["coverageFiles"] = "../data/ATLAS_GW170104.dat"

    if "telescopes" not in params.keys():
        params["telescopes"] = 'ATLAS'

    if type(params["telescopes"]) == str:
        params["telescopes"] = params["telescopes"].split(",")

    if "lightcurveFiles" not in params.keys():
        params["lightcurveFiles"] = "../lightcurves/Me2017_H4M050V20.dat"

    if "tilesType" not in params.keys():
        params["tilesType"] = "moc"

    if "scheduleType" not in params.keys():
        params["scheduleType"] = "greedy"

    if "timeallocationType" not in params.keys():
        params["timeallocationType"] = "powerlaw"

    if "Ninj" not in params.keys():
        params["Ninj"] = 1000

    if "Ndet" not in params.keys():
        params["Ndet"] = 1

    if "Ntiles" not in params.keys():
        params["Ntiles"] = 10

    if "Ntiles_cr" not in params.keys():
        params["Ntiles_cr"] = 0.70

    if "Dscale" not in params.keys():
        params["Dscale"] = 1.0

    if "nside" not in params.keys():
        params["nside"] = 256

    if "Tobs" not in params.keys():
        params["Tobs"] = np.array([0.0, 1.0])

    if "powerlaw_c1" not in params.keys():
        params["powerlaw_c1"] = 0.9

    if "powerlaw_n" not in params.keys():
        params["powerlaw_n"] = 1.0

    if "powerlaw_dist_exp" not in params.keys():
        params["powerlaw_dist_exp"] = 0

    if "galaxies_FoV_sep" not in params.keys():
        params["galaxies_FoV_sep"] = 1.0

    if "footprint_ra" not in params.keys():
        params["footprint_ra"] = 30.0

    if "footprint_dec" not in params.keys():
        params["footprint_dec"] = 60.0

    if "footprint_radius" not in params.keys():
        params["footprint_radius"] = 10.0

    if "transientsFile" not in params.keys():
        params["transientsFile"] = "../transients/ps1_objects.csv"

    if "dt" not in params.keys():
        params["dt"] = 14.0

    if "galaxy_catalog" not in params.keys():
        params["galaxy_catalog"] = "GLADE"

    if "filters" not in params.keys():
        params["filters"] = ['r', 'g', 'r']

    if "exposuretimes" not in params.keys():
        params["exposuretimes"] = np.array([30.0, 30.0, 30.0])

    if "max_nb_tiles" not in params.keys():
        params["max_nb_tiles"] = np.array([-1, -1, -1])

    if "mindiff" not in params.keys():
        params["mindiff"] = 0.0

    if "airmass" not in params.keys():
        params["airmass"] = 2.5

    if "iterativeOverlap" not in params.keys():
        params["iterativeOverlap"] = 0.0

    if "maximumOverlap" not in params.keys():
        params["maximumOverlap"] = 1.0

    if "catalog_n" not in params.keys():
        params["catalog_n"] = 1.0

    if "galaxy_grade" not in params.keys():
        params["galaxy_grade"] = "S"

    if "splitType" not in params.keys():
        params["splitType"] = "regional"

    if "Nregions" not in params.keys():
        params["Nregions"] = 768

    if "configDirectory" not in params.keys():
        params["configDirectory"] = "../config/"

    if "Ncores" not in params.keys():
        params["Ncores"] = 4

    if "config" not in params.keys():
        params["config"] = {}
        configFiles = glob.glob("%s/*.config" % params["configDirectory"])
        for configFile in configFiles:
            telescope = configFile.split("/")[-1].replace(".config", "")
            if not telescope in params["telescopes"]: continue
            params["config"][telescope] = gwemopt.utils.readParamsFromFile(
                configFile)
            params["config"][telescope]["telescope"] = telescope
            if params["doSingleExposure"]:
                exposuretime = np.array(opts.exposuretimes.split(","),
                                        dtype=np.float)[0]

                nmag = np.log(
                    exposuretime /
                    params["config"][telescope]["exposuretime"]) / np.log(2.5)
                params["config"][telescope]["magnitude"] = params["config"][
                    telescope]["magnitude"] + nmag
                params["config"][telescope]["exposuretime"] = exposuretime
            if "tesselationFile" in params["config"][telescope]:
                if not os.path.isfile(
                        params["config"][telescope]["tesselationFile"]):
                    if params["config"][telescope]["FOV_type"] == "circle":
                        gwemopt.tiles.tesselation_spiral(
                            params["config"][telescope])
                    elif params["config"][telescope]["FOV_type"] == "square":
                        gwemopt.tiles.tesselation_packing(
                            params["config"][telescope])
                if params["tilesType"] == "galaxy":
                    params["config"][telescope]["tesselation"] = np.empty(
                        (3, ))
                else:
                    params["config"][telescope]["tesselation"] = np.loadtxt(
                        params["config"][telescope]["tesselationFile"],
                        usecols=(0, 1, 2),
                        comments='%')

            if "referenceFile" in params["config"][telescope]:
                refs = table.unique(
                    table.Table.read(
                        params["config"][telescope]["referenceFile"],
                        format='ascii',
                        data_start=2,
                        data_end=-1)['field', 'fid'])
                reference_images =\
                    {group[0]['field']: group['fid'].astype(int).tolist()
                    for group in refs.group_by('field').groups}
                reference_images_map = {1: 'g', 2: 'r', 3: 'i'}
                for key in reference_images:
                    reference_images[key] = [
                        reference_images_map.get(n, n)
                        for n in reference_images[key]
                    ]
                params["config"][telescope][
                    "reference_images"] = reference_images

            location = astropy.coordinates.EarthLocation(
                params["config"][telescope]["longitude"],
                params["config"][telescope]["latitude"],
                params["config"][telescope]["elevation"])
            observer = astroplan.Observer(location=location)
            params["config"][telescope]["observer"] = observer

    return params
Beispiel #16
0
    elevation = 220

    # daysOfTheYear = [datetime(2020, x,) for x in range(1,13)]
    # startDate = datetime(1678, 1,1)
    startDate = datetime(2020, 1,1,12)
    # endDate = datetime(2020, 1,20)
    # startDate = datetime(2020, 12,10)
    endDate = datetime(2020, 12,31)
    # endDate = datetime(2020, 12,31)
    __cores = cpu_count()
    daysOfTheYear = astropy.time.Time(pd.date_range(startDate,endDate,freq='d'))
    daysOfTheYear = daysOfTheYear[::6]

    observerLocation = astropy.coordinates.EarthLocation(lat=latitude*u.deg, lon=longitude*u.deg, height=elevation*u.m)
    # observer = astroplan.Observer(observerLocation,name="Krakow", timezone="Europe/Warsaw")
    observer = astroplan.Observer(observerLocation)
    sun = astropy.coordinates.get_sun(daysOfTheYear[0])
    moon =  astropy.coordinates.get_moon(daysOfTheYear[0])

    toPlot_sun = [{"day": day, "observer": observer, "observerLocation": observerLocation,
            "target": sun} for day in daysOfTheYear]
    toPlot_moon = [{"day": day, "observer": observer, "observerLocation": observerLocation,
            "target": moon} for day in daysOfTheYear]
    with Pool(processes=__cores) as pool:
        toPlot_sun = pool.map(getCelestialArgs, toPlot_sun)
        toPlot_moon = pool.map(getCelestialArgs, toPlot_moon)

    toPlot_sun = pd.DataFrame(toPlot_sun)
    toPlot_moon = pd.DataFrame(toPlot_moon)

    plotTarget("Sun",toPlot_sun)
Beispiel #17
0
                                          duration=transit_duration2)

midnight = Time('2020-7-13 00:00:00') - utcoffset

delta_midnight = np.linspace(-12, 12, 1000) * u.hour
times_July12_to_13 = midnight + delta_midnight
frame_July12_to_13 = AltAz(obstime=times_July12_to_13, location=paranal_loc)
sunaltazs_July12_to_13 = get_sun(times_July12_to_13).transform_to(
    frame_July12_to_13)

GJ9827baltaz = GJ9827b.transform_to(AltAz(obstime=time, location=paranal_loc))

delta_midnight = np.linspace(-2, 10, 100) * u.hour
obstime = midnight + delta_midnight

paranal = astroplan.Observer(paranal_loc, timezone='Etc/GMT-4')

Altcons = astroplan.AltitudeConstraint(min=+30 * u.deg, max=None)
Airmasscons = astroplan.AirmassConstraint(min=None, max=3.0)

Alt_constraints = Altcons.compute_constraint(times=obstime,
                                             observer=paranal,
                                             targets=GJ9827b)
Airmass_constraints = Airmasscons.compute_constraint(times=obstime,
                                                     observer=paranal,
                                                     targets=GJ9827b)

observable = astroplan.is_observable(constraints=[Altcons, Airmasscons],
                                     observer=paranal,
                                     targets=GJ9827b,
                                     times=obstime)
Beispiel #18
0
#     plot the motion in the sky for a given hour of the night with passing of days
# for a given date and a list of objects: produce
#     filter the list based on observability for that date
#     plot their motion in the sky

import astroplan, astroplan.plots
import astropy.coordinates, astropy.time
import astropy.units as u
import numpy, pandas, pytz, datetime, click
import matplotlib.pyplot as plt
import astroquery.vizier

astropy.coordinates.solar_system_ephemeris.set('jpl')

polse = astroplan.Observer(latitude=46 + (28 + 9.1 / 60) / 60,
                           longitude=13 + (0 + 42.6 / 60) / 60,
                           elevation=750 * u.meter,
                           timezone=pytz.timezone('Europe/Rome'))

polse_constraints = [
    astroplan.AltitudeConstraint(min=20 * u.deg),
    astroplan.AtNightConstraint.twilight_civil(),
    astroplan.MoonSeparationConstraint(min=20 * u.deg),
    astroplan.LocalTimeConstraint(min=datetime.time(20, 0),
                                  max=datetime.time(1, 0))
]

months_labels = [
    'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
    'Nov', 'Dec'
]
Beispiel #19
0
def schedule(observations: List[Dict], session: Dict, program: Dict) -> List[ObservingBlock]:
    """ Return the next object to be imaged according to the 'general' scheduling
    algorithm, and the time that the executor must wait before imaging this observation.

    Parameters
    ----------
    observations: List[Dict]
        A list of dictionaries representing the observations to be scheduled
    program: Dict
        The Program object containing the configuration of this observational program

    Returns
    -------
    obs: Dict
        The next observation to be executed
    wait: int
         The time (in seconds) to wait before imaging this observation.

    Authors: rprechelt
    """
    # create observer
    observatory = astroplan.Observer(latitude=config.general.latitude*units.deg,
                                     longitude=config.general.longitude*units.deg,
                                     elevation=config.general.altitude*units.m,
                                     name="Atlas", timezone="UTC")

    # build default constraints
    global_constraints = [constraints.AltitudeConstraint(min=40*units.deg), # set minimum altitude
                          constraints.AtNightConstraint.twilight_nautical()] # sun below -18

    # list to store observing blocks
    blocks = []

    # create targets
    for observation in observations:
        # target coordinates
        center = SkyCoord(observation['RA']+' '+observation['Dec'], unit=(units.hourangle, units.deg))

        # create and apply offset
        ra_offset = Angle(observation['options'].get('ra_offset') or 0, unit=units.arcsec)
        dec_offset = Angle(observation['options'].get('dec_offset') or 0, unit=units.arcsec)

        # offset coordinates
        coord = SkyCoord(center.ra + ra_offset, center.dec + dec_offset)

        # create astroplan traget
        target = FixedTarget(coord=coord, name=observation['target'])

        # priority - if the observation has a priority, otherwise 1
        priority = observation['options'].get('priority') or 1

        # create local constraints
        ltc = constraints.LocalTimeConstraint(min=datetime.datetime.now().time(),
                                              max=session['end'].time())

        # if specified, restrict airmass, otherwise no airmass restriction
        max_airmass = observation['options'].get('airmass') or 38
        airmass = constraints.AirmassConstraint(max=max_airmass, boolean_constraint = False)]  # rank by airmass

        # if specified, use observations moon separation, otherwise use 2 degrees
        moon_sep = observation['options'].get('moon')*units.deg or 2*units.deg
        moon = constraints.MoonSeparationConstraint(min=moon_sep*units.deg),

        # time, airmass, moon, + altitude, and at night
        constraints = [ltc, airmass, moon]

        # create observing block for this target
        blocks.append(ObservingBlock.from_exposures(target, priority, observation['exposure_time']*units.second,
                                                    observation['exposure_count']*len(observation['filters']),
                                                    config.telescope.readout_time*units.second,
                                                    configuration = observation,
                                                    constraints = [ltc]))

    # we need to create a transitioner to go between blocks
    transitioner = astroplan.Transitioner(1*units.deg/units.second,
                                          {'filter': {'default': 3*units.second}})
Beispiel #20
0
def observability(cand=[],
                  site='VLT',
                  time=['2017-09-01T00:00:00.00', '2018-03-01T00:00:00.00'],
                  airmass=1.3):
    """
    cand is class object with parameters: name, ra, dec
    """
    # set observation site
    if site == 'VLT':
        if 0:
            longitude = '-70d24m12.000s'
            latitude = '-24d37m34.000s'
            elevation = 2635 * u.m
            vlt = EarthLocation.from_geodetic(longitude, latitude, elevation)
            observer = astroplan.Observer(
                name='VLT',
                location=vlt,
                pressure=0.750 * u.bar,
                relative_humidity=0.11,
                temperature=0 * u.deg_C,
                timezone=timezone('America/Santiago'),
                description="Very Large Telescope, Cerro Paranal")
            eso = astroplan.Observer.at_site('eso')
        else:
            observer = Observer.at_site('Cerro Paranal')

    if site == 'MagE':
        observer = Observer.at_site('las campanas observatory')
    if site == 'keck':
        observer = Observer.at_site('keck')

    print(observer)
    # set time range constrains

    if isinstance(time, str):
        # all year
        if len(time) == 4:
            timerange = 'period'
            time_range = Time(time + "-01-01T00:00:00.00",
                              time + "-12-31T23:59:00.00")
        else:
            timerange = 'onenight'
            time = Time(time)

    elif isinstance(time, list):
        if len(time) == 2:
            timerange = 'period'
            print(Time(['2017-01-03']), time)
            time_range = Time(time)
        else:
            timerange = 'onenight'
            time = Time(time[0])

    if timerange == 'onenight':
        # calculate sunset and sunrise
        sunset = observer.sun_set_time(time, which='nearest')
        print('Sunset at ', sunset.iso)
        sunrise = observer.sun_rise_time(time, which='nearest')
        print('Sunrise at ', sunrise.iso)
        time_range = Time([sunset, sunrise])

        # set time array during the night
        time = time_range[0] + (time_range[1] - time_range[0]) * np.linspace(
            0, 1, 55)

    print(time)
    # set visibility constrains
    # constraints = [AirmassConstraint(1.5), AtNightConstraint.twilight_civil()]
    print(airmass)
    constraints = [
        AirmassConstraint(airmass),
        AtNightConstraint.twilight_civil()
    ]

    # set parameters of calculations
    read_vis = 0
    if read_vis == 0:
        f_vis = open('DR12_cand_vis_temp.dat', 'w')
    month_detalied = 1
    show_moon = 0
    airmass_plot = 0
    sky_plot = 0
    if airmass_plot == 1:
        f, ax_air = plt.subplots()
    if sky_plot == 1:
        f, ax_sky = plt.subplots()

    targets = []

    if show_moon == 1:
        print(observer.moon_altaz(time).alt)
        print(observer.moon_altaz(time).az)
        # moon = SkyCoord(alt = observer.moon_altaz(time).alt, az = observer.moon_altaz(time).az, obstime = time, frame = 'altaz', location = observer.location)
        # print(moon.icrs)

    for i, can in enumerate(cand):

        print(can.name)
        # calculate target coordinates
        coordinates = SkyCoord(float(can.ra) * u.deg,
                               float(can.dec) * u.deg,
                               frame='icrs')
        #print(can.ra, can.dec)
        #print(coordinates.to_string('hmsdms'))
        target = FixedTarget(name=can.name, coord=coordinates)
        targets.append(target)

        # print(observer.target_is_up(time, targets[i]))
        # calculate airmass
        if timerange == 'onenight':
            if sky_plot == 1:
                plot_sky(target, observer, time)

            airmass = observer.altaz(time, target).secz
            if airmass_plot == 1:
                plot_airmass(target, observer, time, ax=ax)

            air_min = 1000
            k_min = -1
            for k, a in enumerate(airmass):
                if 0 < a < air_min:
                    air_min = a
                    k_min = k
            print(air_min, time[k_min].iso)

            if k_min > -1 and show_moon == 1:
                moon = SkyCoord(alt=observer.moon_altaz(time[k_min]).alt,
                                az=observer.moon_altaz(time[k_min]).az,
                                obstime=time[k_min],
                                frame='altaz',
                                location=observer.location)
                can.moon_sep = Angle(moon.separation(
                    target.coord)).to_string(fields=1)
                print(can.moon_sep)

            can.airmass = air_min
            can.time = time[k_min].iso

        # ever_observable = astroplan.is_observable(constraints, observer, targets, time_range=time_range)
        # print(ever_observable)

        if month_detalied == 1:
            tim = []
            months = [
                '2017-10-01', '2017-11-01', '2017-12-01', '2018-01-01',
                '2018-02-01', '2018-03-01', '2018-04-01'
            ]
            #for l in range(int(str(time_range[0])[5:7]), int(str(time_range[1])[5:7]) + 1):
            for l in range(len(months) - 1):
                if 0:
                    start = "2017-" + "{0:0>2}".format(l) + "-01T00:00"
                    end = "2017-" + "{0:0>2}".format(l + 1) + "-01T00:00"
                    if l == 12:
                        end = "2018-01-01T00:00"
                else:
                    start = months[l]
                    end = months[l + 1]

                time_range_temp = Time([start, end])
                table = astroplan.observability_table(
                    constraints,
                    observer, [target],
                    time_range=time_range_temp)
                tim.append(table[0][3])

            # print(tim, max(tim), tim.index(max(tim)))
            print(tim)
            can.time = max(tim)

            if max(tim) != 0:
                if 0:
                    can.month = str(calendar.month_name[tim.index(max(tim)) +
                                                        1])[:3]
                else:
                    can.month = tim.index(max(tim))
                can.up = 'True'
            else:
                can.up = 'False'
                can.month = '---'

            print(can.up, can.month, can.time)

    if month_detalied == 0:
        table = astroplan.observability_table(constraints,
                                              observer,
                                              targets,
                                              time_range=time_range)
        print(table)
        for i, can in enumerate(cand):
            can.up = table[i][1]
            can.time = table[i][3]

    # print(table[k][0], table[k][1], table[k][2], table[k][3])
    #table.write('DR12_candidates_obs.dat', format='ascii')
    # f_out.write(table)

    if sky_plot == 1:
        plt.legend(loc='center left', bbox_to_anchor=(1.25, 0.5))
        plt.show()