GenPatientProfile 0.1.0__py3-none-any.whl
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.
- genpatientprofile/__init__.py +17 -0
- genpatientprofile/base.py +57 -0
- genpatientprofile/config.py +11 -0
- genpatientprofile/core.py +116 -0
- genpatientprofile/fictive.py +52 -0
- genpatientprofile/registry.py +31 -0
- genpatientprofile/scenario.py +51 -0
- genpatientprofile/sites/__init__.py +0 -0
- genpatientprofile/sites/aphp/__init__.py +17 -0
- genpatientprofile/sites/aphp/code_cards.py +311 -0
- genpatientprofile/sites/aphp/constants.py +75 -0
- genpatientprofile/sites/aphp/fictive.py +159 -0
- genpatientprofile/sites/aphp/loader.py +388 -0
- genpatientprofile/sites/aphp/managment.py +500 -0
- genpatientprofile/sites/aphp/pipeline.py +221 -0
- genpatientprofile/sites/aphp/prompt.py +427 -0
- genpatientprofile/sites/aphp/prompt_sets.py +118 -0
- genpatientprofile/sites/aphp/sampler.py +291 -0
- genpatientprofile/sites/aphp/scenario.py +674 -0
- genpatientprofile/sites/aphp/templates/default/manifest.yaml +6 -0
- genpatientprofile/sites/aphp/templates/default/one_stage/delivery_inpatient_csection_hospit.txt +163 -0
- genpatientprofile/sites/aphp/templates/default/one_stage/delivery_inpatient_csection_urg.txt +163 -0
- genpatientprofile/sites/aphp/templates/default/one_stage/delivery_inpatient_hospit.txt +157 -0
- genpatientprofile/sites/aphp/templates/default/one_stage/delivery_inpatient_urg.txt +157 -0
- genpatientprofile/sites/aphp/templates/default/one_stage/medical_inpatient.txt +146 -0
- genpatientprofile/sites/aphp/templates/default/one_stage/medical_inpatient_obsteric.txt +147 -0
- genpatientprofile/sites/aphp/templates/default/one_stage/medical_inpatient_onco.txt +169 -0
- genpatientprofile/sites/aphp/templates/default/one_stage/medical_outpatient.txt +138 -0
- genpatientprofile/sites/aphp/templates/default/one_stage/medical_outpatient_onco.txt +168 -0
- genpatientprofile/sites/aphp/templates/default/one_stage/surgery_inpatient.txt +159 -0
- genpatientprofile/sites/aphp/templates/default/one_stage/surgery_inpatient_onco.txt +184 -0
- genpatientprofile/sites/aphp/templates/default/one_stage/surgery_outpatient.txt +131 -0
- genpatientprofile/sites/aphp/templates/default/one_stage/surgery_outpatient_onco.txt +141 -0
- genpatientprofile/sites/aphp/templates/default/prefix.txt +1 -0
- genpatientprofile/sites/aphp/templates/old/final/delivery_inpatient_csection_hospit.txt +170 -0
- genpatientprofile/sites/aphp/templates/old/final/delivery_inpatient_csection_urg.txt +170 -0
- genpatientprofile/sites/aphp/templates/old/final/delivery_inpatient_hospit.txt +164 -0
- genpatientprofile/sites/aphp/templates/old/final/delivery_inpatient_urg.txt +164 -0
- genpatientprofile/sites/aphp/templates/old/final/medical_inpatient.txt +152 -0
- genpatientprofile/sites/aphp/templates/old/final/medical_inpatient_obsteric.txt +154 -0
- genpatientprofile/sites/aphp/templates/old/final/medical_inpatient_onco.txt +175 -0
- genpatientprofile/sites/aphp/templates/old/final/medical_outpatient.txt +144 -0
- genpatientprofile/sites/aphp/templates/old/final/medical_outpatient_onco.txt +174 -0
- genpatientprofile/sites/aphp/templates/old/final/surgery_inpatient.txt +164 -0
- genpatientprofile/sites/aphp/templates/old/final/surgery_inpatient_onco.txt +190 -0
- genpatientprofile/sites/aphp/templates/old/final/surgery_outpatient.txt +140 -0
- genpatientprofile/sites/aphp/templates/old/final/surgery_outpatient_onco.txt +150 -0
- genpatientprofile/sites/aphp/templates/old/manifest.yaml +6 -0
- genpatientprofile/sites/aphp/templates/old/one_stage/delivery_inpatient_csection_hospit.txt +151 -0
- genpatientprofile/sites/aphp/templates/old/one_stage/delivery_inpatient_csection_urg.txt +151 -0
- genpatientprofile/sites/aphp/templates/old/one_stage/delivery_inpatient_hospit.txt +145 -0
- genpatientprofile/sites/aphp/templates/old/one_stage/delivery_inpatient_urg.txt +145 -0
- genpatientprofile/sites/aphp/templates/old/one_stage/medical_inpatient.txt +134 -0
- genpatientprofile/sites/aphp/templates/old/one_stage/medical_inpatient_obsteric.txt +135 -0
- genpatientprofile/sites/aphp/templates/old/one_stage/medical_inpatient_onco.txt +157 -0
- genpatientprofile/sites/aphp/templates/old/one_stage/medical_outpatient.txt +126 -0
- genpatientprofile/sites/aphp/templates/old/one_stage/medical_outpatient_onco.txt +156 -0
- genpatientprofile/sites/aphp/templates/old/one_stage/surgery_inpatient.txt +146 -0
- genpatientprofile/sites/aphp/templates/old/one_stage/surgery_inpatient_onco.txt +172 -0
- genpatientprofile/sites/aphp/templates/old/one_stage/surgery_outpatient.txt +122 -0
- genpatientprofile/sites/aphp/templates/old/one_stage/surgery_outpatient_onco.txt +132 -0
- genpatientprofile/sites/aphp/templates/old/summary/delivery_inpatient_csection_hospit.txt +96 -0
- genpatientprofile/sites/aphp/templates/old/summary/delivery_inpatient_csection_urg.txt +96 -0
- genpatientprofile/sites/aphp/templates/old/summary/delivery_inpatient_hospit.txt +96 -0
- genpatientprofile/sites/aphp/templates/old/summary/delivery_inpatient_urg.txt +96 -0
- genpatientprofile/sites/aphp/templates/old/summary/medical_inpatient.txt +94 -0
- genpatientprofile/sites/aphp/templates/old/summary/medical_inpatient_obsteric.txt +96 -0
- genpatientprofile/sites/aphp/templates/old/summary/medical_inpatient_onco.txt +94 -0
- genpatientprofile/sites/aphp/templates/old/summary/medical_outpatient.txt +94 -0
- genpatientprofile/sites/aphp/templates/old/summary/medical_outpatient_onco.txt +94 -0
- genpatientprofile/sites/aphp/templates/old/summary/surgery_inpatient.txt +94 -0
- genpatientprofile/sites/aphp/templates/old/summary/surgery_inpatient_onco.txt +94 -0
- genpatientprofile/sites/aphp/templates/old/summary/surgery_outpatient.txt +94 -0
- genpatientprofile/sites/aphp/templates/old/summary/surgery_outpatient_onco.txt +94 -0
- genpatientprofile/sites/aphp/templates/regles_atih.yml +482 -0
- genpatientprofile/sites/brest/__init__.py +0 -0
- genpatientprofile/sites/brest/constants.py +16 -0
- genpatientprofile/sites/brest/fictive.py +175 -0
- genpatientprofile/sites/brest/pipeline.py +104 -0
- genpatientprofile/sites/brest/sampler.py +89 -0
- genpatientprofile/sites/brest/scenario.py +113 -0
- genpatientprofile-0.1.0.dist-info/METADATA +258 -0
- genpatientprofile-0.1.0.dist-info/RECORD +86 -0
- genpatientprofile-0.1.0.dist-info/WHEEL +5 -0
- genpatientprofile-0.1.0.dist-info/licenses/LICENSE.md +353 -0
- genpatientprofile-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Hardcoded ICD-10 / CCAM / GHM code lists used by the AP-HP pipeline.
|
|
2
|
+
|
|
3
|
+
These are the literal lists from ``recode-scenario/utils_v2.py``
|
|
4
|
+
(``generate_scenario.__init__``, lines 179–216). They are clinical
|
|
5
|
+
classifications maintained by AP-HP and do not change frequently, so
|
|
6
|
+
inlining them keeps the code self-documenting.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
# ---- Cancer metastasis
|
|
12
|
+
ICD_CANCER_META_LN: list[str] = [
|
|
13
|
+
"C770", "C771", "C772", "C773", "C774", "C775", "C778", "C779",
|
|
14
|
+
]
|
|
15
|
+
ICD_CANCER_META: list[str] = [
|
|
16
|
+
"C780", "C781", "C782", "C783", "C784", "C785", "C786", "C787", "C788",
|
|
17
|
+
"C790", "C791", "C792", "C793", "C794", "C795", "C796", "C797", "C798",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
# ---- Treatment / contact codes
|
|
21
|
+
ICD_CONTACT_TT_REP: list[str] = ["Z491", "Z511", "Z512", "Z5101", "Z513", "Z516"]
|
|
22
|
+
ICD_CHIMIO_NON_TUM: list[str] = ["Z512"]
|
|
23
|
+
|
|
24
|
+
# ---- Cancer-treatment GHM groups
|
|
25
|
+
DRG_CHIMIO: list[str] = ["28Z07", "17M05", "17M06"]
|
|
26
|
+
DRG_RADIO: list[str] = [
|
|
27
|
+
"17K04", "17K05", "17K08", "17K09",
|
|
28
|
+
"28Z10", "28Z11", "28Z18", "28Z19", "28Z20", "28Z21", "28Z22", "28Z23",
|
|
29
|
+
"28Z24", "28Z25",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
# ---- Comfort / cosmetic / prophylactic
|
|
33
|
+
ICD_T2_CHRONIC_INTRACTABLE_PAIN: list[str] = ["R5210", "R5218"]
|
|
34
|
+
ICD_ASCITES: list[str] = ["R18"]
|
|
35
|
+
ICD_PLEURAL_EFFUSION: list[str] = ["J90", "J91", "J940", "J941", "J942", "J948", "J949"]
|
|
36
|
+
ICD_COSMETIC_SURGERY: list[str] = ["Z410", "Z411"]
|
|
37
|
+
ICD_COMFORT_INTERVENTION: list[str] = ["Z4180"]
|
|
38
|
+
ICD_PLASTIC_SURGERY: list[str] = [
|
|
39
|
+
"Z420", "Z421", "Z423", "Z424", "Z425", "Z426", "Z427", "Z428", "Z429",
|
|
40
|
+
]
|
|
41
|
+
ICD_PROPHYLACTIC_INTERVENTION: list[str] = ["Z400", "Z401", "Z408"]
|
|
42
|
+
|
|
43
|
+
# ---- Special-context GHM groups
|
|
44
|
+
DRG_GREFFE: list[str] = ["27Z02", "27Z03", "27Z04"]
|
|
45
|
+
DRG_TRANSFUSION: list[str] = ["28Z14"]
|
|
46
|
+
DRG_PALLIATIVE_CARE: list[str] = ["23Z02"]
|
|
47
|
+
DRG_STOMIES: list[str] = ["06M17"]
|
|
48
|
+
DRG_APHERESIS: list[str] = ["28Z16"]
|
|
49
|
+
DRG_DECEASED: list[str] = ["04M24"]
|
|
50
|
+
DRG_BILAN: list[str] = ["23M03"]
|
|
51
|
+
|
|
52
|
+
# ---- Delivery
|
|
53
|
+
DRG_VAGINAL_DELIVERY: list[str] = [
|
|
54
|
+
"14C03", "14Z09", "14Z10", "14Z11", "14Z12", "14Z13", "14Z14",
|
|
55
|
+
]
|
|
56
|
+
DRG_CSECTION: list[str] = ["14C06", "14C07", "14C08"]
|
|
57
|
+
DRG_DELIVERY: list[str] = DRG_VAGINAL_DELIVERY + DRG_CSECTION
|
|
58
|
+
|
|
59
|
+
PROC_VAGINAL_DELIVERY: list[str] = [
|
|
60
|
+
"JQGD001", "JQGD002", "JQGD003", "JQGD004", "JQGD005",
|
|
61
|
+
"JQGD007", "JQGD008", "JQGD010", "JQGD012", "JQGD013",
|
|
62
|
+
]
|
|
63
|
+
PROC_CSECTION: list[str] = ["JQGA002", "JQGA003", "JQGA004", "JQGA005"]
|
|
64
|
+
|
|
65
|
+
# ---- Exclusions
|
|
66
|
+
ICD_EXCLUSIONS: list[str] = [
|
|
67
|
+
"Z40", "Z08", "Z09", "Z48", "Z71", "Z48", "Z34", "Z35", "Z39",
|
|
68
|
+
"Z94", "Z95", "Z94", "Z96", "Z3908", "Z762",
|
|
69
|
+
]
|
|
70
|
+
EXCLUSION_SPECIALTY: list[str] = [
|
|
71
|
+
"THERAPIE TRANSFUSION",
|
|
72
|
+
"PSYCHIATRIE INFANTO-JUVENILE NON SECTORISE",
|
|
73
|
+
"PHYSIOLOGIE",
|
|
74
|
+
"PHYSIOLOGIE PEDIATRIQUE",
|
|
75
|
+
]
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import random as _random
|
|
2
|
+
import uuid
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import polars as pl
|
|
7
|
+
from tqdm import tqdm
|
|
8
|
+
|
|
9
|
+
from genpatientprofile.sites.aphp import managment
|
|
10
|
+
from genpatientprofile.sites.aphp import scenario as sc
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
# The _dicts_to_df helper is now in genpatientprofile.fictive.py
|
|
14
|
+
def generate_aphp_fictive(
|
|
15
|
+
data: dict[str, pl.LazyFrame],
|
|
16
|
+
n_sejours: int = 10,
|
|
17
|
+
seed: int | None = None,
|
|
18
|
+
) -> pl.DataFrame:
|
|
19
|
+
"""AP-HP-specific fictive generation (scenario-based sampling)."""
|
|
20
|
+
rng = _random.Random(seed)
|
|
21
|
+
np_rng = np.random.default_rng(seed)
|
|
22
|
+
|
|
23
|
+
steps = ["Contexte", "Profils", "Scénarios"]
|
|
24
|
+
pbar = tqdm(steps, desc="AP-HP génération", unit="étape")
|
|
25
|
+
|
|
26
|
+
# -- Build context objects (materialise all code sets)
|
|
27
|
+
pbar.set_description("Construction contexte")
|
|
28
|
+
sc_ctx = sc.build_context(data)
|
|
29
|
+
mg_ctx = managment.build_context(data, sc_ctx.cancer_codes, sc_ctx.chronic_codes)
|
|
30
|
+
pbar.update(1)
|
|
31
|
+
|
|
32
|
+
# -- Prepare profiles: join descriptions + LOS stats + specialty
|
|
33
|
+
pbar.set_description("Chargement profils")
|
|
34
|
+
profiles_df = sc_ctx.profiles
|
|
35
|
+
|
|
36
|
+
# Drop incomplete profiles from the new AP-HP scenarios file.
|
|
37
|
+
# Some rows have missing age / LOS / admission / discharge information
|
|
38
|
+
# and cannot be used to build a complete scenario.
|
|
39
|
+
required_cols = [
|
|
40
|
+
"age2",
|
|
41
|
+
"los",
|
|
42
|
+
"admission_mode",
|
|
43
|
+
"discharge_disposition",
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
for col in required_cols:
|
|
47
|
+
if col in profiles_df.columns:
|
|
48
|
+
if profiles_df[col].dtype in (pl.Float32, pl.Float64):
|
|
49
|
+
profiles_df = profiles_df.filter(
|
|
50
|
+
pl.col(col).is_not_null() & ~pl.col(col).is_nan()
|
|
51
|
+
)
|
|
52
|
+
else:
|
|
53
|
+
profiles_df = profiles_df.filter(pl.col(col).is_not_null())
|
|
54
|
+
|
|
55
|
+
# Join drg_parent_description if not already present
|
|
56
|
+
if "drg_parent_description" not in profiles_df.columns:
|
|
57
|
+
drg_descr = (
|
|
58
|
+
data["drg_parents_groups"]
|
|
59
|
+
.select(["drg_parent_code", "drg_parent_description"])
|
|
60
|
+
.collect()
|
|
61
|
+
)
|
|
62
|
+
profiles_df = profiles_df.join(drg_descr, on="drg_parent_code", how="left")
|
|
63
|
+
|
|
64
|
+
# Join LOS stats (los_mean, los_sd) if absent
|
|
65
|
+
missing_los = (
|
|
66
|
+
"los_mean" not in profiles_df.columns or "los_sd" not in profiles_df.columns
|
|
67
|
+
)
|
|
68
|
+
if missing_los:
|
|
69
|
+
los_stats = (
|
|
70
|
+
data["drg_statistics"]
|
|
71
|
+
.select(["drg_parent_code", "los_mean", "los_sd"])
|
|
72
|
+
.collect()
|
|
73
|
+
)
|
|
74
|
+
profiles_df = profiles_df.join(los_stats, on="drg_parent_code", how="left")
|
|
75
|
+
|
|
76
|
+
# Join dominant specialty if absent
|
|
77
|
+
if "specialty" not in profiles_df.columns:
|
|
78
|
+
spe = (
|
|
79
|
+
data["specialty"]
|
|
80
|
+
.collect()
|
|
81
|
+
.group_by("drg_parent_code")
|
|
82
|
+
.agg(pl.col("specialty").first())
|
|
83
|
+
)
|
|
84
|
+
profiles_df = profiles_df.join(spe, on="drg_parent_code", how="left")
|
|
85
|
+
|
|
86
|
+
# Weighted sampling (weight = nb count)
|
|
87
|
+
if "nb" in profiles_df.columns:
|
|
88
|
+
weights = profiles_df["nb"].cast(pl.Float64).fill_null(1.0).to_numpy().copy()
|
|
89
|
+
else:
|
|
90
|
+
weights = np.ones(len(profiles_df))
|
|
91
|
+
weights /= weights.sum()
|
|
92
|
+
|
|
93
|
+
n_to_sample = min(n_sejours, len(profiles_df)) ## TEMPORAIRE
|
|
94
|
+
|
|
95
|
+
indices = np_rng.choice(len(profiles_df), size=n_to_sample, replace=False, p=weights) ## FALSE TEMPORAIRE
|
|
96
|
+
sampled = profiles_df[indices]
|
|
97
|
+
pbar.update(1)
|
|
98
|
+
|
|
99
|
+
# -- Build one scenario per sampled profile
|
|
100
|
+
pbar.set_description("Construction scénarios")
|
|
101
|
+
rows: list[dict[str, Any]] = []
|
|
102
|
+
for profile in tqdm(
|
|
103
|
+
sampled.iter_rows(named=True),
|
|
104
|
+
desc="Scénarios",
|
|
105
|
+
unit="séjour",
|
|
106
|
+
total=n_sejours,
|
|
107
|
+
leave=False,
|
|
108
|
+
):
|
|
109
|
+
sc_dict = sc.build_scenario(sc_ctx, profile, rng=rng, np_rng=np_rng)
|
|
110
|
+
|
|
111
|
+
# Management decision (coding rule + situa text + template)
|
|
112
|
+
dec = managment.define_managment_type(sc_dict, mg_ctx, np_rng=np_rng)
|
|
113
|
+
sc_dict["situa"] = dec.situa
|
|
114
|
+
sc_dict["coding_rule"] = dec.coding_rule
|
|
115
|
+
sc_dict["template_name"] = dec.template_name
|
|
116
|
+
|
|
117
|
+
sc_dict["generation_id"] = str(uuid.uuid4())
|
|
118
|
+
rows.append(sc_dict)
|
|
119
|
+
|
|
120
|
+
pbar.update(1)
|
|
121
|
+
pbar.close()
|
|
122
|
+
|
|
123
|
+
return _dicts_to_df(rows)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _dicts_to_df(rows: list[dict[str, Any]]) -> pl.DataFrame:
|
|
127
|
+
"""Convert a list of scenario dicts to a Polars DataFrame.
|
|
128
|
+
|
|
129
|
+
Polars requires all series to have the same type. We cast list-valued
|
|
130
|
+
columns (``icd_secondary_code``) to ``pl.List(pl.Utf8)`` explicitly and
|
|
131
|
+
fall back to ``pl.Utf8`` for anything else that isn't already a scalar.
|
|
132
|
+
"""
|
|
133
|
+
if not rows:
|
|
134
|
+
return pl.DataFrame()
|
|
135
|
+
|
|
136
|
+
columns: dict[str, pl.Series] = {}
|
|
137
|
+
all_keys = list(rows[0].keys())
|
|
138
|
+
|
|
139
|
+
for key in all_keys:
|
|
140
|
+
values = [r.get(key) for r in rows]
|
|
141
|
+
# List-valued columns → List(Utf8)
|
|
142
|
+
if any(isinstance(v, list) for v in values):
|
|
143
|
+
columns[key] = pl.Series(
|
|
144
|
+
key,
|
|
145
|
+
[v if isinstance(v, list) else [] for v in values],
|
|
146
|
+
dtype=pl.List(pl.Utf8),
|
|
147
|
+
)
|
|
148
|
+
else:
|
|
149
|
+
try:
|
|
150
|
+
columns[key] = pl.Series(key, values)
|
|
151
|
+
except Exception:
|
|
152
|
+
# Last resort: stringify everything
|
|
153
|
+
columns[key] = pl.Series(
|
|
154
|
+
key,
|
|
155
|
+
[str(v) if v is not None else None for v in values],
|
|
156
|
+
dtype=pl.Utf8,
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
return pl.DataFrame(columns)
|
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
"""Lazy loaders for AP-HP referentials and PMSI input data.
|
|
2
|
+
|
|
3
|
+
Exposes two entry points:
|
|
4
|
+
|
|
5
|
+
- :func:`load_referentials` — returns versioned referential tables (ICD-10,
|
|
6
|
+
CCAM, GHM stats, French names, cancer methodology, …) as ``LazyFrame``
|
|
7
|
+
objects. The directory that contains those files is user-configured (see
|
|
8
|
+
``config/servers.yaml`` ``data.referentials`` key) so the files are kept
|
|
9
|
+
outside the repository.
|
|
10
|
+
- :func:`load_pmsi` — returns the three user-provided PMSI extracts
|
|
11
|
+
(profiles, secondary ICD, procedures) from ``config["data"]["input"]``.
|
|
12
|
+
- :func:`load_data` — merges both dicts into one for the pipeline.
|
|
13
|
+
|
|
14
|
+
Column names are normalised to the conventions used by AP-HP's
|
|
15
|
+
``recode-scenario`` (``drg_parent_code``, ``icd_primary_code``,
|
|
16
|
+
``case_management_type``, …) so downstream modules are a 1:1 port of
|
|
17
|
+
``utils_v2.py``.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
import polars as pl
|
|
26
|
+
import yaml
|
|
27
|
+
|
|
28
|
+
# ---------------------------------------------------------------------------
|
|
29
|
+
# Package-level paths (templates only — referentials are external)
|
|
30
|
+
# ---------------------------------------------------------------------------
|
|
31
|
+
|
|
32
|
+
PACKAGE_DIR = Path(__file__).resolve().parent
|
|
33
|
+
TEMPLATES_DIR = PACKAGE_DIR / "templates"
|
|
34
|
+
|
|
35
|
+
# ---------------------------------------------------------------------------
|
|
36
|
+
# Referentials — small helpers
|
|
37
|
+
# ---------------------------------------------------------------------------
|
|
38
|
+
|
|
39
|
+
# Code-list referentials: single-column ``code`` extracted from a ``code;descr``
|
|
40
|
+
# CSV. The downstream code only consumes the codes themselves.
|
|
41
|
+
_CODE_LIST_FILES: dict[str, str] = {
|
|
42
|
+
"icd_codes_chronic_attack": "icd_codes_chronic_attack.csv",
|
|
43
|
+
"procedure_botulic_toxin": "procedure_botulic_toxine.csv",
|
|
44
|
+
"icd_codes_prophylactic_intervention": "icd_codes_prophylactic_intervention.csv",
|
|
45
|
+
"attention_artificial_openings_external_prosthetic_device": "attention_artificial_openings_external_prosthetic_device.csv",
|
|
46
|
+
"icd_codes_iron_deficiency_anemia": "icd_codes_iron_deficiency_anemia.csv",
|
|
47
|
+
"icd_codes_sessions": "icd_codes_sessions.csv",
|
|
48
|
+
"icd_codes_diabetes_chronic": "icd_codes_diabetes_chronic.csv",
|
|
49
|
+
"icd_codes_spontaneous_vertex_delivery": "icd_codes_spontaneous_vertex_delivery.csv",
|
|
50
|
+
"icd_codes_liveborn_infants": "icd_codes_liveborn_infants.csv",
|
|
51
|
+
"icd_codes_medical_abortion": "icd_codes_medical_abortion.csv",
|
|
52
|
+
"icd_codes_legal_abortion": "icd_codes_legal_abortion.csv",
|
|
53
|
+
"icd_codes_supervision": "icd_codes_supervision.csv",
|
|
54
|
+
"icd_codes_supervision_chronic_disease": "icd_codes_supervision_chronic_disease.csv",
|
|
55
|
+
"icd_codes_surgical_followup": "icd_codes_surgical_followup.csv",
|
|
56
|
+
"icd_codes_supervision_pregnancy": "icd_codes_supervision_pregnancy.csv",
|
|
57
|
+
"icd_codes_supervision_post_partum": "icd_codes_supervision_post_partum.csv",
|
|
58
|
+
"icd_codes_cardic_vascular_implants": "icd_codes_cardic_vascular_implants.csv",
|
|
59
|
+
"icd_codes_overnight_study": "icd_codes_overnight_study.csv",
|
|
60
|
+
"icd_codes_sensitization_tests": "icd_codes_sensitization_tests.csv",
|
|
61
|
+
"icd_codes_preoperative_assessment": "icd_codes_preoperative_assessment.csv",
|
|
62
|
+
"icd_codes_family_history": "icd_codes_family_history.csv",
|
|
63
|
+
"icd_codes_personnel_history": "icd_codes_personnel_history.csv",
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _scan_code_list(r: Path, filename: str) -> pl.LazyFrame:
|
|
68
|
+
"""Read a ``code;description`` CSV and return only the ``code`` column."""
|
|
69
|
+
return pl.scan_csv(r / filename, separator=";").select("code")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
# ---------------------------------------------------------------------------
|
|
73
|
+
# Referentials — proper tables
|
|
74
|
+
# ---------------------------------------------------------------------------
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _scan_official_icd(r: Path) -> pl.LazyFrame:
|
|
78
|
+
"""Official ICD-10 dictionary from ATIH 2025."""
|
|
79
|
+
return (
|
|
80
|
+
pl.scan_parquet(r / "CIM_ATIH_2025" / "LIBCIM10MULTI.parquet")
|
|
81
|
+
.with_columns(
|
|
82
|
+
pl.col("icd_code")
|
|
83
|
+
.cast(pl.Utf8)
|
|
84
|
+
.str.strip_chars()
|
|
85
|
+
.alias("icd_code")
|
|
86
|
+
)
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
def _scan_icd_synonyms(r: Path) -> pl.LazyFrame:
|
|
90
|
+
"""Synonyms / alternative phrasings for ICD-10 codes."""
|
|
91
|
+
return (
|
|
92
|
+
pl.scan_csv(r / "cim_synonymes.csv")
|
|
93
|
+
.drop_nulls()
|
|
94
|
+
.rename({"dictionary_keys": "icd_code_description", "code": "icd_code"})
|
|
95
|
+
.with_columns(
|
|
96
|
+
pl.col("icd_code")
|
|
97
|
+
.cast(pl.Utf8)
|
|
98
|
+
.str.strip_chars()
|
|
99
|
+
.alias("icd_code")
|
|
100
|
+
)
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _scan_drg_statistics(r: Path) -> pl.LazyFrame:
|
|
105
|
+
"""Mean / SD length of stay per GHM root (``drg_parent_code``)."""
|
|
106
|
+
return pl.scan_parquet(r / "stat_racines.parquet").rename(
|
|
107
|
+
{"racine": "drg_parent_code", "dms": "los_mean", "dsd": "los_sd"}
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _scan_drg_parents_groups(r: Path) -> pl.LazyFrame:
|
|
112
|
+
"""GHM root descriptions and groupings (2024 ATIH classification)."""
|
|
113
|
+
return pl.scan_parquet(r / "ghm_rghm_regroupement_2024.parquet").rename(
|
|
114
|
+
{"racine": "drg_parent_code", "libelle_racine": "drg_parent_description"}
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _scan_chronic(r: Path) -> pl.LazyFrame:
|
|
119
|
+
"""Chronic-disease classification (code, chronic flag, libelle)."""
|
|
120
|
+
return pl.scan_parquet(r / "Affections chroniques.parquet")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _scan_complications(r: Path) -> pl.LazyFrame:
|
|
124
|
+
"""ICD codes flagged as acute complications (CMA list)."""
|
|
125
|
+
return pl.scan_csv(r / "cma.csv").drop_nulls()
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _scan_names(r: Path) -> pl.LazyFrame:
|
|
129
|
+
"""French first/last names with gender (``sexe`` ∈ {1, 2})."""
|
|
130
|
+
return pl.scan_csv(r / "prenoms_nom_sexe.csv", separator=";").drop_nulls()
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _scan_hospitals(r: Path) -> pl.LazyFrame:
|
|
134
|
+
"""One-column list of CHU hospital names."""
|
|
135
|
+
return pl.scan_csv(r / "chu", has_header=False, new_columns=["hospital"])
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _scan_specialty(r: Path) -> pl.LazyFrame:
|
|
139
|
+
"""Specialty ↔ DRG mapping with allocation ratios (AP-HP local)."""
|
|
140
|
+
return pl.scan_parquet(r / "dictionnaire_spe_racine.parquet").rename(
|
|
141
|
+
{
|
|
142
|
+
"racine": "drg_parent_code",
|
|
143
|
+
"lib_spe_uma": "specialty",
|
|
144
|
+
"ratio_spe_racine": "ratio",
|
|
145
|
+
}
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _scan_procedure_official(r: Path) -> pl.LazyFrame:
|
|
150
|
+
"""Official CCAM procedure dictionary (2024)."""
|
|
151
|
+
return pl.scan_parquet(r / "ccam_actes_2024.parquet").rename(
|
|
152
|
+
{"code": "procedure", "libelle_long": "procedure_description"}
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _scan_cancer_codes(r: Path) -> pl.LazyFrame:
|
|
157
|
+
"""ICD-10 codes flagged as cancer by the 2014 ATIH DIM methodology."""
|
|
158
|
+
return pl.scan_parquet(
|
|
159
|
+
r / "REFERENTIEL_METHODE_DIM_CANCER_20140411__CODES_CIM-10_CANCER.parquet"
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _scan_cancer_treatment(r: Path) -> pl.LazyFrame:
|
|
164
|
+
"""Cancer treatment recommendations (per primary site / histology)."""
|
|
165
|
+
return pl.scan_parquet(
|
|
166
|
+
r / "Tableau récapitulatif traitement cancer__Feuille_1.parquet"
|
|
167
|
+
).rename(
|
|
168
|
+
{
|
|
169
|
+
"Code CIM": "icd_parent_code",
|
|
170
|
+
"Localisation": "primary_site",
|
|
171
|
+
"Type Histologique": "histological_type",
|
|
172
|
+
"Stade": "stage",
|
|
173
|
+
"Marqueurs Tumoraux": "biomarkers",
|
|
174
|
+
"Traitement": "treatment_recommandation",
|
|
175
|
+
"Protocole de Chimiothérapie": "chemotherapy_regimen",
|
|
176
|
+
}
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _scan_icd_categ_weight(r: Path) -> pl.LazyFrame:
|
|
181
|
+
"""Per-ICD-category sampling weights (used by load_icd_categ_weight)."""
|
|
182
|
+
return pl.scan_csv(
|
|
183
|
+
r / "ponderation_code_categ.csv",
|
|
184
|
+
separator=";",
|
|
185
|
+
decimal_comma=True,
|
|
186
|
+
).rename({"diag": "icd_code", "ponderation": "weight"})
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _scan_exclusions(r: Path) -> pl.LazyFrame:
|
|
190
|
+
"""GHM groups excluded from sampling (transplants, dialysis, …)."""
|
|
191
|
+
return pl.scan_csv(r / "exclusions")
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
# ---------------------------------------------------------------------------
|
|
195
|
+
# ATIH coding rules (YAML, stays in the package alongside templates)
|
|
196
|
+
# ---------------------------------------------------------------------------
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def load_atih_rules() -> dict[str, dict]:
|
|
200
|
+
"""Parse ``templates/regles_atih.yml`` into ``{rule_id: {texte, criteres}}``.
|
|
201
|
+
|
|
202
|
+
Mirrors the YAML-loading block in ``generate_scenario.__init__``
|
|
203
|
+
(utils_v2.py:295–301). The file lives in ``genpatientprofile/sites/aphp/templates/``
|
|
204
|
+
(part of the codebase, not the external referentials directory).
|
|
205
|
+
"""
|
|
206
|
+
with (TEMPLATES_DIR / "regles_atih.yml").open("r", encoding="utf-8") as f:
|
|
207
|
+
rules = yaml.safe_load(f)
|
|
208
|
+
|
|
209
|
+
return {
|
|
210
|
+
d["id"]: {
|
|
211
|
+
"texte": d["clinical_coding_scenario"],
|
|
212
|
+
"criteres": d["classification_profile_criteria"],
|
|
213
|
+
}
|
|
214
|
+
for d in rules["regles"]
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
# ---------------------------------------------------------------------------
|
|
219
|
+
# PMSI input data (user-provided, in self.config["data"]["input"])
|
|
220
|
+
# ---------------------------------------------------------------------------
|
|
221
|
+
|
|
222
|
+
# Chaque motif porte une extension : un motif nu (``scenarios_*``) attrapait
|
|
223
|
+
# aussi les rapports texte déposés à côté des profils (``scenarios_C1_dp.rapport.txt``)
|
|
224
|
+
# et les faisait passer pour « le fichier de profils le plus récent ».
|
|
225
|
+
# ``.pq`` est l'extension historique des profils (``scenarios_bn_all_*.pq``).
|
|
226
|
+
_PMSI_PATTERNS: dict[str, tuple[str, ...]] = {
|
|
227
|
+
"profiles": ("scenarios_*.parquet", "scenarios_*.pq"),
|
|
228
|
+
"secondary_icd": ("bn_pmsi_related_diag_*.csv",),
|
|
229
|
+
"procedures": ("bn_pmsi_procedures_*.csv",),
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _resolve_pmsi_file(input_dir: Path, key: str) -> Path:
|
|
234
|
+
"""Pick the most recent file matching one of the patterns for *key*."""
|
|
235
|
+
patterns = _PMSI_PATTERNS[key]
|
|
236
|
+
matches: list[Path] = []
|
|
237
|
+
for pattern in patterns:
|
|
238
|
+
matches.extend(input_dir.glob(pattern))
|
|
239
|
+
if not matches:
|
|
240
|
+
raise FileNotFoundError(
|
|
241
|
+
f"Aucun fichier PMSI trouvé pour '{key}' dans {input_dir} "
|
|
242
|
+
f"(patterns essayés : {', '.join(patterns)})."
|
|
243
|
+
)
|
|
244
|
+
return max(matches, key=lambda p: p.stat().st_mtime)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
_PROFILE_RENAME: dict[str, str] = {
|
|
248
|
+
"racine": "drg_parent_code",
|
|
249
|
+
"diagnostic_associes": "icd_secondary_code",
|
|
250
|
+
"diag2": "icd_primary_code",
|
|
251
|
+
"mdp": "case_management_type",
|
|
252
|
+
"n": "nb",
|
|
253
|
+
"mode_entree": "admission_mode",
|
|
254
|
+
"mode_sortie": "discharge_disposition",
|
|
255
|
+
"mode_hospit": "admission_type",
|
|
256
|
+
"duree": "los",
|
|
257
|
+
"age": "cage",
|
|
258
|
+
"agean": "age2",
|
|
259
|
+
"nbda": "nb_associated",
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
_SECONDARY_RENAME: dict[str, str] = {
|
|
263
|
+
"racine": "drg_parent_code",
|
|
264
|
+
"das": "icd_secondary_code",
|
|
265
|
+
"diag": "icd_primary_code",
|
|
266
|
+
"categ_cim": "icd_primary_parent_code",
|
|
267
|
+
"mdp": "case_management_type",
|
|
268
|
+
"nb_situations": "nb",
|
|
269
|
+
"acte": "procedure",
|
|
270
|
+
"mode_entree": "admission_mode",
|
|
271
|
+
"mode_sortie": "discharge_disposition",
|
|
272
|
+
"mode_hospit": "admission_type",
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _safe_rename(lf: pl.LazyFrame, mapping: dict[str, str]) -> pl.LazyFrame:
|
|
277
|
+
"""Rename only the columns of *lf* that actually exist in *mapping*,
|
|
278
|
+
and whose target does not already exist in *lf*."""
|
|
279
|
+
existing = set(lf.collect_schema().names())
|
|
280
|
+
# On ignore aussi les renommages dont la CIBLE existe déjà : le renommage
|
|
281
|
+
# age→cage servait l'ancien format (scenarios_bn_all_*.pq) où « age » était
|
|
282
|
+
# la classe d'âge. Quand le profil apporte déjà « cage » (campagnes C1+),
|
|
283
|
+
# la donnée est à sa place et « age » porte autre chose (pivot ou âge
|
|
284
|
+
# exact) : il faut le laisser intact. La collision polars DuplicateError
|
|
285
|
+
# (« column 'cage' is duplicate ») n'en était que le symptôme.
|
|
286
|
+
# Ce filtre simple suppose qu'aucune cible du mapping n'est aussi une
|
|
287
|
+
# source (vérifié par tests/test_aphp_loader.py).
|
|
288
|
+
return lf.rename(
|
|
289
|
+
{k: v for k, v in mapping.items() if k in existing and v not in existing}
|
|
290
|
+
)
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _scan_profiles(input_dir: Path) -> pl.LazyFrame:
|
|
294
|
+
path = _resolve_pmsi_file(input_dir, "profiles")
|
|
295
|
+
return _safe_rename(pl.scan_parquet(path), _PROFILE_RENAME)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _scan_secondary_icd(input_dir: Path) -> pl.LazyFrame:
|
|
299
|
+
path = _resolve_pmsi_file(input_dir, "secondary_icd")
|
|
300
|
+
return _safe_rename(pl.scan_csv(path, separator=";"), _SECONDARY_RENAME)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _scan_procedures(input_dir: Path) -> pl.LazyFrame:
|
|
304
|
+
path = _resolve_pmsi_file(input_dir, "procedures")
|
|
305
|
+
return _safe_rename(pl.scan_csv(path, separator=";"), _SECONDARY_RENAME)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
# ---------------------------------------------------------------------------
|
|
309
|
+
# Public entry points
|
|
310
|
+
# ---------------------------------------------------------------------------
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def load_referentials(referentials_dir: str | Path) -> dict[str, pl.LazyFrame]:
|
|
314
|
+
"""Return all versioned referentials as ``LazyFrame`` objects.
|
|
315
|
+
|
|
316
|
+
Parameters
|
|
317
|
+
----------
|
|
318
|
+
referentials_dir:
|
|
319
|
+
Directory containing the AP-HP referential files (Parquet + CSV).
|
|
320
|
+
Configured via ``config["data"]["referentials"]`` in ``servers.yaml``.
|
|
321
|
+
"""
|
|
322
|
+
r = Path(referentials_dir)
|
|
323
|
+
data: dict[str, pl.LazyFrame] = {
|
|
324
|
+
"icd_official": _scan_official_icd(r),
|
|
325
|
+
"icd_synonyms": _scan_icd_synonyms(r),
|
|
326
|
+
"icd_categ_weight": _scan_icd_categ_weight(r),
|
|
327
|
+
"drg_statistics": _scan_drg_statistics(r),
|
|
328
|
+
"drg_parents_groups": _scan_drg_parents_groups(r),
|
|
329
|
+
"chronic": _scan_chronic(r),
|
|
330
|
+
"complications": _scan_complications(r),
|
|
331
|
+
"names": _scan_names(r),
|
|
332
|
+
"hospitals": _scan_hospitals(r),
|
|
333
|
+
"specialty": _scan_specialty(r),
|
|
334
|
+
"procedure_official": _scan_procedure_official(r),
|
|
335
|
+
"cancer_codes": _scan_cancer_codes(r),
|
|
336
|
+
"cancer_treatment": _scan_cancer_treatment(r),
|
|
337
|
+
"exclusions": _scan_exclusions(r),
|
|
338
|
+
}
|
|
339
|
+
for key, filename in _CODE_LIST_FILES.items():
|
|
340
|
+
data[key] = _scan_code_list(r, filename)
|
|
341
|
+
return data
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def load_pmsi(input_dir: str | Path) -> dict[str, pl.LazyFrame]:
|
|
345
|
+
"""Return the three PMSI input tables as ``LazyFrame`` objects.
|
|
346
|
+
|
|
347
|
+
Parameters
|
|
348
|
+
----------
|
|
349
|
+
input_dir:
|
|
350
|
+
Directory containing the user-provided PMSI extracts. The most recent
|
|
351
|
+
file matching each known pattern is picked.
|
|
352
|
+
"""
|
|
353
|
+
input_dir = Path(input_dir)
|
|
354
|
+
if not input_dir.is_dir():
|
|
355
|
+
raise FileNotFoundError(
|
|
356
|
+
f"Le répertoire d'entrée PMSI n'existe pas : {input_dir}"
|
|
357
|
+
)
|
|
358
|
+
return {
|
|
359
|
+
"profiles": _scan_profiles(input_dir),
|
|
360
|
+
"secondary_icd": _scan_secondary_icd(input_dir),
|
|
361
|
+
"procedures": _scan_procedures(input_dir),
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def load_data(
|
|
366
|
+
input_dir: str | Path,
|
|
367
|
+
referentials_dir: str | Path,
|
|
368
|
+
) -> dict[str, pl.LazyFrame]:
|
|
369
|
+
"""Merge :func:`load_referentials` and :func:`load_pmsi` into one dict.
|
|
370
|
+
|
|
371
|
+
Parameters
|
|
372
|
+
----------
|
|
373
|
+
input_dir:
|
|
374
|
+
Directory with user-provided PMSI extracts (``data.input`` in config).
|
|
375
|
+
referentials_dir:
|
|
376
|
+
Directory with AP-HP referential files (``data.referentials`` in config).
|
|
377
|
+
"""
|
|
378
|
+
return {**load_referentials(referentials_dir), **load_pmsi(input_dir)}
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def referential_paths(referentials_dir: str | Path) -> dict[str, Any]:
|
|
382
|
+
"""Expose key on-disk paths for use by ``check_data()``."""
|
|
383
|
+
r = Path(referentials_dir)
|
|
384
|
+
return {
|
|
385
|
+
"referentials_dir": r,
|
|
386
|
+
"templates_dir": TEMPLATES_DIR,
|
|
387
|
+
"atih_rules": TEMPLATES_DIR / "regles_atih.yml",
|
|
388
|
+
}
|