Spaces:
Runtime error
Runtime error
Upload 9 files
Browse filesFiles changed (9)
- app.pyAdded+127
- page1_intro.pyAdded+289
- page2_risk_register.pyAdded+310
- page3_simulation.pyAdded+863
- page4_results.pyAdded+951
- page5_optimisation.pyAdded+320
- requirements.txt+5-3
- simulation_engine.pyAdded+443
- styles.pyAdded+252
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127"""app.py — Main Streamlit entry point for No-CelH Self-Learning RMSRun: streamlit run app.pyHugging Face Spaces: set SDK=streamlit, app_file=app.py"""
import streamlit as st
st.set_page_config( page_title="No-CelH · Self-Learning RMS", page_icon="🛃", layout="wide", initial_sidebar_state="expanded", menu_items={ "Get Help": "https://www.wcoomd.org/en/topics/enforcement-and-compliance/activities-and-programmes/risk-management.aspx", "Report a bug": None, "About": "No-CelH: Self-Learning RMS — WCO Accredited Expert Simulation Tool\n\nBuilt on DATE + gATE Active Learning (Kim et al. 2022, IEEE TKDE)", },)
import page1_introimport page2_risk_registerimport page3_simulationimport page4_resultsimport page5_optimisationfrom styles import WCO_GOLD, WCO_NAVY, WCO_BORDER, WCO_CARD_BG, WCO_MUTED, WCO_RED, WCO_GREEN
PAGES = { "🏠 Introduction & Architecture": page1_intro, "📋 Risk Register & Matrix": page2_risk_register, "🔄 Simulation Engine": page3_simulation, "📊 Simulation Results": page4_results, "🏆 Bandwidth Optimisation": page5_optimisation,}
def sidebar(): with st.sidebar: st.markdown(f""" <div style="text-align:center;padding:20px 10px 14px;"> <div style="font-size:42px;">🛃</div> <div style="color:{WCO_GOLD};font-family:'Playfair Display',Georgia,serif; font-size:16px;font-weight:700;margin-top:8px;line-height:1.3;"> No-CelH<br/>Self-Learning RMS </div> <div style="color:{WCO_MUTED};font-size:10px;margin-top:6px; font-family:'IBM Plex Mono',monospace;letter-spacing:0.06em;"> WCO ACCREDITED · v2.0 </div> </div> <hr style="border-color:{WCO_BORDER};margin:0 0 16px;"/> """, unsafe_allow_html=True)
st.markdown(f""" <div style="color:{WCO_GOLD};font-size:11px;font-weight:600; letter-spacing:0.1em;text-transform:uppercase; padding:0 4px;margin-bottom:8px;">Navigation</div> """, unsafe_allow_html=True)
selected = st.radio("", list(PAGES.keys()), key="nav_page", label_visibility="collapsed")
st.markdown(f"<hr style='border-color:{WCO_BORDER};margin:16px 0;'/>", unsafe_allow_html=True)
# Session state status panel sim_ready = "sim_df" in st.session_state st.markdown(f""" <div style="background:{WCO_CARD_BG};border:1px solid {WCO_BORDER}; border-radius:10px;padding:14px;"> <div style="color:{WCO_GOLD};font-size:11px;font-weight:600; text-transform:uppercase;letter-spacing:0.08em;margin-bottom:10px;"> Session Status </div> <div style="font-size:12px;line-height:2.1;color:#8BAAD4;"> <span style="color:{'#44CC88' if sim_ready else WCO_MUTED};"> {'✅' if sim_ready else '⬜'}</span> Simulation Run<br/> <span style="color:{'#44CC88' if 'rule_weights' in st.session_state else WCO_MUTED};"> {'✅' if 'rule_weights' in st.session_state else '⬜'}</span> Weights Configured<br/> <span style="color:{'#44CC88' if 'sim_efficiency' in st.session_state else WCO_MUTED};"> {'✅' if 'sim_efficiency' in st.session_state else '⬜'}</span> Results Available </div> </div> """, unsafe_allow_html=True)
if sim_ready: df = st.session_state.sim_df eff = st.session_state.get("sim_efficiency", {}).get("hybrid", {}) st.markdown(f""" <div style="background:{WCO_CARD_BG};border:1px solid {WCO_BORDER}; border-radius:10px;padding:14px;margin-top:10px;"> <div style="color:{WCO_GOLD};font-size:11px;font-weight:600; text-transform:uppercase;letter-spacing:0.08em;margin-bottom:10px;"> Last Simulation </div> <div style="font-size:12px;line-height:2.1;color:#8BAAD4;"> 📦 Bills: <b style="color:#D0DCF0;">{len(df):,}</b><br/> 🔴 RED: <b style="color:{WCO_RED};">{(df['channel']=='RED').sum()}</b><br/> 🟡 YEL: <b style="color:{WCO_GOLD};">{(df['channel']=='YELLOW').sum()}</b><br/> 🟢 GRN: <b style="color:{WCO_GREEN};">{(df['channel']=='GREEN').sum()}</b><br/> 🚨 Detected: <b style="color:{WCO_RED};"> {(df['inspection_outcome']=='FRAUD_DETECTED').sum()}</b><br/> 📈 Efficiency: <b style="color:{WCO_GREEN};"> {eff.get('efficiency_index',0):.3f}</b> </div> </div> """, unsafe_allow_html=True)
st.markdown(f""" <hr style="border-color:{WCO_BORDER};margin:16px 0 10px;"/> <div style="color:{WCO_MUTED};font-size:10px;text-align:center;line-height:1.7;padding:0 4px;"> Based on: Kim et al. (2022)<br/> <i>Active Learning for Human-in-the-Loop Customs Inspection</i><br/> IEEE TKDE · WCO Compendium<br/> <span style="color:{WCO_GOLD};">WCO BACUDA Initiative</span> </div> """, unsafe_allow_html=True)
return selected
def main(): selected = sidebar() PAGES[selected].show()
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289"""page1_intro.py — Introduction, How to Use, Objectives, Architecture Diagram"""
import streamlit as stfrom styles import (inject_global_css, page_header, metric_row, WCO_GOLD, WCO_BLUE, WCO_GREEN, WCO_RED, WCO_CARD_BG, WCO_BORDER, WCO_MUTED)
ARCH_SVG = """<svg viewBox="0 0 980 620" xmlns="http://www.w3.org/2000/svg" style="width:100%;border-radius:14px;background:#070E1C;"> <defs> <linearGradient id="hbg" x1="0" y1="0" x2="1" y2="1"> <stop offset="0%" stop-color="#003087"/><stop offset="100%" stop-color="#001040"/> </linearGradient> <linearGradient id="gold" x1="0" y1="0" x2="1" y2="0"> <stop offset="0%" stop-color="#C8A951"/><stop offset="100%" stop-color="#FFD966"/> </linearGradient> <marker id="arr" markerWidth="9" markerHeight="9" refX="7" refY="3" orient="auto"> <path d="M0,0 L0,6 L9,3z" fill="#C8A951"/> </marker> <marker id="arrb" markerWidth="9" markerHeight="9" refX="7" refY="3" orient="auto"> <path d="M0,0 L0,6 L9,3z" fill="#66AAFF"/> </marker> <marker id="arrg" markerWidth="9" markerHeight="9" refX="7" refY="3" orient="auto"> <path d="M0,0 L0,6 L9,3z" fill="#44CC88"/> </marker> <marker id="arrp" markerWidth="9" markerHeight="9" refX="7" refY="3" orient="auto"> <path d="M0,0 L0,6 L9,3z" fill="#CC77FF"/> </marker> <filter id="glow"><feGaussianBlur stdDeviation="4" result="b"/> <feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge></filter> </defs>
<!-- background --> <rect width="980" height="620" fill="#070E1C" rx="14"/> <rect width="980" height="3" fill="url(#gold)" rx="2"/>
<!-- title bar --> <text x="490" y="32" text-anchor="middle" font-family="Georgia,serif" font-size="17" fill="#C8A951" font-weight="bold">No-CelH · Self-Learning RMS Architecture</text> <text x="490" y="52" text-anchor="middle" font-family="monospace" font-size="10" fill="#557"> DATE Exploitation ◈ gATE Exploration ◈ Human-in-the-Loop ◈ WCO Compendium </text>
<!-- ══════════════════════ ROW 1 BOXES ══════════════════════ --> <!-- [1] Import Declarations --> <rect x="18" y="74" width="130" height="64" rx="9" fill="#0A1E4A" stroke="#C8A951" stroke-width="1.5"/> <text x="83" y="97" text-anchor="middle" font-family="Georgia" font-size="13" fill="#C8A951">📦 Import</text> <text x="83" y="114" text-anchor="middle" font-family="Georgia" font-size="11" fill="#AAC">Declarations</text> <text x="83" y="128" text-anchor="middle" font-family="monospace" font-size="9" fill="#667">1,000 Bills / Batch</text>
<!-- [2] Risk Register --> <rect x="180" y="74" width="138" height="64" rx="9" fill="#0A1E4A" stroke="#0066CC" stroke-width="1.5"/> <text x="249" y="97" text-anchor="middle" font-family="Georgia" font-size="13" fill="#66AAFF">📋 Risk Register</text> <text x="249" y="114" text-anchor="middle" font-family="Georgia" font-size="11" fill="#AAC">5 Risk Areas · Rules</text> <text x="249" y="128" text-anchor="middle" font-family="monospace" font-size="9" fill="#667">Weights · Targets</text>
<!-- [3] DATE Scoring Engine --> <rect x="356" y="64" width="170" height="84" rx="9" fill="#071A10" stroke="#00843D" stroke-width="2" filter="url(#glow)"/> <text x="441" y="89" text-anchor="middle" font-family="Georgia" font-size="14" fill="#44CC88" font-weight="bold">🧠 DATE Engine</text> <text x="441" y="107" text-anchor="middle" font-family="Georgia" font-size="11" fill="#AAC">Exploitation: ŷᶜˡˢ + ŷʳᵉᵛ</text> <text x="441" y="122" text-anchor="middle" font-family="monospace" font-size="9" fill="#44CC88">Fraud Score × Revenue</text> <text x="441" y="136" text-anchor="middle" font-family="monospace" font-size="9" fill="#557">Risk Scoring Pipeline</text>
<!-- [4] Hybrid Selector --> <rect x="566" y="64" width="168" height="84" rx="9" fill="#1A1000" stroke="#C8A951" stroke-width="2" filter="url(#glow)"/> <text x="650" y="89" text-anchor="middle" font-family="Georgia" font-size="14" fill="#C8A951" font-weight="bold">⚖️ Hybrid Selector</text> <text x="650" y="107" text-anchor="middle" font-family="Georgia" font-size="11" fill="#AAC">90% DATE + 10% gATE</text> <text x="650" y="122" text-anchor="middle" font-family="monospace" font-size="9" fill="#C8A951">Bandwidth: 10% (adj.)</text> <text x="650" y="136" text-anchor="middle" font-family="monospace" font-size="9" fill="#557">Optimal Selection</text>
<!-- [5] gATE Engine --> <rect x="356" y="178" width="170" height="74" rx="9" fill="#110A1E" stroke="#9933CC" stroke-width="1.8"/> <text x="441" y="200" text-anchor="middle" font-family="Georgia" font-size="13" fill="#CC77FF" font-weight="bold">🔍 gATE Engine</text> <text x="441" y="217" text-anchor="middle" font-family="Georgia" font-size="11" fill="#AAC">unc_i × log(ŷʳᵉᵛ + ε)</text> <text x="441" y="232" text-anchor="middle" font-family="monospace" font-size="9" fill="#CC77FF">K-means++ Diversity</text> <text x="441" y="244" text-anchor="middle" font-family="monospace" font-size="9" fill="#557">Concept Drift Guard</text>
<!-- CHANNEL BOXES --> <!-- RED --> <rect x="775" y="60" width="100" height="44" rx="7" fill="#1E0008" stroke="#C8102E" stroke-width="1.8"/> <text x="825" y="79" text-anchor="middle" font-family="Georgia" font-size="13" fill="#FF4466" font-weight="bold">🔴 RED</text> <text x="825" y="96" text-anchor="middle" font-family="monospace" font-size="9" fill="#FF8899">Physical Exam</text> <!-- YELLOW --> <rect x="775" y="111" width="100" height="44" rx="7" fill="#1A0F00" stroke="#F5A800" stroke-width="1.8"/> <text x="825" y="130" text-anchor="middle" font-family="Georgia" font-size="13" fill="#FFD700" font-weight="bold">🟡 YELLOW</text> <text x="825" y="147" text-anchor="middle" font-family="monospace" font-size="9" fill="#FFE066">Doc Check</text> <!-- GREEN --> <rect x="775" y="162" width="100" height="44" rx="7" fill="#00100A" stroke="#00843D" stroke-width="1.8"/> <text x="825" y="181" text-anchor="middle" font-family="Georgia" font-size="13" fill="#44CC88" font-weight="bold">🟢 GREEN</text> <text x="825" y="198" text-anchor="middle" font-family="monospace" font-size="9" fill="#88EEBB">Facilitated</text>
<!-- ══════════ ARROWS ROW 1 ══════════ --> <line x1="148" y1="106" x2="178" y2="106" stroke="#C8A951" stroke-width="1.6" marker-end="url(#arr)"/> <line x1="318" y1="106" x2="354" y2="106" stroke="#C8A951" stroke-width="1.6" marker-end="url(#arr)"/> <line x1="526" y1="106" x2="564" y2="106" stroke="#C8A951" stroke-width="1.6" marker-end="url(#arr)"/> <line x1="734" y1="106" x2="773" y2="106" stroke="#C8A951" stroke-width="1.6" marker-end="url(#arr)"/> <!-- DATE → gATE (vertical) --> <line x1="441" y1="148" x2="441" y2="178" stroke="#44CC88" stroke-width="1.3" stroke-dasharray="5,3" marker-end="url(#arrg)"/> <!-- gATE → Hybrid --> <path d="M526 215 Q560 215 560 148 Q560 106 564 106" stroke="#CC77FF" stroke-width="1.4" stroke-dasharray="5,3" fill="none" marker-end="url(#arrp)"/>
<!-- ══════════════ ROW 2: OFFICER INSPECTION ══════════════ --> <rect x="566" y="290" width="168" height="64" rx="9" fill="#0A1832" stroke="#0066CC" stroke-width="1.5"/> <text x="650" y="313" text-anchor="middle" font-family="Georgia" font-size="13" fill="#66AAFF" font-weight="bold">👮 Officer Inspection</text> <text x="650" y="330" text-anchor="middle" font-family="Georgia" font-size="11" fill="#AAC">Labels: yᶜˡˢ + yʳᵉᵛ</text> <text x="650" y="344" text-anchor="middle" font-family="monospace" font-size="9" fill="#667">Human-in-the-Loop</text>
<!-- Channels → Officer --> <line x1="825" y1="206" x2="825" y2="298" stroke="#66AAFF" stroke-width="1.3" stroke-dasharray="4,3"/> <line x1="825" y1="298" x2="736" y2="316" stroke="#66AAFF" stroke-width="1.3" marker-end="url(#arrb)"/>
<!-- ══════════════ ROW 2: OFFENCE DATABASE ══════════════ --> <rect x="356" y="290" width="170" height="64" rx="9" fill="#1A0008" stroke="#C8102E" stroke-width="1.5"/> <text x="441" y="313" text-anchor="middle" font-family="Georgia" font-size="13" fill="#FF6688" font-weight="bold">🗄️ Offence Database</text> <text x="441" y="330" text-anchor="middle" font-family="Georgia" font-size="11" fill="#AAC">Augmented Real-Time</text> <text x="441" y="344" text-anchor="middle" font-family="monospace" font-size="9" fill="#667">5 Risk Categories</text>
<!-- Officer → Offence DB --> <line x1="566" y1="322" x2="528" y2="322" stroke="#FF4466" stroke-width="1.5" marker-end="url(#arr)"/>
<!-- ══════════ FEEDBACK LOOPS ══════════ --> <!-- Offence DB → DATE (model update) --> <path d="M441 290 Q441 260 441 252 Q441 148 526 148" stroke="#44CC88" stroke-width="1.4" stroke-dasharray="6,3" fill="none" marker-end="url(#arrg)"/> <!-- Offence DB → Risk Register (weight update) --> <path d="M356 322 Q249 322 249 160 Q249 138 318 138" stroke="#66AAFF" stroke-width="1.3" stroke-dasharray="6,3" fill="none" marker-end="url(#arrb)"/>
<!-- feedback labels --> <text x="480" y="258" font-family="monospace" font-size="9" fill="#44CC88">Model Update</text> <text x="255" y="275" font-family="monospace" font-size="9" fill="#66AAFF">Weight Update</text>
<!-- ══════════════ BOTTOM METRICS BAND ══════════════ --> <rect x="18" y="390" width="290" height="90" rx="9" fill="#0F1C35" stroke="#C8102E" stroke-width="1.2"/> <text x="163" y="413" text-anchor="middle" font-family="Georgia" font-size="12" fill="#FF4466" font-weight="bold">📉 Static Model (Baseline)</text> <text x="163" y="433" text-anchor="middle" font-family="Georgia" font-size="11" fill="#AAC">Selection Rate: 10% | Detection: 4.1%</text> <text x="163" y="452" text-anchor="middle" font-family="Georgia" font-size="11" fill="#AAC">Efficiency Index: <tspan font-weight="bold" fill="#FF4466">0.41</tspan></text> <text x="163" y="470" text-anchor="middle" font-family="monospace" font-size="9" fill="#667">Exploitation-only · No Learning</text>
<rect x="328" y="390" width="290" height="90" rx="9" fill="#0F1C35" stroke="#00843D" stroke-width="2"/> <text x="473" y="413" text-anchor="middle" font-family="Georgia" font-size="12" fill="#44CC88" font-weight="bold">📈 Hybrid Model (No-CelH)</text> <text x="473" y="433" text-anchor="middle" font-family="Georgia" font-size="11" fill="#AAC">Selection Rate: 10% | Detection: 8.2%</text> <text x="473" y="452" text-anchor="middle" font-family="Georgia" font-size="11" fill="#AAC">Efficiency Index: <tspan font-weight="bold" fill="#44CC88">0.82</tspan></text> <text x="473" y="470" text-anchor="middle" font-family="monospace" font-size="9" fill="#44CC88">DATE 90% + gATE 10% · Self-Learning</text>
<!-- improvement arrow --> <line x1="320" y1="432" x2="326" y2="432" stroke="#C8A951" stroke-width="2" marker-end="url(#arr)"/> <text x="323" y="427" text-anchor="middle" font-family="Georgia" font-size="10" fill="#C8A951">+100%</text>
<rect x="638" y="390" width="322" height="90" rx="9" fill="#0F1C35" stroke="#9933CC" stroke-width="1.2"/> <text x="799" y="413" text-anchor="middle" font-family="Georgia" font-size="12" fill="#CC77FF" font-weight="bold">🔬 Discovery Barometer</text> <text x="799" y="433" text-anchor="middle" font-family="Georgia" font-size="11" fill="#AAC">New Importers Discovered: ~10× more</text> <text x="799" y="452" text-anchor="middle" font-family="Georgia" font-size="11" fill="#AAC">New HS Codes Mapped: 2,000+ in 5 yrs</text> <text x="799" y="471" text-anchor="middle" font-family="monospace" font-size="9" fill="#CC77FF">Sequential Fraud Detection: ✓ Enabled</text>
<!-- ══════════════ FORMULA BAND ══════════════ --> <rect x="18" y="498" width="942" height="50" rx="8" fill="#0A1020" stroke="#1E3A6E" stroke-width="1"/> <text x="490" y="520" text-anchor="middle" font-family="monospace" font-size="11" fill="#C8A951"> Uncertainty: unc_i = −1.8 × |ŷᶜˡˢ − 0.5| + 1 Scale: S_i = unc_i × log(ŷʳᵉᵛ + ε) </text> <text x="490" y="538" text-anchor="middle" font-family="monospace" font-size="10" fill="#557"> Efficiency Index = Detection Rate / Selection Rate Reference: Kim et al. (2022) IEEE TKDE · WCO Risk Compendium </text>
<!-- WCO badge --> <rect x="370" y="562" width="240" height="30" rx="15" fill="#C8A951"/> <text x="490" y="582" text-anchor="middle" font-family="Georgia" font-size="11" fill="#003087" font-weight="bold"> 🌐 WCO Accredited Expert Framework </text></svg>"""
def show(): inject_global_css() page_header("🛃", "No-CelH: Self-Learning RMS", "WCO ACCREDITED · CUSTOMS RISK MANAGEMENT SYSTEM · ACTIVE LEARNING SIMULATION")
# ── KPI strip ───────────────────────────────────────────────── metric_row([ ("5", "Risk Areas", WCO_GOLD), ("1,000","Declarations / Run", WCO_BLUE), ("10%", "Interdiction Bandwidth", WCO_RED), ("0.82", "Target Efficiency Index", WCO_GREEN), ("2×", "Revenue vs Static", WCO_GOLD), ])
# ── Architecture SVG ────────────────────────────────────────── st.markdown('<div class="section-title">🏗️ System Architecture</div>', unsafe_allow_html=True) st.markdown(ARCH_SVG, unsafe_allow_html=True)
st.markdown("<br/>", unsafe_allow_html=True)
# ── Three info columns ──────────────────────────────────────── c1, c2, c3 = st.columns(3) with c1: st.markdown(""" <div class="wco-card"> <h3>🎯 Objectives</h3> <ul style="color:#D0DCF0;font-size:13px;line-height:2;padding-left:16px;"> <li>Demonstrate <b style="color:#C8A951;">self-learning RMS</b> vs static models</li> <li>Prove exploration + exploitation <b style="color:#44CC88;">hybrid superiority</b></li> <li>Optimise <b>10% interdiction bandwidth</b> dynamically</li> <li>Build offence database via Red/Yellow feedback</li> <li>Adapt to <b style="color:#CC77FF;">concept drift</b> in real-time</li> <li>WCO compendium risk scoring with 5 risk areas</li> </ul></div>""", unsafe_allow_html=True) with c2: st.markdown(""" <div class="wco-card"> <h3>📖 How to Use This App</h3> <div style="color:#D0DCF0;font-size:13px;line-height:2.0;"> <p><b style="color:#C8A951;">📋 Page 2 →</b> Configure 5-area Risk Register, 3×3 Matrix, rules & annual weights</p> <p><b style="color:#C8A951;">🔄 Page 3 →</b> Run live simulation — watch 1,000 bills routed in real-time</p> <p><b style="color:#C8A951;">📊 Page 4 →</b> Analyse offence DB growth, exploration gains, rule hit tables</p> <p><b style="color:#C8A951;">🏆 Page 5 →</b> Optimisation report — efficiency, accuracy, bandwidth ROI</p> </div></div>""", unsafe_allow_html=True) with c3: st.markdown(""" <div class="wco-card"> <h3>🔬 Recommended Exploration Strategy</h3> <div style="color:#D0DCF0;font-size:13px;line-height:2.0;"> <p><b style="color:#CC77FF;">bATE</b> — Best for customs context</p> <p>✅ Uncertainty-scaled gradient embeddings</p> <p>✅ Revenue-weighted diversity (K-means++)</p> <p>✅ Outperforms BADGE & random by large margin</p> <p>✅ Anomaly + probability-based hybrid sampling</p> <p style="color:#6B85AA;font-size:11px;">gATE adds gatekeeping randomness for adversarial robustness</p> </div></div>""", unsafe_allow_html=True)
# ── How RMS works ───────────────────────────────────────────── st.markdown('<div class="section-title">⚙️ How the Self-Learning Cycle Works</div>', unsafe_allow_html=True)
steps = [ ("1", "#C8A951", "📥 Ingest", "Batch of import declarations enters the scoring pipeline each week"), ("2", "#0066CC", "🧠 Score (DATE)", "Exploitation engine scores each bill: fraud probability ŷᶜˡˢ + revenue ŷʳᵉᵛ"), ("3", "#9933CC", "🔍 Explore (gATE)","Exploration engine identifies uncertain bills (unc_i near 0.5) for new knowledge"), ("4", "#C8A951", "⚖️ Hybrid Select", "10% bandwidth split: 90% exploitation + 10% exploration → RED/YELLOW/GREEN"), ("5", "#0066CC", "👮 Inspect", "Officers examine Red & Yellow — outcomes labelled (fraud / clean / doc-query)"), ("6", "#00843D", "🗄️ Feedback", "Confirmed frauds augment offence DB; rule weights auto-update → model retrains"), ] cols = st.columns(6) for i, (num, col, title, desc) in enumerate(steps): with cols[i]: st.markdown(f""" <div style="background:#0F1C35;border:1px solid {col};border-radius:10px; padding:16px 12px;text-align:center;height:160px;"> <div style="background:{col};color:#070E1C;border-radius:50%;width:28px;height:28px; line-height:28px;font-weight:700;margin:0 auto 10px;font-size:14px;">{num}</div> <div style="color:{col};font-weight:600;font-size:12px;margin-bottom:8px;">{title}</div> <div style="color:#8BAAD4;font-size:11px;line-height:1.5;">{desc}</div> </div>""", unsafe_allow_html=True)
st.markdown("<br/>", unsafe_allow_html=True)
# ── Scientific basis ────────────────────────────────────────── with st.expander("📚 Scientific Basis & Mathematical Formulas"): fc1, fc2 = st.columns(2) with fc1: st.markdown(""" <div class="wco-card-gold"> <h3>DATE Exploitation Engine</h3> <p style="color:#D0DCF0;font-size:13px;">Dual Attentive Tree-aware Embedding model optimises two objectives simultaneously:</p> <ul style="color:#D0DCF0;font-size:13px;line-height:2;"> <li><b style="color:#44CC88;">ŷᶜˡˢ</b> — Probability of fraudulent transaction</li> <li><b style="color:#44CC88;">ŷʳᵉᵛ</b> — Predicted additional revenue upon inspection</li> </ul> <p style="color:#C8A951;font-family:monospace;font-size:13px;"> h_θ(x) = σ(W · z_φ(x)) </p> </div>""", unsafe_allow_html=True) with fc2: st.markdown(""" <div class="wco-card-gold"> <h3>gATE Exploration Engine</h3> <p style="color:#D0DCF0;font-size:13px;">Selects uncertain, high-revenue, diverse bills via:</p> <ul style="color:#D0DCF0;font-size:13px;line-height:2;"> <li><b style="color:#CC77FF;">unc_i</b> = −1.8 × |ŷᶜˡˢ − 0.5| + 1</li> <li><b style="color:#CC77FF;">S_i</b> = unc_i × log(ŷʳᵉᵛ + ε)</li> <li>K-means++ seeding for batch diversity</li> </ul> <p style="color:#C8A951;font-family:monospace;font-size:13px;"> Efficiency Index = Detection Rate / Selection Rate </p> </div>""", unsafe_allow_html=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310"""page2_risk_register.py — Risk Register, 3×3 Matrix, Rules, Weights"""
import streamlit as stimport plotly.graph_objects as goimport pandas as pdfrom styles import (inject_global_css, page_header, metric_row, WCO_GOLD, WCO_BLUE, WCO_GREEN, WCO_RED, WCO_CARD_BG, WCO_BORDER, WCO_MUTED, WCO_GREY_BG)from simulation_engine import RISK_AREAS, get_default_weights
# ── Static risk matrix data ──────────────────────────────────────────────────RISK_MATRIX_DATA = { "Drugs & Narcotics": {"likelihood": 3, "impact": 3, "priority": 1, "color": "#C8102E"}, "Revenue Leakage": {"likelihood": 3, "impact": 2, "priority": 2, "color": "#F5A800"}, "IPR Enforcement": {"likelihood": 2, "impact": 2, "priority": 3, "color": "#9B59B6"}, "Environmental/Plastic Waste": {"likelihood": 2, "impact": 3, "priority": 4, "color": "#00843D"}, "Wildlife Smuggling": {"likelihood": 1, "impact": 3, "priority": 5, "color": "#E67E22"},}
RISK_PRIORITY_DATA = [ { "Priority": 1, "Risk Area": "Drugs & Narcotics", "Likelihood": "High (3)", "Impact": "High (3)", "Risk Level": "CRITICAL", "Strategy": "Exploit + Explore", "Annual Target": "Zero tolerance – 100% risk-score flagging", "WCO Reference": "Compendium Vol.1 Ch.3", }, { "Priority": 2, "Risk Area": "Revenue Leakage", "Likelihood": "High (3)", "Impact": "Medium (2)", "Risk Level": "HIGH", "Strategy": "DATE Exploitation", "Annual Target": "≥85% recovery rate on flagged shipments", "WCO Reference": "Compendium Vol.2 Ch.6", }, { "Priority": 3, "Risk Area": "IPR Enforcement", "Likelihood": "Medium (2)", "Impact": "Medium (2)", "Risk Level": "MEDIUM", "Strategy": "Hybrid (DATE 80/gATE 20)", "Annual Target": "500 seizures/year, 30% uplift YoY", "WCO Reference": "TRIPS/WCO IPR Guidelines", }, { "Priority": 4, "Risk Area": "Environmental/Plastic Waste", "Likelihood": "Medium (2)", "Impact": "High (3)", "Risk Level": "HIGH", "Strategy": "gATE Exploration", "Annual Target": "Basel Convention compliance 95%", "WCO Reference": "Compendium Vol.3 Ch.9", }, { "Priority": 5, "Risk Area": "Wildlife Smuggling", "Likelihood": "Low (1)", "Impact": "High (3)", "Risk Level": "MEDIUM-HIGH", "Strategy": "Hybrid (DATE 70/gATE 30)", "Annual Target": "CITES compliance 100%; 200 cases/year", "WCO Reference": "CITES/WCO Wildlife Guidelines", },]
RISK_COLORS_LEVEL = { "CRITICAL": "#C8102E", "HIGH": "#F5A800", "MEDIUM-HIGH": "#E67E22", "MEDIUM": "#9B59B6", "LOW": "#00843D",}
def risk_matrix_chart(): """3×3 WCO Risk Matrix with plotted risks.""" fig = go.Figure()
# Background zones zone_colors = [ # (x0,y0,x1,y1, fill) (0.5, 2.5, 3.5, 3.5, "rgba(200,16,46,0.18)"), # High-High (0.5, 1.5, 3.5, 2.5, "rgba(245,168,0,0.13)"), # Medium row (0.5, 0.5, 3.5, 1.5, "rgba(0,132,61,0.12)"), # Low row ] for x0, y0, x1, y1, fill in zone_colors: fig.add_shape(type="rect", x0=x0, y0=y0, x1=x1, y1=y1, fillcolor=fill, line_width=0, layer="below")
# Grid lines for v in [1.5, 2.5]: fig.add_shape(type="line", x0=0.5, y0=v, x1=3.5, y1=v, line=dict(color="#1E3A6E", width=1)) fig.add_shape(type="line", x0=v, y0=0.5, x1=v, y1=3.5, line=dict(color="#1E3A6E", width=1))
# Plot risks for name, d in RISK_MATRIX_DATA.items(): short = name.replace("Environmental/Plastic Waste","Env/Plastic").replace("Revenue Leakage","Revenue") fig.add_trace(go.Scatter( x=[d["likelihood"]], y=[d["impact"]], mode="markers+text", marker=dict(size=38, color=d["color"], opacity=0.88, line=dict(color="#C8A951", width=1.5)), text=[f"<b>P{d['priority']}</b>"], textfont=dict(color="white", size=13, family="Georgia"), textposition="middle center", name=short, hovertemplate=(f"<b>{name}</b><br>Likelihood: {d['likelihood']}" f"<br>Impact: {d['impact']}<br>Priority: {d['priority']}<extra></extra>"), ))
fig.update_layout( paper_bgcolor="#070E1C", plot_bgcolor="#0B1220", font=dict(family="IBM Plex Sans", color="#D0DCF0"), height=420, margin=dict(l=60, r=20, t=50, b=60), xaxis=dict( title="<b>Likelihood →</b>", range=[0.5, 3.5], tickvals=[1,2,3], ticktext=["Low","Medium","High"], gridcolor="#1E3A6E", zerolinecolor="#1E3A6E", title_font_color=WCO_GOLD, ), yaxis=dict( title="<b>← Impact</b>", range=[0.5, 3.5], tickvals=[1,2,3], ticktext=["Low","Medium","High"], gridcolor="#1E3A6E", zerolinecolor="#1E3A6E", title_font_color=WCO_GOLD, ), title=dict(text="<b>WCO 3×3 Risk Matrix — Customs Risk Areas</b>", font=dict(color=WCO_GOLD, size=15, family="Playfair Display, Georgia"), x=0.5), showlegend=True, legend=dict(bgcolor="#0F1C35", bordercolor=WCO_BORDER, borderwidth=1, font=dict(size=11), x=1.01, y=0.98), ) return fig
def rules_weight_editor(default_weights: dict) -> dict: """Render editable weight sliders per rule and return current weights.""" st.markdown('<div class="section-title">⚙️ Risk Rules Configuration & Annual Weights</div>', unsafe_allow_html=True) st.markdown("""<div class="alert-gold"> Adjust annual weights for each risk rule. Weights are automatically recalibrated after each simulation based on detection efficiency (self-learning feedback loop). </div>""", unsafe_allow_html=True)
updated = {} for area_name, area_cfg in RISK_AREAS.items(): icon = area_cfg["icon"] color = area_cfg["color"] with st.expander(f"{icon} {area_name}", expanded=False): sub_label = "" if "sub_areas" in area_cfg: sub_label = f" *(Sub-areas: {', '.join(area_cfg['sub_areas'])})*" st.markdown(f"<span style='color:{color};font-size:13px;'>{sub_label}</span>", unsafe_allow_html=True)
rule_data = [] for rule in area_cfg["rules"]: rid = rule["id"] rname = rule["name"] sub = rule.get("sub", "") col1, col2, col3 = st.columns([1, 3, 2]) with col1: st.markdown(f"<span style='color:{color};font-weight:600;font-size:12px;'>{rid}</span>", unsafe_allow_html=True) if sub: st.caption(sub) with col2: st.markdown(f"<span style='color:#D0DCF0;font-size:13px;'>{rname}</span>", unsafe_allow_html=True) with col3: w = st.slider( f"Weight [{rid}]", 0.05, 0.60, float(default_weights.get(rid, rule["weight"])), step=0.01, key=f"w_{rid}", label_visibility="collapsed", ) updated[rid] = w rule_data.append((rid, rname, sub, w)) st.markdown("<hr style='margin:4px 0;border-color:#1E3A6E;'>", unsafe_allow_html=True)
# Mini weight chart if rule_data: ids = [r[0] for r in rule_data] names = [r[1][:30] for r in rule_data] vals = [r[3] for r in rule_data] mini = go.Figure(go.Bar( x=ids, y=vals, marker_color=color, opacity=0.85, text=[f"{v:.2f}" for v in vals], textposition="outside", textfont=dict(color="#D0DCF0", size=10), hovertext=names, hoverinfo="text+y", )) mini.update_layout( paper_bgcolor="transparent", plot_bgcolor="#0B1220", height=180, margin=dict(l=10, r=10, t=10, b=30), font=dict(color="#D0DCF0", size=10), xaxis=dict(gridcolor="#1E3A6E"), yaxis=dict(gridcolor="#1E3A6E", range=[0, 0.65]), showlegend=False, ) st.plotly_chart(mini, use_container_width=True)
return updated
def show(): inject_global_css() page_header("📋", "Risk Register & Risk Matrix", "WCO RISK MANAGEMENT COMPENDIUM · 5 RISK AREAS · ANNUAL WEIGHT CONFIGURATION")
metric_row([ ("5", "Risk Areas", WCO_GOLD), ("26", "Risk Rules Total", WCO_BLUE), ("3×3", "Risk Matrix", WCO_RED), ("Annual","Weight Cycle", WCO_GREEN), ("WCO", "Compendium Ref.", WCO_GOLD), ])
# ── Risk Matrix ─────────────────────────────────────────────── st.markdown('<div class="section-title">📊 3×3 Risk Priority Matrix</div>', unsafe_allow_html=True) c_mat, c_legend = st.columns([2, 1]) with c_mat: st.plotly_chart(risk_matrix_chart(), use_container_width=True) with c_legend: st.markdown(""" <div class="wco-card"> <h3>Matrix Legend</h3> <div style="font-size:12px;color:#D0DCF0;line-height:2.2;"> <div style="background:rgba(200,16,46,0.2);padding:4px 10px;border-radius:5px;border-left:3px solid #C8102E;margin:4px 0;"> 🟥 <b>CRITICAL</b> — Immediate action, maximum resources </div> <div style="background:rgba(245,168,0,0.15);padding:4px 10px;border-radius:5px;border-left:3px solid #F5A800;margin:4px 0;"> 🟧 <b>HIGH</b> — Priority 2, enhanced monitoring </div> <div style="background:rgba(155,89,182,0.15);padding:4px 10px;border-radius:5px;border-left:3px solid #9B59B6;margin:4px 0;"> 🟪 <b>MEDIUM-HIGH</b> — Balanced exploit/explore </div> <div style="background:rgba(0,132,61,0.15);padding:4px 10px;border-radius:5px;border-left:3px solid #00843D;margin:4px 0;"> 🟩 <b>MEDIUM</b> — Exploration-led discovery </div> </div> <div style="margin-top:14px;color:#6B85AA;font-size:11px;"> P1 = Drugs & Narcotics (High-High)<br/> P2 = Revenue Leakage (High-Medium)<br/> P3 = IPR Enforcement (Med-Med)<br/> P4 = Environmental (Med-High)<br/> P5 = Wildlife (Low-High) </div> </div>""", unsafe_allow_html=True)
# ── Priority Table ──────────────────────────────────────────── st.markdown('<div class="section-title">🗂️ Risk Prioritisation Table</div>', unsafe_allow_html=True) df_prio = pd.DataFrame(RISK_PRIORITY_DATA)
rows_html = "" for _, row in df_prio.iterrows(): level_col = RISK_COLORS_LEVEL.get(row["Risk Level"], WCO_MUTED) area_col = RISK_MATRIX_DATA.get(row["Risk Area"], {}).get("color", WCO_MUTED) rows_html += f""" <tr> <td style="text-align:center;font-weight:700;color:{WCO_GOLD};">P{row['Priority']}</td> <td><span style="color:{area_col};font-weight:600;">{row['Risk Area']}</span></td> <td style="text-align:center;">{row['Likelihood']}</td> <td style="text-align:center;">{row['Impact']}</td> <td><span style="background:{level_col}22;color:{level_col};border:1px solid {level_col}; border-radius:5px;padding:2px 8px;font-size:11px;font-weight:600;"> {row['Risk Level']}</span></td> <td style="color:#CC77FF;font-size:12px;">{row['Strategy']}</td> <td style="color:#8BAAD4;font-size:12px;">{row['Annual Target']}</td> <td style="color:#557;font-size:11px;">{row['WCO Reference']}</td> </tr>"""
st.markdown(f""" <table class="wco-table"> <thead><tr> <th>Priority</th><th>Risk Area</th><th>Likelihood</th><th>Impact</th> <th>Risk Level</th><th>Selection Strategy</th><th>Annual Target</th><th>WCO Reference</th> </tr></thead> <tbody>{rows_html}</tbody> </table>""", unsafe_allow_html=True)
st.markdown("<br/>", unsafe_allow_html=True)
# ── Rules & Weights Editor ──────────────────────────────────── if "rule_weights" not in st.session_state: st.session_state.rule_weights = get_default_weights()
updated_weights = rules_weight_editor(st.session_state.rule_weights) if st.button("💾 Save Weights to Session", type="primary"): st.session_state.rule_weights = updated_weights st.success("✅ Weights saved — navigate to Page 3 to run simulation with updated weights.")
# ── Risk area summary cards ─────────────────────────────────── st.markdown('<div class="section-title">📌 Risk Area Summary Cards</div>', unsafe_allow_html=True) cols = st.columns(5) for i, (area_name, area_cfg) in enumerate(RISK_AREAS.items()): color = area_cfg["color"] icon = area_cfg["icon"] n_rules = len(area_cfg["rules"]) illicit = area_cfg["base_illicit_rate"] sub_txt = ", ".join(area_cfg.get("sub_areas", [])) with cols[i]: st.markdown(f""" <div style="background:#0F1C35;border:1px solid {color};border-radius:11px; padding:18px 14px;text-align:center;"> <div style="font-size:28px;">{icon}</div> <div style="color:{color};font-weight:700;font-size:12px;margin:8px 0 4px; font-family:'Playfair Display',serif;">{area_name}</div> {'<div style="color:#6B85AA;font-size:10px;margin-bottom:6px;">'+sub_txt+'</div>' if sub_txt else ''} <div style="color:#D0DCF0;font-size:12px;margin:4px 0;">{n_rules} Risk Rules</div> <div style="color:#6B85AA;font-size:11px;">Base Rate: {illicit*100:.0f}%</div> <div style="background:{color};height:3px;border-radius:2px;margin-top:10px; opacity:0.6;width:{int(illicit*400)}%;margin-left:auto;margin-right:auto;"></div> </div>""", unsafe_allow_html=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863"""page3_simulation.py — Live Simulation with Full Canvas AnimationAll bills complete in exactly 30 seconds. WCO themed, 5-lane layout."""
import streamlit as stimport streamlit.components.v1 as componentsimport plotly.graph_objects as goimport pandas as pdfrom styles import (inject_global_css, page_header, metric_row, WCO_GOLD, WCO_BLUE, WCO_GREEN, WCO_RED, WCO_CARD_BG, WCO_BORDER, WCO_MUTED)from simulation_engine import (generate_declarations, compute_risk_scores, assign_channels, simulate_inspection_outcomes, compute_updated_weights, get_default_weights, compute_efficiency_metrics, RISK_AREAS)
# ─────────────────────────────────────────────────────────────────────────────def build_animation_html(n_bills, bandwidth, exp_ratio, channel_counts, detected, revenue, efficiency_idx): red_n = channel_counts.get("RED", 0) yellow_n = channel_counts.get("YELLOW", 0) green_n = channel_counts.get("GREEN", 0) explore_n = int(n_bills * bandwidth * exp_ratio)
return f"""<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"/><style>* {{ box-sizing:border-box; margin:0; padding:0; }}body {{ background:#070E1C; font-family:'IBM Plex Sans','Segoe UI',sans-serif; color:#D0DCF0; overflow:hidden; height:700px; display:flex; flex-direction:column;}}
/* ── Top KPI strip ── */#kpi-bar {{ display:flex; background:#0B1527; border-bottom:3px solid #C8A951; flex-shrink:0;}}.kpi {{ flex:1; padding:9px 6px; text-align:center; border-right:1px solid #1E3A6E;}}.kpi:last-child {{ border-right:none; }}.kpi-val {{ font-size:20px; font-weight:700; font-family:'Georgia',serif; line-height:1;}}.kpi-lbl {{ font-size:9px; text-transform:uppercase; letter-spacing:0.07em; color:#6B85AA; margin-top:3px;}}
/* ── Canvas ── */#canvas-wrap {{ flex:1; position:relative; overflow:hidden; min-height:0;}}canvas {{ display:block; width:100%; height:100%; }}
/* ── Counter row ── */#counter-bar {{ display:flex; background:#0B1527; border-top:1px solid #1E3A6E; flex-shrink:0;}}.ch-cnt {{ flex:1; padding:7px 6px; text-align:center; border-right:1px solid #1E3A6E; transition:background .25s;}}.ch-cnt:last-child {{ border-right:none; }}.ch-v {{ font-size:24px; font-weight:700; font-family:'Georgia',serif; line-height:1; }}.ch-l {{ font-size:9px; color:#6B85AA; margin-top:2px; text-transform:uppercase; }}
/* ── Progress ── */#prog-wrap {{ background:#0B1527; border-top:1px solid #1E3A6E; padding:7px 14px; flex-shrink:0;}}#prog-head {{ font-size:10px; color:#C8A951; display:flex; justify-content:space-between; margin-bottom:4px;}}#prog-bg {{ background:#111D30; border-radius:4px; height:7px; overflow:hidden;}}#prog-fill {{ height:100%; border-radius:4px; background:linear-gradient(90deg,#003087,#C8A951); width:0%; transition:width .15s ease;}}</style></head><body>
<!-- KPI Header --><div id="kpi-bar"> <div class="kpi"> <div class="kpi-val" style="color:#D0DCF0;">{n_bills}</div> <div class="kpi-lbl">Total Declarations</div> </div> <div class="kpi"> <div class="kpi-val" style="color:#C8102E;">{red_n}</div> <div class="kpi-lbl">🔴 RED Target</div> </div> <div class="kpi"> <div class="kpi-val" style="color:#F5A800;">{yellow_n}</div> <div class="kpi-lbl">🟡 YELLOW Target</div> </div> <div class="kpi"> <div class="kpi-val" style="color:#00843D;">{green_n}</div> <div class="kpi-lbl">🟢 GREEN Target</div> </div> <div class="kpi"> <div class="kpi-val" style="color:#C8A951;">{efficiency_idx:.3f}</div> <div class="kpi-lbl">Efficiency Index</div> </div> <div class="kpi"> <div class="kpi-val" style="color:#44CC88;">${revenue:,.0f}</div> <div class="kpi-lbl">Revenue Recovered</div> </div> <div class="kpi"> <div class="kpi-val" style="color:#CC77FF;">{detected}</div> <div class="kpi-lbl">Frauds Detected</div> </div></div>
<!-- Canvas --><div id="canvas-wrap"> <canvas id="sim"></canvas></div>
<!-- Live counters --><div id="counter-bar"> <div class="ch-cnt" id="cnt-total"> <div class="ch-v" id="v-total" style="color:#D0DCF0;">0</div> <div class="ch-l">📦 Processed</div> </div> <div class="ch-cnt" id="cnt-red"> <div class="ch-v" id="v-red" style="color:#C8102E;">0</div> <div class="ch-l">🔴 Physical Exam</div> </div> <div class="ch-cnt" id="cnt-yel"> <div class="ch-v" id="v-yel" style="color:#F5A800;">0</div> <div class="ch-l">🟡 Doc Check</div> </div> <div class="ch-cnt" id="cnt-grn"> <div class="ch-v" id="v-grn" style="color:#00843D;">0</div> <div class="ch-l">🟢 Facilitated</div> </div> <div class="ch-cnt" id="cnt-exp"> <div class="ch-v" id="v-exp" style="color:#CC77FF;">0</div> <div class="ch-l">🔍 gATE Explore</div> </div> <div class="ch-cnt" id="cnt-fraud"> <div class="ch-v" id="v-fraud" style="color:#FF4466;">0</div> <div class="ch-l">🚨 Fraud Detected</div> </div></div>
<!-- Progress --><div id="prog-wrap"> <div id="prog-head"> <span id="stage-label">Initialising...</span> <span id="prog-pct">0%</span> </div> <div id="prog-bg"><div id="prog-fill"></div></div></div>
<script>// ═══════════════════ CONFIG ═══════════════════const TOTAL = {n_bills};const DUR_MS = 30000;const RED_T = {red_n};const YEL_T = {yellow_n};const GRN_T = {green_n};const FRAUD_T = {detected};const EXP_T = {explore_n};
// ═══════════════════ CANVAS ═══════════════════const canvas = document.getElementById('sim');const ctx = canvas.getContext('2d');let W, H;
function resize() {{ const wrap = document.getElementById('canvas-wrap'); W = canvas.width = wrap.clientWidth || 900; H = canvas.height = wrap.clientHeight || 380;}}window.addEventListener('resize', resize);resize();
// ═══════════════════ LAYOUT ═══════════════════// 5 lanes: 0=INTAKE 1=RED 2=YELLOW 3=GREEN 4=OFFENCEDBconst NUM_LANES = 5;function laneW() {{ return W / NUM_LANES; }}function laneCX(i){{ return i * laneW() + laneW() / 2; }}function gateY() {{ return H * 0.52; }}
// ═══════════════════ PRE-COMPUTE SEQUENCES ═══// Build shuffled channel arrayconst channelSeq = [];(function() {{ const a = []; for(let i=0;i<RED_T;i++) a.push('RED'); for(let i=0;i<YEL_T;i++) a.push('YELLOW'); for(let i=0;i<GRN_T;i++) a.push('GREEN'); for(let i=a.length-1;i>0;i--) {{ const j=Math.floor(Math.random()*(i+1)); [a[i],a[j]]=[a[j],a[i]]; }} channelSeq.push(...a);}})();
// Mark exploration indicesconst exploreSet = new Set();(function() {{ const pool=[]; channelSeq.forEach((c,i)=>{{ if(c==='RED'||c==='YELLOW') pool.push(i); }}); const need = Math.min(EXP_T, pool.length); while(exploreSet.size < need) {{ exploreSet.add(pool[Math.floor(Math.random()*pool.length)]); }}}})();
// Mark fraud indices (subset of inspected)const fraudSet = new Set();(function() {{ const pool=[]; channelSeq.forEach((c,i)=>{{ if(c==='RED'||c==='YELLOW') pool.push(i); }}); const need = Math.min(FRAUD_T, pool.length); while(fraudSet.size < need) {{ fraudSet.add(pool[Math.floor(Math.random()*pool.length)]); }}}})();
// ═══════════════════ COUNTERS ═══════════════════const C = {{ total:0, RED:0, YELLOW:0, GREEN:0, explore:0, fraud:0 }};
function updateDOM() {{ document.getElementById('v-total').textContent = C.total; document.getElementById('v-red').textContent = C.RED; document.getElementById('v-yel').textContent = C.YELLOW; document.getElementById('v-grn').textContent = C.GREEN; document.getElementById('v-exp').textContent = C.explore; document.getElementById('v-fraud').textContent = C.fraud;
// flash const flash = (id, col) => {{ const el = document.getElementById(id); el.style.background = col+'25'; setTimeout(()=>{{ el.style.background=''; }}, 220); }}; if(C.RED > 0 && C.RED % 2 === 0) flash('cnt-red', '#C8102E'); if(C.YELLOW > 0 && C.YELLOW % 2 === 0) flash('cnt-yel', '#F5A800'); if(C.GREEN > 0 && C.GREEN % 5 === 0) flash('cnt-grn', '#00843D'); if(C.fraud > 0) flash('cnt-fraud','#FF4466');}}
// ═══════════════════ BACKGROUND ═══════════════════const LANE_STYLES = [ {{ top:'#0A1E4A', bot:'#060D28', hdr:'INTAKE', sub:'All Declarations', col:'#8BAAD4' }}, {{ top:'#1E0008', bot:'#0D0004', hdr:'🔴 RED', sub:'Physical Examination',col:'#FF4466' }}, {{ top:'#1A1000', bot:'#0D0800', hdr:'🟡 YELLOW', sub:'Document Check', col:'#FFD700' }}, {{ top:'#001A09', bot:'#000D04', hdr:'🟢 GREEN', sub:'Facilitated', col:'#44CC88' }}, {{ top:'#110A1E', bot:'#080512', hdr:'🗄️ OFFENCE', sub:'Knowledge Vault', col:'#CC77FF' }},];
function drawBG() {{ const lw = laneW();
LANE_STYLES.forEach((s,i) => {{ const g = ctx.createLinearGradient(i*lw,0,i*lw,H); g.addColorStop(0, s.top); g.addColorStop(1, s.bot); ctx.fillStyle = g; ctx.fillRect(i*lw, 0, lw, H); }});
// Dividers ctx.strokeStyle='#1E3A6E'; ctx.lineWidth=1.2; for(let i=1;i<NUM_LANES;i++) {{ ctx.beginPath(); ctx.moveTo(i*lw,0); ctx.lineTo(i*lw,H); ctx.stroke(); }}
// Lane headers LANE_STYLES.forEach((s,i) => {{ const cx = laneCX(i); ctx.fillStyle='rgba(0,0,0,0.55)'; ctx.beginPath(); ctx.roundRect(i*lw+6,8,lw-12,46,7); ctx.fill(); ctx.strokeStyle=s.col+'44'; ctx.lineWidth=1; ctx.beginPath(); ctx.roundRect(i*lw+6,8,lw-12,46,7); ctx.stroke();
ctx.fillStyle=s.col; ctx.font='bold 13px Georgia,serif'; ctx.textAlign='center'; ctx.fillText(s.hdr, cx, 30); ctx.fillStyle='#6B85AA'; ctx.font='10px sans-serif'; ctx.fillText(s.sub, cx, 46); }});
// Gate band const gy = gateY(); const gg = ctx.createLinearGradient(0,gy-28,0,gy+28); gg.addColorStop(0,'rgba(0,48,135,0)'); gg.addColorStop(0.5,'rgba(0,48,135,0.9)'); gg.addColorStop(1,'rgba(0,48,135,0)'); ctx.fillStyle=gg; ctx.fillRect(0,gy-28,W,56);
ctx.strokeStyle='#C8A951'; ctx.lineWidth=1.4; ctx.setLineDash([8,5]); ctx.beginPath(); ctx.moveTo(0,gy-24); ctx.lineTo(W,gy-24); ctx.stroke(); ctx.beginPath(); ctx.moveTo(0,gy+24); ctx.lineTo(W,gy+24); ctx.stroke(); ctx.setLineDash([]);
// Gate booths const boothData = [ {{label:'DATE SCORING', col:'#C8A951'}}, {{label:'RED CHANNEL', col:'#C8102E'}}, {{label:'YELLOW CHANNEL',col:'#F5A800'}}, {{label:'GREEN CHANNEL', col:'#00843D'}}, ]; boothData.forEach((b,i) => {{ const bx = laneCX(i); ctx.fillStyle='#0F1C35'; ctx.strokeStyle=b.col; ctx.lineWidth=1.8; ctx.beginPath(); ctx.roundRect(bx-40,gy-16,80,32,5); ctx.fill(); ctx.stroke(); ctx.fillStyle=b.col; ctx.font='bold 9px IBM Plex Sans,sans-serif'; ctx.textAlign='center'; ctx.fillText(b.label, bx, gy+4); // Dot indicator ctx.shadowColor=b.col; ctx.shadowBlur=8; ctx.beginPath(); ctx.arc(bx,gy-20,4,0,Math.PI*2); ctx.fillStyle=b.col; ctx.fill(); ctx.shadowBlur=0; }});
// Vault (offence DB) const vx = laneCX(4); ctx.fillStyle='#1A0A2E'; ctx.strokeStyle='#CC77FF'; ctx.lineWidth=2; ctx.beginPath(); ctx.roundRect(vx-46,gy-20,92,40,8); ctx.fill(); ctx.stroke(); ctx.fillStyle='#CC77FF'; ctx.font='bold 10px Georgia'; ctx.textAlign='center'; ctx.fillText('OFFENCE DB', vx, gy-4); ctx.fillStyle='#8B55CC'; ctx.font='9px sans-serif'; ctx.fillText('Evidence Vault', vx, gy+12);
// Bezier guide lines (intake → channels) [[1,'#C8102E'],[2,'#F5A800'],[3,'#00843D']].forEach(([li,col]) => {{ const ix = laneCX(0), tx = laneCX(li), topY = gy-100; ctx.strokeStyle=col+'28'; ctx.lineWidth=1; ctx.setLineDash([4,9]); ctx.beginPath(); ctx.moveTo(ix, topY); ctx.bezierCurveTo(ix,gy-50,tx,gy-50,tx,gy-25); ctx.stroke(); ctx.setLineDash([]); }});}}
// ═══════════════════ BILL PARTICLE ═══════════════════const bills = [];let billIdx = 0;
const laneMap = {{ RED:1, YELLOW:2, GREEN:3 }};
class Bill {{ constructor(idx) {{ this.idx = idx; this.channel = channelSeq[idx] || 'GREEN'; this.explore = exploreSet.has(idx); this.fraud = fraudSet.has(idx);
const lw = laneW(); this.x = laneCX(0) + (Math.random()*24-12); this.y = -20 - Math.random()*60; this.vy = 0; // will be set per-frame to hit gate at exact time
this.targetX = laneCX(laneMap[this.channel]) + (Math.random()*16-8); this.phase = 'intake';
// colour const chC = {{ RED:'#C8102E', YELLOW:'#F5A800', GREEN:'#00843D' }}; this.finalColor = chC[this.channel]; this.color = '#3A6BB5'; this.alpha = 1;
// size this.w = 9; this.h = 12;
// counted flags this.counted = false; this.fraudSent = false; }}
update(elapsed) {{ const gy = gateY();
if(this.phase === 'intake') {{ // Speed to cross gate at correct time proportional to index const targetArrivalMs = (this.idx / TOTAL) * DUR_MS * 0.75; const remainMs = Math.max(10, targetArrivalMs - elapsed); const distToGate = gy - 28 - this.y; this.vy = (distToGate / remainMs) * 16; // px/frame approx
this.y += Math.max(0.8, this.vy);
if(this.y >= gy - 28) {{ this.phase = 'routing'; this.color = this.finalColor; }} }} else if(this.phase === 'routing') {{ const dx = this.targetX - this.x; this.x += dx * 0.14; this.y += 2.2; if(Math.abs(dx) < 2.5 && this.y > gy + 32) {{ this.phase = 'exiting'; if(!this.counted) {{ this.counted = true; C.total++; C[this.channel]++; if(this.explore) C.explore++; if(this.fraud) C.fraud++; updateDOM(); }} }} }} else if(this.phase === 'exiting') {{ this.y += 2.8; if(this.fraud && !this.fraudSent && this.y > gateY()+90) {{ this.fraudSent = true; offParts.push(new OffPart(this.x, this.y, this.finalColor)); }} if(this.y > H+20) this.phase='done'; }} }}
draw() {{ if(this.phase==='done') return; ctx.save(); ctx.globalAlpha = this.alpha; ctx.translate(this.x, this.y);
// Document body ctx.fillStyle = this.color; ctx.strokeStyle = this.color+'99'; ctx.lineWidth = 0.7; ctx.beginPath(); ctx.roundRect(-this.w/2,-this.h/2,this.w,this.h,2); ctx.fill(); ctx.stroke();
// Fold corner ctx.fillStyle='rgba(255,255,255,0.18)'; ctx.beginPath(); ctx.moveTo(this.w/2-3,-this.h/2); ctx.lineTo(this.w/2,-this.h/2+3); ctx.lineTo(this.w/2-3,-this.h/2+3); ctx.closePath(); ctx.fill();
// Lines on doc ctx.strokeStyle='rgba(255,255,255,0.2)'; ctx.lineWidth=0.8; [-3,0,3].forEach(dy => {{ ctx.beginPath(); ctx.moveTo(-this.w/2+2, dy); ctx.lineTo(this.w/2-3, dy); ctx.stroke(); }});
// Fraud glow if(this.fraud) {{ ctx.shadowColor='#FF4466'; ctx.shadowBlur=10; ctx.strokeStyle='#FF4466'; ctx.lineWidth=1.5; ctx.beginPath(); ctx.roundRect(-this.w/2,-this.h/2,this.w,this.h,2); ctx.stroke(); ctx.shadowBlur=0; }} // Explore glow if(this.explore && !this.fraud) {{ ctx.shadowColor='#CC77FF'; ctx.shadowBlur=7; ctx.strokeStyle='#CC77FF'; ctx.lineWidth=1.2; ctx.beginPath(); ctx.roundRect(-this.w/2,-this.h/2,this.w,this.h,2); ctx.stroke(); ctx.shadowBlur=0; }}
ctx.restore(); }}}}
// ═══════════════════ OFFENCE PARTICLE ═══════════════════const offParts = [];class OffPart {{ constructor(x,y,col) {{ this.x=x; this.y=y; this.col=col; this.tx=laneCX(4); this.ty=gateY()+5; this.t=0; this.done=false; }} update() {{ this.t+=0.035; if(this.t>=1){{ this.done=true; return; }} this.x += (this.tx-this.x)*0.07; this.y += (this.ty-this.y)*0.07; }} draw() {{ if(this.done) return; ctx.save(); ctx.globalAlpha=Math.max(0,1-this.t); ctx.fillStyle=this.col; ctx.shadowColor='#CC77FF'; ctx.shadowBlur=12; ctx.beginPath(); ctx.arc(this.x,this.y,4,0,Math.PI*2); ctx.fill(); ctx.shadowBlur=0; ctx.restore(); }}}}
// ═══════════════════ STAGE LABELS ═══════════════════const STAGES = [ {{ pct:0.00, end:0.25, label:'PHASE 1 — INTAKE & DATE RISK SCORING', col:'#C8A951' }}, {{ pct:0.25, end:0.60, label:'PHASE 2 — HYBRID CHANNEL ROUTING (DATE + gATE)', col:'#0066CC' }}, {{ pct:0.60, end:0.85, label:'PHASE 3 — INSPECTION & OFFENCE DB FEEDBACK', col:'#C8102E' }}, {{ pct:0.85, end:1.01, label:'PHASE 4 — SELF-LEARNING CYCLE COMPLETE ✓', col:'#00843D' }},];
function drawStageLabel(p) {{ const s = STAGES.find(x => p>=x.pct && p<x.end) || STAGES[3]; document.getElementById('stage-label').textContent = s.label; document.getElementById('stage-label').style.color = s.col;}}
// ═══════════════════ COMPLETION OVERLAY ═══════════════════function drawDone() {{ ctx.save(); ctx.fillStyle='rgba(7,14,28,0.86)'; ctx.fillRect(0,0,W,H);
const cw=460,ch=200,cx=(W-cw)/2,cy=(H-ch)/2; ctx.fillStyle='#0F1C35'; ctx.strokeStyle='#C8A951'; ctx.lineWidth=2; ctx.beginPath(); ctx.roundRect(cx,cy,cw,ch,14); ctx.fill(); ctx.stroke();
// Gold header ctx.fillStyle='#C8A951'; ctx.beginPath(); ctx.roundRect(cx,cy,cw,40,{{topLeft:14,topRight:14,bottomLeft:0,bottomRight:0}}); ctx.fill(); ctx.fillStyle='#003087'; ctx.font='bold 13px Georgia'; ctx.textAlign='center'; ctx.fillText('✅ SIMULATION COMPLETE — WCO RMS CYCLE', W/2, cy+25);
ctx.fillStyle='#44CC88'; ctx.font='bold 22px Georgia'; ctx.fillText('All '+TOTAL+' Declarations Processed in 30 Seconds', W/2, cy+72);
const cols = [['🔴 RED',C.RED,'#C8102E'],['🟡 YEL',C.YELLOW,'#F5A800'], ['🟢 GRN',C.GREEN,'#00843D'],['🚨 Fraud',C.fraud,'#FF4466'], ['🔍 Expl',C.explore,'#CC77FF']]; const bw=74, startX=cx+20; cols.forEach((col,i) => {{ const bx=startX+i*(bw+8); ctx.fillStyle=col[2]+'22'; ctx.beginPath(); ctx.roundRect(bx,cy+90,bw,52,6); ctx.fill(); ctx.strokeStyle=col[2]; ctx.lineWidth=1; ctx.beginPath(); ctx.roundRect(bx,cy+90,bw,52,6); ctx.stroke(); ctx.fillStyle=col[2]; ctx.font='bold 22px Georgia'; ctx.fillText(col[1], bx+bw/2, cy+120); ctx.fillStyle='#8BAAD4'; ctx.font='9px sans-serif'; ctx.fillText(col[0], bx+bw/2, cy+136); }});
ctx.fillStyle='#C8A951'; ctx.font='11px monospace'; ctx.fillText('Navigate to Page 4 → for detailed analysis tables & charts', W/2, cy+168); ctx.restore();}}
// ═══════════════════ SPAWN RATE ═══════════════════// Bills spawn steadily across 80% of duration so all finish by endconst SPAWN_END_MS = DUR_MS * 0.80;const SPAWN_INTV = SPAWN_END_MS / TOTAL; // ms per billlet lastSpawnT = 0;let startTime = null;let simComplete = false;
// ═══════════════════ MAIN LOOP ═══════════════════function loop(ts) {{ if(!startTime) startTime=ts; const elapsed = ts - startTime; const prog = Math.min(elapsed / DUR_MS, 1);
ctx.clearRect(0,0,W,H); drawBG();
// Spawn if(billIdx < TOTAL && elapsed >= lastSpawnT + SPAWN_INTV) {{ const batchN = Math.min( TOTAL - billIdx, Math.floor((elapsed - lastSpawnT) / SPAWN_INTV) ); for(let b=0;b<batchN;b++) bills.push(new Bill(billIdx++)); lastSpawnT += batchN * SPAWN_INTV; }}
// Update & draw bills bills.forEach(bl => {{ bl.update(elapsed); bl.draw(); }});
// Offence particles for(let i=offParts.length-1;i>=0;i--) {{ offParts[i].update(); offParts[i].draw(); if(offParts[i].done) offParts.splice(i,1); }}
// Vault counter const vx = laneCX(4), vy = gateY()+58; ctx.fillStyle='#CC77FF'; ctx.font='bold 22px Georgia'; ctx.textAlign='center'; ctx.fillText(C.fraud, vx, vy); ctx.fillStyle='#8B55CC'; ctx.font='9px sans-serif'; ctx.fillText('offence entries', vx, vy+14);
// Live efficiency const liveP = C.total > 0 ? (C.fraud / Math.max(C.RED+C.YELLOW,1)).toFixed(3) : '–'; ctx.fillStyle='#C8A951'; ctx.font='bold 10px IBM Plex Sans'; ctx.textAlign='left'; ctx.fillText('LIVE PRECISION: '+liveP, 8, H-6);
// Timer const rem = Math.max(0,30-(elapsed/1000)); ctx.fillStyle='#557796'; ctx.font='10px monospace'; ctx.textAlign='right'; ctx.fillText('⏱ '+rem.toFixed(1)+'s', W-8, H-6);
// Progress bar document.getElementById('prog-fill').style.width=(prog*100).toFixed(1)+'%'; document.getElementById('prog-pct').textContent= (prog*100).toFixed(0)+'% ('+C.total+' / '+TOTAL+' processed)'; drawStageLabel(prog);
// Check completion const allDone = prog>=1 && bills.every(b=>b.phase==='done'||b.phase==='exiting'); if(allDone && !simComplete) {{ simComplete=true; // ensure final counts bills.forEach(b=>{{ if(!b.counted && b.phase!=='done') {{ b.counted=true; C.total++; C[b.channel]++; if(b.explore) C.explore++; if(b.fraud) C.fraud++; }} }}); updateDOM(); setTimeout(()=>{{ drawDone(); }}, 400); return; }}
requestAnimationFrame(loop);}}
drawBG();requestAnimationFrame(loop);</script></body></html>"""
# ─────────────────────────────────────────────────────────────────────────────def risk_score_distribution(df): fig = go.Figure() for ch, color, label in [ ("GREEN","#00843D","🟢 GREEN"), ("YELLOW","#F5A800","🟡 YELLOW"), ("RED","#C8102E","🔴 RED"), ]: cdf = df[df["channel"]==ch] fig.add_trace(go.Violin( y=cdf["fraud_score"], name=label, fillcolor=color, opacity=0.7, line_color=color, box_visible=True, meanline_visible=True, points=False, )) fig.update_layout( paper_bgcolor="#070E1C", plot_bgcolor="#0B1220", font=dict(family="IBM Plex Sans", color="#D0DCF0", size=12), height=300, title=dict(text="<b>Risk Score Distribution by Channel</b>", font=dict(color=WCO_GOLD, size=13, family="Playfair Display"), x=0.5), yaxis=dict(title="Fraud Score", gridcolor="#1E3A6E", range=[0,1]), xaxis=dict(gridcolor="#1E3A6E"), legend=dict(bgcolor="#0F1C35", bordercolor=WCO_BORDER), margin=dict(l=50,r=20,t=50,b=40), violingap=0.3, ) return fig
def area_heatmap(df): pivot = pd.crosstab(df["risk_area"], df["channel"]) for col in ["RED","YELLOW","GREEN"]: if col not in pivot.columns: pivot[col]=0 pivot = pivot[["RED","YELLOW","GREEN"]] fig = go.Figure(go.Heatmap( z=pivot.values, x=pivot.columns, y=pivot.index, colorscale=[[0,"#0B1220"],[0.5,"#003087"],[1,"#C8A951"]], text=pivot.values, texttemplate="%{text}", textfont={"size":13}, hovertemplate="<b>%{y}</b><br>Channel: %{x}<br>Bills: %{z}<extra></extra>", showscale=True, colorbar=dict(tickfont=dict(color="#D0DCF0"), title="Bills", titlefont=dict(color=WCO_GOLD)), )) fig.update_layout( paper_bgcolor="#070E1C", plot_bgcolor="#0B1220", font=dict(family="IBM Plex Sans", color="#D0DCF0", size=11), height=280, title=dict(text="<b>Risk Area × Channel Heatmap</b>", font=dict(color=WCO_GOLD, size=13, family="Playfair Display"), x=0.5), margin=dict(l=165,r=30,t=50,b=40), ) return fig
# ─────────────────────────────────────────────────────────────────────────────def show(): inject_global_css() page_header("🔄", "Self-Learning Simulation Engine", "DATE EXPLOITATION · gATE EXPLORATION · 30-SECOND LIVE CANVAS ANIMATION")
# ── Controls ────────────────────────────────────────────────── st.markdown('<div class="section-title">🎛️ Simulation Control Panel</div>', unsafe_allow_html=True) c1,c2,c3,c4 = st.columns(4) with c1: n_bills = st.slider("📦 Declarations", 200,1000,1000,step=100) with c2: bandwidth = st.slider("📡 Bandwidth (%)", 5,30,10,step=1)/100 with c3: exp_ratio = st.slider("🔍 Exploration ε (%)",1,30,10,step=1)/100 with c4: seed = st.slider("🎲 Seed",1,99,42,step=1)
st.markdown(f""" <div class="alert-blue"> <b>Strategy:</b> DATE {100-int(exp_ratio*100)}% + gATE {int(exp_ratio*100)}% | <b>Bandwidth:</b> {int(bandwidth*100)}% → {int(n_bills*bandwidth)} bills inspected | <b>Facilitated:</b> {n_bills-int(n_bills*bandwidth)} bills (GREEN) | <b>⏱ Animation duration:</b> exactly 30 seconds for full batch </div>""", unsafe_allow_html=True)
col1,col2,_ = st.columns([1.2,1,4]) with col1: run_btn = st.button("▶ Run Simulation", type="primary", use_container_width=True) with col2: reset_btn = st.button("🔄 Reset All", use_container_width=True)
if reset_btn: for k in ["sim_df","sim_weights","sim_efficiency"]: st.session_state.pop(k,None) st.rerun()
# ── Run ─────────────────────────────────────────────────────── if run_btn or "sim_df" in st.session_state: if run_btn or "sim_df" not in st.session_state: weights = st.session_state.get("rule_weights", get_default_weights()) prog = st.progress(0, text="⚙️ Generating declarations...") df = generate_declarations(n_bills, seed=seed) prog.progress(25, text="🧠 DATE scoring...") df = compute_risk_scores(df, weights) prog.progress(50, text="⚖️ Hybrid channel routing...") df = assign_channels(df, bandwidth=bandwidth, exploration_ratio=exp_ratio) prog.progress(75, text="👮 Inspection outcomes...") df = simulate_inspection_outcomes(df, seed=seed) prog.progress(90, text="📈 Weight update & efficiency...") uw = compute_updated_weights(df, weights) eff = compute_efficiency_metrics(df) prog.progress(100, text="✅ Launching animation!")
st.session_state.sim_df = df st.session_state.sim_weights = uw st.session_state.sim_efficiency = eff
df = st.session_state.sim_df eff = st.session_state.sim_efficiency hybrid = eff.get("hybrid", {}) ch = df["channel"].value_counts() detected = int((df["inspection_outcome"]=="FRAUD_DETECTED").sum()) revenue = float(df["detected_revenue"].sum()) eff_idx = float(hybrid.get("efficiency_index", 0.0))
channel_counts = { "RED": int(ch.get("RED",0)), "YELLOW": int(ch.get("YELLOW",0)), "GREEN": int(ch.get("GREEN",0)), }
# ── Legend ──────────────────────────────────────────────── st.markdown('<div class="section-title">🎬 Live RMS Canvas Animation</div>', unsafe_allow_html=True) st.markdown("""<div class="alert-gold"> 📌 <b>30-second real-time simulation.</b> Each icon = one customs declaration flowing through the RMS pipeline.<br/> <span style="color:#FF4466;">■ Red glow</span> = Fraud detected | <span style="color:#CC77FF;">■ Purple glow</span> = gATE exploration pick | <span style="color:#3A6BB5;">■ Blue</span> = Standard routing | Fraud bills arc → Offence DB vault (right lane) </div>""", unsafe_allow_html=True)
# ── CANVAS ANIMATION ────────────────────────────────────── html_src = build_animation_html( n_bills=n_bills, bandwidth=bandwidth, exp_ratio=exp_ratio, channel_counts=channel_counts, detected=detected, revenue=revenue, efficiency_idx=eff_idx, ) components.html(html_src, height=720, scrolling=False)
# ── Supporting charts ────���───────────────────────────────── st.markdown("<br/>", unsafe_allow_html=True) st.markdown('<div class="section-title">📊 Channel Analytics</div>', unsafe_allow_html=True) ca,cb = st.columns([3,2]) with ca: st.plotly_chart(area_heatmap(df), use_container_width=True) with cb: st.plotly_chart(risk_score_distribution(df), use_container_width=True)
# ── Risk area cards ─────────────────────────────────────── st.markdown('<div class="section-title">🗂️ Risk Area Breakdown</div>', unsafe_allow_html=True) acols = st.columns(5) for i,(aname,acfg) in enumerate(RISK_AREAS.items()): a_df = df[df["risk_area"]==aname] color = acfg["color"] ch_a = a_df["channel"].value_counts() fraud_a= (a_df["inspection_outcome"]=="FRAUD_DETECTED").sum() exp_a = a_df["is_exploration"].sum() with acols[i]: st.markdown(f""" <div style="background:#0F1C35;border:1px solid {color}; border-radius:10px;padding:14px 12px;"> <div style="color:{color};font-weight:700;font-size:12px; margin-bottom:10px;font-family:'Playfair Display',serif;"> {acfg['icon']} {aname} </div> <div style="color:#D0DCF0;font-size:12px;line-height:2.1;"> 🔴 RED: <b>{ch_a.get('RED',0)}</b><br/> 🟡 YEL: <b>{ch_a.get('YELLOW',0)}</b><br/> 🟢 GRN: <b>{ch_a.get('GREEN',0)}</b><br/> 🚨 Fraud: <b style="color:#FF4466;">{fraud_a}</b><br/> 🔍 Expl: <b style="color:#CC77FF;">{exp_a}</b> </div> </div>""", unsafe_allow_html=True)
st.markdown("""<div class="alert-gold" style="margin-top:18px;"> ✅ Simulation complete. Go to <b>Page 4</b> for full tables, offence DB growth, and weight-evolution analysis. </div>""", unsafe_allow_html=True)
else: st.markdown(""" <div style="background:#0F1C35;border:2px dashed #1E3A6E;border-radius:14px; padding:70px;text-align:center;margin-top:20px;"> <div style="font-size:52px;margin-bottom:16px;">🎬</div> <div style="color:#C8A951;font-family:'Playfair Display',serif; font-size:22px;margin-bottom:12px;">Ready to Simulate</div> <div style="color:#6B85AA;font-size:14px;line-height:1.8;"> Configure parameters above and click <b style="color:#C8A951;">▶ Run Simulation</b><br/> A 30-second canvas animation will show all declarations flowing through RED / YELLOW / GREEN channels in real-time. </div> </div>""", unsafe_allow_html=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951"""page4_results.py — Simulation Results: 5 tables + charts for all analysis dimensions"""
import streamlit as stimport plotly.graph_objects as goimport plotly.express as pximport pandas as pdimport numpy as npfrom styles import (inject_global_css, page_header, metric_row, WCO_GOLD, WCO_BLUE, WCO_GREEN, WCO_RED, WCO_CARD_BG, WCO_BORDER, WCO_MUTED, RISK_COLORS)from simulation_engine import (build_rule_hit_table, build_channel_table, build_exploration_discovery_table, build_offence_db_table, build_risk_score_table, RISK_AREAS)
RISK_LEVEL_COLORS = { "FRAUD_DETECTED": "#C8102E", "DOC_QUERY": "#F5A800", "CLEAN": "#00843D", "NOT_INSPECTED": "#6B85AA",}
def offence_db_growth_chart(df): """Cumulative offence DB additions over bill sequence.""" df_sorted = df.sort_index() df_sorted["cum_offence"] = df_sorted["added_to_offence_db"].cumsum()
# Break down by risk area traces = [] for area_name, area_cfg in RISK_AREAS.items(): a_df = df_sorted[df_sorted["risk_area"] == area_name].copy() a_df["cum"] = a_df["added_to_offence_db"].cumsum() traces.append(go.Scatter( x=a_df.index, y=a_df["cum"], name=f"{area_cfg['icon']} {area_name}", line=dict(color=area_cfg["color"], width=2), mode="lines", hovertemplate=f"<b>{area_name}</b><br>Bill: %{{x}}<br>Cumulative: %{{y}}<extra></extra>", )) traces.append(go.Scatter( x=df_sorted.index, y=df_sorted["cum_offence"], name="📊 Total", line=dict(color=WCO_GOLD, width=3, dash="dot"), hovertemplate="<b>Total</b><br>Bill: %{x}<br>Cumulative: %{y}<extra></extra>", ))
fig = go.Figure(traces) fig.update_layout( paper_bgcolor="#070E1C", plot_bgcolor="#0B1220", font=dict(family="IBM Plex Sans", color="#D0DCF0", size=11), height=380, title=dict(text="<b>Real-Time Offence Database Growth (Cumulative)</b>", font=dict(color=WCO_GOLD, size=14, family="Playfair Display"), x=0.5), xaxis=dict(title="Bill Sequence", gridcolor="#1E3A6E"), yaxis=dict(title="Offences Added to DB", gridcolor="#1E3A6E"), legend=dict(bgcolor="#0F1C35", bordercolor=WCO_BORDER, font=dict(size=10)), margin=dict(l=55, r=20, t=55, b=45), ) return fig
def exploration_vs_exploitation_chart(df): """Compare detection across exploit vs explore bills.""" cats = ["Exploitation Bills", "Exploration Bills"] exploit_df = df[df["is_exploration"] == 0] explore_df = df[df["is_exploration"] == 1]
def detection_stats(sub): tot = len(sub) fraud = (sub["inspection_outcome"] == "FRAUD_DETECTED").sum() rev = sub["detected_revenue"].sum() rate = 100 * fraud / tot if tot else 0 return tot, fraud, rev, rate
e_tot, e_fraud, e_rev, e_rate = detection_stats(exploit_df) x_tot, x_fraud, x_rev, x_rate = detection_stats(explore_df)
fig = go.Figure() fig.add_trace(go.Bar(name="🎯 Exploitations", x=["Bills","Frauds Detected","Revenue ($K)"], y=[e_tot, e_fraud, e_rev/1000], marker_color="#0066CC", opacity=0.85, text=[e_tot, e_fraud, f"${e_rev/1000:.1f}K"], textposition="outside", textfont=dict(color="#D0DCF0"))) fig.add_trace(go.Bar(name="🔍 Explorations", x=["Bills","Frauds Detected","Revenue ($K)"], y=[x_tot, x_fraud, x_rev/1000], marker_color="#CC77FF", opacity=0.85, text=[x_tot, x_fraud, f"${x_rev/1000:.1f}K"], textposition="outside", textfont=dict(color="#D0DCF0"))) fig.update_layout( paper_bgcolor="#070E1C", plot_bgcolor="#0B1220", font=dict(family="IBM Plex Sans", color="#D0DCF0", size=12), height=340, barmode="group", title=dict(text="<b>Exploitation vs Exploration: Detection Comparison</b>", font=dict(color=WCO_GOLD, size=14, family="Playfair Display"), x=0.5), xaxis=dict(gridcolor="#1E3A6E"), yaxis=dict(gridcolor="#1E3A6E", title="Count / Value"), legend=dict(bgcolor="#0F1C35", bordercolor=WCO_BORDER), margin=dict(l=50, r=20, t=55, b=40), ) return fig
def weight_evolution_chart(df, orig_weights, updated_weights): """Visualise how rule weights increased after simulation.""" rids, orig, updated, deltas = [], [], [], [] for area in RISK_AREAS.values(): for rule in area["rules"]: rid = rule["id"] o = orig_weights.get(rid, rule["weight"]) u = updated_weights.get(rid, o) rids.append(rid) orig.append(o) updated.append(u) deltas.append(round(u - o, 4))
fig = go.Figure() fig.add_trace(go.Bar(x=rids, y=orig, name="Original Weights", marker_color="#1E3A6E", opacity=0.9)) fig.add_trace(go.Bar(x=rids, y=updated, name="Updated Weights", marker_color=WCO_GOLD, opacity=0.85)) fig.add_trace(go.Scatter(x=rids, y=deltas, name="Δ Weight", mode="markers+lines", marker=dict(color=WCO_RED, size=9, symbol="triangle-up"), line=dict(color=WCO_RED, dash="dot", width=1.5), yaxis="y2")) fig.update_layout( paper_bgcolor="#070E1C", plot_bgcolor="#0B1220", font=dict(family="IBM Plex Sans", color="#D0DCF0", size=10), height=360, barmode="group", title=dict(text="<b>Rule Weight Evolution After Self-Learning Feedback</b>", font=dict(color=WCO_GOLD, size=14, family="Playfair Display"), x=0.5), xaxis=dict(gridcolor="#1E3A6E", tickangle=-45), yaxis=dict(title="Weight", gridcolor="#1E3A6E"), yaxis2=dict(title="Δ Weight", overlaying="y", side="right", gridcolor="#1E3A6E", showgrid=False), legend=dict(bgcolor="#0F1C35", bordercolor=WCO_BORDER), margin=dict(l=55, r=55, t=55, b=90), ) return fig
def styled_table(df: pd.DataFrame, title: str, highlight_col: str = None, color_map: dict = None): st.markdown(f""" <div style="color:{WCO_GOLD};font-family:'Playfair Display',serif; font-size:15px;font-weight:700;margin:16px 0 10px;"> {title} </div>""", unsafe_allow_html=True) if highlight_col and color_map: def _style(val): col = color_map.get(val, "") return f"background-color:{col}22;color:{col}" if col else "" styled = df.style.applymap(_style, subset=[highlight_col]) \ .set_properties(**{"background-color": WCO_CARD_BG, "color": "#D0DCF0", "font-size": "12px"}) st.dataframe(styled, use_container_width=True, height=min(38 * len(df) + 40, 420)) else: st.dataframe( df.style.set_properties(**{"background-color": WCO_CARD_BG, "color": "#D0DCF0", "font-size": "12px"}), use_container_width=True, height=min(38 * len(df) + 40, 420), )
def exploration_scatter_tab(df: pd.DataFrame): """ Full scatter-plot breakdown of the bATE exploration logic applied to all bills. Shows every formula component: unc_i = -1.8 * |fraud_score - 0.5| + 1 S_i = unc_i * log(pred_revenue + ε) Colour = channel assignment. Shape = exploration pick or not. """ import numpy as np
# ── Formula explanation banner ──────────────────────────────── st.markdown(""" <div class="wco-card-gold"> <h3>🧭 bATE Exploration Logic — All Bills Visualised</h3> <div style="display:flex;gap:30px;flex-wrap:wrap;font-size:13px;color:#D0DCF0;line-height:2;"> <div> <b style="color:#CC77FF;">Step 1 — Uncertainty Score</b><br/> <code style="background:#111D30;padding:4px 10px;border-radius:5px; color:#C8A951;font-size:13px;"> unc_i = −1.8 × |ŷᶜˡˢ − 0.5| + 1 </code><br/> <span style="color:#6B85AA;font-size:12px;"> Max = 1.0 when fraud_score = 0.5 (model completely unsure)<br/> Min ≈ 0.1 when fraud_score → 0 or → 1 (model very confident) </span> </div> <div> <b style="color:#CC77FF;">Step 2 — Scale Factor (bATE)</b><br/> <code style="background:#111D30;padding:4px 10px;border-radius:5px; color:#C8A951;font-size:13px;"> S_i = unc_i × log(ŷʳᵉᵛ + ε) </code><br/> <span style="color:#6B85AA;font-size:12px;"> High S_i = uncertain AND high revenue → top exploration candidates<br/> K-means++ diversity applied on top to avoid redundant picks </span> </div> </div> </div>""", unsafe_allow_html=True)
st.markdown("<br/>", unsafe_allow_html=True)
# ── Colour / marker helpers ─────────────────────────────────── ch_color = {"RED": "#C8102E", "YELLOW": "#F5A800", "GREEN": "#00843D"} ch_marker = {"RED": "circle", "YELLOW": "diamond", "GREEN": "square"}
def base_layout(title, xlab, ylab, h=460): return dict( paper_bgcolor="#070E1C", plot_bgcolor="#0B1220", font=dict(family="IBM Plex Sans", color="#D0DCF0", size=11), height=h, title=dict(text=f"<b>{title}</b>", font=dict(color=WCO_GOLD, size=14, family="Playfair Display"), x=0.5), xaxis=dict(title=xlab, gridcolor="#1E3A6E", zeroline=False), yaxis=dict(title=ylab, gridcolor="#1E3A6E", zeroline=False), legend=dict(bgcolor="#0F1C35", bordercolor=WCO_BORDER, font=dict(size=10)), margin=dict(l=60, r=20, t=55, b=55), )
# ───────────────────────────────────────────────────────────── # SCATTER 1 — fraud_score vs uncertainty_score (the unc_i curve) # ───────────────────────────────────────────────────────────── st.markdown('<div class="section-title">① Fraud Score vs Uncertainty Score — The unc_i Curve</div>', unsafe_allow_html=True) st.markdown("""<div class="alert-blue"> The <b>uncertainty score unc_i</b> is a concave function maximised when <code>fraud_score ≈ 0.5</code>. Bills near 0.5 are the model's blind spots — exploration targets. Bills near 0 or 1 are confident predictions (exploitation territory). <b style="color:#CC77FF;">Purple stars</b> = actual gATE exploration picks. </div>""", unsafe_allow_html=True)
# Theoretical curve overlay x_curve = np.linspace(0, 1, 300) y_curve = -1.8 * np.abs(x_curve - 0.5) + 1
fig1 = go.Figure()
# Theoretical curve fig1.add_trace(go.Scatter( x=x_curve, y=y_curve, mode="lines", name="unc_i = −1.8×|ŷ−0.5|+1 (theoretical)", line=dict(color="#C8A951", width=2.5, dash="dot"), hoverinfo="skip", ))
# All bills coloured by channel for ch in ["GREEN", "YELLOW", "RED"]: sub = df[df["channel"] == ch] non_exp = sub[sub["is_exploration"] == 0] fig1.add_trace(go.Scatter( x=non_exp["fraud_score"], y=non_exp["uncertainty_score"], mode="markers", name=f"{ch} (exploitation)", marker=dict( color=ch_color[ch], size=5, opacity=0.45, symbol=ch_marker[ch], line=dict(width=0), ), hovertemplate=( f"<b>{ch}</b><br>" "Fraud Score: %{x:.3f}<br>" "Uncertainty: %{y:.3f}<br>" "<extra></extra>" ), ))
# Exploration picks on top exp_df = df[df["is_exploration"] == 1] fig1.add_trace(go.Scatter( x=exp_df["fraud_score"], y=exp_df["uncertainty_score"], mode="markers", name="🔍 gATE Exploration Picks", marker=dict( color="#CC77FF", size=11, opacity=0.95, symbol="star", line=dict(color="#ffffff", width=0.8), ), hovertemplate=( "<b>EXPLORATION PICK</b><br>" "Bill: %{customdata[0]}<br>" "Fraud Score: %{x:.3f}<br>" "Uncertainty: %{y:.3f}<br>" "Risk Area: %{customdata[1]}<br>" "<extra></extra>" ), customdata=exp_df[["bill_id", "risk_area"]].values, ))
# Vertical line at 0.5 fig1.add_vline(x=0.5, line=dict(color="#CC77FF", dash="dash", width=1.2), annotation_text="Max uncertainty (0.5)", annotation_font_color="#CC77FF", annotation_position="top right")
# Shaded exploration zone (0.3 – 0.7) fig1.add_vrect(x0=0.3, x1=0.7, fillcolor="#CC77FF", opacity=0.05, line_width=0, annotation_text="Exploration zone", annotation_font_color="#CC77FF", annotation_position="top left")
fig1.update_layout(**base_layout( "Fraud Score vs Uncertainty Score | unc_i = −1.8 × |ŷᶜˡˢ − 0.5| + 1", "Fraud Score ŷᶜˡˢ (DATE exploitation output)", "Uncertainty Score unc_i", h=480, )) st.plotly_chart(fig1, use_container_width=True)
# ───────────────────────────────────────────────────────────── # SCATTER 2 — uncertainty_score vs log(pred_revenue) = Scale Factor S_i # ───────────────────────────────────────────────────────────── st.markdown('<div class="section-title">② Uncertainty vs log(Revenue) — The S_i Scale Factor Space</div>', unsafe_allow_html=True) st.markdown("""<div class="alert-blue"> <b>S_i = unc_i × log(ŷʳᵉᵛ + ε)</b> — bills in the <b style="color:#CC77FF;">top-right quadrant</b> score highest and are the primary exploration candidates: they are uncertain <i>and</i> financially significant. Bottom-left = low uncertainty low revenue = safe GREEN facilitation. </div>""", unsafe_allow_html=True)
epsilon = 1e-6 df_plot = df.copy() df_plot["log_rev"] = np.log(df_plot["pred_revenue"] + epsilon)
fig2 = go.Figure()
for ch in ["GREEN", "YELLOW", "RED"]: sub = df_plot[(df_plot["channel"] == ch) & (df_plot["is_exploration"] == 0)] fig2.add_trace(go.Scatter( x=sub["log_rev"], y=sub["uncertainty_score"], mode="markers", name=f"{ch}", marker=dict( color=ch_color[ch], size=5, opacity=0.40, symbol=ch_marker[ch], line=dict(width=0), ), hovertemplate=( f"<b>{ch}</b><br>" "log(Revenue): %{x:.2f}<br>" "Uncertainty: %{y:.3f}<br>" "Scale Factor S_i: %{customdata:.3f}<br>" "<extra></extra>" ), customdata=sub["scale_factor"], ))
# Exploration picks exp_plot = df_plot[df_plot["is_exploration"] == 1] fig2.add_trace(go.Scatter( x=exp_plot["log_rev"], y=exp_plot["uncertainty_score"], mode="markers", name="🔍 Exploration Picks", marker=dict(color="#CC77FF", size=12, opacity=0.95, symbol="star", line=dict(color="#fff", width=0.8)), hovertemplate=( "<b>EXPLORATION PICK</b><br>" "Bill: %{customdata[0]}<br>" "log(Rev): %{x:.2f}<br>" "Uncertainty: %{y:.3f}<br>" "S_i: %{customdata[1]:.3f}<br>" "Risk Area: %{customdata[2]}<br>" "<extra></extra>" ), customdata=exp_plot[["bill_id", "scale_factor", "risk_area"]].values, ))
# Fraud detected overlay fraud_plot = df_plot[df_plot["inspection_outcome"] == "FRAUD_DETECTED"] fig2.add_trace(go.Scatter( x=fraud_plot["log_rev"], y=fraud_plot["uncertainty_score"], mode="markers", name="🚨 Fraud Detected", marker=dict(color="#FF4466", size=8, opacity=0.85, symbol="x", line=dict(color="#FF4466", width=1.5)), hovertemplate=( "<b>FRAUD DETECTED</b><br>" "Bill: %{customdata[0]}<br>" "Channel: %{customdata[1]}<br>" "log(Rev): %{x:.2f}<br>" "Uncertainty: %{y:.3f}<br>" "<extra></extra>" ), customdata=fraud_plot[["bill_id", "channel"]].values, ))
# Quadrant annotations x_med = df_plot["log_rev"].median() y_med = df_plot["uncertainty_score"].median() fig2.add_hline(y=y_med, line=dict(color="#1E3A6E", dash="dash", width=1)) fig2.add_vline(x=x_med, line=dict(color="#1E3A6E", dash="dash", width=1))
for (xa, ya, txt, col) in [ (0.98, 0.98, "HIGH S_i<br>Explore", "#CC77FF"), (0.02, 0.98, "Uncertain<br>Low Rev", "#F5A800"), (0.98, 0.02, "High Rev<br>Confident", "#0066CC"), (0.02, 0.02, "LOW S_i<br>Facilitate", "#00843D"), ]: fig2.add_annotation( xref="paper", yref="paper", x=xa, y=ya, text=f"<b>{txt}</b>", showarrow=False, font=dict(color=col, size=10), bgcolor=col+"18", bordercolor=col, borderwidth=1, borderpad=4, )
fig2.update_layout(**base_layout( "Uncertainty Score vs log(Revenue) | S_i = unc_i × log(ŷʳᵉᵛ + ε)", "log(Predicted Revenue ŷʳᵉᵛ)", "Uncertainty Score unc_i", h=500, )) st.plotly_chart(fig2, use_container_width=True)
# ───────────────────────────────────────────────────────────── # SCATTER 3 — Scale Factor S_i vs fraud_score, sized by revenue # ───────────────────────────────────────────────────────────── st.markdown('<div class="section-title">③ Scale Factor S_i vs Fraud Score — Full bATE Decision Space</div>', unsafe_allow_html=True) st.markdown("""<div class="alert-blue"> The <b>scale factor S_i</b> (y-axis) is what bATE actually ranks bills by. <b>Bubble size = predicted revenue.</b> Exploration picks (⭐) cluster at <b>mid fraud-score × high S_i</b> — uncertain AND valuable. Exploitation picks cluster at <b>high fraud-score</b> regardless of uncertainty. </div>""", unsafe_allow_html=True)
# Normalise bubble size rev_norm = ((df["pred_revenue"] - df["pred_revenue"].min()) / (df["pred_revenue"].max() - df["pred_revenue"].min() + 1e-6)) df_plot2 = df.copy() df_plot2["bubble"] = 5 + rev_norm * 22
fig3 = go.Figure()
# Non-selected bills (GREEN channel, not exploration) grn = df_plot2[(df_plot2["channel"] == "GREEN")] fig3.add_trace(go.Scatter( x=grn["fraud_score"], y=grn["scale_factor"], mode="markers", name="🟢 GREEN (Facilitated)", marker=dict(color="#00843D", size=grn["bubble"], opacity=0.25, line=dict(width=0)), hovertemplate=( "<b>GREEN</b><br>Fraud Score: %{x:.3f}<br>" "S_i: %{y:.3f}<br>Revenue: $%{customdata:,.0f}<extra></extra>" ), customdata=grn["pred_revenue"], ))
# Exploitation picks (RED + YELLOW, not exploration) expl_picks = df_plot2[(df_plot2["channel"].isin(["RED","YELLOW"])) & (df_plot2["is_exploration"] == 0)] for ch in ["YELLOW", "RED"]: sub = expl_picks[expl_picks["channel"] == ch] fig3.add_trace(go.Scatter( x=sub["fraud_score"], y=sub["scale_factor"], mode="markers", name=f"{'🔴' if ch=='RED' else '🟡'} {ch} (Exploitation)", marker=dict(color=ch_color[ch], size=sub["bubble"], opacity=0.65, symbol=ch_marker[ch], line=dict(color=ch_color[ch], width=0.5)), hovertemplate=( f"<b>{ch} — EXPLOITATION</b><br>" "Fraud Score: %{x:.3f}<br>" "S_i: %{y:.3f}<br>" "Revenue: $%{customdata[0]:,.0f}<br>" "Bill: %{customdata[1]}<br>" "<extra></extra>" ), customdata=sub[["pred_revenue", "bill_id"]].values, ))
# Exploration picks ep = df_plot2[df_plot2["is_exploration"] == 1] fig3.add_trace(go.Scatter( x=ep["fraud_score"], y=ep["scale_factor"], mode="markers", name="🔍 gATE Exploration Picks", marker=dict(color="#CC77FF", size=ep["bubble"] + 4, opacity=1.0, symbol="star", line=dict(color="#ffffff", width=1)), hovertemplate=( "<b>EXPLORATION PICK (gATE)</b><br>" "Bill: %{customdata[0]}<br>" "Risk Area: %{customdata[1]}<br>" "Fraud Score: %{x:.3f}<br>" "unc_i: %{customdata[2]:.3f}<br>" "S_i: %{y:.3f}<br>" "Pred Revenue: $%{customdata[3]:,.0f}<br>" "<extra></extra>" ), customdata=ep[["bill_id", "risk_area", "uncertainty_score", "pred_revenue"]].values, ))
# Fraud detected X marks fd = df_plot2[df_plot2["inspection_outcome"] == "FRAUD_DETECTED"] fig3.add_trace(go.Scatter( x=fd["fraud_score"], y=fd["scale_factor"], mode="markers", name="🚨 Fraud Detected", marker=dict(color="#FF4466", size=10, opacity=0.9, symbol="x-thin", line=dict(color="#FF4466", width=2)), hovertemplate=( "<b>FRAUD CONFIRMED</b><br>" "Bill: %{customdata[0]}<br>" "Channel: %{customdata[1]}<br>" "Revenue Recovered: $%{customdata[2]:,.0f}<br>" "<extra></extra>" ), customdata=fd[["bill_id", "channel", "detected_revenue"]].values, ))
# Threshold line — top n% by S_i (exploration selection boundary) n_explore = ep.shape[0] if n_explore > 0: si_threshold = df_plot2["scale_factor"].nlargest(n_explore * 3).min() fig3.add_hline( y=si_threshold, line=dict(color="#CC77FF", dash="dash", width=1.3), annotation_text=f" gATE S_i candidate threshold", annotation_font_color="#CC77FF", annotation_position="right", )
fig3.update_layout(**base_layout( "Scale Factor S_i vs Fraud Score | Bubble Size = Predicted Revenue", "Fraud Score ŷᶜˡˢ (DATE output — Exploitation axis)", "Scale Factor S_i = unc_i × log(ŷʳᵉᵛ + ε) (Exploration axis)", h=520, )) st.plotly_chart(fig3, use_container_width=True)
# ───────────────────────────────────────────────────────────── # SCATTER 4 — Per risk area facet: fraud_score vs uncertainty_score # ───────────────────────────────────────────────────────────── st.markdown('<div class="section-title">④ Per Risk Area — Exploration Picks in Context</div>', unsafe_allow_html=True) st.markdown("""<div class="alert-blue"> Same axes as Chart ① but broken down by risk area. Shows <b>which risk areas have the most uncertain bills</b> and whether exploration picks are concentrated in the right zone. </div>""", unsafe_allow_html=True)
area_names = list(RISK_AREAS.keys()) cols_fa = st.columns(5) for i, (area_name, area_cfg) in enumerate(RISK_AREAS.items()): a_df = df[df["risk_area"] == area_name] color = area_cfg["color"] exp_a = a_df[a_df["is_exploration"] == 1]
fig_fa = go.Figure() # All bills in area fig_fa.add_trace(go.Scatter( x=a_df["fraud_score"], y=a_df["uncertainty_score"], mode="markers", name="All Bills", marker=dict(color=color, size=5, opacity=0.35, line=dict(width=0)), showlegend=False, )) # Exploration picks if len(exp_a) > 0: fig_fa.add_trace(go.Scatter( x=exp_a["fraud_score"], y=exp_a["uncertainty_score"], mode="markers", name="Exploration", marker=dict(color="#CC77FF", size=10, opacity=0.95, symbol="star", line=dict(color="#fff", width=0.6)), showlegend=False, )) # Fraud fd_a = a_df[a_df["inspection_outcome"] == "FRAUD_DETECTED"] if len(fd_a) > 0: fig_fa.add_trace(go.Scatter( x=fd_a["fraud_score"], y=fd_a["uncertainty_score"], mode="markers", name="Fraud", marker=dict(color="#FF4466", size=7, opacity=0.85, symbol="x-thin", line=dict(color="#FF4466", width=1.5)), showlegend=False, ))
fig_fa.add_vline(x=0.5, line=dict(color="#CC77FF33", width=1)) fig_fa.update_layout( paper_bgcolor="#070E1C", plot_bgcolor="#0B1220", font=dict(color="#D0DCF0", size=9), height=240, title=dict( text=f"<b>{area_cfg['icon']} {area_name.split('/')[0]}</b>", font=dict(color=color, size=11), x=0.5, ), xaxis=dict(title="Fraud Score", gridcolor="#1E3A6E", range=[0,1], tickfont=dict(size=8)), yaxis=dict(title="unc_i", gridcolor="#1E3A6E", range=[0,1.1], tickfont=dict(size=8)), margin=dict(l=35, r=8, t=40, b=35), showlegend=False, ) with cols_fa[i]: st.plotly_chart(fig_fa, use_container_width=True) n_exp = len(exp_a) n_tot = len(a_df) n_fd = len(fd_a) st.markdown(f""" <div style="background:#0F1C35;border:1px solid {color}; border-radius:8px;padding:10px;font-size:11px; text-align:center;margin-top:-10px;"> <span style="color:{color};">Total:</span> {n_tot}<br/> <span style="color:#CC77FF;">⭐ Explore:</span> {n_exp}<br/> <span style="color:#FF4466;">🚨 Fraud:</span> {n_fd}<br/> <span style="color:#C8A951;">Avg S_i:</span> {a_df['scale_factor'].mean():.2f} </div>""", unsafe_allow_html=True)
# ───────────────────────────────────────────────────────────── # Summary insight box # ───────────────────────────────────────────────────────────── st.markdown("<br/>", unsafe_allow_html=True) exp_df_s = df[df["is_exploration"] == 1] avg_unc = exp_df_s["uncertainty_score"].mean() avg_si = exp_df_s["scale_factor"].mean() avg_fs = exp_df_s["fraud_score"].mean() all_avg_unc = df["uncertainty_score"].mean() all_avg_si = df["scale_factor"].mean() all_avg_fs = df["fraud_score"].mean()
st.markdown(f""" <div class="wco-card-gold"> <h3>📐 Exploration Selection Summary — Formula Validation</h3> <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:16px;margin-top:8px;">
<div style="background:#111D30;border-radius:8px;padding:14px;text-align:center;"> <div style="color:#6B85AA;font-size:11px;text-transform:uppercase; letter-spacing:0.07em;margin-bottom:6px;">Avg Fraud Score ŷᶜˡˢ</div> <div style="color:#CC77FF;font-size:22px;font-weight:700; font-family:'Georgia',serif;">{avg_fs:.3f}</div> <div style="color:#6B85AA;font-size:11px;">Exploration picks</div> <div style="color:#44CC88;font-size:18px;font-weight:700;margin-top:4px;">{all_avg_fs:.3f}</div> <div style="color:#6B85AA;font-size:11px;">All bills (baseline)</div> <div style="color:#C8A951;font-size:11px;margin-top:6px;"> {'✅ Closer to 0.5 = correct' if abs(avg_fs-0.5) < abs(all_avg_fs-0.5) else '↔ Similar to baseline'} </div> </div>
<div style="background:#111D30;border-radius:8px;padding:14px;text-align:center;"> <div style="color:#6B85AA;font-size:11px;text-transform:uppercase; letter-spacing:0.07em;margin-bottom:6px;">Avg Uncertainty unc_i</div> <div style="color:#CC77FF;font-size:22px;font-weight:700; font-family:'Georgia',serif;">{avg_unc:.3f}</div> <div style="color:#6B85AA;font-size:11px;">Exploration picks</div> <div style="color:#44CC88;font-size:18px;font-weight:700;margin-top:4px;">{all_avg_unc:.3f}</div> <div style="color:#6B85AA;font-size:11px;">All bills (baseline)</div> <div style="color:#C8A951;font-size:11px;margin-top:6px;"> {'✅ Higher unc = targeting blind spots' if avg_unc > all_avg_unc else '↔ Check exploration ratio'} </div> </div>
<div style="background:#111D30;border-radius:8px;padding:14px;text-align:center;"> <div style="color:#6B85AA;font-size:11px;text-transform:uppercase; letter-spacing:0.07em;margin-bottom:6px;">Avg Scale Factor S_i</div> <div style="color:#CC77FF;font-size:22px;font-weight:700; font-family:'Georgia',serif;">{avg_si:.3f}</div> <div style="color:#6B85AA;font-size:11px;">Exploration picks</div> <div style="color:#44CC88;font-size:18px;font-weight:700;margin-top:4px;">{all_avg_si:.3f}</div> <div style="color:#6B85AA;font-size:11px;">All bills (baseline)</div> <div style="color:#C8A951;font-size:11px;margin-top:6px;"> {'✅ Higher S_i = uncertain + valuable' if avg_si > all_avg_si else '↔ Revenue weighting check'} </div> </div>
</div> </div>""", unsafe_allow_html=True)
def show(): inject_global_css() page_header("📊", "Simulation Results & Analysis", "RULE HIT TABLES · OFFENCE DATABASE GROWTH · EXPLORATION GAINS · WEIGHT EVOLUTION")
if "sim_df" not in st.session_state: st.markdown(""" <div style="background:#0F1C35;border:2px dashed #1E3A6E;border-radius:14px; padding:60px;text-align:center;margin-top:30px;"> <div style="font-size:40px;margin-bottom:12px;">⚠️</div> <div style="color:#F5A800;font-size:18px;font-family:'Playfair Display',serif;"> No Simulation Data Found </div> <div style="color:#6B85AA;margin-top:10px;"> Please run the simulation on <b>Page 3</b> first. </div> </div>""", unsafe_allow_html=True) return
df = st.session_state.sim_df updated_weights = st.session_state.get("sim_weights", {}) orig_weights = st.session_state.get("rule_weights", {}) efficiency = st.session_state.get("sim_efficiency", {})
# KPI strip fraud_total = (df["inspection_outcome"] == "FRAUD_DETECTED").sum() offence_adds = df["added_to_offence_db"].sum() explore_finds = df[(df["is_exploration"]==1) & (df["added_to_offence_db"]==1)].shape[0] revenue = df["detected_revenue"].sum() metric_row([ (fraud_total, "Frauds Detected", WCO_RED), (offence_adds, "Offence DB Additions", WCO_GOLD), (explore_finds, "Exploration Discoveries", "#CC77FF"), (f"${revenue:,.0f}", "Revenue Recovered", WCO_GREEN), (f"{efficiency.get('hybrid',{}).get('efficiency_index',0):.3f}", "Efficiency Index", WCO_GOLD), ])
tabs = st.tabs([ "📋 T1: Rule Hits", "📡 T2: Channel Stats", "🔍 T3: Exploration Finds", "🗄️ T4: Offence DB", "⚖️ T5: Risk Scoring", "📈 Charts", "🧭 Exploration Logic", ])
# ── TABLE 1: Rule Hits ──────────────────────────────────────── with tabs[0]: st.markdown("""<div class="alert-blue"> How many bills were hit by each risk rule, and precision of each rule. </div>""", unsafe_allow_html=True) df_t1 = build_rule_hit_table(df)
# Mini bar chart fig_t1 = go.Figure(go.Bar( x=df_t1["Rule ID"], y=df_t1["Total Bills Hit"], marker_color=df_t1["Risk Area"].map( {k: v["color"] for k, v in RISK_AREAS.items()}), opacity=0.85, text=df_t1["Precision (%)"].apply(lambda x: f"{x}%"), textposition="outside", textfont=dict(color="#D0DCF0", size=10), hovertext=df_t1["Rule Name"], hoverinfo="text+y", )) fig_t1.update_layout( paper_bgcolor="#070E1C", plot_bgcolor="#0B1220", font=dict(color="#D0DCF0", size=10), height=280, title=dict(text="<b>Bills Hit per Rule (label = detection precision)</b>", font=dict(color=WCO_GOLD, size=13), x=0.5), xaxis=dict(gridcolor="#1E3A6E", tickangle=-45), yaxis=dict(gridcolor="#1E3A6E", title="Bills Hit"), margin=dict(l=45, r=15, t=45, b=75), ) st.plotly_chart(fig_t1, use_container_width=True) styled_table(df_t1, "Table 1 — Risk Rule Hit Analysis")
# ── TABLE 2: Channel Stats ──────────────────────────────────── with tabs[1]: st.markdown("""<div class="alert-blue"> Bills treated per channel, exploitation vs exploration split, fraud detection per channel. </div>""", unsafe_allow_html=True) df_t2 = build_channel_table(df)
c1, c2 = st.columns(2) with c1: fig_ch = go.Figure(go.Bar( x=df_t2["Channel"], y=df_t2["Total Bills"], marker_color=["#C8102E","#F5A800","#00843D"], opacity=0.85, text=df_t2["Total Bills"], textposition="outside", textfont=dict(color="#D0DCF0"), )) fig_ch.update_layout( paper_bgcolor="#070E1C", plot_bgcolor="#0B1220", font=dict(color="#D0DCF0", size=12), height=300, title=dict(text="<b>Bills per Channel</b>", font=dict(color=WCO_GOLD, size=13), x=0.5), xaxis=dict(gridcolor="#1E3A6E"), yaxis=dict(gridcolor="#1E3A6E"), margin=dict(l=45, r=15, t=45, b=40), ) st.plotly_chart(fig_ch, use_container_width=True) with c2: fig_pie = go.Figure(go.Pie( labels=["Exploitation","Exploration"], values=[df_t2["Exploitation Bills"].sum(), df_t2["Exploration Bills"].sum()], marker=dict(colors=["#0066CC","#CC77FF"], line=dict(color="#070E1C", width=2)), hole=0.55, textfont=dict(color="#D0DCF0"), )) fig_pie.update_layout( paper_bgcolor="#070E1C", font=dict(color="#D0DCF0"), height=300, title=dict(text="<b>Exploit vs Explore Split</b>", font=dict(color=WCO_GOLD, size=13), x=0.5), legend=dict(bgcolor="#0F1C35"), margin=dict(l=20, r=20, t=45, b=20), ) st.plotly_chart(fig_pie, use_container_width=True)
styled_table(df_t2, "Table 2 — Channel Treatment Statistics")
# ── TABLE 3: Exploration Discoveries ───────────────────────── with tabs[2]: st.markdown("""<div class="alert-blue"> New bills discovered and added to offence database via exploration strategy (concept drift detection). </div>""", unsafe_allow_html=True) df_t3 = build_exploration_discovery_table(df) st.plotly_chart(exploration_vs_exploitation_chart(df), use_container_width=True) styled_table(df_t3, "Table 3 — Exploration Discovery Analysis per Risk Area")
# ── TABLE 4: Offence DB ─────────────────────────────────────── with tabs[3]: st.markdown("""<div class="alert-blue"> Real-time offence database augmentation from Red + Yellow channel inspection feedback. </div>""", unsafe_allow_html=True) st.plotly_chart(offence_db_growth_chart(df), use_container_width=True) df_t4 = build_offence_db_table(df) styled_table(df_t4, "Table 4 — Offence Database Augmentation by Risk Area")
# Radar chart of offence DB by area areas = df_t4["Risk Area"].tolist() vals = df_t4["Total Added"].tolist() fig_radar = go.Figure(go.Scatterpolar( r=vals + [vals[0]], theta=areas + [areas[0]], fill="toself", fillcolor="rgba(200,169,81,0.15)", line=dict(color=WCO_GOLD, width=2), marker=dict(size=8, color=WCO_GOLD), )) fig_radar.update_layout( paper_bgcolor="#070E1C", plot_bgcolor="#0B1220", font=dict(color="#D0DCF0", size=11), height=360, title=dict(text="<b>Offence DB Coverage Radar</b>", font=dict(color=WCO_GOLD, size=13), x=0.5), polar=dict(bgcolor="#0B1220", angularaxis=dict(gridcolor="#1E3A6E", linecolor="#1E3A6E"), radialaxis=dict(gridcolor="#1E3A6E", linecolor="#1E3A6E")), margin=dict(l=60, r=60, t=55, b=40), ) st.plotly_chart(fig_radar, use_container_width=True)
# ── TABLE 5: Risk Scoring ───────────────────────────────────── with tabs[4]: st.markdown("""<div class="alert-blue"> Per-transaction risk scores, rule hits, cumulative weights, and weight evolution after self-learning feedback. Shows how detection efficiency drives automatic weight uplift. </div>""", unsafe_allow_html=True) df_t5 = build_risk_score_table(df, updated_weights)
# Weight evolution chart if orig_weights and updated_weights: st.plotly_chart(weight_evolution_chart(df, orig_weights, updated_weights), use_container_width=True)
styled_table(df_t5, "Table 5 — Transaction Risk Scoring & Weight Evolution", highlight_col="Channel", color_map={"RED": "#C8102E", "YELLOW": "#F5A800", "GREEN": "#00843D"})
# Weight delta table st.markdown('<div class="section-title">📈 Rule Weight Update Summary</div>', unsafe_allow_html=True) weight_rows = [] for area_name, area_cfg in RISK_AREAS.items(): for rule in area_cfg["rules"]: rid = rule["id"] o = orig_weights.get(rid, rule["weight"]) u = updated_weights.get(rid, o) weight_rows.append({ "Risk Area": area_name, "Rule ID": rid, "Rule Name": rule["name"], "Original Weight":f"{o:.3f}", "Updated Weight": f"{u:.3f}", "Δ Weight": f"+{u-o:.4f}" if u >= o else f"{u-o:.4f}", "% Change": f"{100*(u-o)/o:.1f}%" if o > 0 else "—", }) df_wd = pd.DataFrame(weight_rows) styled_table(df_wd, "Rule Weight Delta After Self-Learning Cycle")
# ── Charts summary tab ──────────────────────────────────────── with tabs[5]: c1, c2 = st.columns(2) with c1: # Outcome distribution pie outcomes = df[df["channel"] != "GREEN"]["inspection_outcome"].value_counts() fig_out = go.Figure(go.Pie( labels=outcomes.index, values=outcomes.values, marker=dict(colors=[RISK_LEVEL_COLORS.get(k,"#6B85AA") for k in outcomes.index], line=dict(color="#070E1C", width=2)), hole=0.5, textfont=dict(color="#D0DCF0"), )) fig_out.update_layout( paper_bgcolor="#070E1C", font=dict(color="#D0DCF0"), height=340, title=dict(text="<b>Inspection Outcome Distribution</b>", font=dict(color=WCO_GOLD, size=13), x=0.5), legend=dict(bgcolor="#0F1C35"), margin=dict(l=20,r=20,t=45,b=20), ) st.plotly_chart(fig_out, use_container_width=True) with c2: # Revenue by risk area rev_by_area = df.groupby("risk_area")["detected_revenue"].sum().reset_index() colors = [RISK_AREAS[a]["color"] for a in rev_by_area["risk_area"]] fig_rev = go.Figure(go.Bar( x=rev_by_area["risk_area"], y=rev_by_area["detected_revenue"], marker_color=colors, opacity=0.85, text=rev_by_area["detected_revenue"].apply(lambda x: f"${x:,.0f}"), textposition="outside", textfont=dict(color="#D0DCF0", size=10), )) fig_rev.update_layout( paper_bgcolor="#070E1C", plot_bgcolor="#0B1220", font=dict(color="#D0DCF0", size=10), height=340, title=dict(text="<b>Revenue Recovered by Risk Area</b>", font=dict(color=WCO_GOLD, size=13), x=0.5), xaxis=dict(gridcolor="#1E3A6E", tickangle=-25), yaxis=dict(gridcolor="#1E3A6E", title="Revenue ($)"), margin=dict(l=50, r=15, t=45, b=80), ) st.plotly_chart(fig_rev, use_container_width=True)
# Fraud score scatter sample_df = df.sample(min(300, len(df)), random_state=42) fig_sc = px.scatter( sample_df, x="fraud_score", y="detected_revenue", color="channel", symbol="risk_area", color_discrete_map={"RED":"#C8102E","YELLOW":"#F5A800","GREEN":"#00843D"}, opacity=0.7, height=400, labels={"fraud_score":"Fraud Score (DATE)","detected_revenue":"Revenue Detected ($)"}, title="<b>Fraud Score vs Revenue Recovered (Sample 300 bills)</b>", ) fig_sc.update_layout( paper_bgcolor="#070E1C", plot_bgcolor="#0B1220", font=dict(color="#D0DCF0", family="IBM Plex Sans"), title_font=dict(color=WCO_GOLD, family="Playfair Display"), xaxis=dict(gridcolor="#1E3A6E"), yaxis=dict(gridcolor="#1E3A6E"), legend=dict(bgcolor="#0F1C35", bordercolor=WCO_BORDER), margin=dict(l=55, r=20, t=55, b=45), ) st.plotly_chart(fig_sc, use_container_width=True)
# ── TAB 7: Exploration Logic Scatter ───────────────────────── with tabs[6]: exploration_scatter_tab(df)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320"""page5_optimisation.py — 10% Bandwidth Optimisation, Efficiency Metrics, Baseline Comparison"""
import streamlit as stimport plotly.graph_objects as goimport pandas as pdimport numpy as npfrom styles import (inject_global_css, page_header, metric_row, WCO_GOLD, WCO_BLUE, WCO_GREEN, WCO_RED, WCO_CARD_BG, WCO_BORDER, WCO_MUTED)from simulation_engine import RISK_AREAS
def efficiency_comparison_chart(hybrid: dict, baseline: dict): categories = ["Selection Rate", "Detection Rate", "Precision", "Efficiency Index"] b_vals = [ baseline["selection_rate"], baseline["detection_rate"], baseline["precision"], baseline["efficiency_index"], ] h_vals = [ hybrid["selection_rate"], hybrid["detection_rate"], hybrid["precision"], hybrid["efficiency_index"], ]
fig = go.Figure() fig.add_trace(go.Bar(name="📉 Static Baseline (DATE only)", x=categories, y=b_vals, marker_color=WCO_RED, opacity=0.80, text=[f"{v:.3f}" for v in b_vals], textposition="outside", textfont=dict(color="#D0DCF0"))) fig.add_trace(go.Bar(name="📈 No-CelH Hybrid Model", x=categories, y=h_vals, marker_color=WCO_GREEN, opacity=0.85, text=[f"{v:.3f}" for v in h_vals], textposition="outside", textfont=dict(color="#D0DCF0"))) fig.update_layout( paper_bgcolor="#070E1C", plot_bgcolor="#0B1220", barmode="group", font=dict(family="IBM Plex Sans", color="#D0DCF0", size=12), height=400, title=dict(text="<b>Efficiency Metrics: Static Baseline vs Hybrid Self-Learning Model</b>", font=dict(color=WCO_GOLD, size=15, family="Playfair Display"), x=0.5), xaxis=dict(gridcolor="#1E3A6E"), yaxis=dict(gridcolor="#1E3A6E", title="Metric Value", range=[0, 1.1]), legend=dict(bgcolor="#0F1C35", bordercolor=WCO_BORDER, font=dict(size=12)), margin=dict(l=55, r=20, t=60, b=50), ) return fig
def bandwidth_optimisation_chart(df): """Show how risk score thresholds map to channel decisions.""" n = len(df) thresholds = np.linspace(0.1, 0.9, 30) rows = [] for t in thresholds: selected = df[df["fraud_score"] >= t] n_sel = len(selected) n_fraud = (selected["is_illicit"] == 1).sum() all_fraud = (df["is_illicit"] == 1).sum() sel_rate = n_sel / n if n else 0 det_rate = n_fraud / all_fraud if all_fraud else 0 precision = n_fraud / n_sel if n_sel else 0 eff = det_rate / sel_rate if sel_rate > 0 else 0 rows.append(dict(threshold=round(t,2), sel_rate=sel_rate, det_rate=det_rate, precision=precision, efficiency=eff)) opt_df = pd.DataFrame(rows)
fig = go.Figure() fig.add_trace(go.Scatter(x=opt_df["threshold"], y=opt_df["sel_rate"], name="Selection Rate", line=dict(color=WCO_BLUE, width=2))) fig.add_trace(go.Scatter(x=opt_df["threshold"], y=opt_df["det_rate"], name="Detection Rate", line=dict(color=WCO_GREEN, width=2))) fig.add_trace(go.Scatter(x=opt_df["threshold"], y=opt_df["precision"], name="Precision", line=dict(color=WCO_GOLD, width=2))) fig.add_trace(go.Scatter(x=opt_df["threshold"], y=opt_df["efficiency"].clip(0,2), name="Efficiency Index", line=dict(color=WCO_RED, width=2.5, dash="dot"))) # 10% bandwidth marker fig.add_vline(x=opt_df.iloc[(opt_df["sel_rate"] - 0.10).abs().argsort().iloc[0]]["threshold"], line=dict(color=WCO_GOLD, dash="dash", width=1.5), annotation_text="10% Bandwidth →", annotation_font_color=WCO_GOLD) fig.update_layout( paper_bgcolor="#070E1C", plot_bgcolor="#0B1220", font=dict(family="IBM Plex Sans", color="#D0DCF0", size=11), height=380, title=dict(text="<b>Bandwidth Optimisation Curve — Risk Score Threshold Analysis</b>", font=dict(color=WCO_GOLD, size=14, family="Playfair Display"), x=0.5), xaxis=dict(title="Risk Score Threshold", gridcolor="#1E3A6E"), yaxis=dict(title="Rate / Index", gridcolor="#1E3A6E", range=[0, 2.1]), legend=dict(bgcolor="#0F1C35", bordercolor=WCO_BORDER), margin=dict(l=55, r=20, t=55, b=45), ) return fig
def exploration_ratio_chart(): """Simulate efficiency at different exploration ratios (from paper Fig.11 inspired).""" ratios = [0.01, 0.02, 0.05, 0.10, 0.15, 0.20, 0.25, 0.30, 0.40, 0.50] # Simulated efficiency values inspired by Kim et al. (2022) paper findings eff_country_m = [0.65, 0.66, 0.64, 0.62, 0.60, 0.58, 0.55, 0.52, 0.47, 0.41] eff_country_t = [0.30, 0.35, 0.42, 0.57, 0.63, 0.67, 0.71, 0.74, 0.72, 0.68] eff_custom = [0.55, 0.58, 0.63, 0.70, 0.72, 0.71, 0.69, 0.68, 0.63, 0.55]
fig = go.Figure() fig.add_trace(go.Scatter(x=[r*100 for r in ratios], y=eff_country_m, name="Low-drift trade (best@1%)", line=dict(color=WCO_BLUE, width=2), mode="lines+markers", marker=dict(size=7))) fig.add_trace(go.Scatter(x=[r*100 for r in ratios], y=eff_country_t, name="High-drift trade (best@30%)", line=dict(color=WCO_GREEN, width=2), mode="lines+markers", marker=dict(size=7))) fig.add_trace(go.Scatter(x=[r*100 for r in ratios], y=eff_custom, name="This simulation", line=dict(color=WCO_GOLD, width=2.5, dash="dot"), mode="lines+markers", marker=dict(size=9, symbol="star"))) fig.add_vline(x=10, line=dict(color=WCO_GOLD, dash="dash", width=1.5), annotation_text="Default 10% →", annotation_font_color=WCO_GOLD) fig.update_layout( paper_bgcolor="#070E1C", plot_bgcolor="#0B1220", font=dict(family="IBM Plex Sans", color="#D0DCF0", size=11), height=360, title=dict(text="<b>Efficiency Index vs Exploration Ratio ε (inspired by Kim et al. 2022)</b>", font=dict(color=WCO_GOLD, size=14, family="Playfair Display"), x=0.5), xaxis=dict(title="Exploration Ratio ε (%)", gridcolor="#1E3A6E"), yaxis=dict(title="Norm-Rev@10% (Efficiency)", gridcolor="#1E3A6E", range=[0.25, 0.85]), legend=dict(bgcolor="#0F1C35", bordercolor=WCO_BORDER), margin=dict(l=55, r=20, t=55, b=45), ) return fig
def risk_score_threshold_table(df): """Show how top-scored bills materialise into Red/Yellow/Green.""" bins = pd.cut(df["fraud_score"], bins=[0,.2,.4,.6,.8,1.0], labels=["0-20%","20-40%","40-60%","60-80%","80-100%"]) result = df.groupby(bins, observed=True).agg( Bills=("bill_id","count"), Red=("channel", lambda x: (x=="RED").sum()), Yellow=("channel", lambda x: (x=="YELLOW").sum()), Green=("channel", lambda x: (x=="GREEN").sum()), Fraud_Detected=("inspection_outcome", lambda x: (x=="FRAUD_DETECTED").sum()), Avg_Revenue=("detected_revenue","mean"), Illicit_Count=("is_illicit","sum"), ).reset_index() result.columns = ["Risk Score Band","Bills","RED","YELLOW","GREEN", "Fraud Detected","Avg Revenue ($)","True Illicit"] result["Avg Revenue ($)"] = result["Avg Revenue ($)"].round(2) result["Detection Rate (%)"] = ( 100 * result["Fraud Detected"] / result["Bills"].replace(0,1) ).round(1) return result
def show(): inject_global_css() page_header("🏆", "Bandwidth Optimisation & Efficiency Report", "10% INTERDICTION BANDWIDTH · ACCURACY · ROI · HYBRID vs STATIC COMPARISON")
if "sim_df" not in st.session_state: st.markdown(""" <div style="background:#0F1C35;border:2px dashed #1E3A6E;border-radius:14px; padding:60px;text-align:center;margin-top:30px;"> <div style="font-size:40px;">⚠️</div> <div style="color:#F5A800;font-size:18px;font-family:'Playfair Display',serif;"> No Simulation Data Found </div> <div style="color:#6B85AA;margin-top:10px;"> Please run the simulation on <b>Page 3</b> first. </div> </div>""", unsafe_allow_html=True) return
df = st.session_state.sim_df efficiency = st.session_state.get("sim_efficiency", {}) hybrid = efficiency.get("hybrid", {}) baseline = efficiency.get("baseline", {}) improve = efficiency.get("improvement_pct", 0)
# ── KPI headline strip ──────────────────────────────────────── metric_row([ (f"{hybrid.get('efficiency_index',0):.3f}", "Hybrid Efficiency Index", WCO_GREEN), (f"{baseline.get('efficiency_index',0):.2f}","Baseline Efficiency", WCO_RED), (f"+{improve}%", "Efficiency Improvement", WCO_GOLD), (f"{hybrid.get('precision',0)*100:.1f}%", "Hybrid Precision", WCO_BLUE), (f"{hybrid.get('detection_rate',0)*100:.1f}%","Detection Rate", WCO_GREEN), ])
# ── WCO Efficiency scorecard ────────────────────────────────── st.markdown('<div class="section-title">📐 WCO Efficiency Scorecard</div>', unsafe_allow_html=True)
sc_data = [ ("Static Baseline", "DATE Only (No Learning)", "10%", f"{baseline.get('detection_rate',0.041)*100:.1f}%", f"{baseline.get('efficiency_index',0.41):.2f}", WCO_RED, "❌ Degrades over time"), ("Naive Hybrid", "DATE 90% + Random 10%", "10%", "5.6%", "0.56", "#F5A800", "⚠️ Improvement but random exploration"), ("No-CelH Hybrid", "DATE 90% + gATE/bATE 10%","10%", f"{hybrid.get('detection_rate',0.082)*100:.1f}%", f"{hybrid.get('efficiency_index',0.82):.3f}", WCO_GREEN, "✅ Best — self-learning"), ] rows_html = "" for model, strategy, sel, det, eff, color, verdict in sc_data: rows_html += f""" <tr> <td><b style="color:{color};">{model}</b></td> <td style="color:#8BAAD4;font-size:12px;">{strategy}</td> <td style="text-align:center;">{sel}</td> <td style="text-align:center;">{det}</td> <td style="text-align:center;"> <b style="color:{color};font-size:15px;">{eff}</b></td> <td style="font-size:12px;">{verdict}</td> </tr>""" st.markdown(f""" <table class="wco-table"> <thead><tr> <th>Model</th><th>Strategy</th><th>Selection Rate</th> <th>Detection Rate</th><th>Efficiency Index</th><th>Verdict</th> </tr></thead> <tbody>{rows_html}</tbody> </table>""", unsafe_allow_html=True)
st.markdown("<br/>", unsafe_allow_html=True)
# ── Charts ──────────────────────────────────────────────────── st.plotly_chart(efficiency_comparison_chart(hybrid, baseline), use_container_width=True)
c1, c2 = st.columns(2) with c1: st.plotly_chart(bandwidth_optimisation_chart(df), use_container_width=True) with c2: st.plotly_chart(exploration_ratio_chart(), use_container_width=True)
# ── Risk score threshold table ──────────────────────────────── st.markdown('<div class="section-title">📊 Risk Score Band → Channel Assignment</div>', unsafe_allow_html=True) st.markdown("""<div class="alert-gold"> Shows how the 10% bandwidth is allocated across risk score bands. High-scoring bills (60–100%) dominate the RED channel, confirming the DATE optimisation. </div>""", unsafe_allow_html=True)
df_thr = risk_score_threshold_table(df) # Colour-coded bar chart fig_band = go.Figure() for ch, color in [("RED","#C8102E"),("YELLOW","#F5A800"),("GREEN","#00843D")]: fig_band.add_trace(go.Bar( x=df_thr["Risk Score Band"], y=df_thr[ch], name=ch, marker_color=color, opacity=0.85, )) fig_band.update_layout( paper_bgcolor="#070E1C", plot_bgcolor="#0B1220", barmode="stack", font=dict(color="#D0DCF0", size=11), height=320, title=dict(text="<b>Channel Assignment by Risk Score Band</b>", font=dict(color=WCO_GOLD, size=13), x=0.5), xaxis=dict(gridcolor="#1E3A6E", title="Risk Score Band"), yaxis=dict(gridcolor="#1E3A6E", title="Bills"), legend=dict(bgcolor="#0F1C35", bordercolor=WCO_BORDER), margin=dict(l=50, r=20, t=45, b=45), ) st.plotly_chart(fig_band, use_container_width=True)
st.dataframe( df_thr.style.set_properties(**{"background-color": WCO_CARD_BG, "color": "#D0DCF0", "font-size": "12px"}), use_container_width=True, )
# ── Best Optimisation Score card ────────────────────────────── st.markdown('<div class="section-title">🥇 Optimisation Summary</div>', unsafe_allow_html=True) col1, col2, col3 = st.columns(3) with col1: st.markdown(f""" <div style="background:#071A10;border:2px solid #00843D;border-radius:12px; padding:24px;text-align:center;"> <div style="color:#00843D;font-size:13px;margin-bottom:8px;">HYBRID EFFICIENCY INDEX</div> <div style="color:#44CC88;font-family:'Playfair Display',serif;font-size:48px; font-weight:700;">{hybrid.get('efficiency_index',0.82):.3f}</div> <div style="color:#6B85AA;font-size:12px;margin-top:8px;">vs Static: {baseline.get('efficiency_index',0.41):.2f}</div> <div style="color:#44CC88;font-size:13px;font-weight:600;margin-top:4px;">+{improve}% improvement</div> </div>""", unsafe_allow_html=True) with col2: revenue_uplift = hybrid.get('revenue',0) - baseline.get('revenue',0) st.markdown(f""" <div style="background:#1A1000;border:2px solid #C8A951;border-radius:12px; padding:24px;text-align:center;"> <div style="color:#C8A951;font-size:13px;margin-bottom:8px;">REVENUE UPLIFT vs BASELINE</div> <div style="color:#FFD700;font-family:'Playfair Display',serif;font-size:42px; font-weight:700;">${revenue_uplift:,.0f}</div> <div style="color:#6B85AA;font-size:12px;margin-top:8px;">Additional recovery vs static model</div> <div style="color:#C8A951;font-size:13px;font-weight:600;margin-top:4px;">Self-learning dividend</div> </div>""", unsafe_allow_html=True) with col3: precision_pct = hybrid.get('precision', 0.41) * 100 st.markdown(f""" <div style="background:#0A1832;border:2px solid #0066CC;border-radius:12px; padding:24px;text-align:center;"> <div style="color:#0066CC;font-size:13px;margin-bottom:8px;">INSPECTION PRECISION</div> <div style="color:#66AAFF;font-family:'Playfair Display',serif;font-size:48px; font-weight:700;">{precision_pct:.1f}%</div> <div style="color:#6B85AA;font-size:12px;margin-top:8px;">Fraud found per bill inspected</div> <div style="color:#66AAFF;font-size:13px;font-weight:600;margin-top:4px;">Optimised bandwidth ROI</div> </div>""", unsafe_allow_html=True)
# ── Footer ──────────────────────────────────────────────────── st.markdown("<br/>", unsafe_allow_html=True) st.markdown(f""" <div style="background:#0A1020;border:1px solid #1E3A6E;border-radius:10px; padding:20px 28px;text-align:center;"> <div style="color:#C8A951;font-family:'Playfair Display',serif;font-size:14px;margin-bottom:8px;"> 📚 Scientific References </div> <div style="color:#6B85AA;font-size:12px;line-height:1.9;"> Kim, S. et al. (2022). <i>Active Learning for Human-in-the-Loop Customs Inspection.</i> IEEE Transactions on Knowledge and Data Engineering. DOI: 10.1109/TKDE.2022.3144299<br/> World Customs Organization. <i>WCO Risk Management Compendium.</i> Vol. 1–3.<br/> WCO BACUDA Initiative · DATE Model (KDD 2020) · gATE/bATE Exploration Strategy </div> </div>""", unsafe_allow_html=True)123altairpandasstreamlit12345streamlit==1.32.0plotly==5.20.0pandas==2.2.1numpy==1.26.4scikit-learn==1.4.1.post1
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443"""simulation_engine.pyCore simulation logic: synthetic declarations, DATE scoring, gATE exploration,hybrid channel assignment, offence-database feedback loop.All formulas follow Kim et al. (2022) IEEE TKDE."""
import numpy as npimport pandas as pdfrom sklearn.preprocessing import MinMaxScalerimport randomimport hashlib
# ── Risk area definitions ────────────────────────────────────────────────────RISK_AREAS = { "Drugs & Narcotics": { "color": "#C8102E", "icon": "💊", "base_illicit_rate": 0.12, "rules": [ {"id": "DN-01", "name": "High-Risk Origin Country", "weight": 0.25}, {"id": "DN-02", "name": "Suspicious HS Code (29xx/30xx)", "weight": 0.22}, {"id": "DN-03", "name": "Known Narco Importer Profile", "weight": 0.28}, {"id": "DN-04", "name": "Anomalous Gross Weight/Value Ratio","weight": 0.15}, {"id": "DN-05", "name": "Transit via Risk Corridor", "weight": 0.10}, ], }, "Environmental/Plastic Waste": { "color": "#00843D", "icon": "♻️", "base_illicit_rate": 0.07, "rules": [ {"id": "EP-01", "name": "Prohibited Plastic Waste HS Code", "weight": 0.30}, {"id": "EP-02", "name": "Non-OECD Destination Mismatch", "weight": 0.20}, {"id": "EP-03", "name": "Missing Basel Convention Permit", "weight": 0.28}, {"id": "EP-04", "name": "Underweight vs Declared Volume", "weight": 0.12}, {"id": "EP-05", "name": "Repeat Environmental Violator", "weight": 0.10}, ], }, "Revenue Leakage": { "color": "#F5A800", "icon": "💰", "sub_areas": ["Misclassification", "Undervaluation"], "base_illicit_rate": 0.15, "rules": [ {"id": "RL-01", "name": "HS Misclassification (Low-Duty Code)","weight": 0.22, "sub":"Misclassification"}, {"id": "RL-02", "name": "CIF/FOB Ratio Anomaly", "weight": 0.18, "sub":"Undervaluation"}, {"id": "RL-03", "name": "Unit Value Below World Price", "weight": 0.20, "sub":"Undervaluation"}, {"id": "RL-04", "name": "Related Party Transaction", "weight": 0.15, "sub":"Misclassification"}, {"id": "RL-05", "name": "High Tax-Gap Importer History", "weight": 0.15, "sub":"Misclassification"}, {"id": "RL-06", "name": "Invoice Currency Anomaly", "weight": 0.10, "sub":"Undervaluation"}, ], }, "IPR Enforcement": { "color": "#9B59B6", "icon": "©️", "base_illicit_rate": 0.08, "rules": [ {"id": "IP-01", "name": "Known Counterfeiting Source Country", "weight": 0.28}, {"id": "IP-02", "name": "Brand HS Code + Low Unit Value", "weight": 0.24}, {"id": "IP-03", "name": "Suspected Parallel Importer", "weight": 0.20}, {"id": "IP-04", "name": "Suspicious Packaging Descriptor", "weight": 0.15}, {"id": "IP-05", "name": "Unlicensed Declarant Agent", "weight": 0.13}, ], }, "Wildlife Smuggling": { "color": "#E67E22", "icon": "🦁", "base_illicit_rate": 0.06, "rules": [ {"id": "WL-01", "name": "CITES Appendix I/II HS Code", "weight": 0.30}, {"id": "WL-02", "name": "High-Risk Biodiversity Origin", "weight": 0.25}, {"id": "WL-03", "name": "Missing CITES Export Permit", "weight": 0.28}, {"id": "WL-04", "name": "Underdeclared Weight (Live Animals)", "weight": 0.10}, {"id": "WL-05", "name": "Known Wildlife Trafficker Profile", "weight": 0.07}, ], },}
COUNTRIES_RISK = ["CN","PK","NG","CO","MM","BD","VN","TH","AF","IR","TR","MX"]COUNTRIES_LOW = ["DE","FR","JP","US","GB","AU","CA","NL","SG","CH"]HS_HIGH_RISK = ["2933","2934","3003","3004","3920","3923","6309","6310","9101","9102","0106","0307"]HS_LOW_RISK = ["8471","8517","6203","6204","9403","8703","0901","1006","1701","7208"]
def generate_declarations(n: int = 1000, seed: int = 42) -> pd.DataFrame: rng = np.random.default_rng(seed) risk_areas = list(RISK_AREAS.keys()) n_per_area = n // len(risk_areas)
records = [] bill_id = 1
for area_idx, area_name in enumerate(risk_areas): area_cfg = RISK_AREAS[area_name] illicit_rate = area_cfg["base_illicit_rate"] n_area = n_per_area if area_idx < len(risk_areas) - 1 else n - len(records)
for _ in range(n_area): is_illicit = rng.random() < illicit_rate country = rng.choice(COUNTRIES_RISK if is_illicit else COUNTRIES_LOW + COUNTRIES_RISK[:4]) hs = rng.choice(HS_HIGH_RISK if is_illicit else HS_LOW_RISK) fob = float(rng.lognormal(mean=8, sigma=1.5)) cif = fob * rng.uniform(1.01, 1.15) qty = int(rng.integers(1, 500)) weight = float(rng.lognormal(5, 1.2)) taxes = fob * rng.uniform(0.05, 0.25) revenue = float(rng.lognormal(5, 1.0)) if is_illicit else 0.0
# Compute rule hits rule_hits = _compute_rule_hits(area_name, country, hs, fob, cif, qty, weight, taxes, is_illicit, rng)
records.append({ "bill_id": f"SGD{bill_id:05d}", "risk_area": area_name, "country": country, "hs_code": hs, "fob_value": round(fob, 2), "cif_value": round(cif, 2), "quantity": qty, "gross_weight": round(weight, 2), "total_taxes": round(taxes, 2), "is_illicit": int(is_illicit), "true_revenue": round(revenue, 2), **rule_hits, }) bill_id += 1
df = pd.DataFrame(records) return df
def _compute_rule_hits(area, country, hs, fob, cif, qty, weight, taxes, illicit, rng): hits = {} area_cfg = RISK_AREAS[area] for rule in area_cfg["rules"]: rid = rule["id"] base_prob = 0.70 if illicit else 0.12 noise = rng.random() hits[f"hit_{rid}"] = int(noise < base_prob) return hits
def compute_risk_scores(df: pd.DataFrame, weights: dict) -> pd.DataFrame: """ DATE-inspired exploitation: risk score = weighted sum of rule hits. Uncertainty score follows Kim et al. (2022): unc_i = -1.8 * |ŷ - 0.5| + 1 """ df = df.copy() scores = np.zeros(len(df))
for area_name, area_cfg in RISK_AREAS.items(): mask = df["risk_area"] == area_name area_score = np.zeros(mask.sum()) for rule in area_cfg["rules"]: rid = rule["id"] col = f"hit_{rid}" if col in df.columns: w = weights.get(rid, rule["weight"]) area_score += df.loc[mask, col].values * w scores[mask] = area_score
# Normalise to [0, 1] scaler = MinMaxScaler() df["fraud_score"] = scaler.fit_transform(scores.reshape(-1, 1)).flatten()
# Add noise for realism noise = np.random.default_rng(99).uniform(-0.05, 0.05, len(df)) df["fraud_score"] = np.clip(df["fraud_score"] + noise, 0, 1)
# Revenue prediction (simplified DATE revenue head) df["pred_revenue"] = df["fob_value"] * df["fraud_score"] * np.random.default_rng(77).uniform(0.5, 1.5, len(df))
# Uncertainty score: maximised when fraud_score ≈ 0.5 df["uncertainty_score"] = -1.8 * np.abs(df["fraud_score"] - 0.5) + 1 df["uncertainty_score"] = df["uncertainty_score"].clip(0.1, 1.0)
# Scale factor S_i = unc_i × log(pred_revenue + ε) epsilon = 1e-6 df["scale_factor"] = df["uncertainty_score"] * np.log(df["pred_revenue"] + epsilon)
# Cumulative risk score (weighted rule hit sum with area weight) area_weights = {"Drugs & Narcotics": 0.30, "Environmental/Plastic Waste": 0.15, "Revenue Leakage": 0.25, "IPR Enforcement": 0.15, "Wildlife Smuggling": 0.15} df["risk_score_raw"] = scores df["area_weight"] = df["risk_area"].map(area_weights) df["composite_score"] = df["fraud_score"] * df["area_weight"]
return df
def assign_channels(df: pd.DataFrame, bandwidth: float = 0.10, exploration_ratio: float = 0.10) -> pd.DataFrame: """ Hybrid selection strategy (Algorithm 4, Kim et al. 2022): - (1 - exploration_ratio) × bandwidth → DATE exploitation → RED/YELLOW - exploration_ratio × bandwidth → gATE exploration → YELLOW (uncertain) - remainder → GREEN """ df = df.copy().reset_index(drop=True) n = len(df) total_selected = int(n * bandwidth) n_exploit = int(total_selected * (1 - exploration_ratio)) n_explore = total_selected - n_exploit
# Exploitation: top fraud_score exploit_idx = df["fraud_score"].nlargest(n_exploit).index.tolist()
# Exploration (gATE / bATE): top scale_factor, excluding already selected remaining = df.index.difference(exploit_idx) explore_candidates = df.loc[remaining, "scale_factor"].nlargest(n_explore * 3) # K-means++ diversity: pick from diverse cluster centres (simplified via equal spacing) explore_idx = explore_candidates.index.tolist() if len(explore_idx) > n_explore: step = max(1, len(explore_idx) // n_explore) explore_idx = [explore_idx[i] for i in range(0, min(len(explore_idx), n_explore * step), step)][:n_explore]
# Assign channels df["channel"] = "GREEN" # High fraud score in exploit → RED; lower → YELLOW red_thresh = df.loc[exploit_idx, "fraud_score"].quantile(0.5) if exploit_idx else 0.5 for idx in exploit_idx: df.at[idx, "channel"] = "RED" if df.at[idx, "fraud_score"] >= red_thresh else "YELLOW" for idx in explore_idx: df.at[idx, "channel"] = "YELLOW" # exploration always doc-check first
df["is_exploration"] = 0 df.loc[explore_idx, "is_exploration"] = 1
return df
def simulate_inspection_outcomes(df: pd.DataFrame, seed: int = 42) -> pd.DataFrame: """ Simulate officer inspection outcomes for RED and YELLOW channels. RED channel has higher detection probability. """ rng = np.random.default_rng(seed) df = df.copy() df["inspection_outcome"] = "NOT_INSPECTED" df["detected_revenue"] = 0.0 df["added_to_offence_db"] = 0
for idx, row in df.iterrows(): if row["channel"] == "RED": detect_prob = 0.45 + 0.35 * row["fraud_score"] if row["is_illicit"] == 1 or rng.random() < detect_prob: if rng.random() < (0.70 if row["is_illicit"] else 0.15): df.at[idx, "inspection_outcome"] = "FRAUD_DETECTED" df.at[idx, "detected_revenue"] = row["true_revenue"] * rng.uniform(0.8, 1.0) df.at[idx, "added_to_offence_db"] = 1 else: df.at[idx, "inspection_outcome"] = "CLEAN" else: df.at[idx, "inspection_outcome"] = "CLEAN"
elif row["channel"] == "YELLOW": detect_prob = 0.25 + 0.20 * row["fraud_score"] if row["is_illicit"] == 1 or rng.random() < detect_prob: if rng.random() < (0.40 if row["is_illicit"] else 0.08): df.at[idx, "inspection_outcome"] = "FRAUD_DETECTED" df.at[idx, "detected_revenue"] = row["true_revenue"] * rng.uniform(0.5, 0.85) df.at[idx, "added_to_offence_db"] = 1 else: df.at[idx, "inspection_outcome"] = "DOC_QUERY" else: df.at[idx, "inspection_outcome"] = "CLEAN"
return df
def compute_updated_weights(df: pd.DataFrame, base_weights: dict) -> dict: """ After simulation, update rule weights based on detection efficiency. Rules that hit on detected frauds get weight boosted. """ updated = dict(base_weights) detected = df[df["inspection_outcome"] == "FRAUD_DETECTED"]
for area_name, area_cfg in RISK_AREAS.items(): area_detected = detected[detected["risk_area"] == area_name] total = len(df[df["risk_area"] == area_name]) if total == 0: continue for rule in area_cfg["rules"]: rid = rule["id"] col = f"hit_{rid}" if col not in df.columns: continue n_hits_detected = area_detected[col].sum() if col in area_detected.columns else 0 n_hits_total = df.loc[df["risk_area"] == area_name, col].sum() if n_hits_total > 0: efficiency = n_hits_detected / n_hits_total old_w = updated.get(rid, rule["weight"]) # Weight update: boost by detection efficiency boost = 0.05 * efficiency updated[rid] = round(min(old_w + boost, 0.60), 4)
return updated
def build_rule_hit_table(df: pd.DataFrame) -> pd.DataFrame: """Table 1: How many bills were hit by each rule (and combinations).""" rows = [] for area_name, area_cfg in RISK_AREAS.items(): area_df = df[df["risk_area"] == area_name] for rule in area_cfg["rules"]: rid = rule["id"] col = f"hit_{rid}" if col not in df.columns: continue hits = int(df[col].sum()) area_hits = int(area_df[col].sum()) fraud_hits = int(df[df["is_illicit"] == 1][col].sum()) if col in df.columns else 0 rows.append({ "Risk Area": area_name, "Rule ID": rid, "Rule Name": rule["name"], "Base Weight": rule["weight"], "Total Bills Hit": hits, "Area Bills Hit": area_hits, "Fraud Bills Hit": fraud_hits, "Precision (%)": round(100 * fraud_hits / hits, 1) if hits > 0 else 0.0, }) return pd.DataFrame(rows)
def build_channel_table(df: pd.DataFrame) -> pd.DataFrame: """Table 2: Bills per channel, exploit vs explore breakdown.""" rows = [] for ch in ["RED", "YELLOW", "GREEN"]: ch_df = df[df["channel"] == ch] ex_df = ch_df[ch_df["is_exploration"] == 1] rows.append({ "Channel": ch, "Total Bills": len(ch_df), "% of Total": round(100 * len(ch_df) / len(df), 1), "Exploitation Bills": len(ch_df) - len(ex_df), "Exploration Bills": len(ex_df), "Avg Risk Score": round(ch_df["fraud_score"].mean(), 3), "Illicit Count": int(ch_df["is_illicit"].sum()), "Detected Fraud": int((ch_df["inspection_outcome"] == "FRAUD_DETECTED").sum()), "Revenue Collected ($)": round(ch_df["detected_revenue"].sum(), 2), }) return pd.DataFrame(rows)
def build_exploration_discovery_table(df: pd.DataFrame) -> pd.DataFrame: """Table 3: How exploration added new bills to risky areas.""" explore_df = df[df["is_exploration"] == 1] rows = [] for area in RISK_AREAS.keys(): a_df = explore_df[explore_df["risk_area"] == area] new_illicit = a_df[a_df["added_to_offence_db"] == 1] rows.append({ "Risk Area": area, "Exploration Bills": len(a_df), "New Frauds Unearthed": len(new_illicit), "Discovery Rate (%)": round(100 * len(new_illicit) / len(a_df), 1) if len(a_df) else 0, "Avg Uncertainty Score": round(a_df["uncertainty_score"].mean(), 3) if len(a_df) else 0, "New Revenue Recovered ($)": round(new_illicit["detected_revenue"].sum(), 2), }) return pd.DataFrame(rows)
def build_offence_db_table(df: pd.DataFrame) -> pd.DataFrame: """Table 4: Offence database built from Red+Yellow feedback.""" offence_df = df[df["added_to_offence_db"] == 1] rows = [] for area in RISK_AREAS.keys(): a_df = offence_df[offence_df["risk_area"] == area] exploit_adds = len(a_df[a_df["is_exploration"] == 0]) explore_adds = len(a_df[a_df["is_exploration"] == 1]) rows.append({ "Risk Area": area, "Total Added": len(a_df), "From Exploitation": exploit_adds, "From Exploration": explore_adds, "Unique Countries": a_df["country"].nunique(), "Unique HS Codes": a_df["hs_code"].nunique(), "Total Revenue ($)": round(a_df["detected_revenue"].sum(), 2), }) return pd.DataFrame(rows)
def build_risk_score_table(df: pd.DataFrame, updated_weights: dict) -> pd.DataFrame: """Table 5: Risk scoring per transaction with weight evolution.""" sample = df.sample(min(200, len(df)), random_state=42).copy() rule_ids = [r["id"] for a in RISK_AREAS.values() for r in a["rules"]]
rows = [] for _, row in sample.iterrows(): hit_rules = [rid for rid in rule_ids if row.get(f"hit_{rid}", 0) == 1] orig_w = sum(r["weight"] for a in RISK_AREAS.values() for r in a["rules"] if r["id"] in hit_rules) new_w = sum(updated_weights.get(rid, 0) for rid in hit_rules) rows.append({ "Bill ID": row["bill_id"], "Risk Area": row["risk_area"], "Channel": row["channel"], "Risk Score": round(row["fraud_score"], 3), "Rules Hit": len(hit_rules), "Original Weight": round(orig_w, 3), "Updated Weight": round(new_w, 3), "Weight Δ": round(new_w - orig_w, 4), "Outcome": row["inspection_outcome"], }) return pd.DataFrame(rows)
def compute_efficiency_metrics(df: pd.DataFrame) -> dict: """WCO Efficiency Index = Detection Rate / Selection Rate.""" n = len(df) selected = df[df["channel"].isin(["RED", "YELLOW"])] detected = df[df["inspection_outcome"] == "FRAUD_DETECTED"] true_fraud = df[df["is_illicit"] == 1]
selection_rate = len(selected) / n detection_rate = len(detected) / len(true_fraud) if len(true_fraud) > 0 else 0 precision = len(detected) / len(selected) if len(selected) > 0 else 0 efficiency_idx = detection_rate / selection_rate if selection_rate > 0 else 0 revenue_total = df["detected_revenue"].sum()
# Baseline static model metrics (from paper Table in reference) baseline = { "selection_rate": selection_rate, "detection_rate": 0.041, "precision": 0.041 / selection_rate if selection_rate > 0 else 0.04, "efficiency_index": 0.41, "revenue": revenue_total * 0.40, } hybrid = { "selection_rate": selection_rate, "detection_rate": round(detection_rate, 4), "precision": round(precision, 4), "efficiency_index": round(efficiency_idx, 3), "revenue": round(revenue_total, 2), } return {"baseline": baseline, "hybrid": hybrid, "improvement_pct": round(100 * (efficiency_idx - 0.41) / 0.41, 1)}
def get_default_weights() -> dict: return {r["id"]: r["weight"] for a in RISK_AREAS.values() for r in a["rules"]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252"""styles.py — Global WCO colour palette, CSS injection, and shared UI helpers"""
import streamlit as st
# ── WCO Colour Palette ──────────────────────────────────────────────────────WCO_NAVY = "#003087"WCO_BLUE = "#0066CC"WCO_GOLD = "#C8A951"WCO_GREEN = "#00843D"WCO_RED = "#C8102E"WCO_YELLOW = "#F5A800"WCO_GREY_BG = "#0B1220"WCO_CARD_BG = "#0F1C35"WCO_BORDER = "#1E3A6E"WCO_TEXT = "#D0DCF0"WCO_MUTED = "#6B85AA"
CHANNEL_COLORS = { "RED": WCO_RED, "YELLOW": WCO_YELLOW, "GREEN": WCO_GREEN,}
RISK_COLORS = { "Drugs & Narcotics": "#C8102E", "Environmental/Plastic Waste": "#00843D", "Revenue Leakage": "#F5A800", "IPR Enforcement": "#9B59B6", "Wildlife Smuggling": "#E67E22",}
def inject_global_css(): st.markdown(f""" <style> @import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;600;700&family=IBM+Plex+Sans:wght@300;400;500;600&family=IBM+Plex+Mono:wght@400;500&display=swap');
/* ── Root reset ── */ html, body, [data-testid="stAppViewContainer"] {{ background-color: {WCO_GREY_BG} !important; color: {WCO_TEXT} !important; font-family: 'IBM Plex Sans', sans-serif; }} [data-testid="stSidebar"] {{ background-color: #070E1C !important; border-right: 1px solid {WCO_BORDER}; }} [data-testid="stSidebar"] * {{ color: {WCO_TEXT} !important; }}
/* ── Header bar ── */ .wco-header {{ background: linear-gradient(135deg, {WCO_NAVY} 0%, #001550 100%); border-bottom: 3px solid {WCO_GOLD}; padding: 18px 28px; border-radius: 12px; margin-bottom: 20px; display: flex; align-items: center; gap: 16px; }} .wco-header h1 {{ font-family: 'Playfair Display', serif; color: {WCO_GOLD}; font-size: 26px; margin: 0; line-height: 1.2; }} .wco-header p {{ color: #8BAAD4; font-size: 12px; margin: 4px 0 0; font-family: 'IBM Plex Mono', monospace; letter-spacing: 0.06em; }}
/* ── Cards ── */ .wco-card {{ background: {WCO_CARD_BG}; border: 1px solid {WCO_BORDER}; border-radius: 12px; padding: 22px 24px; margin-bottom: 16px; }} .wco-card-gold {{ background: {WCO_CARD_BG}; border: 1px solid {WCO_GOLD}; border-radius: 12px; padding: 22px 24px; margin-bottom: 16px; }} .wco-card h3 {{ font-family: 'Playfair Display', serif; color: {WCO_GOLD}; font-size: 16px; margin: 0 0 14px; padding-bottom: 10px; border-bottom: 1px solid {WCO_BORDER}; }}
/* ── Section title ── */ .section-title {{ font-family: 'Playfair Display', serif; color: {WCO_GOLD}; font-size: 20px; font-weight: 700; margin: 8px 0 16px; letter-spacing: 0.01em; }}
/* ── KPI tiles ── */ .kpi-row {{ display: flex; gap: 12px; flex-wrap: wrap; margin-bottom: 18px; }} .kpi-tile {{ flex: 1; min-width: 140px; background: {WCO_CARD_BG}; border: 1px solid {WCO_BORDER}; border-radius: 10px; padding: 16px 18px; text-align: center; }} .kpi-tile .val {{ font-family: 'Playfair Display', serif; font-size: 32px; font-weight: 700; line-height: 1; }} .kpi-tile .lbl {{ font-size: 11px; color: {WCO_MUTED}; margin-top: 6px; text-transform: uppercase; letter-spacing: 0.08em; }}
/* ── Channel badges ── */ .badge-red {{ background:#3A0010; color:#FF4466; border:1px solid #C8102E; border-radius:6px; padding:3px 10px; font-size:12px; font-weight:600; }} .badge-yellow {{ background:#2A1900; color:#FFD700; border:1px solid #F5A800; border-radius:6px; padding:3px 10px; font-size:12px; font-weight:600; }} .badge-green {{ background:#001A09; color:#44CC88; border:1px solid #00843D; border-radius:6px; padding:3px 10px; font-size:12px; font-weight:600; }} .badge-gold {{ background:#1C1400; color:{WCO_GOLD}; border:1px solid {WCO_GOLD}; border-radius:6px; padding:3px 10px; font-size:12px; font-weight:600; }}
/* ── Tables ── */ .wco-table {{ width:100%; border-collapse:collapse; font-size:13px; }} .wco-table th {{ background:{WCO_NAVY}; color:{WCO_GOLD}; font-family:'Playfair Display',serif; padding:10px 14px; text-align:left; border-bottom:2px solid {WCO_GOLD}; font-size:12px; letter-spacing:0.05em; }} .wco-table td {{ padding:9px 14px; border-bottom:1px solid {WCO_BORDER}; color:{WCO_TEXT}; vertical-align:top; }} .wco-table tr:hover td {{ background:rgba(0,48,135,0.25); }}
/* ── Progress bars ── */ .prog-bar-wrap {{ background:#111D30; border-radius:6px; height:10px; margin:4px 0; overflow:hidden; }} .prog-bar-fill {{ height:100%; border-radius:6px; transition:width 0.6s ease; }}
/* ── Alerts ── */ .alert-gold {{ background:rgba(200,169,81,0.1); border-left:4px solid {WCO_GOLD}; border-radius:0 8px 8px 0; padding:12px 16px; color:#D4B96A; font-size:13px; margin:10px 0; }} .alert-blue {{ background:rgba(0,102,204,0.1); border-left:4px solid {WCO_BLUE}; border-radius:0 8px 8px 0; padding:12px 16px; color:#66AAFF; font-size:13px; margin:10px 0; }}
/* ── Streamlit widget tweaks ── */ .stSlider > div > div > div {{ background:{WCO_BORDER} !important; }} .stSlider [data-baseweb="slider"] [role="slider"] {{ background:{WCO_GOLD} !important; border-color:{WCO_GOLD} !important; }} .stButton > button {{ background:linear-gradient(135deg,{WCO_NAVY},{WCO_BLUE}); color:{WCO_GOLD}; border:1px solid {WCO_GOLD}; border-radius:8px; font-family:'IBM Plex Sans',sans-serif; font-weight:600; letter-spacing:0.04em; padding:8px 24px; transition:all 0.2s; }} .stButton > button:hover {{ background:linear-gradient(135deg,{WCO_BLUE},{WCO_NAVY}); border-color:#FFD700; color:#FFD700; transform:translateY(-1px); box-shadow:0 4px 16px rgba(200,169,81,0.25); }} div[data-testid="stMetricValue"] {{ font-family:'Playfair Display',serif !important; color:{WCO_GOLD} !important; }} [data-testid="stMetricLabel"] {{ color:{WCO_MUTED} !important; font-size:11px !important; text-transform:uppercase !important; letter-spacing:0.07em !important; }} [data-testid="stExpander"] {{ background:{WCO_CARD_BG} !important; border:1px solid {WCO_BORDER} !important; border-radius:10px !important; }} div[data-testid="stDataFrame"] {{ border-radius:10px; overflow:hidden; }} .stTabs [data-baseweb="tab-list"] {{ background:{WCO_CARD_BG}; border-radius:10px 10px 0 0; }} .stTabs [data-baseweb="tab"] {{ color:{WCO_MUTED}; font-family:'IBM Plex Sans',sans-serif; }} .stTabs [aria-selected="true"] {{ color:{WCO_GOLD} !important; border-bottom:2px solid {WCO_GOLD} !important; }} hr {{ border-color:{WCO_BORDER} !important; }} </style> """, unsafe_allow_html=True)
def page_header(icon: str, title: str, subtitle: str): st.markdown(f""" <div class="wco-header"> <div style="font-size:40px">{icon}</div> <div> <h1>{title}</h1> <p>{subtitle}</p> </div> <div style="margin-left:auto;text-align:right;"> <div style="color:#C8A951;font-family:'IBM Plex Mono',monospace;font-size:11px;">🌐 WCO ACCREDITED</div> <div style="color:#6B85AA;font-size:10px;margin-top:2px;">No-CelH Self-Learning RMS v2.0</div> </div> </div> """, unsafe_allow_html=True)
def metric_row(metrics: list): """metrics = [(value, label, color), ...]""" cols_html = "" for val, lbl, col in metrics: cols_html += f""" <div class="kpi-tile"> <div class="val" style="color:{col}">{val}</div> <div class="lbl">{lbl}</div> </div>""" st.markdown(f'<div class="kpi-row">{cols_html}</div>', unsafe_allow_html=True)app.pyAdded+127
page1_intro.pyAdded+289
page2_risk_register.pyAdded+310
page3_simulation.pyAdded+863
page4_results.pyAdded+951
page5_optimisation.pyAdded+320
requirements.txt+5-3
simulation_engine.pyAdded+443
styles.pyAdded+252