def main():

    x = np.random.normal(0, 50, 50000)
    y = np.random.normal(0, 15, 50000)

    ranges = ([(-100, 0), (-50, 0)],
              [(0, 100), (-50, 0)],
              [(-100, 0), (0, 50)],
              [(0, 100), (0, 50)])
    types = ('reverse_bw', 'color', 'bw', 'area')
    bitmaps = (True, True, False, False)
    subplot_idxs = [(1, 0), (1, 1), (0, 0), (0, 1)]

    plot = Plot()
    mplot = MultiPlot(2, 2, width=r'.4\linewidth')

    for idx, r, t, b in zip(subplot_idxs, ranges, types, bitmaps):
        n, xbins, ybins = np.histogram2d(x, y, bins=15, range=r)
        plot.histogram2d(n, xbins, ybins, type=t, bitmap=b)
        p = mplot.get_subplot_at(*idx)
        p.histogram2d(n, xbins, ybins, type=t, bitmap=b)

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

    plot.save('histogram2d')
    mplot.save('multi_histogram2d')
Beispiel #2
0
    def plot_hisparc_kascade_detector(self, ni, k_ni):
        plot = MultiPlot(2,
                         2,
                         'loglog',
                         width=r'.3\linewidth',
                         height=r'.3\linewidth')
        for i in range(4):
            splot = plot.get_subplot_at(i / 2, i % 2)
            counts, xbins, ybins = histogram2d(ni[:, i],
                                               k_ni[:, i],
                                               bins=self.log_bins,
                                               normed=True)
            counts[counts == -inf] = 0
            splot.histogram2d(counts,
                              xbins,
                              ybins,
                              bitmap=True,
                              type='reverse_bw')
            self.plot_xy(splot)

        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'KASCADE predicted density [\si{\per\meter\squared}]')
        return plot
Beispiel #3
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')
Beispiel #4
0
 def plot_contribution_detector(self, ni, ref_ni):
     plot = MultiPlot(2,
                      2,
                      'semilogy',
                      width=r'.3\linewidth',
                      height=r'.3\linewidth')
     colors = [
         'red', 'blue', 'green', 'purple', 'gray', 'brown', 'cyan',
         'magenta', 'orange', 'teal'
     ]
     padding = 0.2
     bins = linspace(0, 20, 100)
     for i in range(4):
         splot = plot.get_subplot_at(i / 2, i % 2)
         splot.histogram(*histogram(ni[:, i], bins=bins))
         splot.draw_vertical_line(1)
         for j, density in enumerate(range(1, 8) + [15] + [20]):
             ni_slice = ni[:, i].compress(
                 abs(ref_ni[:, i] - density) < padding)
             counts, bins = histogram(ni_slice, bins=bins)
             splot.histogram(counts,
                             bins + (j / 100.),
                             linestyle=colors[j % len(colors)])
     plot.set_ylimits_for_all(min=0.9, max=1e5)
     plot.set_xlimits_for_all(min=bins[0], max=bins[-1])
     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'Counts')
     return plot
Beispiel #5
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')
Beispiel #6
0
def plot_spectrum_componenten():
    """Plot voor componenten pulshoogte spectrum"""

    multiplot = MultiPlot(3, 1, axis='semilogy', width=r'0.5\linewidth')

    pylab.clf()
    subplot0 = multiplot.get_subplot_at(0, 0)
    subplot1 = multiplot.get_subplot_at(1, 0)
    subplot2 = multiplot.get_subplot_at(2, 0)
    x = pylab.linspace(1e-10, 11, 200)
    th_signal = []
    signal = pylab.zeros(x.shape)
    for N in range(1, 15):
        scale = 100. / N ** 3
        pdf = 80 * scale * pylab.normpdf(x, N, pylab.sqrt(N) * 0.35)
        # pylab.plot(x, pdf)
        subplot1.plot(x, pdf, mark=None)
        # subplot1.add_pin('%d MIP' % N, 'above right', x=N, use_arrow=True,
        #                  style='lightgray')
        subplot2.plot(x, pdf, mark=None, linestyle='lightgray')
        signal += pdf
        th_signal.extend(int(100 * scale) * [N])

    gammas = 1e2 * x ** -3
    subplot1.plot(x, gammas, mark=None)
    subplot2.plot(x, gammas, mark=None, linestyle='lightgray')

    signal += gammas
    pylab.plot(x, signal)
    pylab.plot(x, gammas)
    subplot2.plot(x, signal, mark=None)
    pylab.yscale('log')
    pylab.ylim(ymin=1)

    n, bins = pylab.histogram(th_signal, bins=pylab.linspace(0, 11, 100))
    n = pylab.where(n == 0, 1e-10, n)
    subplot0.histogram(n, bins)

    multiplot.show_xticklabels_for_all([(0, 0), (2, 0)])
    multiplot.set_xticks_for_all([(0, 0), (2, 0)], range(20))
    # multiplot.show_yticklabels_for_all([(0, 0), (1, 0), (2, 0)])
    multiplot.set_xlabel('Aantal deeltjes')
    multiplot.set_ylabel('Aantal events')
    multiplot.set_ylimits_for_all(min=1, max=1e5)
    multiplot.set_xlimits_for_all(min=0, max=10.5)

    multiplot.save('spectrum_componenten')
Beispiel #7
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)
Beispiel #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)
Beispiel #9
0
def plot_afstelling_pmt():
    """Plot voor afstellen spanning"""

    multiplot = MultiPlot(1, 3, width=r'0.4\linewidth')

    x = pylab.linspace(1e-10, 11, 200)

    signal = pylab.zeros(x.shape)

    for N in range(1, 15):
        scale = 100. / N ** 3
        pdf = 80 * scale * pylab.normpdf(x, N, pylab.sqrt(N) * 0.35)
        signal += pdf

    gammas = 1e2 * x ** -3
    signal += gammas

    p = multiplot.get_subplot_at(0, 0)
    v = x * 35
    p.plot(v, pylab.where(v >= 30, signal, 1), mark=None)
    p.draw_vertical_line(200, linestyle='gray')
    p.set_label(r"$V_\mathrm{PMT}$ te laag")

    p = multiplot.get_subplot_at(0, 1)
    v = x * 200
    p.plot(v, pylab.where(v >= 30, signal, 1), mark=None)
    p.draw_vertical_line(200, linestyle='gray')
    p.set_label(r"$V_\mathrm{PMT}$ correct")

    p = multiplot.get_subplot_at(0, 2)
    v = x * 400
    p.plot(v, pylab.where(v >= 30, signal, 1), mark=None)
    p.draw_vertical_line(200, linestyle='gray')
    p.set_label(r"$V_\mathrm{PMT}$ te hoog")

    multiplot.set_xlabel(r"Pulseheight [\si{\milli\volt}]")
    multiplot.set_ylabel("Counts")
    multiplot.set_xlimits_for_all(min=0, max=1000)
    multiplot.set_ylimits_for_all(min=1)
    multiplot.show_xticklabels_for_all()
    multiplot.set_xticklabels_position(0, 1, 'top')
    multiplot.set_yticks_for_all(ticks=None)
    multiplot.save('afstelling_pmt')
Beispiel #10
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')
Beispiel #11
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)
Beispiel #12
0
 def plot_detector_average(self, n, ni):
     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)
         counts, xbins, ybins = histogram2d(ni[:, i], n, bins=self.log_bins)
         counts[counts == -inf] = 0
         splot.histogram2d(counts,
                           xbins,
                           ybins,
                           bitmap=True,
                           type='reverse_bw')
     plot.show_xticklabels_for_all([(1, 0), (0, 1)])
     plot.show_yticklabels_for_all([(1, 0), (0, 1)])
     return plot
Beispiel #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')
Beispiel #14
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')
Beispiel #15
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))
Beispiel #16
0
def multiplot():
    # data series
    x = [0, 40, 60, 69, 80, 90, 100]
    y = [0, 0, 0.5, 2.96, 2, 1, .5]

    multiplot = MultiPlot(1, 2)

    # make graph
    graph1 = multiplot.get_subplot_at(0, 0)
    graph2 = multiplot.get_subplot_at(0, 1)

    # make Plot
    graph1.plot(x, y, mark=None, linestyle='smooth,very thick')
    graph2.plot(x, y, mark=None, linestyle='smooth,very thick')

    multiplot.show_xticklabels_for_all()
    multiplot.show_yticklabels(0, 0)
    multiplot.set_xticklabels_position(0, 1, 'top')
    multiplot.set_yticks_for_all(ticks=range(6))

    graph1.set_xlimits(0, 100)
    graph2.set_xlimits(60, 80)
    multiplot.set_ylimits_for_all(min=0, max=5)

    # set scale: 1cm equals 10 or 5 units along the x-axis
    graph1.set_xscale(cm=10)
    graph2.set_xscale(cm=5)
    # set scale: 1cm equals 1 unit along the y-axis
    graph1.set_yscale(cm=1)
    graph2.set_yscale(cm=1)

    # set graph paper
    graph1.use_graph_paper()
    graph2.use_graph_paper()

    # set labels
    multiplot.set_xlabel(r"$f [\si{\mega\hertz}]$")
    multiplot.set_ylabel("signal strength")

    # save graph to file
    multiplot.save('mm_paper_multiplot')
Beispiel #17
0
from pylab import *
from artist import MultiPlot, Plot


multiplot = MultiPlot(3, 1, axis='semilogy', width=r'.5\linewidth')

clf()
subplot0 = multiplot.get_subplot_at(0, 0)
subplot1 = multiplot.get_subplot_at(1, 0)
subplot2 = multiplot.get_subplot_at(2, 0)
x = linspace(1e-10, 11, 200)
th_signal = []
signal = zeros(x.shape)
for N in range(1, 15):
    scale = 100. / N ** 3
    pdf = 80 * scale * normpdf(x, N, sqrt(N) * .35)
    #plot(x, pdf)
    subplot1.plot(x, pdf, mark=None)
    #subplot1.add_pin('%d MIP' % N, 'above right', x=N, use_arrow=True,
    #                style='lightgray')
    subplot2.plot(x, pdf, mark=None, linestyle='lightgray')
    signal += pdf
    th_signal.extend(int(100 * scale) * [N])

gammas = 1e2 * x ** -3
subplot1.plot(x, gammas, mark=None)
subplot2.plot(x, gammas, mark=None, linestyle='lightgray')

signal += gammas
plot(x, signal)
plot(x, gammas)
Beispiel #18
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')
Beispiel #19
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'])
Beispiel #20
0
def plot_arrival_time_distribution_v_distance(data, seeds):

    results = []
    cor_t = None

    for group in data.walk_groups('/'):
        if (seeds not in group._v_pathname or group._v_name != 'coincidences'):
            continue
        coincidences = group.coincidences
        events = data.get_node(group.s_index[0]).events

        r = next(
            int(y[1:]) for y in group._v_pathname.split('/')
            if y.startswith('r'))
        seeds = next(y[1:] for y in group._v_pathname.split('/')
                     if y.startswith('s'))

        if cor_t is None:
            with tables.open_file(CORSIKA_DATA % seeds) as data:
                gp = data.root.groundparticles
                query = '(x < 10) & (x > -10) & (r < 10)'
                cor_t = gp.read_where(query, field='t').min()


#         i = get_info(seeds)['first_interaction_altitude']
#         cor_t = i / 0.299792458

# Round ts to seconds because it is the ts for first event, not the shower
        t = [
            station_arrival_time(
                event,
                int(cets['ext_timestamp'] / int(1e9)) * int(1e9),
                detector_ids=[0, 1, 2, 3]) - cor_t for event, cets in zip(
                    events[:], coincidences.read_where('N == 1'))
        ]

        if not len(t) or len(t) < 10:
            continue

        quantiles = [25, 50, 75]
        qt = percentile(t, q=quantiles)

        results.append([r] + list(qt) +
                       [100 * events.nrows / float(coincidences.nrows)])

    if not len(results):
        return

    results = sorted(results)

    (core_distances, arrival_times_low, arrival_times, arrival_times_high,
     efficiency) = zip(*results)

    causal = causal_front(i, core_distances)

    plot = MultiPlot(2, 1)

    splot = plot.get_subplot_at(0, 0)
    plot_shower_profile(seeds, splot, core_distances, cor_t)
    splot.plot(core_distances, causal, mark=None, linestyle='purple, dashed')
    splot.plot(core_distances, arrival_times, mark='*')
    splot.shade_region(core_distances,
                       arrival_times_low,
                       arrival_times_high,
                       color='blue, semitransparent')
    splot.set_ylabel(r'Arrival time [\si{\ns}]')

    splot = plot.get_subplot_at(1, 0)
    splot.plot(core_distances, efficiency)
    splot.set_ylabel(r'Detection efficiency [\si{\percent}]')
    splot.set_axis_options(r'height=0.25\textwidth')

    plot.set_ylimits(0, 0, min=-10, max=210)
    plot.set_ylimits(1, 0, min=-5, max=105)
    plot.set_xlimits_for_all(None, 0, 550)
    plot.set_xlabel(r'Core distance [\si{\meter}]')
    plot.show_xticklabels(1, 0)
    plot.show_yticklabels_for_all()
    plot.save_as_document(
        '/data/hisparc/adelaat/corsika_accuracy/plots/%s.tex' %
        get_info_string(seeds))
Beispiel #21
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))
Beispiel #22
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')
Beispiel #23
0
def combine_delta_data():
    delta_data = genfromtxt('data/time_delta.tsv',
                            delimiter='\t',
                            dtype=None,
                            names=['ext_timestamp', 'time_delta'])
    delta_data = {ets: td for ets, td in delta_data}

    tm = []
    ts = []
    td = []
    te = []
    with tables.open_file('data/data.h5', 'r') as data:
        for row in data.root.s99.events:
            ets = row['ext_timestamp']
            try:
                dt = delta_data[ets]
            except KeyError:
                continue
            tm.append(row['t1'])
            ts.append(row['t3'])
            td.append(dt)
            te.append(ets)
    tm = array(tm)
    ts = array(ts)
    td = array(td)
    te = array(te)
    filter = (tm >= 0) & (ts >= 0)
    tm = tm.compress(filter)
    ts = ts.compress(filter)
    td = td.compress(filter)
    te = te.compress(filter)

    bins = arange(-10.25, 10.26, .5)
    mplot = MultiPlot(3, 2, width=r'.4\linewidth', height=r'.3\linewidth')
    mplot.show_xticklabels_for_all([(2, 0), (2, 1)])
    mplot.show_yticklabels_for_all([(0, 0), (1, 1), (2, 0)])
    mplot.set_xlimits_for_all(min=-11, max=11)
    mplot.set_ylimits_for_all(min=0, max=1500)
    mplot.set_ylabel('Counts')
    mplot.set_xlabel(r'Time difference [\si{\nano\second}]')

    plot = mplot.get_subplot_at(0, 0)
    counts, bins = histogram(tm - ts, bins=bins)
    popt = fit_timing_offset(counts / 3., bins)
    plot.set_label(r'$t_{M} - t_{S}$, $%.1f\pm%.1f$\si{\nano\second}, scaled' %
                   (popt[1], popt[2]))
    plot.histogram(counts / 3., bins)
    plot.plot(bins, gauss(bins, *popt), mark=None, linestyle='gray')

    plot = mplot.get_subplot_at(1, 0)
    plot.set_label(r'$t_{\delta}$')
    plot.histogram(*histogram(td, bins=bins))

    plot = mplot.get_subplot_at(2, 0)
    counts, bins = histogram(tm - (ts + td), bins=bins)
    popt = fit_timing_offset(counts, bins)
    plot.set_label(
        r'$t_{M} - (t_{S} + t_{\delta})$, $%.1f\pm%.1f$\si{\nano\second}' %
        (popt[1], popt[2]))
    plot.histogram(counts, bins)
    plot.plot(bins, gauss(bins, *popt), mark=None, linestyle='gray')

    plot = mplot.get_subplot_at(0, 1)
    plot.set_label(r'$t_{\delta}$ where $t_{M} - t_{S} == -5$')
    plot.draw_vertical_line(-5, linestyle='gray')
    plot.histogram(*histogram(td.compress(tm - ts == -5), bins=bins))
    plot = mplot.get_subplot_at(1, 1)
    plot.set_label(r'$t_{\delta}$ where $t_{M} - t_{S} == -2.5$')
    plot.draw_vertical_line(-2.5, linestyle='gray')
    plot.histogram(*histogram(td.compress(tm - ts == -2.5), bins=bins))
    plot = mplot.get_subplot_at(2, 1)
    plot.set_label(r'$t_{\delta}$ where $t_{M} - t_{S} == 0$')
    plot.draw_vertical_line(0, linestyle='gray')
    plot.histogram(*histogram(td.compress(tm - ts == 0), bins=bins))
    mplot.save_as_pdf('dt_time_delta')

    plot = Plot()

    counts, xbins, ybins = histogram2d(tm - ts, td, bins=bins)
    plot.histogram2d(counts, xbins, ybins, bitmap=True, type='reverse_bw')
    plot.set_xlabel(r'$t_{M} - t_{S}$ [\si{\nano\second}]')
    plot.set_ylabel(r'$t_{\delta}$ [\si{\nano\second}]')

    plot.save_as_pdf('dt_vs_time_delta')