Skip to content

detectionParams module¤

Manage SanPy spike-detection parameters and presets.

Classes¤

DetectionParameters ¤

Bases: BaseModel

Validated spike-detection parameter values.

Source code in sanpy/bDetection.py
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
class DetectionParameters(BaseModel):
    """Validated spike-detection parameter values."""

    model_config = ConfigDict(
        extra="forbid", frozen=True, json_schema_extra={"additionalProperties": False}
    )

    detectionName: str = _field(
        "default",
        title="Detection Preset",
        description="The name of detection preset",
        category=DetectionParameterCategory.PRESETS,
    )
    userSaveName: str = _field(
        "",
        title="Save User Name",
        description="The name of saved user detection params",
        category=DetectionParameterCategory.PRESETS,
    )
    detectionType: detectionTypes_ = _field(
        detectionTypes_.dvdt,
        title="Detection Type",
        description="Detect using derivative (dvdt) or membrane potential (mV)",
        category=DetectionParameterCategory.DETECTION,
    )
    dvdtThreshold: float | None = _field(
        20,
        title="dV/dt Threshold",
        description="Minimum dV/dt used to detect a spike threshold",
        category=DetectionParameterCategory.DETECTION,
        units="mV/ms",
    )
    mvThreshold: float = _field(
        -20,
        title="mV Threshold",
        description="mV threshold for spike AND minimum spike mV when detecting with dV/dt",
        category=DetectionParameterCategory.DETECTION,
        units="mV",
    )
    startSeconds: float | None = _field(
        None,
        title="Start(s)",
        description="Start seconds of analysis, set from the visible x-range when detecting",
        category=DetectionParameterCategory.WINDOWS,
        show_in_editor=False,
        units="s",
    )
    stopSeconds: float | None = _field(
        None,
        title="Stop(s)",
        description="Stop seconds of analysis, set from the visible x-range when detecting",
        category=DetectionParameterCategory.WINDOWS,
        show_in_editor=False,
        units="s",
    )
    dvdt_percentOfMax: float = _field(
        0.1,
        title="dV/dt Percent of max",
        description="For dV/dt detection, the final TOP is when dV/dt drops to this percent from dV/dt AP peak",
        category=DetectionParameterCategory.DETECTION,
        units="Percent",
    )
    onlyPeaksAbove_mV: float | None = _field(
        None,
        title="Accept Peaks Above (mV)",
        description="Only accept APs with peaks above this value (mV)",
        category=DetectionParameterCategory.WAVEFORM,
        units="mV",
    )
    onlyPeaksBelow_mV: float | None = _field(
        None,
        title="Accept Peaks Below (mV)",
        description="Only accept APs below this value (mV)",
        category=DetectionParameterCategory.WAVEFORM,
        units="mV",
    )
    doBackupSpikeVm: bool = _field(
        False,
        title="Backup Vm Spikes",
        description="If true, APs detected with just mV will be backed up until Vm falls to xxx",
        category=DetectionParameterCategory.ADVANCED,
        units="Boolean",
    )
    refractory_ms: float = _field(
        170,
        title="Minimum AP interval (ms)",
        description="APs with interval (wrt previous AP) less than this will be removed",
        category=DetectionParameterCategory.WINDOWS,
        units="ms",
    )
    peakWindow_ms: float = _field(
        100,
        title="Peak Window (ms)",
        description="Window after TOP (ms) to seach for AP peak (mV)",
        category=DetectionParameterCategory.WINDOWS,
        units="ms",
    )
    dvdtPreWindow_ms: float = _field(
        10,
        title="dV/dt Pre Window (ms)",
        description="Window (ms) to search before each TOP for real threshold crossing",
        category=DetectionParameterCategory.WINDOWS,
        units="ms",
    )
    dvdtPostWindow_ms: float = _field(
        20,
        title="dV/dt Post Window (ms)",
        description="Window (ms) to search after each AP peak for minimum in dv/dt",
        category=DetectionParameterCategory.WINDOWS,
        units="ms",
    )
    mdp_ms: float = _field(
        250,
        title="Pre AP MDP window (ms)",
        description="Window (ms) before an AP to look for MDP",
        category=DetectionParameterCategory.WINDOWS,
        units="ms",
    )
    avgWindow_ms: float = _field(
        5,
        title="MDP averaging window (ms)",
        description="Window (ms) to calculate MDP (mV) as a mean rather than mV at single point for MDP",
        category=DetectionParameterCategory.WINDOWS,
        units="ms",
    )
    lowEddRate_warning: float = _field(
        8,
        title="EDD slope warning",
        description="Generate warning when EED slope is lower than this value.",
        category=DetectionParameterCategory.ADVANCED,
        units="EDD slope",
    )
    halfWidthWindow_ms: float = _field(
        200,
        title="Half Width Window (ms)",
        description="Window (ms) after TOP to look for AP widths",
        category=DetectionParameterCategory.WINDOWS,
        units="ms",
    )
    preSpikeClipWidth_ms: float = _field(
        4,
        title="Pre AP Clip Width (ms)",
        description="The pre duration of generated AP clips (Before AP)",
        category=DetectionParameterCategory.SPIKE_CLIPS,
        units="ms",
    )
    postSpikeClipWidth_ms: float = _field(
        8,
        title="Post AP Clip Width (ms)",
        description="The post duration of generated AP clips (After AP)",
        category=DetectionParameterCategory.SPIKE_CLIPS,
        units="ms",
    )
    fastAhpWindow_ms: float = _field(
        8,
        title="Fast AHP Window (ms)",
        description="Window (ms) after peak to look for a fast AHP",
        category=DetectionParameterCategory.WINDOWS,
        units="ms",
    )
    medianFilter: int | None = _field(
        0,
        title="Median Filter Points",
        description="Number of points in median filter, must be odd, 0 for no filter",
        category=DetectionParameterCategory.FILTERING,
        units="points",
    )
    SavitzkyGolay_pnts: int | None = _field(
        5,
        title="SavitzkyGolay Points",
        description="Number of points in SavitzkyGolay filter, must be odd, 0 for no filter",
        category=DetectionParameterCategory.FILTERING,
        units="points",
    )
    SavitzkyGolay_poly: int = _field(
        2,
        title="SavitzkyGolay Poly Deg",
        description="The degree of the polynomial for Savitzky-Golay filter",
        category=DetectionParameterCategory.FILTERING,
    )
    verbose: bool = _field(
        False,
        title="Verbose",
        description="Verbose Detection Reporting",
        category=DetectionParameterCategory.ADVANCED,
        units="Boolean",
    )

    @classmethod
    def from_saved(cls, data: Mapping[str, Any]) -> Self:
        """Load saved parameters while tolerating obsolete fields.

        Args:
            data: Saved detection parameter mapping.

        Returns:
            Validated parameters with current defaults added.

        Raises:
            ValidationError: If a known field contains an invalid value.
        """
        unknown = sorted(set(data) - set(cls.model_fields))
        for name in unknown:
            logger.warning(f'Ignoring unknown saved detection parameter "{name}"')
        normalized = {
            name: _normalize_missing(value)
            for name, value in data.items()
            if name in cls.model_fields
        }
        return cls.model_validate(normalized)

    def get_value(self, name: str) -> Any:
        """Return one parameter selected dynamically by name.

        Args:
            name: Detection parameter field name.

        Returns:
            The typed parameter value.

        Raises:
            KeyError: If the parameter name is unknown.
        """
        if name not in type(self).model_fields:
            raise KeyError(name)
        return getattr(self, name)

    def with_value(self, name: str, value: Any) -> Self:
        """Return a strictly validated copy with one changed value.

        Args:
            name: Detection parameter field name.
            value: Replacement parameter value.

        Returns:
            A new validated parameter model.

        Raises:
            KeyError: If the parameter name is unknown.
            ValidationError: If the replacement has the wrong type or value.
        """
        if name not in type(self).model_fields:
            raise KeyError(name)
        if name == "detectionType" and isinstance(value, str):
            value = detectionTypes_(value)
        candidate = self.model_dump(mode="python")
        candidate[name] = value
        return type(self).model_validate(candidate, strict=True)

Methods:¤

from_saved(data) classmethod ¤

Load saved parameters while tolerating obsolete fields.

Args: data: Saved detection parameter mapping.

Returns: Validated parameters with current defaults added.

Raises: ValidationError: If a known field contains an invalid value.

Source code in sanpy/bDetection.py
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
@classmethod
def from_saved(cls, data: Mapping[str, Any]) -> Self:
    """Load saved parameters while tolerating obsolete fields.

    Args:
        data: Saved detection parameter mapping.

    Returns:
        Validated parameters with current defaults added.

    Raises:
        ValidationError: If a known field contains an invalid value.
    """
    unknown = sorted(set(data) - set(cls.model_fields))
    for name in unknown:
        logger.warning(f'Ignoring unknown saved detection parameter "{name}"')
    normalized = {
        name: _normalize_missing(value)
        for name, value in data.items()
        if name in cls.model_fields
    }
    return cls.model_validate(normalized)
get_value(name) ¤

Return one parameter selected dynamically by name.

Args: name: Detection parameter field name.

Returns: The typed parameter value.

Raises: KeyError: If the parameter name is unknown.

Source code in sanpy/bDetection.py
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
def get_value(self, name: str) -> Any:
    """Return one parameter selected dynamically by name.

    Args:
        name: Detection parameter field name.

    Returns:
        The typed parameter value.

    Raises:
        KeyError: If the parameter name is unknown.
    """
    if name not in type(self).model_fields:
        raise KeyError(name)
    return getattr(self, name)
with_value(name, value) ¤

Return a strictly validated copy with one changed value.

Args: name: Detection parameter field name. value: Replacement parameter value.

Returns: A new validated parameter model.

Raises: KeyError: If the parameter name is unknown. ValidationError: If the replacement has the wrong type or value.

Source code in sanpy/bDetection.py
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
def with_value(self, name: str, value: Any) -> Self:
    """Return a strictly validated copy with one changed value.

    Args:
        name: Detection parameter field name.
        value: Replacement parameter value.

    Returns:
        A new validated parameter model.

    Raises:
        KeyError: If the parameter name is unknown.
        ValidationError: If the replacement has the wrong type or value.
    """
    if name not in type(self).model_fields:
        raise KeyError(name)
    if name == "detectionType" and isinstance(value, str):
        value = detectionTypes_(value)
    candidate = self.model_dump(mode="python")
    candidate[name] = value
    return type(self).model_validate(candidate, strict=True)

bDetection ¤

Manage bundled and user-defined detection presets.

Source code in sanpy/bDetection.py
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
class bDetection:
    """Manage bundled and user-defined detection presets."""

    detectionTypes = detectionTypes_

    def __init__(self, sanpy_paths: SanPyPaths | None = None) -> None:
        """Load all bundled and user detection presets.

        Args:
            sanpy_paths: Optional application path manager.
        """
        self._sanpy_paths = sanpy_paths or SanPyPaths()
        self._userPresetNames: set[str] = set()
        self._detectionPreset = self._getPresetsDict()

    def getDetectionPresetList(self) -> list[str]:
        """Return the names of all loaded detection presets.

        Returns:
            Bundled and user-defined preset names.
        """
        return list(self._detectionPreset)

    def isUserPreset(self, name: str) -> bool:
        """Return whether a preset came from the user detection folder.

        Args:
            name: Detection-preset name.

        Returns:
            True when the preset was loaded from the user folder.
        """
        return name in self._userPresetNames

    def reloadPresets(self) -> None:
        """Reload bundled and user detection presets from disk."""
        self._userPresetNames = set()
        self._detectionPreset = self._getPresetsDict()

    def _getPresetsDict(self) -> dict[str, DetectionParameters]:
        """Load and validate bundled and user detection presets.

        Returns:
            Preset models keyed by filename stem.

        Raises:
            ValidationError: If a preset contains an invalid known value.
        """
        presets: dict[str, DetectionParameters] = {}
        bundled = self._sanpy_paths.bundled_dir / "detection-presets" / "*.json"
        for file_path in glob.glob(str(bundled)):
            _, key = _preset_names(file_path)
            with open(file_path, "r", encoding="utf-8") as handle:
                presets[key] = DetectionParameters.from_saved(json.load(handle))
        for file_path in self._getUserFiles():
            _, key = _preset_names(file_path)
            with open(file_path, "r", encoding="utf-8") as handle:
                presets[key] = DetectionParameters.from_saved(json.load(handle))
            self._userPresetNames.add(key)
        return presets

    def _getUserFiles(self) -> list[pathlib.Path]:
        """Return paths to user detection-preset files.

        Returns:
            Detection-preset JSON paths, or an empty list when unavailable.
        """
        path = self._sanpy_paths.detection_dir
        return list(path.glob("*.json")) if path.is_dir() else []

    def getDetectionDict(
        self, detectionType: str, allParameter: bool = True
    ) -> dict[str, Any]:
        """Return an independent JSON-compatible preset dictionary.

        Args:
            detectionType: Preset name, such as ``"SA Node"``.
            allParameter: Retained for compatibility; all fields are returned.

        Returns:
            Validated detection parameter values.

        Raises:
            KeyError: If the preset name is unknown.
        """
        return self._detectionPreset[detectionType].model_dump(mode="json")

    def getValue(self, detectionType: str, key: str) -> Any:
        """Return one value from a loaded detection preset.

        Args:
            detectionType: Loaded detection-preset name.
            key: Detection parameter field name.

        Returns:
            The parameter value, or ``None`` when either name is unknown.
        """
        try:
            return self._detectionPreset[detectionType].get_value(key)
        except KeyError:
            logger.warning(
                f'Did not find detectionType "{detectionType}" or key "{key}" to get current value'
            )
            return None

    def setValue(self, detectionType: str, key: str, value: Any) -> bool:
        """Strictly validate and store one preset value.

        Args:
            detectionType: Loaded detection-preset name.
            key: Detection parameter field name.
            value: Replacement value.

        Returns:
            True when the value was stored, otherwise False.
        """
        try:
            current = self._detectionPreset[detectionType]
            self._detectionPreset[detectionType] = current.with_value(key, value)
        except (KeyError, ValueError, ValidationError) as error:
            logger.warning(
                f'Could not set detectionType:{detectionType}, key:"{key}" to "{value}": {error}'
            )
            return False
        return True

Methods:¤

__init__(sanpy_paths=None) ¤

Load all bundled and user detection presets.

Args: sanpy_paths: Optional application path manager.

Source code in sanpy/bDetection.py
349
350
351
352
353
354
355
356
357
def __init__(self, sanpy_paths: SanPyPaths | None = None) -> None:
    """Load all bundled and user detection presets.

    Args:
        sanpy_paths: Optional application path manager.
    """
    self._sanpy_paths = sanpy_paths or SanPyPaths()
    self._userPresetNames: set[str] = set()
    self._detectionPreset = self._getPresetsDict()
getDetectionDict(detectionType, allParameter=True) ¤

Return an independent JSON-compatible preset dictionary.

Args: detectionType: Preset name, such as "SA Node". allParameter: Retained for compatibility; all fields are returned.

Returns: Validated detection parameter values.

Raises: KeyError: If the preset name is unknown.

Source code in sanpy/bDetection.py
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
def getDetectionDict(
    self, detectionType: str, allParameter: bool = True
) -> dict[str, Any]:
    """Return an independent JSON-compatible preset dictionary.

    Args:
        detectionType: Preset name, such as ``"SA Node"``.
        allParameter: Retained for compatibility; all fields are returned.

    Returns:
        Validated detection parameter values.

    Raises:
        KeyError: If the preset name is unknown.
    """
    return self._detectionPreset[detectionType].model_dump(mode="json")
getDetectionPresetList() ¤

Return the names of all loaded detection presets.

Returns: Bundled and user-defined preset names.

Source code in sanpy/bDetection.py
359
360
361
362
363
364
365
def getDetectionPresetList(self) -> list[str]:
    """Return the names of all loaded detection presets.

    Returns:
        Bundled and user-defined preset names.
    """
    return list(self._detectionPreset)
getValue(detectionType, key) ¤

Return one value from a loaded detection preset.

Args: detectionType: Loaded detection-preset name. key: Detection parameter field name.

Returns: The parameter value, or None when either name is unknown.

Source code in sanpy/bDetection.py
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
def getValue(self, detectionType: str, key: str) -> Any:
    """Return one value from a loaded detection preset.

    Args:
        detectionType: Loaded detection-preset name.
        key: Detection parameter field name.

    Returns:
        The parameter value, or ``None`` when either name is unknown.
    """
    try:
        return self._detectionPreset[detectionType].get_value(key)
    except KeyError:
        logger.warning(
            f'Did not find detectionType "{detectionType}" or key "{key}" to get current value'
        )
        return None
isUserPreset(name) ¤

Return whether a preset came from the user detection folder.

Args: name: Detection-preset name.

Returns: True when the preset was loaded from the user folder.

Source code in sanpy/bDetection.py
367
368
369
370
371
372
373
374
375
376
def isUserPreset(self, name: str) -> bool:
    """Return whether a preset came from the user detection folder.

    Args:
        name: Detection-preset name.

    Returns:
        True when the preset was loaded from the user folder.
    """
    return name in self._userPresetNames
reloadPresets() ¤

Reload bundled and user detection presets from disk.

Source code in sanpy/bDetection.py
378
379
380
381
def reloadPresets(self) -> None:
    """Reload bundled and user detection presets from disk."""
    self._userPresetNames = set()
    self._detectionPreset = self._getPresetsDict()
setValue(detectionType, key, value) ¤

Strictly validate and store one preset value.

Args: detectionType: Loaded detection-preset name. key: Detection parameter field name. value: Replacement value.

Returns: True when the value was stored, otherwise False.

Source code in sanpy/bDetection.py
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
def setValue(self, detectionType: str, key: str, value: Any) -> bool:
    """Strictly validate and store one preset value.

    Args:
        detectionType: Loaded detection-preset name.
        key: Detection parameter field name.
        value: Replacement value.

    Returns:
        True when the value was stored, otherwise False.
    """
    try:
        current = self._detectionPreset[detectionType]
        self._detectionPreset[detectionType] = current.with_value(key, value)
    except (KeyError, ValueError, ValidationError) as error:
        logger.warning(
            f'Could not set detectionType:{detectionType}, key:"{key}" to "{value}": {error}'
        )
        return False
    return True

detectionTypes_ ¤

Bases: Enum

Available spike-detection algorithms.

Source code in sanpy/bDetection.py
22
23
24
25
26
class detectionTypes_(Enum):
    """Available spike-detection algorithms."""

    dvdt = "dvdt"
    mv = "mv"

Functions:¤

All material is Copyright 2019-2026 Robert H. Cudmore