egfr40 0.0.1a1__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.
egfr40-0.0.1a1/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Leonid Shpaner
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,183 @@
1
+ Metadata-Version: 2.4
2
+ Name: egfr40
3
+ Version: 0.0.1a1
4
+ Summary: CKD-PC risk equation for a >=40% eGFR decline or kidney failure over 2-3 years (Grams et al., Diabetes Care 2022)
5
+ Author-email: Leonid Shpaner <lshpaner@ucla.edu>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/lshpaner/egfr40
8
+ Project-URL: Issues, https://github.com/lshpaner/egfr40/issues
9
+ Keywords: nephrology,ckd,egfr,risk prediction,ckd-pc,kidney
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: numpy>=1.20
18
+ Requires-Dist: pandas>=1.3
19
+ Provides-Extra: dev
20
+ Requires-Dist: pytest>=7; extra == "dev"
21
+ Requires-Dist: build; extra == "dev"
22
+ Requires-Dist: twine; extra == "dev"
23
+ Provides-Extra: nhanes
24
+ Requires-Dist: requests; extra == "nhanes"
25
+ Requires-Dist: typer; extra == "nhanes"
26
+ Requires-Dist: pyarrow; extra == "nhanes"
27
+ Dynamic: license-file
28
+
29
+ # egfr40
30
+
31
+ Python implementation of the CKD Prognosis Consortium (CKD-PC) risk equation for the
32
+ **3-year probability of a ≥40% decline in eGFR or kidney failure**, from Grams et al.,
33
+ *Diabetes Care* 2022. This is the equation behind the
34
+ [ckdpcrisk.org/gfrdecline40](https://ckdpcrisk.org/gfrdecline40/) calculator.
35
+
36
+ > **Not affiliated with the CKD Prognosis Consortium.** This is an independent
37
+ > implementation of a published equation, intended for research use. It is not a
38
+ > medical device and should not be used to make clinical decisions.
39
+
40
+ ## Installation
41
+
42
+ ```bash
43
+ pip install egfr40
44
+ ```
45
+
46
+ Development install:
47
+
48
+ ```bash
49
+ git clone https://github.com/lshpaner/egfr40.git
50
+ cd egfr40
51
+ pip install -e ".[dev]"
52
+ ```
53
+
54
+ ## Usage
55
+
56
+ ### One patient
57
+
58
+ ```python
59
+ from egfr40 import egfr40_risk
60
+
61
+ egfr40_risk(
62
+ age=70, male=1, egfr=40, uacr=150, sbp=140, bp_meds=1,
63
+ hf=0, chd=1, afib=1, smoking="former", bmi=28,
64
+ dm=True, hba1c=7, oral_dm=0, insulin=0,
65
+ )
66
+ # 0.166
67
+ ```
68
+
69
+ ### eGFR
70
+
71
+ ```python
72
+ from egfr40 import ckd_epi_2021
73
+
74
+ ckd_epi_2021(scr=1.2, age=70, male=1) # mL/min/1.73 m^2, race-free 2021 equation
75
+ ```
76
+
77
+ ### A whole cohort
78
+
79
+ ```python
80
+ from egfr40 import add_egfr40_risk_col
81
+
82
+ df = add_egfr40_risk_col(
83
+ df,
84
+ age_col="age", sex_col="sex", egfr_col="eGFR", uacr_col="uACR",
85
+ sbp_col="sbp", bp_meds_col="bp_meds",
86
+ hf_col="hf", chd_col="chd", afib_col="afib",
87
+ smoking_col="smoking", bmi_col="bmi",
88
+ dm_col="dm", hba1c_col="hba1c", oral_dm_col="oral_dm", insulin_col="insulin",
89
+ )
90
+ df["egfr40_3year"]
91
+ ```
92
+
93
+ Each row is scored with its own stratum. Rows missing any required input get `NaN`.
94
+
95
+ ## Inputs
96
+
97
+ | Input | Units / values |
98
+ |---|---|
99
+ | Age | years |
100
+ | Sex | `male`/`female`, `m`/`f`, or 1 = male / 0 = female |
101
+ | eGFR | mL/min/1.73 m², CKD-EPI 2021 creatinine equation |
102
+ | uACR | mg/g |
103
+ | Systolic BP | mmHg |
104
+ | Antihypertensive medication | 1/0 or yes/no |
105
+ | History of heart failure, CHD, atrial fibrillation | 1/0 or yes/no |
106
+ | Smoking | `never`, `former`, `current` |
107
+ | BMI | kg/m² |
108
+ | Diabetes | 1/0 or yes/no (**required**: selects the model) |
109
+ | HbA1c | % (diabetes only) |
110
+ | Oral diabetes medication, insulin | 1/0 or yes/no (diabetes only) |
111
+
112
+ ## The model
113
+
114
+ Four logistic models, stratified by diabetes status and eGFR (≥60 or <60):
115
+
116
+ $$
117
+ p = \frac{1}{1 + e^{-(\beta_0 + \sum_i \beta_i x_i)}}
118
+ $$
119
+
120
+ Coefficients, intercepts, and the centering and scaling of each predictor are taken from
121
+ **Supplemental Table S5** of the paper. All 52 coefficients match the model 2 odds
122
+ ratios reported in Tables 2 and 3, and the package reproduces the online calculator.
123
+
124
+ **eGFR = 60 boundary.** The stratified models do not meet at eGFR 60. Following the
125
+ CKD-PC website, risk at exactly eGFR 60 is the average of the two strata.
126
+
127
+ **Notes on the source**
128
+
129
+ - The calculator also asks for race and hypertension status. Neither appears in the
130
+ published Table S5 model, so neither is an input here.
131
+ - The hypertension-based alternative models (Supplemental Tables S6 and S7) are published
132
+ without intercepts and cannot be implemented.
133
+ - HbA1c is labeled "mmol" in the paper's tables. Its centering at 7 in Table S5 shows the
134
+ unit is percent.
135
+
136
+ ## Testing
137
+
138
+ ```bash
139
+ make test
140
+ ```
141
+
142
+ The tests check the coefficients against the paper's odds ratios, a case verified
143
+ against the online calculator, the eGFR 60 averaging, and agreement between the
144
+ single-patient and DataFrame functions.
145
+
146
+ ## NHANES example
147
+
148
+ `data_gen.py` downloads the raw NHANES 2017–March 2020 pre-pandemic files needed to apply
149
+ the equation to a nationally representative sample:
150
+
151
+ ```bash
152
+ pip install -e ".[nhanes]"
153
+ make data_gen
154
+ ```
155
+
156
+ Files are saved to `data/raw/` (gitignored). Then build the analysis file:
157
+
158
+ ```bash
159
+ make preprocess
160
+ ```
161
+
162
+ This merges the files, computes CKD-EPI 2021 eGFR, recodes each predictor, and applies
163
+ the inclusion criteria (age 20-80, not pregnant, eGFR >= 15, complete inputs). Output:
164
+ `data/processed/nhanes_egfr40.parquet`.
165
+
166
+ NHANES-specific choices:
167
+
168
+ - Atrial fibrillation is not collected, so it is set to 0.
169
+ - CHD includes self-reported coronary heart disease or heart attack.
170
+ - Diabetes is self-reported diagnosis, diabetes medication, or HbA1c >= 6.5%.
171
+ - SBP is the mean of the available oscillometric readings.
172
+
173
+ ## Citation
174
+
175
+ If you use this package, please cite the original paper:
176
+
177
+ > Grams ME, Brunskill NJ, Ballew SH, et al. Development and Validation of Prediction
178
+ > Models of Adverse Kidney Outcomes in the Population With and Without Diabetes.
179
+ > *Diabetes Care*. 2022;45(9):2055-2063. doi:10.2337/dc22-0698
180
+
181
+ ## License
182
+
183
+ MIT
@@ -0,0 +1,155 @@
1
+ # egfr40
2
+
3
+ Python implementation of the CKD Prognosis Consortium (CKD-PC) risk equation for the
4
+ **3-year probability of a ≥40% decline in eGFR or kidney failure**, from Grams et al.,
5
+ *Diabetes Care* 2022. This is the equation behind the
6
+ [ckdpcrisk.org/gfrdecline40](https://ckdpcrisk.org/gfrdecline40/) calculator.
7
+
8
+ > **Not affiliated with the CKD Prognosis Consortium.** This is an independent
9
+ > implementation of a published equation, intended for research use. It is not a
10
+ > medical device and should not be used to make clinical decisions.
11
+
12
+ ## Installation
13
+
14
+ ```bash
15
+ pip install egfr40
16
+ ```
17
+
18
+ Development install:
19
+
20
+ ```bash
21
+ git clone https://github.com/lshpaner/egfr40.git
22
+ cd egfr40
23
+ pip install -e ".[dev]"
24
+ ```
25
+
26
+ ## Usage
27
+
28
+ ### One patient
29
+
30
+ ```python
31
+ from egfr40 import egfr40_risk
32
+
33
+ egfr40_risk(
34
+ age=70, male=1, egfr=40, uacr=150, sbp=140, bp_meds=1,
35
+ hf=0, chd=1, afib=1, smoking="former", bmi=28,
36
+ dm=True, hba1c=7, oral_dm=0, insulin=0,
37
+ )
38
+ # 0.166
39
+ ```
40
+
41
+ ### eGFR
42
+
43
+ ```python
44
+ from egfr40 import ckd_epi_2021
45
+
46
+ ckd_epi_2021(scr=1.2, age=70, male=1) # mL/min/1.73 m^2, race-free 2021 equation
47
+ ```
48
+
49
+ ### A whole cohort
50
+
51
+ ```python
52
+ from egfr40 import add_egfr40_risk_col
53
+
54
+ df = add_egfr40_risk_col(
55
+ df,
56
+ age_col="age", sex_col="sex", egfr_col="eGFR", uacr_col="uACR",
57
+ sbp_col="sbp", bp_meds_col="bp_meds",
58
+ hf_col="hf", chd_col="chd", afib_col="afib",
59
+ smoking_col="smoking", bmi_col="bmi",
60
+ dm_col="dm", hba1c_col="hba1c", oral_dm_col="oral_dm", insulin_col="insulin",
61
+ )
62
+ df["egfr40_3year"]
63
+ ```
64
+
65
+ Each row is scored with its own stratum. Rows missing any required input get `NaN`.
66
+
67
+ ## Inputs
68
+
69
+ | Input | Units / values |
70
+ |---|---|
71
+ | Age | years |
72
+ | Sex | `male`/`female`, `m`/`f`, or 1 = male / 0 = female |
73
+ | eGFR | mL/min/1.73 m², CKD-EPI 2021 creatinine equation |
74
+ | uACR | mg/g |
75
+ | Systolic BP | mmHg |
76
+ | Antihypertensive medication | 1/0 or yes/no |
77
+ | History of heart failure, CHD, atrial fibrillation | 1/0 or yes/no |
78
+ | Smoking | `never`, `former`, `current` |
79
+ | BMI | kg/m² |
80
+ | Diabetes | 1/0 or yes/no (**required**: selects the model) |
81
+ | HbA1c | % (diabetes only) |
82
+ | Oral diabetes medication, insulin | 1/0 or yes/no (diabetes only) |
83
+
84
+ ## The model
85
+
86
+ Four logistic models, stratified by diabetes status and eGFR (≥60 or <60):
87
+
88
+ $$
89
+ p = \frac{1}{1 + e^{-(\beta_0 + \sum_i \beta_i x_i)}}
90
+ $$
91
+
92
+ Coefficients, intercepts, and the centering and scaling of each predictor are taken from
93
+ **Supplemental Table S5** of the paper. All 52 coefficients match the model 2 odds
94
+ ratios reported in Tables 2 and 3, and the package reproduces the online calculator.
95
+
96
+ **eGFR = 60 boundary.** The stratified models do not meet at eGFR 60. Following the
97
+ CKD-PC website, risk at exactly eGFR 60 is the average of the two strata.
98
+
99
+ **Notes on the source**
100
+
101
+ - The calculator also asks for race and hypertension status. Neither appears in the
102
+ published Table S5 model, so neither is an input here.
103
+ - The hypertension-based alternative models (Supplemental Tables S6 and S7) are published
104
+ without intercepts and cannot be implemented.
105
+ - HbA1c is labeled "mmol" in the paper's tables. Its centering at 7 in Table S5 shows the
106
+ unit is percent.
107
+
108
+ ## Testing
109
+
110
+ ```bash
111
+ make test
112
+ ```
113
+
114
+ The tests check the coefficients against the paper's odds ratios, a case verified
115
+ against the online calculator, the eGFR 60 averaging, and agreement between the
116
+ single-patient and DataFrame functions.
117
+
118
+ ## NHANES example
119
+
120
+ `data_gen.py` downloads the raw NHANES 2017–March 2020 pre-pandemic files needed to apply
121
+ the equation to a nationally representative sample:
122
+
123
+ ```bash
124
+ pip install -e ".[nhanes]"
125
+ make data_gen
126
+ ```
127
+
128
+ Files are saved to `data/raw/` (gitignored). Then build the analysis file:
129
+
130
+ ```bash
131
+ make preprocess
132
+ ```
133
+
134
+ This merges the files, computes CKD-EPI 2021 eGFR, recodes each predictor, and applies
135
+ the inclusion criteria (age 20-80, not pregnant, eGFR >= 15, complete inputs). Output:
136
+ `data/processed/nhanes_egfr40.parquet`.
137
+
138
+ NHANES-specific choices:
139
+
140
+ - Atrial fibrillation is not collected, so it is set to 0.
141
+ - CHD includes self-reported coronary heart disease or heart attack.
142
+ - Diabetes is self-reported diagnosis, diabetes medication, or HbA1c >= 6.5%.
143
+ - SBP is the mean of the available oscillometric readings.
144
+
145
+ ## Citation
146
+
147
+ If you use this package, please cite the original paper:
148
+
149
+ > Grams ME, Brunskill NJ, Ballew SH, et al. Development and Validation of Prediction
150
+ > Models of Adverse Kidney Outcomes in the Population With and Without Diabetes.
151
+ > *Diabetes Care*. 2022;45(9):2055-2063. doi:10.2337/dc22-0698
152
+
153
+ ## License
154
+
155
+ MIT
@@ -0,0 +1,12 @@
1
+ """egfr40: CKD-PC risk equation for a >=40% eGFR decline or kidney failure.
2
+
3
+ Implements Grams ME et al., Diabetes Care 2022;45(9):2055-2063
4
+ (doi:10.2337/dc22-0698), Supplemental Table S5.
5
+ """
6
+
7
+ from .egfr import ckd_epi_2021
8
+ from .risk import add_egfr40_risk_col, egfr40_risk
9
+
10
+ __version__ = "0.0.1a1"
11
+
12
+ __all__ = ["egfr40_risk", "add_egfr40_risk_col", "ckd_epi_2021", "__version__"]
@@ -0,0 +1,36 @@
1
+ import numpy as np
2
+
3
+
4
+ def ckd_epi_2021(scr, age, male):
5
+ """eGFR from serum creatinine, CKD-EPI 2021 (race-free) equation.
6
+
7
+ Inker LA et al. N Engl J Med 2021;385:1737-1749.
8
+
9
+ Parameters
10
+ ----------
11
+ scr : float or array serum creatinine, mg/dL
12
+ age : float or array years
13
+ male : int or array 1 = male, 0 = female
14
+
15
+ Returns
16
+ -------
17
+ eGFR in mL/min/1.73 m^2 (float or ndarray). NaN where inputs are missing.
18
+ """
19
+ scr = np.asarray(scr, dtype=float)
20
+ age = np.asarray(age, dtype=float)
21
+ male = np.asarray(male, dtype=float)
22
+
23
+ kappa = np.where(male == 1, 0.9, 0.7)
24
+ alpha = np.where(male == 1, -0.302, -0.241)
25
+ female_factor = np.where(male == 1, 1.0, 1.012)
26
+
27
+ ratio = scr / kappa
28
+ egfr = (
29
+ 142
30
+ * np.minimum(ratio, 1) ** alpha
31
+ * np.maximum(ratio, 1) ** -1.200
32
+ * 0.9938**age
33
+ * female_factor
34
+ )
35
+ egfr = np.where(np.isnan(male), np.nan, egfr)
36
+ return egfr.item() if egfr.ndim == 0 else egfr
@@ -0,0 +1,279 @@
1
+ import math
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+
6
+ # CKD-PC 40% eGFR decline risk equation (3-year probability)
7
+ # Grams ME et al. Diabetes Care 2022;45(9):2055-2063, Supplemental Table S5
8
+ # Strata keyed by (eGFR >= 60, diabetes)
9
+ _COEFS = {
10
+ (True, False): {
11
+ "const": -4.7045, "age": 0.3690, "male": -0.1433, "egfr": 0.0325,
12
+ "lnacr": 0.4190, "sbp": 0.3048, "bpmed": 0.2656, "sbp_bpmed": -0.1140,
13
+ "hf": 1.0534, "chd": 0.4102, "afib": 0.1140, "current_smoker": 0.3803,
14
+ "former_smoker": 0.1862, "bmi": 0.0425,
15
+ },
16
+ (True, True): {
17
+ "const": -4.2125, "age": 0.1465, "male": -0.2481, "egfr": -0.0562,
18
+ "lnacr": 0.4098, "sbp": 0.1518, "bpmed": 0.2846, "sbp_bpmed": -0.0321,
19
+ "hf": 0.9234, "chd": 0.2168, "afib": 0.3087, "current_smoker": 0.1186,
20
+ "former_smoker": 0.0777, "bmi": 0.0308,
21
+ "hba1c": 0.0987, "oral_dm": -0.0638, "insulin": 0.2359,
22
+ },
23
+ (False, False): {
24
+ "const": -3.4540, "age": -0.0796, "male": 0.0626, "egfr": -0.1672,
25
+ "lnacr": 0.3915, "sbp": 0.2373, "bpmed": 0.0790, "sbp_bpmed": -0.0214,
26
+ "hf": 0.4898, "chd": 0.2343, "afib": 0.0739, "current_smoker": 0.2903,
27
+ "former_smoker": 0.1725, "bmi": -0.0231,
28
+ },
29
+ (False, True): {
30
+ "const": -3.2874, "age": -0.1725, "male": -0.1452, "egfr": -0.0769,
31
+ "lnacr": 0.4658, "sbp": 0.2068, "bpmed": 0.1665, "sbp_bpmed": -0.0549,
32
+ "hf": 0.4216, "chd": 0.2173, "afib": 0.0456, "current_smoker": -0.0338,
33
+ "former_smoker": 0.1386, "bmi": 0.0253,
34
+ "hba1c": -0.0031, "oral_dm": -0.1232, "insulin": 0.0980,
35
+ },
36
+ }
37
+
38
+
39
+ def _stratum_risk(high_egfr, dm, x):
40
+ b = _COEFS[(high_egfr, dm)]
41
+ egfr_center = 85 if high_egfr else 45
42
+ sbp_c = (x["sbp"] - 130) / 20
43
+
44
+ lp = (
45
+ b["const"]
46
+ + b["age"] * (x["age"] - 60) / 10
47
+ + b["male"] * (x["male"] - 0.5)
48
+ + b["egfr"] * (x["egfr"] - egfr_center) / 5
49
+ + b["lnacr"] * math.log(x["uacr"] / 10)
50
+ + b["sbp"] * sbp_c
51
+ + b["bpmed"] * x["bp_meds"]
52
+ + b["sbp_bpmed"] * sbp_c * x["bp_meds"]
53
+ + b["hf"] * (x["hf"] - 0.05)
54
+ + b["chd"] * (x["chd"] - 0.15)
55
+ + b["afib"] * x["afib"]
56
+ + b["current_smoker"] * (x["smoking"] == "current")
57
+ + b["former_smoker"] * (x["smoking"] == "former")
58
+ + b["bmi"] * (x["bmi"] - 30) / 5
59
+ )
60
+ if dm:
61
+ lp += (
62
+ b["hba1c"] * (x["hba1c"] - 7)
63
+ + b["oral_dm"] * x["oral_dm"]
64
+ + b["insulin"] * x["insulin"]
65
+ )
66
+ return 1 / (1 + math.exp(-lp))
67
+
68
+
69
+ def egfr40_risk(
70
+ age,
71
+ male,
72
+ egfr,
73
+ uacr,
74
+ sbp,
75
+ bp_meds,
76
+ hf,
77
+ chd,
78
+ afib,
79
+ smoking,
80
+ bmi,
81
+ dm,
82
+ hba1c=None,
83
+ oral_dm=0,
84
+ insulin=0,
85
+ ):
86
+ """3-year probability of >=40% eGFR decline or kidney failure.
87
+
88
+ Parameters
89
+ ----------
90
+ age : float years
91
+ male : int 1 = male, 0 = female
92
+ egfr : float CKD-EPI 2021, mL/min/1.73 m^2
93
+ uacr : float urine albumin-to-creatinine ratio, mg/g
94
+ sbp : float systolic blood pressure, mmHg
95
+ bp_meds : int antihypertensive medication use (1/0)
96
+ hf, chd, afib : int history of heart failure, CHD, atrial fibrillation (1/0)
97
+ smoking : str 'never', 'former', or 'current'
98
+ bmi : float kg/m^2
99
+ dm : bool diabetes (required: selects the diabetes or no-diabetes model)
100
+ hba1c : float %, required when dm is True
101
+ oral_dm : int oral diabetes medication (1/0)
102
+ insulin : int insulin use (1/0)
103
+
104
+ Returns
105
+ -------
106
+ float in [0, 1]. At eGFR == 60 the two strata are averaged, as on
107
+ ckdpcrisk.org.
108
+ """
109
+ if dm and hba1c is None:
110
+ raise ValueError("hba1c is required when dm=True")
111
+ if uacr <= 0:
112
+ raise ValueError("uacr must be > 0")
113
+ if smoking not in ("never", "former", "current"):
114
+ raise ValueError("smoking must be 'never', 'former', or 'current'")
115
+
116
+ x = dict(
117
+ age=age, male=male, egfr=egfr, uacr=uacr, sbp=sbp, bp_meds=bp_meds,
118
+ hf=hf, chd=chd, afib=afib, smoking=smoking, bmi=bmi,
119
+ hba1c=hba1c, oral_dm=oral_dm, insulin=insulin,
120
+ )
121
+
122
+ if egfr == 60:
123
+ return (_stratum_risk(True, dm, x) + _stratum_risk(False, dm, x)) / 2
124
+ return _stratum_risk(egfr > 60, dm, x)
125
+
126
+
127
+ def _to_binary(s, name):
128
+ """Coerce a yes/no column to 1.0/0.0 (NaN stays NaN)."""
129
+ if s.dtype == object or pd.api.types.is_string_dtype(s):
130
+ m = s.astype(str).str.strip().str.lower()
131
+ out = pd.Series(np.nan, index=s.index)
132
+ out[m.isin(["1", "yes", "y", "true", "t"])] = 1.0
133
+ out[m.isin(["0", "no", "n", "false", "f"])] = 0.0
134
+ bad = s.notna() & out.isna()
135
+ if bad.any():
136
+ raise ValueError(f"Unrecognized values in '{name}': {s[bad].unique()[:5]}")
137
+ return out
138
+ return s.astype(float)
139
+
140
+
141
+ def _to_male(s):
142
+ """Coerce a sex column (text or 1/0) to 1.0 = male, 0.0 = female."""
143
+ if s.dtype == object or pd.api.types.is_string_dtype(s):
144
+ m = s.astype(str).str.strip().str.lower()
145
+ out = pd.Series(np.nan, index=s.index)
146
+ out[m.isin(["male", "m", "1"])] = 1.0
147
+ out[m.isin(["female", "f", "0"])] = 0.0
148
+ return out
149
+ return s.astype(float)
150
+
151
+
152
+ def _lp_vectorized(high_egfr, dm, d):
153
+ """Linear predictor for one stratum, applied to every row of d."""
154
+ b = _COEFS[(high_egfr, dm)]
155
+ egfr_center = 85 if high_egfr else 45
156
+ sbp_c = (d["sbp"] - 130) / 20
157
+
158
+ lp = (
159
+ b["const"]
160
+ + b["age"] * (d["age"] - 60) / 10
161
+ + b["male"] * (d["male"] - 0.5)
162
+ + b["egfr"] * (d["egfr"] - egfr_center) / 5
163
+ + b["lnacr"] * np.log(d["uacr"] / 10)
164
+ + b["sbp"] * sbp_c
165
+ + b["bpmed"] * d["bp_meds"]
166
+ + b["sbp_bpmed"] * sbp_c * d["bp_meds"]
167
+ + b["hf"] * (d["hf"] - 0.05)
168
+ + b["chd"] * (d["chd"] - 0.15)
169
+ + b["afib"] * d["afib"]
170
+ + b["current_smoker"] * d["current"]
171
+ + b["former_smoker"] * d["former"]
172
+ + b["bmi"] * (d["bmi"] - 30) / 5
173
+ )
174
+ if dm:
175
+ lp = (
176
+ lp
177
+ + b["hba1c"] * (d["hba1c"] - 7)
178
+ + b["oral_dm"] * d["oral_dm"]
179
+ + b["insulin"] * d["insulin"]
180
+ )
181
+ return lp
182
+
183
+
184
+ def add_egfr40_risk_col(
185
+ df,
186
+ age_col="age",
187
+ sex_col="sex",
188
+ egfr_col="eGFR",
189
+ uacr_col="uACR",
190
+ sbp_col="sbp",
191
+ bp_meds_col="bp_meds",
192
+ hf_col="hf",
193
+ chd_col="chd",
194
+ afib_col="afib",
195
+ smoking_col="smoking",
196
+ bmi_col="bmi",
197
+ dm_col="dm",
198
+ hba1c_col="hba1c",
199
+ oral_dm_col="oral_dm",
200
+ insulin_col="insulin",
201
+ risk_col="egfr40_3year",
202
+ copy=True,
203
+ ):
204
+ """Add the CKD-PC 3-year >=40% eGFR decline risk to every row of a DataFrame.
205
+
206
+ Each row is scored with its own stratum (eGFR >= 60 or < 60, with or
207
+ without diabetes). Rows at exactly eGFR 60 get the average of the two
208
+ eGFR strata, as on ckdpcrisk.org.
209
+
210
+ Column expectations
211
+ -------------------
212
+ sex : 'male'/'female' (or 'm'/'f'), or 1 = male / 0 = female
213
+ yes/no : bp_meds, hf, chd, afib, dm, oral_dm, insulin as 1/0 or yes/no
214
+ smoking : 'never', 'former', or 'current'
215
+ uACR : mg/g; eGFR: CKD-EPI 2021; HbA1c: %
216
+
217
+ Missing values: a row with any required input missing gets NaN.
218
+ HbA1c, oral_dm and insulin are only required for rows with dm == 1.
219
+ Missing oral_dm / insulin in diabetic rows are treated as NaN (not 0).
220
+
221
+ Returns
222
+ -------
223
+ DataFrame with a new column `risk_col` (probability in [0, 1]).
224
+ """
225
+ out = df.copy() if copy else df
226
+
227
+ smk = out[smoking_col].astype(str).str.strip().str.lower()
228
+ smk = smk.where(out[smoking_col].notna())
229
+ bad_smk = smk.notna() & ~smk.isin(["never", "former", "current"])
230
+ if bad_smk.any():
231
+ raise ValueError(
232
+ f"Unrecognized values in '{smoking_col}': {out.loc[bad_smk, smoking_col].unique()[:5]}"
233
+ )
234
+
235
+ d = pd.DataFrame(
236
+ {
237
+ "age": out[age_col].astype(float),
238
+ "male": _to_male(out[sex_col]),
239
+ "egfr": out[egfr_col].astype(float),
240
+ "uacr": out[uacr_col].astype(float),
241
+ "sbp": out[sbp_col].astype(float),
242
+ "bp_meds": _to_binary(out[bp_meds_col], bp_meds_col),
243
+ "hf": _to_binary(out[hf_col], hf_col),
244
+ "chd": _to_binary(out[chd_col], chd_col),
245
+ "afib": _to_binary(out[afib_col], afib_col),
246
+ "current": (smk == "current").astype(float).where(smk.notna()),
247
+ "former": (smk == "former").astype(float).where(smk.notna()),
248
+ "bmi": out[bmi_col].astype(float),
249
+ "dm": _to_binary(out[dm_col], dm_col),
250
+ },
251
+ index=out.index,
252
+ )
253
+ for col, src in (("hba1c", hba1c_col), ("oral_dm", oral_dm_col), ("insulin", insulin_col)):
254
+ if src in out.columns:
255
+ d[col] = out[src].astype(float) if col == "hba1c" else _to_binary(out[src], src)
256
+ else:
257
+ d[col] = np.nan
258
+
259
+ # uACR must be positive for the log
260
+ d.loc[d["uacr"] <= 0, "uacr"] = np.nan
261
+
262
+ def prob(lp):
263
+ return 1 / (1 + np.exp(-lp))
264
+
265
+ risk = pd.Series(np.nan, index=out.index)
266
+ for dm in (False, True):
267
+ mask = d["dm"] == (1.0 if dm else 0.0)
268
+ if not mask.any():
269
+ continue
270
+ sub = d[mask]
271
+ p_hi = prob(_lp_vectorized(True, dm, sub))
272
+ p_lo = prob(_lp_vectorized(False, dm, sub))
273
+ r = np.where(sub["egfr"] > 60, p_hi, p_lo)
274
+ r = np.where(sub["egfr"] == 60, (p_hi + p_lo) / 2, r)
275
+ r = np.where(sub["egfr"].isna(), np.nan, r)
276
+ risk[mask] = r
277
+
278
+ out[risk_col] = risk
279
+ return out
@@ -0,0 +1,183 @@
1
+ Metadata-Version: 2.4
2
+ Name: egfr40
3
+ Version: 0.0.1a1
4
+ Summary: CKD-PC risk equation for a >=40% eGFR decline or kidney failure over 2-3 years (Grams et al., Diabetes Care 2022)
5
+ Author-email: Leonid Shpaner <lshpaner@ucla.edu>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/lshpaner/egfr40
8
+ Project-URL: Issues, https://github.com/lshpaner/egfr40/issues
9
+ Keywords: nephrology,ckd,egfr,risk prediction,ckd-pc,kidney
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: numpy>=1.20
18
+ Requires-Dist: pandas>=1.3
19
+ Provides-Extra: dev
20
+ Requires-Dist: pytest>=7; extra == "dev"
21
+ Requires-Dist: build; extra == "dev"
22
+ Requires-Dist: twine; extra == "dev"
23
+ Provides-Extra: nhanes
24
+ Requires-Dist: requests; extra == "nhanes"
25
+ Requires-Dist: typer; extra == "nhanes"
26
+ Requires-Dist: pyarrow; extra == "nhanes"
27
+ Dynamic: license-file
28
+
29
+ # egfr40
30
+
31
+ Python implementation of the CKD Prognosis Consortium (CKD-PC) risk equation for the
32
+ **3-year probability of a ≥40% decline in eGFR or kidney failure**, from Grams et al.,
33
+ *Diabetes Care* 2022. This is the equation behind the
34
+ [ckdpcrisk.org/gfrdecline40](https://ckdpcrisk.org/gfrdecline40/) calculator.
35
+
36
+ > **Not affiliated with the CKD Prognosis Consortium.** This is an independent
37
+ > implementation of a published equation, intended for research use. It is not a
38
+ > medical device and should not be used to make clinical decisions.
39
+
40
+ ## Installation
41
+
42
+ ```bash
43
+ pip install egfr40
44
+ ```
45
+
46
+ Development install:
47
+
48
+ ```bash
49
+ git clone https://github.com/lshpaner/egfr40.git
50
+ cd egfr40
51
+ pip install -e ".[dev]"
52
+ ```
53
+
54
+ ## Usage
55
+
56
+ ### One patient
57
+
58
+ ```python
59
+ from egfr40 import egfr40_risk
60
+
61
+ egfr40_risk(
62
+ age=70, male=1, egfr=40, uacr=150, sbp=140, bp_meds=1,
63
+ hf=0, chd=1, afib=1, smoking="former", bmi=28,
64
+ dm=True, hba1c=7, oral_dm=0, insulin=0,
65
+ )
66
+ # 0.166
67
+ ```
68
+
69
+ ### eGFR
70
+
71
+ ```python
72
+ from egfr40 import ckd_epi_2021
73
+
74
+ ckd_epi_2021(scr=1.2, age=70, male=1) # mL/min/1.73 m^2, race-free 2021 equation
75
+ ```
76
+
77
+ ### A whole cohort
78
+
79
+ ```python
80
+ from egfr40 import add_egfr40_risk_col
81
+
82
+ df = add_egfr40_risk_col(
83
+ df,
84
+ age_col="age", sex_col="sex", egfr_col="eGFR", uacr_col="uACR",
85
+ sbp_col="sbp", bp_meds_col="bp_meds",
86
+ hf_col="hf", chd_col="chd", afib_col="afib",
87
+ smoking_col="smoking", bmi_col="bmi",
88
+ dm_col="dm", hba1c_col="hba1c", oral_dm_col="oral_dm", insulin_col="insulin",
89
+ )
90
+ df["egfr40_3year"]
91
+ ```
92
+
93
+ Each row is scored with its own stratum. Rows missing any required input get `NaN`.
94
+
95
+ ## Inputs
96
+
97
+ | Input | Units / values |
98
+ |---|---|
99
+ | Age | years |
100
+ | Sex | `male`/`female`, `m`/`f`, or 1 = male / 0 = female |
101
+ | eGFR | mL/min/1.73 m², CKD-EPI 2021 creatinine equation |
102
+ | uACR | mg/g |
103
+ | Systolic BP | mmHg |
104
+ | Antihypertensive medication | 1/0 or yes/no |
105
+ | History of heart failure, CHD, atrial fibrillation | 1/0 or yes/no |
106
+ | Smoking | `never`, `former`, `current` |
107
+ | BMI | kg/m² |
108
+ | Diabetes | 1/0 or yes/no (**required**: selects the model) |
109
+ | HbA1c | % (diabetes only) |
110
+ | Oral diabetes medication, insulin | 1/0 or yes/no (diabetes only) |
111
+
112
+ ## The model
113
+
114
+ Four logistic models, stratified by diabetes status and eGFR (≥60 or <60):
115
+
116
+ $$
117
+ p = \frac{1}{1 + e^{-(\beta_0 + \sum_i \beta_i x_i)}}
118
+ $$
119
+
120
+ Coefficients, intercepts, and the centering and scaling of each predictor are taken from
121
+ **Supplemental Table S5** of the paper. All 52 coefficients match the model 2 odds
122
+ ratios reported in Tables 2 and 3, and the package reproduces the online calculator.
123
+
124
+ **eGFR = 60 boundary.** The stratified models do not meet at eGFR 60. Following the
125
+ CKD-PC website, risk at exactly eGFR 60 is the average of the two strata.
126
+
127
+ **Notes on the source**
128
+
129
+ - The calculator also asks for race and hypertension status. Neither appears in the
130
+ published Table S5 model, so neither is an input here.
131
+ - The hypertension-based alternative models (Supplemental Tables S6 and S7) are published
132
+ without intercepts and cannot be implemented.
133
+ - HbA1c is labeled "mmol" in the paper's tables. Its centering at 7 in Table S5 shows the
134
+ unit is percent.
135
+
136
+ ## Testing
137
+
138
+ ```bash
139
+ make test
140
+ ```
141
+
142
+ The tests check the coefficients against the paper's odds ratios, a case verified
143
+ against the online calculator, the eGFR 60 averaging, and agreement between the
144
+ single-patient and DataFrame functions.
145
+
146
+ ## NHANES example
147
+
148
+ `data_gen.py` downloads the raw NHANES 2017–March 2020 pre-pandemic files needed to apply
149
+ the equation to a nationally representative sample:
150
+
151
+ ```bash
152
+ pip install -e ".[nhanes]"
153
+ make data_gen
154
+ ```
155
+
156
+ Files are saved to `data/raw/` (gitignored). Then build the analysis file:
157
+
158
+ ```bash
159
+ make preprocess
160
+ ```
161
+
162
+ This merges the files, computes CKD-EPI 2021 eGFR, recodes each predictor, and applies
163
+ the inclusion criteria (age 20-80, not pregnant, eGFR >= 15, complete inputs). Output:
164
+ `data/processed/nhanes_egfr40.parquet`.
165
+
166
+ NHANES-specific choices:
167
+
168
+ - Atrial fibrillation is not collected, so it is set to 0.
169
+ - CHD includes self-reported coronary heart disease or heart attack.
170
+ - Diabetes is self-reported diagnosis, diabetes medication, or HbA1c >= 6.5%.
171
+ - SBP is the mean of the available oscillometric readings.
172
+
173
+ ## Citation
174
+
175
+ If you use this package, please cite the original paper:
176
+
177
+ > Grams ME, Brunskill NJ, Ballew SH, et al. Development and Validation of Prediction
178
+ > Models of Adverse Kidney Outcomes in the Population With and Without Diabetes.
179
+ > *Diabetes Care*. 2022;45(9):2055-2063. doi:10.2337/dc22-0698
180
+
181
+ ## License
182
+
183
+ MIT
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ egfr40/__init__.py
5
+ egfr40/egfr.py
6
+ egfr40/risk.py
7
+ egfr40.egg-info/PKG-INFO
8
+ egfr40.egg-info/SOURCES.txt
9
+ egfr40.egg-info/dependency_links.txt
10
+ egfr40.egg-info/requires.txt
11
+ egfr40.egg-info/top_level.txt
12
+ tests/test_egfr.py
13
+ tests/test_risk.py
@@ -0,0 +1,12 @@
1
+ numpy>=1.20
2
+ pandas>=1.3
3
+
4
+ [dev]
5
+ pytest>=7
6
+ build
7
+ twine
8
+
9
+ [nhanes]
10
+ requests
11
+ typer
12
+ pyarrow
@@ -0,0 +1 @@
1
+ egfr40
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "egfr40"
7
+ version = "0.0.1a1"
8
+ description = "CKD-PC risk equation for a >=40% eGFR decline or kidney failure over 2-3 years (Grams et al., Diabetes Care 2022)"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "Leonid Shpaner", email = "lshpaner@ucla.edu" }]
13
+ requires-python = ">=3.9"
14
+ dependencies = ["numpy>=1.20", "pandas>=1.3"]
15
+ keywords = ["nephrology", "ckd", "egfr", "risk prediction", "ckd-pc", "kidney"]
16
+ classifiers = [
17
+ "Programming Language :: Python :: 3",
18
+ "Operating System :: OS Independent",
19
+ "Intended Audience :: Science/Research",
20
+ "Topic :: Scientific/Engineering :: Medical Science Apps.",
21
+ ]
22
+
23
+ [project.optional-dependencies]
24
+ dev = ["pytest>=7", "build", "twine"]
25
+ nhanes = ["requests", "typer", "pyarrow"]
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/lshpaner/egfr40"
29
+ Issues = "https://github.com/lshpaner/egfr40/issues"
30
+
31
+ [tool.setuptools]
32
+ packages = ["egfr40"]
33
+
34
+ [tool.pytest.ini_options]
35
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,31 @@
1
+ import math
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ from egfr40 import ckd_epi_2021
7
+
8
+
9
+ def reference(scr, age, male):
10
+ k, a = (0.9, -0.302) if male else (0.7, -0.241)
11
+ f = 1.0 if male else 1.012
12
+ return 142 * min(scr / k, 1) ** a * max(scr / k, 1) ** -1.2 * 0.9938**age * f
13
+
14
+
15
+ @pytest.mark.parametrize("scr,age,male", [
16
+ (0.7, 60, 0), (1.0, 50, 1), (0.5, 30, 0), (2.5, 75, 1), (0.9, 45, 1), (1.4, 80, 0),
17
+ ])
18
+ def test_scalar_matches_reference(scr, age, male):
19
+ assert ckd_epi_2021(scr, age, male) == pytest.approx(reference(scr, age, male))
20
+
21
+
22
+ def test_at_kappa_only_age_and_sex_matter():
23
+ # Scr equal to kappa: both min/max terms are 1
24
+ assert ckd_epi_2021(0.9, 40, 1) == pytest.approx(142 * 0.9938**40)
25
+ assert ckd_epi_2021(0.7, 40, 0) == pytest.approx(142 * 0.9938**40 * 1.012)
26
+
27
+
28
+ def test_vectorized_and_missing():
29
+ out = ckd_epi_2021([1.0, np.nan, 1.0], [50, 50, 50], [1, 1, np.nan])
30
+ assert out[0] == pytest.approx(reference(1.0, 50, 1))
31
+ assert math.isnan(out[1]) and math.isnan(out[2])
@@ -0,0 +1,120 @@
1
+ import math
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+ import pytest
6
+
7
+ from egfr40 import add_egfr40_risk_col, egfr40_risk
8
+ from egfr40.risk import _COEFS
9
+
10
+ # Model 2 odds ratios from Tables 2 and 3 of Grams et al. 2022 (rounded to 2 dp)
11
+ KEYS = ["age", "male", "egfr", "lnacr", "sbp", "bpmed", "sbp_bpmed", "hf", "chd",
12
+ "afib", "current_smoker", "former_smoker", "bmi"]
13
+ PAPER_OR = {
14
+ (True, False): [1.45, 0.87, 1.03, 1.52, 1.36, 1.30, 0.89, 2.87, 1.51, 1.12, 1.46, 1.20, 1.04],
15
+ (True, True): [1.16, 0.78, 0.95, 1.51, 1.16, 1.33, 0.97, 2.52, 1.24, 1.36, 1.13, 1.08, 1.03],
16
+ (False, False): [0.92, 1.06, 0.85, 1.48, 1.27, 1.08, 0.98, 1.63, 1.26, 1.08, 1.34, 1.19, 0.98],
17
+ (False, True): [0.84, 0.86, 0.93, 1.59, 1.23, 1.18, 0.95, 1.52, 1.24, 1.05, 0.97, 1.15, 1.03],
18
+ }
19
+
20
+ SITE_CASE = dict(age=70, male=1, egfr=40, uacr=150, sbp=140, bp_meds=1, hf=0, chd=1,
21
+ afib=1, smoking="former", bmi=28, dm=True, hba1c=7, oral_dm=0, insulin=0)
22
+
23
+
24
+ @pytest.mark.parametrize("stratum", list(PAPER_OR))
25
+ def test_coefficients_match_paper_odds_ratios(stratum):
26
+ for key, odds in zip(KEYS, PAPER_OR[stratum]):
27
+ assert round(math.exp(_COEFS[stratum][key]), 2) == pytest.approx(odds, abs=0.011), key
28
+
29
+
30
+ def test_matches_ckdpcrisk_site():
31
+ # Verified against ckdpcrisk.org/gfrdecline40 on 2026-11-17: 16.6%
32
+ assert round(egfr40_risk(**SITE_CASE), 3) == 0.166
33
+
34
+
35
+ @pytest.mark.parametrize("case,expected", [
36
+ # Diabetes, eGFR >= 60, oral meds (verified on the site 2026-11-18: 3.2%)
37
+ (dict(age=60, male=1, egfr=80, uacr=30, sbp=140, bp_meds=1, hf=0, chd=0, afib=0,
38
+ smoking="current", bmi=30, dm=True, hba1c=8, oral_dm=1, insulin=0), 0.032),
39
+ # Diabetes, eGFR >= 60, insulin (verified on the site 2026-11-18: 12.1%)
40
+ (dict(age=45, male=0, egfr=100, uacr=300, sbp=150, bp_meds=1, hf=0, chd=0, afib=1,
41
+ smoking="never", bmi=35, dm=True, hba1c=9, oral_dm=0, insulin=1), 0.121),
42
+ ])
43
+ def test_matches_ckdpcrisk_site_dm_high_egfr(case, expected):
44
+ assert round(egfr40_risk(**case), 3) == expected
45
+
46
+
47
+ def test_dm_is_required():
48
+ kw = {k: v for k, v in SITE_CASE.items() if k not in ("dm", "hba1c", "oral_dm", "insulin")}
49
+ with pytest.raises(TypeError):
50
+ egfr40_risk(**kw)
51
+
52
+
53
+ def test_dm_requires_hba1c():
54
+ with pytest.raises(ValueError):
55
+ egfr40_risk(**{**SITE_CASE, "hba1c": None})
56
+
57
+
58
+ def test_egfr_60_averages_strata():
59
+ kw = {**SITE_CASE, "dm": False, "hba1c": None}
60
+ at_60 = egfr40_risk(**{**kw, "egfr": 60})
61
+ above = egfr40_risk(**{**kw, "egfr": 60.0000001})
62
+ below = egfr40_risk(**{**kw, "egfr": 59.9999999})
63
+ assert at_60 == pytest.approx((above + below) / 2, abs=1e-6)
64
+
65
+
66
+ def _synthetic_cohort(n=500, seed=0):
67
+ rng = np.random.default_rng(seed)
68
+ df = pd.DataFrame({
69
+ "age": rng.integers(20, 81, n),
70
+ "sex": rng.choice(["male", "female"], n),
71
+ "eGFR": rng.integers(15, 120, n).astype(float),
72
+ "uACR": np.round(np.exp(rng.normal(3, 1.5, n)), 1) + 0.1,
73
+ "sbp": rng.integers(100, 180, n),
74
+ "bp_meds": rng.integers(0, 2, n),
75
+ "hf": rng.integers(0, 2, n),
76
+ "chd": rng.integers(0, 2, n),
77
+ "afib": rng.integers(0, 2, n),
78
+ "smoking": rng.choice(["never", "former", "current"], n),
79
+ "bmi": rng.uniform(18, 45, n),
80
+ "dm": rng.integers(0, 2, n),
81
+ })
82
+ df["hba1c"] = np.where(df.dm == 1, rng.uniform(5.5, 11, n), np.nan)
83
+ df["oral_dm"] = np.where(df.dm == 1, rng.integers(0, 2, n), 0)
84
+ df["insulin"] = np.where(df.dm == 1, rng.integers(0, 2, n), 0)
85
+ df.loc[:4, "eGFR"] = 60
86
+ return df
87
+
88
+
89
+ def test_dataframe_matches_scalar():
90
+ df = _synthetic_cohort()
91
+ scored = add_egfr40_risk_col(df)
92
+ scalar = [
93
+ egfr40_risk(age=r.age, male=int(r.sex == "male"), egfr=r.eGFR, uacr=r.uACR,
94
+ sbp=r.sbp, bp_meds=r.bp_meds, hf=r.hf, chd=r.chd, afib=r.afib,
95
+ smoking=r.smoking, bmi=r.bmi, dm=bool(r.dm),
96
+ hba1c=r.hba1c if r.dm else None, oral_dm=r.oral_dm, insulin=r.insulin)
97
+ for r in df.itertuples()
98
+ ]
99
+ np.testing.assert_allclose(scored["egfr40_3year"], scalar, atol=1e-12)
100
+
101
+
102
+ def test_dataframe_missing_inputs_give_nan():
103
+ df = _synthetic_cohort(n=3)
104
+ df.loc[0, "sbp"] = np.nan
105
+ df.loc[1, ["dm", "hba1c"]] = [1, np.nan]
106
+ scored = add_egfr40_risk_col(df)
107
+ assert scored["egfr40_3year"].iloc[:2].isna().all()
108
+
109
+
110
+ def test_dataframe_rejects_bad_smoking():
111
+ df = _synthetic_cohort(n=3)
112
+ df.loc[0, "smoking"] = "sometimes"
113
+ with pytest.raises(ValueError):
114
+ add_egfr40_risk_col(df)
115
+
116
+
117
+ def test_dataframe_does_not_modify_input_by_default():
118
+ df = _synthetic_cohort(n=5)
119
+ add_egfr40_risk_col(df)
120
+ assert "egfr40_3year" not in df.columns