ionique.parsers
The parsers module provides event detection and signal segmentation
algorithms for ionic current data. All parsers subclass Parser and
implement a parse() method that returns boundary tuples.
Event detectors — find translocation events within voltage steps:
AutoSquareParser— square-pulse blockade detectorSpikeParser— scipy.signal.find_peaks wrapper with fractional scalinglambda_event_parser— simple threshold with rule-based filteringsnakebase_parser— peak-to-peak amplitude segmentation
Sub-state segmenters — split already-detected events into current levels:
SpeedyStatSplit— recursive variance splitting (Cython-accelerated)FilterDerivativeSegmenter— derivative threshold segmentation
Signal classification:
NoiseFilterParser— classifies clean vs noisy regions
IV analysis:
IVCurveParser— voltage protocol pattern matchingIVCurveAnalyzer— mean current per voltage level
Utilities:
ExclusionParser— excludes time regionsMemoryParse— reconstructs segments from saved boundaries
See the Parsers Guide for usage examples and parameter tuning.
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) – Original License included in “PYPORE_LICENSE.txt”.
- class ionique.parsers.AutoSquareParser(threshold_baseline=0.7, expected_conductance=1.9, conductance_tolerance=1.2, wrap_padding: int = 50, rules=[])
Bases:
ParserParser for detecting square-pulse blocking events in ionic current data.
Builds a reusable pipeline that locates downward current deflections within a voltage step using histogram-based baseline estimation and customisable filtering rules.
- Parameters:
threshold_baseline (float, optional) – Fraction of the estimated open-channel baseline below which a sample is considered part of an event. Defaults to 0.7.
expected_conductance (float, optional) – Expected open-channel conductance in nS, used to estimate the baseline current from the voltage. Defaults to 1.9.
conductance_tolerance (float, optional) – Multiplicative tolerance applied to the expected conductance when validating the event baseline. Defaults to 1.2.
wrap_padding (int, optional) – Number of samples added around each event for context storage. Defaults to 50.
rules (list[callable], optional) – Additional lambda rules used to filter detected events. Defaults to an empty list.
- __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)
Detect square-pulse blocking events in the current array.
- Parameters:
current (numpy.ndarray) – Ionic current samples for a single voltage step.
eff_sampling_freq (float) – Effective sampling frequency of the data in Hz.
voltage (float) – Voltage applied during this step, used to estimate the baseline current.
- Returns:
A list of
(start, end, unique_features)tuples for each accepted event.unique_featurescontains keysbaseline,wrap,mean, andfrac.- Return type:
- class ionique.parsers.ExclusionParser(regions: list[tuple[float, float]])
Bases:
ParserParser that outputs clean children by excluding user-specified time regions.
Regions are specified in global seconds and are subtracted from each segment to produce one or more clean sub-segments.
- Parameters:
regions (list[tuple[float, float]]) – List of
(start_sec, end_sec)pairs in global seconds to exclude.
- __init__(regions: list[tuple[float, float]])
Initialize ExclusionParser with the regions to exclude.
- parse(current, eff_sampling_freq, start=None, **kwargs)
Exclude the specified regions and return the remaining clean intervals.
- Parameters:
current (numpy.ndarray) – Ionic current samples for the segment being parsed.
eff_sampling_freq (float) – Effective sampling frequency of the data in Hz, used to convert global seconds to sample indices.
start (int or None, optional) – Absolute sample index of the segment’s start within the recording. Defaults to None (treated as 0).
**kwargs (dict) – Additional keyword arguments (unused).
- Returns:
A list of
(start, end, features)tuples for each clean interval remaining after exclusion.featurescontainsexcluded_windows_localandparent_start_sec.- Return type:
- class ionique.parsers.FilterDerivativeSegmenter(low_threshold=1, high_threshold=2, cutoff_freq=1000.0, sampling_freq=100000.0)
Bases:
ParserThis 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()
Read threshold values from the GUI and update the parser parameters.
- class ionique.parsers.IVCurveAnalyzer(current, parent_segment, sampling_frequency, method='simple')
Bases:
ParserAnalyzer for computing current statistics across IV curve voltage steps.
Confirms that a parent segment has at least two voltage steps, divides the data into per-voltage segments, and computes the mean and standard deviation of the current for each step, returning an array of
(voltage: (imean, istd))pairs.- Parameters:
current (numpy.ndarray) – The ionic current array.
parent_segment (Segment) – The parent segment containing voltage-step children.
sampling_frequency (float) – Sampling frequency of the recording in Hz.
method (str, optional) – Analysis method; either
"simple"or"extra". Defaults to"simple".
Notes
This class is not yet implemented.
- __init__(current, parent_segment, sampling_frequency, method='simple')
Initialize a Parser instance
- analyze()
Analyze each voltage step in the parent segment.
- Returns:
A dictionary mapping each voltage value to a
(imean, istd)tuple of current statistics.- Return type:
- Raises:
ValueError – If the parent segment has fewer than two voltage-step children or if an invalid method is specified.
- class ionique.parsers.IVCurveParser(voltage)
Bases:
objectParser for identifying IV curve regions in voltage data by pattern matching.
The class accepts voltage information and performs pattern matching to detect one or more of several known IV curve sweep patterns (cyclical, ramp, flip-flop) within the recording.
- Parameters:
voltage (numpy.ndarray) – The voltage array to search for IV curve patterns.
Notes
This class is not yet implemented.
- __init__(voltage)
- class ionique.parsers.MemoryParse(starts, ends)
Bases:
objectA 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)
Initialize MemoryParse with precomputed split boundaries.
- parse(current)
Reconstruct segments from previously recorded start/end positions.
- Parameters:
current (numpy.ndarray) – The ionic current array to slice into segments.
- Returns:
Segments constructed from the stored start/end pairs.
- Return type:
- class ionique.parsers.NoiseFilterParser(noise_threshold=60, detect_noise=True)
Bases:
ParserThis 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)
Identify clean and noisy regions and return MetaSegment boundaries.
- Parameters:
data (numpy.ndarray) – The ionic current array to analyse.
segment_start (int, optional) – Start index within data. Defaults to 0.
segment_end (int or None, optional) – End index within data. Defaults to len(data).
- Returns:
MetaSegments tagged with
unique_features="clean"orunique_features="noisy".- Return type:
- class ionique.parsers.Parser
Bases:
ABCThis 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.
- abstractmethod __init__()
Initialize a Parser instance
- classmethod from_json(_json)
Reconstruct a Parser instance from a JSON string or file.
- Parameters:
_json (str) – A JSON string or path to a
.jsonfile to load.- Returns:
The reconstructed parser instance, or None.
- Return type:
Parser or None
Notes
Not yet implemented.
- classmethod get_init_params()
Get the initialization parameters of the parser class.
- Returns:
A dictionary of initialization parameters, or None if not defined.
- Return type:
dict or None
- classmethod get_name()
Get the name of the parser class.
- Returns:
The name of the class.
- Return type:
- classmethod get_process_inputs()
Return the required inputs for the parse process.
- Returns:
A dictionary of parse input specifications, or None if not defined.
- Return type:
dict or None
- classmethod get_process_outputs()
Get the outputs generated by processing.
- Returns:
A list of outputs generated by the parse method, or None if not defined.
- Return type:
list or None
- get_required_parent_attributes()
Get the list of required attributes from the parent segment.
- parse(**kwargs)
Take in a current segment and return a list of segment boundary tuples.
Subclasses must implement this.
- set_params(param_dict)
Update each parameter to the value provided in the given dictionary.
- Parameters:
param_dict (dict) – A dictionary mapping parameter names to their new values.
- to_dict()
Convert the parser’s attributes to a dictionary.
- Returns:
A dictionary representation of the parser’s attributes.
- Return type:
- 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:
ParserA 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 in Hz.
min_width (int, optional) – Minimum width of a segment in samples. Defaults to 100.
max_width (int, optional) – Maximum width of a segment in samples. Defaults to 1000000.
window_width (int, optional) – Width of the sliding window in samples. Defaults to 10000.
min_gain_per_sample (float or None, optional) – Minimum gain per sample for a split to be accepted. Defaults to None.
false_positive_rate (float or None, optional) – Expected false positive rate for split detection. Defaults to None.
prior_segments_per_second (float or None, optional) – Prior number of segments per second. Defaults to None.
cutoff_freq (float or None, optional) – Cutoff frequency for optional pre-filtering. Defaults to None.
- best_single_split(current)
Determine the best single split point in the current data.
- Parameters:
current (numpy.ndarray) – The ionic current data to be analyzed.
- Returns:
The index of the best split point, or None if no split is found.
- Return type:
int or None
- parse(current)
Parse the current data to detect segments using FastStatSplit.
- Parameters:
current (numpy.ndarray) – The ionic current data to be parsed.
- Returns:
A list of
(start, end, {})tuples representing each detected segment boundary.- Return type:
- parse_meta(current)
Parse the current data and return MetaSegment objects.
- Parameters:
current (numpy.ndarray) – The ionic current data to be parsed.
- Returns:
A list of MetaSegment objects describing each detected segment.
- Return type:
- 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:
ParserA 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, optional) – Minimum spike height. Defaults to None.
threshold (float or tuple or None, optional) – Minimum vertical threshold. Defaults to None.
distance (float or tuple or None, optional) – Minimum horizontal distance between peaks. Defaults to None.
prominence (float or tuple or None, optional) – Minimum peak prominence. Defaults to None.
prominence_snr (tuple or None, optional) – Alternative to prominence, specified as a tuple of signal-to-noise (SNR) ratios. Defaults to None.
width (float or tuple or None, optional) – Full width at half maximum of the peak. Defaults to None.
wlen (float or None, optional) – Width of the window used to calculate prominence. Defaults to None.
rel_height (float, optional) – Relative height used in width calculation (range 0 to 1). Defaults to 0.5.
plateu_size (float or None, optional) – Minimum length of a flat-topped peak. Defaults to None.
fractional (bool, optional) – Whether to interpret height, prominence, etc., as a fraction of the signal mean. Defaults to True.
- parse(current, sampling_freq, mean, std, start)
Detect spike events in the current array using
scipy.signal.find_peaks.- Parameters:
current (numpy.ndarray) – Array of ionic current samples to search for peaks.
sampling_freq (float) – Sampling frequency of the data in Hz.
mean (float) – Mean current level of the parent segment, used to scale fractional parameters.
std (float) – Standard deviation of the parent segment current.
start (int) – Absolute start index of the segment within the full recording.
- Returns:
Yields
(event_start, event_end, unique_features)tuples for each detected spike, whereunique_featurescontains keys such asidx_rel,idx_abs,peak_val,deli,dwell,dt, andfrac.- Return type:
generator
- class ionique.parsers.lambda_event_parser(threshold=90, rules=None)
Bases:
ParserA 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)
Initialize the lambda_event_parser.
- 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)
Return successive overlapping pairs from an iterable.
s -> (s0,s1), (s1,s2), (s2, s3), ...- Parameters:
iterable (iterable) – The input iterable to consume pairwise.
- Returns:
An iterator of consecutive overlapping 2-tuples.
- Return type:
zip
- class ionique.parsers.snakebase_parser(threshold=1.5)
Bases:
ParserA 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)
Segment the current by detecting edges where cumulative amplitude exceeds the threshold.
- Parameters:
current (numpy.ndarray) – The ionic current array to segment.
- Returns:
Segments corresponding to regions that pass the amplitude threshold.
- Return type: