Example #1
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)
Example #2
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')
Example #3
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")
Example #4
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)
Example #5
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'
Example #6
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)
Example #7
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))
Example #8
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__)
Example #9
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))
Example #10
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))
Example #11
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')
Example #12
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)
Example #13
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()
Example #14
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')
Example #15
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')
Example #16
0
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)
Example #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)
Example #18
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')
Example #19
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'))
Example #20
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)
Example #21
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)
Example #22
0
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')
Example #23
0
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')
Example #24
0
def plot_zenith(zenith, name=''):

    graph = Plot()
    n, bins = histogram(zenith, bins=linspace(0, pi / 2., 41))
    graph.histogram(n, bins)
    graph.set_title('Zenith distribution')
    graph.set_xlimits(0, pi / 2.)
    graph.set_ylimits(min=0)
    graph.set_xlabel('Zenith [rad]')
    graph.set_ylabel('Counts')
    graph.save_as_pdf('zen_%s' % name)
Example #25
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')
Example #26
0
def plot_azimuth(azimuth, name=''):

    # graph = PolarPlot(use_radians=True)
    graph = Plot()
    n, bins = histogram(azimuth, bins=linspace(-pi, pi, 21))
    graph.histogram(n, bins)
    graph.set_title('Azimuth distribution')
    graph.set_xlimits(-pi, pi)
    graph.set_ylimits(min=0)
    graph.set_xlabel('Azimuth [rad]')
    graph.set_ylabel('Counts')
    graph.save_as_pdf('azi_norm_%s' % name)
Example #27
0
def plot_zenith_density_small():
    with tables.open_file(RESULT_DATA_SMALL, 'r') as data:
        e = data.root.cluster_simulations.station_501.events.read()
        density = (e['n1'] + e['n2'] + e['n3'] + e['n4']) / 2.
        zenith = data.root.cluster_simulations.station_501.reconstructions.col('zenith')
        plot = Plot('semilogx')
        plot.scatter(density, degrees(zenith), markstyle='thin, mark size=.75pt')
        plot.set_xlabel(r'Particle density [\si{\per\meter\squared}]')
        plot.set_ylabel(r'Reconstructed zenith [\si{\degree}]')
        plot.set_xlimits(1, 1e4)
        plot.set_ylimits(-5, 95)
        plot.save_as_pdf('plots/zenith_density_e14_5_z0')
Example #28
0
def plot_zenith_core_distance():
    with tables.open_file(RESULT_DATA, 'r') as data:
        sim = data.root.coincidences.coincidences.read_where('N == 1')
        core_distance = sqrt(sim['x'] ** 2 + sim['y'] ** 2)
        zenith = data.root.cluster_simulations.station_501.reconstructions.col('zenith')
        plot = Plot('semilogx')
        plot.scatter(core_distance, degrees(zenith), markstyle='thin, mark size=.75pt')
        plot.set_xlabel(r'Core distance [\si{\meter}]')
        plot.set_ylabel(r'Reconstructed zenith [\si{\degree}]')
        plot.set_xlimits(1, 1e3)
        plot.set_ylimits(-5, 95)
        plot.save_as_pdf('plots/zenith_distance_e17_z0')
Example #29
0
    def plot_n_histogram(self, n, ni, bins):
        """Plot histogram of detected signals"""

        plot = Plot('semilogy')
        plot.histogram(*histogram(n, bins=bins), linestyle='dotted')
        for i in range(4):
            plot.histogram(*histogram(ni[:, i], bins=bins),
                           linestyle=COLORS[i])
        plot.set_ylimits(min=.99, max=1e4)
        plot.set_xlimits(min=bins[0], max=bins[-1])
        plot.set_ylabel(r'Counts')
        return plot
Example #30
0
def print_coincident_time_delta():

    cq = CoincidenceQuery(DATA, coincidence_group='/coincidences')
    coincidences = cq.coincidences
    events = [cq._get_events(c) for c in coincidences]

    cq_orig = CoincidenceQuery(DATA,
                               coincidence_group='/coincidences_original')
    coincidences_orig = cq_orig.coincidences
    events_orig = [cq_orig._get_events(c) for c in coincidences_orig]

    t3_501 = []
    t3_510 = []

    for event1, event2 in events:
        if event1[0] == 501:
            t3_501.append(event1[1]['t3'])
            t3_510.append(event2[1]['t3'])
        else:
            t3_501.append(event2[1]['t3'])
            t3_510.append(event1[1]['t3'])

    t3_501_orig = []
    t3_510_orig = []

    for event1, event2 in events_orig:
        if event1[0] == 501:
            t3_501_orig.append(event1[1]['t3'])
            t3_510_orig.append(event2[1]['t3'])
        else:
            t3_501_orig.append(event2[1]['t3'])
            t3_510_orig.append(event1[1]['t3'])

    t3_501 = array(t3_501)
    t3_510 = array(t3_510)
    t3_501_orig = array(t3_501_orig)
    t3_510_orig = array(t3_510_orig)

    filter = (t3_501_orig != -999) & (t3_510_orig != -999)

    dt3_501 = t3_501 - t3_501_orig
    dt3_510 = t3_510 - t3_510_orig
    dt = dt3_501 - dt3_510

    # Plot distribution
    plot = Plot()
    counts, bins = histogram(dt.compress(filter), bins=arange(-10.5, 11.5, 1))
    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('time_delta_501_510')
Example #31
0
def make_map(station=None, label='map', detectors=False):

    get_locations = (get_detector_locations
                     if detectors else get_station_locations)

    latitudes, longitudes = get_locations(station)

    bounds = (min(latitudes), min(longitudes), max(latitudes), max(longitudes))

    map = Map(bounds, margin=0, z=18)
    image = map.to_pil()

    map_w, map_h = image.size

    xmin, ymin = map.to_pixels(map.box[:2])
    xmax, ymax = map.to_pixels(map.box[2:])
    aspect = abs(xmax - xmin) / abs(ymax - ymin)

    width = 0.67
    height = width / aspect
    plot = Plot(width=r'%.2f\linewidth' % width,
                height=r'%.2f\linewidth' % height)

    plot.draw_image(image, 0, 0, map_w, map_h)
    plot.set_axis_equal()

    plot.set_xlimits(xmin, xmax)
    plot.set_ylimits(map_h - ymin, map_h - ymax)

    x, y = map.to_pixels(array(latitudes), array(longitudes))

    marks = cycle(['o'] * 4 + ['triangle'] * 4 + ['*'] * 4)
    colors = cycle(['black', 'red', 'green', 'blue'])
    if detectors:
        for xi, yi in zip(x, y):
            plot.scatter([xi], [map_h - yi],
                         markstyle="%s, thick" % colors.next(),
                         mark=marks.next())
    else:
        plot.scatter(x, map_h - y, markstyle="black!50!green")

    plot.set_xlabel('Longitude [$^\circ$]')
    plot.set_xticks([xmin, xmax])
    plot.set_xtick_labels(['%.4f' % x for x in (map.box[1], map.box[3])])

    plot.set_ylabel('Latitude [$^\circ$]')
    plot.set_yticks([map_h - ymin, map_h - ymax])
    plot.set_ytick_labels(['%.4f' % x for x in (map.box[0], map.box[2])])
    #     plot.set_title(label)

    # save plot to file
    plot.save_as_pdf(label.replace(' ', '-'))
Example #32
0
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')
Example #33
0
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))
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)
graph.plot(x=X, y=Y(8), mark=None, linestyle='black!40')
add_custom_pin(graph, X, Y(8), 8)
graph.plot(x=X, y=Y(13), mark=None, linestyle='black!60')
add_custom_pin(graph, X, Y(13), 13, distance='5ex')
graph.plot(x=X, y=Y(55), mark=None, linestyle='black!80')
add_custom_pin(graph, X, Y(55), 55)
graph.plot(x=X, y=Y_sqr, mark=None, linestyle='thick')

graph.set_ylimits(max=1.7)

graph.save('fourier_with_labels')
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')