本文整理汇总了Python中neo.core.AnalogSignal类的典型用法代码示例。如果您正苦于以下问题:Python AnalogSignal类的具体用法?Python AnalogSignal怎么用?Python AnalogSignal使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了AnalogSignal类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: read_analogsignal
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
示例2: read_analogsignal
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
示例3: create_analogsignal3
def create_analogsignal3(self, parent=None, name='AnalogSignal3'):
signal = AnalogSignal([[1, 2, 3], [4, 5, 6]], units='mV',
sampling_rate=2 * pq.kHz, t_start=100 * pq.s)
signal.segment = parent
self._assign_basic_attributes(signal, name=name)
return signal
示例4: create_analogsignal2
def create_analogsignal2(self, parent=None, name='AnalogSignal2'):
signal = AnalogSignal([[1], [2], [3], [4], [5]], units='mA',
sampling_period=0.5 * pq.ms)
signal.segment = parent
self._assign_annotations(signal)
return signal
示例5: create_analogsignal
def create_analogsignal(self, parent=None, name='AnalogSignal1'):
signal = AnalogSignal([[1.0, 2.5], [2.2, 3.1], [3.2, 4.4]], units='mV',
sampling_rate=100 * pq.Hz, t_start=2 * pq.min)
signal.segment = parent
self._assign_basic_attributes(signal, name=name)
self._assign_annotations(signal)
return signal
示例6: read_analogsignal
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
示例7: read_segment
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
示例8: _read_analogsignalarray
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)
signal.segment = parent
self.object_refs[node.attrs["object_ref"]] = signal
return signal
示例9: read_block
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
示例10: _extract_signals
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
示例11: create_all_annotated
def create_all_annotated(cls):
times = cls.rquant(1, pq.s)
signal = cls.rquant(1, pq.V)
blk = Block()
blk.annotate(**cls.rdict(3))
seg = Segment()
seg.annotate(**cls.rdict(4))
blk.segments.append(seg)
asig = AnalogSignal(signal=signal, sampling_rate=pq.Hz)
asig.annotate(**cls.rdict(2))
seg.analogsignals.append(asig)
isig = IrregularlySampledSignal(times=times, signal=signal,
time_units=pq.s)
isig.annotate(**cls.rdict(2))
seg.irregularlysampledsignals.append(isig)
epoch = Epoch(times=times, durations=times)
epoch.annotate(**cls.rdict(4))
seg.epochs.append(epoch)
event = Event(times=times)
event.annotate(**cls.rdict(4))
seg.events.append(event)
spiketrain = SpikeTrain(times=times, t_stop=pq.s, units=pq.s)
d = cls.rdict(6)
d["quantity"] = pq.Quantity(10, "mV")
d["qarray"] = pq.Quantity(range(10), "mA")
spiketrain.annotate(**d)
seg.spiketrains.append(spiketrain)
chx = ChannelIndex(name="achx", index=[1, 2], channel_ids=[0, 10])
chx.annotate(**cls.rdict(5))
blk.channel_indexes.append(chx)
unit = Unit()
unit.annotate(**cls.rdict(2))
chx.units.append(unit)
return blk
示例12: read_analogsignal
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
示例13: _extract_signal
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
示例14: gettrace
def gettrace(trec,f):
import numpy as np
format_type_lenghts = [2,4,4,8]
format_type = [np.int16,np.int32,np.float32,np.float64]
pointsize = format_type_lenghts[int(trec.trDataFormat)]
dtype = format_type[int(trec.trDataFormat)]
f.seek(int(trec.trData))
byte_string = f.read(int(trec.trDataPoints)*pointsize)
import numpy as np
ydata = np.fromstring(byte_string,dtype = dtype)
tunit = pq.Quantity(1,str(trec.trXUnit))
yunit = pq.Quantity(1,str(trec.trYUnit))
sig = AnalogSignal(ydata*float(trec.trDataScaler)*yunit,
sampling_period=float(trec.trXInterval)*tunit,
units = trec.trYUnit[0])
annotations = trec.__dict__.keys()
annotations.remove('readlist')
for a in annotations:
d = {a:str(trec.__dict__[a])}
sig.annotate(**d)
return sig
示例15: read_analogsignal
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