Example #1
0
def plot_delta_test(ids, **kwargs):
    """ Plot the delta with std

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

    # Define Bins
    low = -200
    high = 200
    bin_size = 1
    bins = np.arange(low - .5 * bin_size, high + bin_size, bin_size)

    # Begin Figure
    plot = Plot()
    for id in ids:
        ext_timestamps, deltas = get(id)
        n, bins = np.histogram(deltas, bins, density=True)
        plot.histogram(n, bins)
    if kwargs.keys():
        plot.set_title('Tijdtest ' + kwargs[kwargs.keys()[0]])
    plot.set_xlabel(r'$\Delta$ t (swap - reference) [ns]')
    plot.set_ylabel(r'p')
    plot.set_xlimits(low, high)
    plot.set_ylimits(0., .15)

    # Save Figure
    if len(ids) == 1:
        name = 'tt_delta_hist_%03d' % ids[0]
    elif kwargs.keys():
        name = 'tt_delta_hist_' + kwargs[kwargs.keys()[0]]

    plot.save_as_pdf(PLOT_PATH + name)
    print 'tt_analyse: Plotted histogram'
Example #2
0
def plot_delta_test():
    """ Plot the delta with std

    """
    # Define Bins
    low = -2000
    high = 2000
    bin_size = 10  # 2.5*n?
    bins = np.arange(low - .5 * bin_size, high + bin_size, bin_size)

    tests = test_log_508()

    # Begin Figure
    plot = Plot()
    with tables.open_file(DELTAS_PATH, 'r') as delta_file:
        for test in tests:
            delta_table = delta_file.get_node('/t%d' % test.id, 'delta')
            ext_timestamps = [row['ext_timestamp'] for row in delta_table]
            deltas = [row['delta'] for row in delta_table]
            bins = np.arange(low - 0.5 * bin_size, high + bin_size, bin_size)
            n, bins = np.histogram(deltas, bins)
            plot.histogram(n, bins)

    plot.set_title('Time difference coincidences 508')
    # plot.set_label(r'$\mu={1:.1f}$, $\sigma={2:.1f}$'.format(*popt))
    plot.set_xlabel(r'$\Delta$ t (station - 508) [\SI{\ns}]')
    plot.set_ylabel(r'p')
    plot.set_xlimits(low, high)
    plot.set_ylimits(min=0., max=0.15)
    plot.save_as_pdf('plots/508/histogram.pdf')
Example #3
0
def offset_distribution(offsets):
    """Examine offset distribution using intermediate stations

    Start and end station are the same, but hops via some other stations.
    The result should ideally be an offset of 0 ns.

    :param offsets: Dictionary of dictionaries with offset functions.

    """
    aoffsets = get_aligned_offsets(offsets, START, STOP, STEP)

    stations = offsets.keys()
    for n in [2, 3, 4, 5]:
        plot = Plot()
        offs = []
        for ref in stations:
            for s in permutations(stations, n):
                if ref in s:
                    continue
                offs.extend(aoffsets[ref][s[0]] + aoffsets[s[-1]][ref] +
                            sum(aoffsets[s[i]][s[i + 1]]
                                for i in range(n - 1)))
        plot.histogram(*histogram(offs, bins=range(-100, 100, 2)))
        plot.set_xlimits(-100, 100)
        plot.set_ylimits(min=0)
        plot.set_title('n = %d' % n)
        plot.set_xlabel(r'Station offset residual [\si{\ns}]')
        plot.save_as_pdf('plots/round_trip_dist_%d' % n)
Example #4
0
def determine_detector_timing_offsets(d, s, events):
    """Determine the offsets between the station detectors.

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

    """
    bins = arange(-100 + 1.25, 100, 2.5)
    col = (cl for cl in COLORS)
    graph = Plot()
    for i, j in itertools.combinations(range(1, 5), 2):
        ti = events.col('t%d' % i)
        tj = events.col('t%d' % j)
        dt = (ti - tj).compress((ti >= 0) & (tj >= 0))
        y, bins = histogram(dt, bins=bins)
        graph.histogram(y, bins, linestyle='color=%s' % col.next())
        x = (bins[:-1] + bins[1:]) / 2
        try:
            popt, pcov = curve_fit(gauss, x, y, p0=(len(dt), 0., 10.))
            print '%d-%d: %f (%f)' % (i, j, popt[1], popt[2])
        except (IndexError, RuntimeError):
            print '%d-%d: failed' % (i, j)
    graph.set_title('Time difference, station %d' % (s))
    graph.set_label('%s' % d.replace('_', ' '))
    graph.set_xlimits(-100, 100)
    graph.set_ylimits(min=0)
    graph.set_xlabel('$\Delta t$')
    graph.set_ylabel('Counts')
    graph.save_as_pdf('%s_%d' % (d, s))
Example #5
0
def plot_zenith(zenith, name=''):

    graph = Plot()
    n, bins = histogram(zenith, bins=linspace(0, pi / 2., 41))
    graph.histogram(n, bins)
    graph.set_title('Zenith distribution')
    graph.set_xlimits(0, pi / 2.)
    graph.set_ylimits(min=0)
    graph.set_xlabel('Zenith [rad]')
    graph.set_ylabel('Counts')
    graph.save_as_pdf('zen_%s' % name)
Example #6
0
def plot_azimuth(azimuth, name=''):

    # graph = PolarPlot(use_radians=True)
    graph = Plot()
    n, bins = histogram(azimuth, bins=linspace(-pi, pi, 21))
    graph.histogram(n, bins)
    graph.set_title('Azimuth distribution')
    graph.set_xlimits(-pi, pi)
    graph.set_ylimits(min=0)
    graph.set_xlabel('Azimuth [rad]')
    graph.set_ylabel('Counts')
    graph.save_as_pdf('azi_norm_%s' % name)
Example #7
0
def plot_reconstruction_accuracy(data, d):

    station_path = '/cluster_simulations/station_%d'
    cluster = cluster_501_510()
    coincidences = data.root.coincidences.coincidences
    recs501 = data.root.hisparc.cluster_amsterdam.station_501.reconstructions
    recs510 = data.root.hisparc.cluster_amsterdam.station_510.reconstructions
    graph = Plot()
    ids = set(recs501.col('id')).intersection(recs510.col('id'))
    filtered_501 = [(row['zenith'], row['azimuth']) for row in recs501
                    if row['id'] in ids]
    filtered_510 = [(row['zenith'], row['azimuth']) for row in recs510
                    if row['id'] in ids]

    zen501, azi501 = zip(*filtered_501)
    zen510, azi510 = zip(*filtered_510)
    zen501 = array(zen501)
    azi501 = array(azi501)
    zen510 = array(zen510)
    azi510 = array(azi510)
    da = angle_between(zen501, azi501, zen510, azi510)

    n, bins = histogram(da, bins=arange(0, pi, .1))
    graph.histogram(n, bins)

    failed = coincidences.nrows - len(ids)
    graph.set_ylimits(min=0)
    graph.set_xlimits(min=0, max=pi)
    graph.set_ylabel('Count')
    graph.set_xlabel('Angle between 501 and 510 [rad]')
    graph.set_title('Coincidences between 501 and 510')
    graph.set_label('Failed to reconstruct %d events' % failed)
    graph.save_as_pdf('coincidences_%s' % d)

    graph_recs = PolarPlot()
    azimuth = degrees(recs501.col('azimuth'))
    zenith = degrees(recs501.col('zenith'))
    graph_recs.scatter(azimuth[:5000],
                       zenith[:5000],
                       mark='*',
                       markstyle='mark size=.2pt')
    graph_recs.set_ylimits(min=0, max=90)
    graph_recs.set_ylabel('Zenith [degrees]')
    graph_recs.set_xlabel('Azimuth [degrees]')
    graph_recs.set_title('Reconstructions by 501')
    graph_recs.save_as_pdf('reconstructions_%s' % d)
Example #8
0
def scatter_n():
    r = 420
    with tables.open_file(RESULT_PATH, 'r') as data:
        cluster = data.root.coincidences._v_attrs.cluster
        coincidences = data.root.coincidences.coincidences
        graph = Plot()
        for n in range(0, len(cluster.stations) + 1):
            c = coincidences.read_where('N == n')
            if len(c) == 0:
                continue
            graph.plot(c['x'],
                       c['y'],
                       mark='*',
                       linestyle=None,
                       markstyle='mark size=.2pt,color=%s' %
                       COLORS[n % len(COLORS)])
            graph1 = Plot()
            graph1.plot(c['x'],
                        c['y'],
                        mark='*',
                        linestyle=None,
                        markstyle='mark size=.2pt')
            plot_cluster(graph1, cluster)
            graph1.set_axis_equal()
            graph1.set_ylimits(-r, r)
            graph1.set_xlimits(-r, r)
            graph1.set_ylabel('y [m]')
            graph1.set_xlabel('x [m]')
            graph1.set_title('Showers that caused triggers in %d stations' % n)
            graph1.save_as_pdf('N_%d' % n)

            graph_azi = PolarPlot(use_radians=True)
            plot_azimuth(graph_azi, c['azimuth'])
            graph_azi.set_label('N = %d' % n)
            graph_azi.save('azi_%d' % n)
            graph_azi.save_as_pdf('azi_%d' % n)

        plot_cluster(graph, cluster)
        graph.set_axis_equal()
        graph.set_ylimits(-r, r)
        graph.set_xlimits(-r, r)
        graph.set_ylabel('y [m]')
        graph.set_xlabel('x [m]')
        graph.set_title('Color indicates the number triggered stations by '
                        'a shower.')
        graph.save_as_pdf('N')
Example #9
0
def round_trip(offsets):
    """Examine offset distribution using intermediate stations over time

    Start and end station are the same, but hops via some other stations.
    The result should ideally be an offset of 0 ns.

    :param offsets: Dictionary of dictionaries with offset functions.

    """
    aoffsets = get_aligned_offsets(offsets, START, STOP, STEP)
    timestamps = range(START, STOP, STEP)
    stations = offsets.keys()
    for n in [2, 3, 4, 5]:
        plot = Plot()
        ts = []
        offs = []
        for ref in stations:
            # Intermediate stations
            for s in combinations(stations, n):
                if ref in s:
                    continue
                offs.extend(aoffsets[ref][s[0]] + aoffsets[s[-1]][ref] +
                            sum(aoffsets[s[i]][s[i + 1]]
                                for i in range(n - 1)))
                ts.extend(timestamps)
        ts = array(ts)
        offs = array(offs)
        ts = ts.compress(~isnan(offs))
        offs = offs.compress(~isnan(offs))
        counts, xedges, yedges = histogram2d(ts,
                                             offs,
                                             bins=(timestamps[::4],
                                                   range(-100, 101, 5)))
        plot.histogram2d(counts,
                         xedges,
                         yedges,
                         bitmap=True,
                         type='color',
                         colormap='viridis')
        plot.set_colorbar()
        plot.set_ylimits(-100, 100)
        plot.set_title('n = %d' % n)
        plot.set_ylabel(r'Station offset residual [\si{\ns}]')
        plot.set_xlabel(r'Timestamp [\si{\s}]')
        plot.save_as_pdf('plots/round_trip_%d' % n)
Example #10
0
def plot_delta_histogram(ids, **kwargs):
    """ Plot a histogram of the deltas

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

    # Bin width
    bin_size = 1  # 2.5*n

    # Begin Figure
    plot = Plot()
    for id in ids:
        ext_timestamps, deltas = get(id)
        low = floor(min(deltas))
        high = ceil(max(deltas))
        bins = np.arange(low - .5 * bin_size, high + bin_size, bin_size)
        n, bins = np.histogram(deltas, bins)
        bin_centers = (bins[:-1] + bins[1:]) / 2
        popt, pcov = curve_fit(gauss,
                               bin_centers,
                               n,
                               p0=[.15, np.mean(deltas),
                                   np.std(deltas)])
        plot.histogram(n, bins)
        plot.plot(bin_centers,
                  gauss(bin_centers, *popt),
                  mark=None,
                  linestyle='gray')
    if kwargs.keys():
        plot.set_title('Tijdtest ' + kwargs[kwargs.keys()[0]])
    plot.set_label(r'$\mu={1:.1f}$, $\sigma={2:.1f}$'.format(*popt))
    plot.set_xlabel(r'Time difference [ns]')
    plot.set_ylabel(r'Counts')
    plot.set_xlimits(low, high)
    plot.set_ylimits(min=0.)

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

    print 'tt_analyse: Plotted histogram'
Example #11
0
def plot_delta_time(ids, **kwargs):
    """ Plot delta versus the timestamps

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

    # Begin Figure
    plot = Plot()
    for index, id in enumerate(ids):
        ext_timestamps, deltas = get(id)
        # daystamps = (np.array(ext_timestamps) - min(ext_timestamps)) / 864e11
        daystamps = (np.array(ext_timestamps) -
                     min(ext_timestamps)) / 864e11 * 24 * 60
        end = min(len(daystamps), 6000)
        skip = 3
        plot.plot(daystamps[:end:skip],
                  deltas[:end:skip],
                  mark=None,
                  linestyle='very thin')

    if kwargs.keys():
        plot.set_title('Tijdtest delta time' + kwargs[kwargs.keys()[0]])
    # plot.set_xlabel(r'Time in test [days]')
    plot.set_xlabel(r'Time in test [minutes]')
    plot.set_ylabel(r'$\Delta$ t (swap - reference) [\si{\ns}]')
    plot.set_xlimits(0, daystamps[:end][-1])
    plot.set_ylimits(-50, 50)
    # plot.set_ylimits(-175, 175)

    plot.set_axis_options('line join=round')

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

    print 'tt_analyse: Plotted delta vs time'
Example #12
0
def plot_ns_histogram(ids, **kwargs):
    """ Plot a histogram of the nanosecond part of the ext_timestamps

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

    # Define Bins
    low = 0
    high = int(1e9)
    bin_size = 5e6  # 1e7 = 10ms, 1e6 = 1 ms, 1e3 = 1 us
    bins = np.arange(low, high + bin_size, bin_size)

    # Begin Figure
    plot = Plot()
    for id in ids:
        ext_timestamps, deltas = get(id)
        nanoseconds = nanoseconds_from_ext_timestamp(ext_timestamps)
        n, bins = np.histogram(nanoseconds, bins, normed=1)
        plot.histogram(n, bins)

    if kwargs.keys():
        plot.set_title('Tijdtest ' + kwargs[kwargs.keys()[0]])
    plot.set_xlabel(r'nanosecond part of timestamp [ns]')
    plot.set_ylabel(r'p')
    plot.set_xlimits(0, 1e9)
    plot.set_ylimits(.95e-9, 1.05e-9)

    # Save Figure
    if len(ids) == 1:
        name = 'nanoseconds_histogram/tt_nanos_hist_%03d' % ids[0]
    elif kwargs.keys():
        name = 'nanoseconds_histogram/tt_nanos_hist_' + kwargs[kwargs.keys()
                                                               [0]]
    try:
        plot.save_as_pdf(PLOT_PATH + name)
    except:
        print 'tt_analyse: Failed ns hist for %s' % str(ids)

    print 'tt_analyse: Plotted histogram'
Example #13
0
def plot_offset_distribution(ids, **kwargs):
    """Offset distribution"""

    # Begin Figure
    plot = Plot()
    offsets = [
        np.average([x for x in get(id)[1] if abs(x) < 100]) for id in ids
    ]
    bins = np.arange(-70, 70, 2)
    n, bins = np.histogram(offsets, bins)
    plot.histogram(n, bins)

    bin_centers = (bins[:-1] + bins[1:]) / 2
    popt, pcov = curve_fit(gauss,
                           bin_centers,
                           n,
                           p0=[1., np.mean(offsets),
                               np.std(offsets)])
    plot.plot(bin_centers,
              gauss(bin_centers, *popt),
              mark=None,
              linestyle='gray')

    if kwargs.keys():
        plot.set_title('Tijdtest offset distribution ' +
                       kwargs[kwargs.keys()[0]])
    plot.set_label(r'$\mu={1:.1f}$, $\sigma={2:.1f}$'.format(*popt))
    plot.set_xlabel(r'Offset [\si{\nano\second}]')
    plot.set_ylabel(r'Counts')
    plot.set_ylimits(min=0)

    # Save Figure
    name = 'box/tt_offset_distribution'
    if kwargs.keys():
        name += kwargs[kwargs.keys()[0]]
    plot.save_as_pdf(PLOT_PATH + name)

    print 'tt_analyse: Plotted offsets'
Example #14
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 #15
0
def plot_traces(event, station):
    s = Station(station)
    plot = Plot()
    traces = s.event_trace(event['timestamp'], event['nanoseconds'], raw=True)
    for j, trace in enumerate(traces):
        t = arange(0, (2.5 * len(traces[0])), 2.5)
        plot.plot(t, trace, mark=None, linestyle=COLORS[j])
    n_peaks = event['n_peaks']
    plot.set_title('%d - %d' % (station, event['ext_timestamp']))
    plot.set_label('%d ' * 4 % tuple(n_peak for n_peak in n_peaks))
    plot.set_xlabel('t [\si{n\second}]')
    plot.set_ylabel('Signal strength')
    plot.set_xlimits(min=0, max=2.5 * len(traces[0]))
    plot.set_ylimits(min=150, max=500)  # max=2 ** 12
    plot.draw_horizontal_line(253, linestyle='gray')
    plot.draw_horizontal_line(323, linestyle='gray')
    plot.draw_horizontal_line(event['baseline'][0] + 20, linestyle='thin,gray')
    plot.draw_horizontal_line(event['baseline'][1] + 20,
                              linestyle='thin,red!40!black')
    plot.draw_horizontal_line(event['baseline'][2] + 20,
                              linestyle='thin,green!40!black')
    plot.draw_horizontal_line(event['baseline'][3] + 20,
                              linestyle='thin,blue!40!black')
    plot.save_as_pdf('traces_%d_%d' % (station, event['ext_timestamp']))
def plot_angles(data):
    """Make azimuth and zenith plots to compare the results"""

    rec = data.root.reconstructions

    zenhis = rec.col('reconstructed_theta')
    zenkas = rec.col('reference_theta')
    azihis = rec.col('reconstructed_phi')
    azikas = rec.col('reference_phi')
    min_n = rec.col('min_n134')

    high_zenith = (zenhis > .2) & (zenkas > .2)

    for minn in [0, 1, 2, 4]:
        filter = (min_n > minn)

        azicounts, x, y = np.histogram2d(azihis.compress(high_zenith & filter),
                                         azikas.compress(high_zenith & filter),
                                         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_\textrm{HiSPARC}$ [\si{\degree}]')
        plota.set_ylabel(r'$\phi_\textrm{KASCADE}$ [\si{\degree}]')
        plota.set_xticks([-180, -90, 0, 90, 180])
        plota.set_yticks([-180, -90, 0, 90, 180])
        plota.save_as_pdf('azimuth_his_kas_minn%d' % minn)

        zencounts, x, y = np.histogram2d(zenhis.compress(filter),
                                         zenkas.compress(filter),
                                         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_\textrm{HiSPARC}$ [\si{\degree}]')
        plotz.set_ylabel(r'$\theta_\textrm{KASCADE}$ [\si{\degree}]')
        plotz.set_xticks([0, 15, 30, 45, 60])
        plotz.set_yticks([0, 15, 30, 45, 60])
        plotz.save_as_pdf('zenith_his_kas_minn%d' % minn)

        distances = angle_between(zenhis.compress(filter),
                                  azihis.compress(filter),
                                  zenkas.compress(filter),
                                  azikas.compress(filter))
        counts, bins = np.histogram(distances, bins=linspace(0, pi, 100))
        plotd = Plot()
        plotd.histogram(counts, degrees(bins))
        sigma = degrees(scoreatpercentile(distances, 67))
        plotd.set_title(r'$N_\textrm{MIP} \geq %d$' % minn)
        plotd.set_label(r'67\%% within \SI{%.1f}{\degree}' % sigma)
        # plotd.set_title('Distance between reconstructed angles for station events')
        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_his_kas_minn%d' % minn)
Example #17
0
def plot_reconstruction_accuracy():

    combinations = ['~d1 | ~d2 | ~d3 | ~d4', 'd1 & d2 & d3 & d4']
    station_path = '/cluster_simulations/station_%d'
    with tables.open_file(RESULT_PATH, 'r') as data:
        cluster = data.root.coincidences._v_attrs.cluster
        coincidences = data.root.coincidences.coincidences
        c_recs = data.root.coincidences.reconstructions
        graph = Plot()
        da = angle_between(c_recs.col('zenith'), c_recs.col('azimuth'),
                           c_recs.col('reference_zenith'),
                           c_recs.col('reference_azimuth'))
        ids = c_recs.col('id')
        N = coincidences.read_coordinates(ids, field='N')
        for k, filter in enumerate([N == 3, N > 3]):
            n, bins = histogram(da.compress(filter), bins=arange(0, pi, .1))
            graph.histogram(n, bins, linestyle=GRAYS[k % len(GRAYS)])

        failed = len(coincidences.get_where_list('N >= 3')) - c_recs.nrows
        graph.set_ylimits(min=0)
        graph.set_xlimits(min=0, max=pi)
        graph.set_ylabel('Count')
        graph.set_xlabel('Angle between input and reconstruction [rad]')
        graph.set_title('Coincidences')
        graph.set_label('Failed to reconstruct %d events' % failed)
        graph.save_as_pdf('coincidences_alt')

        for station in cluster.stations:
            station_group = data.get_node(station_path % station.number)
            recs = station_group.reconstructions
            rows = coincidences.get_where_list('s%d == True' % station.number)
            reference_azimuth = coincidences.read_coordinates(rows,
                                                              field='azimuth')
            reference_zenith = coincidences.read_coordinates(rows,
                                                             field='zenith')
            graph = Plot()
            for k, combo in enumerate(combinations):
                selected_reconstructions = recs.read_where(combo)
                filtered_azimuth = array([
                    reference_azimuth[i]
                    for i in selected_reconstructions['id']
                ])
                filtered_zenith = array([
                    reference_zenith[i] for i in selected_reconstructions['id']
                ])
                azimuth = selected_reconstructions['azimuth']
                zenith = selected_reconstructions['zenith']

                da = angle_between(zenith, azimuth, filtered_zenith,
                                   filtered_azimuth)
                n, bins = histogram(da, bins=arange(0, pi, .1))
                graph.histogram(n, bins, linestyle=GRAYS[k % len(GRAYS)])
            failed = station_group.events.nrows - recs.nrows

            graph.set_ylimits(min=0)
            graph.set_xlimits(min=0, max=pi)
            graph.set_ylabel('Count')
            graph.set_xlabel('Angle between input and reconstruction [rad]')
            graph.set_title('Station: %d' % station.number)
            graph.set_label('Failed to reconstruct %d events' % failed)
            graph.save_as_pdf('s_%d' % station.number)
Example #18
0
import tables

from numpy import degrees, histogram, isnan

from artist import Plot

from sapphire import ReconstructESDEvents

with tables.open_file('/Users/arne/Datastore/esd/2013/10/2013_10_28.h5',
                      'r') as data:
    for s in [501, 502, 503, 504, 505, 506, 508, 509]:
        rec = ReconstructESDEvents(data,
                                   '/hisparc/cluster_amsterdam/station_%d' % s,
                                   s)
        rec.reconstruct_directions(detector_ids=[0, 2, 3])
        azimuths = [
            degrees(a) for a, z in zip(rec.phi, rec.theta)
            if degrees(z) > 10 and not isnan(a)
        ]
        n, bins = histogram(azimuths, bins=range(-180, 190, 10))
        graph = Plot()
        graph.histogram(n, bins)
        graph.set_title('Station %d' % s)
        graph.set_xlabel('Azimuth')
        graph.set_xlimits(-180, 180)
        graph.set_ylimits(min=0)
        graph.save_as_pdf('azimuths_123_s%d' % s)
Example #19
0
def determine_station_timing_offsets(data):
    """Determine the offsets between the stations."""

    c = .3

    ref_station_number = 501
    ref_d_off = DETECTOR_OFFSETS[ref_station_number]
    ref_events = data.root.hisparc.cluster_amsterdam.station_501.events
    ref_t = array([
        where(
            ref_events.col('t1') == -999, 9000,
            ref_events.col('t1') - ref_d_off[0]),
        where(
            ref_events.col('t2') == -999, 9000,
            ref_events.col('t2') - ref_d_off[1]),
        where(
            ref_events.col('t3') == -999, 9000,
            ref_events.col('t3') - ref_d_off[2]),
        where(
            ref_events.col('t4') == -999, 9000,
            ref_events.col('t4') - ref_d_off[3])
    ])
    ref_min_t = ref_t.min(axis=0)

    station_number = 510
    d_off = DETECTOR_OFFSETS[station_number]
    events = data.root.hisparc.cluster_amsterdam.station_510.events
    t = array([
        where(events.col('t1') == -999, 90000,
              events.col('t1') - d_off[0]),
        where(events.col('t2') == -999, 90000,
              events.col('t2') - d_off[1]),
        where(events.col('t3') == -999, 90000,
              events.col('t3') - d_off[2]),
        where(events.col('t4') == -999, 90000,
              events.col('t4') - d_off[3])
    ])
    min_t = t.min(axis=0)

    dt = []
    for event, ref_event in itertools.izip(events, ref_events):
        if (ref_event['t_trigger'] in ERR or event['t_trigger'] in ERR):
            dt.append(nan)
            continue
        dt.append((int(event['ext_timestamp']) -
                   int(ref_event['ext_timestamp'])) -
                  (event['t_trigger'] - ref_event['t_trigger']))

    dt = array(dt)
    dt = dt + (min_t - ref_min_t)

    plot = Plot()
    bins = linspace(-50, 50, 100)
    y, bins = histogram(dt, bins=bins)
    plot.histogram(y, bins)

    x = (bins[:-1] + bins[1:]) / 2
    try:
        popt, pcov = curve_fit(gauss, x, y, p0=(len(dt), 0., 10))
        station_offset = popt[1]
        plot.draw_vertical_line(station_offset)
        bins = linspace(-50, 50, 1000)
        plot.plot(bins, gauss(bins, *popt), mark=None, linestyle='gray')
    except RuntimeError:
        station_offset = 0.
    print station_offset

    plot.set_title('Time difference, station 510-501')
    plot.set_xlimits(-50, 50)
    plot.set_ylimits(min=0)
    plot.set_xlabel('$\Delta t$ [ns]')
    plot.set_ylabel('Counts')
    plot.save_as_pdf('station_offsets')
Example #20
0
def determine_station_timing_offsets(d, data):
    # First determine detector offsets for each station
    offsets = {}
    for s in [501, 510]:
        station_group = data.get_node('/hisparc/cluster_amsterdam/station_%d' % s)
        offsets[s] = determine_detector_timing_offsets2(station_group.events)

    ref_station = 501
    ref_d_off = offsets[ref_station]

    station = 510

    cq = CoincidenceQuery(data, '/coincidences')
    dt = []
    d_off = offsets[station]
    stations = [ref_station, station]
    coincidences = cq.all(stations)
    c_events = cq.events_from_stations(coincidences, stations)
    for events in c_events:
        # Filter for possibility of same station twice in coincidence
        if len(events) is not 2:
            continue
        if events[0][0] == ref_station:
            ref_event = events[0][1]
            event = events[1][1]
        else:
            ref_event = events[1][1]
            event = events[0][1]

        try:
            ref_t = min([ref_event['t%d' % (i + 1)] - ref_d_off[i]
                         for i in range(4)
                         if ref_event['t%d' % (i + 1)] not in ERR])
            t = min([event['t%d' % (i + 1)] - d_off[i]
                     for i in range(4)
                     if event['t%d' % (i + 1)] not in ERR])
        except ValueError:
            continue
        if (ref_event['t_trigger'] in ERR or event['t_trigger'] in ERR):
            continue
        dt.append((int(event['ext_timestamp']) -
                   int(ref_event['ext_timestamp'])) -
                  (event['t_trigger'] - ref_event['t_trigger']) +
                  (t - ref_t))

    bins = linspace(-150, 150, 200)
    y, bins = histogram(dt, bins=bins)
    x = (bins[:-1] + bins[1:]) / 2
    try:
        popt, pcov = curve_fit(gauss, x, y, p0=(len(dt), 0., 50))
        station_offset = popt[1]
    except RuntimeError:
        station_offset = 0.
    offsets[station] = [detector_offset + station_offset
                        for detector_offset in offsets[station]]
    print 'Station 501 - 510: %f (%f)' % (popt[1], popt[2])
    graph = Plot()
    graph.histogram(y, bins)
    graph.set_title('Time difference, between station 501-510')
    graph.set_label('%s' % d.replace('_', ' '))
    graph.set_xlimits(-150, 150)
    graph.set_ylimits(min=0)
    graph.set_xlabel('$\Delta t$')
    graph.set_ylabel('Counts')
    graph.save_as_pdf('%s' % d)
Example #21
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')