io
File-IO helpers shared across stages.
This module is the one place in the pipeline where file-format dispatch
(parquet / par / csv / csv.gz) and layout resolution
(bare file vs. sub-sharded directory) live. Stages call :func:scan_source
(read one or more files, concatenated) and :func:resolve_source_files
(find the files for a given prefix) rather than rolling their own
scan_parquet / glob calls.
_decode_expr(c, t)
Decode String column c to its inferred dtype t, as the CSV reader would.
Polars does not support String→Boolean casts at all (#199), so Boolean columns are
decoded by matching the reader’s case-insensitive true token instead —
inference already guaranteed every non-null value is some casing of true/false,
and str.contains preserves nulls. Numeric columns cast directly;
strict=False never actually nulls a value here, because the inference probes
only award a dtype when every non-null value is castable to it.
Source code in MEDS_extract/io.py
convert_csv_to_parquet(src, dest, columns=None, *, tmp_dir=None)
Convert a csv-family file to parquet in three bounded passes; return the schema.
The obvious one-liner — scan_csv(infer_schema_length=None).sink_parquet() —
is not an option: full-file inference materializes the file to decide types, so
it peaks at more memory than reading the CSV outright (measured 3.1 GB on a 1 GB
input, against 2.6 GB for a plain eager read). Splitting inference from
conversion is what makes both halves cheap:
- CSV → all-String parquet.
infer_schema_length=0types nothing, so polars streams straight through. Empty fields become nulls here, exactly as they would under inference — the distinction CSV itself cannot express, and the one downstream??coalescing and null-drops depend on. - Infer each column’s dtype off that parquet (:func:
infer_column_dtypes) — a per-column aggregate over a columnar file, not a table scan. - Cast and write the final typed parquet, projecting to
columns.
The intermediate is written under tmp_dir (default: beside dest) and
removed afterwards, so the cost is transient disk rather than memory.
The written parquet matches what pl.read_csv(src, infer_schema_length=None)
would produce — same schema, same values — for every CSV polars itself can read;
tests/test_convert_to_parquet.py enforces that round-trip with a property
test. The sole deliberate deviation: where polars’ full read hard-errors on a
column its inference classifies as typed but whose values it then cannot parse
(an integer-shaped column overflowing Int64, in practice), this conversion
degrades gracefully instead — lossy Float64 for the overflow case.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src
|
Path | UPath
|
The csv / csv.gz file to convert. |
required |
dest
|
Path
|
Where to write the typed parquet. Parent directories are created. |
required |
columns
|
list[str] | None
|
Project to these columns. |
None
|
tmp_dir
|
Path | None
|
Where the intermediate String parquet goes. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, DataType]
|
The inferred schema of the written columns. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> with yaml_disk('''
... labs.csv: |
... subject_id,value,unit,note
... 1,1.5,mg,ok
... 2,3,mg,
... ''') as d:
... out = Path(d) / "labs.parquet"
... schema = convert_csv_to_parquet(Path(d) / "labs.csv", out)
... print(schema)
... pl.read_parquet(out)
{'subject_id': Int64, 'value': Float64, 'unit': String, 'note': String}
shape: (2, 4)
┌────────────┬───────┬──────┬──────┐
│ subject_id ┆ value ┆ unit ┆ note │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ str ┆ str │
╞════════════╪═══════╪══════╪══════╡
│ 1 ┆ 1.5 ┆ mg ┆ ok │
│ 2 ┆ 3.0 ┆ mg ┆ null │
└────────────┴───────┴──────┴──────┘
The empty note on row 2 arrives as a real null, not "" — carrying
CSV’s missing-value semantics across the conversion.
Projection keeps only what the MESSY config needs, so a wide source table never costs downstream stages anything for columns nobody reads:
>>> with yaml_disk('''
... labs.csv: |
... subject_id,value,unit,note
... 1,1.5,mg,ok
... ''') as d:
... out = Path(d) / "labs.parquet"
... _ = convert_csv_to_parquet(Path(d) / "labs.csv", out, ["subject_id", "value"])
... pl.read_parquet(out).columns
['subject_id', 'value']
A requested column the file lacks fails naming both sides:
>>> with yaml_disk('''
... labs.csv: |
... subject_id,value
... 1,2
... ''') as d:
... convert_csv_to_parquet(Path(d) / "labs.csv", Path(d) / "o.parquet", ["nope"])
Traceback (most recent call last):
...
ValueError: ...labs.csv is missing requested column(s) ['nope']. It has:
['subject_id', 'value'].
Source code in MEDS_extract/io.py
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 551 552 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 | |
infer_column_dtypes(lf)
Infer each String column’s dtype the way full-file CSV inference would.
This is the middle pass of :func:convert_csv_to_parquet. It runs over a
columnar frame (the all-String parquet written by pass 1), so deciding a
column’s type is an aggregate over one column rather than a scan of the whole
table — which is what lets full-file-accurate inference happen without the
file in memory. polars’ own infer_schema_length=None cannot do this:
it materializes the CSV to decide.
A column is given the narrowest type that EVERY non-null value satisfies, judged
by polars’ own field-acceptor regexes (see _CSV_*_RE above), and an all-null
column stays String — matching what polars infers for a CSV column that is
empty in every row (a real case: an always-empty dod).
Non-String columns pass through unchanged, so this is a no-op on frames that already carry types.
Examples:
>>> lf = pl.LazyFrame({
... "ints": ["1", "2", None],
... "floats": ["1.5", "2", None],
... "bools": ["true", "false", None],
... "strs": ["1", "abc", None],
... "empty": [None, None, None],
... }, schema={c: pl.String for c in ("ints", "floats", "bools", "strs", "empty")})
>>> infer_column_dtypes(lf)
{'ints': Int64, 'floats': Float64, 'bools': Boolean, 'strs': String, 'empty': String}
The acceptors are polars’, not Python’s: booleans match in any casing, while a
+-prefixed integer — which int() (and a String→Int64 cast) would take —
keeps its column String, exactly as CSV inference leaves it:
>>> lf = pl.LazyFrame({
... "bools": ["True", "FALSE", "tRuE"],
... "plus": ["+1", "2"] + [None],
... }, schema={"bools": pl.String, "plus": pl.String})
>>> infer_column_dtypes(lf)
{'bools': Boolean, 'plus': String}
A single unparsable value keeps the whole column String — inference is over every row, never a sample, so there is no mid-file “type flip” to fear:
>>> lf = pl.LazyFrame({"mostly_int": ["1"] * 999 + ["NOT_A_NUMBER"]})
>>> infer_column_dtypes(lf)
{'mostly_int': String}
The one deliberate divergence from infer_schema_length=None: an
integer-shaped column that overflows Int64 makes polars’ full-file read
hard-error, while this ladder degrades it to (lossy) Float64:
Source code in MEDS_extract/io.py
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 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 | |
resolve_source_files(dir, prefix)
Find all source files for prefix under dir.
Two supported layouts:
- Sub-sharded directory:
{dir}/{prefix}/*.{parquet,par,csv.gz,csv}— the format of user-supplied pre-sharded data, preserved throughconvert_to_parquet. - Single bare file:
{dir}/{prefix}.{parquet,par,csv.gz,csv}— raw user data or subject-sharded stage output.
Both layouts are checked. If both match simultaneously (e.g. a user
has both labs.parquet and labs/*.parquet under the same
directory), this is an ambiguity and raises ValueError. If neither
matches, raises FileNotFoundError.
prefix may contain slashes (e.g. hosp/patients); that’s just a
path component, not a glob — no recursive walking happens.
Examples:
Bare file layout — a single file per prefix, typical of raw input
to convert_to_parquet and subject-sharded output elsewhere:
>>> with yaml_disk('''
... patients.parquet:
... subject_id: [1, 2]
... labs.csv: |
... subject_id,value
... 1,5.0
... 2,7.0
... ''') as d:
... resolved = resolve_source_files(Path(d), "patients")
... [fp.name for fp in resolved]
['patients.parquet']
>>> with yaml_disk('''
... labs.csv: |
... subject_id,value
... 1,5.0
... ''') as d:
... [fp.name for fp in resolve_source_files(Path(d), "labs")]
['labs.csv']
Sub-sharded directory layout — many chunks per prefix, typical
layout of a pre-sharded source table. All non-hidden files under
{prefix}/ are returned sorted by name; the chunks must share one
format family (csv-family or parquet-family — scan_source rejects
a mix):
>>> with yaml_disk('''
... vitals/[0-2).parquet:
... hr: [80, 85]
... vitals/[2-4).parquet:
... hr: [72, 78]
... ''') as d:
... resolved = resolve_source_files(Path(d), "vitals")
... [fp.name for fp in resolved]
['[0-2).parquet', '[2-4).parquet']
Hidden files are never source data, so dotfile debris in a sub-sharded directory (e.g. a stranded writer intermediate) is ignored:
>>> with yaml_disk('''
... vitals/chunk_0.parquet:
... hr: [80, 85]
... ''') as d:
... (Path(d) / "vitals" / ".x.parquet.strings.tmp.parquet").touch()
... [fp.name for fp in resolve_source_files(Path(d), "vitals")]
['chunk_0.parquet']
Nested prefixes like hosp/patients are handled naturally as
path components — no recursive walking happens, so a nested prefix
maps directly to its nested filesystem path:
>>> with yaml_disk('''
... hosp:
... patients.parquet:
... subject_id: [1]
... ''') as d:
... [str(fp.relative_to(Path(d))) for fp in resolve_source_files(Path(d), "hosp/patients")]
['hosp/patients.parquet']
Ambiguous layouts raise — having both a bare file and a sub-sharded directory for the same prefix is never intentional:
>>> with yaml_disk('''
... labs.parquet:
... subject_id: [1]
... labs/extra.parquet:
... subject_id: [2]
... ''') as d:
... resolve_source_files(Path(d), "labs")
Traceback (most recent call last):
...
ValueError: Ambiguous source layout for prefix 'labs' ...
matched sub-sharded directory 'labs/', bare file 'labs.parquet'...
Similarly, having multiple bare files in different formats (e.g.
labs.parquet AND labs.csv) is ambiguous:
>>> with yaml_disk('''
... labs.parquet:
... subject_id: [1]
... labs.csv: |
... subject_id
... 2
... ''') as d:
... resolve_source_files(Path(d), "labs")
Traceback (most recent call last):
...
ValueError: Ambiguous source layout for prefix 'labs' ...
matched bare file 'labs.parquet', bare file 'labs.csv'...
No match raises FileNotFoundError listing what was tried:
>>> with yaml_disk('other.parquet:\n x: [1]') as d:
... resolve_source_files(Path(d), "missing")
Traceback (most recent call last):
...
FileNotFoundError: No source files found for prefix 'missing' under ...
Source code in MEDS_extract/io.py
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 | |
scan_source(fps, **scan_kwargs)
Scan one or more source files, dispatching on extension.
Accepts either a single path or an iterable of paths. In the multi-path case
the resulting LazyFrames are concatenated with vertical_relaxed.
Extension-specific adjustments (parquet glob=False, csv.gz via
gzip.open + read_csv, parquet ignoring the csv-only
infer_schema_length kwarg) live here — and are applied per file,
not per batch — so callers never need to care about format. Multi-file
sources must be format-homogeneous (csv-family or parquet-family, not a
mix); heterogeneity across separate single-file scans is fine.
Examples:
Scanning a single parquet file returns a LazyFrame for that file alone.
>>> with yaml_disk('''
... patients.parquet:
... subject_id: [1, 2, 3]
... dob: ['1980-01-01', '1985-06-15', '1990-12-31']
... ''') as d:
... scan_source(Path(d) / 'patients.parquet').collect()
shape: (3, 2)
┌────────────┬────────────┐
│ subject_id ┆ dob │
│ --- ┆ --- │
│ i64 ┆ str │
╞════════════╪════════════╡
│ 1 ┆ 1980-01-01 │
│ 2 ┆ 1985-06-15 │
│ 3 ┆ 1990-12-31 │
└────────────┴────────────┘
Passing a list of paths concatenates them vertically. This is the common case for a pre-sharded source table, where a prefix resolves to many files.
>>> with yaml_disk('''
... vitals/[0-2).parquet:
... subject_id: [1, 1]
... hr: [80, 85]
... vitals/[2-4).parquet:
... subject_id: [2, 2]
... hr: [72, 78]
... ''') as d:
... fps = sorted((Path(d) / 'vitals').glob('*.parquet'))
... scan_source(fps).collect().sort('subject_id', 'hr')
shape: (4, 2)
┌────────────┬─────┐
│ subject_id ┆ hr │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞════════════╪═════╡
│ 1 ┆ 80 │
│ 1 ┆ 85 │
│ 2 ┆ 72 │
│ 2 ┆ 78 │
└────────────┴─────┘
A multi-file scan must be format-homogeneous — mixing csv-family and
parquet-family chunks in one source is a config error rather than a silent
dtype coercion (typed parquet + all-String csv would otherwise unify through
vertical_relaxed):
>>> with yaml_disk('''
... items/a.csv: |
... itemid,label
... 1,Heart Rate
... items/b.parquet:
... itemid: [2]
... label: [NBP systolic]
... ''') as d:
... fps = sorted((Path(d) / 'items').glob('*'))
... scan_source(fps, infer_schema=False)
Traceback (most recent call last):
...
ValueError: Cannot scan a mix of csv- and parquet-family files as one source: ...
Unsupported formats raise ValueError:
>>> scan_source(Path("t.json"))
Traceback (most recent call last):
...
ValueError: Unsupported source file type: t.json
Source code in MEDS_extract/io.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 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 | |