Example #1
0
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')
Example #2
0
def plot_results(distances, energies, results):
    plot = Plot('loglog')
    plot.histogram2d(np.log10(results[:-1, :-1] + 10),
                     distances,
                     energies,
                     bitmap=True)
    plot.set_ylabel('Shower energy')
    plot.set_xlabel('Distance between stations')
    plot.save_as_pdf('distance_energy_v_area')
Example #3
0
def plot_filtered(filtered_trace):
    plot = Plot()

    time = arange(0, len(filtered_trace) * 2.5, 2.5)
    plot.plot(time, filtered_trace, mark=None, linestyle='const plot')

    plot.set_xlabel(r'Trace time [\si{\ns}]')
    plot.set_ylabel(r'Signal strength [ADC]')
    plot.save_as_pdf('mean_filter')
Example #4
0
def plot_zenith_core_distance_small_2d():
    with tables.open_file(RESULT_DATA_SMALL, 'r') as data:
        sim = data.root.coincidences.coincidences.read_where('N == 1')
        core_distance = sqrt(sim['x'] ** 2 + sim['y'] ** 2)
        zenith = data.root.cluster_simulations.station_501.reconstructions.col('zenith')
        plot = Plot('semilogx')
        core_distance = core_distance[~isnan(zenith)]
        zenith = zenith[~isnan(zenith)]
        counts, x, y = histogram2d(core_distance, degrees(zenith), bins=50)
        plot.histogram2d(counts, x, y, type='color', bitmap=True)
        plot.set_xlabel(r'Core distance [\si{\meter}]')
        plot.set_ylabel(r'Reconstructed zenith [\si{\degree}]')
        plot.save_as_pdf('zenith_distance_e14_5_z0_2d')
Example #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')
Example #6
0
def plot_input_detected_zenith_distribution():
    plot = Plot()
    z_bins = arange(-3.75, 63.76, 7.5)
    shades = ['black', 'black!75', 'black!50', 'black!25']
    for i, e in enumerate([16, 16.5, 17, 17.5]):
        c_init, b = histogram(zenith_init.compress(energy_init == e),
                              bins=z_bins)
        c_in, b = histogram(zenith_in.compress(energy_in == e), bins=z_bins)
        corrected_counts = where(isnan(c_in / c_init), 0,
                                 sin(radians(b[1:])) * c_in / c_init)
        plot.histogram(corrected_counts, b, linestyle=shades[i])

    # plot.set_title('Input and detected zeniths for shower energy: %.1f' % e)
    plot.set_xlimits(0, 65)
    plot.set_ylimits(0)
    plot.save_as_pdf('e%.1f.pdf' % e)
Example #7
0
def plot_interaction_altitude_size(cq):
    for p in ['proton', 'iron', 'gamma']:
        for z in cq.available_parameters('zenith', particle=p):
            sims = cq.simulations(zenith=z, particle=p)
            altitudes = sims['first_interaction_altitude'] / 1e3
            size = sims['n_electron'] + sims['n_muon']
            alt_size_hist = histogram2d(
                altitudes,
                size,
                bins=[linspace(0, 70, 100),
                      logspace(0, 9, 100)])
            plot = Plot('semilogy')
            plot.histogram2d(*alt_size_hist, bitmap=True, type='color')
            plot.set_xlabel(r'First interaction altitude [m]')
            plot.set_ylabel(r'Shower size')
            plot.save_as_pdf('plots/interaction_altitude_v_size_%s_%.1f.pdf' %
                             (p if p is not None else 'all', z))
Example #8
0
 def plot_hisparc_kascade_station(self, n, k_n):
     plot = Plot('loglog')
     counts, xbins, ybins = histogram2d(n,
                                        k_n,
                                        bins=self.log_bins,
                                        normed=True)
     counts[counts == -inf] = 0
     plot.histogram2d(counts, xbins, ybins, bitmap=True, type='reverse_bw')
     self.plot_xy(plot)
     plot.set_xlabel(r'HiSPARC detected density [\si{\per\meter\squared}]')
     plot.set_ylabel(r'KASCADE predicted density [\si{\per\meter\squared}]')
     return plot
Example #9
0
def reconstruct_simulations(data):

    # Station 510
    station = cluster.get_station(STATIONS[1])
    station_group = '/hisparc/cluster_amsterdam/station_%d' % station.number
    rec_510 = ReconstructESDEvents(data,
                                   station_group,
                                   station,
                                   overwrite=True,
                                   progress=True)
    rec_510.offsets = offset(station.number)
    rec_510.reconstruct_directions()

    rec_510.theta = array(rec_510.theta)
    rec_510.phi = array(rec_510.phi)

    # Station 501
    for order in itertools.permutations(range(4), 4):
        cluster = get_cluster()
        station = cluster.get_station(STATIONS[0])
        station_group = '/hisparc/cluster_amsterdam/station_%d' % station.number
        station._detectors = [station.detectors[id] for id in order]

        rec_501 = ReconstructESDEvents(data,
                                       station_group,
                                       station,
                                       overwrite=True,
                                       progress=True)
        rec_501.offsets = offset(station.number)
        rec_501.reconstruct_directions()

        rec_501.theta = array(rec_501.theta)
        rec_501.phi = array(rec_501.phi)

        high_zenith = (rec_501.theta > .2) & (rec_510.theta > .2)

        plot = Plot()
        plot.histogram2d(*histogram2d(rec_501.phi.compress(high_zenith),
                                      rec_510.phi.compress(high_zenith),
                                      bins=linspace(-pi, pi, 100)))
        plot.save_as_pdf('order_%d%d%d%d' % order)
Example #10
0
def make_logo():
    size = '.02\linewidth'
    x = arange(0, 2*pi, .01)
    y = sin(x)
    plot = Plot(width=size, height=size)
    plot.set_ylimits(-1.3, 1.3)
    plot.set_yticks([-1, 0, 1])
    plot.set_ytick_labels(['', '', ''])
    plot.set_xticks([0, pi, 2*pi])
    plot.set_xtick_labels(['', '', ''])
    plot.plot(x, y, mark=None, linestyle='thick')
    plot.set_axis_options("axis line style=thick, major tick length=.04cm")
    plot.save_as_pdf('logo')
def analyse():
    """Plot results from reconstructions compared to the simulated input"""

    with tables.open_file(DATAPATH, 'r') as data:
        coincidences = data.get_node('/coincidences/coincidences')
        reconstructions = data.get_node(STATION_PATH)
        assert coincidences.nrows == reconstructions.nrows
        zenith_in = coincidences.col('zenith')
        azimuth_in = coincidences.col('azimuth')
        zenith_re = reconstructions.col('zenith')
        azimuth_re = reconstructions.col('azimuth')

    d_angle = angle_between(zenith_in, azimuth_in, zenith_re, azimuth_re)
    print sum(isnan(d_angle))

    plot = Plot()
    counts, bins = histogram(d_angle[invert(isnan(d_angle))], bins=50)
    plot.histogram(counts, bins)
    plot.set_ylimits(min=0)
    plot.set_xlabel(r'Angle between \si{\radian}')
    plot.set_ylabel('Counts')
    plot.save_as_pdf('angle_between')

    plot = Plot()
    counts, bins = histogram(zenith_in, bins=50)
    plot.histogram(counts, bins, linestyle='red')
    counts, bins = histogram(zenith_re, bins=bins)
    plot.histogram(counts, bins)
    plot.set_ylimits(min=0)
    plot.set_xlimits(min=0)
    plot.set_xlabel(r'Zenith \si{\radian}')
    plot.set_ylabel('Counts')
    plot.save_as_pdf('zenith')

    plot = Plot()
    counts, bins = histogram(azimuth_in, bins=50)
    plot.histogram(counts, bins, linestyle='red')
    counts, bins = histogram(azimuth_re, bins=bins)
    plot.histogram(counts, bins)
    plot.set_ylimits(min=0)
    plot.set_xlabel(r'Azimuth \si{\radian}')
    plot.set_ylabel('Counts')
    plot.save_as_pdf('azimuth')

    unique_coordinates = list({(z, a) for z, a in zip(zenith_re, azimuth_re)})
    zenith_uni, azimuth_uni = zip(*unique_coordinates)
    plot = PolarPlot(use_radians=True)
    plot.scatter(array(azimuth_uni),
                 array(zenith_uni),
                 markstyle='mark size=.75pt')
    plot.set_xlabel(r'Azimuth \si{\radian}')
    plot.set_ylabel(r'Zenith \si{\radian}')
    plot.save_as_pdf('polar')
Example #12
0
def main():
    x, t25, t50, t75 = np.loadtxt('data/DIR-boxplot_arrival_times-1.txt')

    graph = Plot()
    graph.plot(x, t50, mark='*')
    graph.shade_region(x, t25, t75)
    graph.set_xlabel(r"Core distance [\si{\meter}]")
    graph.set_ylabel(r"Arrival time delay [\si{\nano\second}]")
    graph.set_ylimits(min=0)
    graph.save('shower-front')
Example #13
0
def determine_detector_timing_offsets(s, events):
    """Determine the offsets between the station detectors.

    ADL: Currently assumes detector 1 is a good reference.
    But this is not always the best choice. Perhaps it should be
    determined using more data (more than one day) to be more
    accurate.

    """
    bins = arange(-100 + 1.25, 100, 2.5)
    col = (cl for cl in COLORS)
    graph = Plot()
    ids = range(1, 5)
    reference = 2
    for j in [1, 3, 4]:
        if j == reference:
            continue
        tref = events.col('t%d' % reference)
        tj = events.col('t%d' % j)
        dt = (tj - tref).compress((tref >= 0) & (tj >= 0))
        y, bins = histogram(dt, bins=bins)
        c = col.next()
        graph.histogram(y, bins, linestyle='%s' % c)
        x = (bins[:-1] + bins[1:]) / 2
        try:
            popt, pcov = curve_fit(gauss, x, y, p0=(len(dt), 0., 10.))
            graph.draw_vertical_line(popt[1], linestyle='%s' % c)
            print '%d-%d: %f (%f)' % (j, reference, popt[1], popt[2])
        except (IndexError, RuntimeError):
            print '%d-%d: failed' % (j, reference)
    graph.set_title('Time difference, station %d' % (s))
    graph.set_xlimits(-100, 100)
    graph.set_ylimits(min=0)
    graph.set_xlabel('$\Delta t$')
    graph.set_ylabel('Counts')
    graph.save_as_pdf('detector_offsets_%s' % s)
Example #14
0
def plot_results(data):
    rec_paths = ['recs_flat', 'recs_curved', 'recs_xy']
    linestyles = ['solid', 'dotted', 'dashed']
    plot = Plot()
    for i, rec_path in enumerate(rec_paths):
        recs = data.get_node('/coincidences/%s' % rec_path)
        angles = angle_between(recs.col('zenith'), recs.col('azimuth'),
                               recs.col('reference_zenith'),
                               recs.col('reference_azimuth'))
        dangles = np.degrees(angles)
        counts, bins = np.histogram(dangles, bins=np.arange(0, 25, .5))
        plot.histogram(counts, bins + (i / 10.), linestyle=linestyles[i])
    plot.set_xlimits(0, 25)
    plot.set_ylimits(0)
    plot.set_xlabel(r'Angle between [\si{\degree}]')
    plot.save_as_pdf('angle_between')
Example #15
0
 def plot_slice(self, n):
     densities = [1, 3, 8, 15, 30]
     bins = linspace(0, 15, 150)
     plot = Plot()
     for density in densities:
         padding = round(sqrt(density) / 2.)
         counts, bins = histogram(
             n.compress(abs(self.src_k - density) < padding),
             bins=bins,
             density=True)
         plot.histogram(counts, bins)
         plot.add_pin(
             r'\SI[multi-part-units=single, separate-uncertainty]{%d\pm%d}{\per\meter\squared}'
             % (density, padding), 'above', bins[counts.argmax()])
     plot.set_ylimits(min=0)
     plot.set_xlimits(min=bins[0], max=bins[-1])
     plot.set_xlabel(r'HiSPARC detected density [\si{\per\meter\squared}]')
     plot.set_ylabel(r'Counts')
     return plot
Example #16
0
    def plot_n_histogram(self, n, ni, bins):
        """Plot histogram of detected signals"""

        plot = Plot('semilogy')
        plot.histogram(*histogram(n, bins=bins), linestyle='dotted')
        for i in range(4):
            plot.histogram(*histogram(ni[:, i], bins=bins),
                           linestyle=COLORS[i])
        plot.set_ylimits(min=.99, max=1e4)
        plot.set_xlimits(min=bins[0], max=bins[-1])
        plot.set_ylabel(r'Counts')
        return plot
Example #17
0
def main():
    """Event display for an event of station 503

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

    Number of MIPs
    35.0  51.9  35.8  78.9

    Arrival time
    15.0  17.5  20.0  27.5

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

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

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

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

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

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

    plot.save('event_display')


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

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

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

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

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

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

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

    plot.save('multi_event_display')
Example #18
0
def main():
    # Draw random numbers from the normal distribution
    np.random.seed(1)
    N = np.random.normal(size=2000)

    # define bin edges
    edge = 5
    bin_width = .1
    bins = np.arange(-edge, edge + .5 * bin_width, bin_width)

    # build histogram and x, y values at the center of the bins
    n, bins = np.histogram(N, bins=bins)
    x = (bins[:-1] + bins[1:]) / 2
    y = n

    # fit normal distribution pdf to data
    f = lambda x, N, mu, sigma: N * scipy.stats.norm.pdf(x, mu, sigma)
    popt, pcov = scipy.optimize.curve_fit(f, x, y)
    print("Parameters from fit (N, mu, sigma):", popt)

    # make graph
    graph = Plot()

    # graph histogram
    graph.histogram(n, bins)

    # graph model with fit parameters
    x = np.linspace(-edge, edge, 100)
    graph.plot(x, f(x, *popt), mark=None)

    # set labels and limits
    graph.set_xlabel("value")
    graph.set_ylabel("count")
    graph.set_label("Fit to data")
    graph.set_xlimits(-6, 6)

    # save graph to file
    graph.save('histogram-fit')
Example #19
0
def main():
    x = np.arange(10)
    y = (x / 2.0) - 3.0
    colors = ["black", "red", "blue", "yellow", "purple"]
    plot = Plot()

    for i in range(5):
        plot.plot(x, y - i, mark="", linestyle=colors[i])

    plot.set_axis_options(
        "yticklabel pos=right,\n"
        "grid=major,\n"
        "legend entries={$a$,[red]$b$,[green]$c$,$d$,$a^2$},\n"
        "legend pos=north west"
    )

    plot.set_xlabel("Something important")
    plot.set_ylabel("A related thing")
    plot.save("any_option")

    x = np.linspace(0.6 * np.pi, 10 * np.pi, 150)
    y = np.sin(x) / x
    plot = MultiPlot(1, 2, width=r".4\linewidth", height=r".25\linewidth")

    subplot = plot.get_subplot_at(0, 0)
    subplot.plot(x, y, mark=None)

    subplot = plot.get_subplot_at(0, 1)
    subplot.plot(x, y, mark=None)

    plot.show_xticklabels_for_all([(0, 0), (0, 1)])
    plot.show_yticklabels(0, 1)
    plot.set_axis_options(0, 1, "yticklabel pos=right, grid=major")

    plot.set_axis_options_for_all(None, r"enlargelimits=false")

    plot.set_xlabel("Something important")
    plot.set_ylabel("A related thing")
    plot.save("multi_any_option")
Example #20
0
def main():
    stations = np.genfromtxt("data/cluster-utrecht-stations.txt", names=["x", "y"])
    image = Image.open("data/cluster-utrecht-background.png")

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

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

    graph.set_axis_equal()

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

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

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

    graph.save("utrecht")
Example #21
0
def main():
    gamma = np.genfromtxt('data/showere15-proton.t2001', usecols=(1, 2))
    e = np.genfromtxt('data/showere15-proton.t2205', usecols=(1, 2))
    mu = np.genfromtxt('data/showere15-proton.t2207', usecols=(1, 2))

    graph = Plot(axis='loglog')

    graph.plot(gamma[:, 0], gamma[:, 1], mark=None)
    graph.add_pin(r'$\gamma$')

    graph.plot(e[:, 0], e[:, 1], mark=None)
    graph.add_pin('e')

    graph.plot(mu[:, 0], mu[:, 1], mark=None)
    graph.add_pin(r'$\mu$')

    graph.set_xlabel(r"Core distance [\si{\meter}]")
    graph.set_ylabel(r"Particle density [\si{\per\square\meter}]")
    graph.set_logyticks(range(-6, 3, 2))
    graph.save('eas-lateral')
    """Add a pin at the maximum value of a data series (sort of)"""

    # only use the second quarter, for cosmetic reasons
    q = int(0.25 * len(y))
    y = y[q:2*q]
    max_index = q + np.argmax(y)
    max_x = x[max_index]
    plot.add_pin(label, x=max_x, location='above', use_arrow=True,
                 style='pin distance=%s' % distance)


X = np.linspace(0., 2 * L, num=1000)
Y_sqr = [square(x) for x in X]
Y = lambda n: [fourier(x, n) for x in X]

graph = Plot()
graph.set_title("Fourier approximation")

graph.plot(x=X, y=Y(3), linestyle='red', mark=None, legend='n=3')
graph.plot(x=X, y=Y(5), linestyle='yellow', mark=None, legend='n=5')
graph.plot(x=X, y=Y(8), linestyle='green', mark=None, legend='n=8')
graph.plot(x=X, y=Y(13), linestyle='blue', mark=None, legend='n=13')
graph.plot(x=X, y=Y(55), linestyle='cyan', mark=None, legend='n=55')
graph.plot(x=X, y=Y_sqr, linestyle='black', mark=None, legend='square')

graph.save('fourier_with_legend')

graph = Plot()
graph.set_title("Fourier approximation")

graph.plot(x=X, y=Y(3), mark=None, linestyle='black!20')
Example #23
0
def main():
    leap = np.genfromtxt('data/leap-prot.dat', delimiter=',',
                         usecols=(0, 1), names=['E', 'F'])
    leap['E'] *= 1e6
    leap['F'] *= 1e3 * 2

    proton = read_data('data/proton', 1, 0)
    akeno_new_lo = read_data('data/akeno-new-lo', 0, 1)
    flys_eye = read_data('data/fe-new', 0, 1)
    yakutsk = read_data('data/yakustk', 1, 0)
    haverah = read_data('data/haverah', 1, 0)

    graph = Plot(axis='loglog', width=r'.5\linewidth', height=r'.65\linewidth')

    graph.plot(leap['E'], leap['F'], mark=None)
    graph.add_pin('LEAP', 'above right', use_arrow=True,
                  relative_position=.5)
    graph.plot(proton['E'], proton['F'], mark=None)
    graph.add_pin('PROTON', 'above right', use_arrow=True,
                  relative_position=.5)
    graph.plot(akeno_new_lo['E'], akeno_new_lo['F'], mark=None)
    graph.add_pin('AGASA', 'above right', use_arrow=True,
                  relative_position=.5)

    graph.plot(yakutsk['E'], yakutsk['F'], mark=None)
    graph.add_pin('Yakutsk', 'below left', use_arrow=True,
                  relative_position=.55)
    graph.plot(haverah['E'], haverah['F'], mark=None)
    graph.add_pin('Haverah Park', 'below left', use_arrow=True,
                  relative_position=.85)
    graph.plot(flys_eye['E'], flys_eye['F'], mark=None)
    graph.add_pin("Fly's Eye", 'below left', use_arrow=True,
                  relative_position=1.0)

    graph.set_xlabel(r"Energy [\si{\electronvolt}]")
    graph.set_ylabel(r"Flux [\si{\per\square\meter\per\steradian"
                     "\per\second\per\giga\electronvolt}]")

    x = np.logspace(11, 17)
    graph.plot(x, 1.5e29 * x ** -2.75, mark=None, linestyle='dashed')

    graph.set_logxticks(range(6, 22, 3))
    graph.save('spectrum')
Example #24
0
    def plot_pmt_curves(self):
        plot = Plot('loglog')
        filter = self.ref_out < 50

        for i in range(4):
            filter2 = self.ref_in_i[:, i] < 500
            pin = self.ref_in_i[:, i].compress(filter & filter2)
            pout = self.ref_out.compress(filter & filter2)
            plot.plot(pout, pin, linestyle=COLORS[i], mark=None)

        filter2 = self.ref_in < 500
        pin = self.ref_in.compress(filter & filter2)
        pout = self.ref_out.compress(filter & filter2)
        plot.plot(pout, pin, linestyle='pink', mark=None)

        plot.set_ylimits(min=min(self.lin_bins), max=max(self.lin_bins))
        plot.set_xlimits(min=min(self.lin_bins), max=max(self.lin_bins))
        plot.set_ylabel(r'Input signal')
        plot.set_xlabel(r'Output signal')
        plot.save_as_pdf('plots/pmt_curves')
Example #25
0
def scatter_n():
    with tables.open_file(RESULT_PATH, 'r') as data:
        cluster = data.root.coincidences._v_attrs.cluster
        coincidences = data.root.coincidences.coincidences
        for n in range(0, len(cluster.stations) + 1):
            graph = Plot()
            c = coincidences.read_where('N == n')
            print 'N = %d: %d' % (n, len(c))
            graph.plot(c['x'],
                       c['y'],
                       mark='*',
                       linestyle=None,
                       markstyle='mark size=.3pt')
            plot_cluster(graph, cluster)
            r = 520
            graph.set_ylimits(-r, r)
            graph.set_xlimits(-r, r)
            graph.set_ylabel('y (m)')
            graph.set_xlabel('x (m)')
            graph.save_as_pdf('N_%d' % n)
Example #26
0
    def plot_fit_residuals_station(self):
        plot = Plot()
        res = fit_function(self.slice_bins_c, *self.fit) - self.med_k
        plot.scatter(self.slice_bins_c,
                     res,
                     xerr=(self.slice_bins[1:] - self.slice_bins[:-1]) / 2.,
                     yerr=self.std_k,
                     markstyle='red, mark size=1pt')
        plot.draw_horizontal_line(0, linestyle='gray')

        plot.set_ylimits(min=-30, max=30)
        plot.set_xlimits(min=0, max=max(self.slice_bins))
        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_station')
Example #27
0
def plot_station_distances(distances, name=''):
    plot = Plot('semilogx')
    bins = numpy.logspace(0, 7, 41)
    counts, bins = numpy.histogram(distances, bins=bins)
    plot.histogram(counts, bins / 1e3)
    plot.set_xlabel(r'Distance [\si{\kilo\meter}]')
    plot.set_ylabel('Occurance')
    plot.set_ylimits(min=0)
    plot.set_xlimits(min=1e-3, max=2e3)
    plot.save_as_pdf('station_distances' + name)
Example #28
0
 def plot_contribution_station(self, n, ref_n):
     plot = Plot('semilogy')
     colors = [
         'red', 'blue', 'green', 'purple', 'gray', 'brown', 'cyan',
         'magenta', 'orange', 'teal'
     ]
     padding = 0.25
     bins = linspace(0, 20, 150)
     plot.histogram(*histogram(n, bins=bins))
     plot.draw_vertical_line(1)
     for j, density in enumerate(range(1, 8) + [15] + [20]):
         n_slice = n.compress(abs(ref_n - density) < padding)
         counts, bins = histogram(n_slice, bins=bins)
         plot.histogram(counts,
                        bins + (j / 100.),
                        linestyle=colors[j % len(colors)])
     plot.set_ylimits(min=0.9, max=1e5)
     plot.set_xlimits(min=bins[0], max=bins[-1])
     plot.set_xlabel(r'HiSPARC detected density [\si{\per\meter\squared}]')
     plot.set_ylabel(r'Counts')
     return plot
Example #29
0
def plot_comparison_501_510(stats, field_name):
    plot = Plot()
    bins = arange(0, 1, .02)

    ref_stat = stats[501][field_name][0]
    stat = stats[510][field_name][0]

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

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

    if field_name in ['event_rate', 'mpv']:
        plot.save_as_pdf('plots_501_510/compare_%s' % field_name)
    else:
        plot.save_as_pdf('plots_501_510/compare_bad_fraction_%s' % field_name)
Example #30
0
 def plot_derrivative_pmt(self):
     plot = Plot()
     plot.plot(self.lin_bins, self.dvindvout, mark=None)
     plot.set_xlimits(min=self.lin_bins[0], max=self.lin_bins[-1])
     plot.set_xlabel(r'Particle density [\si{\per\meter\squared}]')
     plot.set_ylabel(
         r'$\sigma V_{\mathrm{in}}\frac{\mathrm{d}V_{\mathrm{out}}}'
         r'{\mathrm{d}V_{\mathrm{in}}}$')
     plot.save_as_pdf('plots/derrivative_pmt_saturation')
Example #31
0
def analyse(name):
    data = genfromtxt('data/%s.tsv' % name, delimiter='\t', dtype=None,
                      names=['ext_timestamp', 'time_delta'])
    time_delta = data['time_delta']

    # Plot distribution
    counts, bins = histogram(time_delta, bins=arange(-10.5, 11.5, 1))
    plot = Plot()
    plot.histogram(counts, bins)
    x = (bins[1:] + bins[:-1]) / 2.
    popt, pcov = curve_fit(gauss, x, counts, p0=(sum(counts), 0., 2.5))
    plot.plot(x, gauss(x, *popt), mark=None)
    print popt
    plot.set_ylimits(min=0)
    plot.set_ylabel('Counts')
    plot.set_xlabel(r'Time delta [\si{\nano\second}]')
    plot.save_as_pdf(name)

    # Plot moving average
    n = 5000
    skip = 100
    moving_average = convolve(time_delta, ones((n,)) / n, mode='valid')
    plot = Plot()
    timestamps = (data['ext_timestamp'][:-n + 1:skip] -
                  data['ext_timestamp'][0]) / 1e9 / 3600.
    plot.plot(timestamps, moving_average[::skip], mark=None)
    plot.set_xlimits(min=0)
    plot.set_ylabel(r'time delta [\si{\nano\second}]')
    plot.set_xlabel('timestamp [\si{\hour}]')
    plot.save_as_pdf('moving_average_%s' % name)
Example #32
0
def make_map(country=None,
             cluster=None,
             subcluster=None,
             station=None,
             stations=None,
             label='map',
             detectors=False,
             weather=False,
             knmi=False):

    get_locations = (get_detector_locations
                     if detectors else get_station_locations)

    if (country is None and cluster is None and subcluster is None
            and station is None and stations is None):
        latitudes, longitudes = ([], [])
    else:
        latitudes, longitudes = get_locations(country, cluster, subcluster,
                                              station, stations)

    if weather:
        weather_latitudes, weather_longitudes = get_weather_locations()
    else:
        weather_latitudes, weather_longitudes = ([], [])

    if knmi:
        knmi_latitudes, knmi_longitudes = get_knmi_locations()
    else:
        knmi_latitudes, knmi_longitudes = ([], [])

    bounds = (min(latitudes + weather_latitudes + knmi_latitudes),
              min(longitudes + weather_longitudes + knmi_longitudes),
              max(latitudes + weather_latitudes + knmi_latitudes),
              max(longitudes + weather_longitudes + knmi_longitudes))

    map = Map(bounds, margin=.1)
    #     map.save_png('map-tiles-background.png')
    image = map.to_pil()

    map_w, map_h = image.size

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

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

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

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

    if knmi:
        x, y = map.to_pixels(array(knmi_latitudes), array(knmi_longitudes))
        plot.scatter(
            x,
            map_h - y,
            mark='square',
            markstyle="mark size=0.5pt, black!50!blue, thick, opacity=0.6")

    x, y = map.to_pixels(array(latitudes), array(longitudes))
    if detectors:
        mark_size = 1.5
    else:
        mark_size = 3
    plot.scatter(x,
                 map_h - y,
                 markstyle="mark size=%fpt, black!50!green, "
                 "thick, opacity=0.9" % mark_size)

    if weather:
        x, y = map.to_pixels(array(weather_latitudes),
                             array(weather_longitudes))
        plot.scatter(
            x,
            map_h - y,
            markstyle="mark size=1.5pt, black!30!red, thick, opacity=0.9")

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

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

    # save plot to file
    plot.save_as_pdf(label.replace(' ', '-'))
Example #33
0
def main():
    # data series
    x = [0, 40, 60, 69, 80, 90, 100]
    y = [0, 0, 0.5, 2.96, 2, 1, .5]

    # make graph
    graph = Plot()

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

    # set labels and limits
    graph.set_xlabel(r"$f [\si{\mega\hertz}]$")
    graph.set_ylabel("signal strength")
    graph.set_xlimits(0, 100)
    graph.set_ylimits(0, 5)

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

    # set ticks at every unit along the y axis
    graph.set_yticks(range(6))

    # set graph paper
    graph.use_graph_paper()

    # save graph to file
    graph.save('mm_paper')
Example #34
0
def display_coincidences(cluster, coincidence_events, coincidence,
                         reconstruction, map):
    offsets = {
        s.number: [d.offset + s.gps_offset for d in s.detectors]
        for s in cluster.stations
    }
    ts0 = coincidence_events[0][1]['ext_timestamp']

    latitudes = []
    longitudes = []
    t = []
    p = []

    for station_number, event in coincidence_events:
        station = cluster.get_station(station_number)
        for detector in station.detectors:
            latitude, longitude, _ = detector.get_lla_coordinates()
            latitudes.append(latitude)
            longitudes.append(longitude)
        t.extend(
            event_utils.relative_detector_arrival_times(
                event, ts0, DETECTOR_IDS, offsets=offsets[station_number]))
        p.extend(event_utils.detector_densities(event, DETECTOR_IDS))

    image = map.to_pil()

    map_w, map_h = image.size
    aspect = float(map_w) / float(map_h)
    width = 0.67
    height = width / aspect
    plot = Plot(width=r'%.2f\linewidth' % width,
                height=r'%.2f\linewidth' % height)

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

    x, y = map.to_pixels(np.array(latitudes), np.array(longitudes))
    mint = np.nanmin(t)

    xx = []
    yy = []
    tt = []
    pp = []

    for xv, yv, tv, pv in zip(x, y, t, p):
        if np.isnan(tv) or np.isnan(pv):
            plot.scatter([xv], [map_h - yv], mark='diamond')
        else:
            xx.append(xv)
            yy.append(map_h - yv)
            tt.append(tv - mint)
            pp.append(pv)

    plot.scatter_table(xx, yy, tt, pp)

    transform = geographic.FromWGS84ToENUTransformation(cluster.lla)

    # Plot reconstructed core
    dx = np.cos(reconstruction['azimuth'])
    dy = np.sin(reconstruction['azimuth'])
    direction_length = reconstruction['zenith'] * 300
    core_x = reconstruction['x']
    core_y = reconstruction['y']

    core_lat, core_lon, _ = transform.enu_to_lla((core_x, core_y, 0))
    core_x, core_y = map.to_pixels(core_lat, core_lon)
    plot.scatter([core_x], [image.size[1] - core_y],
                 mark='10-pointed star',
                 markstyle='red')
    plot.plot([core_x, core_x + direction_length * dx], [
        image.size[1] - core_y, image.size[1] -
        (core_y - direction_length * dy)
    ],
              mark=None)

    # Plot simulated core
    dx = np.cos(reconstruction['reference_azimuth'])
    dy = np.sin(reconstruction['reference_azimuth'])
    direction_length = reconstruction['reference_zenith'] * 300
    core_x = reconstruction['reference_x']
    core_y = reconstruction['reference_y']

    core_lat, core_lon, _ = transform.enu_to_lla((core_x, core_y, 0))
    core_x, core_y = map.to_pixels(core_lat, core_lon)
    plot.scatter([core_x], [image.size[1] - core_y],
                 mark='asterisk',
                 markstyle='orange')
    plot.plot([core_x, core_x + direction_length * dx], [
        image.size[1] - core_y, image.size[1] -
        (core_y - direction_length * dy)
    ],
              mark=None)

    plot.set_scalebar(location="lower left")
    plot.set_slimits(min=1, max=30)
    plot.set_colorbar('$\Delta$t [\si{n\second}]')
    plot.set_axis_equal()
    plot.set_colormap('viridis')

    nw = num2deg(map.xmin, map.ymin, map.z)
    se = num2deg(map.xmin + map_w / TILE_SIZE, map.ymin + map_h / TILE_SIZE,
                 map.z)

    x0, y0, _ = transform.lla_to_enu((nw[0], nw[1], 0))
    x1, y1, _ = transform.lla_to_enu((se[0], se[1], 0))

    plot.set_xlabel('x [\si{\meter}]')
    plot.set_xticks([0, map_w])
    plot.set_xtick_labels([int(x0), int(x1)])

    plot.set_ylabel('y [\si{\meter}]')
    plot.set_yticks([0, map_h])
    plot.set_ytick_labels([int(y1), int(y0)])

    plot.save_as_pdf('map/event_display_%d' % coincidence['id'])
Example #35
0
def analyse_reconstructions(data):
    cq = CoincidenceQuery(data)
    c_ids = data.root.coincidences.coincidences.read_where('s501', field='id')
    c_recs = cq.reconstructions.read_coordinates(c_ids)

    s_recs = data.root.hisparc.cluster_amsterdam.station_501.reconstructions

    zenc = c_recs['zenith']
    azic = c_recs['azimuth']

    zens = s_recs.col('zenith')
    azis = s_recs.col('azimuth')

    high_zenith = (zenc > .2) & (zens > .2)

    for minn in [1, 2, 4, 8, 16]:
        filter = (s_recs.col('min_n') > minn)

        length = len(azis.compress(high_zenith & filter))
        shifts501 = np.random.normal(0, .06, length)
        azicounts, x, y = np.histogram2d(azis.compress(high_zenith & filter) +
                                         shifts501,
                                         azic.compress(high_zenith & filter),
                                         bins=np.linspace(-np.pi, np.pi, 73))
        plota = Plot()
        plota.histogram2d(azicounts,
                          np.degrees(x),
                          np.degrees(y),
                          type='reverse_bw',
                          bitmap=True)
        # plota.set_title('Reconstructed azimuths for events in coincidence (zenith gt .2 rad)')
        plota.set_xlabel(r'$\phi_{501}$ [\si{\degree}]')
        plota.set_ylabel(r'$\phi_{Science Park}$ [\si{\degree}]')
        plota.set_xticks([-180, -90, 0, 90, 180])
        plota.set_yticks([-180, -90, 0, 90, 180])
        plota.save_as_pdf('azimuth_501_spa_minn%d' % minn)

        length = sum(filter)
        shifts501 = np.random.normal(0, .04, length)

        zencounts, x, y = np.histogram2d(zens.compress(filter) + shifts501,
                                         zenc.compress(filter),
                                         bins=np.linspace(0, np.pi / 3., 41))
        plotz = Plot()
        plotz.histogram2d(zencounts,
                          np.degrees(x),
                          np.degrees(y),
                          type='reverse_bw',
                          bitmap=True)
        # plotz.set_title('Reconstructed zeniths for station events in coincidence')
        plotz.set_xlabel(r'$\theta_{501}$ [\si{\degree}]')
        plotz.set_ylabel(r'$\theta_{Science Park}$ [\si{\degree}]')
        plotz.set_xticks([0, 15, 30, 45, 60])
        plotz.set_yticks([0, 15, 30, 45, 60])
        plotz.save_as_pdf('zenith_501_spa_minn%d' % minn)

        distances = angle_between(zens.compress(filter), azis.compress(filter),
                                  zenc.compress(filter), azic.compress(filter))
        counts, bins = np.histogram(distances, bins=np.linspace(0, np.pi, 91))
        plotd = Plot()
        plotd.histogram(counts, np.degrees(bins))
        sigma = np.degrees(np.percentile(distances[np.isfinite(distances)],
                                         67))
        plotd.set_label(r'67\%% within \SI{%.1f}{\degree}' % sigma)
        # plotd.set_title('Distance between reconstructed angles for station and cluster')
        plotd.set_xlabel('Angle between reconstructions [\si{\degree}]')
        plotd.set_ylabel('Counts')
        plotd.set_xlimits(min=0, max=90)
        plotd.set_ylimits(min=0)
        plotd.save_as_pdf('angle_between_501_spa_minn%d' % minn)
Example #36
0
File: main.py Project: 153957/topaz
    506: 'pink!80!black',
    508: 'blue!40!black',
    509: 'red!40!black'
}

if __name__ == "__main__":
    with tables.open_file(COIN_DATA, 'r') as data:
        cq = CoincidenceQuery(data)
        coincidence = cq.coincidences[4323]
        coincidence_events = next(
            cq.events_from_stations([coincidence], STATIONS))
        reconstruction = cq._get_reconstruction(coincidence)
        core_x = reconstruction['x']
        core_y = reconstruction['y']

        plot = Plot()

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

        distances = arange(1, 370, 1)
        times = (2.43 * (1 + distances / 30.)**1.55) + 20
        plot.plot(distances, times, mark=None)

        for station_number, event in coincidence_events:
            station = CLUSTER.get_station(station_number)
            offsets = OFFSETS[station_number]
            t = relative_detector_arrival_times(event,
                                                ref_extts,
                                                offsets=offsets)
            core_distances = []
            for d in station.detectors:
Example #37
0
        if x > 0.0:
            return 1.0
    return 2 * (H(x / L) - H(x / L - 1)) - 1


def fourier(x, N):
    ''' fourier approximation with N terms'''
    term = 0.0
    for n in range(1, N, 2):
        term += (1.0 / n) * math.sin(n * math.pi * x / L)
    return (4.0 / (math.pi)) * term


X     = npy.linspace(0.0, 2 * L, num=1000)
Y_sqr = [square(x) for x in X]
Y     = lambda n: [fourier(x, n) for x in X]

graph = Plot()
graph.set_title("Fourier approximation")

graph.plot(x=X, y=Y( 3), linestyle='red'   , mark=None, legend='n=3' )
graph.plot(x=X, y=Y( 5), linestyle='yellow', mark=None, legend='n=5' )
graph.plot(x=X, y=Y( 8), linestyle='green' , mark=None, legend='n=8' )
graph.plot(x=X, y=Y(13), linestyle='blue'  , mark=None, legend='n=13')
#graph.plot(x=X, y=Y(21), linestyle='violet', mark=None, legend='n=21')
#graph.plot(x=X, y=Y(34), linestyle='violet', mark=None, legend='n=34')
graph.plot(x=X, y=Y(55), linestyle='cyan'  , mark=None, legend='n=55')
graph.plot(x=X, y=Y_sqr, linestyle='black' , mark=None, legend='square')

graph.save_as_pdf('plot')
Example #38
0
def compared_nikhef_senstech():
    plot = Plot(height=r".67\linewidth")
    plot_pi_ph(plot, data_nikhef_final_integral, 'square')
    plot_pi_ph(plot, data_nikhef_integral, 'x')
    plot_pi_ph(plot, data_nikhef_senstech_integral, 'triangle')
    plot_pi_ph(plot, data_senstech_integral, 'o')
    plot.plot([0, 7 * data_nikhef_final_integral.RATIO], [0, 7],
              mark=None,
              linestyle='gray')
    plot.plot([0, 7 * data_nikhef_integral.RATIO], [0, 7],
              mark=None,
              linestyle='gray')
    plot.plot([0, 7 * data_nikhef_senstech_integral.RATIO], [0, 7],
              mark=None,
              linestyle='gray')
    plot.set_xlabel(r'Multiple-LED pulseintegrals [\si{\nano\volt\second}]')
    plot.set_ylabel(r'Multiple-LED pulseheights [\si{\volt}]')
    plot.set_xlimits(0, 7 * data_nikhef_final_integral.RATIO)
    plot.set_ylimits(0, 7)
    plot.save_as_pdf('plots/ph_pi_compared_nikhef_senstech')
def main():
    plot = Plot(width=r'.5\linewidth', height=r'.5\linewidth')
    r = linspace(1, 5, 100)
    phi = linspace(0, 4.5 * pi, 100)
    x = r * cos(phi)
    y = r * sin(phi)
    plot.plot(x, y, mark=None)
    plot.add_pin('start', relative_position=0, use_arrow=True)
    plot.add_pin('half', relative_position=.5, use_arrow=True)
    plot.add_pin('46\%', relative_position=.46, use_arrow=True,
                 location='above')
    plot.add_pin('end', relative_position=1, use_arrow=True, location='below')

    phi = linspace(0, 2 * pi, 10)
    x = 6 * cos(phi)
    y = 6 * sin(phi)
    plot.plot(x, y, mark=None, linestyle='thick, gray')
    plot.add_pin('start', relative_position=0, use_arrow=True,
                 location='above right')
    plot.add_pin('half', relative_position=.5, use_arrow=True,
                 location='above left')
    plot.add_pin('70\%', relative_position=.7, use_arrow=True,
                 location='below')
    plot.add_pin('end', relative_position=1, use_arrow=True,
                 location='below right')

    plot.plot([-5, 2, 5], [-7.5, -7.5, -7.5], linestyle='lightgray')
    plot.add_pin('50\%', relative_position=.5, use_arrow=True,
                 location='above right')

    plot.set_xlimits(-8, 8)
    plot.set_ylimits(-8, 8)
    plot.save('relative_pin')

    # With one logarithmic axis
    plot = Plot(axis='semilogy')

    x = [2, 2, 2]
    y = [1, 10, 100]
    plot.plot(x, y)
    for xi, yi in zip(x, y):
        plot.add_pin_at_xy(xi, yi, '(%d,%d)' % (xi, yi),
                           location='below right')
    plot.add_pin('half', relative_position=.5, use_arrow=True,
                 location='right')

    x = [4, 5, 6]
    y = [3, 3, 3]
    plot.plot(x, y)
    for xi, yi in zip(x, y):
        plot.add_pin_at_xy(xi, yi, '(%d,%d)' % (xi, yi), location='below')
    plot.add_pin('half', relative_position=.5, use_arrow=True,
                 location='above')

    x = [3, 4, 5]
    y = [1, 10, 100]
    plot.plot(x, y)
    for xi, yi in zip(x, y):
        plot.add_pin_at_xy(xi, yi, '(%d,%d)' % (xi, yi), location='above left')
    plot.add_pin('half', relative_position=.5, use_arrow=True,
                 location='right')

    plot.save('relative_pin_log')
Example #40
0
def plot_detector_offsets(offsets, type='month'):
    d1, d2, d3, d4 = zip(*offsets)
    x = range(len(d1))
    graph = Plot()
    graph.plot(x, d1, markstyle='mark size=.5pt')
    graph.plot(x, d2, markstyle='mark size=.5pt', linestyle='red')
    graph.plot(x, d3, markstyle='mark size=.5pt', linestyle='green')
    graph.plot(x, d4, markstyle='mark size=.5pt', linestyle='blue')
    graph.set_ylabel('$\Delta t$ [ns]')
    graph.set_xlabel('Date')
    graph.set_xlimits(0, max(x))
    graph.set_ylimits(-LIMITS, LIMITS)
    graph.save_as_pdf('detector_offset_drift_%s_%d' % (type, station))
Example #41
0
def plot_min_max(variable_pairs):
    plot = Plot()
    variable_pairs = sorted(variable_pairs)
    for i, minmax_d in enumerate(variable_pairs):
        plot.plot([i, i], minmax_d, mark=None)
    plot.set_xlabel('Station pair')
    plot.set_xtick_labels([' '])
    plot.set_ylabel(r'Distance between stations [\si{\meter}]')
    plot.save_as_pdf('min_max_distances')
Example #42
0
def plot_angles(data):
    """Make azimuth and zenith plots to compare the results"""

    rec501 = data.get_node('/hisparc/cluster_amsterdam/station_501',
                           'reconstructions')
    rec510 = data.get_node('/hisparc/cluster_amsterdam/station_510',
                           'reconstructions')

    zen501 = rec501.col('zenith')
    zen510 = rec510.col('zenith')
    azi501 = rec501.col('azimuth')
    azi510 = rec510.col('azimuth')
    minn501 = rec501.col('min_n')
    minn510 = rec510.col('min_n')

    sigmas = []
    blas = []
    minns = [0, 1, 2, 4, 8, 16, 24]

    high_zenith = (zen501 > .2) & (zen510 > .2)

    for minn in minns:
        filter = (minn501 > minn) & (minn510 > minn)

        length = len(azi501.compress(high_zenith & filter))
        shifts501 = np.random.normal(0, .06, length)
        shifts510 = np.random.normal(0, .06, length)
        azicounts, x, y = np.histogram2d(
            azi501.compress(high_zenith & filter) + shifts501,
            azi510.compress(high_zenith & filter) + shifts510,
            bins=np.linspace(-pi, pi, 73))
        plota = Plot()
        plota.histogram2d(azicounts,
                          degrees(x),
                          degrees(y),
                          type='reverse_bw',
                          bitmap=True)
        #         plota.set_title('Reconstructed azimuths for events in coincidence (zenith gt .2 rad)')
        plota.set_xlabel(r'$\phi_{501}$ [\si{\degree}]')
        plota.set_ylabel(r'$\phi_{510}$ [\si{\degree}]')
        plota.set_xticks([-180, -90, 0, 90, 180])
        plota.set_yticks([-180, -90, 0, 90, 180])
        plota.save_as_pdf('azimuth_501_510_minn%d' % minn)

        length = len(zen501.compress(filter))
        shifts501 = np.random.normal(0, .04, length)
        shifts510 = np.random.normal(0, .04, length)
        zencounts, x, y = np.histogram2d(zen501.compress(filter) + shifts501,
                                         zen510.compress(filter) + shifts510,
                                         bins=np.linspace(0, pi / 3., 41))
        plotz = Plot()
        plotz.histogram2d(zencounts,
                          degrees(x),
                          degrees(y),
                          type='reverse_bw',
                          bitmap=True)
        #         plotz.set_title('Reconstructed zeniths for station events in coincidence')
        plotz.set_xlabel(r'$\theta_{501}$ [\si{\degree}]')
        plotz.set_ylabel(r'$\theta_{510}$ [\si{\degree}]')
        plotz.set_xticks([0, 15, 30, 45, 60])
        plotz.set_yticks([0, 15, 30, 45, 60])
        plotz.save_as_pdf('zenith_501_510_minn%d' % minn)

        distances = angle_between(zen501.compress(filter),
                                  azi501.compress(filter),
                                  zen510.compress(filter),
                                  azi510.compress(filter))
        counts, bins = np.histogram(distances, bins=linspace(0, pi, 100))
        plotd = Plot()
        plotd.histogram(counts, degrees(bins))
        sigma = degrees(percentile(distances[isfinite(distances)], 68))
        sigmas.append(sigma)
        bla = degrees(percentile(distances[isfinite(distances)], 95))
        blas.append(bla)
        plotd.set_label(r'67\%% within \SI{%.1f}{\degree}' % sigma)
        #         plotd.set_title('Distance between reconstructed angles for station events')
        plotd.set_xlabel(r'Angle between reconstructions [\si{\degree}]')
        plotd.set_ylabel('Counts')
        plotd.set_xlimits(min=0, max=90)
        plotd.set_ylimits(min=0)
        plotd.save_as_pdf('angle_between_501_510_minn%d' % minn)

    plot = Plot()
    plot.plot(minns, sigmas, mark='*')
    plot.plot(minns, blas)
    plot.set_ylimits(min=0, max=40)
    plot.set_xlabel('Minimum number of particles in each station')
    plot.set_ylabel(r'Angle between reconstructions [\si{\degree}]')
    plot.save_as_pdf('angle_between_501_510_v_minn')
Example #43
0
def main():
    plot = Plot()

    size = 20
    x = np.linspace(1, 20, size)
    y = np.linspace(10, 50, size)
    y_random = y + np.random.uniform(-3, 1, size)

    err_l = np.random.uniform(0, 2, size)
    err_h = np.random.uniform(1, 5, size)
    err_x = [0.4] * size

    plot.plot(x, y, mark=None)
    plot.scatter(x, y_random, xerr=err_x, yerr=list(zip(err_l, err_h)))

    plot.set_xlabel("Value with symmetric error")
    plot.set_ylabel("Other value with asymmetric errors")
    plot.save("error_bars")
Example #44
0
def analyse(name):
    data = genfromtxt('data/%s.tsv' % name, delimiter='\t', dtype=None,
                      names=['ext_timestamp', 'time_delta'])
    time_delta = data['time_delta']

    # Plot distribution
    counts, bins = histogram(time_delta, bins=arange(-10.5, 11.5, 1))
    plot = Plot()
    plot.histogram(counts, bins)
    plot.set_ylimits(min=0)
    plot.set_ylabel('counts')
    plot.set_xlabel(r'time delta [\si{\nano\second}]')
    plot.save_as_pdf(name)

    # Plot moving average
    n = 300
    skip = 20
    moving_average = convolve(time_delta, ones((n,)) / n, mode='valid')
    plot = Plot()
    timestamps = (data['ext_timestamp'][:-n + 1:skip] -
                  data['ext_timestamp'][0]) / 1e9 / 3600.
    plot.plot(timestamps, moving_average[::skip], mark=None)
    plot.set_xlimits(min=0)
    plot.set_ylabel(r'time delta [\si{\nano\second}]')
    plot.set_xlabel('timestamp [\si{\hour}]')
    plot.save_as_pdf('moving_average_%s' % name)
Example #45
0
def main():
    locations = np.genfromtxt(
        'data/SP-DIR-plot_sciencepark_cluster-detectors.txt',
        names=['x', 'y'])
    stations = np.genfromtxt(
        'data/SP-DIR-plot_sciencepark_cluster-stations.txt',
        names=['id', 'x', 'y'])

    graph = Plot()

    graph.scatter(locations['x'], locations['y'])
    graph.set_axis_equal()

    locations = ['right'] * len(stations)
    locations[0] = 'left'
    locations[5] = 'above right'
    locations = iter(locations)
    for num, x, y in stations:
        graph.add_pin_at_xy(x, y, int(num), location=next(locations),
                            use_arrow=False, style='gray,label distance=1ex')

    x = [stations['x'][u] for u in [0, 2, 5]]
    y = [stations['y'][u] for u in [0, 2, 5]]
    x.append(x[0])
    y.append(y[0])
    graph.plot(x, y, mark=None, linestyle='dashed')

    graph.add_pin_at_xy([x[0], x[1]], [y[0], y[1]], r'\SI{128}{\meter}',
                        relative_position=.4, location='below right',
                        use_arrow=False)
    graph.add_pin_at_xy([x[0], x[2]], [y[0], y[2]], r'\SI{151}{\meter}',
                        relative_position=.5, location='left',
                        use_arrow=False)
    graph.add_pin_at_xy([x[2], x[1]], [y[2], y[1]], r'\SI{122}{\meter}',
                        relative_position=.5, location='above right',
                        use_arrow=False)

    graph.set_xlabel(r"Distance [\si{\meter}]")
    graph.set_ylabel(r"Distance [\si{\meter}]")

    graph.save('sciencepark')