Skip to content

Add bounds checking for mathematical operations in SCORE2 #6

@fbraza

Description

@fbraza

Issue Description

The SCORE2 and SCORE2-Diabetes implementations contain complex nested logarithm calculations that could fail with edge cases.

Problem

  • SCORE2: Line 177 in vitals/score2/compute.py has nested logarithms: np.log(-np.log(1 - uncalibrated_risk))
  • SCORE2-Diabetes: Line 218 in vitals/score2_diabetes/compute.py has the same pattern
  • If uncalibrated_risk is very close to 1.0, this could cause numerical instability
  • SCORE2-Diabetes specific: eGFR logarithm calculation math.log(biomarkers.egfr) could fail for very low eGFR values
  • No bounds checking for extreme values in either module

Current Code Patterns

SCORE2:

calibrated_risk = float((1 - np.exp(-np.exp(scale1 + scale2 * np.log(-np.log(1 - uncalibrated_risk))))) * 100)

SCORE2-Diabetes:

# Line 144: eGFR transformation
cegfr: float = (math.log(biomarkers.egfr) - 4.5) / 0.15

# Line 218: Same nested logarithm issue
calibrated_risk = float((1 - np.exp(-np.exp(scale1 + scale2 * np.log(-np.log(1 - uncalibrated_risk))))) * 100)

Suggested Implementation

For both modules - Calibration calculation:

# Add bounds checking
if uncalibrated_risk >= 0.999:
    uncalibrated_risk = 0.999  # Cap at 99.9%
elif uncalibrated_risk <= 0.001:
    uncalibrated_risk = 0.001  # Floor at 0.1%

# Safe calculation with error handling
try:
    calibrated_risk = float((1 - np.exp(-np.exp(scale1 + scale2 * np.log(-np.log(1 - uncalibrated_risk))))) * 100)
except (ValueError, OverflowError) as e:
    raise ValueError(f"Numerical error in risk calculation: {e}")

For SCORE2-Diabetes - eGFR validation:

# Add eGFR bounds checking before logarithm
if biomarkers.egfr <= 0:
    raise ValueError(f"eGFR must be positive for logarithm calculation, got {biomarkers.egfr}")
if biomarkers.egfr < 5:  # Extremely low eGFR
    # Log warning or handle appropriately
    pass

cegfr: float = (math.log(biomarkers.egfr) - 4.5) / 0.15

Impact

  • Prevents runtime errors from mathematical domain issues
  • Improves robustness for edge cases in both SCORE2 modules
  • Better error messages for debugging
  • Specifically addresses eGFR edge cases in SCORE2-Diabetes

Related

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions