-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfix_lifelines_import.py
More file actions
79 lines (63 loc) · 2.84 KB
/
fix_lifelines_import.py
File metadata and controls
79 lines (63 loc) · 2.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env python
"""
Helper script to fix the "cannot import name 'trapz' from 'scipy.integrate'" error in lifelines.
This script monkey-patches the lifelines package to use scipy's trapezoid function instead of trapz,
which has been moved in newer scipy versions.
"""
import inspect
import sys
import warnings
def apply_lifelines_patch():
"""
Apply a monkey patch to lifelines to fix the scipy.integrate.trapz import error.
"""
try:
# Try to import lifelines using find_spec
import importlib.util
lifelines_spec = importlib.util.find_spec("lifelines")
if lifelines_spec is None:
raise ImportError("lifelines package not found")
from scipy import integrate # Need to check if trapz exists
# Check if trapz is directly available in scipy.integrate
if not hasattr(integrate, "trapz"):
print(
"Applying patch for lifelines: scipy.integrate.trapz is not available"
)
# Import trapezoid function from scipy
from scipy import trapezoid
# Monkey patch the trapz function in lifelines modules that use it
# Get the path to lifelines fitters for reference (not used but kept for debugging)
# fitters_init_path = Path(inspect.getfile(lifelines.fitters))
# List of lifelines modules that might use trapz
modules_to_patch = [
"lifelines.fitters",
"lifelines.fitters.kaplan_meier_fitter",
"lifelines.fitters.nelson_aalen_fitter",
"lifelines.utils",
]
for module_name in modules_to_patch:
try:
module = importlib.import_module(module_name)
if hasattr(module, "trapz"):
# Module already has trapz defined, no need to patch
continue
# Add trapezoid function as trapz
module.trapz = trapezoid
# If the module imports trapz directly
module_code = inspect.getsource(module)
if "from scipy.integrate import trapz" in module_code:
print(f"Patched {module_name}")
except (ImportError, AttributeError) as e:
print(f"Could not patch {module_name}: {e}")
# Specifically patch scipy.integrate
if not hasattr(integrate, "trapz"):
integrate.trapz = trapezoid
print("Patched scipy.integrate.trapz")
print("Lifelines patch applied successfully")
return True
except ImportError as e:
warnings.warn(f"Could not patch lifelines: {e}", stacklevel=2)
return False
if __name__ == "__main__":
success = apply_lifelines_patch()
sys.exit(0 if success else 1)