Esempio n. 1
0
def airmass_png():
    # Parse the arguments
    date = flask.request.args.get('date', default=None, type=str)
    location = flask.request.args.get('location', default=None, type=str)
    targets = flask.request.args.get('targets', default=None, type=str)
    observer = astroplan.Observer.at_site(location)
    if date is None:
        midnight = observer.midnight(Time.now())
    else:
        # +10*u.minute circumvents astroplan issue #155
        midnight = observer.midnight(Time(date)) + 10 * u.minute
    targets = _parse_targets(targets)
    # Create the airmass plot
    fig = pl.figure()
    ax = fig.add_subplot(111)
    for target in targets:
        plot_altitude(target, observer, midnight, ax=ax)
    pl.tight_layout()
    # Stream the image to the browser using BytesIO
    img = BytesIO()
    fig.savefig(img, transparent=True, format='png')
    img.seek(0)
    response = flask.send_file(img, mimetype="image/png")
    return response
Esempio n. 2
0
def plot_partial_transit(
    midpoint,
    target_coord,
    obs_site,
    transit_duration=None,
    name=None,
    ephem_label=None,
    night_only=True,
):
    """
    transit_duration : float
        in days
    """
    fig, ax = pl.subplots(1, 1, figsize=(10, 6))
    if transit_duration is not None:
        ing = midpoint - dt.timedelta(days=transit_duration / 2)
        egr = midpoint + dt.timedelta(days=transit_duration / 2)
        sunset = obs_site.sun_set_time(ing)
        sunrise = obs_site.sun_rise_time(egr)
    else:
        sunset = obs_site.sun_set_time(midpoint)
        sunrise = obs_site.sun_rise_time(midpoint)
    _ = plot_altitude(
        targets=target_coord,
        observer=obs_site,
        time=midpoint.datetime,
        brightness_shading=True,
        airmass_yaxis=True,
        min_altitude=20,  # deg
        ax=ax,
    )

    ax.axhline(30, 0, 1, c="r", ls="--", label="limit")
    ax.axvline(midpoint.datetime, 0, 1, c="k", ls="-", label="mid")
    if transit_duration is not None:
        ax.axvline(ing.datetime, 0, 1, c="k", ls="--", label="ing/egr")
        ax.axvline(egr.datetime, 0, 1, c="k", ls="--", label="_nolegend_")
    if name is None:
        name = f"ra, dec=({target_coord.to_string()})"

    if ephem_label is not None:
        name += f" @ {obs_site.name}, {ephem_label}"
    ax.set_title(name)
    if night_only:
        ax.set_xlim(sunset.datetime, sunrise.datetime)
    fig.tight_layout()
    return fig
Esempio n. 3
0
def plot_full_transit(
    obs_date,
    target_coord,
    obs_site,
    name=None,
    ephem_label=None,
    night_only=True,
):
    """
    """
    fig, ax = pl.subplots(1, 1, figsize=(10, 6))
    # plot moon
    # mon_altitude = obs_site.moon_altaz(ing_egr).alt
    # ax.plot(ing_egr, moon_altitude, ls='--', label='Moon')

    # plot target
    ing = obs_date[0]
    egr = obs_date[1]
    t14 = (obs_date[1] - obs_date[0]).value
    mid = ing + dt.timedelta(days=t14 / 2)

    _ = plot_altitude(
        targets=target_coord,
        observer=obs_site,
        time=mid.datetime,
        brightness_shading=True,
        airmass_yaxis=True,
        min_altitude=20,  # deg
        ax=ax,
    )

    ax.axhline(30, 0, 1, c="r", ls="--", label="limit")
    ax.axvline(ing.datetime, 0, 1, c="k", ls="--", label="ing/egr")
    ax.axvline(mid.datetime, 0, 1, c="k", ls="-", label="mid")
    ax.axvline(egr.datetime, 0, 1, c="k", ls="--", label="_nolegend_")
    if name is None:
        name = f"ra, dec=({target_coord.to_string()})"

    if ephem_label is not None:
        name += f" @ {obs_site.name}, {ephem_label}"
    ax.set_title(name)
    if night_only:
        sunset = obs_site.sun_set_time(ing)
        sunrise = obs_site.sun_rise_time(egr)
        ax.set_xlim(sunset.datetime, sunrise.datetime)
    fig.tight_layout()
    return fig
Esempio n. 4
0
import astroplan
from astroplan.plots import plot_altitude, plot_airmass, plot_schedule_airmass
from astropy import constants, units as u, table, stats, coordinates, wcs, log, coordinates as coord, convolution, modeling; from astropy.io import fits, ascii; from astropy.table import Table
from astroplan import Observer
import astropy.time


targets = coordinates.SkyCoord([0.67, 10.47, 29], [0.0, 0.0, 0.0], frame='galactic', unit=(u.deg, u.deg))
observer = Observer.at_site('VLA', timezone='US/Mountain')
time = astropy.time.Time('2019-01-31', location=observer.location)

import pylab as pl
pl.clf()
for target in targets:
    plot_altitude(target, observer, time, brightness_shading=True)
pl.ylim(0,55)
pl.ylabel("Altitude")
pl.title(f"{time.strftime('%D')}")
Esempio n. 5
0
def createPlot(args, saveflag, id):
    observer = Observer.at_site('lbt')
    try:
        args.coordinate[0] = float(args.coordinate[0])
        args.coordinate[1] = float(args.coordinate[1])
        coordinates = SkyCoord(args.coordinate[0],
                               args.coordinate[1],
                               unit=(u.deg, u.deg),
                               frame='icrs')
    except:
        coordinates = SkyCoord(args.coordinate[0],
                               args.coordinate[1],
                               unit=(u.hourangle, u.deg),
                               frame='icrs')

    observe_time = Time(f'{args.time[0]} {args.time[1]}', scale='utc')
    target = FixedTarget(name=args.output, coord=coordinates)
    if args.mode == 'single':
        obs_time = Time(f'{args.time[0]} {args.time[1]}')
        lbtcoord = EarthLocation(lat=32.7016 * u.deg,
                                 lon=-109.8719 * u.deg,
                                 height=3221.0 * u.m)
        altazcoord = coordinates.transform_to(
            AltAz(obstime=obs_time, location=lbtcoord))
        if args.output is None: args.output = 'Unknown'
        print(f'\n{args.output}:')
        print("Altitude = {0.alt:.4}".format(altazcoord))
    if args.plot == 'Alt' or args.plot == 'all':
        if id == 0:
            plt.figure(figsize=(10, 6))
        if args.mode == "list":
            plt.title(args.filename + '\n' + args.time[0])
        else:
            plt.title(args.output + '\n' + args.time[0])
        plot_altitude(target, observer, observe_time, brightness_shading=True)

        if saveflag == 1:
            if args.mode == 'list':
                filename = args.filename + '_' + str(ceil(id / args.number))
            else:
                filename = args.output
            #plt.tight_layout()
            plt.axhline(y=30, ls='--', color='k')

            plt.legend()
            plt.savefig(f'{filename}_Alt.png')
            plt.clf()
    if args.plot == 'Sky' or args.plot == 'all':
        observe_time2 = observe_time + np.linspace(-6, 6, 13) * u.hour
        if id == 0:
            plt.figure(figsize=(8, 6))
        if args.mode == "list":
            plt.title(f'{args.filename}\n{args.time[0]} - {args.time[1]} UT',
                      pad=13)
        else:
            plt.title(f'{args.time[0]} - {args.time[1]} UT', pad=13)
        plot_sky(target,
                 observer,
                 observe_time,
                 style_kwargs={
                     'marker': '+',
                     'c': 'k',
                     's': 160
                 })
        plot_sky(target, observer, observe_time2)
        if saveflag == 1:
            if args.mode == 'list':
                filename = args.filename + '_' + str(ceil(id / args.number))
            else:
                filename = args.output
            handles, labels = plt.gca().get_legend_handles_labels()
            by_label = dict(zip(labels, handles))
            plt.legend(by_label.values(),
                       by_label.keys(),
                       loc='center left',
                       bbox_to_anchor=(1.25, 0.5))
            plt.tight_layout()
            plt.savefig(f'{filename}_Sky.png')
            plt.clf()
    if args.plot == 'FC' or args.plot == 'all':
        plt.figure(figsize=(8, 8))
        ax, hdu = plot_finder_image(target,
                                    survey=args.survey,
                                    fov_radius=5 * u.arcmin,
                                    grid=True,
                                    reticle=True)
        if saveflag == 1:
            plt.savefig(f'{args.output}_FC.png')
            plt.clf()
    if args.plot == 'par' or args.plot == 'all':
        if id == 0:
            plt.figure(figsize=(10, 6))
            #plt.locator_params(axis='y', nbins=13)
            #plt.locator_params(axis='x', nbins=18)
        plot_parallactic(target, observer, observe_time)
        if args.mode == "list":
            plt.title(args.filename + '\n' + args.time[0])
        if saveflag == 1:
            if args.mode == 'list':
                filename = args.filename + '_' + str(ceil(id / args.number))
            else:
                filename = args.output
            plt.ylim(deg2rad(-360), deg2rad(360))
            plt.yticks(np.arange(deg2rad(-360), deg2rad(360),
                                 step=deg2rad(45)))
            locs, labels = plt.yticks()
            label = []
            for parrad in locs:
                label.append(round(rad2deg(parrad)))
            plt.yticks(locs, label)

            plt.ylabel('Parallactic angle')
            plt.grid()
            plt.legend()
            plt.tight_layout()
            plt.savefig(f'{filename}_par.png')
            plt.clf()
    if args.plot != 'None':
        del observe_time
        del observer
        del coordinates
        del target
        del observe_time2
def astroplan_test():
    '''
    '''

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

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

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

    print(' Observer:', observer.name)

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

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

    #utr2 = Observer.at_site(observer)

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

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

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

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

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

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

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

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

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

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

    return
Esempio n. 7
0
    def plot_target(self):
        """ """
        if self.date is not None:
            _date = self.date + " 12:00:00.000000"
            time = _date
        else:
            time = self.now

        ax = plot_altitude(
            self.target,
            self.site,
            time,
            # brightness_shading=True,
            min_altitude=10,
        )

        ax.axvspan(
            self.twilight_evening.plot_date,
            self.twilight_morning.plot_date,
            alpha=0.2,
            color="gray",
        )

        # Plot a vertical line for the current time
        ax.axvline(Time(self.now).plot_date, color="black", label="now", ls="dotted")

        # Plot a vertical line for the neutrino arrival time if available
        if self.arrivaltime is not None:
            ax.axvline(
                Time(self.arrivaltime).plot_date,
                color="indigo",
                label="neutrino arrival",
                ls="dashed",
            )

        start, end = ax.get_xlim()

        plt.text(
            start,
            100,
            self.summarytext,
            fontsize=8,
        )

        if self.date is not None:
            ax.set_xlabel(f"{self.date} [UTC]")
        else:
            ax.set_xlabel(f"{self.now.datetime.date()} [UTC]")
        plt.grid(True, color="gray", linestyle="dotted", which="both", alpha=0.5)

        if self.observable:
            if "g" in self.bands:
                ax.axvspan(
                    self.g_band_recommended_time_start.plot_date,
                    self.g_band_recommended_time_end.plot_date,
                    alpha=0.5,
                    color="green",
                )
            if "r" in self.bands:
                ax.axvspan(
                    self.r_band_recommended_time_start.plot_date,
                    self.r_band_recommended_time_end.plot_date,
                    alpha=0.5,
                    color="red",
                )

        # Now we plot the moon altitudes and separation
        moon_altitudes = []
        moon_times = []
        moon_separations = []
        for moon in self.moon:
            moonalt = moon.transform_to(
                AltAz(obstime=moon.obstime, location=self.site.location)
            ).alt.deg
            moon_altitudes.append(moonalt)
            moon_times.append(moon.obstime.plot_date)
            separation = moon.separation(self.coordinates).deg
            moon_separations.append(separation)
        ax.plot(
            moon_times,
            moon_altitudes,
            color="orange",
            linestyle=(0, (1, 2)),
            label="moon",
        )

        # And we annotate the separations
        for i, moonalt in enumerate(moon_altitudes):
            if moonalt > 20 and i % 3 == 0:
                if moon_separations[i] < 20:
                    color = "red"
                else:
                    color = "green"
                ax.annotate(
                    f"{moon_separations[i]:.0f}",
                    xy=(moon_times[i], moonalt),
                    textcoords="data",
                    fontsize=6,
                    color=color,
                )

        x = np.linspace(start + 0.03, end + 0.03, 9)

        # Add recommended upper limit for airmass
        y = np.full((len(x), 1), 30)
        ax.errorbar(x, y, 2, color="red", lolims=True, fmt=" ")

        # Plot an airmass scale
        ax2 = ax.secondary_yaxis(
            "right", functions=(self.altitude_to_airmass, self.airmass_to_altitude)
        )
        altitude_ticks = np.linspace(10, 90, 9)
        airmass_ticks = np.round(self.altitude_to_airmass(altitude_ticks), 2)
        ax2.set_yticks(airmass_ticks)
        ax2.set_ylabel("Airmass")

        if self.observable:
            plt.legend()

        if self.observable is False:
            plt.text(
                0.5,
                0.5,
                f"NOT OBSERVABLE\ndue to {self.rejection_reason}",
                size=20,
                rotation=30.0,
                ha="center",
                va="center",
                bbox=dict(
                    boxstyle="round",
                    ec=(1.0, 0.5, 0.5),
                    fc=(1.0, 0.8, 0.8),
                ),
                transform=ax.transAxes,
            )

        plt.tight_layout()

        outpath_png = os.path.join(self.name, f"{self.name}_airmass.png")
        outpath_pdf = os.path.join(self.name, f"{self.name}_airmass.pdf")
        plt.savefig(outpath_png, dpi=300, bbox_inches="tight")
        plt.savefig(outpath_pdf, bbox_inches="tight")
        # plt.close()
        
        return ax