API reference¶
Generated from the source. The documented public surface is everything exported
from the top-level ehrlint package; the modules below are where it lives.
Running an audit¶
ehrlint.audit ¶
Running the check battery and assembling a report.
One function, :func:run_audit. It resolves the checks, runs each one, records
skips separately from passes, validates that every finding's evidence really
exists in the input, and computes the exit code.
The distinction the whole report hangs on: a skipped check is not a passed check. A clean report that quietly skipped six of ten checks is worse than a dirty one, because it reads as reassurance. Skips are first-class in the summary and the exit code logic, and the report prints them above the findings.
AuditSummary
dataclass
¶
Counts a reader needs before looking at anything else.
Source code in src/ehrlint/audit.py
to_dict ¶
JSON-safe dict.
Source code in src/ehrlint/audit.py
to_markdown ¶
A compact summary table.
Source code in src/ehrlint/audit.py
AuditReport
dataclass
¶
The complete result of one audit.
Source code in src/ehrlint/audit.py
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | |
by_severity ¶
findings_for ¶
Every finding from one check, worst first.
A check may emit more than one: LK001 describes post-index events as an observation and flags a leaky feature matrix as an error.
Source code in src/ehrlint/audit.py
finding ¶
The most serious finding from one check, or None if it skipped.
Returns the one that fired where there is one, not the first emitted. A caller asking "what did LK001 find?" must not be handed the descriptive observation while an error sits behind it.
Source code in src/ehrlint/audit.py
was_skipped ¶
to_dict ¶
The SPEC §6.4 report JSON.
Source code in src/ehrlint/audit.py
write_json ¶
Write the report JSON.
Source code in src/ehrlint/audit.py
write_findings_jsonl ¶
Write the findings as JSONL (SPEC §6.3).
write_markdown ¶
Write the Markdown report.
Source code in src/ehrlint/audit.py
write_html ¶
write_all ¶
Write every artifact: HTML, Markdown, JSON, findings JSONL, figures.
run_audit ¶
run_audit(
ctx: AuditContext,
checks: list[str] | None = None,
*,
fail_on: Severity | str = Severity.ERROR,
validate_evidence: bool = True,
) -> AuditReport
Run the check battery against a context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ctx
|
AuditContext
|
The resolved inputs. |
required |
checks
|
list[str] | None
|
Check ids to run. None or empty runs all of them. |
None
|
fail_on
|
Severity | str
|
The severity at which the audit is considered failed. |
ERROR
|
validate_evidence
|
bool
|
Assert each finding's example subjects exist in the input. On by default — it is the mechanical guard against a check reporting rows it invented. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
An |
AuditReport
|
class: |
Source code in src/ehrlint/audit.py
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 | |
The context¶
ehrlint.context ¶
The audit context: everything a check needs, resolved once.
Index dates are the expensive, fiddly part — they come either from an event code or from a labels table, and every check needs them — so they are resolved once here and cached rather than recomputed per check.
This module is an addition to the SPEC §4.1 layout. §5.2 names
AuditContext.from_meds(...) as public API but gives it no home; putting it in
checks/base.py would make the check protocol import the loaders, and putting
it in cli.py would make it unavailable to the Python API. See
docs/decisions.md D-005.
AuditContext
dataclass
¶
The resolved inputs for one audit.
Attributes:
| Name | Type | Description |
|---|---|---|
events |
DataFrame
|
The canonical event table. |
task |
TaskSpec
|
The task specification. |
splits |
Splits | None
|
Split assignments, if supplied. |
features |
FeatureMatrix | None
|
A feature matrix, if supplied. |
labels |
DataFrame | None
|
A labels frame with |
source_format |
str
|
|
source_path |
str | None
|
Where the data came from. |
dataset_metadata |
dict[str, Any]
|
Whatever the MEDS manifest said. |
warnings |
list[str]
|
Non-fatal problems found while loading. |
Source code in src/ehrlint/context.py
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 | |
n_subjects
property
¶
Distinct subjects in the event data. The denominator for every rate.
from_meds
classmethod
¶
from_meds(
data_dir: str | Path,
*,
task_spec: str | Path | TaskSpec,
splits_path: str | Path | None = None,
labels_path: str | Path | None = None,
features_path: str | Path | None = None,
encounter_column: str | None = None,
) -> AuditContext
Build a context from a MEDS dataset directory.
When splits_path is omitted, the dataset's own
metadata/subject_splits.parquet is used if present — that is where
MEDS keeps them, and requiring a separate file would be busywork.
Source code in src/ehrlint/context.py
from_omop
classmethod
¶
from_omop(
data_dir: str | Path,
*,
task_spec: str | Path | TaskSpec,
splits_path: str | Path | None = None,
labels_path: str | Path | None = None,
features_path: str | Path | None = None,
) -> AuditContext
Build a context from an OMOP CDM extract.
Source code in src/ehrlint/context.py
from_frames
classmethod
¶
from_frames(
events: DataFrame,
*,
task_spec: str | Path | TaskSpec,
splits: Splits | dict[str, list[str]] | None = None,
labels: DataFrame | None = None,
features: FeatureMatrix | None = None,
) -> AuditContext
Build a context from in-memory frames, for tests and the library API.
Source code in src/ehrlint/context.py
timed ¶
index_dates ¶
Each subject's index date, resolved once and cached.
Two sources, in this order:
- a labels table, whose
prediction_timeis the index date — this wins because it is what the model was actually trained against; - the task spec's index event code.
Returns:
| Type | Description |
|---|---|
DataFrame
|
A frame with |
DataFrame
|
resolvable index date are absent, not given a fabricated one. |
Source code in src/ehrlint/context.py
events_with_index ¶
Timed events joined to their subject's index date.
An inner join: a subject with no index date has no task to leak relative to, so their events are excluded rather than compared against a null.
Source code in src/ehrlint/context.py
match_code_sets ¶
Filter events to any of several :class:CodeSet objects.
A code set with no system matches the bare code in any vocabulary, which can cross-match; the context records a warning for that rather than refusing, since many datasets carry no systems at all.
Source code in src/ehrlint/context.py
subject_split ¶
Subject id to split name, or an empty frame when no splits exist.
describe ¶
Summary for the report header.
Source code in src/ehrlint/context.py
all_warnings ¶
Loading warnings plus anything the task and splits flag.
Collected here so the report shows every reason a result might be weaker than it looks, in one place above the findings.
Source code in src/ehrlint/context.py
Checks¶
ehrlint.checks.base ¶
The check protocol and registry.
A check is a small class with an id, a name, a rationale, a default severity,
and a run(ctx) that returns findings. Third parties register their own with
:func:register_check.
Two rules every check obeys:
- Evidence or nothing. A finding with a non-zero subject count must carry
the rows that produced it. :func:
~ehrlint.schemas.findings.make_findingis the only constructor, and it derives counts from the offending frame rather than taking them on trust. - Skip loudly. A check that cannot run — no encounter ids, no horizon, no
splits — returns a :class:
~ehrlint.schemas.findings.SkippedCheckwith a reason. It never returns "no findings", because a skipped check is not a pass and a reader must be able to tell the difference.
Checks are also expected to be deterministic: same input, same findings, same examples, same order. A property test asserts it.
Check ¶
Bases: Protocol
Anything that can audit an :class:~ehrlint.context.AuditContext.
Source code in src/ehrlint/checks/base.py
BaseCheck ¶
Convenience base for the built-in checks.
Supplies the metadata attributes and a few helpers every check wants: building a skip, counting the denominator, and resolving code sets.
Source code in src/ehrlint/checks/base.py
skip ¶
clean ¶
A zero-count finding, meaning the check ran and found nothing.
Distinct from a skip: this is a genuine pass, and it appears in the report as such so a reader can see what was actually verified.
Source code in src/ehrlint/checks/base.py
metadata ¶
Check metadata for the report and the docs.
Source code in src/ehrlint/checks/base.py
register ¶
Add a check instance to the registry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
check
|
Check
|
The check. |
required |
replace
|
bool
|
Allow overwriting an existing id. Off by default, because two checks silently sharing an id would make findings ambiguous. |
False
|
Raises:
| Type | Description |
|---|---|
RegistryError
|
On a duplicate id, or on a check missing its metadata. |
Source code in src/ehrlint/checks/base.py
register_check ¶
register_check(
*,
id: str,
name: str,
severity: Severity | str = Severity.WARNING,
description: str = "",
rationale: str = "",
replace: bool = False,
) -> Callable[
[Callable[[AuditContext], CheckResult]],
Callable[[AuditContext], CheckResult],
]
Decorator registering a plain function as a check.
The SPEC §5.2 extension point::
@el.register_check(id="LK099", name="my_check", severity="warning")
def my_check(ctx: el.AuditContext) -> list[el.Finding]:
...
Returns the undecorated function, so it stays directly callable and testable.
Source code in src/ehrlint/checks/base.py
get_check ¶
Look up a check by id.
Raises:
| Type | Description |
|---|---|
RegistryError
|
If unknown, listing what is registered — a typo in a
|
Source code in src/ehrlint/checks/base.py
all_checks ¶
check_ids ¶
resolve_checks ¶
Resolve a selection of check ids to check instances.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
selection
|
list[str] | None
|
Ids to run. None or empty means all of them. |
None
|
Returns:
| Type | Description |
|---|---|
list[Check]
|
Checks in id order. |
Source code in src/ehrlint/checks/base.py
clear_registry ¶
registry_snapshot ¶
restore_registry ¶
ehrlint.checks.leakage ¶
The check battery: LK001 through LK010.
Each check documents its rationale, runs one stated query, and returns findings
that carry the rows that triggered them. The query string on every finding is
SQL-ish pseudocode of the exact logic, so a reader can reproduce the result by
hand rather than trusting the implementation.
The checks live in one module rather than ten files. SPEC §4.1 sketches
lk001_post_index.py, lk002_same_encounter.py, and so on, but they share the
index-date join, the code-set matcher, and the skip vocabulary — splitting them
would mean ten files importing the same six helpers and a reader hopping
between them to compare two checks that differ by one predicate. See
docs/decisions.md D-006.
PostIndexFeatures ¶
Bases: BaseCheck
LK001 — events used as predictors that happen after the index date.
Source code in src/ehrlint/checks/leakage.py
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | |
SameEncounter ¶
Bases: BaseCheck
LK002 — outcome codes recorded in the same encounter as the index event.
Source code in src/ehrlint/checks/leakage.py
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 | |
OutcomeProxy ¶
Bases: BaseCheck
LK003 — proxy codes for the outcome present before the index date.
Source code in src/ehrlint/checks/leakage.py
ImmortalTime ¶
Bases: BaseCheck
LK004 — negatives who were not observed for the full horizon.
Source code in src/ehrlint/checks/leakage.py
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 | |
SplitOverlap ¶
Bases: BaseCheck
LK005 — a subject appearing in more than one split.
Source code in src/ehrlint/checks/leakage.py
TemporalSplit ¶
Bases: BaseCheck
LK006 — a temporal split that does not actually respect time.
Source code in src/ehrlint/checks/leakage.py
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 | |
LabelDefinition ¶
Bases: BaseCheck
LK007 — the outcome ascertained with information from after the window.
Source code in src/ehrlint/checks/leakage.py
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 | |
EncounterGroup ¶
Bases: BaseCheck
LK008 — one encounter or provider contributing to two splits.
Source code in src/ehrlint/checks/leakage.py
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 | |
DuplicateSubjects ¶
Bases: BaseCheck
LK009 — one person under more than one subject id.
Source code in src/ehrlint/checks/leakage.py
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 | |
HorizonViolation ¶
Bases: BaseCheck
LK010 — outcomes outside the declared horizon counted as positives.
Source code in src/ehrlint/checks/leakage.py
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 | |
register_builtins ¶
Register every built-in check.
Called at import time of :mod:ehrlint.checks. Idempotent by default, so
re-importing does not raise on duplicate ids.
Source code in src/ehrlint/checks/leakage.py
Schemas¶
ehrlint.schemas.events ¶
The canonical event table.
Everything ehrlint audits is reduced to one long-format table:
| column | type | meaning |
|---|---|---|
subject_id |
string | the person. String, always -- see below |
time |
datetime, nullable | when it happened; null for static facts |
code |
string | what happened |
code_system |
string, nullable | which vocabulary code belongs to |
numeric_value |
float, nullable | a measured value |
text_value |
string, nullable | a free-text value |
encounter_id |
string, nullable | for the same-encounter and group checks |
subject_id is normalized to string even though MEDS types it int64.
ehrlint joins subject ids against splits files, feature matrices, and label
tables that come from different tools, and an int/string mismatch between two
of them produces an empty join that looks like "no leakage found". A silent
false-clean is the worst failure mode an auditor can have, so everything is
coerced to string at the boundary and compared as strings throughout.
encounter_id and code_system are extensions beyond MEDS, which has
neither. See docs/decisions.md D-002. Both are nullable, and the checks
that need them skip with a stated reason rather than silently passing when they
are absent.
empty_events ¶
An empty canonical event table with the right dtypes.
Returned rather than a bare pl.DataFrame() so that downstream filters
and joins behave identically on empty input. An auditor that crashes on an
empty table is an auditor nobody runs twice.
Source code in src/ehrlint/schemas/events.py
coerce_events ¶
Coerce a frame to the canonical schema.
Adds any missing optional columns as all-null, casts every column to its
canonical dtype, and orders the columns. subject_id and
encounter_id become strings, which is the normalization that
prevents a silent empty join later.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
The frame to coerce. |
required |
source
|
str
|
Named in error messages. |
'events'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A frame with exactly :data: |
Raises:
| Type | Description |
|---|---|
SchemaError
|
If a required column is missing, naming which. |
Source code in src/ehrlint/schemas/events.py
split_meds_code ¶
Recover code_system from the MEDS SYSTEM//code convention.
MEDS has no code_system column; the convention is to namespace inside
the code string. This splits on the first separator, leaving code as
the local part. A code with no separator keeps a null system rather
than being assigned a guessed one.
Source code in src/ehrlint/schemas/events.py
validate_events ¶
Check an event table for problems worth warning about.
Returns human-readable warnings rather than raising: every one of these is survivable, and a completed audit is more useful than a hard stop. An empty list means nothing notable.
Source code in src/ehrlint/schemas/events.py
events_hash ¶
A stable content hash of an event table.
Recorded in the report so two audits can be compared and a finding can be tied to the exact data that produced it. Computed from the shape plus a digest of the sorted contents, so it is invariant to row order — the same data loaded by two different readers hashes the same.
Source code in src/ehrlint/schemas/events.py
subjects ¶
Distinct non-null subject ids, sorted. Deterministic ordering.
Source code in src/ehrlint/schemas/events.py
timed_events ¶
Events that carry a timestamp.
Static events (null time) are excluded from every time-ordering check.
Treating a null time as the epoch would make every static fact look like a
pre-index event, which is both wrong and the kind of wrong that produces
confident false findings.
Source code in src/ehrlint/schemas/events.py
ehrlint.schemas.task ¶
The task specification: index date, outcome, horizon, follow-up.
This is the object every check reasons against. A leak is only definable relative to a task: "post-index features" needs an index date, and "immortal-time bias" needs a follow-up rule.
The spec is deliberately strict. A task definition that is ambiguous about its own horizon cannot be audited meaningfully, so ehrlint refuses it at load time rather than producing findings whose meaning depends on a guess.
SplitStrategy ¶
Duration ¶
Bases: BaseModel
A horizon or window length, e.g. 2y.
Source code in src/ehrlint/schemas/task.py
days
property
¶
Length in days.
Months and years use 30.4375 and 365.25 days. That is an approximation, and it is the right one for a horizon: "within two years of the index date" is a study design choice with a tolerance of days, not a calendar-exact boundary. Where exactness matters, express the horizon in days.
parse
classmethod
¶
Parse "2y" into Duration(n=2, unit="y").
Raises:
| Type | Description |
|---|---|
TaskSpecError
|
On anything unparseable, with the accepted forms named. A horizon is load-bearing, so a typo must not become a silently different number. |
Source code in src/ehrlint/schemas/task.py
CodeSet ¶
Bases: BaseModel
A set of codes in one vocabulary.
Source code in src/ehrlint/schemas/task.py
IndexDef ¶
Bases: BaseModel
How each subject's index date is determined.
Source code in src/ehrlint/schemas/task.py
from_labels
property
¶
Whether index dates come from a labels table rather than an event code.
OutcomeDef ¶
Bases: BaseModel
How the outcome is ascertained.
Source code in src/ehrlint/schemas/task.py
FollowUp ¶
Bases: BaseModel
Follow-up requirements, which is where immortal-time bias lives.
Source code in src/ehrlint/schemas/task.py
SplitsSpec ¶
Bases: BaseModel
How the splits were constructed, so the split checks know what to expect.
Source code in src/ehrlint/schemas/task.py
TaskSpec ¶
Bases: BaseModel
A complete task definition.
Source code in src/ehrlint/schemas/task.py
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 | |
from_yaml
classmethod
¶
Load a task spec from YAML.
Source code in src/ehrlint/schemas/task.py
from_dict
classmethod
¶
Build a task spec from a plain dict, accepting documented shorthands.
Source code in src/ehrlint/schemas/task.py
to_yaml ¶
Write the task spec to YAML, round-trippable through from_yaml.
Source code in src/ehrlint/schemas/task.py
describe ¶
Short summary for the report header.
Source code in src/ehrlint/schemas/task.py
warnings ¶
Things about this spec that will limit what can be audited.
Returned rather than raised: an under-specified task is still worth auditing for what it does declare, but the report should say which checks were weakened.
Source code in src/ehrlint/schemas/task.py
ehrlint.schemas.splits ¶
Train/validation/test splits.
Two input shapes, one model:
- ehrlint's own JSON —
{"train": ["s1", ...], "valid": [...], "test": [...]}(SPEC §6.2); - a MEDS
subject_splits.parquetwithsubject_idandsplit, whose split names aretrain,tuning,held_outrather than train/valid/test.
Those two vocabularies are reconciled here, with an alias map, because
tuning and valid mean the same thing and a user should not have to rename
their splits to run an audit. See docs/decisions.md D-003.
Subject ids are normalized to string for the same reason as in the event table: an int/string mismatch between a splits file and an event table produces an empty intersection, which looks exactly like "no overlap found".
Splits ¶
Bases: BaseModel
Subject ids per split.
Source code in src/ehrlint/schemas/splits.py
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | |
get ¶
all_subjects ¶
sizes ¶
overlaps ¶
Subject ids appearing in more than one split.
Returns:
| Type | Description |
|---|---|
dict[tuple[str, str], list[str]]
|
|
dict[tuple[str, str], list[str]]
|
intersects, sorted. Empty when the splits are disjoint. |
Source code in src/ehrlint/schemas/splits.py
split_of ¶
Subject id -> the splits it appears in.
A subject with more than one entry is an LK005 finding.
Source code in src/ehrlint/schemas/splits.py
as_frame ¶
Long-format frame with subject_id and split.
Source code in src/ehrlint/schemas/splits.py
describe ¶
Summary for the report header.
Source code in src/ehrlint/schemas/splits.py
from_json
classmethod
¶
Load ehrlint's own splits JSON (SPEC §6.2).
Source code in src/ehrlint/schemas/splits.py
from_mapping
classmethod
¶
Build from a plain mapping of split name to subject ids.
Source code in src/ehrlint/schemas/splits.py
from_meds
classmethod
¶
Load a MEDS subject_splits.parquet.
Expects subject_id and split. MEDS split names (train,
tuning, held_out) are mapped to ehrlint's canonical ones.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
The splits parquet. |
required |
id_map
|
dict[str, str] | None
|
Surrogate-to-original subject id mapping, when the dataset carries one. The splits file has to use the same int64 ids as the event shards; without the same mapping applied here, the splits would name subjects the event table does not contain and LK005 and LK008 would both find nothing to compare. |
None
|
Source code in src/ehrlint/schemas/splits.py
from_frame
classmethod
¶
Build from a long-format frame with subject_id and split.
Source code in src/ehrlint/schemas/splits.py
write_json ¶
Write in ehrlint's splits JSON format.
Source code in src/ehrlint/schemas/splits.py
warnings ¶
Problems worth reporting that are not themselves findings.
Source code in src/ehrlint/schemas/splits.py
canonical_split_name ¶
Map a split name to its canonical form.
An unrecognized name is kept as-is rather than guessed at: a project may legitimately have a fourth split, and renaming it would hide that.
Source code in src/ehrlint/schemas/splits.py
ehrlint.schemas.findings ¶
Findings: what a check reports, and the evidence it must carry.
The §0 rule this module exists to enforce: do not fabricate leakage statistics. Every finding references the concrete rows that triggered it — subject ids, event times, feature names — not just a count.
A Finding with a non-zero n_subjects and no examples is a contradiction,
and :meth:Finding.validate_evidence raises on it. That is deliberate: a
count without rows is an assertion a user cannot check, and an auditor whose
claims cannot be checked is worse than no auditor.
Findings are also deterministic: given the same inputs, the same findings in the same order with the same examples. Example rows are sorted before truncation so a run on shuffled input produces identical output. A property test asserts it.
Severity ¶
Bases: StrEnum
What a finding means for the task.
error-- the task is invalid as defined. Post-index features, split overlap, a label using future information.warning-- a suspicious pattern needing human review. Proxies, temporal edge cases.info-- descriptive statistics, not a problem.
Source code in src/ehrlint/schemas/findings.py
Finding ¶
Bases: BaseModel
One leakage finding, with the evidence that produced it.
Source code in src/ehrlint/schemas/findings.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 | |
subject_rate
property
¶
Affected fraction of subjects, or None when the denominator is zero.
None rather than 0.0: a rate with no denominator is undefined,
and reporting zero would read as "no subjects affected".
validate_evidence ¶
Assert the example rows exist in the source data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
events
|
DataFrame | None
|
The canonical event table, when the examples are events. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If an example references a subject absent from the data, which would mean the finding was constructed rather than observed. |
Source code in src/ehrlint/schemas/findings.py
to_dict ¶
JSON-safe dict, the §6.3 findings-JSONL shape.
Source code in src/ehrlint/schemas/findings.py
examples_frame ¶
The example rows as a frame, for finding.examples.head() ergonomics.
SkippedCheck ¶
Bases: BaseModel
A check that could not run, and why.
Recorded explicitly so a clean report is distinguishable from an incomplete one. A skipped check is not a pass.
Source code in src/ehrlint/schemas/findings.py
make_finding ¶
make_finding(
check_id: str,
*,
name: str,
severity: Severity,
message: str,
offending: DataFrame,
n_total_subjects: int,
query: str,
subject_column: str = "subject_id",
example_columns: list[str] | None = None,
detail: dict[str, Any] | None = None,
max_examples: int = MAX_EXAMPLES,
) -> Finding
Build a finding from the rows that triggered it.
The single constructor every check uses, so evidence handling is uniform: counts come from the offending frame, examples are sorted before truncation for determinism, and the subject list is derived rather than passed in.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
check_id
|
str
|
e.g. |
required |
name
|
str
|
Human-readable check name. |
required |
severity
|
Severity
|
Finding severity. |
required |
message
|
str
|
One actionable sentence. |
required |
offending
|
DataFrame
|
The rows that triggered the finding. Empty means the check did not fire, and a zero-count finding is returned. |
required |
n_total_subjects
|
int
|
Denominator for the rate. |
required |
query
|
str
|
SQL-ish pseudocode of the logic. |
required |
subject_column
|
str
|
Which column holds the subject id. |
'subject_id'
|
example_columns
|
list[str] | None
|
Columns to include in examples. Defaults to all. |
None
|
detail
|
dict[str, Any] | None
|
Extra structured context. |
None
|
max_examples
|
int
|
How many example rows to carry. |
MAX_EXAMPLES
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
Finding
|
class: |
Source code in src/ehrlint/schemas/findings.py
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 | |
write_findings_jsonl ¶
Write findings as JSONL, the §6.3 format. Returns the count.
Source code in src/ehrlint/schemas/findings.py
Input and output¶
ehrlint.io.meds ¶
MEDS ingestion.
Verified against meds 0.4.1, by installing and introspecting the package
rather than reading about it (docs/decisions.md D-002). The data schema is:
| column | type | required |
|---|---|---|
subject_id |
int64 | yes |
time |
timestamp[us] | yes (nullable for static events) |
code |
string | yes |
numeric_value |
float | no |
text_value |
large_string | no |
Three differences from the spec's §2 sketch, all handled here:
- There is no
code_systemcolumn. MEDS namespaces the vocabulary inside the code string by convention, asICD10CM//E11.9. ehrlint splits on the first//to recover a system, and leaves it null when there is no separator rather than guessing one. - There is no
encounter_idcolumn. The same-encounter checks (LK002, LK008) therefore skip on plain MEDS input unless an extra column supplies one — MEDS setsallow_extra_columns = True, so a dataset may carry one. subject_idisint64, while ehrlint compares subject ids as strings everywhere. It is cast at ingestion.
Dataset layout, from the package's own constants:
<root>/data/**/*.parquet the event shards
<root>/metadata/dataset.json dataset metadata
<root>/metadata/codes.parquet code metadata (description, parent_codes)
<root>/metadata/subject_splits.parquet subject_id, split
read_meds_events ¶
Read a MEDS dataset directory into the canonical event table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_dir
|
str | Path
|
The MEDS dataset root, or a directory of parquet shards. |
required |
encounter_column
|
str | None
|
An extra column holding an encounter id. When None,
the candidates in :data: |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A canonical event table. |
Raises:
| Type | Description |
|---|---|
InputError
|
If the path is missing or holds no parquet. |
SchemaError
|
If a required MEDS column is absent, naming which. |
Source code in src/ehrlint/io/meds.py
read_subject_id_map ¶
The dataset's surrogate-to-original subject id mapping, or None.
Anything reading a sibling file keyed by subject id -- splits, labels, a feature matrix -- has to apply the same mapping the event shards used, or it will name subjects the event table does not contain.
Source code in src/ehrlint/io/meds.py
meds_frame_to_canonical ¶
Convert a MEDS-shaped frame to the canonical event table.
Source code in src/ehrlint/io/meds.py
read_dataset_metadata ¶
Read metadata/dataset.json, or return an empty dict.
Absence is not an error: a hand-made extract often has no manifest, and the audit does not depend on one. What is in it goes into the report header so a reader knows which ETL produced the data.
Source code in src/ehrlint/io/meds.py
read_code_metadata ¶
Read metadata/codes.parquet, or return None.
MEDS code metadata carries code, description, and parent_codes.
ehrlint uses it only to make findings readable — a code's description
alongside its id — never to expand a code set, because silently matching a
parent code would change what the task means.
Source code in src/ehrlint/io/meds.py
find_meds_splits ¶
Locate metadata/subject_splits.parquet if the dataset has one.
validate_with_meds_package ¶
Validate a MEDS frame with the meds package, if it is installed.
Returns a list of warnings. The meds extra is optional, so its absence
is reported as a single informational line rather than failing the audit.
Source code in src/ehrlint/io/meds.py
write_meds_dataset ¶
write_meds_dataset(
events: DataFrame,
out_dir: str | Path,
*,
dataset_name: str = "ehrlint-synthetic",
dataset_version: str = "1.0.0",
splits: DataFrame | None = None,
) -> dict[str, Path]
Write a canonical event table out in MEDS layout.
Used by the synthetic generator so the demo exercises the real MEDS reader
rather than a shortcut. Codes are re-joined into the SYSTEM//code form so
a round trip is faithful.
MEDS requires an int64 subject_id. Where ehrlint's string ids are not
integers, a deterministic surrogate is assigned and the original is written
to :data:SUBJECT_ID_MAP_FILEPATH, which the reader uses to restore them.
A plain cast(Int64, strict=False) would turn every "S000042" into
null, and a dataset with no subject ids audits perfectly clean.
Returns:
| Type | Description |
|---|---|
dict[str, Path]
|
A mapping of artifact name to path. |
Source code in src/ehrlint/io/meds.py
ehrlint.io.omop ¶
OMOP CDM ingestion.
Reads the seven clinical tables SPEC §3.1 lists and converts them to the canonical event table. Parquet or CSV, whichever is present.
The conversion is a per-table mapping of which column is the event time and
which column is the code. That choice is the interesting part, and each one
is stated below rather than buried, because picking the wrong date column is
itself a leakage bug: using condition_end_date as the event time would place
a diagnosis at its resolution rather than its onset, and every
post-index check downstream would be measuring the wrong thing.
OMOP carries visit_occurrence_id on most clinical tables, which is what makes
the same-encounter checks (LK002, LK008) runnable on OMOP input where they
cannot run on plain MEDS.
OmopTableSpec
dataclass
¶
How one OMOP table becomes canonical events.
Attributes:
| Name | Type | Description |
|---|---|---|
table |
str
|
OMOP table name. |
time_column |
tuple[str, ...]
|
The column taken as the event time, in preference order. |
code_column |
str
|
The concept id column. |
code_system |
str
|
The vocabulary label written to |
numeric_column |
str | None
|
A numeric value column, if the table has one. |
text_column |
str | None
|
A text value column, if the table has one. |
source_value_column |
str | None
|
The source code, used when the concept id is 0 -- OMOP's "no mapping" sentinel. |
required |
bool
|
Whether a missing table is an error. |
Source code in src/ehrlint/io/omop.py
read_omop_events ¶
Read an OMOP CDM extract into the canonical event table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_dir
|
str | Path
|
Directory of OMOP tables, as parquet or CSV. |
required |
include_person
|
bool
|
Convert |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A canonical event table. |
Raises:
| Type | Description |
|---|---|
InputError
|
If the path is missing, or no recognized table was found — with the names it looked for, since a silently empty audit is worse than an error. |
Source code in src/ehrlint/io/omop.py
omop_tables_present ¶
Which recognized OMOP tables exist, for the report header.
Source code in src/ehrlint/io/omop.py
ehrlint.io.features ¶
The optional feature matrix.
When a user supplies the actual training features, ehrlint can check them directly rather than inferring what they must have contained from the event stream. That is a strictly stronger audit: the event stream tells you what could have leaked, the matrix tells you what did.
Expected shape: one row per prediction unit, with a subject_id column and
optionally a timestamp column naming when each feature was computed as of.
Everything else is treated as a feature.
FeatureMatrix ¶
A training feature matrix, with its identifier columns located.
Attributes:
| Name | Type | Description |
|---|---|---|
df |
The frame, with |
|
subject_column |
The resolved subject id column, always renamed to
|
|
time_column |
The as-of timestamp column, or None. |
|
feature_columns |
Everything treated as a feature. |
|
label_column |
A detected label column, or None. |
|
source |
Where it came from. |
Source code in src/ehrlint/io/features.py
subjects ¶
numeric_features ¶
describe ¶
Summary for the report header.
Source code in src/ehrlint/io/features.py
warnings ¶
Things that limit what can be checked on this matrix.
Source code in src/ehrlint/io/features.py
read_feature_matrix ¶
read_feature_matrix(
path: str | Path,
*,
subject_column: str | None = None,
time_column: str | None = None,
) -> FeatureMatrix
Read a feature matrix from parquet or CSV.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
The file. |
required |
subject_column
|
str | None
|
Override the subject id column. |
None
|
time_column
|
str | None
|
Override the as-of timestamp column. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
FeatureMatrix
|
class: |
Raises:
| Type | Description |
|---|---|
InputError
|
If the file is missing or unreadable. |
SchemaError
|
If no subject id column can be found, listing the names it looked for — guessing one would risk auditing the wrong column. |
Source code in src/ehrlint/io/features.py
build_feature_matrix ¶
build_feature_matrix(
df: DataFrame,
*,
subject_column: str | None = None,
time_column: str | None = None,
source: str | None = None,
) -> FeatureMatrix
Locate the identifier columns in a frame and wrap it.
Source code in src/ehrlint/io/features.py
read_labels ¶
Read a labels table, MEDS-shaped or ehrlint-shaped.
MEDS LabelSchema is subject_id, prediction_time, boolean_value,
integer_value, float_value, categorical_value — verified against meds
0.4.1. ehrlint normalizes whichever typed value column is populated into a
single label column, and takes prediction_time as the index date
when the task spec does not define one from an event code.
Returns:
| Type | Description |
|---|---|
DataFrame
|
A frame with |
Source code in src/ehrlint/io/features.py
Reports¶
ehrlint.report.builder ¶
Report generation: a single offline HTML file, Markdown, and JSON.
The HTML is one self-contained file: figures are inlined as base64 data
URIs and there is no JavaScript. An audit report gets attached to a review, a
ticket, or a submission, and a report that breaks when its figures/ directory
is lost is a report that will be seen broken.
The ordering is deliberate and is the opposite of a dashboard's. Warnings and skipped checks come before the findings, because "six of ten checks did not run" changes how every result below should be read, and a reader who sees a green summary first will stop there.
plot_severity_summary ¶
Horizontal bars of check outcome by severity, including the zeros.
Source code in src/ehrlint/report/builder.py
plot_subject_rates ¶
Affected subject rate per fired check.
A rate, not a count: "42 subjects" means something different in a cohort of 100 than in one of 100,000, and the denominator is what a reviewer needs.
Source code in src/ehrlint/report/builder.py
render_markdown ¶
Render the Markdown report.
Source code in src/ehrlint/report/builder.py
render_html ¶
Render the HTML report as a single self-contained string.
Source code in src/ehrlint/report/builder.py
write_report ¶
write_report(
report: AuditReport,
outdir: str | Path,
*,
embed_figures: bool = True,
) -> dict[str, Path]
Write every report artifact into outdir.
Produces report.html (one self-contained file), report.md,
report.json, and findings.jsonl.
Returns:
| Type | Description |
|---|---|
dict[str, Path]
|
A mapping of artifact name to path. |
Source code in src/ehrlint/report/builder.py
Synthetic data and injectors¶
ehrlint.synth.generator ¶
Clean synthetic EHR data, deterministic given a seed.
This is the only data ehrlint ships or tests against. Nothing here derives from a real record: subjects are sequential, codes come from a fixed vocabulary, and every timestamp is computed from a constant epoch.
The baseline is clean by construction — no post-index events used as features, full follow-up for negatives, disjoint splits, outcomes inside the horizon. That matters because the test strategy is differential: generate clean data, assert no check fires, inject one specific leak, assert exactly that check fires. A baseline that already leaked would make every injector test meaningless.
SyntheticDataset
dataclass
¶
Generated events, labels, splits, and the task they describe.
Attributes:
| Name | Type | Description |
|---|---|---|
events |
DataFrame
|
The canonical event table. |
labels |
DataFrame
|
|
splits |
DataFrame
|
|
task |
TaskSpec
|
The task spec these data satisfy. |
features |
DataFrame | None
|
An optional feature matrix. The clean generator produces
none; |
seed |
int
|
The seed used. |
injected |
list[str]
|
Check ids whose leak has been planted, in injection order. |
Source code in src/ehrlint/synth/generator.py
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 | |
splits_mapping ¶
Splits as the {name: [subject_id]} mapping ehrlint's JSON uses.
Source code in src/ehrlint/synth/generator.py
copy ¶
A deep-enough copy for an injector to mutate.
Source code in src/ehrlint/synth/generator.py
describe ¶
Summary for the manifest.
Source code in src/ehrlint/synth/generator.py
write ¶
Write the dataset in MEDS layout plus ehrlint's own side files.
Source code in src/ehrlint/synth/generator.py
default_task ¶
The task spec the generated data satisfies.
A two-year DKA-style task: index on an ED visit, outcome from two ICD-10 codes, full follow-up required for negatives, temporal subject split.
Source code in src/ehrlint/synth/generator.py
generate ¶
generate(
n_subjects: int = 500,
*,
seed: int = 0,
positive_rate: float = 0.2,
horizon_days: float = 730.5,
history_years: float = 2.0,
) -> SyntheticDataset
Generate a clean synthetic dataset.
Clean means: every predictor event predates the index date, every negative is observed for the full horizon, splits are disjoint and time-ordered, and every positive's outcome falls inside the horizon.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_subjects
|
int
|
How many subjects. |
500
|
seed
|
int
|
Seed for all randomness; identical arguments give identical output. |
0
|
positive_rate
|
float
|
Share of subjects with the outcome. |
0.2
|
horizon_days
|
float
|
The task horizon, in days. |
730.5
|
history_years
|
float
|
How much pre-index history to generate. |
2.0
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
SyntheticDataset
|
class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
On arguments that cannot produce a usable dataset. |
Source code in src/ehrlint/synth/generator.py
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 | |
ehrlint.inject ¶
Leak injectors: one per check.
The testing strategy this module exists for. Generate clean data, assert no check fires. Inject one specific leak, assert that check fires and names the subjects it was planted into. That is ground truth no amount of staring at a real dataset can give you.
Each injector returns the mutated dataset and the subject ids it touched, so a test can assert the check found the right people rather than merely finding someone. A check that fires on the wrong subjects is as broken as one that does not fire.
SPEC §11 requires injector/check duality: every check has an injector, and an injected leak is always caught. A property test asserts it over seeds and subject counts.
Injection
dataclass
¶
The result of planting a leak.
Attributes:
| Name | Type | Description |
|---|---|---|
dataset |
SyntheticDataset
|
The mutated dataset. |
check_id |
str
|
The check this leak should trigger. |
subjects |
list[str]
|
Subject ids the leak was planted into. The ground truth a test compares the finding against. |
description |
str
|
What was done, for the test's failure message. |
Source code in src/ehrlint/inject.py
inject_lk001 ¶
inject_lk001(
dataset: SyntheticDataset,
*,
n: int = 5,
seed: int = 0,
exclude: set[str] | None = None,
) -> Injection
LK001 — add a feature matrix whose rows postdate the index date.
The clean baseline already contains post-index events (outcomes live there), so planting more would not distinguish a leak from normal data. The unambiguous leak is a feature matrix stamped after the index date, which is what LK001's matrix branch checks.
Source code in src/ehrlint/inject.py
inject_lk002 ¶
inject_lk002(
dataset: SyntheticDataset,
*,
n: int = 5,
seed: int = 0,
exclude: set[str] | None = None,
) -> Injection
LK002 — put an outcome code inside the index encounter.
Source code in src/ehrlint/inject.py
inject_lk003 ¶
inject_lk003(
dataset: SyntheticDataset,
*,
n: int = 5,
seed: int = 0,
exclude: set[str] | None = None,
) -> Injection
LK003 — put the outcome proxy before the index date.
Source code in src/ehrlint/inject.py
inject_lk004 ¶
inject_lk004(
dataset: SyntheticDataset,
*,
n: int = 5,
seed: int = 0,
exclude: set[str] | None = None,
) -> Injection
LK004 — truncate a negative's follow-up well inside the horizon.
Every event after index + 30 days is removed for the chosen subjects, and they keep their negative label. They are now censored patients counted as two-year negatives, which is the immortal-time error exactly.
Source code in src/ehrlint/inject.py
inject_lk005 ¶
inject_lk005(
dataset: SyntheticDataset,
*,
n: int = 5,
seed: int = 0,
exclude: set[str] | None = None,
) -> Injection
LK005 — copy test subjects into the train split.
Source code in src/ehrlint/inject.py
inject_lk006 ¶
inject_lk006(
dataset: SyntheticDataset,
*,
n: int = 5,
seed: int = 0,
exclude: set[str] | None = None,
) -> Injection
LK006 — move the earliest train subjects into the test split.
The split stays disjoint — this is not LK005 — but the test set now contains the oldest index dates, so a split declared temporal is not.
Source code in src/ehrlint/inject.py
inject_lk007 ¶
inject_lk007(
dataset: SyntheticDataset,
*,
n: int = 5,
seed: int = 0,
exclude: set[str] | None = None,
) -> Injection
LK007 — flip negatives to positive without any in-window outcome.
The label now asserts an outcome the event data does not support inside the declared window, which is what "ascertained with post-index information" looks like from the outside.
Source code in src/ehrlint/inject.py
inject_lk008 ¶
inject_lk008(
dataset: SyntheticDataset,
*,
n: int = 3,
seed: int = 0,
exclude: set[str] | None = None,
) -> Injection
LK008 — give a train and a test subject the same encounter id.
Subject-level splits stay disjoint, so LK005 is clean; the encounter is what straddles.
Source code in src/ehrlint/inject.py
inject_lk009 ¶
inject_lk009(
dataset: SyntheticDataset,
*,
n: int = 3,
seed: int = 0,
exclude: set[str] | None = None,
) -> Injection
LK009 — duplicate a subject under a second id with identical demographics.
Source code in src/ehrlint/inject.py
inject_lk010 ¶
inject_lk010(
dataset: SyntheticDataset,
*,
n: int = 5,
seed: int = 0,
exclude: set[str] | None = None,
) -> Injection
LK010 — give negatives an outcome occurrence beyond the horizon.
They have no in-window occurrence, so if they are counted as positives the task's real horizon is longer than declared.
Source code in src/ehrlint/inject.py
inject ¶
inject(
dataset: SyntheticDataset,
check_id: str,
*,
n: int = 5,
seed: int = 0,
exclude: set[str] | None = None,
) -> Injection
Plant the leak that should trigger check_id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset
|
SyntheticDataset
|
The dataset to copy and mutate. |
required |
check_id
|
str
|
Which leak to plant. |
required |
n
|
int
|
How many subjects to affect. |
5
|
seed
|
int
|
Seed; the same arguments plant the same leak. |
0
|
exclude
|
set[str] | None
|
Subjects to leave alone, normally those already carrying a planted leak. |
None
|
Raises:
| Type | Description |
|---|---|
EhrlintError
|
If no injector exists for the check, listing those that do. |
Source code in src/ehrlint/inject.py
inject_many ¶
inject_many(
dataset: SyntheticDataset,
check_ids: list[str],
*,
n: int = 5,
seed: int = 0,
) -> tuple[SyntheticDataset, dict[str, list[str]]]
Plant several leaks in sequence, on disjoint subjects.
Disjoint because every injector is seeded identically and would otherwise choose the same people -- and then one leak masks another. Giving a negative an outcome long after the horizon (LK010) extends the follow-up that LK004 had just truncated, and LK004 goes quiet. A dataset built to be ground truth cannot have that in it.
Returns:
| Type | Description |
|---|---|
SyntheticDataset
|
|
dict[str, list[str]]
|
sorted id order so the result is deterministic regardless of the order |
tuple[SyntheticDataset, dict[str, list[str]]]
|
the caller listed them. |
Source code in src/ehrlint/inject.py
Errors¶
ehrlint.exceptions ¶
Exception hierarchy for ehrlint.
Errors carry enough context to locate the problem: a file path, a column name, a subject id. None of them carry patient data beyond the identifiers needed to find the offending row -- which is the same discipline the findings follow.
EhrlintError ¶
InputError ¶
Bases: EhrlintError
Input data could not be read, or is missing something required.
Source code in src/ehrlint/exceptions.py
SchemaError ¶
Bases: InputError
Input data does not satisfy the schema ehrlint requires.
Source code in src/ehrlint/exceptions.py
TaskSpecError ¶
Bases: EhrlintError
A task specification is missing, malformed, or self-contradictory.
SplitsError ¶
Bases: EhrlintError
A splits definition is missing, malformed, or inconsistent with the data.
CheckError ¶
Bases: EhrlintError
A check could not run.
Distinct from a check firing: a finding means a leak was found, this means the check itself failed. The audit records it as skipped with a reason rather than silently reporting a clean result.
Source code in src/ehrlint/exceptions.py
RegistryError ¶
Bases: EhrlintError
A check could not be registered or resolved.
ReportError ¶
Bases: EhrlintError
A report could not be rendered or written.