Skip to content

Commit af6038b

Browse files
committed
Add to_gam
1 parent 8acfa15 commit af6038b

File tree

3 files changed

+35
-3
lines changed

3 files changed

+35
-3
lines changed

quantecon/game_theory/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,4 @@
2424
from .logitdyn import LogitDynamics
2525
from .polymatrix_game import PolymatrixGame
2626
from .howson_lcp import polym_lcp_solver
27-
from .game_converters import GAMReader, GAMWriter, from_gam
27+
from .game_converters import GAMReader, GAMWriter, from_gam, to_gam

quantecon/game_theory/game_converters.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,3 +226,21 @@ def from_gam(filename: str) -> NormalFormGame:
226226
227227
"""
228228
return GAMReader.from_file(filename)
229+
230+
231+
def to_gam(g, file_path=None):
232+
"""
233+
Write a NormalFormGame to a file in gam format.
234+
235+
Parameters
236+
----------
237+
g : NormalFormGame
238+
239+
file_path : str, optional(default=None)
240+
Path to the file to write to. If None, the result is returned as
241+
a string.
242+
243+
"""
244+
if file_path is None:
245+
return GAMWriter.to_string(g)
246+
return GAMWriter.to_file(g, file_path)

quantecon/game_theory/tests/test_game_converters.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,10 @@
55
import os
66
from tempfile import NamedTemporaryFile
77
from numpy.testing import assert_string_equal
8-
from quantecon.game_theory import NormalFormGame, GAMWriter
8+
from quantecon.game_theory import NormalFormGame, GAMWriter, to_gam
99

1010

11-
class TestGAMWrite:
11+
class TestGAMWriter:
1212
def setup_method(self):
1313
nums_actions = (2, 2, 2)
1414
g = NormalFormGame(nums_actions)
@@ -45,3 +45,17 @@ def test_to_string(self):
4545
s_actual = GAMWriter.to_string(self.g)
4646

4747
assert_string_equal(s_actual, self.s_desired)
48+
49+
def test_to_gam(self):
50+
s_actual = to_gam(self.g)
51+
assert_string_equal(s_actual, self.s_desired)
52+
53+
with NamedTemporaryFile(delete=False) as tmp_file:
54+
temp_path = tmp_file.name
55+
to_gam(self.g, temp_path)
56+
57+
with open(temp_path, 'r') as f:
58+
s_actual = f.read()
59+
assert_string_equal(s_actual, self.s_desired + '\n')
60+
61+
os.remove(temp_path)

0 commit comments

Comments
 (0)