File size: 18,825 Bytes
584f841 b19f21d 584f841 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 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 |
---
license: apache-2.0
library_name: geobot
pipeline_tag: other
tags:
- geopolitics
- forecasting
- simulation
- causal-inference
- monte-carlo
- time-series
- python-library
- framework
---
# GeoBotv1: Research-Grade Geopolitical Forecasting Framework
[]() []() []()
**GeoBotv1** is a complete, research-grade framework for geopolitical forecasting, conflict prediction, and causal policy analysis. Built on rigorous mathematical foundations, it combines optimal transport theory, structural causal inference, Bayesian reasoning, stochastic processes, econometric methods, and machine learning to provide actionable intelligence on regime shifts, conflict escalation, and intervention outcomes.
**Status: β
100% Complete** - All core mathematical frameworks implemented and production-ready.
---
## π― Key Capabilities
- **Causal Policy Analysis**: Simulate interventions (sanctions, deployments, regime changes) and estimate counterfactual outcomes
- **Conflict Contagion Modeling**: Model self-exciting escalation dynamics and cross-country spillovers using Hawkes processes
- **Multi-Country Forecasting**: Capture interdependencies and shock propagation with Vector Autoregression (VAR/SVAR)
- **Quasi-Experimental Inference**: Estimate treatment effects from observational data (Synthetic Control, DiD, RDD, IV)
- **Regime Detection**: Identify structural breaks and state transitions in real-time
- **Scenario Comparison**: Measure distances between geopolitical futures using optimal transport geometry
- **Intelligence Integration**: Bayesian belief updating from text, events, and structured data
- **Nowcasting**: High-dimensional factor models for real-time situational awareness
---
## π Complete Mathematical Framework
### β
Implemented Core Components
<table>
<tr>
<td width="50%">
**1. Optimal Transport Theory**
- Wasserstein distances (W1, W2, Wβ)
- Kantorovich duality (primal/dual formulations)
- Sinkhorn algorithm (entropic regularization)
- Unbalanced optimal transport
- Gromov-Wasserstein for network comparison
- Gradient-based OT optimization
**2. Causal Inference**
- Directed Acyclic Graphs (DAGs)
- Structural Causal Models (SCMs)
- Pearl's Do-Calculus for interventions
- Backdoor/frontdoor adjustment
- Counterfactual computation
- Causal discovery algorithms
**3. Bayesian Inference**
- Markov Chain Monte Carlo (MCMC)
- Sequential Monte Carlo (Particle Filters)
- Bootstrap, Auxiliary, Rao-Blackwellized
- Variational Inference (ELBO, CAVI, ADVI)
- Belief updating from intelligence
- Posterior predictive distributions
**4. Stochastic Processes**
- Stochastic Differential Equations (SDEs)
- Euler-Maruyama, Milstein, Stochastic RK
- Jump-diffusion processes (Merton model)
- Ornstein-Uhlenbeck processes
- GeopoliticalSDE framework
- Continuous-time dynamics
</td>
<td width="50%">
**5. Time-Series & Econometrics**
- Kalman Filters (Linear & Extended)
- Hidden Markov Models (HMM)
- Regime-Switching Models
- **Vector Autoregression (VAR)**
- **Structural VAR (SVAR)**
- **Dynamic Factor Models (DFM)**
- **Granger Causality Testing**
- Impulse Response Functions (IRF)
- Forecast Error Variance Decomposition
**6. Point Processes**
- **Univariate Hawkes Processes**
- **Multivariate Hawkes Processes**
- **Conflict Contagion Models**
- Branching ratio estimation
- Self-excitation dynamics
- Cross-country excitation matrices
**7. Quasi-Experimental Methods**
- **Synthetic Control Method (SCM)**
- **Difference-in-Differences (DiD)**
- **Regression Discontinuity Design (RDD)**
- **Instrumental Variables (2SLS)**
- Placebo tests and robustness checks
- Treatment effect bounds
**8. Machine Learning**
- Graph Neural Networks (GNN, GAT)
- CausalGNN for directed graphs
- Risk scoring and classification
- Feature discovery and embeddings
- Transformer-based text encoding
</td>
</tr>
</table>
---
## π Quick Start
### Installation
```bash
# Clone the repository
git clone https://github.com/your-org/AIGEOPOLITICAL.git
cd AIGEOPOLITICAL
# Install dependencies
pip install -r requirements.txt
# Optional: Install Graph Neural Network support
# (Requires matching torch version)
pip install torch-geometric torch-scatter torch-sparse
```
### Basic Usage Example
```python
from geobot.core import Scenario, ScenarioComparator
from geobot.models import CausalGraph
from geobot.inference import DoCalculus
from geobot.timeseries import VARModel
import numpy as np
# 1. Create geopolitical scenarios
scenario_baseline = Scenario(
name="Baseline",
features={
"military_readiness": np.array([0.6, 0.4, 0.5]),
"economic_stability": np.array([0.7, 0.6, 0.5])
}
)
scenario_intervention = Scenario(
name="Post-Sanctions",
features={
"military_readiness": np.array([0.8, 0.4, 0.5]),
"economic_stability": np.array([0.3, 0.6, 0.5])
}
)
# 2. Compare scenarios using optimal transport
comparator = ScenarioComparator()
distance = comparator.compare(scenario_baseline, scenario_intervention)
print(f"Wasserstein distance: {distance:.4f}")
# 3. Build causal model
causal_graph = CausalGraph()
causal_graph.add_edge("sanctions", "economy", strength=0.8)
causal_graph.add_edge("economy", "stability", strength=0.6)
causal_graph.add_edge("stability", "conflict_risk", strength=-0.7)
# 4. Simulate intervention
do_calc = DoCalculus(causal_graph)
intervention_effect = do_calc.compute_intervention_effect(
intervention={"sanctions": 1.0},
outcome="conflict_risk"
)
print(f"Estimated effect on conflict risk: {intervention_effect:.3f}")
# 5. Multi-country VAR forecasting
# (Simulated data for demonstration)
data = np.random.randn(100, 3) # 100 time periods, 3 countries
var = VARModel(n_lags=2)
results = var.fit(data, variable_names=['Country_A', 'Country_B', 'Country_C'])
forecast = var.forecast(results, steps=10)
print(f"10-step forecast:\n{forecast}")
```
### Conflict Contagion Example
```python
from geobot.timeseries import ConflictContagionModel
# Model conflict spread between countries
countries = ['Syria', 'Iraq', 'Lebanon', 'Turkey']
model = ConflictContagionModel(countries=countries)
# Historical conflict events (times when conflicts occurred)
events = {
'Syria': [1.2, 5.3, 10.1, 15.2, 22.3],
'Iraq': [3.4, 8.9, 12.1, 18.5],
'Lebanon': [12.3, 19.8, 25.1],
'Turkey': [28.2, 30.5]
}
# Fit contagion model
result = model.fit(events, T=365.0) # 1 year of data
print(f"Most contagious source: {result['most_contagious_source']}")
print(f"Most vulnerable target: {result['most_vulnerable_target']}")
# Assess future risk
risks = model.contagion_risk(events, result, t=370.0, horizon=30.0)
for country, risk in risks.items():
print(f"{country} conflict risk (next 30 days): {risk:.1%}")
```
### Synthetic Control for Policy Evaluation
```python
from geobot.models import SyntheticControlMethod
import numpy as np
# Evaluate impact of sanctions on target country
scm = SyntheticControlMethod()
# Data: treated country vs. control countries
treated_outcome = gdp_growth_target_country # Shape: (T,)
control_outcomes = gdp_growth_other_countries # Shape: (T, J)
result = scm.fit(
treated_outcome=treated_outcome,
control_outcomes=control_outcomes,
treatment_time=50, # Sanctions imposed at t=50
control_names=['Country_1', 'Country_2', ..., 'Country_J']
)
# Estimated treatment effect
avg_effect = np.mean(result.treatment_effect[50:])
print(f"Average treatment effect: {avg_effect:.3f}")
# Statistical significance via placebo test
p_value = scm.placebo_test(treated_outcome, control_outcomes,
treatment_time=50, n_permutations=100)
print(f"Placebo test p-value: {p_value:.3f}")
```
---
## π Project Structure
```
AIGEOPOLITICAL/
βββ geobot/ # Main package
β βββ core/ # Core mathematical primitives
β β βββ optimal_transport.py # Wasserstein distances
β β βββ advanced_optimal_transport.py # Kantorovich, Sinkhorn, Gromov-W
β β βββ scenario.py # Scenario representations
β β
β βββ models/ # Causal models
β β βββ causal_graph.py # DAGs and SCMs
β β βββ causal_discovery.py # Causal structure learning
β β βββ quasi_experimental.py # SCM, DiD, RDD, IV methods
β β
β βββ inference/ # Probabilistic inference
β β βββ do_calculus.py # Interventions and counterfactuals
β β βββ bayesian_engine.py # Bayesian belief updating
β β βββ particle_filter.py # Sequential Monte Carlo
β β βββ variational_inference.py # VI, ELBO, ADVI
β β
β βββ simulation/ # Stochastic simulation
β β βββ monte_carlo.py # Basic Monte Carlo
β β βββ sde_solver.py # Stochastic differential equations
β β βββ agent_based.py # Agent-based models
β β
β βββ timeseries/ # Time-series models
β β βββ kalman_filter.py # Kalman filters
β β βββ hmm.py # Hidden Markov Models
β β βββ regime_switching.py # Regime-switching models
β β βββ var_models.py # VAR, SVAR, DFM, Granger causality
β β βββ point_processes.py # Hawkes processes, conflict contagion
β β
β βββ ml/ # Machine learning
β β βββ risk_models.py # Risk scoring
β β βββ graph_neural_networks.py # GNNs for causal/geopolitical networks
β β βββ embeddings.py # Feature embeddings
β β
β βββ data_ingestion/ # Data processing
β β βββ pdf_reader.py # PDF intelligence extraction
β β βββ web_scraper.py # Web scraping
β β βββ event_extraction.py # NLP-based event structuring
β β βββ event_database.py # Event storage and querying
β β
β βββ utils/ # Utilities
β β βββ data_processing.py # Data preprocessing
β β βββ visualization.py # Plotting and visualization
β β
β βββ config/ # Configuration
β βββ settings.py # System configuration
β
βββ examples/ # Comprehensive examples
β βββ 01_basic_usage.py # Scenarios, causal graphs, Monte Carlo
β βββ 02_data_ingestion.py # PDF/web scraping pipeline
β βββ 03_intervention_simulation.py # Do-calculus and counterfactuals
β βββ 04_advanced_features.py # Particle filters, VI, SDEs, GNNs
β βββ 05_complete_framework.py # VAR, Hawkes, quasi-experimental
β
βββ requirements.txt # Python dependencies
βββ README.md # This file
```
---
## π¬ Mathematical Foundations
### Causality-First Principle
GeoBotv1 grounds all forecasting in **explicit causal structure**. This prevents spurious correlations and enables simulation of interventions that have never been observed.
**Structural Causal Model (SCM):**
```
X := f_X(Pa_X, U_X)
Y := f_Y(Pa_Y, U_Y)
```
**Pearl's Do-Calculus** enables reasoning about interventions `do(X = x)` even when only observational data is available.
### Optimal Transport for Scenario Comparison
The Wasserstein distance measures the "cost" of transforming one probability distribution into another:
```
W_2(ΞΌ, Ξ½) = inf_{Ο β Ξ (ΞΌ,Ξ½)} β(β«β« ||x - y||Β² dΟ(x,y))
```
**Kantorovich Duality** provides computational efficiency and geometric interpretation.
### Hawkes Processes for Conflict Dynamics
Self-exciting point processes capture escalation and contagion:
```
Ξ»_k(t) = ΞΌ_k + β_{j=1}^K Ξ±_{kj} β_{t_i^j < t} exp(-Ξ²_{kj}(t - t_i^j))
```
**Branching ratio** `n = Ξ±/Ξ²` determines stability:
- `n < 1`: Process is stable (subcritical)
- `n β₯ 1`: Process is explosive (supercritical)
### Stochastic Differential Equations
Continuous-time geopolitical dynamics:
```
dX_t = ΞΌ(X_t, t) dt + Ο(X_t, t) dW_t + dJ_t
```
Where:
- `ΞΌ`: Drift (deterministic component)
- `Ο dW_t`: Diffusion (continuous shocks)
- `dJ_t`: Jumps (discrete events)
---
## π‘ Use Cases
### 1. Strategic Intelligence & Risk Assessment
- **Multi-country risk dashboards** with VAR-based interdependency analysis
- **Real-time belief updating** as intelligence arrives (Bayesian inference)
- **Regime detection** using HMM and particle filters
### 2. Conflict Prediction & Early Warning
- **Hawkes process models** for escalation dynamics and contagion
- **Structural break detection** in military/economic indicators
- **Cross-country spillover analysis** with SVAR impulse responses
### 3. Policy Impact Analysis
- **Synthetic control** for sanctions/intervention evaluation
- **Difference-in-differences** for regime change effects
- **Regression discontinuity** for election outcome impacts
- **Do-calculus** for counterfactual policy simulation
### 4. Resource Allocation & Logistics
- **Optimal transport** for supply chain optimization under uncertainty
- **Monte Carlo simulation** for contingency planning
- **Stochastic optimization** with SDE-based constraints
### 5. Diplomatic Forecasting
- **Game-theoretic extensions** (can be added via causal graphs)
- **Network centrality** analysis with GNNs
- **Alliance dynamics** using multivariate Hawkes processes
---
## π οΈ Technical Requirements
### Core Dependencies
- **Python**: 3.9+
- **NumPy**: 1.24+
- **SciPy**: 1.10+
- **Pandas**: 2.0+
- **NetworkX**: 3.0+ (causal graphs)
- **POT**: 0.9+ (optimal transport)
- **PyMC**: 5.0+ (Bayesian inference)
- **Statsmodels**: 0.14+ (econometrics)
### Optional but Recommended
- **PyTorch**: 2.0+ (for GNNs, deep learning)
- **PyTorch Geometric**: 2.3+ (graph neural networks)
- **spaCy**: 3.6+ (NLP for event extraction)
- **Transformers**: 4.30+ (text embeddings)
### Data Ingestion
- **Beautiful Soup**: 4.12+ (web scraping)
- **PDFPlumber**: 0.10+ (PDF extraction)
- **Newspaper3k**: 0.2.8+ (article extraction)
- **Feedparser**: 6.0+ (RSS feeds)
See `requirements.txt` for complete dependency list.
---
## π Documentation & Examples
### Example Scripts
All examples are fully functional and demonstrate end-to-end workflows:
1. **`01_basic_usage.py`**: Scenarios, causal graphs, Monte Carlo basics, Bayesian updating
2. **`02_data_ingestion.py`**: PDF extraction, web scraping, event databases
3. **`03_intervention_simulation.py`**: Do-calculus, counterfactuals, policy simulation
4. **`04_advanced_features.py`**: Particle filters, VI, SDEs, GNNs, event extraction
5. **`05_complete_framework.py`**: VAR/SVAR/DFM, Hawkes processes, quasi-experimental methods
### Running Examples
```bash
cd examples
# Basic usage
python 01_basic_usage.py
# Data ingestion pipeline
python 02_data_ingestion.py
# Intervention simulation
python 03_intervention_simulation.py
# Advanced mathematical features
python 04_advanced_features.py
# Complete framework demonstration (VAR, Hawkes, quasi-experimental)
python 05_complete_framework.py
```
---
## π Theoretical Background
GeoBotv1 synthesizes methods from multiple fields:
### Economics & Econometrics
- Vector Autoregression (Sims, 1980)
- Structural VAR identification (Blanchard & Quah, 1989)
- Synthetic Control Method (Abadie et al., 2010, 2015)
- Difference-in-Differences (Card & Krueger, 1994)
- Regression Discontinuity (Thistlethwaite & Campbell, 1960)
### Statistics & Probability
- Optimal Transport (Villani, 2003, 2009)
- Hawkes Processes (Hawkes, 1971; Hawkes & Oakes, 1974)
- Sequential Monte Carlo (Doucet et al., 2001)
- Variational Inference (Jordan et al., 1999; Blei et al., 2017)
### Computer Science & AI
- Causal Inference (Pearl, 2000, 2009)
- Do-Calculus (Pearl, 1995)
- Graph Neural Networks (Kipf & Welling, 2017; VeliΔkoviΔ et al., 2018)
- Structural Causal Models (Pearl & Mackenzie, 2018)
### Geopolitics & Conflict Studies
- Conflict contagion (Gleditsch, 2007; Braithwaite, 2010)
- Regime change dynamics (Acemoglu & Robinson, 2006)
- Economic sanctions effects (Hufbauer et al., 2007)
---
## π§ͺ Testing & Validation
### Mathematical Correctness
- Kantorovich duality: Verify primal-dual gap β 0
- Hawkes stability: Check branching ratio < 1 for subcritical processes
- Causal identification: Validate backdoor/frontdoor criteria
- Particle filter: Monitor Effective Sample Size (ESS)
### Statistical Properties
- VAR stationarity: Check eigenvalues of companion matrix
- SVAR identification: Verify order conditions satisfied
- Synthetic control: Pre-treatment fit quality (RMSPE)
- RDD: Bandwidth sensitivity analysis
### Reproducibility
All examples include `np.random.seed()` for deterministic results.
---
## π§ Extensions & Future Work
While GeoBotv1 is complete for core forecasting tasks, potential extensions include:
- **Game-Theoretic Modules**: Strategic interaction between actors
- **Spatial Statistics**: Geographic contagion with distance decay
- **Network Effects**: Centrality measures, community detection
- **Deep Learning**: Attention mechanisms for text-to-risk pipelines
- **Real-Time Data Feeds**: API integrations for live intelligence
- **Uncertainty Quantification**: Conformal prediction, calibration
- **Ensemble Methods**: Model averaging across multiple frameworks
---
## π License
MIT License - See LICENSE file for details
---
## π Acknowledgments
GeoBotv1 builds on decades of research in:
- Causal inference (Judea Pearl, Donald Rubin)
- Optimal transport theory (CΓ©dric Villani, Leonid Kantorovich)
- Econometrics (Christopher Sims, Alberto Abadie)
- Point processes (Alan Hawkes, Daryl Daley)
- Bayesian statistics (Andrew Gelman, Michael Jordan)
- Stochastic calculus (Kiyosi ItΓ΄, Bernt Γksendal)
---
## π§ Contact & Support
For questions, issues, or collaboration:
- **Issues**: [GitHub Issues](https://github.com/your-org/AIGEOPOLITICAL/issues)
- **Documentation**: [Full documentation](https://your-org.github.io/AIGEOPOLITICAL)
- **Citation**: If you use GeoBotv1 in research, please cite this repository
---
<div align="center">
**GeoBotv1** - Where rigorous mathematics meets geopolitical forecasting
*Built with causality, powered by probability, validated by theory*
</div>
|