示例#1
0
def create_graphs(file_path, event, site_data, fov=30):
    """Create airmass and finder plots."""
    # Plot airmass during the night
    delta_t = site_data['sun_rise'] - site_data['sun_set']
    time_range = site_data['sun_set'] + delta_t * np.linspace(0, 1, 75)
    plot_airmass(event.coord,
                 site_data['observer'],
                 time_range,
                 altitude_yaxis=True,
                 style_sheet=dark_style_sheet)
    airmass_file = "{}_AIRMASS.png".format(event.name)
    plt.savefig(os.path.join(file_path, 'airmass_plots', airmass_file))
    plt.clf()

    # Plot finder chart
    import warnings
    with warnings.catch_warnings():
        warnings.simplefilter('ignore')
        plot_finder_image(event.target,
                          fov_radius=fov * u.arcmin,
                          grid=False,
                          reticle=True)
    airmass_file = "{}_FINDER.png".format(event.name)
    plt.savefig(os.path.join(file_path, 'finder_charts', airmass_file))
    plt.clf()
示例#2
0
def airmass_altitude_plot_given_target(name_observatory,
                                       day,
                                       target,
                                       path_target_list=None):
    """

    Parameters
    ----------
    name_observatory : str
        name of the observatory
    day  : date
        date in format  'yyyy-mm-dd'
    target :  str
         name of  target
    path_target_list  : path
        path of the target  list

    Returns
    -------

    """
    if path_target_list is None:
        path_target_list = path_spock + '/target_lists/speculoos_target_list_v6.txt'
    observatory = charge_observatories(name_observatory)[0]
    delta_midnight = Time(np.linspace(observatory.twilight_evening_nautical(day, which='next').jd - 0.07, \
                                      observatory.twilight_morning_nautical(day + 1, which='nearest').jd + 0.07, 100),
                          format='jd')
    sun_set = observatory.twilight_evening_nautical(day, which='next').iso
    sun_rise = observatory.twilight_morning_nautical(day + 1,
                                                     which='nearest').iso
    target_list = pd.read_csv(path_target_list, delimiter=' ')
    idx_target_list = list(target_list['Sp_ID']).index(target)

    fig, axs = plt.subplots(1, figsize=(9, 7))
    colors_start_new_target = ['black', 'darkgray', 'lightgray']

    dec = target_list['DEC'][idx_target_list]
    ra = target_list['RA'][idx_target_list]
    plot_styles = {'linestyle': '-', 'color': 'k'}
    if name_observatory == 'SSO':
        plot_styles = {'linestyle': '-', 'color': 'skyblue'}
    if name_observatory == 'SNO':
        plot_styles = {'linestyle': '-', 'color': 'teal'}
    if name_observatory == 'Saint-Ex':
        plot_styles = {'linestyle': '-', 'color': 'gold'}
    plot_airmass(FixedTarget(coord=SkyCoord(ra=ra, dec=dec, unit=(u.deg, u.deg)), \
                             name=target), observatory, delta_midnight, brightness_shading=True, altitude_yaxis=True,
                 style_kwargs=plot_styles)
    #axs.vlines(sun_set, 3, 1, linestyle='--', color='orange', alpha=0.9, linewidth=2)
    #axs.vlines(sun_rise, 3, 1, linestyle='--', color='orange', alpha=0.9, linewidth=2)

    plt.ylabel('Altitude (degrees)')
    plt.grid(color='gainsboro', linestyle='-', linewidth=1, alpha=0.3)
    plt.title('Visibility  plot for ' + target + ' on the ' +
              str(day.tt.datetime.strftime("%Y-%m-%d")) + ' at ' +
              name_observatory,
              y=-0.01)
    #plt.title('Visibility plot for target ' + target + ' on the ' + str(day.tt.datetime.strftime("%Y-%m-%d")))
    plt.show()
示例#3
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))
示例#4
0
def airmass_altitude_plot_saved(name_observatory, telescope, day):
    """

    Parameters
    ----------
    name_observatory : str
        name of the observatory (ex : 'SSO')
    telescope : str
        name of the telescope (exx : 'Io')
    day : date
        date of day in fmt "yyyy-mm-dd"


    Returns
    -------
    plot
         visibility plot on telescope at a given day

    """
    night_block = pd.read_csv(os.path.join(path_spock + '/DATABASE/', telescope,
                                              'Archive_night_blocks','night_blocks_' + telescope + '_' + day.tt.datetime.strftime("%Y-%m-%d") + '.txt'),\
                              sep=' ', skipinitialspace=True)
    observatory = charge_observatories(name_observatory)[0]
    day = Time(night_block['start time (UTC)'][0]) - 5 * u.hour
    delta_midnight = Time(np.linspace(observatory.twilight_evening_nautical(day,which='next').jd - 0.07,\
                                      observatory.twilight_morning_nautical(day+1,which='nearest').jd + 0.07, 100),format='jd')
    sun_set = observatory.twilight_evening_nautical(day, which='next').iso
    sun_rise = observatory.twilight_morning_nautical(day + 1,
                                                     which='nearest').iso
    fig, axs = plt.subplots(1)
    colors_start_new_target = ['black', 'darkgray', 'lightgray']
    for i in range(len(night_block)):
        dec = str(int(float(night_block['dec (d)'][i]))) + ' ' + str(
            int(abs(float(night_block['dec (m)'][i])))) + ' ' + str(
                int(abs(float(night_block['dec (s)'][i]))))
        ra = str(int(float(night_block['ra (h)'][i]))) + ' ' + str(
            int(abs(float(night_block['ra (m)'][i])))) + ' ' + str(
                int(abs(float(night_block['ra (s)'][i]))))
        plot_airmass(FixedTarget(coord=SkyCoord(ra=ra,dec=dec,unit=(u.hourangle, u.deg)),\
                                 name=night_block['target'][i]), observatory, delta_midnight, altitude_yaxis=True)
        plt.ylabel('Altitude (degrees)')
        t = Time(night_block['start time (UTC)'][i])
        axs.vlines(t.iso,
                   3,
                   1,
                   linestyle='--',
                   color=colors_start_new_target[i],
                   alpha=0.7,
                   label='start ' + str(night_block['target'][i]))
        axs.vlines(sun_set, 3, 1, linestyle=':', color='yellow', alpha=0.9)
        axs.vlines(sun_rise, 3, 1, linestyle=':', color='yellow', alpha=0.9)
        #plt.legend(loc=2)
        plt.grid(color='gainsboro', linestyle='-', linewidth=1, alpha=0.3)
        plt.title('Visibility plot for the night of the ' +
                  str(day.tt.datetime.strftime("%Y-%m-%d")) + ' on ' +
                  str(telescope))
示例#5
0
    def _make_figure(self, xlim=None, ylim=None, ax=None):
        if ax:
            self.ax = ax

        plot_airmass(self.coord,
                     self.observer,
                     self.time,
                     ax=self.ax,
                     altitude_yaxis=True,
                     brightness_shading=True)

        self.ax.tick_params(labelsize=8)
示例#6
0
文件: gaua.py 项目: jmichelet/bila
    def sortie_graphique(self, etoile_cible, date_obs, observatoire):
        matplotlib.rcParams['backend'] = 'Qt5Agg'
        # Etoiles
        etoile = FixedTarget(etoile_cible['equat'], name=etoile_cible['nom'])

        # Intervalle de temps
        temps_obs = Time(date_obs)
        debut = temps_obs - TimeDelta(10800.0, format='sec')
        fin = temps_obs + TimeDelta(10800.0, format='sec')
        delta_t = fin - debut
        intervalle_temps_1 = debut + delta_t * np.linspace(0, 1, 75)
        intervalle_temps_2 = debut + delta_t * np.linspace(0, 1, 11)

        # Observatoire
        obs = Observer(location=observatoire, timezone="UTC")

        # Masse d'air
        if self.graph1 is None:
            self.fig1, self.graph1 = plt.subplots()
        else:
            self.graph1.clear()
        plot_airmass(etoile,
                     obs,
                     intervalle_temps_1,
                     ax=self.graph1,
                     altitude_yaxis=True,
                     max_region=2.0)
        self.graph1.legend(shadow=True, loc='best')
        plt.tight_layout()

        # Carte
        # Il faut obligatoirement que le graphique soit en mode polaire avant l'appel à plot_sky
        if self.graph2 is None:
            self.fig2, self.graph2 = plt.subplots(
                subplot_kw=dict([('projection', 'polar')]))
        else:
            self.graph2.clear()
        style = {'marker': '.'}
        plot_sky(etoile,
                 obs,
                 intervalle_temps_2,
                 ax=self.graph2,
                 style_kwargs=style)
        self.graph2.legend(shadow=True, loc='best')
        plt.tight_layout()

        plt.show(block=False)
        plt.pause(.1)
示例#7
0
def airmass_png():
    # Parse the arguments
    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)
    targets = _parse_targets(targets)
    time = Time.now()
    # Create the airmass plot
    fig = pl.figure()
    ax = fig.add_subplot(111)
    plot_airmass(targets[0], observer, time, ax=ax)
    pl.tight_layout()
    # Stream the image to the browser using BytesIO
    img = BytesIO()
    fig.savefig(img)
    img.seek(0)
    response = flask.send_file(img, mimetype="image/png")
    return response
示例#8
0
def main():

    site = Observer.at_site('Las Campanas Observatory')

    ra = "07:21:28.72"
    dec = "-45:34:03.85"
    name = "TIC_59859387.01"
    start_time = Time('2020-02-05 23:30:00')
    end_time = Time('2020-02-06 09:30:00')

    ##########################################

    range_time = end_time - start_time
    observe_time = start_time + range_time*np.linspace(0,1,100)

    if (isinstance(ra, u.quantity.Quantity) and
        isinstance(dec, u.quantity.Quantity)
    ):
        target_coord = SkyCoord(ra=ra, dec=dec)
    elif (isinstance(ra, str) and
          isinstance(dec, str)
    ):
        target_coord = SkyCoord(ra=ra, dec=dec, unit=(u.hourangle, u.deg))
    else:
        raise NotImplementedError

    target = FixedTarget(coord=target_coord, name=name)

    outdir = "../results/{}".format(name)
    if not os.path.exists(outdir):
        os.mkdir(outdir)

    outname = '{}_{}_start{}_airmass.png'.format(
        name, site.name.replace(' ','_'), repr(start_time.value)
    )
    outpath = os.path.join(outdir,outname)

    plot_airmass(target, site, observe_time, style_sheet=dark_style_sheet,
                 altitude_yaxis=True)

    plt.tight_layout()
    plt.savefig(outpath, dpi=250, bbox_inches='tight')
    print('made {}'.format(outpath))
def plot_all(startimes, endtimes, midtimes, duration, target, obs):
	n = len(startimes)
	w = int(np.ceil(np.sqrt(n)))
	h = int(np.ceil(n/w))

	half_duration = datetime.timedelta(hours=0.5*duration[0])

	fig, axs = plt.subplots(w,h,figsize=(3*h,3*w),sharey=True)
	
	m = 0
	for i in np.arange(w):
		for j in np.arange(h):
			if m>=n:
				axs[i,j].set_visible(False)
				continue

			year = midtimes[m][6:10]
			mid_time = Time(year  + '-' + midtimes[m].replace('/','-').replace('-%s'%year,'') + ':00')
			
			start_time = -1*half_duration + mid_time.datetime
			end_time   = half_duration + mid_time.datetime

			# add airmass plot - sample airmass time window from UT 0 so x axis reads correct data - created start of grid by dumb hack of taking start_time and subtracting start_time.hour
			dt_array = np.arange(0,30,0.1)
			time_array = [start_time - datetime.timedelta(hours=start_time.hour) + datetime.timedelta(hours=q) for q in dt_array]
			ax = plot_airmass(target, obs, time_array, ax=axs[i,j],brightness_shading=False, altitude_yaxis=False)
			
			# get moon info
			moon_ill = round(moon.moon_illumination(mid_time),2)
			moon_coord = moon.get_moon(mid_time,location=obs.location) 
			moon_sep = np.abs(moon_coord.ra  - target.ra)

			axs[i,j].axvspan(start_time, end_time,ymin=0, ymax=10, color='plum',alpha=0.8)

			# narrower x-axis
			xlo = datetime.datetime(day=start_time.day, year=start_time.year, month= start_time.month)
			axs[i,j].set_xlim(xlo + datetime.timedelta(hours=4),xlo + datetime.timedelta(hours=17))

			# Put moon info in each panel
			txt_shift = 5 if start_time.hour > 8 else 12
			txt = axs[i,j].annotate('moon:%s\n%sdeg'%(moon_ill,round(moon_sep.value)),\
				(xlo + datetime.timedelta(hours=txt_shift),2.5),\
				fontsize=8)
			txt.set_bbox(dict(facecolor='white', alpha=0.5))

			start = start_time - datetime.timedelta(hours=10)
			twilight1 =obs.twilight_evening_astronomical(Time(start), which='next').datetime
			twilight2 = obs.twilight_morning_astronomical(Time(start), which='next').datetime
			ax.axvspan(twilight1, twilight2, ymin=0, ymax=1, color='lightgrey',zorder=-10)

			fig.suptitle(planet + ' from ' + site, fontsize=18)
			m+=1

	plt.subplots_adjust(hspace=0.6,top=0.92)
示例#10
0
    def affichage_masse_air(self, etoile_cible, selection_etoiles, date_obs,
                            observatoire):
        # Etoiles
        # Bogue dans plot_airmass : le 1er FixedTarget ne génère pas de légende. Donc on duplique le 1er enregistrement dans la liste
        etoiles = [
            FixedTarget(etoile_cible['equat'], name=etoile_cible['nom']),
            [FixedTarget(etoile_cible['equat'], name=etoile_cible['nom'])]
        ]
        for etoile in selection_etoiles:
            if len(etoiles) > 6:
                break
            if (etoile['Sp'] in type_pickles) or etoile['Miles']:
                etoiles.append(
                    FixedTarget(etoile['equat'], name=etoile['Name']))
        # Intervalle de temps
        temps_obs = Time(date_obs)
        debut = temps_obs - TimeDelta(10800.0, format='sec')
        fin = temps_obs + TimeDelta(10800.0, format='sec')
        delta_t = fin - debut
        intervalle_temps = debut + delta_t * np.linspace(0, 1, 75)
        # Observatoire
        obs = Observer(location=observatoire, timezone="UTC")

        # Graphique
        #   Nettoyage d'un éventuel graphique pré-existant
        if self.graphique_masse_air:
            self.graphique_masse_air.clear()
            plt.pause(.1)
        #   Affichage
        self.graphique_masse_air = plot_airmass(etoiles,
                                                obs,
                                                intervalle_temps,
                                                altitude_yaxis=True,
                                                brightness_shading=True,
                                                max_region=2.0)
        self.graphique_masse_air.legend(shadow=True, loc='best')
        plt.tight_layout()
        plt.show(block=False)
        plt.pause(.1)
示例#11
0
def airmass(ra=0.,
            dec=0.,
            obs='apo',
            date='2019-10-01',
            name='object',
            plot=False,
            tz='US/Mountain'):
    """  Get airmass table for specified object position, observatory, date
    """

    # set the site
    site = Observer.at_site(obs, timezone=tz)

    # set the objects
    if type(ra) is float:
        obj = FixedTarget(name=name,
                          coord=SkyCoord(str(ra) + 'd',
                                         str(dec) + 'd'))
    else:
        obj = FixedTarget(name=name, coord=SkyCoord(ra + 'h', dec + 'd'))

    time = Time('{:s} 00:00:00'.format(date),
                scale='utc',
                location=(site.location.lon, site.location.lat),
                precision=0)
    sunset = site.sun_set_time(time)
    civil = site.twilight_evening_civil(time)
    nautical = site.twilight_evening_nautical(time)
    astronomical = site.twilight_evening_astronomical(time)
    for t in [sunset, civil, nautical, astronomical]:
        t.format = 'isot'
        t.precision = 0
    print('Observatory: ', obs)
    print('Sunset: ', sunset)
    print('Civil twilight: ', civil)
    print('Nautical twilight: ', nautical)
    print('Astronomical twilight: ', astronomical)

    # loop over all UTC hours for this date (would prefer local!)
    print('{:8s}{:8s}{:8s}{:8s}{:8s}{:9s}{:8s}{:8s} {:16s}{:20s}'.format(
        'Local', 'UT', 'LST', 'HA', 'Airmass', 'ParAng', 'Phase', 'Moon Alt',
        'Moon RA', 'Moon DEC'))
    for hr in np.arange(24):
        time = Time('{:s} {:d}:00:00'.format(date, hr),
                    scale='utc',
                    location=(site.location.lon, site.location.lat),
                    precision=0)
        sun = get_sun(time)
        if site.sun_altaz(time).alt.value > 10: continue

        moon = get_moon(time)

        val = site.altaz(time, obj).secz
        if val < 0:
            airmass = '     ...'
        else:
            airmass = '{:8.2f}'.format(val)
        val = site.moon_altaz(time).alt.value
        if val < 0:
            moonalt = '     ...'
        else:
            moonalt = '{:8.2f}'.format(val)
        lst = time.sidereal_time('mean').hms
        ha = site.target_hour_angle(time, obj)
        ha.wrap_angle = 180 * units.deg
        local = site.astropy_time_to_datetime(time)
        print(
            '{:02d}:{:02d}  {:02d}:{:02d}  {:02d}:{:02d} {:3d}:{:02d} {:8s} {:8.2f} {:8.2f} {:8s} {:s} {:s}'
            .format(
                local.hour,
                local.minute,
                time.datetime.hour,
                time.datetime.minute,
                int(round(lst[0])),
                int(round(lst[1])),
                int(round(ha.hms[0])),
                int(abs(round(ha.hms[1]))),
                airmass,
                #site.altaz(time,obj).secz,
                site.parallactic_angle(time, obj).deg,
                astroplan.moon_illumination(time),
                moonalt,
                str(moon.ra.to_string(units.hour)),
                str(moon.dec)))

    if plot:
        fig, ax = plt.subplots(2, 1)
        fig.subplots_adjust(hspace=0.001)

        plot_airmass(obj, site, time, ax=ax[0])
        plot_parallactic(obj, site, time, ax=ax[1])
示例#12
0
def plot(date, objects):
    # In[ ]:

    print(objects)
    #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')

    # In[ ]:

    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]

    # In[ ]:

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

    # ### Stars ###

    # In[ ]:

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

    # In[ ]:

    x = 0
    for i in target_list:
        target_list[x] = FixedTarget.from_name(target_list[x])
        x += 1

    # ### Airmass Curve ###

    # In[ ]:
    """
    plt.rcParams['font.family'] = "Times New Roman"
    plt.rcParams['legend.loc'] = "Upper Right"
    plt.rcParams['figure.dpi'] = 300


    x = 0
    for i in target_list:
        plot_airmass(target_list[x], las, observe_time, max_airmass = 2.25, brightness_shading=True, altitude_yaxis=True)
        x += 1


    plt.legend(shadow=True, loc='center left', bbox_to_anchor=(1.1, 1))
    plt.title('Airmass Curve for Night of ' + date)

    plt.savefig('airmass.png', bbox_inches='tight', pad_inches=0.25)
    """

    plt.rcParams['font.family'] = "Times New Roman"
    plt.rcParams['legend.loc'] = "Upper Right"
    plt.rcParams['figure.dpi'] = 300

    x = 0
    for i in target_list:
        plot_airmass(target_list[x],
                     las,
                     observe_time,
                     max_airmass=2.25,
                     brightness_shading=True,
                     altitude_yaxis=True)
        x += 1

    plt.legend(shadow=True, loc='center left', bbox_to_anchor=(1.1, 1))
    plt.title('Airmass Curve for Night of ' + date)

    #os.remove("static/airmass.png") idk if necesarry
    plt.savefig('static/data/airmass.png',
                bbox_inches='tight',
                pad_inches=0.25)
    plt.clf()
示例#13
0
def main():
    #================ASKING HERE THE DETAILS OF YOUR OBSERVATION
    name_of_the_observatory = str(
        input("\nType the name of the observatory, e.g.: subaru : "))
    name_timezone = str(input("Type the timezone e.g. US/Hawaii : "))
    time_str = str(
        input(
            "Type the date and the time of observation e.g. 2000-06-30 23:30:00 : "
        ))

    see_sun = str(input("Would you like to target the sun? [yes/no] "))
    see_moon = str(input("Would you like to target the moon? [yes/no] "))
    how_many_targets = int(
        input("How many objects would you like to observe? "))
    #/\ Here is in UTC

    #IF YOU WANT TO PLOT THE MOON/SUN AIRMASS + MOON/SUN IN SKY
    see_moon = 'yes'
    see_sun = 'no'

    observe_time = Time(time_str)

    #time window
    time = observe_time + np.linspace(-12, 12, 100) * u.hour
    to_be_plot = time.plot_date
    observer = observer_function(name_of_the_observatory, name_timezone)

    i = 0
    while how_many_targets > 0:
        fig = plt.figure(figsize=(11, 7))
        fig.subplots_adjust(hspace=0.5)

        if see_sun == 'yes':
            sun = targeting_sun(observe_time)

            ax = plt.subplot(1, 2, 1)
            plot_airmass(sun,
                         observer,
                         observe_time,
                         brightness_shading=True,
                         style_kwargs={'color': 'r'},
                         min_airmass=0.5,
                         max_airmass=3.5)
            ax.set_title('Airmass')
            plt.legend(shadow=True, loc=2)

            ax = plt.subplot(1, 2, 2, projection='polar')
            plot_sky(sun, observer, observe_time, style_kwargs={'color': 'r'})
            ax.set_title('Position at time: ' + time_str + '[UTC]\n \n')
        else:
            pass

        if see_moon == 'yes':
            moon = targeting_moon(observe_time)

            ax = plt.subplot(1, 2, 1)
            plot_airmass(moon,
                         observer,
                         observe_time,
                         brightness_shading=True,
                         min_airmass=0.5,
                         max_airmass=3.5)
            ax.set_title('Airmass')
            plt.legend(shadow=True, loc=2)

            ax = plt.subplot(1, 2, 2, projection='polar')
            plot_sky(moon, observer, observe_time)
            ax.set_title('Position at time: ' + time_str + '[UTC]\n \n')
        else:
            pass

        #TARGET DATA

        RA = str(input("Type the RA of your target e.g. 06h45m08.9173s : "))
        DEC = str(input("Type the DEC of your target e.g. -16d42m58.017s : "))
        NAME = str(input("Type the name of your target : "))
        frame = str(input("Type the frame of your target e.g. icrs: "))
        #frame = 'icrs'

        target = target_wanted(RA, DEC, NAME)

        ax = plt.subplot(1, 2, 1)
        plot_airmass(target,
                     observer,
                     observe_time,
                     brightness_shading=True,
                     min_airmass=0.5,
                     max_airmass=3.5)
        plt.text(0.5,
                 0.9,
                 'Observatory: ' + name_of_the_observatory + '\n Timezone: ' +
                 name_timezone,
                 horizontalalignment='center',
                 verticalalignment='center',
                 transform=ax.transAxes)
        ax.set_title('Airmass')
        plt.legend(shadow=True, loc=2)

        ax = plt.subplot(1, 2, 2, projection='polar')
        plot_sky(target, observer, observe_time)
        ax.set_title('Position at time: ' + time_str + '[UTC]\n \n')

        how_many_targets -= 1
        i += 1

        plt.legend(shadow=True, loc=2)
        plt.tight_layout()
        #CHANGE HERE THE PATH AND NAME YOUR DIRECTORY SHOULD BE SAVED IN/AS
        plt.savefig('graph_representation/' + NAME + '.png')
示例#14
0
def main():
    #=================ADD HERE YOUR .TXT FILE WITH THE ID OF YOUR TARGETS
    file_read = np.loadtxt('list_TIC_output.txt', skiprows=1)
    ID_array = file_read[:, 0]
    RA_array = file_read[:, 1]
    DEC_array = file_read[:, 2]

    #================ADD HERE THE DETAILS OF YOUR OBSERVATION
    name_of_the_observatory = 'ctio'
    name_timezone = 'America/Santiago'
    time_str = '2019-07-25 04:00:00'
    #/\ Here is in UTC

    #IF YOU WANT TO PLOT THE MOON/SUN AIRMASS + MOON/SUN IN SKY
    see_moon = 'yes'
    see_sun = 'no'

    how_many_targets = len(ID_array)
    observe_time = Time(time_str)

    #time window
    time = observe_time + np.linspace(-12, 12, 100) * u.hour
    to_be_plot = time.plot_date
    observer = observer_function(name_of_the_observatory, name_timezone)

    i = 0
    while how_many_targets > 0:
        fig = plt.figure(figsize=(11, 7))
        fig.subplots_adjust(hspace=0.5)

        if see_sun == 'yes':
            sun = targeting_sun(observe_time)

            ax = plt.subplot(1, 2, 1)
            plot_airmass(sun,
                         observer,
                         observe_time,
                         brightness_shading=True,
                         style_kwargs={'color': 'r'},
                         min_airmass=0.5,
                         max_airmass=3.5)
            ax.set_title('Airmass')
            plt.legend(shadow=True, loc=2)

            ax = plt.subplot(1, 2, 2, projection='polar')
            plot_sky(sun, observer, observe_time, style_kwargs={'color': 'r'})
            ax.set_title('Position at time: ' + time_str + '[UTC]\n \n')
        else:
            pass

        if see_moon == 'yes':
            moon = targeting_moon(observe_time)

            ax = plt.subplot(1, 2, 1)
            plot_airmass(moon,
                         observer,
                         observe_time,
                         brightness_shading=True,
                         min_airmass=0.5,
                         max_airmass=3.5)
            ax.set_title('Airmass')
            plt.legend(shadow=True, loc=2)

            ax = plt.subplot(1, 2, 2, projection='polar')
            plot_sky(moon, observer, observe_time)
            ax.set_title('Position at time: ' + time_str + '[UTC]\n \n')
        else:
            pass

        #TARGET DATA

        RA = str(RA_array[i])
        DEC = str(DEC_array[i])
        NAME = str(int(ID_array[i]))
        #frame = 'icrs'

        target = target_wanted(RA, DEC, NAME)

        ax = plt.subplot(1, 2, 1)
        plot_airmass(target,
                     observer,
                     observe_time,
                     brightness_shading=True,
                     min_airmass=0.5,
                     max_airmass=3.5)
        plt.text(0.5,
                 0.9,
                 'Observatory: ' + name_of_the_observatory + '\n Timezone: ' +
                 name_timezone,
                 horizontalalignment='center',
                 verticalalignment='center',
                 transform=ax.transAxes)
        ax.set_title('Airmass')
        plt.legend(shadow=True, loc=2)

        ax = plt.subplot(1, 2, 2, projection='polar')
        plot_sky(target, observer, observe_time)
        ax.set_title('Position at time: ' + time_str + '[UTC]\n \n')

        how_many_targets -= 1
        i += 1

        plt.legend(shadow=True, loc=2)
        plt.tight_layout()
        #CHANGE HERE THE PATH AND NAME YOUR DIRECTORY SHOULD BE SAVED IN/AS
        plt.savefig('graph_representation/' + NAME + '.png')
示例#15
0
def airmassplot(request, transient_id, obs_id, telescope_id):
    import random
    import django
    import datetime
    from astroplan.plots import plot_airmass

    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    from matplotlib.dates import DateFormatter
    from matplotlib import rcParams
    rcParams['figure.figsize'] = (7, 7)

    transient = Transient.objects.get(pk=transient_id)
    if int(obs_id):
        obsnight = ClassicalObservingDate.objects.get(pk=obs_id)
        obs_date = obsnight.obs_date
    else:
        obs_date = datetime.date.today()  #time.now()

    telescope = Telescope.objects.get(pk=telescope_id)

    target = SkyCoord(transient.ra, transient.dec, unit=u.deg)
    time = Time(str(obs_date).split('+')[0], format='iso')

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

    fig = Figure()
    ax = fig.add_subplot(111)
    canvas = FigureCanvas(fig)

    ax.set_title("%s, %s, %s" %
                 (telescope.tostring(), transient.name, obs_date))

    night_start = tel.twilight_evening_astronomical(time, which="previous")
    night_end = tel.twilight_morning_astronomical(time, which="previous")
    delta_t = night_end - night_start
    observe_time = night_start + delta_t * np.linspace(0, 1, 75)
    plot_airmass(target, tel, observe_time, ax=ax)

    yr, mn, day, hr, minu, sec = night_start.iso.replace(':', ' ').replace(
        '-', ' ').split()
    starttime = datetime.datetime(int(yr), int(mn), int(day), int(hr),
                                  int(minu))
    if int(hr) == 0:
        xlow = datetime.datetime(int(yr), int(mn), int(day) - 1, 23, int(minu))
    else:
        xlow = datetime.datetime(int(yr), int(mn), int(day),
                                 int(hr) - 1, int(minu))
    yr, mn, day, hr, minu, sec = night_end.iso.replace(':', ' ').replace(
        '-', ' ').split()
    endtime = datetime.datetime(int(yr), int(mn), int(day), int(hr), int(minu))
    xhi = datetime.datetime(int(yr), int(mn), int(day), int(hr) + 1, int(minu))
    ax.axvline(starttime, color='r',
               label='18 deg twilight')  #night_start.iso)
    ax.axvline(endtime, color='r')
    ax.legend(loc='lower right')

    ax.set_xlim([xlow, xhi])

    response = django.http.HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
示例#16
0
def plot_quadrature_windows(ra,
                            dec,
                            ticid,
                            t0,
                            period,
                            start_time,
                            end_time,
                            site,
                            obs_per_night=None,
                            N_points=500):

    if (isinstance(ra, u.quantity.Quantity)
            and isinstance(dec, u.quantity.Quantity)):
        target_coord = SkyCoord(ra=ra, dec=dec)
    elif (isinstance(ra, str) and isinstance(dec, str)):
        target_coord = SkyCoord(ra=ra, dec=dec, unit=(u.hourangle, u.deg))
    else:
        raise NotImplementedError

    target = FixedTarget(coord=target_coord, name='TIC' + ticid)

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

    fig = plt.figure(figsize=(24, 4))
    ax = plt.gca()

    plot_airmass(target, site, observe_time)

    plt.plot_date(observe_time.plot_date, np.ones(len(observe_time)), alpha=0)

    formatter = DateFormatter('%m/%d/%y')
    ax.xaxis.set_major_formatter(formatter)

    ax.xaxis.set_minor_locator(AutoMinorLocator())

    ax.set_ylabel('Airmass', color='C0')

    if not obs_per_night is None:

        ix = 0
        for o in obs_per_night:

            if ix == 0:
                ax.plot_date([o[0].plot_date, o[1].plot_date], [1.01, 1.01],
                             c='C2',
                             alpha=0.5,
                             zorder=2,
                             fmt='-',
                             lw=10,
                             label='06 to 10 UT')
            else:
                ax.plot_date([o[0].plot_date, o[1].plot_date], [1.01, 1.01],
                             c='C2',
                             alpha=0.5,
                             zorder=2,
                             fmt='-',
                             lw=10)

            ix += 1

    # calculate the expected RV signal. note we are ignoring barycentric timing
    # effects (BJD vs JD), which are of order 16 minutes.
    #
    # note: it's cos, not sin. Eg., Eq 3 from Fulton+2018.
    rv = np.cos(((2 * pi / period) * (observe_time.jd * u.day - t0)) * u.rad)

    ax.legend(loc='best')
    ax.get_xaxis().set_tick_params(which='both', direction='in')

    ax2 = ax.twinx()
    ax2.plot_date(observe_time.plot_date, rv, fmt='-', c='C1')
    ax2.set_ylabel('RV', color='C1')

    outpath = (os.path.join(OUTDIR, 'TIC{}.png'.format(ticid)))
    fig.savefig(outpath, bbox_inches='tight')
    print('made {}'.format(outpath))
示例#17
0
kmtnet_styles = {
    'linestyle': '-',
    'color': 'g',
    'alpha': 0.9,
    'linewidth': 2.9
}
#meerkat_styles = {'linestyle': '-', 'color': 'b', 'alpha': 0.9, 'linewidth': 2.9 }
askap_styles = {
    'linestyle': '-',
    'color': '#F39C12',
    'alpha': 0.9,
    'linewidth': 2.9
}

#Plotting airmasses
plot_airmass(hydraA4, telescope, date_range, style_kwargs=observatory1_styles)

plot_airmass(hydraA2, ctio, date_range, style_kwargs=ctio_styles)

plot_airmass(hydraA3, kmtnet, date_range, style_kwargs=kmtnet_styles)

plot_airmass(hydraA5, askap, date_range, style_kwargs=askap_styles)

plt.title('AIRMASSES AT' + ' ' + Observatory_name + ' ' + ctio.name.upper() +
          ' ' + askap.name + ' ' + 'KmtNeT Telescope/Observatory',
          fontsize=30)
plt.xlabel('TIMES', fontsize=20)
plt.xticks(fontsize=20)
plt.ylabel('AIRMASSES', fontsize=20)
plt.yticks(fontsize=20)
plt.legend(shadow=True, loc=1, prop={'size': 12})
示例#18
0
trunctable = objtab['OBJ', 'RA', 'Dec']

trunctable.pprint(max_lines=-1, max_width=-1)

# In[17]:

plt.clf()
for line in trunctable:
    cur_targ = FixedTarget(name=line['OBJ'],
                           coord=SkyCoord(line['RA'],
                                          line['Dec'],
                                          frame='icrs'))
    if line == trunctable[0]:
        plot_airmass(cur_targ,
                     observatory,
                     daytime,
                     brightness_shading=True,
                     altitude_yaxis=True)
    else:
        plot_airmass(cur_targ,
                     observatory,
                     daytime,
                     brightness_shading=False,
                     altitude_yaxis=False)
plt.savefig((subdir + '\\amassplot.png'),
            dpi=900,
            orientation='landscape',
            bbox_inches='tight')
plt.clf()

# In[18]:
示例#19
0
from astroplan import Observer
from astropy.time import Time
from astropy.coordinates import SkyCoord
from astroplan import FixedTarget
from astroplan.plots import plot_airmass
from astroplan.plots import plot_sky
import numpy as np

latitude = '+40d45m31.3236s'
longitude = '-111d52m34.2588s'
elevation = 1288 * u.m
location = EarthLocation.from_geodetic(longitude, latitude, elevation)
slc = Observer(name='SLC', location=location, timezone=timezone('US/Mountain'))

time = Time('2020-01-18 03:00:00')

betelgeuse = FixedTarget.from_name('Betelgeuse')
sirius = FixedTarget.from_name('Sirius')
plot_airmass(betelgeuse,
             slc,
             time,
             brightness_shading=True,
             altitude_yaxis=True)
plot_airmass(sirius, slc, time, brightness_shading=True, altitude_yaxis=True)
plt.show()

manytimes = time + np.linspace(-3, 9, 13) * u.hour
plot_sky(betelgeuse, slc, manytimes, north_to_east_ccw=False)
plot_sky(sirius, slc, manytimes, north_to_east_ccw=False)
plt.show()
示例#20
0
文件: plan.py 项目: franpoz/SHERLOCK
def create_observation_observables(object_id,
                                   object_dir,
                                   since,
                                   name,
                                   epoch,
                                   epoch_low_err,
                                   epoch_up_err,
                                   period,
                                   period_low_err,
                                   period_up_err,
                                   duration,
                                   observatories_file,
                                   timezone,
                                   latitude,
                                   longitude,
                                   altitude,
                                   max_days,
                                   min_altitude,
                                   moon_min_dist,
                                   moon_max_dist,
                                   transit_fraction,
                                   baseline,
                                   error_alert=True):
    """

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

table = observability_table(global_constraints,
                            kp,
                            FixedTargets,
                            time_range=[tstart, tend])
idx = np.where(table["ever observable"])[0]
print("%d/%d targets observable from %s-%s" %
      (len(idx), len(table), tstart, tend))
FixedTargets = [FixedTargets[i] for i in idx]

plt.figure(figsize=(30, 20))
ax = plot_airmass(FixedTargets, kp, observe_time, brightness_shading=True)
plt.legend(shadow=True, loc=2)
altitude_ticks = np.array([90, 60, 50, 40, 30, 20])
airmass_ticks = 1. / np.cos(np.radians(90 - altitude_ticks))
ax2 = ax.twinx()
ax2.invert_yaxis()
ax2.set_yticks(airmass_ticks)
ax2.set_yticklabels(altitude_ticks)
ax2.set_ylim(ax.get_ylim())
ax2.set_ylabel('Altitude [degrees]')
plotName = outfile.replace(".dat", ".png").replace(".txt", ".png")
plt.savefig(plotName)
plt.close()
def main(args=None):
    p = parser()
    opts = p.parse_args(args)

    # Late imports
    import operator
    import sys

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    # Show or save output.
    opts.output()
示例#23
0
################################################################################
--------------------------------------------------------------------------------
################################################################################
'''
print('Please note this code is very much a work in progress')
# Defining location of observatory
loc = EarthLocation.from_geodetic(-73.751433 * u.deg, 42.719546 * u.deg,
                                  106 * u.m)
Breyo = Observer(location=loc, name="Breyo", timezone="US/Eastern")

# Defining time of observation
obsDate = input('Date of Observation run [yyyy-mm-dd]:')
obsTime = input('Time of Observation in military [hh:mm:ss]:')
obsDateTime = obsDate + ' ' + obsTime
print(obsDateTime)

# Target info
targetname = input('Name of the target:')
tra = float(input('Target RA in degrees:'))
tdec = float(input('Target DEC in degrees:'))

center_coord = SkyCoord(ra=tra * u.deg, dec=tdec * u.deg)
center = FixedTarget(coord=center_coord, name=targetname)

plot_airmass(center,
             Breyo,
             obsDateTime,
             brightness_shading=True,
             altitude_yaxis=True)
plt.show()
示例#24
0
def observe(request, method="POST"):
    if request.POST['observing_date'] == "":
        messages.error(request, 'Please choose a date!')
    if request.POST['name'] == "":
        messages.error(request, 'Object name cannot be empty!')
    if request.POST['ra'] == "":
        messages.error(request, 'Object RA cannot be empty!')
    if request.POST['dec'] == "":
        messages.error(request, 'Object Dec cannot be empty!')

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

    observatory = None
    offset = None

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

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

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

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

    start_time = astro_set

    end_time = astro_rise
    delta_t = end_time - start_time

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

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

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

    plt.ioff()
    finder_image = plot_finder_image(target)
    finder_image[0].figure.savefig(
        'apps/project_app/static/project_app/plot_finder_image.png')
    plt.close()
    request.session['context'] = {
        "sunset": Time(sunset_here, format="iso").value,
        "sunrise": Time(sunrise_here, format="iso").value,
        "date": Time(observe_date, format="iso").value,
        "midnight": Time(midnight_here, format="iso").value,
        "site": request.POST['observatory'],
        "ra": request.POST['ra'],
        "dec": request.POST['dec'],
        "name": request.POST['name']
    }
    return redirect('/display')
def airmass():
    plot_airmass(altair, subaru, time)
    plot_airmass(vega, subaru, time)
    plt.legend(loc=1, bbox_to_anchor=(1, 1))
    plt.show()
示例#26
0
    object_set = site.target_set_time(time, obj) - 5 * u.minute
    from astroplan import download_IERS_A
    download_IERS_A()
    sunset_tonight = site.sun_set_time(time, which='nearest')

    if sunset_tonight < time:
        print("the sun has already set at this location")

    else:
        print("sunset at your selected site will be " + sunset_tonight.iso +
              " UTC")

    t.sleep(3)
    from astroplan.plots import plot_airmass
    import matplotlib.pyplot as plt
    plot_airmass(obj, site, time)
    plt.title("Visibility Chart")
    plt.legend(loc=1, bbox_to_anchor=(1, 1))
    plt.show()
    t.sleep(3)
    site.altaz(time, obj).secz
    from astroplan.plots import plot_parallactic
    plot_parallactic(obj, site, time)
    plt.legend(loc=2)
    plt.show()
    t.sleep(3)

    moon_rise = site.moon_rise_time(time)
    moon_set = site.moon_set_time(time)

    print("Moon rise will be at: " + str(moon_rise))
示例#27
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()
示例#28
0
# Object rise / set

star_rise = obs.target_rise_time(now, star)
star_set = obs.target_set_time(now, star)
print(star_name, "rise time", star_rise.iso)
print(star_name, "set  time", star_set.iso)

# Observation window
start = np.max([sunset_tonight, star_rise])
end = np.min([sunrise_tomorrow, star_set])
print(star_name, "obs_start", start.iso)
print(star_name, "obs_end  ", end.iso)

# Make Plot of airmass vs time.
fig, ax = plt.subplots()

# Time array for sunset to sunrise
times = sunset_tonight + np.linspace(0, night_length_h, 100) * u.hour
etwil = sunset_tonight + 0.5 * u.hour * np.ones(2)
mtwil = sunrise_tomorrow - 0.5 * u.hour * np.ones(2)

plot_airmass(star, obs, times, ax=ax, max_airmass=2.5)
plot_airmass(star2, obs, times, ax=ax, max_airmass=2.5)
plt.legend(shadow=True)

ax.plot_date(etwil.plot_date, [1.0, 2.5], 'red',
             alpha=0.5)  # sunset plus 1/2 hour
ax.plot_date(mtwil.plot_date, [1.0, 2.5], 'red', alpha=0.5)
plt.show()
示例#29
0
from astroplan.plots import plot_airmass

subaru = Observer.at_site('subaru')

altair = FixedTarget.from_name('Altair')
vega = FixedTarget.from_name('Vega')

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

time = Time('2015-06-16 12:00:00')
sunset_tonight = subaru.sun_set_time(time, which='nearest')
sunrise_tonight = subaru.sun_rise_time(time, which='nearest')

# Are our targets up at the appropriate time?
subaru.target_is_up(time, altair)
subaru.target_is_up(time, vega)
subaru.is_night(time)

# What are optimal observation times, in terms of air mass?
altair_rise = subaru.target_rise_time(time, altair) + 5*u.minute
altair_set = subaru.target_set_time(time, altair) - 5*u.minute

plot_airmass(altair, subaru, time) 
plot_airmass(vega, subaru, time) 
plot_airmass(deneb, subaru, time)  
plt.legend(loc=1, bbox_to_anchor=(1, 1)) 
plt.savefig('stars_vs_airmass.png', dpi=200)