id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
235,200 | MIT-LCP/wfdb-python | wfdb/io/_header.py | HeaderMixin.set_default | def set_default(self, field):
"""
Set the object's attribute to its default value if it is missing
and there is a default.
Not responsible for initializing the
attribute. That is done by the constructor.
"""
# Record specification fields
if field in RECORD_SPECS.index:
# Return if no default to set, or if the field is already
# present.
if RECORD_SPECS.loc[field, 'write_default'] is None or getattr(self, field) is not None:
return
setattr(self, field, RECORD_SPECS.loc[field, 'write_default'])
# Signal specification fields
# Setting entire list default, not filling in blanks in lists.
elif field in SIGNAL_SPECS.index:
# Specific dynamic case
if field == 'file_name' and self.file_name is None:
self.file_name = self.n_sig * [self.record_name + '.dat']
return
item = getattr(self, field)
# Return if no default to set, or if the field is already
# present.
if SIGNAL_SPECS.loc[field, 'write_default'] is None or item is not None:
return
# Set more specific defaults if possible
if field == 'adc_res' and self.fmt is not None:
self.adc_res = _signal._fmt_res(self.fmt)
return
setattr(self, field,
[SIGNAL_SPECS.loc[field, 'write_default']] * self.n_sig) | python | def set_default(self, field):
# Record specification fields
if field in RECORD_SPECS.index:
# Return if no default to set, or if the field is already
# present.
if RECORD_SPECS.loc[field, 'write_default'] is None or getattr(self, field) is not None:
return
setattr(self, field, RECORD_SPECS.loc[field, 'write_default'])
# Signal specification fields
# Setting entire list default, not filling in blanks in lists.
elif field in SIGNAL_SPECS.index:
# Specific dynamic case
if field == 'file_name' and self.file_name is None:
self.file_name = self.n_sig * [self.record_name + '.dat']
return
item = getattr(self, field)
# Return if no default to set, or if the field is already
# present.
if SIGNAL_SPECS.loc[field, 'write_default'] is None or item is not None:
return
# Set more specific defaults if possible
if field == 'adc_res' and self.fmt is not None:
self.adc_res = _signal._fmt_res(self.fmt)
return
setattr(self, field,
[SIGNAL_SPECS.loc[field, 'write_default']] * self.n_sig) | [
"def",
"set_default",
"(",
"self",
",",
"field",
")",
":",
"# Record specification fields",
"if",
"field",
"in",
"RECORD_SPECS",
".",
"index",
":",
"# Return if no default to set, or if the field is already",
"# present.",
"if",
"RECORD_SPECS",
".",
"loc",
"[",
"field",... | Set the object's attribute to its default value if it is missing
and there is a default.
Not responsible for initializing the
attribute. That is done by the constructor. | [
"Set",
"the",
"object",
"s",
"attribute",
"to",
"its",
"default",
"value",
"if",
"it",
"is",
"missing",
"and",
"there",
"is",
"a",
"default",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/_header.py#L345-L384 |
235,201 | MIT-LCP/wfdb-python | wfdb/io/_header.py | HeaderMixin.check_field_cohesion | def check_field_cohesion(self, rec_write_fields, sig_write_fields):
"""
Check the cohesion of fields used to write the header
"""
# If there are no signal specification fields, there is nothing to check.
if self.n_sig>0:
# The length of all signal specification fields must match n_sig
# even if some of its elements are None.
for f in sig_write_fields:
if len(getattr(self, f)) != self.n_sig:
raise ValueError('The length of field: '+f+' must match field n_sig.')
# Each file_name must correspond to only one fmt, (and only one byte offset if defined).
datfmts = {}
for ch in range(self.n_sig):
if self.file_name[ch] not in datfmts:
datfmts[self.file_name[ch]] = self.fmt[ch]
else:
if datfmts[self.file_name[ch]] != self.fmt[ch]:
raise ValueError('Each file_name (dat file) specified must have the same fmt')
datoffsets = {}
if self.byte_offset is not None:
# At least one byte offset value exists
for ch in range(self.n_sig):
if self.byte_offset[ch] is None:
continue
if self.file_name[ch] not in datoffsets:
datoffsets[self.file_name[ch]] = self.byte_offset[ch]
else:
if datoffsets[self.file_name[ch]] != self.byte_offset[ch]:
raise ValueError('Each file_name (dat file) specified must have the same byte offset') | python | def check_field_cohesion(self, rec_write_fields, sig_write_fields):
# If there are no signal specification fields, there is nothing to check.
if self.n_sig>0:
# The length of all signal specification fields must match n_sig
# even if some of its elements are None.
for f in sig_write_fields:
if len(getattr(self, f)) != self.n_sig:
raise ValueError('The length of field: '+f+' must match field n_sig.')
# Each file_name must correspond to only one fmt, (and only one byte offset if defined).
datfmts = {}
for ch in range(self.n_sig):
if self.file_name[ch] not in datfmts:
datfmts[self.file_name[ch]] = self.fmt[ch]
else:
if datfmts[self.file_name[ch]] != self.fmt[ch]:
raise ValueError('Each file_name (dat file) specified must have the same fmt')
datoffsets = {}
if self.byte_offset is not None:
# At least one byte offset value exists
for ch in range(self.n_sig):
if self.byte_offset[ch] is None:
continue
if self.file_name[ch] not in datoffsets:
datoffsets[self.file_name[ch]] = self.byte_offset[ch]
else:
if datoffsets[self.file_name[ch]] != self.byte_offset[ch]:
raise ValueError('Each file_name (dat file) specified must have the same byte offset') | [
"def",
"check_field_cohesion",
"(",
"self",
",",
"rec_write_fields",
",",
"sig_write_fields",
")",
":",
"# If there are no signal specification fields, there is nothing to check.",
"if",
"self",
".",
"n_sig",
">",
"0",
":",
"# The length of all signal specification fields must ma... | Check the cohesion of fields used to write the header | [
"Check",
"the",
"cohesion",
"of",
"fields",
"used",
"to",
"write",
"the",
"header"
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/_header.py#L387-L420 |
235,202 | MIT-LCP/wfdb-python | wfdb/io/_header.py | HeaderMixin.wr_header_file | def wr_header_file(self, rec_write_fields, sig_write_fields, write_dir):
"""
Write a header file using the specified fields. Converts Record
attributes into appropriate wfdb format strings.
Parameters
----------
rec_write_fields : list
List of record specification fields to write
sig_write_fields : dict
Dictionary of signal specification fields to write, values
being equal to a list of channels to write for each field.
write_dir : str
The directory in which to write the header file
"""
# Create record specification line
record_line = ''
# Traverse the ordered dictionary
for field in RECORD_SPECS.index:
# If the field is being used, add it with its delimiter
if field in rec_write_fields:
string_field = str(getattr(self, field))
# Certain fields need extra processing
if field == 'fs' and isinstance(self.fs, float):
if round(self.fs, 8) == float(int(self.fs)):
string_field = str(int(self.fs))
elif field == 'base_time' and '.' in string_field:
string_field = string_field.rstrip('0')
elif field == 'base_date':
string_field = '/'.join((string_field[8:],
string_field[5:7],
string_field[:4]))
record_line += RECORD_SPECS.loc[field, 'delimiter'] + string_field
# The 'base_counter' field needs to be closed with ')'
if field == 'base_counter':
record_line += ')'
header_lines = [record_line]
# Create signal specification lines (if any) one channel at a time
if self.n_sig > 0:
signal_lines = self.n_sig * ['']
for ch in range(self.n_sig):
# Traverse the signal fields
for field in SIGNAL_SPECS.index:
# If the field is being used, add each of its
# elements with the delimiter to the appropriate
# line
if field in sig_write_fields and ch in sig_write_fields[field]:
signal_lines[ch] += SIGNAL_SPECS.loc[field, 'delimiter'] + str(getattr(self, field)[ch])
# The 'baseline' field needs to be closed with ')'
if field == 'baseline':
signal_lines[ch] += ')'
header_lines += signal_lines
# Create comment lines (if any)
if 'comments' in rec_write_fields:
comment_lines = ['# ' + comment for comment in self.comments]
header_lines += comment_lines
lines_to_file(self.record_name + '.hea', write_dir, header_lines) | python | def wr_header_file(self, rec_write_fields, sig_write_fields, write_dir):
# Create record specification line
record_line = ''
# Traverse the ordered dictionary
for field in RECORD_SPECS.index:
# If the field is being used, add it with its delimiter
if field in rec_write_fields:
string_field = str(getattr(self, field))
# Certain fields need extra processing
if field == 'fs' and isinstance(self.fs, float):
if round(self.fs, 8) == float(int(self.fs)):
string_field = str(int(self.fs))
elif field == 'base_time' and '.' in string_field:
string_field = string_field.rstrip('0')
elif field == 'base_date':
string_field = '/'.join((string_field[8:],
string_field[5:7],
string_field[:4]))
record_line += RECORD_SPECS.loc[field, 'delimiter'] + string_field
# The 'base_counter' field needs to be closed with ')'
if field == 'base_counter':
record_line += ')'
header_lines = [record_line]
# Create signal specification lines (if any) one channel at a time
if self.n_sig > 0:
signal_lines = self.n_sig * ['']
for ch in range(self.n_sig):
# Traverse the signal fields
for field in SIGNAL_SPECS.index:
# If the field is being used, add each of its
# elements with the delimiter to the appropriate
# line
if field in sig_write_fields and ch in sig_write_fields[field]:
signal_lines[ch] += SIGNAL_SPECS.loc[field, 'delimiter'] + str(getattr(self, field)[ch])
# The 'baseline' field needs to be closed with ')'
if field == 'baseline':
signal_lines[ch] += ')'
header_lines += signal_lines
# Create comment lines (if any)
if 'comments' in rec_write_fields:
comment_lines = ['# ' + comment for comment in self.comments]
header_lines += comment_lines
lines_to_file(self.record_name + '.hea', write_dir, header_lines) | [
"def",
"wr_header_file",
"(",
"self",
",",
"rec_write_fields",
",",
"sig_write_fields",
",",
"write_dir",
")",
":",
"# Create record specification line",
"record_line",
"=",
"''",
"# Traverse the ordered dictionary",
"for",
"field",
"in",
"RECORD_SPECS",
".",
"index",
"... | Write a header file using the specified fields. Converts Record
attributes into appropriate wfdb format strings.
Parameters
----------
rec_write_fields : list
List of record specification fields to write
sig_write_fields : dict
Dictionary of signal specification fields to write, values
being equal to a list of channels to write for each field.
write_dir : str
The directory in which to write the header file | [
"Write",
"a",
"header",
"file",
"using",
"the",
"specified",
"fields",
".",
"Converts",
"Record",
"attributes",
"into",
"appropriate",
"wfdb",
"format",
"strings",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/_header.py#L423-L489 |
235,203 | MIT-LCP/wfdb-python | wfdb/io/_header.py | MultiHeaderMixin.get_write_fields | def get_write_fields(self):
"""
Get the list of fields used to write the multi-segment header.
Returns the default required fields, the user defined fields,
and their dependencies.
"""
# Record specification fields
write_fields = self.get_write_subset('record')
# Segment specification fields are all mandatory
write_fields = write_fields + ['seg_name', 'seg_len']
# Comments
if self.comments !=None:
write_fields.append('comments')
return write_fields | python | def get_write_fields(self):
# Record specification fields
write_fields = self.get_write_subset('record')
# Segment specification fields are all mandatory
write_fields = write_fields + ['seg_name', 'seg_len']
# Comments
if self.comments !=None:
write_fields.append('comments')
return write_fields | [
"def",
"get_write_fields",
"(",
"self",
")",
":",
"# Record specification fields",
"write_fields",
"=",
"self",
".",
"get_write_subset",
"(",
"'record'",
")",
"# Segment specification fields are all mandatory",
"write_fields",
"=",
"write_fields",
"+",
"[",
"'seg_name'",
... | Get the list of fields used to write the multi-segment header.
Returns the default required fields, the user defined fields,
and their dependencies. | [
"Get",
"the",
"list",
"of",
"fields",
"used",
"to",
"write",
"the",
"multi",
"-",
"segment",
"header",
".",
"Returns",
"the",
"default",
"required",
"fields",
"the",
"user",
"defined",
"fields",
"and",
"their",
"dependencies",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/_header.py#L533-L550 |
235,204 | MIT-LCP/wfdb-python | wfdb/io/_header.py | MultiHeaderMixin.wr_header_file | def wr_header_file(self, write_fields, write_dir):
"""
Write a header file using the specified fields
"""
# Create record specification line
record_line = ''
# Traverse the ordered dictionary
for field in RECORD_SPECS.index:
# If the field is being used, add it with its delimiter
if field in write_fields:
record_line += RECORD_SPECS.loc[field, 'delimiter'] + str(getattr(self, field))
header_lines = [record_line]
# Create segment specification lines
segment_lines = self.n_seg * ['']
# For both fields, add each of its elements with the delimiter
# to the appropriate line
for field in SEGMENT_SPECS.index:
for seg_num in range(self.n_seg):
segment_lines[seg_num] += SEGMENT_SPECS.loc[field, 'delimiter'] + str(getattr(self, field)[seg_num])
header_lines = header_lines + segment_lines
# Create comment lines (if any)
if 'comments' in write_fields:
comment_lines = ['# '+ comment for comment in self.comments]
header_lines += comment_lines
lines_to_file(self.record_name + '.hea', header_lines, write_dir) | python | def wr_header_file(self, write_fields, write_dir):
# Create record specification line
record_line = ''
# Traverse the ordered dictionary
for field in RECORD_SPECS.index:
# If the field is being used, add it with its delimiter
if field in write_fields:
record_line += RECORD_SPECS.loc[field, 'delimiter'] + str(getattr(self, field))
header_lines = [record_line]
# Create segment specification lines
segment_lines = self.n_seg * ['']
# For both fields, add each of its elements with the delimiter
# to the appropriate line
for field in SEGMENT_SPECS.index:
for seg_num in range(self.n_seg):
segment_lines[seg_num] += SEGMENT_SPECS.loc[field, 'delimiter'] + str(getattr(self, field)[seg_num])
header_lines = header_lines + segment_lines
# Create comment lines (if any)
if 'comments' in write_fields:
comment_lines = ['# '+ comment for comment in self.comments]
header_lines += comment_lines
lines_to_file(self.record_name + '.hea', header_lines, write_dir) | [
"def",
"wr_header_file",
"(",
"self",
",",
"write_fields",
",",
"write_dir",
")",
":",
"# Create record specification line",
"record_line",
"=",
"''",
"# Traverse the ordered dictionary",
"for",
"field",
"in",
"RECORD_SPECS",
".",
"index",
":",
"# If the field is being us... | Write a header file using the specified fields | [
"Write",
"a",
"header",
"file",
"using",
"the",
"specified",
"fields"
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/_header.py#L578-L608 |
235,205 | MIT-LCP/wfdb-python | wfdb/processing/basic.py | resample_ann | def resample_ann(resampled_t, ann_sample):
"""
Compute the new annotation indices
Parameters
----------
resampled_t : numpy array
Array of signal locations as returned by scipy.signal.resample
ann_sample : numpy array
Array of annotation locations
Returns
-------
resampled_ann_sample : numpy array
Array of resampled annotation locations
"""
tmp = np.zeros(len(resampled_t), dtype='int16')
j = 0
tprec = resampled_t[j]
for i, v in enumerate(ann_sample):
while True:
d = False
if v < tprec:
j -= 1
tprec = resampled_t[j]
if j+1 == len(resampled_t):
tmp[j] += 1
break
tnow = resampled_t[j+1]
if tprec <= v and v <= tnow:
if v-tprec < tnow-v:
tmp[j] += 1
else:
tmp[j+1] += 1
d = True
j += 1
tprec = tnow
if d:
break
idx = np.where(tmp>0)[0].astype('int64')
res = []
for i in idx:
for j in range(tmp[i]):
res.append(i)
assert len(res) == len(ann_sample)
return np.asarray(res, dtype='int64') | python | def resample_ann(resampled_t, ann_sample):
tmp = np.zeros(len(resampled_t), dtype='int16')
j = 0
tprec = resampled_t[j]
for i, v in enumerate(ann_sample):
while True:
d = False
if v < tprec:
j -= 1
tprec = resampled_t[j]
if j+1 == len(resampled_t):
tmp[j] += 1
break
tnow = resampled_t[j+1]
if tprec <= v and v <= tnow:
if v-tprec < tnow-v:
tmp[j] += 1
else:
tmp[j+1] += 1
d = True
j += 1
tprec = tnow
if d:
break
idx = np.where(tmp>0)[0].astype('int64')
res = []
for i in idx:
for j in range(tmp[i]):
res.append(i)
assert len(res) == len(ann_sample)
return np.asarray(res, dtype='int64') | [
"def",
"resample_ann",
"(",
"resampled_t",
",",
"ann_sample",
")",
":",
"tmp",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"resampled_t",
")",
",",
"dtype",
"=",
"'int16'",
")",
"j",
"=",
"0",
"tprec",
"=",
"resampled_t",
"[",
"j",
"]",
"for",
"i",
"... | Compute the new annotation indices
Parameters
----------
resampled_t : numpy array
Array of signal locations as returned by scipy.signal.resample
ann_sample : numpy array
Array of annotation locations
Returns
-------
resampled_ann_sample : numpy array
Array of resampled annotation locations | [
"Compute",
"the",
"new",
"annotation",
"indices"
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/basic.py#L7-L57 |
235,206 | MIT-LCP/wfdb-python | wfdb/processing/basic.py | resample_sig | def resample_sig(x, fs, fs_target):
"""
Resample a signal to a different frequency.
Parameters
----------
x : numpy array
Array containing the signal
fs : int, or float
The original sampling frequency
fs_target : int, or float
The target frequency
Returns
-------
resampled_x : numpy array
Array of the resampled signal values
resampled_t : numpy array
Array of the resampled signal locations
"""
t = np.arange(x.shape[0]).astype('float64')
if fs == fs_target:
return x, t
new_length = int(x.shape[0]*fs_target/fs)
resampled_x, resampled_t = signal.resample(x, num=new_length, t=t)
assert resampled_x.shape == resampled_t.shape and resampled_x.shape[0] == new_length
assert np.all(np.diff(resampled_t) > 0)
return resampled_x, resampled_t | python | def resample_sig(x, fs, fs_target):
t = np.arange(x.shape[0]).astype('float64')
if fs == fs_target:
return x, t
new_length = int(x.shape[0]*fs_target/fs)
resampled_x, resampled_t = signal.resample(x, num=new_length, t=t)
assert resampled_x.shape == resampled_t.shape and resampled_x.shape[0] == new_length
assert np.all(np.diff(resampled_t) > 0)
return resampled_x, resampled_t | [
"def",
"resample_sig",
"(",
"x",
",",
"fs",
",",
"fs_target",
")",
":",
"t",
"=",
"np",
".",
"arange",
"(",
"x",
".",
"shape",
"[",
"0",
"]",
")",
".",
"astype",
"(",
"'float64'",
")",
"if",
"fs",
"==",
"fs_target",
":",
"return",
"x",
",",
"t"... | Resample a signal to a different frequency.
Parameters
----------
x : numpy array
Array containing the signal
fs : int, or float
The original sampling frequency
fs_target : int, or float
The target frequency
Returns
-------
resampled_x : numpy array
Array of the resampled signal values
resampled_t : numpy array
Array of the resampled signal locations | [
"Resample",
"a",
"signal",
"to",
"a",
"different",
"frequency",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/basic.py#L60-L92 |
235,207 | MIT-LCP/wfdb-python | wfdb/processing/basic.py | resample_singlechan | def resample_singlechan(x, ann, fs, fs_target):
"""
Resample a single-channel signal with its annotations
Parameters
----------
x: numpy array
The signal array
ann : wfdb Annotation
The wfdb annotation object
fs : int, or float
The original frequency
fs_target : int, or float
The target frequency
Returns
-------
resampled_x : numpy array
Array of the resampled signal values
resampled_ann : wfdb Annotation
Annotation containing resampled annotation locations
"""
resampled_x, resampled_t = resample_sig(x, fs, fs_target)
new_sample = resample_ann(resampled_t, ann.sample)
assert ann.sample.shape == new_sample.shape
resampled_ann = Annotation(record_name=ann.record_name,
extension=ann.extension,
sample=new_sample,
symbol=ann.symbol,
subtype=ann.subtype,
chan=ann.chan,
num=ann.num,
aux_note=ann.aux_note,
fs=fs_target)
return resampled_x, resampled_ann | python | def resample_singlechan(x, ann, fs, fs_target):
resampled_x, resampled_t = resample_sig(x, fs, fs_target)
new_sample = resample_ann(resampled_t, ann.sample)
assert ann.sample.shape == new_sample.shape
resampled_ann = Annotation(record_name=ann.record_name,
extension=ann.extension,
sample=new_sample,
symbol=ann.symbol,
subtype=ann.subtype,
chan=ann.chan,
num=ann.num,
aux_note=ann.aux_note,
fs=fs_target)
return resampled_x, resampled_ann | [
"def",
"resample_singlechan",
"(",
"x",
",",
"ann",
",",
"fs",
",",
"fs_target",
")",
":",
"resampled_x",
",",
"resampled_t",
"=",
"resample_sig",
"(",
"x",
",",
"fs",
",",
"fs_target",
")",
"new_sample",
"=",
"resample_ann",
"(",
"resampled_t",
",",
"ann"... | Resample a single-channel signal with its annotations
Parameters
----------
x: numpy array
The signal array
ann : wfdb Annotation
The wfdb annotation object
fs : int, or float
The original frequency
fs_target : int, or float
The target frequency
Returns
-------
resampled_x : numpy array
Array of the resampled signal values
resampled_ann : wfdb Annotation
Annotation containing resampled annotation locations | [
"Resample",
"a",
"single",
"-",
"channel",
"signal",
"with",
"its",
"annotations"
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/basic.py#L95-L134 |
235,208 | MIT-LCP/wfdb-python | wfdb/processing/basic.py | resample_multichan | def resample_multichan(xs, ann, fs, fs_target, resamp_ann_chan=0):
"""
Resample multiple channels with their annotations
Parameters
----------
xs: numpy array
The signal array
ann : wfdb Annotation
The wfdb annotation object
fs : int, or float
The original frequency
fs_target : int, or float
The target frequency
resample_ann_channel : int, optional
The signal channel used to compute new annotation indices
Returns
-------
resampled_xs : numpy array
Array of the resampled signal values
resampled_ann : wfdb Annotation
Annotation containing resampled annotation locations
"""
assert resamp_ann_chan < xs.shape[1]
lx = []
lt = None
for chan in range(xs.shape[1]):
resampled_x, resampled_t = resample_sig(xs[:, chan], fs, fs_target)
lx.append(resampled_x)
if chan == resamp_ann_chan:
lt = resampled_t
new_sample = resample_ann(lt, ann.sample)
assert ann.sample.shape == new_sample.shape
resampled_ann = Annotation(record_name=ann.record_name,
extension=ann.extension,
sample=new_sample,
symbol=ann.symbol,
subtype=ann.subtype,
chan=ann.chan,
num=ann.num,
aux_note=ann.aux_note,
fs=fs_target)
return np.column_stack(lx), resampled_ann | python | def resample_multichan(xs, ann, fs, fs_target, resamp_ann_chan=0):
assert resamp_ann_chan < xs.shape[1]
lx = []
lt = None
for chan in range(xs.shape[1]):
resampled_x, resampled_t = resample_sig(xs[:, chan], fs, fs_target)
lx.append(resampled_x)
if chan == resamp_ann_chan:
lt = resampled_t
new_sample = resample_ann(lt, ann.sample)
assert ann.sample.shape == new_sample.shape
resampled_ann = Annotation(record_name=ann.record_name,
extension=ann.extension,
sample=new_sample,
symbol=ann.symbol,
subtype=ann.subtype,
chan=ann.chan,
num=ann.num,
aux_note=ann.aux_note,
fs=fs_target)
return np.column_stack(lx), resampled_ann | [
"def",
"resample_multichan",
"(",
"xs",
",",
"ann",
",",
"fs",
",",
"fs_target",
",",
"resamp_ann_chan",
"=",
"0",
")",
":",
"assert",
"resamp_ann_chan",
"<",
"xs",
".",
"shape",
"[",
"1",
"]",
"lx",
"=",
"[",
"]",
"lt",
"=",
"None",
"for",
"chan",
... | Resample multiple channels with their annotations
Parameters
----------
xs: numpy array
The signal array
ann : wfdb Annotation
The wfdb annotation object
fs : int, or float
The original frequency
fs_target : int, or float
The target frequency
resample_ann_channel : int, optional
The signal channel used to compute new annotation indices
Returns
-------
resampled_xs : numpy array
Array of the resampled signal values
resampled_ann : wfdb Annotation
Annotation containing resampled annotation locations | [
"Resample",
"multiple",
"channels",
"with",
"their",
"annotations"
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/basic.py#L137-L185 |
235,209 | MIT-LCP/wfdb-python | wfdb/processing/basic.py | normalize_bound | def normalize_bound(sig, lb=0, ub=1):
"""
Normalize a signal between the lower and upper bound
Parameters
----------
sig : numpy array
Original signal to be normalized
lb : int, or float
Lower bound
ub : int, or float
Upper bound
Returns
-------
x_normalized : numpy array
Normalized signal
"""
mid = ub - (ub - lb) / 2
min_v = np.min(sig)
max_v = np.max(sig)
mid_v = max_v - (max_v - min_v) / 2
coef = (ub - lb) / (max_v - min_v)
return sig * coef - (mid_v * coef) + mid | python | def normalize_bound(sig, lb=0, ub=1):
mid = ub - (ub - lb) / 2
min_v = np.min(sig)
max_v = np.max(sig)
mid_v = max_v - (max_v - min_v) / 2
coef = (ub - lb) / (max_v - min_v)
return sig * coef - (mid_v * coef) + mid | [
"def",
"normalize_bound",
"(",
"sig",
",",
"lb",
"=",
"0",
",",
"ub",
"=",
"1",
")",
":",
"mid",
"=",
"ub",
"-",
"(",
"ub",
"-",
"lb",
")",
"/",
"2",
"min_v",
"=",
"np",
".",
"min",
"(",
"sig",
")",
"max_v",
"=",
"np",
".",
"max",
"(",
"s... | Normalize a signal between the lower and upper bound
Parameters
----------
sig : numpy array
Original signal to be normalized
lb : int, or float
Lower bound
ub : int, or float
Upper bound
Returns
-------
x_normalized : numpy array
Normalized signal | [
"Normalize",
"a",
"signal",
"between",
"the",
"lower",
"and",
"upper",
"bound"
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/basic.py#L188-L213 |
235,210 | MIT-LCP/wfdb-python | wfdb/processing/basic.py | smooth | def smooth(sig, window_size):
"""
Apply a uniform moving average filter to a signal
Parameters
----------
sig : numpy array
The signal to smooth.
window_size : int
The width of the moving average filter.
"""
box = np.ones(window_size)/window_size
return np.convolve(sig, box, mode='same') | python | def smooth(sig, window_size):
box = np.ones(window_size)/window_size
return np.convolve(sig, box, mode='same') | [
"def",
"smooth",
"(",
"sig",
",",
"window_size",
")",
":",
"box",
"=",
"np",
".",
"ones",
"(",
"window_size",
")",
"/",
"window_size",
"return",
"np",
".",
"convolve",
"(",
"sig",
",",
"box",
",",
"mode",
"=",
"'same'",
")"
] | Apply a uniform moving average filter to a signal
Parameters
----------
sig : numpy array
The signal to smooth.
window_size : int
The width of the moving average filter. | [
"Apply",
"a",
"uniform",
"moving",
"average",
"filter",
"to",
"a",
"signal"
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/basic.py#L216-L229 |
235,211 | MIT-LCP/wfdb-python | wfdb/processing/basic.py | get_filter_gain | def get_filter_gain(b, a, f_gain, fs):
"""
Given filter coefficients, return the gain at a particular
frequency.
Parameters
----------
b : list
List of linear filter b coefficients
a : list
List of linear filter a coefficients
f_gain : int or float, optional
The frequency at which to calculate the gain
fs : int or float, optional
The sampling frequency of the system
"""
# Save the passband gain
w, h = signal.freqz(b, a)
w_gain = f_gain * 2 * np.pi / fs
ind = np.where(w >= w_gain)[0][0]
gain = abs(h[ind])
return gain | python | def get_filter_gain(b, a, f_gain, fs):
# Save the passband gain
w, h = signal.freqz(b, a)
w_gain = f_gain * 2 * np.pi / fs
ind = np.where(w >= w_gain)[0][0]
gain = abs(h[ind])
return gain | [
"def",
"get_filter_gain",
"(",
"b",
",",
"a",
",",
"f_gain",
",",
"fs",
")",
":",
"# Save the passband gain",
"w",
",",
"h",
"=",
"signal",
".",
"freqz",
"(",
"b",
",",
"a",
")",
"w_gain",
"=",
"f_gain",
"*",
"2",
"*",
"np",
".",
"pi",
"/",
"fs",... | Given filter coefficients, return the gain at a particular
frequency.
Parameters
----------
b : list
List of linear filter b coefficients
a : list
List of linear filter a coefficients
f_gain : int or float, optional
The frequency at which to calculate the gain
fs : int or float, optional
The sampling frequency of the system | [
"Given",
"filter",
"coefficients",
"return",
"the",
"gain",
"at",
"a",
"particular",
"frequency",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/basic.py#L232-L256 |
235,212 | MIT-LCP/wfdb-python | wfdb/io/record.py | _check_item_type | def _check_item_type(item, field_name, allowed_types, expect_list=False,
required_channels='all'):
"""
Check the item's type against a set of allowed types.
Vary the print message regarding whether the item can be None.
Helper to `BaseRecord.check_field`.
Parameters
----------
item : any
The item to check.
field_name : str
The field name.
allowed_types : iterable
Iterable of types the item is allowed to be.
expect_list : bool, optional
Whether the item is expected to be a list.
required_channels : list, optional
List of integers specifying which channels of the item must be
present. May be set to 'all' to indicate all channels. Only used
if `expect_list` is True, ie. item is a list, and its
subelements are to be checked.
Notes
-----
This is called by `check_field`, which determines whether the item
should be a list or not. This function should generally not be
called by the user directly.
"""
if expect_list:
if not isinstance(item, list):
raise TypeError('Field `%s` must be a list.' % field_name)
# All channels of the field must be present.
if required_channels == 'all':
required_channels = list(range(len(item)))
for ch in range(len(item)):
# Check whether the field may be None
if ch in required_channels:
allowed_types_ch = allowed_types
else:
allowed_types_ch = allowed_types + (type(None),)
if not isinstance(item[ch], allowed_types_ch):
raise TypeError('Channel %d of field `%s` must be one of the following types:' % (ch, field_name),
allowed_types_ch)
else:
if not isinstance(item, allowed_types):
raise TypeError('Field `%s` must be one of the following types:',
allowed_types) | python | def _check_item_type(item, field_name, allowed_types, expect_list=False,
required_channels='all'):
if expect_list:
if not isinstance(item, list):
raise TypeError('Field `%s` must be a list.' % field_name)
# All channels of the field must be present.
if required_channels == 'all':
required_channels = list(range(len(item)))
for ch in range(len(item)):
# Check whether the field may be None
if ch in required_channels:
allowed_types_ch = allowed_types
else:
allowed_types_ch = allowed_types + (type(None),)
if not isinstance(item[ch], allowed_types_ch):
raise TypeError('Channel %d of field `%s` must be one of the following types:' % (ch, field_name),
allowed_types_ch)
else:
if not isinstance(item, allowed_types):
raise TypeError('Field `%s` must be one of the following types:',
allowed_types) | [
"def",
"_check_item_type",
"(",
"item",
",",
"field_name",
",",
"allowed_types",
",",
"expect_list",
"=",
"False",
",",
"required_channels",
"=",
"'all'",
")",
":",
"if",
"expect_list",
":",
"if",
"not",
"isinstance",
"(",
"item",
",",
"list",
")",
":",
"r... | Check the item's type against a set of allowed types.
Vary the print message regarding whether the item can be None.
Helper to `BaseRecord.check_field`.
Parameters
----------
item : any
The item to check.
field_name : str
The field name.
allowed_types : iterable
Iterable of types the item is allowed to be.
expect_list : bool, optional
Whether the item is expected to be a list.
required_channels : list, optional
List of integers specifying which channels of the item must be
present. May be set to 'all' to indicate all channels. Only used
if `expect_list` is True, ie. item is a list, and its
subelements are to be checked.
Notes
-----
This is called by `check_field`, which determines whether the item
should be a list or not. This function should generally not be
called by the user directly. | [
"Check",
"the",
"item",
"s",
"type",
"against",
"a",
"set",
"of",
"allowed",
"types",
".",
"Vary",
"the",
"print",
"message",
"regarding",
"whether",
"the",
"item",
"can",
"be",
"None",
".",
"Helper",
"to",
"BaseRecord",
".",
"check_field",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/record.py#L858-L909 |
235,213 | MIT-LCP/wfdb-python | wfdb/io/record.py | check_np_array | def check_np_array(item, field_name, ndim, parent_class, channel_num=None):
"""
Check a numpy array's shape and dtype against required
specifications.
Parameters
----------
item : numpy array
The numpy array to check
field_name : str
The name of the field to check
ndim : int
The required number of dimensions
parent_class : type
The parent class of the dtype. ie. np.integer, np.floating.
channel_num : int, optional
If not None, indicates that the item passed in is a subelement
of a list. Indicate this in the error message if triggered.
"""
# Check shape
if item.ndim != ndim:
error_msg = 'Field `%s` must have ndim == %d' % (field_name, ndim)
if channel_num is not None:
error_msg = ('Channel %d of f' % channel_num) + error_msg[1:]
raise TypeError(error_msg)
# Check dtype
if not np.issubdtype(item.dtype, parent_class):
error_msg = 'Field `%s` must have a dtype that subclasses %s' % (field_name, parent_class)
if channel_num is not None:
error_msg = ('Channel %d of f' % channel_num) + error_msg[1:]
raise TypeError(error_msg) | python | def check_np_array(item, field_name, ndim, parent_class, channel_num=None):
# Check shape
if item.ndim != ndim:
error_msg = 'Field `%s` must have ndim == %d' % (field_name, ndim)
if channel_num is not None:
error_msg = ('Channel %d of f' % channel_num) + error_msg[1:]
raise TypeError(error_msg)
# Check dtype
if not np.issubdtype(item.dtype, parent_class):
error_msg = 'Field `%s` must have a dtype that subclasses %s' % (field_name, parent_class)
if channel_num is not None:
error_msg = ('Channel %d of f' % channel_num) + error_msg[1:]
raise TypeError(error_msg) | [
"def",
"check_np_array",
"(",
"item",
",",
"field_name",
",",
"ndim",
",",
"parent_class",
",",
"channel_num",
"=",
"None",
")",
":",
"# Check shape",
"if",
"item",
".",
"ndim",
"!=",
"ndim",
":",
"error_msg",
"=",
"'Field `%s` must have ndim == %d'",
"%",
"("... | Check a numpy array's shape and dtype against required
specifications.
Parameters
----------
item : numpy array
The numpy array to check
field_name : str
The name of the field to check
ndim : int
The required number of dimensions
parent_class : type
The parent class of the dtype. ie. np.integer, np.floating.
channel_num : int, optional
If not None, indicates that the item passed in is a subelement
of a list. Indicate this in the error message if triggered. | [
"Check",
"a",
"numpy",
"array",
"s",
"shape",
"and",
"dtype",
"against",
"required",
"specifications",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/record.py#L912-L944 |
235,214 | MIT-LCP/wfdb-python | wfdb/io/record.py | rdheader | def rdheader(record_name, pb_dir=None, rd_segments=False):
"""
Read a WFDB header file and return a `Record` or `MultiRecord`
object with the record descriptors as attributes.
Parameters
----------
record_name : str
The name of the WFDB record to be read, without any file
extensions. If the argument contains any path delimiter
characters, the argument will be interpreted as PATH/BASE_RECORD.
Both relative and absolute paths are accepted. If the `pb_dir`
parameter is set, this parameter should contain just the base
record name, and the files fill be searched for remotely.
Otherwise, the data files will be searched for in the local path.
pb_dir : str, optional
Option used to stream data from Physiobank. The Physiobank
database directory from which to find the required record files.
eg. For record '100' in 'http://physionet.org/physiobank/database/mitdb'
pb_dir='mitdb'.
rd_segments : bool, optional
Used when reading multi-segment headers. If True, segment headers will
also be read (into the record object's `segments` field).
Returns
-------
record : Record or MultiRecord
The wfdb Record or MultiRecord object representing the contents
of the header read.
Examples
--------
>>> ecg_record = wfdb.rdheader('sample-data/test01_00s', sampfrom=800,
channels = [1,3])
"""
dir_name, base_record_name = os.path.split(record_name)
dir_name = os.path.abspath(dir_name)
# Read the header file. Separate comment and non-comment lines
header_lines, comment_lines = _header._read_header_lines(base_record_name,
dir_name, pb_dir)
# Get fields from record line
record_fields = _header._parse_record_line(header_lines[0])
# Single segment header - Process signal specification lines
if record_fields['n_seg'] is None:
# Create a single-segment WFDB record object
record = Record()
# There are signals
if len(header_lines)>1:
# Read the fields from the signal lines
signal_fields = _header._parse_signal_lines(header_lines[1:])
# Set the object's signal fields
for field in signal_fields:
setattr(record, field, signal_fields[field])
# Set the object's record line fields
for field in record_fields:
if field == 'n_seg':
continue
setattr(record, field, record_fields[field])
# Multi segment header - Process segment specification lines
else:
# Create a multi-segment WFDB record object
record = MultiRecord()
# Read the fields from the segment lines
segment_fields = _header._read_segment_lines(header_lines[1:])
# Set the object's segment fields
for field in segment_fields:
setattr(record, field, segment_fields[field])
# Set the objects' record fields
for field in record_fields:
setattr(record, field, record_fields[field])
# Determine whether the record is fixed or variable
if record.seg_len[0] == 0:
record.layout = 'variable'
else:
record.layout = 'fixed'
# If specified, read the segment headers
if rd_segments:
record.segments = []
# Get the base record name (could be empty)
for s in record.seg_name:
if s == '~':
record.segments.append(None)
else:
record.segments.append(rdheader(os.path.join(dir_name, s),
pb_dir))
# Fill in the sig_name attribute
record.sig_name = record.get_sig_name()
# Fill in the sig_segments attribute
record.sig_segments = record.get_sig_segments()
# Set the comments field
record.comments = [line.strip(' \t#') for line in comment_lines]
return record | python | def rdheader(record_name, pb_dir=None, rd_segments=False):
dir_name, base_record_name = os.path.split(record_name)
dir_name = os.path.abspath(dir_name)
# Read the header file. Separate comment and non-comment lines
header_lines, comment_lines = _header._read_header_lines(base_record_name,
dir_name, pb_dir)
# Get fields from record line
record_fields = _header._parse_record_line(header_lines[0])
# Single segment header - Process signal specification lines
if record_fields['n_seg'] is None:
# Create a single-segment WFDB record object
record = Record()
# There are signals
if len(header_lines)>1:
# Read the fields from the signal lines
signal_fields = _header._parse_signal_lines(header_lines[1:])
# Set the object's signal fields
for field in signal_fields:
setattr(record, field, signal_fields[field])
# Set the object's record line fields
for field in record_fields:
if field == 'n_seg':
continue
setattr(record, field, record_fields[field])
# Multi segment header - Process segment specification lines
else:
# Create a multi-segment WFDB record object
record = MultiRecord()
# Read the fields from the segment lines
segment_fields = _header._read_segment_lines(header_lines[1:])
# Set the object's segment fields
for field in segment_fields:
setattr(record, field, segment_fields[field])
# Set the objects' record fields
for field in record_fields:
setattr(record, field, record_fields[field])
# Determine whether the record is fixed or variable
if record.seg_len[0] == 0:
record.layout = 'variable'
else:
record.layout = 'fixed'
# If specified, read the segment headers
if rd_segments:
record.segments = []
# Get the base record name (could be empty)
for s in record.seg_name:
if s == '~':
record.segments.append(None)
else:
record.segments.append(rdheader(os.path.join(dir_name, s),
pb_dir))
# Fill in the sig_name attribute
record.sig_name = record.get_sig_name()
# Fill in the sig_segments attribute
record.sig_segments = record.get_sig_segments()
# Set the comments field
record.comments = [line.strip(' \t#') for line in comment_lines]
return record | [
"def",
"rdheader",
"(",
"record_name",
",",
"pb_dir",
"=",
"None",
",",
"rd_segments",
"=",
"False",
")",
":",
"dir_name",
",",
"base_record_name",
"=",
"os",
".",
"path",
".",
"split",
"(",
"record_name",
")",
"dir_name",
"=",
"os",
".",
"path",
".",
... | Read a WFDB header file and return a `Record` or `MultiRecord`
object with the record descriptors as attributes.
Parameters
----------
record_name : str
The name of the WFDB record to be read, without any file
extensions. If the argument contains any path delimiter
characters, the argument will be interpreted as PATH/BASE_RECORD.
Both relative and absolute paths are accepted. If the `pb_dir`
parameter is set, this parameter should contain just the base
record name, and the files fill be searched for remotely.
Otherwise, the data files will be searched for in the local path.
pb_dir : str, optional
Option used to stream data from Physiobank. The Physiobank
database directory from which to find the required record files.
eg. For record '100' in 'http://physionet.org/physiobank/database/mitdb'
pb_dir='mitdb'.
rd_segments : bool, optional
Used when reading multi-segment headers. If True, segment headers will
also be read (into the record object's `segments` field).
Returns
-------
record : Record or MultiRecord
The wfdb Record or MultiRecord object representing the contents
of the header read.
Examples
--------
>>> ecg_record = wfdb.rdheader('sample-data/test01_00s', sampfrom=800,
channels = [1,3]) | [
"Read",
"a",
"WFDB",
"header",
"file",
"and",
"return",
"a",
"Record",
"or",
"MultiRecord",
"object",
"with",
"the",
"record",
"descriptors",
"as",
"attributes",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/record.py#L950-L1051 |
235,215 | MIT-LCP/wfdb-python | wfdb/io/record.py | rdsamp | def rdsamp(record_name, sampfrom=0, sampto=None, channels=None, pb_dir=None,
channel_names=None, warn_empty=False):
"""
Read a WFDB record, and return the physical signals and a few important
descriptor fields.
Parameters
----------
record_name : str
The name of the WFDB record to be read (without any file
extensions). If the argument contains any path delimiter
characters, the argument will be interpreted as PATH/baserecord
and the data files will be searched for in the local path.
sampfrom : int, optional
The starting sample number to read for all channels.
sampto : int, or 'end', optional
The sample number at which to stop reading for all channels.
Reads the entire duration by default.
channels : list, optional
List of integer indices specifying the channels to be read.
Reads all channels by default.
pb_dir : str, optional
Option used to stream data from Physiobank. The Physiobank
database directory from which to find the required record files.
eg. For record '100' in 'http://physionet.org/physiobank/database/mitdb'
pb_dir='mitdb'.
channel_names : list, optional
List of channel names to return. If this parameter is specified,
it takes precedence over `channels`.
warn_empty : bool, optional
Whether to display a warning if the specified channel indices
or names are not contained in the record, and no signal is
returned.
Returns
-------
signals : numpy array
A 2d numpy array storing the physical signals from the record.
fields : dict
A dictionary containing several key attributes of the read
record:
- fs: The sampling frequency of the record
- units: The units for each channel
- sig_name: The signal name for each channel
- comments: Any comments written in the header
Notes
-----
If a signal range or channel selection is specified when calling
this function, the resulting attributes of the returned object will
be set to reflect the section of the record that is actually read,
rather than necessarily the entire record. For example, if
`channels=[0, 1, 2]` is specified when reading a 12 channel record,
the 'n_sig' attribute will be 3, not 12.
The `rdrecord` function is the base function upon which this one is
built. It returns all attributes present, along with the signals, as
attributes in a `Record` object. The function, along with the
returned data type, has more options than `rdsamp` for users who
wish to more directly manipulate WFDB content.
Examples
--------
>>> signals, fields = wfdb.rdsamp('sample-data/test01_00s',
sampfrom=800,
channel =[1,3])
"""
record = rdrecord(record_name=record_name, sampfrom=sampfrom,
sampto=sampto, channels=channels, physical=True,
pb_dir=pb_dir, m2s=True, channel_names=channel_names,
warn_empty=warn_empty)
signals = record.p_signal
fields = {}
for field in ['fs','sig_len', 'n_sig', 'base_date', 'base_time',
'units','sig_name', 'comments']:
fields[field] = getattr(record, field)
return signals, fields | python | def rdsamp(record_name, sampfrom=0, sampto=None, channels=None, pb_dir=None,
channel_names=None, warn_empty=False):
record = rdrecord(record_name=record_name, sampfrom=sampfrom,
sampto=sampto, channels=channels, physical=True,
pb_dir=pb_dir, m2s=True, channel_names=channel_names,
warn_empty=warn_empty)
signals = record.p_signal
fields = {}
for field in ['fs','sig_len', 'n_sig', 'base_date', 'base_time',
'units','sig_name', 'comments']:
fields[field] = getattr(record, field)
return signals, fields | [
"def",
"rdsamp",
"(",
"record_name",
",",
"sampfrom",
"=",
"0",
",",
"sampto",
"=",
"None",
",",
"channels",
"=",
"None",
",",
"pb_dir",
"=",
"None",
",",
"channel_names",
"=",
"None",
",",
"warn_empty",
"=",
"False",
")",
":",
"record",
"=",
"rdrecord... | Read a WFDB record, and return the physical signals and a few important
descriptor fields.
Parameters
----------
record_name : str
The name of the WFDB record to be read (without any file
extensions). If the argument contains any path delimiter
characters, the argument will be interpreted as PATH/baserecord
and the data files will be searched for in the local path.
sampfrom : int, optional
The starting sample number to read for all channels.
sampto : int, or 'end', optional
The sample number at which to stop reading for all channels.
Reads the entire duration by default.
channels : list, optional
List of integer indices specifying the channels to be read.
Reads all channels by default.
pb_dir : str, optional
Option used to stream data from Physiobank. The Physiobank
database directory from which to find the required record files.
eg. For record '100' in 'http://physionet.org/physiobank/database/mitdb'
pb_dir='mitdb'.
channel_names : list, optional
List of channel names to return. If this parameter is specified,
it takes precedence over `channels`.
warn_empty : bool, optional
Whether to display a warning if the specified channel indices
or names are not contained in the record, and no signal is
returned.
Returns
-------
signals : numpy array
A 2d numpy array storing the physical signals from the record.
fields : dict
A dictionary containing several key attributes of the read
record:
- fs: The sampling frequency of the record
- units: The units for each channel
- sig_name: The signal name for each channel
- comments: Any comments written in the header
Notes
-----
If a signal range or channel selection is specified when calling
this function, the resulting attributes of the returned object will
be set to reflect the section of the record that is actually read,
rather than necessarily the entire record. For example, if
`channels=[0, 1, 2]` is specified when reading a 12 channel record,
the 'n_sig' attribute will be 3, not 12.
The `rdrecord` function is the base function upon which this one is
built. It returns all attributes present, along with the signals, as
attributes in a `Record` object. The function, along with the
returned data type, has more options than `rdsamp` for users who
wish to more directly manipulate WFDB content.
Examples
--------
>>> signals, fields = wfdb.rdsamp('sample-data/test01_00s',
sampfrom=800,
channel =[1,3]) | [
"Read",
"a",
"WFDB",
"record",
"and",
"return",
"the",
"physical",
"signals",
"and",
"a",
"few",
"important",
"descriptor",
"fields",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/record.py#L1323-L1402 |
235,216 | MIT-LCP/wfdb-python | wfdb/io/record.py | _get_wanted_channels | def _get_wanted_channels(wanted_sig_names, record_sig_names, pad=False):
"""
Given some wanted signal names, and the signal names contained in a
record, return the indices of the record channels that intersect.
Parameters
----------
wanted_sig_names : list
List of desired signal name strings
record_sig_names : list
List of signal names for a single record
pad : bool, optional
Whether the output channels is to always have the same number
of elements and the wanted channels. If True, pads missing
signals with None.
Returns
-------
wanted_channel_inds
"""
if pad:
return [record_sig_names.index(s) if s in record_sig_names else None for s in wanted_sig_names]
else:
return [record_sig_names.index(s) for s in wanted_sig_names if s in record_sig_names] | python | def _get_wanted_channels(wanted_sig_names, record_sig_names, pad=False):
if pad:
return [record_sig_names.index(s) if s in record_sig_names else None for s in wanted_sig_names]
else:
return [record_sig_names.index(s) for s in wanted_sig_names if s in record_sig_names] | [
"def",
"_get_wanted_channels",
"(",
"wanted_sig_names",
",",
"record_sig_names",
",",
"pad",
"=",
"False",
")",
":",
"if",
"pad",
":",
"return",
"[",
"record_sig_names",
".",
"index",
"(",
"s",
")",
"if",
"s",
"in",
"record_sig_names",
"else",
"None",
"for",... | Given some wanted signal names, and the signal names contained in a
record, return the indices of the record channels that intersect.
Parameters
----------
wanted_sig_names : list
List of desired signal name strings
record_sig_names : list
List of signal names for a single record
pad : bool, optional
Whether the output channels is to always have the same number
of elements and the wanted channels. If True, pads missing
signals with None.
Returns
-------
wanted_channel_inds | [
"Given",
"some",
"wanted",
"signal",
"names",
"and",
"the",
"signal",
"names",
"contained",
"in",
"a",
"record",
"return",
"the",
"indices",
"of",
"the",
"record",
"channels",
"that",
"intersect",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/record.py#L1405-L1429 |
235,217 | MIT-LCP/wfdb-python | wfdb/io/record.py | wrsamp | def wrsamp(record_name, fs, units, sig_name, p_signal=None, d_signal=None,
fmt=None, adc_gain=None, baseline=None, comments=None,
base_time=None, base_date=None, write_dir=''):
"""
Write a single segment WFDB record, creating a WFDB header file and any
associated dat files.
Parameters
----------
record_name : str
The string name of the WFDB record to be written (without any file
extensions).
fs : int, or float
The sampling frequency of the record.
units : list
A list of strings giving the units of each signal channel.
sig_name :
A list of strings giving the signal name of each signal channel.
p_signal : numpy array, optional
An (MxN) 2d numpy array, where M is the signal length. Gives the
physical signal values intended to be written. Either p_signal or
d_signal must be set, but not both. If p_signal is set, this method will
use it to perform analogue-digital conversion, writing the resultant
digital values to the dat file(s). If fmt is set, gain and baseline must
be set or unset together. If fmt is unset, gain and baseline must both
be unset.
d_signal : numpy array, optional
An (MxN) 2d numpy array, where M is the signal length. Gives the
digital signal values intended to be directly written to the dat
file(s). The dtype must be an integer type. Either p_signal or d_signal
must be set, but not both. In addition, if d_signal is set, fmt, gain
and baseline must also all be set.
fmt : list, optional
A list of strings giving the WFDB format of each file used to store each
channel. Accepted formats are: '80','212",'16','24', and '32'. There are
other WFDB formats as specified by:
https://www.physionet.org/physiotools/wag/signal-5.htm
but this library will not write (though it will read) those file types.
adc_gain : list, optional
A list of numbers specifying the ADC gain.
baseline : list, optional
A list of integers specifying the digital baseline.
comments : list, optional
A list of string comments to be written to the header file.
base_time : str, optional
A string of the record's start time in 24h 'HH:MM:SS(.ms)' format.
base_date : str, optional
A string of the record's start date in 'DD/MM/YYYY' format.
write_dir : str, optional
The directory in which to write the files.
Notes
-----
This is a gateway function, written as a simple method to write WFDB record
files using the most common parameters. Therefore not all WFDB fields can be
set via this function.
For more control over attributes, create a `Record` object, manually set its
attributes, and call its `wrsamp` instance method. If you choose this more
advanced method, see also the `set_defaults`, `set_d_features`, and
`set_p_features` instance methods to help populate attributes.
Examples
--------
>>> # Read part of a record from Physiobank
>>> signals, fields = wfdb.rdsamp('a103l', sampfrom=50000, channels=[0,1],
pb_dir='challenge/2015/training')
>>> # Write a local WFDB record (manually inserting fields)
>>> wfdb.wrsamp('ecgrecord', fs = 250, units=['mV', 'mV'],
sig_name=['I', 'II'], p_signal=signals, fmt=['16', '16'])
"""
# Check input field combinations
if p_signal is not None and d_signal is not None:
raise Exception('Must only give one of the inputs: p_signal or d_signal')
if d_signal is not None:
if fmt is None or adc_gain is None or baseline is None:
raise Exception("When using d_signal, must also specify 'fmt', 'gain', and 'baseline' fields.")
# Depending on whether d_signal or p_signal was used, set other
# required features.
if p_signal is not None:
# Create the Record object
record = Record(record_name=record_name, p_signal=p_signal, fs=fs,
fmt=fmt, units=units, sig_name=sig_name,
adc_gain=adc_gain, baseline=baseline,
comments=comments, base_time=base_time,
base_date=base_date)
# Compute optimal fields to store the digital signal, carry out adc,
# and set the fields.
record.set_d_features(do_adc=1)
else:
# Create the Record object
record = Record(record_name=record_name, d_signal=d_signal, fs=fs,
fmt=fmt, units=units, sig_name=sig_name,
adc_gain=adc_gain, baseline=baseline,
comments=comments, base_time=base_time,
base_date=base_date)
# Use d_signal to set the fields directly
record.set_d_features()
# Set default values of any missing field dependencies
record.set_defaults()
# Write the record files - header and associated dat
record.wrsamp(write_dir=write_dir) | python | def wrsamp(record_name, fs, units, sig_name, p_signal=None, d_signal=None,
fmt=None, adc_gain=None, baseline=None, comments=None,
base_time=None, base_date=None, write_dir=''):
# Check input field combinations
if p_signal is not None and d_signal is not None:
raise Exception('Must only give one of the inputs: p_signal or d_signal')
if d_signal is not None:
if fmt is None or adc_gain is None or baseline is None:
raise Exception("When using d_signal, must also specify 'fmt', 'gain', and 'baseline' fields.")
# Depending on whether d_signal or p_signal was used, set other
# required features.
if p_signal is not None:
# Create the Record object
record = Record(record_name=record_name, p_signal=p_signal, fs=fs,
fmt=fmt, units=units, sig_name=sig_name,
adc_gain=adc_gain, baseline=baseline,
comments=comments, base_time=base_time,
base_date=base_date)
# Compute optimal fields to store the digital signal, carry out adc,
# and set the fields.
record.set_d_features(do_adc=1)
else:
# Create the Record object
record = Record(record_name=record_name, d_signal=d_signal, fs=fs,
fmt=fmt, units=units, sig_name=sig_name,
adc_gain=adc_gain, baseline=baseline,
comments=comments, base_time=base_time,
base_date=base_date)
# Use d_signal to set the fields directly
record.set_d_features()
# Set default values of any missing field dependencies
record.set_defaults()
# Write the record files - header and associated dat
record.wrsamp(write_dir=write_dir) | [
"def",
"wrsamp",
"(",
"record_name",
",",
"fs",
",",
"units",
",",
"sig_name",
",",
"p_signal",
"=",
"None",
",",
"d_signal",
"=",
"None",
",",
"fmt",
"=",
"None",
",",
"adc_gain",
"=",
"None",
",",
"baseline",
"=",
"None",
",",
"comments",
"=",
"Non... | Write a single segment WFDB record, creating a WFDB header file and any
associated dat files.
Parameters
----------
record_name : str
The string name of the WFDB record to be written (without any file
extensions).
fs : int, or float
The sampling frequency of the record.
units : list
A list of strings giving the units of each signal channel.
sig_name :
A list of strings giving the signal name of each signal channel.
p_signal : numpy array, optional
An (MxN) 2d numpy array, where M is the signal length. Gives the
physical signal values intended to be written. Either p_signal or
d_signal must be set, but not both. If p_signal is set, this method will
use it to perform analogue-digital conversion, writing the resultant
digital values to the dat file(s). If fmt is set, gain and baseline must
be set or unset together. If fmt is unset, gain and baseline must both
be unset.
d_signal : numpy array, optional
An (MxN) 2d numpy array, where M is the signal length. Gives the
digital signal values intended to be directly written to the dat
file(s). The dtype must be an integer type. Either p_signal or d_signal
must be set, but not both. In addition, if d_signal is set, fmt, gain
and baseline must also all be set.
fmt : list, optional
A list of strings giving the WFDB format of each file used to store each
channel. Accepted formats are: '80','212",'16','24', and '32'. There are
other WFDB formats as specified by:
https://www.physionet.org/physiotools/wag/signal-5.htm
but this library will not write (though it will read) those file types.
adc_gain : list, optional
A list of numbers specifying the ADC gain.
baseline : list, optional
A list of integers specifying the digital baseline.
comments : list, optional
A list of string comments to be written to the header file.
base_time : str, optional
A string of the record's start time in 24h 'HH:MM:SS(.ms)' format.
base_date : str, optional
A string of the record's start date in 'DD/MM/YYYY' format.
write_dir : str, optional
The directory in which to write the files.
Notes
-----
This is a gateway function, written as a simple method to write WFDB record
files using the most common parameters. Therefore not all WFDB fields can be
set via this function.
For more control over attributes, create a `Record` object, manually set its
attributes, and call its `wrsamp` instance method. If you choose this more
advanced method, see also the `set_defaults`, `set_d_features`, and
`set_p_features` instance methods to help populate attributes.
Examples
--------
>>> # Read part of a record from Physiobank
>>> signals, fields = wfdb.rdsamp('a103l', sampfrom=50000, channels=[0,1],
pb_dir='challenge/2015/training')
>>> # Write a local WFDB record (manually inserting fields)
>>> wfdb.wrsamp('ecgrecord', fs = 250, units=['mV', 'mV'],
sig_name=['I', 'II'], p_signal=signals, fmt=['16', '16']) | [
"Write",
"a",
"single",
"segment",
"WFDB",
"record",
"creating",
"a",
"WFDB",
"header",
"file",
"and",
"any",
"associated",
"dat",
"files",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/record.py#L1435-L1539 |
235,218 | MIT-LCP/wfdb-python | wfdb/io/record.py | is_monotonic | def is_monotonic(full_list):
"""
Determine whether elements in a list are monotonic. ie. unique
elements are clustered together.
ie. [5,5,3,4] is, [5,3,5] is not.
"""
prev_elements = set({full_list[0]})
prev_item = full_list[0]
for item in full_list:
if item != prev_item:
if item in prev_elements:
return False
prev_item = item
prev_elements.add(item)
return True | python | def is_monotonic(full_list):
prev_elements = set({full_list[0]})
prev_item = full_list[0]
for item in full_list:
if item != prev_item:
if item in prev_elements:
return False
prev_item = item
prev_elements.add(item)
return True | [
"def",
"is_monotonic",
"(",
"full_list",
")",
":",
"prev_elements",
"=",
"set",
"(",
"{",
"full_list",
"[",
"0",
"]",
"}",
")",
"prev_item",
"=",
"full_list",
"[",
"0",
"]",
"for",
"item",
"in",
"full_list",
":",
"if",
"item",
"!=",
"prev_item",
":",
... | Determine whether elements in a list are monotonic. ie. unique
elements are clustered together.
ie. [5,5,3,4] is, [5,3,5] is not. | [
"Determine",
"whether",
"elements",
"in",
"a",
"list",
"are",
"monotonic",
".",
"ie",
".",
"unique",
"elements",
"are",
"clustered",
"together",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/record.py#L1542-L1559 |
235,219 | MIT-LCP/wfdb-python | wfdb/io/record.py | BaseRecord._adjust_datetime | def _adjust_datetime(self, sampfrom):
"""
Adjust date and time fields to reflect user input if possible.
Helper function for the `_arrange_fields` of both Record and
MultiRecord objects.
"""
if sampfrom:
dt_seconds = sampfrom / self.fs
if self.base_date and self.base_time:
self.base_datetime = datetime.datetime.combine(self.base_date,
self.base_time)
self.base_datetime += datetime.timedelta(seconds=dt_seconds)
self.base_date = self.base_datetime.date()
self.base_time = self.base_datetime.time()
# We can calculate the time even if there is no date
elif self.base_time:
tmp_datetime = datetime.datetime.combine(
datetime.datetime.today().date(), self.base_time)
self.base_time = (tmp_datetime
+ datetime.timedelta(seconds=dt_seconds)).time() | python | def _adjust_datetime(self, sampfrom):
if sampfrom:
dt_seconds = sampfrom / self.fs
if self.base_date and self.base_time:
self.base_datetime = datetime.datetime.combine(self.base_date,
self.base_time)
self.base_datetime += datetime.timedelta(seconds=dt_seconds)
self.base_date = self.base_datetime.date()
self.base_time = self.base_datetime.time()
# We can calculate the time even if there is no date
elif self.base_time:
tmp_datetime = datetime.datetime.combine(
datetime.datetime.today().date(), self.base_time)
self.base_time = (tmp_datetime
+ datetime.timedelta(seconds=dt_seconds)).time() | [
"def",
"_adjust_datetime",
"(",
"self",
",",
"sampfrom",
")",
":",
"if",
"sampfrom",
":",
"dt_seconds",
"=",
"sampfrom",
"/",
"self",
".",
"fs",
"if",
"self",
".",
"base_date",
"and",
"self",
".",
"base_time",
":",
"self",
".",
"base_datetime",
"=",
"dat... | Adjust date and time fields to reflect user input if possible.
Helper function for the `_arrange_fields` of both Record and
MultiRecord objects. | [
"Adjust",
"date",
"and",
"time",
"fields",
"to",
"reflect",
"user",
"input",
"if",
"possible",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/record.py#L235-L255 |
235,220 | MIT-LCP/wfdb-python | wfdb/io/record.py | Record.wrsamp | def wrsamp(self, expanded=False, write_dir=''):
"""
Write a wfdb header file and any associated dat files from this
object.
Parameters
----------
expanded : bool, optional
Whether to write the expanded signal (e_d_signal) instead
of the uniform signal (d_signal).
write_dir : str, optional
The directory in which to write the files.
"""
# Perform field validity and cohesion checks, and write the
# header file.
self.wrheader(write_dir=write_dir)
if self.n_sig > 0:
# Perform signal validity and cohesion checks, and write the
# associated dat files.
self.wr_dats(expanded=expanded, write_dir=write_dir) | python | def wrsamp(self, expanded=False, write_dir=''):
# Perform field validity and cohesion checks, and write the
# header file.
self.wrheader(write_dir=write_dir)
if self.n_sig > 0:
# Perform signal validity and cohesion checks, and write the
# associated dat files.
self.wr_dats(expanded=expanded, write_dir=write_dir) | [
"def",
"wrsamp",
"(",
"self",
",",
"expanded",
"=",
"False",
",",
"write_dir",
"=",
"''",
")",
":",
"# Perform field validity and cohesion checks, and write the",
"# header file.",
"self",
".",
"wrheader",
"(",
"write_dir",
"=",
"write_dir",
")",
"if",
"self",
"."... | Write a wfdb header file and any associated dat files from this
object.
Parameters
----------
expanded : bool, optional
Whether to write the expanded signal (e_d_signal) instead
of the uniform signal (d_signal).
write_dir : str, optional
The directory in which to write the files. | [
"Write",
"a",
"wfdb",
"header",
"file",
"and",
"any",
"associated",
"dat",
"files",
"from",
"this",
"object",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/record.py#L350-L370 |
235,221 | MIT-LCP/wfdb-python | wfdb/io/record.py | MultiRecord.wrsamp | def wrsamp(self, write_dir=''):
"""
Write a multi-segment header, along with headers and dat files
for all segments, from this object.
"""
# Perform field validity and cohesion checks, and write the
# header file.
self.wrheader(write_dir=write_dir)
# Perform record validity and cohesion checks, and write the
# associated segments.
for seg in self.segments:
seg.wrsamp(write_dir=write_dir) | python | def wrsamp(self, write_dir=''):
# Perform field validity and cohesion checks, and write the
# header file.
self.wrheader(write_dir=write_dir)
# Perform record validity and cohesion checks, and write the
# associated segments.
for seg in self.segments:
seg.wrsamp(write_dir=write_dir) | [
"def",
"wrsamp",
"(",
"self",
",",
"write_dir",
"=",
"''",
")",
":",
"# Perform field validity and cohesion checks, and write the",
"# header file.",
"self",
".",
"wrheader",
"(",
"write_dir",
"=",
"write_dir",
")",
"# Perform record validity and cohesion checks, and write th... | Write a multi-segment header, along with headers and dat files
for all segments, from this object. | [
"Write",
"a",
"multi",
"-",
"segment",
"header",
"along",
"with",
"headers",
"and",
"dat",
"files",
"for",
"all",
"segments",
"from",
"this",
"object",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/record.py#L479-L490 |
235,222 | MIT-LCP/wfdb-python | wfdb/io/record.py | MultiRecord._check_segment_cohesion | def _check_segment_cohesion(self):
"""
Check the cohesion of the segments field with other fields used
to write the record
"""
if self.n_seg != len(self.segments):
raise ValueError("Length of segments must match the 'n_seg' field")
for i in range(n_seg):
s = self.segments[i]
# If segment 0 is a layout specification record, check that its file names are all == '~''
if i == 0 and self.seg_len[0] == 0:
for file_name in s.file_name:
if file_name != '~':
raise ValueError("Layout specification records must have all file_names named '~'")
# Sampling frequencies must all match the one in the master header
if s.fs != self.fs:
raise ValueError("The 'fs' in each segment must match the overall record's 'fs'")
# Check the signal length of the segment against the corresponding seg_len field
if s.sig_len != self.seg_len[i]:
raise ValueError('The signal length of segment '+str(i)+' does not match the corresponding segment length')
totalsig_len = totalsig_len + getattr(s, 'sig_len') | python | def _check_segment_cohesion(self):
if self.n_seg != len(self.segments):
raise ValueError("Length of segments must match the 'n_seg' field")
for i in range(n_seg):
s = self.segments[i]
# If segment 0 is a layout specification record, check that its file names are all == '~''
if i == 0 and self.seg_len[0] == 0:
for file_name in s.file_name:
if file_name != '~':
raise ValueError("Layout specification records must have all file_names named '~'")
# Sampling frequencies must all match the one in the master header
if s.fs != self.fs:
raise ValueError("The 'fs' in each segment must match the overall record's 'fs'")
# Check the signal length of the segment against the corresponding seg_len field
if s.sig_len != self.seg_len[i]:
raise ValueError('The signal length of segment '+str(i)+' does not match the corresponding segment length')
totalsig_len = totalsig_len + getattr(s, 'sig_len') | [
"def",
"_check_segment_cohesion",
"(",
"self",
")",
":",
"if",
"self",
".",
"n_seg",
"!=",
"len",
"(",
"self",
".",
"segments",
")",
":",
"raise",
"ValueError",
"(",
"\"Length of segments must match the 'n_seg' field\"",
")",
"for",
"i",
"in",
"range",
"(",
"n... | Check the cohesion of the segments field with other fields used
to write the record | [
"Check",
"the",
"cohesion",
"of",
"the",
"segments",
"field",
"with",
"other",
"fields",
"used",
"to",
"write",
"the",
"record"
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/record.py#L492-L518 |
235,223 | MIT-LCP/wfdb-python | wfdb/io/record.py | MultiRecord._required_segments | def _required_segments(self, sampfrom, sampto):
"""
Determine the segments and the samples within each segment in a
multi-segment record, that lie within a sample range.
Parameters
----------
sampfrom : int
The starting sample number to read for each channel.
sampto : int
The sample number at which to stop reading for each channel.
"""
# The starting segment with actual samples
if self.layout == 'fixed':
startseg = 0
else:
startseg = 1
# Cumulative sum of segment lengths (ignoring layout segment)
cumsumlengths = list(np.cumsum(self.seg_len[startseg:]))
# Get first segment
seg_numbers = [[sampfrom < cs for cs in cumsumlengths].index(True)]
# Get final segment
if sampto == cumsumlengths[len(cumsumlengths) - 1]:
seg_numbers.append(len(cumsumlengths) - 1)
else:
seg_numbers.append([sampto <= cs for cs in cumsumlengths].index(True))
# Add 1 for variable layout records
seg_numbers = list(np.add(seg_numbers,startseg))
# Obtain the sampfrom and sampto to read for each segment
if seg_numbers[1] == seg_numbers[0]:
# Only one segment to read
seg_numbers = [seg_numbers[0]]
# The segment's first sample number relative to the entire record
segstartsamp = sum(self.seg_len[0:seg_numbers[0]])
readsamps = [[sampfrom-segstartsamp, sampto-segstartsamp]]
else:
# More than one segment to read
seg_numbers = list(range(seg_numbers[0], seg_numbers[1]+1))
readsamps = [[0, self.seg_len[s]] for s in seg_numbers]
# Starting sample for first segment.
readsamps[0][0] = sampfrom - ([0] + cumsumlengths)[seg_numbers[0]-startseg]
# End sample for last segment
readsamps[-1][1] = sampto - ([0] + cumsumlengths)[seg_numbers[-1]-startseg]
return (seg_numbers, readsamps) | python | def _required_segments(self, sampfrom, sampto):
# The starting segment with actual samples
if self.layout == 'fixed':
startseg = 0
else:
startseg = 1
# Cumulative sum of segment lengths (ignoring layout segment)
cumsumlengths = list(np.cumsum(self.seg_len[startseg:]))
# Get first segment
seg_numbers = [[sampfrom < cs for cs in cumsumlengths].index(True)]
# Get final segment
if sampto == cumsumlengths[len(cumsumlengths) - 1]:
seg_numbers.append(len(cumsumlengths) - 1)
else:
seg_numbers.append([sampto <= cs for cs in cumsumlengths].index(True))
# Add 1 for variable layout records
seg_numbers = list(np.add(seg_numbers,startseg))
# Obtain the sampfrom and sampto to read for each segment
if seg_numbers[1] == seg_numbers[0]:
# Only one segment to read
seg_numbers = [seg_numbers[0]]
# The segment's first sample number relative to the entire record
segstartsamp = sum(self.seg_len[0:seg_numbers[0]])
readsamps = [[sampfrom-segstartsamp, sampto-segstartsamp]]
else:
# More than one segment to read
seg_numbers = list(range(seg_numbers[0], seg_numbers[1]+1))
readsamps = [[0, self.seg_len[s]] for s in seg_numbers]
# Starting sample for first segment.
readsamps[0][0] = sampfrom - ([0] + cumsumlengths)[seg_numbers[0]-startseg]
# End sample for last segment
readsamps[-1][1] = sampto - ([0] + cumsumlengths)[seg_numbers[-1]-startseg]
return (seg_numbers, readsamps) | [
"def",
"_required_segments",
"(",
"self",
",",
"sampfrom",
",",
"sampto",
")",
":",
"# The starting segment with actual samples",
"if",
"self",
".",
"layout",
"==",
"'fixed'",
":",
"startseg",
"=",
"0",
"else",
":",
"startseg",
"=",
"1",
"# Cumulative sum of segme... | Determine the segments and the samples within each segment in a
multi-segment record, that lie within a sample range.
Parameters
----------
sampfrom : int
The starting sample number to read for each channel.
sampto : int
The sample number at which to stop reading for each channel. | [
"Determine",
"the",
"segments",
"and",
"the",
"samples",
"within",
"each",
"segment",
"in",
"a",
"multi",
"-",
"segment",
"record",
"that",
"lie",
"within",
"a",
"sample",
"range",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/record.py#L525-L577 |
235,224 | MIT-LCP/wfdb-python | wfdb/io/record.py | MultiRecord._required_channels | def _required_channels(self, seg_numbers, channels, dir_name, pb_dir):
"""
Get the channel numbers to be read from each specified segment,
given the channel numbers specified for the entire record.
Parameters
----------
seg_numbers : list
List of segment numbers to read.
channels : list
The channel indices to read for the whole record. Same one
specified by user input.
Returns
-------
required_channels : list
List of lists, containing channel indices to read for each
desired segment.
"""
# Fixed layout. All channels are the same.
if self.layout == 'fixed':
required_channels = [channels] * len(seg_numbers)
# Variable layout: figure out channels by matching record names
else:
required_channels = []
# The overall layout signal names
l_sig_names = self.segments[0].sig_name
# The wanted signals
w_sig_names = [l_sig_names[c] for c in channels]
# For each segment
for i in range(len(seg_numbers)):
# Skip empty segments
if self.seg_name[seg_numbers[i]] == '~':
required_channels.append([])
else:
# Get the signal names of the current segment
s_sig_names = rdheader(
os.path.join(dir_name, self.seg_name[seg_numbers[i]]),
pb_dir=pb_dir).sig_name
required_channels.append(_get_wanted_channels(
w_sig_names, s_sig_names))
return required_channels | python | def _required_channels(self, seg_numbers, channels, dir_name, pb_dir):
# Fixed layout. All channels are the same.
if self.layout == 'fixed':
required_channels = [channels] * len(seg_numbers)
# Variable layout: figure out channels by matching record names
else:
required_channels = []
# The overall layout signal names
l_sig_names = self.segments[0].sig_name
# The wanted signals
w_sig_names = [l_sig_names[c] for c in channels]
# For each segment
for i in range(len(seg_numbers)):
# Skip empty segments
if self.seg_name[seg_numbers[i]] == '~':
required_channels.append([])
else:
# Get the signal names of the current segment
s_sig_names = rdheader(
os.path.join(dir_name, self.seg_name[seg_numbers[i]]),
pb_dir=pb_dir).sig_name
required_channels.append(_get_wanted_channels(
w_sig_names, s_sig_names))
return required_channels | [
"def",
"_required_channels",
"(",
"self",
",",
"seg_numbers",
",",
"channels",
",",
"dir_name",
",",
"pb_dir",
")",
":",
"# Fixed layout. All channels are the same.",
"if",
"self",
".",
"layout",
"==",
"'fixed'",
":",
"required_channels",
"=",
"[",
"channels",
"]"... | Get the channel numbers to be read from each specified segment,
given the channel numbers specified for the entire record.
Parameters
----------
seg_numbers : list
List of segment numbers to read.
channels : list
The channel indices to read for the whole record. Same one
specified by user input.
Returns
-------
required_channels : list
List of lists, containing channel indices to read for each
desired segment. | [
"Get",
"the",
"channel",
"numbers",
"to",
"be",
"read",
"from",
"each",
"specified",
"segment",
"given",
"the",
"channel",
"numbers",
"specified",
"for",
"the",
"entire",
"record",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/record.py#L580-L625 |
235,225 | MIT-LCP/wfdb-python | wfdb/io/tff.py | rdtff | def rdtff(file_name, cut_end=False):
"""
Read values from a tff file
Parameters
----------
file_name : str
Name of the .tff file to read
cut_end : bool, optional
If True, cuts out the last sample for all channels. This is for
reading files which appear to terminate with the incorrect
number of samples (ie. sample not present for all channels).
Returns
-------
signal : numpy array
A 2d numpy array storing the physical signals from the record.
fields : dict
A dictionary containing several key attributes of the read record.
markers : numpy array
A 1d numpy array storing the marker locations.
triggers : numpy array
A 1d numpy array storing the trigger locations.
Notes
-----
This function is slow because tff files may contain any number of
escape sequences interspersed with the signals. There is no way to
know the number of samples/escape sequences beforehand, so the file
is inefficiently parsed a small chunk at a time.
It is recommended that you convert your tff files to wfdb format.
"""
file_size = os.path.getsize(file_name)
with open(file_name, 'rb') as fp:
fields, file_fields = _rdheader(fp)
signal, markers, triggers = _rdsignal(fp, file_size=file_size,
header_size=file_fields['header_size'],
n_sig=file_fields['n_sig'],
bit_width=file_fields['bit_width'],
is_signed=file_fields['is_signed'],
cut_end=cut_end)
return signal, fields, markers, triggers | python | def rdtff(file_name, cut_end=False):
file_size = os.path.getsize(file_name)
with open(file_name, 'rb') as fp:
fields, file_fields = _rdheader(fp)
signal, markers, triggers = _rdsignal(fp, file_size=file_size,
header_size=file_fields['header_size'],
n_sig=file_fields['n_sig'],
bit_width=file_fields['bit_width'],
is_signed=file_fields['is_signed'],
cut_end=cut_end)
return signal, fields, markers, triggers | [
"def",
"rdtff",
"(",
"file_name",
",",
"cut_end",
"=",
"False",
")",
":",
"file_size",
"=",
"os",
".",
"path",
".",
"getsize",
"(",
"file_name",
")",
"with",
"open",
"(",
"file_name",
",",
"'rb'",
")",
"as",
"fp",
":",
"fields",
",",
"file_fields",
"... | Read values from a tff file
Parameters
----------
file_name : str
Name of the .tff file to read
cut_end : bool, optional
If True, cuts out the last sample for all channels. This is for
reading files which appear to terminate with the incorrect
number of samples (ie. sample not present for all channels).
Returns
-------
signal : numpy array
A 2d numpy array storing the physical signals from the record.
fields : dict
A dictionary containing several key attributes of the read record.
markers : numpy array
A 1d numpy array storing the marker locations.
triggers : numpy array
A 1d numpy array storing the trigger locations.
Notes
-----
This function is slow because tff files may contain any number of
escape sequences interspersed with the signals. There is no way to
know the number of samples/escape sequences beforehand, so the file
is inefficiently parsed a small chunk at a time.
It is recommended that you convert your tff files to wfdb format. | [
"Read",
"values",
"from",
"a",
"tff",
"file"
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/tff.py#L14-L57 |
235,226 | MIT-LCP/wfdb-python | wfdb/io/tff.py | _rdheader | def _rdheader(fp):
"""
Read header info of the windaq file
"""
tag = None
# The '2' tag indicates the end of tags.
while tag != 2:
# For each header element, there is a tag indicating data type,
# followed by the data size, followed by the data itself. 0's
# pad the content to the nearest 4 bytes. If data_len=0, no pad.
tag = struct.unpack('>H', fp.read(2))[0]
data_size = struct.unpack('>H', fp.read(2))[0]
pad_len = (4 - (data_size % 4)) % 4
pos = fp.tell()
# Currently, most tags will be ignored...
# storage method
if tag == 1001:
storage_method = fs = struct.unpack('B', fp.read(1))[0]
storage_method = {0:'recording', 1:'manual', 2:'online'}[storage_method]
# fs, unit16
elif tag == 1003:
fs = struct.unpack('>H', fp.read(2))[0]
# sensor type
elif tag == 1007:
# Each byte contains information for one channel
n_sig = data_size
channel_data = struct.unpack('>%dB' % data_size, fp.read(data_size))
# The documentation states: "0 : Channel is not used"
# This means the samples are NOT saved.
channel_map = ((1, 1, 'emg'),
(15, 30, 'goniometer'), (31, 46, 'accelerometer'),
(47, 62, 'inclinometer'),
(63, 78, 'polar_interface'), (79, 94, 'ecg'),
(95, 110, 'torque'), (111, 126, 'gyrometer'),
(127, 142, 'sensor'))
sig_name = []
# The number range that the data lies between gives the
# channel
for data in channel_data:
# Default case if byte value falls outside of channel map
base_name = 'unknown'
# Unused channel
if data == 0:
n_sig -= 1
break
for item in channel_map:
if item[0] <= data <= item[1]:
base_name = item[2]
break
existing_count = [base_name in name for name in sig_name].count(True)
sig_name.append('%s_%d' % (base_name, existing_count))
# Display scale. Probably not useful.
elif tag == 1009:
# 100, 500, 1000, 2500, or 8500uV
display_scale = struct.unpack('>I', fp.read(4))[0]
# sample format, uint8
elif tag == 3:
sample_fmt = struct.unpack('B', fp.read(1))[0]
is_signed = bool(sample_fmt >> 7)
# ie. 8 or 16 bits
bit_width = sample_fmt & 127
# Measurement start time - seconds from 1.1.1970 UTC
elif tag == 101:
n_seconds = struct.unpack('>I', fp.read(4))[0]
base_datetime = datetime.datetime.utcfromtimestamp(n_seconds)
base_date = base_datetime.date()
base_time = base_datetime.time()
# Measurement start time - minutes from UTC
elif tag == 102:
n_minutes = struct.unpack('>h', fp.read(2))[0]
# Go to the next tag
fp.seek(pos + data_size + pad_len)
header_size = fp.tell()
# For interpreting the waveforms
fields = {'fs':fs, 'n_sig':n_sig, 'sig_name':sig_name,
'base_time':base_time, 'base_date':base_date}
# For reading the signal samples
file_fields = {'header_size':header_size, 'n_sig':n_sig,
'bit_width':bit_width, 'is_signed':is_signed}
return fields, file_fields | python | def _rdheader(fp):
tag = None
# The '2' tag indicates the end of tags.
while tag != 2:
# For each header element, there is a tag indicating data type,
# followed by the data size, followed by the data itself. 0's
# pad the content to the nearest 4 bytes. If data_len=0, no pad.
tag = struct.unpack('>H', fp.read(2))[0]
data_size = struct.unpack('>H', fp.read(2))[0]
pad_len = (4 - (data_size % 4)) % 4
pos = fp.tell()
# Currently, most tags will be ignored...
# storage method
if tag == 1001:
storage_method = fs = struct.unpack('B', fp.read(1))[0]
storage_method = {0:'recording', 1:'manual', 2:'online'}[storage_method]
# fs, unit16
elif tag == 1003:
fs = struct.unpack('>H', fp.read(2))[0]
# sensor type
elif tag == 1007:
# Each byte contains information for one channel
n_sig = data_size
channel_data = struct.unpack('>%dB' % data_size, fp.read(data_size))
# The documentation states: "0 : Channel is not used"
# This means the samples are NOT saved.
channel_map = ((1, 1, 'emg'),
(15, 30, 'goniometer'), (31, 46, 'accelerometer'),
(47, 62, 'inclinometer'),
(63, 78, 'polar_interface'), (79, 94, 'ecg'),
(95, 110, 'torque'), (111, 126, 'gyrometer'),
(127, 142, 'sensor'))
sig_name = []
# The number range that the data lies between gives the
# channel
for data in channel_data:
# Default case if byte value falls outside of channel map
base_name = 'unknown'
# Unused channel
if data == 0:
n_sig -= 1
break
for item in channel_map:
if item[0] <= data <= item[1]:
base_name = item[2]
break
existing_count = [base_name in name for name in sig_name].count(True)
sig_name.append('%s_%d' % (base_name, existing_count))
# Display scale. Probably not useful.
elif tag == 1009:
# 100, 500, 1000, 2500, or 8500uV
display_scale = struct.unpack('>I', fp.read(4))[0]
# sample format, uint8
elif tag == 3:
sample_fmt = struct.unpack('B', fp.read(1))[0]
is_signed = bool(sample_fmt >> 7)
# ie. 8 or 16 bits
bit_width = sample_fmt & 127
# Measurement start time - seconds from 1.1.1970 UTC
elif tag == 101:
n_seconds = struct.unpack('>I', fp.read(4))[0]
base_datetime = datetime.datetime.utcfromtimestamp(n_seconds)
base_date = base_datetime.date()
base_time = base_datetime.time()
# Measurement start time - minutes from UTC
elif tag == 102:
n_minutes = struct.unpack('>h', fp.read(2))[0]
# Go to the next tag
fp.seek(pos + data_size + pad_len)
header_size = fp.tell()
# For interpreting the waveforms
fields = {'fs':fs, 'n_sig':n_sig, 'sig_name':sig_name,
'base_time':base_time, 'base_date':base_date}
# For reading the signal samples
file_fields = {'header_size':header_size, 'n_sig':n_sig,
'bit_width':bit_width, 'is_signed':is_signed}
return fields, file_fields | [
"def",
"_rdheader",
"(",
"fp",
")",
":",
"tag",
"=",
"None",
"# The '2' tag indicates the end of tags.",
"while",
"tag",
"!=",
"2",
":",
"# For each header element, there is a tag indicating data type,",
"# followed by the data size, followed by the data itself. 0's",
"# pad the co... | Read header info of the windaq file | [
"Read",
"header",
"info",
"of",
"the",
"windaq",
"file"
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/tff.py#L60-L139 |
235,227 | MIT-LCP/wfdb-python | wfdb/io/tff.py | _rdsignal | def _rdsignal(fp, file_size, header_size, n_sig, bit_width, is_signed, cut_end):
"""
Read the signal
Parameters
----------
cut_end : bool, optional
If True, enables reading the end of files which appear to terminate
with the incorrect number of samples (ie. sample not present for all channels),
by checking and skipping the reading the end of such files.
Checking this option makes reading slower.
"""
# Cannot initially figure out signal length because there
# are escape sequences.
fp.seek(header_size)
signal_size = file_size - header_size
byte_width = int(bit_width / 8)
# numpy dtype
dtype = str(byte_width)
if is_signed:
dtype = 'i' + dtype
else:
dtype = 'u' + dtype
# big endian
dtype = '>' + dtype
# The maximum possible samples given the file size
# All channels must be present
max_samples = int(signal_size / byte_width)
max_samples = max_samples - max_samples % n_sig
# Output information
signal = np.empty(max_samples, dtype=dtype)
markers = []
triggers = []
# Number of (total) samples read
sample_num = 0
# Read one sample for all channels at a time
if cut_end:
stop_byte = file_size - n_sig * byte_width + 1
while fp.tell() < stop_byte:
chunk = fp.read(2)
sample_num = _get_sample(fp, chunk, n_sig, dtype, signal, markers, triggers, sample_num)
else:
while True:
chunk = fp.read(2)
if not chunk:
break
sample_num = _get_sample(fp, chunk, n_sig, dtype, signal, markers, triggers, sample_num)
# No more bytes to read. Reshape output arguments.
signal = signal[:sample_num]
signal = signal.reshape((-1, n_sig))
markers = np.array(markers, dtype='int')
triggers = np.array(triggers, dtype='int')
return signal, markers, triggers | python | def _rdsignal(fp, file_size, header_size, n_sig, bit_width, is_signed, cut_end):
# Cannot initially figure out signal length because there
# are escape sequences.
fp.seek(header_size)
signal_size = file_size - header_size
byte_width = int(bit_width / 8)
# numpy dtype
dtype = str(byte_width)
if is_signed:
dtype = 'i' + dtype
else:
dtype = 'u' + dtype
# big endian
dtype = '>' + dtype
# The maximum possible samples given the file size
# All channels must be present
max_samples = int(signal_size / byte_width)
max_samples = max_samples - max_samples % n_sig
# Output information
signal = np.empty(max_samples, dtype=dtype)
markers = []
triggers = []
# Number of (total) samples read
sample_num = 0
# Read one sample for all channels at a time
if cut_end:
stop_byte = file_size - n_sig * byte_width + 1
while fp.tell() < stop_byte:
chunk = fp.read(2)
sample_num = _get_sample(fp, chunk, n_sig, dtype, signal, markers, triggers, sample_num)
else:
while True:
chunk = fp.read(2)
if not chunk:
break
sample_num = _get_sample(fp, chunk, n_sig, dtype, signal, markers, triggers, sample_num)
# No more bytes to read. Reshape output arguments.
signal = signal[:sample_num]
signal = signal.reshape((-1, n_sig))
markers = np.array(markers, dtype='int')
triggers = np.array(triggers, dtype='int')
return signal, markers, triggers | [
"def",
"_rdsignal",
"(",
"fp",
",",
"file_size",
",",
"header_size",
",",
"n_sig",
",",
"bit_width",
",",
"is_signed",
",",
"cut_end",
")",
":",
"# Cannot initially figure out signal length because there",
"# are escape sequences.",
"fp",
".",
"seek",
"(",
"header_siz... | Read the signal
Parameters
----------
cut_end : bool, optional
If True, enables reading the end of files which appear to terminate
with the incorrect number of samples (ie. sample not present for all channels),
by checking and skipping the reading the end of such files.
Checking this option makes reading slower. | [
"Read",
"the",
"signal"
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/tff.py#L142-L196 |
235,228 | MIT-LCP/wfdb-python | wfdb/processing/qrs.py | xqrs_detect | def xqrs_detect(sig, fs, sampfrom=0, sampto='end', conf=None,
learn=True, verbose=True):
"""
Run the 'xqrs' qrs detection algorithm on a signal. See the
docstring of the XQRS class for algorithm details.
Parameters
----------
sig : numpy array
The input ecg signal to apply the qrs detection on.
fs : int or float
The sampling frequency of the input signal.
sampfrom : int, optional
The starting sample number to run the detection on.
sampto :
The final sample number to run the detection on. Set as 'end' to
run on the entire signal.
conf : XQRS.Conf object, optional
The configuration object specifying signal configuration
parameters. See the docstring of the XQRS.Conf class.
learn : bool, optional
Whether to apply learning on the signal before running the main
detection. If learning fails or is not conducted, the default
configuration parameters will be used to initialize these
variables.
verbose : bool, optional
Whether to display the stages and outcomes of the detection
process.
Returns
-------
qrs_inds : numpy array
The indices of the detected qrs complexes
Examples
--------
>>> import wfdb
>>> from wfdb import processing
>>> sig, fields = wfdb.rdsamp('sample-data/100', channels=[0])
>>> qrs_inds = processing.xqrs_detect(sig=sig[:,0], fs=fields['fs'])
"""
xqrs = XQRS(sig=sig, fs=fs, conf=conf)
xqrs.detect(sampfrom=sampfrom, sampto=sampto, verbose=verbose)
return xqrs.qrs_inds | python | def xqrs_detect(sig, fs, sampfrom=0, sampto='end', conf=None,
learn=True, verbose=True):
xqrs = XQRS(sig=sig, fs=fs, conf=conf)
xqrs.detect(sampfrom=sampfrom, sampto=sampto, verbose=verbose)
return xqrs.qrs_inds | [
"def",
"xqrs_detect",
"(",
"sig",
",",
"fs",
",",
"sampfrom",
"=",
"0",
",",
"sampto",
"=",
"'end'",
",",
"conf",
"=",
"None",
",",
"learn",
"=",
"True",
",",
"verbose",
"=",
"True",
")",
":",
"xqrs",
"=",
"XQRS",
"(",
"sig",
"=",
"sig",
",",
"... | Run the 'xqrs' qrs detection algorithm on a signal. See the
docstring of the XQRS class for algorithm details.
Parameters
----------
sig : numpy array
The input ecg signal to apply the qrs detection on.
fs : int or float
The sampling frequency of the input signal.
sampfrom : int, optional
The starting sample number to run the detection on.
sampto :
The final sample number to run the detection on. Set as 'end' to
run on the entire signal.
conf : XQRS.Conf object, optional
The configuration object specifying signal configuration
parameters. See the docstring of the XQRS.Conf class.
learn : bool, optional
Whether to apply learning on the signal before running the main
detection. If learning fails or is not conducted, the default
configuration parameters will be used to initialize these
variables.
verbose : bool, optional
Whether to display the stages and outcomes of the detection
process.
Returns
-------
qrs_inds : numpy array
The indices of the detected qrs complexes
Examples
--------
>>> import wfdb
>>> from wfdb import processing
>>> sig, fields = wfdb.rdsamp('sample-data/100', channels=[0])
>>> qrs_inds = processing.xqrs_detect(sig=sig[:,0], fs=fields['fs']) | [
"Run",
"the",
"xqrs",
"qrs",
"detection",
"algorithm",
"on",
"a",
"signal",
".",
"See",
"the",
"docstring",
"of",
"the",
"XQRS",
"class",
"for",
"algorithm",
"details",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/qrs.py#L603-L648 |
235,229 | MIT-LCP/wfdb-python | wfdb/processing/qrs.py | gqrs_detect | def gqrs_detect(sig=None, fs=None, d_sig=None, adc_gain=None, adc_zero=None,
threshold=1.0, hr=75, RRdelta=0.2, RRmin=0.28, RRmax=2.4,
QS=0.07, QT=0.35, RTmin=0.25, RTmax=0.33,
QRSa=750, QRSamin=130):
"""
Detect qrs locations in a single channel ecg. Functionally, a direct port
of the gqrs algorithm from the original wfdb package. Accepts either a
physical signal, or a digital signal with known adc_gain and adc_zero.
See the notes below for a summary of the program. This algorithm is not
being developed/supported.
Parameters
----------
sig : 1d numpy array, optional
The input physical signal. The detection algorithm which replicates
the original, works using digital samples, and this physical option is
provided as a convenient interface. If this is the specified input
signal, automatic adc is performed using 24 bit precision, to obtain
the `d_sig`, `adc_gain`, and `adc_zero` parameters. There may be minor
differences in detection results (ie. an occasional 1 sample
difference) between using `sig` and `d_sig`. To replicate the exact
output of the original gqrs algorithm, use the `d_sig` argument
instead.
fs : int, or float
The sampling frequency of the signal.
d_sig : 1d numpy array, optional
The input digital signal. If this is the specified input signal rather
than `sig`, the `adc_gain` and `adc_zero` parameters must be specified.
adc_gain : int, or float, optional
The analogue to digital gain of the signal (the number of adus per
physical unit).
adc_zero: int, optional
The value produced by the ADC given a 0 volt input.
threshold : int, or float, optional
The relative amplitude detection threshold. Used to initialize the peak
and qrs detection threshold.
hr : int, or float, optional
Typical heart rate, in beats per minute.
RRdelta : int or float, optional
Typical difference between successive RR intervals in seconds.
RRmin : int or float, optional
Minimum RR interval ("refractory period"), in seconds.
RRmax : int or float, optional
Maximum RR interval, in seconds. Thresholds will be adjusted if no
peaks are detected within this interval.
QS : int or float, optional
Typical QRS duration, in seconds.
QT : int or float, optional
Typical QT interval, in seconds.
RTmin : int or float, optional
Minimum interval between R and T peaks, in seconds.
RTmax : int or float, optional
Maximum interval between R and T peaks, in seconds.
QRSa : int or float, optional
Typical QRS peak-to-peak amplitude, in microvolts.
QRSamin : int or float, optional
Minimum QRS peak-to-peak amplitude, in microvolts.
Returns
-------
qrs_locs : numpy array
Detected qrs locations
Notes
-----
This function should not be used for signals with fs <= 50Hz
The algorithm theoretically works as follows:
- Load in configuration parameters. They are used to set/initialize the:
* allowed rr interval limits (fixed)
* initial recent rr interval (running)
* qrs width, used for detection filter widths (fixed)
* allowed rt interval limits (fixed)
* initial recent rt interval (running)
* initial peak amplitude detection threshold (running)
* initial qrs amplitude detection threshold (running)
* `Note`: this algorithm does not normalize signal amplitudes, and
hence is highly dependent on configuration amplitude parameters.
- Apply trapezoid low-pass filtering to the signal
- Convolve a QRS matched filter with the filtered signal
- Run the learning phase using a calculated signal length: detect qrs and
non-qrs peaks as in the main detection phase, without saving the qrs
locations. During this phase, running parameters of recent intervals
and peak/qrs thresholds are adjusted.
- Run the detection::
if a sample is bigger than its immediate neighbors and larger
than the peak detection threshold, it is a peak.
if it is further than RRmin from the previous qrs, and is a
*primary peak.
if it is further than 2 standard deviations from the
previous qrs, do a backsearch for a missed low amplitude
beat
return the primary peak between the current sample
and the previous qrs if any.
if it surpasses the qrs threshold, it is a qrs complex
save the qrs location.
update running rr and qrs amplitude parameters.
look for the qrs complex's t-wave and mark it if
found.
else if it is not a peak
lower the peak detection threshold if the last peak found
was more than RRmax ago, and not already at its minimum.
*A peak is secondary if there is a larger peak within its neighborhood
(time +- rrmin), or if it has been identified as a T-wave associated with a
previous primary peak. A peak is primary if it is largest in its neighborhood,
or if the only larger peaks are secondary.
The above describes how the algorithm should theoretically work, but there
are bugs which make the program contradict certain parts of its supposed
logic. A list of issues from the original c, code and hence this python
implementation can be found here:
https://github.com/bemoody/wfdb/issues/17
gqrs will not be supported/developed in this library.
Examples
--------
>>> import numpy as np
>>> import wfdb
>>> from wfdb import processing
>>> # Detect using a physical input signal
>>> record = wfdb.rdrecord('sample-data/100', channels=[0])
>>> qrs_locs = processing.gqrs_detect(record.p_signal[:,0], fs=record.fs)
>>> # Detect using a digital input signal
>>> record_2 = wfdb.rdrecord('sample-data/100', channels=[0], physical=False)
>>> qrs_locs_2 = processing.gqrs_detect(d_sig=record_2.d_signal[:,0],
fs=record_2.fs,
adc_gain=record_2.adc_gain[0],
adc_zero=record_2.adc_zero[0])
"""
# Perform adc if input signal is physical
if sig is not None:
record = Record(p_signal=sig.reshape([-1,1]), fmt=['24'])
record.set_d_features(do_adc=True)
d_sig = record.d_signal[:,0]
adc_zero = 0
adc_gain = record.adc_gain[0]
conf = GQRS.Conf(fs=fs, adc_gain=adc_gain, hr=hr, RRdelta=RRdelta, RRmin=RRmin,
RRmax=RRmax, QS=QS, QT=QT, RTmin=RTmin, RTmax=RTmax, QRSa=QRSa,
QRSamin=QRSamin, thresh=threshold)
gqrs = GQRS()
annotations = gqrs.detect(x=d_sig, conf=conf, adc_zero=adc_zero)
return np.array([a.time for a in annotations]) | python | def gqrs_detect(sig=None, fs=None, d_sig=None, adc_gain=None, adc_zero=None,
threshold=1.0, hr=75, RRdelta=0.2, RRmin=0.28, RRmax=2.4,
QS=0.07, QT=0.35, RTmin=0.25, RTmax=0.33,
QRSa=750, QRSamin=130):
# Perform adc if input signal is physical
if sig is not None:
record = Record(p_signal=sig.reshape([-1,1]), fmt=['24'])
record.set_d_features(do_adc=True)
d_sig = record.d_signal[:,0]
adc_zero = 0
adc_gain = record.adc_gain[0]
conf = GQRS.Conf(fs=fs, adc_gain=adc_gain, hr=hr, RRdelta=RRdelta, RRmin=RRmin,
RRmax=RRmax, QS=QS, QT=QT, RTmin=RTmin, RTmax=RTmax, QRSa=QRSa,
QRSamin=QRSamin, thresh=threshold)
gqrs = GQRS()
annotations = gqrs.detect(x=d_sig, conf=conf, adc_zero=adc_zero)
return np.array([a.time for a in annotations]) | [
"def",
"gqrs_detect",
"(",
"sig",
"=",
"None",
",",
"fs",
"=",
"None",
",",
"d_sig",
"=",
"None",
",",
"adc_gain",
"=",
"None",
",",
"adc_zero",
"=",
"None",
",",
"threshold",
"=",
"1.0",
",",
"hr",
"=",
"75",
",",
"RRdelta",
"=",
"0.2",
",",
"RR... | Detect qrs locations in a single channel ecg. Functionally, a direct port
of the gqrs algorithm from the original wfdb package. Accepts either a
physical signal, or a digital signal with known adc_gain and adc_zero.
See the notes below for a summary of the program. This algorithm is not
being developed/supported.
Parameters
----------
sig : 1d numpy array, optional
The input physical signal. The detection algorithm which replicates
the original, works using digital samples, and this physical option is
provided as a convenient interface. If this is the specified input
signal, automatic adc is performed using 24 bit precision, to obtain
the `d_sig`, `adc_gain`, and `adc_zero` parameters. There may be minor
differences in detection results (ie. an occasional 1 sample
difference) between using `sig` and `d_sig`. To replicate the exact
output of the original gqrs algorithm, use the `d_sig` argument
instead.
fs : int, or float
The sampling frequency of the signal.
d_sig : 1d numpy array, optional
The input digital signal. If this is the specified input signal rather
than `sig`, the `adc_gain` and `adc_zero` parameters must be specified.
adc_gain : int, or float, optional
The analogue to digital gain of the signal (the number of adus per
physical unit).
adc_zero: int, optional
The value produced by the ADC given a 0 volt input.
threshold : int, or float, optional
The relative amplitude detection threshold. Used to initialize the peak
and qrs detection threshold.
hr : int, or float, optional
Typical heart rate, in beats per minute.
RRdelta : int or float, optional
Typical difference between successive RR intervals in seconds.
RRmin : int or float, optional
Minimum RR interval ("refractory period"), in seconds.
RRmax : int or float, optional
Maximum RR interval, in seconds. Thresholds will be adjusted if no
peaks are detected within this interval.
QS : int or float, optional
Typical QRS duration, in seconds.
QT : int or float, optional
Typical QT interval, in seconds.
RTmin : int or float, optional
Minimum interval between R and T peaks, in seconds.
RTmax : int or float, optional
Maximum interval between R and T peaks, in seconds.
QRSa : int or float, optional
Typical QRS peak-to-peak amplitude, in microvolts.
QRSamin : int or float, optional
Minimum QRS peak-to-peak amplitude, in microvolts.
Returns
-------
qrs_locs : numpy array
Detected qrs locations
Notes
-----
This function should not be used for signals with fs <= 50Hz
The algorithm theoretically works as follows:
- Load in configuration parameters. They are used to set/initialize the:
* allowed rr interval limits (fixed)
* initial recent rr interval (running)
* qrs width, used for detection filter widths (fixed)
* allowed rt interval limits (fixed)
* initial recent rt interval (running)
* initial peak amplitude detection threshold (running)
* initial qrs amplitude detection threshold (running)
* `Note`: this algorithm does not normalize signal amplitudes, and
hence is highly dependent on configuration amplitude parameters.
- Apply trapezoid low-pass filtering to the signal
- Convolve a QRS matched filter with the filtered signal
- Run the learning phase using a calculated signal length: detect qrs and
non-qrs peaks as in the main detection phase, without saving the qrs
locations. During this phase, running parameters of recent intervals
and peak/qrs thresholds are adjusted.
- Run the detection::
if a sample is bigger than its immediate neighbors and larger
than the peak detection threshold, it is a peak.
if it is further than RRmin from the previous qrs, and is a
*primary peak.
if it is further than 2 standard deviations from the
previous qrs, do a backsearch for a missed low amplitude
beat
return the primary peak between the current sample
and the previous qrs if any.
if it surpasses the qrs threshold, it is a qrs complex
save the qrs location.
update running rr and qrs amplitude parameters.
look for the qrs complex's t-wave and mark it if
found.
else if it is not a peak
lower the peak detection threshold if the last peak found
was more than RRmax ago, and not already at its minimum.
*A peak is secondary if there is a larger peak within its neighborhood
(time +- rrmin), or if it has been identified as a T-wave associated with a
previous primary peak. A peak is primary if it is largest in its neighborhood,
or if the only larger peaks are secondary.
The above describes how the algorithm should theoretically work, but there
are bugs which make the program contradict certain parts of its supposed
logic. A list of issues from the original c, code and hence this python
implementation can be found here:
https://github.com/bemoody/wfdb/issues/17
gqrs will not be supported/developed in this library.
Examples
--------
>>> import numpy as np
>>> import wfdb
>>> from wfdb import processing
>>> # Detect using a physical input signal
>>> record = wfdb.rdrecord('sample-data/100', channels=[0])
>>> qrs_locs = processing.gqrs_detect(record.p_signal[:,0], fs=record.fs)
>>> # Detect using a digital input signal
>>> record_2 = wfdb.rdrecord('sample-data/100', channels=[0], physical=False)
>>> qrs_locs_2 = processing.gqrs_detect(d_sig=record_2.d_signal[:,0],
fs=record_2.fs,
adc_gain=record_2.adc_gain[0],
adc_zero=record_2.adc_zero[0]) | [
"Detect",
"qrs",
"locations",
"in",
"a",
"single",
"channel",
"ecg",
".",
"Functionally",
"a",
"direct",
"port",
"of",
"the",
"gqrs",
"algorithm",
"from",
"the",
"original",
"wfdb",
"package",
".",
"Accepts",
"either",
"a",
"physical",
"signal",
"or",
"a",
... | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/qrs.py#L1123-L1278 |
235,230 | MIT-LCP/wfdb-python | wfdb/processing/qrs.py | XQRS._set_conf | def _set_conf(self):
"""
Set configuration parameters from the Conf object into the detector
object.
Time values are converted to samples, and amplitude values are in mV.
"""
self.rr_init = 60 * self.fs / self.conf.hr_init
self.rr_max = 60 * self.fs / self.conf.hr_min
self.rr_min = 60 * self.fs / self.conf.hr_max
# Note: if qrs_width is odd, qrs_width == qrs_radius*2 + 1
self.qrs_width = int(self.conf.qrs_width * self.fs)
self.qrs_radius = int(self.conf.qrs_radius * self.fs)
self.qrs_thr_init = self.conf.qrs_thr_init
self.qrs_thr_min = self.conf.qrs_thr_min
self.ref_period = int(self.conf.ref_period * self.fs)
self.t_inspect_period = int(self.conf.t_inspect_period * self.fs) | python | def _set_conf(self):
self.rr_init = 60 * self.fs / self.conf.hr_init
self.rr_max = 60 * self.fs / self.conf.hr_min
self.rr_min = 60 * self.fs / self.conf.hr_max
# Note: if qrs_width is odd, qrs_width == qrs_radius*2 + 1
self.qrs_width = int(self.conf.qrs_width * self.fs)
self.qrs_radius = int(self.conf.qrs_radius * self.fs)
self.qrs_thr_init = self.conf.qrs_thr_init
self.qrs_thr_min = self.conf.qrs_thr_min
self.ref_period = int(self.conf.ref_period * self.fs)
self.t_inspect_period = int(self.conf.t_inspect_period * self.fs) | [
"def",
"_set_conf",
"(",
"self",
")",
":",
"self",
".",
"rr_init",
"=",
"60",
"*",
"self",
".",
"fs",
"/",
"self",
".",
"conf",
".",
"hr_init",
"self",
".",
"rr_max",
"=",
"60",
"*",
"self",
".",
"fs",
"/",
"self",
".",
"conf",
".",
"hr_min",
"... | Set configuration parameters from the Conf object into the detector
object.
Time values are converted to samples, and amplitude values are in mV. | [
"Set",
"configuration",
"parameters",
"from",
"the",
"Conf",
"object",
"into",
"the",
"detector",
"object",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/qrs.py#L126-L145 |
235,231 | MIT-LCP/wfdb-python | wfdb/processing/qrs.py | XQRS._bandpass | def _bandpass(self, fc_low=5, fc_high=20):
"""
Apply a bandpass filter onto the signal, and save the filtered
signal.
"""
self.fc_low = fc_low
self.fc_high = fc_high
b, a = signal.butter(2, [float(fc_low) * 2 / self.fs,
float(fc_high) * 2 / self.fs], 'pass')
self.sig_f = signal.filtfilt(b, a, self.sig[self.sampfrom:self.sampto],
axis=0)
# Save the passband gain (x2 due to double filtering)
self.filter_gain = get_filter_gain(b, a, np.mean([fc_low, fc_high]),
self.fs) * 2 | python | def _bandpass(self, fc_low=5, fc_high=20):
self.fc_low = fc_low
self.fc_high = fc_high
b, a = signal.butter(2, [float(fc_low) * 2 / self.fs,
float(fc_high) * 2 / self.fs], 'pass')
self.sig_f = signal.filtfilt(b, a, self.sig[self.sampfrom:self.sampto],
axis=0)
# Save the passband gain (x2 due to double filtering)
self.filter_gain = get_filter_gain(b, a, np.mean([fc_low, fc_high]),
self.fs) * 2 | [
"def",
"_bandpass",
"(",
"self",
",",
"fc_low",
"=",
"5",
",",
"fc_high",
"=",
"20",
")",
":",
"self",
".",
"fc_low",
"=",
"fc_low",
"self",
".",
"fc_high",
"=",
"fc_high",
"b",
",",
"a",
"=",
"signal",
".",
"butter",
"(",
"2",
",",
"[",
"float",... | Apply a bandpass filter onto the signal, and save the filtered
signal. | [
"Apply",
"a",
"bandpass",
"filter",
"onto",
"the",
"signal",
"and",
"save",
"the",
"filtered",
"signal",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/qrs.py#L148-L162 |
235,232 | MIT-LCP/wfdb-python | wfdb/processing/qrs.py | XQRS._set_init_params | def _set_init_params(self, qrs_amp_recent, noise_amp_recent, rr_recent,
last_qrs_ind):
"""
Set initial online parameters
"""
self.qrs_amp_recent = qrs_amp_recent
self.noise_amp_recent = noise_amp_recent
# What happens if qrs_thr is calculated to be less than the explicit
# min threshold? Should print warning?
self.qrs_thr = max(0.25*self.qrs_amp_recent
+ 0.75*self.noise_amp_recent,
self.qrs_thr_min * self.transform_gain)
self.rr_recent = rr_recent
self.last_qrs_ind = last_qrs_ind
# No qrs detected initially
self.last_qrs_peak_num = None | python | def _set_init_params(self, qrs_amp_recent, noise_amp_recent, rr_recent,
last_qrs_ind):
self.qrs_amp_recent = qrs_amp_recent
self.noise_amp_recent = noise_amp_recent
# What happens if qrs_thr is calculated to be less than the explicit
# min threshold? Should print warning?
self.qrs_thr = max(0.25*self.qrs_amp_recent
+ 0.75*self.noise_amp_recent,
self.qrs_thr_min * self.transform_gain)
self.rr_recent = rr_recent
self.last_qrs_ind = last_qrs_ind
# No qrs detected initially
self.last_qrs_peak_num = None | [
"def",
"_set_init_params",
"(",
"self",
",",
"qrs_amp_recent",
",",
"noise_amp_recent",
",",
"rr_recent",
",",
"last_qrs_ind",
")",
":",
"self",
".",
"qrs_amp_recent",
"=",
"qrs_amp_recent",
"self",
".",
"noise_amp_recent",
"=",
"noise_amp_recent",
"# What happens if ... | Set initial online parameters | [
"Set",
"initial",
"online",
"parameters"
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/qrs.py#L314-L330 |
235,233 | MIT-LCP/wfdb-python | wfdb/processing/qrs.py | XQRS._set_default_init_params | def _set_default_init_params(self):
"""
Set initial running parameters using default values.
The steady state equation is:
`qrs_thr = 0.25*qrs_amp + 0.75*noise_amp`
Estimate that qrs amp is 10x noise amp, giving:
`qrs_thr = 0.325 * qrs_amp or 13/40 * qrs_amp`
"""
if self.verbose:
print('Initializing using default parameters')
# Multiply the specified ecg thresholds by the filter and mwi gain
# factors
qrs_thr_init = self.qrs_thr_init * self.transform_gain
qrs_thr_min = self.qrs_thr_min * self.transform_gain
qrs_amp = 27/40 * qrs_thr_init
noise_amp = qrs_amp / 10
rr_recent = self.rr_init
last_qrs_ind = 0
self._set_init_params(qrs_amp_recent=qrs_amp,
noise_amp_recent=noise_amp,
rr_recent=rr_recent,
last_qrs_ind=last_qrs_ind)
self.learned_init_params = False | python | def _set_default_init_params(self):
if self.verbose:
print('Initializing using default parameters')
# Multiply the specified ecg thresholds by the filter and mwi gain
# factors
qrs_thr_init = self.qrs_thr_init * self.transform_gain
qrs_thr_min = self.qrs_thr_min * self.transform_gain
qrs_amp = 27/40 * qrs_thr_init
noise_amp = qrs_amp / 10
rr_recent = self.rr_init
last_qrs_ind = 0
self._set_init_params(qrs_amp_recent=qrs_amp,
noise_amp_recent=noise_amp,
rr_recent=rr_recent,
last_qrs_ind=last_qrs_ind)
self.learned_init_params = False | [
"def",
"_set_default_init_params",
"(",
"self",
")",
":",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"'Initializing using default parameters'",
")",
"# Multiply the specified ecg thresholds by the filter and mwi gain",
"# factors",
"qrs_thr_init",
"=",
"self",
".",
"q... | Set initial running parameters using default values.
The steady state equation is:
`qrs_thr = 0.25*qrs_amp + 0.75*noise_amp`
Estimate that qrs amp is 10x noise amp, giving:
`qrs_thr = 0.325 * qrs_amp or 13/40 * qrs_amp` | [
"Set",
"initial",
"running",
"parameters",
"using",
"default",
"values",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/qrs.py#L333-L361 |
235,234 | MIT-LCP/wfdb-python | wfdb/processing/qrs.py | XQRS._update_qrs | def _update_qrs(self, peak_num, backsearch=False):
"""
Update live qrs parameters. Adjust the recent rr-intervals and
qrs amplitudes, and the qrs threshold.
Parameters
----------
peak_num : int
The peak number of the mwi signal where the qrs is detected
backsearch: bool, optional
Whether the qrs was found via backsearch
"""
i = self.peak_inds_i[peak_num]
# Update recent rr if the beat is consecutive (do this before
# updating self.last_qrs_ind)
rr_new = i - self.last_qrs_ind
if rr_new < self.rr_max:
self.rr_recent = 0.875*self.rr_recent + 0.125*rr_new
self.qrs_inds.append(i)
self.last_qrs_ind = i
# Peak number corresponding to last qrs
self.last_qrs_peak_num = self.peak_num
# qrs recent amplitude is adjusted twice as quickly if the peak
# was found via backsearch
if backsearch:
self.backsearch_qrs_inds.append(i)
self.qrs_amp_recent = (0.75*self.qrs_amp_recent
+ 0.25*self.sig_i[i])
else:
self.qrs_amp_recent = (0.875*self.qrs_amp_recent
+ 0.125*self.sig_i[i])
self.qrs_thr = max((0.25*self.qrs_amp_recent
+ 0.75*self.noise_amp_recent), self.qrs_thr_min)
return | python | def _update_qrs(self, peak_num, backsearch=False):
i = self.peak_inds_i[peak_num]
# Update recent rr if the beat is consecutive (do this before
# updating self.last_qrs_ind)
rr_new = i - self.last_qrs_ind
if rr_new < self.rr_max:
self.rr_recent = 0.875*self.rr_recent + 0.125*rr_new
self.qrs_inds.append(i)
self.last_qrs_ind = i
# Peak number corresponding to last qrs
self.last_qrs_peak_num = self.peak_num
# qrs recent amplitude is adjusted twice as quickly if the peak
# was found via backsearch
if backsearch:
self.backsearch_qrs_inds.append(i)
self.qrs_amp_recent = (0.75*self.qrs_amp_recent
+ 0.25*self.sig_i[i])
else:
self.qrs_amp_recent = (0.875*self.qrs_amp_recent
+ 0.125*self.sig_i[i])
self.qrs_thr = max((0.25*self.qrs_amp_recent
+ 0.75*self.noise_amp_recent), self.qrs_thr_min)
return | [
"def",
"_update_qrs",
"(",
"self",
",",
"peak_num",
",",
"backsearch",
"=",
"False",
")",
":",
"i",
"=",
"self",
".",
"peak_inds_i",
"[",
"peak_num",
"]",
"# Update recent rr if the beat is consecutive (do this before",
"# updating self.last_qrs_ind)",
"rr_new",
"=",
... | Update live qrs parameters. Adjust the recent rr-intervals and
qrs amplitudes, and the qrs threshold.
Parameters
----------
peak_num : int
The peak number of the mwi signal where the qrs is detected
backsearch: bool, optional
Whether the qrs was found via backsearch | [
"Update",
"live",
"qrs",
"parameters",
".",
"Adjust",
"the",
"recent",
"rr",
"-",
"intervals",
"and",
"qrs",
"amplitudes",
"and",
"the",
"qrs",
"threshold",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/qrs.py#L396-L435 |
235,235 | MIT-LCP/wfdb-python | wfdb/processing/qrs.py | XQRS._is_twave | def _is_twave(self, peak_num):
"""
Check whether a segment is a t-wave. Compare the maximum gradient of
the filtered signal segment with that of the previous qrs segment.
Parameters
----------
peak_num : int
The peak number of the mwi signal where the qrs is detected
"""
i = self.peak_inds_i[peak_num]
# Due to initialization parameters, last_qrs_ind may be negative.
# No way to check in this instance.
if self.last_qrs_ind - self.qrs_radius < 0:
return False
# Get half the qrs width of the signal to the left.
# Should this be squared?
sig_segment = normalize((self.sig_f[i - self.qrs_radius:i]
).reshape(-1, 1), axis=0)
last_qrs_segment = self.sig_f[self.last_qrs_ind - self.qrs_radius:
self.last_qrs_ind]
segment_slope = np.diff(sig_segment)
last_qrs_slope = np.diff(last_qrs_segment)
# Should we be using absolute values?
if max(segment_slope) < 0.5*max(abs(last_qrs_slope)):
return True
else:
return False | python | def _is_twave(self, peak_num):
i = self.peak_inds_i[peak_num]
# Due to initialization parameters, last_qrs_ind may be negative.
# No way to check in this instance.
if self.last_qrs_ind - self.qrs_radius < 0:
return False
# Get half the qrs width of the signal to the left.
# Should this be squared?
sig_segment = normalize((self.sig_f[i - self.qrs_radius:i]
).reshape(-1, 1), axis=0)
last_qrs_segment = self.sig_f[self.last_qrs_ind - self.qrs_radius:
self.last_qrs_ind]
segment_slope = np.diff(sig_segment)
last_qrs_slope = np.diff(last_qrs_segment)
# Should we be using absolute values?
if max(segment_slope) < 0.5*max(abs(last_qrs_slope)):
return True
else:
return False | [
"def",
"_is_twave",
"(",
"self",
",",
"peak_num",
")",
":",
"i",
"=",
"self",
".",
"peak_inds_i",
"[",
"peak_num",
"]",
"# Due to initialization parameters, last_qrs_ind may be negative.",
"# No way to check in this instance.",
"if",
"self",
".",
"last_qrs_ind",
"-",
"s... | Check whether a segment is a t-wave. Compare the maximum gradient of
the filtered signal segment with that of the previous qrs segment.
Parameters
----------
peak_num : int
The peak number of the mwi signal where the qrs is detected | [
"Check",
"whether",
"a",
"segment",
"is",
"a",
"t",
"-",
"wave",
".",
"Compare",
"the",
"maximum",
"gradient",
"of",
"the",
"filtered",
"signal",
"segment",
"with",
"that",
"of",
"the",
"previous",
"qrs",
"segment",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/qrs.py#L438-L470 |
235,236 | MIT-LCP/wfdb-python | wfdb/processing/qrs.py | XQRS._update_noise | def _update_noise(self, peak_num):
"""
Update live noise parameters
"""
i = self.peak_inds_i[peak_num]
self.noise_amp_recent = (0.875*self.noise_amp_recent
+ 0.125*self.sig_i[i])
return | python | def _update_noise(self, peak_num):
i = self.peak_inds_i[peak_num]
self.noise_amp_recent = (0.875*self.noise_amp_recent
+ 0.125*self.sig_i[i])
return | [
"def",
"_update_noise",
"(",
"self",
",",
"peak_num",
")",
":",
"i",
"=",
"self",
".",
"peak_inds_i",
"[",
"peak_num",
"]",
"self",
".",
"noise_amp_recent",
"=",
"(",
"0.875",
"*",
"self",
".",
"noise_amp_recent",
"+",
"0.125",
"*",
"self",
".",
"sig_i",... | Update live noise parameters | [
"Update",
"live",
"noise",
"parameters"
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/qrs.py#L472-L479 |
235,237 | MIT-LCP/wfdb-python | wfdb/processing/qrs.py | XQRS._require_backsearch | def _require_backsearch(self):
"""
Determine whether a backsearch should be performed on prior peaks
"""
if self.peak_num == self.n_peaks_i-1:
# If we just return false, we may miss a chance to backsearch.
# Update this?
return False
next_peak_ind = self.peak_inds_i[self.peak_num + 1]
if next_peak_ind-self.last_qrs_ind > self.rr_recent*1.66:
return True
else:
return False | python | def _require_backsearch(self):
if self.peak_num == self.n_peaks_i-1:
# If we just return false, we may miss a chance to backsearch.
# Update this?
return False
next_peak_ind = self.peak_inds_i[self.peak_num + 1]
if next_peak_ind-self.last_qrs_ind > self.rr_recent*1.66:
return True
else:
return False | [
"def",
"_require_backsearch",
"(",
"self",
")",
":",
"if",
"self",
".",
"peak_num",
"==",
"self",
".",
"n_peaks_i",
"-",
"1",
":",
"# If we just return false, we may miss a chance to backsearch.",
"# Update this?",
"return",
"False",
"next_peak_ind",
"=",
"self",
".",... | Determine whether a backsearch should be performed on prior peaks | [
"Determine",
"whether",
"a",
"backsearch",
"should",
"be",
"performed",
"on",
"prior",
"peaks"
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/qrs.py#L481-L495 |
235,238 | MIT-LCP/wfdb-python | wfdb/processing/qrs.py | XQRS._run_detection | def _run_detection(self):
"""
Run the qrs detection after all signals and parameters have been
configured and set.
"""
if self.verbose:
print('Running QRS detection...')
# Detected qrs indices
self.qrs_inds = []
# qrs indices found via backsearch
self.backsearch_qrs_inds = []
# Iterate through mwi signal peak indices
for self.peak_num in range(self.n_peaks_i):
if self._is_qrs(self.peak_num):
self._update_qrs(self.peak_num)
else:
self._update_noise(self.peak_num)
# Before continuing to the next peak, do backsearch if
# necessary
if self._require_backsearch():
self._backsearch()
# Detected indices are relative to starting sample
if self.qrs_inds:
self.qrs_inds = np.array(self.qrs_inds) + self.sampfrom
else:
self.qrs_inds = np.array(self.qrs_inds)
if self.verbose:
print('QRS detection complete.') | python | def _run_detection(self):
if self.verbose:
print('Running QRS detection...')
# Detected qrs indices
self.qrs_inds = []
# qrs indices found via backsearch
self.backsearch_qrs_inds = []
# Iterate through mwi signal peak indices
for self.peak_num in range(self.n_peaks_i):
if self._is_qrs(self.peak_num):
self._update_qrs(self.peak_num)
else:
self._update_noise(self.peak_num)
# Before continuing to the next peak, do backsearch if
# necessary
if self._require_backsearch():
self._backsearch()
# Detected indices are relative to starting sample
if self.qrs_inds:
self.qrs_inds = np.array(self.qrs_inds) + self.sampfrom
else:
self.qrs_inds = np.array(self.qrs_inds)
if self.verbose:
print('QRS detection complete.') | [
"def",
"_run_detection",
"(",
"self",
")",
":",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"'Running QRS detection...'",
")",
"# Detected qrs indices",
"self",
".",
"qrs_inds",
"=",
"[",
"]",
"# qrs indices found via backsearch",
"self",
".",
"backsearch_qrs_i... | Run the qrs detection after all signals and parameters have been
configured and set. | [
"Run",
"the",
"qrs",
"detection",
"after",
"all",
"signals",
"and",
"parameters",
"have",
"been",
"configured",
"and",
"set",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/qrs.py#L510-L543 |
235,239 | MIT-LCP/wfdb-python | wfdb/processing/qrs.py | XQRS.detect | def detect(self, sampfrom=0, sampto='end', learn=True, verbose=True):
"""
Detect qrs locations between two samples.
Parameters
----------
sampfrom : int, optional
The starting sample number to run the detection on.
sampto : int, optional
The final sample number to run the detection on. Set as
'end' to run on the entire signal.
learn : bool, optional
Whether to apply learning on the signal before running the
main detection. If learning fails or is not conducted, the
default configuration parameters will be used to initialize
these variables. See the `XQRS._learn_init_params` docstring
for details.
verbose : bool, optional
Whether to display the stages and outcomes of the detection
process.
"""
if sampfrom < 0:
raise ValueError("'sampfrom' cannot be negative")
self.sampfrom = sampfrom
if sampto == 'end':
sampto = self.sig_len
elif sampto > self.sig_len:
raise ValueError("'sampto' cannot exceed the signal length")
self.sampto = sampto
self.verbose = verbose
# Don't attempt to run on a flat signal
if np.max(self.sig) == np.min(self.sig):
self.qrs_inds = np.empty(0)
if self.verbose:
print('Flat signal. Detection skipped.')
return
# Get/set signal configuration fields from Conf object
self._set_conf()
# Bandpass filter the signal
self._bandpass()
# Compute moving wave integration of filtered signal
self._mwi()
# Initialize the running parameters
if learn:
self._learn_init_params()
else:
self._set_default_init_params()
# Run the detection
self._run_detection() | python | def detect(self, sampfrom=0, sampto='end', learn=True, verbose=True):
if sampfrom < 0:
raise ValueError("'sampfrom' cannot be negative")
self.sampfrom = sampfrom
if sampto == 'end':
sampto = self.sig_len
elif sampto > self.sig_len:
raise ValueError("'sampto' cannot exceed the signal length")
self.sampto = sampto
self.verbose = verbose
# Don't attempt to run on a flat signal
if np.max(self.sig) == np.min(self.sig):
self.qrs_inds = np.empty(0)
if self.verbose:
print('Flat signal. Detection skipped.')
return
# Get/set signal configuration fields from Conf object
self._set_conf()
# Bandpass filter the signal
self._bandpass()
# Compute moving wave integration of filtered signal
self._mwi()
# Initialize the running parameters
if learn:
self._learn_init_params()
else:
self._set_default_init_params()
# Run the detection
self._run_detection() | [
"def",
"detect",
"(",
"self",
",",
"sampfrom",
"=",
"0",
",",
"sampto",
"=",
"'end'",
",",
"learn",
"=",
"True",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"sampfrom",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"'sampfrom' cannot be negative\"",
")",... | Detect qrs locations between two samples.
Parameters
----------
sampfrom : int, optional
The starting sample number to run the detection on.
sampto : int, optional
The final sample number to run the detection on. Set as
'end' to run on the entire signal.
learn : bool, optional
Whether to apply learning on the signal before running the
main detection. If learning fails or is not conducted, the
default configuration parameters will be used to initialize
these variables. See the `XQRS._learn_init_params` docstring
for details.
verbose : bool, optional
Whether to display the stages and outcomes of the detection
process. | [
"Detect",
"qrs",
"locations",
"between",
"two",
"samples",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/qrs.py#L546-L600 |
235,240 | MIT-LCP/wfdb-python | wfdb/processing/qrs.py | GQRS.detect | def detect(self, x, conf, adc_zero):
"""
Run detection. x is digital signal
"""
self.c = conf
self.annotations = []
self.sample_valid = False
if len(x) < 1:
return []
self.x = x
self.adc_zero = adc_zero
self.qfv = np.zeros((self.c._BUFLN), dtype="int64")
self.smv = np.zeros((self.c._BUFLN), dtype="int64")
self.v1 = 0
t0 = 0
self.tf = len(x) - 1
self.t = 0 - self.c.dt4
self.annot = GQRS.Annotation(0, "NOTE", 0, 0)
# Cicular buffer of Peaks
first_peak = GQRS.Peak(0, 0, 0)
tmp = first_peak
for _ in range(1, self.c._NPEAKS):
tmp.next_peak = GQRS.Peak(0, 0, 0)
tmp.next_peak.prev_peak = tmp
tmp = tmp.next_peak
tmp.next_peak = first_peak
first_peak.prev_peak = tmp
self.current_peak = first_peak
if self.c.spm > self.c._BUFLN:
if self.tf - t0 > self.c._BUFLN:
tf_learn = t0 + self.c._BUFLN - self.c.dt4
else:
tf_learn = self.tf - self.c.dt4
else:
if self.tf - t0 > self.c.spm:
tf_learn = t0 + self.c.spm - self.c.dt4
else:
tf_learn = self.tf - self.c.dt4
self.countdown = -1
self.state = "LEARNING"
self.gqrs(t0, tf_learn)
self.rewind_gqrs()
self.state = "RUNNING"
self.t = t0 - self.c.dt4
self.gqrs(t0, self.tf)
return self.annotations | python | def detect(self, x, conf, adc_zero):
self.c = conf
self.annotations = []
self.sample_valid = False
if len(x) < 1:
return []
self.x = x
self.adc_zero = adc_zero
self.qfv = np.zeros((self.c._BUFLN), dtype="int64")
self.smv = np.zeros((self.c._BUFLN), dtype="int64")
self.v1 = 0
t0 = 0
self.tf = len(x) - 1
self.t = 0 - self.c.dt4
self.annot = GQRS.Annotation(0, "NOTE", 0, 0)
# Cicular buffer of Peaks
first_peak = GQRS.Peak(0, 0, 0)
tmp = first_peak
for _ in range(1, self.c._NPEAKS):
tmp.next_peak = GQRS.Peak(0, 0, 0)
tmp.next_peak.prev_peak = tmp
tmp = tmp.next_peak
tmp.next_peak = first_peak
first_peak.prev_peak = tmp
self.current_peak = first_peak
if self.c.spm > self.c._BUFLN:
if self.tf - t0 > self.c._BUFLN:
tf_learn = t0 + self.c._BUFLN - self.c.dt4
else:
tf_learn = self.tf - self.c.dt4
else:
if self.tf - t0 > self.c.spm:
tf_learn = t0 + self.c.spm - self.c.dt4
else:
tf_learn = self.tf - self.c.dt4
self.countdown = -1
self.state = "LEARNING"
self.gqrs(t0, tf_learn)
self.rewind_gqrs()
self.state = "RUNNING"
self.t = t0 - self.c.dt4
self.gqrs(t0, self.tf)
return self.annotations | [
"def",
"detect",
"(",
"self",
",",
"x",
",",
"conf",
",",
"adc_zero",
")",
":",
"self",
".",
"c",
"=",
"conf",
"self",
".",
"annotations",
"=",
"[",
"]",
"self",
".",
"sample_valid",
"=",
"False",
"if",
"len",
"(",
"x",
")",
"<",
"1",
":",
"ret... | Run detection. x is digital signal | [
"Run",
"detection",
".",
"x",
"is",
"digital",
"signal"
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/qrs.py#L750-L806 |
235,241 | MIT-LCP/wfdb-python | wfdb/processing/hr.py | compute_hr | def compute_hr(sig_len, qrs_inds, fs):
"""
Compute instantaneous heart rate from peak indices.
Parameters
----------
sig_len : int
The length of the corresponding signal
qrs_inds : numpy array
The qrs index locations
fs : int, or float
The corresponding signal's sampling frequency.
Returns
-------
heart_rate : numpy array
An array of the instantaneous heart rate, with the length of the
corresponding signal. Contains numpy.nan where heart rate could
not be computed.
"""
heart_rate = np.full(sig_len, np.nan, dtype='float32')
if len(qrs_inds) < 2:
return heart_rate
for i in range(0, len(qrs_inds)-2):
a = qrs_inds[i]
b = qrs_inds[i+1]
c = qrs_inds[i+2]
rr = (b-a) * (1.0 / fs) * 1000
hr = 60000.0 / rr
heart_rate[b+1:c+1] = hr
heart_rate[qrs_inds[-1]:] = heart_rate[qrs_inds[-1]]
return heart_rate | python | def compute_hr(sig_len, qrs_inds, fs):
heart_rate = np.full(sig_len, np.nan, dtype='float32')
if len(qrs_inds) < 2:
return heart_rate
for i in range(0, len(qrs_inds)-2):
a = qrs_inds[i]
b = qrs_inds[i+1]
c = qrs_inds[i+2]
rr = (b-a) * (1.0 / fs) * 1000
hr = 60000.0 / rr
heart_rate[b+1:c+1] = hr
heart_rate[qrs_inds[-1]:] = heart_rate[qrs_inds[-1]]
return heart_rate | [
"def",
"compute_hr",
"(",
"sig_len",
",",
"qrs_inds",
",",
"fs",
")",
":",
"heart_rate",
"=",
"np",
".",
"full",
"(",
"sig_len",
",",
"np",
".",
"nan",
",",
"dtype",
"=",
"'float32'",
")",
"if",
"len",
"(",
"qrs_inds",
")",
"<",
"2",
":",
"return",... | Compute instantaneous heart rate from peak indices.
Parameters
----------
sig_len : int
The length of the corresponding signal
qrs_inds : numpy array
The qrs index locations
fs : int, or float
The corresponding signal's sampling frequency.
Returns
-------
heart_rate : numpy array
An array of the instantaneous heart rate, with the length of the
corresponding signal. Contains numpy.nan where heart rate could
not be computed. | [
"Compute",
"instantaneous",
"heart",
"rate",
"from",
"peak",
"indices",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/hr.py#L4-L40 |
235,242 | MIT-LCP/wfdb-python | wfdb/processing/hr.py | calc_rr | def calc_rr(qrs_locs, fs=None, min_rr=None, max_rr=None, qrs_units='samples',
rr_units='samples'):
"""
Compute rr intervals from qrs indices by extracting the time
differences.
Parameters
----------
qrs_locs : numpy array
1d array of qrs locations.
fs : float, optional
Sampling frequency of the original signal. Needed if
`qrs_units` does not match `rr_units`.
min_rr : float, optional
The minimum allowed rr interval. Values below this are excluded
from the returned rr intervals. Units are in `rr_units`.
max_rr : float, optional
The maximum allowed rr interval. Values above this are excluded
from the returned rr intervals. Units are in `rr_units`.
qrs_units : str, optional
The time unit of `qrs_locs`. Must be one of: 'samples',
'seconds'.
rr_units : str, optional
The desired time unit of the returned rr intervals in. Must be
one of: 'samples', 'seconds'.
Returns
-------
rr : numpy array
Array of rr intervals.
"""
rr = np.diff(qrs_locs)
# Empty input qrs_locs
if not len(rr):
return rr
# Convert to desired output rr units if needed
if qrs_units == 'samples' and rr_units == 'seconds':
rr = rr / fs
elif qrs_units == 'seconds' and rr_units == 'samples':
rr = rr * fs
# Apply rr interval filters
if min_rr is not None:
rr = rr[rr > min_rr]
if max_rr is not None:
rr = rr[rr < max_rr]
return rr | python | def calc_rr(qrs_locs, fs=None, min_rr=None, max_rr=None, qrs_units='samples',
rr_units='samples'):
rr = np.diff(qrs_locs)
# Empty input qrs_locs
if not len(rr):
return rr
# Convert to desired output rr units if needed
if qrs_units == 'samples' and rr_units == 'seconds':
rr = rr / fs
elif qrs_units == 'seconds' and rr_units == 'samples':
rr = rr * fs
# Apply rr interval filters
if min_rr is not None:
rr = rr[rr > min_rr]
if max_rr is not None:
rr = rr[rr < max_rr]
return rr | [
"def",
"calc_rr",
"(",
"qrs_locs",
",",
"fs",
"=",
"None",
",",
"min_rr",
"=",
"None",
",",
"max_rr",
"=",
"None",
",",
"qrs_units",
"=",
"'samples'",
",",
"rr_units",
"=",
"'samples'",
")",
":",
"rr",
"=",
"np",
".",
"diff",
"(",
"qrs_locs",
")",
... | Compute rr intervals from qrs indices by extracting the time
differences.
Parameters
----------
qrs_locs : numpy array
1d array of qrs locations.
fs : float, optional
Sampling frequency of the original signal. Needed if
`qrs_units` does not match `rr_units`.
min_rr : float, optional
The minimum allowed rr interval. Values below this are excluded
from the returned rr intervals. Units are in `rr_units`.
max_rr : float, optional
The maximum allowed rr interval. Values above this are excluded
from the returned rr intervals. Units are in `rr_units`.
qrs_units : str, optional
The time unit of `qrs_locs`. Must be one of: 'samples',
'seconds'.
rr_units : str, optional
The desired time unit of the returned rr intervals in. Must be
one of: 'samples', 'seconds'.
Returns
-------
rr : numpy array
Array of rr intervals. | [
"Compute",
"rr",
"intervals",
"from",
"qrs",
"indices",
"by",
"extracting",
"the",
"time",
"differences",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/hr.py#L43-L94 |
235,243 | MIT-LCP/wfdb-python | wfdb/processing/hr.py | calc_mean_hr | def calc_mean_hr(rr, fs=None, min_rr=None, max_rr=None, rr_units='samples'):
"""
Compute mean heart rate in beats per minute, from a set of rr
intervals. Returns 0 if rr is empty.
Parameters
----------
rr : numpy array
Array of rr intervals.
fs : int, or float
The corresponding signal's sampling frequency. Required if
'input_time_units' == 'samples'.
min_rr : float, optional
The minimum allowed rr interval. Values below this are excluded
when calculating the heart rate. Units are in `rr_units`.
max_rr : float, optional
The maximum allowed rr interval. Values above this are excluded
when calculating the heart rate. Units are in `rr_units`.
rr_units : str, optional
The time units of the input rr intervals. Must be one of:
'samples', 'seconds'.
Returns
-------
mean_hr : float
The mean heart rate in beats per minute
"""
if not len(rr):
return 0
if min_rr is not None:
rr = rr[rr > min_rr]
if max_rr is not None:
rr = rr[rr < max_rr]
mean_rr = np.mean(rr)
mean_hr = 60 / mean_rr
# Convert to bpm
if rr_units == 'samples':
mean_hr = mean_hr * fs
return mean_hr | python | def calc_mean_hr(rr, fs=None, min_rr=None, max_rr=None, rr_units='samples'):
if not len(rr):
return 0
if min_rr is not None:
rr = rr[rr > min_rr]
if max_rr is not None:
rr = rr[rr < max_rr]
mean_rr = np.mean(rr)
mean_hr = 60 / mean_rr
# Convert to bpm
if rr_units == 'samples':
mean_hr = mean_hr * fs
return mean_hr | [
"def",
"calc_mean_hr",
"(",
"rr",
",",
"fs",
"=",
"None",
",",
"min_rr",
"=",
"None",
",",
"max_rr",
"=",
"None",
",",
"rr_units",
"=",
"'samples'",
")",
":",
"if",
"not",
"len",
"(",
"rr",
")",
":",
"return",
"0",
"if",
"min_rr",
"is",
"not",
"N... | Compute mean heart rate in beats per minute, from a set of rr
intervals. Returns 0 if rr is empty.
Parameters
----------
rr : numpy array
Array of rr intervals.
fs : int, or float
The corresponding signal's sampling frequency. Required if
'input_time_units' == 'samples'.
min_rr : float, optional
The minimum allowed rr interval. Values below this are excluded
when calculating the heart rate. Units are in `rr_units`.
max_rr : float, optional
The maximum allowed rr interval. Values above this are excluded
when calculating the heart rate. Units are in `rr_units`.
rr_units : str, optional
The time units of the input rr intervals. Must be one of:
'samples', 'seconds'.
Returns
-------
mean_hr : float
The mean heart rate in beats per minute | [
"Compute",
"mean",
"heart",
"rate",
"in",
"beats",
"per",
"minute",
"from",
"a",
"set",
"of",
"rr",
"intervals",
".",
"Returns",
"0",
"if",
"rr",
"is",
"empty",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/hr.py#L97-L142 |
235,244 | MIT-LCP/wfdb-python | wfdb/processing/evaluate.py | compare_annotations | def compare_annotations(ref_sample, test_sample, window_width, signal=None):
"""
Compare a set of reference annotation locations against a set of
test annotation locations.
See the Comparitor class docstring for more information.
Parameters
----------
ref_sample : 1d numpy array
Array of reference sample locations
test_sample : 1d numpy array
Array of test sample locations to compare
window_width : int
The maximum absolute difference in sample numbers that is
permitted for matching annotations.
signal : 1d numpy array, optional
The original signal of the two annotations. Only used for
plotting.
Returns
-------
comparitor : Comparitor object
Object containing parameters about the two sets of annotations
Examples
--------
>>> import wfdb
>>> from wfdb import processing
>>> sig, fields = wfdb.rdsamp('sample-data/100', channels=[0])
>>> ann_ref = wfdb.rdann('sample-data/100','atr')
>>> xqrs = processing.XQRS(sig=sig[:,0], fs=fields['fs'])
>>> xqrs.detect()
>>> comparitor = processing.compare_annotations(ann_ref.sample[1:],
xqrs.qrs_inds,
int(0.1 * fields['fs']),
sig[:,0])
>>> comparitor.print_summary()
>>> comparitor.plot()
"""
comparitor = Comparitor(ref_sample=ref_sample, test_sample=test_sample,
window_width=window_width, signal=signal)
comparitor.compare()
return comparitor | python | def compare_annotations(ref_sample, test_sample, window_width, signal=None):
comparitor = Comparitor(ref_sample=ref_sample, test_sample=test_sample,
window_width=window_width, signal=signal)
comparitor.compare()
return comparitor | [
"def",
"compare_annotations",
"(",
"ref_sample",
",",
"test_sample",
",",
"window_width",
",",
"signal",
"=",
"None",
")",
":",
"comparitor",
"=",
"Comparitor",
"(",
"ref_sample",
"=",
"ref_sample",
",",
"test_sample",
"=",
"test_sample",
",",
"window_width",
"=... | Compare a set of reference annotation locations against a set of
test annotation locations.
See the Comparitor class docstring for more information.
Parameters
----------
ref_sample : 1d numpy array
Array of reference sample locations
test_sample : 1d numpy array
Array of test sample locations to compare
window_width : int
The maximum absolute difference in sample numbers that is
permitted for matching annotations.
signal : 1d numpy array, optional
The original signal of the two annotations. Only used for
plotting.
Returns
-------
comparitor : Comparitor object
Object containing parameters about the two sets of annotations
Examples
--------
>>> import wfdb
>>> from wfdb import processing
>>> sig, fields = wfdb.rdsamp('sample-data/100', channels=[0])
>>> ann_ref = wfdb.rdann('sample-data/100','atr')
>>> xqrs = processing.XQRS(sig=sig[:,0], fs=fields['fs'])
>>> xqrs.detect()
>>> comparitor = processing.compare_annotations(ann_ref.sample[1:],
xqrs.qrs_inds,
int(0.1 * fields['fs']),
sig[:,0])
>>> comparitor.print_summary()
>>> comparitor.plot() | [
"Compare",
"a",
"set",
"of",
"reference",
"annotation",
"locations",
"against",
"a",
"set",
"of",
"test",
"annotation",
"locations",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/evaluate.py#L334-L381 |
235,245 | MIT-LCP/wfdb-python | wfdb/processing/evaluate.py | benchmark_mitdb | def benchmark_mitdb(detector, verbose=False, print_results=False):
"""
Benchmark a qrs detector against mitdb's records.
Parameters
----------
detector : function
The detector function.
verbose : bool, optional
The verbose option of the detector function.
print_results : bool, optional
Whether to print the overall performance, and the results for
each record.
Returns
-------
comparitors : dictionary
Dictionary of Comparitor objects run on the records, keyed on
the record names.
specificity : float
Aggregate specificity.
positive_predictivity : float
Aggregate positive_predictivity.
false_positive_rate : float
Aggregate false_positive_rate.
Notes
-----
TODO:
- remove non-qrs detections from reference annotations
- allow kwargs
Examples
--------
>>> import wfdb
>> from wfdb.processing import benchmark_mitdb, xqrs_detect
>>> comparitors, spec, pp, fpr = benchmark_mitdb(xqrs_detect)
"""
record_list = get_record_list('mitdb')
n_records = len(record_list)
# Function arguments for starmap
args = zip(record_list, n_records * [detector], n_records * [verbose])
# Run detector and compare against reference annotations for all
# records
with Pool(cpu_count() - 1) as p:
comparitors = p.starmap(benchmark_mitdb_record, args)
# Calculate aggregate stats
specificity = np.mean([c.specificity for c in comparitors])
positive_predictivity = np.mean(
[c.positive_predictivity for c in comparitors])
false_positive_rate = np.mean(
[c.false_positive_rate for c in comparitors])
comparitors = dict(zip(record_list, comparitors))
print('Benchmark complete')
if print_results:
print('\nOverall MITDB Performance - Specificity: %.4f, Positive Predictivity: %.4f, False Positive Rate: %.4f\n'
% (specificity, positive_predictivity, false_positive_rate))
for record_name in record_list:
print('Record %s:' % record_name)
comparitors[record_name].print_summary()
print('\n\n')
return comparitors, specificity, positive_predictivity, false_positive_rate | python | def benchmark_mitdb(detector, verbose=False, print_results=False):
record_list = get_record_list('mitdb')
n_records = len(record_list)
# Function arguments for starmap
args = zip(record_list, n_records * [detector], n_records * [verbose])
# Run detector and compare against reference annotations for all
# records
with Pool(cpu_count() - 1) as p:
comparitors = p.starmap(benchmark_mitdb_record, args)
# Calculate aggregate stats
specificity = np.mean([c.specificity for c in comparitors])
positive_predictivity = np.mean(
[c.positive_predictivity for c in comparitors])
false_positive_rate = np.mean(
[c.false_positive_rate for c in comparitors])
comparitors = dict(zip(record_list, comparitors))
print('Benchmark complete')
if print_results:
print('\nOverall MITDB Performance - Specificity: %.4f, Positive Predictivity: %.4f, False Positive Rate: %.4f\n'
% (specificity, positive_predictivity, false_positive_rate))
for record_name in record_list:
print('Record %s:' % record_name)
comparitors[record_name].print_summary()
print('\n\n')
return comparitors, specificity, positive_predictivity, false_positive_rate | [
"def",
"benchmark_mitdb",
"(",
"detector",
",",
"verbose",
"=",
"False",
",",
"print_results",
"=",
"False",
")",
":",
"record_list",
"=",
"get_record_list",
"(",
"'mitdb'",
")",
"n_records",
"=",
"len",
"(",
"record_list",
")",
"# Function arguments for starmap",... | Benchmark a qrs detector against mitdb's records.
Parameters
----------
detector : function
The detector function.
verbose : bool, optional
The verbose option of the detector function.
print_results : bool, optional
Whether to print the overall performance, and the results for
each record.
Returns
-------
comparitors : dictionary
Dictionary of Comparitor objects run on the records, keyed on
the record names.
specificity : float
Aggregate specificity.
positive_predictivity : float
Aggregate positive_predictivity.
false_positive_rate : float
Aggregate false_positive_rate.
Notes
-----
TODO:
- remove non-qrs detections from reference annotations
- allow kwargs
Examples
--------
>>> import wfdb
>> from wfdb.processing import benchmark_mitdb, xqrs_detect
>>> comparitors, spec, pp, fpr = benchmark_mitdb(xqrs_detect) | [
"Benchmark",
"a",
"qrs",
"detector",
"against",
"mitdb",
"s",
"records",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/evaluate.py#L384-L454 |
235,246 | MIT-LCP/wfdb-python | wfdb/processing/evaluate.py | benchmark_mitdb_record | def benchmark_mitdb_record(rec, detector, verbose):
"""
Benchmark a single mitdb record
"""
sig, fields = rdsamp(rec, pb_dir='mitdb', channels=[0])
ann_ref = rdann(rec, pb_dir='mitdb', extension='atr')
qrs_inds = detector(sig=sig[:,0], fs=fields['fs'], verbose=verbose)
comparitor = compare_annotations(ref_sample=ann_ref.sample[1:],
test_sample=qrs_inds,
window_width=int(0.1 * fields['fs']))
if verbose:
print('Finished record %s' % rec)
return comparitor | python | def benchmark_mitdb_record(rec, detector, verbose):
sig, fields = rdsamp(rec, pb_dir='mitdb', channels=[0])
ann_ref = rdann(rec, pb_dir='mitdb', extension='atr')
qrs_inds = detector(sig=sig[:,0], fs=fields['fs'], verbose=verbose)
comparitor = compare_annotations(ref_sample=ann_ref.sample[1:],
test_sample=qrs_inds,
window_width=int(0.1 * fields['fs']))
if verbose:
print('Finished record %s' % rec)
return comparitor | [
"def",
"benchmark_mitdb_record",
"(",
"rec",
",",
"detector",
",",
"verbose",
")",
":",
"sig",
",",
"fields",
"=",
"rdsamp",
"(",
"rec",
",",
"pb_dir",
"=",
"'mitdb'",
",",
"channels",
"=",
"[",
"0",
"]",
")",
"ann_ref",
"=",
"rdann",
"(",
"rec",
","... | Benchmark a single mitdb record | [
"Benchmark",
"a",
"single",
"mitdb",
"record"
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/evaluate.py#L457-L471 |
235,247 | MIT-LCP/wfdb-python | wfdb/processing/evaluate.py | Comparitor._calc_stats | def _calc_stats(self):
"""
Calculate performance statistics after the two sets of annotations
are compared.
Example:
-------------------
ref=500 test=480
{ 30 { 470 } 10 }
-------------------
tp = 470
fp = 10
fn = 30
specificity = 470 / 500
positive_predictivity = 470 / 480
false_positive_rate = 10 / 480
"""
# Reference annotation indices that were detected
self.matched_ref_inds = np.where(self.matching_sample_nums != -1)[0]
# Reference annotation indices that were missed
self.unmatched_ref_inds = np.where(self.matching_sample_nums == -1)[0]
# Test annotation indices that were matched to a reference annotation
self.matched_test_inds = self.matching_sample_nums[
self.matching_sample_nums != -1]
# Test annotation indices that were unmatched to a reference annotation
self.unmatched_test_inds = np.setdiff1d(np.array(range(self.n_test)),
self.matched_test_inds, assume_unique=True)
# Sample numbers that were matched and unmatched
self.matched_ref_sample = self.ref_sample[self.matched_ref_inds]
self.unmatched_ref_sample = self.ref_sample[self.unmatched_ref_inds]
self.matched_test_sample = self.test_sample[self.matched_test_inds]
self.unmatched_test_sample = self.test_sample[self.unmatched_test_inds]
# True positives = matched reference samples
self.tp = len(self.matched_ref_inds)
# False positives = extra test samples not matched
self.fp = self.n_test - self.tp
# False negatives = undetected reference samples
self.fn = self.n_ref - self.tp
# No tn attribute
self.specificity = float(self.tp) / self.n_ref
self.positive_predictivity = float(self.tp) / self.n_test
self.false_positive_rate = float(self.fp) / self.n_test | python | def _calc_stats(self):
# Reference annotation indices that were detected
self.matched_ref_inds = np.where(self.matching_sample_nums != -1)[0]
# Reference annotation indices that were missed
self.unmatched_ref_inds = np.where(self.matching_sample_nums == -1)[0]
# Test annotation indices that were matched to a reference annotation
self.matched_test_inds = self.matching_sample_nums[
self.matching_sample_nums != -1]
# Test annotation indices that were unmatched to a reference annotation
self.unmatched_test_inds = np.setdiff1d(np.array(range(self.n_test)),
self.matched_test_inds, assume_unique=True)
# Sample numbers that were matched and unmatched
self.matched_ref_sample = self.ref_sample[self.matched_ref_inds]
self.unmatched_ref_sample = self.ref_sample[self.unmatched_ref_inds]
self.matched_test_sample = self.test_sample[self.matched_test_inds]
self.unmatched_test_sample = self.test_sample[self.unmatched_test_inds]
# True positives = matched reference samples
self.tp = len(self.matched_ref_inds)
# False positives = extra test samples not matched
self.fp = self.n_test - self.tp
# False negatives = undetected reference samples
self.fn = self.n_ref - self.tp
# No tn attribute
self.specificity = float(self.tp) / self.n_ref
self.positive_predictivity = float(self.tp) / self.n_test
self.false_positive_rate = float(self.fp) / self.n_test | [
"def",
"_calc_stats",
"(",
"self",
")",
":",
"# Reference annotation indices that were detected",
"self",
".",
"matched_ref_inds",
"=",
"np",
".",
"where",
"(",
"self",
".",
"matching_sample_nums",
"!=",
"-",
"1",
")",
"[",
"0",
"]",
"# Reference annotation indices ... | Calculate performance statistics after the two sets of annotations
are compared.
Example:
-------------------
ref=500 test=480
{ 30 { 470 } 10 }
-------------------
tp = 470
fp = 10
fn = 30
specificity = 470 / 500
positive_predictivity = 470 / 480
false_positive_rate = 10 / 480 | [
"Calculate",
"performance",
"statistics",
"after",
"the",
"two",
"sets",
"of",
"annotations",
"are",
"compared",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/evaluate.py#L69-L116 |
235,248 | MIT-LCP/wfdb-python | wfdb/processing/evaluate.py | Comparitor.compare | def compare(self):
"""
Main comparison function
"""
"""
Note: Make sure to be able to handle these ref/test scenarios:
A:
o----o---o---o
x-------x----x
B:
o----o-----o---o
x--------x--x--x
C:
o------o-----o---o
x-x--------x--x--x
D:
o------o-----o---o
x-x--------x-----x
"""
test_samp_num = 0
ref_samp_num = 0
# Iterate through the reference sample numbers
while ref_samp_num < self.n_ref and test_samp_num < self.n_test:
# Get the closest testing sample number for this reference sample
closest_samp_num, smallest_samp_diff = (
self._get_closest_samp_num(ref_samp_num, test_samp_num))
# Get the closest testing sample number for the next reference
# sample. This doesn't need to be called for the last index.
if ref_samp_num < self.n_ref - 1:
closest_samp_num_next, smallest_samp_diff_next = (
self._get_closest_samp_num(ref_samp_num + 1, test_samp_num))
else:
# Set non-matching value if there is no next reference sample
# to compete for the test sample
closest_samp_num_next = -1
# Found a contested test sample number. Decide which
# reference sample it belongs to. If the sample is closer to
# the next reference sample, leave it to the next reference
# sample and label this reference sample as unmatched.
if (closest_samp_num == closest_samp_num_next
and smallest_samp_diff_next < smallest_samp_diff):
# Get the next closest sample for this reference sample,
# if not already assigned to a previous sample.
# It will be the previous testing sample number in any
# possible case (scenario D below), or nothing.
if closest_samp_num and (not ref_samp_num or closest_samp_num - 1 != self.matching_sample_nums[ref_samp_num - 1]):
# The previous test annotation is inspected
closest_samp_num = closest_samp_num - 1
smallest_samp_diff = abs(self.ref_sample[ref_samp_num]
- self.test_sample[closest_samp_num])
# Assign the reference-test pair if close enough
if smallest_samp_diff < self.window_width:
self.matching_sample_nums[ref_samp_num] = closest_samp_num
# Set the starting test sample number to inspect
# for the next reference sample.
test_samp_num = closest_samp_num + 1
# Otherwise there is no matching test annotation
# If there is no clash, or the contested test sample is
# closer to the current reference, keep the test sample
# for this reference sample.
else:
# Assign the reference-test pair if close enough
if smallest_samp_diff < self.window_width:
self.matching_sample_nums[ref_samp_num] = closest_samp_num
# Increment the starting test sample number to inspect
# for the next reference sample.
test_samp_num = closest_samp_num + 1
ref_samp_num += 1
self._calc_stats() | python | def compare(self):
"""
Note: Make sure to be able to handle these ref/test scenarios:
A:
o----o---o---o
x-------x----x
B:
o----o-----o---o
x--------x--x--x
C:
o------o-----o---o
x-x--------x--x--x
D:
o------o-----o---o
x-x--------x-----x
"""
test_samp_num = 0
ref_samp_num = 0
# Iterate through the reference sample numbers
while ref_samp_num < self.n_ref and test_samp_num < self.n_test:
# Get the closest testing sample number for this reference sample
closest_samp_num, smallest_samp_diff = (
self._get_closest_samp_num(ref_samp_num, test_samp_num))
# Get the closest testing sample number for the next reference
# sample. This doesn't need to be called for the last index.
if ref_samp_num < self.n_ref - 1:
closest_samp_num_next, smallest_samp_diff_next = (
self._get_closest_samp_num(ref_samp_num + 1, test_samp_num))
else:
# Set non-matching value if there is no next reference sample
# to compete for the test sample
closest_samp_num_next = -1
# Found a contested test sample number. Decide which
# reference sample it belongs to. If the sample is closer to
# the next reference sample, leave it to the next reference
# sample and label this reference sample as unmatched.
if (closest_samp_num == closest_samp_num_next
and smallest_samp_diff_next < smallest_samp_diff):
# Get the next closest sample for this reference sample,
# if not already assigned to a previous sample.
# It will be the previous testing sample number in any
# possible case (scenario D below), or nothing.
if closest_samp_num and (not ref_samp_num or closest_samp_num - 1 != self.matching_sample_nums[ref_samp_num - 1]):
# The previous test annotation is inspected
closest_samp_num = closest_samp_num - 1
smallest_samp_diff = abs(self.ref_sample[ref_samp_num]
- self.test_sample[closest_samp_num])
# Assign the reference-test pair if close enough
if smallest_samp_diff < self.window_width:
self.matching_sample_nums[ref_samp_num] = closest_samp_num
# Set the starting test sample number to inspect
# for the next reference sample.
test_samp_num = closest_samp_num + 1
# Otherwise there is no matching test annotation
# If there is no clash, or the contested test sample is
# closer to the current reference, keep the test sample
# for this reference sample.
else:
# Assign the reference-test pair if close enough
if smallest_samp_diff < self.window_width:
self.matching_sample_nums[ref_samp_num] = closest_samp_num
# Increment the starting test sample number to inspect
# for the next reference sample.
test_samp_num = closest_samp_num + 1
ref_samp_num += 1
self._calc_stats() | [
"def",
"compare",
"(",
"self",
")",
":",
"\"\"\"\n Note: Make sure to be able to handle these ref/test scenarios:\n\n A:\n o----o---o---o\n x-------x----x\n\n B:\n o----o-----o---o\n x--------x--x--x\n\n C:\n o------o-----o---o\n x-x-... | Main comparison function | [
"Main",
"comparison",
"function"
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/evaluate.py#L118-L197 |
235,249 | MIT-LCP/wfdb-python | wfdb/processing/evaluate.py | Comparitor._get_closest_samp_num | def _get_closest_samp_num(self, ref_samp_num, start_test_samp_num):
"""
Return the closest testing sample number for the given reference
sample number. Limit the search from start_test_samp_num.
"""
if start_test_samp_num >= self.n_test:
raise ValueError('Invalid starting test sample number.')
ref_samp = self.ref_sample[ref_samp_num]
test_samp = self.test_sample[start_test_samp_num]
samp_diff = ref_samp - test_samp
# Initialize running parameters
closest_samp_num = start_test_samp_num
smallest_samp_diff = abs(samp_diff)
# Iterate through the testing samples
for test_samp_num in range(start_test_samp_num, self.n_test):
test_samp = self.test_sample[test_samp_num]
samp_diff = ref_samp - test_samp
abs_samp_diff = abs(samp_diff)
# Found a better match
if abs_samp_diff < smallest_samp_diff:
closest_samp_num = test_samp_num
smallest_samp_diff = abs_samp_diff
# Stop iterating when the ref sample is first passed or reached
if samp_diff <= 0:
break
return closest_samp_num, smallest_samp_diff | python | def _get_closest_samp_num(self, ref_samp_num, start_test_samp_num):
if start_test_samp_num >= self.n_test:
raise ValueError('Invalid starting test sample number.')
ref_samp = self.ref_sample[ref_samp_num]
test_samp = self.test_sample[start_test_samp_num]
samp_diff = ref_samp - test_samp
# Initialize running parameters
closest_samp_num = start_test_samp_num
smallest_samp_diff = abs(samp_diff)
# Iterate through the testing samples
for test_samp_num in range(start_test_samp_num, self.n_test):
test_samp = self.test_sample[test_samp_num]
samp_diff = ref_samp - test_samp
abs_samp_diff = abs(samp_diff)
# Found a better match
if abs_samp_diff < smallest_samp_diff:
closest_samp_num = test_samp_num
smallest_samp_diff = abs_samp_diff
# Stop iterating when the ref sample is first passed or reached
if samp_diff <= 0:
break
return closest_samp_num, smallest_samp_diff | [
"def",
"_get_closest_samp_num",
"(",
"self",
",",
"ref_samp_num",
",",
"start_test_samp_num",
")",
":",
"if",
"start_test_samp_num",
">=",
"self",
".",
"n_test",
":",
"raise",
"ValueError",
"(",
"'Invalid starting test sample number.'",
")",
"ref_samp",
"=",
"self",
... | Return the closest testing sample number for the given reference
sample number. Limit the search from start_test_samp_num. | [
"Return",
"the",
"closest",
"testing",
"sample",
"number",
"for",
"the",
"given",
"reference",
"sample",
"number",
".",
"Limit",
"the",
"search",
"from",
"start_test_samp_num",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/evaluate.py#L200-L232 |
235,250 | MIT-LCP/wfdb-python | wfdb/processing/evaluate.py | Comparitor.print_summary | def print_summary(self):
"""
Print summary metrics of the annotation comparisons.
"""
# True positives = matched reference samples
self.tp = len(self.matched_ref_inds)
# False positives = extra test samples not matched
self.fp = self.n_test - self.tp
# False negatives = undetected reference samples
self.fn = self.n_ref - self.tp
# No tn attribute
self.specificity = self.tp / self.n_ref
self.positive_predictivity = self.tp / self.n_test
self.false_positive_rate = self.fp / self.n_test
print('%d reference annotations, %d test annotations\n'
% (self.n_ref, self.n_test))
print('True Positives (matched samples): %d' % self.tp)
print('False Positives (unmatched test samples: %d' % self.fp)
print('False Negatives (unmatched reference samples): %d\n' % self.fn)
print('Specificity: %.4f (%d/%d)'
% (self.specificity, self.tp, self.n_ref))
print('Positive Predictivity: %.4f (%d/%d)'
% (self.positive_predictivity, self.tp, self.n_test))
print('False Positive Rate: %.4f (%d/%d)'
% (self.false_positive_rate, self.fp, self.n_test)) | python | def print_summary(self):
# True positives = matched reference samples
self.tp = len(self.matched_ref_inds)
# False positives = extra test samples not matched
self.fp = self.n_test - self.tp
# False negatives = undetected reference samples
self.fn = self.n_ref - self.tp
# No tn attribute
self.specificity = self.tp / self.n_ref
self.positive_predictivity = self.tp / self.n_test
self.false_positive_rate = self.fp / self.n_test
print('%d reference annotations, %d test annotations\n'
% (self.n_ref, self.n_test))
print('True Positives (matched samples): %d' % self.tp)
print('False Positives (unmatched test samples: %d' % self.fp)
print('False Negatives (unmatched reference samples): %d\n' % self.fn)
print('Specificity: %.4f (%d/%d)'
% (self.specificity, self.tp, self.n_ref))
print('Positive Predictivity: %.4f (%d/%d)'
% (self.positive_predictivity, self.tp, self.n_test))
print('False Positive Rate: %.4f (%d/%d)'
% (self.false_positive_rate, self.fp, self.n_test)) | [
"def",
"print_summary",
"(",
"self",
")",
":",
"# True positives = matched reference samples",
"self",
".",
"tp",
"=",
"len",
"(",
"self",
".",
"matched_ref_inds",
")",
"# False positives = extra test samples not matched",
"self",
".",
"fp",
"=",
"self",
".",
"n_test"... | Print summary metrics of the annotation comparisons. | [
"Print",
"summary",
"metrics",
"of",
"the",
"annotation",
"comparisons",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/evaluate.py#L234-L261 |
235,251 | MIT-LCP/wfdb-python | wfdb/processing/evaluate.py | Comparitor.plot | def plot(self, sig_style='', title=None, figsize=None,
return_fig=False):
"""
Plot the comparison of two sets of annotations, possibly
overlaid on their original signal.
Parameters
----------
sig_style : str, optional
The matplotlib style of the signal
title : str, optional
The title of the plot
figsize: tuple, optional
Tuple pair specifying the width, and height of the figure.
It is the'figsize' argument passed into matplotlib.pyplot's
`figure` function.
return_fig : bool, optional
Whether the figure is to be returned as an output argument.
"""
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(1, 1, 1)
legend = ['Signal',
'Matched Reference Annotations (%d/%d)' % (self.tp, self.n_ref),
'Unmatched Reference Annotations (%d/%d)' % (self.fn, self.n_ref),
'Matched Test Annotations (%d/%d)' % (self.tp, self.n_test),
'Unmatched Test Annotations (%d/%d)' % (self.fp, self.n_test)
]
# Plot the signal if any
if self.signal is not None:
ax.plot(self.signal, sig_style)
# Plot reference annotations
ax.plot(self.matched_ref_sample,
self.signal[self.matched_ref_sample], 'ko')
ax.plot(self.unmatched_ref_sample,
self.signal[self.unmatched_ref_sample], 'ko',
fillstyle='none')
# Plot test annotations
ax.plot(self.matched_test_sample,
self.signal[self.matched_test_sample], 'g+')
ax.plot(self.unmatched_test_sample,
self.signal[self.unmatched_test_sample], 'rx')
ax.legend(legend)
# Just plot annotations
else:
# Plot reference annotations
ax.plot(self.matched_ref_sample, np.ones(self.tp), 'ko')
ax.plot(self.unmatched_ref_sample, np.ones(self.fn), 'ko',
fillstyle='none')
# Plot test annotations
ax.plot(self.matched_test_sample, 0.5 * np.ones(self.tp), 'g+')
ax.plot(self.unmatched_test_sample, 0.5 * np.ones(self.fp), 'rx')
ax.legend(legend[1:])
if title:
ax.set_title(title)
ax.set_xlabel('time/sample')
fig.show()
if return_fig:
return fig, ax | python | def plot(self, sig_style='', title=None, figsize=None,
return_fig=False):
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(1, 1, 1)
legend = ['Signal',
'Matched Reference Annotations (%d/%d)' % (self.tp, self.n_ref),
'Unmatched Reference Annotations (%d/%d)' % (self.fn, self.n_ref),
'Matched Test Annotations (%d/%d)' % (self.tp, self.n_test),
'Unmatched Test Annotations (%d/%d)' % (self.fp, self.n_test)
]
# Plot the signal if any
if self.signal is not None:
ax.plot(self.signal, sig_style)
# Plot reference annotations
ax.plot(self.matched_ref_sample,
self.signal[self.matched_ref_sample], 'ko')
ax.plot(self.unmatched_ref_sample,
self.signal[self.unmatched_ref_sample], 'ko',
fillstyle='none')
# Plot test annotations
ax.plot(self.matched_test_sample,
self.signal[self.matched_test_sample], 'g+')
ax.plot(self.unmatched_test_sample,
self.signal[self.unmatched_test_sample], 'rx')
ax.legend(legend)
# Just plot annotations
else:
# Plot reference annotations
ax.plot(self.matched_ref_sample, np.ones(self.tp), 'ko')
ax.plot(self.unmatched_ref_sample, np.ones(self.fn), 'ko',
fillstyle='none')
# Plot test annotations
ax.plot(self.matched_test_sample, 0.5 * np.ones(self.tp), 'g+')
ax.plot(self.unmatched_test_sample, 0.5 * np.ones(self.fp), 'rx')
ax.legend(legend[1:])
if title:
ax.set_title(title)
ax.set_xlabel('time/sample')
fig.show()
if return_fig:
return fig, ax | [
"def",
"plot",
"(",
"self",
",",
"sig_style",
"=",
"''",
",",
"title",
"=",
"None",
",",
"figsize",
"=",
"None",
",",
"return_fig",
"=",
"False",
")",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"figsize",
")",
"ax",
"=",
"fig",
"... | Plot the comparison of two sets of annotations, possibly
overlaid on their original signal.
Parameters
----------
sig_style : str, optional
The matplotlib style of the signal
title : str, optional
The title of the plot
figsize: tuple, optional
Tuple pair specifying the width, and height of the figure.
It is the'figsize' argument passed into matplotlib.pyplot's
`figure` function.
return_fig : bool, optional
Whether the figure is to be returned as an output argument. | [
"Plot",
"the",
"comparison",
"of",
"two",
"sets",
"of",
"annotations",
"possibly",
"overlaid",
"on",
"their",
"original",
"signal",
"."
] | cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/evaluate.py#L264-L331 |
235,252 | numba/llvmlite | llvmlite/binding/executionengine.py | ExecutionEngine.add_module | def add_module(self, module):
"""
Ownership of module is transferred to the execution engine
"""
if module in self._modules:
raise KeyError("module already added to this engine")
ffi.lib.LLVMPY_AddModule(self, module)
module._owned = True
self._modules.add(module) | python | def add_module(self, module):
if module in self._modules:
raise KeyError("module already added to this engine")
ffi.lib.LLVMPY_AddModule(self, module)
module._owned = True
self._modules.add(module) | [
"def",
"add_module",
"(",
"self",
",",
"module",
")",
":",
"if",
"module",
"in",
"self",
".",
"_modules",
":",
"raise",
"KeyError",
"(",
"\"module already added to this engine\"",
")",
"ffi",
".",
"lib",
".",
"LLVMPY_AddModule",
"(",
"self",
",",
"module",
"... | Ownership of module is transferred to the execution engine | [
"Ownership",
"of",
"module",
"is",
"transferred",
"to",
"the",
"execution",
"engine"
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/executionengine.py#L80-L88 |
235,253 | numba/llvmlite | llvmlite/binding/executionengine.py | ExecutionEngine.remove_module | def remove_module(self, module):
"""
Ownership of module is returned
"""
with ffi.OutputString() as outerr:
if ffi.lib.LLVMPY_RemoveModule(self, module, outerr):
raise RuntimeError(str(outerr))
self._modules.remove(module)
module._owned = False | python | def remove_module(self, module):
with ffi.OutputString() as outerr:
if ffi.lib.LLVMPY_RemoveModule(self, module, outerr):
raise RuntimeError(str(outerr))
self._modules.remove(module)
module._owned = False | [
"def",
"remove_module",
"(",
"self",
",",
"module",
")",
":",
"with",
"ffi",
".",
"OutputString",
"(",
")",
"as",
"outerr",
":",
"if",
"ffi",
".",
"lib",
".",
"LLVMPY_RemoveModule",
"(",
"self",
",",
"module",
",",
"outerr",
")",
":",
"raise",
"Runtime... | Ownership of module is returned | [
"Ownership",
"of",
"module",
"is",
"returned"
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/executionengine.py#L105-L113 |
235,254 | numba/llvmlite | llvmlite/binding/executionengine.py | ExecutionEngine.target_data | def target_data(self):
"""
The TargetData for this execution engine.
"""
if self._td is not None:
return self._td
ptr = ffi.lib.LLVMPY_GetExecutionEngineTargetData(self)
self._td = targets.TargetData(ptr)
self._td._owned = True
return self._td | python | def target_data(self):
if self._td is not None:
return self._td
ptr = ffi.lib.LLVMPY_GetExecutionEngineTargetData(self)
self._td = targets.TargetData(ptr)
self._td._owned = True
return self._td | [
"def",
"target_data",
"(",
"self",
")",
":",
"if",
"self",
".",
"_td",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_td",
"ptr",
"=",
"ffi",
".",
"lib",
".",
"LLVMPY_GetExecutionEngineTargetData",
"(",
"self",
")",
"self",
".",
"_td",
"=",
"target... | The TargetData for this execution engine. | [
"The",
"TargetData",
"for",
"this",
"execution",
"engine",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/executionengine.py#L116-L125 |
235,255 | numba/llvmlite | llvmlite/binding/executionengine.py | ExecutionEngine._find_module_ptr | def _find_module_ptr(self, module_ptr):
"""
Find the ModuleRef corresponding to the given pointer.
"""
ptr = cast(module_ptr, c_void_p).value
for module in self._modules:
if cast(module._ptr, c_void_p).value == ptr:
return module
return None | python | def _find_module_ptr(self, module_ptr):
ptr = cast(module_ptr, c_void_p).value
for module in self._modules:
if cast(module._ptr, c_void_p).value == ptr:
return module
return None | [
"def",
"_find_module_ptr",
"(",
"self",
",",
"module_ptr",
")",
":",
"ptr",
"=",
"cast",
"(",
"module_ptr",
",",
"c_void_p",
")",
".",
"value",
"for",
"module",
"in",
"self",
".",
"_modules",
":",
"if",
"cast",
"(",
"module",
".",
"_ptr",
",",
"c_void_... | Find the ModuleRef corresponding to the given pointer. | [
"Find",
"the",
"ModuleRef",
"corresponding",
"to",
"the",
"given",
"pointer",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/executionengine.py#L136-L144 |
235,256 | numba/llvmlite | llvmlite/binding/executionengine.py | ExecutionEngine.set_object_cache | def set_object_cache(self, notify_func=None, getbuffer_func=None):
"""
Set the object cache "notifyObjectCompiled" and "getBuffer"
callbacks to the given Python functions.
"""
self._object_cache_notify = notify_func
self._object_cache_getbuffer = getbuffer_func
# Lifetime of the object cache is managed by us.
self._object_cache = _ObjectCacheRef(self)
# Note this doesn't keep a reference to self, to avoid reference
# cycles.
ffi.lib.LLVMPY_SetObjectCache(self, self._object_cache) | python | def set_object_cache(self, notify_func=None, getbuffer_func=None):
self._object_cache_notify = notify_func
self._object_cache_getbuffer = getbuffer_func
# Lifetime of the object cache is managed by us.
self._object_cache = _ObjectCacheRef(self)
# Note this doesn't keep a reference to self, to avoid reference
# cycles.
ffi.lib.LLVMPY_SetObjectCache(self, self._object_cache) | [
"def",
"set_object_cache",
"(",
"self",
",",
"notify_func",
"=",
"None",
",",
"getbuffer_func",
"=",
"None",
")",
":",
"self",
".",
"_object_cache_notify",
"=",
"notify_func",
"self",
".",
"_object_cache_getbuffer",
"=",
"getbuffer_func",
"# Lifetime of the object cac... | Set the object cache "notifyObjectCompiled" and "getBuffer"
callbacks to the given Python functions. | [
"Set",
"the",
"object",
"cache",
"notifyObjectCompiled",
"and",
"getBuffer",
"callbacks",
"to",
"the",
"given",
"Python",
"functions",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/executionengine.py#L157-L168 |
235,257 | numba/llvmlite | llvmlite/binding/executionengine.py | ExecutionEngine._raw_object_cache_notify | def _raw_object_cache_notify(self, data):
"""
Low-level notify hook.
"""
if self._object_cache_notify is None:
return
module_ptr = data.contents.module_ptr
buf_ptr = data.contents.buf_ptr
buf_len = data.contents.buf_len
buf = string_at(buf_ptr, buf_len)
module = self._find_module_ptr(module_ptr)
if module is None:
# The LLVM EE should only give notifications for modules
# known by us.
raise RuntimeError("object compilation notification "
"for unknown module %s" % (module_ptr,))
self._object_cache_notify(module, buf) | python | def _raw_object_cache_notify(self, data):
if self._object_cache_notify is None:
return
module_ptr = data.contents.module_ptr
buf_ptr = data.contents.buf_ptr
buf_len = data.contents.buf_len
buf = string_at(buf_ptr, buf_len)
module = self._find_module_ptr(module_ptr)
if module is None:
# The LLVM EE should only give notifications for modules
# known by us.
raise RuntimeError("object compilation notification "
"for unknown module %s" % (module_ptr,))
self._object_cache_notify(module, buf) | [
"def",
"_raw_object_cache_notify",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"_object_cache_notify",
"is",
"None",
":",
"return",
"module_ptr",
"=",
"data",
".",
"contents",
".",
"module_ptr",
"buf_ptr",
"=",
"data",
".",
"contents",
".",
"buf_p... | Low-level notify hook. | [
"Low",
"-",
"level",
"notify",
"hook",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/executionengine.py#L170-L186 |
235,258 | numba/llvmlite | llvmlite/binding/executionengine.py | ExecutionEngine._raw_object_cache_getbuffer | def _raw_object_cache_getbuffer(self, data):
"""
Low-level getbuffer hook.
"""
if self._object_cache_getbuffer is None:
return
module_ptr = data.contents.module_ptr
module = self._find_module_ptr(module_ptr)
if module is None:
# The LLVM EE should only give notifications for modules
# known by us.
raise RuntimeError("object compilation notification "
"for unknown module %s" % (module_ptr,))
buf = self._object_cache_getbuffer(module)
if buf is not None:
# Create a copy, which will be freed by the caller
data[0].buf_ptr = ffi.lib.LLVMPY_CreateByteString(buf, len(buf))
data[0].buf_len = len(buf) | python | def _raw_object_cache_getbuffer(self, data):
if self._object_cache_getbuffer is None:
return
module_ptr = data.contents.module_ptr
module = self._find_module_ptr(module_ptr)
if module is None:
# The LLVM EE should only give notifications for modules
# known by us.
raise RuntimeError("object compilation notification "
"for unknown module %s" % (module_ptr,))
buf = self._object_cache_getbuffer(module)
if buf is not None:
# Create a copy, which will be freed by the caller
data[0].buf_ptr = ffi.lib.LLVMPY_CreateByteString(buf, len(buf))
data[0].buf_len = len(buf) | [
"def",
"_raw_object_cache_getbuffer",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"_object_cache_getbuffer",
"is",
"None",
":",
"return",
"module_ptr",
"=",
"data",
".",
"contents",
".",
"module_ptr",
"module",
"=",
"self",
".",
"_find_module_ptr",
... | Low-level getbuffer hook. | [
"Low",
"-",
"level",
"getbuffer",
"hook",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/executionengine.py#L188-L206 |
235,259 | numba/llvmlite | llvmlite/ir/builder.py | IRBuilder.position_before | def position_before(self, instr):
"""
Position immediately before the given instruction. The current block
is also changed to the instruction's basic block.
"""
self._block = instr.parent
self._anchor = self._block.instructions.index(instr) | python | def position_before(self, instr):
self._block = instr.parent
self._anchor = self._block.instructions.index(instr) | [
"def",
"position_before",
"(",
"self",
",",
"instr",
")",
":",
"self",
".",
"_block",
"=",
"instr",
".",
"parent",
"self",
".",
"_anchor",
"=",
"self",
".",
"_block",
".",
"instructions",
".",
"index",
"(",
"instr",
")"
] | Position immediately before the given instruction. The current block
is also changed to the instruction's basic block. | [
"Position",
"immediately",
"before",
"the",
"given",
"instruction",
".",
"The",
"current",
"block",
"is",
"also",
"changed",
"to",
"the",
"instruction",
"s",
"basic",
"block",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/builder.py#L182-L188 |
235,260 | numba/llvmlite | llvmlite/ir/builder.py | IRBuilder.position_after | def position_after(self, instr):
"""
Position immediately after the given instruction. The current block
is also changed to the instruction's basic block.
"""
self._block = instr.parent
self._anchor = self._block.instructions.index(instr) + 1 | python | def position_after(self, instr):
self._block = instr.parent
self._anchor = self._block.instructions.index(instr) + 1 | [
"def",
"position_after",
"(",
"self",
",",
"instr",
")",
":",
"self",
".",
"_block",
"=",
"instr",
".",
"parent",
"self",
".",
"_anchor",
"=",
"self",
".",
"_block",
".",
"instructions",
".",
"index",
"(",
"instr",
")",
"+",
"1"
] | Position immediately after the given instruction. The current block
is also changed to the instruction's basic block. | [
"Position",
"immediately",
"after",
"the",
"given",
"instruction",
".",
"The",
"current",
"block",
"is",
"also",
"changed",
"to",
"the",
"instruction",
"s",
"basic",
"block",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/builder.py#L190-L196 |
235,261 | numba/llvmlite | llvmlite/ir/builder.py | IRBuilder.resume | def resume(self, landingpad):
"""
Resume an in-flight exception.
"""
br = instructions.Branch(self.block, "resume", [landingpad])
self._set_terminator(br)
return br | python | def resume(self, landingpad):
br = instructions.Branch(self.block, "resume", [landingpad])
self._set_terminator(br)
return br | [
"def",
"resume",
"(",
"self",
",",
"landingpad",
")",
":",
"br",
"=",
"instructions",
".",
"Branch",
"(",
"self",
".",
"block",
",",
"\"resume\"",
",",
"[",
"landingpad",
"]",
")",
"self",
".",
"_set_terminator",
"(",
"br",
")",
"return",
"br"
] | Resume an in-flight exception. | [
"Resume",
"an",
"in",
"-",
"flight",
"exception",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/builder.py#L809-L815 |
235,262 | numba/llvmlite | llvmlite/ir/builder.py | IRBuilder.asm | def asm(self, ftype, asm, constraint, args, side_effect, name=''):
"""
Inline assembler.
"""
asm = instructions.InlineAsm(ftype, asm, constraint, side_effect)
return self.call(asm, args, name) | python | def asm(self, ftype, asm, constraint, args, side_effect, name=''):
asm = instructions.InlineAsm(ftype, asm, constraint, side_effect)
return self.call(asm, args, name) | [
"def",
"asm",
"(",
"self",
",",
"ftype",
",",
"asm",
",",
"constraint",
",",
"args",
",",
"side_effect",
",",
"name",
"=",
"''",
")",
":",
"asm",
"=",
"instructions",
".",
"InlineAsm",
"(",
"ftype",
",",
"asm",
",",
"constraint",
",",
"side_effect",
... | Inline assembler. | [
"Inline",
"assembler",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/builder.py#L829-L834 |
235,263 | numba/llvmlite | llvmlite/ir/builder.py | IRBuilder.extract_element | def extract_element(self, vector, idx, name=''):
"""
Returns the value at position idx.
"""
instr = instructions.ExtractElement(self.block, vector, idx, name=name)
self._insert(instr)
return instr | python | def extract_element(self, vector, idx, name=''):
instr = instructions.ExtractElement(self.block, vector, idx, name=name)
self._insert(instr)
return instr | [
"def",
"extract_element",
"(",
"self",
",",
"vector",
",",
"idx",
",",
"name",
"=",
"''",
")",
":",
"instr",
"=",
"instructions",
".",
"ExtractElement",
"(",
"self",
".",
"block",
",",
"vector",
",",
"idx",
",",
"name",
"=",
"name",
")",
"self",
".",... | Returns the value at position idx. | [
"Returns",
"the",
"value",
"at",
"position",
"idx",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/builder.py#L872-L878 |
235,264 | numba/llvmlite | llvmlite/ir/module.py | Module.functions | def functions(self):
"""
A list of functions declared or defined in this module.
"""
return [v for v in self.globals.values()
if isinstance(v, values.Function)] | python | def functions(self):
return [v for v in self.globals.values()
if isinstance(v, values.Function)] | [
"def",
"functions",
"(",
"self",
")",
":",
"return",
"[",
"v",
"for",
"v",
"in",
"self",
".",
"globals",
".",
"values",
"(",
")",
"if",
"isinstance",
"(",
"v",
",",
"values",
".",
"Function",
")",
"]"
] | A list of functions declared or defined in this module. | [
"A",
"list",
"of",
"functions",
"declared",
"or",
"defined",
"in",
"this",
"module",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/module.py#L120-L125 |
235,265 | numba/llvmlite | llvmlite/ir/module.py | Module.add_global | def add_global(self, globalvalue):
"""
Add a new global value.
"""
assert globalvalue.name not in self.globals
self.globals[globalvalue.name] = globalvalue | python | def add_global(self, globalvalue):
assert globalvalue.name not in self.globals
self.globals[globalvalue.name] = globalvalue | [
"def",
"add_global",
"(",
"self",
",",
"globalvalue",
")",
":",
"assert",
"globalvalue",
".",
"name",
"not",
"in",
"self",
".",
"globals",
"self",
".",
"globals",
"[",
"globalvalue",
".",
"name",
"]",
"=",
"globalvalue"
] | Add a new global value. | [
"Add",
"a",
"new",
"global",
"value",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/module.py#L140-L145 |
235,266 | numba/llvmlite | docs/gh-pages.py | sh2 | def sh2(cmd):
"""Execute command in a subshell, return stdout.
Stderr is unbuffered from the subshell.x"""
p = Popen(cmd, stdout=PIPE, shell=True, env=sub_environment())
out = p.communicate()[0]
retcode = p.returncode
if retcode:
raise CalledProcessError(retcode, cmd)
else:
return out.rstrip() | python | def sh2(cmd):
p = Popen(cmd, stdout=PIPE, shell=True, env=sub_environment())
out = p.communicate()[0]
retcode = p.returncode
if retcode:
raise CalledProcessError(retcode, cmd)
else:
return out.rstrip() | [
"def",
"sh2",
"(",
"cmd",
")",
":",
"p",
"=",
"Popen",
"(",
"cmd",
",",
"stdout",
"=",
"PIPE",
",",
"shell",
"=",
"True",
",",
"env",
"=",
"sub_environment",
"(",
")",
")",
"out",
"=",
"p",
".",
"communicate",
"(",
")",
"[",
"0",
"]",
"retcode"... | Execute command in a subshell, return stdout.
Stderr is unbuffered from the subshell.x | [
"Execute",
"command",
"in",
"a",
"subshell",
"return",
"stdout",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/docs/gh-pages.py#L53-L63 |
235,267 | numba/llvmlite | docs/gh-pages.py | sh3 | def sh3(cmd):
"""Execute command in a subshell, return stdout, stderr
If anything appears in stderr, print it out to sys.stderr"""
p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True,
env=sub_environment())
out, err = p.communicate()
retcode = p.returncode
if retcode:
raise CalledProcessError(retcode, cmd)
else:
return out.rstrip(), err.rstrip() | python | def sh3(cmd):
p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True,
env=sub_environment())
out, err = p.communicate()
retcode = p.returncode
if retcode:
raise CalledProcessError(retcode, cmd)
else:
return out.rstrip(), err.rstrip() | [
"def",
"sh3",
"(",
"cmd",
")",
":",
"p",
"=",
"Popen",
"(",
"cmd",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"PIPE",
",",
"shell",
"=",
"True",
",",
"env",
"=",
"sub_environment",
"(",
")",
")",
"out",
",",
"err",
"=",
"p",
".",
"communic... | Execute command in a subshell, return stdout, stderr
If anything appears in stderr, print it out to sys.stderr | [
"Execute",
"command",
"in",
"a",
"subshell",
"return",
"stdout",
"stderr"
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/docs/gh-pages.py#L66-L77 |
235,268 | numba/llvmlite | docs/gh-pages.py | init_repo | def init_repo(path):
"""clone the gh-pages repo if we haven't already."""
sh("git clone %s %s"%(pages_repo, path))
here = os.getcwd()
cd(path)
sh('git checkout gh-pages')
cd(here) | python | def init_repo(path):
sh("git clone %s %s"%(pages_repo, path))
here = os.getcwd()
cd(path)
sh('git checkout gh-pages')
cd(here) | [
"def",
"init_repo",
"(",
"path",
")",
":",
"sh",
"(",
"\"git clone %s %s\"",
"%",
"(",
"pages_repo",
",",
"path",
")",
")",
"here",
"=",
"os",
".",
"getcwd",
"(",
")",
"cd",
"(",
"path",
")",
"sh",
"(",
"'git checkout gh-pages'",
")",
"cd",
"(",
"her... | clone the gh-pages repo if we haven't already. | [
"clone",
"the",
"gh",
"-",
"pages",
"repo",
"if",
"we",
"haven",
"t",
"already",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/docs/gh-pages.py#L80-L86 |
235,269 | numba/llvmlite | docs/source/user-guide/examples/ll_fpadd.py | create_execution_engine | def create_execution_engine():
"""
Create an ExecutionEngine suitable for JIT code generation on
the host CPU. The engine is reusable for an arbitrary number of
modules.
"""
# Create a target machine representing the host
target = llvm.Target.from_default_triple()
target_machine = target.create_target_machine()
# And an execution engine with an empty backing module
backing_mod = llvm.parse_assembly("")
engine = llvm.create_mcjit_compiler(backing_mod, target_machine)
return engine | python | def create_execution_engine():
# Create a target machine representing the host
target = llvm.Target.from_default_triple()
target_machine = target.create_target_machine()
# And an execution engine with an empty backing module
backing_mod = llvm.parse_assembly("")
engine = llvm.create_mcjit_compiler(backing_mod, target_machine)
return engine | [
"def",
"create_execution_engine",
"(",
")",
":",
"# Create a target machine representing the host",
"target",
"=",
"llvm",
".",
"Target",
".",
"from_default_triple",
"(",
")",
"target_machine",
"=",
"target",
".",
"create_target_machine",
"(",
")",
"# And an execution eng... | Create an ExecutionEngine suitable for JIT code generation on
the host CPU. The engine is reusable for an arbitrary number of
modules. | [
"Create",
"an",
"ExecutionEngine",
"suitable",
"for",
"JIT",
"code",
"generation",
"on",
"the",
"host",
"CPU",
".",
"The",
"engine",
"is",
"reusable",
"for",
"an",
"arbitrary",
"number",
"of",
"modules",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/docs/source/user-guide/examples/ll_fpadd.py#L26-L38 |
235,270 | numba/llvmlite | docs/source/user-guide/examples/ll_fpadd.py | compile_ir | def compile_ir(engine, llvm_ir):
"""
Compile the LLVM IR string with the given engine.
The compiled module object is returned.
"""
# Create a LLVM module object from the IR
mod = llvm.parse_assembly(llvm_ir)
mod.verify()
# Now add the module and make sure it is ready for execution
engine.add_module(mod)
engine.finalize_object()
engine.run_static_constructors()
return mod | python | def compile_ir(engine, llvm_ir):
# Create a LLVM module object from the IR
mod = llvm.parse_assembly(llvm_ir)
mod.verify()
# Now add the module and make sure it is ready for execution
engine.add_module(mod)
engine.finalize_object()
engine.run_static_constructors()
return mod | [
"def",
"compile_ir",
"(",
"engine",
",",
"llvm_ir",
")",
":",
"# Create a LLVM module object from the IR",
"mod",
"=",
"llvm",
".",
"parse_assembly",
"(",
"llvm_ir",
")",
"mod",
".",
"verify",
"(",
")",
"# Now add the module and make sure it is ready for execution",
"en... | Compile the LLVM IR string with the given engine.
The compiled module object is returned. | [
"Compile",
"the",
"LLVM",
"IR",
"string",
"with",
"the",
"given",
"engine",
".",
"The",
"compiled",
"module",
"object",
"is",
"returned",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/docs/source/user-guide/examples/ll_fpadd.py#L41-L53 |
235,271 | numba/llvmlite | llvmlite/binding/targets.py | get_default_triple | def get_default_triple():
"""
Return the default target triple LLVM is configured to produce code for.
"""
with ffi.OutputString() as out:
ffi.lib.LLVMPY_GetDefaultTargetTriple(out)
return str(out) | python | def get_default_triple():
with ffi.OutputString() as out:
ffi.lib.LLVMPY_GetDefaultTargetTriple(out)
return str(out) | [
"def",
"get_default_triple",
"(",
")",
":",
"with",
"ffi",
".",
"OutputString",
"(",
")",
"as",
"out",
":",
"ffi",
".",
"lib",
".",
"LLVMPY_GetDefaultTargetTriple",
"(",
"out",
")",
"return",
"str",
"(",
"out",
")"
] | Return the default target triple LLVM is configured to produce code for. | [
"Return",
"the",
"default",
"target",
"triple",
"LLVM",
"is",
"configured",
"to",
"produce",
"code",
"for",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/targets.py#L72-L78 |
235,272 | numba/llvmlite | llvmlite/binding/targets.py | TargetData.get_element_offset | def get_element_offset(self, ty, position):
"""
Get byte offset of type's ty element at the given position
"""
offset = ffi.lib.LLVMPY_OffsetOfElement(self, ty, position)
if offset == -1:
raise ValueError("Could not determined offset of {}th "
"element of the type '{}'. Is it a struct type?".format(
position, str(ty)))
return offset | python | def get_element_offset(self, ty, position):
offset = ffi.lib.LLVMPY_OffsetOfElement(self, ty, position)
if offset == -1:
raise ValueError("Could not determined offset of {}th "
"element of the type '{}'. Is it a struct type?".format(
position, str(ty)))
return offset | [
"def",
"get_element_offset",
"(",
"self",
",",
"ty",
",",
"position",
")",
":",
"offset",
"=",
"ffi",
".",
"lib",
".",
"LLVMPY_OffsetOfElement",
"(",
"self",
",",
"ty",
",",
"position",
")",
"if",
"offset",
"==",
"-",
"1",
":",
"raise",
"ValueError",
"... | Get byte offset of type's ty element at the given position | [
"Get",
"byte",
"offset",
"of",
"type",
"s",
"ty",
"element",
"at",
"the",
"given",
"position"
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/targets.py#L136-L146 |
235,273 | numba/llvmlite | llvmlite/binding/targets.py | Target.create_target_machine | def create_target_machine(self, cpu='', features='',
opt=2, reloc='default', codemodel='jitdefault',
jitdebug=False, printmc=False):
"""
Create a new TargetMachine for this target and the given options.
Specifying codemodel='default' will result in the use of the "small"
code model. Specifying codemodel='jitdefault' will result in the code
model being picked based on platform bitness (32="small", 64="large").
"""
assert 0 <= opt <= 3
assert reloc in RELOC
assert codemodel in CODEMODEL
triple = self._triple
# MCJIT under Windows only supports ELF objects, see
# http://lists.llvm.org/pipermail/llvm-dev/2013-December/068341.html
# Note we still want to produce regular COFF files in AOT mode.
if os.name == 'nt' and codemodel == 'jitdefault':
triple += '-elf'
tm = ffi.lib.LLVMPY_CreateTargetMachine(self,
_encode_string(triple),
_encode_string(cpu),
_encode_string(features),
opt,
_encode_string(reloc),
_encode_string(codemodel),
int(jitdebug),
int(printmc),
)
if tm:
return TargetMachine(tm)
else:
raise RuntimeError("Cannot create target machine") | python | def create_target_machine(self, cpu='', features='',
opt=2, reloc='default', codemodel='jitdefault',
jitdebug=False, printmc=False):
assert 0 <= opt <= 3
assert reloc in RELOC
assert codemodel in CODEMODEL
triple = self._triple
# MCJIT under Windows only supports ELF objects, see
# http://lists.llvm.org/pipermail/llvm-dev/2013-December/068341.html
# Note we still want to produce regular COFF files in AOT mode.
if os.name == 'nt' and codemodel == 'jitdefault':
triple += '-elf'
tm = ffi.lib.LLVMPY_CreateTargetMachine(self,
_encode_string(triple),
_encode_string(cpu),
_encode_string(features),
opt,
_encode_string(reloc),
_encode_string(codemodel),
int(jitdebug),
int(printmc),
)
if tm:
return TargetMachine(tm)
else:
raise RuntimeError("Cannot create target machine") | [
"def",
"create_target_machine",
"(",
"self",
",",
"cpu",
"=",
"''",
",",
"features",
"=",
"''",
",",
"opt",
"=",
"2",
",",
"reloc",
"=",
"'default'",
",",
"codemodel",
"=",
"'jitdefault'",
",",
"jitdebug",
"=",
"False",
",",
"printmc",
"=",
"False",
")... | Create a new TargetMachine for this target and the given options.
Specifying codemodel='default' will result in the use of the "small"
code model. Specifying codemodel='jitdefault' will result in the code
model being picked based on platform bitness (32="small", 64="large"). | [
"Create",
"a",
"new",
"TargetMachine",
"for",
"this",
"target",
"and",
"the",
"given",
"options",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/targets.py#L217-L249 |
235,274 | numba/llvmlite | llvmlite/binding/targets.py | TargetMachine._emit_to_memory | def _emit_to_memory(self, module, use_object=False):
"""Returns bytes of object code of the module.
Args
----
use_object : bool
Emit object code or (if False) emit assembly code.
"""
with ffi.OutputString() as outerr:
mb = ffi.lib.LLVMPY_TargetMachineEmitToMemory(self, module,
int(use_object),
outerr)
if not mb:
raise RuntimeError(str(outerr))
bufptr = ffi.lib.LLVMPY_GetBufferStart(mb)
bufsz = ffi.lib.LLVMPY_GetBufferSize(mb)
try:
return string_at(bufptr, bufsz)
finally:
ffi.lib.LLVMPY_DisposeMemoryBuffer(mb) | python | def _emit_to_memory(self, module, use_object=False):
with ffi.OutputString() as outerr:
mb = ffi.lib.LLVMPY_TargetMachineEmitToMemory(self, module,
int(use_object),
outerr)
if not mb:
raise RuntimeError(str(outerr))
bufptr = ffi.lib.LLVMPY_GetBufferStart(mb)
bufsz = ffi.lib.LLVMPY_GetBufferSize(mb)
try:
return string_at(bufptr, bufsz)
finally:
ffi.lib.LLVMPY_DisposeMemoryBuffer(mb) | [
"def",
"_emit_to_memory",
"(",
"self",
",",
"module",
",",
"use_object",
"=",
"False",
")",
":",
"with",
"ffi",
".",
"OutputString",
"(",
")",
"as",
"outerr",
":",
"mb",
"=",
"ffi",
".",
"lib",
".",
"LLVMPY_TargetMachineEmitToMemory",
"(",
"self",
",",
"... | Returns bytes of object code of the module.
Args
----
use_object : bool
Emit object code or (if False) emit assembly code. | [
"Returns",
"bytes",
"of",
"object",
"code",
"of",
"the",
"module",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/targets.py#L285-L305 |
235,275 | numba/llvmlite | llvmlite/binding/module.py | parse_assembly | def parse_assembly(llvmir, context=None):
"""
Create Module from a LLVM IR string
"""
if context is None:
context = get_global_context()
llvmir = _encode_string(llvmir)
strbuf = c_char_p(llvmir)
with ffi.OutputString() as errmsg:
mod = ModuleRef(
ffi.lib.LLVMPY_ParseAssembly(context, strbuf, errmsg),
context)
if errmsg:
mod.close()
raise RuntimeError("LLVM IR parsing error\n{0}".format(errmsg))
return mod | python | def parse_assembly(llvmir, context=None):
if context is None:
context = get_global_context()
llvmir = _encode_string(llvmir)
strbuf = c_char_p(llvmir)
with ffi.OutputString() as errmsg:
mod = ModuleRef(
ffi.lib.LLVMPY_ParseAssembly(context, strbuf, errmsg),
context)
if errmsg:
mod.close()
raise RuntimeError("LLVM IR parsing error\n{0}".format(errmsg))
return mod | [
"def",
"parse_assembly",
"(",
"llvmir",
",",
"context",
"=",
"None",
")",
":",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"get_global_context",
"(",
")",
"llvmir",
"=",
"_encode_string",
"(",
"llvmir",
")",
"strbuf",
"=",
"c_char_p",
"(",
"llvmir"... | Create Module from a LLVM IR string | [
"Create",
"Module",
"from",
"a",
"LLVM",
"IR",
"string"
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/module.py#L12-L27 |
235,276 | numba/llvmlite | llvmlite/binding/module.py | ModuleRef.as_bitcode | def as_bitcode(self):
"""
Return the module's LLVM bitcode, as a bytes object.
"""
ptr = c_char_p(None)
size = c_size_t(-1)
ffi.lib.LLVMPY_WriteBitcodeToString(self, byref(ptr), byref(size))
if not ptr:
raise MemoryError
try:
assert size.value >= 0
return string_at(ptr, size.value)
finally:
ffi.lib.LLVMPY_DisposeString(ptr) | python | def as_bitcode(self):
ptr = c_char_p(None)
size = c_size_t(-1)
ffi.lib.LLVMPY_WriteBitcodeToString(self, byref(ptr), byref(size))
if not ptr:
raise MemoryError
try:
assert size.value >= 0
return string_at(ptr, size.value)
finally:
ffi.lib.LLVMPY_DisposeString(ptr) | [
"def",
"as_bitcode",
"(",
"self",
")",
":",
"ptr",
"=",
"c_char_p",
"(",
"None",
")",
"size",
"=",
"c_size_t",
"(",
"-",
"1",
")",
"ffi",
".",
"lib",
".",
"LLVMPY_WriteBitcodeToString",
"(",
"self",
",",
"byref",
"(",
"ptr",
")",
",",
"byref",
"(",
... | Return the module's LLVM bitcode, as a bytes object. | [
"Return",
"the",
"module",
"s",
"LLVM",
"bitcode",
"as",
"a",
"bytes",
"object",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/module.py#L62-L75 |
235,277 | numba/llvmlite | llvmlite/binding/module.py | ModuleRef.verify | def verify(self):
"""
Verify the module IR's correctness. RuntimeError is raised on error.
"""
with ffi.OutputString() as outmsg:
if ffi.lib.LLVMPY_VerifyModule(self, outmsg):
raise RuntimeError(str(outmsg)) | python | def verify(self):
with ffi.OutputString() as outmsg:
if ffi.lib.LLVMPY_VerifyModule(self, outmsg):
raise RuntimeError(str(outmsg)) | [
"def",
"verify",
"(",
"self",
")",
":",
"with",
"ffi",
".",
"OutputString",
"(",
")",
"as",
"outmsg",
":",
"if",
"ffi",
".",
"lib",
".",
"LLVMPY_VerifyModule",
"(",
"self",
",",
"outmsg",
")",
":",
"raise",
"RuntimeError",
"(",
"str",
"(",
"outmsg",
... | Verify the module IR's correctness. RuntimeError is raised on error. | [
"Verify",
"the",
"module",
"IR",
"s",
"correctness",
".",
"RuntimeError",
"is",
"raised",
"on",
"error",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/module.py#L110-L116 |
235,278 | numba/llvmlite | llvmlite/binding/module.py | ModuleRef.data_layout | def data_layout(self):
"""
This module's data layout specification, as a string.
"""
# LLVMGetDataLayout() points inside a std::string managed by LLVM.
with ffi.OutputString(owned=False) as outmsg:
ffi.lib.LLVMPY_GetDataLayout(self, outmsg)
return str(outmsg) | python | def data_layout(self):
# LLVMGetDataLayout() points inside a std::string managed by LLVM.
with ffi.OutputString(owned=False) as outmsg:
ffi.lib.LLVMPY_GetDataLayout(self, outmsg)
return str(outmsg) | [
"def",
"data_layout",
"(",
"self",
")",
":",
"# LLVMGetDataLayout() points inside a std::string managed by LLVM.",
"with",
"ffi",
".",
"OutputString",
"(",
"owned",
"=",
"False",
")",
"as",
"outmsg",
":",
"ffi",
".",
"lib",
".",
"LLVMPY_GetDataLayout",
"(",
"self",
... | This module's data layout specification, as a string. | [
"This",
"module",
"s",
"data",
"layout",
"specification",
"as",
"a",
"string",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/module.py#L130-L137 |
235,279 | numba/llvmlite | llvmlite/binding/module.py | ModuleRef.triple | def triple(self):
"""
This module's target "triple" specification, as a string.
"""
# LLVMGetTarget() points inside a std::string managed by LLVM.
with ffi.OutputString(owned=False) as outmsg:
ffi.lib.LLVMPY_GetTarget(self, outmsg)
return str(outmsg) | python | def triple(self):
# LLVMGetTarget() points inside a std::string managed by LLVM.
with ffi.OutputString(owned=False) as outmsg:
ffi.lib.LLVMPY_GetTarget(self, outmsg)
return str(outmsg) | [
"def",
"triple",
"(",
"self",
")",
":",
"# LLVMGetTarget() points inside a std::string managed by LLVM.",
"with",
"ffi",
".",
"OutputString",
"(",
"owned",
"=",
"False",
")",
"as",
"outmsg",
":",
"ffi",
".",
"lib",
".",
"LLVMPY_GetTarget",
"(",
"self",
",",
"out... | This module's target "triple" specification, as a string. | [
"This",
"module",
"s",
"target",
"triple",
"specification",
"as",
"a",
"string",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/module.py#L146-L153 |
235,280 | numba/llvmlite | llvmlite/binding/module.py | ModuleRef.global_variables | def global_variables(self):
"""
Return an iterator over this module's global variables.
The iterator will yield a ValueRef for each global variable.
Note that global variables don't include functions
(a function is a "global value" but not a "global variable" in
LLVM parlance)
"""
it = ffi.lib.LLVMPY_ModuleGlobalsIter(self)
return _GlobalsIterator(it, dict(module=self)) | python | def global_variables(self):
it = ffi.lib.LLVMPY_ModuleGlobalsIter(self)
return _GlobalsIterator(it, dict(module=self)) | [
"def",
"global_variables",
"(",
"self",
")",
":",
"it",
"=",
"ffi",
".",
"lib",
".",
"LLVMPY_ModuleGlobalsIter",
"(",
"self",
")",
"return",
"_GlobalsIterator",
"(",
"it",
",",
"dict",
"(",
"module",
"=",
"self",
")",
")"
] | Return an iterator over this module's global variables.
The iterator will yield a ValueRef for each global variable.
Note that global variables don't include functions
(a function is a "global value" but not a "global variable" in
LLVM parlance) | [
"Return",
"an",
"iterator",
"over",
"this",
"module",
"s",
"global",
"variables",
".",
"The",
"iterator",
"will",
"yield",
"a",
"ValueRef",
"for",
"each",
"global",
"variable",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/module.py#L171-L181 |
235,281 | numba/llvmlite | llvmlite/binding/module.py | ModuleRef.functions | def functions(self):
"""
Return an iterator over this module's functions.
The iterator will yield a ValueRef for each function.
"""
it = ffi.lib.LLVMPY_ModuleFunctionsIter(self)
return _FunctionsIterator(it, dict(module=self)) | python | def functions(self):
it = ffi.lib.LLVMPY_ModuleFunctionsIter(self)
return _FunctionsIterator(it, dict(module=self)) | [
"def",
"functions",
"(",
"self",
")",
":",
"it",
"=",
"ffi",
".",
"lib",
".",
"LLVMPY_ModuleFunctionsIter",
"(",
"self",
")",
"return",
"_FunctionsIterator",
"(",
"it",
",",
"dict",
"(",
"module",
"=",
"self",
")",
")"
] | Return an iterator over this module's functions.
The iterator will yield a ValueRef for each function. | [
"Return",
"an",
"iterator",
"over",
"this",
"module",
"s",
"functions",
".",
"The",
"iterator",
"will",
"yield",
"a",
"ValueRef",
"for",
"each",
"function",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/module.py#L184-L190 |
235,282 | numba/llvmlite | llvmlite/binding/module.py | ModuleRef.struct_types | def struct_types(self):
"""
Return an iterator over the struct types defined in
the module. The iterator will yield a TypeRef.
"""
it = ffi.lib.LLVMPY_ModuleTypesIter(self)
return _TypesIterator(it, dict(module=self)) | python | def struct_types(self):
it = ffi.lib.LLVMPY_ModuleTypesIter(self)
return _TypesIterator(it, dict(module=self)) | [
"def",
"struct_types",
"(",
"self",
")",
":",
"it",
"=",
"ffi",
".",
"lib",
".",
"LLVMPY_ModuleTypesIter",
"(",
"self",
")",
"return",
"_TypesIterator",
"(",
"it",
",",
"dict",
"(",
"module",
"=",
"self",
")",
")"
] | Return an iterator over the struct types defined in
the module. The iterator will yield a TypeRef. | [
"Return",
"an",
"iterator",
"over",
"the",
"struct",
"types",
"defined",
"in",
"the",
"module",
".",
"The",
"iterator",
"will",
"yield",
"a",
"TypeRef",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/module.py#L193-L199 |
235,283 | numba/llvmlite | llvmlite/binding/options.py | set_option | def set_option(name, option):
"""
Set the given LLVM "command-line" option.
For example set_option("test", "-debug-pass=Structure") would display
all optimization passes when generating code.
"""
ffi.lib.LLVMPY_SetCommandLine(_encode_string(name),
_encode_string(option)) | python | def set_option(name, option):
ffi.lib.LLVMPY_SetCommandLine(_encode_string(name),
_encode_string(option)) | [
"def",
"set_option",
"(",
"name",
",",
"option",
")",
":",
"ffi",
".",
"lib",
".",
"LLVMPY_SetCommandLine",
"(",
"_encode_string",
"(",
"name",
")",
",",
"_encode_string",
"(",
"option",
")",
")"
] | Set the given LLVM "command-line" option.
For example set_option("test", "-debug-pass=Structure") would display
all optimization passes when generating code. | [
"Set",
"the",
"given",
"LLVM",
"command",
"-",
"line",
"option",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/options.py#L6-L14 |
235,284 | numba/llvmlite | llvmlite/ir/types.py | Type._get_ll_pointer_type | def _get_ll_pointer_type(self, target_data, context=None):
"""
Convert this type object to an LLVM type.
"""
from . import Module, GlobalVariable
from ..binding import parse_assembly
if context is None:
m = Module()
else:
m = Module(context=context)
foo = GlobalVariable(m, self, name="foo")
with parse_assembly(str(m)) as llmod:
return llmod.get_global_variable(foo.name).type | python | def _get_ll_pointer_type(self, target_data, context=None):
from . import Module, GlobalVariable
from ..binding import parse_assembly
if context is None:
m = Module()
else:
m = Module(context=context)
foo = GlobalVariable(m, self, name="foo")
with parse_assembly(str(m)) as llmod:
return llmod.get_global_variable(foo.name).type | [
"def",
"_get_ll_pointer_type",
"(",
"self",
",",
"target_data",
",",
"context",
"=",
"None",
")",
":",
"from",
".",
"import",
"Module",
",",
"GlobalVariable",
"from",
".",
".",
"binding",
"import",
"parse_assembly",
"if",
"context",
"is",
"None",
":",
"m",
... | Convert this type object to an LLVM type. | [
"Convert",
"this",
"type",
"object",
"to",
"an",
"LLVM",
"type",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/types.py#L35-L48 |
235,285 | numba/llvmlite | llvmlite/ir/types.py | BaseStructType.structure_repr | def structure_repr(self):
"""
Return the LLVM IR for the structure representation
"""
ret = '{%s}' % ', '.join([str(x) for x in self.elements])
return self._wrap_packed(ret) | python | def structure_repr(self):
ret = '{%s}' % ', '.join([str(x) for x in self.elements])
return self._wrap_packed(ret) | [
"def",
"structure_repr",
"(",
"self",
")",
":",
"ret",
"=",
"'{%s}'",
"%",
"', '",
".",
"join",
"(",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"elements",
"]",
")",
"return",
"self",
".",
"_wrap_packed",
"(",
"ret",
")"
] | Return the LLVM IR for the structure representation | [
"Return",
"the",
"LLVM",
"IR",
"for",
"the",
"structure",
"representation"
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/types.py#L477-L482 |
235,286 | numba/llvmlite | llvmlite/ir/types.py | IdentifiedStructType.get_declaration | def get_declaration(self):
"""
Returns the string for the declaration of the type
"""
if self.is_opaque:
out = "{strrep} = type opaque".format(strrep=str(self))
else:
out = "{strrep} = type {struct}".format(
strrep=str(self), struct=self.structure_repr())
return out | python | def get_declaration(self):
if self.is_opaque:
out = "{strrep} = type opaque".format(strrep=str(self))
else:
out = "{strrep} = type {struct}".format(
strrep=str(self), struct=self.structure_repr())
return out | [
"def",
"get_declaration",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_opaque",
":",
"out",
"=",
"\"{strrep} = type opaque\"",
".",
"format",
"(",
"strrep",
"=",
"str",
"(",
"self",
")",
")",
"else",
":",
"out",
"=",
"\"{strrep} = type {struct}\"",
".",
"... | Returns the string for the declaration of the type | [
"Returns",
"the",
"string",
"for",
"the",
"declaration",
"of",
"the",
"type"
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/types.py#L563-L572 |
235,287 | numba/llvmlite | llvmlite/binding/ffi.py | ObjectRef.close | def close(self):
"""
Close this object and do any required clean-up actions.
"""
try:
if not self._closed and not self._owned:
self._dispose()
finally:
self.detach() | python | def close(self):
try:
if not self._closed and not self._owned:
self._dispose()
finally:
self.detach() | [
"def",
"close",
"(",
"self",
")",
":",
"try",
":",
"if",
"not",
"self",
".",
"_closed",
"and",
"not",
"self",
".",
"_owned",
":",
"self",
".",
"_dispose",
"(",
")",
"finally",
":",
"self",
".",
"detach",
"(",
")"
] | Close this object and do any required clean-up actions. | [
"Close",
"this",
"object",
"and",
"do",
"any",
"required",
"clean",
"-",
"up",
"actions",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/ffi.py#L226-L234 |
235,288 | numba/llvmlite | llvmlite/binding/ffi.py | ObjectRef.detach | def detach(self):
"""
Detach the underlying LLVM resource without disposing of it.
"""
if not self._closed:
del self._as_parameter_
self._closed = True
self._ptr = None | python | def detach(self):
if not self._closed:
del self._as_parameter_
self._closed = True
self._ptr = None | [
"def",
"detach",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_closed",
":",
"del",
"self",
".",
"_as_parameter_",
"self",
".",
"_closed",
"=",
"True",
"self",
".",
"_ptr",
"=",
"None"
] | Detach the underlying LLVM resource without disposing of it. | [
"Detach",
"the",
"underlying",
"LLVM",
"resource",
"without",
"disposing",
"of",
"it",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/ffi.py#L236-L243 |
235,289 | numba/llvmlite | llvmlite/binding/dylib.py | load_library_permanently | def load_library_permanently(filename):
"""
Load an external library
"""
with ffi.OutputString() as outerr:
if ffi.lib.LLVMPY_LoadLibraryPermanently(
_encode_string(filename), outerr):
raise RuntimeError(str(outerr)) | python | def load_library_permanently(filename):
with ffi.OutputString() as outerr:
if ffi.lib.LLVMPY_LoadLibraryPermanently(
_encode_string(filename), outerr):
raise RuntimeError(str(outerr)) | [
"def",
"load_library_permanently",
"(",
"filename",
")",
":",
"with",
"ffi",
".",
"OutputString",
"(",
")",
"as",
"outerr",
":",
"if",
"ffi",
".",
"lib",
".",
"LLVMPY_LoadLibraryPermanently",
"(",
"_encode_string",
"(",
"filename",
")",
",",
"outerr",
")",
"... | Load an external library | [
"Load",
"an",
"external",
"library"
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/dylib.py#L23-L30 |
235,290 | numba/llvmlite | ffi/build.py | find_win32_generator | def find_win32_generator():
"""
Find a suitable cmake "generator" under Windows.
"""
# XXX this assumes we will find a generator that's the same, or
# compatible with, the one which was used to compile LLVM... cmake
# seems a bit lacking here.
cmake_dir = os.path.join(here_dir, 'dummy')
# LLVM 4.0+ needs VS 2015 minimum.
generators = []
if os.environ.get("CMAKE_GENERATOR"):
generators.append(os.environ.get("CMAKE_GENERATOR"))
# Drop generators that are too old
vspat = re.compile(r'Visual Studio (\d+)')
def drop_old_vs(g):
m = vspat.match(g)
if m is None:
return True # keep those we don't recognize
ver = int(m.group(1))
return ver >= 14
generators = list(filter(drop_old_vs, generators))
generators.append('Visual Studio 14 2015' + (' Win64' if is_64bit else ''))
for generator in generators:
build_dir = tempfile.mkdtemp()
print("Trying generator %r" % (generator,))
try:
try_cmake(cmake_dir, build_dir, generator)
except subprocess.CalledProcessError:
continue
else:
# Success
return generator
finally:
shutil.rmtree(build_dir)
raise RuntimeError("No compatible cmake generator installed on this machine") | python | def find_win32_generator():
# XXX this assumes we will find a generator that's the same, or
# compatible with, the one which was used to compile LLVM... cmake
# seems a bit lacking here.
cmake_dir = os.path.join(here_dir, 'dummy')
# LLVM 4.0+ needs VS 2015 minimum.
generators = []
if os.environ.get("CMAKE_GENERATOR"):
generators.append(os.environ.get("CMAKE_GENERATOR"))
# Drop generators that are too old
vspat = re.compile(r'Visual Studio (\d+)')
def drop_old_vs(g):
m = vspat.match(g)
if m is None:
return True # keep those we don't recognize
ver = int(m.group(1))
return ver >= 14
generators = list(filter(drop_old_vs, generators))
generators.append('Visual Studio 14 2015' + (' Win64' if is_64bit else ''))
for generator in generators:
build_dir = tempfile.mkdtemp()
print("Trying generator %r" % (generator,))
try:
try_cmake(cmake_dir, build_dir, generator)
except subprocess.CalledProcessError:
continue
else:
# Success
return generator
finally:
shutil.rmtree(build_dir)
raise RuntimeError("No compatible cmake generator installed on this machine") | [
"def",
"find_win32_generator",
"(",
")",
":",
"# XXX this assumes we will find a generator that's the same, or",
"# compatible with, the one which was used to compile LLVM... cmake",
"# seems a bit lacking here.",
"cmake_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"here_dir",
"... | Find a suitable cmake "generator" under Windows. | [
"Find",
"a",
"suitable",
"cmake",
"generator",
"under",
"Windows",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/ffi/build.py#L48-L84 |
235,291 | numba/llvmlite | llvmlite/ir/values.py | _escape_string | def _escape_string(text, _map={}):
"""
Escape the given bytestring for safe use as a LLVM array constant.
"""
if isinstance(text, str):
text = text.encode('ascii')
assert isinstance(text, (bytes, bytearray))
if not _map:
for ch in range(256):
if ch in _VALID_CHARS:
_map[ch] = chr(ch)
else:
_map[ch] = '\\%02x' % ch
if six.PY2:
_map[chr(ch)] = _map[ch]
buf = [_map[ch] for ch in text]
return ''.join(buf) | python | def _escape_string(text, _map={}):
if isinstance(text, str):
text = text.encode('ascii')
assert isinstance(text, (bytes, bytearray))
if not _map:
for ch in range(256):
if ch in _VALID_CHARS:
_map[ch] = chr(ch)
else:
_map[ch] = '\\%02x' % ch
if six.PY2:
_map[chr(ch)] = _map[ch]
buf = [_map[ch] for ch in text]
return ''.join(buf) | [
"def",
"_escape_string",
"(",
"text",
",",
"_map",
"=",
"{",
"}",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"str",
")",
":",
"text",
"=",
"text",
".",
"encode",
"(",
"'ascii'",
")",
"assert",
"isinstance",
"(",
"text",
",",
"(",
"bytes",
",",... | Escape the given bytestring for safe use as a LLVM array constant. | [
"Escape",
"the",
"given",
"bytestring",
"for",
"safe",
"use",
"as",
"a",
"LLVM",
"array",
"constant",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/values.py#L20-L38 |
235,292 | numba/llvmlite | llvmlite/ir/values.py | _ConstOpMixin.bitcast | def bitcast(self, typ):
"""
Bitcast this pointer constant to the given type.
"""
if typ == self.type:
return self
op = "bitcast ({0} {1} to {2})".format(self.type, self.get_reference(),
typ)
return FormattedConstant(typ, op) | python | def bitcast(self, typ):
if typ == self.type:
return self
op = "bitcast ({0} {1} to {2})".format(self.type, self.get_reference(),
typ)
return FormattedConstant(typ, op) | [
"def",
"bitcast",
"(",
"self",
",",
"typ",
")",
":",
"if",
"typ",
"==",
"self",
".",
"type",
":",
"return",
"self",
"op",
"=",
"\"bitcast ({0} {1} to {2})\"",
".",
"format",
"(",
"self",
".",
"type",
",",
"self",
".",
"get_reference",
"(",
")",
",",
... | Bitcast this pointer constant to the given type. | [
"Bitcast",
"this",
"pointer",
"constant",
"to",
"the",
"given",
"type",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/values.py#L46-L54 |
235,293 | numba/llvmlite | llvmlite/ir/values.py | _ConstOpMixin.inttoptr | def inttoptr(self, typ):
"""
Cast this integer constant to the given pointer type.
"""
if not isinstance(self.type, types.IntType):
raise TypeError("can only call inttoptr() on integer constants, not '%s'"
% (self.type,))
if not isinstance(typ, types.PointerType):
raise TypeError("can only inttoptr() to pointer type, not '%s'"
% (typ,))
op = "inttoptr ({0} {1} to {2})".format(self.type,
self.get_reference(),
typ)
return FormattedConstant(typ, op) | python | def inttoptr(self, typ):
if not isinstance(self.type, types.IntType):
raise TypeError("can only call inttoptr() on integer constants, not '%s'"
% (self.type,))
if not isinstance(typ, types.PointerType):
raise TypeError("can only inttoptr() to pointer type, not '%s'"
% (typ,))
op = "inttoptr ({0} {1} to {2})".format(self.type,
self.get_reference(),
typ)
return FormattedConstant(typ, op) | [
"def",
"inttoptr",
"(",
"self",
",",
"typ",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"type",
",",
"types",
".",
"IntType",
")",
":",
"raise",
"TypeError",
"(",
"\"can only call inttoptr() on integer constants, not '%s'\"",
"%",
"(",
"self",
".",
... | Cast this integer constant to the given pointer type. | [
"Cast",
"this",
"integer",
"constant",
"to",
"the",
"given",
"pointer",
"type",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/values.py#L56-L70 |
235,294 | numba/llvmlite | llvmlite/ir/values.py | _ConstOpMixin.gep | def gep(self, indices):
"""
Call getelementptr on this pointer constant.
"""
if not isinstance(self.type, types.PointerType):
raise TypeError("can only call gep() on pointer constants, not '%s'"
% (self.type,))
outtype = self.type
for i in indices:
outtype = outtype.gep(i)
strindices = ["{0} {1}".format(idx.type, idx.get_reference())
for idx in indices]
op = "getelementptr ({0}, {1} {2}, {3})".format(
self.type.pointee, self.type,
self.get_reference(), ', '.join(strindices))
return FormattedConstant(outtype.as_pointer(self.addrspace), op) | python | def gep(self, indices):
if not isinstance(self.type, types.PointerType):
raise TypeError("can only call gep() on pointer constants, not '%s'"
% (self.type,))
outtype = self.type
for i in indices:
outtype = outtype.gep(i)
strindices = ["{0} {1}".format(idx.type, idx.get_reference())
for idx in indices]
op = "getelementptr ({0}, {1} {2}, {3})".format(
self.type.pointee, self.type,
self.get_reference(), ', '.join(strindices))
return FormattedConstant(outtype.as_pointer(self.addrspace), op) | [
"def",
"gep",
"(",
"self",
",",
"indices",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"type",
",",
"types",
".",
"PointerType",
")",
":",
"raise",
"TypeError",
"(",
"\"can only call gep() on pointer constants, not '%s'\"",
"%",
"(",
"self",
".",
... | Call getelementptr on this pointer constant. | [
"Call",
"getelementptr",
"on",
"this",
"pointer",
"constant",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/values.py#L72-L90 |
235,295 | numba/llvmlite | llvmlite/ir/values.py | Constant.literal_array | def literal_array(cls, elems):
"""
Construct a literal array constant made of the given members.
"""
tys = [el.type for el in elems]
if len(tys) == 0:
raise ValueError("need at least one element")
ty = tys[0]
for other in tys:
if ty != other:
raise TypeError("all elements must have the same type")
return cls(types.ArrayType(ty, len(elems)), elems) | python | def literal_array(cls, elems):
tys = [el.type for el in elems]
if len(tys) == 0:
raise ValueError("need at least one element")
ty = tys[0]
for other in tys:
if ty != other:
raise TypeError("all elements must have the same type")
return cls(types.ArrayType(ty, len(elems)), elems) | [
"def",
"literal_array",
"(",
"cls",
",",
"elems",
")",
":",
"tys",
"=",
"[",
"el",
".",
"type",
"for",
"el",
"in",
"elems",
"]",
"if",
"len",
"(",
"tys",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"need at least one element\"",
")",
"ty",
"="... | Construct a literal array constant made of the given members. | [
"Construct",
"a",
"literal",
"array",
"constant",
"made",
"of",
"the",
"given",
"members",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/values.py#L147-L158 |
235,296 | numba/llvmlite | llvmlite/ir/values.py | Constant.literal_struct | def literal_struct(cls, elems):
"""
Construct a literal structure constant made of the given members.
"""
tys = [el.type for el in elems]
return cls(types.LiteralStructType(tys), elems) | python | def literal_struct(cls, elems):
tys = [el.type for el in elems]
return cls(types.LiteralStructType(tys), elems) | [
"def",
"literal_struct",
"(",
"cls",
",",
"elems",
")",
":",
"tys",
"=",
"[",
"el",
".",
"type",
"for",
"el",
"in",
"elems",
"]",
"return",
"cls",
"(",
"types",
".",
"LiteralStructType",
"(",
"tys",
")",
",",
"elems",
")"
] | Construct a literal structure constant made of the given members. | [
"Construct",
"a",
"literal",
"structure",
"constant",
"made",
"of",
"the",
"given",
"members",
"."
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/values.py#L161-L166 |
235,297 | numba/llvmlite | llvmlite/ir/values.py | Function.insert_basic_block | def insert_basic_block(self, before, name=''):
"""Insert block before
"""
blk = Block(parent=self, name=name)
self.blocks.insert(before, blk)
return blk | python | def insert_basic_block(self, before, name=''):
blk = Block(parent=self, name=name)
self.blocks.insert(before, blk)
return blk | [
"def",
"insert_basic_block",
"(",
"self",
",",
"before",
",",
"name",
"=",
"''",
")",
":",
"blk",
"=",
"Block",
"(",
"parent",
"=",
"self",
",",
"name",
"=",
"name",
")",
"self",
".",
"blocks",
".",
"insert",
"(",
"before",
",",
"blk",
")",
"return... | Insert block before | [
"Insert",
"block",
"before"
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/values.py#L622-L627 |
235,298 | numba/llvmlite | llvmlite/ir/values.py | Block.replace | def replace(self, old, new):
"""Replace an instruction"""
if old.type != new.type:
raise TypeError("new instruction has a different type")
pos = self.instructions.index(old)
self.instructions.remove(old)
self.instructions.insert(pos, new)
for bb in self.parent.basic_blocks:
for instr in bb.instructions:
instr.replace_usage(old, new) | python | def replace(self, old, new):
if old.type != new.type:
raise TypeError("new instruction has a different type")
pos = self.instructions.index(old)
self.instructions.remove(old)
self.instructions.insert(pos, new)
for bb in self.parent.basic_blocks:
for instr in bb.instructions:
instr.replace_usage(old, new) | [
"def",
"replace",
"(",
"self",
",",
"old",
",",
"new",
")",
":",
"if",
"old",
".",
"type",
"!=",
"new",
".",
"type",
":",
"raise",
"TypeError",
"(",
"\"new instruction has a different type\"",
")",
"pos",
"=",
"self",
".",
"instructions",
".",
"index",
"... | Replace an instruction | [
"Replace",
"an",
"instruction"
] | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/values.py#L796-L806 |
235,299 | numba/llvmlite | llvmlite/binding/analysis.py | get_function_cfg | def get_function_cfg(func, show_inst=True):
"""Return a string of the control-flow graph of the function in DOT
format. If the input `func` is not a materialized function, the module
containing the function is parsed to create an actual LLVM module.
The `show_inst` flag controls whether the instructions of each block
are printed.
"""
assert func is not None
if isinstance(func, ir.Function):
mod = parse_assembly(str(func.module))
func = mod.get_function(func.name)
# Assume func is a materialized function
with ffi.OutputString() as dotstr:
ffi.lib.LLVMPY_WriteCFG(func, dotstr, show_inst)
return str(dotstr) | python | def get_function_cfg(func, show_inst=True):
assert func is not None
if isinstance(func, ir.Function):
mod = parse_assembly(str(func.module))
func = mod.get_function(func.name)
# Assume func is a materialized function
with ffi.OutputString() as dotstr:
ffi.lib.LLVMPY_WriteCFG(func, dotstr, show_inst)
return str(dotstr) | [
"def",
"get_function_cfg",
"(",
"func",
",",
"show_inst",
"=",
"True",
")",
":",
"assert",
"func",
"is",
"not",
"None",
"if",
"isinstance",
"(",
"func",
",",
"ir",
".",
"Function",
")",
":",
"mod",
"=",
"parse_assembly",
"(",
"str",
"(",
"func",
".",
... | Return a string of the control-flow graph of the function in DOT
format. If the input `func` is not a materialized function, the module
containing the function is parsed to create an actual LLVM module.
The `show_inst` flag controls whether the instructions of each block
are printed. | [
"Return",
"a",
"string",
"of",
"the",
"control",
"-",
"flow",
"graph",
"of",
"the",
"function",
"in",
"DOT",
"format",
".",
"If",
"the",
"input",
"func",
"is",
"not",
"a",
"materialized",
"function",
"the",
"module",
"containing",
"the",
"function",
"is",
... | fcadf8af11947f3fd041c5d6526c5bf231564883 | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/analysis.py#L14-L29 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.