ionique
Modules
ionique.core
adaptation from “core.py” by Jacob Scheriber https://github.com/jmschrei/PyPore
This holds the core data types which may be abstracted in many different applications. This module defines a tree-based framework for representing, parsing, and annotating segments of ionic current data.
- class ionique.core.AbstractSegmentTree
Bases:
object
Class for managing hierarchical segments.
This class supports a tree structure where each segment can contain multiple child segments, enabling recursive parsing and analysis of nested data. It provides utilities to manage relationships between segments, apply parsers, and extract subsegments by rank.
- __init__() None
Initialize the segment
- add_child(child: AnySegment) None
Add a single child
- add_children(children: list[AnySegment]) None
Add multiple children if: 1. Child position is the within parent’s segment. 2. The length of the child’s segment is > 0 3. There is no overlap between consecutive children
Or add children with no check
- children: list[AnySegment]
- clear_children()
Clear the list of children
- climb_to_rank(rank: str) AnySegment | None
Go up and find the segment with the specified rank :return: segment
- end: int | None
- get_feature(name: str)
Gets the ‘name’ feature of the current segment or its parent
- get_top_parent() AnySegment
Recursively go up and find top most parent :return: parent
- property n: int
Get the length of the segment :return: len(segment)
- parent: AnySegment | None
- parse(parser, newrank: str, at_child_rank: str | None = None, **kwargs) bool
Parses the data in the segment or at a particular rank of child segments into children segments with a new rank.
- Parameters:
parser (Parser) – A parser object with a parse method and required input attributes.
newrank (str) – Rank to assign to the newly created child segments.
at_child_rank (str or None) – Determines whether to traverse the children tree down to a given rank.
kwargs – Additional arguments to pass to the parser.
- Returns:
True if parsing was successful, otherwise raises an exception.
- Return type:
bool
- rank: str
- property relative_end: int
Get end position relative to parent segment :return: end position
- property relative_slice: ndarray
Slice the array to get the data between end-start segment :return: sliced np array
- property relative_start: int
Get the start position relative to parent segment :return: start position
- property slice: ndarray
Slice the array to get the data between start-end segment :return: sliced np array
- start: int | None
- traverse_to_rank(rank: str) list
Traverse the tree rank and get the list of the segments of the rank :param: rank :return: list of segments
- class ionique.core.MetaSegment(start: int, end: int, parent: AnySegment | None = None, rank: str | None = None, unique_features: dict | None = {}, **kwargs)
Bases:
AbstractSegmentTree
The metadata on an abstract segment of ionic current. All information about a segment can be loaded, without the expectation of the array of floats.
- __init__(start: int, end: int, parent: AnySegment | None = None, rank: str | None = None, unique_features: dict | None = {}, **kwargs)
- Parameters:
start (int) – Start index of the segment.
end (int) – End index of the segment.
parent (AbstractSegmentTree or None) – Parent segment in the tree (optional).
rank (str or None) – Rank identifier for this segment (optional).
unique_features (dict) – Dictionary of metadata features.
- property current
Get the current data of the segment if the segment correlates to the file :return: current
- delete()
Delete itself. There are no arrays with which to delete references for.
- property duration: float
Get the duration of the segment = start - end :return: duration
- classmethod from_json(filename=None, in_json=None)
Read in a metasegment from a JSON and return a metasegment object. Either pass in a file which has a segment stored, or an actual JSON object.
- property max
Calculate the maximum value of the current array.
- Returns:
Maximum value of the current array.
- Return type:
float
- property mean
Calculate the mean of the current array.
- Returns:
Mean value of the current array.
- Return type:
float
- property min
Calculate the minimum value of the current array.
- Returns:
Minimum value of the current array.
- Return type:
float
- property std
Calculate the standard deviation of the current array.
- Returns:
Standard deviation of the current array.
- Return type:
float
- property time
Get the time data of the segment if the corresponding rank is in file :return: time
- to_dict()
Return a dict representation of the metadata, usually used prior to converting the dict to a JSON.
- to_json(filename=None)
Return a JSON representation of this, by reporting the important metadata.
- to_meta()
Kept to allow for error handling, but since it’s already a metasegment it won’t actually do anything.
- unique_features
- class ionique.core.Segment(current, **kwargs)
Bases:
AbstractSegmentTree
A segment of ionic current, and methods relevant for collecting metadata. The ionic current is expected to be passed as a numpy array of floats. Metadata methods (mean, std..) are decorated as properties to reduce overall computational time, making them calculated on the fly rather than during analysis.
- __init__(current, **kwargs)
The segment must have a list of ionic current, of which it stores some statistics about. It may also take in as many keyword arguments as needed, such as start time or duration if already known. Cannot override statistical measurements. :param current: Numpy array of current data points. :type current: np.ndarray :param kwargs: Additional attributes like ‘start’, ‘end’, ‘rank’, etc.
- children: list[AnySegment]
- delete()
Deleting this segment requires deleting its reference to the ionic current array, and then deleting itself.
- end: int | None
- classmethod from_json(filename=None, json=None)
Read in a segment from a JSON and return a metasegment object. Either pass in a file which has a segment stored, or an actual JSON object.
- property max
Calculate the maximum value of the current array.
- Returns:
Maximum value of the current array.
- Return type:
float
- property mean
Calculate the mean of the current array.
- Returns:
Mean value of the current array.
- Return type:
float
- property min
Calculate the minimum value of the current array.
- Returns:
Minimum value of the current array.
- Return type:
float
- property n
Get the number of elements in the current array.
- Returns:
Number of elements in the current array.
- Return type:
int
- parent: AnySegment | None
- rank: str
- scale(sampling_freq)
Rescale all of the values to go from samples to seconds.
- start: int | None
- property std
Calculate the standard deviation of the current array.
- Returns:
Standard deviation of the current array.
- Return type:
float
- to_dict()
Return a dict representation of the metadata, usually used prior to converting the dict to a JSON.
- to_json(filename=None)
Return a JSON representation of this, by reporting the important metadata.
- to_meta()
Convert from a segment to a ‘metasegment’, which stores only metadata about the segment and not the full array of ionic current.
- ionique.core.ignored(*exceptions)
Replace the “try, except: pass” paradigm by replacing those three lines with a single line. Taken from the latest 3.4 python update push by Raymond Hettinger, see: http://hg.python.org/cpython/rev/406b47c64480
ionique.cparsers
This contains cython implementations of ionic current parsers which are in parsers.py. Currently the only parser is StatSplit, which is implemented as FastStatSplit.
- class ionique.cparsers.FastStatSplit
Bases:
object
A cython implementation of the segmenter written by Kevin Karplus. Sped up approximately 50-100x compared to the Python implementation depending on parameters.
- __init__(*args, **kwargs)
- best_single_split(current)
Wrapper for a single call to _best_single_split. It will find the single best split in a series of current, and return the index of that split. Returns a tuple of ( gain, index ) where gain is the gain in variance by splitting there, and index is the index at which the split should occur in the current array.
- min_gain
- parse(current)
Wrapper function for the segmentation, which is implemented in cython.
- parse_meta(current)
Wrapper function for the segmentation, which is implemented in cython. returns meta segments (no current array)
- score_samples(current, no_split=False)
Return a series of lists scoring each sample. However, this isn’t just scoring each sample once. Every time a split is detected, it will return a new list with newly scored samples. In essence, it returns one list per scan of the current using the recursive method.
- ionique.cparsers.pairwise(iterable)
ionique.datatypes
Data structure definitions and session file management for analysis.
- class ionique.datatypes.SessionFileManager(*args, **kwargs)
Bases:
MetaSegment
Singleton-based session manager for hierarchical data.
This class inherits from MetaSegment and uses the Singleton metaclass to ensure only one instance exists during a given session. It serves as the root segment for a data analysis session and is responsible for managing metadata and registered “affectors” (i.e., objects that modify or interact with the session).
- __init__() None
Initialize the session manager.
Sets the session start time and prepares the affector log structure.
- add_child(child: AnySegment) None
Add a single child segment to the session’s hierarchy.
- Parameters:
child (AnySegment) – The segment to be added as a child.
- add_children(children: list[AnySegment]) None
Add multiple child segments to the session.
- Parameters:
children (list[AnySegment]) – A list of segments to be added as children.
- rank: str = 'root'
- register_affector(affector)
Register an affector object that influences the session data.
Records metadata including class name, string representation, and timestamp, and logs the event with a unique identifier.
- Parameters:
affector (object) – An object that modifies or interacts with the session.
- Returns:
A UUID string uniquely identifying the registered affector.
- Return type:
str
- unique_features
- class ionique.datatypes.TraceFile(current: ndarray, voltage=None, rank='file', parent=None, unique_features: dict = {}, metadata: dict = {})
Bases:
Segment
Data structure for representing a single trace file with current and optional voltage information.
This class inherits from Segment and encapsulates current and voltage data. It sets up segment metadata, defines parent-child hierarchy, and optionally initializes child segments based on voltage steps.
Typical usage includes assigning metadata and organizing hierarchical data structures for downstream processing or visualization.
- __init__(current: ndarray, voltage=None, rank='file', parent=None, unique_features: dict = {}, metadata: dict = {})
If voltage steps are provided, corresponding child segments of rank “vstep” are created.
- Parameters:
current (numpy.ndarray) – current array.
voltage (list[tuple[tuple[int, int], float]] or None) – Optional list of tuples containing (start, end) index pairs and voltage values. Used to create child segments for each voltage step.
rank (str) – Segment rank label, defaults to “file”.
parent (Segment or None) – Optional parent segment to which this trace belongs.
unique_features (dict) – Dictionary of metadata such as sampling frequency.
metadata (dict) – Additional metadata.
- children: list[AnySegment]
- delete()
Delete the current object, removing it from its parent
- end: int | None
- parent: AnySegment | None
- plot(rank, axes, downsample_per_rank, color_per_rank)
Method for plotting
- rank: str
- start: int | None
ionique.io
Input/output utilities for data files.
This module provides an interface for loading, parsing, and preprocessing signal data from various file formats (e.g., .edh, .opt, .abf, .dat, .xml). It defines a base reader class and concrete implementations that handle format-specific logic, metadata extraction, data alignment, and optional preprocessing steps.
This module is central to converting raw experimental data into analyzable form.
- class ionique.io.AbstractFileReader
Bases:
object
An abstract class for reading various data files (.abf, .edh, .mat, .opt, .xml) This class defines the structure for file readers
- __init__()
- accepted_keywords = []
- current_multiplier: float = 1.0
- ext = '___'
- read(filename: str, **kwargs)
Read a datafile or series of files. Files are identified according to their extension. Data formats that come with a header file must be referred to by the header file. If inheriting from the AbstractFileReader class, do not override this function; instead, create a custom _read method.
- Parameters:
filename – file name or list of file names, typically
given as a string or PathLike object. :type filename: str or os.PathLike or list[str] or list[os.PathLike] :param **kwargs: keyword arguments passed directly to the file reader class that matches the data format. :return: [metadata, current, etc.. ]. If the input “filename” is a list, this function returns a generator object that yields the output of _read() for every file in the input list. :rtype: tuple[dict,np.ndarray [,np.ndarray or tuple[slice,np.float32]]]
- voltage_multiplier: float = 1.0
- class ionique.io.EDHReader(edh_filename, voltage_compress=False, n_remove=0, downsample=1, prefilter=None)
Bases:
AbstractFileReader
Reader class for loading .edh data files and their associated current data.
This class parses the .edh header file and automatically loads the corresponding signal data (either from .abf or .dat files in the same directory). It extracts metadata, converts raw current and voltage data to SI units, and supports optional preprocessing steps such as voltage step segmentation, downsampling, and signal filtering.
- __init__(edh_filename, voltage_compress=False, n_remove=0, downsample=1, prefilter=None)
Initialize the EDHReader and load signal data from associated files.
- Parameters:
edh_filename (str) – Path to the .edh header file.
voltage_compress (bool) – If True, splits signal into segments based on voltage steps.
n_remove (int) – Number of samples to remove from the beginning of each voltage step.
downsample (int) – Downsampling factor to reduce data size.
prefilter (callable or None) – Callable to apply preprocessing to the current signal.
- accepted_keywords = ['voltage_compress', 'n_remove', 'downsample', 'prefilter']
- current_multiplier: float = 1e-09
- ext = '.edh'
- voltage_multiplier: float = 0.001
- class ionique.io.OPTReader(opt_filename: str, voltage_compress=False, n_remove=0, downsample=1, prefilter=None)
Bases:
AbstractFileReader
Reader for .opt data files with corresponding XML or _volt.opt metadata.
This class reads current data from .opt files and attempts to extract or reconstruct corresponding voltage data using associated .xml or _volt.opt files found in the same directory. It handles metadata extraction, signal preprocessing, voltage alignment, and segment compression based on voltage steps.
Supported XML structures include both standard HWtiming_cap_step formats and timestamp-based custom formats.
- __init__(opt_filename: str, voltage_compress=False, n_remove=0, downsample=1, prefilter=None)
Initialize the OPTReader instance and load corresponding files.
- Parameters:
opt_filename (str) – Path to the .opt header file.
voltage_compress (bool) – If True, splits signal into segments based on voltage steps.
n_remove (int) – Number of samples to remove from the beginning of each voltage step.
downsample (int) – Downsampling factor to reduce data size.
prefilter (callable or None) – Callable to apply preprocessing to the current signal.
- accepted_keywords = ['voltage_compress', 'n_remove', 'downsample', 'prefilter']
- current_multiplier: float = 1000000000.0
- ext = '.opt'
- find_peaks_in_segment(current_data, start_index, end_index)
Apply “find_peaks” on a segment of the current data and return the indices of the found peak
- find_peaks_slide_window(current, start_index, window_shift_duration=0.002, sampling_frequency=250000, sign='negative')
Find peaks in the current every time the voltage changes. The search for the peaks happens in the window of the timestamp 0.02 seconds.
- process_custom_xml()
Processes the custom XML file to extract voltage data, align the voltage waveform with the current, and detect peaks in the current signal every time the voltage changes.
ionique.parsers
Parser module for event and state segmentation in current recordings. This module provides a framework for parsing current trace data. It includes an abstract base Parser class and multiple concrete parser implementations for detecting spikes, noise, square pulses, and other event structures in ionic current signals.
Some of the parsers and the parser base class were adapted from the PyPore Package by Jacob Schreiber and Kevin Karplus (https://github.com/jmschrei/PyPore)
- class ionique.parsers.AutoSquareParser(threshold_baseline=0.7, expected_conductance=1.9, conductance_tolerance=1.2, wrap_padding: int = 50, rules=[])
Bases:
Parser
Class for building a straightforward pipeline of data analysis to make it reusable with customized parameters
- __init__(threshold_baseline=0.7, expected_conductance=1.9, conductance_tolerance=1.2, wrap_padding: int = 50, rules=[])
Initialize a Parser instance
- parse(current, eff_sampling_freq, voltage)
Takes in a current segment, and returns a list of segment objects
- Parameters:
kwargs (dict) – Keyword arguments containing the data, such as current
- Returns:
A list of tuples representing the start and end indices of the segment and an empty dictionary.
- Return type:
list[tuple]
- required_parent_attributes: list[str] = ['current', 'eff_sampling_freq', 'voltage']
- class ionique.parsers.FilterDerivativeSegmenter(low_threshold=1, high_threshold=2, cutoff_freq=1000.0, sampling_freq=100000.0)
Bases:
Parser
This parser will segment an event using a filter-derivative method. It will first apply a bessel filter at a certain cutoff to the current, then it will take the derivative of that, and segment when the derivative passes a threshold.
- __init__(low_threshold=1, high_threshold=2, cutoff_freq=1000.0, sampling_freq=100000.0)
Initialize a Parser instance
- parse(current)
Apply the filter-derivative method to filter the ionic current.
- set_params()
- Returns:
- class ionique.parsers.IVCurveAnalyzer(current, parent_segment, sampling_frequency, method='simple')
Bases:
Parser
THIS CLASS IS NOT IMPLEMENTED YET. DO NOT USE. Check for at Least Two Voltage Steps: confirm that the segment has at least two voltage steps.
Divide into Voltage Segments: separate data into voltage segments.
Call IVAnalyzer on Parent Segment: compute the mean and std of the current in each voltage segment.
Return an Array of (voltage: (imean, istd)) pair:
Also mean and std should be calulated in two ways
- __init__(current, parent_segment, sampling_frequency, method='simple')
Initialize a Parser instance
- analyze()
Analyze each voltage step in a parent segment
- class ionique.parsers.IVCurveParser(voltage)
Bases:
object
THIS CLASS IS NOT IMPLEMENTED YET! DO NOT USE. The class handles:
Identifies a file where an IV curve is recorded based on the pattern.
Here, the goal is to feed the voltage information to a module and have it search and do pattern matching to find one of these possibilities. .This can be a parser that accepts voltage array or compressed voltage as one of the inputs.
- __init__(voltage)
- parse()
Searches for a pattern in the voltage data to identify IV. If none exists, the given datafile does not contain IV curves. If one or multiple IV curves are found, it returns start and end regions of each of them. Returns: list of indices: start and end for each deteced IV curve
- class ionique.parsers.MemoryParse(starts, ends)
Bases:
object
A parser based on being fed previous split points, and splitting a raw file based those splits. Used predominately when loading previous split points from the database cache, to reconstruct a parsed file from “memory.
- __init__(starts, ends)
- Parameters:
starts (list[int]) – A list of start indices for each segment.
ends (list[int]) – A list of end indices corresponding to each start index.
- parse(current)
- class ionique.parsers.NoiseFilterParser(noise_threshold=60, detect_noise=True)
Bases:
Parser
This unit is a parser subclass. when invoked on a segment (whole file or subsegment), it identifies the areas where bad things happened, and areas where the data is clean. Examples of bad things include high noise (60Hz noise from opening the cage), membrane rupture, and membrane formation attempts. it produces children from the good regions of the data and ignore the bad regions.
- __init__(noise_threshold=60, detect_noise=True)
Initialize a Parser instance
- parse(data, segment_start=0, segment_end=None)
Takes in a current segment, and returns a list of segment objects
- Parameters:
kwargs (dict) – Keyword arguments containing the data, such as current
- Returns:
A list of tuples representing the start and end indices of the segment and an empty dictionary.
- Return type:
list[tuple]
- class ionique.parsers.Parser
Bases:
ABC
This class defines the interface and shared utility methods for parser implementations. Parsers are used to segment ionic current data into structured regions of interest (events).
Subclasses should implement the parse method and define any additional logic required to detect features in the data.
- abstract __init__()
Initialize a Parser instance
- classmethod from_json(_json)
Critical: Not implemented yet, figure out how to make this work in pythion
- classmethod get_init_params()
Get the initialization parameters of the parser class.
- Returns:
A dictionary of initialization parameters, default None.
- Return type:
dict or None
- classmethod get_name()
Get the name of the parser class :return: The name of the class. :rtype: str
- classmethod get_process_inputs()
- classmethod get_process_outputs()
Get the outputs generated by processing
- Returns:
A list of outputs generated by parse method
- Return type:
list or None
- get_required_parent_attributes()
Get the list of required attributes from the parent segment
- Returns:
A list of required parent attributes
- Return type:
list[str]
- parse(**kwargs)
Takes in a current segment, and returns a list of segment objects
- Parameters:
kwargs (dict) – Keyword arguments containing the data, such as current
- Returns:
A list of tuples representing the start and end indices of the segment and an empty dictionary.
- Return type:
list[tuple]
- required_parent_attributes: list[str] = ['current']
- set_params(param_dict)
Updates each paramater presented in the GUI to the value input in the lineEdit corresponding to that value. :param param_dict: A dictionary :type param_dict: dict
- to_dict()
Convert the parser’s attributes to a dictionary.
- Returns:
A dictionary representation of the parser’s attributes.
- Return type:
dict
- to_json(filename=False)
Convert the parser’s attributes to a JSON string.
- Parameters:
filename (str, default bool) – If filename, it writes the JSON string to the specified file.
- Returns:
A dictionary representation of the parser’s attributes.
- Return type:
str
- class ionique.parsers.SpeedyStatSplit(sampling_freq, min_width=100, max_width=1000000, window_width=10000, min_gain_per_sample=None, false_positive_rate=None, prior_segments_per_second=None, cutoff_freq=None)
Bases:
Parser
A parser wrapper for the Cython-accelerated FastStatSplit algorithm.
See cparsers.pyx FastStatSplit for full documentation. This is just a wrapper for the cyton implementation to add a GUI.
- __init__(sampling_freq, min_width=100, max_width=1000000, window_width=10000, min_gain_per_sample=None, false_positive_rate=None, prior_segments_per_second=None, cutoff_freq=None)
Initialize the SpeedyStatSplit instance
- Parameters:
sampling_freq (int) – The sampling frequency of the data
min_width (int, optional) – Minimum width of a segment, default=100
max_width (int, optional) – Maximum width of a segment, default=1000000.
window_width (int, optional) – Width of the window, defaults to 10000.
min_gain_per_sample (float or None, optional) – Minimum gain per sample, default=None
false_positive_rate (float or None, optional) – Expected false positive rate , default=None
prior_segments_per_second (float or None, optional) – Prior number of segments per second, default=None.
cutoff_freq (float or None, optional) – Cutoff frequency for filtering, default=None
- best_single_split(current)
Determine the best single split point in the current data
- Parameters:
current (numpy.ndarray) – The current data to be analyzed.
- Returns:
The best split point
- Return type:
int or None
- parse(current)
Parse the current data to detect segments using the FastStatSplit
- Parameters:
current (numpy.ndarray) – The current data to be parsed
- Returns:
A list of detected segments
- Return type:
- parse_meta(current)
Parse the current data and extract meta information
- Parameters:
current (numpy.ndarray) – The current data to be parsed.
- set_params()
Set the parameters
- uiTemplate = [('sampling_freq', 'spin', {'bounds': [0, None], 'dec': True, 'siPrefix': True, 'step': 1, 'suffix': 'Hz', 'value': 200000}), ('min_width', 'spin', {'dec': True, 'int': True, 'min': 2, 'step': 1, 'value': 100}), ('max_width', 'spin', {'dec': True, 'int': True, 'step': 1, 'value': 1000000}), ('window_width', 'spin', {'dec': True, 'int': True, 'step': 1, 'value': 10000}), ('cutoff_freq', 'spin', {'hidden': True})]
- class ionique.parsers.SpikeParser(height=None, threshold=None, distance=None, prominence=None, prominence_snr=None, width=None, wlen=None, rel_height: float = 0.5, plateu_size=None, fractional: bool = True)
Bases:
Parser
A parser for detecting spike-like events in ionic current data.
This parser wraps scipy.signal.find_peaks, supporting thresholds for features like peak height, prominence, and width. It computes event characteristics such as dwell time, relative prominence, and peak positions.
- __init__(height=None, threshold=None, distance=None, prominence=None, prominence_snr=None, width=None, wlen=None, rel_height: float = 0.5, plateu_size=None, fractional: bool = True) None
Initialize the SpikeParser.
- Parameters:
height (float or tuple or None) – Minimum spike height.
threshold (float or tuple or None) – Minimum vertical threshold.
distance (float or tuple or None) – Minimum horizontal distance between peaks.
prominence (float or tuple or None) – Minimum peak prominence.
prominence_snr (tuple or None) – Alternative to prominence, specified as a tuple of signal-to-noise (SNR) ratios.
width (float or tuple or None) – Full width at half maximum of the peak.
wlen (float or None) – Width of the window used to calculate prominence.
rel_height (float) – Relative height used in width calculation (range 0 to 1).
plateu_size (float or None) – Minimum length of a flat-topped peak.
fractional (bool) – Whether to interpret height, prominence, etc., as a fraction of the signal mean.
- parse(current, sampling_freq, mean, std, start)
Takes in a current segment, and returns a list of segment objects
- Parameters:
kwargs (dict) – Keyword arguments containing the data, such as current
- Returns:
A list of tuples representing the start and end indices of the segment and an empty dictionary.
- Return type:
list[tuple]
- required_parent_attributes: list[str] = ['current', 'sampling_freq', 'mean', 'start', 'std']
- class ionique.parsers.lambda_event_parser(threshold=90, rules=None)
Bases:
Parser
A simple rule-based parser which defines events as a sequential series of points which are below a certain threshold, then filtered based on other critereon such as total time or minimum current. Rules can be passed in at initiation, or set later, but must be a lambda function takes in a PreEvent object and performs some boolean operation.
- __init__(threshold=90, rules=None)
- Parameters:
threshold (float) – The threshold for detecting events (e.g., current < threshold).
rules (list[callable] or None) – A list of lambda functions that accept an event and return a bool.
- parse(current)
Perform a large capture of events by creating a boolean mask for when the current is below a threshold, then detecting the edges in those masks, and using the edges to partitition the sample. The events are then filtered before being returned.
- set_params()
Read in the data from the GUI and use it to customize the rules or threshold of the parser.
- ionique.parsers.pairwise(iterable)
s -> (s0,s1), (s1,s2), (s2, s3), …
- Parameters:
iterable
- Returns:
- class ionique.parsers.snakebase_parser(threshold=1.5)
Bases:
Parser
A simple parser based on dividing when the peak-to-peak amplitude of a wave exceeds a certain threshold.
- __init__(threshold=1.5)
Initialize a Parser instance
- parse(current)
Takes in a current segment, and returns a list of segment objects
- Parameters:
kwargs (dict) – Keyword arguments containing the data, such as current
- Returns:
A list of tuples representing the start and end indices of the segment and an empty dictionary.
- Return type:
list[tuple]
- set_params()
Updates each paramater presented in the GUI to the value input in the lineEdit corresponding to that value. :param param_dict: A dictionary :type param_dict: dict
ionique.utils
Signal Processing and Data Extraction Utilities
This module provides a set of utility functions and classes designed for use in signal processing workflows.
These tools are intended for both internal processing and external use cases such as analysis pipelines and API integrations.
- class ionique.utils.Filter(cutoff_frequency: float, filter_type: Literal['lowpass', 'highpass', 'bandpass', 'bandstop'], filter_method: Literal['butter', 'bessel'] = 'butter', order: int = 2, bidirectional: bool = True, sampling_frequency: float | None = None)
Bases:
object
This class allows a user to apply low-pass, high-pass, band-pass, or band-stop filters using standard filter types (Butterworth or Bessel). Filters are implemented using second-order sections (SOS) for numerical stability and can be applied in either forward-only or bidirectional mode.
- Parameters:
cutoff_frequency (float or list[float]) – The cutoff frequency or frequency band for the filter in Hz. For band filters, provide the band center or list of [low, high] values.
filter_type (Literal["lowpass", "highpass", "bandpass", "bandstop"]) – The type of filter to apply. Options are “lowpass”, “highpass”, “bandpass”, or “bandstop”.
filter_method (Literal["butter", "bessel"]) – The filter method. Supported options: “butter” (Butterworth), “bessel”. Defaults to “butter”.
order (int) – The order of the filter. Must be >= 1. Defaults to 2.
bidirectional (bool) – If True, applies filtering forward and backward using sosfiltfilt. If False, uses causal sosfilt. Defaults to True.
sampling_frequency (float, optional) – Sampling frequency of the signal in Hz.
- __init__(cutoff_frequency: float, filter_type: Literal['lowpass', 'highpass', 'bandpass', 'bandstop'], filter_method: Literal['butter', 'bessel'] = 'butter', order: int = 2, bidirectional: bool = True, sampling_frequency: float | None = None) None
- bidirectional: bool = True
- cutoff_frequency: float
- filter_method: Literal['butter', 'bessel'] = 'butter'
- filter_type: Literal['lowpass', 'highpass', 'bandpass', 'bandstop']
- order: int = 2
- sampling_frequency: float = None
- class ionique.utils.Singleton(*args, **kwargs)
Bases:
type
Generic singleton metaclass.
This metaclass ensures the same return every time the class is instanced.
- __init__(*args, **kwargs)
Class initialization
- Parameters:
args – Arguments for the class
kwargs – Keyword arguments for the class
- class ionique.utils.Trimmer(samples_to_remove: int, rank: str = 'vstep', newrank: str = 'vstepgap')
Bases:
object
Segment trimming utility for hierarchical signal data.
This class operates on a segment tree. It traverses segments of a given rank (e.g., “vstep”) and trims a fixed number of samples from the start of each segment. The resulting trimmed segments are added as new child segments with a specified new rank (e.g., “vstepgap”).
This is useful when initial samples of each segment include artifacts that should be excluded from analysis.
- Parameters:
samples_to_remove (int) – Number of samples to trim from the beginning of each segment.
rank (str) – The hierarchical rank of segments to target for trimming. Defaults to “vstep”.
newrank (str) – The rank name to assign to newly created trimmed child segments. Defaults to “vstepgap”.
- __init__(samples_to_remove: int, rank: str = 'vstep', newrank: str = 'vstepgap') None
- newrank: str = 'vstepgap'
- rank: str = 'vstep'
- samples_to_remove: int
- ionique.utils.extract_features(seg, bottom_rank, extractions: list[str], add_ons: dict = {}, lambdas={})
Extract features from hierarchical segments into a DataFrame.
Traverses a hierarchical segment structure down to bottom_rank, then collects feature values from each segment. Static features are retrieved via get_feature(), constants can be added via add_ons, and custom computed features can be provided through lambdas.
This is useful for generating structured datasets from annotated traces for statistical analysis or machine learning.
- Parameters:
seg (object) – The root segment or trace object containing a hierarchical structure. It must implement traverse_to_rank() and support get_feature().
bottom_rank (str) – The rank name of the lowest-level segments from which to extract features.
extractions (list[str]) – List of feature names to extract directly using get_feature() on each segment. Common examples include: ‘mean’, ‘frac’, ‘duration’, ‘baseline’, ‘current’, ‘wrap’, ‘start’.
add_ons (dict) – A dictionary of fixed key-value pairs to include as constant columns in the resulting DataFrame.
lambdas (dict) – A dictionary mapping column names to lambda functions that compute derived values from each segment.
- Returns:
A pandas DataFrame where each row corresponds to a bottom-rank segment and columns represent extracted and computed features.
- Return type:
pandas.DataFrame
- ionique.utils.si_eval(value, unit=None, return_unit=False)
Evaluate and convert a value with an SI unit prefix to its numeric base value.
This function handles both string-based and numeric values with SI (International System of Units) prefixes such as “k” (kilo), “M” (mega), “μ” (micro), etc. It multiplies the input value by the appropriate factor based on the SI prefix.
This utility is useful when parsing human-readable measurement strings or standardizing units across data pipelines that mix strings and numeric formats.
- Parameters:
value (str or float) – The value to be converted. Can be a string like “1.2 kHz” or a numeric value (int or float).
unit (str, optional) – The unit string (e.g., “kHz”, “mV”). Required only if value is a numeric type.
return_unit (bool, optional) – If True, returns a tuple containing the converted numeric value and the base unit (e.g., ‘Hz’). If False, only the numeric value is returned.
- Raises:
ValueError – If the input format is invalid or the unit is missing for numeric input.
TypeError – If the value is neither a string nor a numeric type.
- Returns:
The converted value, optionally paired with the base unit.
- Return type:
float or tuple[float, str]
- ionique.utils.split_voltage_steps(voltage: ndarray, n_remove=0, as_tuples=False)
Split a voltage signal into segments based on step changes.
This function detects changes in the voltage signal and splits it into individual segments (or steps) wherever a change in value occurs. It is useful in analyzing stepwise voltage protocols.
Optionally, a number of initial samples can be removed from each segment using the n_remove parameter. The output can either be two separate arrays of start and end indices, or a list of tuples representing each segment.
- Parameters:
voltage (numpy.ndarray) – 1D voltage signal array to be segmented.
n_remove (int) – Number of samples to remove from the start of each split. Defaults to 0.
as_tuples (bool) – If True, returns a list of (start, end) index tuples. If False, returns two arrays: start_indices and end_indices. Defaults to False.
- Raises:
ValueError – If n_remove is negative or larger than the start of the voltage changes.
- Returns:
Either: - A tuple of (start_indices, end_indices), where each is a numpy array of indices. - A list of (start, end) tuples if as_tuples=True.
- Return type:
tuple[numpy.ndarray, numpy.ndarray] or list[tuple[int, int]]