mtscomp


Namemtscomp JSON
Version 1.0.2 PyPI version JSON
download
home_pagehttps://github.com/int-brain-lab/mtscomp
SummaryLossless compression for electrophysiology time-series
upload_time2021-05-11 11:32:31
maintainer
docs_urlNone
authorCyrille Rossant (International Brain Laboratory)
requires_python
licenseBSD
keywords lossless compresssion electrophysiology neuroscience
VCS
bugtrack_url
requirements numpy
Travis-CI
coveralls test coverage No coveralls.
            # Multichannel time series lossless compression in Python

[![Build Status](https://travis-ci.org/int-brain-lab/mtscomp.svg?branch=master)](https://travis-ci.org/int-brain-lab/mtscomp)
[![Coverage Status](https://codecov.io/gh/int-brain-lab/mtscomp/branch/master/graph/badge.svg)](https://codecov.io/gh/int-brain-lab/mtscomp)

This library implements a simple lossless compression scheme adapted to time-dependent high-frequency, high-dimensional signals. It is being developed within the [International Brain Laboratory](https://www.internationalbrainlab.com/) with the aim of being the compression library used for all large-scale electrophysiological recordings based on Neuropixels. The signals are typically recorded at 30 kHz and 10 bit depth, and contain several hundreds of channels.


## Compression scheme

The requested features for the compression scheme were as follows:

* Lossless compression only (one should retrieve byte-to-byte exact decompressed data).
* Written in pure Python (no C extensions) with minimal dependencies so as to simplify distribution.
* Scalable to large sample rates, large number of channels, long recording time.
* Faster than real time (i.e. it should take less time to compress than to record).
* Multithreaded so as to leverage multiple CPU cores.
* On-the-fly decompression and random read accesses.
* As simple as possible.

The compression scheme is the following:

* The data is split into chunks along the time axis.
* The time differences are computed for all channels.
* These time differences are compressed with zlib.
* The compressed chunks (and initial values of each chunk) are appended in a binary file.
* Metadata about the compression, including the chunk offsets within the compressed binary file, are saved in a secondary JSON file.

Saving the offsets allows for on-the-fly decompression and random data access: one simply has to determine which chunks should be loaded, and load them directly from the compressed binary file. The compressed chunks are decompressed with zlib, and the original data is recovered with a cumulative sum (the inverse of the time difference operation).

With large-scale neurophysiological recordings, we achieved a compression ratio of 3x.

As a consistency check, the compressed file is by default automatically and transparently decompressed and compared to the original file on a byte-per-byte basis.


## Dependencies

* Python 3.7+
* NumPy
* tqdm [for the progress bar]

For development only:

* flake8
* pytest
* pytest-cov
* coverage


## Installation

```
pip install mtscomp
```


## Command-line interface

Example:

```bash
# Compression: specify the number of channels, sample rate, dtype, optionally save the parameters
# as default in ~/.mtscomp with --set-default
mtscomp data.bin -n 385 -s 30000 -d int16 [--set-default]
# Decompression
mtsdecomp data.cbin -o data.decomp.bin
```

Usage:

```
usage: mtscomp [-h] [-d DTYPE] [-s SAMPLE_RATE] [-n N_CHANNELS] [-p CPUS]
               [-c CHUNK] [-nc] [-v] [--set-default]
               path [out] [outmeta]

Compress a raw binary file.

positional arguments:
  path                  input path of a raw binary file
  out                   output path of the compressed binary file (.cbin)
  outmeta               output path of the compression metadata JSON file
                        (.ch)

optional arguments:
  -h, --help            show this help message and exit
  -d DTYPE, --dtype DTYPE
                        data type
  -s SAMPLE_RATE, --sample-rate SAMPLE_RATE
                        sample rate
  -n N_CHANNELS, --n-channels N_CHANNELS
                        number of channels
  -p CPUS, --cpus CPUS  number of CPUs to use
  -c CHUNK, --chunk CHUNK
                        chunk duration
  -nc, --no-check       no check
  -v, --debug           verbose
  --set-default         set the specified parameters as the default



usage: mtsdecomp [-h] [-o [OUT]] [--overwrite] [-nc] [-v] cdata [cmeta]

Decompress a raw binary file.

positional arguments:
  cdata                 path to the input compressed binary file (.cbin)
  cmeta                 path to the input compression metadata JSON file (.ch)

optional arguments:
  -h, --help            show this help message and exit
  -o [OUT], --out [OUT]
                        path to the output decompressed file (.bin)
  --overwrite, -f       overwrite existing output
  -nc, --no-check       no check
  -v, --debug           verbose
```


## High-level API

Example:

```python
import numpy as np
from mtscomp.mtscomp import compress, decompress

# Compress a .bin file into a pair .cbin (compressed binary file) and .ch (JSON file).
compress('data.bin', 'data.cbin', 'data.ch', sample_rate=20000., n_channels=256, dtype=np.int16)
# Decompress a pair (.cbin, .ch) and return an object that can be sliced like a NumPy array.
arr = decompress('data.cbin', 'data.ch')
X = arr[start:end, :]  # decompress the data on the fly directly from the file on disk
arr.close()  # Close the file when done
```


## Low-level API

Example:

```python
import numpy as np
from mtscomp import Writer, Reader

# Define a writer to compress a flat raw binary file.
w = Writer(chunk_duration=1.)
# Open the file to compress.
w.open('data.bin', sample_rate=20000., n_channels=256, dtype=np.int16)
# Compress it into a compressed binary file, and a JSON header file.
w.write('data.cbin', 'data.ch')
w.close()

# Define a reader to decompress a compressed array.
r = Reader()
# Open the compressed dataset.
r.open('data.cbin', 'data.ch')
# The reader can be sliced as a NumPy array: decompression happens on the fly. Only chunks
# that need to be loaded are loaded and decompressed.
# Here, we load everything in memory.
array = r[:]
# Or we can decompress into a new raw binary file on disk.
r.tofile('data_dec.bin')
r.close()
```


## Implementation details

* **Multithreading**: since Python's zlib releases the GIL, the library uses multiple threads when compressing a file. The chunks are grouped in batches containing as many chunks as threads. After each batch, the chunks are written in the binary file in the right order (since the threads of the batch have no reason to finish in order).


## Performance

Performance on an Neuropixels dataset (30 kHz, 385 channels) and Intel 10-core i9-9820X CPU @ 3.3GHz:

* Compression ratio: -63% (compressed files are nearly 3x smaller)
* Compression time (20 threads): 88 MB/s, **4x faster than real time**
* Decompression time (single-threaded at the moment): 22 MB/s, **3x faster than real time**



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/int-brain-lab/mtscomp",
    "name": "mtscomp",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "lossless,compresssion,electrophysiology,neuroscience",
    "author": "Cyrille Rossant (International Brain Laboratory)",
    "author_email": "cyrille.rossant@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/2e/ef/365e2dd214155b06d22622b3278de769d20e9e1d201538a941d62b609248/mtscomp-1.0.2.tar.gz",
    "platform": "",
    "description": "# Multichannel time series lossless compression in Python\n\n[![Build Status](https://travis-ci.org/int-brain-lab/mtscomp.svg?branch=master)](https://travis-ci.org/int-brain-lab/mtscomp)\n[![Coverage Status](https://codecov.io/gh/int-brain-lab/mtscomp/branch/master/graph/badge.svg)](https://codecov.io/gh/int-brain-lab/mtscomp)\n\nThis library implements a simple lossless compression scheme adapted to time-dependent high-frequency, high-dimensional signals. It is being developed within the [International Brain Laboratory](https://www.internationalbrainlab.com/) with the aim of being the compression library used for all large-scale electrophysiological recordings based on Neuropixels. The signals are typically recorded at 30 kHz and 10 bit depth, and contain several hundreds of channels.\n\n\n## Compression scheme\n\nThe requested features for the compression scheme were as follows:\n\n* Lossless compression only (one should retrieve byte-to-byte exact decompressed data).\n* Written in pure Python (no C extensions) with minimal dependencies so as to simplify distribution.\n* Scalable to large sample rates, large number of channels, long recording time.\n* Faster than real time (i.e. it should take less time to compress than to record).\n* Multithreaded so as to leverage multiple CPU cores.\n* On-the-fly decompression and random read accesses.\n* As simple as possible.\n\nThe compression scheme is the following:\n\n* The data is split into chunks along the time axis.\n* The time differences are computed for all channels.\n* These time differences are compressed with zlib.\n* The compressed chunks (and initial values of each chunk) are appended in a binary file.\n* Metadata about the compression, including the chunk offsets within the compressed binary file, are saved in a secondary JSON file.\n\nSaving the offsets allows for on-the-fly decompression and random data access: one simply has to determine which chunks should be loaded, and load them directly from the compressed binary file. The compressed chunks are decompressed with zlib, and the original data is recovered with a cumulative sum (the inverse of the time difference operation).\n\nWith large-scale neurophysiological recordings, we achieved a compression ratio of 3x.\n\nAs a consistency check, the compressed file is by default automatically and transparently decompressed and compared to the original file on a byte-per-byte basis.\n\n\n## Dependencies\n\n* Python 3.7+\n* NumPy\n* tqdm [for the progress bar]\n\nFor development only:\n\n* flake8\n* pytest\n* pytest-cov\n* coverage\n\n\n## Installation\n\n```\npip install mtscomp\n```\n\n\n## Command-line interface\n\nExample:\n\n```bash\n# Compression: specify the number of channels, sample rate, dtype, optionally save the parameters\n# as default in ~/.mtscomp with --set-default\nmtscomp data.bin -n 385 -s 30000 -d int16 [--set-default]\n# Decompression\nmtsdecomp data.cbin -o data.decomp.bin\n```\n\nUsage:\n\n```\nusage: mtscomp [-h] [-d DTYPE] [-s SAMPLE_RATE] [-n N_CHANNELS] [-p CPUS]\n               [-c CHUNK] [-nc] [-v] [--set-default]\n               path [out] [outmeta]\n\nCompress a raw binary file.\n\npositional arguments:\n  path                  input path of a raw binary file\n  out                   output path of the compressed binary file (.cbin)\n  outmeta               output path of the compression metadata JSON file\n                        (.ch)\n\noptional arguments:\n  -h, --help            show this help message and exit\n  -d DTYPE, --dtype DTYPE\n                        data type\n  -s SAMPLE_RATE, --sample-rate SAMPLE_RATE\n                        sample rate\n  -n N_CHANNELS, --n-channels N_CHANNELS\n                        number of channels\n  -p CPUS, --cpus CPUS  number of CPUs to use\n  -c CHUNK, --chunk CHUNK\n                        chunk duration\n  -nc, --no-check       no check\n  -v, --debug           verbose\n  --set-default         set the specified parameters as the default\n\n\n\nusage: mtsdecomp [-h] [-o [OUT]] [--overwrite] [-nc] [-v] cdata [cmeta]\n\nDecompress a raw binary file.\n\npositional arguments:\n  cdata                 path to the input compressed binary file (.cbin)\n  cmeta                 path to the input compression metadata JSON file (.ch)\n\noptional arguments:\n  -h, --help            show this help message and exit\n  -o [OUT], --out [OUT]\n                        path to the output decompressed file (.bin)\n  --overwrite, -f       overwrite existing output\n  -nc, --no-check       no check\n  -v, --debug           verbose\n```\n\n\n## High-level API\n\nExample:\n\n```python\nimport numpy as np\nfrom mtscomp.mtscomp import compress, decompress\n\n# Compress a .bin file into a pair .cbin (compressed binary file) and .ch (JSON file).\ncompress('data.bin', 'data.cbin', 'data.ch', sample_rate=20000., n_channels=256, dtype=np.int16)\n# Decompress a pair (.cbin, .ch) and return an object that can be sliced like a NumPy array.\narr = decompress('data.cbin', 'data.ch')\nX = arr[start:end, :]  # decompress the data on the fly directly from the file on disk\narr.close()  # Close the file when done\n```\n\n\n## Low-level API\n\nExample:\n\n```python\nimport numpy as np\nfrom mtscomp import Writer, Reader\n\n# Define a writer to compress a flat raw binary file.\nw = Writer(chunk_duration=1.)\n# Open the file to compress.\nw.open('data.bin', sample_rate=20000., n_channels=256, dtype=np.int16)\n# Compress it into a compressed binary file, and a JSON header file.\nw.write('data.cbin', 'data.ch')\nw.close()\n\n# Define a reader to decompress a compressed array.\nr = Reader()\n# Open the compressed dataset.\nr.open('data.cbin', 'data.ch')\n# The reader can be sliced as a NumPy array: decompression happens on the fly. Only chunks\n# that need to be loaded are loaded and decompressed.\n# Here, we load everything in memory.\narray = r[:]\n# Or we can decompress into a new raw binary file on disk.\nr.tofile('data_dec.bin')\nr.close()\n```\n\n\n## Implementation details\n\n* **Multithreading**: since Python's zlib releases the GIL, the library uses multiple threads when compressing a file. The chunks are grouped in batches containing as many chunks as threads. After each batch, the chunks are written in the binary file in the right order (since the threads of the batch have no reason to finish in order).\n\n\n## Performance\n\nPerformance on an Neuropixels dataset (30 kHz, 385 channels) and Intel 10-core i9-9820X CPU @ 3.3GHz:\n\n* Compression ratio: -63% (compressed files are nearly 3x smaller)\n* Compression time (20 threads): 88 MB/s, **4x faster than real time**\n* Decompression time (single-threaded at the moment): 22 MB/s, **3x faster than real time**\n\n\n",
    "bugtrack_url": null,
    "license": "BSD",
    "summary": "Lossless compression for electrophysiology time-series",
    "version": "1.0.2",
    "split_keywords": [
        "lossless",
        "compresssion",
        "electrophysiology",
        "neuroscience"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "md5": "d857b448cd22860eb334017056428e4a",
                "sha256": "a00a6d46a6155af5bca44931ccf5045756ea8256db8fd452f5e0592b71b4db69"
            },
            "downloads": -1,
            "filename": "mtscomp-1.0.2-py2.py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "d857b448cd22860eb334017056428e4a",
            "packagetype": "bdist_wheel",
            "python_version": "py2.py3",
            "requires_python": null,
            "size": 16382,
            "upload_time": "2021-05-11T11:32:29",
            "upload_time_iso_8601": "2021-05-11T11:32:29.676498Z",
            "url": "https://files.pythonhosted.org/packages/5e/12/449d679e3aef2dcadfb9b275e2809d87bfeb798c7e9a911ee4bae536e24a/mtscomp-1.0.2-py2.py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "md5": "899b535494ee757e3b4bfd1296f870d7",
                "sha256": "609c4fe5a0d00532c1452b10318a74e04add8e47c562aca216e7b40de0e4bf73"
            },
            "downloads": -1,
            "filename": "mtscomp-1.0.2.tar.gz",
            "has_sig": false,
            "md5_digest": "899b535494ee757e3b4bfd1296f870d7",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 15967,
            "upload_time": "2021-05-11T11:32:31",
            "upload_time_iso_8601": "2021-05-11T11:32:31.014780Z",
            "url": "https://files.pythonhosted.org/packages/2e/ef/365e2dd214155b06d22622b3278de769d20e9e1d201538a941d62b609248/mtscomp-1.0.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2021-05-11 11:32:31",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "int-brain-lab",
    "github_project": "mtscomp",
    "travis_ci": true,
    "coveralls": false,
    "github_actions": false,
    "requirements": [
        {
            "name": "numpy",
            "specs": []
        }
    ],
    "lcname": "mtscomp"
}
        
Elapsed time: 0.02240s