specatwrap8 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- specatwrap8-0.2.0/PKG-INFO +13 -0
- specatwrap8-0.2.0/README.md +0 -0
- specatwrap8-0.2.0/pyproject.toml +33 -0
- specatwrap8-0.2.0/src/specatwrap8/__init__.py +208 -0
- specatwrap8-0.2.0/src/specatwrap8/prep/__init__.py +124 -0
- specatwrap8-0.2.0/src/specatwrap8/prep/diagnosis.py +94 -0
- specatwrap8-0.2.0/src/specatwrap8/prep/io_handler.py +86 -0
- specatwrap8-0.2.0/src/specatwrap8/sas_converter.py +163 -0
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: specatwrap8
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: A simple wrapper
|
|
5
|
+
Author: Casper Lauge Nørup Koch
|
|
6
|
+
Author-email: Casper Lauge Nørup Koch <kochcasper@gmail.com>
|
|
7
|
+
Requires-Dist: click>=8.3.1
|
|
8
|
+
Requires-Dist: pm4py>=2.7.19.8
|
|
9
|
+
Requires-Dist: polars>=1.38.1
|
|
10
|
+
Requires-Dist: pyreadstat>=1.3.3
|
|
11
|
+
Requires-Python: >=3.12
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
File without changes
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "specatwrap8"
|
|
3
|
+
version = "0.2.0"
|
|
4
|
+
description = "A simple wrapper"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
authors = [
|
|
7
|
+
{ name = "Casper Lauge Nørup Koch", email = "kochcasper@gmail.com" }
|
|
8
|
+
]
|
|
9
|
+
requires-python = ">=3.12"
|
|
10
|
+
dependencies = [
|
|
11
|
+
"click>=8.3.1",
|
|
12
|
+
"pm4py>=2.7.19.8",
|
|
13
|
+
"polars>=1.38.1",
|
|
14
|
+
"pyreadstat>=1.3.3",
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
[project.scripts]
|
|
18
|
+
specatwrap = "specatwrap8:main"
|
|
19
|
+
|
|
20
|
+
[build-system]
|
|
21
|
+
requires = ["uv_build>=0.10.3,<0.11.0"]
|
|
22
|
+
build-backend = "uv_build"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
[tool.pyright]
|
|
26
|
+
reportUnannotatedClassAttribute = "none"
|
|
27
|
+
reportImplicitOverride = "none"
|
|
28
|
+
reportUnknownParameterType = "none"
|
|
29
|
+
reportMissingParameterType = "none"
|
|
30
|
+
reportUnknownVariableType = "none"
|
|
31
|
+
reportUnknownMemberType = "none"
|
|
32
|
+
reportUnknownArgumentType = "none"
|
|
33
|
+
reportAny = "none"
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Specatwrap - A wrapper for processing healthcare data.
|
|
3
|
+
|
|
4
|
+
This module provides a CLI for converting and processing healthcare data files.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import click
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import sys
|
|
10
|
+
import pyreadstat
|
|
11
|
+
|
|
12
|
+
from .sas_converter import convert_sas_to_parquet
|
|
13
|
+
from .prep import prep
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@click.group()
|
|
17
|
+
@click.version_option(version="0.1.0")
|
|
18
|
+
def cli():
|
|
19
|
+
"""
|
|
20
|
+
Specatwrap - A wrapper for processing healthcare data.
|
|
21
|
+
|
|
22
|
+
A command-line tool for processing and converting healthcare data files.
|
|
23
|
+
"""
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
# Register command groups
|
|
28
|
+
cli.add_command(prep)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@cli.command()
|
|
32
|
+
@click.argument("input_file", type=click.Path(exists=True, path_type=Path))
|
|
33
|
+
@click.argument("output_path", type=click.Path(path_type=Path))
|
|
34
|
+
@click.option(
|
|
35
|
+
"-c",
|
|
36
|
+
"--chunk-size",
|
|
37
|
+
type=int,
|
|
38
|
+
default=100000,
|
|
39
|
+
help="Number of rows to read per chunk (default: 100000)",
|
|
40
|
+
)
|
|
41
|
+
@click.option(
|
|
42
|
+
"--compression",
|
|
43
|
+
type=click.Choice(["zstd", "lz4", "snappy", "gzip"], case_sensitive=False),
|
|
44
|
+
default="zstd",
|
|
45
|
+
help="Parquet compression algorithm (default: zstd)",
|
|
46
|
+
)
|
|
47
|
+
@click.option(
|
|
48
|
+
"--encoding",
|
|
49
|
+
type=str,
|
|
50
|
+
default=None,
|
|
51
|
+
help="File encoding (default: auto-detect)",
|
|
52
|
+
)
|
|
53
|
+
@click.option(
|
|
54
|
+
"--overwrite",
|
|
55
|
+
is_flag=True,
|
|
56
|
+
default=False,
|
|
57
|
+
help="Overwrite existing output directory if it exists",
|
|
58
|
+
)
|
|
59
|
+
@click.option("-v", "--verbose", is_flag=True, help="Enable verbose output")
|
|
60
|
+
def sas2parquet(
|
|
61
|
+
input_file, output_path, chunk_size, compression, encoding, overwrite, verbose
|
|
62
|
+
):
|
|
63
|
+
"""
|
|
64
|
+
Convert a SAS file to Parquet format in chunks.
|
|
65
|
+
|
|
66
|
+
INPUT_FILE: Path to the SAS file (.sas7bdat)
|
|
67
|
+
|
|
68
|
+
OUTPUT_PATH: Path to output directory for Parquet files
|
|
69
|
+
|
|
70
|
+
This command processes large SAS files in chunks to minimize memory usage.
|
|
71
|
+
Each chunk is written to a separate Parquet file in the output directory.
|
|
72
|
+
|
|
73
|
+
Example usage:
|
|
74
|
+
|
|
75
|
+
specatwrap sas2parquet input.sas7bdat output_dir/
|
|
76
|
+
|
|
77
|
+
specatwrap sas2parquet input.sas7bdat output_dir/ --chunk-size 50000 -v
|
|
78
|
+
|
|
79
|
+
specatwrap sas2parquet input.sas7bdat output_dir/ --compression lz4
|
|
80
|
+
|
|
81
|
+
Reading the data later with Polars:
|
|
82
|
+
|
|
83
|
+
import polars as pl
|
|
84
|
+
|
|
85
|
+
df = pl.read_parquet("output_dir/*.parquet")
|
|
86
|
+
"""
|
|
87
|
+
try:
|
|
88
|
+
convert_sas_to_parquet(
|
|
89
|
+
input_file=input_file,
|
|
90
|
+
output_path=output_path,
|
|
91
|
+
chunk_size=chunk_size,
|
|
92
|
+
compression=compression,
|
|
93
|
+
encoding=encoding,
|
|
94
|
+
overwrite=overwrite,
|
|
95
|
+
verbose=verbose,
|
|
96
|
+
)
|
|
97
|
+
except FileNotFoundError as e:
|
|
98
|
+
click.secho(f"✗ Error: File not found - {e}", fg="red", err=True)
|
|
99
|
+
sys.exit(1)
|
|
100
|
+
except PermissionError as e:
|
|
101
|
+
click.secho(f"✗ Error: Permission denied - {e}", fg="red", err=True)
|
|
102
|
+
sys.exit(1)
|
|
103
|
+
except ValueError as e:
|
|
104
|
+
click.secho(f"✗ Error: Invalid input - {e}", fg="red", err=True)
|
|
105
|
+
sys.exit(1)
|
|
106
|
+
except MemoryError:
|
|
107
|
+
click.secho(
|
|
108
|
+
f"✗ Error: Out of memory. Try a smaller --chunk-size", fg="red", err=True
|
|
109
|
+
)
|
|
110
|
+
sys.exit(1)
|
|
111
|
+
except Exception as e:
|
|
112
|
+
click.secho(f"✗ Error: {e}", fg="red", err=True)
|
|
113
|
+
if verbose:
|
|
114
|
+
import traceback
|
|
115
|
+
|
|
116
|
+
traceback.print_exc()
|
|
117
|
+
sys.exit(1)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
@cli.command()
|
|
121
|
+
@click.argument("input_file", type=click.Path(exists=True, path_type=Path))
|
|
122
|
+
@click.option(
|
|
123
|
+
"-n",
|
|
124
|
+
"--num-rows",
|
|
125
|
+
type=int,
|
|
126
|
+
default=10,
|
|
127
|
+
help="Number of rows to display (default: 10)",
|
|
128
|
+
)
|
|
129
|
+
@click.option(
|
|
130
|
+
"--encoding",
|
|
131
|
+
type=str,
|
|
132
|
+
default=None,
|
|
133
|
+
help="File encoding (default: auto-detect)",
|
|
134
|
+
)
|
|
135
|
+
def preview(input_file, num_rows, encoding):
|
|
136
|
+
"""
|
|
137
|
+
Preview the first N rows of a SAS file.
|
|
138
|
+
|
|
139
|
+
INPUT_FILE: Path to the SAS file (.sas7bdat)
|
|
140
|
+
|
|
141
|
+
This command quickly reads and displays the first few rows of a SAS file
|
|
142
|
+
to help you inspect the data structure and content without converting
|
|
143
|
+
the entire file.
|
|
144
|
+
|
|
145
|
+
Example usage:
|
|
146
|
+
|
|
147
|
+
specatwrap preview input.sas7bdat
|
|
148
|
+
|
|
149
|
+
specatwrap preview input.sas7bdat --num-rows 20
|
|
150
|
+
|
|
151
|
+
specatwrap preview input.sas7bdat --encoding latin1
|
|
152
|
+
"""
|
|
153
|
+
try:
|
|
154
|
+
# Validate file exists
|
|
155
|
+
if not input_file.exists():
|
|
156
|
+
click.secho(f"✗ Error: File not found: {input_file}", fg="red", err=True)
|
|
157
|
+
sys.exit(1)
|
|
158
|
+
|
|
159
|
+
if input_file.suffix.lower() != ".sas7bdat":
|
|
160
|
+
click.secho(
|
|
161
|
+
"✗ Error: Input file must be a .sas7bdat file", fg="red", err=True
|
|
162
|
+
)
|
|
163
|
+
sys.exit(1)
|
|
164
|
+
|
|
165
|
+
click.echo(f"Reading first {num_rows} rows from: {input_file.name}")
|
|
166
|
+
click.echo()
|
|
167
|
+
|
|
168
|
+
# Read first N rows using pyreadstat
|
|
169
|
+
df, meta = pyreadstat.read_sas7bdat(
|
|
170
|
+
str(input_file),
|
|
171
|
+
row_limit=num_rows,
|
|
172
|
+
encoding=encoding,
|
|
173
|
+
output_format="polars",
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
# Display metadata
|
|
177
|
+
click.echo(f"Total columns: {len(meta.column_names)}")
|
|
178
|
+
click.echo(f"Column names: {', '.join(meta.column_names)}")
|
|
179
|
+
if encoding:
|
|
180
|
+
click.echo(f"Encoding: {encoding}")
|
|
181
|
+
click.echo()
|
|
182
|
+
|
|
183
|
+
# Display the data using Polars' pretty print
|
|
184
|
+
click.echo(str(df))
|
|
185
|
+
click.echo()
|
|
186
|
+
click.secho(f"✓ Showing {len(df)} row(s)", fg="green")
|
|
187
|
+
|
|
188
|
+
except FileNotFoundError as e:
|
|
189
|
+
click.secho(f"✗ Error: File not found - {e}", fg="red", err=True)
|
|
190
|
+
sys.exit(1)
|
|
191
|
+
except PermissionError as e:
|
|
192
|
+
click.secho(f"✗ Error: Permission denied - {e}", fg="red", err=True)
|
|
193
|
+
sys.exit(1)
|
|
194
|
+
except ValueError as e:
|
|
195
|
+
click.secho(f"✗ Error: Invalid input - {e}", fg="red", err=True)
|
|
196
|
+
sys.exit(1)
|
|
197
|
+
except Exception as e:
|
|
198
|
+
click.secho(f"✗ Error: {e}", fg="red", err=True)
|
|
199
|
+
sys.exit(1)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def main():
|
|
203
|
+
"""Entry point for the CLI application."""
|
|
204
|
+
cli()
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
if __name__ == "__main__":
|
|
208
|
+
main()
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Prep command group for preprocessing healthcare data files.
|
|
3
|
+
|
|
4
|
+
This module provides commands for filtering and preprocessing parquet files
|
|
5
|
+
before converting them to XES format.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import click
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
import sys
|
|
11
|
+
|
|
12
|
+
from .io_handler import process_parquet_files
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@click.group()
|
|
16
|
+
def prep():
|
|
17
|
+
"""
|
|
18
|
+
Preprocess and filter healthcare data files.
|
|
19
|
+
|
|
20
|
+
Commands in this group help prepare raw data files by filtering,
|
|
21
|
+
cleaning, and transforming them before further processing.
|
|
22
|
+
"""
|
|
23
|
+
pass
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@prep.command()
|
|
27
|
+
@click.option(
|
|
28
|
+
"-i",
|
|
29
|
+
"--input",
|
|
30
|
+
"input_dir",
|
|
31
|
+
type=click.Path(exists=True, file_okay=False, dir_okay=True, path_type=Path),
|
|
32
|
+
required=True,
|
|
33
|
+
help="Path to directory containing parquet files to process.",
|
|
34
|
+
)
|
|
35
|
+
@click.option(
|
|
36
|
+
"-o",
|
|
37
|
+
"--output",
|
|
38
|
+
"output_file",
|
|
39
|
+
type=click.Path(dir_okay=False, file_okay=True, path_type=Path),
|
|
40
|
+
required=True,
|
|
41
|
+
help="Path to output parquet file.",
|
|
42
|
+
)
|
|
43
|
+
@click.option("-v", "--verbose", is_flag=True, help="Enable verbose output.")
|
|
44
|
+
def diagnosis(input_dir, output_file, verbose):
|
|
45
|
+
"""
|
|
46
|
+
Filter and preprocess diagnosis parquet files.
|
|
47
|
+
|
|
48
|
+
This command lazily reads all parquet files from a directory, applies
|
|
49
|
+
filtering and preprocessing transformations, and writes the results to
|
|
50
|
+
a single output parquet file.
|
|
51
|
+
|
|
52
|
+
INPUT: Directory path containing parquet files to process.
|
|
53
|
+
|
|
54
|
+
OUTPUT: Path to output parquet file for processed data.
|
|
55
|
+
|
|
56
|
+
Example usage:
|
|
57
|
+
|
|
58
|
+
specatwrap prep diagnosis -i ./data/parquet_files/ -o ./processed/diagnosis.parquet
|
|
59
|
+
|
|
60
|
+
specatwrap prep diagnosis --input ./raw_data/ --output ./clean_data.parquet -v
|
|
61
|
+
"""
|
|
62
|
+
try:
|
|
63
|
+
# Display processing information
|
|
64
|
+
click.echo(f"Input directory: {input_dir}")
|
|
65
|
+
click.echo(f"Output file: {output_file}")
|
|
66
|
+
click.echo()
|
|
67
|
+
|
|
68
|
+
# Find all parquet files in input directory (for verbose output)
|
|
69
|
+
if verbose:
|
|
70
|
+
parquet_pattern = str(input_dir / "*.parquet")
|
|
71
|
+
click.echo(f"Searching for parquet files: {parquet_pattern}")
|
|
72
|
+
parquet_files = list(input_dir.glob("*.parquet"))
|
|
73
|
+
if parquet_files:
|
|
74
|
+
click.echo(f"Found {len(parquet_files)} parquet file(s):")
|
|
75
|
+
for f in parquet_files:
|
|
76
|
+
click.echo(f" - {f.name}")
|
|
77
|
+
click.echo()
|
|
78
|
+
|
|
79
|
+
# Process the parquet files using the io_handler
|
|
80
|
+
click.echo("Loading and applying filters...")
|
|
81
|
+
with click.progressbar(
|
|
82
|
+
length=100, label="Processing", show_eta=False, show_percent=True
|
|
83
|
+
) as bar:
|
|
84
|
+
# Call the generic I/O handler with "diagnosis" filter type
|
|
85
|
+
process_parquet_files(
|
|
86
|
+
input_dir=input_dir,
|
|
87
|
+
output_file=output_file,
|
|
88
|
+
filter_type="diagnosis",
|
|
89
|
+
verbose=verbose,
|
|
90
|
+
)
|
|
91
|
+
bar.update(100)
|
|
92
|
+
|
|
93
|
+
# Display success message
|
|
94
|
+
click.secho("✓ Processing completed successfully!", fg="green", bold=True)
|
|
95
|
+
click.echo(f"Output file: {output_file}")
|
|
96
|
+
|
|
97
|
+
# Display file statistics
|
|
98
|
+
if output_file.exists():
|
|
99
|
+
size_mb = output_file.stat().st_size / (1024 * 1024)
|
|
100
|
+
click.echo(f"File size: {size_mb:.2f} MB")
|
|
101
|
+
|
|
102
|
+
except FileNotFoundError as e:
|
|
103
|
+
click.secho(f"✗ Error: File or directory not found - {e}", fg="red", err=True)
|
|
104
|
+
sys.exit(1)
|
|
105
|
+
except PermissionError as e:
|
|
106
|
+
click.secho(f"✗ Error: Permission denied - {e}", fg="red", err=True)
|
|
107
|
+
sys.exit(1)
|
|
108
|
+
except ValueError as e:
|
|
109
|
+
click.secho(f"✗ Error: Invalid input - {e}", fg="red", err=True)
|
|
110
|
+
sys.exit(1)
|
|
111
|
+
except MemoryError:
|
|
112
|
+
click.secho(
|
|
113
|
+
"✗ Error: Out of memory. Try processing smaller batches.",
|
|
114
|
+
fg="red",
|
|
115
|
+
err=True,
|
|
116
|
+
)
|
|
117
|
+
sys.exit(1)
|
|
118
|
+
except Exception as e:
|
|
119
|
+
click.secho(f"✗ Error: {e}", fg="red", err=True)
|
|
120
|
+
if verbose:
|
|
121
|
+
import traceback
|
|
122
|
+
|
|
123
|
+
traceback.print_exc()
|
|
124
|
+
sys.exit(1)
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Diagnosis filter classes.
|
|
3
|
+
|
|
4
|
+
This module provides filter classes for preprocessing diagnosis parquet files.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from abc import ABC, abstractmethod
|
|
8
|
+
import polars as pl
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class BaseFilter(ABC):
|
|
12
|
+
"""
|
|
13
|
+
Abstract base class for parquet file filters.
|
|
14
|
+
|
|
15
|
+
Each filter type (diagnosis, procedure, medication, etc.) should inherit
|
|
16
|
+
from this class and implement the apply() method with their specific
|
|
17
|
+
filtering and transformation logic.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
@abstractmethod
|
|
21
|
+
def apply(self, lazy_frame: pl.LazyFrame) -> pl.LazyFrame:
|
|
22
|
+
"""
|
|
23
|
+
Apply filtering and preprocessing logic to a LazyFrame.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
lazy_frame: Input Polars LazyFrame to filter/transform
|
|
27
|
+
|
|
28
|
+
Returns:
|
|
29
|
+
Transformed Polars LazyFrame
|
|
30
|
+
"""
|
|
31
|
+
pass
|
|
32
|
+
|
|
33
|
+
def get_name(self) -> str:
|
|
34
|
+
"""
|
|
35
|
+
Get the name of this filter type.
|
|
36
|
+
|
|
37
|
+
Returns:
|
|
38
|
+
Filter type name (defaults to class name without 'Filter' suffix)
|
|
39
|
+
"""
|
|
40
|
+
class_name = self.__class__.__name__
|
|
41
|
+
if class_name.endswith("Filter"):
|
|
42
|
+
return class_name[:-6].lower()
|
|
43
|
+
return class_name.lower()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class DiagnosisFilter(BaseFilter):
|
|
47
|
+
"""
|
|
48
|
+
Filter for diagnosis parquet files.
|
|
49
|
+
|
|
50
|
+
Applies diagnosis-specific filtering and column transformations:
|
|
51
|
+
- Filters by birthdate (year > 1980)
|
|
52
|
+
- Filters by region (Region Sjælland)
|
|
53
|
+
- Renames columns to standardized event log format
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
CASE_ATTR = {
|
|
57
|
+
k: f"case:{v}"
|
|
58
|
+
for k, v in {
|
|
59
|
+
"BORGER_FOEDSELSDATO": "patient:birthdate",
|
|
60
|
+
"Personnummer": "concept:name",
|
|
61
|
+
}.items()
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
EVENT_ATTR = {
|
|
65
|
+
"ADIAG": "concept:name",
|
|
66
|
+
"KONT_ANS_GEO_REG_TEKST": "org:group",
|
|
67
|
+
"KONT_LPR_ENTITY_ID": "org:resource",
|
|
68
|
+
"KONT_INST_EJERTYPE": "org:role",
|
|
69
|
+
"KONT_STARTTIDSPUNKT": "start_timestamp",
|
|
70
|
+
"KONT_SLUTTIDSPUNKT": "time:timestamp",
|
|
71
|
+
# "BORGER_ALDER_AAR_IND": "patient:age",
|
|
72
|
+
"PRIORITET_TEKST": "medical:priority",
|
|
73
|
+
"KONT_TYPE_TEKST": "medical:contact_type",
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
def apply(self, lazy_frame: pl.LazyFrame) -> pl.LazyFrame:
|
|
77
|
+
"""
|
|
78
|
+
Apply diagnosis-specific filtering and transformations.
|
|
79
|
+
|
|
80
|
+
Args:
|
|
81
|
+
lazy_frame: Input LazyFrame containing diagnosis data
|
|
82
|
+
|
|
83
|
+
Returns:
|
|
84
|
+
Filtered and transformed LazyFrame
|
|
85
|
+
"""
|
|
86
|
+
return (
|
|
87
|
+
lazy_frame
|
|
88
|
+
# Filter by Birthdate (assuming it's a date/datetime type)
|
|
89
|
+
.filter(pl.col("BORGER_FOEDSELSDATO").dt.year() > 1980)
|
|
90
|
+
# Filter by Region
|
|
91
|
+
.filter(pl.col("KONT_ANS_GEO_REG_TEKST") == "Region Sjælland")
|
|
92
|
+
# Apply column name mappings
|
|
93
|
+
.rename(self.CASE_ATTR | self.EVENT_ATTR)
|
|
94
|
+
)
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""
|
|
2
|
+
I/O handler for parquet file processing.
|
|
3
|
+
|
|
4
|
+
This module provides generic I/O functionality for reading, filtering,
|
|
5
|
+
and writing parquet files. It uses a filter registry pattern to support
|
|
6
|
+
different filter types (diagnosis, procedure, medication, etc.).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Type
|
|
11
|
+
import polars as pl
|
|
12
|
+
|
|
13
|
+
from .diagnosis import BaseFilter, DiagnosisFilter
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
# Registry mapping filter type strings to filter classes
|
|
17
|
+
FILTER_REGISTRY: dict[str, Type[BaseFilter]] = {
|
|
18
|
+
"diagnosis": DiagnosisFilter,
|
|
19
|
+
# Future additions:
|
|
20
|
+
# "procedure": ProcedureFilter,
|
|
21
|
+
# "medication": MedicationFilter,
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def process_parquet_files(
|
|
26
|
+
input_dir: Path,
|
|
27
|
+
output_file: Path,
|
|
28
|
+
filter_type: str,
|
|
29
|
+
verbose: bool = False,
|
|
30
|
+
):
|
|
31
|
+
"""
|
|
32
|
+
Process parquet files with a specified filter type.
|
|
33
|
+
|
|
34
|
+
This function handles all I/O operations:
|
|
35
|
+
- Discovers parquet files in the input directory
|
|
36
|
+
- Lazily loads them using Polars
|
|
37
|
+
- Applies the specified filter transformation
|
|
38
|
+
- Collects the results and writes to output file
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
input_dir: Directory containing input parquet files
|
|
42
|
+
output_file: Path to output parquet file
|
|
43
|
+
filter_type: Type of filter to apply (e.g., "diagnosis", "procedure")
|
|
44
|
+
verbose: Whether to include verbose processing (currently unused in I/O layer)
|
|
45
|
+
|
|
46
|
+
Returns:
|
|
47
|
+
Tuple of (row_count, column_count, column_names)
|
|
48
|
+
|
|
49
|
+
Raises:
|
|
50
|
+
FileNotFoundError: If no parquet files found in input directory
|
|
51
|
+
ValueError: If filter_type is not registered
|
|
52
|
+
PermissionError: If unable to read/write files
|
|
53
|
+
MemoryError: If insufficient memory to process data
|
|
54
|
+
"""
|
|
55
|
+
# Validate filter type
|
|
56
|
+
if filter_type not in FILTER_REGISTRY:
|
|
57
|
+
available_filters = ", ".join(FILTER_REGISTRY.keys())
|
|
58
|
+
raise ValueError(
|
|
59
|
+
f"Unknown filter type '{filter_type}'. "
|
|
60
|
+
f"Available filters: {available_filters}"
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
# Check if input directory contains parquet files
|
|
64
|
+
parquet_files = list(input_dir.glob("*.parquet"))
|
|
65
|
+
if not parquet_files:
|
|
66
|
+
raise FileNotFoundError(f"No parquet files found in {input_dir}")
|
|
67
|
+
|
|
68
|
+
# Create parquet file pattern for lazy loading
|
|
69
|
+
parquet_pattern = str(input_dir / "*.parquet")
|
|
70
|
+
|
|
71
|
+
# Lazy load all parquet files
|
|
72
|
+
lazy_frame = pl.scan_parquet(parquet_pattern)
|
|
73
|
+
|
|
74
|
+
# Instantiate the appropriate filter
|
|
75
|
+
filter_class = FILTER_REGISTRY[filter_type]
|
|
76
|
+
filter_instance = filter_class()
|
|
77
|
+
|
|
78
|
+
# Apply the filter transformation
|
|
79
|
+
filtered_lazy_frame = filter_instance.apply(lazy_frame)
|
|
80
|
+
|
|
81
|
+
# Collect the lazy frame (materialize the data)
|
|
82
|
+
|
|
83
|
+
# Ensure output directory exists
|
|
84
|
+
output_file.parent.mkdir(parents=True, exist_ok=True)
|
|
85
|
+
|
|
86
|
+
filtered_lazy_frame.sink_parquet(output_file)
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""
|
|
2
|
+
SAS to Parquet converter module.
|
|
3
|
+
|
|
4
|
+
This module provides functionality to convert large SAS7BDAT files to Parquet format
|
|
5
|
+
in a memory-efficient way by processing the data in chunks.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Optional
|
|
11
|
+
import shutil
|
|
12
|
+
import click
|
|
13
|
+
import pyreadstat
|
|
14
|
+
import polars as pl
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def convert_sas_to_parquet(
|
|
18
|
+
input_file: Path,
|
|
19
|
+
output_path: Path,
|
|
20
|
+
chunk_size: int = 100000,
|
|
21
|
+
compression: str = "zstd",
|
|
22
|
+
encoding: Optional[str] = None,
|
|
23
|
+
overwrite: bool = False,
|
|
24
|
+
verbose: bool = False,
|
|
25
|
+
):
|
|
26
|
+
"""
|
|
27
|
+
Convert a SAS7BDAT file to Parquet format in chunks.
|
|
28
|
+
|
|
29
|
+
Parameters
|
|
30
|
+
----------
|
|
31
|
+
input_file : Path
|
|
32
|
+
Path to the SAS file (.sas7bdat)
|
|
33
|
+
output_path : Path
|
|
34
|
+
Path to output directory for Parquet files
|
|
35
|
+
chunk_size : int, optional
|
|
36
|
+
Number of rows to read per chunk (default: 100000)
|
|
37
|
+
compression : str, optional
|
|
38
|
+
Parquet compression algorithm (default: 'zstd')
|
|
39
|
+
encoding : str, optional
|
|
40
|
+
File encoding (default: auto-detect)
|
|
41
|
+
overwrite : bool, optional
|
|
42
|
+
Whether to overwrite existing output directory (default: False)
|
|
43
|
+
verbose : bool, optional
|
|
44
|
+
Enable verbose output (default: False)
|
|
45
|
+
|
|
46
|
+
Raises
|
|
47
|
+
------
|
|
48
|
+
FileNotFoundError
|
|
49
|
+
If the input file does not exist
|
|
50
|
+
ValueError
|
|
51
|
+
If the input file is not a .sas7bdat file or output path is invalid
|
|
52
|
+
PermissionError
|
|
53
|
+
If there are permission issues with files/directories
|
|
54
|
+
MemoryError
|
|
55
|
+
If there's insufficient memory (suggest smaller chunk_size)
|
|
56
|
+
"""
|
|
57
|
+
# Validate input file
|
|
58
|
+
if not input_file.exists():
|
|
59
|
+
click.secho(f"✗ Error: Input file not found: {input_file}", fg="red", err=True)
|
|
60
|
+
sys.exit(1)
|
|
61
|
+
|
|
62
|
+
if input_file.suffix.lower() != ".sas7bdat":
|
|
63
|
+
click.secho("✗ Error: Input file must be a .sas7bdat file", fg="red", err=True)
|
|
64
|
+
sys.exit(1)
|
|
65
|
+
|
|
66
|
+
# Handle output directory
|
|
67
|
+
output_path = Path(output_path)
|
|
68
|
+
|
|
69
|
+
if output_path.exists():
|
|
70
|
+
if not output_path.is_dir():
|
|
71
|
+
click.secho(
|
|
72
|
+
f"✗ Error: Output path exists and is not a directory: {output_path}",
|
|
73
|
+
fg="red",
|
|
74
|
+
err=True,
|
|
75
|
+
)
|
|
76
|
+
sys.exit(1)
|
|
77
|
+
|
|
78
|
+
if overwrite:
|
|
79
|
+
if verbose:
|
|
80
|
+
click.echo(f"Removing existing directory: {output_path}")
|
|
81
|
+
shutil.rmtree(output_path)
|
|
82
|
+
output_path.mkdir(parents=True, exist_ok=True)
|
|
83
|
+
else:
|
|
84
|
+
# Check if directory has parquet files
|
|
85
|
+
existing_parquet = list(output_path.glob("*.parquet"))
|
|
86
|
+
if existing_parquet:
|
|
87
|
+
click.secho(
|
|
88
|
+
f"⚠ Warning: Output directory already contains {len(existing_parquet)} .parquet file(s)",
|
|
89
|
+
fg="yellow",
|
|
90
|
+
)
|
|
91
|
+
if not click.confirm(
|
|
92
|
+
"Do you want to continue and potentially mix files?"
|
|
93
|
+
):
|
|
94
|
+
click.echo("Aborted.")
|
|
95
|
+
sys.exit(0)
|
|
96
|
+
else:
|
|
97
|
+
output_path.mkdir(parents=True, exist_ok=True)
|
|
98
|
+
|
|
99
|
+
# Display processing information
|
|
100
|
+
click.echo(f"Processing: {input_file}")
|
|
101
|
+
click.echo(f"Output directory: {output_path}")
|
|
102
|
+
if verbose:
|
|
103
|
+
click.echo(f"Chunk size: {chunk_size:,} rows")
|
|
104
|
+
click.echo(f"Compression: {compression}")
|
|
105
|
+
click.echo(f"Encoding: {encoding if encoding else 'auto-detect'}")
|
|
106
|
+
click.echo()
|
|
107
|
+
|
|
108
|
+
# Process file in chunks
|
|
109
|
+
click.echo("Converting SAS to Parquet...")
|
|
110
|
+
|
|
111
|
+
reader = pyreadstat.read_file_in_chunks(
|
|
112
|
+
pyreadstat.read_sas7bdat,
|
|
113
|
+
str(input_file),
|
|
114
|
+
chunksize=chunk_size,
|
|
115
|
+
encoding=encoding,
|
|
116
|
+
output_format="polars",
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
chunk_num = 0
|
|
120
|
+
total_rows = 0
|
|
121
|
+
num_columns = 0
|
|
122
|
+
|
|
123
|
+
for df_polars, meta in reader:
|
|
124
|
+
# Generate chunk filename with zero-padded numbering
|
|
125
|
+
chunk_filename = f"chunk_{chunk_num:04d}.parquet"
|
|
126
|
+
chunk_path = output_path / chunk_filename
|
|
127
|
+
|
|
128
|
+
# Write chunk to parquet
|
|
129
|
+
df_polars.write_parquet(chunk_path, compression=compression)
|
|
130
|
+
|
|
131
|
+
# Update statistics
|
|
132
|
+
chunk_rows = len(df_polars)
|
|
133
|
+
total_rows += chunk_rows
|
|
134
|
+
num_columns = len(meta.column_names)
|
|
135
|
+
chunk_num += 1
|
|
136
|
+
|
|
137
|
+
if verbose:
|
|
138
|
+
click.echo(
|
|
139
|
+
f" Wrote chunk {chunk_num}: {chunk_rows:,} rows → {chunk_filename}"
|
|
140
|
+
)
|
|
141
|
+
elif chunk_num % 10 == 0:
|
|
142
|
+
# Show progress every 10 chunks in non-verbose mode
|
|
143
|
+
click.echo(f" Processed {chunk_num} chunks ({total_rows:,} rows)...")
|
|
144
|
+
|
|
145
|
+
# Calculate file sizes
|
|
146
|
+
input_size = input_file.stat().st_size / (1024 * 1024) # MB
|
|
147
|
+
output_files = list(output_path.glob("*.parquet"))
|
|
148
|
+
output_size = sum(f.stat().st_size for f in output_files) / (1024 * 1024) # MB
|
|
149
|
+
compression_ratio = input_size / output_size if output_size > 0 else 0
|
|
150
|
+
|
|
151
|
+
# Display success message
|
|
152
|
+
click.echo()
|
|
153
|
+
click.secho("✓ Conversion completed successfully!", fg="green", bold=True)
|
|
154
|
+
click.echo(f"Input file: {input_size:.2f} MB ({input_file.name})")
|
|
155
|
+
click.echo(f"Output files: {output_size:.2f} MB ({len(output_files)} chunks)")
|
|
156
|
+
click.echo(f"Compression: {compression_ratio:.2f}x")
|
|
157
|
+
click.echo(f"Total rows: {total_rows:,}")
|
|
158
|
+
click.echo(f"Columns: {num_columns}")
|
|
159
|
+
click.echo(f"Chunk size: {chunk_size:,} rows/chunk")
|
|
160
|
+
click.echo()
|
|
161
|
+
click.echo("To read the data:")
|
|
162
|
+
click.echo(f" import polars as pl")
|
|
163
|
+
click.echo(f" df = pl.read_parquet('{output_path}/*.parquet')")
|