Skip to main content

RespMech — respiratory mechanics, work of breathing and diaphragm EMG

(c) Copyright 2019–2026 Emil Ingerslev Walsted (emilwalsted@gmail.com), ORCID 0000-0002-6640-7175

DOI

RespMech analyses a time series of respiratory physiological recordings (e.g. exported from LabChart) breath by breath, and calculates:

  • respiratory mechanics
  • inspiratory and expiratory work of breathing (Campbell diagram)
  • diaphragm EMG — RMS envelope, ECG-artefact removal, spectral noise reduction
  • Sample Entropy1,2 (e.g. of diaphragm EMG)

Version 2 is a desktop application with a guided setup, a live preview/QC screen, and a batch runner that opens as a drawer right where you're looking. The physiology is a faithful port of the original v1 code and is locked by golden/characterisation tests — see Correctness.

RespMech — Setup


Install

Recommended — the desktop app. Download the installer for your platform from the latest release: a .dmg (macOS) or .msi (Windows). It bundles its own Python — nothing else to install.

Python package (CLI + core; the GUI is an extra):

pip install respmech            # command-line tool + analysis engine
pip install "respmech[gui]"     # + the PySide6 desktop app (respmech-gui)

From source (developers, or to use the CLI):

git clone https://github.com/emilwalsted/respmech.git
cd respmech
pip install -e ".[dev,gui]"      # gui = PySide6 desktop app;  dev adds the test stack
respmech-gui                     # launch the desktop app

Extras: gui (desktop app), emg (librosa — spectral noise reduction), plots (matplotlib diagnostic figures), dev (tests). See docs/INSTALL.md for details.

See CHANGELOG.md for what changed in each release.

Using the app

respmech-gui

First time in? Choose Explore with sample data on the start screen to load a ready-made synthetic recording — the one shown in the figures below, complete with a heartbeat artefact on the EMG and a little volume drift, so every step has something to demonstrate.

Two tabs:

Tab What you do
Setup Point at your recordings, map the data columns to channels — RespMech suggests roles from the file's own column names, or assign them visually from the data if you prefer — and choose what to save. Settings validate as you type — the status bar flags anything inconsistent.
Preview & QC See the analysis on one file before running the batch: breath segmentation, the Campbell loop and the per-breath table, and dedicated subtabs to tune EMG – ECG reduction and EMG – noise reduction against the live signal. Click a breath to exclude it.

Run & results is a drawer, not a third tab: a compact "Run & results ▸" bar sits below Preview & QC's file list on every subtab, and opens into the batch's progress, per-file status, averaged metrics and output folder — it opens itself the moment you start a run, so you never have to remember to check it.

RespMech — Preview & QC, with Run & results open

Settings are stored as a declarative TOML analysis file (no longer an executable .py). Open, save and switch between analyses — including your recently opened files — from the Analysis menu in the header, which is available on every screen; RespMech marks unsaved edits in the title bar and asks before discarding them. The same actions, plus keyboard shortcuts, live in the window's File menu, alongside View (jump to a tab) and Help (documentation, website, About).

Command line

respmech run settings.toml            # process a batch  (--dry-run computes without writing)
respmech validate settings.toml       # check the settings and the input files
respmech migrate old_settings.py -o settings.toml   # convert a v1 settings file (runs no v1 code)

migrate prints a report of every field moved, renamed or dropped.


Data recording requirements

Input data do not need to be a specific length, but because some outputs are per-time (e.g. minute ventilation) you must specify the sampling frequency of the recording.

The code analyses data breath by breath, and it is imperative that the recording starts with the last part of an expiration and ends with the first part of an inspiration. The recording is trimmed automatically to start at exactly the first inspiration and end at exactly the last expiration.

Breaths are segmented by joining an inspiration with the following expiration, using the flow signal to find the transition. A breath-separation buffer absorbs "wobbly" flow around zero (common in quiet breathing); its length depends on your sampling and breathing frequency. In Preview & QC you can click any breath — e.g. an IC manoeuvre or a cough — to drop it from the analysis:

Breath segmentation and exclusion

Flow and volume conventions. The analysis assumes flow is negative on inspiration and positive on expiration — invert it in Setup if your recording is the other way around. Volume must be inspired volume; it can be inverted, or integrated from the flow signal if your recording has no volume channel. Volume drift (common when integrating from flow) is corrected automatically, with an optional trend adjustment on top — each breath's end-expiratory volume should return to the same baseline, and when it creeps the correction pulls it back. The trend adjustment anchors on the end-expiratory trough of each breath; which troughs count is judged relative to each recording's own volume range, so it needs no tuning at any tidal volume (Preview & QC → Mechanics → Advanced… if a recording does need it):

Volume drift correction

Supported input formats: MATLAB, Excel, CSV/text. (MATLAB files exported from the Windows and macOS versions of LabChart differ — pick the variant in Setup ▸ Advanced.)

Work of breathing

Two options: calculate WOB from each breath's Campbell diagram and average the results, or first build an averaged pressure/volume loop and calculate WOB from that. The two give similar results, but with irregular breaths the averaged loop is more robust. The number of resampling points used when averaging the loop is configurable (a good default is the sampling frequency ÷ 8–10; it must be lower than the shortest inspiration or expiration in the file).

Campbell / PV loop

The enclosed area of the oesophageal-pressure–volume loop is the inspiratory work of breathing: the faint loops are the individual breaths, the bold one their average, the diagonal the passive elastic-recoil line, and the shaded triangle the elastic component.

Diaphragm EMG

When EMG channels are present, each is conditioned in steps before its RMS envelope and (optionally) sample entropy are measured. The heartbeat (ECG) R-wave is typically several times the EMG amplitude, so if left in it dominates the signal and badly inflates the RMS — it is detected on the clearest channel and subtracted first. Then spectral noise reduction — trained on a diaphragm-quiet reference — cleans the residual noise floor while preserving the inspiratory burst. Both steps are tuned against the live signal on the Preview screen's EMG tabs, and every stage is written to the diagnostic figures. The bold envelope below is the RMS the analysis actually measures: the raw one is dominated by the heartbeat (the R-waves run off the shared scale), and removing the ECG then reducing the noise drops the between-breath floor while keeping the bursts — the signal-to-noise of the inspiratory pattern roughly doubles from step 2 to step 3:

Diaphragm EMG conditioning stages

Entropy

Sample Entropy is calculated per breath for the selected channels and averaged like the other measurements, in Setup's "Sample entropy" card (shown once a channel is assigned to Entropy in the channel picker). The two settings there are named after what they literally are, not after the neighbouring textbook parameter: Template length (m + 1) is one more than the embedding dimension m used in the sample-entropy literature — the app's default of 2 gives m = 1, and 3 gives the m = 2 that is conventional there. Tolerance (r), × SD is a multiple of the per-column standard deviation, not an absolute tolerance — the app's default of 0.1 means 0.1 × SD, and 0.2 × SD is the common literature value. A read-out under the two fields states the resulting m and r in those terms, and the same wording is recorded in each output workbook's Provenance sheet whenever entropy is actually computed.

1) Lozano-García M, Leonardo, Moxham J, Rafferty F., Torres A, Jolley CJ, Jané R. Assessment of Inspiratory Muscle Activation using Surface Diaphragm Mechanomyography and Crural Diaphragm Electromyography. doi:10.1109/EMBC.2018.8513046.

2) Aboy M, David, Austin D, Pau. Characterization of Sample Entropy in the Context of Biomedical Signal Analysis. 2007. doi:10.1109/IEMBS.2007.4353701.


Output

Everything lands in the output folder you choose:

  • data/ — Excel workbooks: the across-file averages, and (optionally) breath-by-breath values per file, plus a cohort summary. Each workbook carries its own Units and Provenance sheets.
  • diagnostics/ — vector PDF figures per file: Campbell/PV loops (averaged and per breath), the analysed and raw signals, the staged volume correction, and per-channel EMG overviews at each conditioning stage (raw → ECG-removed → noise-reduced). Optionally the EMG channels as WAV.
  • analysis-used.toml and run-report.txt — the exact settings and a log of what was read, kept, excluded and written, so a folder of results carries its own recipe.

Use the diagnostic figures (or the Preview screen) to spot breaths to exclude — e.g. IC manoeuvres or coughs — then exclude them by clicking them in Preview.

RespMech — the Run & results drawer, expanded after a run

Correctness

The v2 engine is a port of the original v1 monolith. Golden/characterisation tests pin the output byte-for-byte against references baked from the original implementation, which is kept frozen in legacy/ for exactly that purpose.


License and usage

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

Read the entire licence here.

Sample entropy is vendored from pyEntropy — see LICENSE pyentrp.

Note to respiratory scientists

I created this code for my own work and shared it hoping that other researchers working with respiratory physiology might find it useful. If you have questions or suggestions that would make it more useful, please drop me an email.

How do I cite this code in scientific papers – and should I?

It is up to you, really. Personally I am a fan of transparency and Open Source / Open Science and I would appreciate a mention. This will also make readers of your papers aware that this code exists – if you found it useful, perhaps they will too.

Every released version has its own DOI. Reference the latest via DOI, or cite a specific version using that version's DOI (click the badge for the list). See CHANGELOG.md for what changed between versions.

An example citation:

[...] were calculated using the Python package RespMech (E Walsted, RespMech v2.2, 2026, https://github.com/emilwalsted/respmech/, DOI: 10.5281/zenodo.3270826) [...]

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

respmech-2.4.0.tar.gz (476.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

respmech-2.4.0-py3-none-any.whl (524.7 kB view details)

Uploaded Python 3

File details

Details for the file respmech-2.4.0.tar.gz.

File metadata

  • Download URL: respmech-2.4.0.tar.gz
  • Upload date:
  • Size: 476.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for respmech-2.4.0.tar.gz
Algorithm Hash digest
SHA256 4bc40c1ce222026eb5c663bfec21cd105592fc597ab500b4e8699f48451f6b2d
MD5 eb14d913fdc22813224144dd4780b1ce
BLAKE2b-256 be79be14f71513b6d67855bef822939439ac01c69a4343d03518123e3c879043

See more details on using hashes here.

Provenance

The following attestation bundles were made for respmech-2.4.0.tar.gz:

Publisher: publish-pypi.yml on emilwalsted/respmech

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file respmech-2.4.0-py3-none-any.whl.

File metadata

  • Download URL: respmech-2.4.0-py3-none-any.whl
  • Upload date:
  • Size: 524.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for respmech-2.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 21e688485755dac3e015700a970abe5d98639ed8e658e4158027dedf2f30f42b
MD5 4295cdcc485571f3ad95854f110c127d
BLAKE2b-256 b78be5ec13cc1cf9002337d1b3285b2ac5978525331d9a367b278f0c1b001463

See more details on using hashes here.

Provenance

The following attestation bundles were made for respmech-2.4.0-py3-none-any.whl:

Publisher: publish-pypi.yml on emilwalsted/respmech

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

This release

2.4.0 This release

2 files

2.3.4

2 files

2.3.3

2 files

2.3.2

2 files

2.3.1

2 files

2.3.0

2 files

2.2.2

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page