Metadata-Version: 2.5
Name: tracetamer
Version: 0.1.0
Summary: Extract and analyse events from solid-state nanopore current traces
Project-URL: Homepage, https://github.com/brewburgr/TraceTamer
Project-URL: Repository, https://github.com/brewburgr/TraceTamer
Project-URL: Issues, https://github.com/brewburgr/TraceTamer/issues
Author: Simon Brauburger, Max K. Earle, James Barrett
Maintainer-email: Simon Brauburger <sb2551@cam.ac.uk>
License-Expression: AGPL-3.0-or-later
License-File: LICENSE
Keywords: abf,electrophysiology,event detection,nanopore,tdms
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: X11 Applications :: Qt
Classifier: Intended Audience :: Science/Research
Classifier: Natural Language :: English
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Classifier: Topic :: Scientific/Engineering :: Physics
Requires-Python: <3.15,>=3.14
Requires-Dist: h5py<4,>=3.11
Requires-Dist: matplotlib<4,>=3.9
Requires-Dist: nptdms<2,>=1.9
Requires-Dist: numpy<3,>=2.0
Requires-Dist: pandas<4,>=2.2
Requires-Dist: pyabf<3,>=2.3
Requires-Dist: pyqt6<7,>=6.7
Requires-Dist: pyqtgraph<1,>=0.13
Requires-Dist: pywavelets<2,>=1.6
Requires-Dist: scikit-learn<2,>=1.5
Requires-Dist: scipy<2,>=1.14
Requires-Dist: shapely<3,>=2.0
Requires-Dist: tables<4,>=3.9
Requires-Dist: umap-learn<1,>=0.5
Provides-Extra: dev
Requires-Dist: pytest-qt>=4.4; extra == 'dev'
Requires-Dist: pytest-timeout>=2.3; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Provides-Extra: phate
Requires-Dist: phate>=1.0; extra == 'phate'
Description-Content-Type: text/markdown

# TraceTamer

Extract and analyse events from solid-state nanopore current traces.

TraceTamer takes raw TDMS or ABF recordings through event extraction,
classification and peak analysis, and stores everything — data, metadata and
analysis state — in a single portable HDF5 file.

## Install

Requires 64-bit CPython 3.14; pip refuses other versions. Python 3.15 is not
usable yet, because h5py, numexpr and ndindex publish no 3.15 wheels for any
platform. Free-threaded builds are untested.

```bash
python -m pip install tracetamer
tracetamer
```

`python -m tracetamer` starts it too, which helps when the environment's
scripts directory is not on PATH.

| Extra | Adds |
| --- | --- |
| `tracetamer[phate]` | PHATE as a 2D representation method |
| `tracetamer[dev]` | pytest, pytest-qt, pytest-timeout |

## A first analysis

1. **Tab 0** — load recordings, check the sampling interval and units, pick a
   baseline estimator and threshold, then detect events.
2. Review events, reject individually or by property filter, and send the
   accepted ones to Tab 1.
3. **Tab 1** — confirm the sample rate, open **Refine event limits and create
   HDF5**, trial a limit-detection algorithm on single events.
4. Optionally add event timestamps, then **Process events and Create HDF5**.
   Keep the application open until saving finishes.
5. **Tabs 2–4** — build representations and assign categories, review
   categories and peaks, inspect individual events.

**Load HDF** reopens an analysis; **Save HDF** opens a Save As dialog. Metadata
is also saved when leaving an analysis tab.

## Keyboard shortcuts

In Tab 0, while reviewing events:

| Key | Action |
| --- | --- |
| `q` / `e` | Previous / next trace |
| `←` / `→` | Previous / next event |
| `a` | Accept event, go to next |
| `r` | Reject event, go to next |
| `f` | Reject whole trace, go to next trace |

In Tab 2, `F` cycles the interaction mode — navigation, multi-event
selection, single-event selection. `T` does the same, kept for compatibility.

## Scripted use

The analysis layer has no dependency on the interface, so detection can be run
from a script or notebook:

```python
from tracetamer.extractor_utils.traces import traces_manager_from_filelist
from tracetamer.extractor_utils.events import EventRules
from tracetamer.extractor_utils.baseline import RankEstimator
from tracetamer.extractor_utils.event_detection import EventExtractor

traces = traces_manager_from_filelist(["recording_001.tdms", "recording_002.tdms"])
for trace in traces:
    trace.set_time_increment(1e-6)          # seconds per sample

rules = EventRules(
    ["threshold", "decimate factor", "event padding"],
    [-0.1, 10, 250],                        # nA, downsampling, raw samples
)
extractor = EventExtractor(traces, rules, RankEstimator(kernel_size=1000))
found = extractor.process_all_traces()

for event in found.events.values():
    values = event.filter_values()
    print(event.name, event.file, values["duration"], values["peak_current"])
```

`traces_manager_from_filelist` accepts `.tdms` and `.abf` paths alike. A
single-sweep ABF becomes one trace; a multi-sweep ABF becomes one per sweep,
because its sweeps are not continuous in time.

## The tabs

### Tab 0 — Event extraction

Loads full TDMS recordings and ABF sweeps. TDMS loading takes the channel with
the most samples across all groups; ABF loading takes a channel labelled with
current units, asking when several qualify.

- **Baselines:** percentile/median (default), mean, morphological. The window
  must exceed the longest event — for the median, by more than twice, or the
  baseline follows the event down instead of stepping over it. The
  morphological estimator is under review and may be reworked or removed.
- **Detection** thresholds the baseline-corrected downsampled signal, then
  refines each edge against the detection baseline at raw resolution. Padding
  is in raw samples; the joining window is in downsampled samples.
- **Joining events between traces** (Input files panel) treats the loaded files
  as consecutive parts of one recording. Each trace's baseline is then
  estimated with its neighbours' samples attached, and an event still running
  at the end of one file is joined to the one that opens the next. Turn it off
  for a set of unrelated files.
- **Automatic extraction** runs from the next file, optionally with plotting.
  Pausing allows detection, baseline and filter settings to be edited; resuming
  rebuilds the extractor for the remaining files and time allowance. Time spent
  paused does not count against that allowance.

Rejected events stay browsable; only accepted events go to Tab 1.

### Tab 1 — Histograms, HDF5 creation

Accepts events from Tab 0, event TDMS files, compatible HDF input, or NumPy
collections (`.npy`, `.npz`). Displays all-points and duration histograms.

The preprocessing dialog navigates events, trials event-limit detection,
prepares timestamps and processes the collection into HDF5, generating event
metadata and fixed-length processed arrays.

Threshold refinement starts its X₀ search at padding + 10 samples. If a cutoff
is never reached, or the limits are equal or reversed, it falls back to the
incoming Tab 0 bounds, otherwise to a dummy width of 10 samples clamped to the
trace. Preview and batch processing use the same fallback.

Check the acquisition rate in **kHz**, especially for imported arrays.
**Rate (kHz)** under Additional Tools changes it for every event; TDMS events
still linked to an active Tab 0 session update in both tabs. Rate changes
multiply the whole timeline, including offsets between recordings — 1000 to
250 kHz multiplies timestamps by four.

**Event timestamps** are held in memory and written to the `Timestamps`
metadata column when the analysis is created, in seconds:

| Source | Behaviour |
| --- | --- |
| Events from Tab 0 | Timing of the detection channel plus the event's position. Relative to experiment start, not calendar time. |
| `.dat` statistics file | Tab-separated, with `Time in file/s` and `File number` (starting at 1). Set the recording duration: timestamp is `Time in file/s + duration × (File number − 1)`. |
| Timestamp file | Tab-separated, with an `Event timestamp (s)` column. |

Statistics rows must match the loaded events in their original order. Loading
new events clears prepared timestamps.

### Tab 2 — 2D Representation

Plot any two stored variables, or compute a representation with t-SNE, UMAP,
Isomap or PCA (PHATE appears when installed). Isomap exposes neighbours,
distance metric and eigen solver, defaulting to 5, `minkowski` and `auto`.

**Clustering** offers scikit-learn HDBSCAN, DBSCAN and KMeans on the displayed
pair of variables. **Normalize axes** scales the input for clustering only.

With **Only selected categories** on, assignments are limited to those events
and use free slots from 1 to 9; density clustering reserves the last slot for
noise. With it off, clustering can use 0 to 9 and warns before overwriting.
Noise is an ordinary numbered category, distinct from **10: Deleted**.

Clustering reflects the chosen representation and parameters — inspect the
events before reading anything physical into the categories.

### Tab 3 — Class overview & Peak analysis

Review events by category, rename categories, delete empty ones (deleting a
populated category asks where to move its events). Peak tables are stored with
the analysis.

### Tab 4 — Single event viewer

Inspect individual events, their metadata and peaks; adjust peak annotations
and save the updated tables.

## Data

Units: durations in **microseconds**, currents in **nA**, charge deficits in
**fC**. Signals must arrive in the expected units for these to mean anything.

Reserved categories: **10** Deleted, **11** Filtered (excluded by the length
criterion), **12** Pre-processing problems.

Analysis files keep the established HDF structure:

```text
/trace_data/raw_traces
/trace_data/processed_traces
/trace_metadata/trace_metadata_table
/peak_data
/program_attributes
```

`detection_parameters` and `threshold_parameters` are readable JSON
attributes; older pickled dictionaries still load. Detection settings hold one
global snapshot.

**Saves are staged.** Every write goes to a temporary file beside the
destination, which is replaced only once all writes succeed and the handles
close. A failed save preserves the previous file and blocks the tab switch or
save-and-close that requested it. This needs room for a second copy of the
analysis and is slower on external drives. After an abrupt termination a hidden
`.tmp.h5` sibling may remain; it is not recovered automatically.

Tab 0 detection and review state is session-only. Reopening an HDF restores the
analysis, not the extraction session that produced it.

## Development

```bash
git clone https://github.com/brewburgr/TraceTamer.git
cd TraceTamer
python -m pip install -e ".[dev]"
pytest
```

An editable install points at `src/tracetamer/`, so edits take effect without
reinstalling. Reinstall only after changing `pyproject.toml`.

Focused batches help when diagnosing native Qt or PyTables failures:

```bash
pytest tests/test_saving_failures.py tests/test_loading.py tests/test_app.py
pytest tests/test_event_boundaries.py tests/test_event_joining.py
pytest tests/test_visualization.py tests/test_clustering.py
```

Checked-in HDF fixtures must stay unchanged; a session-wide check fails any
test that modifies one. See [tests/README.md](tests/README.md).

### Layout

```text
src/tracetamer/
    main.py                  application shell and the five tabs
    tab0_pyqtgraph.py …      one module per tab
    extractor_utils/         loading, baselines, event detection (no Qt)
    denoise.py, peaks.py, hdf_saving.py, misc.py, flow_layout.py
tests/                       regression suite
```

`requirements.txt` pins the exact development set; `pyproject.toml` carries the
wider ranges an install resolves against.

### Releases

CI runs the suite on Linux, macOS and Windows and builds the distributions on
every push and pull request.

To publish: bump `__version__` in `src/tracetamer/__init__.py`, tag the commit
`vX.Y.Z` and push the tag. The release workflow checks the tag against
`__version__`, builds, and uploads to PyPI through a trusted publisher once the
`pypi` environment is approved — no API tokens are stored. Running the workflow
by hand publishes to TestPyPI instead, for a rehearsal.

## Troubleshooting

**The interface is too large or too small.** It sizes itself from the system
font and the display scaling the OS reports, and the control panels wrap onto
further rows as the window narrows. If an override is still needed, Qt reads
`QT_SCALE_FACTOR` from the environment:

```bash
QT_SCALE_FACTOR=0.8 tracetamer
```

## Licence

AGPL-3.0-or-later. TraceTamer ships PyQt6, which is offered under the GPL or a
commercial licence from Riverbank; GPLv3 section 13 permits combining that code
with AGPLv3 code, so the application as a whole is AGPL. Section 13 adds one
obligation beyond the GPL: anyone who lets users interact with a modified
version over a network must offer those users its source.
See [LICENSE](LICENSE).
