Skip to content

Commit

Permalink
Add to_gam
Browse files Browse the repository at this point in the history
  • Loading branch information
oyamad committed Jan 5, 2025
1 parent 8acfa15 commit af6038b
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
2 changes: 1 addition & 1 deletion quantecon/game_theory/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
18 changes: 18 additions & 0 deletions quantecon/game_theory/game_converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
18 changes: 16 additions & 2 deletions quantecon/game_theory/tests/test_game_converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)

0 comments on commit af6038b

Please sign in to comment.