Exemple #1
0
def date2dict_times(date):
    day = Time(date, format='iso')

    longitude = '78d57m53s'
    latitude = '32d46m44s'
    elevation = 4500 * u.m
    location = EarthLocation.from_geodetic(longitude, latitude, elevation)
    iaohanle = Observer(location=location,
                        name="IAO",
                        timezone='Asia/Kolkata',
                        description="GROWTH-India 70cm telescope")

    sunset_iao = iaohanle.sun_set_time(day, which='next')
    sunrise_iao = iaohanle.sun_rise_time(day, which='next')
    twelve_twil_eve_iao = iaohanle.twilight_evening_nautical(day, which='next')
    eighteen_twil_eve_iao = iaohanle.twilight_evening_astronomical(
        day, which='next')
    twelve_twil_morn_iao = iaohanle.twilight_morning_nautical(day,
                                                              which='next')
    eighteen_twil_morn_iao = iaohanle.twilight_morning_astronomical(
        day, which='next')

    dict_times = OrderedDict()
    dict_times['Sunset '] = time2utc_ist(sunset_iao)
    dict_times['Sunrise '] = time2utc_ist(sunrise_iao)
    dict_times['Twelve degree Evening Twilight '] = time2utc_ist(
        twelve_twil_eve_iao)
    dict_times['Eighteen degree Evening Twilight '] = time2utc_ist(
        eighteen_twil_eve_iao)
    dict_times['Twelve degree Morning Twilight '] = time2utc_ist(
        twelve_twil_morn_iao)
    dict_times['Eighteen degree Morning Twilight '] = time2utc_ist(
        eighteen_twil_morn_iao)
    return dict_times
Exemple #2
0
    def nautical_twilight(self,
                          date_obs,
                          site_longitude=30.335555,
                          site_latitude=36.824166,
                          site_elevation=2500,
                          site_name="tug",
                          time_zone="Europe/Istanbul",
                          which="next"):

        # TUG's location info settings
        tug = Observer(longitude=site_longitude * u.deg,
                       latitude=site_latitude * u.deg,
                       elevation=site_elevation * u.m,
                       name=site_name,
                       timezone=time_zone)

        # convert date astropy date format
        astropy_time = Time(date_obs)

        # evening tw calculate
        et = tug.twilight_evening_nautical(astropy_time, which=which)

        # morning tw calculate
        mt = tug.twilight_morning_nautical(astropy_time, which=which)

        # localized time conversion
        return (tug.astropy_time_to_datetime(mt),
                tug.astropy_time_to_datetime(et))
Exemple #3
0
    def nautical_twilight(self, date_obs,
                              site_longitude=30.335555,
                              site_latitude=36.824166,
                              site_elevation=2500,
                              site_name="tug",
                              time_zone="Europe/Istanbul",
                              which="next"):

        # TUG's location info settings
        tug = Observer(longitude=site_longitude*u.deg,
                       latitude=site_latitude*u.deg,
                       elevation=site_elevation*u.m,
                       name=site_name,
                       timezone=time_zone)

        # convert date astropy date format
        astropy_time = Time(date_obs)

        # evening tw calculate
        et = tug.twilight_evening_nautical(astropy_time,
                                               which=which)

        # morning tw calculate
        mt = tug.twilight_morning_nautical(astropy_time,
                                               which=which)

        # localized time conversion
        return(tug.astropy_time_to_datetime(mt),
               tug.astropy_time_to_datetime(et))
def get_twilights(start, end):
    """ Determine sunrise and sunset times """
    location = EarthLocation(
        lat=+19.53602,
        lon=-155.57608,
        height=3400,
    )
    obs = Observer(location=location, name='VYSOS', timezone='US/Hawaii')

    sunset = obs.sun_set_time(Time(start), which='next').datetime
    sunrise = obs.sun_rise_time(Time(start), which='next').datetime

    # Calculate and order twilights and set plotting alpha for each
    twilights = [
        (start, 'start', 0.0),
        (sunset, 'sunset', 0.0),
        (obs.twilight_evening_civil(Time(start),
                                    which='next').datetime, 'ec', 0.1),
        (obs.twilight_evening_nautical(Time(start),
                                       which='next').datetime, 'en', 0.2),
        (obs.twilight_evening_astronomical(Time(start),
                                           which='next').datetime, 'ea', 0.3),
        (obs.twilight_morning_astronomical(Time(start),
                                           which='next').datetime, 'ma', 0.5),
        (obs.twilight_morning_nautical(Time(start),
                                       which='next').datetime, 'mn', 0.3),
        (obs.twilight_morning_civil(Time(start),
                                    which='next').datetime, 'mc', 0.2),
        (sunrise, 'sunrise', 0.1),
    ]

    twilights.sort(key=lambda x: x[0])
    final = {
        'sunset': 0.1,
        'ec': 0.2,
        'en': 0.3,
        'ea': 0.5,
        'ma': 0.3,
        'mn': 0.2,
        'mc': 0.1,
        'sunrise': 0.0
    }
    twilights.append((end, 'end', final[twilights[-1][1]]))

    return twilights
Exemple #5
0
 def __init__(self, observatory, observations):
     self.observatory = observatory
     self.observations = observations
     
     #assign unique ids to observations
     for observation in self.observations:
         observation.id = self.last_id
         self.last_id += 1
     
     #uncomment to download the latest for astroplan
     logger.debug('Updating Astroplan IERS Bulletin A...')
     download_IERS_A()
     
     #get *nearest* sunset and *next* sunrise times
     #still not a big fan of this!
     observatory_location_obsplan = Observer(longitude=self.observatory.longitude*u.deg, latitude=self.observatory.latitude*u.deg, elevation=self.observatory.altitude*u.m, name=self.observatory.code, timezone=self.observatory.timezone) 
     self.sunset_time = observatory_location_obsplan.twilight_evening_nautical(Time.now(), which="nearest") 
     self.sunrise_time = observatory_location_obsplan.twilight_morning_nautical(Time.now(), which="next") 
     logger.debug('The nearest sunset is %s. The next sunrise is %s.'%(self.sunset_time.iso, self.sunrise_time.iso))       
Exemple #6
0
    def get_twilights(self, config=None):
        """ Determine sunrise and sunset times """
        print('  Determining sunrise, sunset, and twilight times')

        if config is None:
            from pocs.utils.config import load_config as pocs_config
            config = pocs_config()['location']

        location = EarthLocation(
            lat=config['latitude'],
            lon=config['longitude'],
            height=config['elevation'],
        )
        obs = Observer(location=location, name='PANOPTES',
                       timezone=config['timezone'])

        sunset = obs.sun_set_time(Time(self.start), which='next').datetime
        sunrise = obs.sun_rise_time(Time(self.start), which='next').datetime

        # Calculate and order twilights and set plotting alpha for each
        twilights = [(self.start, 'start', 0.0),
                     (sunset, 'sunset', 0.0),
                     (obs.twilight_evening_civil(Time(self.start),
                                                 which='next').datetime, 'ec', 0.1),
                     (obs.twilight_evening_nautical(Time(self.start),
                                                    which='next').datetime, 'en', 0.2),
                     (obs.twilight_evening_astronomical(Time(self.start),
                                                        which='next').datetime, 'ea', 0.3),
                     (obs.twilight_morning_astronomical(Time(self.start),
                                                        which='next').datetime, 'ma', 0.5),
                     (obs.twilight_morning_nautical(Time(self.start),
                                                    which='next').datetime, 'mn', 0.3),
                     (obs.twilight_morning_civil(Time(self.start),
                                                 which='next').datetime, 'mc', 0.2),
                     (sunrise, 'sunrise', 0.1),
                     ]

        twilights.sort(key=lambda x: x[0])
        final = {'sunset': 0.1, 'ec': 0.2, 'en': 0.3, 'ea': 0.5,
                 'ma': 0.3, 'mn': 0.2, 'mc': 0.1, 'sunrise': 0.0}
        twilights.append((self.end, 'end', final[twilights[-1][1]]))

        return twilights
Exemple #7
0
def get_twilights(start, end, webcfg, nsample=256):
    """ Determine sunrise and sunset times """
    location = c.EarthLocation(
        lat=webcfg['site'].getfloat('site_lat'),
        lon=webcfg['site'].getfloat('site_lon'),
        height=webcfg['site'].getfloat('site_elevation'),
    )
    obs = Observer(location=location, name=webcfg['site'].get('name', ''))
    sunset = obs.sun_set_time(Time(start), which='next').datetime
    sunrise = obs.sun_rise_time(Time(start), which='next').datetime

    # Calculate and order twilights and set plotting alpha for each
    twilights = [
        (start, 'start', 0.0),
        (sunset, 'sunset', 0.0),
        (obs.twilight_evening_civil(Time(start),
                                    which='next').datetime, 'ec', 0.1),
        (obs.twilight_evening_nautical(Time(start),
                                       which='next').datetime, 'en', 0.2),
        (obs.twilight_evening_astronomical(Time(start),
                                           which='next').datetime, 'ea', 0.3),
        (obs.twilight_morning_astronomical(Time(start),
                                           which='next').datetime, 'ma', 0.5),
        (obs.twilight_morning_nautical(Time(start),
                                       which='next').datetime, 'mn', 0.3),
        (obs.twilight_morning_civil(Time(start),
                                    which='next').datetime, 'mc', 0.2),
        (sunrise, 'sunrise', 0.1),
    ]
    twilights.sort(key=lambda x: x[0])
    final = {
        'sunset': 0.1,
        'ec': 0.2,
        'en': 0.3,
        'ea': 0.5,
        'ma': 0.3,
        'mn': 0.2,
        'mc': 0.1,
        'sunrise': 0.0
    }
    twilights.append((end, 'end', final[twilights[-1][1]]))

    return twilights
Exemple #8
0
def calculate_twilights(date):
    """ Determine sunrise and sunset times """

    from astropy import units as u
    from astropy.time import Time
    from astropy.coordinates import EarthLocation
    from astroplan import Observer

    h = 4.2 * u.km
    R = (1.0 * u.earthRad).to(u.km)
    d = np.sqrt(h * (2 * R + h))
    phi = (np.arccos((d / R).value) * u.radian).to(u.deg)
    MK = phi - 90 * u.deg

    location = EarthLocation(
        lat=19 + 49 / 60 + 33.40757 / 60**2,
        lon=-(155 + 28 / 60 + 28.98665 / 60**2),
        height=4159.58,
    )
    obs = Observer(location=location, name='Keck', timezone='US/Hawaii')
    date = Time(dt.strptime(f'{date} 18:00:00', '%Y-%m-%d %H:%M:%S'))

    t = {}
    sunset = obs.sun_set_time(date, which='nearest', horizon=MK).datetime
    t['seto'] = sunset
    t['ento'] = obs.twilight_evening_nautical(Time(sunset),
                                              which='next').datetime
    t['eato'] = obs.twilight_evening_astronomical(Time(sunset),
                                                  which='next').datetime
    t['mato'] = obs.twilight_morning_astronomical(Time(sunset),
                                                  which='next').datetime
    t['mnto'] = obs.twilight_morning_nautical(Time(sunset),
                                              which='next').datetime
    t['riseo'] = obs.sun_rise_time(Time(sunset), which='next').datetime
    t['set'] = t['seto'].strftime('%H:%M UT')
    t['ent'] = t['ento'].strftime('%H:%M UT')
    t['eat'] = t['eato'].strftime('%H:%M UT')
    t['mat'] = t['mato'].strftime('%H:%M UT')
    t['mnt'] = t['mnto'].strftime('%H:%M UT')
    t['rise'] = t['riseo'].strftime('%H:%M UT')

    return t
def calculate_twilights(date):
    """ Determine sunrise and sunset times """

    from astropy import units as u
    from astropy.time import Time
    from astropy.coordinates import EarthLocation
    from astroplan import Observer

    h = 4.2*u.km
    R = (1.0*u.earthRad).to(u.km)
    d = np.sqrt(h*(2*R+h))
    phi = (np.arccos((d/R).value)*u.radian).to(u.deg)
    MK = phi - 90*u.deg

    location = EarthLocation(
        lat=19+49/60+33.40757/60**2,
        lon=-(155+28/60+28.98665/60**2),
        height=4159.58,
    )
    obs = Observer(location=location, name='Keck', timezone='US/Hawaii')
    date = Time(dt.strptime(f'{date} 18:00:00', '%Y-%m-%d %H:%M:%S'))

    t = {}
    sunset = obs.sun_set_time(date, which='nearest', horizon=MK).datetime
    t['seto'] = sunset
    t['ento'] = obs.twilight_evening_nautical(Time(sunset), which='next').datetime
    t['eato'] = obs.twilight_evening_astronomical(Time(sunset), which='next').datetime
    t['mato'] = obs.twilight_morning_astronomical(Time(sunset), which='next').datetime
    t['mnto'] = obs.twilight_morning_nautical(Time(sunset), which='next').datetime
    t['riseo'] = obs.sun_rise_time(Time(sunset), which='next').datetime
    t['set'] = t['seto'].strftime('%H:%M UT')
    t['ent'] = t['ento'].strftime('%H:%M UT')
    t['eat'] = t['eato'].strftime('%H:%M UT')
    t['mat'] = t['mato'].strftime('%H:%M UT')
    t['mnt'] = t['mnto'].strftime('%H:%M UT')
    t['rise'] = t['riseo'].strftime('%H:%M UT')

    return t
Exemple #10
0
def post_save_night(sender, **kwargs):
    if not kwargs.get('raw', False):
        night = kwargs['instance']

        location = night.location
        astropy_time = Time(datetime.combine(night.date, time(12)))
        astropy_time_delta = TimeDelta(600.0, format='sec')

        # guess if the moon is waxing or waning
        if ephem.next_full_moon(night.date) - ephem.Date(night.date) < ephem.Date(night.date) - ephem.previous_full_moon(night.date):
            waxing_moon = True
        else:
            waxing_moon = False

        observer = Observer(
            longitude=location.longitude,
            latitude=location.latitude,
            timezone='UTC'
        )

        moon_phase = observer.moon_phase(astropy_time).value

        if waxing_moon:
            moon_phase = (math.pi - moon_phase) / (2 * math.pi)
        else:
            moon_phase = (math.pi + moon_phase) / (2 * math.pi)

        times = {
            'sunset': observer.sun_set_time(astropy_time, which='next'),
            'civil_dusk': observer.twilight_evening_civil(astropy_time, which='next'),
            'nautical_dusk': observer.twilight_evening_nautical(astropy_time, which='next'),
            'astronomical_dusk': observer.twilight_evening_astronomical(astropy_time, which='next'),
            'midnight': observer.midnight(astropy_time, which='next'),
            'astronomical_dawn': observer.twilight_morning_astronomical(astropy_time, which='next'),
            'nautical_dawn': observer.twilight_morning_nautical(astropy_time, which='next'),
            'civil_dawn': observer.twilight_morning_civil(astropy_time, which='next'),
            'sunrise': observer.sun_rise_time(astropy_time, which='next'),
        }

        night.mjd = int(astropy_time.mjd) + 1
        night.moon_phase = moon_phase
        for key in times:
            if times[key].jd > 0:
                setattr(night, key, times[key].to_datetime(timezone=utc))

        post_save.disconnect(post_save_night, sender=sender)
        night.save()
        post_save.connect(post_save_night, sender=sender)

        moon_positions = []
        for i in range(144):
            moon_altitude = observer.moon_altaz(astropy_time).alt.degree

            moon_position = MoonPosition(
                timestamp=astropy_time.to_datetime(timezone=utc),
                altitude=moon_altitude,
                location=location
            )

            moon_positions.append(moon_position)
            astropy_time += astropy_time_delta

        MoonPosition.objects.bulk_create(moon_positions)
Exemple #11
0
n_transits = []

for trial in range(n_trials):
    target_inds_observed = set([])

    obs_database = {
        name: dict(times=[], fluxes=[], model=[], transit=False)
        for name in table['spc']
    }

    for i in range(n_years * 365):
        # Simulate weather losses
        if np.random.rand() > fraction_cloudy:
            time = start_time + i * u.day
            night_start = saintex.twilight_evening_nautical(time,
                                                            which='previous')
            night_end = saintex.twilight_morning_nautical(time, which='next')
            night_duration = night_end - night_start

            times = time_grid_from_range((night_start, night_end),
                                         time_resolution=1.6 * u.min)

            obs_table = observability_table(constraints,
                                            saintex,
                                            targets,
                                            times=times)
            # Prevent memory from getting out of hand by clearing out cache:
            saintex._altaz_cache = {}
            mask_targets_visible_2hrs = obs_table[
                'fraction of time observable'] * night_duration > 6 * u.hr
    sunsets = observer.sun_set_time(times)

    sunsets = np.unique(np.round(sunsets.mjd, decimals=4))

    names = [
        'night', 'sunset', 'sun_n12_setting', 'sun_n18_setting',
        'sun_n18_rising', 'sun_n12_rising', 'sunrise', 'moonrise', 'moonset'
    ]
    types = [int]
    types.extend([float] * (len(names) - 1))
    almanac = np.zeros(sunsets.size, dtype=list(zip(names, types)))
    almanac['sunset'] = sunsets

    times = Time(sunsets, format='mjd')
    print('evening twilight 1')
    almanac['sun_n12_setting'] = observer.twilight_evening_nautical(times).mjd
    almanac['sun_n18_setting'] = observer.twilight_evening_astronomical(
        times).mjd
    almanac['sun_n18_rising'] = observer.twilight_morning_astronomical(
        times).mjd
    almanac['sun_n12_rising'] = observer.twilight_morning_nautical(times).mjd
    almanac['sunrise'] = observer.sun_rise_time(times).mjd
    almanac['moonset'] = observer.moon_set_time(times).mjd
    print('moonrise')
    almanac['moonrise'] = observer.moon_rise_time(times).mjd
    results.append(almanac)

almanac = np.concatenate(results)
umjds, indx = np.unique(almanac['sunset'], return_index=True)
almanac = almanac[indx]
almanac['night'] = np.arange(almanac['night'].size)
Exemple #13
0
def plan_when_transits_will_occur(
        filename='targets.txt',
        observatory='Southern African Large Telescope',
        start='2017-06-22',
        end='2017-06-28',
        airmass_limit=2.5,
        moon_distance=10,
        do_secondary=True,
        method='by_night'):
    '''
    Plan when targets will be visibile and transiting from a site. 
    
    Inputs
    ------
    filename : str
        A plain text file with the following columns:
            target : The name of the target (e.g. J0555-57).
            RA     : The right ascension of the target (e.g. 05h55m32.62s).
            DEC    : The declination of the target (e.g. -57d17m26.1s).
            epoch* : The epoch of the transit. Youc can either use:
                         epoch_HJD-2400000 : HJD - 24500000
                         epoch_BJD-2455000 : MJD
            Period : The period of the system (days).
            Secondary : can be True or False depending on whether you want
                        to see when the secondary transits will be.
    observatory : str
        The observatory you are observing from. See later for list of available
        observatories (accepted by astropy).    
    start : str
        The first night of observation (e.g. 2017-08-31).
    end : str
        The last night of observation (e.g. 2017-09-10).
    airmass_limit : float
        The maximum airmass you want to observe through. 
    moon_distance : float
        The closest the target can be t the moon in arcmins.
    do_secondary = True:
        Look for secondary eclipses assuming circularised orbits. 
        
    Available observator names are:
         'ALMA',
         'Anglo-Australian Observatory',
         'Apache Point',
         'Apache Point Observatory',
         'Atacama Large Millimeter Array',
         'BAO',
         'Beijing XingLong Observatory',
         'Black Moshannon Observatory',
         'CHARA',
         'Canada-France-Hawaii Telescope',
         'Catalina Observatory',
         'Cerro Pachon',
         'Cerro Paranal',
         'Cerro Tololo',
         'Cerro Tololo Interamerican Observatory',
         'DCT',
         'Discovery Channel Telescope',
         'Dominion Astrophysical Observatory',
         'Gemini South',
         'Hale Telescope',
         'Haleakala Observatories',
         'Happy Jack',
         'Jansky Very Large Array',
         'Keck Observatory',
         'Kitt Peak',
         'Kitt Peak National Observatory',
         'La Silla Observatory',
         'Large Binocular Telescope',
         'Las Campanas Observatory',
         'Lick Observatory',
         'Lowell Observatory',
         'Manastash Ridge Observatory',
         'McDonald Observatory',
         'Medicina',
         'Medicina Dish',
         'Michigan-Dartmouth-MIT Observatory',
         'Mount Graham International Observatory',
         'Mt Graham',
         'Mt. Ekar 182 cm. Telescope',
         'Mt. Stromlo Observatory',
         'Multiple Mirror Telescope',
         'NOV',
         'National Observatory of Venezuela',
         'Noto',
         'Observatorio Astronomico Nacional, San Pedro Martir',
         'Observatorio Astronomico Nacional, Tonantzintla',
         'Palomar',
         'Paranal Observatory',
         'Roque de los Muchachos',
         'SAAO',
         'SALT',
         'SRT',
         'Siding Spring Observatory',
         'Southern African Large Telescope',
         'Subaru',
         'Subaru Telescope',
         'Sutherland',
         'Vainu Bappu Observatory',
         'Very Large Array',
         'W. M. Keck Observatory',
         'Whipple',
         'Whipple Observatory',
         'aao',
         'alma',
         'apo',
         'bmo',
         'cfht',
         'ctio',
         'dao',
         'dct',
         'ekar',
         'example_site',
         'flwo',
         'gemini_north',
         'gemini_south',
         'gemn',
         'gems',
         'greenwich',
         'haleakala',
         'irtf',
         'keck',
         'kpno',
         'lapalma',
         'lasilla',
         'lbt',
         'lco',
         'lick',
         'lowell',
         'mcdonald',
         'mdm',
         'medicina',
         'mmt',
         'mro',
         'mso',
         'mtbigelow',
         'mwo',
         'noto',
         'ohp',
         'paranal',
         'salt',
         'sirene',
         'spm',
         'srt',
         'sso',
         'tona',
         'vbo',
         'vla'.
    '''
    ###################
    # Try reading table
    ###################
    try:
        target_table = Table.read(filename, format='ascii')
    except:
        raise ValueError(
            'I cant open the target file (make sure its ascii with the following first line:\ntarget		RA		DEC		epoch_HJD-2400000	Period		Secondary'
        )

##############################
# try reading observation site
##############################
    try:
        observation_site = coord.EarthLocation.of_site(observatory)
        observation_handle = Observer(location=observation_site)
        observation_handle1 = Observer.at_site(observatory)
    except:
        print(coord.EarthLocation.get_site_names())
        raise ValueError('The site is not understood')

###################################
# Try reading start and end times
###################################
    try:
        start_time = Time(start + ' 12:01:00', location=observation_site)
        end_time = Time(end + ' 12:01:00', location=observation_site)
        number_of_nights = int(end_time.jd - start_time.jd)
        time_range = Time([start + ' 12:01:00', end + ' 12:01:00'])
        print('Number of nights: {}'.format(number_of_nights))
    except:
        raise ValueError('Start and end times not understood')

#####################
# Now do constraints
#####################
#try:

    constraints = [
        AltitudeConstraint(0 * u.deg, 90 * u.deg),
        AirmassConstraint(3),
        AtNightConstraint.twilight_civil()
    ]
    #except:
    #	raise ValueError('Unable to get set constraints')

    if method == 'by_night':
        for i in range(number_of_nights):
            start_time_tmp = start_time + TimeDelta(
                i,
                format='jd')  #  get start time (doesent need to be accurate)
            end_time_tmp = start_time + TimeDelta(
                i + 1,
                format='jd')  #  get start time (doesent need to be accurate)
            print('#' * 80)
            start_time_tmpss = start_time_tmp.datetime.ctime().split(
            )  # ['Fri', 'Dec', '24', '12:00:00', '2010']
            print('Night {} - {} {} {} {}'.format(i + 1, start_time_tmpss[0],
                                                  start_time_tmpss[2],
                                                  start_time_tmpss[1],
                                                  start_time_tmpss[-1]))
            print('#' * 80)

            # Now print Almnac information (sunset and end of evening twilight
            print('Almnac:')
            sun_set = observation_handle.sun_set_time(start_time_tmp,
                                                      which='next')
            print('Sunset:\t\t\t\t\t\t\t' + sun_set.utc.datetime.ctime())

            twilight_evening_astronomical = observation_handle.twilight_evening_astronomical(
                start_time_tmp, which='next')  # -18
            twilight_evening_nautical = observation_handle.twilight_evening_nautical(
                start_time_tmp, which='next')  # -12
            twilight_evening_civil = observation_handle.twilight_evening_civil(
                start_time_tmp, which='next')  # -6 deg
            print('Civil evening twilight (-6 deg) (U.T.C):\t\t' +
                  twilight_evening_civil.utc.datetime.ctime())
            print('Nautical evening twilight (-12 deg) (U.T.C):\t\t' +
                  twilight_evening_nautical.utc.datetime.ctime())
            print('Astronomical evening twilight (-18 deg) (U.T.C):\t' +
                  twilight_evening_astronomical.utc.datetime.ctime())
            print('\n')

            twilight_morning_astronomical = observation_handle.twilight_morning_astronomical(
                start_time_tmp, which='next')  # -18
            twilight_morning_nautical = observation_handle.twilight_morning_nautical(
                start_time_tmp, which='next')  # -12
            twilight_morning_civil = observation_handle.twilight_morning_civil(
                start_time_tmp, which='next')  # -6 deg
            print('Astronomical morning twilight (-18 deg) (U.T.C):\t' +
                  twilight_morning_astronomical.utc.datetime.ctime())
            print('Nautical morning twilight (-12 deg) (U.T.C):\t\t' +
                  twilight_morning_nautical.utc.datetime.ctime())
            print('Civil morning twilight (-6 deg) (U.T.C):\t\t' +
                  twilight_morning_civil.utc.datetime.ctime())
            sun_rise = observation_handle.sun_rise_time(start_time_tmp,
                                                        which='next')
            print('Sunrise:\t\t\t\t\t\t' + sun_rise.utc.datetime.ctime())
            print('\n')

            # stuff for creating plot
            plot_mids = []
            plot_names = []
            plot_widths = []

            for j in range(len(target_table)):
                # Extract information
                star_coordinates = coord.SkyCoord('{} {}'.format(
                    target_table['RA'][j], target_table['DEC'][j]),
                                                  unit=(u.hourangle, u.deg),
                                                  frame='icrs')
                star_fixed_coord = FixedTarget(coord=star_coordinates,
                                               name=target_table['target'][j])

                ####################
                # Get finder image
                ####################
                '''
                plt.close()
                try:
                finder_image = plot_finder_image(star_fixed_coord,reticle=True,fov_radius=10*u.arcmin)
                except:
                pass
                plt.savefig(target_table['target'][j]+'_finder_chart.eps')
                '''

                P = target_table['Period'][j]
                Secondary_transit = target_table['Secondary'][j]
                transit_half_width = TimeDelta(
                    target_table['width'][j] * 60 * 60 / 2,
                    format='sec')  # in seconds for a TimeDelta

                # now convert T0 to HJD -> JD -> BJD so we can cout period
                if 'epoch_HJD-2400000' in target_table.colnames:
                    #print('Using HJD-2400000')
                    T0 = target_table['epoch_HJD-2400000'][j]
                    T0 = Time(T0 + 2400000, format='jd')  # HJD given by WASP
                    ltt_helio = T0.light_travel_time(star_coordinates,
                                                     'heliocentric',
                                                     location=observation_site)
                    T0 = T0 - ltt_helio  # HJD -> JD
                    ltt_bary = T0.light_travel_time(star_coordinates,
                                                    'barycentric',
                                                    location=observation_site)
                    T0 = T0 + ltt_bary  # JD -> BJD
                elif 'epoch_BJD-2455000' in target_table.colnames:
                    #print('Using BJD-2455000')
                    T0 = target_table['epoch_BJD-2455000'][j] + 2455000
                    T0 = Time(T0, format='jd')  # BJD
                else:
                    print('\n\n\n\n FAILE\n\n\n\n')
                    continue

                ##########################################################
                # Now start from T0 and count in periods to find transits
                ##########################################################
                # convert star and end time to BJD
                ltt_bary_start_time = start_time_tmp.light_travel_time(
                    star_coordinates, 'barycentric',
                    location=observation_site)  # + TimeDelta(i,format='jd')
                start_time_bary = start_time_tmp + ltt_bary_start_time  # + TimeDelta(i,format='jd') #  convert start time to BJD

                ltt_bary_end_time_tmp = end_time_tmp.light_travel_time(
                    star_coordinates, 'barycentric',
                    location=observation_site)  # + TimeDelta(i,format='jd')
                end_time_bary = end_time_tmp + ltt_bary_start_time  #+ TimeDelta(i+1,format='jd') #  convert end time to BJD and add 1 day 12pm -> 12pm the next day

                elapsed = end_time_bary - start_time_bary  # now this is 24 hours from the start day 12:00 pm

                # now count transits
                time = Time(T0.jd, format='jd')  # make a temporary copy
                transits = []
                primary_count, secondary_count = 0, 0
                while time.jd < end_time_bary.jd:
                    if (time.jd > start_time_bary.jd) and (time.jd <
                                                           end_time_bary.jd):
                        if is_observable(constraints,
                                         observation_handle,
                                         [star_fixed_coord],
                                         times=[time])[0] == True:
                            transits.append(time)
                            primary_count += 1
                    if Secondary_transit == 'yes':
                        timesecondary = time + TimeDelta(P / 2, format='jd')
                        if (timesecondary.jd > start_time_bary.jd) and (
                                timesecondary.jd < end_time_bary.jd):
                            if is_observable(constraints,
                                             observation_handle,
                                             [star_fixed_coord],
                                             times=[timesecondary])[0] == True:
                                transits.append(timesecondary)
                                secondary_count += 1

                    time = time + TimeDelta(P,
                                            format='jd')  # add another P to T0

                # Now find visible transits
                transits = [
                    i for i in transits
                    if is_observable(constraints,
                                     observation_handle, [star_fixed_coord],
                                     times=[i])[0] == True
                ]

                if len(transits) == 0:
                    message = '{} has no transits.'.format(
                        target_table['target'][j])
                    print('-' * len(message))
                    print(message)
                    print('-' * len(message))
                    print('\n')
                    plt.close()
                    continue
                else:
                    message = '{} has {} primary transits and {} secondary transits.'.format(
                        target_table['target'][j], primary_count,
                        secondary_count)
                    print('-' * len(message))
                    print(message)
                    print('RA: {}'.format(target_table['RA'][j]))
                    print('DEC: {}'.format(target_table['DEC'][j]))
                    print('Epoch: 2000')
                    print('T0 (BJD): {}'.format(T0.jd))
                    print('Period: {}'.format(P))
                    print('Transit width (hr): {}'.format(
                        target_table['width'][j]))
                    print('-' * len(message))
                    print('\n')

                for i in transits:
                    # currently transit times are in BJD (need to convert to HJD to check
                    ltt_helio = i.light_travel_time(star_coordinates,
                                                    'barycentric',
                                                    location=observation_site)
                    ii = i - ltt_helio
                    ltt_helio = ii.light_travel_time(star_coordinates,
                                                     'heliocentric',
                                                     location=observation_site)
                    ii = ii + ltt_helio

                    transit_1 = i - transit_half_width - TimeDelta(
                        7200, format='sec')  # ingress - 2 hr
                    transit_2 = i - transit_half_width - TimeDelta(
                        3600, format='sec')  # ingress - 2 hr
                    transit_3 = i - transit_half_width  # ingress
                    transit_4 = i + transit_half_width  # egress
                    transit_5 = i + transit_half_width + TimeDelta(
                        3600, format='sec')  # ingress - 2 hr
                    transit_6 = i + transit_half_width + TimeDelta(
                        7200, format='sec')  # ingress - 2 hr

                    if (((i.jd - time.jd) / P) - np.floor(
                        (i.jd - time.jd) / P) < 0.1) or ((
                            (i.jd - time.jd) / P) - np.floor(
                                (i.jd - time.jd) / P) > 0.9):
                        print('Primary Transit:')
                        print('-' * len('Primary Transit'))
                    if 0.4 < ((i.jd - time.jd) / P) - np.floor(
                        (i.jd - time.jd) / P) < 0.6:
                        print('Secondary Transit')
                        print('-' * len('Secondary Transit'))

                    ##################
                    # now get sirmass
                    ##################
                    altaz = star_coordinates.transform_to(
                        AltAz(obstime=transit_1, location=observation_site))
                    hourangle = observation_handle1.target_hour_angle(
                        transit_1, star_coordinates)
                    hourangle = 24 * hourangle.degree / 360
                    if hourangle > 12:
                        hourangle -= 24
                    print('Ingress - 2hr (U.T.C):\t\t\t\t\t' +
                          transit_1.utc.datetime.ctime() +
                          '\tAirmass: {:.2f}\tHA:{:.2f}'.format(
                              altaz.secz, hourangle))

                    altaz = star_coordinates.transform_to(
                        AltAz(obstime=transit_2, location=observation_site))
                    hourangle = observation_handle1.target_hour_angle(
                        transit_2, star_coordinates)
                    hourangle = 24 * hourangle.degree / 360
                    if hourangle > 12:
                        hourangle -= 24
                    print('Ingress - 1hr (U.T.C):\t\t\t\t\t' +
                          transit_2.utc.datetime.ctime() +
                          '\tAirmass: {:.2f}\tHA:{:.2f}'.format(
                              altaz.secz, hourangle))

                    altaz = star_coordinates.transform_to(
                        AltAz(obstime=transit_3, location=observation_site))
                    hourangle = observation_handle1.target_hour_angle(
                        transit_3, star_coordinates)
                    hourangle = 24 * hourangle.degree / 360
                    if hourangle > 12:
                        hourangle -= 24
                    print('Ingress (U.T.C):\t\t\t\t\t' +
                          transit_3.utc.datetime.ctime() +
                          '\tAirmass: {:.2f}\tHA:{:.2f}'.format(
                              altaz.secz, hourangle))

                    altaz = star_coordinates.transform_to(
                        AltAz(obstime=i, location=observation_site))
                    hourangle = observation_handle1.target_hour_angle(
                        i, star_coordinates)
                    hourangle = 24 * hourangle.degree / 360
                    if hourangle > 12:
                        hourangle -= 24
                    print('Mid transit (U.T.C):\t\t\t\t\t' +
                          i.utc.datetime.ctime() +
                          '\tAirmass: {:.2f}\tHA:{:.2f}'.format(
                              altaz.secz, hourangle))

                    altaz = star_coordinates.transform_to(
                        AltAz(obstime=transit_4, location=observation_site))
                    hourangle = observation_handle1.target_hour_angle(
                        transit_4, star_coordinates)
                    hourangle = 24 * hourangle.degree / 360
                    if hourangle > 12:
                        hourangle -= 24
                    print('Egress (U.T.C):\t\t\t\t\t\t' +
                          transit_4.utc.datetime.ctime() +
                          '\tAirmass: {:.2f}\tHA:{:.2f}'.format(
                              altaz.secz, hourangle))

                    altaz = star_coordinates.transform_to(
                        AltAz(obstime=transit_5, location=observation_site))
                    hourangle = observation_handle1.target_hour_angle(
                        transit_5, star_coordinates)
                    hourangle = 24 * hourangle.degree / 360
                    if hourangle > 12:
                        hourangle -= 24
                    print('Egress + 1hr (U.T.C):\t\t\t\t\t' +
                          transit_5.utc.datetime.ctime() +
                          '\tAirmass: {:.2f}\tHA:{:.2f}'.format(
                              altaz.secz, hourangle))

                    altaz = star_coordinates.transform_to(
                        AltAz(obstime=transit_6, location=observation_site))
                    hourangle = observation_handle1.target_hour_angle(
                        transit_6, star_coordinates)
                    hourangle = 24 * hourangle.degree / 360
                    if hourangle > 12:
                        hourangle -= 24
                    print('Egress + 2hr (U.T.C):\t\t\t\t\t' +
                          transit_6.utc.datetime.ctime() +
                          '\tAirmass: {:.2f}\tHA:{:.2f}'.format(
                              altaz.secz, hourangle))
                    print('HJD {} (to check with http://var2.astro.cz/)\n'.
                          format(ii.jd))

                    # append stuff for plots
                    plot_mids.append(i)  # astropy Time
                    plot_names.append(target_table['target'][j])
                    plot_widths.append(target_table['width'][j])

            # Now plot

            plt.close()
            if len(plot_mids) == 0:
                continue
            date_formatter = dates.DateFormatter('%H:%M')
            #ax.xaxis.set_major_formatter(date_formatter)

            # now load dummy transit lightcurves
            xp, yp = np.load('lc.npy')
            xs, ys = np.load('lcs.npy')

            # x = np.linspace(0, 2*np.pi, 400)
            # y = np.sin(x**2)

            subplots_adjust(hspace=0.000)
            number_of_subplots = len(
                plot_names)  # number of targets transiting that night

            time = sun_set + np.linspace(-1, 14,
                                         100) * u.hour  # take us to sunset
            for i, v in enumerate(xrange(number_of_subplots)):
                # exctract params
                width = plot_widths[v]
                name = plot_names[v]
                mid = plot_mids[v]

                # now set up dummy lc plot
                x_tmp = mid + xp * (width /
                                    2) * u.hour  # get right width in hours

                # now set up axis
                v = v + 1
                ax1 = subplot(number_of_subplots, 1, v)
                ax1.xaxis.set_major_formatter(date_formatter)

                if v == 1:
                    ax1.set_title(start)

                # plot transit model
                ax1.plot_date(x_tmp.plot_date, ys, 'k-')

                # plot continuum
                #xx  =time.plot_date
                #xx = [uu for uu in xx if (uu<min(x_tmp.plot_date)) or (uu>max(x_tmp.plot_date))]

                #ax1.plot_date(xx, np.ones(len(xx)),'k--', alpha=0.3)
                ax1.set_xlim(min(time.plot_date), max(time.plot_date))
                #ax1.plot_date(mid.plot_date, 0.5, 'ro')
                plt.setp(ax1.get_xticklabels(), rotation=30, ha='right')
                ax1.set_ylabel(name, rotation=45, labelpad=20)

                twilights = [
                    (sun_set.datetime, 0.0),
                    (twilight_evening_civil.datetime, 0.1),
                    (twilight_evening_nautical.datetime, 0.2),
                    (twilight_evening_astronomical.datetime, 0.3),
                    (twilight_morning_astronomical.datetime, 0.4),
                    (twilight_morning_nautical.datetime, 0.3),
                    (twilight_morning_civil.datetime, 0.2),
                    (sun_rise.datetime, 0.1),
                ]

                for ii, twii in enumerate(twilights[1:], 1):
                    ax1.axvspan(twilights[ii - 1][0],
                                twilights[ii][0],
                                ymin=0,
                                ymax=1,
                                color='grey',
                                alpha=twii[1])

                ax1.grid(alpha=0.5)
                ax1.get_yaxis().set_ticks([])
                if v != number_of_subplots:
                    ax1.get_xaxis().set_ticks([])

            plt.xlabel('Time [U.T.C]')
            #plt.tight_layout()
            #plt.savefig('test.eps',format='eps')
            plt.show()
def main(args=None):
    p = parser()
    opts = p.parse_args(args)

    # Late imports
    import operator
    import sys

    from astroplan import Observer
    from astroplan.plots import plot_airmass
    from astropy.coordinates import EarthLocation, SkyCoord
    from astropy.table import Table
    from astropy.time import Time
    from astropy import units as u
    from matplotlib import dates
    from matplotlib.cm import ScalarMappable
    from matplotlib.colors import Normalize
    from matplotlib.patches import Patch
    from matplotlib import pyplot as plt
    from tqdm import tqdm
    import pytz

    from ..io import fits
    from .. import moc
    from .. import plot  # noqa
    from ..extern.quantile import percentile

    if opts.site is None:
        if opts.site_longitude is None or opts.site_latitude is None:
            p.error('must specify either --site or both '
                    '--site-longitude and --site-latitude')
        location = EarthLocation(lon=opts.site_longitude * u.deg,
                                 lat=opts.site_latitude * u.deg,
                                 height=(opts.site_height or 0) * u.m)
        if opts.site_timezone is not None:
            location.info.meta = {'timezone': opts.site_timezone}
        observer = Observer(location)
    else:
        if not ((opts.site_longitude is None) and
                (opts.site_latitude is None) and (opts.site_height is None) and
                (opts.site_timezone is None)):
            p.error('argument --site not allowed with arguments '
                    '--site-longitude, --site-latitude, '
                    '--site-height, or --site-timezone')
        observer = Observer.at_site(opts.site)

    m = fits.read_sky_map(opts.input.name, moc=True)

    # Make an empty airmass chart.
    t0 = Time(opts.time) if opts.time is not None else Time.now()
    t0 = observer.midnight(t0)
    ax = plot_airmass([], observer, t0, altitude_yaxis=True)

    # Remove the fake source and determine times that were used for the plot.
    del ax.lines[:]
    times = Time(np.linspace(*ax.get_xlim()), format='plot_date')

    theta, phi = moc.uniq2ang(m['UNIQ'])
    coords = SkyCoord(phi, 0.5 * np.pi - theta, unit='rad')
    prob = moc.uniq2pixarea(m['UNIQ']) * m['PROBDENSITY']

    levels = np.arange(90, 0, -10)
    nlevels = len(levels)
    percentiles = np.concatenate((50 - 0.5 * levels, 50 + 0.5 * levels))

    airmass = np.column_stack([
        percentile(condition_secz(coords.transform_to(observer.altaz(t)).secz),
                   percentiles,
                   weights=prob) for t in tqdm(times)
    ])

    cmap = ScalarMappable(Normalize(0, 100), plt.get_cmap())
    for level, lo, hi in zip(levels, airmass[:nlevels], airmass[nlevels:]):
        ax.fill_between(
            times.plot_date,
            clip_verylarge(lo),  # Clip infinities to large but finite values
            clip_verylarge(hi),  # because fill_between cannot handle inf
            color=cmap.to_rgba(level),
            zorder=2)

    ax.legend([Patch(facecolor=cmap.to_rgba(level)) for level in levels],
              ['{}%'.format(level) for level in levels])
    # ax.set_title('{} from {}'.format(m.meta['objid'], observer.name))

    # Adapted from astroplan
    start = times[0]
    twilights = [
        (times[0].datetime, 0.0),
        (observer.sun_set_time(Time(start), which='next').datetime, 0.0),
        (observer.twilight_evening_civil(Time(start),
                                         which='next').datetime, 0.1),
        (observer.twilight_evening_nautical(Time(start),
                                            which='next').datetime, 0.2),
        (observer.twilight_evening_astronomical(Time(start),
                                                which='next').datetime, 0.3),
        (observer.twilight_morning_astronomical(Time(start),
                                                which='next').datetime, 0.4),
        (observer.twilight_morning_nautical(Time(start),
                                            which='next').datetime, 0.3),
        (observer.twilight_morning_civil(Time(start),
                                         which='next').datetime, 0.2),
        (observer.sun_rise_time(Time(start), which='next').datetime, 0.1),
        (times[-1].datetime, 0.0),
    ]

    twilights.sort(key=operator.itemgetter(0))
    for i, twi in enumerate(twilights[1:], 1):
        if twi[1] != 0:
            ax.axvspan(twilights[i - 1][0],
                       twilights[i][0],
                       ymin=0,
                       ymax=1,
                       color='grey',
                       alpha=twi[1],
                       linewidth=0)
        if twi[1] != 0.4:
            ax.axvspan(twilights[i - 1][0],
                       twilights[i][0],
                       ymin=0,
                       ymax=1,
                       color='white',
                       alpha=0.8 - 2 * twi[1],
                       zorder=3,
                       linewidth=0)

    # Add local time axis
    timezone = (observer.location.info.meta or {}).get('timezone')
    if timezone:
        tzinfo = pytz.timezone(timezone)
        ax2 = ax.twiny()
        ax2.set_xlim(ax.get_xlim())
        ax2.set_xticks(ax.get_xticks())
        ax2.xaxis.set_major_formatter(dates.DateFormatter('%H:%M', tz=tzinfo))
        plt.setp(ax2.get_xticklabels(), rotation=-30, ha='right')
        ax2.set_xlabel("Time from {} [{}]".format(
            min(times).to_datetime(tzinfo).date(), timezone))

    if opts.verbose:
        # Write airmass table to stdout.
        times.format = 'isot'
        table = Table(masked=True)
        table['time'] = times
        table['sun_alt'] = np.ma.masked_greater_equal(
            observer.sun_altaz(times).alt, 0)
        table['sun_alt'].format = lambda x: '{}'.format(int(np.round(x)))
        for p, data in sorted(zip(percentiles, airmass)):
            table[str(p)] = np.ma.masked_invalid(data)
            table[str(p)].format = lambda x: '{:.01f}'.format(np.around(x, 1))
        table.write(sys.stdout, format='ascii.fixed_width')

    # Show or save output.
    opts.output()
Exemple #15
0
def create_observation_observables(object_id,
                                   object_dir,
                                   since,
                                   name,
                                   epoch,
                                   epoch_low_err,
                                   epoch_up_err,
                                   period,
                                   period_low_err,
                                   period_up_err,
                                   duration,
                                   observatories_file,
                                   timezone,
                                   latitude,
                                   longitude,
                                   altitude,
                                   max_days,
                                   min_altitude,
                                   moon_min_dist,
                                   moon_max_dist,
                                   transit_fraction,
                                   baseline,
                                   error_alert=True):
    """

    @param object_id: the candidate id
    @param object_dir: the candidate directory
    @param since: starting plan date
    @param name: the name given to the candidate
    @param epoch: the candidate epoch
    @param epoch_low_err: the candidate epoch's lower error
    @param epoch_up_err: the candidate epoch's upper error
    @param period: the candidate period
    @param period_low_err: the candidate period's lower error
    @param period_up_err: the candidate period's upper error
    @param duration: the candidate duration
    @param observatories_file: the file containing the observatories file (csv format)
    @param timezone: the timezone of the observatory (if observatories_file=None)
    @param latitude: the latitude of the observatory (if observatories_file=None)
    @param longitude: the longitude of the observatory (if observatories_file=None)
    @param altitude: the altitude of the observatory (if observatories_file=None)
    @param max_days: the maximum number of days to compute the observables
    @param min_altitude: the minimum altitude of the target above the horizon
    @param moon_min_dist: the minimum moon distance for moon illumination = 0
    @param moon_max_dist: the minimum moon distance for moon illumination = 1
    @param transit_fraction: the minimum transit observability (0.25 for at least ingress/egress, 0.5 for ingress/egress
    + midtime, 1 for ingress, egress and midtime).
    @param baseline: the required baseline in hours.
    @param: error_alert: whether to create the alert date to signal imprecise observations
    @return: the generated data and target folders
    """
    if observatories_file is not None:
        observatories_df = pd.read_csv(observatories_file, comment='#')
    else:
        observatories_df = pd.DataFrame(
            columns=['name', 'tz', 'lat', 'long', 'alt'])
        observatories_df = observatories_df.append("Obs-1", timezone, latitude,
                                                   longitude, altitude)
    # TODO probably convert epoch to proper JD
    mission, mission_prefix, id_int = LcBuilder().parse_object_info(object_id)
    if mission == "TESS":
        primary_eclipse_time = Time(epoch, format='btjd', scale="tdb")
    elif mission == "Kepler" or mission == "K2":
        primary_eclipse_time = Time(epoch, format='bkjd', scale="tdb")
    else:
        primary_eclipse_time = Time(epoch, format='jd')
    target = FixedTarget(SkyCoord(coords, unit=(u.deg, u.deg)))
    n_transits = int(max_days // period)
    system = EclipsingSystem(primary_eclipse_time=primary_eclipse_time,
                             orbital_period=u.Quantity(period, unit="d"),
                             duration=u.Quantity(duration, unit="h"),
                             name=name)
    observables_df = pd.DataFrame(columns=[
        'observatory', 'timezone', 'start_obs', 'end_obs', 'ingress', 'egress',
        'midtime', "midtime_up_err_h", "midtime_low_err_h", 'twilight_evening',
        'twilight_morning', 'observable', 'moon_phase', 'moon_dist'
    ])
    plan_dir = object_dir + "/plan"
    images_dir = plan_dir + "/images"
    if os.path.exists(plan_dir):
        shutil.rmtree(plan_dir, ignore_errors=True)
    os.mkdir(plan_dir)
    if os.path.exists(images_dir):
        shutil.rmtree(images_dir, ignore_errors=True)
    os.mkdir(images_dir)
    alert_date = None
    for index, observatory_row in observatories_df.iterrows():
        observer_site = Observer(latitude=observatory_row["lat"],
                                 longitude=observatory_row["lon"],
                                 elevation=u.Quantity(observatory_row["alt"],
                                                      unit="m"))
        midtransit_times = system.next_primary_eclipse_time(
            since, n_eclipses=n_transits)
        ingress_egress_times = system.next_primary_ingress_egress_time(
            since, n_eclipses=n_transits)
        constraints = [
            AtNightConstraint.twilight_nautical(),
            AltitudeConstraint(min=min_altitude * u.deg),
            MoonIlluminationSeparationConstraint(
                min_dist=moon_min_dist * u.deg, max_dist=moon_max_dist * u.deg)
        ]
        moon_for_midtransit_times = get_moon(midtransit_times)
        moon_dist_midtransit_times = moon_for_midtransit_times.separation(
            SkyCoord(star_df.iloc[0]["ra"], star_df.iloc[0]["dec"],
                     unit="deg"))
        moon_phase_midtransit_times = np.round(
            astroplan.moon_illumination(midtransit_times), 2)
        transits_since_epoch = np.round(
            (midtransit_times - primary_eclipse_time).jd / period)
        midtransit_time_low_err = np.round(
            (((transits_since_epoch * period_low_err)**2 + epoch_low_err**2)
             **(1 / 2)) * 24, 2)
        midtransit_time_up_err = np.round(
            (((transits_since_epoch * period_up_err)**2 + epoch_up_err**2)
             **(1 / 2)) * 24, 2)
        low_err_delta = TimeDelta(midtransit_time_low_err * 3600, format='sec')
        up_err_delta = TimeDelta(midtransit_time_up_err * 3600, format='sec')
        i = 0
        for midtransit_time in midtransit_times:
            twilight_evening = observer_site.twilight_evening_nautical(
                midtransit_time)
            twilight_morning = observer_site.twilight_morning_nautical(
                midtransit_time)
            ingress = ingress_egress_times[i][0]
            egress = ingress_egress_times[i][1]
            lowest_ingress = ingress - low_err_delta[i]
            highest_egress = egress + up_err_delta[i]
            if error_alert and (highest_egress - lowest_ingress).jd > 0.33:
                alert_date = midtransit_time if (alert_date is None) or (
                    alert_date is not None
                    and alert_date >= midtransit_time) else alert_date
                break
            else:
                baseline_low = lowest_ingress - baseline * u.hour
                baseline_up = highest_egress + baseline * u.hour
                transit_times = baseline_low + (
                    baseline_up - baseline_low) * np.linspace(0, 1, 100)
                observable_transit_times = astroplan.is_event_observable(
                    constraints, observer_site, target, times=transit_times)[0]
                observable_transit_times_true = np.argwhere(
                    observable_transit_times)
                observable = len(observable_transit_times_true) / 100
                if observable < transit_fraction:
                    i = i + 1
                    continue
                start_obs = transit_times[observable_transit_times_true[0]][0]
                end_obs = transit_times[observable_transit_times_true[
                    len(observable_transit_times_true) - 1]][0]
                start_plot = baseline_low
                end_plot = baseline_up
                if twilight_evening > start_obs:
                    start_obs = twilight_evening
                if twilight_morning < end_obs:
                    end_obs = twilight_morning
            moon_dist = round(moon_dist_midtransit_times[i].degree)
            moon_phase = moon_phase_midtransit_times[i]
            # TODO get is_event_observable for several parts of the transit (ideally each 5 mins) to get the proper observable percent. Also with baseline
            if observatory_row["tz"] is not None and not np.isnan(
                    observatory_row["tz"]):
                observer_timezone = observatory_row["tz"]
            else:
                observer_timezone = get_offset(observatory_row["lat"],
                                               observatory_row["lon"],
                                               midtransit_time.datetime)
            observables_df = observables_df.append(
                {
                    "observatory":
                    observatory_row["name"],
                    "timezone":
                    observer_timezone,
                    "ingress":
                    ingress.isot,
                    "start_obs":
                    start_obs.isot,
                    "end_obs":
                    end_obs.isot,
                    "egress":
                    egress.isot,
                    "midtime":
                    midtransit_time.isot,
                    "midtime_up_err_h":
                    str(int(midtransit_time_up_err[i] // 1)) + ":" +
                    str(int(midtransit_time_up_err[i] % 1 * 60)).zfill(2),
                    "midtime_low_err_h":
                    str(int(midtransit_time_low_err[i] // 1)) + ":" +
                    str(int(midtransit_time_low_err[i] % 1 * 60)).zfill(2),
                    "twilight_evening":
                    twilight_evening.isot,
                    "twilight_morning":
                    twilight_morning.isot,
                    "observable":
                    observable,
                    "moon_phase":
                    moon_phase,
                    "moon_dist":
                    moon_dist
                },
                ignore_index=True)
            plot_time = start_plot + (end_plot - start_plot) * np.linspace(
                0, 1, 100)
            plt.tick_params(labelsize=6)
            airmass_ax = plot_airmass(target,
                                      observer_site,
                                      plot_time,
                                      brightness_shading=False,
                                      altitude_yaxis=True)
            airmass_ax.axvspan(twilight_morning.plot_date,
                               end_plot.plot_date,
                               color='white')
            airmass_ax.axvspan(start_plot.plot_date,
                               twilight_evening.plot_date,
                               color='white')
            airmass_ax.axvspan(twilight_evening.plot_date,
                               twilight_morning.plot_date,
                               color='gray')
            airmass_ax.axhspan(1. / np.cos(np.radians(90 - min_altitude)),
                               5.0,
                               color='green')
            airmass_ax.get_figure().gca().set_title("")
            airmass_ax.get_figure().gca().set_xlabel("")
            airmass_ax.get_figure().gca().set_ylabel("")
            airmass_ax.set_xlabel("")
            airmass_ax.set_ylabel("")
            xticks = []
            xticks_labels = []
            xticks.append(start_obs.plot_date)
            hour_min_sec_arr = start_obs.isot.split("T")[1].split(":")
            xticks_labels.append("T1_" + hour_min_sec_arr[0] + ":" +
                                 hour_min_sec_arr[1])
            plt.axvline(x=start_obs.plot_date, color="violet")
            xticks.append(end_obs.plot_date)
            hour_min_sec_arr = end_obs.isot.split("T")[1].split(":")
            xticks_labels.append("T1_" + hour_min_sec_arr[0] + ":" +
                                 hour_min_sec_arr[1])
            plt.axvline(x=end_obs.plot_date, color="violet")
            if start_plot < lowest_ingress < end_plot:
                xticks.append(lowest_ingress.plot_date)
                hour_min_sec_arr = lowest_ingress.isot.split("T")[1].split(":")
                xticks_labels.append("T1_" + hour_min_sec_arr[0] + ":" +
                                     hour_min_sec_arr[1])
                plt.axvline(x=lowest_ingress.plot_date, color="red")
            if start_plot < ingress < end_plot:
                xticks.append(ingress.plot_date)
                hour_min_sec_arr = ingress.isot.split("T")[1].split(":")
                xticks_labels.append("T1_" + hour_min_sec_arr[0] + ":" +
                                     hour_min_sec_arr[1])
                plt.axvline(x=ingress.plot_date, color="orange")
            if start_plot < midtransit_time < end_plot:
                xticks.append(midtransit_time.plot_date)
                hour_min_sec_arr = midtransit_time.isot.split("T")[1].split(
                    ":")
                xticks_labels.append("T0_" + hour_min_sec_arr[0] + ":" +
                                     hour_min_sec_arr[1])
                plt.axvline(x=midtransit_time.plot_date, color="black")
            if start_plot < egress < end_plot:
                xticks.append(egress.plot_date)
                hour_min_sec_arr = egress.isot.split("T")[1].split(":")
                xticks_labels.append("T4_" + hour_min_sec_arr[0] + ":" +
                                     hour_min_sec_arr[1])
                plt.axvline(x=egress.plot_date, color="orange")
            if start_plot < highest_egress < end_plot:
                xticks.append(highest_egress.plot_date)
                hour_min_sec_arr = highest_egress.isot.split("T")[1].split(":")
                xticks_labels.append("T4_" + hour_min_sec_arr[0] + ":" +
                                     hour_min_sec_arr[1])
                plt.axvline(x=highest_egress.plot_date, color="red")
            airmass_ax.xaxis.set_tick_params(labelsize=5)
            airmass_ax.set_xticks([])
            airmass_ax.set_xticklabels([])
            degrees_ax = get_twin(airmass_ax)
            degrees_ax.yaxis.set_tick_params(labelsize=6)
            degrees_ax.set_yticks([1., 1.55572383, 2.])
            degrees_ax.set_yticklabels([90, 50, 30])
            fig = matplotlib.pyplot.gcf()
            fig.set_size_inches(1.25, 0.75)
            plt.savefig(plan_dir + "/images/" + observatory_row["name"] + "_" +
                        str(midtransit_time.isot)[:-4] + ".png",
                        bbox_inches='tight')
            plt.close()
            i = i + 1
    observables_df = observables_df.sort_values(["midtime", "observatory"],
                                                ascending=True)
    observables_df.to_csv(plan_dir + "/observation_plan.csv", index=False)
    print("Observation plan created in directory: " + object_dir)
    return observatories_df, observables_df, alert_date, plan_dir, images_dir
obs.moon_rise(time_obs, which='nearest')

# moon set
obs.moon_set(time_obs, which='nearest')

# The above functions can be called with an `angle` keyword argument to specify
# a particular horizon angle for rising or setting, or can be called with
# convenience functions for particular morning/evening twilight.
# For example, to compute astronomical twilight by specifying the `angle`:
obs.sun_set_time(time_obs, which='next', angle=18*u.degree)

# evening (astronomical) twilight
obs.twilight_evening_astronomical(time_obs)

# evening (nautical) twilight
obs.twilight_evening_nautical(time_obs)

# evening (civil) twilight
obs.twilight_evening_civil(time_obs)

# morning (nautical) twilight
obs.twilight_morning_nautical(time_obs)

# morning (civil) twilight
obs.twilight_morning_civil(time_obs)

# morning (astronomical) twilight
obs.twilight_morning_astronomical(time_obs)

# what is the moon illumination?
# returns a float, which is percentage of the moon illuminated
Exemple #17
0
]
types = [int]
types.extend([float] * (len(names) - 1))
base_al = np.zeros(1, dtype=list(zip(names, types)))

while mjd < (mjd_start + duration):
    times = Time(mjd, format='mjd')
    sunsets = observer.sun_set_time(times, which='next')
    times = sunsets

    almanac = base_al.copy()
    almanac['sunset'] = sunsets.mjd

    almanac['moonset'] = observer.moon_set_time(times, which='next').mjd
    almanac['moonrise'] = observer.moon_rise_time(times, which='next').mjd
    almanac['sun_n12_setting'] = observer.twilight_evening_nautical(
        times, which='next').mjd
    times = observer.twilight_evening_astronomical(times, which='next')
    almanac['sun_n18_setting'] = times.mjd
    almanac['sun_n18_rising'] = observer.twilight_morning_astronomical(
        times, which='next').mjd
    almanac['sun_n12_rising'] = observer.twilight_morning_nautical(
        times, which='next').mjd
    almanac['sunrise'] = observer.sun_rise_time(times, which='next').mjd
    results.append(almanac)
    mjd = almanac['sunrise'] + t_step

    progress = (mjd - mjd_start) / duration * 100
    text = "\rprogress = %.2f%%" % progress
    sys.stdout.write(text)
    sys.stdout.flush()