def sun_moon_pos(waktu, jam): plt.rcParams['lines.markersize'] = 20 plt.rcParams['legend.markerscale'] = 0.25 plt.rcParams['grid.alpha'] = 0.5 plt.rcParams['grid.linestyle'] = 'dotted' plot_sky(moonaltaz, lokasi, waktu[jam]) plot_sky(sunaltaz, lokasi, waktu[jam]) plt.legend(loc='center left', bbox_to_anchor=(1, 0.20)) plt.figtext(0.79, 0.945, '{}, {}'.format(lokasi.name, wita(waktu[jam].value)[:16]), size=9) plt.figtext(0.79, 0.915, 'Sunrise/set {}/{}'.format( wita(sunrise.iso)[-8:-3], wita(sunset.iso)[-8:-3]), size=9) plt.figtext(0.79, 0.885, 'Moonrise/set {}/{}'.format( wita(moonrise.iso)[-8:-3], wita(moonset.iso)[-8:-3]), size=9) plt.figtext(0.79, 0.855, 'Moon illumination {:.2}'.format(moon_ill), size=9) plt.tight_layout() plt.savefig('gms_21062020/miangas/sun_moon_{}.png'.format(str(jam)), dpi=150) plt.clf() plt.rcdefaults() return jam
def show_graph(self): global plt for i in range(len(arr)): star1 = FixedTarget(coord=self.transformed[i].transform_to('fk5'), name="Star" + str(i)) plot_sky(star1, self.observer, reftime) plt.plot(self.transformed[i].alt, self.transformed[i].az, 'bo') plt.legend(loc='center left', bbox_to_anchor=(1.25, 0.5)) plt.show()
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)
def skychart_jejak(obj, waktu, nama_waktu): #c/ obj = alcen if nama_waktu == 'night': plot_sky(obj[0], lokasi, waktu, style_sheet=dark_style_sheet) plt.figtext(0.79, 0.945, '{}, {}'.format(lokasi.name, day[0].value[:10]), size=9) plt.figtext(0.79, 0.915, 'Sunset/rise {}/{}'.format( wita(sunset.iso)[-8:-3], wita(sunrise.iso)[-8:-3]), size=9) plt.figtext(0.79, 0.885, 'Moonrise/set {}/{}'.format( wita(moonrise.iso)[-8:-3], wita(moonset.iso)[-8:-3]), size=9) plt.figtext(0.79, 0.855, 'Moon ill {:.2}'.format(moon_ill), size=9) else: plot_sky(obj[0], lokasi, waktu) plt.figtext(0.75, 0.945, '{}, {}'.format(lokasi.name, day[0].value[:10]), size=9) plt.figtext(0.75, 0.915, 'Sunset/rise {}/{}'.format( wita(sunset.iso)[-8:-3], wita(sunrise.iso)[-8:-3]), size=9) plt.legend(loc='center left', bbox_to_anchor=(1, 0.20)) plt.figtext(0.78, 0.19, 'rise {}'.format(wita(obj[2][0].iso)[-8:-3]), size=9) plt.figtext(0.78, 0.16, 'set {}'.format(wita(obj[4][0].iso)[-8:-3]), size=9) plt.tight_layout() plt.show() plt.savefig('jejak/{}_{}.png'.format(obj[0].name, nama_waktu), dpi=150) plt.clf() plt.rcdefaults()
def result(request): long = request.POST.get('obsLon') lat = request.POST.get('obsLat') obsdate = request.POST.get('obsDate') obsTime = request.POST.get('obsTime') ob = ephem.Observer() ob.long = long ob.lat = lat ob.date = ephem.localtime(ephem.Date(str(obsdate) + " " + str(obsTime))) ob.elevation = 100 stars = [["65:7:30", "45:38:42"], ["25:5:31.2", "50:29:27.6"], ["91.17.27.6", "19:15:14.4"], ["158:13:1.2", "25:13:19.2"], ["224:24:7.2", "73:4:40.8"]] mandiobserver = ephem.Observer() mandiobserver.long = "31:46:31.44" mandiobserver.lat = "76.59.9.96" mandiobserver.elevation = 1000 mandiobserver.date = ephem.localtime(ephem.Date("2018/03/30 03:00:00")) new_values = [] for star in stars: ra, dec = mandiobserver.radec_of(star[0], star[1]) star1 = ephem.FixedBody() star1._ra = ra star1._dec = dec star1.compute(ob) new_values.append(star1) new_values1 = [] for value in new_values: s = [str(value.alt), str(value.az)] new_values1.append(s) context = {'values': new_values1, 'long': long, 'lat': lat} newt = TimezoneInfo(utc_offset=5.5 * u.hour) ob1 = Observer(latitude=ob.lat * u.deg, longitude=ob.long * u.deg, elevation=ob.elevation * u.m, timezone=newt) for value in new_values: starCoord = SkyCoord(ra=value.ra * u.deg, dec=value.dec * u.deg) starObj = FixedTarget(coord=starCoord) plot_sky(starObj, ob1, Time(["2018-03-30 12:00:00"])) plt.show() # plt.savefig('static/astro/images/plot.jpg') return render(request, 'astro/result.html', context)
def skychart_spesifik(obj, waktu, nama_waktu, jam): # 0 = 18:44; 1 = tambah 30' if nama_waktu == 'night': plot_sky(obj[0], lokasi, waktu[jam], style_sheet=dark_style_sheet) plot_sky(moonaltaz, lokasi, waktu[jam]) plt.figtext(0.79, 0.945, '{}, {}'.format(lokasi.name, wita(waktu[jam].value)[:16]), size=9) plt.figtext(0.79, 0.915, 'Sunset/rise {}/{}'.format( wita(sunset.iso)[-8:-3], wita(sunrise.iso)[-8:-3]), size=9) plt.figtext(0.79, 0.885, 'Moonrise/set {}/{}'.format( wita(moonrise.iso)[-8:-3], wita(moonset.iso)[-8:-3]), size=9) plt.figtext(0.79, 0.855, 'Moon ill {:.2}'.format(moon_ill), size=9) else: plot_sky(obj[0], lokasi, waktu[jam]) plot_sky(sunaltaz, lokasi, waktu[jam]) plt.figtext(0.75, 0.945, '{}, {}'.format(lokasi.name, wita(waktu[jam].value)[:16]), size=9) plt.figtext(0.75, 0.915, 'Sunset/rise {}/{}'.format( wita(sunset.iso)[-8:-3], wita(sunrise.iso)[-8:-3]), size=9) plt.legend(loc='center left', bbox_to_anchor=(1, 0.20)) plt.figtext(0.78, 0.17, 'rise {}'.format(wita(obj[2][0].iso)[-8:-3]), size=9) plt.figtext(0.78, 0.14, 'set {}'.format(wita(obj[4][0].iso)[-8:-3]), size=9) plt.tight_layout() plt.savefig('spesifik/{}_{}_{}.png'.format(obj[0].name, nama_waktu, str(jam)), dpi=150) plt.clf() plt.rcdefaults() return jam
def __single_target_path_plot__(self,observer,times,target,tidx,total): cmap = cm.Set1 ax = plot_sky(target,observer,times,\ style_kwargs=dict(color=cmap(float(tidx)/total),label=target.name)) fontP = FontProperties() fontP.set_size('small') lgd = plt.legend(prop=fontP,loc='center left',bbox_to_anchor=(1.25, 0.5), ncol=2) art = [lgd] fig = plt.gcf() fig.savefig('{0}{1}.png'.format(T_DIR,target.name), additional_artists=art, dpi=100,\ bbox_inches='tight') fig.clear()
def draw(self, observer, time=None): ''' Draw the plot to the screen Parameters ---------- observer: `~astroplan.Observer` Astroplan observer object determining the location of the map time: `~astropy.time.Time` (optional) Time of the observation. If no time is given, it will default to the current local time ''' if (time is None): time = Time(datetime.now()) for key, val in self.objects.items(): plot_sky(val, observer, time, warn_below_horizon=False) return plt
def __multi_target_plot__(self,observer,time,targets,name): cmap = cm.Set1 for i, t in enumerate(targets): ax = plot_sky(t,observer,time,\ style_kwargs=dict(color=cmap(float(i)/len(T)),label=t.name)) fontP = FontProperties() fontP.set_size('small') lgd = plt.legend(prop=fontP,loc='center left',bbox_to_anchor=(1.25, 0.5), ncol=2) art = [lgd] fig = plt.gcf() fig.savefig('{0}{1}.png'.format(G_DIR,name), additional_artists=art, dpi=100,\ bbox_inches='tight') fig.clear()
def plot_night_movement(): #when obj rise and set altair_rise = subaru.target_rise_time(time, altair) + 5 * u.minute altair_set = subaru.target_set_time(time, altair) - 5 * u.minute vega_rise = subaru.target_rise_time(time, vega) + 5 * u.minute vega_set = subaru.target_set_time(time, vega) - 5 * u.minute # we will make starting time for bouth obj and ending time too all_up_start = np.max([altair_rise, vega_rise]) all_up_end = np.min([altair_set, vega_set]) # sun rise and set for specific observer sunrise_tonight = subaru.sun_rise_time(time, which='nearest') sunset_tonight = subaru.sun_set_time(time, which='nearest') # when obseration starts and ends start = np.max([sunset_tonight, all_up_start]) end = np.min([sunrise_tonight, all_up_end]) time_window = start + (end - start) * np.linspace(0, 1, 10) altair_style = {'color': 'r'} plot_sky(altair, subaru, time_window, style_kwargs=altair_style) plot_sky(vega, subaru, time_window) plt.legend(loc='center left', bbox_to_anchor=(1.25, 0.5)) plt.show()
visible_time = start + (end - start) * np.linspace(0, 1, 20) print("Altitude of Moon during observation: " + str(visible_time)) t.sleep(3) from astroplan.plots import plot_sky obj_style = {'color': 'r'} ''' plot_sky(obj, site, start, style_kwargs=obj_style) plt.title("Object position at start of observing window") plt.legend(loc='center left', bbox_to_anchor=(1.25, 0.5)) plt.show() plot_sky(obj, site, end, style_kwargs=obj_style) plt.legend(loc='center left', bbox_to_anchor=(1.25, 0.5)) plt.title("Object position at end of observing window") plt.show() ''' time_window = start + (end - start) * np.linspace(0, 1, 10) plot_sky(obj, site, time_window, style_kwargs=obj_style) plt.title("Object movement over observing window duration") plt.legend(loc='center left', bbox_to_anchor=(1.25, 0.5)) plt.show() else: print( "Your object isn't visible from the site selected and therefore planning cannot take place." ) t.sleep(3)
#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') #fig.tight_layout() fig.savefig('../Figures/TargetPlot.pdf',dpi=300) plt.show() for t in targets: print t
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')
x3C286= FixedTarget(name='3C286', coord=coordinates) x3C286_style={'color':'red'} coords="J052109.90+163822.1" coordinates= SkyCoord(coords,frame='icrs',unit=(u.hour, u.deg)) x3C138=FixedTarget(name='3C138',coord=coordinates) x3C138_style={'color':'blue'} coords="17:45:40.0383-29:00:28.069" coordinates= SkyCoord(coords,frame='icrs',unit=(u.hour, u.deg)) pks1742=FixedTarget(name='PKS1742-289',coord=coordinates) pks1742_style={'color':'green'} # Note that this is not a scalar. observe_time = Time(['2015-11-15 05:30:00']) plot_sky(pks1934, observer, observe_time,style_kwargs=pks1934_style) plot_sky(x3C286,observer, observe_time,style_kwargs=x3C286_style) plot_sky(x3C138,observer, observe_time,style_kwargs=x3C138_style) plot_sky(pks1742, observer, observe_time,style_kwargs=pks1742_style) # Note that you don't need this code block to produce the plot. # It reduces the plot size for the documentation. ax = plt.gca() box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.75, box.height * 0.75]) plt.legend(loc='center left', bbox_to_anchor=(1.25, 0.5)) plt.show()
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')
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
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()
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()
location = EarthLocation.from_geodetic(longitude * u.deg, latitude * u.deg, 1000 * u.m) observer = Observer(location=location, name="observer", timezone="Asia/Kolkata") # observer = Observer(longitude=longitude*u.deg, latitude=latitude*u.deg, elevation=1000*u.m, name="Observer1", timezone="Asia/Kolkata") observer_time = Time(['2018-03-31 12:00:00']) star1_style = {'color': 'k'} star2_style = {'color': 'g'} star3_style = {'color': 'r'} star4_style = {'color': 'c'} star5_style = {'color': 'b'} plot_sky(star1_1, observer, observer_time, style_kwargs=star1_style) plot_sky(star2_2, observer, observer_time, style_kwargs=star2_style) plot_sky(star3_3, observer, observer_time, style_kwargs=star3_style) plot_sky(star4_4, observer, observer_time, style_kwargs=star4_style) plot_sky(star5_5, observer, observer_time, style_kwargs=star5_style) plt.legend(loc='center left', bbox_to_anchor=(1.25, 0.5)) plt.savefig('fig1.png') plt.show() for i in range(1, 12): starz_coord = SkyCoord(ra=star_ra * u.deg, dec=star_dec * u.deg) star = FixedTarget(coord=starz_coord, name="star" + str(i)) star_ra = star_ra + step_ra #star_dec = star_dec + step_dec plot_sky(starz_coord, observer, observer_time, style_kwargs=star1_style)
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')
def eop(self): IERS_A_in_cache() # astroplan.get_IERS_A_or_workaround() iers.conf.auto_download = False iers.conf.auto_max_age = None now = Time.now() longitude = '78d57m53s' latitude = '32d46m44s' elevation = 4500 * u.m location = EarthLocation.from_geodetic(longitude, latitude, elevation) iaohanle = Observer(location=location, timezone='Asia/Kolkata', name="IAO", description="IAO Hanle telescopes") iaohanle # Calculating the sunset, midnight and sunrise times for our observatory sunset_iao = iaohanle.sun_set_time(now, which='nearest') eve_twil_iao = iaohanle.twilight_evening_astronomical(now, which='nearest') midnight_iao = iaohanle.midnight(now, which='next') morn_twil_iao = iaohanle.twilight_morning_astronomical(now, which='next') sunrise_iao = iaohanle.sun_rise_time(now, which='next') moon_rise = iaohanle.moon_rise_time(eve_twil_iao, which='nearest') moon_set = iaohanle.moon_set_time(now, which='nearest') # moon_alt = iaohanle.moon_altaz(now).alt # moon_az = iaohanle.moon_altaz(now).az #lst_now = iaohanle.local_sidereal_time(now) #lst_mid = iaohanle.local_sidereal_time(midnight_iao) #print("LST at IAO now is {0:.2f}".format(lst_now)) #print("LST at IAO at local midnight will be {0:.2f}".format(lst_mid)) Automation.moon_strength = moon_illumination(midnight_iao) observing_time = (morn_twil_iao - eve_twil_iao).to(u.h) #print("Total Night hours at IAO tonight {0:.1f} ".format(observing_time)) img = Image.new('RGB', (850, 320), color=(0, 0, 0)) fnt = ImageFont.truetype( '/var/lib/defoma/gs.d/dirs/fonts/DejaVuSerif.ttf', 15) d = ImageDraw.Draw(img) d.text((10, 11), "IAO Hanle Coordinates: " + str(iaohanle), font=fnt, fill=(255, 255, 255)) d.text((10, 71), "Moon Illumination Strength : " + str(moon_illumination(midnight_iao)), font=fnt, fill=(255, 255, 255)) d.text((10, 101), "Sunset : " + Time(sunset_iao, out_subfmt='date_hms').iso + " UTC", font=fnt, fill=(255, 255, 255)) d.text((10, 131), "Astronomical evening twilight : " + Time(eve_twil_iao, out_subfmt='date_hms').iso + " UTC", font=fnt, fill=(255, 255, 255)) d.text((10, 161), "Astronomical morning twilight : " + Time(morn_twil_iao, out_subfmt='date_hms').iso + " UTC", font=fnt, fill=(255, 255, 255)) d.text((10, 191), "Sunrise : " + Time(sunrise_iao, out_subfmt='date_hms').iso + " UTC", font=fnt, fill=(255, 255, 255)) d.text((10, 221), "Moon Rise : " + Time(moon_rise, out_subfmt='date_hms').iso + " UTC", font=fnt, fill=(255, 255, 255)) d.text((10, 251), "Moon Set : " + Time(moon_set, out_subfmt='date_hms').iso + " UTC", font=fnt, fill=(255, 255, 255)) d.text((10, 281), "Total Astronomical hours tonight : " + str(observing_time), font=fnt, fill=(255, 255, 255)) img.save('tonight.png') img.close() t_start = eve_twil_iao t_end = morn_twil_iao # We can turn solar system objects into 'pseudo-fixed' targets to plan observations mercury_midnight = FixedTarget(name='Mercury', coord=get_body('mercury', midnight_iao)) mercury_midnight.coord venus_midnight = FixedTarget(name='Venus', coord=get_body('venus', midnight_iao)) venus_midnight.coord uranus_midnight = FixedTarget(name='Uranus', coord=get_body('uranus', midnight_iao)) uranus_midnight.coord neptune_midnight = FixedTarget(name='Neptune', coord=get_body('neptune', midnight_iao)) neptune_midnight.coord saturn_midnight = FixedTarget(name='Saturn', coord=get_body('saturn', midnight_iao)) saturn_midnight.coord jupiter_midnight = FixedTarget(name='Jupiter', coord=get_body('jupiter', midnight_iao)) jupiter_midnight.coord mars_midnight = FixedTarget(name='Mars', coord=get_body('mars', midnight_iao)) mars_midnight.coord targets = [ mercury_midnight, venus_midnight, mars_midnight, jupiter_midnight, saturn_midnight, uranus_midnight, neptune_midnight ] targets #for target in targets: #print(iaohanle.target_rise_time(now, target, which='next', horizon=10 * u.deg).iso) # iaohanle.altaz(now, targets[0]) # print(iaohanle.target_rise_time(now, target, which='next', horizon=10 * u.deg).iso) # iaohanle.altaz(now, targets[0]) times = (t_start - 0.5 * u.h) + (t_end - t_start + 1 * u.h) * np.linspace(0.0, 1.0, 20) for target in targets: plot_sky(target, iaohanle, times) plt.legend(loc=[1.0, 0]) plt.xlabel('Planets motion tonight') # plt.ylim(4,0.5) # plt.legend() plt.savefig('planets_motion.png') plt.close() # plt.legend(loc=[1.1,0]) coords1 = SkyCoord( '15h58m3s', '-18d10m0.0s', frame='icrs') # coordinates of Andromeda Galaxy (M32) tt1 = FixedTarget(name='Moon', coord=coords1) tt1.coord t_observe = t_start + (t_end - t_start) * np.linspace(0.0, 1.0, 20) plot_sky(tt1, iaohanle, t_observe) plt.xlabel('Moon motion tonight') plt.savefig('moon_motion.png') plt.close() if (eve_twil_iao <= now): Automation.eve_twilight_flag = 1 Automation.mor_twilight_flag = 0 Automation.moon_setting_flag = 0 elif (morn_twil_iao <= now): Automation.eve_twilight_flag = 0 Automation.mor_twilight_flag = 1 Automation.moon_setting_flag = 0 elif (Automation.moon_strength > 0.30): if (moon_rise <= now): Automation.eve_twilight_flag = 0 Automation.mor_twilight_flag = 0 Automation.moon_setting_flag = 1 elif (moon_set <= now): Automation.eve_twilight_flag = 1 Automation.mor_twilight_flag = 0 Automation.moon_setting_flag = 0
subaru = Observer.at_site('subaru') altair = FixedTarget.from_name('Altair') vega = FixedTarget.from_name('Vega') altair_style = {'color': 'r'} deneb_style = {'color': 'g'} time = Time('2015-06-16 12:00:00') coordinates = SkyCoord('20h41m25.9s', '+45d16m49.3s', frame='icrs') deneb = FixedTarget(name='Deneb', coord=coordinates) altair_rise = subaru.target_rise_time(time, altair) + 5 * u.minute altair_set = subaru.target_set_time(time, altair) - 5 * u.minute vega_rise = subaru.target_rise_time(time, vega) + 5 * u.minute vega_set = subaru.target_set_time(time, vega) - 5 * u.minute deneb_rise = subaru.target_rise_time(time, deneb) + 5 * u.minute deneb_set = subaru.target_set_time(time, deneb) - 5 * u.minute sunset_tonight = subaru.sun_set_time(time, which='nearest') all_up_start = np.max([altair_rise, vega_rise, deneb_rise]) start = np.max([sunset_tonight, all_up_start]) plot_sky(altair, subaru, start, style_kwargs=altair_style) plot_sky(vega, subaru, start) plot_sky(deneb, subaru, start, style_kwargs=deneb_style) plt.legend(loc='center left', bbox_to_anchor=(1.25, 0.5)) plt.show()