Exemple #1
0
def getSpectData(datapath,
                 run,
                 event_limit,
                 bin_size=10,
                 trigger_type=1,
                 group_fft=False):
    '''
    This function obtains the data for a spectrogram.

    Parameters
    ----------
    datapath : str
        The path to the data where the runs are stored.  This is the same as the input to
        the reader class.
    run : int
        The run number to be loaded.
    event_limit : int
        This limits the number of events to load.  Loads from beginning of run to end, so
        reducing this speeds up the calculation by cutting off the later portions of the
        run.
    bin_size : int
        This is the number of seconds to include in each time slice of the spectrogram.  The
        average spectra will be computed per bin.  Default is 10.
    trigger_type : int
        This is the trigger type of events included in the spectrogram.  The default is 1.
    group_fft : bool
        This enables the fft calculation to be performed simultaneously for all events, rather
        than per waveform as they are loaded in.  This may be faster but requires more memory.
        Default is False.

    Returns
    -------
    reader : examples.beacon_data_reader.Reader
        This is the reader for the selected run.
    freqs : numpy.ndarray of floats
        This is the list of frequencies for corresponding to the y-axis of the spectrogram data.
    spectra_dbish_binned : dict
        This is the data corresponding to the spectrogram.  Each entry in the dictionary contains
        the spectrogram data for a particular channel.  This are returned in dB-like units.  I.e.
        they are calculated as if the waveforms were in volts, but in reality the waveforms are in
        adu.  Some there is some offset from these values to true dB units.
    '''
    reader = Reader(datapath, run)
    N = reader.N() if event_limit == None else min(reader.N(),
                                                   abs(event_limit))

    print('\nReader:')
    d = tools.interpret.getReaderDict(reader)
    pprint(d)
    print('\nHeader:')
    h = tools.interpret.getHeaderDict(reader)
    pprint(h)
    print('\nStatus:')
    s = tools.interpret.getStatusDict(reader)
    pprint(s)

    if reader.N() == 0:
        print('No events found in the selected run.')
    else:

        def rfftWrapper(channel, waveform_times, *args, **kwargs):
            spec = numpy.fft.rfft(*args, **kwargs)
            real_power_multiplier = 2.0 * numpy.ones_like(
                spec
            )  #The factor of 2 because rfft lost half of the power except for dc and Nyquist bins (handled below).
            if len(numpy.shape(spec)) != 1:
                real_power_multiplier[:, [0, -1]] = 1.0
            else:
                real_power_multiplier[[0, -1]] = 1.0
            spec_dbish = 10.0 * numpy.log10(
                real_power_multiplier * spec * numpy.conj(spec) /
                len(waveform_times)
            )  #10 because doing power in log.  Dividing by N to match monutau.
            return channel, spec_dbish

        waveform_times = reader.t()
        freq_step = 1.0 / (len(waveform_times) *
                           (numpy.diff(waveform_times)[0] * 1e-9))
        freqs = numpy.arange(len(waveform_times) // 2 + 1) * freq_step
        freq_nyquist = 1 / (2.0 * numpy.diff(waveform_times)[0] * 1e-9)

        if group_fft == True:
            waveforms = {}
        spectra_dbish = {}
        readout_times = []

        for channel in range(8):
            if group_fft == True:
                waveforms['ch%i' % channel] = numpy.zeros(
                    (N, reader.header().buffer_length), dtype=int)
            spectra_dbish['ch%i' % channel] = numpy.zeros(
                (N, reader.header().buffer_length // 2 + 1), dtype=float)

        print('')

        for event_index, eventid in enumerate(
                range(N if event_limit == None else event_limit)):
            sys.stdout.write('\r(%i/%i)' % (eventid + 1, N))
            sys.stdout.flush()
            reader.setEntry(eventid)
            readout_times.append(getattr(reader.header(), 'readout_time'))
            for channel in range(8):
                if group_fft == True:
                    waveforms['ch%i' %
                              channel][event_index] = reader.wf(channel)
                else:
                    spectra_dbish['ch%i' % channel][event_index] = rfftWrapper(
                        'ch%i' % channel, waveform_times,
                        reader.wf(channel))[1]
        if group_fft == True:
            with concurrent.futures.ThreadPoolExecutor(
                    max_workers=cpu_count()) as executor:
                thread_results = []
                for channel in range(8):
                    thread_results.append(
                        executor.submit(rfftWrapper, 'ch%i' % channel,
                                        waveform_times,
                                        waveforms['ch%i' % channel]))

            print('Weaving threads')
            sys.stdout.flush()

            for index, future in enumerate(
                    concurrent.futures.as_completed(thread_results)):
                spectra_dbish[future.result()[0]] = future.result()[1]
                print('%i/8 Channel FFTs Completed' % (index + 1))

        bin_edges = numpy.arange(min(readout_times),
                                 max(readout_times) + bin_size, bin_size)
        bin_L_2d = numpy.tile(bin_edges[:-1], (len(readout_times), 1))
        bin_R_2d = numpy.tile(
            numpy.roll(bin_edges, -1)[:-1], (len(readout_times), 1))
        readout_times_2d = numpy.tile(readout_times, (len(bin_edges) - 1, 1)).T

        cut_2d = numpy.logical_and(readout_times_2d >= bin_L_2d,
                                   readout_times_2d < bin_R_2d).T

        del bin_L_2d
        del bin_R_2d
        del readout_times_2d

        spectra_dbish_binned = {}
        for channel in range(8):
            spectra_dbish_binned['ch%i' % channel] = numpy.zeros(
                (len(freqs), len(bin_edges) - 1))
            for index, cut in enumerate(cut_2d):
                spectra_dbish_binned['ch%i' % channel][:, index] = numpy.mean(
                    spectra_dbish['ch%i' % channel][cut], axis=0)
            spectra_dbish_binned['ch%i' % channel] = numpy.flipud(
                numpy.ma.array(spectra_dbish_binned['ch%i' % channel],
                               mask=numpy.isnan(
                                   spectra_dbish_binned['ch%i' % channel])))

        return reader, freqs, spectra_dbish_binned
Exemple #2
0
    for day_label in list(clean_days.keys()):
        flagged_runs[day_label] = []
    flagged_runs_cfg = {}
    for day_label in list(clean_days.keys()):
        flagged_runs_cfg[day_label] = []


    min_ts = []
    max_ts = []
    run_ids = []
    print('')
    for run_index,run_label in enumerate(run_labels):
        if 'run' in run_label:
            run = int(run_label.split('run')[-1])
            reader = Reader(datapath,run)
            if reader.N() == 0:
                continue

            sys.stdout.write('\r%i/%i'%(run_index+1,len(run_labels)))
            sys.stdout.flush()
            min_t = reader.head_tree.GetMinimum('readout_time')#utc.localize(datetime.fromtimestamp(reader.head_tree.GetMinimum('readout_time')))
            max_t = reader.head_tree.GetMaximum('readout_time')#utc.localize(datetime.fromtimestamp(reader.head_tree.GetMaximum('readout_time')))
            min_ts.append(min_t)
            max_ts.append(max_t)
            run_ids.append(run)

            for day_label in list(clean_days.keys()):
                cfg = numpy.array([],dtype=int)

                #Leading end in window.
                if numpy.any(numpy.logical_and(min_t > clean_days[day_label]['starts'],min_t < clean_days[day_label]['ends'])):
Exemple #3
0
        crit_freq_high_pass_MHz = 65
        high_pass_filter_order = 12

        apply_phase_response = True
        hilbert = False

        #Load antenna position information from the info.py script
        origin = info.loadAntennaZeroLocation()  #Assuming default_deploy
        antennas_physical, antennas_phase_hpol, antennas_phase_vpol = info.loadAntennaLocationsENU(
        )  #Assuming default_deploy

        #Create a Reader object for the specific run.
        reader = Reader(datapath, run)
        print('The run associated with this reader is:')
        print(reader.run)
        print('This run has %i events' % (reader.N()))

        #Create a TimeDelayCalculator object for the specified run. Note that if the above parameters haven't been change
        tdc_raw = TimeDelayCalculator(reader,
                                      final_corr_length=final_corr_length,
                                      crit_freq_low_pass_MHz=None,
                                      crit_freq_high_pass_MHz=None,
                                      low_pass_filter_order=None,
                                      high_pass_filter_order=None,
                                      plot_filters=False,
                                      apply_phase_response=False)
        #Plot raw event
        tdc_raw.plotEvent(eventids[0],
                          channels=[0, 1, 2, 3, 4, 5, 6, 7],
                          apply_filter=False,
                          hilbert=False,
    printCredit()
    # If your data is elsewhere, pass it as an argument
    datapath = sys.argv[1] if len(sys.argv) > 1 else os.environ['BEACON_DATA']
    run = 1509  #Selects which run to examine
    eventids = numpy.array(
        [2401])  #numpy.array([90652,90674,90718,90766,90792,91019,91310])

    for eventid in eventids:
        #eventid = None#numpy.array([1,2,3]) #If None then a random event id is selected. Can be array of eventids as well.

        reader = Reader(datapath, run)
        verbose = True

        # this is a random event
        if type(eventid) == None:
            eventid = numpy.array([numpy.random.randint(reader.N())])
        elif type(eventid) == int:
            eventid = numpy.array([eventid])
        elif type(eventid) == list:
            eventid = numpy.array(eventid)
        elif type(eventid) == numpy.ndarray:
            pass
        else:
            print('event id not set in valid way, setting to random')
            eventid = numpy.array([numpy.random.randint(reader.N())])

        eventid = [2401]
        for eid in eventid:
            reader.setEntry(eid)

            ## dump the headers and status, just to show they're there
Exemple #5
0
        'all'
    )  #Uncomment this if you want figures to be closed before this is run (helps if running multiple times in a row to avoid plot congestion).
    '''
    Here we pick a run, create a reader, get the eventids, get which eventids correspond to which trigger type,
    then plot 1 event from each trigger type.
    '''
    if True:
        plot_N_per_type = 2  #The number of events to plot her trigger type.  Meant to demonstrate what looping over events might look like.

        #Get run and events you want to look at.
        run = 1650
        #Create a Reader object for the specific run.
        reader = Reader(datapath, run)
        print('The run associated with this reader is:')
        print(reader.run)
        print('This run has %i events' % (reader.N()))
        eventids = numpy.arange(reader.N())
        trigger_type = loadTriggerTypes(reader)

        times = reader.t()  #The times of a waveform in ns.  Not upsampled.

        for trig_type in [1, 2, 3]:
            print('Plotting %i eventids of trig type %i' %
                  (plot_N_per_type, trig_type))
            trig_eventids = eventids[
                trigger_type == trig_type]  #All eventids of this trig type
            trig_eventids = numpy.sort(
                numpy.random.choice(trig_eventids, 2)
            )  #Randomly choosing a subset and sorting for faster loading of events

            for eventid in trig_eventids: