import json import os from datetime import datetime from typing import Any, Dict, List, Optional, Tuple import pandas as pd import requests import streamlit as st st.set_page_config(page_title="Simulation & Prescriptive Analysis Engine", page_icon="📈", layout="wide") COMPLEXITY_FACTORS = {"Low": 0.85, "Medium": 1.0, "High": 1.25, "Critical": 1.55} TECH_RISK_FACTORS = {"Low": 0.8, "Medium": 1.0, "High": 1.3} CLIENT_TIER_FACTORS = {"SMB": 0.95, "Mid-Market": 1.0, "Enterprise": 1.08} COMPLEXITY_OPTIONS = ["Low", "Medium", "High", "Critical"] TECH_RISK_OPTIONS = ["Low", "Medium", "High"] CLIENT_TIER_OPTIONS = ["SMB", "Mid-Market", "Enterprise"] SAMPLE = { "project_description": "Replatform fragmented order lifecycle workflows into a unified commerce operations platform across finance, fulfillment, and support.", "budget": 880000, "team_size": 14, "timeline_weeks": 30, "scope_complexity": "High", "tech_risk": "Medium", "client_tier": "Enterprise", "dependencies": 3, } def clamp(value: float, min_value: float, max_value: float) -> float: return max(min_value, min(value, max_value)) def safe_get_api_key() -> Optional[str]: try: key = st.secrets.get("GEMINI_API_KEY") if key: return key except Exception: pass env_key = os.getenv("GEMINI_API_KEY") return env_key if env_key else None @st.cache_data def load_historical_data() -> pd.DataFrame: df = pd.read_csv("data/historical_projects.csv") for col in [ "budget", "team_size", "timeline_weeks", "dependencies", "actual_margin_pct", "success_score", "delivery_risk_score", "year", ]: df[col] = pd.to_numeric(df[col], errors="coerce") return df def initialize_state() -> None: defaults = { "unlocked_step": 1, "request_timestamps": [], "base_inputs": None, "scenario_snapshot": None, "recommendations": None, "report": None, "custom_scenario_enabled": False, } for k, v in defaults.items(): if k not in st.session_state: st.session_state[k] = v def reset_all() -> None: keep = {"request_timestamps"} for k in list(st.session_state.keys()): if k not in keep: del st.session_state[k] initialize_state() def load_sample() -> None: for k, v in SAMPLE.items(): st.session_state[k] = v def rate_limiter(max_requests: int = 8, window_seconds: int = 60) -> Tuple[bool, int]: now_ts = datetime.utcnow().timestamp() active = [ts for ts in st.session_state.get("request_timestamps", []) if now_ts - ts <= window_seconds] if len(active) >= max_requests: st.session_state["request_timestamps"] = active return False, 0 active.append(now_ts) st.session_state["request_timestamps"] = active return True, max_requests - len(active) def timeline_pressure_score(inputs: Dict[str, Any]) -> float: complexity = COMPLEXITY_FACTORS[inputs["scope_complexity"]] budget_units = inputs["budget"] / 100000 suggested_weeks = (budget_units * 1.8 * complexity) / max(inputs["team_size"] / 6, 0.7) suggested_weeks = clamp(suggested_weeks, 8, 56) pressure = ((suggested_weeks - inputs["timeline_weeks"]) / suggested_weeks) * 100 return clamp(pressure, -35, 60) def compute_margin_estimate(inputs: Dict[str, Any]) -> float: complexity = COMPLEXITY_FACTORS[inputs["scope_complexity"]] tech_factor = TECH_RISK_FACTORS[inputs["tech_risk"]] tier_factor = CLIENT_TIER_FACTORS[inputs["client_tier"]] budget_scale = min(inputs["budget"] / 1000000, 2.4) team_density = inputs["team_size"] / max(inputs["budget"] / 100000, 1.0) pressure = timeline_pressure_score(inputs) base_margin = 23.5 size_bonus = budget_scale * 2.8 complexity_drag = (complexity - 1.0) * 9.5 tech_drag = (tech_factor - 1.0) * 8.2 staffing_drag = max(0, (team_density - 1.55) * 4.2) pressure_drag = max(0, pressure) * 0.09 margin = (base_margin + size_bonus - complexity_drag - tech_drag - staffing_drag - pressure_drag) * tier_factor return clamp(margin, 3.0, 48.0) def compute_risk_score(inputs: Dict[str, Any]) -> float: complexity_weight = {"Low": 8, "Medium": 18, "High": 30, "Critical": 42}[inputs["scope_complexity"]] tech_weight = {"Low": 7, "Medium": 16, "High": 30}[inputs["tech_risk"]] dependency_weight = inputs["dependencies"] * 7.5 pressure_weight = max(0, timeline_pressure_score(inputs)) * 0.65 raw = complexity_weight + tech_weight + dependency_weight + pressure_weight if inputs["client_tier"] == "Enterprise": raw += 4.5 if inputs["team_size"] < 4 and inputs["scope_complexity"] in {"High", "Critical"}: raw += 9 return clamp(raw, 6, 97) def compute_success_probability(inputs: Dict[str, Any], margin: float, risk_score: float) -> float: budget_fit = clamp((inputs["budget"] - 200000) / 18000, 0, 24) dependency_penalty = inputs["dependencies"] * 2.7 complexity_penalty = {"Low": 2, "Medium": 6, "High": 13, "Critical": 20}[inputs["scope_complexity"]] probability = 78 + budget_fit + (margin - 20) * 0.6 - (risk_score - 35) * 0.62 probability -= dependency_penalty + complexity_penalty if inputs["client_tier"] == "SMB": probability += 2 if inputs["tech_risk"] == "High": probability -= 5 return clamp(probability, 8, 96) def risk_level_label(score: float) -> str: if score < 30: return "Low" if score < 55: return "Moderate" if score < 75: return "High" return "Critical" def normalize_inputs( project_description: str, budget: int, team_size: int, timeline_weeks: int, scope_complexity: str, tech_risk: str, client_tier: str, dependencies: int, ) -> Dict[str, Any]: description = project_description.strip() return { "project_description": description, "project_name": description[:80] if description else "Untitled Simulation", "budget": float(budget), "team_size": int(team_size), "timeline_weeks": int(timeline_weeks), "scope_complexity": scope_complexity, "tech_risk": tech_risk, "client_tier": client_tier, "dependencies": int(dependencies), } def quick_preview(inputs: Dict[str, Any]) -> Dict[str, Any]: margin = compute_margin_estimate(inputs) risk = compute_risk_score(inputs) pressure = timeline_pressure_score(inputs) pressure_label = "Low" if pressure < 8 else "Moderate" if pressure < 20 else "High" return { "margin": round(margin, 1), "risk_score": round(risk, 1), "risk_label": risk_level_label(risk), "pressure": round(pressure, 1), "pressure_label": pressure_label, } def scenario_defaults(slug: str) -> Dict[str, Any]: defaults = { "conservative": { "team_delta": 2, "timeline_delta": 4, "budget_delta_pct": 5, "dependency_delta": 0, "complexity_override": "Same as project", "tech_override": "Same as project", "client_override": "Same as project", }, "baseline": { "team_delta": 0, "timeline_delta": 0, "budget_delta_pct": 0, "dependency_delta": 0, "complexity_override": "Same as project", "tech_override": "Same as project", "client_override": "Same as project", }, "aggressive": { "team_delta": -1, "timeline_delta": -4, "budget_delta_pct": -3, "dependency_delta": 1, "complexity_override": "Same as project", "tech_override": "Same as project", "client_override": "Same as project", }, } return defaults[slug] def apply_adjustments(base_inputs: Dict[str, Any], adjustments: Dict[str, Any]) -> Dict[str, Any]: complexity = base_inputs["scope_complexity"] if adjustments["complexity_override"] == "Same as project" else adjustments["complexity_override"] tech = base_inputs["tech_risk"] if adjustments["tech_override"] == "Same as project" else adjustments["tech_override"] tier = base_inputs["client_tier"] if adjustments["client_override"] == "Same as project" else adjustments["client_override"] return { "project_description": base_inputs["project_description"], "project_name": base_inputs["project_name"], "budget": float(clamp(base_inputs["budget"] * (1 + adjustments["budget_delta_pct"] / 100), 50000, 2000000)), "team_size": int(clamp(base_inputs["team_size"] + adjustments["team_delta"], 2, 30)), "timeline_weeks": int(clamp(base_inputs["timeline_weeks"] + adjustments["timeline_delta"], 4, 52)), "scope_complexity": complexity, "tech_risk": tech, "client_tier": tier, "dependencies": int(clamp(base_inputs["dependencies"] + adjustments["dependency_delta"], 0, 5)), } def scenario_metrics(inputs: Dict[str, Any], name: str) -> Dict[str, Any]: margin = compute_margin_estimate(inputs) risk = compute_risk_score(inputs) success = compute_success_probability(inputs, margin, risk) return { "Scenario": name, "Projected Margin %": round(margin, 1), "Success Probability %": round(success, 1), "Delivery Risk": risk_level_label(risk), "Risk Score": round(risk, 1), "Projected Timeline (weeks)": int(inputs["timeline_weeks"]), "Team Size": int(inputs["team_size"]), "Budget": float(inputs["budget"]), "Dependencies": int(inputs["dependencies"]), "Complexity": inputs["scope_complexity"], "Tech Risk": inputs["tech_risk"], "Client Tier": inputs["client_tier"], } def compute_similarity_distance(inputs: Dict[str, Any], row: pd.Series) -> float: budget_norm = abs(inputs["budget"] - float(row["budget"])) / 2000000 team_norm = abs(inputs["team_size"] - float(row["team_size"])) / 30 timeline_norm = abs(inputs["timeline_weeks"] - float(row["timeline_weeks"])) / 52 dep_norm = abs(inputs["dependencies"] - float(row["dependencies"])) / 5 complexity_pen = 0 if row["scope_complexity"] == inputs["scope_complexity"] else 0.2 tier_pen = 0 if row["client_tier"] == inputs["client_tier"] else 0.12 tech_pen = 0 if row["tech_risk"] == inputs["tech_risk"] else 0.14 return budget_norm * 0.32 + team_norm * 0.2 + timeline_norm * 0.18 + dep_norm * 0.12 + complexity_pen + tier_pen + tech_pen def find_similar_projects(inputs: Dict[str, Any], historical_df: pd.DataFrame, top_n: int = 5) -> pd.DataFrame: df = historical_df.copy() df["similarity_distance"] = df.apply(lambda row: compute_similarity_distance(inputs, row), axis=1) cols = [ "project_id", "name", "scope_complexity", "budget", "team_size", "timeline_weeks", "tech_risk", "client_tier", "dependencies", "actual_margin_pct", "success_score", "delivery_risk_score", "outcome", "year", "similarity_distance", ] return pd.DataFrame(df.sort_values("similarity_distance", ascending=True).head(top_n)[cols]) def compute_capacity_impact(inputs: Dict[str, Any], historical_df: pd.DataFrame) -> Dict[str, Any]: recent = historical_df[historical_df["year"] >= 2023].copy() if recent.empty: recent = historical_df.copy() avg_team = float(recent["team_size"].mean()) active_ref = max(5, int(round(len(recent) * 0.45))) org_capacity = max(40, int(round(avg_team * active_ref * 1.42))) current_committed = int(round(avg_team * active_ref * 0.88)) projected_committed = current_committed + inputs["team_size"] current_util = (current_committed / org_capacity) * 100 projected_util = (projected_committed / org_capacity) * 100 high_risk_recent = recent[recent["delivery_risk_score"] >= 60] risk_before = (len(high_risk_recent) / len(recent)) * 100 if len(recent) else 0 candidate_high_risk = compute_risk_score(inputs) >= 60 risk_after = ((len(high_risk_recent) + (1 if candidate_high_risk else 0)) / (len(recent) + 1)) * 100 bottleneck = "No immediate bottleneck detected" driver = "Balanced utilization across key disciplines" if projected_util >= 90: bottleneck, driver = "Critical staffing contention", "Platform and data engineering exceed safe portfolio headroom" elif projected_util >= 80: bottleneck, driver = "Moderate specialist contention", "Solution architecture and QA become schedule constraints" elif inputs["dependencies"] >= 4: bottleneck, driver = "Dependency orchestration risk", "Cross-team sequencing overhead likely to slow throughput" return { "org_capacity_slots": org_capacity, "current_committed_slots": current_committed, "projected_committed_slots": projected_committed, "current_utilization_pct": round(current_util, 1), "projected_utilization_pct": round(projected_util, 1), "utilization_delta_pct": round(projected_util - current_util, 1), "risk_concentration_before_pct": round(risk_before, 1), "risk_concentration_after_pct": round(risk_after, 1), "risk_concentration_delta_pct": round(risk_after - risk_before, 1), "portfolio_bottleneck": bottleneck, "portfolio_bottleneck_driver": driver, } def build_gemini_prompt(base_inputs: Dict[str, Any], scenario_df: pd.DataFrame, capacity: Dict[str, Any], similar_df: pd.DataFrame) -> str: scenarios = [] for _, row in scenario_df.iterrows(): scenarios.append( f"- {row['Scenario']}: margin={row['Projected Margin %']}%, success={row['Success Probability %']}%, risk={row['Delivery Risk']} ({row['Risk Score']}), timeline={row['Projected Timeline (weeks)']}w" ) similars = [] for _, row in similar_df.iterrows(): similars.append( f"- {row['name']} ({int(row['year'])}): margin={row['actual_margin_pct']}%, success={row['success_score']}, risk={row['delivery_risk_score']}, outcome={row['outcome']}, distance={round(float(row['similarity_distance']), 3)}" ) return f""" You are a portfolio strategy advisor. Return only strict JSON with keys: - recommended_path: 3 bullets - scope_adjustments: 3 bullets - risk_mitigations: 3 bullets - executive_call: one sentence Project: - Description: {base_inputs['project_description']} - Budget: ${base_inputs['budget']:,.0f} - Team size: {base_inputs['team_size']} - Timeline: {base_inputs['timeline_weeks']} weeks - Complexity: {base_inputs['scope_complexity']} - Tech risk: {base_inputs['tech_risk']} - Client tier: {base_inputs['client_tier']} - Dependencies: {base_inputs['dependencies']} Scenarios: {chr(10).join(scenarios)} Capacity context: - Current utilization: {capacity['current_utilization_pct']}% - Projected utilization: {capacity['projected_utilization_pct']}% - Risk concentration delta: {capacity['risk_concentration_delta_pct']}% - Bottleneck: {capacity['portfolio_bottleneck']} ({capacity['portfolio_bottleneck_driver']}) Closest historical projects: {chr(10).join(similars)} """.strip() def call_gemini(prompt: str, api_key: Optional[str]) -> Optional[str]: if not api_key: return None try: res = requests.post( f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={api_key}", json={"contents": [{"parts": [{"text": prompt}]}]}, timeout=30, ) if res.status_code != 200: return None payload = res.json() candidates = payload.get("candidates") if not candidates: return None parts = candidates[0].get("content", {}).get("parts", []) if not parts: return None text = parts[0].get("text") return text.strip() if text else None except Exception: return None def parse_gemini_output(text: str) -> Optional[Dict[str, Any]]: cleaned = text.strip().replace("```json", "").replace("```", "").strip() try: parsed = json.loads(cleaned) except Exception: return None keys = ["recommended_path", "scope_adjustments", "risk_mitigations", "executive_call"] if not all(k in parsed for k in keys): return None rec_path = [str(x).strip() for x in parsed["recommended_path"] if str(x).strip()][:3] scope_adj = [str(x).strip() for x in parsed["scope_adjustments"] if str(x).strip()][:3] mitigations = [str(x).strip() for x in parsed["risk_mitigations"] if str(x).strip()][:3] if min(len(rec_path), len(scope_adj), len(mitigations)) < 3: return None return { "recommended_path": rec_path, "scope_adjustments": scope_adj, "risk_mitigations": mitigations, "executive_call": str(parsed["executive_call"]).strip(), } def heuristic_recommendations(base_inputs: Dict[str, Any], scenario_df: pd.DataFrame, capacity: Dict[str, Any], similar_df: pd.DataFrame) -> Dict[str, Any]: baseline = scenario_df[scenario_df["Scenario"] == "Baseline"].iloc[0].to_dict() best = scenario_df.sort_values(["Success Probability %", "Projected Margin %"], ascending=False).iloc[0].to_dict() rec_path = [] if best["Scenario"] == "Conservative": rec_path.append("Lead with the Conservative posture to absorb integration volatility and protect confidence.") elif best["Scenario"] == "Aggressive": rec_path.append("Use the Aggressive posture only with strict dependency governance and weekly executive unblockers.") else: rec_path.append("Run with Baseline posture and lock milestone decisions around delivery gates.") rec_path.append("Phase high-uncertainty interfaces into early waves with dedicated integration ownership.") rec_path.append( "Protect economics with scope discipline and change-order controls." if baseline["Projected Margin %"] >= 18 else "Reprice or reduce non-core scope to restore margin above 18%." ) scope_adj = [] scope_adj.append("Move dependency-heavy workstreams behind readiness gates.") if base_inputs["dependencies"] >= 4 else scope_adj.append("Defer low-value enhancements into an optional tranche.") scope_adj.append("Reduce acceptance complexity for compressed timelines.") if baseline["Projected Timeline (weeks)"] < base_inputs["timeline_weeks"] else scope_adj.append("Keep timeline and remove low-value edge cases to reduce QA spread.") completion_rate = float((similar_df["outcome"] == "completed").sum()) / float(len(similar_df)) if len(similar_df) else 0 scope_adj.append("Tie commercial milestones to value slices due weaker historical completion patterns.") if completion_rate < 0.5 else scope_adj.append("Replicate staffing and sequencing from strongest historical analogs.") mitigations = [] if capacity["projected_utilization_pct"] >= 90: mitigations.append("Pre-book contract specialists to avoid critical utilization breaches.") elif capacity["projected_utilization_pct"] >= 80: mitigations.append("Reserve architecture and QA pods now to prevent contention.") else: mitigations.append("Maintain weekly allocation checks to preserve portfolio headroom.") mitigations.append("Assign a dependency manager with blocker SLA escalation to steering committee.") mitigations.append("Add launch readiness gates with rollback criteria.") if baseline["Risk Score"] >= 60 else mitigations.append("Run monthly steering checkpoints with strict change qualification.") return { "recommended_path": rec_path[:3], "scope_adjustments": scope_adj[:3], "risk_mitigations": mitigations[:3], "executive_call": "Proceed on the path that keeps risk below critical, margin above 18%, and utilization below 90%.", } def generate_recommendations(base_inputs: Dict[str, Any], scenario_df: pd.DataFrame, capacity: Dict[str, Any], similar_df: pd.DataFrame) -> Dict[str, Any]: source = "Deterministic Heuristic" body = None api_key = safe_get_api_key() if api_key: prompt = build_gemini_prompt(base_inputs, scenario_df, capacity, similar_df) text = call_gemini(prompt, api_key) if text: parsed = parse_gemini_output(text) if parsed: body = parsed source = "Gemini 2.5 Flash" if not body: body = heuristic_recommendations(base_inputs, scenario_df, capacity, similar_df) return {"source": source, "generated_at": datetime.utcnow().isoformat(), **body} def apply_style(unlocked_step: int) -> None: lock_start = unlocked_step + 1 lock_css = "" if lock_start <= 4: lock_css = f"div[role='tablist'] button:nth-child(n+{lock_start}){{opacity:.38!important;filter:grayscale(1)!important;pointer-events:none!important;}}" st.markdown( f""" """, unsafe_allow_html=True, ) def show_header() -> None: st.title("Simulation and Prescriptive Analysis Engine") st.caption( "An AI engine that simulates custom work and recommends optimal paths, projecting delivery complexity, margin impact, and likelihood of success while factoring in all other projects in flight." ) def section_banner(step: int) -> None: lines = { 1: "Define project assumptions and watch live margin/risk/timeline pressure update instantly.", 2: "Tune Conservative, Baseline, Aggressive, and optional Custom scenarios with inline controls.", 3: "Review prescriptive recommendations, capture ratings, and validate capacity and bottlenecks.", 4: "Generate the executive report with scenario comparison, recommendations, ratings, and export.", } st.markdown(f"
", unsafe_allow_html=True) def show_quick_cards(preview: Dict[str, Any]) -> None: c1, c2, c3 = st.columns(3) c1.markdown(f"