This cookbook details how to deploy a localized, containerized pediatric allergy, clinical immunology, and inborn errors of immunity ($\text{IEI}$) decision-support engine for pediatric immunology clinics, newborn screening laboratories, and inpatient pediatric wards to ingest recurrent infection chronologies, dried blood spot T-cell receptor excision circle ($\text{TREC}$) copy numbers, quantitative serum immunoglobulins ($\text{IgG, IgA, IgM, IgE}$), and flow cytometric lymphocyte subsets, evaluate the Jeffrey Modell Foundation 10 Warning Signs ($\ge 2\text{ signs}$), triage Severe Combined Immunodeficiency ($\text{SCID}$) TREC Newborn Screening ($< 252\text{ copies/}\mu\text{L}$), compute Pediatric Age-Adjusted Immunoglobulin Z-Scores, classify Humoral, Cellular, Combined, and Phagocytic Inborn Errors of Immunity ($\text{XLA, CVID, SCID, CGD}$), guide Replacement Intravenous / Subcutaneous Immunoglobulin ($\text{IVIG / SCIG}$ $400 - 600\text{ mg/kg}$) pharmacokinetics, and enforce the Live Attenuated Vaccine Absolute Prohibition Sentinel according to Clinical Immunology Society ($\text{CIS}$), AAAAI, and ESID consensus guidelines without external cloud API reliance.
Primary Immunodeficiency Diseases ($\text{PIDD}$), newly classified as Inborn Errors of Immunity ($\text{IEI}$), encompass over 480 monogenic disorders of immune system development and function:
[Pediatric Telemetry: Modell 10 Signs, TREC Copies, Age-Adjusted Igs, Flow Cytometry]
β
βΌ
[Jeffrey Modell 10 Warning Signs Evaluator: >= 2 Signs Triggers Comprehensive Workup]
β
βΌ
[SCID TREC Newborn Screening Engine: TREC < 252 -> STAT CD3+ T-Cell Flow Cytometry]
β
βΌ
[Age-Adjusted Immunoglobulin Z-Score Calculator: IgG, IgA, IgM, IgE vs Age Norms]
β
βΌ
[Phenotype Classifier: SCID vs XLA vs CVID vs CGD vs Transient Hypogamma]
β
βΌ
[Live Vaccine Absolute Prohibition Sentinel + IVIG/SCIG 400-600mg/kg Titrator]
Install required scientific Python and clinical immunology modeling packages:
pip install numpy scipy pandas torch torchvision matplotlib
"""
Cookbook 335: Offline Pediatric Immunology Primary Immunodeficiency, TREC & IVIG Engine
OpenPHR Clinical AI Working Group (https://openphr.org)
"""
import math
import numpy as np
import pandas as pd
from typing import Dict, List, Tuple, Optional
from dataclasses import dataclass
@dataclass
class PediatricImmunoTelemetry:
patient_id: str
age_months: int = 14 # 14 months old
sex: str = "Male"
patient_weight_kg: float = 9.8 # kg
# Jeffrey Modell 10 Warning Signs Checklist
ear_infections_past_year: int = 5 # >= 4 is positive
serious_sinus_infections_past_year: int = 2 # >= 2 is positive
months_on_antibiotics_little_effect: int = 2 # >= 2 is positive
pneumonias_past_year: int = 2 # >= 2 is positive
failure_to_thrive_present: bool = True
recurrent_deep_abscesses: bool = False
persistent_thrush_after_age_1: bool = True # Positive
need_for_iv_antibiotics: bool = True
deep_seated_sepsis_meningitis: bool = False
family_history_of_pidd: bool = True # Positive (Maternal uncle died in infancy)
# Newborn Screening TREC Telemetry
trec_copies_per_microliter: float = 38.0 # copies/uL (< 252 = Positive / Abnormal SCID screen)
# Quantitative Serum Immunoglobulins Telemetry
serum_igg_mg_dl: float = 45.0 # mg/dL (Normal for 1-3y is 400-1000 mg/dL -> Profoundly Low)
serum_iga_mg_dl: float = 4.0 # mg/dL (Normal 20-100 mg/dL -> Low)
serum_igm_mg_dl: float = 8.0 # mg/dL (Normal 40-140 mg/dL -> Low)
serum_ige_iu_ml: float = 1.0 # IU/mL
# Flow Cytometry Lymphocyte Subsets Telemetry (Cells/uL)
absolute_cd3_t_cells_ul: float = 180.0 # Normal > 1200 (< 300 = SCID definition)
absolute_cd4_helper_ul: float = 110.0 # Normal > 700
absolute_cd8_cytotoxic_ul: float = 65.0
absolute_cd19_b_cells_ul: float = 12.0 # Normal 200-1000 (< 20 = Absent B-cells)
absolute_cd56_nk_cells_ul: float = 45.0
# Neutrophil Function
dhr_stimulation_index: float = 85.0 # Normal > 30 (> 10 rules out CGD)
@dataclass
class PIDDEvaluationReport:
patient_id: str
modell_warning_signs_count: int # 0 - 10
modell_screening_status: str # "π¨ POSITIVE PIDD SCREEN (7/10 Warning Signs Met)", "Negative"
trec_newborn_status: str # "POSITIVE SCID SCREEN (38 copies/uL < 252 cutoff)"
immunoglobulin_z_scores: Dict[str, float]
immunological_phenotype: str # "Severe Combined Immunodeficiency (SCID, T-B-NK- Phenotype)"
ivig_replacement_protocol: List[str]
safety_sentinels: List[str]
clinical_cis_aaaai_directive: str
class PediatricImmunodeficiencyDecisionEngine:
"""
Offline clinical engine for Jeffrey Modell 10 warning signs evaluation,
TREC newborn screening triage, age-adjusted immunoglobulin Z-score calculation,
and IVIG replacement titration with live-attenuated vaccine safety sentinels.
"""
# Age-specific Immunoglobulin Means and Standard Deviations (mg/dL)
# Format: (IgG_mean, IgG_sd, IgA_mean, IgA_sd, IgM_mean, IgM_sd)
IG_AGE_NORMS = {
"0-1m": (900.0, 200.0, 5.0, 3.0, 20.0, 10.0),
"1-3m": (550.0, 150.0, 15.0, 8.0, 40.0, 15.0),
"4-6m": (400.0, 120.0, 25.0, 12.0, 50.0, 20.0), # Physiological nadir
"7-12m": (550.0, 150.0, 40.0, 18.0, 65.0, 25.0),
"1-3y": (700.0, 180.0, 60.0, 25.0, 80.0, 30.0),
"4-6y": (850.0, 200.0, 90.0, 35.0, 90.0, 35.0),
"7-12y": (1000.0, 220.0, 140.0, 50.0, 100.0, 40.0),
">12y": (1150.0, 250.0, 200.0, 70.0, 110.0, 45.0)
}
def evaluate_modell_signs(self, d: PediatricImmunoTelemetry) -> Tuple[int, List[str]]:
count = 0
signs = []
if d.ear_infections_past_year >= 4:
count += 1
signs.append(f"β’ >= 4 Ear Infections in past year ({d.ear_infections_past_year} recorded)")
if d.serious_sinus_infections_past_year >= 2:
count += 1
signs.append(f"β’ >= 2 Serious Sinus Infections in past year ({d.serious_sinus_infections_past_year} recorded)")
if d.months_on_antibiotics_little_effect >= 2:
count += 1
signs.append(f"β’ >= 2 Months on antibiotics with little effect ({d.months_on_antibiotics_little_effect} months)")
if d.pneumonias_past_year >= 2:
count += 1
signs.append(f"β’ >= 2 Pneumonias in past year ({d.pneumonias_past_year} recorded)")
if d.failure_to_thrive_present:
count += 1
signs.append("β’ Failure to Thrive (FTT) / Poor growth velocity")
if d.recurrent_deep_abscesses:
count += 1
signs.append("β’ Recurrent deep skin or organ abscesses")
if d.persistent_thrush_after_age_1 and d.age_months >= 12:
count += 1
signs.append("β’ Persistent oral/cutaneous candidiasis after age 1 year")
if d.need_for_iv_antibiotics:
count += 1
signs.append("β’ Required intravenous antibiotics to clear infections")
if d.deep_seated_sepsis_meningitis:
count += 1
signs.append("β’ >= 2 Deep-seated severe infections (sepsis/meningitis)")
if d.family_history_of_pidd:
count += 1
signs.append("β’ Family history of Primary Immunodeficiency / unexplained early infant death")
return count, signs
def get_age_bracket(self, months: int) -> str:
if months <= 1: return "0-1m"
elif months <= 3: return "1-3m"
elif months <= 6: return "4-6m"
elif months <= 12: return "7-12m"
elif months <= 36: return "1-3y"
elif months <= 72: return "4-6y"
elif months <= 144: return "7-12y"
else: return ">12y"
def calculate_immunoglobulin_z_scores(self, d: PediatricImmunoTelemetry) -> Dict[str, float]:
bracket = self.get_age_bracket(d.age_months)
igg_m, igg_sd, iga_m, iga_sd, igm_m, igm_sd = self.IG_AGE_NORMS[bracket]
z_igg = round((d.serum_igg_mg_dl - igg_m) / igg_sd, 2)
z_iga = round((d.serum_iga_mg_dl - iga_m) / iga_sd, 2)
z_igm = round((d.serum_igm_mg_dl - igm_m) / igm_sd, 2)
return {"Z_IgG": z_igg, "Z_IgA": z_iga, "Z_IgM": z_igm}
def classify_immunodeficiency_phenotype(self, d: PediatricImmunoTelemetry, z_scores: Dict[str, float]) -> str:
# SCID: TREC < 252 + CD3+ T-cells < 300
is_scid = d.trec_copies_per_microliter < 252.0 and d.absolute_cd3_t_cells_ul < 300.0
is_xla = d.absolute_cd19_b_cells_ul < 20.0 and z_scores["Z_IgG"] < -2.5 and z_scores["Z_IgA"] < -2.0
is_cgd = d.dhr_stimulation_index < 10.0
is_cvid = z_scores["Z_IgG"] < -2.0 and (z_scores["Z_IgA"] < -2.0 or z_scores["Z_IgM"] < -2.0) and d.absolute_cd19_b_cells_ul >= 50.0
if is_scid:
sub = "T- B- NK-" if (d.absolute_cd19_b_cells_ul < 20 and d.absolute_cd56_nk_cells_ul < 100) else "T- B+ NK+"
return f"π¨ SEVERE COMBINED IMMUNODEFICIENCY (SCID) [{sub} Phenotype] β CD3+ T-cells {d.absolute_cd3_t_cells_ul:.0f}/uL (<300), TREC {d.trec_copies_per_microliter:.0f} copies/uL"
elif is_xla:
return f"X-LINKED AGAMMAGLOBULINEMIA (XLA / Bruton's) β Absent CD19+ B-cells ({d.absolute_cd19_b_cells_ul:.0f}/uL) and Pan-Hypogammaglobulinemia"
elif is_cgd:
return f"CHRONIC GRANULOMATOUS DISEASE (CGD) β Defective Neutrophil Oxidative Burst (DHR SI {d.dhr_stimulation_index:.1f} < 10)"
elif is_cvid:
return "COMMON VARIABLE IMMUNODEFICIENCY (CVID) β Significant Hypogammaglobulinemia with Preserved B-cells"
elif z_scores["Z_IgG"] < -2.0:
return "HYPOGAMMAGLOBULINEMIA (Unspecified / Transient Hypogammaglobulinemia of Infancy)"
else:
return "Normal Immunological Phenotype / Evaluation Pending"
def generate_management_plans(self, phenotype: str, d: PediatricImmunoTelemetry) -> Tuple[List[str], List[str]]:
ivig_plan = []
sentinels = []
is_severe = any(s in phenotype for s in ["SCID", "AGAMMAGLOBULINEMIA", "CVID", "HYPOGAMMAGLOBULINEMIA"])
# 1. Replacement Immunoglobulin Therapy
if is_severe:
dose_low_g = round((d.patient_weight_kg * 400.0) / 1000.0, 1)
dose_high_g = round((d.patient_weight_kg * 600.0) / 1000.0, 1)
ivig_plan.append(f"1. REPLACEMENT IVIG PROTOCOL: Administer Intravenous Immunoglobulin (IVIG) 400 - 600 mg/kg ({dose_low_g:.1f} - {dose_high_g:.1f} grams) IV every 3 to 4 weeks.")
ivig_plan.append(" β’ Subcutaneous Alternative (SCIG): 100 - 150 mg/kg/week SC via programmable pump.")
ivig_plan.append(" β’ Target Trough Serum IgG: Maintain trough IgG > 700 - 800 mg/dL checked immediately prior to next infusion.")
# 2. Safety Sentinel: Live Attenuated Vaccine Prohibition
sentinels.append("π¨ ABSOLUTE LIVE VACCINE PROHIBITION: Live attenuated vaccines (Rotavirus, MMR, Varicella, Yellow Fever, BCG, Live Flu) are STRICTLY CONTRAINDICATED in SCID, severe T-cell lymphopenia, and agammaglobulinemia. Administration leads to fatal disseminated vaccine-strain infection!")
# 3. Transfusion Safety Sentinel
if "SCID" in phenotype:
sentinels.append("IRRADIATED & CMV-SAFE BLOOD PRODUCTS: All cellular blood products (pRBC, platelets) must be IRRADIATED (to prevent fatal Transfusion-Associated Graft-versus-Host Disease [TA-GvHD]) and CMV-seronegative/leukoreduced.")
ivig_plan.append("2. STAT PNEUMOCYSTIS PROPHYLAXIS: Start Trimethoprim-Sulfamethoxazole (TMP-SMX 5 mg/kg/day TMP) divided BID 3 days per week to prevent Pneumocystis jirovecii pneumonia (PJP).")
ivig_plan.append("3. ALLOGENEIC HEMATOPOIETIC CELL TRANSPLANTATION (HCT): Emergency referral to pediatric bone marrow transplant center for curative HCT or gene therapy.")
return ivig_plan, sentinels
def evaluate_case(self, data: PediatricImmunoTelemetry) -> PIDDEvaluationReport:
sign_count, sign_list = self.evaluate_modell_signs(data)
screen_status = f"π¨ POSITIVE PIDD SCREEN ({sign_count}/10 Warning Signs Met)" if sign_count >= 2 else f"Negative PIDD Screen ({sign_count}/10 Warning Signs Met)"
trec_status = f"POSITIVE ABNORMAL SCID SCREEN ({data.trec_copies_per_microliter:.0f} copies/uL < 252 cutoff)" if data.trec_copies_per_microliter < 252.0 else f"Normal TREC Screen ({data.trec_copies_per_microliter:.0f} copies/uL)"
z_scores = self.calculate_immunoglobulin_z_scores(data)
phenotype = self.classify_immunodeficiency_phenotype(data, z_scores)
ivig_plan, sentinels = self.generate_management_plans(phenotype, data)
directives = []
directives.append(f"MODELL SCREEN: {screen_status}.")
directives.append(f"TREC: {trec_status}.")
directives.append(f"DIAGNOSIS: {phenotype}.")
directives.append("THERAPY: Replacement IVIG/SCIG, live vaccine strict prohibition, and HCT evaluation.")
return PIDDEvaluationReport(
patient_id=data.patient_id,
modell_warning_signs_count=sign_count,
modell_screening_status=screen_status,
trec_newborn_status=trec_status,
immunoglobulin_z_scores=z_scores,
immunological_phenotype=phenotype,
ivig_replacement_protocol=ivig_plan,
safety_sentinels=sentinels,
clinical_cis_aaaai_directive=" ".join(directives)
)
# Example Execution & Verification
if __name__ == "__main__":
engine = PediatricImmunodeficiencyDecisionEngine()
print("=" * 80)
print("OpenPHR Clinical Pediatric Immunology Primary Immunodeficiency & TREC Engine")
print("=" * 80)
# Test Case 1: 14-month-old male with recurrent pneumonias, FTT, persistent oral thrush, and positive family history.
# Jeffrey Modell: 7/10 Warning Signs Met (Positive PIDD Screen!).
# TREC: 38 copies/uL (< 252). Serum IgG: 45 mg/dL (Z-score -3.64), IgA 4 mg/dL, IgM 8 mg/dL.
# Flow Cytometry: CD3+ 180 cells/uL (< 300), CD19+ 12 cells/uL -> SCID (T- B- NK- Phenotype)!
# Triage: π¨ Live Vaccine Absolute Prohibition + IVIG 400-600 mg/kg + TMP-SMX PJP + Urgent HCT!
pidd1 = PediatricImmunoTelemetry(
patient_id="PEDS-IMM-6601",
age_months=14,
sex="Male",
patient_weight_kg=9.8,
ear_infections_past_year=5,
serious_sinus_infections_past_year=2,
months_on_antibiotics_little_effect=2,
pneumonias_past_year=2,
failure_to_thrive_present=True,
persistent_thrush_after_age_1=True,
need_for_iv_antibiotics=True,
family_history_of_pidd=True,
trec_copies_per_microliter=38.0,
serum_igg_mg_dl=45.0,
serum_iga_mg_dl=4.0,
serum_igm_mg_dl=8.0,
absolute_cd3_t_cells_ul=180.0,
absolute_cd4_helper_ul=110.0,
absolute_cd8_cytotoxic_ul=65.0,
absolute_cd19_b_cells_ul=12.0,
absolute_cd56_nk_cells_ul=45.0,
dhr_stimulation_index=85.0
)
rep1 = engine.evaluate_case(pidd1)
print(f"\n[Patient {rep1.patient_id} - Pediatric Immunological Assessment]")
print(f"Modell Warning Signs: {rep1.modell_warning_signs_count}/10 ({rep1.modell_screening_status})")
print(f"Newborn TREC Status: {rep1.trec_newborn_status}")
print(f"Age-Adjusted Ig Z-Scores: IgG Z={rep1.immunoglobulin_z_scores['Z_IgG']}, IgA Z={rep1.immunoglobulin_z_scores['Z_IgA']}, IgM Z={rep1.immunoglobulin_z_scores['Z_IgM']}")
print(f"\nImmunological Phenotype:\n {rep1.immunological_phenotype}")
print("\nReplacement Immunoglobulin Protocol:")
for iv in rep1.ivig_replacement_protocol:
print(f" {iv}")
if rep1.safety_sentinels:
print("\nImmunology Safety Sentinels:")
for s in rep1.safety_sentinels:
print(f" π¨ {s}")
print(f"\nCIS / AAAAI Consensus Directive:\n{rep1.clinical_cis_aaaai_directive}")