def sanity_checkExample(self): """ Check angular distance example """ from PyAstronomy import pyasl print "Angular distance between the poles (deg):" print pyasl.getAngDist(98.0, -90.0, 100., +90.0) print "Angular distance between Vega and Altair (deg)" print pyasl.getAngDist(279.23473479, +38.78368896,297.69582730, +08.86832120)
def sampler(self): # get "new" data for brown dwarf # grab random samples of whichever is in self.vary vary_data = { 'bd_ra': [self.bd.ra, self.bd.pm_ra], 'bd_dec': [self.bd.dec, self.bd.pm_dec], 'pi': [self.bd.pi, self.bd.pm_pi], 'mu_alpha': [self.bd.mu_a, self.bd.pm_mu_a], 'mu_delta': [self.bd.mu_d, self.bd.pm_mu_d] } # add data to a list for ease all_data = [ np.random.normal( loc=vary_data[i][0], scale=vary_data[i][1], size=self.samples) if i in self.vary else vary_data[i][0] for i in vary_data ] # run through each sample and get the measurement uncertainty mass_unc_list, sep_list, time_list = list(), list(), list() for i in range(self.samples): # grab data if needs to be indexed or not instance_data = [ j[i] if isinstance(j, np.ndarray) else j for j in all_data ] # create a BrownDwarf instance bd_new = BrownDwarf( np.array([ instance_data[0], instance_data[1], instance_data[2], instance_data[3], instance_data[4] ]), observ_date=self.bd.observ_date, array_col_names=['ra', 'dec', 'pi', 'mu_alpha', 'mu_delta']) bd_path = bd_new.find_path(start=self.bd.start, end=self.bd.end, step=self.bd.step) # take star info from event table and the brown dwarf path to find a list of distance separations = [ pyasl.getAngDist(row.ra, row.dec, self.event.bs_ra, self.event.bs_dec) * 3600 for index, row in bd_path.iterrows() ] # get minimum distance and calculate the mass uncertainty min_separation = min(separations) min_index = separations.index(min_separation) delta_ml = self.delta_ml_calc(min_separation) mass_unc_list.append(delta_ml) sep_list.append(min_separation) time_list.append(bd_path.time[min_index]) self.mass_unc_list = mass_unc_list return mass_unc_list, sep_list, time_list
def add_event(ax, ra_i, dec_i, sigma_i, coords='ra', **kwargs): if abs(dec_i) > np.radians(70): ext = 20. elif abs(dec_i) > np.radians(30): ext = 10. else: ext = 3. val = ext * np.degrees(sigma_i) n = 200 #get all points on the map for which the angular distance is euqal the 1 sigma level ra_bins = np.linspace(np.degrees(ra_i)-val, np.degrees(ra_i)+val, num=n) dec_bins = np.linspace(np.degrees(dec_i)-val, np.degrees(dec_i)+val, num=n) xx, yy =np.meshgrid(ra_bins, dec_bins, indexing='ij') DIST = pyasl.getAngDist(xx,yy, np.degrees(ra_i),np.degrees(dec_i)) - np.degrees(sigma_i) c = kwargs.pop('color', 'black') d = np.zeros_like(DIST) d[DIST==0.] = 1 if coords=='ra': xx,yy= _trans(np.radians(xx), np.radians(yy)) ra_i, dec_i = _trans(ra_i,dec_i) res = ax.contour(xx, yy, DIST, levels=[ 0.], colors = c, alpha=0.8, **kwargs) return res
def checkDistances(inFileName, angDiamFileName, outFileName): hashSearch = csvFree.readCSVFile( hashSearchFileName[:hashSearchFileName.rfind('.')] + '_with_header.csv') hashFound = csvFree.readCSVFile(inFileName) angDiams = csvFree.readCSVFile(angDiamFileName) csvOut = csvData.CSVData() csvOut.header = hashFound.header nNotFound = 0 ra_3238 = hmsToDeg('17:59:45.20') dec_3238 = dmsToDeg('-33:21:13.00') toDelete = [] for i in range(hashFound.size()): name = hashFound.getData('id', i) idPNMain = hashFound.getData('pndb', i) if idPNMain == '': csvOut.append(hashFound.getData(i)) else: dist = float(hashFound.getData('dist[arcsec]', i)) found = False for j in range(angDiams.size()): if angDiams.getData('idPNMain', j) == idPNMain: if angDiams.getData('InUse', j) == '1': found = True if dist > float(angDiams.getData('MajDiam', j)): csvOut.append([name, '', '']) else: csvOut.append(hashFound.getData(i)) if not found: nNotFound += 1 print( 'Problem: did not find an angular diameter for <' + name + '>: idPNMain = ', idPNMain, ', dist = ', dist) if dist > 50.: csvOut.append([name, '', '']) else: csvOut.append(hashFound.getData(i)) for j in range(hashSearch.size()): if hashSearch.getData('id', j) == csvOut.getData('id', csvOut.size() - 1): ra = hmsToDeg(hashSearch.getData('ra', j)) dec = dmsToDeg(hashSearch.getData('dec', j)) angDist = angularDistance(ra, dec, ra_3238, dec_3238) print('ra = ', ra, ', dec = ', dec, ': angDist = ', angDist) angDistPyAsl = pyasl.getAngDist(ra, dec, ra_3238, dec_3238) * 3600. if angDist < 800: if csvOut.getData('pndb', csvOut.size() - 1) != '3238': toDelete.append([ csvOut.getData('pndb', csvOut.size() - 1), ra, dec, angDist, angDistPyAsl ]) csvOut.setData('pndb', csvOut.size() - 1, '3238') csvFree.writeCSVFile(csvOut, outFileName) for i in toDelete: print('toDelete : ', i)
def obj_lst(reboot): #读取目标的赤经赤纬 scriptpath = os.path.dirname(os.path.abspath(__file__)) lst = [i.split() for i in file(scriptpath + os.sep + 'objradec.lst')] namelst = [i[0] for i in lst] ralst = [float(i[1]) for i in lst] declst = [float(i[2]) for i in lst] fitnamelst = glob.glob('ftb*.fits') namedic = {} # fitnamelst = [i for i in fitnamelst if # pyfits.getval(i, 'INSFLNAM').strip().lower() == 'johnsonv'] print '1' #进行Ra,Dec匹配 for fitname in fitnamelst: ra = pyfits.getval(fitname, 'RA') dec = pyfits.getval(fitname, 'DEC') objname = pyfits.getval(fitname, 'OBJECT') flag = False for i, name in enumerate(namelst): angdis = pyasl.getAngDist(ralst[i], declst[i], ra, dec) if angdis < 0.6: flag = True print '%s %15s ----> %s' % (fitname, objname, name) if name in namedic: namedic[name].append(fitname) else: namedic[name] = [fitname] break if flag is False: print '%s %s %f %f not found in objradec.lst' % ( fitname, objname, ra, dec) print 'please check the fits file ,edit and save objradec.lst!!!' webbrowser.open(scriptpath + os.sep + 'objradec.lst') if ra == 0 and dec == 0: os.remove(fitname) reboot = 1 break else: raw_input('press any key to reboot') reboot = 1 break if reboot == 0: #生成目标list文件 for name in namedic: fn = 'obj_' + name + '.lst' fil = open(fn, 'w') for fitname in namedic[name]: fil.write(fitname + '\n') fil.close() return reboot
def centroid_shift(self, which, masses=None): # if mass = None, run through Mjup=5,10,20,40 if masses == None: mjups = [5, 10, 20, 40] else: mjups = list(masses) self.mjups = mjups # find respective einstein radii self.einstein_radii = [self.einstein_radius(mass) for mass in mjups] # calculate for all the masses and have their centroid shifts # create the dataframe shift_df = pd.DataFrame(columns=['time'] + ['shift_' + str(mass) for mass in mjups]) mag_df = pd.DataFrame(columns=['time'] + ['mag_' + str(mass) for mass in mjups]) theta_list = list() for index, row in self.bd.coord_df.iterrows(): # create dict of a row for the df temp_dict_shift = {'time': row.time} temp_dict_mag = {'time': row.time} # loop through each mjup and add it to temp_dict for each mass for j in range(len(mjups)): theta = pyasl.getAngDist(row.ra, row.dec, list(self.event_table.bs_ra)[which], list(self.event_table.bs_dec)[which]) #convert from degrees to mas theta *= 3600 * 1000 theta_norm = theta / self.einstein_radii[j] shift = ((self.einstein_radii[j]) * theta_norm) / ( (theta_norm**2) + 2) mag = ((theta_norm**2) + 2) / (theta_norm * math.sqrt((theta_norm**2) + 4)) temp_dict_shift['shift_{}'.format(str(mjups[j]))] = shift temp_dict_mag['mag_{}'.format(str(mjups[j]))] = mag theta_list.append(theta) # add each row to the df shift_df = shift_df.append(temp_dict_shift, ignore_index=True) mag_df = mag_df.append(temp_dict_mag, ignore_index=True) self.theta_list = theta_list self.shift_df = shift_df self.mag_df = mag_df return shift_df
def deltaV_sky_pos(self, mjd, targ_ra, targ_dec): """create inputs to KS91 from convenient params, return deltaV array Parameters: ---------- mjd: np.float64 decimal mjd to compute delta for targ_ra: np.float64 (or array) target ra targ_dec: np.float64 (or array) target dec Returns: ------- deltaV : np.float64 (or array) change in V mag at targ location due to moon """ moon_pos = self.moon_radec(mjd=mjd) lunar_phase = self.moon_illumination(mjd=mjd) alpha = 180. * np.arccos(2 * lunar_phase - 1) / 3.1415 moon_targ_dist = pyasl.getAngDist(moon_pos[0], moon_pos[1], targ_ra, targ_dec) malt, maz = self.radec2altaz(mjd=mjd, ra=moon_pos[0], dec=moon_pos[1]) talt, taz = self.radec2altaz(mjd=mjd, ra=targ_ra, dec=targ_dec) zee = 90 - talt zee_m = 90 - malt # print(moon_pos) deltaV = KS91_deltaV(alpha, moon_targ_dist, zee, zee_m) # if len(moon_targ_dist) > 1: # for m, d in zip(moon_targ_dist, deltaV): # print(mjd, f"{float(lunar_phase):.2f} {float(alpha):3.1f} {float(m):.1f} {d}") # for tt, z in zip(talt, zee): # print(f"{float(tt):.1f} *{float(z):.1f}* {float(malt):.1f} *{float(zee_m):.1f}*") # else: # print(mjd, f"{float(lunar_phase):.2f} {float(alpha):3.1f} {float(moon_targ_dist):.1f} {deltaV}") return deltaV
def crossMatchWeidmann(fNameInW, fNameInHASH, fNameOutMatch=None, fNameOutNoMatch=None): with open(fNameInW, 'r') as f: linesW = f.readlines() with open(fNameInHASH, 'r') as f: linesHASH = f.readlines() for iLine in np.arange(0,len(linesHASH),1): linesHASH[iLine] = linesHASH[iLine].rstrip('\n').split(',') match = [] noMatch = [] headerW = [] nFound = 0 for lineW in linesW: lineW = lineW.rstrip('\n') itemsW = lineW.split(',') if len(headerW) == 0: headerW = itemsW else: nameW = itemsW[0] # print('read name <'+nameW+'> from Weidmann file') found = False for iLine in np.arange(0,len(linesHASH),1): # print('nameHASH = <'+linesHASH[iLine][2].strip('"')+'>') if (linesHASH[iLine][2].strip('"') == nameW) or ('G'+linesHASH[iLine][1] == nameW): print('nameW = <'+nameW+'> found in HASH as '+linesHASH[iLine][2].strip('"')) found = True nFound += 1 if not found: l = float(itemsW[1]) b = float(itemsW[2]) ra1,dec1 = lonLatToRaDec(l, b) for iLine in np.arange(1,len(linesHASH),1): ra2 = float(linesHASH[iLine][6]) dec2 = float(linesHASH[iLine][7]) dist = pyasl.getAngDist(ra1, dec1, ra2, dec2) * 3600. # print('dist = ',dist) if dist < 5.: found = True nFound += 1 print('nameW = <'+nameW+'> identified as ',linesHASH[iLine][2]) if not found: print('nameW = <'+nameW+'> not found in HASH: l=',itemsW[1],', b=',itemsW[2]) # print('nameW = <'+nameW+'> NOT found in HASH') print('found ',nFound,' names in both catalogues out of ',len(linesW),' PN in Weidmann table')
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 angular_separation(self, dataList, sourceRa, sourceDe): for item in dataList: angular_separation = pyasl.getAngDist(sourceRa, sourceDe, float(item['RAJ2000']), float(item['DEJ2000'])) item.update({'angular_separation': angular_separation})
print(nucleus + ' (Z = ' + str(Z[i]) + ') ' + str(E[i]) + ' EeV') try: file2load = ('data/' + gmf_dir + str(Nside) + '/' + filename) with lzma.open(file2load, 'rt') as f: summary = np.genfromtxt(f, dtype=float) # Coordinates observed at Earth #lat_earth_deg = summary[:,0] #lon_earth_deg = summary[:,1] # Coordinates at the boundary of the Galaxy lat_gal_deg = summary[:, 2] lon_gal_deg = summary[:, 3] # We need angular separtion between the source and # arrival directions at the Galaxy boundary ang_sep = getAngDist(source_lon, source_lat, lon_gal_deg, lat_gal_deg) # Find EECRs that fit in the given source vicinity at # the Galaxy boundary, if any close_dirs = np.asarray( np.where(ang_sep <= source_vicinity_radius + 0.01)) N_close = np.size(close_dirs) if N_close: print('{:4d} close EECRs'.format(N_close)) print('To be selected: ' + str(M[i]) + '\n') close_dirs = np.reshape(close_dirs, N_close) # This is the 1st version: arrival directions are chosen # w/0 replacement. Due to this, we sometimes lack a number
def plot_event_path(self, zoom=0.2, years=1, figsize=(10, 10), gaia_check=False, legend=True, point_size=10, font_size=10, label_size=20, ntick_x=None, ntick_y=None): # basic setup fig = plt.figure(figsize=figsize) fig.subplots_adjust(left=0.0, right=1.0, bottom=0.0, top=1.0, wspace=0.00, hspace=0.00) ax1 = fig.add_axes([0.09, 0.09, 0.90, 0.90]) # set titles ax1.set_xlabel(r'$ \Delta \alpha_{J2000, deg} $', fontsize=label_size) ax1.set_ylabel(r'$ \Delta \delta_{J2000, deg}$', fontsize=label_size) #plt.title(str(self.bd.bd.object_name), fontsize=label_size) # set limits +-zoom length. I had initially done based on change of ra and dec, but that scaled the plot weird path_length = pyasl.getAngDist(self.a_ends[0] / 3600, self.d_ends[0] / 3600, self.a_ends[1] / 3600, self.d_ends[1] / 3600) #angular difference in degrees path_length *= 3600 #convert from degrees to arcseconds # see if add or subtract (plus or minus 1 which will be mult to zoom * path_length) a_dir = (self.a_ends[1] - self.a_ends[0]) / abs(self.a_ends[1] - self.a_ends[0]) d_dir = (self.d_ends[1] - self.d_ends[0]) / abs(self.d_ends[1] - self.d_ends[0]) # add lims themselves ax1.axis('equal') ax1.set_xlim(self.a_ends[0] + (-1 * a_dir * zoom * path_length), self.a_ends[1] + (a_dir * zoom * path_length)) ax1.set_ylim(self.d_ends[0] + (-1 * d_dir * zoom * path_length), self.d_ends[1] + (d_dir * zoom * path_length)) # ticks if ntick_x is not None: ax1.xaxis.set_major_locator(MaxNLocator(ntick_x)) if ntick_y is not None: ax1.yaxis.set_major_locator(MaxNLocator(ntick_y)) #make list of alpha and dec every 10 years and plot them with text as visual markers. easy to see in plot and see #direction the dwarf goes. """measure_dict = {'1day': 365, '7days': 52, '1month': 12, '3months': 4, '4months': 3, '1year' : 1} measure_in_year = measure_dict[self.bd.step] a_years = [i for i in self.bd.coord_df.ra if list(self.bd.coord_df.ra).index(i) % (years * measure_in_year) == 0] d_years = [i for i in self.bd.coord_df.dec if list(self.bd.coord_df.dec).index(i) % (years * measure_in_year) == 0] # plot year labels ax1.scatter(a_years, d_years, s=point_size+1, c='blue', marker="D")""" # adding text to 10 yr plot # finding placement to put plots based on change of ra/dec (10x more off with dec than ra bc of length of time) start_year = int(self.bd.start.split('-')[0]) end_year = int(self.bd.end.split('-')[0]) years = range(start_year, end_year + 1, years) #ax1.annotate(years[0], (a_years[0], d_years[0]), fontsize=font_size) #for i, txt in enumerate(years): # ax1.annotate(txt, (a_years[i], d_years[i]), fontsize=font_size) # plot the background stars """gaia = self.stars.gaia_pointsource if gaia_check == True: gaia_c = ['red' if x==1 else 'grey' for x in gaia] gaia_handle = mpatches.Patch(color='red', label='$\it{Gaia}$ point source') not_gaia_handle = mpatches.Patch(color='grey', label='Not a $\it{Gaia}$ point source') if legend == True: ax1.legend(handles=[gaia_handle, not_gaia_handle]) else: gaia_c = 'grey'""" colors = ['#003f5c', '#7a5195', '#ef5675', '#ffa600'] ax1.scatter(self.stars.ra, self.stars.dec, s=point_size + 8, c=colors[1]) # plot the brown dwarf path ax1.scatter(self.coord_df.ra, self.coord_df.dec, s=point_size, c=colors[3]) self.event_plot = fig return fig
def find_events(self): # df can append events to close_df = pd.DataFrame(columns=[ 'object_name', 'sep', 'delta_m', 'bd_ra', 'bd_dec', 'ls_id', 'bs_ra', 'bs_dec', 'mag', 'time_of_min' ]) # find "box" where events may possibly occur. this is the maximum distance for an event added on to each end # also convert theta_max from mas to deg a_low = self.a_ends[0] - (self.theta_max / 3600) a_high = self.a_ends[1] + (self.theta_max / 3600) d_low = self.d_ends[0] - (self.theta_max / 3600) d_high = self.d_ends[1] + (self.theta_max / 3600) self.arange = abs(a_high - a_low) self.drange = abs(d_high - d_low) # run through each background star for i in range(len(self.stars)): # if the star is within the range of ra and dec I am looking at a_check = (abs(a_high - list(self.stars.ra)[i]) + abs(list(self.stars.ra)[i] - a_low)) == abs(a_high - a_low) d_check = (abs(d_high - list(self.stars.dec)[i]) + abs(list(self.stars.dec)[i] - d_low)) == abs(d_high - d_low) if a_check and d_check: # if within check, see if there is gaia data on the star gaia_data = self.fields.get_gaia_data(index=i) # grab paths or position (if no gaia data) if len(gaia_data) == 1: # grab actual data parallax = 0 if len(gaia_data.parallax) == 0 or np.isnan( gaia_data.parallax).bool() else gaia_data.parallax mu_a = 0 if len(gaia_data.pmra) == 0 or np.isnan( gaia_data.pmra).bool() else gaia_data.pmra mu_d = 0 if len(gaia_data.pmdec) == 0 or np.isnan( gaia_data.pmdec).bool() else gaia_data.pmdec # compute path as needed star_path = self.fields.find_star_path(i, parallax, mu_a, mu_d, self.bd.start, self.bd.end, step=self.bd.step) ras = list(star_path.ra) decs = list(star_path.dec) thetas = np.array([ pyasl.getAngDist(row['ra'], row['dec'], ras[index], decs[index]) for index, row in self.coord_df.iterrows() ]) else: ras = list(self.stars.ra)[i] decs = list(self.stars.dec)[i] thetas = np.array([ pyasl.getAngDist(row['ra'], row['dec'], ras, decs) for index, row in self.coord_df.iterrows() ]) thetas *= 3600 # deg to arcseconds self.thetas = thetas min_index = np.where(thetas == min(thetas))[0][ 0] # assuming 1 moment of minimum separation self.min_sep = thetas[min_index] # if theta is small enough for an event if thetas[min_index] < self.theta_max: delta_ml = self.delta_ml_calc(thetas[min_index]) # grab values bd_ra = self.coord_df['ra'][min_index] bd_dec = self.coord_df['dec'][min_index] ls_id = list(self.stars.ls_id)[i] bs_ra = list(self.stars.ra)[i] bs_dec = list(self.stars.dec)[i] mag = list(self.stars.dered_mag_g)[i] time_of_min = self.coord_df['time'][min_index] # add to table close_df = self.add_to_close(close_df, self.bd.bd.object_name, thetas[min_index], delta_ml, bd_ra, bd_dec, ls_id, bs_ra, bs_dec, mag, time_of_min) return close_df
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
if sat_ra < 0: sat_ra=sat_ra+360 print("SATELLITE_RA (ECI)", round(sat_ra,2),"degrees") print("SATELLITE_DEC (ECI)", round(math.degrees(decrad),2),"degrees") print("SATELLITE_RADIUS (Km)", round(radius,1),"Km") print("EARTH_RA", round(tbdata['EARTH_RA'],2),"degrees") print("EARTH_DEC", round(tbdata['EARTH_DEC'],2),"degrees") #print("EARTH_THETA", tbdata['EARTH_THETA']) #print("EARTH_PHI", tbdata['EARTH_PHI']) print("EARTH_THETA", round(pyasl.getAngDist(tbdata['EARTH_RA'], tbdata['EARTH_DEC'], tbdata['ATTITUDE_RA_Y'], tbdata['ATTITUDE_DEC_Y']),2),"degrees") print("RATEM_ST", tbdata['RATEM_ST']) print("RATEM_ST_AC", tbdata['RATEM_ST_AC']) print("RATEM_ST_MCAL_CT", tbdata['RATEM_ST_MCAL_CT']) print("RATEM_ST_MCAL_AC_CT", tbdata['RATEM_ST_MCAL_AC_CT']) print("RATEM_ST_MCAL", tbdata['RATEM_ST_MCAL']) print("RATEM_ST_MCAL_AC", tbdata['RATEM_ST_MCAL_AC']) print("LIVETIME", tbdata['LIVETIME'],"ms") print("LATITUDE (ECEF)",round(latitude,2),"degrees")