0
# Analysis Tools
1
2
Specialized analysis modules for action potential detection, membrane test analysis, and sweep-level measurements. These tools are located in the `pyabf.tools` subpackage and must be imported explicitly.
3
4
## Capabilities
5
6
### Action Potential Analysis
7
8
Functions for detecting and analyzing action potentials in electrophysiology recordings.
9
10
```python { .api }
11
from pyabf.tools import ap
12
13
def ap_points_currentSweep(
14
abf,
15
dVthresholdPos: float = 15,
16
betweenSec1: Union[float, None] = None,
17
betweenSec2: Union[float, None] = None
18
) -> List[int]:
19
"""
20
Find action potential peak indices in the current sweep.
21
22
Parameters:
23
- abf: ABF object with active sweep set
24
- dVthresholdPos: Positive threshold for AP detection (mV/ms)
25
- betweenSec1: Start time for analysis window (seconds)
26
- betweenSec2: End time for analysis window (seconds)
27
28
Returns:
29
List of data point indices where action potentials occur
30
31
Note: Call abf.setSweep() before using this function
32
"""
33
34
def ap_freq_per_sweep(abf, singleEpoch: bool = False) -> List[List[float]]:
35
"""
36
Calculate action potential frequency for each sweep.
37
38
Parameters:
39
- abf: ABF object
40
- singleEpoch: If True, analyze only first epoch of each sweep
41
42
Returns:
43
List containing [frequencies_in_bin, frequencies_first] - two lists of frequencies
44
"""
45
46
def extract_first_ap(abf, paddingMsec: float = 50) -> Union[np.ndarray, None]:
47
"""
48
Extract the first action potential with surrounding data.
49
50
Parameters:
51
- abf: ABF object with active sweep set
52
- paddingMsec: Padding around AP in milliseconds
53
54
Returns:
55
numpy array containing voltage data around the first AP, or None if no AP found
56
"""
57
```
58
59
### Membrane Test Analysis
60
61
Class for analyzing membrane properties from voltage clamp recordings.
62
63
```python { .api }
64
from pyabf.tools import memtest
65
66
class Memtest:
67
def __init__(self, abf: ABF, channel: int = 0):
68
"""
69
Initialize membrane test analysis.
70
71
Parameters:
72
- abf: ABF object containing membrane test data
73
- channel: Channel number to analyze
74
75
Note: ABF should contain voltage clamp recordings with
76
hyperpolarizing voltage steps for membrane property analysis
77
"""
78
79
@property
80
def summary(self) -> str:
81
"""
82
Generate summary of membrane test results.
83
84
Returns:
85
Multi-line string with membrane resistance, capacitance,
86
and time constant measurements
87
"""
88
89
def __repr__(self) -> str:
90
"""
91
String representation showing basic membrane properties.
92
93
Returns:
94
Formatted string with key membrane test parameters
95
"""
96
97
# Additional measurement properties on Memtest instances:
98
Ra: SweepMeasurement
99
"""Access resistance measurements. Use Ra.values for list of values (MOhm)."""
100
101
Rm: SweepMeasurement
102
"""Membrane resistance measurements. Use Rm.values for list of values (MOhm)."""
103
104
Cm: SweepMeasurement
105
"""Membrane capacitance measurements. Use Cm.values for list of values (pF)."""
106
107
tau: SweepMeasurement
108
"""Time constant measurements. Use tau.values for list of values (ms)."""
109
```
110
111
### Membrane Test Mathematical Functions
112
113
Low-level mathematical functions for membrane property calculations.
114
115
```python { .api }
116
from pyabf.tools import memtestMath
117
118
def currentSweepRamp(abf) -> Union[np.ndarray, float]:
119
"""
120
Calculate capacitance from a voltage clamp ramp.
121
122
Parameters:
123
- abf: ABF object with active sweep set
124
125
Returns:
126
Capacitance value or np.nan if calculation fails
127
128
Note: Expects a downward ramp followed by an upward ramp
129
"""
130
131
def currentSweepStep(abf) -> List[float]:
132
"""
133
Extract membrane test values from a step protocol.
134
135
Parameters:
136
- abf: ABF object with active sweep set
137
138
Returns:
139
List containing [Ih, Rm, Ra, Cm] where:
140
- Ih: Holding current (pA)
141
- Rm: Membrane resistance (MOhm)
142
- Ra: Access resistance (MOhm)
143
- Cm: Membrane capacitance (pF)
144
"""
145
```
146
147
### Signal Generation
148
149
Functions for creating synthetic electrophysiology signals.
150
151
```python { .api }
152
from pyabf.tools import generate
153
154
def generate_exp(
155
tauMs: int = 100,
156
rateHz: int = 20000,
157
filterHz: int = 2000
158
) -> np.ndarray:
159
"""
160
Generate exponential decay signal similar to EPSC/IPSC.
161
162
Parameters:
163
- tauMs: Time constant in milliseconds
164
- rateHz: Sample rate in Hz
165
- filterHz: Filter cutoff frequency in Hz
166
167
Returns:
168
numpy array with exponential decay waveform
169
"""
170
171
def generate_alpha(tauMs: int = 100, rateHz: int = 20000) -> np.ndarray:
172
"""
173
Generate alpha function signal similar to EPSP/IPSP.
174
175
Parameters:
176
- tauMs: Time constant in milliseconds
177
- rateHz: Sample rate in Hz
178
179
Returns:
180
numpy array with alpha function waveform
181
"""
182
183
class SynthSweep:
184
def __init__(
185
self,
186
sampleRate: int = 20000,
187
sweepLengthSec: int = 5,
188
voltageClamp: bool = True
189
):
190
"""
191
Create synthetic electrophysiology sweep with events and noise.
192
193
Parameters:
194
- sampleRate: Sample rate in Hz
195
- sweepLengthSec: Sweep duration in seconds
196
- voltageClamp: True for voltage clamp, False for current clamp
197
"""
198
199
def addOffset(self, offset: float) -> None:
200
"""Add DC offset to the sweep."""
201
202
def addNoise(self, magnitude: float = 3) -> None:
203
"""Add random noise to the sweep."""
204
205
def addEvent(
206
self,
207
timeSec: float = 1.23,
208
magnitude: float = 20,
209
tauMs: float = 100,
210
excitatory: bool = True
211
) -> None:
212
"""Add single synaptic event at specified time."""
213
214
def addEvents(
215
self,
216
frequencyHz: float,
217
maxMagnitude: float = 10,
218
tauMs: float = 100,
219
excitatory: bool = True,
220
AP: bool = False
221
) -> None:
222
"""Add multiple events with specified frequency."""
223
```
224
225
### Header Information Tools
226
227
Functions for displaying and formatting ABF header information.
228
229
```python { .api }
230
from pyabf.tools import abfHeaderDisplay
231
232
def standardNumpyText(data) -> str:
233
"""
234
Convert numpy array to standard string representation.
235
236
Parameters:
237
- data: numpy array or list
238
239
Returns:
240
String representation regardless of numpy version
241
"""
242
243
def abfInfoPage(abf) -> InfoPage:
244
"""
245
Create comprehensive information page for ABF object.
246
247
Parameters:
248
- abf: ABF object
249
250
Returns:
251
InfoPage object with methods for displaying ABF information
252
"""
253
254
class InfoPage:
255
def __init__(self, title: str = "PageTitle"):
256
"""
257
Container for displaying object information in multiple formats.
258
259
Parameters:
260
- title: Page title for display
261
"""
262
263
def addSection(self, name: str) -> None:
264
"""Add a new section to the information page."""
265
266
def addThing(self, name: str, value=None) -> None:
267
"""Add an item to the current section."""
268
269
def generateHTML(self, saveAs: Union[str, bool] = False) -> str:
270
"""Generate HTML representation of the information."""
271
272
def generateMarkdown(self, saveAs: Union[str, bool] = False) -> str:
273
"""Generate markdown representation of the information."""
274
275
def launchTempWebpage(self) -> None:
276
"""Launch information page in web browser."""
277
```
278
279
### Sweep-Level Analysis
280
281
Functions for analyzing data at the sweep level across multiple recordings.
282
283
```python { .api }
284
from pyabf.tools import sweep
285
286
def getMeanSweep(abf, baseline: Union[float, None] = None) -> np.ndarray:
287
"""
288
Calculate mean sweep across all sweeps in the file.
289
290
Parameters:
291
- abf: ABF object
292
- baseline: Baseline value to subtract (if None, uses first 10% of sweep)
293
294
Returns:
295
numpy array representing the mean sweep data
296
"""
297
298
class SweepMeasurement:
299
def __init__(self, sweepCount: int, name: str, abbreviation: str, units: str):
300
"""
301
Container for sweep-level measurements.
302
303
Parameters:
304
- sweepCount: Number of sweeps
305
- name: Full name of the measurement
306
- abbreviation: Short abbreviation
307
- units: Units of measurement
308
"""
309
310
@property
311
def valuesReal(self) -> List[float]:
312
"""Real (non-NaN) measurement values."""
313
314
@property
315
def mean(self) -> float:
316
"""Mean of all real values."""
317
318
@property
319
def stdev(self) -> float:
320
"""Standard deviation of all real values."""
321
322
@property
323
def stdErr(self) -> float:
324
"""Standard error of the mean."""
325
```
326
327
### Usage Examples
328
329
```python
330
import pyabf
331
from pyabf.tools import ap, memtest, sweep
332
333
# Load ABF file
334
abf = pyabf.ABF("current_clamp_recording.abf")
335
336
# Action potential analysis
337
abf.setSweep(0)
338
ap_indices = ap.ap_points_currentSweep(abf, dVthresholdPos=20)
339
print(f"Found {len(ap_indices)} action potentials in sweep 0")
340
341
# Extract first AP
342
if ap_indices:
343
ap_voltage = ap.extract_first_ap(abf, paddingMsec=100)
344
if ap_voltage is not None:
345
print(f"Extracted AP with {len(ap_voltage)} data points")
346
347
# AP frequency analysis across all sweeps
348
freq_data = ap.ap_freq_per_sweep(abf)
349
frequencies_in_bin, frequencies_first = freq_data
350
print(f"AP frequencies in bin: {frequencies_in_bin}")
351
352
# Membrane test analysis (for voltage clamp data)
353
vc_abf = pyabf.ABF("voltage_clamp_memtest.abf")
354
mt = memtest.Memtest(vc_abf, channel=0)
355
print(mt.summary)
356
357
# Access individual membrane properties using .values
358
print(f"Access resistance: {mt.Ra.values[0]:.1f} MOhm")
359
print(f"Membrane resistance: {mt.Rm.values[0]:.1f} MOhm")
360
print(f"Membrane capacitance: {mt.Cm.values[0]:.1f} pF")
361
print(f"Tau: {mt.tau.values[0]:.2f} ms")
362
363
# Sweep-level analysis
364
mean_sweep = sweep.getMeanSweep(abf)
365
print(f"Mean sweep shape: {mean_sweep.shape}")
366
367
# Custom sweep measurements
368
measurement = sweep.SweepMeasurement(
369
sweepCount=abf.sweepCount,
370
name="Peak Voltage",
371
abbreviation="Vpeak",
372
units="mV"
373
)
374
```
375
376
## Analysis Workflow Patterns
377
378
### Current Clamp Analysis
379
380
```python
381
import pyabf
382
from pyabf.tools import ap
383
import numpy as np
384
385
# Load current clamp recording
386
abf = pyabf.ABF("current_clamp.abf")
387
388
# Analyze each sweep for action potentials
389
results = []
390
for sweep_num in range(abf.sweepCount):
391
abf.setSweep(sweep_num)
392
393
# Find APs in this sweep
394
ap_indices = ap.ap_points_currentSweep(abf)
395
ap_count = len(ap_indices)
396
397
# Calculate AP frequency if multiple APs found
398
if ap_count > 1:
399
sweep_duration = abf.sweepX[-1] - abf.sweepX[0]
400
frequency = (ap_count - 1) / sweep_duration
401
else:
402
frequency = 0
403
404
results.append({
405
'sweep': sweep_num,
406
'ap_count': ap_count,
407
'frequency': frequency
408
})
409
410
print("AP Analysis Results:")
411
for result in results:
412
print(f"Sweep {result['sweep']}: {result['ap_count']} APs, "
413
f"{result['frequency']:.1f} Hz")
414
```
415
416
### Voltage Clamp Analysis
417
418
```python
419
import pyabf
420
from pyabf.tools import memtest
421
422
# Load voltage clamp recording with membrane test
423
abf = pyabf.ABF("voltage_clamp.abf")
424
425
# Perform membrane test analysis
426
mt = memtest.Memtest(abf, channel=0)
427
428
# Display comprehensive results
429
print("Membrane Test Results")
430
print("=" * 40)
431
print(mt.summary)
432
433
# Track membrane properties over time
434
if len(mt.Ra.values) > 1:
435
print(f"\nAccess resistance trend:")
436
for i, ra in enumerate(mt.Ra.values):
437
print(f" Sweep {i}: {ra:.1f} MOhm")
438
```