def main(): progname = 'find_peak.py' args = get_opt(progname) # in_files = ['/Users/ferdman/Work/pulsar/0737-3039A/profs/add_campaigns/0737-3039A.20??.??.add.asc'] # in_files = ['/Users/ferdman/Work/pulsar/1756-2251/profs/add_epochs/*.add.asc'] # in_files = ['/Users/ferdman/Work/pulsar/1756-2251/profs/template/gasp/1756-2251.1400.2048_bins.std'] # in_files = ['/Users/ferdman/Work/pulsar/1756-2251/profs/singleprofs/gasp/TemplateTestRot.asc'] #phase_cut = [] # number of points on *each* side of the profile in fit, so there are # 2*n_poly_fit + 1 points to choose from # matplotlib.rc('font', size=22) input_files = [] for file_name in args.profiles: # For some reason this works and ".append()" doesn't: input_files[len(input_files):] = glob.glob(file_name) n_files = len(input_files) print "Number of input profiles: ", n_files, '\n' # print "Input files = ", input_files if(len(args.phasecut) > 0): print "Will separate profiles into separate phase ranges before processing." if(len(args.phasecut) ==1): print " Profile will be split along phase ", args.phasecut[0] else: print " Profile will be split along phases ", args.phasecut print " " mjd_obs = np.zeros(len(input_files)) # A = np.zeros((len(input_files), len(phase_cut)+1)) # pdf_width = np.zeros((len(input_files), len(phase_cut)+1), n_hist_bins) # x_width = np.zeros((len(input_files), len(phase_cut)+1), n_hist_bins) for i_prof in np.arange(n_files): prof_data = read_asc_prof(input_files[i_prof]) prof_head = read_asc_header(input_files[i_prof]) psr_name = prof_head['psrname'] mjd_obs[i_prof] = prof_head['imjd'] + prof_head['smjd']/86400. n_bins = len(prof_data['i']) phase_cut_bins = np.append(0., args.phasecut)*n_bins phase_cut_bins = np.append(phase_cut_bins, n_bins) phase_cut_bins = phase_cut_bins.astype(int) #print "phase_cut_bins = ", phase_cut_bins phase_cuts = phase_cut_bins.astype(float)/n_bins #print "arange = ", np.arange(len(phase_cut_bins) - 1) # print "File ", input_files[i_prof] print " " mjdtext = 'MJD {0:8.2f}'.format(mjd_obs[i_prof]) datetext = '{0:10s}'.format(mjd.mjdtodate(mjd_obs[i_prof], dateformat="%Y-%b-%d")) print mjdtext, ' ', datetext prof_in = prof_data.copy() for i_phase in np.arange(len(phase_cut_bins) - 1): plt.figure() print " Phase range {0:.2f} to {1:.2f}".format(prof_data['phase'][phase_cut_bins[i_phase]], \ prof_data['phase'][phase_cut_bins[i_phase+1]-1]) print " " prof_in['i'] = prof_data['i'][phase_cut_bins[i_phase]:phase_cut_bins[i_phase+1]-1] prof_in['phase'] = prof_data['phase'][phase_cut_bins[i_phase]:phase_cut_bins[i_phase+1]-1] x_peak, y_peak = get_peak(prof_in, n_pts_fit=12, n_order=5, n_test_fit=4) if(len(args.phasecut) > 0): plt.savefig('peak_fit.'+'{0:5.0f}'.format(mjd_obs[i_prof])+ '.phase_{0:d}'.format(i_phase)+'.png') else: plt.savefig('peak_fit.'+'{0:5.0f}'.format(mjd_obs[i_prof])+ '.png') if(x_peak < 0): print 'Could not choose one. Exiting: ' exit() print 'Peak phase: ', x_peak[0] print 'Peak height: ', y_peak[0]
def main(): # Input asp-style ascii profile will be first argument. # (command-line options to come later) prog_name = argv[0].strip(".py") # Scale factor for plotting difference plots scale = 2.0 # ref_file = argv[len(argv)-1] ref_file = argv[1] # arg = get_opt(prog_name) print "n_args = ", len(argv) - 1 # prof_file = argv[1] input_files = [] for file in argv[1:]: # For some reason this works and ".appen()" doesn't: input_files[len(input_files) :] = glob.glob(file) # input_files.append(glob.glob(file)) input_files.reverse() if input_files.count(ref_file) > 0: input_files.remove(ref_file) # First, read in profile data file, and assign each column to a separate # numpy array # prof_file = input_files[0] # prof_header = read_asc_header(prof_file) # prof_data[0] = read_asc_prof(prof_file) ref_header = read_asc_header(ref_file) ref_data = read_asc_prof(ref_file) # ref_data['i'] = norm(ref_data['i'], duty) # if(len(input_files) > 1): # for prof_file in input_files: prof_data = [] date_text = [] nobs = [] for i_prof in np.arange(len(input_files)): prof_header = read_asc_header(input_files[i_prof]) duty = get_duty(prof_header["psrname"]) nobs.append(prof_header["obscode"]) print "NOBS = ", nobs prof_data_temp = read_asc_prof(input_files[i_prof]) # prof_data_temp['i'] = norm(prof_data_temp['i'], duty) # prof_data_temp['i'] = prof_data_temp['i'] + i_prof diff_prof = remove_base((prof_data_temp["i"] - ref_data["i"]), duty) prof_data_temp["i"] = scale * (diff_prof) + i_prof + 1.2 print "Index = ", i_prof, ", Min = ", np.min(prof_data_temp["i"]), ", Max = ", np.max(prof_data_temp["i"]) prof_data.append(prof_data_temp) # Set up labelling for each profile: prof_date = mjd.mjdtodate(prof_header["imjd"], dateformat="%Y %b %d") date_text.append((0.8, i_prof + 0.25, prof_date)) print "Date = ", date_text # Make first prof in list for plot to be the ref profile prof_data.append(ref_data) ref_date = mjd.mjdtodate(ref_header["imjd"], dateformat="%Y %b %d") date_text.append((0.5, 0.20, ref_date)) nobs.append(ref_header["obscode"]) nobs_unique = list(set(nobs)) clr = [] for i_nobs in range(len(nobs)): if nobs_unique <= 1: clr.append("black") else: clr.append(cm.gist_heat(float(nobs_unique.index(nobs[i_nobs])) / float(len(nobs_unique)))) # Do this just to make the ordering such that the first alphanumerically # is at the top... # prof_data.reverse() # date_text.reverse() print "LENGTH of PROF DATA = ", len(prof_data) print "LENGTH of colour = ", len(clr) plot_prof( prof_data, yticks=False, canvassize=(8, 10), hgrid=False, vgrid=False, ylim=(np.min(prof_data[0]["i"]) - 0.1, len(input_files) + 0.1 + 1.0), figtext=date_text, linecolour=clr, ) # meaningThe following means that the 2nd argument is the # desired output plot file name # plot_file = 'multi_profile.png' plot_file = "diff_profile.pdf" # plt.show() plt.savefig(plot_file)
def main(): progname = 'find_widths.py' args = get_opt(progname) # Cast command-line arguments into separate variables: in_files = args.profiles percent_height = args.percent phase_cut = args.phasecut n_poly_fit = args.npolyfit n_poly_order = args.npolyorder if(args.poisson): n_pts_omit = 0 else: n_pts_omit = n_poly_fit - 1 n_bootstrap = args.niter n_hist_bins = args.nhistbins n_pts_test = args.ntestphase peak_phase = args.peakphase peak_height = args.peakheight n_peak_bins = int(args.npeakbins/2.) # making it to be number of points on either side of data peak if(args.nobase): no_base=True else: no_base=False ## in_files = ['/Users/ferdman/Work/pulsar/0737-3039A/profs/add_campaigns/0737-3039A.20??.??.add.asc'] ### in_files = ['/Users/ferdman/Work/pulsar/1756-2251/profs/add_epochs/*.add.asc'] ## in_files = ['/Users/ferdman/Work/pulsar/1756-2251/profs/singleprofs/gasp/TemplateTestRot.asc'] ## percent_height = float(argv[1]) # percent_height = 25. # phase_cut = [0.5] ## phase_cut = [] # number of points on *each* side of the profile in fit, so there are # 2*n_poly_fit + 1 points to choose from ## n_poly_fit = 12 ## n_poly_fit = 12 # number of iterations of fit ## n_bootstrap = 32768 ## n_hist_bins = 48 ## n_hist_bins = 32 # number of points to omit for each iteration of fit # (= half total # of points -1) ## n_pts_omit = n_poly_fit-1 # number of points to use around expected phase to do root finding # for getting exact phase ## n_pts_test = 4 # order of polynomial in fit ## n_poly_order = 6 ## n_poly_order = 10 ##### peak_phase = 0.00321002 # known from finding peak in high-S/N template which we assume is aligned # n_poly_fit = 16 # n_bootstrap = 32768 # n_hist_bins = 48 # n_pts_omit = n_poly_fit # n_pts_test = 6 # n_poly_order = 8 # n_poly_order = 2*n_poly_fit - n_pts_omit - ## n_subplot_rows = 3 # 0737A ## n_subplot_cols = 5 # 0737A n_subplot_rows = 6 n_subplot_cols = 6 # matplotlib.rc('font', size=22) input_files = [] for file_name in in_files: # For some reason this works and ".append()" doesn't: input_files[len(input_files):] = glob.glob(file_name) n_files = len(input_files) # Determine number of rows and columns for subplotting # bootstrap results histograms. Always have it so n_cols >= n_rows n_subplot_rows, n_subplot_cols = get_rows_cols(n_files) print "n_profs = ", n_files print "Input files = ", input_files print " " print "Percent height = ", percent_height print "Num rows = ", n_subplot_rows print "Num cols = ", n_subplot_cols if(len(phase_cut) > 0): print "Will separate profiles into separate phase ranges before processing." if(len(phase_cut) ==1): print " Profile will be split along phase ", phase_cut[0] else: print " Profile will be split along phases ", phase_cut print " " mjd_width = np.zeros(len(input_files)) width = np.zeros((len(input_files), len(phase_cut)+1)) width_err = np.zeros((len(input_files), len(phase_cut)+1)) # A = np.zeros((len(input_files), len(phase_cut)+1)) # pdf_width = np.zeros((len(input_files), len(phase_cut)+1), n_hist_bins) # x_width = np.zeros((len(input_files), len(phase_cut)+1), n_hist_bins) for i_prof in np.arange(n_files): prof_data = read_asc_prof(input_files[i_prof], ionly=True) # Stokes I only for now prof_head = read_asc_header(input_files[i_prof]) psr_name = prof_head['psrname'] mjd_width[i_prof] = prof_head['imjd'] + prof_head['smjd']/86400. n_bins = len(prof_data['i']) phase_cut_bins = np.append(0., phase_cut)*n_bins phase_cut_bins = np.append(phase_cut_bins, n_bins) phase_cut_bins = phase_cut_bins.astype(int) #print "phase_cut_bins = ", phase_cut_bins phase_cuts = phase_cut_bins.astype(float)/n_bins #print "arange = ", np.arange(len(phase_cut_bins) - 1) # print "File ", input_files[i_prof] print " " mjdtext = 'MJD {0:8.2f}'.format(mjd_width[i_prof]) datetext = '{0:10s}'.format(mjd.mjdtodate(mjd_width[i_prof], dateformat="%Y-%b-%d")) print mjdtext, ' ', datetext prof_in = prof_data.copy() # x_peak, y_peak = get_peak(prof_in, n_pts_fit=10, n_order=19, n_test_fit=4) # plt.savefig('peak_fit.'+'{0:5.0f}'.format(mjd_width[i_prof])+'.png') for i_phase in np.arange(len(phase_cut_bins) - 1): print " Phase range {0:.2f} to {1:.2f}".format(prof_data['phase'][phase_cut_bins[i_phase]], \ prof_data['phase'][phase_cut_bins[i_phase+1]-1]) print " " prof_in['i'] = prof_data['i'][phase_cut_bins[i_phase]:phase_cut_bins[i_phase+1]-1] prof_in['phase'] = prof_data['phase'][phase_cut_bins[i_phase]:phase_cut_bins[i_phase+1]-1] width[i_prof,i_phase], width_err[i_prof,i_phase], A, pdf_width, x_width = \ get_width(prof_in, psr_name, percent_height, x_peak=peak_phase, y_peak=peak_height, nobase=no_base, n_pts_fit=n_poly_fit, n_order=n_poly_order, n_omit=n_pts_omit, n_test_fit=n_pts_test, n_boot=n_bootstrap, hist_bins=n_hist_bins, n_peak_bins=n_peak_bins, poisson=args.poisson, return_more=True) # Plot gaussian fit to bootstrap histograms as we go along as a grid of subplots: fig = plt.figure(i_phase) print 'N_ROWS = ', n_subplot_rows print 'N_COLS = ', n_subplot_cols print 'I_PROF = ', i_prof ax = fig.add_subplot(n_subplot_rows, n_subplot_cols, i_prof+1) # plt.subplot(3, 4, i_prof) ax.plot(x_width*360., pdf_width, linestyle='steps-mid', linewidth=1.4, color='blue') ax.plot(x_width*360., gaussian(x_width, A, width[i_prof, i_phase], width_err[i_prof, i_phase]), color='red') # Set y limits here since we can't retrieve them later: ax.set_ylim(0., 1.1*np.amax(np.append(pdf_width, A))) # set the number of ticks, putting them at nice locations, pruning off edge labels if they # happen on the plot corners: ax.xaxis.set_major_locator(matplotlib.ticker.MaxNLocator(4, prune='both')) ax.yaxis.set_major_locator(matplotlib.ticker.MaxNLocator(4, prune='both')) # No y ticklabels: ax.yaxis.set_ticklabels([]) # Add date as text to the top left corner of each subplot ax.text(0.04, 0.96, datetext, horizontalalignment='left', verticalalignment='top', \ fontsize='6', transform=ax.transAxes) print " Width = ", width[i_prof, i_phase], "+/-", width_err[i_prof, i_phase] print "" print "" # plt.show() # Set up formatter for scaling xtick labels: # major_formatter = FuncFormatter(tick_scale_formatter) print "len(phase_cut_bins) = ", len(phase_cut_bins) # print "phase_cuts = ", phase_cuts for i_phase in np.arange(len(phase_cut_bins) - 1): width_data = {'mjd':mjd_width, 'width':width[:, i_phase], 'werr':width_err[:, i_phase]} if(args.outbase==None): outfile_root = '{0}.w{1:.1f}.{2:3.1f}_{3:3.1f}'.format(psr_name, percent_height, phase_cuts[i_phase], phase_cuts[i_phase+1]) else: outfile_root = args.outbase # Plot widths we just calculated plot_widths(width_data, yunits='deg') plt.savefig(outfile_root+'.png') print np.std(width_data['width'])*360. # std dev in degrees print np.mean(width_data['werr'])*360. # Mean error print np.median(width_data['werr'])*360. # Mean error # Output plot of bootstrap histogram fig = plt.figure(i_phase) # Find overall lowest and highest x values, and calculate differnce x_lo = 360.0*np.amin((width_data['width'] - 6.0*width_data['werr'])) x_hi = 360.0*np.amin((width_data['width'] + 6.0*width_data['werr'])) x_span = np.abs(x_hi - x_lo) # Run through each profile and adjust limits to be consistent and show variation, and fix up labels for i_prof in np.arange(n_files): ax = fig.add_subplot(n_subplot_rows, n_subplot_cols, i_prof+1) # Centre on histogram, but set limits so that all subplots are on same scale: ax.set_xlim(360.*(width_data['width'][i_prof]) - 0.5*x_span, \ 360.0*(width_data['width'][i_prof]) + 0.5*x_span) # Set text size for tick labels, and get rid of all labels other than lower x axis: ax.tick_params(axis='x', labelsize=8, top='off') ax.tick_params(axis='y', left='off', right='off') # Rescale tick labels to some reasonable numbers by removing the lowest x value of all width hists major_formatter = FuncFormatter(lambda x, pos: ('%.1f')%(x - x_lo)) ax.xaxis.set_major_formatter(major_formatter) # x_tick_labels = ax.get_xticklabels() # tick_label.set_label(str( float(tick_label.get_text())/x_base_val) ) # x_tick_vals = [str( float(x_tick_labels[i_tick])/x_base_val ) for i_tick in len(x_ticks)] # ax.xticks(x_tick_locs, x_tick_labels) # ax.ticklabel_format(useOffset=0.6475, axis='x') # for tick in ax.xaxis.get_major_ticks(): # tick.label1.set_fontsize(8) # for tick in ax.yaxis.get_major_ticks(): # tick.label1.set_fontsize(8) # Set common labels by setting text on current plot (easiest way I found) -- x label only here: fig.text(0.5, 0.04, \ '{0:2d}% profile width (- {1:.1f} degrees)'.format(int(percent_height), x_lo), \ ha='center', va='center') # Output bootstrap histogram plots: plt.savefig(outfile_root+'.boot_fit.png') # Now output widths to file. outfile = '{0}.w{1:.1f}.{2:3.1f}_{3:3.1f}'.format(psr_name, percent_height, phase_cuts[i_phase], phase_cuts[i_phase+1])+'.dat' f_out = open(outfile, 'w') # First include a header line containing PSR name, percent height, # and phase range (which will usually be 0.0 to 1.0) f_out.write('# {0} w{1:.1f} {2:3.1f} {3:3.1f}\n'.format(psr_name, percent_height, phase_cuts[i_phase], phase_cuts[i_phase+1])) np.savetxt(outfile_root+'.dat', np.transpose((width_data['mjd'], width_data['width'], width_data['werr'])), fmt='%-23.15f %14.10f %14.10f') # x,y,z equal sized 1D arrays
def main(): # Input asp-style ascii profile will be first argument. # (command-line options to come later) prog_name = argv[0].strip('.py') # Scale factor for plotting difference plots scale = 2.0 # arg = get_opt(prog_name) # prof_file = argv[1] # ref_file = argv[1] ref_file = argv[len(argv)-1] input_files = [] for file in argv[1:]: # For some reason this works and ".append()" doesn't: input_files[len(input_files):] = glob.glob(file) # input_files.append(glob.glob(file)) input_files.reverse() # Remove reference file from list if it is in the plotting list if(input_files.count(ref_file) > 0): input_files.remove(ref_file) duty = get_duty('0737-3039A') # Read in reference profile ref_header = read_asc_header(ref_file) ref_data = read_asc_prof(ref_file) # ref_data['i'] = norm(ref_data['i'], duty) # Make first prof in list for plot to be the ref profile prof_data = [ref_data] ref_date = mjd.mjdtodate(ref_header['imjd'], \ dateformat='%Y %b %d') date_text = [(0.5, 0.20, ref_date)] nobs = [] # Now calculate difference profiles and append to plotting list for i_prof in np.arange(len(input_files)): prof_header = read_asc_header(input_files[i_prof]) nobs.append(prof_header['obscode']) print 'NOBS = ', nobs prof_data_temp = read_asc_prof(input_files[i_prof]) # prof_data_temp['i'] = norm(prof_data_temp['i'], duty) diff_prof = remove_base((prof_data_temp['i'] - ref_data['i']), duty) prof_data_temp['i'] = scale*(diff_prof) + i_prof + 1.2 print "Index = ", i_prof prof_data.append(prof_data_temp) # Set up labelling for each profile: prof_date = mjd.mjdtodate(prof_header['imjd'], \ dateformat='%Y %b %d') date_text.append((0.5, i_prof+1.4+scale*0.02, prof_date)) print "Date = ", date_text nobs_unique = list(set(nobs)) clr=[] for i_nobs in range(len(nobs)): if(nobs_unique <= 1): clr.append('black') else: clr.append(cm.gist_heat(float(nobs_unique.index(nobs[i_nobs]))/float(len(nobs_unique)))) # Do this just to make the ordering such that the first alphanumerically # is at the top... # prof_data.reverse() # date_text.reverse() plot_prof(prof_data, yticks=False, canvassize=(8,10), vgrid=False, \ ylim=(np.min(prof_data[0]['i'])-0.1, len(input_files)+1 +0.1), \ figtext=date_text, linecolour=clr) # meaningThe following means that the 2nd argument is the # desired output plot file name # plot_file = 'diff_profile.png' plot_file = 'diff_profile.pdf' plt.savefig(plot_file)
def main(): # Input asp-style ascii profile will be first argument. # (command-line options to come later) prog_name = argv[0].strip('.py') # arg = get_opt(prog_name) # prof_file = argv[1] input_files = [] for file in argv[1:]: # For some reason this works and ".appen()" doesn't: input_files[len(input_files):] = glob.glob(file) # input_files.append(glob.glob(file)) input_files.reverse() prof_data = [] # prof_date = [] date_text = [] # First, read in profile data file, and assign each column to a separate # numpy array # prof_file = input_files[0] # prof_header = read_asc_header(prof_file) # prof_data[0] = read_asc_prof(prof_file) duty = get_duty('0737-3039A') # if(len(input_files) > 1): # for prof_file in input_files: for i_prof in np.arange(len(input_files)): prof_header = read_asc_header(input_files[i_prof]) prof_data_temp = read_asc_prof(input_files[i_prof]) prof_data_temp['i'] = norm(prof_data_temp['i'], duty) prof_data_temp['i'] = prof_data_temp['i'] + i_prof print "Index = ", i_prof, \ ", Min = ", np.min(prof_data_temp['i']), \ ", Max = ", np.max(prof_data_temp['i']) prof_data.append(prof_data_temp) # Set up labelling for each profile: prof_date = mjd.mjdtodate(prof_header['imjd'], \ dateformat='%Y %b %d') date_text.append((0.5, i_prof+0.16, prof_date)) print "Date = ", date_text # Do this just to make the ordering such that the first alphanumerically # is at the top... # prof_data.reverse() # date_text.reverse() plot_prof(prof_data, yticks=False, canvassize=(8,10), \ hgrid=False, vgrid=False, \ ylim=(np.min(prof_data[0]['i'])-0.1, len(input_files)+0.1), \ figtext=date_text) # meaningThe following means that the 2nd argument is the # desired output plot file name # plot_file = 'multi_profile.png' plot_file = 'multi_profile.eps' plt.savefig(plot_file)
def main(): # Input asp-style ascii profile will be first argument. # (command-line options to come later) prog_name = argv[0].strip('.py') # arg = get_opt(prog_name) print 'n_args = ', len(argv) - 1 # prof_file = argv[1] input_files = [] for file in argv[1:]: # For some reason this works and ".appen()" doesn't: input_files[len(input_files):] = glob.glob(file) # input_files.append(glob.glob(file)) input_files.reverse() prof_data = [] # prof_date = [] date_text = [] # First, read in profile data file, and assign each column to a separate # numpy array # prof_file = input_files[0] # prof_header = read_asc_header(prof_file) # prof_data[0] = read_asc_prof(prof_file) # if(len(input_files) > 1): # for prof_file in input_files: nobs = [] for i_prof in np.arange(len(input_files)): prof_header = read_asc_header(input_files[i_prof]) duty = get_duty(prof_header['psrname']) nobs.append(prof_header['obscode']) print 'NOBS = ', nobs prof_data_temp = read_asc_prof(input_files[i_prof], ionly=True) prof_data_temp['i'] = norm(prof_data_temp['i'], duty) prof_data_temp['i'] = prof_data_temp['i'] + i_prof print "Index = ", i_prof, \ ", Min = ", np.min(prof_data_temp['i']), \ ", Max = ", np.max(prof_data_temp['i']) prof_data.append(prof_data_temp) # Set up labelling for each profile: prof_date = mjd.mjdtodate(prof_header['imjd'], \ dateformat='%Y %b %d') date_text.append((0.8, i_prof+0.25, prof_date)) print "Date = ", date_text nobs_unique = list(set(nobs)) clr=[] for i_nobs in range(len(nobs)): if(nobs_unique <= 1): clr.append('black') else: clr.append(cm.gist_heat(float(nobs_unique.index(nobs[i_nobs]))/float(len(nobs_unique)))) # Do this just to make the ordering such that the first alphanumerically # is at the top... # prof_data.reverse() # date_text.reverse() plot_prof(prof_data, yticks=False, canvassize=(8,10), \ hgrid=False, vgrid=False, \ ylim=(np.min(prof_data[0]['i'])-0.1, len(input_files)+0.1), figtext=date_text, linecolour=clr) # meaningThe following means that the 2nd argument is the # desired output plot file name # plot_file = 'multi_profile.png' plot_file = 'multi_profile.png' # plt.show() plt.savefig(plot_file)
def xte_chan2energy(ph_mjd, ph_chan, ph_pcuid, return_chans=False): # Set up start and stop dates for channel-energy table start_date = [datetime(1800,1,1,0,0,0), # just pick a time far in the past here datetime(1996, 3, 21, 18, 33, 0), datetime(1996, 4, 15, 23, 5, 0), datetime(1999, 3, 22, 17, 37, 0), datetime(2000, 5, 13, 0, 0, 0)] stop_date = [datetime(1996, 3, 21, 18, 33, 0), datetime(1996, 4, 15, 23, 5, 0), datetime(1999, 3, 22, 17, 37, 0), datetime(2000, 5, 13, 0, 0, 0), datetime(3000, 1, 1, 0, 0, 0)] # just pick a time far in the future here n_date = len(start_date) # Set chan_list to lower limit of channel range instead of a string with dashes... chan_list = np.loadtxt(chan_table_file, dtype=str, skiprows=13, usecols=(0,)) #chan_list = np.append(chan_list, 256) for i_chan in range(len(chan_list)): n_dash = chan_list[i_chan].count('-') if(n_dash > 0): chan_list[i_chan] = chan_list[i_chan][0:chan_list[i_chan].index('-')] chan_list = np.array(map(int, chan_list)) # Now fill in 'in between' indices and map them to energy index. energy_ind = [] for i_chan in range(len(chan_list)): # Not counting the last element, in which case I will append, not insert if(i_chan < len(chan_list)-1): n_diff = chan_list[i_chan+1] - chan_list[i_chan] else: n_diff = 256 - chan_list[len(chan_list) - 1] for i_ind in range(n_diff): energy_ind.append(i_chan) energy_ind = np.array(energy_ind) # print 'n_energy = ', len(energy_ind) # print 'energy_ind = ', energy_ind # add a final number on the end here for ease of testing ranges #print 'n_chan = ', len(chan_list) #print 'n_chan = ', len(chan_list) #print 'CHAN_LIST = ', chan_list # Now read in table of energies, which depend on date the datra was taken chan_table = np.loadtxt(chan_table_file, skiprows=13, usecols=(2,3,4,5,6,7)) # Channel table is now indexed as chan_table[pha_range][date/pcuid] # Need to differentiate between PCUOD = 0 OR > 0 for start/stop_date[4] n_event = len(ph_mjd) ## ph_chan_new = np.zeros_like(ph_chan) # Map ph_chan input (0-255) to a row number from table (0-128) using chan_list extracted above ## for i_event in range(n_event): # for i_chan in range(len(chan_list)): ## i_chan = 0 ## while((i_chan < len(chan_list)-1) and (not (chan_list[i_chan] <= ph_chan[i_event] < chan_list[i_chan+1]))): #print 'i_chan = ', i_chan ## i_chan += 1 ## if(i_chan >= len(chan_list)): ## print 'Warning: PHA value at MJD {0:10.4f} is {1:d}'.format(ph_mjd, ph_chan) ## print ' Setting to -1.' ## ph_chan_new[i_event] = -1 ## else: ## ph_chan_new[i_event] = i_chan # Make array of datetime-format dates from MJDs ph_datetime = mjd.mjdtodate(ph_mjd) ph_chan_col = np.zeros_like(ph_datetime) - 1 # initialize to -1 for i_date in range(n_date): if(i_date < 4): match_ind = np.where((ph_datetime > start_date[i_date]) & (ph_datetime < stop_date[i_date])) ph_chan_col[match_ind] = i_date else: # to accoutn for final date split between PCUID 0 vs 1/2/3/4 match_ind = np.where((ph_datetime > start_date[i_date]) & (ph_datetime < stop_date[i_date]) & (ph_pcuid == 0)) ph_chan_col[match_ind] = 4 match_ind = np.where((ph_datetime > start_date[i_date]) & (ph_datetime < stop_date[i_date]) & (ph_pcuid > 0)) ph_chan_col[match_ind] = 5 # Read off energies from table based on PHA channel keyword and date index. # Energies in table are EMAX, so EMIN for a given channel is given as the energy corresponding to channel-1 # If channel = 0, then EMIN = 0. ph_emin = np.array([chan_table[energy_ind[ph_chan[i_event]]-1][ph_chan_col[i_event]] if(energy_ind[ph_chan[i_event]]>0) else 0. for i_event in range(n_event)]) ph_emin[ph_chan_col < 0] = -1. ph_emax = np.array([chan_table[energy_ind[ph_chan[i_event]]][ph_chan_col[i_event]] for i_event in range(n_event)]) ph_emax[ph_chan_col < 0] = -1. ph_erange = np.array([(ph_emin[i_event], ph_emax[i_event]) for i_event in range(n_event)]) if(return_chans==True): return ph_erange, ph_chan, energy_ind[ph_chan] else: return ph_erange