本文整理汇总了Python中neo.core.AnalogSignal.lazy_shape方法的典型用法代码示例。如果您正苦于以下问题:Python AnalogSignal.lazy_shape方法的具体用法?Python AnalogSignal.lazy_shape怎么用?Python AnalogSignal.lazy_shape使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类neo.core.AnalogSignal
的用法示例。
在下文中一共展示了AnalogSignal.lazy_shape方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _read_analogsignalarray
# 需要导入模块: from neo.core import AnalogSignal [as 别名]
# 或者: from neo.core.AnalogSignal import lazy_shape [as 别名]
def _read_analogsignalarray(self, node, parent):
attributes = self._get_standard_attributes(node)
# todo: handle channel_index
sampling_rate = self._get_quantity(node["sampling_rate"])
t_start = self._get_quantity(node["t_start"])
signal = AnalogSignal(self._get_quantity(node["signal"]),
sampling_rate=sampling_rate, t_start=t_start,
**attributes)
if self._lazy:
signal.lazy_shape = node["signal"].shape
if len(signal.lazy_shape) == 1:
signal.lazy_shape = (signal.lazy_shape[0], 1)
signal.segment = parent
self.object_refs[node.attrs["object_ref"]] = signal
return signal
示例2: read_analogsignal
# 需要导入模块: from neo.core import AnalogSignal [as 别名]
# 或者: from neo.core.AnalogSignal import lazy_shape [as 别名]
def read_analogsignal(self, channel_index=None, lazy=False, cascade=True):
"""
Read raw traces
Arguments:
channel_index: must be integer array
"""
if self._attrs["app_data"]:
bit_volts = self._attrs["app_data"]["channel_bit_volts"]
sig_unit = "uV"
else:
bit_volts = np.ones((self._attrs["shape"][1])) # TODO: find conversion in phy generated files
sig_unit = "bit"
if lazy:
anasig = AnalogSignal(
[],
units=sig_unit,
sampling_rate=self._attrs["kwik"]["sample_rate"] * pq.Hz,
t_start=self._attrs["kwik"]["start_time"] * pq.s,
)
# we add the attribute lazy_shape with the size if loaded
anasig.lazy_shape = self._attrs["shape"][0]
else:
data = self._kwd["recordings"][str(self._dataset)]["data"].value[:, channel_index]
data = data * bit_volts[channel_index]
anasig = AnalogSignal(
data,
units=sig_unit,
sampling_rate=self._attrs["kwik"]["sample_rate"] * pq.Hz,
t_start=self._attrs["kwik"]["start_time"] * pq.s,
)
data = [] # delete from memory
# for attributes out of neo you can annotate
anasig.annotate(info="raw traces")
return anasig
示例3: read_analogsignal
# 需要导入模块: from neo.core import AnalogSignal [as 别名]
# 或者: from neo.core.AnalogSignal import lazy_shape [as 别名]
def read_analogsignal(self ,
# the 2 first key arguments are imposed by neo.io API
lazy = False,
cascade = True,
channel_index = 0,
segment_duration = 15.,
t_start = -1,
):
"""
With this IO AnalogSignal can e acces directly with its channel number
"""
sr = 10000.
sinus_freq = 3. # Hz
#time vector for generated signal:
tvect = np.arange(t_start, t_start+ segment_duration , 1./sr)
if lazy:
anasig = AnalogSignal([], units='V', sampling_rate=sr * pq.Hz,
t_start=t_start * pq.s,
channel_index=channel_index)
# we add the attribute lazy_shape with the size if loaded
anasig.lazy_shape = tvect.shape
else:
# create analogsignal (sinus of 3 Hz)
sig = np.sin(2*np.pi*tvect*sinus_freq + channel_index/5.*2*np.pi)+np.random.rand(tvect.size)
anasig = AnalogSignal(sig, units= 'V', sampling_rate=sr * pq.Hz,
t_start=t_start * pq.s,
channel_index=channel_index)
# for attributes out of neo you can annotate
anasig.annotate(info = 'it is a sinus of %f Hz' %sinus_freq )
return anasig
示例4: read_analogsignal
# 需要导入模块: from neo.core import AnalogSignal [as 别名]
# 或者: from neo.core.AnalogSignal import lazy_shape [as 别名]
def read_analogsignal(self,
# the 2 first key arguments are imposed by neo.io
lazy = False,
cascade = True,
#channel index as given by the neuroshare API
channel_index = 0,
#time in seconds to be read
segment_duration = 0.,
#time in seconds to start reading from
t_start = 0.,
):
#some controls:
#if no segment duration is given, use the complete file
if segment_duration ==0.:
segment_duration=float(self.metadata["TimeSpan"])
#if the segment duration is bigger than file, use the complete file
if segment_duration >=float(self.metadata["TimeSpan"]):
segment_duration=float(self.metadata["TimeSpan"])
if lazy:
anasig = AnalogSignal([], units="V", sampling_rate = self.metadata["sampRate"] * pq.Hz,
t_start=t_start * pq.s,
)
#create a dummie time vector
tvect = np.arange(t_start, t_start+ segment_duration , 1./self.metadata["sampRate"])
# we add the attribute lazy_shape with the size if loaded
anasig.lazy_shape = tvect.shape
else:
#get the analog object
sig = self.fd.get_entity(channel_index)
#get the units (V, mV etc)
sigUnits = sig.units
#get the electrode number
chanName = sig.label[-4:]
#transform t_start into index (reading will start from this index)
startat = int(t_start*self.metadata["sampRate"])
#get the number of bins to read in
bins = int((segment_duration+t_start) * self.metadata["sampRate"])
#if the number of bins to read is bigger than
#the total number of bins, read only till the end of analog object
if startat+bins > sig.item_count:
bins = sig.item_count-startat
#read the data from the sig object
sig,_,_ = sig.get_data(index = startat, count = bins)
#store it to the 'AnalogSignal' object
anasig = AnalogSignal(sig, units = sigUnits, sampling_rate=self.metadata["sampRate"] * pq.Hz,
t_start=t_start * pq.s,
t_stop = (t_start+segment_duration)*pq.s,
channel_index=channel_index)
# annotate from which electrode the signal comes from
anasig.annotate(info = "signal from channel %s" %chanName )
return anasig
示例5: read_segment
# 需要导入模块: from neo.core import AnalogSignal [as 别名]
# 或者: from neo.core.AnalogSignal import lazy_shape [as 别名]
def read_segment(self, n_start, n_stop, chlist=None, lazy=False, cascade=True):
"""Reads a Segment from the file and stores in database.
The Segment will contain one AnalogSignal for each channel
and will go from n_start to n_stop (in samples).
Arguments:
n_start : time in samples that the Segment begins
n_stop : time in samples that the Segment ends
Python indexing is used, so n_stop is not inclusive.
Returns a Segment object containing the data.
"""
# If no channel numbers provided, get all of them
if chlist is None:
chlist = self.loader.get_neural_channel_numbers()
# Conversion from bits to full_range units
conversion = self.full_range / 2**(8*self.header.sample_width)
# Create the Segment
seg = Segment(file_origin=self.filename)
t_start = float(n_start) / self.header.f_samp
t_stop = float(n_stop) / self.header.f_samp
seg.annotate(t_start=t_start)
seg.annotate(t_stop=t_stop)
# Load data from each channel and store
for ch in chlist:
if lazy:
sig = np.array([]) * conversion
else:
# Get the data from the loader
sig = np.array(\
self.loader._get_channel(ch)[n_start:n_stop]) * conversion
# Create an AnalogSignal with the data in it
anasig = AnalogSignal(signal=sig,
sampling_rate=self.header.f_samp*pq.Hz,
t_start=t_start*pq.s, file_origin=self.filename,
description='Channel %d from %f to %f' % (ch, t_start, t_stop),
channel_index=int(ch))
if lazy:
anasig.lazy_shape = n_stop-n_start
# Link the signal to the segment
seg.analogsignals.append(anasig)
# Link the signal to the recording channel from which it came
#rc = self.channel_number_to_recording_channel[ch]
#rc.analogsignals.append(anasig)
return seg
示例6: read_block
# 需要导入模块: from neo.core import AnalogSignal [as 别名]
# 或者: from neo.core.AnalogSignal import lazy_shape [as 别名]
def read_block(self, lazy=False, cascade=True):
if self.filename is not None:
self.stfio_rec = stfio.read(self.filename)
bl = Block()
bl.description = self.stfio_rec.file_description
bl.annotate(comment=self.stfio_rec.comment)
try:
bl.rec_datetime = self.stfio_rec.datetime
except:
bl.rec_datetime = None
if not cascade:
return bl
dt = np.round(self.stfio_rec.dt * 1e-3, 9) * pq.s # ms to s
sampling_rate = 1.0/dt
t_start = 0 * pq.s
# iterate over sections first:
for j, recseg in enumerate(self.stfio_rec[0]):
seg = Segment(index=j)
length = len(recseg)
# iterate over channels:
for i, recsig in enumerate(self.stfio_rec):
name = recsig.name
unit = recsig.yunits
try:
pq.Quantity(1, unit)
except:
unit = ''
if lazy:
signal = pq.Quantity([], unit)
else:
signal = pq.Quantity(recsig[j], unit)
anaSig = AnalogSignal(signal, sampling_rate=sampling_rate,
t_start=t_start, name=str(name),
channel_index=i)
if lazy:
anaSig.lazy_shape = length
seg.analogsignals.append(anaSig)
bl.segments.append(seg)
t_start = t_start + length * dt
bl.create_many_to_one_relationship()
return bl
示例7: read_analogsignal
# 需要导入模块: from neo.core import AnalogSignal [as 别名]
# 或者: from neo.core.AnalogSignal import lazy_shape [as 别名]
def read_analogsignal(self,
channel_index=None,
lazy=False,
cascade=True,
):
"""
Read raw traces
Arguments:
channel_index: must be integer
"""
try:
channel_index = int(channel_index)
except TypeError:
print('channel_index must be int, not %s' %type(channel_index))
if self._attrs['app_data']:
bit_volts = self._attrs['app_data']['channel_bit_volts']
sig_unit = 'uV'
else:
bit_volts = np.ones((self._attrs['shape'][1])) # TODO: find conversion in phy generated files
sig_unit = 'bit'
if lazy:
anasig = AnalogSignal([],
units=sig_unit,
sampling_rate=self._attrs['kwik']['sample_rate']*pq.Hz,
t_start=self._attrs['kwik']['start_time']*pq.s,
channel_index=channel_index,
)
# we add the attribute lazy_shape with the size if loaded
anasig.lazy_shape = self._attrs['shape'][0]
else:
data = self._kwd['recordings'][str(self._dataset)]['data'].value[:,channel_index]
data = data * bit_volts[channel_index]
anasig = AnalogSignal(data,
units=sig_unit,
sampling_rate=self._attrs['kwik']['sample_rate']*pq.Hz,
t_start=self._attrs['kwik']['start_time']*pq.s,
channel_index=channel_index,
)
data = [] # delete from memory
# for attributes out of neo you can annotate
anasig.annotate(info='raw traces')
return anasig
示例8: _extract_signals
# 需要导入模块: from neo.core import AnalogSignal [as 别名]
# 或者: from neo.core.AnalogSignal import lazy_shape [as 别名]
def _extract_signals(self, data, metadata, lazy):
signal = None
if lazy and data.size > 0:
signal = AnalogSignal([],
units=self._determine_units(metadata),
sampling_period=metadata['dt']*pq.ms)
signal.lazy_shape = None
else:
arr = numpy.vstack(self._extract_array(data, channel_index)
for channel_index in range(metadata['first_index'], metadata['last_index'] + 1))
if len(arr) > 0:
signal = AnalogSignal(arr.T,
units=self._determine_units(metadata),
sampling_period=metadata['dt']*pq.ms)
if signal is not None:
signal.annotate(label=metadata["label"],
variable=metadata["variable"])
return signal
示例9: _extract_signal
# 需要导入模块: from neo.core import AnalogSignal [as 别名]
# 或者: from neo.core.AnalogSignal import lazy_shape [as 别名]
def _extract_signal(self, data, metadata, channel_index, lazy):
signal = None
if lazy:
if channel_index in data[:, 1]:
signal = AnalogSignal([],
units=self._determine_units(metadata),
sampling_period=metadata['dt']*pq.ms,
channel_index=channel_index)
signal.lazy_shape = None
else:
arr = self._extract_array(data, channel_index)
if len(arr) > 0:
signal = AnalogSignal(arr,
units=self._determine_units(metadata),
sampling_period=metadata['dt']*pq.ms,
channel_index=channel_index)
if signal is not None:
signal.annotate(label=metadata["label"],
variable=metadata["variable"])
return signal
示例10: read_analogsignal
# 需要导入模块: from neo.core import AnalogSignal [as 别名]
# 或者: from neo.core.AnalogSignal import lazy_shape [as 别名]
def read_analogsignal(self, lazy=False, cascade=True):
if not HAVE_IGOR:
raise Exception("igor package not installed. Try `pip install igor`")
data = bw.load(self.filename)
version = data['version']
if version > 3:
raise IOError("Igor binary wave file format version {0} is not supported.".format(version))
content = data['wave']
if "padding" in content:
assert content['padding'].size == 0, "Cannot handle non-empty padding"
if lazy:
# not really lazy, since the `igor` module loads the data anyway
signal = np.array((), dtype=content['wData'].dtype)
else:
signal = content['wData']
note = content['note']
header = content['wave_header']
name = header['bname']
assert header['botFullScale'] == 0
assert header['topFullScale'] == 0
units = "".join(header['dataUnits'])
time_units = "".join(header['xUnits']) or "s"
t_start = pq.Quantity(header['hsB'], time_units)
sampling_period = pq.Quantity(header['hsA'], time_units)
if self.parse_notes:
try:
annotations = self.parse_notes(note)
except ValueError:
warn("Couldn't parse notes field.")
annotations = {'note': note}
else:
annotations = {'note': note}
signal = AnalogSignal(signal, units=units, copy=False, t_start=t_start,
sampling_period=sampling_period, name=name,
file_origin=self.filename, **annotations)
if lazy:
signal.lazy_shape = content['wData'].shape
return signal
示例11: read_segment
# 需要导入模块: from neo.core import AnalogSignal [as 别名]
# 或者: from neo.core.AnalogSignal import lazy_shape [as 别名]
#.........这里部分代码省略.........
float_signal = self.rescale_signal_raw_to_float(
raw_signal,
dtype='float32',
channel_indexes=channel_indexes)
for i, (ind_within, ind_abs) in self._make_signal_channel_subgroups(
channel_indexes,
signal_group_mode=signal_group_mode).items():
units = np.unique(signal_channels[ind_abs]['units'])
assert len(units) == 1
units = ensure_signal_units(units[0])
if signal_group_mode == 'split-all':
# in that case annotations by channel is OK
chan_index = ind_abs[0]
d = self.raw_annotations['blocks'][block_index]['segments'][seg_index][
'signals'][chan_index]
annotations = dict(d)
if 'name' not in annotations:
annotations['name'] = signal_channels['name'][chan_index]
else:
# when channel are grouped by same unit
# annotations have channel_names and channel_ids array
# this will be moved in array annotations soon
annotations = {}
annotations['name'] = 'Channel bundle ({}) '.format(
','.join(signal_channels[ind_abs]['name']))
annotations['channel_names'] = signal_channels[ind_abs]['name']
annotations['channel_ids'] = signal_channels[ind_abs]['id']
annotations = check_annotations(annotations)
if lazy:
anasig = AnalogSignal(np.array([]), units=units, copy=False,
sampling_rate=sr, t_start=sig_t_start, **annotations)
anasig.lazy_shape = (sig_size, len(ind_within))
else:
anasig = AnalogSignal(float_signal[:, ind_within], units=units, copy=False,
sampling_rate=sr, t_start=sig_t_start, **annotations)
seg.analogsignals.append(anasig)
# SpikeTrain and waveforms (optional)
unit_channels = self.header['unit_channels']
for unit_index in range(len(unit_channels)):
if not lazy and load_waveforms:
raw_waveforms = self.get_spike_raw_waveforms(block_index=block_index,
seg_index=seg_index,
unit_index=unit_index,
t_start=t_start_, t_stop=t_stop_)
float_waveforms = self.rescale_waveforms_to_float(raw_waveforms, dtype='float32',
unit_index=unit_index)
wf_units = ensure_signal_units(unit_channels['wf_units'][unit_index])
waveforms = pq.Quantity(float_waveforms, units=wf_units,
dtype='float32', copy=False)
wf_sampling_rate = unit_channels['wf_sampling_rate'][unit_index]
wf_left_sweep = unit_channels['wf_left_sweep'][unit_index]
if wf_left_sweep > 0:
wf_left_sweep = float(wf_left_sweep) / wf_sampling_rate * pq.s
else:
wf_left_sweep = None
wf_sampling_rate = wf_sampling_rate * pq.Hz
else:
waveforms = None
wf_left_sweep = None
wf_sampling_rate = None
d = self.raw_annotations['blocks'][block_index]['segments'][seg_index]['units'][
unit_index]
示例12: read_segment
# 需要导入模块: from neo.core import AnalogSignal [as 别名]
# 或者: from neo.core.AnalogSignal import lazy_shape [as 别名]
def read_segment(self, lazy=False, cascade=True):
fid = open(self.filename, 'rb')
global_header = HeaderReader(fid, GlobalHeader).read_f(offset=0)
# ~ print globalHeader
#~ print 'version' , globalHeader['version']
seg = Segment()
seg.file_origin = os.path.basename(self.filename)
seg.annotate(neuroexplorer_version=global_header['version'])
seg.annotate(comment=global_header['comment'])
if not cascade:
return seg
offset = 544
for i in range(global_header['nvar']):
entity_header = HeaderReader(fid, EntityHeader).read_f(
offset=offset + i * 208)
entity_header['name'] = entity_header['name'].replace('\x00', '')
#print 'i',i, entityHeader['type']
if entity_header['type'] == 0:
# neuron
if lazy:
spike_times = [] * pq.s
else:
spike_times = np.memmap(self.filename, np.dtype('i4'), 'r',
shape=(entity_header['n']),
offset=entity_header['offset'])
spike_times = spike_times.astype('f8') / global_header[
'freq'] * pq.s
sptr = SpikeTrain(
times=spike_times,
t_start=global_header['tbeg'] /
global_header['freq'] * pq.s,
t_stop=global_header['tend'] /
global_header['freq'] * pq.s,
name=entity_header['name'])
if lazy:
sptr.lazy_shape = entity_header['n']
sptr.annotate(channel_index=entity_header['WireNumber'])
seg.spiketrains.append(sptr)
if entity_header['type'] == 1:
# event
if lazy:
event_times = [] * pq.s
else:
event_times = np.memmap(self.filename, np.dtype('i4'), 'r',
shape=(entity_header['n']),
offset=entity_header['offset'])
event_times = event_times.astype('f8') / global_header[
'freq'] * pq.s
labels = np.array([''] * event_times.size, dtype='S')
evar = Event(times=event_times, labels=labels,
channel_name=entity_header['name'])
if lazy:
evar.lazy_shape = entity_header['n']
seg.events.append(evar)
if entity_header['type'] == 2:
# interval
if lazy:
start_times = [] * pq.s
stop_times = [] * pq.s
else:
start_times = np.memmap(self.filename, np.dtype('i4'), 'r',
shape=(entity_header['n']),
offset=entity_header['offset'])
start_times = start_times.astype('f8') / global_header[
'freq'] * pq.s
stop_times = np.memmap(self.filename, np.dtype('i4'), 'r',
shape=(entity_header['n']),
offset=entity_header['offset'] +
entity_header['n'] * 4)
stop_times = stop_times.astype('f') / global_header[
'freq'] * pq.s
epar = Epoch(times=start_times,
durations=stop_times - start_times,
labels=np.array([''] * start_times.size,
dtype='S'),
channel_name=entity_header['name'])
if lazy:
epar.lazy_shape = entity_header['n']
seg.epochs.append(epar)
if entity_header['type'] == 3:
# spiketrain and wavefoms
if lazy:
spike_times = [] * pq.s
waveforms = None
else:
spike_times = np.memmap(self.filename, np.dtype('i4'), 'r',
shape=(entity_header['n']),
offset=entity_header['offset'])
spike_times = spike_times.astype('f8') / global_header[
'freq'] * pq.s
waveforms = np.memmap(self.filename, np.dtype('i2'), 'r',
#.........这里部分代码省略.........
示例13: read_segment
# 需要导入模块: from neo.core import AnalogSignal [as 别名]
# 或者: from neo.core.AnalogSignal import lazy_shape [as 别名]
#.........这里部分代码省略.........
zname2, pos, length = f.read_f('8sII')
zones[zname] = zname2, pos, length
#~ print zname2, pos, length
# reading raw data
if not lazy:
f.seek(Data_Start_Offset, 0)
rawdata = np.fromstring(f.read(), dtype='u' + str(Bytes))
rawdata = rawdata.reshape((-1, Num_Chan))
# Reading Code Info
zname2, pos, length = zones['ORDER']
f.seek(pos, 0)
code = np.fromstring(f.read(Num_Chan*2), dtype='u2', count=Num_Chan)
units = {-1: pq.nano * pq.V, 0: pq.uV, 1: pq.mV, 2: 1, 100: pq.percent,
101: pq.dimensionless, 102: pq.dimensionless}
for c in range(Num_Chan):
zname2, pos, length = zones['LABCOD']
f.seek(pos + code[c] * 128 + 2, 0)
label = f.read(6).strip(b"\x00").decode('ascii')
ground = f.read(6).strip(b"\x00").decode('ascii')
(logical_min, logical_max, logical_ground, physical_min,
physical_max) = f.read_f('iiiii')
k, = f.read_f('h')
if k in units.keys():
unit = units[k]
else:
unit = pq.uV
f.seek(8, 1)
sampling_rate, = f.read_f('H') * pq.Hz
sampling_rate *= Rate_Min
if lazy:
signal = [] * unit
else:
factor = float(physical_max - physical_min) / float(
logical_max - logical_min + 1)
signal = (rawdata[:, c].astype(
'f') - logical_ground) * factor * unit
ana_sig = AnalogSignal(signal, sampling_rate=sampling_rate,
name=str(label), channel_index=c)
if lazy:
ana_sig.lazy_shape = None
ana_sig.annotate(ground=ground)
seg.analogsignals.append(ana_sig)
sampling_rate = np.mean(
[ana_sig.sampling_rate for ana_sig in seg.analogsignals]) * pq.Hz
# Read trigger and notes
for zname, label_dtype in [('TRIGGER', 'u2'), ('NOTE', 'S40')]:
zname2, pos, length = zones[zname]
f.seek(pos, 0)
triggers = np.fromstring(f.read(length), dtype=[('pos', 'u4'), (
'label', label_dtype)])
if not lazy:
keep = (triggers['pos'] >= triggers['pos'][0]) & (
triggers['pos'] < rawdata.shape[0]) & (
triggers['pos'] != 0)
triggers = triggers[keep]
ea = Event(name=zname[0] + zname[1:].lower(),
labels=triggers['label'].astype('S'),
times=(triggers['pos'] / sampling_rate).rescale('s'))
else:
ea = Event(name=zname[0] + zname[1:].lower())
ea.lazy_shape = triggers.size
seg.events.append(ea)
# Read Event A and B
# Not so well tested
for zname in ['EVENT A', 'EVENT B']:
zname2, pos, length = zones[zname]
f.seek(pos, 0)
epochs = np.fromstring(f.read(length),
dtype=[('label', 'u4'), ('start', 'u4'),
('stop', 'u4'), ])
ep = Epoch(name=zname[0] + zname[1:].lower())
if not lazy:
keep = (epochs['start'] > 0) & (
epochs['start'] < rawdata.shape[0]) & (
epochs['stop'] < rawdata.shape[0])
epochs = epochs[keep]
ep = Epoch(name=zname[0] + zname[1:].lower(),
labels=epochs['label'].astype('S'),
times=(epochs['start'] / sampling_rate).rescale('s'),
durations=((epochs['stop'] - epochs['start']) / sampling_rate).rescale('s'))
else:
ep = Epoch(name=zname[0] + zname[1:].lower())
ep.lazy_shape = triggers.size
seg.epochs.append(ep)
seg.create_many_to_one_relationship()
f.close()
return seg
示例14: read_segment
# 需要导入模块: from neo.core import AnalogSignal [as 别名]
# 或者: from neo.core.AnalogSignal import lazy_shape [as 别名]
def read_segment(self, blockname=None, lazy=False, cascade=True, sortname=''):
"""
Read a single segment from the tank. Note that TDT blocks are Neo
segments, and TDT tanks are Neo blocks, so here the 'blockname' argument
refers to the TDT block's name, which will be the Neo segment name.
sortname is used to specify the external sortcode generated by offline spike sorting, if sortname=='PLX',
there should be a ./sort/PLX/*.SortResult file in the tdt block, which stores the sortcode for every spike,
default to '', which uses the original online sort
"""
if not blockname:
blockname = os.listdir(self.dirname)[0]
if blockname == 'TempBlk': return None
if not self.is_tdtblock(blockname): return None # if not a tdt block
subdir = os.path.join(self.dirname, blockname)
if not os.path.isdir(subdir): return None
seg = Segment(name=blockname)
tankname = os.path.basename(self.dirname)
#TSQ is the global index
tsq_filename = os.path.join(subdir, tankname+'_'+blockname+'.tsq')
dt = [('size','int32'),
('evtype','int32'),
('code','S4'),
('channel','uint16'),
('sortcode','uint16'),
('timestamp','float64'),
('eventoffset','int64'),
('dataformat','int32'),
('frequency','float32'),
]
tsq = np.fromfile(tsq_filename, dtype=dt)
#0x8801: 'EVTYPE_MARK' give the global_start
global_t_start = tsq[tsq['evtype']==0x8801]['timestamp'][0]
#TEV is the old data file
try:
tev_filename = os.path.join(subdir, tankname+'_'+blockname+'.tev')
#tev_array = np.memmap(tev_filename, mode = 'r', dtype = 'uint8') # if memory problem use this instead
tev_array = np.fromfile(tev_filename, dtype='uint8')
except IOError:
tev_filename = None
#if exists an external sortcode in ./sort/[sortname]/*.SortResult (generated after offline sortting)
sortresult_filename = None
if sortname is not '':
try:
for file in os.listdir(os.path.join(subdir, 'sort', sortname)):
if file.endswith(".SortResult"):
sortresult_filename = os.path.join(subdir, 'sort', sortname, file)
# get new sortcode
newsorcode = np.fromfile(sortresult_filename,'int8')[1024:] # the first 1024 byte is file header
# update the sort code with the info from this file
tsq['sortcode'][1:-1]=newsorcode
# print('sortcode updated')
break
except OSError:
sortresult_filename = None
except IOError:
sortresult_filename = None
for type_code, type_label in tdt_event_type:
mask1 = tsq['evtype']==type_code
codes = np.unique(tsq[mask1]['code'])
for code in codes:
mask2 = mask1 & (tsq['code']==code)
channels = np.unique(tsq[mask2]['channel'])
for channel in channels:
mask3 = mask2 & (tsq['channel']==channel)
if type_label in ['EVTYPE_STRON', 'EVTYPE_STROFF']:
if lazy:
times = [ ]*pq.s
labels = np.array([ ], dtype=str)
else:
times = (tsq[mask3]['timestamp'] - global_t_start) * pq.s
labels = tsq[mask3]['eventoffset'].view('float64').astype('S')
ea = Event(times=times,
name=code,
channel_index=int(channel),
labels=labels)
if lazy:
ea.lazy_shape = np.sum(mask3)
seg.events.append(ea)
elif type_label == 'EVTYPE_SNIP':
sortcodes = np.unique(tsq[mask3]['sortcode'])
for sortcode in sortcodes:
mask4 = mask3 & (tsq['sortcode']==sortcode)
nb_spike = np.sum(mask4)
#.........这里部分代码省略.........
示例15: read_segment
# 需要导入模块: from neo.core import AnalogSignal [as 别名]
# 或者: from neo.core.AnalogSignal import lazy_shape [as 别名]
def read_segment(self , lazy = False, cascade = True):
seg = Segment(
file_origin = os.path.basename(self.filename),
)
if not cascade:
return seg
fid = open(self.filename , 'rb')
headertext = fid.read(2048)
if PY3K:
headertext = headertext.decode('ascii')
header = {}
for line in headertext.split('\r\n'):
if '=' not in line : continue
#print '#' , line , '#'
key,val = line.split('=')
if key in ['NC', 'NR','NBH','NBA','NBD','ADCMAX','NP','NZ','ADCMAX' ] :
val = int(val)
elif key in ['AD', 'DT', ] :
val = val.replace(',','.')
val = float(val)
header[key] = val
if not lazy:
data = np.memmap(self.filename , np.dtype('i2') , 'r',
#shape = (header['NC'], header['NP']) ,
shape = (header['NP']/header['NC'],header['NC'], ) ,
offset = header['NBH'])
for c in range(header['NC']):
YCF = float(header['YCF%d'%c].replace(',','.'))
YAG = float(header['YAG%d'%c].replace(',','.'))
YZ = float(header['YZ%d'%c].replace(',','.'))
ADCMAX = header['ADCMAX']
AD = header['AD']
DT = header['DT']
if 'TU' in header:
if header['TU'] == 'ms':
DT *= .001
unit = header['YU%d'%c]
try :
unit = pq.Quantity(1., unit)
except:
unit = pq.Quantity(1., '')
if lazy:
signal = [ ] * unit
else:
signal = (data[:,header['YO%d'%c]].astype('f4')-YZ) *AD/( YCF*YAG*(ADCMAX+1)) * unit
ana = AnalogSignal(signal,
sampling_rate=pq.Hz / DT,
t_start=0. * pq.s,
name=header['YN%d' % c],
channel_index=c)
if lazy:
ana.lazy_shape = header['NP']/header['NC']
seg.analogsignals.append(ana)
seg.create_many_to_one_relationship()
return seg