This C++17 library reads, writes, compresses, decompresses and validates biomedical time series data (PPG, ACC, ECG) in the
pcore format, a protobuf-based file format (specification). It implements
pcore 2.1.0 (see .pcore-version) and behaves like the TypeScript implementation
pcore_ts.
- Read/write binary
.pcorefiles (protobuf) - Compression and decompression of timestamps, sensor values (integer and double) and metadata
- Validation of all rules of the specification, when compressing, decompressing, reading and writing
- Conversion between protobuf data and JSON, compressed (protobuf JSON format) or decompressed (human-readable)
- Builders for creating data
Everything is in the namespace PCore; #include "Pcore.h" includes all of it.
| Class / type | Responsibility |
|---|---|
Data, Sensor, Metadata, Photoplethysmograph, … |
Decompressed data model (include/models/) |
DataBuilder, MetadataBuilder, SensorBuilder |
Builders for creating decompressed data |
DataCompressor |
Compresses metadata, timestamps and sensors into protobuf data |
DataDecompressor |
Decompresses protobuf data into the decompressed data model |
PcoreFile |
Reading/writing binary .pcore files and JSON files |
Converter, DataForm |
Converts between protobuf data and compressed or decompressed JSON |
Inspector |
Reads properties of protobuf data without decompressing it, validation |
DataPb, SensorPb, MetadataPb, … |
Protobuf types generated from the pcore definition |
InvalidDataException, WrongValueException |
Thrown when data violates the pcore validation rules (structure / value range) |
PcoreVersion |
The implemented version of the specification |
#include "Pcore.h"
using namespace PCore;
const auto sensor = SensorBuilder().withIntValues({5, 7}).withElectrocardiogramChannel(1).build();
const auto data = DataBuilder().withTimestamps({1000, 1010}).withSensor(sensor).build();
PcoreFile::writePcoreBinary(DataCompressor::compress(data), "output.pcore");
const auto dataPb = PcoreFile::readPcoreBinary("output.pcore");
PcoreFile::writePcoreJson(Converter::convertToJson(dataPb, DataForm::Decompressed, 2), "output.json");
const Data decompressed = DataDecompressor::decompress(Converter::convertFromJson(PcoreFile::readPcoreJson("output.json")));Data is validated wherever it enters or leaves the library: DataCompressor::compress, DataDecompressor::decompress,
PcoreFile::readPcoreBinary, PcoreFile::decodePcoreBinary, PcoreFile::writePcoreBinary, Converter::convertToJson and Converter::convertFromJson throw an
InvalidDataException or a WrongValueException for invalid data. The get… functions of the Inspector therefore do not
validate again; for a protobuf object that was built by hand, call Inspector::validateCompressed first.
To examine a .pcore file that the validation rejects, switch the validation off explicitly. The file is then only decoded; a
file that cannot be decoded at all is still rejected with an InvalidDataException:
const auto dataPb = PcoreFile::readPcoreBinary("rejected.pcore", {false});PcoreFile::readPcoreBinary reads a local file. For the content of a .pcore file that comes from somewhere else, e.g. over
the network or from a database, use PcoreFile::decodePcoreBinary. It does the same checks and takes the same options (as
PcoreFile.decodePcoreBinary in pcore_ts). Do not decode such content with DataPb::ParseFromString alone, which does not
validate it:
const auto dataPb = PcoreFile::decodePcoreBinary(bytes); // bytes: std::string or std::string_viewErrors of the file system (e.g. a missing file) are thrown as std::system_error.
Exception messages do not quote values of the data (e.g. a device id or a wrong timezone offset), since messages often end
up in logs; a message about malformed JSON names the field instead. Messages of PcoreFile contain the path of the file,
which may itself be personal data if file names contain e.g. patient identifiers.
Writing replaces a file as a whole: the content goes into a new file next to it, which then takes the place of the old one.
If writing fails, e.g. because the disk is full, the old file stays as it was. The directory must be writable.
A new file can only be read and written by its owner (permissions 0600), since it holds health data. To share it with
other users, change its permissions after writing; an existing file keeps its permissions when it is written again.
Decoding and decompressing can need about 35 times the size of the data in memory: a valid file in which every value takes one byte grows by a factor of eight for every list of values and timestamps. A file of 48 MiB, for example, needs about 1.7 GiB. Usual recordings are far smaller (about 500 KB). If you read files or JSON from sources you do not control, e.g. uploads to a service, limit their size, so that a crafted file cannot exhaust the memory:
const auto dataPb = PcoreFile::readPcoreBinary(path, {true, 50'000'000}); // validate, at most 50 MB
const auto bytesPb = PcoreFile::decodePcoreBinary(bytes, {true, 50'000'000});
const auto json = PcoreFile::readPcoreJson(path, {50'000'000});
const auto jsonPb = Converter::convertFromJson(json, {50'000'000});Larger input is rejected with an InvalidDataException before it is read or parsed. Without the option only the limit of
protobuf applies to binary data (2 GiB) and there is no limit for JSON. Best reject large uploads already when receiving them.
Unix timestamps (UnixTimestamp, milliseconds) and integer sensor values are signed 64-bit integers. The full range is
supported; decompressed timestamps beyond INT64_MAX are rejected with a WrongValueException.
Converter::convertToJson writes one of two forms, and Converter::convertFromJson reads both.
DataForm::Compressed is the compressed data in the protobuf JSON format.
Every protobuf implementation can read and write it with the pcore proto file. A sensor holds its values container and its sensor
type directly, enum values are written by name, 64-bit integers as strings, and fields with their default value are omitted:
{
"metadata": { "pcoreVersion": { "major": 2, "minor": 1 } },
"compressedTimestampsContainer": { "firstUnixTimestampMs": "1000", "outerSectionsDurationsMs": [0], "innerSectionsDurationsMs": [10], "sectionsSizes": [2] },
"sensors": [ { "intValuesContainer": { "values": ["5", "2"] }, "electrocardiogram": { "channel": 1 } } ]
}When reading, the alternatives that protobuf JSON allows are accepted as well: numbers instead of strings for 64-bit integers,
numbers instead of names for enum values, and the field names of the proto file (compressed_timestamps_container).
DataForm::Decompressed is the human-readable form of the pcore libraries with the decompressed timestamps and values (the
same as in pcore_ts). It is not a protobuf JSON format:
{
"metadata": { "timezoneOffsetMin": 0, "pcoreVersion": { "major": 2, "minor": 1, "patch": 0 } },
"timestamps": [1000, 1010],
"sensors": [ { "valuesType": "intValuesContainer", "values": [5, 7], "electrocardiogram": { "channel": 1 } } ]
}For more examples see examples/ (pcore_file_example, pcore_inspector_example, pcore_converter_example).
Requirements: CMake ≥ 3.24, a C++17 compiler, git and network access to github.com when configuring.
git submodule update --init --recursive
make unittestmake unittest configures the project as an optimized Release build (another type with cmake -DCMAKE_BUILD_TYPE=Debug;
the first run builds protobuf 3.21.9 from the submodule external/google-protobuf with the same type and compiler),
builds the library pcore_extern (libpcore_extern.a), the tests and the examples, and runs all tests with ctest:
build/test/bin/specTest— the language-independent test cases of the specification (unittest/**/*.jsonof the tag in.pcore-version), read at runtimebuild/test/bin/unitTest— the tests of this implementation
make format formats the sources with clang-format, make doxygen generates the API documentation into html/.
make sanitize builds and runs the tests once more with AddressSanitizer and UndefinedBehaviorSanitizer in build-sanitize/,
which stop a test at every access outside of memory and every undefined behavior (as the CI does).
The checks run on every pull request on GitHub (.github/workflows/checks.yml): make format with clang-format 14 must leave
no diff, and make unittest and make sanitize must pass, with g++ 11 and CMake 3.24, the minimum version.
To implement a new version of the specification, change the tag in .pcore-version and reconfigure: the proto file, the version
stamped into every compressed file (PcoreVersion) and the spec test cases are taken from that tag.
The project can also be built as a part of another CMake project. Then only the library is built, and no setting of the other project is changed:
add_subdirectory(pcore_cpp) # or FetchContent
target_link_libraries(my_target PRIVATE pcore_extern)The include directories, protobuf and C++17 come with the target pcore_extern. The tests and examples are switched off in
this case; -DPCORE_BUILD_TESTS=ON and -DPCORE_BUILD_EXAMPLES=ON switch them on, and ctest --test-dir <build directory>/pcore_cpp
runs the tests. As in a build of its own, protobuf is built and the pcore specification is fetched when configuring.
Releases are git tags of the form vMAJOR.MINOR.PATCH, equal to PCORE_CPP_VERSION_* in CMakeLists.txt, the same
scheme as the TypeScript implementation pcore_ts:
| Part | Meaning |
|---|---|
| MAJOR | The generation of the pcore format that the library implements: 2 for pcore2. pcore1 is outdated and not supported. |
| MINOR | A new feature or a changed interface of the library, also for a new minor version of the pcore specification. |
| PATCH | A fix of the library. |
The library version counts independently of the version of the specification it implements (.pcore-version).
Which release implements which version of the specification:
| pcore_cpp | pcore specification |
|---|---|
| 2.0.0 (first release) | 2.1.0 |
Copyright © 2023 PREVENTICUS GmbH
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
-
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
-
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
-
Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.