arcalab commited on
Commit
a17d99a
·
verified ·
1 Parent(s): 7eeed87

Upload folder using huggingface_hub

Browse files
Files changed (6) hide show
  1. .streamlit/config.toml +6 -0
  2. Dockerfile +18 -0
  3. README.md +6 -9
  4. app.py +583 -0
  5. data/historical_projects.csv +26 -0
  6. requirements.txt +3 -0
.streamlit/config.toml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ [theme]
2
+ primaryColor="#6C63FF"
3
+ backgroundColor="#0E1117"
4
+ secondaryBackgroundColor="#1A1D29"
5
+ textColor="#FAFAFA"
6
+ font="sans serif"
Dockerfile ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+ ENV PYTHONDONTWRITEBYTECODE=1
3
+ ENV PYTHONUNBUFFERED=1
4
+ WORKDIR /code
5
+ COPY ./requirements.txt /code/requirements.txt
6
+ RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
7
+ RUN useradd -m -u 1000 user
8
+ USER user
9
+ ENV HOME=/home/user PATH=/home/user/.local/bin:$PATH
10
+ ENV STREAMLIT_SERVER_PORT=7860
11
+ ENV STREAMLIT_SERVER_ADDRESS=0.0.0.0
12
+ ENV STREAMLIT_SERVER_HEADLESS=true
13
+ ENV STREAMLIT_SERVER_ENABLE_CORS=false
14
+ ENV STREAMLIT_SERVER_ENABLE_XSRF_PROTECTION=false
15
+ WORKDIR $HOME/app
16
+ COPY --chown=user . $HOME/app
17
+ EXPOSE 7860
18
+ CMD ["streamlit", "run", "app.py", "--server.port", "7860", "--server.address", "0.0.0.0"]
README.md CHANGED
@@ -1,10 +1,7 @@
1
- ---
2
- title: Simulation Prescriptive
3
- emoji: 🏆
4
- colorFrom: gray
5
- colorTo: green
6
- sdk: docker
7
- pinned: false
8
- ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
1
+ # Simulation & Prescriptive Analysis Engine
 
 
 
 
 
 
 
2
 
3
+ Streamlit app for enterprise deal desk and PMO what-if analysis.
4
+
5
+ It simulates Conservative, Baseline, and Aggressive project scenarios, estimates margin/success/risk, evaluates portfolio capacity impact, and suggests prescriptive actions.
6
+
7
+ The app uses Gemini when `GEMINI_API_KEY` is available and automatically falls back to a deterministic heuristic model when it is not.
app.py ADDED
@@ -0,0 +1,583 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from datetime import datetime
3
+ from typing import Any, Dict, List, Optional, Tuple
4
+
5
+ import pandas as pd
6
+ import requests
7
+ import streamlit as st
8
+
9
+ st.set_page_config(
10
+ page_title="Simulation & Prescriptive Analysis Engine",
11
+ layout="wide",
12
+ initial_sidebar_state="collapsed",
13
+ )
14
+
15
+ COMPLEXITY_FACTORS = {"Low": 0.85, "Medium": 1.0, "High": 1.25, "Critical": 1.55}
16
+ TECH_RISK_FACTORS = {"Low": 0.8, "Medium": 1.0, "High": 1.3}
17
+ CLIENT_TIER_FACTORS = {"SMB": 0.95, "Mid-Market": 1.0, "Enterprise": 1.08}
18
+
19
+
20
+ def clamp(value: float, min_value: float, max_value: float) -> float:
21
+ return max(min_value, min(value, max_value))
22
+
23
+
24
+ def safe_get_api_key() -> Optional[str]:
25
+ try:
26
+ secret_key = st.secrets.get("GEMINI_API_KEY")
27
+ if secret_key:
28
+ return secret_key
29
+ except Exception:
30
+ pass
31
+ env_key = os.getenv("GEMINI_API_KEY")
32
+ return env_key if env_key else None
33
+
34
+
35
+ @st.cache_data
36
+ def load_historical_data() -> pd.DataFrame:
37
+ df = pd.read_csv("data/historical_projects.csv")
38
+ numeric_cols = [
39
+ "budget",
40
+ "team_size",
41
+ "timeline_weeks",
42
+ "dependencies",
43
+ "actual_margin_pct",
44
+ "success_score",
45
+ "delivery_risk_score",
46
+ "year",
47
+ ]
48
+ for col in numeric_cols:
49
+ df[col] = pd.to_numeric(df[col], errors="coerce")
50
+ return df
51
+
52
+
53
+ def initialize_state() -> None:
54
+ defaults = {
55
+ "project_name": "",
56
+ "scope_complexity": "Medium",
57
+ "budget": 350000,
58
+ "team_size": 8,
59
+ "timeline_weeks": 20,
60
+ "tech_risk": "Medium",
61
+ "client_tier": "Mid-Market",
62
+ "dependencies": 1,
63
+ "request_timestamps": [],
64
+ "simulation_result": None,
65
+ "example_loaded_at": None,
66
+ }
67
+ for key, value in defaults.items():
68
+ if key not in st.session_state:
69
+ st.session_state[key] = value
70
+
71
+
72
+ def load_example_values() -> None:
73
+ st.session_state.project_name = "Aurora ERP + CRM Modernization"
74
+ st.session_state.scope_complexity = "High"
75
+ st.session_state.budget = 860000
76
+ st.session_state.team_size = 14
77
+ st.session_state.timeline_weeks = 28
78
+ st.session_state.tech_risk = "Medium"
79
+ st.session_state.client_tier = "Enterprise"
80
+ st.session_state.dependencies = 3
81
+ st.session_state.example_loaded_at = datetime.utcnow().isoformat()
82
+
83
+
84
+ def get_inputs_from_state() -> Dict[str, Any]:
85
+ return {
86
+ "project_name": st.session_state.project_name.strip() or "Untitled Opportunity",
87
+ "scope_complexity": st.session_state.scope_complexity,
88
+ "budget": float(st.session_state.budget),
89
+ "team_size": int(st.session_state.team_size),
90
+ "timeline_weeks": int(st.session_state.timeline_weeks),
91
+ "tech_risk": st.session_state.tech_risk,
92
+ "client_tier": st.session_state.client_tier,
93
+ "dependencies": int(st.session_state.dependencies),
94
+ }
95
+
96
+
97
+ def timeline_pressure_score(inputs: Dict[str, Any]) -> float:
98
+ complexity = COMPLEXITY_FACTORS[inputs["scope_complexity"]]
99
+ budget_units = inputs["budget"] / 100000
100
+ suggested_weeks = (budget_units * 1.8 * complexity) / max(inputs["team_size"] / 6, 0.7)
101
+ suggested_weeks = clamp(suggested_weeks, 8, 56)
102
+ pressure = ((suggested_weeks - inputs["timeline_weeks"]) / suggested_weeks) * 100
103
+ return clamp(pressure, -35, 60)
104
+
105
+
106
+ def compute_margin_estimate(inputs: Dict[str, Any]) -> float:
107
+ complexity = COMPLEXITY_FACTORS[inputs["scope_complexity"]]
108
+ tech_factor = TECH_RISK_FACTORS[inputs["tech_risk"]]
109
+ tier_factor = CLIENT_TIER_FACTORS[inputs["client_tier"]]
110
+ budget_scale = min(inputs["budget"] / 1000000, 2.4)
111
+ team_density = inputs["team_size"] / max(inputs["budget"] / 100000, 1.0)
112
+ timeline_pressure = timeline_pressure_score(inputs)
113
+
114
+ base_margin = 23.5
115
+ size_bonus = budget_scale * 2.8
116
+ complexity_drag = (complexity - 1.0) * 9.5
117
+ tech_drag = (tech_factor - 1.0) * 8.2
118
+ staffing_drag = max(0, (team_density - 1.55) * 4.2)
119
+ pressure_drag = max(0, timeline_pressure) * 0.09
120
+
121
+ margin = (base_margin + size_bonus - complexity_drag - tech_drag - staffing_drag - pressure_drag) * tier_factor
122
+ return clamp(margin, 3.0, 48.0)
123
+
124
+
125
+ def compute_risk_score(inputs: Dict[str, Any]) -> float:
126
+ complexity_weight = {"Low": 8, "Medium": 18, "High": 30, "Critical": 42}[inputs["scope_complexity"]]
127
+ tech_weight = {"Low": 7, "Medium": 16, "High": 30}[inputs["tech_risk"]]
128
+ dependency_weight = inputs["dependencies"] * 7.5
129
+ pressure_weight = max(0, timeline_pressure_score(inputs)) * 0.65
130
+ raw_risk = complexity_weight + tech_weight + dependency_weight + pressure_weight
131
+ if inputs["client_tier"] == "Enterprise":
132
+ raw_risk += 4.5
133
+ if inputs["team_size"] < 4 and inputs["scope_complexity"] in {"High", "Critical"}:
134
+ raw_risk += 9
135
+ return clamp(raw_risk, 6, 97)
136
+
137
+
138
+ def compute_success_probability(inputs: Dict[str, Any], margin: float, risk_score: float) -> float:
139
+ budget_fit = clamp((inputs["budget"] - 200000) / 18000, 0, 24)
140
+ dependency_penalty = inputs["dependencies"] * 2.7
141
+ complexity_penalty = {"Low": 2, "Medium": 6, "High": 13, "Critical": 20}[inputs["scope_complexity"]]
142
+ probability = 78 + budget_fit + (margin - 20) * 0.6 - (risk_score - 35) * 0.62
143
+ probability -= dependency_penalty + complexity_penalty
144
+ if inputs["client_tier"] == "SMB":
145
+ probability += 2
146
+ if inputs["tech_risk"] == "High":
147
+ probability -= 5
148
+ return clamp(probability, 8, 96)
149
+
150
+
151
+ def risk_level_label(score: float) -> str:
152
+ if score < 30:
153
+ return "Low"
154
+ if score < 55:
155
+ return "Moderate"
156
+ if score < 75:
157
+ return "High"
158
+ return "Critical"
159
+
160
+
161
+ def simulate_scenarios(inputs: Dict[str, Any]) -> Tuple[pd.DataFrame, Dict[str, Any]]:
162
+ margin = compute_margin_estimate(inputs)
163
+ risk = compute_risk_score(inputs)
164
+ success = compute_success_probability(inputs, margin, risk)
165
+ baseline_timeline = inputs["timeline_weeks"]
166
+
167
+ baseline = {
168
+ "Scenario": "Baseline",
169
+ "Projected Margin %": round(margin, 1),
170
+ "Success Probability %": round(success, 1),
171
+ "Delivery Risk": risk_level_label(risk),
172
+ "Risk Score": round(risk, 1),
173
+ "Projected Timeline (weeks)": int(round(baseline_timeline)),
174
+ "Assumption": "As-entered plan with current parameters.",
175
+ }
176
+ conservative_risk = clamp(risk - 10, 4, 95)
177
+ conservative_margin = clamp(margin - 3.2, 2, 50)
178
+ conservative_success = clamp(success + 7, 5, 98)
179
+ conservative = {
180
+ "Scenario": "Conservative",
181
+ "Projected Margin %": round(conservative_margin, 1),
182
+ "Success Probability %": round(conservative_success, 1),
183
+ "Delivery Risk": risk_level_label(conservative_risk),
184
+ "Risk Score": round(conservative_risk, 1),
185
+ "Projected Timeline (weeks)": int(round(baseline_timeline * 1.2)),
186
+ "Assumption": "Adds delivery buffer and stronger governance coverage.",
187
+ }
188
+ aggressive_risk = clamp(risk + 12, 4, 99)
189
+ aggressive_margin = clamp(margin + 3.8, 2, 55)
190
+ aggressive_success = clamp(success - 8.5, 4, 96)
191
+ aggressive = {
192
+ "Scenario": "Aggressive",
193
+ "Projected Margin %": round(aggressive_margin, 1),
194
+ "Success Probability %": round(aggressive_success, 1),
195
+ "Delivery Risk": risk_level_label(aggressive_risk),
196
+ "Risk Score": round(aggressive_risk, 1),
197
+ "Projected Timeline (weeks)": int(round(max(4, baseline_timeline * 0.85))),
198
+ "Assumption": "Timeline compression with lean staffing and tighter scope cuts.",
199
+ }
200
+ ordered = pd.DataFrame([conservative, baseline, aggressive])
201
+ model_summary = {
202
+ "baseline_margin": margin,
203
+ "baseline_risk_score": risk,
204
+ "baseline_success": success,
205
+ "timeline_pressure": timeline_pressure_score(inputs),
206
+ }
207
+ return ordered, model_summary
208
+
209
+
210
+ def compute_capacity_impact(inputs: Dict[str, Any], historical_df: pd.DataFrame) -> Dict[str, Any]:
211
+ recent = historical_df[historical_df["year"] >= 2023].copy()
212
+ if recent.empty:
213
+ recent = historical_df.copy()
214
+ avg_team_size = float(recent["team_size"].mean())
215
+ active_reference = max(5, int(round(len(recent) * 0.45)))
216
+ org_capacity = max(40, int(round(avg_team_size * active_reference * 1.42)))
217
+ current_committed = int(round(avg_team_size * active_reference * 0.88))
218
+ projected_committed = current_committed + inputs["team_size"]
219
+ current_util = (current_committed / org_capacity) * 100
220
+ projected_util = (projected_committed / org_capacity) * 100
221
+
222
+ high_risk_recent = recent[recent["delivery_risk_score"] >= 60]
223
+ risk_before = (len(high_risk_recent) / len(recent)) * 100 if len(recent) else 0
224
+ candidate_high_risk = compute_risk_score(inputs) >= 60
225
+ risk_after = ((len(high_risk_recent) + (1 if candidate_high_risk else 0)) / (len(recent) + 1)) * 100
226
+
227
+ bottleneck = "No immediate bottleneck detected"
228
+ if projected_util >= 90:
229
+ bottleneck = "Critical staffing contention across platform and data engineering"
230
+ elif projected_util >= 80:
231
+ bottleneck = "Moderate contention in solution architecture and QA"
232
+ elif inputs["dependencies"] >= 4:
233
+ bottleneck = "Dependency management likely to become portfolio constraint"
234
+
235
+ return {
236
+ "org_capacity_slots": org_capacity,
237
+ "current_committed_slots": current_committed,
238
+ "projected_committed_slots": projected_committed,
239
+ "current_utilization_pct": round(current_util, 1),
240
+ "projected_utilization_pct": round(projected_util, 1),
241
+ "utilization_delta_pct": round(projected_util - current_util, 1),
242
+ "risk_concentration_before_pct": round(risk_before, 1),
243
+ "risk_concentration_after_pct": round(risk_after, 1),
244
+ "risk_concentration_delta_pct": round(risk_after - risk_before, 1),
245
+ "portfolio_bottleneck": bottleneck,
246
+ }
247
+
248
+
249
+ def compute_similarity_distance(inputs: Dict[str, Any], row: pd.Series) -> float:
250
+ budget_norm = abs(inputs["budget"] - float(row["budget"])) / 2000000
251
+ team_norm = abs(inputs["team_size"] - float(row["team_size"])) / 30
252
+ timeline_norm = abs(inputs["timeline_weeks"] - float(row["timeline_weeks"])) / 52
253
+ dep_norm = abs(inputs["dependencies"] - float(row["dependencies"])) / 5
254
+ complexity_pen = 0 if row["scope_complexity"] == inputs["scope_complexity"] else 0.2
255
+ tier_pen = 0 if row["client_tier"] == inputs["client_tier"] else 0.12
256
+ tech_pen = 0 if row["tech_risk"] == inputs["tech_risk"] else 0.14
257
+ return budget_norm * 0.32 + team_norm * 0.2 + timeline_norm * 0.18 + dep_norm * 0.12 + complexity_pen + tier_pen + tech_pen
258
+
259
+
260
+ def find_similar_projects(inputs: Dict[str, Any], historical_df: pd.DataFrame, top_n: int = 5) -> pd.DataFrame:
261
+ df = historical_df.copy()
262
+ df["similarity_distance"] = df.apply(lambda row: compute_similarity_distance(inputs, row), axis=1)
263
+ df = df.sort_values("similarity_distance", ascending=True).head(top_n)
264
+ show_cols = [
265
+ "project_id",
266
+ "name",
267
+ "scope_complexity",
268
+ "budget",
269
+ "team_size",
270
+ "timeline_weeks",
271
+ "tech_risk",
272
+ "client_tier",
273
+ "dependencies",
274
+ "actual_margin_pct",
275
+ "success_score",
276
+ "delivery_risk_score",
277
+ "outcome",
278
+ "year",
279
+ "similarity_distance",
280
+ ]
281
+ return pd.DataFrame(df[show_cols])
282
+
283
+
284
+ def build_gemini_prompt(inputs: Dict[str, Any], scenario_df: pd.DataFrame, capacity: Dict[str, Any], similar: pd.DataFrame) -> str:
285
+ scenario_lines = []
286
+ for _, row in scenario_df.iterrows():
287
+ scenario_lines.append(
288
+ f"- {row['Scenario']}: margin={row['Projected Margin %']}%, success={row['Success Probability %']}%, "
289
+ f"risk={row['Delivery Risk']} ({row['Risk Score']}), timeline={row['Projected Timeline (weeks)']} weeks"
290
+ )
291
+ similar_lines = []
292
+ for _, row in similar.iterrows():
293
+ similar_lines.append(
294
+ f"- {row['name']} ({int(row['year'])}): margin={row['actual_margin_pct']}%, success={row['success_score']}, "
295
+ f"risk={row['delivery_risk_score']}, outcome={row['outcome']}, distance={round(float(row['similarity_distance']), 3)}"
296
+ )
297
+ prompt = f"""
298
+ You are an enterprise deal desk and PMO strategy advisor.
299
+ Evaluate the candidate project and return practical recommendations.
300
+ Use concise business language with actionable bullets.
301
+
302
+ Candidate project:
303
+ - Name: {inputs['project_name']}
304
+ - Scope complexity: {inputs['scope_complexity']}
305
+ - Budget: ${inputs['budget']:,.0f}
306
+ - Team size: {inputs['team_size']}
307
+ - Timeline: {inputs['timeline_weeks']} weeks
308
+ - Technology risk: {inputs['tech_risk']}
309
+ - Client tier: {inputs['client_tier']}
310
+ - Dependencies: {inputs['dependencies']}
311
+
312
+ Scenarios:
313
+ {chr(10).join(scenario_lines)}
314
+
315
+ Capacity context:
316
+ - Current utilization: {capacity['current_utilization_pct']}%
317
+ - Projected utilization: {capacity['projected_utilization_pct']}%
318
+ - Risk concentration after add: {capacity['risk_concentration_after_pct']}%
319
+ - Bottleneck: {capacity['portfolio_bottleneck']}
320
+
321
+ Nearest historical projects:
322
+ {chr(10).join(similar_lines)}
323
+
324
+ Provide only these sections:
325
+ 1) Recommended Path (3 bullets)
326
+ 2) Scope/Pricing Adjustments (3 bullets)
327
+ 3) Risk Mitigations and Phasing (3 bullets)
328
+ 4) Executive Call (single sentence)
329
+ """.strip()
330
+ return prompt
331
+
332
+
333
+ def call_gemini(prompt: str, api_key: Optional[str]) -> Optional[str]:
334
+ if not api_key:
335
+ return None
336
+ try:
337
+ response = requests.post(
338
+ f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={api_key}",
339
+ json={"contents": [{"parts": [{"text": prompt}]}]},
340
+ timeout=25,
341
+ )
342
+ if response.status_code != 200:
343
+ return None
344
+ payload = response.json()
345
+ candidates = payload.get("candidates")
346
+ if not candidates:
347
+ return None
348
+ parts = candidates[0].get("content", {}).get("parts", [])
349
+ if not parts:
350
+ return None
351
+ text = parts[0].get("text")
352
+ return text.strip() if text else None
353
+ except Exception:
354
+ return None
355
+
356
+
357
+ def build_heuristic_recommendations(
358
+ inputs: Dict[str, Any], scenario_df: pd.DataFrame, capacity: Dict[str, Any], similar: pd.DataFrame
359
+ ) -> List[str]:
360
+ baseline = scenario_df[scenario_df["Scenario"] == "Baseline"].iloc[0].to_dict()
361
+ recs: List[str] = []
362
+ if baseline["Risk Score"] >= 70:
363
+ recs.append("Phase delivery into two releases, isolating highest-uncertainty integrations in release one.")
364
+ elif baseline["Risk Score"] >= 52:
365
+ recs.append("Gate scope through milestone acceptance and hold dependency owners to weekly commitments.")
366
+ else:
367
+ recs.append("Current structure is feasible; preserve core scope and avoid uncontrolled feature growth.")
368
+
369
+ if baseline["Projected Margin %"] < 16:
370
+ recs.append("Reprice by 8-12% or reduce non-core features to protect delivery margin above 18%.")
371
+ elif baseline["Projected Margin %"] > 30:
372
+ recs.append("Keep current pricing and include a value-based change-order framework for optional add-ons.")
373
+ else:
374
+ recs.append("Use baseline pricing with explicit assumptions tied to external dependency availability.")
375
+
376
+ util = capacity["projected_utilization_pct"]
377
+ if util >= 90:
378
+ recs.append("Delay mobilization by 2-4 weeks or pre-book specialist contractors to avoid a capacity breach.")
379
+ elif util >= 80:
380
+ recs.append("Reserve architecture and QA pods now to prevent portfolio contention.")
381
+ else:
382
+ recs.append("Capacity impact is manageable; prioritize fast kickoff with fixed governance cadence.")
383
+
384
+ completed_ratio = (similar["outcome"] == "completed").sum() / len(similar) if len(similar) else 0
385
+ if completed_ratio < 0.5:
386
+ recs.append("Similar projects underperformed historically; increase steering oversight and tighten acceptance criteria.")
387
+ else:
388
+ recs.append("Comparable projects show positive precedent; proceed with disciplined execution controls.")
389
+
390
+ if inputs["dependencies"] >= 4:
391
+ recs.append("Add a dedicated dependency manager and pre-negotiate escalation SLAs with upstream teams.")
392
+ return recs
393
+
394
+
395
+ def parse_ai_to_bullets(text: str) -> List[str]:
396
+ lines = [line.strip() for line in text.splitlines() if line.strip()]
397
+ bullets: List[str] = []
398
+ for line in lines:
399
+ if line.startswith("-"):
400
+ bullets.append(line[1:].strip())
401
+ elif line[0].isdigit() and ")" in line[:4]:
402
+ bullets.append(line)
403
+ elif line.lower().startswith("executive call"):
404
+ bullets.append(line)
405
+ return bullets[:12] if bullets else lines[:12]
406
+
407
+
408
+ def enforce_rate_limit(max_requests: int = 8, window_seconds: int = 60) -> Tuple[bool, int]:
409
+ now_ts = datetime.utcnow().timestamp()
410
+ existing = st.session_state.get("request_timestamps", [])
411
+ active = [ts for ts in existing if now_ts - ts <= window_seconds]
412
+ if len(active) >= max_requests:
413
+ st.session_state.request_timestamps = active
414
+ return False, 0
415
+ active.append(now_ts)
416
+ st.session_state.request_timestamps = active
417
+ return True, max_requests - len(active)
418
+
419
+
420
+ def run_simulation(historical_df: pd.DataFrame) -> None:
421
+ allowed, remaining = enforce_rate_limit(max_requests=8, window_seconds=60)
422
+ if not allowed:
423
+ st.warning("Rate limit reached: max 8 simulations per 60 seconds. Please wait and retry.")
424
+ return
425
+
426
+ inputs = get_inputs_from_state()
427
+ scenario_df, model_summary = simulate_scenarios(inputs)
428
+ capacity = compute_capacity_impact(inputs, historical_df)
429
+ similar = find_similar_projects(inputs, historical_df, top_n=5)
430
+
431
+ api_key = safe_get_api_key()
432
+ ai_response = None
433
+ if api_key:
434
+ prompt = build_gemini_prompt(inputs, scenario_df, capacity, similar)
435
+ ai_response = call_gemini(prompt, api_key)
436
+
437
+ if ai_response:
438
+ recommendations = parse_ai_to_bullets(ai_response)
439
+ recommendation_source = "Gemini AI"
440
+ else:
441
+ recommendations = build_heuristic_recommendations(inputs, scenario_df, capacity, similar)
442
+ recommendation_source = "Deterministic Heuristic"
443
+
444
+ st.session_state.simulation_result = {
445
+ "inputs": inputs,
446
+ "scenario_df": scenario_df,
447
+ "model_summary": model_summary,
448
+ "capacity": capacity,
449
+ "similar": similar,
450
+ "recommendations": recommendations,
451
+ "recommendation_source": recommendation_source,
452
+ "remaining_quota": remaining,
453
+ "ran_at": datetime.utcnow().isoformat(),
454
+ }
455
+
456
+
457
+ def render_header() -> None:
458
+ st.title("Simulation & Prescriptive Analysis Engine")
459
+ st.caption(
460
+ "What-if scenario simulator for enterprise projects/deals with multi-scenario outcomes, "
461
+ "capacity impact analysis, and prescriptive recommendations."
462
+ )
463
+
464
+
465
+ def render_left_panel() -> Tuple[bool, bool]:
466
+ st.subheader("Project Inputs")
467
+ st.text_input("Project name", key="project_name", placeholder="e.g., Northstar CRM + Data Platform Rollout")
468
+ st.selectbox("Scope complexity", options=["Low", "Medium", "High", "Critical"], key="scope_complexity")
469
+ st.slider("Estimated budget ($)", min_value=50000, max_value=2000000, step=10000, key="budget")
470
+ st.slider("Team size required", min_value=2, max_value=30, step=1, key="team_size")
471
+ st.slider("Timeline weeks", min_value=4, max_value=52, step=1, key="timeline_weeks")
472
+ st.selectbox("Technology risk", options=["Low", "Medium", "High"], key="tech_risk")
473
+ st.selectbox("Client tier", options=["Enterprise", "Mid-Market", "SMB"], key="client_tier")
474
+ st.slider("Dependencies on in-flight projects", min_value=0, max_value=5, step=1, key="dependencies")
475
+ c1, c2 = st.columns(2)
476
+ with c1:
477
+ load_clicked = st.button("Load Example", use_container_width=True)
478
+ with c2:
479
+ run_clicked = st.button("Run Simulation", type="primary", use_container_width=True)
480
+ return load_clicked, run_clicked
481
+
482
+
483
+ def render_scenario_tab(result: Dict[str, Any]) -> None:
484
+ scenario_df = result["scenario_df"]
485
+ baseline = scenario_df[scenario_df["Scenario"] == "Baseline"].iloc[0]
486
+ k1, k2, k3, k4 = st.columns(4)
487
+ k1.metric("Baseline Margin", f"{baseline['Projected Margin %']}%")
488
+ k2.metric("Baseline Success", f"{baseline['Success Probability %']}%")
489
+ k3.metric("Baseline Risk", f"{baseline['Delivery Risk']} ({baseline['Risk Score']})")
490
+ k4.metric("Baseline Timeline", f"{int(baseline['Projected Timeline (weeks)'])} weeks")
491
+ styled = scenario_df.copy()
492
+ styled["Projected Margin %"] = styled["Projected Margin %"].map(lambda x: f"{x}%")
493
+ styled["Success Probability %"] = styled["Success Probability %"].map(lambda x: f"{x}%")
494
+ st.dataframe(styled, use_container_width=True, hide_index=True)
495
+ st.caption("Conservative adds schedule buffer. Baseline uses entered assumptions. Aggressive trims timeline.")
496
+
497
+
498
+ def render_capacity_tab(result: Dict[str, Any]) -> None:
499
+ capacity = result["capacity"]
500
+ c1, c2, c3 = st.columns(3)
501
+ c1.metric("Current Utilization", f"{capacity['current_utilization_pct']}%")
502
+ c2.metric("Projected Utilization", f"{capacity['projected_utilization_pct']}%", f"+{capacity['utilization_delta_pct']}%")
503
+ c3.metric("Risk Concentration", f"{capacity['risk_concentration_after_pct']}%", f"+{capacity['risk_concentration_delta_pct']}%")
504
+ st.progress(min(capacity["projected_utilization_pct"] / 100, 1.0))
505
+ st.write(
506
+ f"Portfolio capacity slots: **{capacity['org_capacity_slots']}** | "
507
+ f"Committed after project: **{capacity['projected_committed_slots']}**"
508
+ )
509
+ st.info(f"Potential bottleneck: {capacity['portfolio_bottleneck']}")
510
+
511
+
512
+ def render_recommendation_tab(result: Dict[str, Any]) -> None:
513
+ st.write(f"Recommendation source: **{result['recommendation_source']}**")
514
+ for rec in result["recommendations"]:
515
+ st.write(f"- {rec}")
516
+
517
+
518
+ def render_historical_tab(result: Dict[str, Any]) -> None:
519
+ similar = result["similar"].copy()
520
+ show = similar.copy()
521
+ show["budget"] = show["budget"].map(lambda x: f"${x:,.0f}")
522
+ show["actual_margin_pct"] = show["actual_margin_pct"].map(lambda x: f"{x}%")
523
+ show["similarity_distance"] = show["similarity_distance"].map(lambda x: round(float(x), 3))
524
+ st.dataframe(show, use_container_width=True, hide_index=True)
525
+ completed = (similar["outcome"] == "completed").sum()
526
+ avg_margin = float(similar["actual_margin_pct"].mean()) if len(similar) else 0
527
+ avg_success = float(similar["success_score"].mean()) if len(similar) else 0
528
+ st.caption(
529
+ f"Top matches: {len(similar)} | Completed: {completed} | Avg historical margin: {avg_margin:.1f}% | "
530
+ f"Avg success score: {avg_success:.1f}"
531
+ )
532
+
533
+
534
+ def render_right_panel(result: Optional[Dict[str, Any]]) -> None:
535
+ st.subheader("Simulation Output")
536
+ if not result:
537
+ st.info("Run simulation to view scenario analysis, capacity impact, recommendations, and historical comparisons.")
538
+ return
539
+ st.caption(f"Last run: {result['ran_at']} UTC | Remaining quota in rolling window: {result['remaining_quota']}")
540
+ tab1, tab2, tab3, tab4 = st.tabs(
541
+ ["Scenario Analysis", "Capacity Impact", "Prescriptive Recommendations", "Historical Comparisons"]
542
+ )
543
+ with tab1:
544
+ render_scenario_tab(result)
545
+ with tab2:
546
+ render_capacity_tab(result)
547
+ with tab3:
548
+ render_recommendation_tab(result)
549
+ with tab4:
550
+ render_historical_tab(result)
551
+
552
+
553
+ def render_dataset_section(df: pd.DataFrame) -> None:
554
+ with st.expander("Sample Dataset", expanded=False):
555
+ st.dataframe(df, use_container_width=True, hide_index=True)
556
+ csv_bytes = df.to_csv(index=False).encode("utf-8")
557
+ st.download_button(
558
+ label="Download historical_projects.csv",
559
+ data=csv_bytes,
560
+ file_name="historical_projects.csv",
561
+ mime="text/csv",
562
+ )
563
+
564
+
565
+ def main() -> None:
566
+ initialize_state()
567
+ historical_df = load_historical_data()
568
+ render_header()
569
+ left, right = st.columns([1, 1.7], gap="large")
570
+ with left:
571
+ load_clicked, run_clicked = render_left_panel()
572
+ if load_clicked:
573
+ load_example_values()
574
+ st.success("Example values loaded.")
575
+ if run_clicked:
576
+ run_simulation(historical_df)
577
+ with right:
578
+ render_right_panel(st.session_state.simulation_result)
579
+ render_dataset_section(historical_df)
580
+
581
+
582
+ if __name__ == "__main__":
583
+ main()
data/historical_projects.csv ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 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
2
+ P-1001,Orion ERP Migration,High,950000,16,34,Medium,Enterprise,4,19.5,81,58,completed,2021
3
+ P-1002,Vista CRM Rollout,Medium,420000,7,18,Low,Mid-Market,1,24.1,88,29,completed,2022
4
+ P-1003,Helix Data Lake Foundation,Critical,1450000,22,40,High,Enterprise,5,11.8,62,82,partial,2023
5
+ P-1004,Nova Ecommerce Replatform,High,780000,12,26,Medium,Mid-Market,3,17.2,74,61,partial,2021
6
+ P-1005,Atlas HRIS Integration,Medium,310000,6,16,Low,SMB,1,27.4,91,24,completed,2024
7
+ P-1006,Beacon AI Service Desk,High,690000,11,24,High,Enterprise,2,14.6,69,68,partial,2024
8
+ P-1007,Stratus Billing Modernization,Medium,560000,9,20,Medium,Enterprise,2,21.9,83,44,completed,2022
9
+ P-1008,Aurora Supply Chain Control Tower,Critical,1820000,27,46,High,Enterprise,5,8.9,54,89,failed,2023
10
+ P-1009,Quasar Marketing Automation,Low,180000,4,10,Low,SMB,0,31.8,93,18,completed,2025
11
+ P-1010,Pulse Clinical Data Hub,High,860000,13,28,Medium,Enterprise,4,16.5,73,63,partial,2025
12
+ P-1011,Vertex Finance Close Platform,Medium,470000,8,19,Medium,Mid-Market,2,22.6,84,39,completed,2020
13
+ P-1012,Summit IoT Telemetry Pipeline,Critical,1260000,20,38,High,Mid-Market,4,10.2,59,80,failed,2022
14
+ P-1013,Meridian Customer 360,High,740000,12,25,Medium,Enterprise,3,18.3,78,57,completed,2024
15
+ P-1014,Lumen Data Governance Program,Medium,520000,9,22,Low,Enterprise,3,20.7,82,42,completed,2021
16
+ P-1015,Titan Claims Workflow Automation,High,670000,10,23,High,Mid-Market,2,15.1,71,66,partial,2023
17
+ P-1016,Horizon Field Ops Mobile Suite,Medium,390000,7,17,Medium,SMB,1,23.4,86,35,completed,2025
18
+ P-1017,Zenith Multi-Cloud Cost Engine,Critical,1580000,24,44,High,Enterprise,5,9.7,57,85,failed,2024
19
+ P-1018,Delta Procurement Portal,Low,230000,5,12,Low,Mid-Market,1,29.2,90,22,completed,2020
20
+ P-1019,Prism AI Recommendation Layer,High,810000,14,27,High,Enterprise,3,13.8,67,72,partial,2025
21
+ P-1020,Cascade Legacy App Decommission,Medium,350000,6,15,Medium,Mid-Market,2,24.7,87,33,completed,2022
22
+ P-1021,Ember Partner API Platform,High,730000,11,24,Medium,Enterprise,3,18.9,79,55,completed,2023
23
+ P-1022,Forge Enterprise CMS Consolidation,Medium,480000,8,20,Low,Enterprise,2,22.1,85,37,completed,2024
24
+ P-1023,Sierra Warehouse Robotics Interface,Critical,1340000,21,39,High,Mid-Market,4,11.3,60,78,partial,2021
25
+ P-1024,Radius Loan Origination Revamp,High,900000,15,30,Medium,Enterprise,4,17.0,75,62,partial,2025
26
+ P-1025,Echo Self-Service Support Portal,Low,160000,3,9,Low,SMB,0,32.6,95,16,completed,2023
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ streamlit
2
+ pandas
3
+ requests