Skip to main content

Imperfekt - Understanding Data Imperfections in Time-Series

PyPI version License: MIT Python 3.10+

A comprehensive analysis toolkit for studying "imperfect" data patterns in time-series datasets. Imperfection refers to missingness, implausible values, irregular sampling, and other data quality issues that can be indicated using a binary mask.

Overview

This library provides tools to analyze data quality issues in time-series data, including:

  • Preliminary analysis of the observed values (description, normality, correlation)
  • Irregularity analysis of the observation time grid (intervals, burstiness, dominant frequency)
  • Intravariable analysis of imperfection patterns for individual variables
  • Intervariable analysis of co-occurring imperfections across multiple parameters
  • Group- and event-based analysis to compare imperfection between cohorts or around events
  • Case-level metrics and stratification to rank and bucket individual cases by imperfection
  • Feature generation based on imperfection patterns for downstream ML tasks

Two imperfection types are supported: "missingness" (nulls) and "plausibility" (values flagged as implausible via IQR/MAD bounds or explicit reference ranges).

Installation

Install the library using pip:

pip install imperfekt

Note: Plots are drawn with matplotlib by default. If you switch to Plotly (plot_library="plotly") and export figures as static images (save_results=True), some environments may raise a plotly_get_chrome/Kaleido error at runtime. This happens because Kaleido needs a Chrome/Chromium binary. Install Chrome manually, or run:

plotly_get_chrome

Quick Start

import polars as pl
from imperfekt import Imperfekt, FeatureGenerator

# Load your time-series data
df = pl.read_parquet("your_data.parquet")

# Configure Analyzer Setup
analyzer = Imperfekt(
    df=df,
    id_col="id",  # Unique identifier column
    clock_col="clock",  # Timestamp column
    cols=["var1", "var2"],  # Variables to analyze
    save_path="./results",
    imperfection="missingness",  # or "plausibility"
)

# Simple intravariable imperfection stats
analyzer.intravariable.column_statistics(save_results=True)
print(analyzer.intravariable.results.cs_overall_statistics)
print(analyzer.intravariable.results.cs_case_level_statistics)

# Run full imperfection analysis (preliminary, irregularity, intra- and intervariable analyses)
analyzer.run()  # cheap_mode=True for a faster, reduced set of analyses

# Compare imperfection between groups/labels, or around events
analyzer.run_grouped_analysis(annotation_col="age")
analyzer.run_event_based_analysis(events_df=events_df, window_size=300)

# Or generate imperfection-aware features for ML
fg = FeatureGenerator(df=df, id_col="id", clock_col="clock", variable_cols=["var1", "var2"])
features_df = fg.add_binary_masks().add_temporal_features().df

# Or restrict individual steps to a subset of variables
features_df = (
    fg.add_binary_masks(cols=["var1"])
    .add_temporal_features(cols=["var1"])
    .add_window_features(rolling_window_sizes=[2], ewma_alphas=[0.3], cols=["var1", "var2"])
    .df
)

# Or generate everything at once
features_df = fg.generate_all_features()

Runnable end-to-end scripts live in examples/scripts/.

Example datasets

imperfekt.datasets generates vital-sign data with a known missingness pattern, to try the analyses out or to see what each metric responds to:

from imperfekt import Imperfekt, datasets

df = datasets.mcar_df(n_cases=100, p=0.2)  # id, clock, heartrate, resprate, o2sat, sbp
Imperfekt(df, id_col="id", clock_col="clock", save_path="results/mcar").run()
Generator Pattern
mcar_df Missing completely at random
mar_df Missingness depends on another, fully observed variable
mnar_df Missingness depends on the missing value itself
sequential_df Each variable drops out in contiguous runs
block_df Variables drop out together (co-missingness)
time_trend_df Missingness changes over each case's stay

All generators take n_cases, n_steps, variables, freq_seconds, irregular and seed; return_complete=True also returns the fully observed data. The mechanisms follow PyGrinder. run_synthetic_datasets.py runs imperfekt on all of them and compares the results.

Library Structure

imperfekt/
├── analysis/
│   ├── preliminary/     # Basic data exploration
│   ├── irregularity/    # Observation-grid irregularity
│   ├── intravariable/   # Single variable analysis
│   ├── intervariable/   # Multi-variable patterns
│   └── utils/           # Shared utilities (masking, statistics, stratification, plotting)
├── features/            # Feature engineering
│   ├── core.py          # FeatureGenerator class
│   ├── temporal.py      # Time-based features
│   ├── window.py        # Rolling and EWMA features
│   ├── irregularity.py  # Sampling-rhythm features
│   └── interaction.py   # Variable interactions
├── datasets/            # Synthetic example data with known missingness patterns
└── config/              # Default settings

Module-level documentation: analysis/intravariable/README.md, analysis/intervariable/README.md, analysis/irregularity/README.md, features/README.md.

Data Format

The library expects time-series data with the following structure:

Column Description
id Unique identifier for each time-series (e.g., patient, sensor)
clock Timestamp for each observation (optional)
var1, var2, ... Variables to analyze

Gridded data

Irregular measurements are often resampled onto a regular grid (e.g. one row per minute), which turns every grid step without a measurement into a row in which all analysed variables are null. Imperfekt treats the rows with at least one observed value as the observation occasions and picks the row set per aspect:

Aspect Rows analysed
Intravariable every row: the share of grid steps without a value per variable
Intervariable the occasions by default; Imperfekt(..., intervariable_rows="all") keeps every row
Irregularity always the occasions: intervals are measured between actual observations
Preliminary observed values only, so the row set does not matter

An all-null row only exists because the data was put on a time grid, so the question is not whether the data is gridded but what the grid means. Keep the default when the grid is a resampling artefact (irregular measurements upsampled for modelling). Use intervariable_rows="all" when the grid is the real measurement schedule (e.g. a monitor with fixed sampling slots), where an all-null row carries information such as a detached sensor.

If whole rows drop out together (block missingness: a disconnected monitor, a transmission outage), the default hides that pattern from the intervariable analysis, because the dropped-out rows are not occasions. It still shows as long intervals in the irregularity metrics and as simultaneous gaps in the intravariable metrics, but to see it as co-missingness, run with intervariable_rows="all".

Diagnosing block missingness

Whether an all-null row is an interruption or a resampling artefact depends on how the data was collected, so check that first. If you are unsure, two numbers from a default run decide it in most cases:

analyzer = Imperfekt(df, id_col="id", clock_col="clock", renderer=None)

# 1. Are there all-null rows at all? (Always computed on every row.)
analyzer.intervariable.row_statistics(save_results=False)
n_empty, pct_empty = analyzer.intervariable.results.rs_empty_statistics

# 2. Is the grid step the measurement rhythm? Bin at the grid step, here 1 minute.
analyzer.irregularity.dominant_frequency(bin_resolution_seconds=60, save_results=False)
analyzer.irregularity.results.domf_frequency_summary.select(
    "dominant_interval_seconds", "adherence_rate"
)
What you see What it means Use
pct_empty ≈ 0 no all-null rows either; the results are the same
dominant interval = grid step, adherence_rate high the grid is the measurement rhythm and all-null rows interrupt it: block missingness intervariable_rows="all"
dominant interval several grid steps, adherence_rate low the grid is finer than the measurements: resampling artefact default ("occasions")

rs_empty_case_level_statistics then shows how the all-null rows are spread over the cases: blocks often concentrate in a few cases, resampling gaps affect every case. For orientation, on the bundled datasets.block_df() (5-minute schedule, 18 % all-null rows) the dominant interval is 300 s with an adherence of 0.97; on irregular ~5-minute measurements upsampled to 1 minute (80 % all-null rows) it is 180 s, three grid steps, with an adherence of 0.45. Occasions are defined on the raw values, so in plausibility mode a row of measured but implausible values still counts. A case without any occasion therefore appears in the intravariable results only.

Bias of "occasions" in the co-imperfection. Keeping only rows with at least one observed value is a selection on the masks themselves: it removes exactly the rows where all variables are missing together. Variables that are missing independently of each other can then show a clearly negative phi and a "significant" chi-squared test. In a simulation with a control variable missing completely at random, phi to the other variables was −0.13 on occasions and −0.005 on all rows. With "all" the bias goes the other way on an upsampled grid, where the artificial all-null rows inflate phi. Neither setting is unbiased in every case, so with "occasions" symmetric_correlation() also reports phi and the chi-squared p-value on every row in results.sc_row_set_sensitivity (and in the HTML report), and warns if phi differs by 0.1 or more for a pair. A large difference means the row choice, not the data, drives the result for that pair.

Key Dependencies

  • polars: High-performance data processing
  • matplotlib / plotly: Static and interactive visualizations
  • statsmodels, pingouin, scikit-posthocs: Statistical computations

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

AI Disclaimer

We used AI (Google Gemini 3.1 Pro, Anthropic Claude Opus 5) during the development of this repository. All AI-generated output was reviewed by the authors, who take full responsibility for the code.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Metadata

Release files for imperfekt 0.7.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for imperfekt 0.7.2
File Size Uploaded Provenance Actions
imperfekt-0.7.2.tar.gz 410.1 kB Without provenance Details for imperfekt-0.7.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for imperfekt 0.7.2
File Interpreter ABI Platform Actions
imperfekt-0.7.2-py3-none-any.whl Python 3 none any Details for imperfekt-0.7.2-py3-none-any.whl

Total release size: 848.5 kB

Release files / imperfekt-0.7.2.tar.gz

Download URL imperfekt-0.7.2.tar.gz
Size 410.1 kB
Tags Source
SHA-256 checksum
How to use checksums
9ef4869a627d1d72b81ad24d70c00a4e82b01970a26a2456fb2b16f959c6198c
BLAKE2b-256 checksum
How to use checksums
69dc747a866011ebdf7790599cde92116d7e04aedc5d1c1cf91c05baa9e3cd49
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.7.6

Release files / imperfekt-0.7.2-py3-none-any.whl

Download URL imperfekt-0.7.2-py3-none-any.whl
Size 438.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0788ba317c7765497ee1eef682cb4b203de8076e572f0eb8a8d0cb7917cf07d3
BLAKE2b-256 checksum
How to use checksums
455d9d3498c53f01f0120f43879e4e72a00a74ff5a3bdad2ef24f053295ec246
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.7.6

Security for imperfekt 0.7.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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