Skip to main content

game_theory_core/
lib.rs

1//! Exact game-theoretic computation.
2//!
3//! No I/O, no async, no protocol handling. A caller-supplied [`StrategicGame`]
4//! passes through [`ValidStrategicGame::validate`] once; every solver takes
5//! that type, so an unchecked game cannot reach a solver.
6//!
7//! Payoffs cross the API as `f64` but are stored and computed as exact
8//! rationals, so there is no tolerance anywhere and answers match published
9//! textbook solutions exactly.
10//!
11//! ```
12//! use game_theory_core::game::{MatrixForm, PayoffKind, StrategicGame, ValidStrategicGame};
13//! use game_theory_core::solve::pure_nash::solve_pure_nash;
14//!
15//! let matrix = MatrixForm {
16//!     players: ["Row".into(), "Col".into()],
17//!     row_strategies: vec!["Cooperate".into(), "Defect".into()],
18//!     col_strategies: vec!["Cooperate".into(), "Defect".into()],
19//!     payoff_matrix: vec![
20//!         vec![[3.0, 3.0], [0.0, 4.0]],
21//!         vec![[4.0, 0.0], [1.0, 1.0]],
22//!     ],
23//!     payoff_kind: PayoffKind::Cardinal,
24//! };
25//!
26//! let game = ValidStrategicGame::validate(StrategicGame::try_from(matrix)?)?;
27//! let result = solve_pure_nash(&game);
28//!
29//! // Both players defect: the unique equilibrium, and worse for both than
30//! // mutual cooperation.
31//! assert_eq!(result.equilibria, vec![vec![1, 1]]);
32//! # Ok::<(), game_theory_core::GtError>(())
33//! ```
34//!
35//! Extensive-form (game-tree) games take the same route — validate once, then
36//! solve. Backward induction returns every subgame-perfect equilibrium:
37//!
38//! ```
39//! use game_theory_core::game::Player;
40//! use game_theory_core::{solve_backward_induction, ExtensiveGame, Node, PayoffKind, ValidExtensiveGame};
41//!
42//! // The Entrant moves first; if it enters, the Incumbent chooses whether to
43//! // fight. Fighting hurts the Incumbent too, so the threat is not credible.
44//! let game = ExtensiveGame {
45//!     players: vec![
46//!         Player { id: 0, name: "Entrant".into() },
47//!         Player { id: 1, name: "Incumbent".into() },
48//!     ],
49//!     root: 0,
50//!     nodes: vec![
51//!         Node::Decision { player: 0, actions: vec![("In".into(), 1), ("Out".into(), 2)] },
52//!         Node::Decision { player: 1, actions: vec![("Fight".into(), 3), ("Accommodate".into(), 4)] },
53//!         Node::Terminal { payoffs: vec![0.0, 2.0] },
54//!         Node::Terminal { payoffs: vec![-1.0, -1.0] },
55//!         Node::Terminal { payoffs: vec![1.0, 1.0] },
56//!     ],
57//!     information_sets: vec![vec![0], vec![1]],
58//!     payoff_kind: PayoffKind::Cardinal,
59//! };
60//!
61//! let game = ValidExtensiveGame::validate(game)?;
62//! let result = solve_backward_induction(&game)?;
63//!
64//! // Unique equilibrium: the Entrant enters and the Incumbent accommodates.
65//! assert_eq!(result.solutions.len(), 1);
66//! assert_eq!(result.solutions[0].path, vec![(0, 0), (1, 1)]);
67//! # Ok::<(), game_theory_core::GtError>(())
68//! ```
69//!
70//! Repeating a stage game changes what is sustainable. Grim trigger with Nash
71//! reversion gives the exact patience cooperation requires:
72//!
73//! ```
74//! use game_theory_core::{
75//!     analyze_repeated_game, MatrixForm, PayoffKind, Punishment, Rational,
76//!     StrategicGame, ValidStrategicGame,
77//! };
78//!
79//! let matrix = MatrixForm {
80//!     players: ["Row".into(), "Col".into()],
81//!     row_strategies: vec!["Cooperate".into(), "Defect".into()],
82//!     col_strategies: vec!["Cooperate".into(), "Defect".into()],
83//!     payoff_matrix: vec![
84//!         vec![[3.0, 3.0], [0.0, 4.0]],
85//!         vec![[4.0, 0.0], [1.0, 1.0]],
86//!     ],
87//!     payoff_kind: PayoffKind::Cardinal,
88//! };
89//! let game = ValidStrategicGame::validate(StrategicGame::try_from(matrix)?)?;
90//!
91//! let report = analyze_repeated_game(&game, &[0, 0], Punishment::GrimTrigger, None)?;
92//!
93//! // Mutual cooperation is sustainable exactly when the discount factor
94//! // reaches 1/3 — an exact fraction, not a rounded decimal.
95//! assert_eq!(
96//!     report.critical_discount_factor,
97//!     Some(Rational::new(1.into(), 3.into()))
98//! );
99//! # Ok::<(), game_theory_core::GtError>(())
100//! ```
101
102pub mod analyze;
103pub mod error;
104pub mod exact;
105pub mod game;
106pub mod limits;
107pub mod solve;
108
109pub use analyze::{
110    analyze_repeated_game, analyze_structure, classify, pareto_dominates, Archetype,
111    ArchetypeReport, DominatedEquilibrium, PlayerThreshold, Punishment, RepeatedGameReport,
112    SecurityLevel, StructureReport,
113};
114pub use error::{Diagnostic, DiagnosticCode, GtError};
115pub use exact::{solve_linear_system, solve_lp, LinearSolution, LpProblem, LpSolution};
116pub use game::{
117    plan_to_strategy_index, to_strategic, ExtensiveGame, MatrixForm, Node, NodeId, Outcome,
118    PayoffKind, Player, PlayerId, Profile, Rational, StrategicGame, StrategyId, ValidExtensiveGame,
119    ValidStrategicGame,
120};
121pub use solve::{
122    expected_payoff_against, expected_payoff_per_strategy, profitable_deviation,
123    solve_backward_induction, solve_dominance, solve_mixed_nash, solve_pure_nash,
124    strictly_dominated_by_mixture, verify_equilibrium, verify_mixed_nash, verify_spe,
125    BackwardInductionResult, Concept, Deviation, DominanceMode, DominanceResult, Dominator,
126    EliminationStep, MixedDeviation, MixedEquilibrium, MixedNashResult, MixedStrategy,
127    MixedVerifyResult, NodeDecision, ProfileCheck, PureNashResult, SpeDeviation, SpeSolution,
128    SpeVerifyResult, SupportViolation, VerifyResult,
129};