""" analytics.py Core data layer for the Plant Operations Voice Assistant. Responsibilities ----------------- 1. Ingest an uploaded operational time-series file (xlsx/csv). 2. Build statistical profiles of every sensor/process variable. 3. Detect fault episodes (contiguous abnormal periods) and characterise them. 4. Produce a fast, deterministic answer for common numeric questions (so the system never has to "guess" at numbers). 5. Produce a set of plain-text "documents" describing the data, which are later embedded and stored in the vector index for retrieval-augmented answers to open-ended questions. This module has NO dependency on any AI model. It is pure pandas/numpy, which keeps the numeric answers 100% accurate and the rest of the system testable in isolation. """ from __future__ import annotations import re import pandas as pd import numpy as np # Human-friendly synonyms -> actual column names. Extend as needed. COLUMN_ALIASES = { "temperature": "reactor_temp", "temp": "reactor_temp", "reactor temp": "reactor_temp", "pressure": "reactor_pressure", "feed": "feed_flow_rate", "feed flow": "feed_flow_rate", "feed rate": "feed_flow_rate", "coolant": "coolant_flow_rate", "coolant flow": "coolant_flow_rate", "agitator": "agitator_speed_rpm", "agitator speed": "agitator_speed_rpm", "rpm": "agitator_speed_rpm", "reaction rate": "reaction_rate", "conversion": "conversion_rate", "selectivity": "selectivity", "yield": "yield_pct", "vibration": "vibration_rms", "current": "motor_current", "motor current": "motor_current", "power": "power_consumption_kw", "power consumption": "power_consumption_kw", "efficiency loss": "efficiency_loss_pct", "efficiency": "efficiency_loss_pct", "ambient": "ambient_temp_effect", } UNITS = { "reactor_temp": "°C", "reactor_pressure": "bar", "feed_flow_rate": "kg/min", "coolant_flow_rate": "kg/min", "agitator_speed_rpm": "rpm", "reaction_rate": "mol/L/min", "conversion_rate": "%", "selectivity": "%", "yield_pct": "%", "vibration_rms": "mm/s", "motor_current": "A", "power_consumption_kw": "kW", "efficiency_loss_pct": "%", "ambient_temp_effect": "°C", } def load_data(path: str) -> pd.DataFrame: """Load an xlsx or csv operational data file and standardise it.""" if str(path).lower().endswith(".csv"): df = pd.read_csv(path) else: df = pd.read_excel(path) # Find the timestamp column heuristically if not literally named 'timestamp' ts_col = None for c in df.columns: if "time" in c.lower() or "date" in c.lower(): ts_col = c break if ts_col is None: raise ValueError("No timestamp/date column could be found in the uploaded file.") df[ts_col] = pd.to_datetime(df[ts_col]) df = df.rename(columns={ts_col: "timestamp"}).sort_values("timestamp").reset_index(drop=True) return df def numeric_columns(df: pd.DataFrame) -> list[str]: exclude = {"fault_type", "time_to_fault_min"} return [c for c in df.select_dtypes(include=[np.number]).columns if c not in exclude] def resolve_column(df: pd.DataFrame, text: str) -> str | None: """Map free-text user wording to an actual dataframe column.""" text = text.lower() cols = numeric_columns(df) # direct hit for c in cols: if c.replace("_", " ") in text or c in text: return c # alias hit (sort by alias length desc so longer/more specific matches win) for alias in sorted(COLUMN_ALIASES, key=len, reverse=True): if alias in text and COLUMN_ALIASES[alias] in cols: return COLUMN_ALIASES[alias] return None # --------------------------------------------------------------------------- # Column statistical profiles (used both for direct answers and RAG context) # --------------------------------------------------------------------------- def build_column_profiles(df: pd.DataFrame) -> list[dict]: docs = [] for col in numeric_columns(df): s = df[col].dropna() if s.empty: continue unit = UNITS.get(col, "") recent = s.iloc[-1] text = ( f"Variable '{col}' ({unit}): mean={s.mean():.3f}, std={s.std():.3f}, " f"min={s.min():.3f}, max={s.max():.3f}, most recent value={recent:.3f}. " f"Over the full record this variable ranged between {s.min():.2f} and {s.max():.2f} {unit}, " f"averaging {s.mean():.2f} {unit}." ) docs.append({"id": f"profile_{col}", "type": "profile", "column": col, "text": text}) return docs # --------------------------------------------------------------------------- # Fault episode detection # --------------------------------------------------------------------------- def detect_fault_episodes(df: pd.DataFrame) -> list[dict]: """Find contiguous runs where fault_type != 0 and characterise each one.""" if "fault_type" not in df.columns: return [] episodes = [] in_fault = False start_idx = None for i, row in df.iterrows(): is_fault = row["fault_type"] != 0 if is_fault and not in_fault: in_fault = True start_idx = i elif not is_fault and in_fault: in_fault = False episodes.append((start_idx, i - 1)) if in_fault: episodes.append((start_idx, df.index[-1])) results = [] for n, (s_idx, e_idx) in enumerate(episodes, start=1): seg = df.loc[s_idx:e_idx] before = df.loc[:s_idx].tail(60) # ~1 hr of context before, if minute data fault_type = int(seg["fault_type"].mode().iloc[0]) duration_min = (seg["timestamp"].iloc[-1] - seg["timestamp"].iloc[0]).total_seconds() / 60.0 impact = {} for col in ["conversion_rate", "yield_pct", "efficiency_loss_pct", "vibration_rms", "reactor_temp"]: if col in df.columns: during = seg[col].dropna() pre = before[col].dropna() if len(during) and len(pre): impact[col] = { "before_avg": float(pre.mean()), "during_avg": float(during.mean()), "delta": float(during.mean() - pre.mean()), } results.append({ "episode": n, "fault_type": fault_type, "start": seg["timestamp"].iloc[0], "end": seg["timestamp"].iloc[-1], "duration_min": duration_min, "impact": impact, }) return results def build_fault_docs(episodes: list[dict]) -> list[dict]: docs = [] for ep in episodes: impact_sentences = [] for col, vals in ep["impact"].items(): direction = "dropped" if vals["delta"] < 0 else "rose" impact_sentences.append( f"{col} {direction} from an average of {vals['before_avg']:.2f} before the event " f"to {vals['during_avg']:.2f} during it (change of {vals['delta']:+.2f})." ) text = ( f"Fault episode #{ep['episode']} (fault_type={ep['fault_type']}) started at " f"{ep['start']} and ended at {ep['end']}, lasting {ep['duration_min']:.1f} minutes. " + " ".join(impact_sentences) ) docs.append({"id": f"fault_{ep['episode']}", "type": "fault", "text": text, "episode": ep}) return docs # --------------------------------------------------------------------------- # Time-window summaries (gives the RAG layer something to retrieve for # "what happened around X time" style questions) # --------------------------------------------------------------------------- def build_time_window_docs(df: pd.DataFrame, freq: str = "1h") -> list[dict]: docs = [] grouped = df.set_index("timestamp").resample(freq) cols = [c for c in numeric_columns(df) if c in df.columns][:6] # keep it concise for ts, window in grouped: if window.empty: continue fault_active = (window["fault_type"] != 0).any() if "fault_type" in window else False stats = ", ".join( f"{c} avg {window[c].mean():.2f}" for c in cols if window[c].notna().any() ) text = ( f"Window starting {ts}: {stats}. " f"Fault condition active during this window: {'yes' if fault_active else 'no'}." ) docs.append({"id": f"window_{ts}", "type": "window", "text": text, "start": ts}) return docs def all_context_docs(df: pd.DataFrame) -> list[dict]: docs = [] docs += build_column_profiles(df) episodes = detect_fault_episodes(df) docs += build_fault_docs(episodes) docs += build_time_window_docs(df, freq="1h") return docs # --------------------------------------------------------------------------- # Fast deterministic intent router — handles the most common question types # directly with pandas so numeric answers are always exact (no LLM needed). # Returns None if no rule matched, so the caller can fall back to RAG+LLM. # --------------------------------------------------------------------------- def try_direct_answer(query: str, df: pd.DataFrame) -> str | None: q = query.lower() # --- fault / shutdown questions ----------------------------------- if any(k in q for k in ["fault", "shutdown", "shut down", "abnormal", "trip", "malfunction"]): episodes = detect_fault_episodes(df) if not episodes: return "No fault episodes were detected in the currently loaded data." if any(k in q for k in ["how many", "count", "number of"]): return f"There {'is' if len(episodes)==1 else 'are'} {len(episodes)} fault episode(s) in this dataset." # default: describe the most relevant (largest/duration) episode ep = max(episodes, key=lambda e: e["duration_min"]) impact_bits = [ f"{c} moved from {v['before_avg']:.2f} to {v['during_avg']:.2f}" for c, v in ep["impact"].items() ] return ( f"The most significant fault episode (type {ep['fault_type']}) ran from " f"{ep['start']:%Y-%m-%d %H:%M} to {ep['end']:%Y-%m-%d %H:%M}, lasting " f"{ep['duration_min']:.0f} minutes. During this period: {'; '.join(impact_bits)}." ) # --- average / mean --------------------------------------------------- if any(k in q for k in ["average", "mean", "typical"]): col = resolve_column(df, q) if col: s = df[col].dropna() return f"The average {col.replace('_',' ')} is {s.mean():.2f} {UNITS.get(col,'')} (over {len(s)} readings)." # --- min/max/range ------------------------------------------------ if any(k in q for k in ["maximum", "max ", "highest", "peak"]): col = resolve_column(df, q) if col: s = df[col].dropna() idx = s.idxmax() return f"The maximum {col.replace('_',' ')} was {s.max():.2f} {UNITS.get(col,'')}, recorded at {df.loc[idx,'timestamp']}." if any(k in q for k in ["minimum", "min ", "lowest"]): col = resolve_column(df, q) if col: s = df[col].dropna() idx = s.idxmin() return f"The minimum {col.replace('_',' ')} was {s.min():.2f} {UNITS.get(col,'')}, recorded at {df.loc[idx,'timestamp']}." # --- current / latest value ---------------------------------------- if any(k in q for k in ["current", "right now", "latest", "currently"]): col = resolve_column(df, q) if col: s = df[col].dropna() return f"The most recent {col.replace('_',' ')} reading is {s.iloc[-1]:.2f} {UNITS.get(col,'')} at {df.loc[s.index[-1],'timestamp']}." # --- trend ------------------------------------------------------------ if any(k in q for k in ["trend", "increasing", "decreasing", "rising", "falling", "stable"]): col = resolve_column(df, q) if col: s = df[col].dropna() n = min(60, len(s)) recent = s.tail(n) slope = np.polyfit(range(len(recent)), recent.values, 1)[0] direction = "increasing" if slope > 1e-3 else ("decreasing" if slope < -1e-3 else "stable") return f"Over the most recent {n} readings, {col.replace('_',' ')} has been {direction} (slope {slope:+.4f} per sample)." return None