| import pandas as pd | |
| import numpy as np | |
| def calculate_sla_metrics( | |
| df: pd.DataFrame, | |
| kpi: str, | |
| rules_df: pd.DataFrame | None = None | |
| ) -> dict: | |
| """ | |
| Calculates simple metrics for the given KPI trace: | |
| - SLA value (if exists) | |
| - Median (recent window) | |
| Returns a dict with: 'sla': float|None, 'median': float|None | |
| """ | |
| res = {"sla": None, "median": None} | |
| if df is None or df.empty or kpi not in df.columns: | |
| return res | |
| # 1. Get SLA from rules | |
| if rules_df is not None and not rules_df.empty: | |
| # Assuming rules_df has 'KPI' and 'sla' columns | |
| # We also need to match RAT? usually passed or handled outside. | |
| # Here we do a simplistic lookup. | |
| try: | |
| row = rules_df[rules_df["KPI"] == kpi] | |
| if not row.empty: | |
| val = row.iloc[0].get("sla") | |
| res["sla"] = float(val) if pd.notna(val) else None | |
| except Exception: | |
| pass | |
| # 2. Calculate Median (entire passed df, usually it's the recent window) | |
| try: | |
| vals = pd.to_numeric(df[kpi], errors="coerce").dropna() | |
| if not vals.empty: | |
| res["median"] = float(vals.median()) | |
| except Exception: | |
| pass | |
| return res | |