# Path: disentanglement_lib/methods/unsupervised/train.py
# @gin.configurable("model", blacklist=["model_dir", "overwrite"])
# def train(model_dir,
#           overwrite=False,
#           model=gin.REQUIRED,
#           training_steps=gin.REQUIRED,
#           random_seed=gin.REQUIRED,
#           batch_size=gin.REQUIRED,
#           eval_steps=1000,
#           name="",
#           model_num=None):
#   """Trains the estimator and exports the snapshot and the gin config.
# 
#   The use of this function requires the gin binding 'dataset.name' to be
#   specified as that determines the data set used for training.
# 
#   Args:
#     model_dir: String with path to directory where model output should be saved.
#     overwrite: Boolean indicating whether to overwrite output directory.
#     model: GaussianEncoderModel that should be trained and exported.
#     training_steps: Integer with number of training steps.
#     random_seed: Integer with random seed used for training.
#     batch_size: Integer with the batch size.
#     eval_steps: Optional integer with number of steps used for evaluation.
#     name: Optional string with name of the model (can be used to name models).
#     model_num: Optional integer with model number (can be used to identify
#       models).
#   """
#   # We do not use the variables 'name' and 'model_num'. Instead, they can be
#   # used to name results as they will be part of the saved gin config.
#   del name, model_num
# 
#   # Delete the output directory if it already exists.
#   if tf.gfile.IsDirectory(model_dir):
#     if overwrite:
#       tf.gfile.DeleteRecursively(model_dir)
#     else:
#       raise ValueError("Directory already exists and overwrite is False.")
# 
#   # Create a numpy random state. We will sample the random seeds for training
#   # and evaluation from this.
#   random_state = np.random.RandomState(random_seed)
# 
#   # Obtain the dataset.
#   dataset = named_data.get_named_ground_truth_data()
# 
#   # We create a TPUEstimator based on the provided model. This is primarily so
#   # that we could switch to TPU training in the future. For now, we train
#   # locally on GPUs.
#   run_config = contrib_tpu.RunConfig(
#       tf_random_seed=random_seed,
#       keep_checkpoint_max=1,
#       tpu_config=contrib_tpu.TPUConfig(iterations_per_loop=500))
#   tpu_estimator = contrib_tpu.TPUEstimator(
#       use_tpu=False,
#       model_fn=model.model_fn,
#       model_dir=os.path.join(model_dir, "tf_checkpoint"),
#       train_batch_size=batch_size,
#       eval_batch_size=batch_size,
#       config=run_config)
# 
#   # Set up time to keep track of elapsed time in results.
#   experiment_timer = time.time()
# 
#   # Do the actual training.
#   tpu_estimator.train(
#       input_fn=_make_input_fn(dataset, random_state.randint(2**32)),
#       steps=training_steps)
# 
#   # Save model as a TFHub module.
#   output_shape = named_data.get_named_ground_truth_data().observation_shape
#   module_export_path = os.path.join(model_dir, "tfhub")
#   gaussian_encoder_model.export_as_tf_hub(model, output_shape,
#                                           tpu_estimator.latest_checkpoint(),
#                                           module_export_path)
# 
#   # Save the results. The result dir will contain all the results and config
#   # files that we copied along, as we progress in the pipeline. The idea is that
#   # these files will be available for analysis at the end.
#   results_dict = tpu_estimator.evaluate(
#       input_fn=_make_input_fn(
#           dataset, random_state.randint(2**32), num_batches=eval_steps))
#   results_dir = os.path.join(model_dir, "results")
#   results_dict["elapsed_time"] = time.time() - experiment_timer
#   results.update_result_directory(results_dir, "train", results_dict)
# 
# Path: disentanglement_lib/utils/resources.py
# def get_file(path):
# def get_files_in_folder(path):
# 
# Path: disentanglement_lib/visualize/visualize_model.py
# def visualize(model_dir,
#               output_dir,
#               overwrite=False,
#               num_animations=5,
#               num_frames=20,
#               fps=10,
#               num_points_irs=10000):
#     def _decoder(latent_vectors):
# def latent_traversal_1d_multi_dim(generator_fn,
#                                   latent_vector,
#                                   dimensions=None,
#                                   values=None,
#                                   transpose=False):
# def sigmoid(x):
# def tanh(x):


from absl.testing import absltest
from absl.testing import parameterized
from disentanglement_lib.methods.unsupervised import train
from disentanglement_lib.utils import resources
from disentanglement_lib.visualize import visualize_model
#
#     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.

"""Test for visualize_model.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

MODEL_CONFIG_PATH = "../config/tests/methods/unsupervised/train_test.gin"


class VisualizeTest(parameterized.TestCase):

  @parameterized.parameters(
      ("logits"),
      ("tanh"),
  )
  def test_visualize_sigmoid(self, activation):
    activation_binding = (
        "reconstruction_loss.activation = '{}'".format(activation))
    self.model_dir = self.create_tempdir(
        "model_{}".format(activation),
        cleanup=absltest.TempFileCleanup.OFF).full_path
    train.train_with_gin(self.model_dir, True, [

# Path: disentanglement_lib/methods/unsupervised/train.py
# @gin.configurable("model", blacklist=["model_dir", "overwrite"])
# def train(model_dir,
#           overwrite=False,
#           model=gin.REQUIRED,
#           training_steps=gin.REQUIRED,
#           random_seed=gin.REQUIRED,
#           batch_size=gin.REQUIRED,
#           eval_steps=1000,
#           name="",
#           model_num=None):
#   """Trains the estimator and exports the snapshot and the gin config.
# 
#   The use of this function requires the gin binding 'dataset.name' to be
#   specified as that determines the data set used for training.
# 
#   Args:
#     model_dir: String with path to directory where model output should be saved.
#     overwrite: Boolean indicating whether to overwrite output directory.
#     model: GaussianEncoderModel that should be trained and exported.
#     training_steps: Integer with number of training steps.
#     random_seed: Integer with random seed used for training.
#     batch_size: Integer with the batch size.
#     eval_steps: Optional integer with number of steps used for evaluation.
#     name: Optional string with name of the model (can be used to name models).
#     model_num: Optional integer with model number (can be used to identify
#       models).
#   """
#   # We do not use the variables 'name' and 'model_num'. Instead, they can be
#   # used to name results as they will be part of the saved gin config.
#   del name, model_num
# 
#   # Delete the output directory if it already exists.
#   if tf.gfile.IsDirectory(model_dir):
#     if overwrite:
#       tf.gfile.DeleteRecursively(model_dir)
#     else:
#       raise ValueError("Directory already exists and overwrite is False.")
# 
#   # Create a numpy random state. We will sample the random seeds for training
#   # and evaluation from this.
#   random_state = np.random.RandomState(random_seed)
# 
#   # Obtain the dataset.
#   dataset = named_data.get_named_ground_truth_data()
# 
#   # We create a TPUEstimator based on the provided model. This is primarily so
#   # that we could switch to TPU training in the future. For now, we train
#   # locally on GPUs.
#   run_config = contrib_tpu.RunConfig(
#       tf_random_seed=random_seed,
#       keep_checkpoint_max=1,
#       tpu_config=contrib_tpu.TPUConfig(iterations_per_loop=500))
#   tpu_estimator = contrib_tpu.TPUEstimator(
#       use_tpu=False,
#       model_fn=model.model_fn,
#       model_dir=os.path.join(model_dir, "tf_checkpoint"),
#       train_batch_size=batch_size,
#       eval_batch_size=batch_size,
#       config=run_config)
# 
#   # Set up time to keep track of elapsed time in results.
#   experiment_timer = time.time()
# 
#   # Do the actual training.
#   tpu_estimator.train(
#       input_fn=_make_input_fn(dataset, random_state.randint(2**32)),
#       steps=training_steps)
# 
#   # Save model as a TFHub module.
#   output_shape = named_data.get_named_ground_truth_data().observation_shape
#   module_export_path = os.path.join(model_dir, "tfhub")
#   gaussian_encoder_model.export_as_tf_hub(model, output_shape,
#                                           tpu_estimator.latest_checkpoint(),
#                                           module_export_path)
# 
#   # Save the results. The result dir will contain all the results and config
#   # files that we copied along, as we progress in the pipeline. The idea is that
#   # these files will be available for analysis at the end.
#   results_dict = tpu_estimator.evaluate(
#       input_fn=_make_input_fn(
#           dataset, random_state.randint(2**32), num_batches=eval_steps))
#   results_dir = os.path.join(model_dir, "results")
#   results_dict["elapsed_time"] = time.time() - experiment_timer
#   results.update_result_directory(results_dir, "train", results_dict)
# 
# Path: disentanglement_lib/utils/resources.py
# def get_file(path):
# def get_files_in_folder(path):
# 
# Path: disentanglement_lib/visualize/visualize_model.py
# def visualize(model_dir,
#               output_dir,
#               overwrite=False,
#               num_animations=5,
#               num_frames=20,
#               fps=10,
#               num_points_irs=10000):
#     def _decoder(latent_vectors):
# def latent_traversal_1d_multi_dim(generator_fn,
#                                   latent_vector,
#                                   dimensions=None,
#                                   values=None,
#                                   transpose=False):
# def sigmoid(x):
# def tanh(x):


# Path: disentanglement_lib/visualize/visualize_model_test.py
from absl.testing import absltest
from absl.testing import parameterized
from disentanglement_lib.methods.unsupervised import train
from disentanglement_lib.utils import resources
from disentanglement_lib.visualize import visualize_model

#
#     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.

"""Test for visualize_model.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

MODEL_CONFIG_PATH = "../config/tests/methods/unsupervised/train_test.gin"


class VisualizeTest(parameterized.TestCase):

  @parameterized.parameters(
      ("logits"),
      ("tanh"),
  )
  def test_visualize_sigmoid(self, activation):
    activation_binding = (
        "reconstruction_loss.activation = '{}'".format(activation))
    self.model_dir = self.create_tempdir(
        "model_{}".format(activation),
        cleanup=absltest.TempFileCleanup.OFF).full_path
    train.train_with_gin(self.model_dir, True, [

        resources.get_file("config/tests/methods/unsupervised/train_test.gin")