pyprevent 0.1.7__cp315-cp315-win_amd64.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.
pyprevent/__init__.py ADDED
@@ -0,0 +1,35 @@
1
+ """AHA PREVENT risk equations for ASCVD, total CVD, and heart failure."""
2
+
3
+ from .ascvd_calc import (
4
+ batch_calculate_10_yr_ascvd_risk,
5
+ batch_calculate_30_yr_ascvd_risk,
6
+ calculate_10_yr_ascvd_risk,
7
+ calculate_30_yr_ascvd_risk,
8
+ )
9
+ from .cvd import (
10
+ batch_calculate_10_yr_cvd_risk,
11
+ batch_calculate_30_yr_cvd_risk,
12
+ calculate_10_yr_cvd_risk,
13
+ calculate_30_yr_cvd_risk,
14
+ )
15
+ from .heart_failure import (
16
+ batch_calculate_10_yr_heart_failure_risk,
17
+ batch_calculate_30_yr_heart_failure_risk,
18
+ calculate_10_yr_heart_failure_risk,
19
+ calculate_30_yr_heart_failure_risk,
20
+ )
21
+
22
+ __all__ = [
23
+ "batch_calculate_10_yr_ascvd_risk",
24
+ "batch_calculate_10_yr_cvd_risk",
25
+ "batch_calculate_10_yr_heart_failure_risk",
26
+ "batch_calculate_30_yr_ascvd_risk",
27
+ "batch_calculate_30_yr_cvd_risk",
28
+ "batch_calculate_30_yr_heart_failure_risk",
29
+ "calculate_10_yr_ascvd_risk",
30
+ "calculate_10_yr_cvd_risk",
31
+ "calculate_10_yr_heart_failure_risk",
32
+ "calculate_30_yr_ascvd_risk",
33
+ "calculate_30_yr_cvd_risk",
34
+ "calculate_30_yr_heart_failure_risk",
35
+ ]
Binary file
@@ -0,0 +1,49 @@
1
+ """Type stub for the native module built from src/ by Maturin."""
2
+
3
+ from typing import TypedDict
4
+
5
+ import numpy as np
6
+ import numpy.typing as npt
7
+
8
+ class RiskFactors(TypedDict):
9
+ """Keys must match the fields of `RiskFactors` in src/risk_factors.rs."""
10
+
11
+ age: float
12
+ total_cholesterol: float
13
+ hdl_cholesterol: float
14
+ systolic_bp: float
15
+ has_diabetes: bool
16
+ current_smoker: bool
17
+ bmi: float
18
+ egfr: float
19
+ on_htn_meds: bool
20
+ on_cholesterol_meds: bool
21
+
22
+ def calculate_10_yr_ascvd_rust(sex: str, risk_factors: RiskFactors) -> float: ...
23
+ def calculate_30_yr_ascvd_rust(sex: str, risk_factors: RiskFactors) -> float: ...
24
+ def calculate_10_yr_cvd_rust(sex: str, risk_factors: RiskFactors) -> float: ...
25
+ def calculate_30_yr_cvd_rust(sex: str, risk_factors: RiskFactors) -> float: ...
26
+ def calculate_10_yr_heart_failure_rust(
27
+ sex: str, risk_factors: RiskFactors
28
+ ) -> float: ...
29
+ def calculate_30_yr_heart_failure_rust(
30
+ sex: str, risk_factors: RiskFactors
31
+ ) -> float: ...
32
+ def calculate_10_yr_ascvd_rust_parallel_np(
33
+ data: npt.NDArray[np.float64],
34
+ ) -> npt.NDArray[np.float64]: ...
35
+ def calculate_30_yr_ascvd_rust_parallel_np(
36
+ data: npt.NDArray[np.float64],
37
+ ) -> npt.NDArray[np.float64]: ...
38
+ def calculate_10_yr_cvd_rust_parallel_np(
39
+ data: npt.NDArray[np.float64],
40
+ ) -> npt.NDArray[np.float64]: ...
41
+ def calculate_30_yr_cvd_rust_parallel_np(
42
+ data: npt.NDArray[np.float64],
43
+ ) -> npt.NDArray[np.float64]: ...
44
+ def calculate_10_yr_hf_rust_parallel_np(
45
+ data: npt.NDArray[np.float64],
46
+ ) -> npt.NDArray[np.float64]: ...
47
+ def calculate_30_yr_hf_rust_parallel_np(
48
+ data: npt.NDArray[np.float64],
49
+ ) -> npt.NDArray[np.float64]: ...
@@ -0,0 +1,335 @@
1
+ """Atherosclerotic cardiovascular disease (ASCVD) risk for one patient or a DataFrame."""
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+
6
+ from . import _pyprevent
7
+ from .batch_preparation import _build_native_batch_array, _report_invalid_row_count
8
+
9
+
10
+ def calculate_10_yr_ascvd_risk(
11
+ sex: str,
12
+ age: float,
13
+ total_cholesterol: float,
14
+ hdl_cholesterol: float,
15
+ systolic_bp: float,
16
+ has_diabetes: bool,
17
+ current_smoker: bool,
18
+ bmi: float,
19
+ egfr: float,
20
+ on_htn_meds: bool,
21
+ on_cholesterol_meds: bool,
22
+ ) -> float:
23
+ """
24
+ Calculate the 10-year risk of atherosclerotic cardiovascular disease (ASCVD).
25
+
26
+ This function uses various health and lifestyle parameters to estimate the risk
27
+ of developing ASCVD over the next 10 years. The input values must fall within
28
+ specified ranges for the calculation to be valid.
29
+
30
+ Parameters:
31
+ - sex (str): The sex of the individual ('male' or 'female'). Case insensitive.
32
+ - age (float): Age of the individual in years. Must be between 30 and 79.
33
+ - total_cholesterol (float): Total cholesterol level (mg/dL). Must be between 130 and 320.
34
+ - hdl_cholesterol (float): High-density lipoprotein cholesterol level (mg/dL). Must be between 20 and 100.
35
+ - systolic_bp (float): Systolic blood pressure (mmHg). Must be between 90 and 200.
36
+ - has_diabetes (bool): Indicates if the individual has diabetes (True or False).
37
+ - current_smoker (bool): Indicates if the individual is a current smoker (True or False).
38
+ - bmi (float): Body mass index (kg/m^2). Must be between 18.5 and 39.9.
39
+ - egfr (float): Estimated glomerular filtration rate (mL/min/1.73 m^2). Must be between 15 and 140.
40
+ - on_htn_meds (bool): Indicates if the individual is on hypertension medication (True or False).
41
+ - on_cholesterol_meds (bool): Indicates if the individual is on cholesterol-lowering medication (True or False).
42
+
43
+ Returns:
44
+ float: The estimated 10-year ASCVD risk percentage.
45
+
46
+ Raises:
47
+ ValueError: If any of the input parameters are outside their valid ranges.
48
+
49
+ Example:
50
+ >>> calculate_10_yr_ascvd_risk(
51
+ ... sex="male",
52
+ ... age=45,
53
+ ... total_cholesterol=210,
54
+ ... hdl_cholesterol=55,
55
+ ... systolic_bp=130,
56
+ ... has_diabetes=False,
57
+ ... current_smoker=True,
58
+ ... bmi=28,
59
+ ... egfr=65,
60
+ ... on_htn_meds=False,
61
+ ... on_cholesterol_meds=False,
62
+ ... )
63
+ # Returns: Estimated 10-year ASCVD risk percentage (e.g., 12.3)
64
+ """
65
+ return _pyprevent.calculate_10_yr_ascvd_rust(
66
+ sex=sex,
67
+ risk_factors={
68
+ "age": age,
69
+ "total_cholesterol": total_cholesterol,
70
+ "hdl_cholesterol": hdl_cholesterol,
71
+ "systolic_bp": systolic_bp,
72
+ "has_diabetes": has_diabetes,
73
+ "current_smoker": current_smoker,
74
+ "bmi": bmi,
75
+ "egfr": egfr,
76
+ "on_htn_meds": on_htn_meds,
77
+ "on_cholesterol_meds": on_cholesterol_meds,
78
+ },
79
+ )
80
+
81
+
82
+ def calculate_30_yr_ascvd_risk(
83
+ sex: str,
84
+ age: float,
85
+ total_cholesterol: float,
86
+ hdl_cholesterol: float,
87
+ systolic_bp: float,
88
+ has_diabetes: bool,
89
+ current_smoker: bool,
90
+ bmi: float,
91
+ egfr: float,
92
+ on_htn_meds: bool,
93
+ on_cholesterol_meds: bool,
94
+ ) -> float:
95
+ """
96
+ Calculate the 30-year risk of atherosclerotic cardiovascular disease (ASCVD).
97
+
98
+ This function uses various health and lifestyle parameters to estimate the risk
99
+ of developing ASCVD over the next 30 years. The input values must fall within
100
+ specified ranges for the calculation to be valid.
101
+
102
+ Parameters:
103
+ - sex (str): The sex of the individual ('male' or 'female'). Case insensitive.
104
+ - age (float): Age of the individual in years. Must be between 30 and 59.
105
+ - total_cholesterol (float): Total cholesterol level (mg/dL). Must be between 130 and 320.
106
+ - hdl_cholesterol (float): High-density lipoprotein cholesterol level (mg/dL). Must be between 20 and 100.
107
+ - systolic_bp (float): Systolic blood pressure (mmHg). Must be between 90 and 200.
108
+ - has_diabetes (bool): Indicates if the individual has diabetes (True or False).
109
+ - current_smoker (bool): Indicates if the individual is a current smoker (True or False).
110
+ - bmi (float): Body mass index (kg/m^2). Must be between 18.5 and 39.9.
111
+ - egfr (float): Estimated glomerular filtration rate (mL/min/1.73 m^2). Must be between 15 and 140.
112
+ - on_htn_meds (bool): Indicates if the individual is on hypertension medication (True or False).
113
+ - on_cholesterol_meds (bool): Indicates if the individual is on cholesterol-lowering medication (True or False).
114
+
115
+ Returns:
116
+ float: The estimated 30-year ASCVD risk percentage.
117
+
118
+ Raises:
119
+ ValueError: If any of the input parameters are outside their valid ranges.
120
+
121
+ Example:
122
+ >>> calculate_30_yr_ascvd_risk(
123
+ ... sex="male",
124
+ ... age=45,
125
+ ... total_cholesterol=210,
126
+ ... hdl_cholesterol=55,
127
+ ... systolic_bp=130,
128
+ ... has_diabetes=False,
129
+ ... current_smoker=True,
130
+ ... bmi=28,
131
+ ... egfr=65,
132
+ ... on_htn_meds=False,
133
+ ... on_cholesterol_meds=False,
134
+ ... )
135
+ # Returns: Estimated 30-year ASCVD risk percentage (e.g., 12.3)
136
+ """
137
+ return _pyprevent.calculate_30_yr_ascvd_rust(
138
+ sex=sex,
139
+ risk_factors={
140
+ "age": age,
141
+ "total_cholesterol": total_cholesterol,
142
+ "hdl_cholesterol": hdl_cholesterol,
143
+ "systolic_bp": systolic_bp,
144
+ "has_diabetes": has_diabetes,
145
+ "current_smoker": current_smoker,
146
+ "bmi": bmi,
147
+ "egfr": egfr,
148
+ "on_htn_meds": on_htn_meds,
149
+ "on_cholesterol_meds": on_cholesterol_meds,
150
+ },
151
+ )
152
+
153
+
154
+ def batch_calculate_10_yr_ascvd_risk(
155
+ df: pd.DataFrame,
156
+ sex: str = "sex",
157
+ age: str = "age",
158
+ total_cholesterol: str = "total_cholesterol",
159
+ hdl_cholesterol: str = "hdl_cholesterol",
160
+ systolic_bp: str = "systolic_bp",
161
+ has_diabetes: str = "has_diabetes",
162
+ current_smoker: str = "current_smoker",
163
+ bmi: str = "bmi",
164
+ egfr: str = "egfr",
165
+ on_htn_meds: str = "on_htn_meds",
166
+ on_cholesterol_meds: str = "on_cholesterol_meds",
167
+ **unexpected_column_mappings: str,
168
+ ) -> np.ndarray:
169
+ """
170
+ Batch calculate the 10-year risk of atherosclerotic cardiovascular disease (ASCVD) for a dataset.
171
+
172
+ This function processes a DataFrame with health and lifestyle parameters to estimate
173
+ the 10-year ASCVD risk for each individual in the dataset. The input values must fall
174
+ within specified ranges for the calculation to be valid.
175
+
176
+ Parameters:
177
+ - df (pd.DataFrame): DataFrame containing the required data.
178
+ - sex (str): Column name for the sex of the individuals ('male' or 'female'). Case insensitive. Default 'sex'.
179
+ - age (str): Column name for the age of the individuals in years. Must be between 30 and 79. Default 'age'.
180
+ - total_cholesterol (str): Column name for the total cholesterol level (mg/dL). Must be between 130 and 320. Default 'total_cholesterol'.
181
+ - hdl_cholesterol (str): Column name for the HDL cholesterol level (mg/dL). Must be between 20 and 100. Default 'hdl_cholesterol'.
182
+ - systolic_bp (str): Column name for the systolic blood pressure (mmHg). Must be between 90 and 200. Default 'systolic_bp'.
183
+ - has_diabetes (str): Column name indicating if the individual has diabetes (True or False). Default 'has_diabetes'.
184
+ - current_smoker (str): Column name indicating if the individual is a current smoker (True or False). Default 'current_smoker'.
185
+ - bmi (str): Column name for the body mass index (kg/m^2). Must be between 18.5 and 39.9. Default 'bmi'.
186
+ - egfr (str): Column name for the estimated glomerular filtration rate (mL/min/1.73 m^2). Must be between 15 and 140. Default 'egfr'.
187
+ - on_htn_meds (str): Column name indicating if the individual is on hypertension medication (True or False). Default 'on_htn_meds'.
188
+ - on_cholesterol_meds (str): Column name indicating if the individual is on cholesterol-lowering medication (True or False). Default 'on_cholesterol_meds'.
189
+ - **unexpected_column_mappings: Any other keyword raises TypeError.
190
+
191
+ Returns:
192
+ numpy.ndarray: The estimated 10-year ASCVD risk percentage for each row, in input order.
193
+
194
+ Raises:
195
+ ValueError: If required columns are missing or column labels are duplicated.
196
+ TypeError: If an unknown column mapping is supplied.
197
+
198
+ Invalid rows produce NaN and a summary warning instead of a score.
199
+
200
+ Example:
201
+ >>> df = pd.DataFrame({...})
202
+ >>> risks = batch_calculate_10_yr_ascvd_risk(df, sex='gender', age='patient_age', ...)
203
+ >>> print(risks)
204
+ # Returns: A numpy array of estimated 10-year ASCVD risk percentages
205
+
206
+ Alternatively, pass a dictionary of column mappings:
207
+ >>> df = pd.DataFrame({...})
208
+ >>> column_mappings = {
209
+ ... 'sex': 'gender_column',
210
+ ... 'age': 'age_column',
211
+ ... 'total_cholesterol': 'cholesterol_total',
212
+ ... 'hdl_cholesterol': 'cholesterol_hdl',
213
+ ... 'systolic_bp': 'bp_systolic',
214
+ ... 'has_diabetes': 'diabetes_status',
215
+ ... 'current_smoker': 'smoker_status',
216
+ ... 'bmi': 'body_mass_index',
217
+ ... 'egfr': 'glomerular_rate',
218
+ ... 'on_htn_meds': 'hypertension_meds',
219
+ ... 'on_cholesterol_meds': 'cholesterol_meds'
220
+ ... }
221
+ >>> risks = batch_calculate_10_yr_ascvd_risk(df, **column_mappings)
222
+ # Returns: A numpy array of estimated 10-year ASCVD risk percentages
223
+ """
224
+ native_batch_array = _build_native_batch_array(
225
+ df=df,
226
+ sex=sex,
227
+ age=age,
228
+ total_cholesterol=total_cholesterol,
229
+ hdl_cholesterol=hdl_cholesterol,
230
+ systolic_bp=systolic_bp,
231
+ has_diabetes=has_diabetes,
232
+ current_smoker=current_smoker,
233
+ bmi=bmi,
234
+ egfr=egfr,
235
+ on_htn_meds=on_htn_meds,
236
+ on_cholesterol_meds=on_cholesterol_meds,
237
+ **unexpected_column_mappings,
238
+ )
239
+ risk_percentages = _pyprevent.calculate_10_yr_ascvd_rust_parallel_np(
240
+ data=native_batch_array
241
+ )
242
+ _report_invalid_row_count(risk_percentages=risk_percentages)
243
+ return risk_percentages
244
+
245
+
246
+ def batch_calculate_30_yr_ascvd_risk(
247
+ df: pd.DataFrame,
248
+ sex: str = "sex",
249
+ age: str = "age",
250
+ total_cholesterol: str = "total_cholesterol",
251
+ hdl_cholesterol: str = "hdl_cholesterol",
252
+ systolic_bp: str = "systolic_bp",
253
+ has_diabetes: str = "has_diabetes",
254
+ current_smoker: str = "current_smoker",
255
+ bmi: str = "bmi",
256
+ egfr: str = "egfr",
257
+ on_htn_meds: str = "on_htn_meds",
258
+ on_cholesterol_meds: str = "on_cholesterol_meds",
259
+ **unexpected_column_mappings: str,
260
+ ) -> np.ndarray:
261
+ """
262
+ Batch calculate the 30-year risk of atherosclerotic cardiovascular disease (ASCVD) for a dataset.
263
+
264
+ This function processes a DataFrame with health and lifestyle parameters to estimate
265
+ the 30-year ASCVD risk for each individual in the dataset. The input values must fall
266
+ within specified ranges for the calculation to be valid.
267
+
268
+ Parameters:
269
+ - df (pd.DataFrame): DataFrame containing the required data.
270
+ - sex (str): Column name for the sex of the individuals ('male' or 'female'). Case insensitive. Default 'sex'.
271
+ - age (str): Column name for the age of the individuals in years. Must be between 30 and 59. Default 'age'.
272
+ - total_cholesterol (str): Column name for the total cholesterol level (mg/dL). Must be between 130 and 320. Default 'total_cholesterol'.
273
+ - hdl_cholesterol (str): Column name for the HDL cholesterol level (mg/dL). Must be between 20 and 100. Default 'hdl_cholesterol'.
274
+ - systolic_bp (str): Column name for the systolic blood pressure (mmHg). Must be between 90 and 200. Default 'systolic_bp'.
275
+ - has_diabetes (str): Column name indicating if the individual has diabetes (True or False). Default 'has_diabetes'.
276
+ - current_smoker (str): Column name indicating if the individual is a current smoker (True or False). Default 'current_smoker'.
277
+ - bmi (str): Column name for the body mass index (kg/m^2). Must be between 18.5 and 39.9. Default 'bmi'.
278
+ - egfr (str): Column name for the estimated glomerular filtration rate (mL/min/1.73 m^2). Must be between 15 and 140. Default 'egfr'.
279
+ - on_htn_meds (str): Column name indicating if the individual is on hypertension medication (True or False). Default 'on_htn_meds'.
280
+ - on_cholesterol_meds (str): Column name indicating if the individual is on cholesterol-lowering medication (True or False). Default 'on_cholesterol_meds'.
281
+ - **unexpected_column_mappings: Any other keyword raises TypeError.
282
+
283
+ Returns:
284
+ numpy.ndarray: The estimated 30-year ASCVD risk percentage for each row, in input order.
285
+
286
+ Raises:
287
+ ValueError: If required columns are missing or column labels are duplicated.
288
+ TypeError: If an unknown column mapping is supplied.
289
+
290
+ Invalid rows produce NaN and a summary warning instead of a score.
291
+
292
+ Example:
293
+ >>> df = pd.DataFrame({...})
294
+ >>> risks = batch_calculate_30_yr_ascvd_risk(df, sex='gender', age='patient_age', ...)
295
+ >>> print(risks)
296
+ # Returns: A numpy array of estimated 30-year ASCVD risk percentages
297
+
298
+ Alternatively, pass a dictionary of column mappings:
299
+ >>> df = pd.DataFrame({...})
300
+ >>> column_mappings = {
301
+ ... 'sex': 'gender_column',
302
+ ... 'age': 'age_column',
303
+ ... 'total_cholesterol': 'cholesterol_total',
304
+ ... 'hdl_cholesterol': 'cholesterol_hdl',
305
+ ... 'systolic_bp': 'bp_systolic',
306
+ ... 'has_diabetes': 'diabetes_status',
307
+ ... 'current_smoker': 'smoker_status',
308
+ ... 'bmi': 'body_mass_index',
309
+ ... 'egfr': 'glomerular_rate',
310
+ ... 'on_htn_meds': 'hypertension_meds',
311
+ ... 'on_cholesterol_meds': 'cholesterol_meds'
312
+ ... }
313
+ >>> risks = batch_calculate_30_yr_ascvd_risk(df, **column_mappings)
314
+ # Returns: A numpy array of estimated 30-year ASCVD risk percentages
315
+ """
316
+ native_batch_array = _build_native_batch_array(
317
+ df=df,
318
+ sex=sex,
319
+ age=age,
320
+ total_cholesterol=total_cholesterol,
321
+ hdl_cholesterol=hdl_cholesterol,
322
+ systolic_bp=systolic_bp,
323
+ has_diabetes=has_diabetes,
324
+ current_smoker=current_smoker,
325
+ bmi=bmi,
326
+ egfr=egfr,
327
+ on_htn_meds=on_htn_meds,
328
+ on_cholesterol_meds=on_cholesterol_meds,
329
+ **unexpected_column_mappings,
330
+ )
331
+ risk_percentages = _pyprevent.calculate_30_yr_ascvd_rust_parallel_np(
332
+ data=native_batch_array
333
+ )
334
+ _report_invalid_row_count(risk_percentages=risk_percentages)
335
+ return risk_percentages
@@ -0,0 +1,95 @@
1
+ """Convert a patient DataFrame into the numeric array the native batch code reads."""
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+
6
+ from .config import (
7
+ BOOLEAN_BATCH_COLUMNS,
8
+ INVALID_ROWS_WARNING_TEMPLATE,
9
+ NATIVE_BATCH_COLUMN_ORDER,
10
+ NATIVE_FLAG_BY_SEX_LABEL,
11
+ )
12
+
13
+
14
+ def _build_native_batch_array(
15
+ df: pd.DataFrame,
16
+ sex: str = "sex",
17
+ age: str = "age",
18
+ total_cholesterol: str = "total_cholesterol",
19
+ hdl_cholesterol: str = "hdl_cholesterol",
20
+ systolic_bp: str = "systolic_bp",
21
+ has_diabetes: str = "has_diabetes",
22
+ current_smoker: str = "current_smoker",
23
+ bmi: str = "bmi",
24
+ egfr: str = "egfr",
25
+ on_htn_meds: str = "on_htn_meds",
26
+ on_cholesterol_meds: str = "on_cholesterol_meds",
27
+ **unexpected_column_mappings: str,
28
+ ) -> np.ndarray:
29
+ """Build the (n, 11) float64 array for the native batch functions.
30
+
31
+ Each keyword names the DataFrame column that holds that input. Invalid
32
+ sex labels and non-0/1 boolean values become NaN, so the native code
33
+ rejects those rows instead of scoring them.
34
+
35
+ Raises:
36
+ TypeError: If an unknown column mapping is supplied.
37
+ ValueError: If column labels are duplicated or a mapped column is missing.
38
+ """
39
+ column_name_by_parameter = {
40
+ "sex": sex,
41
+ "age": age,
42
+ "total_cholesterol": total_cholesterol,
43
+ "hdl_cholesterol": hdl_cholesterol,
44
+ "systolic_bp": systolic_bp,
45
+ "has_diabetes": has_diabetes,
46
+ "current_smoker": current_smoker,
47
+ "bmi": bmi,
48
+ "egfr": egfr,
49
+ "on_htn_meds": on_htn_meds,
50
+ "on_cholesterol_meds": on_cholesterol_meds,
51
+ }
52
+
53
+ if unexpected_column_mappings:
54
+ raise TypeError(
55
+ f"Unexpected column mappings: {', '.join(sorted(unexpected_column_mappings))}"
56
+ )
57
+ if not df.columns.is_unique:
58
+ raise ValueError("DataFrame column names must be unique.")
59
+ for parameter_name in NATIVE_BATCH_COLUMN_ORDER:
60
+ column_name = column_name_by_parameter[parameter_name]
61
+ if column_name not in df.columns:
62
+ raise ValueError(
63
+ f"Column '{column_name}' for parameter '{parameter_name}' not found in DataFrame."
64
+ )
65
+
66
+ # Allocate the native layout once, without copying the whole DataFrame.
67
+ native_batch_array = np.empty(
68
+ (len(df), len(NATIVE_BATCH_COLUMN_ORDER)), dtype=np.float64
69
+ )
70
+ for column_index, parameter_name in enumerate(NATIVE_BATCH_COLUMN_ORDER):
71
+ column_values = df[column_name_by_parameter[parameter_name]]
72
+ if parameter_name == "sex":
73
+ try:
74
+ column_values = column_values.str.lower().map(NATIVE_FLAG_BY_SEX_LABEL)
75
+ except AttributeError:
76
+ # An entirely numeric or missing column has no string accessor.
77
+ native_batch_array[:, column_index] = np.nan
78
+ continue
79
+ elif parameter_name in BOOLEAN_BATCH_COLUMNS and not pd.api.types.is_bool_dtype(
80
+ column_values.dtype
81
+ ):
82
+ column_values = column_values.where(column_values.isin([0, 1]))
83
+ if not pd.api.types.is_numeric_dtype(column_values.dtype):
84
+ column_values = pd.to_numeric(column_values, errors="coerce")
85
+ native_batch_array[:, column_index] = column_values.to_numpy(
86
+ dtype=np.float64, na_value=np.nan
87
+ )
88
+ return native_batch_array
89
+
90
+
91
+ def _report_invalid_row_count(risk_percentages: np.ndarray) -> None:
92
+ """Print one warning line when any row could not be scored."""
93
+ invalid_row_count = np.isnan(risk_percentages).sum()
94
+ if invalid_row_count > 0:
95
+ print(INVALID_ROWS_WARNING_TEMPLATE.format(invalid_row_count=invalid_row_count))
pyprevent/config.py ADDED
@@ -0,0 +1,32 @@
1
+ """Static values shared by the Python wrappers."""
2
+
3
+ # ============================================================
4
+ # Native Batch Array Layout
5
+ # ============================================================
6
+ # Column order of the (n, 11) array read by src/risk_calculation.rs; it must
7
+ # match the *_COLUMN indexes in src/config.rs.
8
+ NATIVE_BATCH_COLUMN_ORDER = (
9
+ "sex",
10
+ "age",
11
+ "total_cholesterol",
12
+ "hdl_cholesterol",
13
+ "systolic_bp",
14
+ "has_diabetes",
15
+ "current_smoker",
16
+ "bmi",
17
+ "egfr",
18
+ "on_htn_meds",
19
+ "on_cholesterol_meds",
20
+ )
21
+ BOOLEAN_BATCH_COLUMNS = frozenset(
22
+ {"has_diabetes", "current_smoker", "on_htn_meds", "on_cholesterol_meds"}
23
+ )
24
+ NATIVE_FLAG_BY_SEX_LABEL = {"female": 0, "male": 1}
25
+
26
+ # ============================================================
27
+ # Messages
28
+ # ============================================================
29
+ INVALID_ROWS_WARNING_TEMPLATE = (
30
+ "WARNING: {invalid_row_count} patients were unable to have the score calculated"
31
+ " as their input parameters were invalid or out of range."
32
+ )