def sanity_nutationExample(self): """ Sanity of example for `nutate` """ from PyAstronomy import pyasl import datetime import numpy as np # Convert calendar date into JD # use the datetime package jd = datetime.datetime(2013, 4, 16) jd = pyasl.jdcnv(jd) print "Nutation for the date." res = pyasl.nutate(jd) print "JD = " + str(jd) + ", Longitude = " + str(res[0]) + \ ", Obliquity = " + str(res[1]) # Get nutation for an array of JDs. startjd = datetime.datetime(2013, 4, 16) endjd = datetime.datetime(2013, 6, 16) startjd = pyasl.jdcnv(startjd) endjd = pyasl.jdcnv(endjd) jds = np.arange(startjd, endjd, .5) print print "Plot the results" res = pyasl.nutate(jds, plot=False) print "Longitude: ", res[0] print "Obliquity: ", res[1]
def sanity_sunposExample(self): """ Sanity of example for `sunpos`. """ import numpy as np from PyAstronomy import pyasl import datetime # Convert calendar date into JD # use the datetime package jd = datetime.datetime(2013, 4, 16) jd = pyasl.jdcnv(jd) print "JD = " + str(jd) pos = pyasl.sunpos(jd, full_output=True) print "Coordinates of the Sun (ra, dec): %g, %g" % (pos[1], pos[2]) print "Solar elongation = %g and obliquity = %g" % (pos[3], pos[4]) # Get the Sun's RA and DEC values for a period of time. startjd = datetime.datetime(2013, 4, 16) endjd = datetime.datetime(2013, 6, 16) # Convert into Julian dates startjd = pyasl.jdcnv(startjd) endjd = pyasl.jdcnv(endjd) print pos = pyasl.sunpos(startjd, end_jd=endjd, jd_steps=10, plot=False, full_output=True) for i in range(len(pos[0])): print "At JD = %g: ra = %g, dec = %g" % (pos[0][i], pos[1][i], pos[2][i])
def sanity_conutateExample(self): """ Sanity of example for `co_nutate`. """ from PyAstronomy import pyasl import datetime import numpy as np # Convert calendar date into JD # use the datetime package jd = datetime.datetime(2013, 4, 16) jd = pyasl.jdcnv(jd) # Specify RA and DEC (degrees) ra = 10. dec = 30. print "Get change in RA and DEC due to Earth's nutation for JD = " \ + str(jd) print pyasl.co_nutate(jd, ra, dec) print print "Get change for several RAs and DECs for the same JD" ra = np.arange(0.,160.,20.) dec = np.arange(-80.,80.,20.) res = pyasl.co_nutate(np.repeat(jd, ra.size), ra, dec) print res[0], res[1] print print "Get change for several RAs and DECs for different JDs" jds = np.arange(jd,jd+ra.size,1) res = pyasl.co_nutate(jds, ra, dec) print "JD delta(RA) delta(DEC)" for i in range(ra.size): print "%12.5f %8.5f %8.5f" % (jds[i], res[0][i], res[1][i])
def sanity_aberrationExample(self): """ Sanity of example for `aberration`. """ from PyAstronomy import pyasl import datetime import numpy as np # Convert calendar date to JD # use the datetime package jd = datetime.datetime(2013, 4, 16) jd = pyasl.jdcnv(jd) # Specify RA and DEC ra = 10. dec = 30. print "Get change in RA and DEC due to annual aberration" print " for JD = " + str(jd) + ":", \ np.ravel(pyasl.co_aberration(jd, ra, dec)) print print "Get change for several RAs and DECs for the same JD" ra = np.arange(10.,50.,10.) dec = np.arange(30.,70.,10.) res = pyasl.co_aberration(np.repeat(jd, ra.size), ra, dec) print res[0], res[1] print print "Get change for several RAs and DECs for different JDs" jds = np.arange(jd,jd+ra.size,1) res = pyasl.co_aberration(jds, ra, dec) print "JD delta(RA) delta(DEC)" for i in range(ra.size): print "%12.5f %8.5f %8.5f" %(jds[i], res[0][i], res[1][i])
def sun_set_rise(start_date, lon, lat, sundown): from PyAstronomy import pyasl jd_set = pyasl.jdcnv(start_date) # find Julian date sunpos = pyasl.sunpos(jd_set) sun_ra, sun_dec = sunpos[1][0], sunpos[2][0] try: set, rise = get_set_rise(start_date, sun_ra / 15, sun_dec, lon, lat, h=sundown) set_date_final = start_date + datetime.timedelta(seconds=set * 60 * 60) rise_date_final = start_date + datetime.timedelta(seconds=rise * 60 * 60) # TODO we should actually adjust for RA and DEC at rise / set return set_date_final, rise_date_final except: pass
def sanity_ETD_compare(self): """ Check transit of Wasp-7 on Oct. 03, 2018, with ETD result. """ from PyAstronomy import pyasl import datetime as dt # Get the data for WASP-7 from NEXA data base nexa = pyasl.NasaExoplanetArchive() dat = nexa.selectByPlanetName("Wasp-7 b") # Convert July 14th, 2018, 10pm to a Julian date d = dt.datetime(2018, 7, 14, 22) jd = pyasl.jdcnv(d) # Calculate transit data for transits within 100 days starting # form July 14th, 2018. dat = pyasl.transitTimes(jd, jd+100., dat, nexaInput=True, \ observatory="esoparanal", obsOffset=0.0, \ minAltitude=10.0) # Choose first transit d = dat[2] print d mt = d["Obs cal"][1] self.assertEqual(mt[0], 2018, "Year does not match") self.assertEqual(mt[1], 10, "Month does not match") self.assertEqual(mt[2], 3, "Day does not match") self.assertAlmostEqual(mt[3], 3.+53./60., delta=5./60., msg="Hour does not match") self.assertAlmostEqual(d["Star alt"][0], 67., msg="Stellar altitude does not match", delta=2.0) self.assertAlmostEqual(d["Star alt"][1], 47., msg="Stellar altitude does not match", delta=2.0) self.assertAlmostEqual(d["Star alt"][2], 27., msg="Stellar altitude does not match", delta=2.0) # Transit duration is specified in Nexa (therefore, 15 min uncertainty here) self.assertAlmostEqual((d["Transit jd"][2] - d["Transit jd"][0])*24.0, \ 3.567 , delta=15./60., msg = "Duration does not match")
def get_ESO_period(period): """ Return the JD of start and end of ESO period """ assert isinstance(period, str) or isinstance(period, int) P = int(period) getjd = lambda y,m,d: pyasl.jdcnv(dt.datetime(y, m, d)) jd_start, jd_end = [getjd(*d) for d in ESO_periods[P]] return jd_start, jd_end
def get_ESO_period(period): """ Return the JD of start and end of ESO period """ assert isinstance(period, str) or isinstance(period, int) P = int(period) getjd = lambda y, m, d: pyasl.jdcnv(dt.datetime(y, m, d)) jd_start, jd_end = [getjd(*d) for d in ESO_periods[P]] return jd_start, jd_end
def moon_get_moon_phase(date): from PyAstronomy import pyasl import numpy as np # Convert calendar date to JD # using the datetime package jd = date jd = pyasl.jdcnv(jd) mp = pyasl.moonphase(jd) return mp[0]
def get_gmst_utc_diff(date): # input: UTC datetime # get gmst/utc difference for a given date # you can then get lst by subtracting EAST longitude jd = pyasl.jdcnv(date) # find Julian date for given date in UTC gmst_dec = get_gmst(jd) # get gmst in decimal format date_dec = date.hour + date.minute / 60 + date.second / 3600 # get UTC for date in decimal format gmst_utc_diff = gmst_dec - date_dec # get gmst - utc difference if gmst_utc_diff < 0: gmst_utc_diff += 24 return gmst_utc_diff
def moon_get_moon_phase_range(start_date, end_date): from PyAstronomy import pyasl import numpy as np from datetime import datetime # Convert calendar date to JD # using the datetime package jd = start_date jd = pyasl.jdcnv(jd) no_of_days = (end_date - start_date).days jd = np.arange(jd, jd + no_of_days + 1, 1) mp = pyasl.moonphase(jd) return mp
def sanity_example(self): """ Checking example of transitTimes """ from PyAstronomy import pyasl import datetime as dt # Get the data for WASP-7 from NEXA data base nexa = pyasl.NasaExoplanetArchive() dat = nexa.selectByPlanetName("Wasp-7 b") # Convert July 14th, 2018, 10pm to a Julian date d = dt.datetime(2018, 7, 14, 22) jd = pyasl.jdcnv(d) # Calculate transit data for transits between July 14th and # July 24th, 2018. dat = pyasl.transitTimes(jd, jd+10.0, dat, nexaInput=True, \ observatory="eso", obsOffset=1./24.)
def sanity_eq2horExample(self): """ Sanity of example for `eq2hor` """ from PyAstronomy import pyasl import matplotlib.pylab as plt import datetime import numpy as np # Convert calender date to JD # use the datetime package jd = datetime.datetime(2013, 4, 16) jd = pyasl.jdcnv(jd) # Specifiy RA and DEC ra = 10. dec = 30. print print "Get horizontal coordinates (alt, az, ha) from JD, RA," print " and DEC for the Hamburger Sternwarte" print pyasl.eq2hor(jd, ra, dec, observatory="HS") print print "From a list of Julian dates ..." jds = np.arange(jd,jd+1,.2) ras = np.zeros(jds.size) + ra decs = np.zeros(jds.size) + dec alt, az, ha = pyasl.eq2hor(jds, ras, decs, lon=-70.4042, lat=-24.6272, alt=2635.) for i in range(alt.size): print "JD = %g : alt = % g, az = % g, ha = % g" % (jds[i], alt[i], az[i], ha[i]) print print "For one object and different times at the VLT..." jds = np.arange(jd-.25,jd+.25,.01) ras = np.zeros(jds.size) + 130. decs = np.zeros(jds.size) - 30. res = pyasl.eq2hor(jds, ras, decs, lon=-70.4042, lat=-24.6272, alt=2635.) plt.plot(jds, res[0]) plt.xlabel("Julian date") plt.ylabel("Altitude [deg]")
def OnCompute(self, event): #Tornar a variável text global------------------------------------------------------------------------------------ global text #Chamar as variáveis escolhidas na interface pelo usuário -------------------------------------------------------- mar = self.ma.GetValue() sax = self.sax.GetValue() di = self.Selected1.GetValue() df = self.Selected2.GetValue() #Informar ao usuário com uma mensagem de erro caso as datas não forem preenchidas---------------------------------- if df == 'Select Stop Date': wx.StaticText(self, 1, 'Error Stop Date', (200, 530)) return (self) elif di == 'Select Start Date': wx.StaticText(self, 1, 'Error Start Date', (200, 530)) return (self) elif df == 'Select Stop Date' and di == 'Select Start Date': wx.StaticText(self, 1, 'Error Start and Stop Date ', (200, 530)) return (self) #Transformar o formato de data escolhido na interface para dia-mês-ano-------------------------------------------- a = datetime.datetime.strptime(di, "%d-%m-%Y").date() b = datetime.datetime.strptime(df, "%d-%m-%Y").date() #Informar o usuário com uma mensagem de erro caso a data inicial for maior que a final----------------------------- if (b > a) == True: a = a b = b else: wx.StaticText(self, 1, 'Error: Stop Date < Star Date', (200, 530)) return (self) #Definir latitude e longitude aos marégrafos---------------------------------------------------------------------- #Selecionar as três primeiras letras do nome dos marégrafos para associar ao link--------------------------------- if mar == "Fortaleza": lat = "03°42’52.55”S" lon = "38°28’36.54”O" lk = "FOR" elif mar == "Imbituba": lat = "28°13’52.30”S" lon = "48°39’2.06”O" lk = "IMB" elif mar == "Macae": lat = "22°23’08” S" lon = "41°46’10” O" lk = "MAC" elif mar == "Salvador": lat = "12°58’26.29”S" lon = "38°31’1.95” O" lk = "SAL" elif mar == "Santana": lat = "00°03’41” S" lon = "51°10’04” O" lk = "SAN" #Informar uma mensagem de erro caso o usuario nao informar um marégrafo------------------------------------------- else: wx.StaticText(self, 1, 'Select one Tide Gauge', (200, 530)) return (self) #Extrair e deszipar os dados maregraficos do site do IBGE--------------------------------------------------------- mar = str(mar) dia = hora = valor = [] for dt in rrule(DAILY, dtstart=a, until=b): ymd = dt.strftime("%y%m%d") md = dt.strftime("%d%m") link = ( 'https://geoftp.ibge.gov.br/informacoes_sobre_posicionamento_geodesico/rmpg/dados/%s/%s%s.zip' % (md, lk, ymd)) url = urlopen(link) zf = ZipFile(StringIO(url.read())) #Ler e unir os dados de diferetes arquivos-------------------------------------------------------------------- for item in zf.namelist(): dads = StringIO(zf.read(item)) dads = np.genfromtxt(dads, dtype=None) dads = np.char.replace(dads, ',', '.') dia = np.append(dia, [dads[:, 0]]) hora = np.append(hora, [dads[:, 1]]) valor = np.append(valor, [dads[:, 2]]) dads = np.concatenate([[dia], [hora], [valor]]) dads = np.transpose(dads) #Filtrar os dados disponíveis num intervalo de 5 minutos---------------------------------------------------------- dia2 = hora2 = valor2 = [] for hor in range(0, 24, 1): for minu in range(0, 56, 5): d = np.delete( dads, np.where((dads[:, 1]) != ('%.2d:%.2d:00' % (hor, minu)))[0], 0) dia2 = np.append(dia2, [d[:, 0]]) hora2 = np.append(hora2, [d[:, 1]]) valor2 = np.append(valor2, [d[:, 2]]) d = np.concatenate([[dia2], [hora2], [valor2]]) d1 = np.transpose(d) dia3 = hora3 = valor3 = [] for dtt in rrule(DAILY, dtstart=a, until=b): dtt = dtt.strftime("%d/%m/%Y") d = np.delete(d1, np.where((d1[:, 0]) <> ('%s' % (dtt)))[0], 0) dia3 = np.append(dia3, [d[:, 0]]) hora3 = np.append(hora3, [d[:, 1]]) valor3 = np.append(valor3, [d[:, 2]]) d = np.concatenate([[dia3], [hora3], [valor3]]) d = np.transpose(d) #Coeficientes Fm do filtro descrita em PUGH (1987,p.416)----------------------------------------------------------- coef = np.matrix([[ 0.0648148, 0.0643225, 0.0628604, 0.0604728, 0.0572315, 0.0532331, 0.0485954, 0.0434525, 0.0379505, 0.0322412, 0.0264773, 0.0208063, 0.0153661, 0.0102800, 0.0056529, 0.0015685, -0.0019127, -0.0047544, -0.0069445, -0.0084938, -0.0094346, -0.0098173, -0.0097074, -0.0091818, -0.0083247, -0.0072233, -0.0059642, -0.0046296, -0.0032942, -0.0020225, -0.0008672, 0.0001321, 0.0009493, 0.0015716, 0.0019984, 0.0022398, 0.0023148, 0.0022492, 0.0020729, 0.0018178, 0.0015155, 0.0011954, 0.0008830, 0.0005986, 0.0003568, 0.0001662, 0.0000294, -0.0000560, -0.0000970, -0.0001032, -0.0000862, -0.0000578, -0.0000288, -0.0000077, 0.0000000 ]]) coef = np.transpose(coef) l = len(d) - 288 v1 = v2 = dat = tim = jul = julday = datenum = datatemp = [] # Primeira parte da equação (x1) de filtragem descrita em PUGH (1987,p.416)------------------------------------------------ for j in range(288, l, 12): data = str(d[j, 0]) time = str(d[j, 1]) x1 = np.multiply(float(coef[0, 0]), float(d[j, 2])) dat = np.append(dat, data) tim = np.append(tim, time) v1 = np.append(v1, x1) # Segunda parte da equação (x2) de filtragem descrita em PUGH (1987,p.416)------------------------------------ for i in range(1, 55, 1): x2 = np.multiply(float(coef[i, 0]), (float(d[(j + i), 2]) + float(d[(j - i), 2]))) v2 = np.append(v2, x2) v1 = np.transpose(np.array(v1)) v2 = np.transpose(np.array([v2])) vv2 = [] for n in range(0, len(v2), 54): m = n + 53 vv2 = np.append(vv2, np.sum(v2[n:m, :1])) vv2 = np.transpose(np.array(vv2)) val = v1 + vv2 for y in range(0, (len(tim)), 1): datt = np.matrix(dat) timm = np.matrix(tim) day, month, year = (int(x) for x in (datt[0, y]).split('/')) hour, minute, secund = (int(x) for x in (timm[0, y]).split(':')) dt = datetime.datetime(year, month, day, hour, minute, secund) datenum = np.append(datenum, mdates.date2num(dt)) julday = np.append(julday, [pyasl.jdcnv(dt)]) julday = np.transpose(np.array([julday])) datenum = np.transpose(np.array(datenum)) #Formatar o arquivo txt------------------------------------------------------------------------------------------- col_data = {'Date': dat, 'Time': tim, 'SeeLevel': val} text = pd.DataFrame(data=col_data) pd.set_option('max_rows', len(text)) text = text[['Date', 'Time', 'SeeLevel']] text = text.to_string(index=False) #%matplotlib notebook f, axs = plt.subplots(1, 1, figsize=(15, 5)) plt.xticks(rotation=85) ax = plt.gca() ttil = ( '\n Sea Level obtained from %s Tide Gauge\n Lat: %s | Long: %s (SIRGAS 2000)\n' % (mar, lat, lon)) #Definir o eixo X em Dia Juliano ou em Data do calendário e plotar o gráfico-------------------------------------- if sax == 'Calendar Date': ax.xaxis_date() xfmt = mdates.DateFormatter('%d-%m-%y %H:%M:%S') ax.xaxis.set_major_formatter(xfmt) ax.plot(datenum, val, color='r', linestyle='-', linewidth=1) ax.set(xlabel='Time', ylabel='Sea Level (m)', title=(ttil.decode('utf-8'))) plt.gcf().autofmt_xdate() plt.grid() plt.show() elif sax == 'Julian Date': ax.plot(julday, val, color='r', linestyle='-', linewidth=1) ax.set(xlabel='Julian Date', ylabel='Sea Level (m)', title=(ttil.decode('utf-8'))) plt.gcf().autofmt_xdate() plt.grid() plt.show() #Informar o usuário com uma mensagem de erro caso o usuario nao escolher uma configuração de data para o eixo X---- else: wx.StaticText(self, 1, 'Select one X axis', (200, 530)) return (self) self.Destroy() self.Salve = MainWindow(wx.Frame) self.Salve.Show()
def StarObsPlot(year=None, targets=None, observatory=None, period=None, hover=False, sunless_hours=None, remove_watermark=False): """ Plot the visibility of target. Parameters ---------- year: int The year for which to calculate the visibility. targets: list List of targets. Each target should be a dictionary with keys 'name' and 'coord'. The key 'name' is a string, 'coord' is a SkyCoord object. observatory: string Name of the observatory that pyasl.observatory can resolve. Basically, any of pyasl.listObservatories().keys() period: string, optional ESO period for which to calculate the visibility. Overrides `year`. hover: boolean, optional If True, color visibility lines when mouse over. sunless_hours: float, optional If not None, plot sunless hours above this airmass """ from mpl_toolkits.axes_grid1 import host_subplot from matplotlib.ticker import MultipleLocator from matplotlib.font_manager import FontProperties from matplotlib import rcParams rcParams['xtick.major.pad'] = 12 font0 = FontProperties() font1 = font0.copy() font0.set_family('sans-serif') font0.set_weight('light') font1.set_family('sans-serif') font1.set_weight('medium') # set the observatory if isinstance(observatory, dict): obs = observatory else: obs = pyasl.observatory(observatory) fig = plt.figure(figsize=(15,10)) fig.subplots_adjust(left=0.07, right=0.8, bottom=0.15, top=0.88) # watermak if not remove_watermark: fig.text(0.99, 0.99, 'Created with\ngithub.com/iastro-pt/ObservationTools', fontsize=10, color='gray', ha='right', va='top', alpha=0.5) # plotting sunless hours? shmode = False if sunless_hours is not None: shmode = True # limit in airmass (assumed plane-parallel atm) shairmass = sunless_hours # correspoing limit in altitude from scipy.optimize import bisect shalt = 90 - bisect(lambda alt: pyasl.airmassPP(alt) - shairmass, 0, 89) if shmode: fig.subplots_adjust(hspace=0.35) ax = host_subplot(211) axsh = host_subplot(212) plt.text(0.5, 0.47, "- sunless hours above airmass {:.1f} - \n".format(shairmass), transform=fig.transFigure, ha='center', va='bottom', fontsize=12) plt.text(0.5, 0.465, "the thick line above the curves represents the total sunless hours "\ "for each day of the year", transform=fig.transFigure, ha='center', va='bottom', fontsize=10) else: ax = host_subplot(111) for n, target in enumerate(targets): target_coord = target['coord'] target_ra = target_coord.ra.deg target_dec = target_coord.dec.deg if period is not None: jd_start, jd_end = get_ESO_period(period) else: jd_start = pyasl.jdcnv(dt.datetime(year, 1, 1)) jd_end = pyasl.jdcnv(dt.datetime(year, 12, 31)) jdbinsize = 1 # every day each_day = np.arange(jd_start, jd_end, jdbinsize) jds = [] ## calculate the mid-dark times sun = ephem.Sun() for day in each_day: date_formatted = '/'.join([str(i) for i in pyasl.daycnv(day)[:-1]]) s = ephem.Observer(); s.date = date_formatted; s.lat = ':'.join([str(i) for i in decdeg2dms(obs['latitude'])]) s.lon = ':'.join([str(i) for i in decdeg2dms(obs['longitude'])]) jds.append(ephem.julian_date(s.next_antitransit(sun))) jds = np.array(jds) # Get JD floating point jdsub = jds - np.floor(jds[0]) # Get alt/az of object altaz = pyasl.eq2hor(jds, np.ones_like(jds)*target_ra, np.ones_like(jds)*target_dec, \ lon=obs['longitude'], lat=obs['latitude'], alt=obs['altitude']) ax.plot( jdsub, altaz[0], '-', color='k') # label for each target plabel = "[{0:2d}] {1!s}".format(n+1, target['name']) # number of target at the top of the curve ind_label = np.argmax(altaz[0]) # or at the bottom if the top is too close to the corners # if jdsub[ind_label] < 5 or jdsub[ind_label] > jdsub.max()-5: # ind_label = np.argmin(altaz[0]) ax.text( jdsub[ind_label], altaz[0][ind_label], str(n+1), color="b", fontsize=14, \ fontproperties=font1, va="bottom", ha="center") if n+1 == 29: # too many? ax.text(1.1, 1.0-float(n+1)*0.04, "too many targets", ha="left", va="top", transform=ax.transAxes, \ fontsize=10, fontproperties=font0, color="r") else: ax.text(1.1, 1.0-float(n+1)*0.04, plabel, ha="left", va="top", transform=ax.transAxes, \ fontsize=12, fontproperties=font0, color="b") if shmode: sunless_hours = [] for day in each_day: date_formatted = '/'.join([str(i) for i in pyasl.daycnv(day)[:-1]]) s = ephem.Observer(); s.date = date_formatted; s.lat = ':'.join([str(i) for i in decdeg2dms(obs['latitude'])]) s.lon = ':'.join([str(i) for i in decdeg2dms(obs['longitude'])]) # hours from sunrise to sunset td = pyasl.daycnv(ephem.julian_date(s.next_setting(sun)), mode='dt') \ - pyasl.daycnv(ephem.julian_date(s.next_rising(sun)), mode='dt') sunless_hours.append(24 - td.total_seconds() / 3600) days = each_day - np.floor(each_day[0]) axsh.plot(days, sunless_hours, '-', color='k', lw=2) axsh.set(ylim=(0, 15), yticks=range(1,15), ylabel='Useful hours', yticklabels=[r'${}^{{\rm h}}$'.format(n) for n in range(1,15)]) ax.text(1.1, 1.03, "List of targets", ha="left", va="top", transform=ax.transAxes, \ fontsize=12, fontproperties=font0, color="b") axrange = ax.get_xlim() if period is None: months = range(1, 13) ndays = [0] + [calendar.monthrange(date, m)[1] for m in months] ax.set_xlim([0, 366]) ax.set_xticks(np.cumsum(ndays)[:-1] + (np.array(ndays)/2.)[1:]) ax.set_xticklabels(map(calendar.month_abbr.__getitem__, months), fontsize=10) if shmode: axsh.set_xlim([0, 366]) axsh.set_xticks(np.cumsum(ndays)[:-1] + (np.array(ndays)/2.)[1:]) axsh.set_xticklabels(map(calendar.month_abbr.__getitem__, months), fontsize=10) else: if int(period) % 2 == 0: # even ESO period, Oct -> Mar months = [10, 11, 12, 1, 2, 3] ndays = [0] + [calendar.monthrange(date, m)[1] for m in months] ax.set_xlim([0, 181]) ax.set_xticks(np.cumsum(ndays)[:-1] + (np.array(ndays)/2.)[1:]) ax.set_xticklabels(map(calendar.month_abbr.__getitem__, months), fontsize=10) if shmode: axsh.set_xlim([0, 181]) axsh.set_xticks(np.cumsum(ndays)[:-1] + (np.array(ndays)/2.)[1:]) axsh.set_xticklabels(map(calendar.month_abbr.__getitem__, months), fontsize=10) else: # odd ESO period, Apr -> Sep months = range(4, 10) ndays = [0] + [calendar.monthrange(date, m)[1] for m in months] ax.set_xlim([0, 182]) ax.set_xticks(np.cumsum(ndays)[:-1] + (np.array(ndays)/2.)[1:]) ax.set_xticklabels(map(calendar.month_abbr.__getitem__, months), fontsize=10) if shmode: axsh.set_xlim([0, 182]) axsh.set_xticks(np.cumsum(ndays)[:-1] + (np.array(ndays)/2.)[1:]) axsh.set_xticklabels(map(calendar.month_abbr.__getitem__, months), fontsize=10) if axrange[1]-axrange[0] <= 1.0: jdhours = np.arange(0,3,1.0/24.) utchours = (np.arange(0,72,dtype=int)+12)%24 else: jdhours = np.arange(0,3,1.0/12.) utchours = (np.arange(0,72, 2, dtype=int)+12)%24 # Make ax2 responsible for "top" axis and "right" axis ax2 = ax.twin() # Set upper x ticks ax2.set_xticks(np.cumsum(ndays)) ax2.set_xlabel("Day") # plane-parallel airmass airmass_ang = np.arange(10, 81, 5) geo_airmass = pyasl.airmass.airmassPP(airmass_ang)[::-1] ax2.set_yticks(airmass_ang) airmassformat = [] for t in range(geo_airmass.size): airmassformat.append("{0:2.2f}".format(geo_airmass[t])) ax2.set_yticklabels(airmassformat)#, rotation=90) ax2.set_ylabel("Relative airmass", labelpad=32) ax2.tick_params(axis="y", pad=6, labelsize=8) plt.text(1.02,-0.04, "Plane-parallel", transform=ax.transAxes, ha='left', \ va='top', fontsize=10, rotation=90) ax22 = ax.twin() ax22.set_xticklabels([]) ax22.set_frame_on(True) ax22.patch.set_visible(False) ax22.yaxis.set_ticks_position('right') ax22.yaxis.set_label_position('right') ax22.spines['right'].set_position(('outward', 30)) ax22.spines['right'].set_color('k') ax22.spines['right'].set_visible(True) airmass2 = list(map(lambda ang: pyasl.airmass.airmassSpherical(90. - ang, obs['altitude']), airmass_ang)) ax22.set_yticks(airmass_ang) airmassformat = [] for t in range(len(airmass2)): airmassformat.append(" {0:2.2f}".format(airmass2[t])) ax22.set_yticklabels(airmassformat, rotation=90) ax22.tick_params(axis="y", pad=8, labelsize=8) plt.text(1.05,-0.04, "Spherical+Alt", transform=ax.transAxes, ha='left', va='top', \ fontsize=10, rotation=90) ax.set_ylim([0, 91]) ax.yaxis.set_major_locator(MultipleLocator(15)) ax.yaxis.set_minor_locator(MultipleLocator(5)) yticks = ax.get_yticks() ytickformat = [] for t in range(yticks.size): ytickformat.append(str(int(yticks[t]))+r"$^\circ$") ax.set_yticklabels(ytickformat, fontsize=16) ax.set_ylabel("Altitude", fontsize=18) yticksminor = ax.get_yticks(minor=True) ymind = np.where( yticksminor % 15. != 0. )[0] yticksminor = yticksminor[ymind] ax.set_yticks(yticksminor, minor=True) m_ytickformat = [] for t in range(yticksminor.size): m_ytickformat.append(str(int(yticksminor[t]))+r"$^\circ$") ax.set_yticklabels(m_ytickformat, minor=True) ax.set_ylim([0, 91]) ax.yaxis.grid(color='gray', linestyle='dashed') ax.yaxis.grid(color='gray', which="minor", linestyle='dotted') ax2.xaxis.grid(color='gray', linestyle='dotted') if period is not None: plt.text(0.5, 0.95, "Visibility over P{0!s}\n - altitudes at mid-dark time -".format(period), transform=fig.transFigure, ha='center', va='bottom', fontsize=12) else: plt.text(0.5, 0.95, "Visibility over {0!s}\n - altitudes at mid-dark time -".format(date), transform=fig.transFigure, ha='center', va='bottom', fontsize=12) obsco = "Obs coord.: {0:8.4f}$^\circ$, {1:8.4f}$^\circ$, {2:4f} m".format(obs['longitude'], obs['latitude'], obs['altitude']) plt.text(0.01,0.97, obsco, transform=fig.transFigure, ha='left', va='center', fontsize=10) plt.text(0.01,0.95, obs['name'], transform=fig.transFigure, ha='left', va='center', fontsize=10) # interactive! if hover: main_axis = fig.axes[0] all_lines = set(main_axis.get_lines()) def on_plot_hover(event): for line in main_axis.get_lines(): if line.contains(event)[0]: line.set_color('red') # make this line red # and all others black all_other_lines = all_lines - set([line]) for other_line in all_other_lines: other_line.set_color('black') fig.canvas.draw_idle() fig.canvas.mpl_connect('motion_notify_event', on_plot_hover) return fig
def VisibilityPlot(date=None, targets=None, observatory=None, plotLegend=True, showMoonDist=True, print2file=False, remove_watermark=False): """ Plot the visibility of target. Parameters ---------- date: datetime The date for which to calculate the visibility. targets: list List of targets. Each target should be a dictionary with keys 'name' and 'coord'. The key 'name' is aa string, 'coord' is a SkyCoord object. observatory: string Name of the observatory that pyasl.observatory can resolve. Basically, any of pyasl.listObservatories().keys() plotLegend: boolean, optional If True (default), show a legend. showMoonDist : boolean, optional If True (default), the Moon distance will be shown. """ from mpl_toolkits.axes_grid1 import host_subplot from matplotlib.ticker import MultipleLocator from matplotlib.font_manager import FontProperties from matplotlib import rcParams rcParams['xtick.major.pad'] = 12 if isinstance(observatory, dict): obs = observatory else: obs = pyasl.observatory(observatory) # observer = ephem.Observer() # observer.pressure = 0 # observer.horizon = '-0:34' # observer.lat, observer.lon = obs['latitude'], obs['longitude'] # observer.date = date # print(observer.date) # print(observer.previous_rising(ephem.Sun())) # print(observer.next_setting(ephem.Sun())) # print(observer.previous_rising(ephem.Moon())) # print(observer.next_setting(ephem.Moon())) # observer.horizon = '-6' # noon = observer.next_transit(ephem.Sun()) # print(noon) # print(observer.previous_rising(ephem.Sun(), start=noon, use_center=True)) # print() fig = plt.figure(figsize=(15,10)) fig.subplots_adjust(left=0.07, right=0.8, bottom=0.15, top=0.88) # watermak if not remove_watermark: fig.text(0.99, 0.99, 'Created with\ngithub.com/iastro-pt/ObservationTools', fontsize=10, color='gray', ha='right', va='top', alpha=0.5) ax = host_subplot(111) font0 = FontProperties() font1 = font0.copy() font0.set_family('sans-serif') font0.set_weight('light') font1.set_family('sans-serif') font1.set_weight('medium') for n, target in enumerate(targets): target_coord = target['coord'] target_ra = target_coord.ra.deg target_dec = target_coord.dec.deg # JD array jdbinsize = 1.0/24./20. # jds = np.arange(allData[n]["Obs jd"][0], allData[n]["Obs jd"][2], jdbinsize) jd = pyasl.jdcnv(date) jd_start = pyasl.jdcnv(date)-0.5 jd_end = pyasl.jdcnv(date)+0.5 jds = np.arange(jd_start, jd_end, jdbinsize) # Get JD floating point jdsub = jds - np.floor(jds[0]) # Get alt/az of object altaz = pyasl.eq2hor(jds, np.ones(jds.size)*target_ra, np.ones(jds.size)*target_dec, \ lon=obs['longitude'], lat=obs['latitude'], alt=obs['altitude']) # Get alt/az of Sun sun_position = pyasl.sunpos(jd) sun_ra, sun_dec = sun_position[1], sun_position[2] sunpos_altaz = pyasl.eq2hor(jds, np.ones(jds.size)*sun_ra, np.ones(jds.size)*sun_dec, \ lon=obs['longitude'], lat=obs['latitude'], alt=obs['altitude']) # Define plot label plabel = "[{0:2d}] {1!s}".format(n+1, target['name']) # Find periods of: day, twilight, and night day = np.where( sunpos_altaz[0] >= 0. )[0] twi = np.where( np.logical_and(sunpos_altaz[0] > -18., sunpos_altaz[0] < 0.) )[0] night = np.where( sunpos_altaz[0] <= -18. )[0] if (len(day) == 0) and (len(twi) == 0) and (len(night) == 0): print print("VisibilityPlot - no points to draw") print mpos = pyasl.moonpos(jds) # mpha = pyasl.moonphase(jds) # mpos_altaz = pyasl.eq2hor(jds, mpos[0], mpos[1], # lon=obs['longitude'], lat=obs['latitude'], alt=obs['altitude']) # moonind = np.where( mpos_altaz[0] > 0. )[0] if showMoonDist: mdist = pyasl.getAngDist(mpos[0], mpos[1], np.ones(jds.size)*target_ra, \ np.ones(jds.size)*target_dec) bindist = int((2.0/24.)/jdbinsize) firstbin = np.random.randint(0,bindist) for mp in range(0, int(len(jds)/bindist)): bind = firstbin+mp*bindist if altaz[0][bind]-1. < 5.: continue ax.text(jdsub[bind], altaz[0][bind]-1., str(int(mdist[bind]))+r"$^\circ$", ha="center", va="top", \ fontsize=8, stretch='ultra-condensed', fontproperties=font0, alpha=1.) if len(twi) > 1: # There are points in twilight linebreak = np.where( (jdsub[twi][1:]-jdsub[twi][:-1]) > 2.0*jdbinsize)[0] if len(linebreak) > 0: plotrjd = np.insert(jdsub[twi], linebreak+1, np.nan) plotdat = np.insert(altaz[0][twi], linebreak+1, np.nan) ax.plot( plotrjd, plotdat, "-", color='#BEBEBE', linewidth=1.5) else: ax.plot( jdsub[twi], altaz[0][twi], "-", color='#BEBEBE', linewidth=1.5) ax.plot( jdsub[night], altaz[0][night], '.k', label=plabel) ax.plot( jdsub[day], altaz[0][day], '.', color='#FDB813') altmax = np.argmax(altaz[0]) ax.text( jdsub[altmax], altaz[0][altmax], str(n+1), color="b", fontsize=14, \ fontproperties=font1, va="bottom", ha="center") if n+1 == 29: ax.text( 1.1, 1.0-float(n+1)*0.04, "too many targets", ha="left", va="top", transform=ax.transAxes, \ fontsize=10, fontproperties=font0, color="r") else: ax.text( 1.1, 1.0-float(n+1)*0.04, plabel, ha="left", va="top", transform=ax.transAxes, \ fontsize=12, fontproperties=font0, color="b") ax.text( 1.1, 1.03, "List of targets", ha="left", va="top", transform=ax.transAxes, \ fontsize=12, fontproperties=font0, color="b") axrange = ax.get_xlim() ax.set_xlabel("UT [hours]") if axrange[1]-axrange[0] <= 1.0: jdhours = np.arange(0,3,1.0/24.) utchours = (np.arange(0,72,dtype=int)+12)%24 else: jdhours = np.arange(0,3,1.0/12.) utchours = (np.arange(0,72, 2, dtype=int)+12)%24 ax.set_xticks(jdhours) ax.set_xlim(axrange) ax.set_xticklabels(utchours, fontsize=18) # Make ax2 responsible for "top" axis and "right" axis ax2 = ax.twin() # Set upper x ticks ax2.set_xticks(jdhours) ax2.set_xticklabels(utchours, fontsize=18) ax2.set_xlabel("UT [hours]") # Horizon angle for airmass airmass_ang = np.arange(5.,90.,5.) geo_airmass = pyasl.airmass.airmassPP(90.-airmass_ang) ax2.set_yticks(airmass_ang) airmassformat = [] for t in range(geo_airmass.size): airmassformat.append("{0:2.2f}".format(geo_airmass[t])) ax2.set_yticklabels(airmassformat, rotation=90) ax2.set_ylabel("Relative airmass", labelpad=32) ax2.tick_params(axis="y", pad=10, labelsize=10) plt.text(1.015,-0.04, "Plane-parallel", transform=ax.transAxes, ha='left', \ va='top', fontsize=10, rotation=90) ax22 = ax.twin() ax22.set_xticklabels([]) ax22.set_frame_on(True) ax22.patch.set_visible(False) ax22.yaxis.set_ticks_position('right') ax22.yaxis.set_label_position('right') ax22.spines['right'].set_position(('outward', 25)) ax22.spines['right'].set_color('k') ax22.spines['right'].set_visible(True) airmass2 = list(map(lambda ang: pyasl.airmass.airmassSpherical(90. - ang, obs['altitude']), airmass_ang)) ax22.set_yticks(airmass_ang) airmassformat = [] for t in airmass2: airmassformat.append("{0:2.2f}".format(t)) ax22.set_yticklabels(airmassformat, rotation=90) ax22.tick_params(axis="y", pad=10, labelsize=10) plt.text(1.045,-0.04, "Spherical+Alt", transform=ax.transAxes, ha='left', va='top', \ fontsize=10, rotation=90) ax3 = ax.twiny() ax3.set_frame_on(True) ax3.patch.set_visible(False) ax3.xaxis.set_ticks_position('bottom') ax3.xaxis.set_label_position('bottom') ax3.spines['bottom'].set_position(('outward', 50)) ax3.spines['bottom'].set_color('k') ax3.spines['bottom'].set_visible(True) ltime, ldiff = pyasl.localtime.localTime(utchours, np.repeat(obs['longitude'], len(utchours))) jdltime = jdhours - ldiff/24. ax3.set_xticks(jdltime) ax3.set_xticklabels(utchours) ax3.set_xlim([axrange[0],axrange[1]]) ax3.set_xlabel("Local time [hours]") ax.set_ylim([0, 91]) ax.yaxis.set_major_locator(MultipleLocator(15)) ax.yaxis.set_minor_locator(MultipleLocator(5)) yticks = ax.get_yticks() ytickformat = [] for t in range(yticks.size): ytickformat.append(str(int(yticks[t]))+r"$^\circ$") ax.set_yticklabels(ytickformat, fontsize=16) ax.set_ylabel("Altitude", fontsize=18) yticksminor = ax.get_yticks(minor=True) ymind = np.where( yticksminor % 15. != 0. )[0] yticksminor = yticksminor[ymind] ax.set_yticks(yticksminor, minor=True) m_ytickformat = [] for t in range(yticksminor.size): m_ytickformat.append(str(int(yticksminor[t]))+r"$^\circ$") ax.set_yticklabels(m_ytickformat, minor=True) ax.set_ylim([0, 91]) ax.yaxis.grid(color='gray', linestyle='dashed') ax.yaxis.grid(color='gray', which="minor", linestyle='dotted') ax2.xaxis.grid(color='gray', linestyle='dotted') plt.text(0.5,0.95,"Visibility on {0!s}".format(date.date()), \ transform=fig.transFigure, ha='center', va='bottom', fontsize=20) if plotLegend: line1 = matplotlib.lines.Line2D((0,0),(1,1), color='#FDB813', linestyle="-", linewidth=2) line2 = matplotlib.lines.Line2D((0,0),(1,1), color='#BEBEBE', linestyle="-", linewidth=2) line3 = matplotlib.lines.Line2D((0,0),(1,1), color='k', linestyle="-", linewidth=2) lgd2 = plt.legend((line1,line2,line3),("day","twilight","night",), \ bbox_to_anchor=(0.88, 0.13), loc='best', borderaxespad=0.,prop={'size':12}, fancybox=True) lgd2.get_frame().set_alpha(.5) obsco = "Obs coord.: {0:8.4f}$^\circ$, {1:8.4f}$^\circ$, {2:4f} m".format(obs['longitude'], obs['latitude'], obs['altitude']) plt.text(0.01,0.97, obsco, transform=fig.transFigure, ha='left', va='center', fontsize=10) plt.text(0.01,0.95, obs['name'], transform=fig.transFigure, ha='left', va='center', fontsize=10) return fig
def obsblock(kic,date=[2014,6,18,0]): print " " str1 = "%2d/%2d/%4d" % (date[1],date[2],date[0]) print 'KIC '+str(kic)+'; UT '+str1 file = get_kic_file(kic) object1 = get_info(file,secondary=False) object2 = get_info(file,secondary=True) kic,path = get_kic(file) d = dt.datetime(date[0],date[1],date[2],date[3]) jd = pyasl.jdcnv(d) ### Primary ### # time after mid-eclipse at JD t1 = np.mod(jd - object1["T0"],object1["orbPer"]) # phase of eclipse at JD p1 = np.mod(jd - object1["T0"],object1["orbPer"])/object1["orbPer"] # Time until ingress t1ing = (object1["orbPer"]-object1["Tdur"]/2.0)-t1 # Time until egress t1egr = (object1["orbPer"]+object1["Tdur"]/2.0)-t1 if (t1ing >= 0 and t1ing <= 0.75) or (t1egr >= 0 and t1egr <= 0.75): print "Potential conflict with primary eclipse:" # Does an ingress happen in the "night" window? if t1ing >= 0 and t1ing <= 0.75: jd1ing = t1ing + jd y,m,d,h = pyasl.daycnv(jd1ing) str1 = "%2d/%2d/%4d" % (m,d,y) hour = dec2sex(h) stri = "%2d:%2d:%.2f" % hour # Observe before the start of ingress print '... observe before UT '+stri else: pass #print 'No primary eclipse conflict' if t1egr >= 0 and t1egr <= 0.75: jd1egr = t1egr + jd y,m,d,h = pyasl.daycnv(jd1egr) str1 = "%2d/%2d/%4d" % (m,d,y) hour = dec2sex(h) stre = "%2d:%2d:%.2f" % hour print '... observe after UT '+stre else: pass ### Secondary ### # time after mid-eclipse at JD t2 = np.mod(jd - object2["T0"],object2["orbPer"]) # phase of eclipse at JD p2 = np.mod(jd - object2["T0"],object2["orbPer"])/object2["orbPer"] # Time until ingress t2ing = (object2["orbPer"]-object2["Tdur"]/2.0)-t2 # Time until egress t2egr = (object2["orbPer"]+object2["Tdur"]/2.0)-t2 if (t2ing >= 0 and t2ing <= 0.75) or (t2egr >= 0 and t2egr <= 0.75): print "Potential conflict with seconary eclipse:" # Does an ingress happen in the "night" window? if t2ing >= 0 and t2ing <= 0.75: jd2ing = t2ing + jd y,m,d,h = pyasl.daycnv(jd2ing) str2 = "%2d/%2d/%4d" % (m,d,y) hour = dec2sex(h) stri = "%2d:%2d:%.2f" % hour # Observe before the start of ingress print '... observe before UT '+stri else: pass #print 'No primary eclipse conflict' if t2egr >= 0 and t2egr <= 0.75: jd2egr = t2egr + jd y,m,d,h = pyasl.daycnv(jd2egr) str2 = "%2d/%2d/%4d" % (m,d,y) hour = dec2sex(h) stre = "%2d:%2d:%.2f" % hour print '... observe after UT '+stre else: pass
def object_etime(object, date=[2015, 9, 15, 0], ndays=60, secondary=False, observatory='Hopkins', minalt=20.0, twilight='nautical', buffer=1.0, write=True): if observatory != None: otag = '_' + observatory else: latstr = '+34 08 10.0' lonstr = '-118 07 34.5' alt = 100.0 otag = '' if observatory == 'Lowell': latstr = '+35 12 10.0' lonstr = '-111 39 52.0' alt = 2210.0 if observatory == 'Hopkins': latstr = '+31 40 49.35' lonstr = '-110 52 44.60' alt = 2210.0 if observatory == 'Caltech': latstr = '+34 08 10.0' lonstr = '-118 07 34.5' alt = 100.0 if observatory == 'Keck': latstr = '19 49 34.9' lonstr = '-155 28 30.04' alt = 4145.0 lat = angcor(latstr).d lon = angcor(lonstr).d + 360 d = dt.datetime(date[0], date[1], date[2], date[3]) jd = pyasl.jdcnv(d) if secondary != False: tag = '_sec' else: tag = '_prim' fn = object['plName'] + otag + tag + '_obs.dat' rmfile = glob.glob(fn) buffer /= 24.0 if rmfile: os.remove(rmfile[0]) rmfile = [] if write == True: dat = pyasl.transitTimes(jd, jd+ndays, object, lon=lon, lat=lat, alt=alt, \ obsOffset=buffer,minAltitude=minalt, \ showTwilight=twilight,fileOutput=fn) else: dat = pyasl.transitTimes(jd, jd+ndays, object, lon=lon, lat=lat, alt=alt, \ obsOffset=buffer,minAltitude=minalt, \ showTwilight=twilight) if dat: if write == True: pyasl.transitVisibilityPlot(dat, markTransit=True, print2file=True) if observatory != None: fold = 'transVis-' + object["plName"] + '.png' rmfile = glob.glob(fold) if rmfile: os.remove(rmfile[0]) fn = object["plName"] + tag + '.png' os.rename(fold, fn) else: fn = object["plName"] + otag + tag + '.png' rmfile = glob.glob(fn) if rmfile: os.remove(rmfile[0]) shutil.move(fn, path) else: pyasl.transitVisibilityPlot(dat, markTransit=True, print2file=False) else: print "No eclipses found!"
def obsblock(kic, date=[2014, 6, 18, 0]): print " " str1 = "%2d/%2d/%4d" % (date[1], date[2], date[0]) print 'KIC ' + str(kic) + '; UT ' + str1 file = get_kic_file(kic) object1 = get_info(file, secondary=False) object2 = get_info(file, secondary=True) kic, path = get_kic(file) d = dt.datetime(date[0], date[1], date[2], date[3]) jd = pyasl.jdcnv(d) ### Primary ### # time after mid-eclipse at JD t1 = np.mod(jd - object1["T0"], object1["orbPer"]) # phase of eclipse at JD p1 = np.mod(jd - object1["T0"], object1["orbPer"]) / object1["orbPer"] # Time until ingress t1ing = (object1["orbPer"] - object1["Tdur"] / 2.0) - t1 # Time until egress t1egr = (object1["orbPer"] + object1["Tdur"] / 2.0) - t1 if (t1ing >= 0 and t1ing <= 0.75) or (t1egr >= 0 and t1egr <= 0.75): print "Potential conflict with primary eclipse:" # Does an ingress happen in the "night" window? if t1ing >= 0 and t1ing <= 0.75: jd1ing = t1ing + jd y, m, d, h = pyasl.daycnv(jd1ing) str1 = "%2d/%2d/%4d" % (m, d, y) hour = dec2sex(h) stri = "%2d:%2d:%.2f" % hour # Observe before the start of ingress print '... observe before UT ' + stri else: pass #print 'No primary eclipse conflict' if t1egr >= 0 and t1egr <= 0.75: jd1egr = t1egr + jd y, m, d, h = pyasl.daycnv(jd1egr) str1 = "%2d/%2d/%4d" % (m, d, y) hour = dec2sex(h) stre = "%2d:%2d:%.2f" % hour print '... observe after UT ' + stre else: pass ### Secondary ### # time after mid-eclipse at JD t2 = np.mod(jd - object2["T0"], object2["orbPer"]) # phase of eclipse at JD p2 = np.mod(jd - object2["T0"], object2["orbPer"]) / object2["orbPer"] # Time until ingress t2ing = (object2["orbPer"] - object2["Tdur"] / 2.0) - t2 # Time until egress t2egr = (object2["orbPer"] + object2["Tdur"] / 2.0) - t2 if (t2ing >= 0 and t2ing <= 0.75) or (t2egr >= 0 and t2egr <= 0.75): print "Potential conflict with seconary eclipse:" # Does an ingress happen in the "night" window? if t2ing >= 0 and t2ing <= 0.75: jd2ing = t2ing + jd y, m, d, h = pyasl.daycnv(jd2ing) str2 = "%2d/%2d/%4d" % (m, d, y) hour = dec2sex(h) stri = "%2d:%2d:%.2f" % hour # Observe before the start of ingress print '... observe before UT ' + stri else: pass #print 'No primary eclipse conflict' if t2egr >= 0 and t2egr <= 0.75: jd2egr = t2egr + jd y, m, d, h = pyasl.daycnv(jd2egr) str2 = "%2d/%2d/%4d" % (m, d, y) hour = dec2sex(h) stre = "%2d:%2d:%.2f" % hour print '... observe after UT ' + stre else: pass
def object_etime(object,date=[2015,9,15,0],ndays=60,secondary=False, observatory='Hopkins',minalt=20.0, twilight='nautical',buffer=1.0,write=True): if observatory != None: otag = '_'+observatory else: latstr = '+34 08 10.0' lonstr = '-118 07 34.5' alt = 100.0 otag = '' if observatory == 'Lowell': latstr = '+35 12 10.0' lonstr = '-111 39 52.0' alt = 2210.0 if observatory == 'Hopkins': latstr = '+31 40 49.35' lonstr = '-110 52 44.60' alt = 2210.0 if observatory == 'Caltech': latstr = '+34 08 10.0' lonstr = '-118 07 34.5' alt = 100.0 if observatory == 'Keck': latstr = '19 49 34.9' lonstr = '-155 28 30.04' alt = 4145.0 lat = angcor(latstr).d lon = angcor(lonstr).d + 360 d = dt.datetime(date[0],date[1],date[2],date[3]) jd = pyasl.jdcnv(d) if secondary != False: tag = '_sec' else: tag = '_prim' fn = object['plName']+otag+tag+'_obs.dat' rmfile = glob.glob(fn) buffer /= 24.0 if rmfile: os.remove(rmfile[0]) rmfile = [] if write == True: dat = pyasl.transitTimes(jd, jd+ndays, object, lon=lon, lat=lat, alt=alt, \ obsOffset=buffer,minAltitude=minalt, \ showTwilight=twilight,fileOutput=fn) else: dat = pyasl.transitTimes(jd, jd+ndays, object, lon=lon, lat=lat, alt=alt, \ obsOffset=buffer,minAltitude=minalt, \ showTwilight=twilight) if dat: if write == True: pyasl.transitVisibilityPlot(dat, markTransit=True,print2file=True) if observatory != None: fold = 'transVis-'+object["plName"]+'.png' rmfile = glob.glob(fold) if rmfile: os.remove(rmfile[0]) fn = object["plName"]+tag+'.png' os.rename(fold,fn) else: fn = object["plName"]+otag+tag+'.png' rmfile = glob.glob(fn) if rmfile: os.remove(rmfile[0]) shutil.move(fn,path) else: pyasl.transitVisibilityPlot(dat, markTransit=True,print2file=False) else: print "No eclipses found!"
def StarObsPlot(year=None, targets=None, observatory=None, period=None, hover=False, sunless_hours=None, remove_watermark=False): """ Plot the visibility of target. Parameters ---------- year: int The year for which to calculate the visibility. targets: list List of targets. Each target should be a dictionary with keys 'name' and 'coord'. The key 'name' is a string, 'coord' is a SkyCoord object. observatory: string Name of the observatory that pyasl.observatory can resolve. Basically, any of pyasl.listObservatories().keys() period: string, optional ESO period for which to calculate the visibility. Overrides `year`. hover: boolean, optional If True, color visibility lines when mouse over. sunless_hours: float, optional If not None, plot sunless hours above this airmass """ from mpl_toolkits.axes_grid1 import host_subplot from matplotlib.ticker import MultipleLocator from matplotlib.font_manager import FontProperties from matplotlib import rcParams rcParams['xtick.major.pad'] = 12 font0 = FontProperties() font1 = font0.copy() font0.set_family('sans-serif') font0.set_weight('light') font1.set_family('sans-serif') font1.set_weight('medium') # set the observatory if isinstance(observatory, dict): obs = observatory else: obs = pyasl.observatory(observatory) fig = plt.figure(figsize=(15, 10)) fig.subplots_adjust(left=0.07, right=0.8, bottom=0.15, top=0.88) # watermak if not remove_watermark: fig.text(0.99, 0.99, 'Created with\ngithub.com/iastro-pt/ObservationTools', fontsize=10, color='gray', ha='right', va='top', alpha=0.5) # plotting sunless hours? shmode = False if sunless_hours is not None: shmode = True # limit in airmass (assumed plane-parallel atm) shairmass = sunless_hours # correspoing limit in altitude from scipy.optimize import bisect shalt = 90 - bisect(lambda alt: pyasl.airmassPP(alt) - shairmass, 0, 89) if shmode: fig.subplots_adjust(hspace=0.35) ax = host_subplot(211) axsh = host_subplot(212) plt.text(0.5, 0.47, "- sunless hours above airmass {:.1f} - \n".format(shairmass), transform=fig.transFigure, ha='center', va='bottom', fontsize=12) plt.text(0.5, 0.465, "the thick line above the curves represents the total sunless hours "\ "for each day of the year", transform=fig.transFigure, ha='center', va='bottom', fontsize=10) else: ax = host_subplot(111) for n, target in enumerate(targets): target_coord = target['coord'] target_ra = target_coord.ra.deg target_dec = target_coord.dec.deg if period is not None: jd_start, jd_end = get_ESO_period(period) else: jd_start = pyasl.jdcnv(dt.datetime(year, 1, 1)) jd_end = pyasl.jdcnv(dt.datetime(year, 12, 31)) jdbinsize = 1 # every day each_day = np.arange(jd_start, jd_end, jdbinsize) jds = [] ## calculate the mid-dark times sun = ephem.Sun() for day in each_day: date_formatted = '/'.join([str(i) for i in pyasl.daycnv(day)[:-1]]) s = ephem.Observer() s.date = date_formatted s.lat = ':'.join([str(i) for i in decdeg2dms(obs['latitude'])]) s.lon = ':'.join([str(i) for i in decdeg2dms(obs['longitude'])]) jds.append(ephem.julian_date(s.next_antitransit(sun))) jds = np.array(jds) # Get JD floating point jdsub = jds - np.floor(jds[0]) # Get alt/az of object altaz = pyasl.eq2hor(jds, np.ones_like(jds)*target_ra, np.ones_like(jds)*target_dec, \ lon=obs['longitude'], lat=obs['latitude'], alt=obs['altitude']) ax.plot(jdsub, altaz[0], '-', color='k') # label for each target plabel = "[{0:2d}] {1!s}".format(n + 1, target['name']) # number of target at the top of the curve ind_label = np.argmax(altaz[0]) # or at the bottom if the top is too close to the corners # if jdsub[ind_label] < 5 or jdsub[ind_label] > jdsub.max()-5: # ind_label = np.argmin(altaz[0]) ax.text( jdsub[ind_label], altaz[0][ind_label], str(n+1), color="b", fontsize=14, \ fontproperties=font1, va="bottom", ha="center") if n + 1 == 29: # too many? ax.text(1.1, 1.0-float(n+1)*0.04, "too many targets", ha="left", va="top", transform=ax.transAxes, \ fontsize=10, fontproperties=font0, color="r") else: ax.text(1.1, 1.0-float(n+1)*0.04, plabel, ha="left", va="top", transform=ax.transAxes, \ fontsize=12, fontproperties=font0, color="b") if shmode: sunless_hours = [] for day in each_day: date_formatted = '/'.join([str(i) for i in pyasl.daycnv(day)[:-1]]) s = ephem.Observer() s.date = date_formatted s.lat = ':'.join([str(i) for i in decdeg2dms(obs['latitude'])]) s.lon = ':'.join([str(i) for i in decdeg2dms(obs['longitude'])]) # hours from sunrise to sunset td = pyasl.daycnv(ephem.julian_date(s.next_setting(sun)), mode='dt') \ - pyasl.daycnv(ephem.julian_date(s.next_rising(sun)), mode='dt') sunless_hours.append(24 - td.total_seconds() / 3600) days = each_day - np.floor(each_day[0]) axsh.plot(days, sunless_hours, '-', color='k', lw=2) axsh.set( ylim=(0, 15), yticks=range(1, 15), ylabel='Useful hours', yticklabels=[r'${}^{{\rm h}}$'.format(n) for n in range(1, 15)]) ax.text(1.1, 1.03, "List of targets", ha="left", va="top", transform=ax.transAxes, \ fontsize=12, fontproperties=font0, color="b") axrange = ax.get_xlim() if period is None: months = range(1, 13) ndays = [0] + [calendar.monthrange(date, m)[1] for m in months] ax.set_xlim([0, 366]) ax.set_xticks(np.cumsum(ndays)[:-1] + (np.array(ndays) / 2.)[1:]) ax.set_xticklabels(map(calendar.month_abbr.__getitem__, months), fontsize=10) if shmode: axsh.set_xlim([0, 366]) axsh.set_xticks(np.cumsum(ndays)[:-1] + (np.array(ndays) / 2.)[1:]) axsh.set_xticklabels(map(calendar.month_abbr.__getitem__, months), fontsize=10) else: if int(period) % 2 == 0: # even ESO period, Oct -> Mar months = [10, 11, 12, 1, 2, 3] ndays = [0] + [calendar.monthrange(date, m)[1] for m in months] ax.set_xlim([0, 181]) ax.set_xticks(np.cumsum(ndays)[:-1] + (np.array(ndays) / 2.)[1:]) ax.set_xticklabels(map(calendar.month_abbr.__getitem__, months), fontsize=10) if shmode: axsh.set_xlim([0, 181]) axsh.set_xticks( np.cumsum(ndays)[:-1] + (np.array(ndays) / 2.)[1:]) axsh.set_xticklabels(map(calendar.month_abbr.__getitem__, months), fontsize=10) else: # odd ESO period, Apr -> Sep months = range(4, 10) ndays = [0] + [calendar.monthrange(date, m)[1] for m in months] ax.set_xlim([0, 182]) ax.set_xticks(np.cumsum(ndays)[:-1] + (np.array(ndays) / 2.)[1:]) ax.set_xticklabels(map(calendar.month_abbr.__getitem__, months), fontsize=10) if shmode: axsh.set_xlim([0, 182]) axsh.set_xticks( np.cumsum(ndays)[:-1] + (np.array(ndays) / 2.)[1:]) axsh.set_xticklabels(map(calendar.month_abbr.__getitem__, months), fontsize=10) if axrange[1] - axrange[0] <= 1.0: jdhours = np.arange(0, 3, 1.0 / 24.) utchours = (np.arange(0, 72, dtype=int) + 12) % 24 else: jdhours = np.arange(0, 3, 1.0 / 12.) utchours = (np.arange(0, 72, 2, dtype=int) + 12) % 24 # Make ax2 responsible for "top" axis and "right" axis ax2 = ax.twin() # Set upper x ticks ax2.set_xticks(np.cumsum(ndays)) ax2.set_xlabel("Day") # plane-parallel airmass airmass_ang = np.arange(10, 81, 5) geo_airmass = pyasl.airmass.airmassPP(airmass_ang)[::-1] ax2.set_yticks(airmass_ang) airmassformat = [] for t in range(geo_airmass.size): airmassformat.append("{0:2.2f}".format(geo_airmass[t])) ax2.set_yticklabels(airmassformat) #, rotation=90) ax2.set_ylabel("Relative airmass", labelpad=32) ax2.tick_params(axis="y", pad=6, labelsize=8) plt.text(1.02,-0.04, "Plane-parallel", transform=ax.transAxes, ha='left', \ va='top', fontsize=10, rotation=90) ax22 = ax.twin() ax22.set_xticklabels([]) ax22.set_frame_on(True) ax22.patch.set_visible(False) ax22.yaxis.set_ticks_position('right') ax22.yaxis.set_label_position('right') ax22.spines['right'].set_position(('outward', 30)) ax22.spines['right'].set_color('k') ax22.spines['right'].set_visible(True) airmass2 = list( map( lambda ang: pyasl.airmass.airmassSpherical(90. - ang, obs[ 'altitude']), airmass_ang)) ax22.set_yticks(airmass_ang) airmassformat = [] for t in range(len(airmass2)): airmassformat.append(" {0:2.2f}".format(airmass2[t])) ax22.set_yticklabels(airmassformat, rotation=90) ax22.tick_params(axis="y", pad=8, labelsize=8) plt.text(1.05,-0.04, "Spherical+Alt", transform=ax.transAxes, ha='left', va='top', \ fontsize=10, rotation=90) ax.set_ylim([0, 91]) ax.yaxis.set_major_locator(MultipleLocator(15)) ax.yaxis.set_minor_locator(MultipleLocator(5)) yticks = ax.get_yticks() ytickformat = [] for t in range(yticks.size): ytickformat.append(str(int(yticks[t])) + r"$^\circ$") ax.set_yticklabels(ytickformat, fontsize=16) ax.set_ylabel("Altitude", fontsize=18) yticksminor = ax.get_yticks(minor=True) ymind = np.where(yticksminor % 15. != 0.)[0] yticksminor = yticksminor[ymind] ax.set_yticks(yticksminor, minor=True) m_ytickformat = [] for t in range(yticksminor.size): m_ytickformat.append(str(int(yticksminor[t])) + r"$^\circ$") ax.set_yticklabels(m_ytickformat, minor=True) ax.set_ylim([0, 91]) ax.yaxis.grid(color='gray', linestyle='dashed') ax.yaxis.grid(color='gray', which="minor", linestyle='dotted') ax2.xaxis.grid(color='gray', linestyle='dotted') if period is not None: plt.text( 0.5, 0.95, "Visibility over P{0!s}\n - altitudes at mid-dark time -".format( period), transform=fig.transFigure, ha='center', va='bottom', fontsize=12) else: plt.text( 0.5, 0.95, "Visibility over {0!s}\n - altitudes at mid-dark time -".format( date), transform=fig.transFigure, ha='center', va='bottom', fontsize=12) obsco = "Obs coord.: {0:8.4f}$^\circ$, {1:8.4f}$^\circ$, {2:4f} m".format( obs['longitude'], obs['latitude'], obs['altitude']) plt.text(0.01, 0.97, obsco, transform=fig.transFigure, ha='left', va='center', fontsize=10) plt.text(0.01, 0.95, obs['name'], transform=fig.transFigure, ha='left', va='center', fontsize=10) # interactive! if hover: main_axis = fig.axes[0] all_lines = set(main_axis.get_lines()) def on_plot_hover(event): for line in main_axis.get_lines(): if line.contains(event)[0]: line.set_color('red') # make this line red # and all others black all_other_lines = all_lines - set([line]) for other_line in all_other_lines: other_line.set_color('black') fig.canvas.draw_idle() fig.canvas.mpl_connect('motion_notify_event', on_plot_hover) return fig
def VisibilityPlot(date=None, targets=None, observatory=None, plotLegend=True, showMoonDist=True, print2file=False, remove_watermark=False): """ Plot the visibility of target. Parameters ---------- date: datetime The date for which to calculate the visibility. targets: list List of targets. Each target should be a dictionary with keys 'name' and 'coord'. The key 'name' is aa string, 'coord' is a SkyCoord object. observatory: string Name of the observatory that pyasl.observatory can resolve. Basically, any of pyasl.listObservatories().keys() plotLegend: boolean, optional If True (default), show a legend. showMoonDist : boolean, optional If True (default), the Moon distance will be shown. """ from mpl_toolkits.axes_grid1 import host_subplot from matplotlib.ticker import MultipleLocator from matplotlib.font_manager import FontProperties from matplotlib import rcParams rcParams['xtick.major.pad'] = 12 if isinstance(observatory, dict): obs = observatory else: obs = pyasl.observatory(observatory) # observer = ephem.Observer() # observer.pressure = 0 # observer.horizon = '-0:34' # observer.lat, observer.lon = obs['latitude'], obs['longitude'] # observer.date = date # print(observer.date) # print(observer.previous_rising(ephem.Sun())) # print(observer.next_setting(ephem.Sun())) # print(observer.previous_rising(ephem.Moon())) # print(observer.next_setting(ephem.Moon())) # observer.horizon = '-6' # noon = observer.next_transit(ephem.Sun()) # print(noon) # print(observer.previous_rising(ephem.Sun(), start=noon, use_center=True)) # print() fig = plt.figure(figsize=(15, 10)) fig.subplots_adjust(left=0.07, right=0.8, bottom=0.15, top=0.88) # watermak if not remove_watermark: fig.text(0.99, 0.99, 'Created with\ngithub.com/iastro-pt/ObservationTools', fontsize=10, color='gray', ha='right', va='top', alpha=0.5) ax = host_subplot(111) font0 = FontProperties() font1 = font0.copy() font0.set_family('sans-serif') font0.set_weight('light') font1.set_family('sans-serif') font1.set_weight('medium') for n, target in enumerate(targets): target_coord = target['coord'] target_ra = target_coord.ra.deg target_dec = target_coord.dec.deg # JD array jdbinsize = 1.0 / 24. / 20. # jds = np.arange(allData[n]["Obs jd"][0], allData[n]["Obs jd"][2], jdbinsize) jd = pyasl.jdcnv(date) jd_start = pyasl.jdcnv(date) - 0.5 jd_end = pyasl.jdcnv(date) + 0.5 jds = np.arange(jd_start, jd_end, jdbinsize) # Get JD floating point jdsub = jds - np.floor(jds[0]) # Get alt/az of object altaz = pyasl.eq2hor(jds, np.ones(jds.size)*target_ra, np.ones(jds.size)*target_dec, \ lon=obs['longitude'], lat=obs['latitude'], alt=obs['altitude']) # Get alt/az of Sun sun_position = pyasl.sunpos(jd) sun_ra, sun_dec = sun_position[1], sun_position[2] sunpos_altaz = pyasl.eq2hor(jds, np.ones(jds.size)*sun_ra, np.ones(jds.size)*sun_dec, \ lon=obs['longitude'], lat=obs['latitude'], alt=obs['altitude']) # Define plot label plabel = "[{0:2d}] {1!s}".format(n + 1, target['name']) # Find periods of: day, twilight, and night day = np.where(sunpos_altaz[0] >= 0.)[0] twi = np.where( np.logical_and(sunpos_altaz[0] > -18., sunpos_altaz[0] < 0.))[0] night = np.where(sunpos_altaz[0] <= -18.)[0] if (len(day) == 0) and (len(twi) == 0) and (len(night) == 0): print print("VisibilityPlot - no points to draw") print mpos = pyasl.moonpos(jds) # mpha = pyasl.moonphase(jds) # mpos_altaz = pyasl.eq2hor(jds, mpos[0], mpos[1], # lon=obs['longitude'], lat=obs['latitude'], alt=obs['altitude']) # moonind = np.where( mpos_altaz[0] > 0. )[0] if showMoonDist: mdist = pyasl.getAngDist(mpos[0], mpos[1], np.ones(jds.size)*target_ra, \ np.ones(jds.size)*target_dec) bindist = int((2.0 / 24.) / jdbinsize) firstbin = np.random.randint(0, bindist) for mp in range(0, int(len(jds) / bindist)): bind = firstbin + mp * bindist if altaz[0][bind] - 1. < 5.: continue ax.text(jdsub[bind], altaz[0][bind]-1., str(int(mdist[bind]))+r"$^\circ$", ha="center", va="top", \ fontsize=8, stretch='ultra-condensed', fontproperties=font0, alpha=1.) if len(twi) > 1: # There are points in twilight linebreak = np.where( (jdsub[twi][1:] - jdsub[twi][:-1]) > 2.0 * jdbinsize)[0] if len(linebreak) > 0: plotrjd = np.insert(jdsub[twi], linebreak + 1, np.nan) plotdat = np.insert(altaz[0][twi], linebreak + 1, np.nan) ax.plot(plotrjd, plotdat, "-", color='#BEBEBE', linewidth=1.5) else: ax.plot(jdsub[twi], altaz[0][twi], "-", color='#BEBEBE', linewidth=1.5) ax.plot(jdsub[night], altaz[0][night], '.k', label=plabel) ax.plot(jdsub[day], altaz[0][day], '.', color='#FDB813') altmax = np.argmax(altaz[0]) ax.text( jdsub[altmax], altaz[0][altmax], str(n+1), color="b", fontsize=14, \ fontproperties=font1, va="bottom", ha="center") if n + 1 == 29: ax.text( 1.1, 1.0-float(n+1)*0.04, "too many targets", ha="left", va="top", transform=ax.transAxes, \ fontsize=10, fontproperties=font0, color="r") else: ax.text( 1.1, 1.0-float(n+1)*0.04, plabel, ha="left", va="top", transform=ax.transAxes, \ fontsize=12, fontproperties=font0, color="b") ax.text( 1.1, 1.03, "List of targets", ha="left", va="top", transform=ax.transAxes, \ fontsize=12, fontproperties=font0, color="b") axrange = ax.get_xlim() ax.set_xlabel("UT [hours]") if axrange[1] - axrange[0] <= 1.0: jdhours = np.arange(0, 3, 1.0 / 24.) utchours = (np.arange(0, 72, dtype=int) + 12) % 24 else: jdhours = np.arange(0, 3, 1.0 / 12.) utchours = (np.arange(0, 72, 2, dtype=int) + 12) % 24 ax.set_xticks(jdhours) ax.set_xlim(axrange) ax.set_xticklabels(utchours, fontsize=18) # Make ax2 responsible for "top" axis and "right" axis ax2 = ax.twin() # Set upper x ticks ax2.set_xticks(jdhours) ax2.set_xticklabels(utchours, fontsize=18) ax2.set_xlabel("UT [hours]") # Horizon angle for airmass airmass_ang = np.arange(5., 90., 5.) geo_airmass = pyasl.airmass.airmassPP(90. - airmass_ang) ax2.set_yticks(airmass_ang) airmassformat = [] for t in range(geo_airmass.size): airmassformat.append("{0:2.2f}".format(geo_airmass[t])) ax2.set_yticklabels(airmassformat, rotation=90) ax2.set_ylabel("Relative airmass", labelpad=32) ax2.tick_params(axis="y", pad=10, labelsize=10) plt.text(1.015,-0.04, "Plane-parallel", transform=ax.transAxes, ha='left', \ va='top', fontsize=10, rotation=90) ax22 = ax.twin() ax22.set_xticklabels([]) ax22.set_frame_on(True) ax22.patch.set_visible(False) ax22.yaxis.set_ticks_position('right') ax22.yaxis.set_label_position('right') ax22.spines['right'].set_position(('outward', 25)) ax22.spines['right'].set_color('k') ax22.spines['right'].set_visible(True) airmass2 = list( map( lambda ang: pyasl.airmass.airmassSpherical(90. - ang, obs[ 'altitude']), airmass_ang)) ax22.set_yticks(airmass_ang) airmassformat = [] for t in airmass2: airmassformat.append("{0:2.2f}".format(t)) ax22.set_yticklabels(airmassformat, rotation=90) ax22.tick_params(axis="y", pad=10, labelsize=10) plt.text(1.045,-0.04, "Spherical+Alt", transform=ax.transAxes, ha='left', va='top', \ fontsize=10, rotation=90) ax3 = ax.twiny() ax3.set_frame_on(True) ax3.patch.set_visible(False) ax3.xaxis.set_ticks_position('bottom') ax3.xaxis.set_label_position('bottom') ax3.spines['bottom'].set_position(('outward', 50)) ax3.spines['bottom'].set_color('k') ax3.spines['bottom'].set_visible(True) ltime, ldiff = pyasl.localtime.localTime( utchours, np.repeat(obs['longitude'], len(utchours))) jdltime = jdhours - ldiff / 24. ax3.set_xticks(jdltime) ax3.set_xticklabels(utchours) ax3.set_xlim([axrange[0], axrange[1]]) ax3.set_xlabel("Local time [hours]") ax.set_ylim([0, 91]) ax.yaxis.set_major_locator(MultipleLocator(15)) ax.yaxis.set_minor_locator(MultipleLocator(5)) yticks = ax.get_yticks() ytickformat = [] for t in range(yticks.size): ytickformat.append(str(int(yticks[t])) + r"$^\circ$") ax.set_yticklabels(ytickformat, fontsize=16) ax.set_ylabel("Altitude", fontsize=18) yticksminor = ax.get_yticks(minor=True) ymind = np.where(yticksminor % 15. != 0.)[0] yticksminor = yticksminor[ymind] ax.set_yticks(yticksminor, minor=True) m_ytickformat = [] for t in range(yticksminor.size): m_ytickformat.append(str(int(yticksminor[t])) + r"$^\circ$") ax.set_yticklabels(m_ytickformat, minor=True) ax.set_ylim([0, 91]) ax.yaxis.grid(color='gray', linestyle='dashed') ax.yaxis.grid(color='gray', which="minor", linestyle='dotted') ax2.xaxis.grid(color='gray', linestyle='dotted') plt.text(0.5,0.95,"Visibility on {0!s}".format(date.date()), \ transform=fig.transFigure, ha='center', va='bottom', fontsize=20) if plotLegend: line1 = matplotlib.lines.Line2D((0, 0), (1, 1), color='#FDB813', linestyle="-", linewidth=2) line2 = matplotlib.lines.Line2D((0, 0), (1, 1), color='#BEBEBE', linestyle="-", linewidth=2) line3 = matplotlib.lines.Line2D((0, 0), (1, 1), color='k', linestyle="-", linewidth=2) lgd2 = plt.legend((line1,line2,line3),("day","twilight","night",), \ bbox_to_anchor=(0.88, 0.13), loc='best', borderaxespad=0.,prop={'size':12}, fancybox=True) lgd2.get_frame().set_alpha(.5) obsco = "Obs coord.: {0:8.4f}$^\circ$, {1:8.4f}$^\circ$, {2:4f} m".format( obs['longitude'], obs['latitude'], obs['altitude']) plt.text(0.01, 0.97, obsco, transform=fig.transFigure, ha='left', va='center', fontsize=10) plt.text(0.01, 0.95, obs['name'], transform=fig.transFigure, ha='left', va='center', fontsize=10) return fig
ncfile = os.path.join(ncpath, file) nc = Dataset(ncfile, mode='r') SSPS = nc.variables['SSPS'] SSTP = nc.variables['SSTP'] TIME = nc.variables['TIME'] CM = nc.cycle_mesure LON = nc.variables['LONGITUDE'] LAT = nc.variables['LATITUDE'] #definition of the day for the current year and the start year of netcdf df = datetime.datetime(annee, 1, 1, 0) dd = datetime.datetime(1950, 1, 1, 0) #convert day to julian day real jul = pyasl.jdcnv(df) jul2 = pyasl.jdcnv(dd) #calculation of the current year julian day since the beginig of julian day DIFF = jul - jul2 #test #from datetime import datetime #units=nc.variables['TIME'].units #buf=nc.variables['TIME'] #TIME=list() #TIME.extend(buf.tolist()) #dates=nc.num2date(TIME,units,'julian').tolist() #import julian #import datetime