Пример #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
Пример #2
0
    def get_sunset_sunrise(self, time):
        """
      Returns the sunset and sunrise times of the night containing the time provided
      time is a astropy Time object
      The sunset and sunrise times are returns as an astropy Time object with the same
      settings as the provided Time object.
      """
        observer = Observer(location=self.get_EarthLocation())
        sunset = observer.sun_set_time(time, which='nearest')
        sunrise = observer.sun_rise_time(time, which='nearest')

        return sunset, sunrise
Пример #3
0
def timeline(request):
    # get location
    location = EarthLocation(
        lon=settings.OBSERVER_LOCATION['longitude'] * u.deg,
        lat=settings.OBSERVER_LOCATION['latitude'] * u.deg,
        height=settings.OBSERVER_LOCATION['elevation'] * u.m)

    # get observer and now
    now = Time.now()
    observer = Observer(location=location)

    # night or day?
    is_day = observer.sun_altaz(now).alt.degree > 0.

    # get sunset to start with
    sunset = observer.sun_set_time(now, which='next' if is_day else 'previous')

    # list of events
    events = []
    events.append(sunset.isot)

    # twilight at sunset
    sunset_twilight = observer.sun_set_time(sunset,
                                            which='next',
                                            horizon=-12. * u.deg)
    events.append(sunset_twilight.isot)

    # twilight at sunrise
    sunrise_twilight = observer.sun_rise_time(sunset_twilight,
                                              which='next',
                                              horizon=-12. * u.deg)
    events.append(sunrise_twilight.isot)

    # sunrise
    sunrise = observer.sun_rise_time(sunset_twilight, which='next')
    events.append(sunrise.isot)

    # return all
    return JsonResponse({'time': now.isot, 'events': events})
Пример #4
0
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
Пример #5
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
Пример #6
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
Пример #7
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
Пример #9
0
def observe(request, method="POST"):
    if request.POST['observing_date'] == "":
        messages.error(request, 'Please choose a date!')
    if request.POST['name'] == "":
        messages.error(request, 'Object name cannot be empty!')
    if request.POST['ra'] == "":
        messages.error(request, 'Object RA cannot be empty!')
    if request.POST['dec'] == "":
        messages.error(request, 'Object Dec cannot be empty!')

    if request.POST['observing_date'] == "" or request.POST[
            'name'] == "" or request.POST['ra'] == "" or request.POST[
                'dec'] == "":
        return redirect('/')

    observatory = None
    offset = None

    for idx, val in enumerate(T['name']):
        if val == request.POST['observatory']:
            observatory = Observer(longitude=T['longitude'][idx] * u.deg,
                                   latitude=T['latitude'][idx] * u.deg,
                                   elevation=T['altitude'][idx] * u.m,
                                   name=T['name'][idx])
            today = datetime.now()
            if tf.certain_timezone_at(lat=T['latitude'][idx],
                                      lng=T['longitude'][idx]) == None:
                return redirect('/error')
            tz_target = timezone(
                tf.certain_timezone_at(lat=T['latitude'][idx],
                                       lng=T['longitude'][idx]))
            # ATTENTION: tf.certain_timezone_at(...) could be None! handle error case
            today_target = tz_target.localize(today)
            today_utc = utc.localize(today)
            offset = (today_utc - today_target).total_seconds() * u.s

    # # offset = offsetfunction(observatory)
    observe_date = Time(request.POST['observing_date'] + ' 00:00:00',
                        format='iso')
    sunset_here = observatory.sun_set_time(observe_date,
                                           which="nearest") + offset
    sunrise_here = observatory.sun_rise_time(observe_date,
                                             which="next") + offset
    midnight_here = observatory.midnight(observe_date,
                                         which="nearest") + offset

    astro_set = observatory.twilight_evening_astronomical(observe_date,
                                                          which='nearest')
    astro_rise = observatory.twilight_morning_astronomical(observe_date,
                                                           which='next')

    coords = SkyCoord(request.POST['ra'], request.POST['dec'], frame='icrs')
    target = FixedTarget(name=request.POST['name'], coord=coords)

    start_time = astro_set

    end_time = astro_rise
    delta_t = end_time - start_time

    observe_time = start_time + delta_t * np.linspace(0.0, 2.0, 100)

    plt.ioff()
    sky = plot_sky(target, observatory, observe_time)
    sky.figure.savefig('apps/project_app/static/project_app/plot_sky.png')
    plt.close()

    plt.ioff()
    airmass = plot_airmass(target, observatory, observe_time)
    airmass.figure.savefig(
        'apps/project_app/static/project_app/plot_airmass.png')
    plt.close()

    plt.ioff()
    finder_image = plot_finder_image(target)
    finder_image[0].figure.savefig(
        'apps/project_app/static/project_app/plot_finder_image.png')
    plt.close()
    request.session['context'] = {
        "sunset": Time(sunset_here, format="iso").value,
        "sunrise": Time(sunrise_here, format="iso").value,
        "date": Time(observe_date, format="iso").value,
        "midnight": Time(midnight_here, format="iso").value,
        "site": request.POST['observatory'],
        "ra": request.POST['ra'],
        "dec": request.POST['dec'],
        "name": request.POST['name']
    }
    return redirect('/display')
Пример #10
0
# Dates are assumed to be UTC by default

"""
We can ask about typical times of interest at this observing position
Returned dates are assumed to be in the observer's time zone for convenience.
The date parameter, if given, can be an astropy Time or a datetime instance.
If no parameter is given, the current date/time is assumed.
"""

# Define a time
from astropy.time import Time
time_obs = Time(2457189.500000, format='jd')

# sun_set_time
obs.sun_set_time(time_obs, which='nearest') # Default
obs.sun_set_time(time_obs, which='next')
obs.sun_set_time(time_obs, which='previous')
obs.sun_set_time() # Will be use time=Time.now(), which='nearest'

# sun_rise_time
obs.sun_rise_time(time_obs, which='nearest') # Default
obs.sun_rise_time(time_obs, which='next')
obs.sun_rise_time(time_obs, which='previous')

# moon rise
obs.moon_rise(time_obs, which='nearest')

# moon set
obs.moon_set(time_obs, which='nearest')
Пример #11
0
def getalt(dt, locname, lat, lng):

    #get time zone
    tf = timezonefinder.TimezoneFinder()
    timezone_str = tf.certain_timezone_at(lat=lat, lng=lng)

    #set location for observer object
    loc = EarthLocation.from_geodetic(lng, lat)

    #setup observer object
    observer = Observer(name=locname,
                        location=loc,
                        timezone=timezone(timezone_str))

    #get the sunset time for the given day, given a date string.
    # for our given location

    sunsettime = observer.sun_set_time(dt, which='next')

    #alternative, can also use nautical twilight as a criteria
    #get nautical twilight time for the given day, given a date string.
    #nautical twilight is when the sun is 12 degrees below the horizon
    # for our given location

    #nautitime=observer.twilight_evening_nautical(dt, which='next')

    #convert time to datetime so that we can manipulate the timezone
    sunset_dt = sunsettime.to_datetime()

    #add utc timezone
    sunset_utc = sunset_dt.replace(tzinfo=timezone('utc'))

    #apply our local time zone
    localtime = sunset_utc.astimezone(timezone(timezone_str))

    #set time
    t = sunsettime

    #setup a dictionary for the visible planets, sun and moon
    bodies = {
        "sun": '',
        "moon": '',
        "mercury": '',
        "venus": '',
        "mars": '',
        "jupiter": '',
        "saturn": ''
    }

    #set up a dictionary for the symbols for the bodies
    bodies_names = {
        "sun": '\u2609',
        #"sun" : '\u1f31e',
        "moon": '\u263d',
        #"moon" : '\u1f31b',
        "mercury": '\u263f',
        "venus": '\u2640',
        "mars": '\u2642',
        "jupiter": '\u2643',
        "saturn": '\u2644'
    }

    #get the alt az position of the bodies for our given time and location
    #we will use the alt number

    with solar_system_ephemeris.set('builtin'):
        for key in bodies:
            bodies[key] = get_body(key, t, loc).transform_to(
                AltAz(obstime=t, location=loc))

    fig = plt.figure(figsize=(10, 10))

    ax = fig.add_subplot(111, polar=True)

    ax.set_theta_direction(-1)
    ax.set_thetamin(180)
    ax.set_thetamax(360)
    ax.set_xticks(np.pi / 180. * np.linspace(180, 360, 5))
    ax.set_xticklabels(['S', 'SW', 'W', 'NW', 'N'])
    ax.set_rorigin(-90)

    ax.set_title("Naked Eye planets, Sun and Moon at sunset on " +
                 str(localtime) + " in " + locname)

    for key, values in bodies.items():
        az_rad = values.az.wrap_at(180 * u.deg).radian
        if key == 'sun':
            plotplanet = ax.scatter(az_rad,
                                    values.alt,
                                    marker='o'.format(bodies_names[key]),
                                    alpha=0.3,
                                    s=700,
                                    color='orange')
            plotplanet.set_label(key)
        else:
            plotplanet = ax.scatter(az_rad,
                                    values.alt,
                                    marker=r"$ {} $".format(bodies_names[key]),
                                    s=250)
            altstr = (values.alt).to_string(precision=0)
            plotplanet.set_label(key + " " + altstr)

    r = np.zeros(360)
    theta = np.arange(0, 2 * np.pi, 2 * np.pi / 360)

    ax.plot(theta, r, color='orange')

    ax.legend(loc='right',
              labelspacing=1.2,
              borderpad=1,
              bbox_to_anchor=(1.4, .55))

    plt.show()
Пример #12
0
    # Start log file to record runs
    f = open('MessierLog.txt', 'w')

    # Set up the plots
    fig = plt.figure(figsize=(8, 7))
    gs = gridspec.GridSpec(2, 1, height_ratios=[1, 1])

    # Set up the current skyview plot
    ax1 = fig.add_subplot(gs[0], projection="polar")

    # Set up the full skyview plot
    ax2 = fig.add_subplot(gs[1], projection="mollweide")

    # Initialize time
    t = Time(Site.sun_set_time(t0, which="next"), format='iso')
    f.write("Start at: {}\n".format(t))

    # Initialize Observed list with starting object
    Observed = [Start(t)]

    # Run the Program
    Final = Run_Through(t, Observed)

    # Add to the counter
    c += 1

    # Get list of all non observed objects
    NO = []
    for g in grid:
        if g not in Final:
Пример #13
0
def component_compare_daily_all(dataFrame, outliers=None):

    componentName = 'H'
    if dataFrame.empty:
        print('No data is available to plot')
        return

    import pytz
    import datetime
    import matplotlib.dates as mdates
    import helper_astro as astro
    from astroplan import Observer
    from datetime import datetime
    from astropy.time import Time
    import astropy.units as u
    import matplotlib.pyplot as plt

    print('Daily comparison graph is being generated.')

    dayDateTimeObj = dataFrame['Date_Time'][
        0]  # just get one of elements from 'Date_Time' list. Will be used to for certian calculations
    localTZ = dayDateTimeObj.tzinfo
    subaru = Observer(longitude=80.07 * u.deg,
                      latitude=6.97 * u.deg,
                      elevation=0 * u.m,
                      name="Subaru",
                      timezone=localTZ)

    noonTimeUTC = subaru.noon(Time(dayDateTimeObj),
                              which='next').to_datetime(pytz.timezone('UTC'))
    print('Local noon time (utc) : ' +
          noonTimeUTC.strftime('%Y-%m-%d %H:%M:%S %z'))
    noonTimeLocal = subaru.noon(Time(dayDateTimeObj),
                                which='next').to_datetime(localTZ)
    print('Local noon time (local time zone) : ' +
          noonTimeLocal.strftime('%Y-%m-%d %H:%M:%S %z'))
    sunRiseTimeLocal = subaru.sun_rise_time(Time(dayDateTimeObj),
                                            which="next").to_datetime(localTZ)
    sunRiseTimeLocalTwilight = subaru.sun_rise_time(Time(dayDateTimeObj),
                                                    which="next",
                                                    horizon=-6 *
                                                    u.deg).to_datetime(localTZ)
    sunSetTimeLocal = subaru.sun_set_time(Time(dayDateTimeObj),
                                          which='next').to_datetime(localTZ)
    print('Sun rise time (local time zone) : ' +
          sunRiseTimeLocal.strftime('%Y-%m-%d %H:%M:%S %z'))
    print('Sun set time (local time zone) : ' +
          sunSetTimeLocal.strftime('%Y-%m-%d %H:%M:%S %z'))

    fig, ax = plt.subplots()
    ax.plot(dataFrame['Date_Time'],
            dataFrame[componentName],
            label=componentName + ' Comp')
    hours = mdates.HourLocator(interval=1)
    h_fmt = mdates.DateFormatter('%d %H:%M:%S', localTZ)
    ax.xaxis.set_major_locator(hours)
    ax.xaxis.set_major_formatter(h_fmt)

    if outliers is not None:
        y_min, y_max = ax.get_ylim()
        outliers[componentName] = y_min
        kw = dict(marker='o', linestyle='none', color='r', alpha=0.3)
        ax.plot(outliers[componentName],
                label=componentName + '-outlier',
                **kw)

    moon_phase = astro.moon_get_moon_phase(dataFrame['Date_Time'][0])
    t = ax.text(0.03,
                0.9,
                'Lunar phase {:3.0f}%'.format(moon_phase * 100),
                horizontalalignment='left',
                verticalalignment='center',
                transform=ax.transAxes)
    t.set_bbox(dict(facecolor='red', alpha=0.5, edgecolor='red'))

    minValueIndex = dataFrame[componentName].idxmin()
    maxValueIndex = dataFrame[componentName].idxmax()

    print('Max value : ' + str(dataFrame.loc[maxValueIndex][componentName]) +
          ', at : ' + dataFrame.loc[maxValueIndex]['Date_Time'].strftime(
              '%Y-%m-%d %H:%M:%S %z'))
    print('Min value : ' + str(dataFrame.loc[minValueIndex][componentName]) +
          ', at : ' + dataFrame.loc[minValueIndex]['Date_Time'].strftime(
              '%Y-%m-%d %H:%M:%S %z'))

    yAxisMiddle = dataFrame.loc[minValueIndex][componentName] + (
        (dataFrame.loc[maxValueIndex][componentName] -
         dataFrame.loc[minValueIndex][componentName]) / 2)

    noonTimeRow = dataFrame[(dataFrame['Date_Time'] == noonTimeLocal.replace(
        second=0, microsecond=0))]
    print('Noon time value of ' + componentName +
          '-Component {:6.3f}'.format(noonTimeRow[componentName][0]))
    ax.axvline(x=noonTimeRow['Date_Time'][0], ls='--', c='orange')
    ax.text(noonTimeRow['Date_Time'][0],
            yAxisMiddle,
            'Local noon',
            rotation=90,
            ha='left',
            va='center')
    ax.axvline(x=sunRiseTimeLocal, ls='--', c='gray')
    ax.axvline(x=sunRiseTimeLocalTwilight, ls='--', c='gray')
    ax.text(sunRiseTimeLocal,
            dataFrame.loc[minValueIndex][componentName],
            'Sun rise',
            rotation=90,
            ha='left',
            va='bottom')
    ax.axvline(x=sunSetTimeLocal, ls='--', c='gray')
    ax.text(sunSetTimeLocal,
            dataFrame.loc[minValueIndex][componentName],
            'Sun set',
            rotation=90,
            ha='left',
            va='bottom')

    ax.axvline(x=dataFrame.loc[maxValueIndex]['Date_Time'], ls='--', c='green')
    ax.text(dataFrame.loc[maxValueIndex]['Date_Time'],
            yAxisMiddle,
            'Max value',
            rotation=90,
            ha='left',
            va='center')

    plt.xlabel('Time (hours)')
    plt.xticks(rotation=90)
    plt.ylabel(componentName + ' Component (nT)')
    plt.legend()
    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()
Пример #15
0
def Isky_parker(airmass, ecl_lat, gal_lat, gal_lon, tai, sun_alt, sun_sep, moon_phase, moon_ill, moon_alt, moon_sep): 
    ''' Parker's sky model, which is a function of: 

    :param airmass: 
        airmass

    :param ecl_lat: 
        ecliptic latitude (used for zodiacal light contribution) 

    :param gal_lat: 
        galactic latitude (used for ISL contribution) 
    
    :param gal_lon: 
        galactic longitude (used for ISL contribution) 

    :param tai: 
        time in seconds 
    
    :param sunalt:
        sun altitude: 0 - 90 deg 
    
    :param sunsep: 
        sun separation: 0 - 90 deg 
    
    :param moonill:  
        moon illumination fraction: 0 - 1 
    
    :param moonalt:  
        moon altitude: 0 - 90 deg 
    
    :param moonsep:  
        moon separation angle: 0 - 180 deg 
    
    '''
    from astroplan import Observer
    from astropy.coordinates import EarthLocation
    X = airmass    # air mass 
    beta = ecl_lat # ecliptic latitude ( used for zodiacal light contribution ) 
    l = gal_lat    # galactic latitude ( used for ISL contribution ) 
    b = gal_lon    # galactic longitude ( used for ISL contribution ) 

    _kpno = EarthLocation.of_site('kitt peak')
    obs_time = Time(tai/86400., scale='tai', format='mjd', location=_kpno)
    mjd = obs_time.mjd

    # fractional months ( used for seasonal contribution) 
    month_frac = obs_time.datetime.month + obs_time.datetime.day/30. 
    
    # fractional hour ( used for hourly contribution) 
    kpno = Observer(_kpno)
    sun_rise    = kpno.sun_rise_time(obs_time, which='next')
    sun_set     = kpno.sun_set_time(obs_time, which='previous')
    hour        = ((obs_time - sun_set).sec)/3600.
    hour_frac   = hour/((Time(sun_rise, format='mjd') - Time(sun_set,format = 'mjd')).sec/3600.)

    alpha = sun_alt    # sun altitude
    delta = sun_sep    # sun separation (separation between the target and the sun's location)
    
    # used for scattered moonlight
    g = moon_phase     # moon phase 
    altm = moon_alt
    illm = moon_ill
    delm = moon_sep
    
    # get coefficients 
    coeffs = _read_parkerCoeffs()

    # sky continuum 
    _w, _Icont = _parker_Icontinuum(coeffs, X, beta, l, b, mjd, month_frac, hour_frac, alpha, delta, altm, illm, delm, g)
    S_continuum = _Icont / np.pi  # BOSS has 2 arcsec diameter

    # sky emission from the UVES continuum subtraction
    w_uves, S_uves = np.loadtxt(''.join([UT.code_dir(), 'dat/sky/UVES_sky_emission.dat']), 
            unpack=True, usecols=[0,1]) 
    f_uves = interp1d(w_uves, S_uves, bounds_error=False, fill_value='extrapolate')
    S_emission = f_uves(_w)

    return _w, S_continuum + S_emission 
Пример #16
0
site = Site('LSST')
observer = Observer(longitude=site.longitude * u.deg,
                    latitude=site.latitude * u.deg,
                    elevation=site.height * u.m,
                    name="LSST")

# This blows up if I try to do it all at once? 250 GB of memory?
results = []

mjds_list = np.array_split(mjds, 500)

for i, mjds in enumerate(mjds_list):
    print('chunk %i of %i' % (i, len(mjds_list)))
    times = Time(mjds, format='mjd')
    print('getting sunsets')
    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
Пример #17
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)
Пример #18
0
class SkySpectrum(object):
    def __init__(self, airmass, ecl_lat, SOLARFLUX, tai, gal_lat, gal_lon,
                 sun_alt, sun_sep, moon_phase, moon_ill, moon_sep, moon_alt,
                 no_zodi):
        self.airmass = airmass
        self.ecl_lat = ecl_lat
        self.tai = tai
        self.gal_lat = gal_lat
        self.gal_lon = gal_lon
        self.sun_alt = sun_alt
        self.sun_sep = sun_sep
        self.moon_phase = moon_phase
        self.moon_ill = moon_ill
        self.moon_sep = moon_sep
        self.moon_alt = moon_alt
        self.SOLARFLUX = SOLARFLUX
        self.no_zodi = no_zodi

        Results = pd.DataFrame.from_csv(
            '/Users/parkerf/Research/SkyModel/BOSS_Sky/SkyModel/ContModel/python/MoonResults.csv'
        )
        Results.columns = [
            'wl', 'model', 'data_var', 'unexplained_var', 'X2', 'rX2', 'c0',
            'c_am', 'tau', 'tau2', 'c_zodi', 'c_isl', 'sol', 'I', 't0', 't1',
            't2', 't3', 't4', 'm0', 'm1', 'm2', 'm3', 'm4', 'm5', 'm6', 'feb',
            'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov',
            'dec', 'c2', 'c3', 'c4', 'c5', 'c6'
        ]
        self.Results = Results[Results['model'] == 'moon']

        THIS_DIR = '/Users/parkerf/Research/SkyModel/BOSS_Sky/SkyModel/ContModel/'  #os.path.split(os.path.abspath(os.getcwd()))[0]
        #print(THIS_DIR)
        #calculate albedo
        albedo_file = THIS_DIR + '/files/albedo_constants.csv'
        albedo_table = pd.read_csv(albedo_file, delim_whitespace=True)
        self.AlbedoConstants = {}
        for constant in list(albedo_table):
            line = interp1d(albedo_table['WAVELENGTH'],
                            albedo_table[constant],
                            bounds_error=False,
                            fill_value=0)
            self.AlbedoConstants[constant] = line

        #get solar flux data
        solar_data = np.load(THIS_DIR + '/files/solar_flux.npy')
        self.solar_flux = interp1d(solar_data['MJD'],
                                   solar_data['fluxobsflux'],
                                   bounds_error=False,
                                   fill_value=0)

        #get zenith extinction curve
        self.zen_ext = np.loadtxt(
            '/Users/parkerf/Research/SkyModel/BOSS_Sky/SkyModel/files/ZenithExtinction-KPNO.dat'
        )
        zen_wave = self.zen_ext[:, 0] / 10.
        ext = self.zen_ext[:, 1]
        zext = interp1d(zen_wave,
                        ext,
                        bounds_error=False,
                        fill_value='extrapolate')
        k = zext(self.Results['wl'])
        self.tput = 1 - (10**(-0.4 * k) - 10**(-0.4 * k * self.airmass))

        self.apache = Observer(APACHE)

        zodi_data = pickle.load(open(THIS_DIR + '/files/s10_zodi.pkl', 'rb'))
        self.zodi = zodi_data(np.abs(self.ecl_lat))

        isl_data = pickle.load(open(THIS_DIR + '/files/isl_map.pkl', 'rb'))
        self.isl = isl_data(self.gal_lon, self.gal_lat)[0]

    def albedo(self, moon_phase):
        p1 = 4.06054
        p2 = 12.8802
        p3 = -30.5858
        p4 = 16.7498
        A = []
        for i in range(4):
            A.append(self.AlbedoConstants['a%d' % i](self.Results['wl']) *
                     (moon_phase**i))
        #for j in range(1,4):
        #    A.append(AlbedoConstants['b%s'%str(j)](wave)*(data_table['SOLAR_SELENO']**(2*j-1)))
        A.append(self.AlbedoConstants['d1'](self.Results['wl']) *
                 np.exp(-moon_phase / p1))
        A.append(self.AlbedoConstants['d2'](self.Results['wl']) *
                 np.exp(-moon_phase / p2))
        A.append(self.AlbedoConstants['d3'](self.Results['wl']) * np.cos(
            (moon_phase - p3) / p4))
        lnA = np.sum(A, axis=0)
        Albedo = np.exp(lnA)
        return Albedo

    def create_features(self):
        obs_time = self.tai / 86400.
        start_time = Time(obs_time, scale='tai', format='mjd', location=APACHE)
        self.mjd = start_time.mjd
        sun_rise = self.apache.sun_rise_time(start_time, which='next')
        sun_set = self.apache.sun_set_time(start_time, which='previous')
        hour = ((start_time - sun_set).sec) / 3600

        month_frac = start_time.datetime.month + start_time.datetime.day / 30.
        hour_frac = hour / (
            (Time(sun_rise, format='mjd') - Time(sun_set, format='mjd')).sec /
            3600.)

        MONTHS = np.zeros(12)

        mm = np.rint(month_frac)
        if mm == 13:
            mm = 1
        MONTHS[int(mm - 1)] = 1

        self.MONTHS = np.array(MONTHS)

        HOURS = np.zeros(6)
        levels = np.linspace(0, 1, 7)

        idx = np.argmin(np.abs(levels - hour_frac))

        HOURS[idx] = 1

        self.HOURS = np.array(HOURS)

    def get_cont_model(self):
        self.create_features()
        solarF = self.Results[
            'sol'] * self.SOLARFLUX  #self.solar_flux(self.mjd-self.Results['I'])
        zodi = self.Results['c_zodi'] * self.zodi

        airmass = self.Results['c_am'] * self.airmass

        months = self.Results['feb'] * self.MONTHS[1] + self.Results[
            'mar'] * self.MONTHS[2] + self.Results['apr'] * self.MONTHS[
                3] + self.Results['may'] * self.MONTHS[4] + self.Results[
                    'jun'] * self.MONTHS[5] + self.Results['jul'] * self.MONTHS[
                        6] + self.Results['sep'] * self.MONTHS[
                            8] + self.Results['oct'] * self.MONTHS[
                                9] + self.Results['nov'] * self.MONTHS[
                                    10] + self.Results['dec'] * self.MONTHS[11]
        hours = self.Results['c2'] * self.HOURS[1] + self.Results[
            'c3'] * self.HOURS[2] + self.Results['c4'] * self.HOURS[
                3] + self.Results['c5'] * self.HOURS[4] + self.Results[
                    'c6'] * self.HOURS[5]

        twi = (self.Results['t0'] * np.abs(self.sun_alt) + self.Results['t1'] *
               (np.abs(self.sun_alt))**2 +
               self.Results['t2'] * np.abs(self.sun_sep)**2 +
               self.Results['t3'] * np.abs(self.sun_sep)) * np.exp(
                   -self.Results['t4'] * self.airmass)

        ALB = self.albedo(self.moon_phase)
        moon = (self.Results['m0'] * self.moon_alt**2 + self.Results['m1'] *
                self.moon_alt + self.Results['m2'] * self.moon_ill**2 +
                self.Results['m3'] * self.moon_ill +
                self.Results['m4'] * self.moon_sep**2 +
                self.Results['m5'] * self.moon_sep) * np.exp(
                    -self.Results['m6'] * self.airmass) * ALB

        if self.sun_alt > -20:

            self.model = (self.Results['c0'] + solarF + months + hours +
                          airmass + zodi +
                          self.Results['c_isl'] * self.isl) * self.tput + twi
        elif self.no_zodi:
            self.model = (self.Results['c0'] + solarF + months + hours +
                          airmass +
                          self.Results['c_isl'] * self.isl) * self.tput + moon
        else:
            self.model = (self.Results['c0'] + solarF + months + hours +
                          airmass + zodi +
                          self.Results['c_isl'] * self.isl) * self.tput + moon

    def get_cont_spectrum(self):
        self.get_cont_model()
        wl = np.array(self.Results['wl'])
        sort = np.argsort(wl)
        func = interp1d(wl[sort],
                        self.model[sort],
                        bounds_error=False,
                        fill_value='extrapolate')

        wave = np.linspace(360, 1000, (1001 - 360))

        return wl[sort], func(wl[sort])
Пример #19
0
results = []

mjd = mjd_start + 0
counter = 0
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))
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
targets = astropy.table.unique(targets, keys=["objectID"])

location = EarthLocation.from_geodetic(-111.5967*u.deg, 31.9583*u.deg,
                                       2096*u.m)
kp = Observer(location=location, name="Kitt Peak",timezone="US/Arizona")

observe_time = Time.now()
observe_time = observe_time + np.linspace(deltat_start, deltat_end, 90)*u.hour
tstart, tend = observe_time[0],observe_time[-1]
frame = AltAz(obstime=observe_time, location=location)
global_constraints = [AirmassConstraint(max = opts.airmass, 
                                        boolean_constraint = False),
                      AtNightConstraint.twilight_civil()]

rise_time = kp.sun_rise_time(tstart, which=u'next', horizon=-12*u.deg).iso
set_time = kp.sun_set_time(tstart, which=u'next', horizon=-12*u.deg).iso

blocks = []
read_out = 10.0 * u.s
nexp = 1
for ii, target in enumerate(targets):
    bandpass = target["filter"]
    exposure_time = int(target["exposure_time"]) * u.s
    priority = target["sig"]

    b = ObservingBlock.from_exposures(target["target"],priority,
                                      exposure_time, nexp, read_out,
                                      configuration = {'filter': bandpass})
    blocks.append(b)

# Initialize a transitioner object with the slew rate and/or the
def astroplan_test():
    '''
    '''

    currentDate = time.strftime("%Y-%m-%d")
    currentTime = time.strftime("%H:%M:%S")
    print('\n  Today is ', currentDate, ' time is ', currentTime, '\n')

    longitude = '36d56m29.000s'
    latitude = '+49d38m10.000s'
    elevation = 156 * u.m
    location = EarthLocation.from_geodetic(longitude, latitude, elevation)

    observer = Observer(
        name='UTR-2 radio telescope',
        location=location,
        pressure=0.615 * u.bar,
        relative_humidity=0.11,
        temperature=0 * u.deg_C,
        timezone=timezone('Europe/Kiev'),
        description=
        "UTR-2 radio telescope, Volokhiv Yar village Kharkiv region Ukraine")

    print(' Observer:', observer.name)

    coordinates = SkyCoord('20h41m25.9s', '+45d16m49.3s', frame='icrs')
    deneb = FixedTarget(name='Deneb', coord=coordinates)

    obs_time = Time('2019-08-06 23:00:00')

    #utr2 = Observer.at_site(observer)

    #obs_time = Time(currentDate +' '+ currentTime)   # Pay attention, not UTC, local time!

    print(' At', obs_time, ' Night is: ', observer.is_night(obs_time))
    print(' Is Deneb on the sky: ', observer.target_is_up(obs_time, deneb))

    sunset_tonight = observer.sun_set_time(obs_time, which='nearest')
    sunrise_tonight = observer.sun_rise_time(obs_time, which='nearest')

    print(' Sunset:', sunset_tonight.iso, ' Sunrise: ', sunrise_tonight.iso)

    # Plotting
    deneb_rise = observer.target_rise_time(obs_time, deneb) + 5 * u.minute
    deneb_set = observer.target_set_time(obs_time, deneb) - 5 * u.minute
    print(' Deneb is up from ', deneb_rise, 'till', deneb_set)

    deneb_style = {'color': 'r'}
    '''
    start = Time('2019-08-06 12:00:00')
    end = Time('2019-08-07 12:00:00')

    time_window = start + (end - start) * np.linspace(0, 1, 20)

    plot_sky(deneb, observer, time_window, style_kwargs=deneb_style)
    plt.legend(loc='center left', bbox_to_anchor=(1.25, 0.5))
    plt.show()
    '''

    start_time = Time('2019-08-06 18:00:00')
    end_time = Time('2019-08-07 09:00:00')
    delta_t = end_time - start_time
    observe_time = start_time + delta_t * np.linspace(0, 1, 75)
    plot_altitude(deneb, observer, observe_time)

    plt.grid(b=True, which='both', color='silver', linestyle='-')
    plt.show()

    return
Пример #22
0
location = EarthLocation.from_geodetic(longitude, latitude, elevation)
# lokasi = Observer(name='Tilong',location=location,timezone=timezone('Asia/Makassar')) # lokasi pengamat
lokasi = Observer(name='Siak', location=location)  #GMS

time = Time('2019-12-26')  #UTC
midnight = Time(lokasi.midnight(time).iso)
delta_md = np.linspace(-5, 5, 22) * u.hour
win_time = midnight + delta_md
night = win_time
# day = (midnight + 12*u.hour) + delta_md
day = (midnight + 12 * u.hour) + np.linspace(0, 3, 30) * u.hour  # GMS
op = pd.read_csv('op.csv', index_col='nama')
ra = op.ra
dec = op.dec

sunset = lokasi.sun_set_time(time)
sunrise = lokasi.sun_rise_time(time)
moonrise = lokasi.moon_rise_time(time)
moonset = lokasi.moon_set_time(time)
moon_ill = lokasi.moon_illumination(time)
moonaltaz = lokasi.moon_altaz(time)
moonaltaz.name = 'moon'
sunaltaz = lokasi.sun_altaz(time)
sunaltaz.name = 'sun'


def objek(nama, ra, dec):
    op = SkyCoord(ra, dec, frame='icrs', unit='deg')
    op_name = FixedTarget(coord=op, name=nama)
    # betelgeus = SkyCoord.from_name('betelgeuse')
    # altaz_frame = lokasi.altaz(time)  # ubah lokasi pengamat ke altaz frame
Пример #23
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 eop(self):

        IERS_A_in_cache()
        # astroplan.get_IERS_A_or_workaround()
        iers.conf.auto_download = False
        iers.conf.auto_max_age = None
        now = Time.now()

        longitude = '78d57m53s'
        latitude = '32d46m44s'
        elevation = 4500 * u.m
        location = EarthLocation.from_geodetic(longitude, latitude, elevation)
        iaohanle = Observer(location=location,
                            timezone='Asia/Kolkata',
                            name="IAO",
                            description="IAO Hanle telescopes")
        iaohanle
        # Calculating the sunset, midnight and sunrise times for our observatory
        sunset_iao = iaohanle.sun_set_time(now, which='nearest')
        eve_twil_iao = iaohanle.twilight_evening_astronomical(now,
                                                              which='nearest')
        midnight_iao = iaohanle.midnight(now, which='next')
        morn_twil_iao = iaohanle.twilight_morning_astronomical(now,
                                                               which='next')
        sunrise_iao = iaohanle.sun_rise_time(now, which='next')
        moon_rise = iaohanle.moon_rise_time(eve_twil_iao, which='nearest')
        moon_set = iaohanle.moon_set_time(now, which='nearest')
        # moon_alt = iaohanle.moon_altaz(now).alt
        # moon_az = iaohanle.moon_altaz(now).az
        #lst_now = iaohanle.local_sidereal_time(now)
        #lst_mid = iaohanle.local_sidereal_time(midnight_iao)
        #print("LST at IAO now is {0:.2f}".format(lst_now))
        #print("LST at IAO at local midnight will be {0:.2f}".format(lst_mid))

        Automation.moon_strength = moon_illumination(midnight_iao)

        observing_time = (morn_twil_iao - eve_twil_iao).to(u.h)
        #print("Total Night hours at IAO tonight  {0:.1f}  ".format(observing_time))

        img = Image.new('RGB', (850, 320), color=(0, 0, 0))
        fnt = ImageFont.truetype(
            '/var/lib/defoma/gs.d/dirs/fonts/DejaVuSerif.ttf', 15)
        d = ImageDraw.Draw(img)
        d.text((10, 11),
               "IAO Hanle Coordinates:   " + str(iaohanle),
               font=fnt,
               fill=(255, 255, 255))

        d.text((10, 71),
               "Moon Illumination Strength          : " +
               str(moon_illumination(midnight_iao)),
               font=fnt,
               fill=(255, 255, 255))
        d.text((10, 101),
               "Sunset                                       : " +
               Time(sunset_iao, out_subfmt='date_hms').iso + " UTC",
               font=fnt,
               fill=(255, 255, 255))
        d.text((10, 131),
               "Astronomical evening twilight : " +
               Time(eve_twil_iao, out_subfmt='date_hms').iso + " UTC",
               font=fnt,
               fill=(255, 255, 255))
        d.text((10, 161),
               "Astronomical morning twilight : " +
               Time(morn_twil_iao, out_subfmt='date_hms').iso + " UTC",
               font=fnt,
               fill=(255, 255, 255))
        d.text((10, 191),
               "Sunrise                                   : " +
               Time(sunrise_iao, out_subfmt='date_hms').iso + " UTC",
               font=fnt,
               fill=(255, 255, 255))
        d.text((10, 221),
               "Moon Rise                    : " +
               Time(moon_rise, out_subfmt='date_hms').iso + " UTC",
               font=fnt,
               fill=(255, 255, 255))

        d.text((10, 251),
               "Moon Set                    : " +
               Time(moon_set, out_subfmt='date_hms').iso + " UTC",
               font=fnt,
               fill=(255, 255, 255))
        d.text((10, 281),
               "Total Astronomical hours tonight                    : " +
               str(observing_time),
               font=fnt,
               fill=(255, 255, 255))
        img.save('tonight.png')
        img.close()

        t_start = eve_twil_iao
        t_end = morn_twil_iao

        # We can turn solar system objects into 'pseudo-fixed' targets to plan observations
        mercury_midnight = FixedTarget(name='Mercury',
                                       coord=get_body('mercury', midnight_iao))
        mercury_midnight.coord
        venus_midnight = FixedTarget(name='Venus',
                                     coord=get_body('venus', midnight_iao))
        venus_midnight.coord

        uranus_midnight = FixedTarget(name='Uranus',
                                      coord=get_body('uranus', midnight_iao))
        uranus_midnight.coord
        neptune_midnight = FixedTarget(name='Neptune',
                                       coord=get_body('neptune', midnight_iao))
        neptune_midnight.coord

        saturn_midnight = FixedTarget(name='Saturn',
                                      coord=get_body('saturn', midnight_iao))
        saturn_midnight.coord

        jupiter_midnight = FixedTarget(name='Jupiter',
                                       coord=get_body('jupiter', midnight_iao))
        jupiter_midnight.coord

        mars_midnight = FixedTarget(name='Mars',
                                    coord=get_body('mars', midnight_iao))
        mars_midnight.coord

        targets = [
            mercury_midnight, venus_midnight, mars_midnight, jupiter_midnight,
            saturn_midnight, uranus_midnight, neptune_midnight
        ]
        targets

        #for target in targets:
        #print(iaohanle.target_rise_time(now, target, which='next', horizon=10 * u.deg).iso)

        # iaohanle.altaz(now, targets[0])

        # print(iaohanle.target_rise_time(now, target, which='next', horizon=10 * u.deg).iso)

        # iaohanle.altaz(now, targets[0])

        times = (t_start - 0.5 * u.h) + (t_end - t_start +
                                         1 * u.h) * np.linspace(0.0, 1.0, 20)
        for target in targets:
            plot_sky(target, iaohanle, times)
        plt.legend(loc=[1.0, 0])
        plt.xlabel('Planets motion tonight')

        # plt.ylim(4,0.5)
        # plt.legend()
        plt.savefig('planets_motion.png')
        plt.close()

        # plt.legend(loc=[1.1,0])

        coords1 = SkyCoord(
            '15h58m3s', '-18d10m0.0s',
            frame='icrs')  # coordinates of Andromeda Galaxy (M32)
        tt1 = FixedTarget(name='Moon', coord=coords1)

        tt1.coord
        t_observe = t_start + (t_end - t_start) * np.linspace(0.0, 1.0, 20)
        plot_sky(tt1, iaohanle, t_observe)
        plt.xlabel('Moon motion tonight')
        plt.savefig('moon_motion.png')
        plt.close()

        if (eve_twil_iao <= now):
            Automation.eve_twilight_flag = 1
            Automation.mor_twilight_flag = 0
            Automation.moon_setting_flag = 0
        elif (morn_twil_iao <= now):
            Automation.eve_twilight_flag = 0
            Automation.mor_twilight_flag = 1
            Automation.moon_setting_flag = 0
        elif (Automation.moon_strength > 0.30):
            if (moon_rise <= now):
                Automation.eve_twilight_flag = 0
                Automation.mor_twilight_flag = 0
                Automation.moon_setting_flag = 1
            elif (moon_set <= now):
                Automation.eve_twilight_flag = 1
                Automation.mor_twilight_flag = 0
                Automation.moon_setting_flag = 0
Пример #25
0
def make_np(t_now, nb_jours, tel):
    telescope = tel
    t0 = Time(t_now)
    dt = Time('2018-01-02 00:00:00',scale='tcg')-Time('2018-01-01 00:00:00',scale='tcg')  # 1 day

    for nb_day in range(0,nb_jours):
        t_now=Time(t0+ nb_day*dt, scale='utc', out_subfmt='date').tt.datetime.strftime("%Y-%m-%d")
        Path = path_spock + '/DATABASE'
        p=os.path.join(Path,str(telescope),'Plans_by_date',str(t_now))
        if not os.path.exists(p):
            os.makedirs(p)

        scheduler_table = Table.read(path_spock + '/DATABASE/' + str(telescope) + '/Archive_night_blocks' +
                                     '/night_blocks_'+ str(telescope) +'_' + str(t_now)+'.txt', format='ascii')

        if (tel == 'Io') or tel == ('Europa') or (tel == 'Ganymede') or (tel == 'Callisto'):
            scheduler_table = dome_rotation(telescope=tel, day_of_night=t_now) # Intentional dome rotation to
            # avoid technical pb on Callisto with dome

        name=scheduler_table['target']
        date_start = scheduler_table['start time (UTC)']
        date_end = scheduler_table['end time (UTC)']
        ra1=scheduler_table['ra (h)']
        ra2=scheduler_table['ra (m)']
        ra3=scheduler_table['ra (s)']
        dec1=scheduler_table['dec (d)']
        dec2=scheduler_table['dec (m)']
        dec3=scheduler_table['dec (s)']
        config = scheduler_table['configuration']
        filt = []
        texp = []

        scheduler_table.add_index('target')
        try:
            index_to_delete=scheduler_table.loc['TransitionBlock'].index
            scheduler_table.remove_row(index_to_delete)
        except KeyError:
            print()

        for i in range(0,len(scheduler_table)):
            if name[i]!='TransitionBlock':
                conf = ast.literal_eval(config[i])
                filt.append(conf['filt'])
                texp.append(conf['texp'])
                if telescope != 'Artemis':
                    if filt[i] == 'z' or filt[i] == 'g' or filt[i] == 'g' or filt[i] == 'i' or filt[i] == 'r':
                        a = filt[i]
                        filt[i] = a+'\''

        if telescope == 'Artemis':
            autofocus = True
        else:
            autofocus = False
        waitlimit = 600
        afinterval = 60
        count = '5000'

        location = EarthLocation.from_geodetic(-70.40300000000002*u.deg, -24.625199999999996*u.deg,
                                               2635.0000000009704*u.m)
        paranal = Observer(location=location, name="paranal", timezone="UTC")
        t = Time(t_now)
        sun_set = paranal.sun_set_time(t, which='next')
        sun_rise = paranal.sun_rise_time(t, which='next')
        location_SNO = EarthLocation.from_geodetic(-16.50583131*u.deg, 28.2999988*u.deg, 2390*u.m)
        teide = Observer(location=location_SNO, name="SNO", timezone="UTC")
        sun_set_teide=teide.sun_set_time(t, which='next')
        sun_rise_teide=teide.sun_rise_time(t+1, which='next')
        location_saintex = EarthLocation.from_geodetic(-115.48694444444445*u.deg, 31.029166666666665*u.deg,
                                                       2829.9999999997976*u.m)
        san_pedro = Observer(location=location_saintex, name="saintex", timezone="UTC")
        sun_set_san_pedro=san_pedro.sun_set_time(t+1, which='next')
        sun_rise_san_pedro=san_pedro.sun_rise_time(t+1, which='next')

        Path=Path_txt_files(telescope)
        if telescope.find('Europa') is not -1:
            startup(t_now, name[0], sun_set.iso, date_start[0], Path, telescope)
        if telescope.find('Ganymede') is not -1:
            startup(t_now, name[0], sun_set.iso, date_start[0], Path, telescope)
        if telescope.find('Io') is not -1:
            startup(t_now, name[0],sun_set.iso, date_start[0], Path, telescope)
        if telescope.find('Callisto') is not -1:
            startup(t_now, name[0], sun_set.iso, date_start[0], Path, telescope)
        if telescope.find('Artemis') is not -1:
            startup_artemis(t_now, name[0], sun_set_teide.iso, date_start[0], Path)
        if telescope.find('Saint-Ex') is not -1:
            startup(t_now, name[0], sun_set_san_pedro.iso, date_start[0], Path, telescope)
        for i, nam in enumerate(name):
            if nam != 'TransitionBlock':
                if len(name) >= 2:
                    if i == 0:
                        first_target(t_now, nam, date_start[i], date_end[i], waitlimit, afinterval, autofocus,count,
                                     filt[i], texp[i],ra1[i], ra2[i], ra3[i], dec1[i], dec2[i], dec3[i], name[i+1],
                                     Path, telescope)
                    if i == 0 and telescope.find('Ganymede') is not -1:
                        first_target(t_now, nam, date_start[i], date_end[i], waitlimit, afinterval, autofocus,count,
                                     filt[i], texp[i], ra1[i], ra2[i], ra3[i], dec1[i], dec2[i], dec3[i], name[i+1],
                                     Path, telescope)
                    if i == 0 and telescope.find('Artemis') is not -1:
                        filt[i] = filt[i].replace('\'', '')
                        if nam == 'haumea':
                            SPOCKtxt.haumea(t_now,date_start[i],date_end[i], count, filt='Exo', exptime=240,
                                            name_2=name[i+1], binning=2, Path=Path, telescope='Artemis')
                        else:
                            first_target(t_now, nam, date_start[i], date_end[i], waitlimit, afinterval, autofocus,count,
                                         filt[i], texp[i], ra1[i], ra2[i],ra3[i], dec1[i], dec2[i], dec3[i], name[i+1],
                                         Path, telescope='Artemis')
                    if i == 0 and telescope.find('Saint-Ex') is not -1:
                        first_target(t_now, nam, date_start[i], date_end[i], waitlimit, afinterval, autofocus,count,
                                     filt[i], texp[i], ra1[i], ra2[i], ra3[i], dec1[i], dec2[i], dec3[i], name[i+1],
                                     Path, telescope='Saint-Ex')
                    if i == (len(name)-1) and telescope.find('Europa') is not -1:
                        target(t_now,nam,date_start[i],date_end[i],waitlimit,afinterval, autofocus,count,filt[i],
                               texp[i],ra1[i],ra2[i],ra3[i],dec1[i],dec2[i],dec3[i], None, Path, telescope)
                        flatdawn(t_now,date_end[i],sun_rise.iso,Path,telescope)
                    if i == (len(name)-1) and telescope.find('Callisto') is not -1:
                        target(t_now,nam,date_start[i],date_end[i],waitlimit,afinterval, autofocus,count,filt[i],
                               texp[i],ra1[i],ra2[i],ra3[i],dec1[i],dec2[i],dec3[i],None,Path,telescope)
                        flatdawn(t_now,date_end[i],sun_rise.iso,Path,telescope)
                    if i == (len(name)-1) and telescope.find('Io') is not -1:
                        target(t_now,nam,date_start[i],date_end[i],waitlimit,afinterval, autofocus,count,filt[i],
                               texp[i],ra1[i],ra2[i],ra3[i],dec1[i],dec2[i],dec3[i],None,Path,telescope)
                        flatdawn(t_now,date_end[i],sun_rise.iso,Path,telescope)
                    if i==(len(name)-1) and telescope.find('Ganymede') is not -1:
                        target(t_now,nam,date_start[i],date_end[i],waitlimit,afinterval, autofocus,count,filt[i],
                               texp[i],ra1[i],ra2[i],ra3[i],dec1[i],dec2[i],dec3[i],None,Path,telescope)
                        flatdawn(t_now,date_end[i],sun_rise.iso,Path,telescope)
                    if i == (len(name)-1) and telescope.find('Artemis') is not -1:
                        filt[i] = filt[i].replace('\'', '')
                        if nam == 'haumea':
                            SPOCKtxt.haumea(t_now, date_start[i],date_end[i], count, filt='Exo', exptime=240,
                                            name_2=None, binning=2, Path=Path, telescope='Artemis')
                        else:
                            target(t_now,nam,date_start[i],date_end[i],waitlimit,afinterval, autofocus,count,
                               filt[i].replace('\'',''),texp[i],ra1[i],ra2[i],ra3[i],dec1[i],dec2[i],dec3[i],None,
                               Path,telescope='Artemis')
                        flatdawn_artemis(t_now,date_end[i],sun_rise_teide.iso,Path)

                    if i == (len(name)-1) and telescope.find('Saint-Ex') is not -1:
                        target(t_now,nam,date_start[i],date_end[i],waitlimit,afinterval, autofocus,count,filt[i],
                               texp[i],ra1[i],ra2[i],ra3[i],dec1[i],dec2[i],dec3[i],None,Path,telescope='Saint-Ex')
                        flatdawn(t_now,date_end[i],sun_rise_san_pedro.iso,Path,telescope)

                    if i < (len(name)-1):
                        if nam == 'haumea':
                            SPOCKtxt.haumea(t_now, date_start[i],date_end[i], count, filt='Exo', exptime=240,
                                            name_2=name[i+1], binning=2, Path=Path, telescope='Artemis')
                        else:
                            target(t_now,nam,date_start[i],date_end[i],waitlimit,afinterval, autofocus,count,filt[i],
                               texp[i],ra1[i],ra2[i],ra3[i],dec1[i],dec2[i],dec3[i],name[i+1],Path,telescope=telescope)

                else:
                    if i == (len(name)-1) and telescope.find('Europa') is not -1:
                        target(t_now,nam,date_start[i],date_end[i],waitlimit,afinterval, autofocus,count,filt[i],
                               texp[i],ra1[i],ra2[i],ra3[i],dec1[i],dec2[i],dec3[i],None,Path,telescope)
                        flatdawn(t_now,date_end[i],sun_rise.iso,Path,telescope)
                    if i==(len(name)-1) and telescope.find('Callisto') is not -1:
                        target(t_now,nam,date_start[i],date_end[i],waitlimit,afinterval, autofocus,count,filt[i],
                               texp[i],ra1[i],ra2[i],ra3[i],dec1[i],dec2[i],dec3[i],None,Path,telescope)
                        flatdawn(t_now,date_end[i],sun_rise.iso,Path,telescope)
                    if i==(len(name)-1) and telescope.find('Io') is not -1:
                        target(t_now,nam,date_start[i],date_end[i],waitlimit,afinterval, autofocus,count,filt[i],
                               texp[i],ra1[i],ra2[i],ra3[i],dec1[i],dec2[i],dec3[i],None,Path,telescope)
                        flatdawn(t_now,date_end[i],sun_rise.iso,Path,telescope)
                    if i == (len(name)-1) and telescope.find('Ganymede') is not -1:
                        target(t_now,nam,date_start[i],date_end[i],waitlimit,afinterval, autofocus,count,filt[i],
                               texp[i],ra1[i],ra2[i],ra3[i],dec1[i],dec2[i],dec3[i],None,Path,telescope)
                        flatdawn(t_now,date_end[i],sun_rise.iso,Path,telescope)
                    if i == (len(name)-1) and telescope.find('Artemis') is not -1:
                        filt[i] = filt[i].replace('\'', '')
                        if nam == 'haumea':
                            SPOCKtxt.haumea(t_now, date_start[i],date_end[i], count, filt='Exo', exptime=240,
                                            name_2=None, binning=2, Path=Path, telescope='Artemis')
                        else:
                            target(t_now,nam,date_start[i],date_end[i],waitlimit,afinterval, autofocus,count,
                               filt[i].replace('\'',''),texp[i],ra1[i],ra2[i],ra3[i],dec1[i],dec2[i],dec3[i],
                               None,Path,telescope='Artemis')
                        flatdawn_artemis(t_now,date_end[i],sun_rise_teide.iso,Path)
                    if i == (len(name)-1) and telescope.find('Saint-Ex') is not -1:
                        target(t_now,nam,date_start[i],date_end[i],waitlimit,afinterval, autofocus,count,
                               filt[i],texp[i],ra1[i],ra2[i],ra3[i],dec1[i],dec2[i],dec3[i],
                               None,Path,telescope='Saint-Ex')
                        flatdawn(t_now,date_end[i],sun_rise_san_pedro.iso,Path,telescope)

                    if i < (len(name)-1):
                        if nam == 'haumea':
                            SPOCKtxt.haumea(t_now, date_start[i],date_end[i], count, filt='Exo', exptime=240,
                                            name_2=name[i+1], binning=2, Path=Path, telescope='Artemis')
                        else:
                            target(t_now,nam,date_start[i],date_end[i],waitlimit,afinterval, autofocus,count,
                               filt[i],texp[i],ra1[i],ra2[i],ra3[i],dec1[i],dec2[i],dec3[i],name[i+1],
                               Path, telescope=telescope)

        if telescope.find('Callisto') is not -1:
            flatexo_calli(Path,t_now,filt,nbu=3,nbB=3,nbz=3,nbV=3,nbr=3,nbi=3,nbg=3,nbIz=7,nbExo=3,nbClear=3)
        if telescope.find('Ganymede') is not -1:
            flatexo_gany(Path,t_now,filt,nbOIII=3,nbHa=3,nbSII=3,nbz=3,nbr=3,nbi=3,nbg=3,nbIz=7,nbExo=3,nbClear=3)
        if telescope.find('Io') is not -1:
            flatexo_io(Path,t_now,filt,nbu=3,nbHa=3,nbRc=3,nbz=3,nbr=3,nbi=3,nbg=3,nbIz=7,nbExo=3,nbClear=3)
        if telescope.find('Europa') is not -1:
            flatexo_euro(Path,t_now,filt,nbRc=3,nbB=3,nbz=3,nbV=3,nbr=3,nbi=3,nbg=3,nbIz=7,nbExo=3,nbClear=3)
        if telescope.find('Artemis') is not -1:
            flatexo_artemis_evening(Path,t_now,filt,nbu=3,nbz=3,nbr=3,nbi=3,nbg=3,nbIz=7,nbExo=7,nbClear=3)
            flatexo_artemis_morning(Path,t_now,filt,nbu=3,nbz=3,nbr=3,nbi=3,nbg=3,nbIz=7,nbExo=7,nbClear=3)
        if telescope.find('Saint-Ex') is not -1:
            flatexo_saintex(Path,t_now,filt,nbu=3,nbz=3,nbr=3,nbi=3,nbg=3,nbIz=9,nbExo=3,nbClear=3)

        if telescope.find('Saint-Ex') is not -1:
            list_texps = [texp[i] for i in range(len(texp))]
            list_texps = list(dict.fromkeys(list_texps))
            biasdark(t_now,Path,telescope,texps=list_texps)
        else:
            if np.any(name == 'haumea'):
                biasdark(t_now, Path, telescope,bining_2=True)
            else:
                biasdark(t_now, Path, telescope, bining_2=False)

        p2 = os.path.join(path_spock + '/DATABASE', str(telescope), 'Zip_files', str(t_now))
        shutil.make_archive(p2, 'zip', p)