signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def _read_segment_lines(segment_lines): | <EOL>segment_fields = {}<EOL>for field in SEGMENT_SPECS.index:<EOL><INDENT>segment_fields[field] = [None] * len(segment_lines)<EOL><DEDENT>for i in range(len(segment_lines)):<EOL><INDENT>(segment_fields['<STR_LIT>'][i], segment_fields['<STR_LIT>'][i]) = _rx_segment.findall(segment_lines[i])[<NUM_LIT:0>]<EOL>if field ==... | Extract fields from segment line strings into a dictionary | f10212:m4 |
def get_write_subset(self, spec_type): | if spec_type == '<STR_LIT>':<EOL><INDENT>write_fields = []<EOL>record_specs = RECORD_SPECS.copy()<EOL>if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>record_specs.drop('<STR_LIT>', inplace=True)<EOL><DEDENT>for field in record_specs.index[-<NUM_LIT:1>::-<NUM_LIT:1>]:<EOL><INDENT>if field in write_fields:<EOL><INDENT>con... | Get a set of fields used to write the header; either 'record'
or 'signal' specification fields. Helper function for
`get_write_fields`. Gets the default required fields, the user
defined fields, and their dependencies.
Parameters
----------
spec_type : str
The set of specification fields desired. Either 'record' o... | f10212:c0:m0 |
def set_defaults(self): | rfields, sfields = self.get_write_fields()<EOL>for f in rfields:<EOL><INDENT>self.set_default(f)<EOL><DEDENT>for f in sfields:<EOL><INDENT>self.set_default(f)<EOL><DEDENT> | Set defaults for fields needed to write the header if they have
defaults.
Notes
-----
- This is NOT called by `rdheader`. It is only automatically
called by the gateway `wrsamp` for convenience.
- This is also not called by `wrheader` since it is supposed to
be an explicit function.
- This is not responsible for i... | f10212:c1:m0 |
def wrheader(self, write_dir='<STR_LIT>'): | <EOL>rec_write_fields, sig_write_fields = self.get_write_fields()<EOL>for field in rec_write_fields:<EOL><INDENT>self.check_field(field)<EOL><DEDENT>for field in sig_write_fields:<EOL><INDENT>self.check_field(field, required_channels=sig_write_fields[field])<EOL><DEDENT>self.check_field_cohesion(rec_write_fields, list(... | Write a wfdb header file. The signals are not used. Before
writing:
- Get the fields used to write the header for this instance.
- Check each required field.
- Check that the fields are cohesive with one another.
Parameters
----------
write_dir : str, optional
The output directory in which the header is written.
... | f10212:c1:m1 |
def get_write_fields(self): | <EOL>rec_write_fields = self.get_write_subset('<STR_LIT>')<EOL>if self.comments != None:<EOL><INDENT>rec_write_fields.append('<STR_LIT>')<EOL><DEDENT>self.check_field('<STR_LIT>')<EOL>if self.n_sig > <NUM_LIT:0>:<EOL><INDENT>sig_write_fields = self.get_write_subset('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>sig_write_... | Get the list of fields used to write the header, separating
record and signal specification fields. Returns the default
required fields, the user defined fields,
and their dependencies.
Does NOT include `d_signal` or `e_d_signal`.
Returns
-------
rec_write_fields : list
Record specification fields to be written. ... | f10212:c1:m2 |
def set_default(self, field): | <EOL>if field in RECORD_SPECS.index:<EOL><INDENT>if RECORD_SPECS.loc[field, '<STR_LIT>'] is None or getattr(self, field) is not None:<EOL><INDENT>return<EOL><DEDENT>setattr(self, field, RECORD_SPECS.loc[field, '<STR_LIT>'])<EOL><DEDENT>elif field in SIGNAL_SPECS.index:<EOL><INDENT>if field == '<STR_LIT>' and self.file_... | 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. | f10212:c1:m3 |
def check_field_cohesion(self, rec_write_fields, sig_write_fields): | <EOL>if self.n_sig><NUM_LIT:0>:<EOL><INDENT>for f in sig_write_fields:<EOL><INDENT>if len(getattr(self, f)) != self.n_sig:<EOL><INDENT>raise ValueError('<STR_LIT>'+f+'<STR_LIT>')<EOL><DEDENT><DEDENT>datfmts = {}<EOL>for ch in range(self.n_sig):<EOL><INDENT>if self.file_name[ch] not in datfmts:<EOL><INDENT>datfmts[self.... | Check the cohesion of fields used to write the header | f10212:c1:m4 |
def wr_header_file(self, rec_write_fields, sig_write_fields, write_dir): | <EOL>record_line = '<STR_LIT>'<EOL>for field in RECORD_SPECS.index:<EOL><INDENT>if field in rec_write_fields:<EOL><INDENT>string_field = str(getattr(self, field))<EOL>if field == '<STR_LIT>' and isinstance(self.fs, float):<EOL><INDENT>if round(self.fs, <NUM_LIT:8>) == float(int(self.fs)):<EOL><INDENT>string_field = str... | 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 li... | f10212:c1:m5 |
def set_defaults(self): | for field in self.get_write_fields():<EOL><INDENT>self.set_default(field)<EOL><DEDENT> | Set defaults for fields needed to write the header if they have
defaults.
This is NOT called by rdheader. It is only called by the gateway
wrsamp for convenience.
It is also not called by wrhea since it is supposed to be an
explicit function.
Not responsible for initializing the
attributes. That is done by the const... | f10212:c2:m0 |
def get_write_fields(self): | <EOL>write_fields = self.get_write_subset('<STR_LIT>')<EOL>write_fields = write_fields + ['<STR_LIT>', '<STR_LIT>']<EOL>if self.comments !=None:<EOL><INDENT>write_fields.append('<STR_LIT>')<EOL><DEDENT>return write_fields<EOL> | Get the list of fields used to write the multi-segment header.
Returns the default required fields, the user defined fields,
and their dependencies. | f10212:c2:m2 |
def wr_header_file(self, write_fields, write_dir): | <EOL>record_line = '<STR_LIT>'<EOL>for field in RECORD_SPECS.index:<EOL><INDENT>if field in write_fields:<EOL><INDENT>record_line += RECORD_SPECS.loc[field, '<STR_LIT>'] + str(getattr(self, field))<EOL><DEDENT><DEDENT>header_lines = [record_line]<EOL>segment_lines = self.n_seg * ['<STR_LIT>']<EOL>for field in SEGMENT_S... | Write a header file using the specified fields | f10212:c2:m5 |
def get_sig_segments(self, sig_name=None): | if self.segments is None:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>if sig_name is None:<EOL><INDENT>sig_name = self.get_sig_name()<EOL><DEDENT>if isinstance(sig_name, list):<EOL><INDENT>sigdict = {}<EOL>for sig in sig_name:<EOL><INDENT>sigdict[sig] = self.get_sig_segments(sig)<EOL><DEDENT>return sigdict<EOL... | Get a list of the segment numbers that contain a particular signal
(or a dictionary of segment numbers for a list of signals)
Only works if information about the segments has been read in | f10212:c2:m6 |
def rdtff(file_name, cut_end=False): | file_size = os.path.getsize(file_name)<EOL>with open(file_name, '<STR_LIT:rb>') as fp:<EOL><INDENT>fields, file_fields = _rdheader(fp)<EOL>signal, markers, triggers = _rdsignal(fp, file_size=file_size,<EOL>header_size=file_fields['<STR_LIT>'],<EOL>n_sig=file_fields['<STR_LIT>'],<EOL>bit_width=file_fields['<STR_LIT>'],<... | 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)... | f10213:m0 |
def _rdheader(fp): | tag = None<EOL>while tag != <NUM_LIT:2>:<EOL><INDENT>tag = struct.unpack('<STR_LIT>', fp.read(<NUM_LIT:2>))[<NUM_LIT:0>]<EOL>data_size = struct.unpack('<STR_LIT>', fp.read(<NUM_LIT:2>))[<NUM_LIT:0>]<EOL>pad_len = (<NUM_LIT:4> - (data_size % <NUM_LIT:4>)) % <NUM_LIT:4><EOL>pos = fp.tell()<EOL>if tag == <NUM_LIT>:<EOL><I... | Read header info of the windaq file | f10213:m1 |
def _rdsignal(fp, file_size, header_size, n_sig, bit_width, is_signed, cut_end): | <EOL>fp.seek(header_size)<EOL>signal_size = file_size - header_size<EOL>byte_width = int(bit_width / <NUM_LIT:8>)<EOL>dtype = str(byte_width)<EOL>if is_signed:<EOL><INDENT>dtype = '<STR_LIT:i>' + dtype<EOL><DEDENT>else:<EOL><INDENT>dtype = '<STR_LIT:u>' + dtype<EOL><DEDENT>dtype = '<STR_LIT:>>' + dtype<EOL>max_samples ... | 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 readi... | f10213:m2 |
def label_triplets_to_df(triplets): | label_df = pd.DataFrame({'<STR_LIT>':np.array([t[<NUM_LIT:0>] for t in triplets],<EOL>dtype='<STR_LIT:int>'),<EOL>'<STR_LIT>':[t[<NUM_LIT:1>] for t in triplets],<EOL>'<STR_LIT:description>':[t[<NUM_LIT:2>] for t in triplets]})<EOL>label_df.set_index(label_df['<STR_LIT>'].values, inplace=True)<EOL>label_df = label_df[li... | Get a pd dataframe from a tuple triplets
used to define annotation labels.
The triplets should come in the
form: (label_store, symbol, description) | f10215:m0 |
def custom_triplet_bytes(custom_triplet): | <EOL>annbytes = [<NUM_LIT:0>, <NUM_LIT>, len(custom_triplet[<NUM_LIT:2>]) + <NUM_LIT:3> + len(str(custom_triplet[<NUM_LIT:0>])), <NUM_LIT>] + [ord(c) for c in str(custom_triplet[<NUM_LIT:0>])]+ [<NUM_LIT:32>] + [ord(custom_triplet[<NUM_LIT:1>])] + [<NUM_LIT:32>] + [ord(c) for c in custom_triplet[<NUM_LIT:2>]]<EOL>if le... | Convert triplet of [label_store, symbol, description] into bytes
for defining custom labels in the annotation file | f10215:m1 |
def compact_carry_field(full_field): | <EOL>if full_field is None:<EOL><INDENT>return None<EOL><DEDENT>compact_field = [None]*len(full_field)<EOL>prev_field = <NUM_LIT:0><EOL>for i in range(len(full_field)):<EOL><INDENT>current_field = full_field[i]<EOL>if current_field != prev_field:<EOL><INDENT>compact_field[i] = current_field<EOL>prev_field = current_fie... | Return the compact list version of a list/array of an
annotation field that has previous values carried over
(chan or num)
- The first sample is 0 by default. Only set otherwise
if necessary.
- Only set fields if they are different from their prev
field | f10215:m3 |
def wrann(record_name, extension, sample, symbol=None, subtype=None, chan=None,<EOL>num=None, aux_note=None, label_store=None, fs=None,<EOL>custom_labels=None, write_dir='<STR_LIT>'): | <EOL>annotation = Annotation(record_name=record_name, extension=extension,<EOL>sample=sample, symbol=symbol, subtype=subtype,<EOL>chan=chan, num=num, aux_note=aux_note,<EOL>label_store=label_store, fs=fs,<EOL>custom_labels=custom_labels)<EOL>if symbol is None:<EOL><INDENT>if label_store is None:<EOL><INDENT>raise Excep... | Write a WFDB annotation file.
Specify at least the following:
- The record name of the WFDB record (record_name)
- The annotation file extension (extension)
- The annotation locations in samples relative to the beginning of
the record (sample)
- Either the numerical values used to store the labels
(`label_store`)... | f10215:m5 |
def show_ann_labels(): | print(ann_label_table)<EOL> | Display the standard wfdb annotation label mapping.
Examples
--------
>>> show_ann_labels() | f10215:m6 |
def show_ann_classes(): | print(ann_class_table)<EOL> | Display the standard wfdb annotation classes
Examples
--------
>>> show_ann_classes() | f10215:m7 |
def rdann(record_name, extension, sampfrom=<NUM_LIT:0>, sampto=None, shift_samps=False,<EOL>pb_dir=None, return_label_elements=['<STR_LIT>'],<EOL>summarize_labels=False): | return_label_elements = check_read_inputs(sampfrom, sampto,<EOL>return_label_elements)<EOL>filebytes = load_byte_pairs(record_name, extension, pb_dir)<EOL>(sample, label_store, subtype,<EOL>chan, num, aux_note) = proc_ann_bytes(filebytes, sampto)<EOL>potential_definition_inds, rm_inds = get_special_inds(sample, label_s... | Read a WFDB annotation file record_name.extension and return an
Annotation object.
Parameters
----------
record_name : str
The record name of the WFDB annotation file. ie. for file '100.atr',
record_name='100'.
extension : str
The annotatator extension of the annotation file. ie. for file
'100.atr', e... | f10215:m8 |
def proc_extra_field(label_store, filebytes, bpi, subtype, chan, num, aux_note, update): | <EOL>if label_store == <NUM_LIT>:<EOL><INDENT>subtype.append(filebytes[bpi, <NUM_LIT:0>].astype('<STR_LIT>'))<EOL>update['<STR_LIT>'] = False<EOL>bpi = bpi + <NUM_LIT:1><EOL><DEDENT>elif label_store == <NUM_LIT>:<EOL><INDENT>chan.append(filebytes[bpi, <NUM_LIT:0>])<EOL>update['<STR_LIT>'] = False<EOL>bpi = bpi + <NUM_L... | Process extra fields belonging to the current annotation.
Potential updated fields: subtype, chan, num, aux_note | f10215:m13 |
def update_extra_fields(subtype, chan, num, aux_note, update): | if update['<STR_LIT>']:<EOL><INDENT>subtype.append(<NUM_LIT:0>)<EOL><DEDENT>if update['<STR_LIT>']:<EOL><INDENT>if chan == []:<EOL><INDENT>chan.append(<NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>chan.append(chan[-<NUM_LIT:1>])<EOL><DEDENT><DEDENT>if update['<STR_LIT>']:<EOL><INDENT>if num == []:<EOL><INDENT>num.append(<... | Update the field if the current annotation did not
provide a value.
- aux_note and sub are set to default values if missing.
- chan and num copy over previous value if missing. | f10215:m14 |
def get_special_inds(sample, label_store, aux_note): | s0_inds = np.where(sample == np.int64(<NUM_LIT:0>))[<NUM_LIT:0>]<EOL>note_inds = np.where(label_store == np.int64(<NUM_LIT>))[<NUM_LIT:0>]<EOL>potential_definition_inds = set(s0_inds).intersection(note_inds)<EOL>notann_inds = np.where(label_store == np.int64(<NUM_LIT:0>))[<NUM_LIT:0>]<EOL>rm_inds = potential_definition... | Get the indices of annotations that hold definition information about
the entire annotation file, and other empty annotations to be removed.
Note: There is no need to deal with SKIP annotations (label_store=59)
which were already dealt with in proc_core_fields and hence not
included here. | f10215:m15 |
def interpret_defintion_annotations(potential_definition_inds, aux_note): | fs = None<EOL>custom_labels = []<EOL>if len(potential_definition_inds) > <NUM_LIT:0>:<EOL><INDENT>i = <NUM_LIT:0><EOL>while i<len(potential_definition_inds):<EOL><INDENT>if aux_note[i].startswith('<STR_LIT>'):<EOL><INDENT>if not fs:<EOL><INDENT>search_fs = rx_fs.findall(aux_note[i])<EOL>if search_fs:<EOL><INDENT>fs = f... | Try to extract annotation definition information from annotation notes.
Information that may be contained:
- fs - sample=0, label_state=22, aux_note='## time resolution: XXX'
- custom annotation label definitions | f10215:m16 |
def rm_empty_indices(*args): | rm_inds = args[<NUM_LIT:0>]<EOL>if not rm_inds:<EOL><INDENT>return args[<NUM_LIT:1>:]<EOL><DEDENT>keep_inds = [i for i in range(len(args[<NUM_LIT:1>])) if i not in rm_inds]<EOL>return [[a[i] for i in keep_inds] for a in args[<NUM_LIT:1>:]]<EOL> | Remove unwanted list indices. First argument is the list
of indices to remove. Other elements are the lists
to trim. | f10215:m17 |
def lists_to_int_arrays(*args): | return [np.array(a, dtype='<STR_LIT:int>') for a in args]<EOL> | Convert lists to numpy int arrays | f10215:m18 |
def rm_last(*args): | if len(args) == <NUM_LIT:1>:<EOL><INDENT>return args[:-<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>return [a[:-<NUM_LIT:1>] for a in args]<EOL><DEDENT>return<EOL> | Remove the last index from each list | f10215:m19 |
def __init__(self, record_name, extension, sample, symbol=None,<EOL>subtype=None, chan=None, num=None, aux_note=None, fs=None,<EOL>label_store=None, description=None, custom_labels=None,<EOL>contained_labels=None): | self.record_name = record_name<EOL>self.extension = extension<EOL>self.sample = sample<EOL>self.symbol = symbol<EOL>self.subtype = subtype<EOL>self.chan = chan<EOL>self.num = num<EOL>self.aux_note = aux_note<EOL>self.fs = fs<EOL>self.label_store = label_store<EOL>self.description = description<EOL>self.custom_labels = ... | Parameters
----------
record_name : str
The base file name (without extension) of the record that the
annotation is associated with.
extension : str
The file extension of the file the annotation is stored in.
sample : numpy array
A numpy array containing the annotation locations in samples relative to
... | f10215:c0:m0 |
def apply_range(self, sampfrom=<NUM_LIT:0>, sampto=None): | sampto = sampto or self.sample[-<NUM_LIT:1>]<EOL>kept_inds = np.intersect1d(np.where(self.sample>=sampfrom),<EOL>np.where(self.sample<=sampto))<EOL>for field in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>setattr(self, field, getattr(self, field)[kept_inds])<EOL><DEDENT>self.aux_note ... | Filter the annotation attributes to keep only items between the
desired sample values | f10215:c0:m2 |
def wrann(self, write_fs=False, write_dir='<STR_LIT>'): | for field in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>if getattr(self, field) is None:<EOL><INDENT>raise Exception('<STR_LIT>',field)<EOL><DEDENT><DEDENT>present_label_fields = self.get_label_fields()<EOL>if not present_label_fields:<EOL><INDENT>raise Exception('<STR_LIT>', ann_label_fields)<EOL><DEDENT>self.check_field... | Write a WFDB annotation file from this object.
Parameters
----------
write_fs : bool, optional
Whether to write the `fs` attribute to the file. | f10215:c0:m3 |
def get_label_fields(self): | present_label_fields = []<EOL>for field in ann_label_fields:<EOL><INDENT>if getattr(self, field) is not None:<EOL><INDENT>present_label_fields.append(field)<EOL><DEDENT><DEDENT>return present_label_fields<EOL> | Get the present label fields in the object | f10215:c0:m4 |
def check_field(self, field): | item = getattr(self, field)<EOL>if not isinstance(item, ALLOWED_TYPES[field]):<EOL><INDENT>raise TypeError('<STR_LIT>'+field+'<STR_LIT>', ALLOWED_TYPES[field])<EOL><DEDENT>if ALLOWED_TYPES[field] == (np.ndarray):<EOL><INDENT>record.check_np_array(item=item, field_name=field, ndim=<NUM_LIT:1>,<EOL>parent_class=np.intege... | Check a particular annotation field | f10215:c0:m6 |
def check_field_cohesion(self, present_label_fields): | <EOL>nannots = len(self.sample)<EOL>for field in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']+present_label_fields:<EOL><INDENT>if getattr(self, field) is not None:<EOL><INDENT>if len(getattr(self, field)) != nannots:<EOL><INDENT>raise ValueError("<STR_LIT>"+field+"<STR_LIT>")<EOL><DEDENT><DEDENT><... | Check that the content and structure of different fields are consistent
with one another. | f10215:c0:m7 |
def standardize_custom_labels(self): | custom_labels = self.custom_labels<EOL>if custom_labels is None:<EOL><INDENT>return<EOL><DEDENT>self.check_field('<STR_LIT>')<EOL>if not isinstance(custom_labels, pd.DataFrame):<EOL><INDENT>if len(self.custom_labels[<NUM_LIT:0>]) == <NUM_LIT:2>:<EOL><INDENT>symbol = self.get_custom_label_attribute('<STR_LIT>')<EOL>desc... | Set the custom_labels field of the object to a standardized format:
3 column pandas df with ann_label_fields as columns.
Does nothing if there are no custom labels defined.
Does nothing if custom_labels is already a df with all 3 columns
If custom_labels is an iterable of pairs/triplets, this
function will convert it... | f10215:c0:m8 |
def get_undefined_label_stores(self): | return list(set(range(<NUM_LIT:50>)) - set(ann_label_table['<STR_LIT>']))<EOL> | Get the label_store values not defined in the
standard wfdb annotation labels. | f10215:c0:m9 |
def get_available_label_stores(self, usefield='<STR_LIT>'): | <EOL>if usefield == '<STR_LIT>':<EOL><INDENT>if self.label_store is not None:<EOL><INDENT>usefield = '<STR_LIT>'<EOL><DEDENT>elif self.symbol is not None:<EOL><INDENT>usefield = '<STR_LIT>'<EOL><DEDENT>elif self.description is not None:<EOL><INDENT>usefield = '<STR_LIT:description>'<EOL><DEDENT>else:<EOL><INDENT>raise ... | Get the label store values that may be used
for writing this annotation.
Available store values include:
- the undefined values in the standard wfdb labels
- the store values not used in the current
annotation object.
- the store values whose standard wfdb symbols/descriptions
match those of the custom labels (if ... | f10215:c0:m10 |
def get_custom_label_attribute(self, attribute): | if attribute not in ann_label_fields:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if isinstance(self.custom_labels, pd.DataFrame):<EOL><INDENT>if '<STR_LIT>' not in list(self.custom_labels):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>a = list(self.custom_labels[attribute].values)<EOL><DEDENT>else:<... | Get a list of the custom_labels attribute.
ie. label_store, symbol, or description.
The custom_labels variable could be in
a number of formats | f10215:c0:m11 |
def create_label_map(self, inplace=True): | label_map = ann_label_table.copy()<EOL>if self.custom_labels is not None:<EOL><INDENT>self.standardize_custom_labels()<EOL>for i in self.custom_labels.index:<EOL><INDENT>label_map.loc[i] = self.custom_labels.loc[i]<EOL><DEDENT><DEDENT>if inplace:<EOL><INDENT>self.__label_map__ = label_map<EOL><DEDENT>else:<EOL><INDENT... | Creates mapping df based on ann_label_table and self.custom_labels.
Table composed of entire WFDB standard annotation table, overwritten/appended
with custom_labels if any. Sets __label_map__ attribute, or returns value. | f10215:c0:m12 |
def wr_ann_file(self, write_fs, write_dir='<STR_LIT>'): | <EOL>if write_fs:<EOL><INDENT>fs_bytes = self.calc_fs_bytes()<EOL><DEDENT>else:<EOL><INDENT>fs_bytes = []<EOL><DEDENT>cl_bytes = self.calc_cl_bytes()<EOL>core_bytes = self.calc_core_bytes()<EOL>if fs_bytes == [] and cl_bytes == []:<EOL><INDENT>end_special_bytes = []<EOL><DEDENT>else:<EOL><INDENT>end_special_bytes = [<N... | Calculate the bytes used to encode an annotation set and
write them to an annotation file | f10215:c0:m13 |
def calc_core_bytes(self): | <EOL>if len(self.sample) == <NUM_LIT:1>:<EOL><INDENT>sampdiff = np.array([self.sample[<NUM_LIT:0>]])<EOL><DEDENT>else:<EOL><INDENT>sampdiff = np.concatenate(([self.sample[<NUM_LIT:0>]], np.diff(self.sample)))<EOL><DEDENT>compact_annotation = copy.deepcopy(self)<EOL>compact_annotation.compact_fields()<EOL>extra_write_fi... | Convert all used annotation fields into bytes to write | f10215:c0:m16 |
def get_contained_labels(self, inplace=True): | if self.custom_labels is not None:<EOL><INDENT>self.check_field('<STR_LIT>')<EOL><DEDENT>label_map = ann_label_table.copy()<EOL>if isinstance(self.custom_labels, (list, tuple)):<EOL><INDENT>custom_labels = label_triplets_to_df(self.custom_labels)<EOL><DEDENT>elif isinstance(self.custom_labels, pd.DataFrame):<EOL><INDEN... | Get the set of unique labels contained in this annotation.
Returns a pandas dataframe or sets the contained_labels
attribute of the object.
Requires the label_store field to be set.
Function will try to use attributes contained in the order:
1. label_store
2. symbol
3. description
This function should also be calle... | f10215:c0:m19 |
def set_label_elements(self, wanted_label_elements): | if isinstance(wanted_label_elements, str):<EOL><INDENT>wanted_label_elements = [wanted_label_elements]<EOL><DEDENT>missing_elements = [e for e in wanted_label_elements if getattr(self, e) is None]<EOL>contained_elements = [e for e in ann_label_fields if getattr(self, e )is not None]<EOL>if not contained_elements:<EOL><... | Set one or more label elements based on
at least one of the others | f10215:c0:m20 |
def convert_label_attribute(self, source_field, target_field, inplace=True,<EOL>overwrite=True): | if inplace and not overwrite:<EOL><INDENT>if getattr(self, target_field) is not None:<EOL><INDENT>return<EOL><DEDENT><DEDENT>label_map = self.create_label_map(inplace=False)<EOL>label_map.set_index(label_map[source_field].values, inplace=True)<EOL>target_item = label_map.loc[getattr(self, source_field), target_field].v... | Convert one label attribute (label_store, symbol, or description) to another.
Input arguments:
- inplace - If True, sets the object attribute. If False, returns the value.
- overwrite - if True, performs conversion and replaces target field attribute even if the
target attribute already has a value. If False, does no... | f10215:c0:m22 |
def plot_items(signal=None, ann_samp=None, ann_sym=None, fs=None,<EOL>time_units='<STR_LIT>', sig_name=None, sig_units=None,<EOL>ylabel=None, title=None, sig_style=['<STR_LIT>'], ann_style=['<STR_LIT>'],<EOL>ecg_grids=[], figsize=None, return_fig=False): | <EOL>sig_len, n_sig, n_annot, n_subplots = get_plot_dims(signal, ann_samp)<EOL>fig, axes = create_figure(n_subplots, figsize)<EOL>if signal is not None:<EOL><INDENT>plot_signal(signal, sig_len, n_sig, fs, time_units, sig_style, axes)<EOL><DEDENT>if ann_samp is not None:<EOL><INDENT>plot_annotation(ann_samp, n_annot, an... | Subplot individual channels of signals and/or annotations.
Parameters
----------
signal : 1d or 2d numpy array, optional
The uniformly sampled signal to be plotted. If signal.ndim is 1, it is
assumed to be a one channel signal. If it is 2, axes 0 and 1, must
represent time and channel number respectively.
... | f10216:m0 |
def get_plot_dims(signal, ann_samp): | if signal is not None:<EOL><INDENT>if signal.ndim == <NUM_LIT:1>:<EOL><INDENT>sig_len = len(signal)<EOL>n_sig = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>sig_len = signal.shape[<NUM_LIT:0>]<EOL>n_sig = signal.shape[<NUM_LIT:1>]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>sig_len = <NUM_LIT:0><EOL>n_sig = <NUM_LIT:0><EOL><DED... | Figure out the number of plot channels | f10216:m1 |
def create_figure(n_subplots, figsize): | fig = plt.figure(figsize=figsize)<EOL>axes = []<EOL>for i in range(n_subplots):<EOL><INDENT>axes.append(fig.add_subplot(n_subplots, <NUM_LIT:1>, i+<NUM_LIT:1>))<EOL><DEDENT>return fig, axes<EOL> | Create the plot figure and subplot axes | f10216:m2 |
def plot_signal(signal, sig_len, n_sig, fs, time_units, sig_style, axes): | <EOL>if len(sig_style) == <NUM_LIT:1>:<EOL><INDENT>sig_style = n_sig * sig_style<EOL><DEDENT>if time_units == '<STR_LIT>':<EOL><INDENT>t = np.linspace(<NUM_LIT:0>, sig_len-<NUM_LIT:1>, sig_len)<EOL><DEDENT>else:<EOL><INDENT>downsample_factor = {'<STR_LIT>':fs, '<STR_LIT>':fs * <NUM_LIT>,<EOL>'<STR_LIT>':fs * <NUM_LIT>}... | Plot signal channels | f10216:m3 |
def plot_annotation(ann_samp, n_annot, ann_sym, signal, n_sig, fs, time_units,<EOL>ann_style, axes): | <EOL>if len(ann_style) == <NUM_LIT:1>:<EOL><INDENT>ann_style = n_annot * ann_style<EOL><DEDENT>if time_units == '<STR_LIT>':<EOL><INDENT>downsample_factor = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>downsample_factor = {'<STR_LIT>':float(fs), '<STR_LIT>':float(fs)*<NUM_LIT>,<EOL>'<STR_LIT>':float(fs)*<NUM_LIT>}[time_un... | Plot annotations, possibly overlaid on signals | f10216:m4 |
def plot_ecg_grids(ecg_grids, fs, units, time_units, axes): | if ecg_grids == '<STR_LIT:all>':<EOL><INDENT>ecg_grids = range(<NUM_LIT:0>, len(axes))<EOL><DEDENT>for ch in ecg_grids:<EOL><INDENT>auto_xlims = axes[ch].get_xlim()<EOL>auto_ylims= axes[ch].get_ylim()<EOL>(major_ticks_x, minor_ticks_x, major_ticks_y,<EOL>minor_ticks_y) = calc_ecg_grids(auto_ylims[<NUM_LIT:0>], auto_yli... | Add ecg grids to the axes | f10216:m5 |
def calc_ecg_grids(minsig, maxsig, sig_units, fs, maxt, time_units): | <EOL>if time_units == '<STR_LIT>':<EOL><INDENT>majorx = <NUM_LIT> * fs<EOL>minorx = <NUM_LIT> * fs<EOL><DEDENT>elif time_units == '<STR_LIT>':<EOL><INDENT>majorx = <NUM_LIT><EOL>minorx = <NUM_LIT><EOL><DEDENT>elif time_units == '<STR_LIT>':<EOL><INDENT>majorx = <NUM_LIT> / <NUM_LIT><EOL>minorx = <NUM_LIT>/<NUM_LIT><EOL... | Calculate tick intervals for ecg grids
- 5mm 0.2s major grids, 0.04s minor grids
- 0.5mV major grids, 0.125 minor grids
10 mm is equal to 1mV in voltage. | f10216:m6 |
def label_figure(axes, n_subplots, time_units, sig_name, sig_units, ylabel,<EOL>title): | if title:<EOL><INDENT>axes[<NUM_LIT:0>].set_title(title)<EOL><DEDENT>if not ylabel:<EOL><INDENT>ylabel = []<EOL>if not sig_name:<EOL><INDENT>sig_name = ['<STR_LIT>'+str(i) for i in range(n_subplots)]<EOL><DEDENT>if not sig_units:<EOL><INDENT>sig_units = n_subplots * ['<STR_LIT>']<EOL><DEDENT>ylabel = ['<STR_LIT:/>'.joi... | Add title, and axes labels | f10216:m7 |
def plot_wfdb(record=None, annotation=None, plot_sym=False,<EOL>time_units='<STR_LIT>', title=None, sig_style=['<STR_LIT>'],<EOL>ann_style=['<STR_LIT>'], ecg_grids=[], figsize=None, return_fig=False): | (signal, ann_samp, ann_sym, fs,<EOL>ylabel, record_name) = get_wfdb_plot_items(record=record,<EOL>annotation=annotation,<EOL>plot_sym=plot_sym)<EOL>return plot_items(signal=signal, ann_samp=ann_samp, ann_sym=ann_sym, fs=fs,<EOL>time_units=time_units, ylabel=ylabel,<EOL>title=(title or record_name),<EOL>sig_style=sig_st... | Subplot individual channels of a wfdb record and/or annotation.
This function implements the base functionality of the `plot_items`
function, while allowing direct input of wfdb objects.
If the record object is input, the function will extract from it:
- signal values, from the `p_signal` (priority) or `d_signal` a... | f10216:m8 |
def get_wfdb_plot_items(record, annotation, plot_sym): | <EOL>if record:<EOL><INDENT>if record.p_signal is not None:<EOL><INDENT>signal = record.p_signal<EOL><DEDENT>elif record.d_signal is not None:<EOL><INDENT>signal = record.d_signal<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>fs = record.fs<EOL>sig_name = record.sig_name<EOL>sig_units = record... | Get items to plot from wfdb objects | f10216:m9 |
def plot_all_records(directory='<STR_LIT>'): | directory = directory or os.getcwd()<EOL>headers = [f for f in os.listdir(directory) if os.path.isfile(<EOL>os.path.join(directory, f))]<EOL>headers = [f for f in headers if f.endswith('<STR_LIT>')]<EOL>records = [h.split('<STR_LIT>')[<NUM_LIT:0>] for h in headers]<EOL>records.sort()<EOL>for record_name in records:<EOL... | Plot all wfdb records in a directory (by finding header files), one at
a time, until the 'enter' key is pressed.
Parameters
----------
directory : str, optional
The directory in which to search for WFDB records. Defaults to
current working directory. | f10216:m10 |
def find_peaks(sig): | if len(sig) == <NUM_LIT:0>:<EOL><INDENT>return np.empty([<NUM_LIT:0>]), np.empty([<NUM_LIT:0>])<EOL><DEDENT>tmp = sig[<NUM_LIT:1>:]<EOL>tmp = np.append(tmp, [sig[-<NUM_LIT:1>]])<EOL>tmp = sig - tmp<EOL>tmp[np.where(tmp><NUM_LIT:0>)] = <NUM_LIT:1><EOL>tmp[np.where(tmp==<NUM_LIT:0>)] = <NUM_LIT:0><EOL>tmp[np.where(tmp<<N... | Find hard peaks and soft peaks in a signal, defined as follows:
- Hard peak: a peak that is either /\ or \/
- Soft peak: a peak that is either /-*\ or \-*/
In this case we define the middle as the peak
Parameters
----------
sig : np array
The 1d signal array
Returns
-------
hard_peaks : numpy array
Array c... | f10219:m0 |
def find_local_peaks(sig, radius): | <EOL>if np.min(sig) == np.max(sig):<EOL><INDENT>return np.empty(<NUM_LIT:0>)<EOL><DEDENT>peak_inds = []<EOL>i = <NUM_LIT:0><EOL>while i < radius + <NUM_LIT:1>:<EOL><INDENT>if sig[i] == max(sig[:i + radius]):<EOL><INDENT>peak_inds.append(i)<EOL>i += radius<EOL><DEDENT>else:<EOL><INDENT>i += <NUM_LIT:1><EOL><DEDENT><DEDE... | Find all local peaks in a signal. A sample is a local peak if it is
the largest value within the <radius> samples on its left and right.
In cases where it shares the max value with nearby samples, the
middle sample is classified as the local peak.
Parameters
----------
sig : numpy array
1d numpy array of the sign... | f10219:m1 |
def correct_peaks(sig, peak_inds, search_radius, smooth_window_size,<EOL>peak_dir='<STR_LIT>'): | sig_len = sig.shape[<NUM_LIT:0>]<EOL>n_peaks = len(peak_inds)<EOL>sig = sig - smooth(sig=sig, window_size=smooth_window_size)<EOL>if peak_dir == '<STR_LIT>':<EOL><INDENT>shifted_peak_inds = shift_peaks(sig=sig,<EOL>peak_inds=peak_inds,<EOL>search_radius=search_radius,<EOL>peak_up=True)<EOL><DEDENT>elif peak_dir == '<ST... | Adjust a set of detected peaks to coincide with local signal maxima,
and
Parameters
----------
sig : numpy array
The 1d signal array
peak_inds : np array
Array of the original peak indices
max_gap : int
The radius within which the original peaks may be shifted.
smooth_window_size : int
The window size ... | f10219:m2 |
def shift_peaks(sig, peak_inds, search_radius, peak_up): | sig_len = sig.shape[<NUM_LIT:0>]<EOL>n_peaks = len(peak_inds)<EOL>shift_inds = np.zeros(n_peaks, dtype='<STR_LIT:int>')<EOL>for i in range(n_peaks):<EOL><INDENT>ind = peak_inds[i]<EOL>local_sig = sig[max(<NUM_LIT:0>, ind - search_radius):min(ind + search_radius, sig_len-<NUM_LIT:1>)]<EOL>if peak_up:<EOL><INDENT>shift_i... | Helper function for correct_peaks. Return the shifted peaks to local
maxima or minima within a radius.
peak_up : bool
Whether the expected peak direction is up | f10219:m3 |
def compute_hr(sig_len, qrs_inds, fs): | heart_rate = np.full(sig_len, np.nan, dtype='<STR_LIT>')<EOL>if len(qrs_inds) < <NUM_LIT:2>:<EOL><INDENT>return heart_rate<EOL><DEDENT>for i in range(<NUM_LIT:0>, len(qrs_inds)-<NUM_LIT:2>):<EOL><INDENT>a = qrs_inds[i]<EOL>b = qrs_inds[i+<NUM_LIT:1>]<EOL>c = qrs_inds[i+<NUM_LIT:2>]<EOL>rr = (b-a) * (<NUM_LIT:1.0> / 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 insta... | f10220:m0 |
def calc_rr(qrs_locs, fs=None, min_rr=None, max_rr=None, qrs_units='<STR_LIT>',<EOL>rr_units='<STR_LIT>'): | rr = np.diff(qrs_locs)<EOL>if not len(rr):<EOL><INDENT>return rr<EOL><DEDENT>if qrs_units == '<STR_LIT>' and rr_units == '<STR_LIT>':<EOL><INDENT>rr = rr / fs<EOL><DEDENT>elif qrs_units == '<STR_LIT>' and rr_units == '<STR_LIT>':<EOL><INDENT>rr = rr * fs<EOL><DEDENT>if min_rr is not None:<EOL><INDENT>rr = rr[rr > min_r... | 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... | f10220:m1 |
def calc_mean_hr(rr, fs=None, min_rr=None, max_rr=None, rr_units='<STR_LIT>'): | if not len(rr):<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>if min_rr is not None:<EOL><INDENT>rr = rr[rr > min_rr]<EOL><DEDENT>if max_rr is not None:<EOL><INDENT>rr = rr[rr < max_rr]<EOL><DEDENT>mean_rr = np.mean(rr)<EOL>mean_hr = <NUM_LIT> / mean_rr<EOL>if rr_units == '<STR_LIT>':<EOL><INDENT>mean_hr = mean_hr * fs<EO... | 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 mi... | f10220:m2 |
def resample_ann(resampled_t, ann_sample): | tmp = np.zeros(len(resampled_t), dtype='<STR_LIT>')<EOL>j = <NUM_LIT:0><EOL>tprec = resampled_t[j]<EOL>for i, v in enumerate(ann_sample):<EOL><INDENT>while True:<EOL><INDENT>d = False<EOL>if v < tprec:<EOL><INDENT>j -= <NUM_LIT:1><EOL>tprec = resampled_t[j]<EOL><DEDENT>if j+<NUM_LIT:1> == len(resampled_t):<EOL><INDENT>... | 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 | f10221:m0 |
def resample_sig(x, fs, fs_target): | t = np.arange(x.shape[<NUM_LIT:0>]).astype('<STR_LIT>')<EOL>if fs == fs_target:<EOL><INDENT>return x, t<EOL><DEDENT>new_length = int(x.shape[<NUM_LIT:0>]*fs_target/fs)<EOL>resampled_x, resampled_t = signal.resample(x, num=new_length, t=t)<EOL>assert resampled_x.shape == resampled_t.shape and resampled_x.shape[<NUM_LIT:... | 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 : n... | f10221:m1 |
def resample_singlechan(x, ann, fs, fs_target): | resampled_x, resampled_t = resample_sig(x, fs, fs_target)<EOL>new_sample = resample_ann(resampled_t, ann.sample)<EOL>assert ann.sample.shape == new_sample.shape<EOL>resampled_ann = Annotation(record_name=ann.record_name,<EOL>extension=ann.extension,<EOL>sample=new_sample,<EOL>symbol=ann.symbol,<EOL>subtype=ann.subtype,... | 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 t... | f10221:m2 |
def resample_multichan(xs, ann, fs, fs_target, resamp_ann_chan=<NUM_LIT:0>): | assert resamp_ann_chan < xs.shape[<NUM_LIT:1>]<EOL>lx = []<EOL>lt = None<EOL>for chan in range(xs.shape[<NUM_LIT:1>]):<EOL><INDENT>resampled_x, resampled_t = resample_sig(xs[:, chan], fs, fs_target)<EOL>lx.append(resampled_x)<EOL>if chan == resamp_ann_chan:<EOL><INDENT>lt = resampled_t<EOL><DEDENT><DEDENT>new_sample = ... | 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 ... | f10221:m3 |
def normalize_bound(sig, lb=<NUM_LIT:0>, ub=<NUM_LIT:1>): | mid = ub - (ub - lb) / <NUM_LIT:2><EOL>min_v = np.min(sig)<EOL>max_v = np.max(sig)<EOL>mid_v = max_v - (max_v - min_v) / <NUM_LIT:2><EOL>coef = (ub - lb) / (max_v - min_v)<EOL>return sig * coef - (mid_v * coef) + mid<EOL> | 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 | f10221:m4 |
def smooth(sig, window_size): | box = np.ones(window_size)/window_size<EOL>return np.convolve(sig, box, mode='<STR_LIT>')<EOL> | 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. | f10221:m5 |
def get_filter_gain(b, a, f_gain, fs): | <EOL>w, h = signal.freqz(b, a)<EOL>w_gain = f_gain * <NUM_LIT:2> * np.pi / fs<EOL>ind = np.where(w >= w_gain)[<NUM_LIT:0>][<NUM_LIT:0>]<EOL>gain = abs(h[ind])<EOL>return gain<EOL> | 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 f... | f10221:m6 |
def benchmark_mitdb(detector, verbose=False, print_results=False): | record_list = get_record_list('<STR_LIT>')<EOL>n_records = len(record_list)<EOL>args = zip(record_list, n_records * [detector], n_records * [verbose])<EOL>with Pool(cpu_count() - <NUM_LIT:1>) as p:<EOL><INDENT>comparitors = p.starmap(benchmark_mitdb_record, args)<EOL><DEDENT>specificity = np.mean([c.specificity for c i... | 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
---... | f10223:m1 |
def benchmark_mitdb_record(rec, detector, verbose): | sig, fields = rdsamp(rec, pb_dir='<STR_LIT>', channels=[<NUM_LIT:0>])<EOL>ann_ref = rdann(rec, pb_dir='<STR_LIT>', extension='<STR_LIT>')<EOL>qrs_inds = detector(sig=sig[:,<NUM_LIT:0>], fs=fields['<STR_LIT>'], verbose=verbose)<EOL>comparitor = compare_annotations(ref_sample=ann_ref.sample[<NUM_LIT:1>:],<EOL>test_sample... | Benchmark a single mitdb record | f10223:m2 |
def _calc_stats(self): | <EOL>self.matched_ref_inds = np.where(self.matching_sample_nums != -<NUM_LIT:1>)[<NUM_LIT:0>]<EOL>self.unmatched_ref_inds = np.where(self.matching_sample_nums == -<NUM_LIT:1>)[<NUM_LIT:0>]<EOL>self.matched_test_inds = self.matching_sample_nums[<EOL>self.matching_sample_nums != -<NUM_LIT:1>]<EOL>self.unmatched_test_inds... | 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 | f10223:c0:m1 |
def compare(self): | """<STR_LIT>"""<EOL>test_samp_num = <NUM_LIT:0><EOL>ref_samp_num = <NUM_LIT:0><EOL>while ref_samp_num < self.n_ref and test_samp_num < self.n_test:<EOL><INDENT>closest_samp_num, smallest_samp_diff = (<EOL>self._get_closest_samp_num(ref_samp_num, test_samp_num))<EOL>if ref_samp_num < self.n_ref - <NUM_LIT:1>:<EOL><INDEN... | Main comparison function | f10223:c0:m2 |
def print_summary(self): | <EOL>self.tp = len(self.matched_ref_inds)<EOL>self.fp = self.n_test - self.tp<EOL>self.fn = self.n_ref - self.tp<EOL>self.specificity = self.tp / self.n_ref<EOL>self.positive_predictivity = self.tp / self.n_test<EOL>self.false_positive_rate = self.fp / self.n_test<EOL>print('<STR_LIT>'<EOL>% (self.n_ref, self.n_test))<... | Print summary metrics of the annotation comparisons. | f10223:c0:m4 |
def plot(self, sig_style='<STR_LIT>', title=None, figsize=None,<EOL>return_fig=False): | fig = plt.figure(figsize=figsize)<EOL>ax = fig.add_subplot(<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>)<EOL>legend = ['<STR_LIT>',<EOL>'<STR_LIT>' % (self.tp, self.n_ref),<EOL>'<STR_LIT>' % (self.fn, self.n_ref),<EOL>'<STR_LIT>' % (self.tp, self.n_test),<EOL>'<STR_LIT>' % (self.fp, self.n_test)<EOL>]<EOL>if self.signal is no... | 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.
... | f10223:c0:m5 |
def xqrs_detect(sig, fs, sampfrom=<NUM_LIT:0>, sampto='<STR_LIT:end>', conf=None,<EOL>learn=True, verbose=True): | xqrs = XQRS(sig=sig, fs=fs, conf=conf)<EOL>xqrs.detect(sampfrom=sampfrom, sampto=sampto, verbose=verbose)<EOL>return xqrs.qrs_inds<EOL> | 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 samp... | f10224:m0 |
def gqrs_detect(sig=None, fs=None, d_sig=None, adc_gain=None, adc_zero=None,<EOL>threshold=<NUM_LIT:1.0>, hr=<NUM_LIT>, RRdelta=<NUM_LIT>, RRmin=<NUM_LIT>, RRmax=<NUM_LIT>,<EOL>QS=<NUM_LIT>, QT=<NUM_LIT>, RTmin=<NUM_LIT>, RTmax=<NUM_LIT>,<EOL>QRSa=<NUM_LIT>, QRSamin=<NUM_LIT>): | <EOL>if sig is not None:<EOL><INDENT>record = Record(p_signal=sig.reshape([-<NUM_LIT:1>,<NUM_LIT:1>]), fmt=['<STR_LIT>'])<EOL>record.set_d_features(do_adc=True)<EOL>d_sig = record.d_signal[:,<NUM_LIT:0>]<EOL>adc_zero = <NUM_LIT:0><EOL>adc_gain = record.adc_gain[<NUM_LIT:0>]<EOL><DEDENT>conf = GQRS.Conf(fs=fs, adc_gain=... | 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.
Par... | f10224:m2 |
def _set_conf(self): | self.rr_init = <NUM_LIT> * self.fs / self.conf.hr_init<EOL>self.rr_max = <NUM_LIT> * self.fs / self.conf.hr_min<EOL>self.rr_min = <NUM_LIT> * self.fs / self.conf.hr_max<EOL>self.qrs_width = int(self.conf.qrs_width * self.fs)<EOL>self.qrs_radius = int(self.conf.qrs_radius * self.fs)<EOL>self.qrs_thr_init = self.conf.qrs... | Set configuration parameters from the Conf object into the detector
object.
Time values are converted to samples, and amplitude values are in mV. | f10224:c0:m1 |
def _bandpass(self, fc_low=<NUM_LIT:5>, fc_high=<NUM_LIT:20>): | self.fc_low = fc_low<EOL>self.fc_high = fc_high<EOL>b, a = signal.butter(<NUM_LIT:2>, [float(fc_low) * <NUM_LIT:2> / self.fs,<EOL>float(fc_high) * <NUM_LIT:2> / self.fs], '<STR_LIT>')<EOL>self.sig_f = signal.filtfilt(b, a, self.sig[self.sampfrom:self.sampto],<EOL>axis=<NUM_LIT:0>)<EOL>self.filter_gain = get_filter_gain... | Apply a bandpass filter onto the signal, and save the filtered
signal. | f10224:c0:m2 |
def _mwi(self): | wavelet_filter = signal.ricker(self.qrs_width, <NUM_LIT:4>)<EOL>self.sig_i = signal.filtfilt(wavelet_filter, [<NUM_LIT:1>], self.sig_f,<EOL>axis=<NUM_LIT:0>) ** <NUM_LIT:2><EOL>self.mwi_gain = get_filter_gain(wavelet_filter, [<NUM_LIT:1>],<EOL>np.mean([self.fc_low, self.fc_high]), self.fs) * <NUM_LIT:2><EOL>self.transf... | Apply moving wave integration (mwi) with a ricker (Mexican hat)
wavelet onto the filtered signal, and save the square of the
integrated signal.
The width of the hat is equal to the qrs width
After integration, find all local peaks in the mwi signal. | f10224:c0:m3 |
def _learn_init_params(self, n_calib_beats=<NUM_LIT:8>): | if self.verbose:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>last_qrs_ind = -self.rr_max<EOL>qrs_inds = []<EOL>qrs_amps = []<EOL>noise_amps = []<EOL>ricker_wavelet = signal.ricker(self.qrs_radius * <NUM_LIT:2>, <NUM_LIT:4>).reshape(-<NUM_LIT:1>,<NUM_LIT:1>)<EOL>peak_inds_f = find_local_peaks(self.sig_f, self.qrs_radius)... | Find a number of consecutive beats and use them to initialize:
- recent qrs amplitude
- recent noise amplitude
- recent rr interval
- qrs detection threshold
The learning works as follows:
- Find all local maxima (largest sample within `qrs_radius`
samples) of the filtered signal.
- Inspect the local maxima until `n... | f10224:c0:m4 |
def _set_init_params(self, qrs_amp_recent, noise_amp_recent, rr_recent,<EOL>last_qrs_ind): | self.qrs_amp_recent = qrs_amp_recent<EOL>self.noise_amp_recent = noise_amp_recent<EOL>self.qrs_thr = max(<NUM_LIT>*self.qrs_amp_recent<EOL>+ <NUM_LIT>*self.noise_amp_recent,<EOL>self.qrs_thr_min * self.transform_gain)<EOL>self.rr_recent = rr_recent<EOL>self.last_qrs_ind = last_qrs_ind<EOL>self.last_qrs_peak_num = None<... | Set initial online parameters | f10224:c0:m5 |
def _set_default_init_params(self): | if self.verbose:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>qrs_thr_init = self.qrs_thr_init * self.transform_gain<EOL>qrs_thr_min = self.qrs_thr_min * self.transform_gain<EOL>qrs_amp = <NUM_LIT>/<NUM_LIT> * qrs_thr_init<EOL>noise_amp = qrs_amp / <NUM_LIT:10><EOL>rr_recent = self.rr_init<EOL>last_qrs_ind = <NUM_LIT:0><... | 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` | f10224:c0:m6 |
def _is_qrs(self, peak_num, backsearch=False): | i = self.peak_inds_i[peak_num]<EOL>if backsearch:<EOL><INDENT>qrs_thr = self.qrs_thr / <NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>qrs_thr = self.qrs_thr<EOL><DEDENT>if (i-self.last_qrs_ind > self.ref_period<EOL>and self.sig_i[i] > qrs_thr):<EOL><INDENT>if i-self.last_qrs_ind < self.t_inspect_period:<EOL><INDENT>if self.... | Check whether a peak is a qrs complex. It is classified as qrs
if it:
- Comes after the refractory period
- Passes qrs threshold
- Is not a t-wave (check it if the peak is close to the previous
qrs).
Parameters
----------
peak_num : int
The peak number of the mwi signal to be inspected
backsearch: bool, optional... | f10224:c0:m7 |
def _update_qrs(self, peak_num, backsearch=False): | i = self.peak_inds_i[peak_num]<EOL>rr_new = i - self.last_qrs_ind<EOL>if rr_new < self.rr_max:<EOL><INDENT>self.rr_recent = <NUM_LIT>*self.rr_recent + <NUM_LIT>*rr_new<EOL><DEDENT>self.qrs_inds.append(i)<EOL>self.last_qrs_ind = i<EOL>self.last_qrs_peak_num = self.peak_num<EOL>if backsearch:<EOL><INDENT>self.backsearch_... | 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 | f10224:c0:m8 |
def _is_twave(self, peak_num): | i = self.peak_inds_i[peak_num]<EOL>if self.last_qrs_ind - self.qrs_radius < <NUM_LIT:0>:<EOL><INDENT>return False<EOL><DEDENT>sig_segment = normalize((self.sig_f[i - self.qrs_radius:i]<EOL>).reshape(-<NUM_LIT:1>, <NUM_LIT:1>), axis=<NUM_LIT:0>)<EOL>last_qrs_segment = self.sig_f[self.last_qrs_ind - self.qrs_radius:<EOL>... | 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 | f10224:c0:m9 |
def _update_noise(self, peak_num): | i = self.peak_inds_i[peak_num]<EOL>self.noise_amp_recent = (<NUM_LIT>*self.noise_amp_recent<EOL>+ <NUM_LIT>*self.sig_i[i])<EOL>return<EOL> | Update live noise parameters | f10224:c0:m10 |
def _require_backsearch(self): | if self.peak_num == self.n_peaks_i-<NUM_LIT:1>:<EOL><INDENT>return False<EOL><DEDENT>next_peak_ind = self.peak_inds_i[self.peak_num + <NUM_LIT:1>]<EOL>if next_peak_ind-self.last_qrs_ind > self.rr_recent*<NUM_LIT>:<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT> | Determine whether a backsearch should be performed on prior peaks | f10224:c0:m11 |
def _backsearch(self): | if self.last_qrs_peak_num is not None:<EOL><INDENT>for peak_num in range(self.last_qrs_peak_num + <NUM_LIT:1>, self.peak_num + <NUM_LIT:1>):<EOL><INDENT>if self._is_qrs(peak_num=peak_num, backsearch=True):<EOL><INDENT>self._update_qrs(peak_num=peak_num, backsearch=True)<EOL><DEDENT><DEDENT><DEDENT> | Inspect previous peaks from the last detected qrs peak (if any),
using a lower threshold | f10224:c0:m12 |
def _run_detection(self): | if self.verbose:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>self.qrs_inds = []<EOL>self.backsearch_qrs_inds = []<EOL>for self.peak_num in range(self.n_peaks_i):<EOL><INDENT>if self._is_qrs(self.peak_num):<EOL><INDENT>self._update_qrs(self.peak_num)<EOL><DEDENT>else:<EOL><INDENT>self._update_noise(self.peak_num)<EOL><DE... | Run the qrs detection after all signals and parameters have been
configured and set. | f10224:c0:m13 |
def detect(self, sampfrom=<NUM_LIT:0>, sampto='<STR_LIT:end>', learn=True, verbose=True): | if sampfrom < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self.sampfrom = sampfrom<EOL>if sampto == '<STR_LIT:end>':<EOL><INDENT>sampto = self.sig_len<EOL><DEDENT>elif sampto > self.sig_len:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self.sampto = sampto<EOL>self.verbose = verbose<EOL>... | 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... | f10224:c0:m14 |
def detect(self, x, conf, adc_zero): | self.c = conf<EOL>self.annotations = []<EOL>self.sample_valid = False<EOL>if len(x) < <NUM_LIT:1>:<EOL><INDENT>return []<EOL><DEDENT>self.x = x<EOL>self.adc_zero = adc_zero<EOL>self.qfv = np.zeros((self.c._BUFLN), dtype="<STR_LIT>")<EOL>self.smv = np.zeros((self.c._BUFLN), dtype="<STR_LIT>")<EOL>self.v1 = <NUM_LIT:0><E... | Run detection. x is digital signal | f10224:c1:m1 |
def get_config(self): | with open(self.path) as f:<EOL><INDENT>return yaml.safe_load(f)<EOL><DEDENT> | Read config file
:returns: the configuration of path to the dict or list | f10227:c0:m1 |
def setup_external_interface(self, *args, **kwargs): | return execute(self._setup_external_interface, *args, **kwargs)<EOL> | host networking
:param public_interface(str): the public interface
:returns: None | f10228:c0:m1 |
def _setup_ntp(self): | sudo('<STR_LIT>')<EOL>sudo('<STR_LIT>')<EOL>sudo('<STR_LIT>')<EOL>sudo('<STR_LIT>')<EOL> | network time protocal (ntp) | f10228:c0:m2 |
def setup_ntp(self): | return execute(self._setup_ntp)<EOL> | Setup ntp service
:returns: None | f10228:c0:m3 |
def _set_openstack_repository(self): | if self._release() == '<STR_LIT>':<EOL><INDENT>print(red(env.host_string + '<STR_LIT>'))<EOL>sudo('<STR_LIT>')<EOL>sudo('<STR_LIT>')<EOL>sudo('<STR_LIT>')<EOL><DEDENT>print(red(env.host_string + '<STR_LIT>'))<EOL>with prefix('<STR_LIT>'):<EOL><INDENT>sudo('<STR_LIT>')<EOL><DEDENT>print(red(env.host_string + '<STR_LIT>'... | openstack packages | f10228:c0:m4 |
def set_openstack_repository(self): | return execute(self._set_openstack_repository)<EOL> | Install OpenStack repository only for trusty.
This method install cloud-archive:mitaka on trusty, when xenial using the default xenial repo.
:returns: None | f10228:c0:m5 |
def create_service_credentials(self, *args, **kwargs): | return execute(self._create_service_credentials, *args, **kwargs)<EOL> | r"""
Create the swift service credentials
:param os_password: the password of openstack `admin` user
:param os_auth_url: keystone endpoint url e.g. `http://CONTROLLER_VIP:35357/v3`
:param swift_pass: password of `swift` user
:param public_endpoint: public endpoint for swift serv... | f10229:c0:m1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.