Exemplo n.º 1
0
def plot_fit(x, data, slope, intercept, pair):
    plot = Plot()
    plot.scatter(x, log(c))
    plot.plot(x, x * slope + intercept, mark=None)
    plot.set_ylimits(min=0)
    plot.set_label(r'%.1e \si{\hertz}' % rate)
    plot.save_as_pdf('intervals/intervals_%d_%d_r' % pair)
Exemplo n.º 2
0
def plot_coincidence_v_interval_rate(data):
    """Plot results

    :param distances: dictionary with occuring distances for different
                      combinations of number of detectors.
    :param coincidence_rates: dictionary of occuring coincidence rates for
                              different combinations of number of detectors.
    :param rate_errors: errors on the coincidence rates.

    """
    (distances, coincidence_rates, interval_rates, distance_errors,
     rate_errors, pairs) = data
    markers = {4: 'o', 6: 'triangle', 8: 'square'}
    colors = {4: 'red', 6: 'black!50!green', 8: 'black!20!blue'}
    plot = Plot('loglog')

    plot.plot([1e-7, 1e-1], [1e-7, 1e-1], mark=None)
    for n in distances.keys():
        plot.scatter(interval_rates[n],
                     coincidence_rates[n],
                     yerr=rate_errors[n],
                     mark=markers[n],
                     markstyle='%s, thin, mark size=.75pt' % colors[n])

    plot.set_xlabel(r'Rate based on coincidence intervals [\si{\hertz}]')
    plot.set_ylabel(r'Rate based on coincidences and exposure [\si{\hertz}]')
    plot.set_axis_options('log origin y=infty')
    plot.set_xlimits(min=1e-7, max=1e-1)
    plot.set_ylimits(min=1e-7, max=1e-1)
    plot.save_as_pdf('interval_v_coincidence_rate')
Exemplo n.º 3
0
def plot_coincidence_rate_distance(data, sim_data):
    """Plot results

    :param distances: dictionary with occuring distances for different
                      combinations of number of detectors.
    :param coincidence_rates: dictionary of occuring coincidence rates for
                              different combinations of number of detectors.
    :param rate_errors: errors on the coincidence rates.

    """
    (distances, coincidence_rates, interval_rates, distance_errors,
     rate_errors, pairs) = data
    sim_distances, sim_energies, sim_areas = sim_data
    markers = {4: 'o', 6: 'triangle', 8: 'square'}
    colors = {4: 'red', 6: 'black!50!green', 8: 'black!20!blue'}

    coincidence_window = 10e-6  # seconds
    freq_2 = 0.3
    freq_4 = 0.6
    background = {
        4: 2 * freq_2 * freq_2 * coincidence_window,
        6: 2 * freq_2 * freq_4 * coincidence_window,
        8: 2 * freq_4 * freq_4 * coincidence_window
    }

    for rates, name in [(coincidence_rates, 'coincidence'),
                        (interval_rates, 'interval')]:
        plot = Plot('loglog')
        for n in distances.keys():
            plot.draw_horizontal_line(background[n], 'dashed,' + colors[n])


#         for n in distances.keys():
        for n in [4, 8]:
            expected_rates = expected_rate(distances[n],
                                           rates[n],
                                           background[n],
                                           sim_distances,
                                           sim_energies,
                                           sim_areas[n],
                                           n=n)
            plot.plot(sim_distances,
                      expected_rates,
                      linestyle=colors[n],
                      mark=None,
                      markstyle='mark size=0.5pt')

        for n in distances.keys():
            plot.scatter(distances[n],
                         rates[n],
                         xerr=distance_errors[n],
                         yerr=rate_errors[n],
                         mark=markers[n],
                         markstyle='%s, mark size=.75pt' % colors[n])
        plot.set_xlabel(r'Distance between stations [\si{\meter}]')
        plot.set_ylabel(r'%s rate [\si{\hertz}]' % name.title())
        plot.set_axis_options('log origin y=infty')
        plot.set_xlimits(min=1, max=20e3)
        plot.set_ylimits(min=1e-7, max=5e-1)
        plot.save_as_pdf('distance_v_%s_rate' % name)
Exemplo n.º 4
0
def compare_ttrigger():
    with tables.open_file(DATA_PATH, 'r') as data:
        processed = data.get_node(GROUP, 'events_processed')
        filtered = data.get_node(GROUP, 'events_filtered')

        assert all(
            processed.col('ext_timestamp') == filtered.col('ext_timestamp'))

        trig_proc = processed.col('t_trigger')
        trig_filt = filtered.col('t_trigger')
        dt_trigger = trig_filt - trig_proc

        density = (processed.col('n1') + processed.col('n2') +
                   processed.col('n3') + processed.col('n4')) / 2
        print 'Density range:', density.min(), density.max()
        print 'dt trigger range:', dt_trigger.min(), dt_trigger.max()

        if len(trig_proc) > 4000:
            plot = Plot()
            bins = [linspace(0, 30, 100), arange(-11.25, 75, 2.5)]
            c, x, y = histogram2d(density, dt_trigger, bins=bins)
            # plot.histogram2d(c, x, y, bitmap=True, type='color', colormap='viridis')
            plot.histogram2d(log10(c + 0.01), x, y, type='area')
            plot.set_xlabel('Particle density')
            plot.set_ylabel('Difference in trigger time')
            plot.save_as_pdf('hist2d')
        else:
            plot = Plot()
            plot.scatter(
                density,
                dt_trigger,
                mark='o',
                markstyle='mark size=0.6pt, very thin, semitransparent')
            plot.set_xlabel('Particle density')
            plot.set_ylabel('Difference in trigger time')
            plot.save_as_pdf('scatter')

        plot = Plot()
        c, bins = histogram(dt_trigger, arange(-10, 200, 2.5))
        c = where(c < 100, c, 100)
        plot.histogram(c, bins)
        plot.set_ylimits(0, 100)
        plot.set_ylabel('Counts')
        plot.set_xlabel('Difference in trigger time')
        plot.save_as_pdf('histogram')

        plot = Plot()
        c, bins = histogram(trig_proc, arange(-10, 200, 2.5))
        plot.histogram(c, bins)
        c, bins = histogram(trig_filt, arange(-10, 200, 2.5))
        plot.histogram(c, bins, linestyle='red')
        plot.set_ylimits(0)
        plot.set_ylabel('Counts')
        plot.set_xlabel('Trigger time')
        plot.save_as_pdf('histogram_t')
Exemplo n.º 5
0
def plot_zenith_density_small():
    with tables.open_file(RESULT_DATA_SMALL, 'r') as data:
        e = data.root.cluster_simulations.station_501.events.read()
        density = (e['n1'] + e['n2'] + e['n3'] + e['n4']) / 2.
        zenith = data.root.cluster_simulations.station_501.reconstructions.col('zenith')
        plot = Plot('semilogx')
        plot.scatter(density, degrees(zenith), markstyle='thin, mark size=.75pt')
        plot.set_xlabel(r'Particle density [\si{\per\meter\squared}]')
        plot.set_ylabel(r'Reconstructed zenith [\si{\degree}]')
        plot.set_xlimits(1, 1e4)
        plot.set_ylimits(-5, 95)
        plot.save_as_pdf('plots/zenith_density_e14_5_z0')
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')
Exemplo n.º 7
0
def plot_zenith_core_distance():
    with tables.open_file(RESULT_DATA, 'r') as data:
        sim = data.root.coincidences.coincidences.read_where('N == 1')
        core_distance = sqrt(sim['x'] ** 2 + sim['y'] ** 2)
        zenith = data.root.cluster_simulations.station_501.reconstructions.col('zenith')
        plot = Plot('semilogx')
        plot.scatter(core_distance, degrees(zenith), markstyle='thin, mark size=.75pt')
        plot.set_xlabel(r'Core distance [\si{\meter}]')
        plot.set_ylabel(r'Reconstructed zenith [\si{\degree}]')
        plot.set_xlimits(1, 1e3)
        plot.set_ylimits(-5, 95)
        plot.save_as_pdf('plots/zenith_distance_e17_z0')
Exemplo n.º 8
0
def make_map(station=None, label='map', detectors=False):

    get_locations = (get_detector_locations
                     if detectors else get_station_locations)

    latitudes, longitudes = get_locations(station)

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

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

    map_w, map_h = image.size

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

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

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

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

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

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

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

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

    # save plot to file
    plot.save_as_pdf(label.replace(' ', '-'))
Exemplo n.º 9
0
def plot_front_shapes():
    r = [20, 29, 41, 58, 84, 120, 171, 245, 350, 501]
    fit_r = arange(0, 510, 5)
    for particle in ['gamma', 'proton', 'iron']:
        for energy in ['15.0', '15.5', '16.0', '16.5', '17.0']:
            files = glob(PATH + '%s_E_%s*' % (particle, energy))
            if not len(files):
                continue

            t = zeros((len(r), len(files)))

            for i, file in enumerate(files):
                detected_t = loadtxt(file, usecols=(1, ))
                t[:, i][:len(detected_t)] = detected_t

            t_src = t.copy()
            for j in range(1, len(t)):
                t[j] -= t[0]
            t[0] -= t[0]
            mean_t = t.mean(axis=1)
            try:
                min_limit = 3
                min_efficiency = 0.9
                limit = min_limit + next(
                    i for i, ti in enumerate(t_src[min_limit:])
                    if not count_nonzero(ti) > min_efficiency * len(files))
            except:
                limit = len(r)

            plot = Plot()
            plot.scatter(r[:limit],
                         mean_t[:limit],
                         yerr=t.std(axis=1)[:limit],
                         xerr=[10] * limit)
            plot.scatter(r[:limit], median(t, axis=1)[:limit], mark='x')

            popt, pcov = curve_fit(front_shape, r[:limit], mean_t[:limit])

            plot.plot(fit_r,
                      front_shape(fit_r, *popt),
                      linestyle='gray',
                      mark=None)
            print particle, energy, popt
            plot.set_ylimits(-10, 130)
            plot.set_xlimits(-10, 510)
            plot.set_ylabel(r'Delay [\si{\ns}]')
            plot.set_xlabel(r'Core distance [\si{\meter}]')
            plot.save_as_pdf('plots/front_shape/%s_%s.pdf' %
                             (particle, energy))
Exemplo n.º 10
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')
Exemplo n.º 11
0
def plot_compared():
    popt, perr = fit_curve(senstech_m_ph, senstech_e_ph)
    fit = FIT % (popt[0], P1, popt[1])

    plot = Plot(width=r'.67\linewidth', height=r'.67\linewidth')
    plot.set_label(fit, location='upper left')
    plot.scatter(senstech_e_ph, senstech_m_ph, mark='*')
    plot.scatter(nikhef_e_ph, nikhef_m_ph, mark='o')
    inputs = linspace(min(senstech_m_ph), max(senstech_m_ph), 500)
    plot.plot(ice_cube_pmt_p1(inputs, *popt), inputs, mark=None)
    plot.plot([0, 6], [0, 6], mark=None, linestyle='gray')
    plot.set_xlimits(0, 6)
    plot.set_ylimits(0, 6)
    plot.set_axis_equal()
    plot.set_xlabel(r'Sum individual LED pulseheights [\si{\volt}]')
    plot.set_ylabel(r'Multiple-LED pulseheight [\si{\volt}]')
    plot.save_as_pdf('plots/linearity_compared')
Exemplo n.º 12
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")
Exemplo n.º 13
0
def possible_zeniths():
    d = 10
    c = 3e8

    tmax = d / c
    ts = 2.5e-9

    n = floor(tmax / ts)

    k = arange(-n, n + 1)

    theta = arcsin(k * ts / tmax)

    plot = Plot()
    plot.scatter(k * ts * 1e9, degrees(theta))
    plot.set_xlabel(r'Time difference [\si{\ns}]')
    plot.set_ylabel(r'Zenith angle [\si{\degree}]')
    plot.set_ylimits(-90, 90)
    plot.save_as_pdf('possible_zeniths')
Exemplo n.º 14
0
def plot_ranges():
    k = arange(26)
    p_low = [percentile_low_density_for_n(ki) for ki in k]
    p_median = [median_density_for_n(ki) for ki in k]
    p_mean = [mean_density_for_n(ki) for ki in k]
#     p_mpv = [most_probable_density_for_n(ki) for ki in k]
    p_high = [percentile_high_density_for_n(ki) for ki in k]
    plot = Plot(height=r'\defaultwidth')
    plot.plot([0, 1.5 * max(k)], [0, 1.5 * max(k)], mark=None, linestyle='dashed')
    plot.scatter(k, p_median)
#     plot.plot(k, p_mean, mark=None, linestyle='green')
#     plot.plot(k, p_mpv, mark=None, linestyle='red')
    plot.shade_region(k, p_low, p_high)
    plot.set_xlimits(min(k) - 0.05 * max(k), 1.05 * max(k))
    plot.set_ylimits(min(k) - 0.05 * max(k), 1.05 * max(k))
    plot.set_axis_equal()
    plot.set_xlabel('Detected number of particles')
    plot.set_ylabel('Expected actual number of particles')
    plot.save_as_pdf('plots/poisson_ranges')
Exemplo n.º 15
0
def plot_detectors(cluster):
    station = cluster.stations[0]
    detectors = station.detectors
    timestamps = set(station.timestamps).union(detectors[0].timestamps)

    plot = Plot()

    for timestamp in sorted(timestamps):
        cluster.set_timestamp(timestamp)
        for i in range(4):
            x, y = detectors[i].get_xy_coordinates()
            plot.scatter([x], [y], mark='*', markstyle=COLORS[i])
        x, y = station.get_xy_coordinates()
        plot.scatter([x], [y], markstyle='purple')
        # print timestamp, gps_to_datetime(timestamp), x, y

    plot.set_xlabel(r'Easting [\si{\meter}]')
    plot.set_ylabel(r'Northing [\si{\meter}]')
    plot.set_axis_equal()
    plot.save_as_pdf('locations_%d' % station.number)
Exemplo n.º 16
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')
Exemplo n.º 17
0
def plot_fit_pulseheight(ph_in, ph_out):

    popt, perr = fit_curve(ph_out, ph_in)
    fit = FIT % (popt[0], P1, popt[1])

    outputs = linspace(0, max(ph_out) + 0.2, 500)

    plot = Plot(width=r'.67\linewidth', height=r'.67\linewidth')
    plot.scatter(ph_in, ph_out, mark='o')

    plot.plot(ice_cube_pmt_p1(outputs, *popt), outputs, mark=None)

    plot.plot([0, 6], [0, 6], mark=None, linestyle='gray')
    plot.set_xlimits(0, 6)
    plot.set_ylimits(0, 6)
    plot.set_axis_equal()

    plot.set_xlabel(r'Sum individual LED pulseheights [\si{\volt}]')
    plot.set_ylabel(r'Multiple-LED pulseheight [\si{\volt}]')

    return plot
Exemplo n.º 18
0
def plot_box(ids, **kwargs):
    """Box Plot like results"""

    if type(ids) is int:
        ids = [ids]

    x = range(len(ids))

    # Begin Figure
    plot = Plot()
    data = [
        determine_stats([i for i in get(id)[1] if abs(i) < 100]) for id in ids
    ]

    low, high, avg, std = zip(*data)

    plot.plot(x,
              avg,
              yerr=std,
              mark='o',
              markstyle="mark size=1pt",
              linestyle=None)
    plot.scatter(x, low, mark='x', markstyle="mark size=.5pt")
    plot.scatter(x, high, mark='x', markstyle="mark size=.5pt")

    #     if kwargs.keys():
    #         plot.set_title('Tijdtest offsets ' + kwargs[kwargs.keys()[0]])
    plot.set_xlabel(r'ids')
    plot.set_ylabel(r'$\Delta$ t (swap - reference) [\si{\nano\second}]')
    plot.set_ylimits(-80, 80)

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

    print 'tt_analyse: Plotted offsets'
Exemplo n.º 19
0
def plot_zenith(angle_centers, mean_counts, std_counts):
    fit_functions = [rossi, iyono, mod_ciampa, mod_ciampa_conv]

    rangle_centers = radians(angle_centers)
    sangle_centers = convert_angles(angle_centers)
    angles = arange(0.1, 85, 0.1)
    rangles = radians(angles)

    for fit_function in fit_functions:
        popt, pcov = curve_fit(fit_function, angle_centers,
                               mean_counts)  # , sigma=std_counts)
        print popt

        plot = Plot()
        plot.scatter(angle_centers,
                     mean_counts,
                     yerr=std_counts,
                     markstyle='red')
        plot.plot(angles, fit_function(angles, *popt), mark=None)
        plot.set_ylabel('Counts')
        plot.set_xlabel(r'Zenith [\si{\degree}]')
        plot.save_as_pdf('zenith_distribution_%s' % fit_function.func_name)

        plot = Plot('semilogy')
        plot.scatter(sangle_centers,
                     mean_counts / sin(rangle_centers),
                     yerr=std_counts)
        fitted_counts = fit_function(angles, *popt)
        plot.plot(convert_angles(angles),
                  fitted_counts / sin(rangles),
                  mark=None)
        plot.plot(convert_angles(angles),
                  fitted_counts,
                  linestyle='gray',
                  mark=None)
        plot.set_ylabel('Counts')
        plot.set_xlimits(0, 1)
        plot.set_xlabel(r'Zenith angle [$\sec \theta - 1$]')
        plot.save_as_pdf('zenith_distribution_sec_%s' % fit_function.func_name)
Exemplo n.º 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")
Exemplo n.º 21
0
def plot_distance_width():

    distances = []
    widths = []

    with tables.open_file(PATH, 'r') as data:
        cluster = data.root.coincidences._v_attrs.cluster
        station_groups = [(id, data.get_node(sidx, 'events'))
                          for id, sidx in enumerate(data.root.coincidences.s_index)]
        bins = arange(-2000, 2000, 20)
        for ref, other in itertools.combinations(station_groups, 2):
            ref_id, ref_events = ref
            id, events = other
            distances.append(cluster.calc_rphiz_for_stations(ref_id, id)[0])

            dt = (ref_events.col('ext_timestamp').astype(int) -
                  events.col('ext_timestamp').astype(int))
            pre_width = std(dt)
            counts, bins = histogram(dt, bins=linspace(-1.8 * pre_width, 1.8 * pre_width, 100), density=True)
            x = (bins[:-1] + bins[1:]) / 2
            popt, pcov = curve_fit(norm.pdf, x, counts, p0=(0., distances[-1]))
            widths.append(popt[1])
            print std(dt), popt[1]

    popt, pcov = curve_fit(lin, distances, widths, p0=(1.1, 1))
    print popt, pcov

    plot = Plot()
    plot.scatter(distances, widths)
    plot.plot([0, 600], [0, 600 / 0.3], mark=None, linestyle='gray')
    plot.plot([0, 600], [lin(0, *popt), lin(600, *popt)], mark=None)
    plot.set_xlimits(min=0, max=600)
    plot.set_ylimits(min=0, max=700)
    plot.set_xlabel(r'Distance [\si{\meter}]')
    plot.set_ylabel(r'Width of dt distribution [\si{\ns}]')
    plot.save_as_pdf('plots/distance_v_width_pr')
Exemplo n.º 22
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'])
Exemplo n.º 23
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(' ', '-'))
Exemplo n.º 24
0
def display_coincidences(coincidence_events, c_id, map):

    cluster = CLUSTER

    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))
        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(array(latitudes), array(longitudes))
    mint = nanmin(t)

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

    for xv, yv, tv, pv in zip(x, y, t, p):
        if isnan(tv) or 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.set_scalebar(location="lower left")
    plot.set_slimits(min=1, max=60)
    plot.set_colorbar('$\Delta$t [\si{n\second}]')
    plot.set_axis_equal()

    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.set_xlimits(min=-250, max=350)
    #     plot.set_ylimits(min=-250, max=250)
    #     plot.set_xlabel('x [\si{\meter}]')
    #     plot.set_ylabel('y [\si{\meter}]')

    plot.save_as_pdf('coincidences/event_display_%d_%d' % (c_id, ts0))
Exemplo n.º 25
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')
Exemplo n.º 26
0
Arquivo: main.py Projeto: 153957/topaz
            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:
                x, y = d.get_xy_coordinates()
                core_distances.append(distance_between(core_x, core_y, x, y))
            plot.scatter(core_distances,
                         t,
                         mark='*',
                         markstyle=COLORS[station_number])
        plot.set_ylabel('Relative arrival time [ns]')
        plot.set_xlabel('Distance from core [m]')
        plot.save_as_pdf('relative_arrival_times')
Exemplo n.º 27
0
def plot_size_energy():
    cq = CorsikaQuery(OVERVIEW)
    p = 'proton'
    plot = Plot(axis='semilogy')
    for z in cq.available_parameters('zenith', particle=p):
        zen_plot = Plot(axis='semilogy')
        shade = 'black!%f' % (100 - z)

        energies = sorted(cq.available_parameters('energy', particle=p,
                                                  zenith=z))
        sizes_m = []
        sizes_e = []
        sizes_l = []
        energies_m = []
        energies_e = []
        energies_l = []

        for e in energies:
            selection = cq.simulations(zenith=z, energy=e, particle=p)
            if median(selection['n_muon']):
                sizes_m.append(median(selection['n_muon']))
                energies_m.append(e)
            if median(selection['n_electron']):
                sizes_e.append(median(selection['n_electron']))
                energies_e.append(e)
            if median(selection['n_muon'] + selection['n_electron']):
                sizes_l.append(median(selection['n_muon'] + selection['n_electron']))
                energies_l.append(e)

        # Plot data points
        zen_plot.scatter(energies_m, sizes_m, mark='+')
        zen_plot.scatter(energies_e, sizes_e, mark='x')
        zen_plot.scatter(energies_l, sizes_l, mark='square')
        plot.scatter(energies_l, sizes_l, mark='square', markstyle=shade)

        # Fit
        initial = (10.2, 1.)
        popt_m, pcov_m = curve_fit(f, energies_m, log10(sizes_m), p0=initial)
        popt_e, pcov_e = curve_fit(f, energies_e, log10(sizes_e), p0=initial)
        popt, pcov = curve_fit(f, energies_l, log10(sizes_l), p0=initial)

        # Plot fits
        fit_energies = arange(10, 20, 0.25)
        sizes = [10 ** f(e, *popt_m) for e in fit_energies]
        zen_plot.plot(fit_energies, sizes, mark=None, linestyle='red')

        sizes = [10 ** f(e, *popt_e) for e in fit_energies]
        zen_plot.plot(fit_energies, sizes, mark=None, linestyle='blue')

        sizes = [10 ** f(e, *popt) for e in fit_energies]
        zen_plot.plot(fit_energies, sizes, mark=None)
        plot.plot(fit_energies, sizes, mark=None, linestyle=shade)

        zen_plot.set_ylimits(1, 1e9)
        zen_plot.set_xlimits(10.5, 18.5)
        zen_plot.set_ylabel(r'Shower size [number of leptons]')
        zen_plot.set_xlabel(r'Shower energy [log10(E/eV)]')
        zen_plot.save_as_pdf('shower_size_v_energy_%.1f.pdf' % z)
    plot.set_ylimits(1, 1e9)
    plot.set_xlimits(10.5, 18.5)
    plot.set_ylabel(r'Shower size [number of leptons]')
    plot.set_xlabel(r'Shower energy [log10(E/eV)]')
    plot.save_as_pdf('shower_size_v_energy')
    cq.finish()