From af6038b8795c1b61c7aa060afbad5badf1e7a090 Mon Sep 17 00:00:00 2001 From: Daisuke Oyama Date: Sun, 5 Jan 2025 16:01:49 +0900 Subject: [PATCH] Add `to_gam` --- quantecon/game_theory/__init__.py | 2 +- quantecon/game_theory/game_converters.py | 18 ++++++++++++++++++ .../game_theory/tests/test_game_converters.py | 18 ++++++++++++++++-- 3 files changed, 35 insertions(+), 3 deletions(-) diff --git a/quantecon/game_theory/__init__.py b/quantecon/game_theory/__init__.py index 4bcfe0a6..7ca07de5 100644 --- a/quantecon/game_theory/__init__.py +++ b/quantecon/game_theory/__init__.py @@ -24,4 +24,4 @@ from .logitdyn import LogitDynamics from .polymatrix_game import PolymatrixGame from .howson_lcp import polym_lcp_solver -from .game_converters import GAMReader, GAMWriter, from_gam +from .game_converters import GAMReader, GAMWriter, from_gam, to_gam diff --git a/quantecon/game_theory/game_converters.py b/quantecon/game_theory/game_converters.py index 5bfeba4b..c5b305a5 100644 --- a/quantecon/game_theory/game_converters.py +++ b/quantecon/game_theory/game_converters.py @@ -226,3 +226,21 @@ def from_gam(filename: str) -> NormalFormGame: """ return GAMReader.from_file(filename) + + +def to_gam(g, file_path=None): + """ + Write a NormalFormGame to a file in gam format. + + Parameters + ---------- + g : NormalFormGame + + file_path : str, optional(default=None) + Path to the file to write to. If None, the result is returned as + a string. + + """ + if file_path is None: + return GAMWriter.to_string(g) + return GAMWriter.to_file(g, file_path) diff --git a/quantecon/game_theory/tests/test_game_converters.py b/quantecon/game_theory/tests/test_game_converters.py index 5e592569..719fcd5d 100644 --- a/quantecon/game_theory/tests/test_game_converters.py +++ b/quantecon/game_theory/tests/test_game_converters.py @@ -5,10 +5,10 @@ import os from tempfile import NamedTemporaryFile from numpy.testing import assert_string_equal -from quantecon.game_theory import NormalFormGame, GAMWriter +from quantecon.game_theory import NormalFormGame, GAMWriter, to_gam -class TestGAMWrite: +class TestGAMWriter: def setup_method(self): nums_actions = (2, 2, 2) g = NormalFormGame(nums_actions) @@ -45,3 +45,17 @@ def test_to_string(self): s_actual = GAMWriter.to_string(self.g) assert_string_equal(s_actual, self.s_desired) + + def test_to_gam(self): + s_actual = to_gam(self.g) + assert_string_equal(s_actual, self.s_desired) + + with NamedTemporaryFile(delete=False) as tmp_file: + temp_path = tmp_file.name + to_gam(self.g, temp_path) + + with open(temp_path, 'r') as f: + s_actual = f.read() + assert_string_equal(s_actual, self.s_desired + '\n') + + os.remove(temp_path)