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 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_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_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 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_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_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 main(): # data series x = [0, 40, 60, 69, 80, 90, 100] y = [0, 0, 0.5, 2.96, 2, 1, .5] # make graph graph = Plot() # make Plot graph.plot(x, y, mark=None, linestyle='smooth,very thick') # set labels and limits graph.set_xlabel(r"$f [\si{\mega\hertz}]$") graph.set_ylabel("signal strength") graph.set_xlimits(0, 100) graph.set_ylimits(0, 5) # set scale: 1cm equals 10 units along the x-axis graph.set_xscale(cm=10) # set scale: 1cm equals 1 unit along the y-axis graph.set_yscale(cm=1) # set ticks at every unit along the y axis graph.set_yticks(range(6)) # set graph paper graph.use_graph_paper() # save graph to file graph.save('mm_paper')
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 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_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 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_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 plot_min_max(variable_pairs): plot = Plot() variable_pairs = sorted(variable_pairs) for i, minmax_d in enumerate(variable_pairs): plot.plot([i, i], minmax_d, mark=None) plot.set_xlabel('Station pair') plot.set_xtick_labels([' ']) plot.set_ylabel(r'Distance between stations [\si{\meter}]') plot.save_as_pdf('min_max_distances')
def plot_filtered(filtered_trace): plot = Plot() time = arange(0, len(filtered_trace) * 2.5, 2.5) plot.plot(time, filtered_trace, mark=None, linestyle='const plot') plot.set_xlabel(r'Trace time [\si{\ns}]') plot.set_ylabel(r'Signal strength [ADC]') plot.save_as_pdf('mean_filter')
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')
def main(): x, t25, t50, t75 = np.loadtxt('data/DIR-boxplot_arrival_times-1.txt') graph = Plot() graph.plot(x, t50, mark='*') graph.shade_region(x, t25, t75) graph.set_xlabel(r"Core distance [\si{\meter}]") graph.set_ylabel(r"Arrival time delay [\si{\nano\second}]") graph.set_ylimits(min=0) graph.save('shower-front')
def make_logo(): size = '.02\linewidth' x = arange(0, 2*pi, .01) y = sin(x) plot = Plot(width=size, height=size) plot.set_ylimits(-1.3, 1.3) plot.set_yticks([-1, 0, 1]) plot.set_ytick_labels(['', '', '']) plot.set_xticks([0, pi, 2*pi]) plot.set_xtick_labels(['', '', '']) plot.plot(x, y, mark=None, linestyle='thick') plot.set_axis_options("axis line style=thick, major tick length=.04cm") plot.save_as_pdf('logo')
def plot_traces(traces, label='', raw=False): """Plot traces Does not take different mV/ADC for HiSPARC II-III into account! :param traces: list of lists of trace values. :param label: name (suffix) for the output pdf. """ colors = ['black', 'red', 'black!40!green', 'blue'] plot = Plot(width=r'.6\textwidth') times = arange(0, len(traces[0]) * 2.5, 2.5) for i, trace in enumerate(traces): if not raw: if max(trace) * 0.57 < 500: use_milli = True trace = [t * -0.57 for t in trace] else: use_milli = False trace = [t * -0.57 / 1e3 for t in trace] plot.plot(times, trace, linestyle='%s, thin' % colors[i], mark=None) if len(traces[0]) == 2400 and raw: plot.add_pin_at_xy(500, 10, 'pre-trigger', location='below', use_arrow=False) plot.add_pin_at_xy(1750, 10, 'trigger', location='below', use_arrow=False) plot.add_pin_at_xy(4250, 10, 'post-trigger', location='below', use_arrow=False) plot.draw_vertical_line(1000, 'gray') plot.draw_vertical_line(2500, 'gray') if raw: plot.set_ylabel(r'Signal strength [ADCcounts]') elif use_milli: plot.set_ylabel(r'Signal strength [\si{\milli\volt}]') else: plot.set_ylabel(r'Signal strength [\si{\volt}]') plot.set_xlabel(r'Event time [\si{\ns}]') plot.set_xlimits(0, times[-1]) plot.set_axis_options('line join=round') plot.save_as_pdf('trace_' + label)
def plot_front_shapes(): r = [20, 29, 41, 58, 84, 120, 171, 245, 350, 501] fit_r = arange(0, 510, 5) for particle in ['gamma', 'proton', 'iron']: for energy in ['15.0', '15.5', '16.0', '16.5', '17.0']: files = glob(PATH + '%s_E_%s*' % (particle, energy)) if not len(files): continue t = zeros((len(r), len(files))) for i, file in enumerate(files): detected_t = loadtxt(file, usecols=(1, )) t[:, i][:len(detected_t)] = detected_t t_src = t.copy() for j in range(1, len(t)): t[j] -= t[0] t[0] -= t[0] mean_t = t.mean(axis=1) try: min_limit = 3 min_efficiency = 0.9 limit = min_limit + next( i for i, ti in enumerate(t_src[min_limit:]) if not count_nonzero(ti) > min_efficiency * len(files)) except: limit = len(r) plot = Plot() plot.scatter(r[:limit], mean_t[:limit], yerr=t.std(axis=1)[:limit], xerr=[10] * limit) plot.scatter(r[:limit], median(t, axis=1)[:limit], mark='x') popt, pcov = curve_fit(front_shape, r[:limit], mean_t[:limit]) plot.plot(fit_r, front_shape(fit_r, *popt), linestyle='gray', mark=None) print particle, energy, popt plot.set_ylimits(-10, 130) plot.set_xlimits(-10, 510) plot.set_ylabel(r'Delay [\si{\ns}]') plot.set_xlabel(r'Core distance [\si{\meter}]') plot.save_as_pdf('plots/front_shape/%s_%s.pdf' % (particle, energy))
def plot_contributions(): colors = ['red', 'blue', 'green', 'purple', 'gray', 'brown', 'cyan', 'magenta', 'orange', 'teal'] lamb = arange(MIN, MAX, 0.1) plot = Plot('semilogy') for j, k in enumerate(range(1, 8) + [15] + [20]): ks = [k] # arange(k - 0.5, k + 0.5, 0.2) p = sum(density_probability(lamb, ki) for ki in ks) / len(ks) plot.plot(lamb, p, linestyle=colors[j % len(colors)], mark=None) plot.set_ylimits(min=0.01) plot.set_xlimits(0, 20) plot.set_xlabel('Expected actual number of particles') plot.set_ylabel('Probability') plot.save_as_pdf('plots/poisson_distributions')
def plot_compared(): popt, perr = fit_curve(senstech_m_ph, senstech_e_ph) fit = FIT % (popt[0], P1, popt[1]) plot = Plot(width=r'.67\linewidth', height=r'.67\linewidth') plot.set_label(fit, location='upper left') plot.scatter(senstech_e_ph, senstech_m_ph, mark='*') plot.scatter(nikhef_e_ph, nikhef_m_ph, mark='o') inputs = linspace(min(senstech_m_ph), max(senstech_m_ph), 500) plot.plot(ice_cube_pmt_p1(inputs, *popt), inputs, mark=None) plot.plot([0, 6], [0, 6], mark=None, linestyle='gray') plot.set_xlimits(0, 6) plot.set_ylimits(0, 6) plot.set_axis_equal() plot.set_xlabel(r'Sum individual LED pulseheights [\si{\volt}]') plot.set_ylabel(r'Multiple-LED pulseheight [\si{\volt}]') plot.save_as_pdf('plots/linearity_compared')
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_delta_histogram(ids, **kwargs): """ Plot a histogram of the deltas """ if type(ids) is int: ids = [ids] # Bin width bin_size = 1 # 2.5*n # Begin Figure plot = Plot() for id in ids: ext_timestamps, deltas = get(id) low = floor(min(deltas)) high = ceil(max(deltas)) bins = np.arange(low - .5 * bin_size, high + bin_size, bin_size) n, bins = np.histogram(deltas, bins) bin_centers = (bins[:-1] + bins[1:]) / 2 popt, pcov = curve_fit(gauss, bin_centers, n, p0=[.15, np.mean(deltas), np.std(deltas)]) plot.histogram(n, bins) plot.plot(bin_centers, gauss(bin_centers, *popt), mark=None, linestyle='gray') if kwargs.keys(): plot.set_title('Tijdtest ' + kwargs[kwargs.keys()[0]]) plot.set_label(r'$\mu={1:.1f}$, $\sigma={2:.1f}$'.format(*popt)) plot.set_xlabel(r'Time difference [ns]') plot.set_ylabel(r'Counts') plot.set_xlimits(low, high) plot.set_ylimits(min=0.) # Save Figure if len(ids) == 1: name = 'delta_histogram/tt_delta_hist_%03d' % ids[0] elif kwargs.keys(): name = 'delta_histogram/tt_delta_hist_' + kwargs[kwargs.keys()[0]] plot.save_as_pdf(PLOT_PATH + name) print 'tt_analyse: Plotted histogram'
def main(): plot = Plot() size = 20 x = np.linspace(1, 20, size) y = np.linspace(10, 50, size) y_random = y + np.random.uniform(-3, 1, size) err_l = np.random.uniform(0, 2, size) err_h = np.random.uniform(1, 5, size) err_x = [0.4] * size plot.plot(x, y, mark=None) plot.scatter(x, y_random, xerr=err_x, yerr=list(zip(err_l, err_h))) plot.set_xlabel("Value with symmetric error") plot.set_ylabel("Other value with asymmetric errors") plot.save("error_bars")
def plot_luminosity(timestamp, aligned_data, aligned_data_all, i): n_active_aligned = (aligned_data != 0).sum(axis=0) cumsummed_data_all = aligned_data_all.sum(axis=0).cumsum() summed_data = aligned_data.sum(axis=0) cumsummed_data = summed_data.cumsum() plot = Plot(width=r'.5\textwidth') # plot.plot([t / 1e9 for t in timestamp[::100]], cumsummed_data_all[::100], # linestyle='black!50!green, thick', mark=None) plot.plot([t / 1e9 for t in timestamp[::100]], cumsummed_data[::100], linestyle='thick', mark=None) plot.set_xticks([datetime_to_gps(date(y, 1, 1)) / 1e9 for y in YEARS[::3]]) plot.set_xtick_labels(['%d' % y for y in YEARS[::3]]) plot.set_ylabel('Cummulative number of events') plot.set_xlabel('Date') plot.save_as_pdf('luminosity_%s' % ['network', 'spa'][i])
def plot_ranges(): k = arange(26) p_low = [percentile_low_density_for_n(ki) for ki in k] p_median = [median_density_for_n(ki) for ki in k] p_mean = [mean_density_for_n(ki) for ki in k] # p_mpv = [most_probable_density_for_n(ki) for ki in k] p_high = [percentile_high_density_for_n(ki) for ki in k] plot = Plot(height=r'\defaultwidth') plot.plot([0, 1.5 * max(k)], [0, 1.5 * max(k)], mark=None, linestyle='dashed') plot.scatter(k, p_median) # plot.plot(k, p_mean, mark=None, linestyle='green') # plot.plot(k, p_mpv, mark=None, linestyle='red') plot.shade_region(k, p_low, p_high) plot.set_xlimits(min(k) - 0.05 * max(k), 1.05 * max(k)) plot.set_ylimits(min(k) - 0.05 * max(k), 1.05 * max(k)) plot.set_axis_equal() plot.set_xlabel('Detected number of particles') plot.set_ylabel('Expected actual number of particles') plot.save_as_pdf('plots/poisson_ranges')
def plot_effiencies(): efficiencies, errors = collect_efficiencies() for energy in efficiencies.keys(): plot = Plot('semilogx') for i, zenith in enumerate(sorted(efficiencies[energy].keys())): if any(abs(zenith - z) < 0.1 for z in [0, 22.5, 37.5]): plot.plot(CORE_DISTANCES, efficiencies[energy][zenith], # yerr=errors[energy][zenith], markstyle='mark size=1pt', linestyle='blue') plot.add_pin(str(zenith), x=15, use_arrow=True) else: plot.plot(CORE_DISTANCES, efficiencies[energy][zenith], mark=None) plot_david_data(plot) plot.set_ylabel('Efficiency') plot.set_ylimits(min=0, max=1.02) plot.set_xlimits(min=2, max=500) plot.set_xlabel('Core distance') plot.save_as_pdf('efficiency_%s_%.1f.pdf' % (STATION_TYPE[STATION_NUMBER], energy))
def plot_integral(trace, baseline): plot = Plot() time = arange(0, len(trace) * 2.5, 2.5) plot.plot(time, trace, mark=None, linestyle='const plot') integral_trace = where(trace > baseline + BASELINE_THRESHOLD, trace, baseline) plot.shade_region(time + 2.5, [baseline] * len(trace), integral_trace, color='lightgray, const plot') plot.draw_horizontal_line(baseline, linestyle='densely dashed, gray') plot.draw_horizontal_line(baseline + BASELINE_THRESHOLD, linestyle='densely dotted, gray') plot.draw_horizontal_line(max(trace), linestyle='densely dashed, gray') # plot.set_ylimits(0) plot.set_xlabel(r'Trace time [\si{\ns}]') plot.set_ylabel(r'Signal strength [ADC]') plot.save_as_pdf('integral')
def plot_detector_offsets(offsets, type='month'): d1, d2, d3, d4 = zip(*offsets) x = range(len(d1)) graph = Plot() graph.plot(x, d1, markstyle='mark size=.5pt') graph.plot(x, d2, markstyle='mark size=.5pt', linestyle='red') graph.plot(x, d3, markstyle='mark size=.5pt', linestyle='green') graph.plot(x, d4, markstyle='mark size=.5pt', linestyle='blue') graph.set_ylabel('$\Delta t$ [ns]') graph.set_xlabel('Date') graph.set_xlimits(0, max(x)) graph.set_ylimits(-LIMITS, LIMITS) graph.save_as_pdf('detector_offset_drift_%s_%d' % (type, station))
def plot_pmt_curves(self): plot = Plot('loglog') filter = self.ref_out < 50 for i in range(4): filter2 = self.ref_in_i[:, i] < 500 pin = self.ref_in_i[:, i].compress(filter & filter2) pout = self.ref_out.compress(filter & filter2) plot.plot(pout, pin, linestyle=COLORS[i], mark=None) filter2 = self.ref_in < 500 pin = self.ref_in.compress(filter & filter2) pout = self.ref_out.compress(filter & filter2) plot.plot(pout, pin, linestyle='pink', mark=None) plot.set_ylimits(min=min(self.lin_bins), max=max(self.lin_bins)) plot.set_xlimits(min=min(self.lin_bins), max=max(self.lin_bins)) plot.set_ylabel(r'Input signal') plot.set_xlabel(r'Output signal') plot.save_as_pdf('plots/pmt_curves')
def scatter_n(): with tables.open_file(RESULT_PATH, 'r') as data: cluster = data.root.coincidences._v_attrs.cluster coincidences = data.root.coincidences.coincidences for n in range(0, len(cluster.stations) + 1): graph = Plot() c = coincidences.read_where('N == n') print 'N = %d: %d' % (n, len(c)) graph.plot(c['x'], c['y'], mark='*', linestyle=None, markstyle='mark size=.3pt') plot_cluster(graph, cluster) r = 520 graph.set_ylimits(-r, r) graph.set_xlimits(-r, r) graph.set_ylabel('y (m)') graph.set_xlabel('x (m)') graph.save_as_pdf('N_%d' % n)
def main(): locations = np.genfromtxt( 'data/SP-DIR-plot_sciencepark_cluster-detectors.txt', names=['x', 'y']) stations = np.genfromtxt( 'data/SP-DIR-plot_sciencepark_cluster-stations.txt', names=['id', 'x', 'y']) graph = Plot() graph.scatter(locations['x'], locations['y']) graph.set_axis_equal() locations = ['right'] * len(stations) locations[0] = 'left' locations[5] = 'above right' locations = iter(locations) for num, x, y in stations: graph.add_pin_at_xy(x, y, int(num), location=next(locations), use_arrow=False, style='gray,label distance=1ex') x = [stations['x'][u] for u in [0, 2, 5]] y = [stations['y'][u] for u in [0, 2, 5]] x.append(x[0]) y.append(y[0]) graph.plot(x, y, mark=None, linestyle='dashed') graph.add_pin_at_xy([x[0], x[1]], [y[0], y[1]], r'\SI{128}{\meter}', relative_position=.4, location='below right', use_arrow=False) graph.add_pin_at_xy([x[0], x[2]], [y[0], y[2]], r'\SI{151}{\meter}', relative_position=.5, location='left', use_arrow=False) graph.add_pin_at_xy([x[2], x[1]], [y[2], y[1]], r'\SI{122}{\meter}', relative_position=.5, location='above right', use_arrow=False) graph.set_xlabel(r"Distance [\si{\meter}]") graph.set_ylabel(r"Distance [\si{\meter}]") graph.save('sciencepark')
def main(): x = np.arange(10) y = (x / 2.0) - 3.0 colors = ["black", "red", "blue", "yellow", "purple"] plot = Plot() for i in range(5): plot.plot(x, y - i, mark="", linestyle=colors[i]) plot.set_axis_options( "yticklabel pos=right,\n" "grid=major,\n" "legend entries={$a$,[red]$b$,[green]$c$,$d$,$a^2$},\n" "legend pos=north west" ) plot.set_xlabel("Something important") plot.set_ylabel("A related thing") plot.save("any_option") x = np.linspace(0.6 * np.pi, 10 * np.pi, 150) y = np.sin(x) / x plot = MultiPlot(1, 2, width=r".4\linewidth", height=r".25\linewidth") subplot = plot.get_subplot_at(0, 0) subplot.plot(x, y, mark=None) subplot = plot.get_subplot_at(0, 1) subplot.plot(x, y, mark=None) plot.show_xticklabels_for_all([(0, 0), (0, 1)]) plot.show_yticklabels(0, 1) plot.set_axis_options(0, 1, "yticklabel pos=right, grid=major") plot.set_axis_options_for_all(None, r"enlargelimits=false") plot.set_xlabel("Something important") plot.set_ylabel("A related thing") plot.save("multi_any_option")
def main(): # Draw random numbers from the normal distribution np.random.seed(1) N = np.random.normal(size=2000) # define bin edges edge = 5 bin_width = .1 bins = np.arange(-edge, edge + .5 * bin_width, bin_width) # build histogram and x, y values at the center of the bins n, bins = np.histogram(N, bins=bins) x = (bins[:-1] + bins[1:]) / 2 y = n # fit normal distribution pdf to data f = lambda x, N, mu, sigma: N * scipy.stats.norm.pdf(x, mu, sigma) popt, pcov = scipy.optimize.curve_fit(f, x, y) print("Parameters from fit (N, mu, sigma):", popt) # make graph graph = Plot() # graph histogram graph.histogram(n, bins) # graph model with fit parameters x = np.linspace(-edge, edge, 100) graph.plot(x, f(x, *popt), mark=None) # set labels and limits graph.set_xlabel("value") graph.set_ylabel("count") graph.set_label("Fit to data") graph.set_xlimits(-6, 6) # save graph to file graph.save('histogram-fit')
def main(): gamma = np.genfromtxt('data/showere15-proton.t2001', usecols=(1, 2)) e = np.genfromtxt('data/showere15-proton.t2205', usecols=(1, 2)) mu = np.genfromtxt('data/showere15-proton.t2207', usecols=(1, 2)) graph = Plot(axis='loglog') graph.plot(gamma[:, 0], gamma[:, 1], mark=None) graph.add_pin(r'$\gamma$') graph.plot(e[:, 0], e[:, 1], mark=None) graph.add_pin('e') graph.plot(mu[:, 0], mu[:, 1], mark=None) graph.add_pin(r'$\mu$') graph.set_xlabel(r"Core distance [\si{\meter}]") graph.set_ylabel(r"Particle density [\si{\per\square\meter}]") graph.set_logyticks(range(-6, 3, 2)) graph.save('eas-lateral')
def main(): leap = np.genfromtxt('data/leap-prot.dat', delimiter=',', usecols=(0, 1), names=['E', 'F']) leap['E'] *= 1e6 leap['F'] *= 1e3 * 2 proton = read_data('data/proton', 1, 0) akeno_new_lo = read_data('data/akeno-new-lo', 0, 1) flys_eye = read_data('data/fe-new', 0, 1) yakutsk = read_data('data/yakustk', 1, 0) haverah = read_data('data/haverah', 1, 0) graph = Plot(axis='loglog', width=r'.5\linewidth', height=r'.65\linewidth') graph.plot(leap['E'], leap['F'], mark=None) graph.add_pin('LEAP', 'above right', use_arrow=True, relative_position=.5) graph.plot(proton['E'], proton['F'], mark=None) graph.add_pin('PROTON', 'above right', use_arrow=True, relative_position=.5) graph.plot(akeno_new_lo['E'], akeno_new_lo['F'], mark=None) graph.add_pin('AGASA', 'above right', use_arrow=True, relative_position=.5) graph.plot(yakutsk['E'], yakutsk['F'], mark=None) graph.add_pin('Yakutsk', 'below left', use_arrow=True, relative_position=.55) graph.plot(haverah['E'], haverah['F'], mark=None) graph.add_pin('Haverah Park', 'below left', use_arrow=True, relative_position=.85) graph.plot(flys_eye['E'], flys_eye['F'], mark=None) graph.add_pin("Fly's Eye", 'below left', use_arrow=True, relative_position=1.0) graph.set_xlabel(r"Energy [\si{\electronvolt}]") graph.set_ylabel(r"Flux [\si{\per\square\meter\per\steradian" "\per\second\per\giga\electronvolt}]") x = np.logspace(11, 17) graph.plot(x, 1.5e29 * x ** -2.75, mark=None, linestyle='dashed') graph.set_logxticks(range(6, 22, 3)) graph.save('spectrum')
if x > 0.0: return 1.0 return 2 * (H(x / L) - H(x / L - 1)) - 1 def fourier(x, N): ''' fourier approximation with N terms''' term = 0.0 for n in range(1, N, 2): term += (1.0 / n) * math.sin(n * math.pi * x / L) return (4.0 / (math.pi)) * term X = npy.linspace(0.0, 2 * L, num=1000) Y_sqr = [square(x) for x in X] Y = lambda n: [fourier(x, n) for x in X] graph = Plot() graph.set_title("Fourier approximation") graph.plot(x=X, y=Y( 3), linestyle='red' , mark=None, legend='n=3' ) graph.plot(x=X, y=Y( 5), linestyle='yellow', mark=None, legend='n=5' ) graph.plot(x=X, y=Y( 8), linestyle='green' , mark=None, legend='n=8' ) graph.plot(x=X, y=Y(13), linestyle='blue' , mark=None, legend='n=13') #graph.plot(x=X, y=Y(21), linestyle='violet', mark=None, legend='n=21') #graph.plot(x=X, y=Y(34), linestyle='violet', mark=None, legend='n=34') graph.plot(x=X, y=Y(55), linestyle='cyan' , mark=None, legend='n=55') graph.plot(x=X, y=Y_sqr, linestyle='black' , mark=None, legend='square') graph.save_as_pdf('plot')
q = int(0.25 * len(y)) y = y[q:2*q] max_index = q + np.argmax(y) max_x = x[max_index] plot.add_pin(label, x=max_x, location='above', use_arrow=True, style='pin distance=%s' % distance) X = np.linspace(0., 2 * L, num=1000) Y_sqr = [square(x) for x in X] Y = lambda n: [fourier(x, n) for x in X] graph = Plot() graph.set_title("Fourier approximation") graph.plot(x=X, y=Y(3), linestyle='red', mark=None, legend='n=3') graph.plot(x=X, y=Y(5), linestyle='yellow', mark=None, legend='n=5') graph.plot(x=X, y=Y(8), linestyle='green', mark=None, legend='n=8') graph.plot(x=X, y=Y(13), linestyle='blue', mark=None, legend='n=13') graph.plot(x=X, y=Y(55), linestyle='cyan', mark=None, legend='n=55') graph.plot(x=X, y=Y_sqr, linestyle='black', mark=None, legend='square') graph.save('fourier_with_legend') graph = Plot() graph.set_title("Fourier approximation") graph.plot(x=X, y=Y(3), mark=None, linestyle='black!20') add_custom_pin(graph, X, Y(3), 3) graph.plot(x=X, y=Y(5), mark=None, linestyle='black!30') add_custom_pin(graph, X, Y(5), 5)
def main(): plot = Plot(width=r'.5\linewidth', height=r'.5\linewidth') r = linspace(1, 5, 100) phi = linspace(0, 4.5 * pi, 100) x = r * cos(phi) y = r * sin(phi) plot.plot(x, y, mark=None) plot.add_pin('start', relative_position=0, use_arrow=True) plot.add_pin('half', relative_position=.5, use_arrow=True) plot.add_pin('46\%', relative_position=.46, use_arrow=True, location='above') plot.add_pin('end', relative_position=1, use_arrow=True, location='below') phi = linspace(0, 2 * pi, 10) x = 6 * cos(phi) y = 6 * sin(phi) plot.plot(x, y, mark=None, linestyle='thick, gray') plot.add_pin('start', relative_position=0, use_arrow=True, location='above right') plot.add_pin('half', relative_position=.5, use_arrow=True, location='above left') plot.add_pin('70\%', relative_position=.7, use_arrow=True, location='below') plot.add_pin('end', relative_position=1, use_arrow=True, location='below right') plot.plot([-5, 2, 5], [-7.5, -7.5, -7.5], linestyle='lightgray') plot.add_pin('50\%', relative_position=.5, use_arrow=True, location='above right') plot.set_xlimits(-8, 8) plot.set_ylimits(-8, 8) plot.save('relative_pin') # With one logarithmic axis plot = Plot(axis='semilogy') x = [2, 2, 2] y = [1, 10, 100] plot.plot(x, y) for xi, yi in zip(x, y): plot.add_pin_at_xy(xi, yi, '(%d,%d)' % (xi, yi), location='below right') plot.add_pin('half', relative_position=.5, use_arrow=True, location='right') x = [4, 5, 6] y = [3, 3, 3] plot.plot(x, y) for xi, yi in zip(x, y): plot.add_pin_at_xy(xi, yi, '(%d,%d)' % (xi, yi), location='below') plot.add_pin('half', relative_position=.5, use_arrow=True, location='above') x = [3, 4, 5] y = [1, 10, 100] plot.plot(x, y) for xi, yi in zip(x, y): plot.add_pin_at_xy(xi, yi, '(%d,%d)' % (xi, yi), location='above left') plot.add_pin('half', relative_position=.5, use_arrow=True, location='right') plot.save('relative_pin_log')