Python library for reading electrophysiology data from Axon Binary Format (ABF) files
—
Additional functionality including file writing, filtering, stimulus waveform handling, and plotting functions. These utilities extend the core pyabf functionality for specialized use cases.
Functions for creating new ABF files from data arrays.
from pyabf import abfWriter
def writeABF1(
sweepData: np.ndarray,
filename: Union[str, pathlib.Path],
sampleRateHz: float,
units: str = 'pA'
) -> None:
"""
Write data to a new ABF1 format file.
Parameters:
- sweepData: 2D numpy array where each row is a sweep
Shape: (number_of_sweeps, points_per_sweep)
- filename: Output file path
- sampleRateHz: Data acquisition sample rate in Hz
- units: Data units (e.g., 'pA', 'mV', 'nA')
Note: Creates ABF1 format files compatible with older analysis software
"""Functions for applying digital filters to ABF data.
from pyabf import filter
def remove(abf) -> None:
"""
Remove any applied filtering from ABF object.
Parameters:
- abf: ABF object to remove filtering from
Note: Modifies the ABF object in place, returns None
"""
def gaussian(abf, sigmaMs: float = 5, channel: int = 0) -> None:
"""
Apply Gaussian smoothing filter to ABF data.
Parameters:
- abf: ABF object to filter
- sigmaMs: Filter sigma in milliseconds (controls smoothing strength)
- channel: Channel number to filter
Note: Modifies the ABF object's data in place, returns None
"""Classes and functions for working with stimulus waveforms and protocols.
from pyabf import stimulus
class Stimulus:
def __init__(self, abf, channel: int):
"""
Create stimulus waveform handler for specified channel.
Parameters:
- abf: ABF object
- channel: DAC channel number
"""
def stimulusWaveform(self, stimulusSweep: int = 0) -> np.ndarray:
"""
Generate stimulus waveform for specified sweep.
Parameters:
- stimulusSweep: Sweep number to generate waveform for
Returns:
numpy array containing the stimulus waveform
"""
def findStimulusWaveformFile(abf, channel: int = 0) -> Union[str, None]:
"""
Find the stimulus waveform file associated with an ABF.
Parameters:
- abf: ABF object
- channel: DAC channel number
Returns:
Path to stimulus file if found, None otherwise
"""
def stimulusWaveformFromFile(abf, channel: int = 0) -> Union[np.ndarray, None]:
"""
Load stimulus waveform from associated file.
Parameters:
- abf: ABF object
- channel: DAC channel number
Returns:
numpy array with stimulus waveform, or None if not found
"""Functions for converting numeric codes to human-readable names.
from pyabf import names
def getDigitizerName(digitizerNumber: int) -> str:
"""
Get digitizer name from numeric code.
Parameters:
- digitizerNumber: Numeric digitizer identifier
Returns:
Human-readable digitizer name
"""
def getTelegraphName(telegraphNumber: int) -> str:
"""
Get telegraph amplifier name from numeric code.
Parameters:
- telegraphNumber: Numeric telegraph identifier
Returns:
Human-readable telegraph amplifier name
"""
def getUserListParameterName(paramNumber: int, epochCount: int = 50) -> str:
"""
Get user list parameter name from numeric code.
Parameters:
- paramNumber: Parameter number
- epochCount: Number of epochs (default 50)
Returns:
Human-readable parameter name
"""Legacy plotting functions using matplotlib. These are marked as obsolete and should not be used in new code.
from pyabf import plot
import warnings
warnings.warn("abf.plot is obsolete and should not be used")
def sweepDataRange(
abf,
fraction: float = 1,
sweepNumber: int = 0,
channel: int = 0
) -> float:
"""
Calculate data range for sweep (DEPRECATED).
Returns magnitude of range between min and max points in sweep.
Use numpy functions directly instead.
"""
def sweeps(
abf,
sweepNumbers: Union[List[int], None] = None,
continuous: bool = False,
offsetXsec: float = 0,
**kwargs
) -> None:
"""
Plot multiple sweeps (DEPRECATED).
Create your own plotting functions using matplotlib directly.
"""import pyabf
import numpy as np
# File writing example
data = np.random.randn(10, 1000) # 10 sweeps, 1000 points each
pyabf.abfWriter.writeABF1(
sweepData=data,
filename="synthetic_data.abf",
sampleRateHz=10000,
units="pA"
)
# Signal filtering
abf = pyabf.ABF("noisy_recording.abf")
print(f"Original data shape: {abf.getAllYs().shape}")
# Apply Gaussian smoothing (modifies ABF in place)
pyabf.filter.gaussian(abf, sigmaMs=2, channel=0)
abf.setSweep(0)
print(f"Filtered sweep 0 max: {np.max(abf.sweepY):.2f}")
# Remove filtering (modifies ABF in place)
pyabf.filter.remove(abf)
# Stimulus waveform handling
stim = pyabf.stimulus.Stimulus(abf, channel=0)
waveform = stim.stimulusWaveform(stimulusSweep=0)
if waveform is not None:
print(f"Stimulus waveform length: {len(waveform)}")
# Find external stimulus file
stim_file = pyabf.stimulus.findStimulusWaveformFile(abf, channel=0)
if stim_file:
print(f"Found stimulus file: {stim_file}")
ext_waveform = pyabf.stimulus.stimulusWaveformFromFile(abf, channel=0)
# Name resolution
digitizer = pyabf.names.getDigitizerName(1)
telegraph = pyabf.names.getTelegraphName(0)
print(f"Digitizer: {digitizer}")
print(f"Telegraph: {telegraph}")
# Hardware parameter names
param_name = pyabf.names.getUserListParameterName(5)
print(f"Parameter 5: {param_name}")Advanced waveform generation capabilities for creating custom stimulus protocols.
from pyabf import waveform
class Epoch:
"""
Represents a single epoch in a stimulus waveform.
"""
@property
def epochLetter(self) -> str:
"""Single letter identifier for the epoch type."""
@property
def epochTypeStr(self) -> str:
"""Human-readable epoch type description."""
class EpochSweepWaveform:
"""
Container for waveform data needed to generate stimulus for a single sweep.
"""
def __init__(self):
"""Initialize empty epoch sweep waveform."""
def addEpoch(
self,
pt1: int, pt2: int,
level: float,
epochType: int,
pulseWidth: float,
pulsePeriod: float,
digitalState: int = 0
) -> None:
"""
Add an epoch to the waveform.
Parameters:
- pt1, pt2: Start and end points for the epoch
- level: Amplitude level for this epoch
- epochType: Type of epoch (step, ramp, pulse, etc.)
- pulseWidth: Width of pulses in this epoch
- pulsePeriod: Period between pulses
- digitalState: Digital output state
"""
def getWaveform(self) -> np.ndarray:
"""
Generate the complete waveform array.
Returns:
numpy array containing the stimulus waveform
"""
def getDigitalWaveform(self, digitalChannel: int) -> np.ndarray:
"""
Generate digital output waveform for specified channel.
Parameters:
- digitalChannel: Digital channel number
Returns:
numpy array of digital states (0 or 1)
"""# Always specify appropriate units
data_pA = measurement_data * 1e12 # Convert to pA
pyabf.abfWriter.writeABF1(data_pA, "output.abf", 20000, units="pA")
# For voltage data
data_mV = voltage_data * 1000 # Convert to mV
pyabf.abfWriter.writeABF1(data_mV, "voltage.abf", 10000, units="mV")# Apply conservative filtering to avoid distorting signals
# Sigma of 1-2 ms is typically appropriate for most recordings
filtered_abf = pyabf.filter.gaussian(abf, sigmaMs=1.5)
# Always keep a reference to the original unfiltered data
original_abf = pyabf.ABF("data.abf") # Reload if neededInstall with Tessl CLI
npx tessl i tessl/pypi-pyabf