# Copyright 2019 DeepMind Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Tests for open_spiel.python.algorithms.exploitability_descent."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import tensorflow.compat.v1 as tf

from open_spiel.python.algorithms import exploitability_descent
import pyspiel

# Temporary disabling of v2 behavior until code is updated.
tf.disable_v2_behavior()


class ExploitabilityDescentTest(tf.test.TestCase):

  def test_solver_kuhn_poker_first_10_steps_convergence(self):
    solver = exploitability_descent.Solver(pyspiel.load_game("kuhn_poker"))
    with self.session() as session:
      session.run(tf.global_variables_initializer())
      nash_conv = [solver.step(session, learning_rate=1.0) for _ in range(11)]

    # Nash conv is 2x exploitability. Values taken from test run, not
    # independently verified.
    np.testing.assert_allclose(nash_conv, [
        0.91666666666666652, 0.67893004801213452, 0.48109148836354743,
        0.40061420923255808, 0.36617242161468722, 0.33676996443499557,
        0.30925081512398128, 0.28827843035940964, 0.26830042206858751,
        0.24418597846799289, 0.22168699344791482
    ])

  def test_solver_leduc_poker_first_10_steps_convergence(self):
    solver = exploitability_descent.Solver(pyspiel.load_game("leduc_poker"))
    with self.session() as session:
      session.run(tf.global_variables_initializer())
      nash_conv = [solver.step(session, learning_rate=1.0) for _ in range(11)]

    # Nash conv is 2x exploitability. Values taken from test run, not
    # independently verified.
    np.testing.assert_allclose(nash_conv, [
        4.7472224, 4.3147216, 3.9900389, 3.7576618, 3.5771275, 3.4414644,
        3.3272073, 3.1898201, 3.1089299, 3.0108435, 2.8992782
    ])


if __name__ == "__main__":
  tf.test.main()
