class tnsVis(): """ Object visability methods for calculating airmass, lengths of observable time for transient name server objects for different observing locations and dates """ def __init__(self, lat, lon, elevation, ra, dec, discDate, airmassConstraint=2): self.airmassConstraint = airmassConstraint self.altConstraint = math.degrees(math.asin(1 / self.airmassConstraint)) self.location = EarthLocation(lat=lat, lon=lon, height=elevation * u.m) self.discDate = discDate self.observer = Observer(location=self.location, name="LT") self.target = SkyCoord(ra=ra, dec=dec, unit=(u.hourangle, u.deg)) self.constraints = [ AirmassConstraint(self.airmassConstraint), AtNightConstraint.twilight_astronomical() ] print("Discovery Date :", discDate.value) def time_since_discovery(self): """ Returns astropy Time delta object of time since Discovery to time now """ return Time.now() - self.discDate def visible_time(self, date): """ For the evening after the date, specify the visible time within the constraintsself. Not really working at present """ # Find astronomical times for next night darkStart = self.observer.twilight_evening_astronomical(date, which=u'next') darkEnd = self.observer.twilight_morning_astronomical(darkStart, which=u'next') # Find rise and set times riseTime = self.observer.target_rise_time(date, self.target, which=u'next', horizon=self.altConstraint * u.deg) setTime = self.observer.target_set_time(date, self.target, which=u'next', horizon=self.altConstraint * u.deg) if (darkStart.value < riseTime.value) and (darkEnd.value > setTime.value): print("During night") return setTime - riseTime elif (darkStart.value > riseTime.value) and (darkEnd.value > setTime.value): print("Darkstart") elif (darkStart.value < riseTime.value) and (darkEnd.value < setTime.value): print("Darkend") elif (darkStart.value > riseTime.value) and (darkEnd.value < setTime.value): print("DarkstartandEnd") else: print("No Constraints matched!!") def reportDate(self, name): """ Input ATel name and scrape TNS web page for value using regex report the in astropy datetime format?? """ # Find AT or SN name. Seems best to take off 1st 3 characters objectAT = name[3:] print(objectAT) # Pull html down try: page = urllib.request.urlopen( ('https://wis-tns.weizmann.ac.il/object/' + objectAT)) bytes = page.read() text = bytes.decode("utf8") except urllib.error.HTTPError: return ('notFound') # Find the time_received value pattern = re.compile( r'class=\"cell-time_received\">\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d') match = re.findall(pattern, text) if match: # get down to YYYY-MM-DD HH:MM:SS value pattern = re.compile(r'\d\d\d\d\-\d\d-\d\d \d\d:\d\d:\d\d') reportDate = re.findall(pattern, match[0])[0] return reportDate else: return 'notFound' def reportDelay(self, date): """ Input the report date as an astropy Time object return the difference between the discovery and report in units of days """ reportDelay = date - self.discDate print("report : ", date) print("discdate : ", self.discDate) print("report.Delay : ", reportDelay) return reportDelay def plot(self, date): """ Produce plot of the object visability for date Modified from https://docs.astropy.org/en/stable/generated/examples/coordinates/plot_obs-planning.html """ import matplotlib.pyplot as plt from astropy.visualization import astropy_mpl_style plt.style.use(astropy_mpl_style) midnight = self.observer.midnight(date, which='next') delta_midnight = np.linspace(-2, 10, 100) * u.hour frame_night = AltAz(obstime=midnight + delta_midnight, location=self.location) targetaltazs_night = self.target.transform_to(frame_night) # Use `~astropy.coordinates.get_sun` to find the location of the Sun at 1000 from astropy.coordinates import get_sun delta_midnight = np.linspace(-12, 12, 1000) * u.hour times = midnight + delta_midnight frame = AltAz(obstime=times, location=self.location) sunaltazs = get_sun(times).transform_to(frame) # Do the same with `~astropy.coordinates.get_moon` to find when the moon is # up. Be aware that this will need to download a 10MB file from the internet # to get a precise location of the moon. from astropy.coordinates import get_moon moon = get_moon(times) moonaltazs = moon.transform_to(frame) ############################################################################## # Find the alt,az coordinates of M33 at those same times: targetaltazs = self.target.transform_to(frame) ############################################################################## # Make a beautiful figure illustrating nighttime and the altitudes of M33 and # the Sun over that time: plt.plot(delta_midnight, sunaltazs.alt, color='r', label='Sun') plt.plot(delta_midnight, moonaltazs.alt, color=[0.75] * 3, ls='--', label='Moon') plt.scatter(delta_midnight, targetaltazs.alt, c=targetaltazs.az, label='Target', lw=0, s=8, cmap='viridis') plt.fill_between(delta_midnight.to('hr').value, 0, 90, sunaltazs.alt < -0 * u.deg, color='0.5', zorder=0) plt.fill_between(delta_midnight.to('hr').value, 0, 90, sunaltazs.alt < -18 * u.deg, color='k', zorder=0) plt.hlines(self.altConstraint, -12, 12, colors='red', linestyles='dotted', lw=1) plt.colorbar().set_label('Azimuth [deg]') plt.legend(loc='upper left') plt.xlim(-12, 12) plt.xticks(np.arange(13) * 2 - 12) plt.ylim(0, 90) plt.xlabel('Hours from Local Midnight') plt.ylabel('Altitude [deg]') plt.show() def get_info(self, date): """ Prints useful info for a given time, for debugging mainly Alt - Az of target Alt - Az of sun Alt - Az of moon ..... """ return def objVis(self): """ Checks if transit is in between twilight hours. If not return error Returns the amount of time the object is above given airmass """ objVis = is_observable(self.constraints, self.observer, self.target, time_range=(self.discDate, self.discDate + 1 * u.day))[0] return objVis
# morning (civil) twilight obs.twilight_morning_civil(time_obs) # morning (astronomical) twilight obs.twilight_morning_astronomical(time_obs) # what is the moon illumination? # returns a float, which is percentage of the moon illuminated obs.moon_illumination(time_obs) # what is the moon altitude and azimuth? obs.moon_altaz(time_obs) # Other sun-related convenience functions: obs.noon(time_obs, which='nearest') obs.midnight(time_obs, which='nearest') # ============== # Target objects # ============== ''' A target object defines a single observation target, with coordinates and an optional name. ''' from astroplan import FixedTarget # Define a target. from astropy.coordinates import SkyCoord t1 = FixedTarget(name='Polaris', coord=SkyCoord('02h31m49.09s', '+89d15m50.8s', frame='icrs'))
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
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 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()
def post_save_night(sender, **kwargs): if not kwargs.get('raw', False): night = kwargs['instance'] location = night.location astropy_time = Time(datetime.combine(night.date, time(12))) astropy_time_delta = TimeDelta(600.0, format='sec') # guess if the moon is waxing or waning if ephem.next_full_moon(night.date) - ephem.Date(night.date) < ephem.Date(night.date) - ephem.previous_full_moon(night.date): waxing_moon = True else: waxing_moon = False observer = Observer( longitude=location.longitude, latitude=location.latitude, timezone='UTC' ) moon_phase = observer.moon_phase(astropy_time).value if waxing_moon: moon_phase = (math.pi - moon_phase) / (2 * math.pi) else: moon_phase = (math.pi + moon_phase) / (2 * math.pi) times = { 'sunset': observer.sun_set_time(astropy_time, which='next'), 'civil_dusk': observer.twilight_evening_civil(astropy_time, which='next'), 'nautical_dusk': observer.twilight_evening_nautical(astropy_time, which='next'), 'astronomical_dusk': observer.twilight_evening_astronomical(astropy_time, which='next'), 'midnight': observer.midnight(astropy_time, which='next'), 'astronomical_dawn': observer.twilight_morning_astronomical(astropy_time, which='next'), 'nautical_dawn': observer.twilight_morning_nautical(astropy_time, which='next'), 'civil_dawn': observer.twilight_morning_civil(astropy_time, which='next'), 'sunrise': observer.sun_rise_time(astropy_time, which='next'), } night.mjd = int(astropy_time.mjd) + 1 night.moon_phase = moon_phase for key in times: if times[key].jd > 0: setattr(night, key, times[key].to_datetime(timezone=utc)) post_save.disconnect(post_save_night, sender=sender) night.save() post_save.connect(post_save_night, sender=sender) moon_positions = [] for i in range(144): moon_altitude = observer.moon_altaz(astropy_time).alt.degree moon_position = MoonPosition( timestamp=astropy_time.to_datetime(timezone=utc), altitude=moon_altitude, location=location ) moon_positions.append(moon_position) astropy_time += astropy_time_delta MoonPosition.objects.bulk_create(moon_positions)
time = (time_datetime + timedelta(hours=8)).strftime( '%d-%m-%Y %H:%M:%S') #GMS return time # longitude = '123d54m35.3160s' #pusat sains tilong # latitude = '-10d3m53.0784s' #pusat sains tilong longitude = '102d11m12.32s' #miangas latitude = '1d03m02s' #miangas elevation = 100 * u.m location = EarthLocation.from_geodetic(longitude, latitude, elevation) # lokasi = Observer(name='Tilong',location=location,timezone=timezone('Asia/Makassar')) # lokasi pengamat lokasi = Observer(name='Siak', location=location) #GMS time = Time('2019-12-26') #UTC midnight = Time(lokasi.midnight(time).iso) delta_md = np.linspace(-5, 5, 22) * u.hour win_time = midnight + delta_md night = win_time # day = (midnight + 12*u.hour) + delta_md day = (midnight + 12 * u.hour) + np.linspace(0, 3, 30) * u.hour # GMS op = pd.read_csv('op.csv', index_col='nama') ra = op.ra dec = op.dec sunset = lokasi.sun_set_time(time) sunrise = lokasi.sun_rise_time(time) moonrise = lokasi.moon_rise_time(time) moonset = lokasi.moon_set_time(time) moon_ill = lokasi.moon_illumination(time) moonaltaz = lokasi.moon_altaz(time)
# morning (civil) twilight obs.morning_civil(date=time_obs) # morning (astronomical) twilight obs.morning_astronomical(date=time_obs) # what is the moon illumination? # returns a float, which is percentage of the moon illuminated obs.moon_illumination(date=time_obs) # what is the moon altitude and azimuth? obs.moon_altaz(date=time_obs) # Other sun-related convenience functions: obs.noon(date=time_obs, which='nearest') obs.midnight(date=time_obs, which='nearest') # ============== # Target objects # ============== ''' A target object defines a single observation target, with coordinates and an optional name. ''' from astroplan import FixedTarget, airmass_plot # Define a target. t1 = FixedTarget(name='Polaris', ra='02:31:49.09', dec='+89:15:50.8') # initializing from astropy entities directly from astropy.coordinates import SkyCoord