# Copyright 2019 The TensorFlow Authors. 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.
# ==============================================================================
"""CSR sparse matrix tests."""

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

import itertools

import numpy as np

from tensorflow.python.framework import dtypes
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework import test_util
from tensorflow.python.ops import math_ops
from tensorflow.python.ops.linalg.sparse import sparse_csr_matrix_ops
from tensorflow.python.platform import test


class CSRSparseMatrixTest(test.TestCase):

  @classmethod
  def setUpClass(cls):  # pylint: disable=g-missing-super-call
    cls._gpu_available = test_util.is_gpu_available()

  @test_util.run_in_graph_and_eager_modes
  def testConstructorFromSparseTensor(self):
    if not self._gpu_available:
      return

    a_indices = np.array([[0, 0], [2, 3], [2, 4], [3, 0]])
    a_values = [1.0, 5.0, -1.0, -2.0]
    a_dense_shape = [5, 6]

    a_st = sparse_tensor.SparseTensor(a_indices, a_values, a_dense_shape)
    a_st = math_ops.cast(a_st, dtypes.float32)
    a_sm = sparse_csr_matrix_ops.CSRSparseMatrix(a_st)
    self.assertEqual(a_sm.shape, a_dense_shape)

    a_st_rt = a_sm.to_sparse_tensor()
    a_st_rt = self.evaluate(a_st_rt)

    self.assertAllEqual(a_indices, a_st_rt.indices)
    self.assertAllClose(a_values, a_st_rt.values)
    self.assertAllEqual(a_dense_shape, a_st_rt.dense_shape)

  @test_util.run_in_graph_and_eager_modes
  def testConstructorFromDenseTensorNoIndices(self):