Exemple #1
0
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)
Exemple #2
0
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")
Exemple #3
0
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('/', '_'))
Exemple #4
0
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)
Exemple #5
0
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)
Exemple #6
0
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)
Exemple #7
0
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')
Exemple #8
0
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')
Exemple #9
0
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__)
Exemple #10
0
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')
Exemple #11
0
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)
Exemple #12
0
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))
Exemple #13
0
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')
Exemple #14
0
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')
Exemple #15
0
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))
Exemple #16
0
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))
Exemple #17
0
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)
Exemple #18
0
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')
Exemple #19
0
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)
Exemple #20
0
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')
Exemple #21
0
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'
Exemple #22
0
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()
Exemple #23
0
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))
Exemple #24
0
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')
Exemple #25
0
def plot_results(distances, energies, results):
    plot = Plot('loglog')
    plot.histogram2d(np.log10(results[:-1, :-1] + 10),
                     distances,
                     energies,
                     bitmap=True)
    plot.set_ylabel('Shower energy')
    plot.set_xlabel('Distance between stations')
    plot.save_as_pdf('distance_energy_v_area')
Exemple #26
0
def plot_and_fit_offsets(x, y, popt, d, id):
    plot = Plot()
    plot_data_and_fit(x, y, popt, plot)
    plot.set_label('$\mu$: %.2f, $\sigma$: %.2f' % (popt[1], popt[2]))
    plot.set_ylabel('Occurrence')
    plot.set_xlabel('$\Delta t$ [ns]')
    plot.set_ylimits(min=0)
    plot.save_as_pdf('api_detector_offset_distribution_%s_' % id +
                     d.strftime('%Y%m%d'))
Exemple #27
0
 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')
Exemple #28
0
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 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')
Exemple #30
0
def plot_station_distances(distances, name=''):
    plot = Plot('semilogx')
    bins = numpy.logspace(0, 7, 41)
    counts, bins = numpy.histogram(distances, bins=bins)
    plot.histogram(counts, bins / 1e3)
    plot.set_xlabel(r'Distance [\si{\kilo\meter}]')
    plot.set_ylabel('Occurance')
    plot.set_ylimits(min=0)
    plot.set_xlimits(min=1e-3, max=2e3)
    plot.save_as_pdf('station_distances' + name)
Exemple #31
0
def plot_distributions(distances, name=''):
    bins = arange(0, 10.001, 0.2)
    plot = Plot()
    plot.histogram(*histogram(distances, bins))
    plot.set_ylimits(min=0)
    plot.set_xlimits(min=0, max=10)
    plot.set_ylabel('Counts')
    plot.set_xlabel(r'Distance to center mass location [\si{\meter}]')
    plot.set_label('67\%% within %.1fm' % percentile(distances, 67))
    plot.save_as_pdf('gps_distance_cm' + name)
Exemple #32
0
def plot_distributions_all(distances, distances_hor, distances_ver):
    bins = arange(0, 10.001, 0.25)
    plot = Plot()
    # plot.histogram(*histogram(distances, bins))
    plot.histogram(*histogram(distances_hor, bins))
    plot.histogram(*histogram(distances_ver, bins - 0.02), linestyle='gray')
    plot.set_ylimits(min=0)
    plot.set_xlimits(min=0, max=6)
    plot.set_ylabel('Counts')
    plot.set_xlabel(r'Distance to center mass location [\si{\meter}]')
    plot.save_as_pdf('gps_distance_cm_all')
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")
Exemple #34
0
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')
Exemple #35
0
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():
    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')
Exemple #39
0
def main():
    stations = np.genfromtxt("data/cluster-utrecht-stations.txt", names=["x", "y"])
    image = Image.open("data/cluster-utrecht-background.png")

    graph = Plot(width=r".75\linewidth", height=r".5\linewidth")

    graph.scatter(stations["x"], stations["y"])
    graph.draw_image(image)

    graph.set_axis_equal()

    nw = ["%.4f" % i for i in (52.10650519075632, 5.053710938)]
    se = ["%.4f" % i for i in (52.05249047600099, 5.185546875)]

    graph.set_xlabel("Longitude [$^\circ$]")
    graph.set_xticks([0, image.size[0]])
    graph.set_xtick_labels([nw[1], se[1]])

    graph.set_ylabel("Latitude [$^\circ$]")
    graph.set_yticks([0, image.size[1]])
    graph.set_ytick_labels([se[0], nw[0]])

    graph.save("utrecht")
def main():
    """Event display for an event of station 503

    Date        Time      Timestamp   Nanoseconds
    2012-03-29  10:51:36  1333018296  870008589

    Number of MIPs
    35.0  51.9  35.8  78.9

    Arrival time
    15.0  17.5  20.0  27.5

    """
    # Detector positions in ENU relative to the station GPS
    x = [-6.34, -2.23, -3.6, 3.46]
    y = [6.34, 2.23, -3.6, 3.46]

    # Scale mips to fit the graph
    n = [35.0, 51.9, 35.8, 78.9]

    # Make times relative to first detection
    t = [15., 17.5, 20., 27.5]
    dt = [ti - min(t) for ti in t]

    plot = Plot()
    plot.scatter([0], [0], mark='triangle')
    plot.add_pin_at_xy(0, 0, 'Station 503', use_arrow=False, location='below')
    plot.scatter_table(x, y, dt, n)

    plot.set_scalebar(location="lower right")
    plot.set_colorbar('$\Delta$t [ns]')
    plot.set_axis_equal()
    plot.set_mlimits(max=16.)
    plot.set_slimits(min=10., max=100.)

    plot.set_xlabel('x [m]')
    plot.set_ylabel('y [m]')

    plot.save('event_display')


    # Add event by Station 508
    # Detector positions in ENU relative to the station GPS
    x508 = [6.12, 0.00, -3.54, 3.54]
    y508 = [-6.12, -13.23, -3.54, 3.54]

    # Event GPS timestamp: 1371498167.016412100
    # MIPS
    n508 = [5.6, 16.7, 36.6, 9.0]
    # Arrival Times
    t508 = [15., 22.5, 22.5, 30.]
    dt508 = [ti - min(t508) for ti in t508]

    plot = MultiPlot(1, 2, width=r'.33\linewidth')
    plot.set_xlimits_for_all(min=-10, max=15)
    plot.set_ylimits_for_all(min=-15, max=10)
    plot.set_mlimits_for_all(min=0., max=16.)
    plot.set_colorbar('$\Delta$t [ns]', False)
    plot.set_colormap('blackwhite')
    plot.set_scalebar_for_all(location="upper right")

    p = plot.get_subplot_at(0, 0)
    p.scatter([0], [0], mark='triangle')
    p.add_pin_at_xy(0, 0, 'Station 503', use_arrow=False, location='below')
    p.scatter_table(x, y, dt, n)
    p.set_axis_equal()

    p = plot.get_subplot_at(0, 1)
    p.scatter([0], [0], mark='triangle')
    p.add_pin_at_xy(0, 0, 'Station 508', use_arrow=False, location='below')
    p.scatter_table(x508, y508, dt508, n508)
    p.set_axis_equal()

    plot.show_yticklabels_for_all([(0, 0)])
    plot.show_xticklabels_for_all([(0, 0), (0, 1)])

    plot.set_xlabel('x [m]')
    plot.set_ylabel('y [m]')

    plot.save('multi_event_display')