File size: 4,606 Bytes
484e3bc |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
"""
Example 1: Basic Usage of GeoBotv1
This example demonstrates the core components of the framework:
- Creating scenarios
- Building causal graphs
- Running Monte Carlo simulations
- Bayesian belief updating
"""
import numpy as np
import sys
sys.path.append('..')
from geobot.core.scenario import Scenario, ScenarioDistribution
from geobot.models.causal_graph import CausalGraph, StructuralCausalModel
from geobot.simulation.monte_carlo import MonteCarloEngine, SimulationConfig
from geobot.inference.bayesian_engine import BayesianEngine, Prior, Evidence, BeliefUpdater
from scipy import stats
def main():
print("=" * 80)
print("GeoBotv1 - Basic Usage Example")
print("=" * 80)
# 1. Create a simple scenario
print("\n1. Creating a geopolitical scenario...")
scenario = Scenario(
name="baseline_scenario",
features={
'military_tension': np.array([0.5]),
'economic_sanctions': np.array([0.3]),
'diplomatic_relations': np.array([0.6]),
},
probability=1.0
)
print(f" Created scenario: {scenario.name}")
print(f" Features: {list(scenario.features.keys())}")
# 2. Build a causal graph
print("\n2. Building causal graph...")
causal_graph = CausalGraph(name="geopolitical_dag")
# Add nodes
causal_graph.add_node('sanctions', node_type='policy')
causal_graph.add_node('tension', node_type='state')
causal_graph.add_node('conflict_risk', node_type='outcome')
# Add causal edges
causal_graph.add_edge('sanctions', 'tension',
strength=0.7,
mechanism="Sanctions increase military tension")
causal_graph.add_edge('tension', 'conflict_risk',
strength=0.8,
mechanism="Tension increases conflict probability")
print(f" Created graph with {len(causal_graph.graph.nodes)} nodes")
print(f" Causal relationships: sanctions -> tension -> conflict_risk")
# 3. Run Monte Carlo simulation
print("\n3. Running Monte Carlo simulation...")
config = SimulationConfig(n_simulations=100, time_horizon=50)
mc_engine = MonteCarloEngine(config)
def transition_fn(state, t, noise):
# Simple dynamics
new_state = {}
new_state['tension'] = state.get('tension', 0.5) + \
0.1 * state.get('sanctions', 0) + \
noise.get('tension', 0)
new_state['conflict_risk'] = 0.5 * new_state['tension'] + \
noise.get('conflict_risk', 0)
# Clip values
new_state['tension'] = np.clip(new_state['tension'], 0, 1)
new_state['conflict_risk'] = np.clip(new_state['conflict_risk'], 0, 1)
return new_state
def noise_fn(t):
return {
'tension': np.random.normal(0, 0.05),
'conflict_risk': np.random.normal(0, 0.05)
}
initial_state = {'tension': 0.3, 'sanctions': 0.2, 'conflict_risk': 0.1}
trajectories = mc_engine.run_basic_simulation(initial_state, transition_fn, noise_fn)
# Compute statistics
stats = mc_engine.compute_statistics(trajectories)
print(f" Ran {config.n_simulations} simulations")
print(f" Final conflict risk (mean): {stats['conflict_risk']['mean'][-1]:.3f}")
print(f" Final conflict risk (95% CI): [{stats['conflict_risk']['q5'][-1]:.3f}, {stats['conflict_risk']['q95'][-1]:.3f}]")
# 4. Bayesian belief updating
print("\n4. Bayesian belief updating...")
updater = BeliefUpdater()
# Initialize belief about conflict risk
updater.initialize_belief(
name='conflict_risk',
prior_mean=0.3,
prior_std=0.1,
belief_type='probability'
)
# Receive intelligence report suggesting higher risk
print(" Received intelligence: conflict risk = 0.6 (reliability: 0.7)")
posterior = updater.update_from_intelligence(
belief='conflict_risk',
observation=0.6,
reliability=0.7
)
print(f" Updated belief - Mean: {posterior['mean']:.3f}, Std: {posterior['std']:.3f}")
print(f" 95% Credible Interval: [{posterior['q5']:.3f}, {posterior['q95']:.3f}]")
# 5. Probability of high risk
prob_high_risk = updater.get_belief_probability(
'conflict_risk',
threshold=0.5,
direction='greater'
)
print(f" Probability of high risk (>0.5): {prob_high_risk:.3f}")
print("\n" + "=" * 80)
print("Example completed successfully!")
print("=" * 80)
if __name__ == "__main__":
main()
|