Exemple #1
0
    def plot_fit_residuals_detector(self):
        plot = MultiPlot(2, 2, width=r'.3\linewidth', height=r'.3\linewidth')
        for i in range(4):
            splot = plot.get_subplot_at(i / 2, i % 2)
            res = fit_function(self.slice_bins_c, *
                               self.fit_i[i]) - self.med_ki[:, i]
            splot.scatter(self.slice_bins_c,
                          res,
                          xerr=(self.slice_bins[1:] - self.slice_bins[:-1]) /
                          2.,
                          yerr=self.std_ki[:, i],
                          markstyle='red, mark size=1pt')
            splot.draw_horizontal_line(0, linestyle='gray')


#             splot.plot(self.lin_bins, fit_function(self.lin_bins, self.fit_i[i])

        plot.set_ylimits_for_all(min=-30, max=30)
        plot.set_xlimits_for_all(min=0, max=max(self.slice_bins))
        plot.show_xticklabels_for_all([(1, 0), (0, 1)])
        plot.show_yticklabels_for_all([(1, 0), (0, 1)])
        plot.set_xlabel(r'HiSPARC detected density [\si{\per\meter\squared}]')
        plot.set_ylabel(
            r'Residuals (Predicted - Fit) [\si{\per\meter\squared}]')
        plot.save_as_pdf('plots/fit_residuals_detector')
Exemple #2
0
def plot_densities(data):
    """Make particle count plots for each detector to compare densities/responses"""

    e501 = data.get_node('/hisparc/cluster_amsterdam/station_501', 'events')
    e510 = data.get_node('/hisparc/cluster_amsterdam/station_510', 'events')

    sn501 = (e501.col('n1') + e501.col('n2') + e501.col('n3') +
             e501.col('n4')) / 2
    sn510 = (e510.col('n1') + e510.col('n2') + e510.col('n3') +
             e510.col('n4')) / 2
    n501 = [e501.col('n1'), e501.col('n2'), e501.col('n3'), e501.col('n4')]
    n510 = [e510.col('n1'), e510.col('n2'), e510.col('n3'), e510.col('n4')]

    n_min = 0.5  # remove peak at 0
    n_max = 200
    bins = np.logspace(np.log10(n_min), np.log10(n_max), 50)

    for minn in [0, 1, 2, 4, 8, 16]:
        # poisson_errors = np.sqrt(bins)
        # filter = sn501 > minn
        filter = (sn501 > minn) & (sn510 > minn)
        plot = MultiPlot(4,
                         4,
                         'loglog',
                         width=r'.22\linewidth',
                         height=r'.22\linewidth')
        for i in range(4):
            for j in range(4):
                ncounts, x, y = np.histogram2d(n501[i].compress(filter),
                                               n510[j].compress(filter),
                                               bins=bins)
                subplot = plot.get_subplot_at(i, j)
                subplot.histogram2d(ncounts,
                                    x,
                                    y,
                                    type='reverse_bw',
                                    bitmap=True)
                # subplot.plot(bins - poisson_errors, bins + poisson_errors,
                #              mark=None, linestyle='red')
                # subplot.plot(bins + poisson_errors, bins - poisson_errors,
                #              mark=None, linestyle='red')

        plot.show_xticklabels_for_all([(3, 0), (3, 1), (3, 2), (3, 3)])
        plot.show_yticklabels_for_all([(0, 3), (1, 3), (2, 3), (3, 3)])
        # plot.set_title(0, 1, 'Particle counts for station 501 and 510')
        for i in range(4):
            plot.set_subplot_xlabel(0, i, 'detector %d' % (i + 1))
            plot.set_subplot_ylabel(i, 0, 'detector %d' % (i + 1))
        plot.set_xlabel('Number of particles 501')
        plot.set_ylabel('Number of particles 510')
        plot.save_as_pdf('n_minn%d_501_510_bins_log' % minn)

    ncounts, x, y = np.histogram2d(sn501, sn510, bins=bins)
    plot = Plot('loglog')
    plot.set_axis_equal()
    plot.histogram2d(ncounts, x, y, type='reverse_bw', bitmap=True)
    # plot.set_title('Particle counts for station 501 and 510')
    plot.set_xlabel('Particle density in 501')
    plot.set_ylabel('Particle density in 510')
    plot.save_as_pdf('n_501_510_sum_log')
Exemple #3
0
def plot_pi(expected, measured, name, expected_err=[], measured_err=[]):
    """

    :param expected: expected pulseintegral from sum individual measurements.
    :param measured: measured pulseintegral.
    :param name: name for output

    """
    plot = MultiPlot(2, 1, height=r".67\linewidth")
    splot = plot.get_subplot_at(0, 0)
    splot.scatter(measured,
                  expected,
                  xerr=measured_err,
                  yerr=expected_err,
                  markstyle='mark size=1pt')
    splot.plot([0, 120], [0, 120], mark=None, linestyle='gray')
    plot_fit(plot, expected, measured, measured_err)

    splot.set_ylabel(
        r'Sum individual LED pulseintegrals [\si{\nano\volt\second}]')
    splot.set_ylimits(0, 60)
    splot.set_axis_equal()

    splot = plot.get_subplot_at(1, 0)
    splot.set_xlabel(r'Multiple-LED pulseintegrals [\si{\nano\volt\second}]')

    plot.set_xlimits_for_all(None, 0, 60)
    plot.show_xticklabels(1, 0)
    plot.show_yticklabels_for_all(None)
    plot.save_as_pdf('plots/data_pi_' + name)
Exemple #4
0
def plot_energy_v_time_for_bin(seeds, gamma_t, electrons_t, muons_t, gamma_e,
                               electrons_e, muons_e):

    plot = MultiPlot(3, 1, 'loglog', height=r'.3\linewidth')
    e_bins = logspace(6, 12, 40)
    t_bins = logspace(
        log10(min(gamma_t.min(), electrons_t.min(), muons_t.min())),
        log10(max(gamma_t.max(), electrons_t.max(), muons_t.max())), 25)

    for splot, t_data, e_data, particle_name in zip(
            plot.subplots, [gamma_t, electrons_t, muons_t],
        [gamma_e, electrons_e, muons_e], ['Gamma', 'Electrons', 'Muons']):
        splot.set_ylabel(particle_name)
        counts, e_bins, t_bins = histogram2d(e_data,
                                             t_data,
                                             bins=[e_bins, t_bins])
        splot.histogram2d(counts,
                          e_bins,
                          t_bins,
                          type='color',
                          colormap='viridis',
                          bitmap=True)
        splot.draw_vertical_line(300e6 if particle_name is 'Muons' else 3e6,
                                 'red')


#         plot.set_xlimits_for_all(None, bins[0], bins[-1])
#         plot.set_ylimits_for_all(None, 0, 120)
    plot.show_xticklabels(2, 0)
    plot.show_yticklabels_for_all()
    plot.subplots[-1].set_xlabel(r'Particle energy [\si{\MeV}]')
    plot.set_ylabel(r'Arrival time [\si{\ns}]')
    plot.save_as_pdf('plots/time_energy_profile/%s.pdf' %
                     get_info_string(seeds))
Exemple #5
0
def plot_multi_delta_time(ids, **kwargs):
    """ Plot delta versus the timestamps

    """
    plot = MultiPlot(1, len(ids))
    for splot, id in zip(plot.subplots, ids):
        ext_timestamps, deltas = get(id)
        daystamps = (np.array(ext_timestamps) - min(ext_timestamps)) / 864e11
        if max(daystamps) > 3:
            idx = next(i for i, v in enumerate(daystamps) if v > 3.2)
            deltas = deltas[:idx]
            daystamps = daystamps[:idx]
        splot.plot(daystamps[::101],
                   deltas[::101],
                   mark=None,
                   linestyle='very thin')
        #         splot.scatter(daystamps[::400], deltas[::400], mark='*',
        #                       markstyle="mark size=.1pt")
        splot.set_axis_options(r'width=%.2f\textwidth' % (.9 / len(ids)))

        splot.set_xlimits(0, max(daystamps))
    plot.show_xticklabels_for_all()
    plot.show_yticklabels(0, 0)
    plot.set_xlabel(r'Time in test [days]')
    plot.set_ylabel(r'$\Delta t$ [\si{\ns}]')
    plot.set_ylimits_for_all(None, -175, 175)

    name = 'delta_time/tt_delta_time_' + '_'.join([str(id) for id in ids])
    plot.save_as_pdf(PLOT_PATH + name)

    print 'tt_analyse: Plotted delta vs time'
Exemple #6
0
def plot_pi_ph(measured_pi, measured_ph, name, ratio, pi_err=[], ph_err=[]):
    """

    :param measured_pi: measured pulseintegral.
    :param measured_ph: measured pulseheight.
    :param name: name for output
    :param ratio: pi / ph ratio (from individual fibers, before saturation)

    """
    plot = MultiPlot(2, 1, height=r".67\linewidth")

    splot = plot.get_subplot_at(0, 0)
    splot.scatter(measured_ph,
                  measured_pi / ratio,
                  xerr=ph_err,
                  yerr=pi_err / ratio,
                  markstyle='mark size=1pt')
    splot.plot([0, 6], [0, 6], mark=None, linestyle='gray')

    plot_fit(plot, measured_pi / ratio, measured_ph, pi_err)

    splot.set_ylabel(r'Multiple-LED pulseintegrals [\si{\nano\volt\second}]')
    splot.set_ylimits(0, 5.5)

    splot = plot.get_subplot_at(1, 0)
    splot.set_xlabel(r'Multiple-LED pulseheights [\si{\volt}]')

    plot.set_xlimits_for_all(None, 0, 5.5)
    plot.show_yticklabels_for_all(None)
    plot.show_xticklabels(1, 0)
    plot.save_as_pdf('plots/data_piph_' + name)
Exemple #7
0
def plot_coinc_window(windows, counts, n_events=0):

    plot = MultiPlot(2,
                     1,
                     axis='semilogx',
                     width=r'.8\linewidth',
                     height=r'.5\linewidth')
    plot.set_title(0, 0,
                   'Number of coincidences as function of coincidence window')
    plot.set_xlabel('Coincidence window (ns)')
    plot.show_xticklabels(1, 0)
    plot.show_yticklabels_for_all()
    plot.set_xlimits_for_all(min=1e1, max=1e8)
    plot.set_ylimits(1, 0, min=0)

    counts = numpy.array(counts)

    subplot = plot.get_subplot_at(0, 0)
    subplot.set_ylabel('Found coincidences')
    subplot.plot(windows, counts, mark=None)

    subplot = plot.get_subplot_at(1, 0)
    subplot.set_ylabel('Delta found coincidences')
    subplot.plot(windows[:-1], counts[1:] - counts[:-1], mark=None)

    plot.save_as_pdf('coincidence_window')
Exemple #8
0
def plot_comparison(stats, field_name):
    plot = MultiPlot(len(STATIONS),
                     len(STATIONS),
                     width=r'.06\textwidth',
                     height=r'.06\textwidth')
    bins = arange(0, 1.2, .03)
    for i, ref_station in enumerate(STATIONS):
        ref_stat = stats[ref_station][field_name][0]
        ref_filter = ref_stat > 0
        for j, station in enumerate(STATIONS):
            if i == j:
                plot.set_empty(i, j)
                plot.set_label(r'%d' % station, location='center')
                continue
            splot = plot.get_subplot_at(i, j)
            stat = stats[station][field_name][0]

            tmp_stat = stat.compress(ref_filter & (stat > 0))
            tmp_ref_stat = ref_stat.compress(ref_filter & (stat > 0))
            counts, xbin, ybin = histogram2d(tmp_stat, tmp_ref_stat, bins=bins)
            splot.histogram2d(counts,
                              xbin,
                              ybin,
                              type='reverse_bw',
                              bitmap=True)
            splot.plot([0, 1.2], [0, 1.2],
                       mark=None,
                       linestyle='red, very thin')


#     plot.set_xlimits_for_all(None, min=bins[0], max=bins[-1])
#     plot.set_ylimits_for_all(None, min=bins[0], max=bins[-1])
#     plot.subplots[-1].set_xtick_labels(YEARS_LABELS)
#     plot.subplots[-1].show_xticklabels()
#
#     plot.show_yticklabels_for_all(None)
#     for row in range(0, len(plot.subplots), 2):
#         plot.set_yticklabels_position(row, 0, 'left')
#     for row in range(1, len(plot.subplots), 2):
#         plot.set_yticklabels_position(row, 0, 'right')
#     plot.set_ylimits_for_all(None, -1e-4)

    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/compare_%s' % field_name)
    else:
        plot.save_as_pdf('plots/compare_bad_fraction_%s' % field_name)
Exemple #9
0
def plot_timeline(stats, field_name):
    step = 0.2 * BIN_WIDTH

    plot = MultiPlot(len(STATIONS),
                     1,
                     width=r'.67\textwidth',
                     height=r'.075\paperheight')
    #     if field_name in ['event_rate', 'mpv']:
    #         plot = MultiPlot(len(STATIONS), 1,
    #                          width=r'.67\textwidth', height=r'.05\paperheight')
    #     else:
    #         plot = MultiPlot(len(STATIONS), 1, 'semilogy',
    #                          width=r'.67\textwidth', height=r'.05\paperheight')

    for splot, station in zip(plot.subplots, STATIONS):
        stat = stats[station][field_name]
        if len(stat.shape) == 2:
            for i, s in enumerate(stat):
                splot.histogram(s,
                                BINS + (step * i),
                                linestyle='thin,' + COLORS[i])
        else:
            splot.histogram(stat, BINS, linestyle='thin')
        splot.set_ylabel(r'%d' % station)

    plot.set_xlimits_for_all(None, min=BINS[0], max=BINS[-1])
    plot.set_xticks_for_all(None, YEARS_TICKS)
    plot.subplots[-1].set_xtick_labels(YEARS_LABELS)
    plot.subplots[-1].show_xticklabels()

    plot.show_yticklabels_for_all(None)
    for row in range(0, len(plot.subplots), 2):
        plot.set_yticklabels_position(row, 0, 'left')
    for row in range(1, len(plot.subplots), 2):
        plot.set_yticklabels_position(row, 0, 'right')
    plot.set_ylimits_for_all(None, -1e-4)

    #     if field_name not in ['event_rate', 'mpv']:
    #         plot.set_ylimits_for_all(None, 1e-4, 100)

    plot.set_xlabel(r'Timestamp')

    if field_name == 'event_rate':
        ylabel = r'Event rate [\si{\hertz}]'
    elif field_name == 'mpv':
        ylabel = r'MPV [ADC.ns]'
    else:
        ylabel = (r'Fraction of bad %s data [\si{\percent}]' %
                  field_name.replace('_', ' '))
    plot.set_ylabel(ylabel)

    if field_name in ['event_rate', 'mpv']:
        plot.save_as_pdf('plots/%s' % field_name)
    else:
        plot.save_as_pdf('plots/bad_fraction_%s' % field_name)
Exemple #10
0
def plot_shower_profile(seeds):

    with tables.open_file(PATH % seeds) as data:
        gp = data.root.groundparticles

        min_t = gp.col('t').min()

        print 'Making plots for %s' % seeds

        gamma = gp.read_where('particle_id == 1')
        electrons = gp.read_where('(particle_id == 3) | (particle_id == 4)')
        muons = gp.read_where('(particle_id == 5) | (particle_id == 6)')

        for correction in ['none', 'median_self']:
            plot = MultiPlot(3, 1, 'semilogx', height=r'.4\linewidth')

            splot = plot.get_subplot_at(0, 0)
            splot.set_ylabel('Gamma')
            plot_statistics(seeds,
                            splot,
                            gamma['r'],
                            gamma['t'] - min_t,
                            'solid',
                            correction=correction)

            splot = plot.get_subplot_at(1, 0)
            splot.set_ylabel('Electrons')
            plot_statistics(seeds,
                            splot,
                            electrons['r'],
                            electrons['t'] - min_t,
                            'solid',
                            correction=correction)

            splot = plot.get_subplot_at(2, 0)
            splot.set_ylabel('Muon')
            plot_statistics(seeds,
                            splot,
                            muons['r'],
                            muons['t'] - min_t,
                            'solid',
                            correction=correction)

            plot.set_xlimits_for_all(None, 1e0, 1e3)
            if correction is 'median_self':
                plot.set_ylimits_for_all(None, -120, 120)
            else:
                plot.set_ylimits_for_all(None, 0, 120)
            plot.show_xticklabels(2, 0)
            plot.show_yticklabels_for_all()
            plot.set_ylabel(r'Arrival time [\si{\ns}]')
            plot.set_xlabel(r'Core distance [\si{\meter}]')
            plot.set_title(0, 0, get_info_string_tex(seeds))
            plot.save_as_pdf('plots/time_profile/%s_%s.pdf' %
                             (get_info_string(seeds), correction))
Exemple #11
0
def plot_detected_zenith_distribution():
    plot = MultiPlot(2, 2, width=r'.3\textwidth', height=r'.3\textwidth')
    for i, e in enumerate([16, 16.5, 17, 17.5]):
        splot = plot.get_subplot_at(int(i / 2), int(i % 2))
        c, b = histogram(zenith.compress(energy_in == e),
                         bins=arange(0, 65, 1))
        splot.histogram(c, b)
    plot.set_title('Reconstructed zeniths per shower energy')
    plot.set_xlimits_for_all(None, 0, 65)
    plot.set_ylimits_for_all(None, 0)
    plot.save_as_pdf('zenith_reconstructed')
Exemple #12
0
def plot_station_offset_matrix():
    n = len(STATIONS)
    stations = {
        station: Station(station, force_stale=True)
        for station in STATIONS
    }

    for type in ['offset', 'error']:
        plot = MultiPlot(n, n, width=r'.08\textwidth', height=r'.08\textwidth')

        for i, station in enumerate(STATIONS):
            for j, ref_station in enumerate(STATIONS):
                splot = plot.get_subplot_at(i, j)
                if i == n:
                    splot.show_xticklabels()
                if station == ref_station:
                    splot.set_empty()
                    splot.set_label(r'%d' % station, location='center')
                    continue
                offsets = stations[station].station_timing_offsets(ref_station)
                bins = list(offsets['timestamp'])
                bins += [bins[-1] + 86400]
                splot.histogram(offsets[type], bins, linestyle='very thin')
                splot.set_axis_options('line join=round')
                plot_cuts_vertically(splot, stations, station, ref_station)

        # Even/row rows/columns
        for row in range(0, n, 2):
            plot.set_yticklabels_position(row, n - 1, 'right')
            plot.set_xticklabels_position(n - 1, row, 'bottom')
            plot.show_yticklabels(row, n - 1)
            #plot.show_xticklabels(n - 1, row)

        for row in range(1, n, 2):
            plot.set_yticklabels_position(row, 0, 'left')
            plot.set_xticklabels_position(0, row, 'top')
            plot.show_yticklabels(row, 0)
            #plot.show_xticklabels(0, row)

        if type == 'offset':
            plot.set_ylimits_for_all(None, min=-70, max=70)
        else:
            plot.set_ylimits_for_all(None, min=0, max=10)
        plot.set_xlimits_for_all(None,
                                 min=datetime_to_gps(date(2011, 1, 1)),
                                 max=datetime_to_gps(date.today()))
        plot.set_xticks_for_all(None, YEARS_TICKS)
        # plot.set_xtick_labels_for_all(YEARS_LABELS)

        plot.set_xlabel(r'Date')
        plot.set_ylabel(r'Station offset [\si{\ns}]')

        plot.save_as_pdf('station_offsets_%s' % type)
Exemple #13
0
def plot_input_v_reconstructed_azimuth():
    plot = MultiPlot(2, 2, width=r'.3\textwidth', height=r'.3\textwidth')
    a_bins = linspace(-180, 180, 60)

    for i, e in enumerate([16, 16.5, 17, 17.5]):
        splot = plot.get_subplot_at(int(i / 2), int(i % 2))
        c, xb, yb = histogram2d(azimuth_in.compress(energy_in == e),
                                azimuth.compress(energy_in == e),
                                bins=a_bins)
        splot.histogram2d(c, xb, yb, bitmap=True, type='reverse_bw')
        splot.plot([-180, 180], [-180, 180], linestyle='red', mark=None)

    plot.show_xticklabels_for_all([(1, 0), (0, 1)])
    plot.show_yticklabels_for_all([(1, 0), (0, 1)])
    plot.save_as_pdf('reconstructed_v_in_azimuth.pdf')
Exemple #14
0
def plot_layouts(path='/'):
    with tables.open_file(RESULT_DATA, 'r') as data:
        cluster = data.get_node_attr(path + 'coincidences', 'cluster')
        plot = MultiPlot(3, 1, width=r'0.67\textwidth', height=r'.2\textwidth')
        for splot, station in zip(plot.subplots, cluster.stations):
            for detector in station.detectors:
                x, y = zip(*detector.get_corners())
                splot.plot(x + x[:1], y + y[:1], mark=None)
                splot.set_axis_equal()
        plot.show_xticklabels_for_all([(2, 0)])
        plot.show_yticklabels_for_all()
        plot.set_ylabel(r'North [\si{\meter}]')
        plot.set_xlabel(r'East [\si{\meter}]')
        plot.set_xlimits_for_all(None, -6, 6)
        plot.set_ylimits_for_all(None, -1.2, 1.2)
        plot.save_as_pdf('layouts' + path.replace('/', '_'))
Exemple #15
0
def plot_energy_v_time(seeds):

    with tables.open_file(PATH % seeds) as data:
        gp = data.root.groundparticles

        min_t = gp.col('t').min()

        gamma = gp.read_where('(particle_id == 1)')
        electrons = gp.read_where('(particle_id >= 3) & (particle_id <= 4)')
        muons = gp.read_where('(particle_id >= 5) & (particle_id <= 6)')

        gamma_t = gamma['t'] - min_t
        electrons_t = electrons['t'] - min_t
        muons_t = muons['t'] - min_t

        gamma_e = particle_energies(gamma)
        electrons_e = particle_energies(electrons)
        muons_e = particle_energies(muons)

    plot = MultiPlot(3, 1, 'loglog', height=r'.3\linewidth')
    e_bins = logspace(6, 12, 40)
    t_bins = logspace(-1, 3, 25)

    for splot, t_data, e_data, particle_name in zip(
            plot.subplots, [gamma_t, electrons_t, muons_t],
        [gamma_e, electrons_e, muons_e], ['Gamma', 'Electrons', 'Muons']):
        splot.set_ylabel(particle_name)
        counts, e_bins, t_bins = histogram2d(e_data,
                                             t_data,
                                             bins=[e_bins, t_bins])
        splot.histogram2d(counts,
                          e_bins,
                          t_bins,
                          type='color',
                          colormap='viridis',
                          bitmap=True)
        splot.draw_vertical_line(300e6 if particle_name is 'Muons' else 3e6,
                                 'red')


#         plot.set_xlimits_for_all(None, bins[0], bins[-1])
#         plot.set_ylimits_for_all(None, 0, 120)
    plot.show_xticklabels(2, 0)
    plot.show_yticklabels_for_all()
    plot.subplots[-1].set_xlabel(r'Particle energy [\si{\MeV}]')
    plot.set_ylabel(r'Arrival time [\si{\ns}]')
    plot.save_as_pdf('plots/time_energy_2D/%s.pdf' % get_info_string(seeds))
def plot_residual_time_differences(data):
    global idxes, dts
    events = data.root.kascade.events
    c_index = data.root.kascade.c_index

    t0 = make_timestamp(2008, 7, 2)
    t1 = make_timestamp(2008, 7, 3)

    idxes = events.get_where_list('(t0 <= timestamp) & (timestamp < t1)')
    t0_idx = min(idxes)
    t1_idx = max(idxes)

    dts = c_index.read_where('(t0_idx <= k_idx) & (k_idx < t1_idx)',
                            field='dt')
    all_dts = c_index.col('dt')

    figure()
    subplot(121)
    hist(all_dts / 1e3, bins=arange(-10, 2, .01), histtype='step')
    title("July 1 - Aug 6, 2008")
    xlabel("Time difference [us]")
    ylabel("Counts")

    subplot(122)
    hist(dts / 1e3, bins=arange(-8, -6, .01), histtype='step')
    title("July 2, 2008")
    xlabel("Time difference [us]")
    utils.saveplot()

    graph = MultiPlot(1, 2, width=r'.45\linewidth')
    n, bins = histogram(all_dts / 1e3, bins=arange(-10, 2, .01))
    graph.histogram(0, 1, n, bins)
    graph.set_title(0, 1, "Jul 1 - Aug 6, 2008")

    n, bins = histogram(dts / 1e3, bins=arange(-8, -6, .01))
    graph.histogram(0, 0, n, bins)
    graph.set_title(0, 0, "Jul 2, 2008")

    graph.set_xlabel(r"Time difference [\si{\micro\second}]")
    graph.set_ylabel("Counts")
    graph.set_ylimits(min=0)
    graph.show_xticklabels_for_all([(0, 0), (0, 1)])
    graph.show_yticklabels_for_all([(0, 0), (0, 1)])

    graph.save('plots/MAT-residual-time-differences')
    graph.save_as_pdf('preview')
Exemple #17
0
def plot_energy_v_distance(seeds):

    with tables.open_file(PATH % seeds) as data:
        gp = data.root.groundparticles

        gamma = gp.read_where('particle_id == 1')
        electrons = gp.read_where('(particle_id == 3) | (particle_id == 4)')
        muons = gp.read_where('(particle_id == 5) | (particle_id == 6)')

        gamma_r = gamma['r']
        electrons_r = electrons['r']
        muons_r = muons['r']

        gamma_e = particle_energies(gamma)
        electrons_e = particle_energies(electrons)
        muons_e = particle_energies(muons)

        plot = MultiPlot(3, 1, 'loglog', height=r'.3\linewidth')
        r_bins = logspace(1, 3, 20)
        e_bins = logspace(6, 12, 40)

        for splot, r_data, e_data, particle_name in zip(
                plot.subplots, [gamma_r, electrons_r, muons_r],
            [gamma_e, electrons_e, muons_e], ['Gamma', 'Electrons', 'Muons']):
            splot.set_ylabel(particle_name)
            counts, r_bins, e_bins = histogram2d(r_data,
                                                 e_data,
                                                 bins=[r_bins, e_bins])
            splot.histogram2d(counts,
                              r_bins,
                              e_bins,
                              type='color',
                              colormap='viridis',
                              bitmap=True)
            splot.draw_horizontal_line(
                300e6 if particle_name is 'Muons' else 3e6, 'red')


#         plot.set_xlimits_for_all(None, bins[0], bins[-1])
#         plot.set_ylimits_for_all(None, 0, 120)
        plot.show_xticklabels(2, 0)
        plot.show_yticklabels_for_all()
        plot.subplots[-1].set_xlabel(r'Core distance [\si{\meter}]')
        plot.set_ylabel(r'Particle energy [\si{\MeV}]')
        plot.save_as_pdf('plots/distance_energy_2D/%s.pdf' %
                         get_info_string(seeds))
def plot_residual_time_differences(data):
    global idxes, dts
    events = data.root.kascade.events
    c_index = data.root.kascade.c_index

    t0 = make_timestamp(2008, 7, 2)
    t1 = make_timestamp(2008, 7, 3)

    idxes = events.get_where_list('(t0 <= timestamp) & (timestamp < t1)')
    t0_idx = min(idxes)
    t1_idx = max(idxes)

    dts = c_index.read_where('(t0_idx <= k_idx) & (k_idx < t1_idx)',
                             field='dt')
    all_dts = c_index.col('dt')

    figure()
    subplot(121)
    hist(all_dts / 1e3, bins=arange(-10, 2, .01), histtype='step')
    title("July 1 - Aug 6, 2008")
    xlabel("Time difference [us]")
    ylabel("Counts")

    subplot(122)
    hist(dts / 1e3, bins=arange(-8, -6, .01), histtype='step')
    title("July 2, 2008")
    xlabel("Time difference [us]")
    utils.saveplot()

    graph = MultiPlot(1, 2, width=r'.45\linewidth')
    n, bins = histogram(all_dts / 1e3, bins=arange(-10, 2, .01))
    graph.histogram(0, 1, n, bins)
    graph.set_title(0, 1, "Jul 1 - Aug 6, 2008")

    n, bins = histogram(dts / 1e3, bins=arange(-8, -6, .01))
    graph.histogram(0, 0, n, bins)
    graph.set_title(0, 0, "Jul 2, 2008")

    graph.set_xlabel(r"Time difference [\si{\micro\second}]")
    graph.set_ylabel("Counts")
    graph.set_ylimits(min=0)
    graph.show_xticklabels_for_all([(0, 0), (0, 1)])
    graph.show_yticklabels_for_all([(0, 0), (0, 1)])

    graph.save('plots/MAT-residual-time-differences')
    graph.save_as_pdf('preview')
Exemple #19
0
def plot_coinc_window(windows,
                      counts,
                      group_name='',
                      n_events=0,
                      n_stations=0,
                      date=datetime.date.today()):
    counts = numpy.array(counts)
    plot = MultiPlot(2, 1)

    splot = plot.get_subplot_at(0, 0)
    splot.set_axis_options(r'ymode=log, xmode=log')
    splot.scatter(windows, counts)
    plot_background_v_window(splot, windows, n_stations)
    plot_chosen_coincidence_window(splot)
    splot = plot.get_subplot_at(1, 0)
    # dy
    #     splot.scatter(windows[:-1], counts[1:] - counts[:-1])
    # dy/dx
    #     splot.scatter(windows[:-1],
    #                   (counts[1:] - counts[:-1]) /
    #                   (windows[1:] - windows[:-1]))
    # dy/dlogx
    #     splot.scatter(windows[:-1],
    #                   (counts[1:] - counts[:-1]) /
    #                   (numpy.log10(windows[1:]) - numpy.log10(windows[:-1])))
    # dlogy/dlogx
    splot.scatter(windows[:-1],
                  (numpy.log10(counts[1:]) - numpy.log10(counts[:-1])) /
                  (numpy.log10(windows[1:]) - numpy.log10(windows[:-1])))
    splot.set_axis_options(r'height=0.2\textwidth, xmode=log, ymode=normal')
    #     splot.set_axis_options(r'height=0.2\textwidth, xmode=log, ymode=log')

    text = ('%s\nDate: %s\nTotal n events: %d' %
            (group_name, date.isoformat(), n_events))
    plot.set_label(0, 0, text, 'upper left')
    plot.set_xlimits_for_all(min=0.5, max=1e14)
    plot.set_ylimits(0, 0, min=1, max=1e8)
    plot.set_ylabel('Found coincidences')
    plot.set_xlabel(r'Coincidence window [\si{\ns}]')
    plot.show_xticklabels(1, 0)
    plot.show_yticklabels_for_all(None)
    plot.set_yticklabels_position(1, 0, 'right')

    plot.save_as_pdf('plots/coincidences_%s' % group_name)
Exemple #20
0
def plot_input_v_reconstructed_zenith():
    plot = MultiPlot(2, 2, width=r'.3\textwidth', height=r'.3\textwidth')
    z_in_bins = arange(-3.75, 63.76, 7.5)
    z_out_bins = arange(0, 70, 1)

    for i, e in enumerate([16, 16.5, 17, 17.5]):
        splot = plot.get_subplot_at(int(i / 2), int(i % 2))
        c, xb, yb = histogram2d(zenith_in.compress(energy_in == e),
                                zenith.compress(energy_in == e),
                                bins=(z_in_bins, z_out_bins))
        splot.histogram2d(c, xb, yb, bitmap=True, type='reverse_bw')
        splot.plot([0, 60], [0, 60], linestyle='red', mark=None)

    # plot.set_title('Input and detected zeniths for shower energy: %.1f' % e)
    # plot.set_xlimits(0, 65)
    # plot.set_ylimits(0)
    plot.show_xticklabels_for_all([(1, 0), (0, 1)])
    plot.show_yticklabels_for_all([(1, 0), (0, 1)])
    plot.save_as_pdf('reconstructed_v_in_zenith.pdf')
Exemple #21
0
def plot_time_profile_for_bin(seeds, gamma_t, electrons_t, muons_t):

    plot = MultiPlot(3, 1, 'semilogx', height=r'.4\linewidth')
    bins = logspace(
        log10(min(gamma_t.min(), electrons_t.min(), muons_t.min())),
        log10(max(gamma_t.max(), electrons_t.max(), muons_t.max())), 25)
    for splot, data, particle_name in zip(plot.subplots,
                                          [gamma_t, electrons_t, muons_t],
                                          ['Gamma', 'Electrons', 'Muons']):
        splot.set_ylabel(particle_name)
        splot.histogram(*histogram(data, bins=bins))

    plot.set_xlimits_for_all(None, bins[0], bins[-1])
    #         plot.set_ylimits_for_all(None, 0, 120)
    plot.show_xticklabels(2, 0)
    plot.show_yticklabels_for_all()
    plot.set_ylabel(r'Number of particles')
    plot.set_xlabel(r'Arrival time [\si{\ns}]')
    plot.save_as_pdf('plots/time_profile_bin/%s.pdf' % get_info_string(seeds))
Exemple #22
0
def plot_densities(data):
    """Make particle count plots for each detector to compare densities/responses"""

    n_min = 0.5  # remove gamma peak
    n_max = 50
    bins = np.linspace(np.log10(n_min), np.log10(n_max), 60)

    for station_number in [501, 510]:
        events = data.get_node('/s%d' % station_number, 'events')
        average_n = (events.col('n1') + events.col('n2') + events.col('n3') + events.col('n4')) / 4.
        n = [events.col('n1'), events.col('n2'), events.col('n3'), events.col('n4')]

        for minn in [0, 1, 2, 4, 8, 16]:
            filter = (average_n > minn) & (n[0] > 0) & (n[1] > 0) & (n[2] > 0) & (n[3] > 0)
            plot = MultiPlot(4, 4, width=r'.25\linewidth',
                             height=r'.25\linewidth')
            for i in range(4):
                for j in range(4):
                    if i < j:
                        continue
                    elif i == j:
                        ncounts, x, y = np.histogram2d(np.log10(average_n.compress(filter)),
                                                       np.log10(n[i].compress(filter)),
                                                       bins=bins)
                    else:
                        ncounts, x, y = np.histogram2d(np.log10(n[i].compress(filter)),
                                                       np.log10(n[j].compress(filter)),
                                                       bins=bins)
                    subplot = plot.get_subplot_at(i, j)
                    subplot.histogram2d(ncounts, x, y, type='reverse_bw',
                                        bitmap=True)
            plot.set_xlimits_for_all(min=0, max=np.log10(n_max))
            plot.set_ylimits_for_all(min=0, max=np.log10(n_max))
            plot.show_xticklabels_for_all([(3, 0), (3, 1), (3, 2), (3, 3)])
            plot.show_yticklabels_for_all([(0, 3), (1, 3), (2, 3), (3, 3)])
        #     plot.set_title(0, 1, 'Particle counts for station 501 and 510')
            for i in range(4):
                plot.set_subplot_xlabel(0, i, 'detector %d' % (i + 1))
                plot.set_subplot_ylabel(i, 0, 'detector %d' % (i + 1))
            plot.set_xlabel('Number of particles')
            plot.set_ylabel('Number of particles')
            plot.save_as_pdf('plots/n_minn%d_%d' % (minn, station_number))
Exemple #23
0
def plot_multi_box(ids1, ids2, **kwargs):
    """Box Plot like results"""

    li = len(ids1) + len(ids2)

    # Begin Figure
    plot = MultiPlot(1, 2)
    for splot, ids in zip(plot.subplots, [ids1, ids2]):
        data = [
            determine_stats([i for i in get(id)[1] if abs(i) < 100])
            for id in ids
        ]
        low, high, avg, std = zip(*data)
        x = range(len(ids))
        splot.plot(x,
                   avg,
                   yerr=std,
                   mark='o',
                   markstyle="mark size=1pt",
                   linestyle=None)
        splot.scatter(x, low, mark='x', markstyle="mark size=.75pt")
        splot.scatter(x, high, mark='x', markstyle="mark size=.75pt")
        splot.set_axis_options(r'height=.67\textwidth, width=%.2f\textwidth' %
                               ((len(ids) * .67 / li)))
        splot.set_xlimits(-0.5, len(ids) - 0.5)
        splot.set_xticks(x)

    plot.set_xlabel(r'Tests')
    plot.set_ylabel(r'$\Delta t$ [\si{\ns}]')
    plot.set_ylimits_for_all(None, -70, 70)
    plot.show_yticklabels(0, 0)

    # Save Figure
    if len(ids) == 1:
        name = 'box/tt_offset_%03d' % ids[0]
    elif kwargs.keys():
        name = 'box/tt_offset_' + kwargs[kwargs.keys()[0]]
    plot.save_as_pdf(PLOT_PATH + name)

    print 'tt_analyse: Plotted offsets'
Exemple #24
0
def plot_configs_timeline(stats, field, field_name):
    step = 86400  # one day
    plot = MultiPlot(len(STATIONS),
                     1,
                     width=r'.67\textwidth',
                     height=r'.05\paperheight')
    for splot, station in zip(plot.subplots, STATIONS):
        config = stats[station][field]
        for i in range(4):
            timestamps = list(config['timestamp'] + (i * step))
            timestamps.append(END_TS)
            splot.histogram(config[field_name % (i + 1)],
                            timestamps,
                            linestyle=COLORS[i])
        splot.set_ylabel(r'%d' % station)

    plot.set_xlimits_for_all(None, min=START_TS, max=END_TS)
    plot.set_xticks_for_all(None, YEARS_TICKS)
    plot.subplots[-1].set_xtick_labels(YEARS_LABELS)
    plot.subplots[-1].show_xticklabels()

    plot.show_yticklabels_for_all(None)
    for row in range(0, len(plot.subplots), 2):
        plot.set_yticklabels_position(row, 0, 'left')
    for row in range(1, len(plot.subplots), 2):
        plot.set_yticklabels_position(row, 0, 'right')

    if field == 'voltages':
        plot.set_ylimits_for_all(None, 300)
        plot.set_ylabel(r'PMT voltage \si{\volt}')
    elif field == 'currents':
        plot.set_ylimits_for_all(None, 0)
        plot.set_ylabel(r'PMT current \si{\milli\volt}')
    elif field == 'detector_timing_offsets':
        plot.set_ylabel(r'Detector timing offsets \si{\ns}')

    plot.set_xlabel(r'Timestamp')
    plot.save_as_pdf('plots/config_%s' % field)
Exemple #25
0
def plot_energy_profile_for_bin(seeds, gamma_e, electrons_e, muons_e):

    plot = MultiPlot(3, 1, 'semilogx', height=r'.4\linewidth')
    print('Min gamma/electron energy: %d MeV,  %d MeV' %
          (gamma_e.min() * 1e-6, electrons_e.min() * 1e-6))
    print 'Min muon energy: %d MeV' % (muons_e.min() * 1e-6, )
    bins = logspace(6, 12, 40)
    for splot, data, particle_name in zip(plot.subplots,
                                          [gamma_e, electrons_e, muons_e],
                                          ['Gamma', 'Electrons', 'Muons']):
        splot.set_ylabel(particle_name)
        splot.draw_vertical_line(300e6 if particle_name is 'Muons' else 3e6,
                                 'red')
        splot.histogram(*histogram(data, bins=bins))

    plot.set_xlimits_for_all(None, bins[0], bins[-1])
    # plot.set_ylimits_for_all(None, 0, 120)
    plot.show_xticklabels(2, 0)
    plot.show_yticklabels_for_all()
    plot.set_ylabel(r'Number of particles')
    plot.set_xlabel(r'Particle energy [\si{\MeV}]')
    plot.save_as_pdf('plots/energy_profile_bin/%s.pdf' %
                     get_info_string(seeds))
Exemple #26
0
def compare_integrals(before, after):
    if len(before) > 5000:
        plot = MultiPlot(4, 1, width=r'.6\textwidth', height=r'.3\textwidth')
        bins = [linspace(100, 6000, 20), linspace(-150, 150, 20)]
        for i, splot in enumerate(plot.subplots):
            c, x, y = histogram2d(before[:, i],
                                  after[:, i] - before[:, i],
                                  bins=bins)
            #             splot.histogram2d(c, x, y, bitmap=True, type='color', colormap='viridis')
            splot.histogram2d(c, x, y, type='area')
        plot.show_yticklabels_for_all(None)
        plot.show_xticklabels(3, 0)
        plot.save_as_pdf('hist2d')
    else:
        plot = MultiPlot(4,
                         1,
                         'semilogx',
                         width=r'.6\textwidth',
                         height=r'.3\textwidth')
        for i, splot in enumerate(plot.subplots):
            splot.scatter(before[:, i],
                          after[:, i] - before[:, i],
                          mark='o',
                          markstyle='mark size=0.6pt, very thin, '
                          'semitransparent, %s' % COLORS[i])
        plot.show_yticklabels_for_all(None)
        plot.show_xticklabels(3, 0)
        plot.set_xlimits_for_all(None, 100, 100000)
        plot.set_ylimits_for_all(None, -150, 150)
        plot.save_as_pdf('scatter')

    plot = MultiPlot(4, 1, width=r'.6\textwidth', height=r'.3\textwidth')
    for i, splot in enumerate(plot.subplots):
        filter = before[:, i] > 0  # Ignore detectors/events with no signal
        c, bins = histogram(after[:, i][filter] - before[:, i][filter],
                            linspace(-150, 150, 100))
        splot.histogram(c, bins, linestyle='%s' % COLORS[i])
    plot.show_yticklabels_for_all(None)
    plot.show_xticklabels(3, 0)
    plot.set_xlimits_for_all(None, -150, 150)
    plot.set_ylimits_for_all(None, 0)
    plot.save_as_pdf('histogram')
Exemple #27
0
def plot_distance_width():

    distances = []
    widths = []
    sim_widths = []

    with tables.open_file(SIM_PATH, 'r') as sim_data:
        for ref_station, station in itertools.combinations(SPA_STAT, 2):
            if ref_station == 501 and station == 509:
                continue
            if ref_station == 501 and station == 510:
                continue
            if ref_station == 505 and station == 509:
                continue
            distances.append(
                CLUSTER.calc_rphiz_for_stations(SPA_STAT.index(ref_station),
                                                SPA_STAT.index(station))[0])
            with tables.open_file(
                    DATA_PATH + 'dt_ref%d_%d.h5' % (ref_station, station),
                    'r') as data:

                table = get_station_dt(data, station)
                ts1 = table[-1]['timestamp'] - WEEK
                ts0 = ts1 - HALFYEAR  # * max(1, (distance / 100))
                dt = table.read_where('(timestamp > ts0) & (timestamp < ts1)',
                                      field='delta')

                sim_ref_events = sim_data.get_node(
                    '/flat/cluster_simulations/station_%d' % ref_station,
                    'events')
                sim_events = sim_data.get_node(
                    '/flat/cluster_simulations/station_%d' % station, 'events')
                sim_dt = (sim_ref_events.col('ext_timestamp').astype(int) -
                          sim_events.col('ext_timestamp').astype(int))

                bins = arange(-2000, 2000.1, 30)
                # bins = linspace(-max_dt, max_dt, 150)
                # bins = linspace(-1.8 * std(dt), 1.8 * std(dt), 100)
                x = (bins[:-1] + bins[1:]) / 2

                sim_counts, bins = histogram(sim_dt, bins=bins, density=True)
                counts, bins = histogram(dt, bins=bins, density=True)

                #                 width = curve_fit(norm.pdf, x, counts, p0=(0., distances[-1]))[0][1]
                #                 widths.append(width)
                #                 sim_width = curve_fit(norm.pdf, x, sim_counts, p0=(0., distances[-1]))[0][1]
                #                 sim_widths.append(sim_width)
                window_width = distances[-1] * 3.5
                width = std(dt.compress(abs(dt) < window_width))
                widths.append(width)
                sim_width = std(sim_dt.compress(abs(sim_dt) < window_width))
                sim_widths.append(sim_width)

    widths = array(widths)
    sim_widths = array(sim_widths)

    popt, pcov = curve_fit(lin,
                           distances,
                           widths,
                           p0=(1.1, 1),
                           sigma=array(distances)**0.3)
    popt, pcov = curve_fit(lin_origin,
                           distances,
                           widths,
                           p0=(1.1),
                           sigma=array(distances)**0.3)
    print popt, pcov

    plot = MultiPlot(2, 1)
    splot = plot.get_subplot_at(0, 0)
    splot.scatter(distances, widths, markstyle='black')
    splot.scatter(distances, sim_widths, markstyle='black', mark='+')
    splot.plot([0, 600], [0, 600 / 0.3], mark=None, linestyle='gray')
    splot.plot(
        [0, 600],
        [lin_origin(0, *popt), lin_origin(600, *popt)], mark=None)
    splot.set_ylimits(min=0, max=700)
    splot.set_ylabel(r'$\sigma_{\Delta t}$ [\si{\ns}]')

    splot = plot.get_subplot_at(1, 0)
    splot.scatter(distances, widths - sim_widths, markstyle='mark size=1pt')
    splot.draw_horizontal_line(0, linestyle='gray')
    splot.set_axis_options(r'height=0.2\textwidth')
    splot.set_ylabel(
        r'$\sigma_{\mathrm{data}} - \sigma_{\mathrm{sim}}$ [\si{\ns}]')

    plot.show_xticklabels(1, 0)
    plot.show_yticklabels_for_all(None)
    plot.set_xlimits_for_all(None, min=0, max=600)
    plot.set_xlabel(r'Distance [\si{\meter}]')
    plot.save_as_pdf('plots/distance_v_width_sim')
Exemple #28
0
def plot_distance_width():

    distances = []
    widths = []
    sim_widths = []

    with tables.open_file(SIM_PATH, 'r') as sim_data:
        for ref_station, station in itertools.combinations(SPA_STAT, 2):
            if ref_station == 501 and station == 509:
                continue
            if ref_station == 501 and station == 510:
                continue
            if ref_station == 505 and station == 509:
                continue
            distances.append(
                CLUSTER.calc_rphiz_for_stations(SPA_STAT.index(ref_station),
                                                SPA_STAT.index(station))[0])
            with tables.open_file(
                    DATA_PATH + 'dt_ref%d_%d.h5' % (ref_station, station),
                    'r') as data:

                table = get_station_dt(data, station)
                ts1 = table[-1]['timestamp'] - WEEK
                ts0 = ts1 - HALFYEAR  # * max(1, (distance / 100))
                dt = table.read_where('(timestamp > ts0) & (timestamp < ts1)',
                                      field='delta')

                sim_ref_events = sim_data.get_node(
                    '/flat/cluster_simulations/station_%d' % ref_station,
                    'events')
                sim_events = sim_data.get_node(
                    '/flat/cluster_simulations/station_%d' % station, 'events')
                sim_dt = (sim_ref_events.col('ext_timestamp').astype(int) -
                          sim_events.col('ext_timestamp').astype(int))

                high = 94
                low = 6
                width = percentile(sorted(dt), high) - percentile(
                    sorted(dt), low)
                widths.append(width)
                sim_width = percentile(sim_dt, high) - percentile(sim_dt, low)
                sim_widths.append(sim_width)

    widths = array(widths)
    sim_widths = array(sim_widths)

    popt, pcov = curve_fit(lin,
                           distances,
                           widths,
                           p0=(1.1, 1),
                           sigma=array(distances)**0.3)
    print popt, pcov

    plot = MultiPlot(2, 1)
    splot = plot.get_subplot_at(0, 0)
    splot.scatter(distances, widths)
    splot.scatter(distances, sim_widths, markstyle='green')
    splot.plot([0, 600], [0, 600 / 0.3], mark=None, linestyle='gray')
    splot.plot([0, 600], [lin(0, *popt), lin(600, *popt)], mark=None)
    splot.set_ylimits(min=0, max=700 / 0.3)

    splot = plot.get_subplot_at(1, 0)
    splot.scatter(distances, widths - sim_widths, markstyle='mark size=1pt')
    splot.draw_horizontal_line(0, linestyle='gray')
    splot.set_axis_options(r'height=0.2\textwidth')

    plot.show_xticklabels(1, 0)
    plot.show_yticklabels_for_all(None)
    plot.set_xlimits_for_all(None, min=0, max=600)
    plot.set_xlabel(r'Distance [\si{\meter}]')
    plot.set_ylabel(r'Width of $\Delta t$ distribution [\si{\ns}]')
    plot.save_as_pdf('plots/distance_v_maxdt_sim')
Exemple #29
0
def plot_offset_distributions():
    with tables.open_file(SIM_PATH, 'r') as sim_data:
        for ref_station, station in itertools.combinations(SPA_STAT,
                                                           2):  # [(504, 509)]:
            if ref_station == 501 and station == 510:
                continue
            with tables.open_file(
                    DATA_PATH + 'dt_ref%d_%d.h5' % (ref_station, station),
                    'r') as data:

                distance = horizontal_distance_between_stations(
                    ref_station, station)
                max_dt = max(distance / .3, 100) * 1.5
                table = get_station_dt(data, station)
                ts1 = table[-1]['timestamp'] - WEEK
                ts0 = ts1 - YEAR  # * max(1, (distance / 100))
                dt = table.read_where('(timestamp > ts0) & (timestamp < ts1)',
                                      field='delta')

                sim_ref_events = sim_data.get_node(
                    '/flat/cluster_simulations/station_%d' % ref_station,
                    'events')
                sim_events = sim_data.get_node(
                    '/flat/cluster_simulations/station_%d' % station, 'events')
                sim_dt = (sim_ref_events.col('ext_timestamp').astype(int) -
                          sim_events.col('ext_timestamp').astype(int))

                bins = arange(-2000, 2000.1,
                              30)  # linspace(-max_dt, max_dt, 150)
                x = (bins[:-1] + bins[1:]) / 2

                sim_counts, bins = histogram(sim_dt, bins=bins, density=True)
                counts, bins = histogram(dt, bins=bins, density=True)

                sim_offset = curve_fit(norm.pdf, x, sim_counts,
                                       p0=(0., 30.))[0][0]
                offset = curve_fit(norm.pdf, x, counts, p0=(0., 30.))[0][0]

                sim_counts, bins = histogram(sim_dt - sim_offset,
                                             bins=bins,
                                             density=True)
                counts, bins = histogram(dt - offset, bins=bins, density=True)

                plot = MultiPlot(2, 1)
                splot = plot.get_subplot_at(0, 0)
                splot.histogram(counts, bins)
                splot.histogram(sim_counts, bins, linestyle='green')
                #                 plot_fits(splot, counts, bins)
                splot.draw_vertical_line(distance * 3.5, linestyle='dashed')
                splot.draw_vertical_line(-distance * 3.5, linestyle='dashed')
                splot.set_ylabel('Counts')
                splot.set_ylimits(min=0)

                splot = plot.get_subplot_at(1, 0)
                splot.scatter(x,
                              counts - sim_counts,
                              markstyle='mark size=1pt')
                splot.draw_horizontal_line(0, linestyle='gray')
                splot.set_axis_options(r'height=0.2\textwidth')

                plot.show_xticklabels(1, 0)
                plot.show_yticklabels_for_all(None)
                plot.set_xlabel(r'$\Delta t$ [\si{\ns}]')
                plot.set_xlimits_for_all(None, -2000, 2000)
                plot.save_as_pdf('plots/distribution/dt_ref%d_%d_dist_width' %
                                 (ref_station, station))
Exemple #30
0
def plot_distance_vs_delay(data):
    colors = {
        501: 'black',
        502: 'red!80!black',
        503: 'blue!80!black',
        504: 'green!80!black',
        505: 'orange!80!black',
        506: 'pink!80!black',
        508: 'blue!40!black',
        509: 'red!40!black',
        510: 'green!40!black',
        511: 'orange!40!black'
    }

    cq = CoincidenceQuery(data)
    cq.reconstructions = cq.data.get_node('/coincidences', 'recs_curved')
    cq.reconstructed = True

    cluster = data.root.coincidences._v_attrs['cluster']
    offsets = {
        s.number: [d.offset + s.gps_offset for d in s.detectors]
        for s in cluster.stations
    }

    front = CorsikaStationFront()
    front_r = np.arange(500)
    front_t = front.delay_at_r(front_r)

    for i, coincidence in enumerate(cq.coincidences.read_where('N > 6')):
        if i > 50:
            break
        coincidence_events = next(cq.all_events([coincidence]))
        reconstruction = cq._get_reconstruction(coincidence)

        core_x = coincidence['x']
        core_y = coincidence['y']

        plot = MultiPlot(2, 1)
        splot = plot.get_subplot_at(0, 0)
        rplot = plot.get_subplot_at(1, 0)

        splot.plot(front_r, front_t, mark=None)

        ref_extts = coincidence_events[0][1]['ext_timestamp']

        front_detect_r = []
        front_detect_t = []

        for station_number, event in coincidence_events:
            station = cluster.get_station(station_number)
            t = event_utils.relative_detector_arrival_times(
                event,
                ref_extts,
                offsets=offsets[station_number],
                detector_ids=DETECTOR_IDS)
            core_distances = []
            for i, d in enumerate(station.detectors):
                x, y, z = d.get_coordinates()
                core_distances.append(distance_between(core_x, core_y, x, y))
                t += d.get_coordinates()[-1] / c
            splot.scatter(core_distances,
                          t,
                          mark='o',
                          markstyle=colors[station_number])
            splot.scatter([np.mean(core_distances)], [np.nanmin(t)],
                          mark='*',
                          markstyle=colors[station_number])
            rplot.scatter(
                [np.mean(core_distances)],
                [np.nanmin(t) - front.delay_at_r(np.mean(core_distances))],
                mark='*',
                markstyle=colors[station_number])

        splot.set_ylabel('Relative arrival time [ns]')
        rplot.set_ylabel(r'Residuals')
        rplot.set_axis_options(r'height=0.25\textwidth')
        splot.set_ylimits(-10, 150)

        plot.set_xlimits_for_all(None, 0, 400)
        plot.set_xlabel('Distance from core [m]')
        plot.show_xticklabels(1, 0)
        plot.show_yticklabels_for_all()

        plot.save_as_pdf('front_shape/distance_v_time_%d_core' %
                         coincidence['id'])
from artist import MultiPlot

from sapphire import api

sns = api.Network(force_stale=True).station_numbers()
original_base = api.LOCAL_BASE

for i in range(8):
    plot = MultiPlot(16, 1, width=r'0.67\linewidth', height=r'0.05\linewidth')
    for splot, sn in zip(plot.subplots, sns[i * 16:(i + 1) * 16]):
        for path, color in [(original_base, 'black'), (original_base + '_old', 'red')]:
            api.LOCAL_BASE = path
            try:
                s = api.Station(sn, force_stale=True)
                if not len(s.detector_timing_offsets):
                    splot.set_empty()
                    continue
            except:
                splot.set_empty()
                continue
            splot.plot(s.detector_timing_offsets['timestamp'],
                       s.detector_timing_offsets['offset1'], mark=None,
                       linestyle='ultra thin, ' + color)
            splot.set_axis_options('line join=round')
            splot.set_ylabel(str(sn))
    plot.set_ylimits_for_all(None, -20, 20)
    plot.set_xlimits_for_all(None, 1224201600, 1465344000)
    plot.save_as_pdf('detector_offset_set_%d' % i)