def angles_between_discrete(angles): theta, phi = zip(*angles) distances = angle_between(0., 0., np.array(theta), np.array(phi)) counts, bins = np.histogram(distances, bins=np.linspace(0, np.pi, 721)) plotd = Plot() plotd.histogram(counts, np.degrees(bins)) # plotd.set_title('Distance between reconstructed angles for station and cluster') plotd.set_xlabel('Angle between reconstructions [\si{\degree}]') plotd.set_ylabel('Counts') plotd.set_xlimits(min=0, max=90) plotd.set_ylimits(min=0) plotd.save_as_pdf('angle_between_Zenith_discrete') plotd = Plot() distances = [] for t, p in angles: distances.extend(angle_between(t, p, np.array(theta), np.array(phi))) counts, bins = np.histogram(distances, bins=np.linspace(0, np.pi, 361)) plotd.histogram(counts, np.degrees(bins)) # plotd.set_title('Distance between reconstructed angles for station and cluster') plotd.set_xlabel('Angle between reconstructions [\si{\degree}]') plotd.set_ylabel('Counts') plotd.set_xlimits(min=0, max=90) plotd.set_ylimits(min=0) plotd.save_as_pdf('angle_between_Zenith_discrete_all')
def analyse(name): data = genfromtxt('data/%s.tsv' % name, delimiter='\t', dtype=None, names=['ext_timestamp', 'time_delta']) time_delta = data['time_delta'] # Plot distribution counts, bins = histogram(time_delta, bins=arange(-10.5, 11.5, 1)) plot = Plot() plot.histogram(counts, bins) plot.set_ylimits(min=0) plot.set_ylabel('counts') plot.set_xlabel(r'time delta [\si{\nano\second}]') plot.save_as_pdf(name) # Plot moving average n = 300 skip = 20 moving_average = convolve(time_delta, ones((n,)) / n, mode='valid') plot = Plot() timestamps = (data['ext_timestamp'][:-n + 1:skip] - data['ext_timestamp'][0]) / 1e9 / 3600. plot.plot(timestamps, moving_average[::skip], mark=None) plot.set_xlimits(min=0) plot.set_ylabel(r'time delta [\si{\nano\second}]') plot.set_xlabel('timestamp [\si{\hour}]') plot.save_as_pdf('moving_average_%s' % name)
def analyse(name): data = genfromtxt('data/%s.tsv' % name, delimiter='\t', dtype=None, names=['ext_timestamp', 'time_delta']) time_delta = data['time_delta'] # Plot distribution counts, bins = histogram(time_delta, bins=arange(-10.5, 11.5, 1)) plot = Plot() plot.histogram(counts, bins) x = (bins[1:] + bins[:-1]) / 2. popt, pcov = curve_fit(gauss, x, counts, p0=(sum(counts), 0., 2.5)) plot.plot(x, gauss(x, *popt), mark=None) print popt plot.set_ylimits(min=0) plot.set_ylabel('Counts') plot.set_xlabel(r'Time delta [\si{\nano\second}]') plot.save_as_pdf(name) # Plot moving average n = 5000 skip = 100 moving_average = convolve(time_delta, ones((n,)) / n, mode='valid') plot = Plot() timestamps = (data['ext_timestamp'][:-n + 1:skip] - data['ext_timestamp'][0]) / 1e9 / 3600. plot.plot(timestamps, moving_average[::skip], mark=None) plot.set_xlimits(min=0) plot.set_ylabel(r'time delta [\si{\nano\second}]') plot.set_xlabel('timestamp [\si{\hour}]') plot.save_as_pdf('moving_average_%s' % name)
def plot_detected_v_energy(): plot = Plot(width=r'.6\textwidth') # plot.set_title('Detected core distances vs shower energy') c, xb, yb = histogram2d(r_in, energy_in, bins=(arange(0, 600, 40), arange(15.75, 17.76, .5))) plot.histogram2d(c, xb, yb, bitmap=True) plot.set_yticks([16, 16.5, 17, 17.5]) plot.set_ytick_labels(['$10^{%.1f}$' % e for e in [16, 16.5, 17, 17.5]]) plot.set_ylabel(r'Shower energy [\si{\eV}]') plot.set_xlabel(r'Core distance [\si{\meter}]') plot.save_as_pdf('detected_v_energy') plot = Plot(width=r'.6\textwidth') # plot.set_title('Detected core distances vs shower energy, scaled to bin area') counts, xbins, ybins = histogram2d(r_in, energy_in, bins=(arange(0, 600, 40), arange(15.75, 17.76, .5))) plot.histogram2d((-counts.T / (pi * (xbins[:-1]**2 - xbins[1:]**2))).T, xbins, ybins, type='area') plot.set_yticks([16, 16.5, 17, 17.5]) plot.set_ytick_labels(['$10^{%.1f}$' % e for e in [16, 16.5, 17, 17.5]]) plot.set_ylabel(r'Shower energy [\si{\eV}]') plot.set_xlabel(r'Core distance [\si{\meter}]') plot.save_as_pdf('detected_v_energy_scaled_area')
def compare_ttrigger(): with tables.open_file(DATA_PATH, 'r') as data: processed = data.get_node(GROUP, 'events_processed') filtered = data.get_node(GROUP, 'events_filtered') assert all( processed.col('ext_timestamp') == filtered.col('ext_timestamp')) trig_proc = processed.col('t_trigger') trig_filt = filtered.col('t_trigger') dt_trigger = trig_filt - trig_proc density = (processed.col('n1') + processed.col('n2') + processed.col('n3') + processed.col('n4')) / 2 print 'Density range:', density.min(), density.max() print 'dt trigger range:', dt_trigger.min(), dt_trigger.max() if len(trig_proc) > 4000: plot = Plot() bins = [linspace(0, 30, 100), arange(-11.25, 75, 2.5)] c, x, y = histogram2d(density, dt_trigger, bins=bins) # plot.histogram2d(c, x, y, bitmap=True, type='color', colormap='viridis') plot.histogram2d(log10(c + 0.01), x, y, type='area') plot.set_xlabel('Particle density') plot.set_ylabel('Difference in trigger time') plot.save_as_pdf('hist2d') else: plot = Plot() plot.scatter( density, dt_trigger, mark='o', markstyle='mark size=0.6pt, very thin, semitransparent') plot.set_xlabel('Particle density') plot.set_ylabel('Difference in trigger time') plot.save_as_pdf('scatter') plot = Plot() c, bins = histogram(dt_trigger, arange(-10, 200, 2.5)) c = where(c < 100, c, 100) plot.histogram(c, bins) plot.set_ylimits(0, 100) plot.set_ylabel('Counts') plot.set_xlabel('Difference in trigger time') plot.save_as_pdf('histogram') plot = Plot() c, bins = histogram(trig_proc, arange(-10, 200, 2.5)) plot.histogram(c, bins) c, bins = histogram(trig_filt, arange(-10, 200, 2.5)) plot.histogram(c, bins, linestyle='red') plot.set_ylimits(0) plot.set_ylabel('Counts') plot.set_xlabel('Trigger time') plot.save_as_pdf('histogram_t')
def plot_comparisons(data): multi_cidx = data.root.coincidences.coincidences.get_where_list('N > 2') c_idx = data.root.coincidences.c_index[multi_cidx] min_zenith = 0.2 r510 = data.get_node('/hisparc/cluster_amsterdam/station_510/', 'reconstructions') subset510 = [True] * r510.nrows id510 = next(i for i, s in enumerate(data.root.coincidences.s_index[:]) if s.endswith('_510')) for cidx in c_idx: if sum(cidx[:, 0] == id510) > 1: eid = next(i for s, i in cidx if s == id510) subset510[eid] = False r510a = r510.col('azimuth').compress(subset510) r510z = r510.col('zenith').compress(subset510) filter510 = r510z > min_zenith for order in itertools.permutations(range(4), 4): r507 = data.get_node('/hisparc/cluster_amsterdam/station_507/', REC_PATH % order) subset507 = [True] * r507.nrows id507 = next(i for i, s in enumerate(data.root.coincidences.s_index[:]) if s.endswith('_507')) for cidx in c_idx: if sum(cidx[:, 0] == id507) > 1: eid = next(i for s, i in cidx if s == id507) subset507[eid] = False r507a = r507.col('azimuth').compress(subset507) r507z = r507.col('zenith').compress(subset507) filter507 = r507z > min_zenith # Ensure neither has low zenith angle to avoid high uncertaintly # on azimuth. filter = filter510 & filter507 counts, xbins, ybins = histogram2d(r507a.compress(filter), r510a.compress(filter), bins=linspace(-pi, pi, 40)) plot = Plot() plot.histogram2d(counts, xbins, ybins, bitmap=True, type='color') plot.set_ylabel(r'Azimuth 510 [\si{\radian}]') plot.set_xlabel(r'Azimuth 507 [\si{\radian}]') plot.save_as_pdf(REC_PATH % order) counts, xbins, ybins = histogram2d(r507z, r510z, bins=linspace(0, pi / 2., 40)) plot = Plot() plot.histogram2d(counts, xbins, ybins, bitmap=True, type='color') plot.set_ylabel(r'Zenith 510 [\si{\radian}]') plot.set_xlabel(r'Zenith 507 [\si{\radian}]') plot.save_as_pdf('zenith_' + REC_PATH % order)
def analyse(): """Plot results from reconstructions compared to the simulated input""" with tables.open_file(DATAPATH, 'r') as data: coincidences = data.get_node('/coincidences/coincidences') reconstructions = data.get_node(STATION_PATH) assert coincidences.nrows == reconstructions.nrows zenith_in = coincidences.col('zenith') azimuth_in = coincidences.col('azimuth') zenith_re = reconstructions.col('zenith') azimuth_re = reconstructions.col('azimuth') d_angle = angle_between(zenith_in, azimuth_in, zenith_re, azimuth_re) print sum(isnan(d_angle)) plot = Plot() counts, bins = histogram(d_angle[invert(isnan(d_angle))], bins=50) plot.histogram(counts, bins) plot.set_ylimits(min=0) plot.set_xlabel(r'Angle between \si{\radian}') plot.set_ylabel('Counts') plot.save_as_pdf('angle_between') plot = Plot() counts, bins = histogram(zenith_in, bins=50) plot.histogram(counts, bins, linestyle='red') counts, bins = histogram(zenith_re, bins=bins) plot.histogram(counts, bins) plot.set_ylimits(min=0) plot.set_xlimits(min=0) plot.set_xlabel(r'Zenith \si{\radian}') plot.set_ylabel('Counts') plot.save_as_pdf('zenith') plot = Plot() counts, bins = histogram(azimuth_in, bins=50) plot.histogram(counts, bins, linestyle='red') counts, bins = histogram(azimuth_re, bins=bins) plot.histogram(counts, bins) plot.set_ylimits(min=0) plot.set_xlabel(r'Azimuth \si{\radian}') plot.set_ylabel('Counts') plot.save_as_pdf('azimuth') unique_coordinates = list({(z, a) for z, a in zip(zenith_re, azimuth_re)}) zenith_uni, azimuth_uni = zip(*unique_coordinates) plot = PolarPlot(use_radians=True) plot.scatter(array(azimuth_uni), array(zenith_uni), markstyle='mark size=.75pt') plot.set_xlabel(r'Azimuth \si{\radian}') plot.set_ylabel(r'Zenith \si{\radian}') plot.save_as_pdf('polar')
def plot_E_d_P(ldf): energies = linspace(13, 21, 100) sizes = energy_to_size(energies, 13.3, 1.07) core_distances = logspace(-1, 4.5, 100) probabilities = [] for size in sizes: prob_temp = [] for distance in core_distances: prob_temp.append(P_2(ldf, distance, size)) probabilities.append(prob_temp) probabilities = array(probabilities) plot = Plot('semilogx') low = [] mid = [] high = [] for p in probabilities: # Using `1 -` to ensure x (i.e. p) is increasing. low.append(interp(1 - 0.10, 1 - p, core_distances)) mid.append(interp(1 - 0.50, 1 - p, core_distances)) high.append(interp(1 - 0.90, 1 - p, core_distances)) plot.plot(low, energies, linestyle='densely dotted', mark=None) plot.plot(mid, energies, linestyle='densely dashed', mark=None) plot.plot(high, energies, mark=None) plot.set_ylimits(13, 20) plot.set_xlimits(1., 1e4) plot.set_xlabel(r'Core distance [\si{\meter}]') plot.set_ylabel(r'Energy [log10(E/\si{\eV})]') plot.save_as_pdf('efficiency_distance_energy_' + ldf.__class__.__name__)
def plot_n_azimuth(path='/'): with tables.open_file(RESULT_DATA, 'r') as data: coin = data.get_node(path + 'coincidences/coincidences') in_azi = coin.col('azimuth') ud_azi = coin.read_where('s0', field='azimuth') lr_azi = coin.read_where('s1', field='azimuth') sq_azi = coin.read_where('s2', field='azimuth') udlr_azi = coin.get_where_list('s0 & s1') print('Percentage detected in both %f ' % (float(len(udlr_azi)) / len(in_azi))) bins = np.linspace(-np.pi, np.pi, 30) in_counts = np.histogram(in_azi, bins)[0].astype(float) ud_counts = np.histogram(ud_azi, bins)[0].astype(float) lr_counts = np.histogram(lr_azi, bins)[0].astype(float) sq_counts = np.histogram(sq_azi, bins)[0].astype(float) print('Detected: UD %d | LR %d | SQ %d' % (sum(ud_counts), sum(lr_counts), sum(sq_counts))) plot = Plot() plot.histogram(ud_counts / in_counts, bins, linestyle='black') plot.histogram(lr_counts / in_counts, bins + 0.01, linestyle='red') plot.histogram(sq_counts / in_counts, bins + 0.01, linestyle='blue') plot.histogram((ud_counts - lr_counts) / in_counts, bins, linestyle='black') plot.set_xlabel(r'Shower azimuth [\si{\radian}]') plot.set_ylabel(r'Percentage detected') plot.set_xlimits(bins[0], bins[-1]) plot.draw_horizontal_line(0, linestyle='thin, gray') # plot.set_ylimits(0) plot.save_as_pdf('azimuth_percentage' + path.replace('/', '_'))
def analyse_reconstructions(data): cq = CoincidenceQuery(data) c_ids = data.root.coincidences.coincidences.read_where('s505 & (timestamp < 1366761600)', field='id') c_recs = cq.reconstructions.read_coordinates(c_ids) s_ids = data.root.hisparc.cluster_amsterdam.station_505.events.get_where_list('timestamp < 1366761600') s_recs = data.root.hisparc.cluster_amsterdam.station_505.reconstructions.read_coordinates(s_ids) assert len(c_recs) == len(s_recs) zenc = c_recs['zenith'] azic = c_recs['azimuth'] zens = s_recs['zenith'] azis = s_recs['azimuth'] high_zenith = (zenc > .2) & (zens > .2) for minn in [1, 2, 4, 8, 16]: filter = (s_recs['min_n'] > minn) length = len(azis.compress(high_zenith & filter)) shifts501 = np.random.normal(0, .06, length) azicounts, x, y = np.histogram2d(azis.compress(high_zenith & filter) + shifts501, azic.compress(high_zenith & filter), bins=np.linspace(-np.pi, np.pi, 73)) plota = Plot() plota.histogram2d(azicounts, np.degrees(x), np.degrees(y), type='reverse_bw', bitmap=True) # plota.set_title('Reconstructed azimuths for events in coincidence (zenith gt .2 rad)') plota.set_xlabel(r'$\phi_{505}$ [\si{\degree}]') plota.set_ylabel(r'$\phi_{Science Park}$ [\si{\degree}]') plota.set_xticks([-180, -90, 0, 90, 180]) plota.set_yticks([-180, -90, 0, 90, 180]) plota.save_as_pdf('azimuth_505_spa_minn%d' % minn)
def main(ts, ns): station = Station(501) traces = station.event_trace(ts, ns, True) dr = DataReduction() reduced_traces, o = dr.reduce_traces(array(traces).T, return_offset=True) reduced_traces = reduced_traces.T plot = Plot() t = arange(len(traces[0])) * 2.5 for i, trace in enumerate(traces): plot.plot(t, trace, linestyle='%s, thin' % COLORS[i], mark=None) plot.draw_vertical_line(o * 2.5, 'gray') plot.draw_vertical_line((o + len(reduced_traces[0])) * 2.5, 'gray') plot.set_axis_options('line join=round') plot.set_xlabel(r'Event time [\si{\ns}]') plot.set_ylabel(r'Signal strength [ADCcounts]') plot.set_xlimits(t[0], t[-1]) plot.save_as_pdf('raw_traces_%d_%d' % (ts, ns)) t = arange(o, o + len(reduced_traces[0])) * 2.5 for i, trace in enumerate(reduced_traces): plot.plot(t, trace, linestyle='%s, thin' % COLORS[i], mark=None) plot.set_axis_options('line join=round') plot.set_xlabel(r'Event time [\si{\ns}]') plot.set_ylabel(r'Signal strength [ADCcounts]') plot.set_xlimits(t[0], t[-1]) plot.save_as_pdf('reduced_traces_%d_%d' % (ts, ns))
def plot_shower_size(leptons=['electron', 'muon']): plot = Plot(axis='semilogy') cq = CorsikaQuery(OVERVIEW) p = 'proton' for e in sorted(cq.available_parameters('energy', particle=p)): median_size = [] min_size = [] max_size = [] zeniths = sorted(cq.available_parameters('zenith', energy=e, particle=p)) for z in zeniths: selection = cq.simulations(zenith=z, energy=e, particle=p) n_leptons = selection['n_%s' % leptons[0]] for lepton in leptons[1:]: n_leptons += selection['n_%s' % lepton] sizes = percentile(n_leptons, [16, 50, 84]) min_size.append(sizes[0] if sizes[0] else 0.1) median_size.append(sizes[1] if sizes[1] else 0.1) max_size.append(sizes[2] if sizes[2] else 0.1) if len(zeniths): plot.plot(zeniths, median_size, linestyle='very thin') plot.shade_region(zeniths, min_size, max_size, color='lightgray, semitransparent') plot.add_pin('%.1f' % e, relative_position=0) plot.set_xticks([t for t in arange(0, 60.1, 7.5)]) plot.set_ylimits(1, 1e9) plot.set_ylabel(r'Shower size (leptons)') plot.set_xlabel(r'Zenith [\si{\degree}]') plot.save_as_pdf('shower_sizes_%s' % '_'.join(leptons)) cq.finish()
def plot_coincidence_rate_distance(data, sim_data): """Plot results :param distances: dictionary with occuring distances for different combinations of number of detectors. :param coincidence_rates: dictionary of occuring coincidence rates for different combinations of number of detectors. :param rate_errors: errors on the coincidence rates. """ (distances, coincidence_rates, interval_rates, distance_errors, rate_errors, pairs) = data sim_distances, sim_energies, sim_areas = sim_data markers = {4: 'o', 6: 'triangle', 8: 'square'} colors = {4: 'red', 6: 'black!50!green', 8: 'black!20!blue'} coincidence_window = 10e-6 # seconds freq_2 = 0.3 freq_4 = 0.6 background = { 4: 2 * freq_2 * freq_2 * coincidence_window, 6: 2 * freq_2 * freq_4 * coincidence_window, 8: 2 * freq_4 * freq_4 * coincidence_window } for rates, name in [(coincidence_rates, 'coincidence'), (interval_rates, 'interval')]: plot = Plot('loglog') for n in distances.keys(): plot.draw_horizontal_line(background[n], 'dashed,' + colors[n]) # for n in distances.keys(): for n in [4, 8]: expected_rates = expected_rate(distances[n], rates[n], background[n], sim_distances, sim_energies, sim_areas[n], n=n) plot.plot(sim_distances, expected_rates, linestyle=colors[n], mark=None, markstyle='mark size=0.5pt') for n in distances.keys(): plot.scatter(distances[n], rates[n], xerr=distance_errors[n], yerr=rate_errors[n], mark=markers[n], markstyle='%s, mark size=.75pt' % colors[n]) plot.set_xlabel(r'Distance between stations [\si{\meter}]') plot.set_ylabel(r'%s rate [\si{\hertz}]' % name.title()) plot.set_axis_options('log origin y=infty') plot.set_xlimits(min=1, max=20e3) plot.set_ylimits(min=1e-7, max=5e-1) plot.save_as_pdf('distance_v_%s_rate' % name)
def plot_fit(x, data, slope, intercept, pair): plot = Plot() plot.scatter(x, log(c)) plot.plot(x, x * slope + intercept, mark=None) plot.set_ylimits(min=0) plot.set_label(r'%.1e \si{\hertz}' % rate) plot.save_as_pdf('intervals/intervals_%d_%d_r' % pair)
def plot_delta_test(): """ Plot the delta with std """ # Define Bins low = -2000 high = 2000 bin_size = 10 # 2.5*n? bins = np.arange(low - .5 * bin_size, high + bin_size, bin_size) tests = test_log_508() # Begin Figure plot = Plot() with tables.open_file(DELTAS_PATH, 'r') as delta_file: for test in tests: delta_table = delta_file.get_node('/t%d' % test.id, 'delta') ext_timestamps = [row['ext_timestamp'] for row in delta_table] deltas = [row['delta'] for row in delta_table] bins = np.arange(low - 0.5 * bin_size, high + bin_size, bin_size) n, bins = np.histogram(deltas, bins) plot.histogram(n, bins) plot.set_title('Time difference coincidences 508') # plot.set_label(r'$\mu={1:.1f}$, $\sigma={2:.1f}$'.format(*popt)) plot.set_xlabel(r'$\Delta$ t (station - 508) [\SI{\ns}]') plot.set_ylabel(r'p') plot.set_xlimits(low, high) plot.set_ylimits(min=0., max=0.15) plot.save_as_pdf('plots/508/histogram.pdf')
def plot_pulseheight_histogram(data): events = data.root.hisparc.cluster_kascade.station_601.events ph = events.col('n1') s = landau.Scintillator() mev_scale = 3.38 / 1. count_scale = 6e3 / .32 n, bins = histogram(ph, bins=arange(0, 9, 0.025)) x = linspace(0, 9, 1500) plot = Plot() n_trunc = where(n <= 100000, n, 100000) plot.histogram(n_trunc, bins, linestyle='gray') plot.plot(x, s.conv_landau_for_x(x, mev_scale=mev_scale, count_scale=count_scale, gauss_scale=.68), mark=None) # plot.add_pin('convolved Landau', x=1.1, location='above right', # use_arrow=True) plot.plot(x, count_scale * s.landau_pdf(x * mev_scale), mark=None, linestyle='black') # plot.add_pin('Landau', x=1., location='above right', use_arrow=True) plot.set_xlabel(r"Number of particles") plot.set_ylabel(r"Number of events") plot.set_xlimits(0, 9) plot.set_ylimits(0, 21000) plot.save_as_pdf("plot_pulseheight_histogram_pylandau")
def offset_distribution(offsets): """Examine offset distribution using intermediate stations Start and end station are the same, but hops via some other stations. The result should ideally be an offset of 0 ns. :param offsets: Dictionary of dictionaries with offset functions. """ aoffsets = get_aligned_offsets(offsets, START, STOP, STEP) stations = offsets.keys() for n in [2, 3, 4, 5]: plot = Plot() offs = [] for ref in stations: for s in permutations(stations, n): if ref in s: continue offs.extend(aoffsets[ref][s[0]] + aoffsets[s[-1]][ref] + sum(aoffsets[s[i]][s[i + 1]] for i in range(n - 1))) plot.histogram(*histogram(offs, bins=range(-100, 100, 2))) plot.set_xlimits(-100, 100) plot.set_ylimits(min=0) plot.set_title('n = %d' % n) plot.set_xlabel(r'Station offset residual [\si{\ns}]') plot.save_as_pdf('plots/round_trip_dist_%d' % n)
def plot_offset_timeline(ref_station, station): ref_s = Station(ref_station) s = Station(station) # ref_gps = ref_s.gps_locations # ref_voltages = ref_s.voltages # ref_n = get_n_events(ref_station) # gps = s.gps_locations # voltages = s.voltages # n = get_n_events(station) # Determine offsets for first day of each month # d_off = s.detector_timing_offsets s_off = get_station_offsets(ref_station, station) graph = Plot(width=r'.6\textwidth') # graph.scatter(ref_gps['timestamp'], [95] * len(ref_gps), mark='square', markstyle='purple,mark size=.5pt') # graph.scatter(ref_voltages['timestamp'], [90] * len(ref_voltages), mark='triangle', markstyle='purple,mark size=.5pt') # graph.scatter(gps['timestamp'], [85] * len(gps), mark='square', markstyle='gray,mark size=.5pt') # graph.scatter(voltages['timestamp'], [80] * len(voltages), mark='triangle', markstyle='gray,mark size=.5pt') # graph.shade_region(n['timestamp'], -ref_n['n'] / 1000, n['n'] / 1000, color='lightgray,const plot') # graph.plot(d_off['timestamp'], d_off['d0'], markstyle='mark size=.5pt') # graph.plot(d_off['timestamp'], d_off['d2'], markstyle='mark size=.5pt', linestyle='green') # graph.plot(d_off['timestamp'], d_off['d3'], markstyle='mark size=.5pt', linestyle='blue') graph.plot(s_off['timestamp'], s_off['offset'], mark='*', markstyle='mark size=1.25pt', linestyle=None) graph.set_ylabel('$\Delta t$ [ns]') graph.set_xlabel('Date') graph.set_xticks( [datetime_to_gps(date(y, 1, 1)) for y in range(2010, 2016)]) graph.set_xtick_labels(['%d' % y for y in range(2010, 2016)]) graph.set_xlimits(1.25e9, 1.45e9) graph.set_ylimits(-150, 150) graph.save_as_pdf('plots/offsets/offsets_ref%d_%d' % (ref_station, station))
def determine_detector_timing_offsets(d, s, events): """Determine the offsets between the station detectors. ADL: Currently assumes detector 1 is a good reference. But this is not always the best choice. Perhaps it should be determined using more data (more than one day) to be more accurate. """ bins = arange(-100 + 1.25, 100, 2.5) col = (cl for cl in COLORS) graph = Plot() for i, j in itertools.combinations(range(1, 5), 2): ti = events.col('t%d' % i) tj = events.col('t%d' % j) dt = (ti - tj).compress((ti >= 0) & (tj >= 0)) y, bins = histogram(dt, bins=bins) graph.histogram(y, bins, linestyle='color=%s' % col.next()) x = (bins[:-1] + bins[1:]) / 2 try: popt, pcov = curve_fit(gauss, x, y, p0=(len(dt), 0., 10.)) print '%d-%d: %f (%f)' % (i, j, popt[1], popt[2]) except (IndexError, RuntimeError): print '%d-%d: failed' % (i, j) graph.set_title('Time difference, station %d' % (s)) graph.set_label('%s' % d.replace('_', ' ')) graph.set_xlimits(-100, 100) graph.set_ylimits(min=0) graph.set_xlabel('$\Delta t$') graph.set_ylabel('Counts') graph.save_as_pdf('%s_%d' % (d, s))
def plot_coincidence_v_interval_rate(data): """Plot results :param distances: dictionary with occuring distances for different combinations of number of detectors. :param coincidence_rates: dictionary of occuring coincidence rates for different combinations of number of detectors. :param rate_errors: errors on the coincidence rates. """ (distances, coincidence_rates, interval_rates, distance_errors, rate_errors, pairs) = data markers = {4: 'o', 6: 'triangle', 8: 'square'} colors = {4: 'red', 6: 'black!50!green', 8: 'black!20!blue'} plot = Plot('loglog') plot.plot([1e-7, 1e-1], [1e-7, 1e-1], mark=None) for n in distances.keys(): plot.scatter(interval_rates[n], coincidence_rates[n], yerr=rate_errors[n], mark=markers[n], markstyle='%s, thin, mark size=.75pt' % colors[n]) plot.set_xlabel(r'Rate based on coincidence intervals [\si{\hertz}]') plot.set_ylabel(r'Rate based on coincidences and exposure [\si{\hertz}]') plot.set_axis_options('log origin y=infty') plot.set_xlimits(min=1e-7, max=1e-1) plot.set_ylimits(min=1e-7, max=1e-1) plot.save_as_pdf('interval_v_coincidence_rate')
def plot_densities(data): """Make particle count plots for each detector to compare densities/responses""" n_min = 0.001 # remove peak at 0 n_max = 9 bins = np.linspace(n_min, n_max, 80) events = data.get_node('/s1001', 'events') sum_n = events.col('n1') + events.col('n2') n = [events.col('n1'), events.col('n2')] for minn in [0, 1, 2, 4, 8, 16]: filter = sum_n > minn plot = Plot(width=r'.25\linewidth', height=r'.25\linewidth') i = 0 j = 1 ncounts, x, y = np.histogram2d(n[i].compress(filter), n[j].compress(filter), bins=bins) plot.histogram2d(ncounts, x, y, type='reverse_bw', bitmap=True) plot.set_xlimits(min=0, max=n_max) plot.set_ylimits(min=0, max=n_max) plot.set_xlabel('Number of particles in detector 1') plot.set_ylabel('Number of particles in detector 2') plot.save_as_pdf('plots/n_minn%d_1001' % minn)
def plot_delta_test(ids, **kwargs): """ Plot the delta with std """ if type(ids) is int: ids = [ids] # Define Bins low = -200 high = 200 bin_size = 1 bins = np.arange(low - .5 * bin_size, high + bin_size, bin_size) # Begin Figure plot = Plot() for id in ids: ext_timestamps, deltas = get(id) n, bins = np.histogram(deltas, bins, density=True) plot.histogram(n, bins) if kwargs.keys(): plot.set_title('Tijdtest ' + kwargs[kwargs.keys()[0]]) plot.set_xlabel(r'$\Delta$ t (swap - reference) [ns]') plot.set_ylabel(r'p') plot.set_xlimits(low, high) plot.set_ylimits(0., .15) # Save Figure if len(ids) == 1: name = 'tt_delta_hist_%03d' % ids[0] elif kwargs.keys(): name = 'tt_delta_hist_' + kwargs[kwargs.keys()[0]] plot.save_as_pdf(PLOT_PATH + name) print 'tt_analyse: Plotted histogram'
def plot_interaction_height(cq): plot = Plot() p = 'proton' for e in sorted(cq.available_parameters('energy', particle=p)): median_altitude = [] min_altitude = [] max_altitude = [] zeniths = [] for z in sorted(cq.available_parameters('zenith', particle=p, energy=e)): selection = cq.simulations(particle=p, energy=e, zenith=z) if len(selection) > 50: interaction_altitudes = selection[ 'first_interaction_altitude'] / 1e3 median_altitude.append(median(interaction_altitudes)) min_altitude.append(percentile(interaction_altitudes, 2)) max_altitude.append(percentile(interaction_altitudes, 98)) zeniths.append(z) if len(zeniths): plot.plot(zeniths + (e - 12) / 3., median_altitude) # plot.shade_region(zeniths, min_altitude, max_altitude, # color='lightgray,semitransparent') plot.add_pin('%.1f' % e, relative_position=0) plot.set_ylabel(r'First interaction altitude [\si{\kilo\meter}]') plot.set_xlabel(r'Zenith [\si{\radian}]') plot.save_as_pdf('plots/interaction_altitude')
def plot_densities(data): """Make particle count plots for each detector to compare densities/responses""" e501 = data.get_node('/hisparc/cluster_amsterdam/station_501', 'events') e510 = data.get_node('/hisparc/cluster_amsterdam/station_510', 'events') sn501 = (e501.col('n1') + e501.col('n2') + e501.col('n3') + e501.col('n4')) / 2 sn510 = (e510.col('n1') + e510.col('n2') + e510.col('n3') + e510.col('n4')) / 2 n501 = [e501.col('n1'), e501.col('n2'), e501.col('n3'), e501.col('n4')] n510 = [e510.col('n1'), e510.col('n2'), e510.col('n3'), e510.col('n4')] n_min = 0.5 # remove peak at 0 n_max = 200 bins = np.logspace(np.log10(n_min), np.log10(n_max), 50) for minn in [0, 1, 2, 4, 8, 16]: # poisson_errors = np.sqrt(bins) # filter = sn501 > minn filter = (sn501 > minn) & (sn510 > minn) plot = MultiPlot(4, 4, 'loglog', width=r'.22\linewidth', height=r'.22\linewidth') for i in range(4): for j in range(4): ncounts, x, y = np.histogram2d(n501[i].compress(filter), n510[j].compress(filter), bins=bins) subplot = plot.get_subplot_at(i, j) subplot.histogram2d(ncounts, x, y, type='reverse_bw', bitmap=True) # subplot.plot(bins - poisson_errors, bins + poisson_errors, # mark=None, linestyle='red') # subplot.plot(bins + poisson_errors, bins - poisson_errors, # mark=None, linestyle='red') plot.show_xticklabels_for_all([(3, 0), (3, 1), (3, 2), (3, 3)]) plot.show_yticklabels_for_all([(0, 3), (1, 3), (2, 3), (3, 3)]) # plot.set_title(0, 1, 'Particle counts for station 501 and 510') for i in range(4): plot.set_subplot_xlabel(0, i, 'detector %d' % (i + 1)) plot.set_subplot_ylabel(i, 0, 'detector %d' % (i + 1)) plot.set_xlabel('Number of particles 501') plot.set_ylabel('Number of particles 510') plot.save_as_pdf('n_minn%d_501_510_bins_log' % minn) ncounts, x, y = np.histogram2d(sn501, sn510, bins=bins) plot = Plot('loglog') plot.set_axis_equal() plot.histogram2d(ncounts, x, y, type='reverse_bw', bitmap=True) # plot.set_title('Particle counts for station 501 and 510') plot.set_xlabel('Particle density in 501') plot.set_ylabel('Particle density in 510') plot.save_as_pdf('n_501_510_sum_log')
def plot_raw(raw_traces): length = 2.5 * len(raw_traces[0]) plot = Plot() max_signal = max(chain.from_iterable(raw_traces)) plot.add_pin_at_xy(500, max_signal, 'pre-trigger', location='above', use_arrow=False) plot.draw_vertical_line(1000, 'gray') plot.add_pin_at_xy(1750, max_signal, 'trigger', location='above', use_arrow=False) plot.draw_vertical_line(2500, 'gray') plot.add_pin_at_xy(4250, max_signal, 'post-trigger', location='above', use_arrow=False) for i, raw_trace in enumerate(raw_traces): plot.plot(arange(0, length, 2.5), raw_trace, mark=None, linestyle=COLORS[i]) plot.set_ylimits(min=0) plot.set_xlimits(min=0, max=length) plot.set_ylabel(r'Signal strength [ADC counts]') plot.set_xlabel(r'Sample [\si{\nano\second}]') plot.save_as_pdf('raw')
def plot_traces(): with tables.open_file(DATA, 'r') as data: for i, pre, coin, post in TIME_WINDOWS: test_node = data.get_node('/t%d' % i) events = test_node.events.read() events.sort(order='ext_timestamp') blobs = test_node.blobs for e_idx in [0, 1]: t_idx = events[e_idx]['traces'][1] extts = events[e_idx]['ext_timestamp'] try: trace = zlib.decompress(blobs[t_idx]).split(',') except zlib.error: trace = zlib.decompress(blobs[t_idx][1:-1]).split(',') if trace[-1] == '': del trace[-1] trace = [int(x) for x in trace] plot = Plot() plot.plot(range(len(trace)), trace, mark=None) plot.set_label('%d' % extts) microsec_to_sample = 400 plot.draw_vertical_line(pre * microsec_to_sample, linestyle='thick,red,semitransparent') plot.draw_vertical_line((pre + coin) * microsec_to_sample, linestyle='thick,blue,semitransparent') plot.set_ylabel('Signal strength [ADCcounts]') plot.set_xlabel('Sample [2.5ns]') plot.set_ylimits(min=150, max=1500) plot.set_xlimits(min=0, max=len(trace)) plot.save_as_pdf('trace_%d_%d' % (i, e_idx))
def plot_comparison_501_510(stats, field_name): plot = Plot() bins = arange(0, 1, .02) ref_stat = stats[501][field_name][0] stat = stats[510][field_name][0] tmp_stat = stat.compress((ref_stat > 0) & (stat > 0)) tmp_ref_stat = ref_stat.compress((ref_stat > 0) & (stat > 0)) counts, xbin, ybin = histogram2d(tmp_stat, tmp_ref_stat, bins=bins) plot.histogram2d(counts, xbin, ybin, type='reverse_bw', bitmap=True) plot.plot([0, 1.2], [0, 1.2], mark=None, linestyle='red, very thin') if field_name == 'event_rate': label = r'Event rate [\si{\hertz}]' elif field_name == 'mpv': label = r'MPV [ADC.ns]' else: label = (r'Fraction of bad %s data [\si{\percent}]' % field_name.replace('_', ' ')) plot.set_ylabel(label) plot.set_xlabel(label) if field_name in ['event_rate', 'mpv']: plot.save_as_pdf('plots_501_510/compare_%s' % field_name) else: plot.save_as_pdf('plots_501_510/compare_bad_fraction_%s' % field_name)
def plot_reconstructions(): with tables.open_file('data.h5', 'r') as data: rec = data.root.s501.reconstructions reco = data.root.s501_original.reconstructions # Compare azimuth distribution bins = linspace(-pi, pi, 20) # Radians plot = Plot() plot.histogram(*histogram(rec.col('azimuth'), bins=bins)) plot.histogram(*histogram(reco.col('azimuth'), bins=bins), linestyle='red') plot.set_ylimits(min=0) plot.set_xlimits(-pi, pi) plot.set_ylabel('counts') plot.set_xlabel(r'Azimuth [\si{\radian}]') plot.save_as_pdf('azimuth') # Compare zenith distribution bins = linspace(0, pi / 2, 20) # Radians plot = Plot() plot.histogram(*histogram(rec.col('zenith'), bins=bins)) plot.histogram(*histogram(reco.col('zenith'), bins=bins), linestyle='red') plot.set_ylimits(min=0) plot.set_xlimits(0, pi / 2) plot.set_ylabel('counts') plot.set_xlabel(r'Zenith [\si{\radian}]') plot.save_as_pdf('zenith') # Compare angles between old and new bins = linspace(0, 20, 20) # Degrees plot = Plot() filter = (rec.col('zenith') > .5) d_angle = angle_between(rec.col('zenith'), rec.col('azimuth'), reco.col('zenith'), reco.col('azimuth')) plot.histogram(*histogram(degrees(d_angle), bins=bins)) plot.histogram(*histogram(degrees(d_angle).compress(filter), bins=bins), linestyle='red') plot.histogram(*histogram(degrees(d_angle).compress(invert(filter)), bins=bins), linestyle='blue') plot.set_ylimits(min=0) plot.set_xlimits(0, 20) plot.set_ylabel('counts') plot.set_xlabel(r'Angle between [\si{\degree}]') plot.save_as_pdf('angle_between')
def scatter_n(): r = 420 with tables.open_file(RESULT_PATH, 'r') as data: cluster = data.root.coincidences._v_attrs.cluster coincidences = data.root.coincidences.coincidences graph = Plot() for n in range(0, len(cluster.stations) + 1): c = coincidences.read_where('N == n') if len(c) == 0: continue graph.plot(c['x'], c['y'], mark='*', linestyle=None, markstyle='mark size=.2pt,color=%s' % COLORS[n % len(COLORS)]) graph1 = Plot() graph1.plot(c['x'], c['y'], mark='*', linestyle=None, markstyle='mark size=.2pt') plot_cluster(graph1, cluster) graph1.set_axis_equal() graph1.set_ylimits(-r, r) graph1.set_xlimits(-r, r) graph1.set_ylabel('y [m]') graph1.set_xlabel('x [m]') graph1.set_title('Showers that caused triggers in %d stations' % n) graph1.save_as_pdf('N_%d' % n) graph_azi = PolarPlot(use_radians=True) plot_azimuth(graph_azi, c['azimuth']) graph_azi.set_label('N = %d' % n) graph_azi.save('azi_%d' % n) graph_azi.save_as_pdf('azi_%d' % n) plot_cluster(graph, cluster) graph.set_axis_equal() graph.set_ylimits(-r, r) graph.set_xlimits(-r, r) graph.set_ylabel('y [m]') graph.set_xlabel('x [m]') graph.set_title('Color indicates the number triggered stations by ' 'a shower.') graph.save_as_pdf('N')
def plot_derrivative_pmt(self): plot = Plot() plot.plot(self.lin_bins, self.dvindvout, mark=None) plot.set_xlimits(min=self.lin_bins[0], max=self.lin_bins[-1]) plot.set_xlabel(r'Particle density [\si{\per\meter\squared}]') plot.set_ylabel( r'$\sigma V_{\mathrm{in}}\frac{\mathrm{d}V_{\mathrm{out}}}' r'{\mathrm{d}V_{\mathrm{in}}}$') plot.save_as_pdf('plots/derrivative_pmt_saturation')