Esempio n. 1
0
    def __init__(self, dir_path):
        RecordingExtractor.__init__(self)
        phy_folder = Path(dir_path)

        self.params = read_python(str(phy_folder / 'params.py'))
        datfile = [x for x in phy_folder.iterdir() if x.suffix == '.dat' or x.suffix == '.bin']

        if (phy_folder / 'channel_map_si.npy').is_file():
            channel_map = list(np.squeeze(np.load(phy_folder / 'channel_map_si.npy')))
            assert len(channel_map) == self.params['n_channels_dat']
        elif (phy_folder / 'channel_map.npy').is_file():
            channel_map = list(np.squeeze(np.load(phy_folder / 'channel_map.npy')))
            assert len(channel_map) == self.params['n_channels_dat']
        else:
            channel_map = list(range(self.params['n_channels_dat']))

        BinDatRecordingExtractor.__init__(self, datfile[0], samplerate=float(self.params['sample_rate']),
                                          dtype=self.params['dtype'], numchan=self.params['n_channels_dat'],
                                          recording_channels=list(channel_map))

        if (phy_folder / 'channel_groups.npy').is_file():
            channel_groups = np.load(phy_folder / 'channel_groups.npy')
            assert len(channel_groups) == self.get_num_channels()
            for (ch, cg) in zip(self.get_channel_ids(), channel_groups):
                self.set_channel_property(ch, 'group', cg)

        if (phy_folder / 'channel_positions.npy').is_file():
            channel_locations = np.load(phy_folder / 'channel_positions.npy')
            assert len(channel_locations) == self.get_num_channels()
            for (ch, loc) in zip(self.get_channel_ids(), channel_locations):
                self.set_channel_property(ch, 'location', loc)
Esempio n. 2
0
    def __init__(self, file_path):
        # load params file related to the given shybrid recording
        assert self.installed, self.installation_mesg
        RecordingExtractor.__init__(self)
        params = sbio.get_params(file_path)['data']

        # create a shybrid probe object
        probe = sbprb.Probe(params['probe'])
        nb_channels = probe.total_nb_channels

        # translate the byte ordering
        # TODO still ambiguous, shybrid should assume time_axis=1, since spike interface makes an assumption on the byte ordering
        byte_order = params['order']
        if byte_order == 'C':
            time_axis = 1
        elif byte_order == 'F':
            time_axis = 0

        # piggyback on binary data recording extractor
        recording = BinDatRecordingExtractor(file_path,
                                             params['fs'],
                                             nb_channels,
                                             params['dtype'],
                                             time_axis=time_axis)

        # load probe file
        self._recording = load_probe_file(recording, params['probe'])
        self._kwargs = {'file_path': str(Path(file_path).absolute())}
Esempio n. 3
0
 def __init__(self, recording, chunk_size=None, save_path=None):
     RecordingExtractor.__init__(self)  # init tmp folder before constructing BinDatRecordingExtractor
     tmp_folder = self.get_tmp_folder()
     self._recording = recording
     if save_path is None:
         self._is_tmp = True
         self._tmp_file = tempfile.NamedTemporaryFile(suffix=".dat", dir=tmp_folder).name
     else:
         save_path = Path(save_path)
         if save_path.suffix != '.dat' and save_path.suffix != '.bin':
             save_path = save_path.with_suffix('.dat')
         if not save_path.parent.is_dir():
             os.makedirs(save_path.parent)
         self._is_tmp = False
         self._tmp_file = save_path
     self._dtype = recording.get_dtype()
     recording.write_to_binary_dat_format(save_path=self._tmp_file, dtype=self._dtype, chunk_size=chunk_size)
     # keep track of filter status when dumping
     self.is_filtered = self._recording.is_filtered
     BinDatRecordingExtractor.__init__(self, self._tmp_file, numchan=recording.get_num_channels(),
                                       recording_channels=recording.get_channel_ids(),
                                       sampling_frequency=recording.get_sampling_frequency(),
                                       dtype=self._dtype, is_filtered=self.is_filtered)
     # keep BinDatRecording kwargs
     self._bindat_kwargs = deepcopy(self._kwargs)
     self.set_tmp_folder(tmp_folder)
     self.copy_channel_properties(recording)
     self._kwargs = {'recording': recording, 'chunk_size': chunk_size}
Esempio n. 4
0
    def __init__(self, recording, threshold=None, seed=0):
        if not isinstance(recording, RecordingExtractor):
            raise ValueError("'recording' must be a RecordingExtractor")
        self._recording = recording
        random_data = self._get_random_data_for_scaling(seed=seed).ravel()
        q = np.quantile(random_data, [0.001, 0.5, 1 - 0.001])
        if 2 * q[1] - q[0] - q[2] < 2 * np.min([q[1] - q[0], q[2] - q[1]]):
            print('Warning, narrow signal range suggests artefact-free data.')
        self._median = q[1]
        if threshold is None:
            if np.abs(q[1] - q[0]) > np.abs(q[1] - q[2]):
                self._threshold = q[0]
                self._lower = True
            else:
                self._threshold = q[2]
                self._lower = False
        else:
            self._threshold = threshold
            if q[1] - threshold < 0:
                self._lower = False
            else:
                self._lower = True
        RecordingExtractor.__init__(self)
        self.copy_channel_properties(recording=self._recording)

        self._kwargs = {
            'recording': recording.make_serialized_dict(),
            'threshold': threshold,
            'seed': seed
        }
Esempio n. 5
0
 def __init__(self, recording_path=None):
     RecordingExtractor.__init__(self)
     self._recording_path = recording_path
     self._fs = None
     self._positions = None
     self._recordings = None
     self._initialize()
    def __init__(self, folder_path):
        RecordingExtractor.__init__(self)
        phy_folder = Path(folder_path)

        self.params = read_python(str(phy_folder / 'params.py'))
        datfile = [x for x in phy_folder.iterdir() if x.suffix == '.dat' or x.suffix == '.bin']

        if (phy_folder / 'channel_map_si.npy').is_file():
            channel_map = list(np.squeeze(np.load(phy_folder / 'channel_map_si.npy')))
            assert len(channel_map) == self.params['n_channels_dat']
        elif (phy_folder / 'channel_map.npy').is_file():
            channel_map = list(np.squeeze(np.load(phy_folder / 'channel_map.npy')))
            assert len(channel_map) == self.params['n_channels_dat']
        else:
            channel_map = list(range(self.params['n_channels_dat']))

        BinDatRecordingExtractor.__init__(self, datfile[0], sampling_frequency=float(self.params['sample_rate']),
                                          dtype=self.params['dtype'], numchan=self.params['n_channels_dat'],
                                          recording_channels=list(channel_map))

        if (phy_folder / 'channel_groups.npy').is_file():
            channel_groups = np.load(phy_folder / 'channel_groups.npy')
            assert len(channel_groups) == self.get_num_channels()
            self.set_channel_groups(channel_groups)

        if (phy_folder / 'channel_positions.npy').is_file():
            channel_locations = np.load(phy_folder / 'channel_positions.npy')
            assert len(channel_locations) == self.get_num_channels()
            self.set_channel_locations(channel_locations)

        self._kwargs = {'folder_path': str(Path(folder_path).absolute())}
    def __init__(self, npx_file, x_pitch=None, y_pitch=None):
        RecordingExtractor.__init__(self)
        self._npxfile = Path(npx_file)
        numchan = 385
        dtype = 'int16'
        root = str(self._npxfile.stem).split('.')[0]
        # find metafile in same folder
        metafile = [
            x for x in self._npxfile.parent.iterdir()
            if 'meta' in str(x) and root in str(x) and 'ap' in str(x)
        ]
        if len(metafile) == 0:
            raise Exception(
                "'meta' file for ap traces should be in the same folder.")
        else:
            metafile = metafile[0]
        tot_chan, ap_chan, samplerate, locations = _parse_spikeglx_metafile(
            metafile, x_pitch, y_pitch)
        frames_first = True
        self._timeseries = read_binary(self._npxfile,
                                       tot_chan,
                                       dtype,
                                       frames_first,
                                       offset=0)
        self._samplerate = float(samplerate)

        if ap_chan < tot_chan:
            self._timeseries = self._timeseries[:ap_chan]
        self._channels = list(range(self._timeseries.shape[0]))

        if len(locations) > 0:
            for m in range(self._timeseries.shape[0]):
                self.set_channel_property(m, 'location', locations[m])
def import_sorting(*, feed: kp.Feed, workspace_name: str,
                   recording: se.RecordingExtractor,
                   sorting: se.SortingExtractor, recording_id: str,
                   sorting_label: str):
    sorting_id = 'S-' + random_id()
    x = {
        'sortingId':
        sorting_id,
        'sortingLabel':
        sorting_label,
        'sortingPath':
        ka.store_object(sorting.object(), basename=f'{sorting_label}.json'),
        'sortingObject':
        sorting.object(),
        'recordingId':
        recording_id,
        'recordingPath':
        ka.store_object(recording.object(), basename=f'{recording_id}.json'),
        'recordingObject':
        recording.object(),
        'description':
        f'Imported from Python: {sorting_label}'
    }
    sortings_subfeed = feed.get_subfeed(
        dict(workspaceName=workspace_name, key='sortings'))
    _import_le_sorting(sortings_subfeed, x)
    return x
Esempio n. 9
0
 def __init__(self, recording_file):
     RecordingExtractor.__init__(self)
     self._recording_file = recording_file
     self._rf, self._nFrames, self._samplingRate, self._nRecCh, self._chIndices, self._file_format, self._signalInv, self._positions, self._read_function = openBiocamFile(
         self._recording_file)
     for m in range(self._nRecCh):
         self.setChannelProperty(m, 'location', self._positions[m])
Esempio n. 10
0
    def __init__(self, block_index=None, seg_index=None, **kargs):
        RecordingExtractor.__init__(self)
        _NeoBaseExtractor.__init__(self, block_index=block_index, seg_index=seg_index, **kargs)

        # TODO propose a meachanisim to select the appropriate channel groups
        # in neo one channel group have the same dtype/sampling_rate/group_id
        try:
            # Neo >= 0.9.0
            channel_indexes_list = self.neo_reader.get_group_signal_channel_indexes()
        except AttributeError:
            # Neo < 0.9.0
            channel_indexes_list = self.neo_reader.get_group_channel_indexes()        
        num_chan_group = len(channel_indexes_list)
        assert num_chan_group == 1, 'This file have several channel groups spikeextractors support only one groups'

        # spikeextractor for units to be uV implicitly
        # check that units are V, mV or uV
        # otherwise raise error
        # @alessio @cole : this can be a problem in extractor evrything is base
        #                     on the fact that the get_traces() give microVolt
        #                     some file don't have units
        #                     do we allow this ?
        units = self.neo_reader.header['signal_channels']['units']
        assert np.all(np.isin(units, ['V', 'mV', 'uV'])), 'Signal units no Volt compatible'
        self.additional_gain = np.ones(units.size, dtype='float')
        self.additional_gain[units == 'V'] = 1e6
        self.additional_gain[units == 'mV'] = 1e3
        self.additional_gain[units == 'uV'] = 1.
        self.additional_gain = self.additional_gain.reshape(1, -1)
Esempio n. 11
0
 def __init__(self,
              folder_path,
              raw_fname='raw.mda',
              params_fname='params.json',
              geom_fname='geom.csv'):
     dataset_directory = Path(folder_path)
     self._dataset_directory = dataset_directory
     timeseries0 = dataset_directory / raw_fname
     self._dataset_params = read_dataset_params(dataset_directory,
                                                params_fname)
     self._sampling_frequency = self._dataset_params['samplerate'] * 1.0
     self._timeseries_path = os.path.abspath(timeseries0)
     geom0 = dataset_directory / geom_fname
     self._geom_fname = geom0
     self._geom = np.loadtxt(self._geom_fname, delimiter=',', ndmin=2)
     X = DiskReadMda(self._timeseries_path)
     if self._geom.shape[0] != X.N1():
         raise Exception(
             'Incompatible dimensions between geom.csv and timeseries file {} <> {}'
             .format(self._geom.shape[0], X.N1()))
     self._num_channels = X.N1()
     self._num_timepoints = X.N2()
     RecordingExtractor.__init__(self)
     self.set_channel_locations(self._geom)
     self._kwargs = {'folder_path': str(Path(folder_path).absolute())}
Esempio n. 12
0
    def __init__(self, file_path, dtype='float', verbose=False):
        assert HAVE_INTAN, self.installation_mesg
        RecordingExtractor.__init__(self)
        assert Path(file_path).suffix == '.rhs' or Path(file_path).suffix == '.rhd', \
            "Only '.rhd' and '.rhs' files are supported"
        self._recording_file = file_path
        self._recording = pyintan.File(file_path, verbose)
        self._num_frames = len(self._recording.times)
        self._analog_channels = np.array([
            ch for ch in self._recording._anas_chan if all([
                other_ch not in ch['name']
                for other_ch in ['ADC', 'VDD', 'AUX']
            ])
        ])
        self._num_channels = len(self._analog_channels)
        self._channel_ids = list(range(self._num_channels))
        self._fs = float(self._recording.sample_rate.rescale('Hz').magnitude)

        assert dtype in ['float',
                         'uint16'], "'dtype' can be either 'float' or 'uint16'"
        self._dtype = dtype

        if self._dtype == 'uint16':
            for i, ch in enumerate(self._analog_channels):
                self.set_channel_property(i, 'gain', ch['gain'])
                self.set_channel_property(i, 'offset', ch['offset'])

        self._kwargs = {
            'file_path': str(Path(file_path).absolute()),
            'verbose': verbose
        }
    def __init__(self, file_path: PathType):
        assert HAVE_BS4_LXML, self.installation_mesg
        file_path = Path(file_path)
        assert file_path.is_file() and file_path.suffix == '.dat', 'file_path must lead to a .dat file!'

        RecordingExtractor.__init__(self)
        self._recording_file = file_path
        file_path = Path(file_path)
        folder_path = file_path.parent

        xml_files = [f for f in folder_path.iterdir() if f.is_file() if f.suffix == '.xml']
        assert any(xml_files), 'No .xml file found in the folder_path.'
        assert len(xml_files) == 1, 'More than one .xml file found in the folder_path.'
        xml_filepath = xml_files[0]

        with xml_filepath.open('r') as xml_file:
            contents = xml_file.read()
            soup = BeautifulSoup(contents, 'lxml')
            # Normally, this would be a .xml, but there were strange issues
            # in the write_recording method that require it to be a .lxml instead
            # which also requires all capital letters to be removed from the tag names

        n_bits = int(soup.nbits.string)
        dtype = 'int' + str(n_bits)
        numchan_from_file = int(soup.nchannels.string)

        numchan = numchan_from_file
        sampling_frequency = float(soup.samplingrate.string)
        BinDatRecordingExtractor.__init__(self, file_path, sampling_frequency=sampling_frequency,
                                          dtype=dtype, numchan=numchan)

        self._kwargs = {'file_path': str(Path(file_path).absolute())}
Esempio n. 14
0
 def __init__(self, file_path):
     assert self.installed, self.installation_mesg
     file_path = str(file_path)
     RecordingExtractor.__init__(self)
     self._file = nix.File.open(file_path, nix.FileMode.ReadOnly)
     self._load_properties()
     self._kwargs = {'file_path': str(Path(file_path).absolute())}
    def __init__(self,
                 file_path,
                 sampling_frequency,
                 numchan,
                 dtype,
                 recording_channels=None,
                 time_axis=0,
                 geom=None,
                 offset=0,
                 gain=None):
        RecordingExtractor.__init__(self)
        self._datfile = Path(file_path)
        self._time_axis = time_axis
        self._dtype = str(dtype)
        self._timeseries = read_binary(self._datfile, numchan, dtype,
                                       time_axis, offset)
        self._sampling_frequency = float(sampling_frequency)
        self._gain = gain
        self._geom = geom

        if recording_channels is not None:
            assert len(recording_channels) == self._timeseries.shape[0], \
                'Provided recording channels have the wrong length'
            self._channels = recording_channels
        else:
            self._channels = list(range(self._timeseries.shape[0]))

        if geom is not None:
            for m in range(self._timeseries.shape[0]):
                self.set_channel_property(m, 'location', self._geom[m, :])
Esempio n. 16
0
    def __init__(self, dataset_directory, *, download=True):
        ca = _load_required_modules()

        RecordingExtractor.__init__(self)
        self._dataset_directory = dataset_directory
        timeseries0 = dataset_directory + '/raw.mda'
        self._dataset_params = read_dataset_params(dataset_directory)
        self._samplerate = self._dataset_params['samplerate'] * 1.0
        if is_kbucket_url(timeseries0):
            download_needed = is_url(ca.findFile(path=timeseries0))
        else:
            download_needed = is_url(timeseries0)
        if download and download_needed:
            print('Downloading file: ' + timeseries0)
            self._timeseries_path = ca.realizeFile(path=timeseries0)
            print('Done.')
        else:
            self._timeseries_path = ca.findFile(path=timeseries0)
        geom0 = dataset_directory + '/geom.csv'
        self._geom_fname = ca.realizeFile(path=geom0)
        self._geom = np.genfromtxt(self._geom_fname, delimiter=',')
        X = DiskReadMda(self._timeseries_path)
        if self._geom.shape[0] != X.N1():
            raise Exception(
                'Incompatible dimensions between geom.csv and timeseries file {} <> {}'.format(self._geom.shape[0],
                                                                                               X.N1()))
        self._num_channels = X.N1()
        self._num_timepoints = X.N2()
        for m in range(self._num_channels):
            self.setChannelProperty(m, 'location', self._geom[m, :])
    def __init__(self,
                 recording,
                 scale=1.0,
                 median=0.0,
                 q1=0.01,
                 q2=0.99,
                 seed=0):
        if not isinstance(recording, RecordingExtractor):
            raise ValueError("'recording' must be a RecordingExtractor")
        self._recording = recording

        random_data = self._get_random_data_for_scaling(seed=seed).ravel()
        loc_q1, pre_median, loc_q2 = np.quantile(random_data, q=[q1, 0.5, q2])
        pre_scale = abs(loc_q2 - loc_q1)

        self._scalar = scale / pre_scale
        self._offset = median - pre_median * self._scalar
        RecordingExtractor.__init__(self)
        self.copy_channel_properties(recording=self._recording)
        self.is_filtered = self._recording.is_filtered

        self._kwargs = {
            'recording': recording.make_serialized_dict(),
            'scale': scale,
            'median': median,
            'q1': q1,
            'q2': q2,
            'seed': seed
        }
Esempio n. 18
0
 def __init__(self, file_path):
     if not HAVE_NIXIO:
         raise ImportError(missing_nixio_msg)
     RecordingExtractor.__init__(self)
     self._file = nix.File.open(file_path, nix.FileMode.ReadOnly)
     self._load_properties()
     self._kwargs = {'file_path': str(Path(file_path).absolute())}
Esempio n. 19
0
def intervals_from_traces(recording: RecordingExtractor):
    """Extract interval times from TTL pulses."""
    traces = recording.get_traces(channel_ids=[1, 2])
    sf = recording.get_sampling_frequency()

    ttls = []
    states = []
    for tr in traces:
        threshold = np.ptp(tr) / 2 + np.min(tr)
        crossings = np.array(tr > threshold).astype("int8")

        rising = np.nonzero(np.diff(crossings, 1) > 0)[0]
        falling = np.nonzero(np.diff(crossings, 1) < 0)[0]

        ttl = np.concatenate((rising, falling))
        sort_order = np.argsort(ttl)
        ttl = np.sort(ttl)
        state = [1] * len(rising) + [-1] * len(falling)
        state = np.array(state)[sort_order]

        ttls.append(ttl)
        states.append(state)

    conditions = []
    for ttl, state in zip(ttls, states):
        assert len(ttl[state == 1]) == len(
            ttl[state == -1]), "Different number of rising/falling edges!"
        condition = np.zeros((len(ttl[state == 1]), 2), dtype="int")

        condition[:, 0] = ttl[state == 1] / sf
        condition[:, 1] = ttl[state == -1] / sf

        conditions.append(condition)

    return conditions
    def __init__(self, file_path: PathType):
        assert HAVE_LXML, self.installation_mesg
        file_path = Path(file_path)
        assert file_path.is_file() and file_path.suffix == '.dat', 'file_path must lead to a .dat file!'

        RecordingExtractor.__init__(self)
        self._recording_file = file_path
        file_path = Path(file_path)
        folder_path = file_path.parent

        xml_files = [f for f in folder_path.iterdir() if f.is_file() if f.suffix == '.xml']
        assert any(xml_files), 'No .xml file found in the folder_path.'
        assert len(xml_files) == 1, 'More than one .xml file found in the folder_path.'
        xml_filepath = xml_files[0]

        xml_root = et.parse(str(xml_filepath.absolute())).getroot()
        n_bits = int(xml_root.find('acquisitionSystem').find('nBits').text)
        dtype = 'int' + str(n_bits)
        numchan_from_file = int(xml_root.find('acquisitionSystem').find('nChannels').text)
        sampling_frequency = float(xml_root.find('acquisitionSystem').find('samplingRate').text)

        BinDatRecordingExtractor.__init__(self, file_path, sampling_frequency=sampling_frequency,
                                          dtype=dtype, numchan=numchan_from_file)

        self._kwargs = {'file_path': str(Path(file_path).absolute())}
 def __init__(self, recording_file, verbose=False):
     assert HAVE_INTAN, "To use the Intan extractor, install pyintan: \n\n pip install pyintan\n\n"
     RecordingExtractor.__init__(self)
     assert Path(recording_file).suffix == '.rhs' or Path(recording_file).suffix == '.rhd', \
         "Only '.rhd' and '.rhs' files are supported"
     self._recording_file = recording_file
     self._recording = pyintan.File(recording_file, verbose)
Esempio n. 22
0
    def __init__(self, recording, reference='median', groups=None, ref_channels=None, dtype=None, verbose=False):
        if not isinstance(recording, RecordingExtractor):
            raise ValueError("'recording' must be a RecordingExtractor")
        if reference != 'median' and reference != 'average' and reference != 'single':
            raise ValueError("'reference' must be either 'median' or 'average'")
        self._recording = recording
        self._ref = reference
        self._groups = groups
        if self._ref == 'single':
            assert ref_channels is not None, "With 'single' reference, provide 'ref_channels'"
            if self._groups is not None:
                assert len(ref_channels) == len(self._groups), "'ref_channel' and 'groups' must have the " \
                                                               "same length"
            else:
                if isinstance(ref_channels, (list, np.ndarray)):
                    assert len(ref_channels) == 1, "'ref_channel' with no 'groups' can be int or a list of one element"
                else:
                    assert isinstance(ref_channels, (int, np.integer)), "'ref_channels' must be int"
                    ref_channels = [ref_channels]
        self._ref_channel = ref_channels
        if dtype is None:
            self._dtype = recording.get_dtype()
        else:
            self._dtype = dtype
        self.verbose = verbose
        RecordingExtractor.__init__(self)
        self.copy_channel_properties(recording=self._recording)
        self.is_filtered = self._recording.is_filtered

        # update dump dict
        self._kwargs = {'recording': recording.make_serialized_dict(), 'reference': reference, 'groups': groups,
                        'ref_channels': ref_channels, 'dtype': dtype, 'verbose': verbose}
Esempio n. 23
0
    def __init__(self,
                 datfile,
                 samplerate,
                 numchan,
                 dtype,
                 recording_channels=None,
                 frames_first=True,
                 geom=None,
                 offset=0,
                 gain=None):
        RecordingExtractor.__init__(self)
        self._datfile = Path(datfile)
        self._frame_first = frames_first
        self._dtype = str(dtype)
        self._timeseries = read_binary(self._datfile, numchan, dtype,
                                       frames_first, offset)
        self._samplerate = float(samplerate)
        self._gain = gain
        self._geom = geom

        if recording_channels is not None:
            assert len(recording_channels) == self._timeseries.shape[0], \
                'Provided recording channels have the wrong length'
            self._channels = recording_channels
        else:
            self._channels = list(range(self._timeseries.shape[0]))

        if geom is not None:
            for m in range(self._timeseries.shape[0]):
                self.set_channel_property(m, 'location', self._geom[m, :])
Esempio n. 24
0
 def __init__(self, timeseries, sampling_frequency, geom=None):
     RecordingExtractor.__init__(self)
     if isinstance(timeseries, str):
         if Path(timeseries).is_file():
             assert Path(
                 timeseries
             ).suffix == '.npy', "'timeseries' file is not a numpy file (.npy)"
             self.is_dumpable = True
             self._timeseries = np.load(timeseries)
             self._kwargs = {
                 'timeseries': str(Path(timeseries).absolute()),
                 'sampling_frequency': sampling_frequency,
                 'geom': geom
             }
         else:
             raise ValueError("'timeeseries' is does not exist")
     elif isinstance(timeseries, np.ndarray):
         self.is_dumpable = False
         self._timeseries = timeseries
         self._kwargs = {
             'timeseries': timeseries,
             'sampling_frequency': sampling_frequency,
             'geom': geom
         }
     else:
         raise TypeError("'timeseries' can be a str or a numpy array")
     self._sampling_frequency = float(sampling_frequency)
     self._geom = geom
     if geom is not None:
         for m in range(self._timeseries.shape[0]):
             self.set_channel_property(m, 'location', self._geom[m, :])
Esempio n. 25
0
    def __init__(self,
                 *,
                 recording_directory=None,
                 timeseries_path=None,
                 download=False,
                 samplerate=None,
                 geom=None,
                 geom_path=None,
                 params_path=None):
        RecordingExtractor.__init__(self)
        if recording_directory:
            timeseries_path = recording_directory + '/raw.mda'
            geom_path = recording_directory + '/geom.csv'
            params_path = recording_directory + '/params.json'
        self._timeseries_path = timeseries_path
        if params_path:
            self._dataset_params = ka.load_object(params_path)
            self._samplerate = self._dataset_params['samplerate']
        else:
            self._dataset_params = dict(samplerate=samplerate)
            self._samplerate = samplerate

        if download:
            path0 = ka.load_file(path=self._timeseries_path)
            if not path0:
                raise Exception('Unable to realize file: ' +
                                self._timeseries_path)
            self._timeseries_path = path0

        self._timeseries = DiskReadMda(self._timeseries_path)
        if self._timeseries is None:
            raise Exception('Unable to load timeseries: {}'.format(
                self._timeseries_path))
        X = self._timeseries
        if geom is not None:
            self._geom = geom
        elif geom_path:
            geom_path2 = ka.load_file(geom_path)
            self._geom = np.genfromtxt(geom_path2, delimiter=',')
        else:
            self._geom = np.zeros((X.N1(), 2))

        if self._geom.shape[0] != X.N1():
            # raise Exception(
            #    'Incompatible dimensions between geom.csv and timeseries file {} <> {}'.format(self._geom.shape[0], X.N1()))
            print(
                'WARNING: Incompatible dimensions between geom.csv and timeseries file {} <> {}'
                .format(self._geom.shape[0], X.N1()))
            self._geom = np.zeros((X.N1(), 2))

        self._hash = ka.get_object_hash(
            dict(timeseries=ka.get_file_hash(self._timeseries_path),
                 samplerate=self._samplerate,
                 geom=_json_serialize(self._geom)))

        self._num_channels = X.N1()
        self._num_timepoints = X.N2()
        for m in range(self._num_channels):
            self.set_channel_property(m, 'location', self._geom[m, :])
Esempio n. 26
0
 def __init__(self, recording, a_min=None, a_max=None):
     if not isinstance(recording, RecordingExtractor):
         raise ValueError("'recording' must be a RecordingExtractor")
     self._recording = recording
     self._a_min = a_min
     self._a_max = a_max
     RecordingExtractor.__init__(self)
     self.copy_channel_properties(recording=self._recording)
 def __init__(self, recording_file, verbose=False):
     assert HAVE_MCSH5, "To use the MCSH5RecordingExtractor install h5py: \n\n pip install h5py\n\n"
     self._recording_file = recording_file
     self._rf, self._nFrames, self._samplingRate, self._nRecCh, \
     self._channel_ids, self._electrodeLabels, self._exponent, self._convFact \
     = openMCSH5File(
         self._recording_file, verbose)
     RecordingExtractor.__init__(self)
Esempio n. 28
0
 def __init__(self, recording, scalar=1, offset=0):
     if not isinstance(recording, RecordingExtractor):
         raise ValueError("'recording' must be a RecordingExtractor")
     self._recording = recording
     self._scalar = scalar
     self._offset = offset
     RecordingExtractor.__init__(self)
     self.copy_channel_properties(recording=self._recording)
Esempio n. 29
0
    def __init__(self, recording, resample_rate):
        assert HAVE_RR, "To use the ResampleRecording, install scipy: \n\n pip install scipy\n\n"
        self._recording = recording
        self._resample_rate = resample_rate
        RecordingExtractor.__init__(self)
        self.copy_channel_properties(recording)

        self._kwargs = {'recording': recording.make_serialized_dict(), 'resample_rate': resample_rate}
    def __init__(self, file_path, stream_id=0, verbose=False):
        assert HAVE_MCSH5, "To use the MCSH5RecordingExtractor install h5py: \n\n pip install h5py\n\n"
        self._recording_file = file_path
        self._verbose = verbose
        self._available_stream_ids = self.get_available_stream_ids()
        self.set_stream_id(stream_id)

        RecordingExtractor.__init__(self)