""" modules/circular_formulation_engine.py First-pass Circular Formulation Engine (CFE) for IntelliForm Enterprise. Treats end-of-life fate as a first-class optimization and reporting axis. """ from __future__ import annotations from dataclasses import dataclass, field from typing import Dict, List import pandas as pd @dataclass class FateComponentScores: biodegradation: float aquatic_safety: float atmospheric_safety: float leachate_safety: float @dataclass class CircularFormulationReport: blend: Dict[str, float] waste_score: float circular_grade: str fate_scores: FateComponentScores lifecycle_notes: List[str] = field(default_factory=list) high_risk_ingredients: List[str] = field(default_factory=list) recommended_actions: List[str] = field(default_factory=list) def _clamp(value: float, lower: float = 0.0, upper: float = 100.0) -> float: return max(lower, min(upper, value)) def _safe_numeric(row: pd.Series, key: str, default: float) -> float: try: value = row.get(key, default) if pd.isna(value): return float(default) return float(value) except Exception: return float(default) def _circular_grade(score: float) -> str: if score >= 85: return "A" if score >= 70: return "B" if score >= 55: return "C" if score >= 40: return "D" return "F" def run_circular_formulation_engine(blend: Dict[str, float], db: pd.DataFrame) -> CircularFormulationReport: if not blend: zero = FateComponentScores(0.0, 0.0, 0.0, 0.0) return CircularFormulationReport({}, 0.0, "F", zero) idx = db.set_index("Ingredient") if "Ingredient" in db.columns else db bio_sum = 0.0 aqua_sum = 0.0 atmos_sum = 0.0 leach_sum = 0.0 weighted_total = 0.0 lifecycle_notes: List[str] = [] high_risk: List[str] = [] actions: List[str] = [] for ingredient, pct in blend.items(): if ingredient not in idx.index: continue row = idx.loc[ingredient] weight = float(pct) / 100.0 weighted_total += weight biodeg = _safe_numeric(row, "Biodegradability", _safe_numeric(row, "Bio_based_pct", 50.0) * 0.9) ecotox_raw = _safe_numeric(row, "Ecotoxicity_Score", 6.0) carbon_raw = _safe_numeric(row, "CarbonFootprint_kgCO2eq", 2.5) renew_raw = _safe_numeric(row, "Renewability_Score", _safe_numeric(row, "Bio_based_pct", 50.0)) reach_flag = str(row.get("REACH_Flag", "Amber")) aquatic_safety = _clamp(ecotox_raw * 10.0) atmospheric_safety = _clamp((1.0 - min(carbon_raw, 5.0) / 5.0) * 100.0) leachate_safety = _clamp((renew_raw * 0.55) + (20.0 if reach_flag == "Green" else 0.0) + (5.0 if reach_flag == "Amber" else -10.0)) bio_sum += biodeg * weight aqua_sum += aquatic_safety * weight atmos_sum += atmospheric_safety * weight leach_sum += leachate_safety * weight if biodeg < 45 or aquatic_safety < 45 or leachate_safety < 40: high_risk.append(ingredient) if weighted_total <= 0: weighted_total = 1.0 fate = FateComponentScores( biodegradation=round(bio_sum / weighted_total, 1), aquatic_safety=round(aqua_sum / weighted_total, 1), atmospheric_safety=round(atmos_sum / weighted_total, 1), leachate_safety=round(leach_sum / weighted_total, 1), ) waste_score = round( (0.35 * fate.biodegradation) + (0.25 * fate.aquatic_safety) + (0.20 * fate.atmospheric_safety) + (0.20 * fate.leachate_safety), 1, ) if high_risk: lifecycle_notes.append( f"High-risk end-of-life contributors detected: {', '.join(high_risk[:5])}" ) actions.append("Substitute or lower the share of ingredients with weak biodegradation or leachate safety scores.") else: lifecycle_notes.append("No obvious high-risk end-of-life ingredients were detected in the current blend.") if fate.atmospheric_safety < 55: actions.append("Reduce carbon-intense or volatile components to improve atmospheric and lifecycle performance.") if fate.aquatic_safety < 60: actions.append("Prioritize ingredients with better aquatic safety profiles before pilot validation.") if not actions: actions.append("Current blend is a strong candidate for Circular Formulation Engine advancement and passport generation.") lifecycle_notes.append( "Waste Score combines biodegradation, aquatic safety, atmospheric safety, and leachate safety into a single circularity signal." ) return CircularFormulationReport( blend=blend, waste_score=waste_score, circular_grade=_circular_grade(waste_score), fate_scores=fate, lifecycle_notes=lifecycle_notes, high_risk_ingredients=high_risk, recommended_actions=actions, )