Esempio n. 1
0
 def __call__(self, time, time_grid_resolution=10 * u.minute):
     if self.name == 'Sun':
         return numpy.nan
     t1 = time
     t2 = time + 1 * u.day
     if not self.isfixed:
         self.target = target_by_name(self.name, time)
     ot = astroplan.observability_table(
         self.constraints,
         self.observer, [self.target],
         time_range=astropy.time.Time([t1, t2]),
         time_grid_resolution=time_grid_resolution)
     otime = ot[0]['fraction of time observable'] * u.day
     return otime.to(u.hour).value
Esempio n. 2
0
def most_obs(n):
    output = "The " + str(
        n
    ) + " most (or equally) observable Radio Loud Galaxies in the 2nd half of April: \n"
    for i in range(0, n):
        output += str(i + 1) + ". " + obs_targs[
            len(obs_targs) - (1 + i)][0] + " is observable for " + str(
                obs_targs[len(obs_targs) -
                          (1 + i)][1]) + " of the second half of April. \n"
        #those_ten.append(total_save[len(obs_targs)-(1+i)])
        newFixedTargs.append(
            FixedTarget(coord=SkyCoord(ra=those_ten[i][0],
                                       dec=those_ten[i][1],
                                       unit=(u.hourangle, u.deg))))
    newOutput = observability_table(
        cons,
        kitt,
        newFixedTargs,
        time_range=Time(["2018-05-15 00:01", "2018-05-31 23:59"]))
    return [output, newOutput]
Esempio n. 3
0
def get_observability_fraction(name="WASP 4", site='keck', ra=None, dec=None,
                               start_time=Time('2019-09-13 20:00:00'),
                               end_time=Time('2020-07-31 20:00:00')):

    if isinstance(name,str) and ra is None and dec is None:
        target = FixedTarget.from_name(name)
    elif isinstance(ra,float) and isinstance(dec,float):
        target_coord = SkyCoord(ra=ra*u.deg, dec=dec*u.deg)
        target = FixedTarget(coord=target_coord, name=name)
    else:
        raise NotImplementedError('failed to make target')

    observer = Observer.at_site(site)

    constraints = [AltitudeConstraint(min=20*u.deg, max=85*u.deg),
                   AirmassConstraint(3),
                   AtNightConstraint.twilight_civil()]

    # over every day between start and end time, check if the observing
    # constraints are meetable.
    days = Time(
        np.arange(start_time.decimalyear, end_time.decimalyear,
                  1/(365.25)),
        format='decimalyear'
    )

    frac, ever_observable = [], []

    for day in days:

        table = observability_table(constraints, observer, [target],
                                    time_range=day)
        frac.append(float(table['fraction of time observable']))
        ever_observable.append(bool(table['ever observable']))

    ever_observable = np.array(ever_observable)
    frac = np.array(frac)

    return frac, ever_observable, days
Esempio n. 4
0
    if np.abs(period - 1.0) < 0.01:
        continue

    if dec_hex[0] == "-":
        objname = "ZTFJ%s%s" % (ra_hex_nodelim[:4], dec_hex_nodelim[:5])
    else:
        objname = "ZTFJ%s%s" % (ra_hex_nodelim[:4], dec_hex_nodelim[:4])

    if objname in observed: continue

    coord = SkyCoord(ra=ra * u.deg, dec=dec * u.deg)
    tar = FixedTarget(coord=coord, name=objname)

    if opts.doCheckObservable:
        table = observability_table(global_constraints,
                                    kp, [tar],
                                    time_range=[tstart, tend])
        idx = np.where(table["ever observable"])[0]
        if len(idx) == 0:
            continue

    ps1 = ps1_query(ra, dec, 5 / 3600.0)
    if not ps1:
        gmag, rmag, imag, zmag, ymag = np.nan, np.nan, np.nan, np.nan, np.nan
    else:
        gmag, rmag, imag, zmag, ymag = ps1["gmag"], ps1["rmag"], ps1[
            "imag"], ps1["zmag"], ps1["ymag"]
        ps1_mag = ps1[str(ps1_filter)]
        if opts.doMagnitudeCut:
            if gmag < opts.magnitude:
                continue
def make_obs_table(obs_info, source_list, save=True, min_uptime=10):

    tab = Table.read(source_list, format="ascii.csv")
    targets = [
        FixedTarget(coord=SkyCoord(ra=ra, dec=dec, unit=(u.hourangle, u.deg)),
                    name=source) for source, ra, dec, _ in tab
    ]

    # Some arecibo specific settings
    arecibo_site = E.from_geocentric(x=2390490.0,
                                     y=-5564764.0,
                                     z=1994727.0,
                                     unit=u.meter)
    arecibo = Observer(location=arecibo_site, name="AO")
    constraints = [
        AltitudeConstraint((90 - 19.7) * u.deg, (90 - 1.06) * u.deg)
    ]
    min_alt = (90 - 19.7) * u.deg
    max_alt = (90 - 1.06) * u.deg
    utc_offset = 4 * u.hour
    ast_to_utc_offset = TimezoneInfo(utc_offset=utc_offset)

    months = [
        'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
        'Nov', 'Dec'
    ]

    tstarts = []
    tends = []
    for index, row in obs_info.iterrows():
        obs_month = row['Month']
        for i, month in enumerate(months):
            if month == obs_month:
                break
        i = i + 1
        if row['End_time(AST)'] == '24:00':
            row['End_time(AST)'] = '23:59'
        tstarts.append(
            f"{row['Year']}-{i:02d}-{row['Start_date']} {row['Start_time(AST)']}"
        )
        tends.append(
            f"{row['Year']}-{i:02d}-{row['End_date']} {row['End_time(AST)']}")

    ots = []
    for st, et in zip(tstarts, tends):

        #setting up for altitude constraints
        tstart_obs = Time(st) + utc_offset
        tobs_len = (Time(et) - Time(st)).sec / (60 * 60)  #hours
        delta_t = np.linspace(0, tobs_len, 100) * u.hour
        frame_obs = AltAz(obstime=tstart_obs + delta_t, location=arecibo_site)

        #setting up for astroplan observability table
        st_utc = str(Time(st).to_datetime(timezone=ast_to_utc_offset))[:-6]
        et_utc = str(Time(et).to_datetime(timezone=ast_to_utc_offset))[:-6]

        time_range = Time([st_utc, et_utc], scale='utc')

        print(f'Making observability table for {st}')
        ot = observability_table(constraints,
                                 arecibo,
                                 targets,
                                 times=time_grid_from_range(
                                     time_range, 5 * u.min)).to_pandas()

        ot['ever obs'] = ot['ever observable']

        ot = ot.drop([
            'fraction of time observable', 'ever observable',
            'always observable'
        ],
                     axis=1)
        ot_obs = ot[ot['ever obs']]

        ra = []
        dec = []
        set_time = []
        up_time = []
        rise_time = []
        tstart_observable = []
        tend_observable = []

        print(f'Processing observability table for {st}')
        for i, row in ot_obs.iterrows():
            ra.append(targets[i].ra.deg)
            dec.append(targets[i].dec.deg)

            # manual altitude constraints
            target = SkyCoord(ra=targets[i].ra, dec=targets[i].dec)
            frame_obs_altaz = target.transform_to(frame_obs)

            times_observable = tstart_obs + delta_t[
                (frame_obs_altaz.alt > min_alt)
                & (frame_obs_altaz.alt < max_alt)]

            tstart_observable.append(times_observable.min() - utc_offset)

            if Time(times_observable.max()) < Time(et_utc):
                tend_observable.append(times_observable.max() - utc_offset)
                up_time.append((Time(times_observable.max()) -
                                Time(times_observable.min())).sec / 60)
            else:
                tend_observable.append(Time(et_utc) - utc_offset)
                up_time.append(
                    (Time(et_utc) - Time(times_observable.min())).sec / 60)

        ot_obs['RA'] = ra
        ot_obs['DEC'] = dec
        ot_obs['uptime (min)'] = up_time

        ot_obs['tstart_obs (AST)'] = tstart_observable
        ot_obs['tend_obs (AST)'] = tend_observable

        ot_obs = ot_obs[ot_obs['uptime (min)'] > min_uptime]
        ot_obs = ot_obs.drop(['ever obs'], axis=1)
        ots.append(ot_obs)

        if save:
            fname = str(Time(st_utc) - utc_offset)
            f = open(fname.replace(' ', '_') + '.tab', 'w')
            f.write(
                f'Observations from {str(Time(st_utc) - utc_offset)} to {str(Time(et_utc) - utc_offset)}\n'
            )
            f.write(f'Length of observations: {tobs_len:.2f}hr \n')
            f.write(
                tabulate(ot_obs,
                         headers='keys',
                         tablefmt='psql',
                         showindex="never"))
            f.close()
Esempio n. 6
0
def vis(date, objects, obj_tab):

    #This tool is designed for the Magellan Telescope @ Las Camapanas Observatory, in Chile
    las = Observer.at_site('LCO')
    #both las and los are the locations of MagAO, but one is used for the plot and the other for the time
    lco = EarthLocation.of_site('Las Campanas Observatory')

    userEntered_list = list(objects.split(","))
    target_list = userEntered_list

    targets = []
    for i in range(1, len(obj_tab)):
        ra = (obj_tab.iloc[i, 2])[1:] + ' hours'
        dec = (obj_tab.iloc[i, 3])[1:] + ' degrees'
        print(ra + ',' + dec)
        targets.append(
            FixedTarget(coord=SkyCoord(ra=ra, dec=dec),
                        name=target_list[i - 1]))

    constraints = [
        AltitudeConstraint(10 * u.deg, 80 * u.deg),
        AirmassConstraint(5),
        AtNightConstraint.twilight_civil()
    ]

    start_time = las.sun_set_time(Time(date), which='nearest')
    end_time = las.sun_rise_time(Time(date), which='nearest')
    date = start_time.iso[:10] + ' to ' + end_time.iso[:10]

    time_range = Time([start_time, end_time])

    # In[ ]:

    delta_t = end_time - start_time
    observe_time = start_time + delta_t * np.linspace(0, 1, 75)

    # In[ ]:

    # Are targets *ever* observable in the time range?
    ever_observable = is_observable(constraints,
                                    las,
                                    targets,
                                    time_range=time_range)

    # Are targets *always* observable in the time range?
    always_observable = is_always_observable(constraints,
                                             las,
                                             targets,
                                             time_range=time_range)

    # During what months are the targets ever observable?
    best_months = months_observable(constraints, las, targets)

    # In[ ]:

    table = observability_table(constraints,
                                las,
                                targets,
                                time_range=time_range)
    print(table)

    table = table.to_pandas()

    np.savetxt(
        'static/data/visibility.txt',
        table,
        fmt="%-30s",
        header=
        'Target name                  ever observable                always observable              fraction of time observable'
    )
Esempio n. 7
0
                                   dec=(t[i]['dec']),
                                   unit=(u.hourangle, u.deg)),
                    name=t[i]['alt_name'] + " [" + t[i]['iau_name'] + ", " +
                    t[i]['ra'] + ", " + t[i]['dec'] + "]"))
    # Accounting for the fact that ra is in [hour min sec] and dec is in [deg arcmin arcsec]
    # the "name" attribute is all of the information just smashed together and I know it's unclean, please don't judge me

    # print((targs[len(targs)-1].name)) # This was just to check where errors occurred

time_range = Time(["2018-04-15 00:01", "2018-04-30 23:59"])
# This just takes the whole swath of time, not refining it or anything

cons = [AirmassConstraint(2), AtNightConstraint.twilight_astronomical()]
# don't use civil twilight because astronomers aren't civil

obs_tab = observability_table(cons, kitt, targs, time_range=time_range)
# print(obs_tab)

obs_targs = []
total_save = []
# total_save is to keep all the data, not just some of it

for i in range(0, len(obs_tab)):
    if obs_tab[i]['ever observable']:
        obs_targs.append([
            obs_tab[i]['target name'],
            obs_tab[i]['fraction of time observable']
        ])
        total_save.append(obs_tab[i])

# if you're sorting it anyway below, there's no reason for the loop above
Esempio n. 8
0
def plot_observability(candidates, constraints, observer, earliestObs,
                       latestObs, timeRes=24*u.hour, timeSubRes=.2*u.hour,
                       fig=None, ax=None, **kwargs):
    """ Visualize long-term observability of a set of targets.

    Parameters
    ----------
    candidates : pandas DataFrame
        Table containing candidates. Must contain a column "Teff".
    constraints : list
        list of constraints
    observer : astroplan Observer object
        e.g. Calar Alto Observatory, Spain
    earliestObs : Time object
        Earliest time of observation
    latestObs : Time object
        Latest time of observation
    timeRes : quantity
        time-resolution of the resulting plot, should be greater than 24h
    timeSubRes : quantity
        fine resolution used for computation of observable time fractions at
        each resolved time in the plot. Has to be (more than an order of
        magnitude) smaller than 'timeRes' for reasonable results.
    fig : matplotlib figure object, optional
        figure to plot on
    ax : matplotlib axis object, optional
        axis to plot on
    **kwargs : keyword arguments to pass to matplotlib's 'imshow'

    Returns
    -------
    fig : matplotlib figure
        figure containing the plot
    ax : matplotlib axis
        axis containing the plot
    """

    # prepare the grid
    rough_grid = time_grid_from_range([earliestObs, latestObs],
                                     time_resolution=timeRes)
    observability_grid = np.zeros((len(candidates), len(rough_grid) - 1))
    for i, t in enumerate(rough_grid[:-1]):
        obsTable = observability_table(constraints, observer, candidates,
                                       time_grid_from_range([rough_grid[i],
                                       rough_grid[i+1]],
                                     time_resolution=timeSubRes))
        hoursObservable = obsTable['fraction of time observable']*24*u.hour
        observability_grid[:,i] = hoursObservable

    # now for the actual plot
    if ax == None:
        fig, ax = plt.subplots()
    dates = rough_grid.plot_date
    extent = [dates[0], dates[-1], -.5, len(candidates) -.5]
    im = ax.imshow(observability_grid, cmap='inferno', aspect='auto',
                   extent=extent, **kwargs)

    # get date ticks right
    ax.xaxis_date()
    date_format = mdates.DateFormatter('%b \'%y')
    ax.xaxis.set_major_formatter(date_format)
    ax.tick_params(rotation=45, axis='x', which='both', length=3, direction='out',
                   pad=2)
    for tick in ax.xaxis.get_major_ticks():
        tick.label1.set_horizontalalignment('left')

    # some eyecandy
    ax.set_yticks(range(len(candidates)))
    ax.set_yticklabels([c.name for c in candidates])
    ax.set_xlabel('Date', labelpad=9)
    ax.set_ylabel('TOI')
    ax.grid(False)
    fig.colorbar(im).set_label('Hours Observable per Night', labelpad=15)

    return fig, ax
Esempio n. 9
0
    }

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

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

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

            object_inds_to_observe = np.random.choice(
                np.argwhere(mask_targets_visible_2hrs)[:, 0],
                size=n_objects_per_night)

            target_inds_observed.update(object_inds_to_observe)

            # Split the night evenly into N chunks
            try:
                split_times = np.split(times, n_objects_per_night)
Esempio n. 10
0
CepheusA 344.07913 62.031778
NGC7129 325.77663 66.115386
IRAS20050+2720 301.77718 27.481741"""
# Read in the table of targets
# NGC2264 100.29251 9.4925956
#NGC2071 86.770544 0.36287845
#NGC1333 52.292875 31.365424
#Ophiuchus 246.78931 -24.621749

from astropy.io import ascii
target_table = ascii.read(target_table_string)
targets = [FixedTarget(coord=SkyCoord(ra=ra*u.deg,dec=dec*u.deg),name=name) for name,ra,dec in target_table]

constraints = [AltitudeConstraint(15*u.deg,75*u.deg)]#[AltitudeConstraint(20*u.deg,75*u.deg),AtNightConstraint.twilight_civil()]

tab = observability_table(constraints,observer,targets,time_range=time_range)

print tab

fig= plt.figure(figsize=(textwidth,0.7*textwidth),dpi=120)
cmap = cm.Set1             # Cycle through this colormap

for i, target in enumerate(targets):
    ax = plot_sky(target, observer, time_grid, 
                  style_kwargs=dict(color=cmap(float(i)/len(targets)),
                                    label=target.name,s=2))
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])

legend=ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
legend.get_frame().set_facecolor('w')
Esempio n. 11
0
def observability(cand=[],
                  site='VLT',
                  time=['2017-09-01T00:00:00.00', '2018-03-01T00:00:00.00'],
                  airmass=1.3):
    """
    cand is class object with parameters: name, ra, dec
    """
    # set observation site
    if site == 'VLT':
        if 0:
            longitude = '-70d24m12.000s'
            latitude = '-24d37m34.000s'
            elevation = 2635 * u.m
            vlt = EarthLocation.from_geodetic(longitude, latitude, elevation)
            observer = astroplan.Observer(
                name='VLT',
                location=vlt,
                pressure=0.750 * u.bar,
                relative_humidity=0.11,
                temperature=0 * u.deg_C,
                timezone=timezone('America/Santiago'),
                description="Very Large Telescope, Cerro Paranal")
            eso = astroplan.Observer.at_site('eso')
        else:
            observer = Observer.at_site('Cerro Paranal')

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

    print(observer)
    # set time range constrains

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

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

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

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

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

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

    targets = []

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

    for i, can in enumerate(cand):

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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