Beispiel #1
0
def selection_counts(filename):
    with MWKFile(filename) as f:
        r_codec = f.reverse_codec
        red_code = r_codec['red_selected']
        green_code = r_codec['green_selected']
        blue_code = r_codec['blue_selected']

        red_count = 0
        green_count = 0
        blue_count = 0

        for evt in f.get_events_iter(codes=[red_code, green_code, blue_code]):
            if evt.data:
                if evt.code == red_code:
                    red_count += 1
                elif evt.code == green_code:
                    green_count += 1
                else:
                    assert evt.code == blue_code
                    blue_count += 1

        index = numpy.arange(3)
        pyplot.bar(index, [red_count, green_count, blue_count],
                   0.5,
                   color=['r', 'g', 'b'],
                   align='center')
        pyplot.xticks(index, ['Red', 'Green', 'Blue'])
        pyplot.title('Selection Counts')
        pyplot.show()
Beispiel #2
0
    def setUpClass(cls):
        cls.event_counts = defaultdict(lambda: 0)
        cls.event_times = []

        for evt in cls.file_reader(cls.filename):
            cls.event_counts[evt[0]] += 1
            cls.event_times.append(evt[1])

        cls.event_counts = dict(cls.event_counts)
        cls.event_times = numpy.array(cls.event_times)

        cls.fp = MWKFile(cls.filename)
Beispiel #3
0
    def setUpClass(cls):
        cls.event_counts = defaultdict(lambda: 0)
        cls.event_times = []

        with MWKStream.open_file(cls.filename) as stream:
            for evt in stream:
                cls.event_counts[evt.code] += 1
                cls.event_times.append(evt.time)

        cls.event_counts = dict(cls.event_counts)
        cls.event_times = numpy.array(cls.event_times)

        cls.fp = MWKFile(cls.filename)
Beispiel #4
0
def validate_dots_data(filename):
    with MWKFile(filename) as f:
        num_events = 0
        for e in f.get_events_iter(codes=['#announceStimulus']):
            value = e.value
            if (isinstance(value, dict) and (value['type'] == 'moving_dots')
                    and ('dots' in value)):
                data = numpy.fromstring(value['dots'], numpy.float32)
                assert len(data) == (2 * value['num_dots'])

                x = data[::2]
                y = data[1::2]
                assert (x * x + y * y).max() <= 1.0

                num_events += 1

        assert num_events > 0
        print 'Processed %d events' % num_events
Beispiel #5
0
 def receive(self):
     try:
         with MWKFile(self.filename) as fp:
             evts = fp.get_events()
             self.assertEqual(1, len(evts))
             e = evts[0]
             self.assertEqual(1, e.code)
             self.assertEqual(2, e.time)
             try:
                 return e.data
             except Exception as e:
                 return e
     finally:
         try:
             fp.unindex()
         except mworks.data.IndexingException:
             pass
         os.remove(self.filename)
Beispiel #6
0
def dump_events(filename, photodiode_file, sample_on_file):
    print(filename)

    event_file = MWKFile(filename)
    event_file.open()

    # Variables we'd like to fetch data for
    names = ['trial_start_line',
             'correct_fixation',
             'stimulus_presented',
             'stim_on_time',
             'stim_off_time',
             'stim_on_delay',
             'stimulus_size',
             'fixation_window_size',
             'fixation_point_size_min']
    data = get_events(event_file=event_file, name=names)
    # event_file.close()

    ###########################################################################
    # Create a dict to store output information
    ###########################################################################
    output = {
        'stim_on_time_ms': data[data.name == 'stim_on_time']['data'].values[-1] / 1000.,
        'stim_off_time_ms': data[data.name == 'stim_off_time']['data'].values[-1] / 1000.,
        'stim_on_delay_ms': data[data.name == 'stim_on_delay']['data'].values[-1] / 1000.,
        'stimulus_size_degrees': data[data.name == 'stimulus_size']['data'].values[-1],
        'fixation_window_size_degrees': data[data.name == 'fixation_window_size']['data'].values[-1],
        'fixation_point_size_degrees': data[data.name == 'fixation_point_size_min']['data'].values[-1],
    }

    ###########################################################################
    # Add column in data to indicate whether stimulus was first in trial or not
    ###########################################################################
    data['first_in_trial'] = False
    # Filter data to only get `trial_start_line` and `stimulus_presented` information
    df = data[(data.name == 'trial_start_line') | ((data.name == 'stimulus_presented') & (data.data != -1))]
    # Extract `time` for the first `stimulus_presented` (which is right after `trial_start_line` has been pulsed)
    first_in_trial_times = [df.time.values[i] for i in range(1, len(df))
                            if ((df.name.values[i - 1] == 'trial_start_line') and
                                (df.name.values[i] == 'stimulus_presented'))]
    data['first_in_trial'] = data['time'].apply(lambda x: True if x in first_in_trial_times else False)

    ###########################################################################
    # Extract stimulus presentation order and fixation information
    ###########################################################################
    stimulus_presented_df = data[data.name == 'stimulus_presented'].reset_index(drop=True)
    correct_fixation_df = data[data.name == 'correct_fixation'].reset_index(drop=True)
    # stimulus_presented_df = stimulus_presented_df[:len(correct_fixation_df)]  # If you have one extra stimulus event but not fixation, use this
    assert len(stimulus_presented_df) == len(correct_fixation_df)
    # Drop `empty` data (i.e. -1) before the experiment actually began and after it had already ended
    correct_fixation_df = correct_fixation_df[stimulus_presented_df.data != -1].reset_index(drop=True)
    stimulus_presented_df = stimulus_presented_df[stimulus_presented_df.data != -1].reset_index(drop=True)
    # Add `first_in_trial` info to other data frame too
    correct_fixation_df['first_in_trial'] = stimulus_presented_df['first_in_trial']

    ###########################################################################
    # Add column to indicate order in trial (1 2 3 1 2 3 etc.)
    ###########################################################################
    assert stimulus_presented_df.iloc[0].first_in_trial
    stimulus_presented_df['stimulus_order_in_trial'] = ''
    counter = 1
    for index, row in stimulus_presented_df.iterrows():
        if row['first_in_trial']:
            counter = 1
        stimulus_presented_df.at[index, 'stimulus_order_in_trial'] = counter
        counter += 1
    correct_fixation_df['stimulus_order_in_trial'] = stimulus_presented_df['stimulus_order_in_trial']

    ###########################################################################
    # Read sample on file
    ###########################################################################
    fid = open(sample_on_file, 'r')
    filesize = os.path.getsize(filename)  # in bytes
    num_samples = filesize // 2  # uint16 = 2 bytes
    digital_in = np.fromfile(fid, 'uint16', num_samples)
    fid.close()

    samp_on, = np.nonzero(digital_in[:-1] < digital_in[1:])  # Look for 0->1 transitions
    samp_on = samp_on + 1  # Previous line returns indexes of 0s seen before spikes, but we want indexes of first spikes

    if len(stimulus_presented_df) > len(samp_on):
        print(f'Warning: Trimming MWorks files as ({len(stimulus_presented_df)} > {len(samp_on)})')
        stimulus_presented_df = stimulus_presented_df[:len(samp_on)]
        correct_fixation_df = correct_fixation_df[:len(samp_on)]

    # samp_on = samp_on[:len(correct_fixation_df)]   # If you have one extra stimulus event but not fixation, use this
    assert len(samp_on) == len(stimulus_presented_df)

    ###########################################################################
    # Read photodiode file
    ###########################################################################
    fid = open(photodiode_file, 'r')
    filesize = os.path.getsize(photodiode_file)  # in bytes
    num_samples = filesize // 2  # uint16 = 2 bytes
    v = np.fromfile(fid, 'uint16', num_samples)
    fid.close()

    # Convert to volts (use this if the data file was generated by Recording Controller)
    v = (v - 32768) * 0.0003125

    # Detect rises in the oscillating photodiode signal
    peaks, _ = find_peaks(v, height=0)  # Find all peaks
    peaks = np.asarray([p for p in peaks if v[p] > THRESHOLD])  # Apply threshold
    photodiode_on = np.asarray([min(peaks[(peaks >= s) & (peaks < (s + 100_000))]) for s in samp_on])
Beispiel #7
0
 def setUp(self):
     with warnings.catch_warnings():
         warnings.simplefilter('ignore', RuntimeWarning)
         self.filename = tempfile.mktemp(suffix=self.file_extension)
     self.fp = MWKFile(self.filename)
Beispiel #8
0
 def setUp(self):
     with warnings.catch_warnings():
         warnings.simplefilter('ignore', RuntimeWarning)
         self.filename = os.tempnam() + '.mwk'
     self.fp = MWKFile(self.filename)