Exemplo n.º 1
0
def format_observatories(observatories):
    """

    A function that takes an input containing observatory information and
    formally casts it into a list of Observer objects.

    TO IMPLEMENT:
        Only takes a list of dictionaries as input, consider generalizing -
            IMPLEMENTED, BUT COULD BE BETTER

    Args:
        observatories: List of dictionaries, with each dictionary containing
            the information necessary to initialize an Observer object

                {'name' key : string value,
                 'location' key : EarthLocation value}

    Returns:
        List of Observer objects

    """
    if type(observatories) is list:
        return [
            Observer(location=observatory.get('location'),
                     name=observatory.get('name'))
            for observatory in observatories
        ]

    elif type(observatories) is dict:
        return Observer(location=observatories.get('location'),
                        name=observatories.get('name'))
Exemplo n.º 2
0
    def nautical_twilight(self, date_obs,
                              site_longitude=30.335555,
                              site_latitude=36.824166,
                              site_elevation=2500,
                              site_name="tug",
                              time_zone="Europe/Istanbul",
                              which="next"):

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

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

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

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

        # localized time conversion
        return(tug.astropy_time_to_datetime(mt),
               tug.astropy_time_to_datetime(et))
def culmination_time_utc_astroplan(source_name, date, print_or_not):
    """
    Calculates culmination time in UTC with astroplan library
    """
    # Coordinates of UTR-2 radio telescope
    longitude = '36d56m27.560s'
    latitude = '+49d38m10.310s'
    elevation = 156 * u.m
    observatory = 'UTR-2, Ukraine'
    utr2_location = EarthLocation.from_geodetic(longitude, latitude, elevation)

    if print_or_not == 1:
        print('\n  Observatory:', observatory, '\n')
        print('  Coordinates: \n  * Longitude: ',
              str(utr2_location.lon).replace("d", "\u00b0 ").replace("m", "\' ").replace("s", "\'\' "),
              ' \n  * Latitude:   ' + str(utr2_location.lat).replace("d", "\u00b0 ").replace("m", "\' ").replace("s", "\'\' ") + '\n')
        print('  Source:', source_name, '\n')

    observer = Observer(location=utr2_location, name='Volokhiv Yar', timezone='UTC')

    alt, az = catalogue_sources(source_name)
    coordinates = SkyCoord(alt, az, frame='icrs')

    target = FixedTarget(coord=coordinates, name="target")
    date_of_obs = Time(date, scale='utc')
    culmination = observer.target_meridian_transit_time(date_of_obs, target, which='next')
    culm_time = culmination.to_datetime().time()

    culm_time = date + ' ' + str(culm_time)[0:8]

    if print_or_not == 1:
        print('  Culmination time:', culm_time, ' UTC \n')

    return culm_time
Exemplo n.º 4
0
    def nautical_twilight(self,
                          date_obs,
                          site_longitude=30.335555,
                          site_latitude=36.824166,
                          site_elevation=2500,
                          site_name="tug",
                          time_zone="Europe/Istanbul",
                          which="next"):

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

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

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

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

        # localized time conversion
        return (tug.astropy_time_to_datetime(mt),
                tug.astropy_time_to_datetime(et))
Exemplo n.º 5
0
def tel_move(RA, DEC, n, COLOR, s):
    #initialize  and update position coordinates
    location = EarthLocation.from_geodetic(lon=-111.5947 * u.deg,
                                           lat=31.95844 * u.deg,
                                           height=2097.024 * u.m)
    kittpeak = Observer(location=location, name='kitt peak')
    coord = SkyCoord(ra=RA * u.deg, dec=DEC * u.deg, unit='deg', frame='icrs')
    time = thetime('2018-4-6 00:00:00')
    times = time + (n * u.second)
    lst = kittpeak.local_sidereal_time(times)
    ha = (lst.hour - (RA / 15.0)
          )  # given in hours, converted to degrees later for PA calc
    frame = AltAz(obstime=times, location=location)
    new_coord = coord.transform_to(frame)
    alt = new_coord.alt.degree
    az = new_coord.az.degree

    # parallactic angle calculation -----------------------------------------------------------------------------------
    sina = np.sin(np.radians(ha * 15.0))
    cosa = (np.tan(np.radians(31.95844)) * np.cos(np.radians(DEC))) - (
        np.sin(np.radians(DEC)) * np.cos(np.radians(ha * 15.0)))
    pa = np.degrees(np.arctan2(sina, cosa))

    #s.send(message.encode('utf-8'))
    packer = struct.Struct('d d d d d d d')
    data = packer.pack(pa, slew_flag, alt, az, ra, dec, othertime.time())
    s.send(data)
    return s
Exemplo n.º 6
0
def rise_time(obsnight, coords, tel=None):

    import time
    tstart = time.time()

    tme = Time(str(obsnight.obs_date).split()[0])
    sc = SkyCoord('%s %s' % (coords[0], coords[1]), unit=(u.hourangle, u.deg))

    location = EarthLocation.from_geodetic(
        obsnight.resource.telescope.longitude * u.deg,
        obsnight.resource.telescope.latitude * u.deg,
        obsnight.resource.telescope.elevation * u.m)
    tel = Observer(location=location, timezone="UTC")

    target_rise_time = tel.target_rise_time(tme,
                                            sc,
                                            horizon=18 * u.deg,
                                            which="previous")

    if target_rise_time:
        returnstarttime = target_rise_time.isot.split('T')[-1]
    else:
        returnstarttime = None

    print(time.time() - tstart)

    return (returnstarttime)
    def __init__(self, targets, tzinfo='Australia/Sydney', portal_htmls=[]):
        ### target and calibrators
        if not isinstance(targets, Sequence):
            targets = [targets]
            
        self.targets = targets
        self.calibrator = [FixedTarget(name='1934-638', coord=SkyCoord('19h39m25.026s -63d42m45.63s')),
                           FixedTarget(name='0823-500', coord=SkyCoord('08h25m26.869s -50d10m38.49s'))]
        ### observer
        ATCA_loc = (149.5501388*u.deg,-30.3128846*u.deg,237*u.m)
        location = EarthLocation.from_geodetic(*ATCA_loc)

        self.observer = Observer(name='ATCA',
                                 location=location,
                                 timezone=timezone('Australia/Sydney'))
        time_now = datetime.now(timezone(tzinfo))
        self.utcoffset = time_now.utcoffset()
        self.tzinfo = tzinfo
        
        if len(portal_htmls) == 0:
            self.portal_tz = None
            self.portal_sched = None
        else:
            atca_scheds = ATCA_sched(portal_htmls)
            self.portal_tz = atca_scheds.timezone
            self.portal_sched = atca_scheds.schedules
            
            ### portal utcoffset
            portal_now = datetime.now(timezone(self.portal_tz))
            self.portal_utcoffset = portal_now.utcoffset()
Exemplo n.º 8
0
def add_obsairmass_df_comp_obs(df_comp_obs, site_dict, df_comps, df_images):
    observer = Observer(longitude=site_dict['longitude'] * u.deg,
                        latitude=site_dict['latitude'] * u.deg,
                        elevation=site_dict['elevation'] * u.m)
    df_comp_obs['ObsAirmass'] = None
    skycoord_dict = {
        comp_id: SkyCoord(ra=ra_deg * u.deg, dec=dec_deg * u.deg)
        for (comp_id, ra_deg, dec_deg
             ) in zip(df_comps.index, df_comps['RA_deg'], df_comps['Dec_deg'])
    }
    altaz_frame_dict = {
        filename: observer.altaz(Time(jd_mid, format='jd'))
        for (filename,
             jd_mid) in zip(df_images['FITSfile'], df_images['JD_mid'])
    }
    print('ObsAirmasses: ', end='', flush=True)
    done_count = 0
    for obs, filename, comp_id in zip(df_comp_obs.index,
                                      df_comp_obs['FITSfile'],
                                      df_comp_obs['CompID']):
        alt = skycoord_dict[comp_id].transform_to(
            altaz_frame_dict[filename]).alt.value
        df_comp_obs.loc[obs,
                        'ObsAirmass'] = 1.0 / sin(alt / DEGREES_PER_RADIAN)
        done_count += 1
        if done_count % 100 == 0:
            print('.', end='', flush=True)
    print('\nObsAirmasses written to df_comp_obs:', str(len(df_comp_obs)))
Exemplo n.º 9
0
def get_info_of_target(target, *args, **kwargs):
    ra = target.ra
    dec = target.dec
    coords = SkyCoord(ra=ra, dec=dec, unit=(u.degree, u.degree))
    hanle = EarthLocation(lat=32.77889 * u.degree,
                          lon=78.96472 * u.degree,
                          height=4500 * u.m)
    iao = Observer(location=hanle, name="GIT", timezone="Asia/Kolkata")
    twilight_prime = iao.sun_rise_time(
        Time(datetime.utcnow()),
        which="next",
        horizon=sunrise_horizon * u.degree) - 12 * u.hour
    targets_rise_time = iao.target_rise_time(twilight_prime,
                                             coords,
                                             which="nearest",
                                             horizon=horizon * u.degree)
    targets_set_time = iao.target_set_time(targets_rise_time,
                                           coords,
                                           which="next",
                                           horizon=horizon * u.degree)
    rise_time_IST = (targets_rise_time + 5.5 * u.hour).isot
    set_time_IST = (targets_set_time + 5.5 * u.hour).isot
    tend = targets_set_time
    mooncoords = get_moon(tend, hanle)
    sep = mooncoords.separation(coords)
    print(target.name, rise_time_IST, set_time_IST, sep)
Exemplo n.º 10
0
def simple_track(ra, dec, frame, time, input_lat, input_lon, alt, plot,
                 alt_limit):
    prototype_dish = EarthLocation(lat=input_lat * u.deg,
                                   lon=input_lon * u.deg,
                                   height=alt * u.m)
    sc = SkyCoord(ra,
                  dec,
                  unit='deg',
                  frame=frame,
                  equinox="J2000",
                  obstime=time[0],
                  location=prototype_dish)
    sc = sc.transform_to('icrs')
    prototype_dish_observer = Observer(location=prototype_dish)

    source_altaz = sc.transform_to(AltAz(obstime=time,
                                         location=prototype_dish))
    for i in range(len(source_altaz)):
        if source_altaz[i].alt.deg > alt_limit:
            print("{0} {1:3.8f} {2:3.8f} {3} {4}".format(
                time[i].mjd,
                source_altaz[i].az.deg,
                source_altaz[i].alt.deg,
                1,
                prototype_dish_observer.parallactic_angle(time=time[i],
                                                          target=sc).deg,
                file=sys.stdout,
                flush=True))
        else:
            break
    if plot == 1:
        plt.scatter(source_altaz.az.deg, source_altaz.alt.deg)
        plt.show()
Exemplo n.º 11
0
    def __init__(self,
                 name,
                 codename,
                 network,
                 location,
                 freqs_sefds,
                 min_elevation=20 * u.deg,
                 fullname=None,
                 all_networks=None,
                 country='',
                 diameter=''):
        """Initializes a station. The given name must be the name of the station that
        observes, with the typical 2-letter format used in the EVN (with exceptions).

        Inputs
        - name : str
            Name of the observer (the station that is going to observe).
        - codename : str
            A code for the name of the station. It can be the same as name.
        - network : str
            Name of the network to which the station belongs.
        - location : EarthLocation
            Position of the observer on Earth.
        - freqs_sefds : dict
            Dictionary with all frequencies the station can observe, and as values
            the SEFD at each frequency.
        - min_elevation : Quantity
            Minimum elevation that the station can observe a source. If no units
            provided, degrees are assumed. By default it 20 degrees.
        - fullname : str [OPTIONAL]
            Full name of the station. If not given, `name` is assumed.
        - all_networks : str [OPTIONAL]
            Networks where the station can participate (free style).
        - country : str [OPTIONAL]
            Country where the station is placed.
        """
        self.observer = Observer(name=name.replace('_', ' '),
                                 location=location)
        self._codename = codename
        self._network = network
        self._freqs_sefds = freqs_sefds
        if (type(min_elevation) is float) or (type(min_elevation) is int):
            self._min_elev = min_elevation * u.deg
        else:
            self._min_elev = min_elevation

        if fullname is None:
            self._fullname = name
        else:
            self._fullname = fullname

        if all_networks is None:
            self._all_networks = network
        else:
            self._all_networks = all_networks

        self._country = country
        self._diameter = diameter
Exemplo n.º 12
0
def airmass_plots(KPNO=False,ING=False,MLO=False):

    observer_site = Observer.at_site("Kitt Peak", timezone="US/Mountain")

    if KPNO:
        print('plotting airmass curves for Kitt Peak')
        observing_location = EarthLocation.of_site('Kitt Peak')
        observer_site = Observer.at_site("Kitt Peak", timezone="US/Mountain")
        start_time = Time('2017-03-12 01:00:00') # UTC time, so 1:00 UTC = 6 pm AZ mountain time
        end_time = Time('2017-03-12 14:00:00')

    elif MLO:
        print('plotting airmass curves for MLO')
        observing_location = EarthLocation.of_site(u'Palomar')
        observer_site = Observer.at_site("Palomar", timezone="US/Pacific")
        # for run starting 2019-Apr-04 at MLO
        start_time = Time('2019-04-03 01:00:00') # need to enter UTC time, MLO UTC+6?
        end_time = Time('2019-04-03 14:00:00')
        
    elif ING:
        print('plotting airmass curves for INT')
        observing_location = EarthLocation.of_site(u'Roque de los Muchachos')
        observer_site = Observer.at_site("Roque de los Muchachos", timezone="GMT")
        # for run starting 2019-Feb-04 at INT
        start_time = Time('2019-02-04 19:00:00') # INT is on UTC
        end_time = Time('2019-02-05 07:00:00')

    #observing_time = Time('2017-05-19 07:00')  # 1am UTC=6pm AZ mountain time
    #observing_time = Time('2018-03-12 07:00')  # 1am UTC=6pm AZ mountain time
    #aa = AltAz(location=observing_location, obstime=observing_time)


    #for i in range(len(pointing_ra)):



    delta_t = end_time - start_time
    observing_time = start_time + delta_t*np.linspace(0, 1, 75)
    nplots = int(sum(obs_mass_flag)/8.)
    print(nplots)
    for j in range(nplots):
        plt.figure()
        legend_list = []
        for i in range(8):
            pointing_center = coords.SkyCoord(pointing_ra[8*j+i]*u.deg, pointing_dec[8*j+i]*u.deg, frame='icrs')
            if i == 3:
                plot_airmass(pointing_center,observer_site,observing_time,brightness_shading=True)
            else:
                plot_airmass(pointing_center,observer_site,observing_time)
            legend_list.append('Pointing %02d'%(8*j+i+1))
    
        plt.legend(legend_list)
        #plt.ylim(0.9,2.5)
        plt.gca().invert_yaxis()
        plt.subplots_adjust(bottom=.15)
        #plt.axvline(x=7*u.hour,ls='--',color='k')
        plt.axhline(y=2,ls='--',color='k')
        plt.savefig(outfile_prefix+'airmass-%02d.png'%(j+1))
Exemplo n.º 13
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
Exemplo n.º 14
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
def get_SMO_pos():
    global lat_i, long_i, RA_i, DEC_i, times, tname_i, option, places
    global coords_s, coords_m, coords_o, dist_sun, dist_moon, loc
    """read in from entry boxes"""

    ##handle if there is a look up to be done
    site = option.get()
    if (site is 'Anywhere Else'):
        lat = float(lat_i.get())
        long = float(long_i.get())

    else:
        if (places.get(site) is None):
            Label(master,
                  bg='red',
                  text='SITE NAME {} IS NOT VALID'.format(site.upper())).grid(
                      row=5, column=3)

            return None
        else:
            lat, long = places[site]

    #loc = coordinates.EarthLocation(lat=lat*u.deg, lon=long*u.deg)
    loc = Observer(longitude=long * u.degree,
                   latitude=lat * u.degree,
                   name=site)

    tname = str(tname_i.get())
    if (tname is ''):
        RA = float(RA_i.get())
        DEC = float(DEC_i.get())
        """target's RA and DEC"""
        coords_o = coordinates.SkyCoord(ra=RA * u.hour,
                                        dec=DEC * u.degree,
                                        frame='gcrs')

    else:
        coords_o = coordinates.SkyCoord.from_name(tname, frame='gcrs')
    """Sun's RA and DEC throughout the given time"""
    coords_s = loc.sun_altaz(times)
    """Moon's RA and DEC at the location, throughout the given time"""
    coords_m = loc.moon_altaz(times)
    """get separation angles in radians for the Sun and Moon"""
    """this returns a value in the range [-180, 180]"""
    dist_sun = (coords_s.separation(coords_o).degree)
    dist_moon = (coords_m.separation(coords_o).degree)
    """change button after press"""
    WHERE_button.config(fg='black', bg='#FFE100')
Exemplo n.º 16
0
    def __init__(self):
        self.scheduler = scheduler.Scheduler()
        self.observatory = Observer.at_site(
            "Anglo-Australian Observatory"
        )  # TODO: enter LAT and LON coordinates

        self.ra_current = None
        self.dec_current = None

        self.number_of_tiles = self.scheduler.number_of_all_tiles(
        )  # total number of all the tiles in this tiling run
        self.number_of_tiles_observed = 0

        self.unique_targets = set()
        self.repeats = Dictlist()
        self.total_number_cumulative_unique = 0  # EXcluding repeated observations
        self.total_number_cumulative = 0  # INcluding repeated observations

        self.number_of_tiles_observed = 0
        self.number_of_all_tiles = scheduler.number_of_all_tiles()

        self.dt = TimeDelta(0, format='sec')
        self.time_with_no_observing = TimeDelta(0, format='sec')

        # print output
        self.f = open(params_simulator.params['simulator_statistics_output'],
                      'wb')
        self.f.write(
            '# time; tile_id; Ntargets_in_this_tile; Nunique_targets_in_this_tile; Ntotal_number_cumulative_unique; Ntotal_number_cumulative; priority; weight; mag_max; json_filename \n'
        )

        # Print calibration files (times)
        self.fc = open(
            params_simulator.params['simulator_statistics_output_calibration'],
            'wb')
Exemplo n.º 17
0
async def test_scheduler():
    # init observer and time
    observer = Observer.at_site('SAAO')
    now = Time('2019-11-21T17:10:00Z')

    # have some test functions
    functions = {
        'B': ' exp(-1.22034 * (h + 3.16086))',
        'V': ' exp(-1.27565 * (h + 3.48265))',
        'R': ' exp(-1.39148 * (h + 3.63401))',
    }

    # set constant priorities
    priorities = ConstSkyflatPriorities({('B', (1, 1)): 1, ('V', (1, 1)): 2, ('R', (1, 1)): 3})

    # create scheduler
    scheduler = Scheduler(functions, priorities, observer)
    await scheduler(now)

    # test order
    assert scheduler[0].filter_name == 'B'
    assert scheduler[1].filter_name == 'V'
    assert scheduler[2].filter_name == 'R'

    # test start/end times
    assert scheduler[0].start == 1160
    assert pytest.approx(scheduler[0].end, 0.01) == 1200.46
    assert scheduler[1].start == 1270
    assert pytest.approx(scheduler[1].end, 0.01) == 1310.59
    assert scheduler[2].start == 1330
    assert pytest.approx(scheduler[2].end, 0.01) == 1370.59
Exemplo n.º 18
0
    def __init__(self,
                 coordinates,
                 observatory='Mt Graham',
                 night=None,
                 timezone='UTC',
                 ax=None,
                 timedelta=None):
        if not isinstance(coordinates, SkyCoord):
            self.coord = SkyCoord(coordinates, unit=(u.hourangle, u.deg))
        else:
            self.coord = coordinates

        try:
            self.observer = Observer.at_site(observatory, timezone=timezone)
        except USE:
            print EarthLocation.get_site_names()
            raise

        if not night:
            self.time = Time.now()
        else:
            self.time = Time(night)

        if timedelta:
            self.time = timedelta

        self.ax = ax

        self._make_figure()
Exemplo n.º 19
0
def test_docs_example():
    # Test the example in astroplan/docs/tutorials/constraints.rst
    target_table_string = """# name ra_degrees dec_degrees
    Polaris 37.95456067 89.26410897
    Vega 279.234734787 38.783688956
    Albireo 292.68033548 27.959680072
    Algol 47.042218553 40.955646675
    Rigel 78.634467067 -8.201638365
    Regulus 152.092962438 11.967208776"""

    from astroplan import Observer, FixedTarget
    from astropy.time import Time
    subaru = Observer.at_site("Subaru")
    time_range = Time(["2015-08-01 06:00", "2015-08-01 12:00"])

    # Read in the table of targets
    from astropy.io import ascii
    target_table = ascii.read(target_table_string)

    # Create astroplan.FixedTarget objects for each one in the table
    from astropy.coordinates import SkyCoord
    import astropy.units as u
    targets = [FixedTarget(coord=SkyCoord(ra=ra*u.deg, dec=dec*u.deg), name=name)
               for name, ra, dec in target_table]

    from astroplan import Constraint, is_observable

    class VegaSeparationConstraint(Constraint):
        """
        Constraint the separation from Vega
        """
        def __init__(self, min=None, max=None):
            """
            min : `~astropy.units.Quantity` or `None` (optional)
                Minimum acceptable separation between Vega and target. `None`
                indicates no limit.
            max : `~astropy.units.Quantity` or `None` (optional)
                Minimum acceptable separation between Vega and target. `None`
                indicates no limit.
            """
            self.min = min if min else 0*u.deg
            self.max = max if max else 180*u.deg

        def compute_constraint(self, times, observer, targets):
            vega = SkyCoord(ra=279.23473479*u.deg, dec=38.78368896*u.deg)

            # Calculate separation between target and vega
            # Targets are automatically converted to SkyCoord objects
            # by __call__ before compute_constraint is called.
            vega_separation = vega.separation(targets)

            # Return an array that is True where the target is observable and
            # False where it is not
            return (self.min < vega_separation) & (vega_separation < self.max)

    constraints = [VegaSeparationConstraint(min=5*u.deg, max=30*u.deg)]
    observability = is_observable(constraints, subaru, targets,
                                  time_range=time_range)

    assert all(observability == [False, False, True, False, False, False])
Exemplo n.º 20
0
def test_docs_example():
    # Test the example in astroplan/docs/tutorials/constraints.rst
    target_table_string = """# name ra_degrees dec_degrees
    Polaris 37.95456067 89.26410897
    Vega 279.234734787 38.783688956
    Albireo 292.68033548 27.959680072
    Algol 47.042218553 40.955646675
    Rigel 78.634467067 -8.201638365
    Regulus 152.092962438 11.967208776"""

    from astroplan import Observer, FixedTarget
    from astropy.time import Time
    subaru = Observer.at_site("Subaru")
    time_range = Time(["2015-08-01 06:00", "2015-08-01 12:00"])

    # Read in the table of targets
    from astropy.io import ascii
    target_table = ascii.read(target_table_string)

    # Create astroplan.FixedTarget objects for each one in the table
    from astropy.coordinates import SkyCoord
    import astropy.units as u
    targets = [FixedTarget(coord=SkyCoord(ra=ra*u.deg, dec=dec*u.deg), name=name)
               for name, ra, dec in target_table]

    from astroplan import Constraint, is_observable

    class VegaSeparationConstraint(Constraint):
        """
        Constraint the separation from Vega
        """
        def __init__(self, min=None, max=None):
            """
            min : `~astropy.units.Quantity` or `None` (optional)
                Minimum acceptable separation between Vega and target. `None`
                indicates no limit.
            max : `~astropy.units.Quantity` or `None` (optional)
                Minimum acceptable separation between Vega and target. `None`
                indicates no limit.
            """
            self.min = min if min else 0*u.deg
            self.max = max if max else 180*u.deg

        def compute_constraint(self, times, observer, targets):
            vega = SkyCoord(ra=279.23473479*u.deg, dec=38.78368896*u.deg)

            # Calculate separation between target and vega
            # Targets are automatically converted to SkyCoord objects
            # by __call__ before compute_constraint is called.
            vega_separation = vega.separation(targets)

            # Return an array that is True where the target is observable and
            # False where it is not
            return (self.min < vega_separation) & (vega_separation < self.max)

    constraints = [VegaSeparationConstraint(min=5*u.deg, max=30*u.deg)]
    observability = is_observable(constraints, subaru, targets,
                                  time_range=time_range)

    assert all(observability == [False, False, True, False, False, False])
Exemplo n.º 21
0
def test_months_observable():
    obs = Observer(latitude=0 * u.deg, longitude=0 * u.deg, elevation=0 * u.m)

    coords = [
        SkyCoord(ra=0 * u.hourangle, dec=0 * u.deg),
        SkyCoord(ra=6 * u.hourangle, dec=0 * u.deg),
        SkyCoord(ra=12 * u.hourangle, dec=0 * u.deg),
        SkyCoord(ra=18 * u.hourangle, dec=0 * u.deg)
    ]
    targets = [FixedTarget(coord=coord) for coord in coords]
    constraints = [
        AltitudeConstraint(min=80 * u.deg),
        AtNightConstraint.twilight_astronomical()
    ]
    time_range = Time(['2014-01-01', '2014-12-31'])
    months = months_observable(constraints, obs, targets, time_range)

    should_be = [
        set({7, 8, 9, 10, 11, 12}),
        set({1, 2, 3, 10, 11, 12}),
        set({1, 2, 3, 4, 5, 6}),
        set({4, 5, 6, 7, 8, 9})
    ]

    assert months == should_be
def site_information(UhaveE_ID, longitude, latitude, altitude):
    site_inf = Observer(longitude=longitude * u.deg,
                        latitude=latitude * u.deg,
                        elevation=altitude * u.m,
                        name=UhaveE_ID)
    # u.deg set the unit to degree
    return site_inf
Exemplo n.º 23
0
def main():

    ticid = '268301217'
    ra = '07:45:28.97'
    dec = '-52:22:59.73'

    t0 = 2458860.60021 * u.day  # BJD_TDB
    period = 0.94667643 * u.day

    site = Observer.at_site('Cerro Tololo')
    start_time = Time('2020-10-24 22:00:00')
    end_time = Time('2020-11-06 07:00:00')

    # axvspan windows
    obs_per_night = [(Time('2020-10-{}'.format(str(d).zfill(2)) + ' 06:00:00'),
                      Time('2020-10-{}'.format(str(d).zfill(2)) + ' 10:00:00'))
                     for d in range(24, 32)]
    for d in range(1, 6):
        obs_per_night.append(
            (Time('2020-11-{}'.format(str(d).zfill(2)) + ' 06:00:00'),
             Time('2020-11-{}'.format(str(d).zfill(2)) + ' 10:00:00')))

    plot_quadrature_windows(ra,
                            dec,
                            ticid,
                            t0,
                            period,
                            start_time,
                            end_time,
                            site,
                            obs_per_night=obs_per_night,
                            N_points=500)
Exemplo n.º 24
0
    def astronomical_twilight(self, date_obs,
                              site_longitude=30.335555,
                              site_latitude=36.824166,
                              site_elevation=2500,
                              site_name="tug",
                              time_zone="Europe/Istanbul",
                              which="next"):
        """
        It calculates astronomical twilight.
        @param date_obs
        @type date_obs: date
        @param site_longitude: Site longitude.
        @type site_longitude: float
        @param site_latitude: Site latitude.
        @type site_latitude: float
        @param site_elevation: Site elevation.
        @type site_elevation: float
        @param site_name: Station name: T60|T100|RTT150.
        @type site_name: string
        @param time_zone: Time zone.
        @type time_zone: int
        @param which: Which.
        @type which: string
        @return: tuple
        """

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

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

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

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

        # localized time conversion
        return(tug.astropy_time_to_datetime(mt),
               tug.astropy_time_to_datetime(et))
Exemplo n.º 25
0
def observer(config):
    loc = config['location']
    location = EarthLocation(lon=loc['longitude'],
                             lat=loc['latitude'],
                             height=loc['elevation'])
    return Observer(location=location,
                    name="Test Observer",
                    timezone=loc['timezone'])
Exemplo n.º 26
0
def main():
    #define observer located at ckoirama observatory
    location = EarthLocation.from_geodetic(-69.930544 * u.deg,
                                           -24.089385 * u.deg, 980 * u.m)
    ckoirama = Observer(location=location,
                        name="Ckoirama",
                        timezone="Chile/Continental")
    time = Time('2018-05-06 12:00:00')
Exemplo n.º 27
0
def tonight_set_time(obsnight,coords):

	time = Time(datetime.datetime.now())
	sc = SkyCoord('%s %s'%(coords[0],coords[1]),unit=(u.hourangle,u.deg))

	location = EarthLocation.from_geodetic(
		obsnight.telescope.longitude*u.deg,obsnight.telescope.latitude*u.deg,
		obsnight.telescope.elevation*u.m)
	tel = Observer(location=location, timezone="UTC")

	target_set_time = tel.target_set_time(time,sc,horizon=18*u.deg,which="previous")

	if target_set_time:
		returnendtime = target_set_time.isot.split('T')[-1]
	else: returnendtime = None

	return(returnendtime)
Exemplo n.º 28
0
    def astronomical_twilight(self,
                              date_obs,
                              site_longitude=30.335555,
                              site_latitude=36.824166,
                              site_elevation=2500,
                              site_name="tug",
                              time_zone="Europe/Istanbul",
                              which="next"):
        """
        It calculates astronomical twilight.
        @param date_obs
        @type date_obs: date
        @param site_longitude: Site longitude.
        @type site_longitude: float
        @param site_latitude: Site latitude.
        @type site_latitude: float
        @param site_elevation: Site elevation.
        @type site_elevation: float
        @param site_name: Station name: T60|T100|RTT150.
        @type site_name: string
        @param time_zone: Time zone.
        @type time_zone: int
        @param which: Which.
        @type which: string
        @return: tuple
        """

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

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

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

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

        # localized time conversion
        return (tug.astropy_time_to_datetime(mt),
                tug.astropy_time_to_datetime(et))
Exemplo n.º 29
0
def compute_is_up(name, time):
    '''
    Computes what V<11 objects in a catalog are up right now.

    args:
        name (str): one in: ['messier', 'ngc']
        time (str): in 24hr format, e.g. "2017-04-17 21:00:00"

    returns:
        catalog with is_up calculated, sorted by v_mag.
    '''

    import datetime
    from astropy.time import Time
    from astroplan import FixedTarget
    from astropy.coordinates import SkyCoord
    from astroplan import Observer, FixedTarget, AltitudeConstraint, \
        AtNightConstraint, is_observable, is_always_observable, \
        months_observable

    assert name in ['messier', 'ngc']

    if name == 'messier':
        data_path = '../data/catalogs/messier.csv'
    elif name == 'ngc':
        data_path = '../data/catalogs/ngc.csv'

    df = pd.read_csv(data_path)
    # The search & target creation is slow for >~thousands of FixedTargets. NGC
    # catalog is 13226 objects. Take those with v_mag<11, since from Peyton we
    # likely won't go fainter.
    df = df.sort_values('v_mag')
    df = df[df['v_mag']<11]

    peyton = Observer(longitude=74.65139*u.deg, latitude=40.34661*u.deg,
        elevation=62*u.m, name='Peyton', timezone='US/Eastern')

    if name == 'ngc':
        ras = np.array(df['ra'])*u.hourangle
        decs = np.array(df['dec'])*u.degree
        names = np.array(df['ngc_id'])
    elif name == 'messier':
        ras = np.array(df['ra'])*u.hourangle
        decs = np.array(df['dec'])*u.degree
        names = np.array(df['messier_id'])

    targets = [FixedTarget(SkyCoord(ra=r, dec=d), name=n) for r, d, n in
            tuple(zip(ras, decs, names))]

    constraints = [AltitudeConstraint(10*u.deg, 82*u.deg),
            AtNightConstraint(max_solar_altitude=-3.*u.deg)]

    t_obs = Time(time)
    is_up = is_observable(constraints, peyton, targets, times=t_obs)

    df['is_up'] = is_up

    return df
Exemplo n.º 30
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
Exemplo n.º 31
0
def goto_north():
    """Observer for GOTO-North on La Palma."""
    lapalma = EarthLocation(lon=-17.8947 * u.deg,
                            lat=28.7636 * u.deg,
                            height=2396 * u.m)
    telescope = Observer(name='goto_north',
                         location=lapalma,
                         timezone='Atlantic/Canary')
    return telescope
Exemplo n.º 32
0
def goto_south():
    """Observer for a (theoretical) GOTO-South in Melbourne."""
    clayton = EarthLocation(lon=145.131389 * u.deg,
                            lat=-37.910556 * u.deg,
                            height=50 * u.m)
    telescope = Observer(name='goto_south',
                         location=clayton,
                         timezone='Australia/Melbourne')
    return telescope
Exemplo n.º 33
0
def _get_observer_tzinfo(session_plan):
    loc_name, latitude, longitude, elevation = _get_location_info_from_session_plan(
        session_plan)
    loc_coords = EarthLocation.from_geodetic(
        longitude * u.deg, latitude * u.deg,
        elevation * u.m if elevation else 0)
    tz_info = _get_session_plan_tzinfo(session_plan)
    observer = Observer(name=loc_name, location=loc_coords, timezone=tz_info)
    return observer, tz_info
Exemplo n.º 34
0
    def _setup_location(self):
        """
        Sets up the site and location details for the observatory

        Note:
            These items are read from the 'site' config directive and include:
                * name
                * latitude
                * longitude
                * timezone
                * presseure
                * elevation
                * horizon

        """
        self.logger.debug('Setting up site details of observatory')

        try:
            config_site = self.config.get('location')

            name = config_site.get('name', 'Nameless Location')

            latitude = config_site.get('latitude')
            longitude = config_site.get('longitude')

            timezone = config_site.get('timezone')
            utc_offset = config_site.get('utc_offset')

            pressure = config_site.get('pressure', 0.680) * u.bar
            elevation = config_site.get('elevation', 0 * u.meter)
            horizon = config_site.get('horizon', 30 * u.degree)
            twilight_horizon = config_site.get('twilight_horizon',
                                               -18 * u.degree)

            self.location = {
                'name': name,
                'latitude': latitude,
                'longitude': longitude,
                'elevation': elevation,
                'timezone': timezone,
                'utc_offset': utc_offset,
                'pressure': pressure,
                'horizon': horizon,
                'twilight_horizon': twilight_horizon,
            }
            self.logger.debug("Location: {}".format(self.location))

            # Create an EarthLocation for the mount
            self.earth_location = EarthLocation(lat=latitude,
                                                lon=longitude,
                                                height=elevation)
            self.observer = Observer(location=self.earth_location,
                                     name=name,
                                     timezone=timezone)
        except Exception:
            raise error.PanError(msg='Bad site information')
Exemplo n.º 35
0
def test_caches_shapes():
    times = Time([2457884.43350526, 2457884.5029497, 2457884.57239415], format='jd')
    m31 = SkyCoord(10.6847929*u.deg, 41.269065*u.deg)
    ippeg = SkyCoord(350.785625*u.deg, 18.416472*u.deg)
    htcas = SkyCoord(17.5566667*u.deg, 60.0752778*u.deg)
    targets = get_skycoord([m31, ippeg, htcas])
    observer = Observer.at_site('lapalma')
    ac = AltitudeConstraint(min=30*u.deg)
    assert ac(observer, targets, times, grid_times_targets=True).shape == (3, 3)
    assert ac(observer, targets, times, grid_times_targets=False).shape == (3,)
Exemplo n.º 36
0
def test_regression_shapes(constraint):
    times = Time(["2015-08-28 03:30", "2015-09-05 10:30", "2015-09-15 18:35"])
    targets = get_skycoord([FixedTarget(SkyCoord(350.7*u.deg, 18.4*u.deg)),
                           FixedTarget(SkyCoord(260.7*u.deg, 22.4*u.deg))])
    lapalma = Observer.at_site('lapalma')

    assert constraint(lapalma, targets[:, np.newaxis], times).shape == (2, 3)
    assert constraint(lapalma, targets[0], times).shape == (3,)
    assert constraint(lapalma, targets[0], times[0]).shape == ()
    assert constraint(lapalma, targets, times[0]).shape == (2,)
    with pytest.raises(ValueError):
        constraint(lapalma, targets, times)
Exemplo n.º 37
0
def test_regression_airmass_141():
    subaru = Observer.at_site("Subaru")
    time = Time("2001-1-1 12:00")

    coord = SkyCoord(ra=16 * u.hour, dec=20 * u.deg)

    assert subaru.altaz(time, coord).alt < 0 * u.deg
    # ok, it's below the horizon, so it *definitely* should fail an airmass
    # constraint of being above 2.  So both of these should give False:
    consmax = AirmassConstraint(2)
    consminmax = AirmassConstraint(2, 1)

    assert not consminmax(subaru, [coord], [time]).ravel()[0]
    # prior to 141 the above works, but the below FAILS
    assert not consmax(subaru, [coord], [time]).ravel()[0]
Exemplo n.º 38
0
def test_eclipses():
    subaru = Observer.at_site("Subaru")

    epoch = Time('2016-01-01')
    period = 3 * u.day
    duration = 1 * u.hour
    eclipsing_system = EclipsingSystem(primary_eclipse_time=epoch, orbital_period=period,
                                       duration=duration, name='test system')
    pec = PrimaryEclipseConstraint(eclipsing_system)
    times = Time(['2016-01-01 00:00', '2016-01-01 03:00', '2016-01-02 12:00'])
    assert np.all(np.array([True, False, False]) == pec(subaru, None, times))

    sec = SecondaryEclipseConstraint(eclipsing_system)
    times = Time(['2016-01-01 00:00', '2016-01-01 03:00', '2016-01-02 12:00'])
    assert np.all(np.array([False, False, True]) == sec(subaru, None, times))

    pc = PhaseConstraint(eclipsing_system, min=0.2, max=0.5)
    times = Time(['2016-01-01 00:00', '2016-01-02 12:00', '2016-01-02 14:00'])
    assert np.all(np.array([False, True, False]) == pc(subaru, None, times))
Exemplo n.º 39
0
    def set_obs_time(self, coords, site, date):
        """Choose times to begin and end observing the PIC between its rise and set.

        :param coords: coordinates of the PIC object from SkyCoord
        :param site: name of the site the unit is at, from astroplan
        :param date: the date of the observation
        :return: randomized start and end time of observation
        """
        loc = Observer.at_site(site)

        # Use astroplan to get rise and set of star, and get reasonable random
        # obs_time and duration
        rise = loc.target_rise_time(date, coords, which='next')
        rise_time = datetime.strptime(rise.isot, "%Y-%m-%dT%H:%M:%S.%f")
        set = loc.target_set_time(rise_time, coords, which='next')
        set_time = datetime.strptime(set.isot, "%Y-%m-%dT%H:%M:%S.%f")
        start_time = self.random_time(rise_time, set_time)
        seq_duration = self.random_duration(start_time, set_time)
        end_time = start_time + seq_duration
        return start_time, end_time
Exemplo n.º 40
0
def test_event_observable():

    epoch = Time(2452826.628514, format='jd')
    period = 3.52474859 * u.day
    duration = 0.1277 * u.day

    hd209458 = EclipsingSystem(primary_eclipse_time=epoch, orbital_period=period, duration=duration,
                               name='HD 209458 b')
    observing_time = Time('2017-09-15 10:20')

    apo = Observer.at_site('APO')

    target = FixedTarget.from_name("HD 209458")
    n_transits = 100  # This is the roughly number of transits per year
    ing_egr = hd209458.next_primary_ingress_egress_time(observing_time,
                                                        n_eclipses=n_transits)
    constraints = [AltitudeConstraint(min=0*u.deg), AtNightConstraint()]
    observable = is_event_observable(constraints, apo, target,
                                     times_ingress_egress=ing_egr)

    # This answer was validated against the Czech Exoplanet Transit Database
    # transit prediction service, at:
    # http://var2.astro.cz/ETD/predict_detail.php?delka=254.1797222222222&submit=submit&sirka=32.780277777777776&STARNAME=HD209458&PLANET=b
    # There is some disagreement, as the ETD considers some transits which begin
    # before sunset or after sunrise to be observable.
    cetd_answer = [[False, False, False, True, False, True, False, True, False,
                    True, False, True, False, False, False, False, False, False,
                    False, False, False, False, True, False, True, False, False,
                    False, False, False, False, False, False, False, False, False,
                    False, False, False, False, False, False, False, False, False,
                    False, False, False, False, False, False, False, False, False,
                    False, False, False, True, False, False, False, False, False,
                    False, False, False, False, False, False, False, False, False,
                    True, False, True, False, False, False, False, False, False,
                    False, False, False, False, False, False, True, False, True,
                    False, True, False, True, False, True, False, True, False,
                    False]]

    assert np.all(observable == np.array(cetd_answer))
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
Exemplo n.º 42
0
def test_docs_example():
    # Test the example in astroplan/docs/tutorials/constraints.rst
    target_table_string = """# name ra_degrees dec_degrees
    Polaris 37.95456067 89.26410897
    Vega 279.234734787 38.783688956
    Albireo 292.68033548 27.959680072
    Algol 47.042218553 40.955646675
    Rigel 78.634467067 -8.201638365
    Regulus 152.092962438 11.967208776"""

    from astroplan import Observer, FixedTarget
    from astropy.time import Time

    subaru = Observer.at_site("Subaru")
    time_range = Time(["2015-08-01 06:00", "2015-08-01 12:00"])

    # Read in the table of targets
    from astropy.io import ascii

    target_table = ascii.read(target_table_string)

    # Create astroplan.FixedTarget objects for each one in the table
    from astropy.coordinates import SkyCoord
    import astropy.units as u

    targets = [FixedTarget(coord=SkyCoord(ra=ra * u.deg, dec=dec * u.deg), name=name) for name, ra, dec in target_table]

    from astroplan import Constraint, is_observable
    from astropy.coordinates import Angle

    class VegaSeparationConstraint(Constraint):
        """
        Constraint the separation from Vega
        """

        def __init__(self, min=None, max=None):
            """
            min : `~astropy.units.Quantity` or `None` (optional)
                Minimum acceptable separation between Vega and target. `None`
                indicates no limit.
            max : `~astropy.units.Quantity` or `None` (optional)
                Minimum acceptable separation between Vega and target. `None`
                indicates no limit.
            """
            self.min = min
            self.max = max

        def compute_constraint(self, times, observer, targets):

            # Vega's coordinate must be non-scalar for the dimensions
            # to work out properly when combined with other constraints which
            # test multiple times
            vega = SkyCoord(ra=[279.23473479] * u.deg, dec=[38.78368896] * u.deg)

            # Calculate separation between target and vega
            vega_separation = Angle([vega.separation(target.coord) for target in targets])

            # If a maximum is specified but no minimum
            if self.min is None and self.max is not None:
                mask = vega_separation < self.max

            # If a minimum is specified but no maximum
            elif self.max is None and self.min is not None:
                mask = self.min < vega_separation

            # If both a minimum and a maximum are specified
            elif self.min is not None and self.max is not None:
                mask = (self.min < vega_separation) & (vega_separation < self.max)

            # Otherwise, raise an error
            else:
                raise ValueError("No max and/or min specified in " "VegaSeparationConstraint.")

            # Return an array that is True where the target is observable and
            # False where it is not
            return mask

    constraints = [VegaSeparationConstraint(min=5 * u.deg, max=30 * u.deg)]
    observability = is_observable(constraints, subaru, targets, time_range=time_range)

    assert all(observability == [False, False, True, False, False, False])
def main():

    ##-------------------------------------------------------------------------
    ## Parse Command Line Arguments
    ##-------------------------------------------------------------------------
    ## create a parser object for understanding command-line arguments
    parser = argparse.ArgumentParser(
             description="Program description.")
    ## add flags
    ## add arguments
    parser.add_argument("-y", "--year",
        type=int, dest="year",
        default=-1,
        help="The calendar year to analyze")
    parser.add_argument("-s", "--site",
        type=str, dest="site",
        default='Keck Observatory',
        help="Site name to use")
    parser.add_argument("-z", "--timezone",
        type=str, dest="timezone",
        default='US/Hawaii',
        help='pytz timezone name')
    parser.add_argument("-d", "--dark_time",
        type=float, dest="dark_time",
        default=2,
        help='Minimum dark time required (hours)')
    parser.add_argument("-w", "--wait_time",
        type=float, dest="wait_time",
        default=2.5,
        help='Maximum time after dusk to wait for moon set (hours)')

    args = parser.parse_args()

    if args.year == -1:
        args.year = dt.now().year

    ##-------------------------------------------------------------------------
    ## 
    ##-------------------------------------------------------------------------
    loc = EarthLocation.of_site(args.site)
    obs = Observer.at_site(args.site)
    utc = pytz.timezone('UTC')
    localtz = pytz.timezone(args.timezone)
#     hour = tdelta(seconds=60.*60.*1.)

#     pyephem_site = ephem.Observer()
#     pyephem_site.lat = str(loc.lat.to(u.degree).value)
#     pyephem_site.lon = str(loc.lon.to(u.deg).value)
#     pyephem_site.elevation = loc.height.to(u.m).value
#     pyephem_moon = ephem.Moon()

    oneday = TimeDelta(60.*60.*24., format='sec')
    date_iso_string = '{:4d}-01-01T00:00:00'.format(args.year)
    start_date = Time(date_iso_string, format='isot', scale='utc', location=loc)
    sunset = obs.sun_set_time(start_date, which='next')

    ical_file = 'DarkMoonCalendar_{:4d}.ics'.format(args.year)
    if os.path.exists(ical_file): os.remove(ical_file)
    with open(ical_file, 'w') as FO:
        FO.write('BEGIN:VCALENDAR\n'.format())
        FO.write('PRODID:-//hacksw/handcal//NONSGML v1.0//EN\n'.format())

        while sunset < start_date + 365*oneday:
            search_around = sunset + oneday
            sunset = analyze_day(search_around, obs, FO, localtz, args,
                                 verbose=True)
        FO.write('END:VCALENDAR\n')
Exemplo n.º 44
0
from PyQt5 import QtGui, QtCore, QtWidgets

from telescope import Telescope
from allsky import AllSky
import gui


# parse configuration file
config = ConfigObj("config.ini")
location = config["LOCATION"]
objects = config["OBJECTS"]

# set new Observer object from config file
obsLocation = EarthLocation(location["LONGITUDE"], location["LATITUDE"],
                            float(location["ELEVATION"]))
add_site(location["SITE_NAME"], obsLocation)

# add objects to a dictionary of `astroplan.FixedTarget`s
fixed_targets = {}
for key in objects:
    coordinates = SkyCoord(objects[key]["RA"], objects[key]["DEC"])
    fixed_targets[key] = FixedTarget(name=key, coord=coordinates)


skymap = AllSky(objects=fixed_targets)
telescope = Telescope(Observer.at_site(location["SITE_NAME"]))
gui.run(telescope, skymap)

#fig = skymap.draw(telescope.Observer)
#fig.savefig("test.png")
Exemplo n.º 45
0
from astroplan import Observer
import astropy.units as u
from astropy.coordinates import EarthLocation
import pytz

# Define the observer with an instance of astropy.coordinates.EarthLocation,
# also use pytz.timezone() argument directly as `timezone` keyword's input
longitude = '-155d28m48.900s'
latitude = '+19d49m42.600s'
elevation = 4163 * u.m
location = EarthLocation.from_geodetic(longitude, latitude, elevation)

obs = Observer(name='Subaru Telescope',
               location=location,
               pressure=0.615 * u.bar,
               relative_humidity=0.11,
               temperature=0 * u.deg_C,
               timezone=pytz.timezone('US/Hawaii'),
               description="Subaru Telescope on Mauna Kea, Hawaii")

# It would also be desirable to be able to have a small database of
# common telescopes.  Maybe this can at first simply take the form of
# a python module:
from astroplan import sites

obs = sites.Keck1

# Environmental conditions should be updatable.
obs.pressure = 0.600 * u.bar
obs.relative_humidity = 0.2
obs.temperature = 10 * u.deg_C
Exemplo n.º 46
0
def get_altaz(obj_name, ipt_lon, ipt_lat, t=None):

    # for html scrapping
    # from lxml import html
    # from bs4 import BeautifulSoup
    # to place requests
    import requests
    import json

    import astropy.units as u
    from astropy.time import Time
    from astropy.coordinates import SkyCoord, EarthLocation, Angle, Latitude, Longitude

    from astroplan import FixedTarget, Observer
    from astroquery.simbad import Simbad as simbad

    import ephem

    if t == None:
        t = Time.now()

    ## Set up the observer
    obs_el = 100 * u.m
    loc = EarthLocation.from_geodetic(ipt_lon, ipt_lat, obs_el)
    my_site = Observer(name="My_Site", location=loc)

    obs_lat = my_site.location.latitude
    obs_lon = my_site.location.longitude

    # observer for pyephem
    ephem_site = ephem.Observer()
    ephem_site.lon, ephem_site.lat = str(obs_lon.deg), str(obs_lat.deg)
    ephem_site.date = ephem.Date(str(t.decimalyear))

    ##Get the object
    # Check for planet-hood.
    # if planet: resolve the individual planet with pyephem.
    # else if satellite or ISS (or TIANGONG) scrap the appropriate websites and return info
    # else query simbad

    ############
    # Put in an auto-correct for kids
    ############
    # just make it lower case for now

    obj_name = obj_name.lower()

    if obj_name in ["sun", "mercury", "venus", "moon", "mars", "jupiter", "saturn", "uranus", "neptune", "pluto"]:

        if obj_name == "sun":
            my_planet = ephem.Sun()
        elif obj_name == "mercury":
            my_planet = ephem.Mercury()
        elif obj_name == "venus":
            my_planet = ephem.Venus()
        elif obj_name == "moon":
            my_planet = ephem.Moon()
        elif obj_name == "mars":
            my_planet = ephem.Mars()
        elif obj_name == "jupiter":
            my_planet = ephem.Jupiter()
        elif obj_name == "saturn":
            my_planet = ephem.Saturn()
        elif obj_name == "uranus":
            my_planet = ephem.Uranus()
        elif obj_name == "neptune":
            my_planet = ephem.Neptune()
        elif obj_name == "pluto":
            my_planet = ephem.Pluto()

        my_planet.compute(ephem_site)
        az = my_planet.az * 180 / 3.1415926535
        alt = my_planet.alt * 180 / 3.1415926535
        # here coded for just ISS but for all satellites we should have similar setups, probably poll site
    elif obj_name == "iss":
        # try a request for the iss from the open notify site. Gives current json data
        page = requests.get("http://api.open-notify.org/iss-now.json")
        issdata = page.json()
        tstamp = issdata["timestamp"]
        isslat = issdata["iss_position"]["latitude"]
        isslon = issdata["iss_position"]["longitude"]
        # there are issues with just this amount of data as you do not know the altitude of the object
        # here we fix it to 350 km
        issheight = 350 * u.km
        isslat = Latitude(isslat, unit=u.deg)
        isslon = Longitude(isslon, unit=u.deg)

        # there are issues however as this data does NOT contain the altitude so lets try scrapping the html
        # the issue with fullissdata is that it contains information in NASA style units (M50 Cartesian & M50 Keplerian)
        page = requests.get(
            "http://spaceflight.nasa.gov/realdata/sightings/SSapplications/Post/JavaSSOP/orbit/ISS/SVPOST.html"
        )
        # fullissdata=html.fromstring(page.text)

        # there are also other satellites liseted in, issue is parsing the information as I do not know what each field contains
        # the issue here is that all sat data contains unknown units and uncertain which entries contain useful information
        page = requests.get("http://www.celestrak.com/NORAD/elements/stations.txt")
        allsatdata = page.text

        c = SkyCoord(isslon, isslat, issheight)
        my_target = FixedTarget(name="ISS", coord=c)
        az = my_site.altaz(t, my_target).az.deg
        alt = my_site.altaz(t, my_target).alt.deg
    else:
        try:
            q = simbad.query_object(obj_name)
            c = SkyCoord(q["RA"][0], q["DEC"][0], unit=(u.hourangle, u.deg))
            my_star = FixedTarget(name="my_star", coord=c)

            az = my_site.altaz(t, my_star).az.deg
            alt = my_site.altaz(t, my_star).alt.deg
        except:
            print("Couldn't find Object in Database")
            alt, az = 0, 0

    return alt, az
Exemplo n.º 47
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)
Exemplo n.º 48
0
environmental attributes thereof that affect observation calculations
at that location.
"""
# Define an observer by full specification.
# Latitude/Longitude take input as strings or quantities,
# elevation, pressure, temperature must be quantities.
# Accept `timezone` from pytz
from astroplan import Observer
import astropy.units as u
import pytz

obs = Observer(name='Subaru Telescope',
               longitude='-155:28:48.900',
               latitude='+19:49:42.600',
               elevation=4163 * u.meter,
               pressure=0.615 * u.bar,
               relative_humidity=0.11,
               temperature=0 * u.deg_C,
               timezone=pytz.timezone('US/Hawaii'),
               description="Subaru Telescope on Mauna Kea, Hawaii")

# Define the same observer with an instance of astropy.coordinates.EarthLocation,
# also use pytz.timezone() argument directly as `timezone` keyword's input
from astropy.coordinates import EarthLocation
obs = Observer(name='Subaru',
               location=EarthLocation(lon='-155:28:48.900',
                                      lat='+19:49:42.600'),
               elevation=4163 * u.meter,
               pressure=0.615 * u.bar,
               relative_humidity=0.11,
               temperature=0 * u.deg_C,