operator_solve = operator3.solve(operator1)
    self.assertTrue(isinstance(
        operator_solve,
        linalg_lib.LinearOperatorDiag))
    self.assertAllClose([2 / 3., 1.], self.evaluate(operator_solve.diag))

  def test_diag_adjoint_type(self):
    diag = [1., 3., 5., 8.]
    operator = linalg.LinearOperatorDiag(diag, is_non_singular=True)
    self.assertIsInstance(operator.adjoint(), linalg.LinearOperatorDiag)

  def test_diag_cholesky_type(self):
    diag = [1., 3., 5., 8.]
    operator = linalg.LinearOperatorDiag(
        diag,
        is_positive_definite=True,
        is_self_adjoint=True,
    )
    self.assertIsInstance(operator.cholesky(), linalg.LinearOperatorDiag)

  def test_diag_inverse_type(self):
    diag = [1., 3., 5., 8.]
    operator = linalg.LinearOperatorDiag(diag, is_non_singular=True)
    self.assertIsInstance(operator.inverse(), linalg.LinearOperatorDiag)


if __name__ == "__main__":
  linear_operator_test_util.add_tests(LinearOperatorDiagTest)
  test.main()
    operator_matmul = operator1.matmul(operator2)
    self.assertTrue(isinstance(
        operator_matmul,
        linalg_lib.LinearOperatorLowerTriangular))
    self.assertAllClose(
        math_ops.matmul(
            operator1.to_dense(),
            operator2.to_dense()),
        self.evaluate(operator_matmul.to_dense()))

    operator_matmul = operator2.matmul(operator1)
    self.assertTrue(isinstance(
        operator_matmul,
        linalg_lib.LinearOperatorLowerTriangular))
    self.assertAllClose(
        math_ops.matmul(
            operator2.to_dense(),
            operator1.to_dense()),
        self.evaluate(operator_matmul.to_dense()))

  def test_tape_safe(self):
    tril = variables_module.Variable([[1., 0.], [0., 1.]])
    operator = linalg_lib.LinearOperatorLowerTriangular(
        tril, is_non_singular=True)
    self.check_tape_safe(operator)


if __name__ == "__main__":
  linear_operator_test_util.add_tests(LinearOperatorLowerTriangularTest)
  test.main()
Exemplo n.º 3
0
        u = rng.rand(5, 3, 2)
        diag = rng.rand(5, 4)  # Last dimension should be 2
        with self.assertRaisesRegex(ValueError, "not compatible"):
            linalg.LinearOperatorLowRankUpdate(base_operator,
                                               u=u,
                                               diag_update=diag)

    def test_diag_incompatible_batch_shape_raises(self):
        base_operator = linalg.LinearOperatorIdentity(num_rows=3,
                                                      dtype=np.float64)
        u = rng.rand(5, 3, 2)
        diag = rng.rand(4, 2)  # First dimension should be 5
        with self.assertRaisesRegex(ValueError, "Incompatible shapes"):
            linalg.LinearOperatorLowRankUpdate(base_operator,
                                               u=u,
                                               diag_update=diag)


if __name__ == "__main__":
    linear_operator_test_util.add_tests(
        LinearOperatorLowRankUpdatetestWithDiagUseCholesky)
    linear_operator_test_util.add_tests(
        LinearOperatorLowRankUpdatetestWithDiagCannotUseCholesky)
    linear_operator_test_util.add_tests(
        LinearOperatorLowRankUpdatetestNoDiagUseCholesky)
    linear_operator_test_util.add_tests(
        LinearOperatorLowRankUpdatetestNoDiagCannotUseCholesky)
    linear_operator_test_util.add_tests(
        LinearOperatorLowRankUpdatetestWithDiagNotSquare)
    test.main()
Exemplo n.º 4
0

@test_util.run_all_in_graph_and_eager_modes
class LinearOperatorAdjointNonSquareTest(
        linear_operator_test_util.NonSquareLinearOperatorDerivedClassTest):
    """Tests done in the base class NonSquareLinearOperatorDerivedClassTest."""
    def operator_and_matrix(self, build_info, dtype, use_placeholder):
        shape_before_adjoint = list(build_info.shape)
        # We need to swap the last two dimensions because we are taking the adjoint
        # of this operator
        shape_before_adjoint[-1], shape_before_adjoint[-2] = (
            shape_before_adjoint[-2], shape_before_adjoint[-1])
        matrix = linear_operator_test_util.random_normal(shape_before_adjoint,
                                                         dtype=dtype)

        lin_op_matrix = matrix

        if use_placeholder:
            lin_op_matrix = array_ops.placeholder_with_default(matrix,
                                                               shape=None)

        operator = LinearOperatorAdjoint(
            linalg.LinearOperatorFullMatrix(lin_op_matrix))

        return operator, linalg.adjoint(matrix)


if __name__ == "__main__":
    linear_operator_test_util.add_tests(LinearOperatorAdjointTest)
    test.main()
    operator = householder.LinearOperatorHouseholder(lin_op_reflection_axis)

    mat = reflection_axis[..., array_ops.newaxis]
    matrix = -2 * linear_operator_util.matmul_with_broadcast(
        mat, mat, adjoint_b=True)
    matrix = array_ops.matrix_set_diag(
        matrix, 1. + array_ops.matrix_diag_part(matrix))

    return operator, matrix

  def test_scalar_reflection_axis_raises(self):
    with self.assertRaisesRegexp(ValueError, "must have at least 1 dimension"):
      householder.LinearOperatorHouseholder(1.)

  def test_householder_adjoint_type(self):
    reflection_axis = [1., 3., 5., 8.]
    operator = householder.LinearOperatorHouseholder(reflection_axis)
    self.assertIsInstance(
        operator.adjoint(), householder.LinearOperatorHouseholder)

  def test_householder_inverse_type(self):
    reflection_axis = [1., 3., 5., 8.]
    operator = householder.LinearOperatorHouseholder(reflection_axis)
    self.assertIsInstance(
        operator.inverse(), householder.LinearOperatorHouseholder)


if __name__ == "__main__":
  linear_operator_test_util.add_tests(LinearOperatorHouseholderTest)
  test.main()
Exemplo n.º 6
0
        flattened_row = np.reshape(row, (-1, shape[-1]))
        flattened_col = np.reshape(col, (-1, shape[-1]))
        flattened_toeplitz = np.zeros(
            [flattened_row.shape[0], shape[-1], shape[-1]])
        for i in range(flattened_row.shape[0]):
            flattened_toeplitz[i] = scipy.linalg.toeplitz(
                flattened_col[i], flattened_row[i])
        matrix = np.reshape(flattened_toeplitz, shape)
        matrix = math_ops.cast(matrix, dtype=dtype)

        return operator, matrix

    def test_scalar_row_col_raises(self):
        with self.assertRaisesRegexp(ValueError,
                                     "must have at least 1 dimension"):
            linear_operator_toeplitz.LinearOperatorToeplitz(1., 1.)

        with self.assertRaisesRegexp(ValueError,
                                     "must have at least 1 dimension"):
            linear_operator_toeplitz.LinearOperatorToeplitz([1.], 1.)

        with self.assertRaisesRegexp(ValueError,
                                     "must have at least 1 dimension"):
            linear_operator_toeplitz.LinearOperatorToeplitz(1., [1.])


if __name__ == "__main__":
    linear_operator_test_util.add_tests(LinearOperatorToeplitzTest)
    test.main()
    with self.assertRaisesRegexp(ValueError, "not compatible"):
      linalg.LinearOperatorLowRankUpdate(base_operator, u=u)

  def test_u_and_diag_incompatible_low_rank_raises(self):
    base_operator = linalg.LinearOperatorIdentity(num_rows=3, dtype=np.float64)
    u = rng.rand(5, 3, 2)
    diag = rng.rand(5, 4)  # Last dimension should be 2
    with self.assertRaisesRegexp(ValueError, "not compatible"):
      linalg.LinearOperatorLowRankUpdate(base_operator, u=u, diag_update=diag)

  def test_diag_incompatible_batch_shape_raises(self):
    base_operator = linalg.LinearOperatorIdentity(num_rows=3, dtype=np.float64)
    u = rng.rand(5, 3, 2)
    diag = rng.rand(4, 2)  # First dimension should be 5
    with self.assertRaisesRegexp(ValueError, "Incompatible shapes"):
      linalg.LinearOperatorLowRankUpdate(base_operator, u=u, diag_update=diag)


if __name__ == "__main__":
  linear_operator_test_util.add_tests(
      LinearOperatorLowRankUpdatetestWithDiagUseCholesky)
  linear_operator_test_util.add_tests(
      LinearOperatorLowRankUpdatetestWithDiagCannotUseCholesky)
  linear_operator_test_util.add_tests(
      LinearOperatorLowRankUpdatetestNoDiagUseCholesky)
  linear_operator_test_util.add_tests(
      LinearOperatorLowRankUpdatetestNoDiagCannotUseCholesky)
  linear_operator_test_util.add_tests(
      LinearOperatorLowRankUpdatetestWithDiagNotSquare)
  test.main()
Exemplo n.º 8
0
        operator = linalg.LinearOperatorFullMatrix(lin_op_matrix,
                                                   is_square=True)

        return operator, matrix

    def test_is_x_flags(self):
        matrix = [[3., 2., 1.], [1., 1., 1.]]
        operator = linalg.LinearOperatorFullMatrix(matrix,
                                                   is_self_adjoint=False)
        self.assertEqual(operator.is_positive_definite, None)
        self.assertEqual(operator.is_non_singular, None)
        self.assertFalse(operator.is_self_adjoint)
        self.assertFalse(operator.is_square)

    def test_matrix_must_have_at_least_two_dims_or_raises(self):
        with self.assertRaisesRegex(ValueError, "at least 2 dimensions"):
            linalg.LinearOperatorFullMatrix([1.])

    def test_tape_safe(self):
        matrix = variables_module.Variable([[2., 1.]])
        operator = linalg.LinearOperatorFullMatrix(matrix)
        self.check_tape_safe(operator)


if __name__ == "__main__":
    linear_operator_test_util.add_tests(SquareLinearOperatorFullMatrixTest)
    linear_operator_test_util.add_tests(NonSquareLinearOperatorFullMatrixTest)
    linear_operator_test_util.add_tests(
        SquareLinearOperatorFullMatrixSymmetricPositiveDefiniteTest)
    test.main()
        linalg_lib.LinearOperatorZeros))

    self.assertTrue(isinstance(
        operator2.matmul(operator1),
        linalg_lib.LinearOperatorZeros))


class LinearOperatorZerosNotSquareTest(
    linear_operator_test_util.NonSquareLinearOperatorDerivedClassTest):

  def operator_and_matrix(self, build_info, dtype, use_placeholder):
    del use_placeholder
    shape = list(build_info.shape)

    batch_shape = shape[:-2]
    num_rows = shape[-2]
    num_columns = shape[-1]

    operator = linalg_lib.LinearOperatorZeros(
        num_rows, num_columns, is_square=False, is_self_adjoint=False,
        batch_shape=batch_shape, dtype=dtype)
    matrix = array_ops.zeros(shape=shape, dtype=dtype)

    return operator, matrix


if __name__ == "__main__":
  linear_operator_test_util.add_tests(LinearOperatorZerosTest)
  linear_operator_test_util.add_tests(LinearOperatorZerosNotSquareTest)
  test.main()
        kronecker.LinearOperatorKronecker)
    self.assertEqual(2, len(cholesky_factor.operators))
    self.assertIsInstance(
        cholesky_factor.operators[0],
        lower_triangular.LinearOperatorLowerTriangular)
    self.assertIsInstance(
        cholesky_factor.operators[1],
        lower_triangular.LinearOperatorLowerTriangular)

  def test_kronecker_inverse_type(self):
    matrix = [[1., 0.], [0., 1.]]
    operator = kronecker.LinearOperatorKronecker(
        [
            linalg.LinearOperatorFullMatrix(
                matrix, is_non_singular=True),
            linalg.LinearOperatorFullMatrix(
                matrix, is_non_singular=True),
        ],
        is_non_singular=True,
    )
    inverse = operator.inverse()
    self.assertIsInstance(
        inverse,
        kronecker.LinearOperatorKronecker)
    self.assertEqual(2, len(inverse.operators))


if __name__ == "__main__":
  linear_operator_test_util.add_tests(SquareLinearOperatorKroneckerTest)
  test.main()
      linalg.LinearOperatorLowerTriangular([1.])

  def test_triangular_diag_matmul(self):
    operator1 = linalg_lib.LinearOperatorLowerTriangular(
        [[1., 0., 0.], [2., 1., 0.], [2., 3., 3.]])
    operator2 = linalg_lib.LinearOperatorDiag([2., 2., 3.])
    operator_matmul = operator1.matmul(operator2)
    self.assertTrue(isinstance(
        operator_matmul,
        linalg_lib.LinearOperatorLowerTriangular))
    self.assertAllClose(
        math_ops.matmul(
            operator1.to_dense(),
            operator2.to_dense()),
        self.evaluate(operator_matmul.to_dense()))

    operator_matmul = operator2.matmul(operator1)
    self.assertTrue(isinstance(
        operator_matmul,
        linalg_lib.LinearOperatorLowerTriangular))
    self.assertAllClose(
        math_ops.matmul(
            operator2.to_dense(),
            operator1.to_dense()),
        self.evaluate(operator_matmul.to_dense()))


if __name__ == "__main__":
  linear_operator_test_util.add_tests(LinearOperatorLowerTriangularTest)
  test.main()
    operator = householder.LinearOperatorHouseholder(lin_op_reflection_axis)

    mat = reflection_axis[..., array_ops.newaxis]
    matrix = -2 * math_ops.matmul(mat, mat, adjoint_b=True)
    matrix = array_ops.matrix_set_diag(
        matrix, 1. + array_ops.matrix_diag_part(matrix))

    return operator, matrix

  def test_scalar_reflection_axis_raises(self):
    with self.assertRaisesRegexp(ValueError, "must have at least 1 dimension"):
      householder.LinearOperatorHouseholder(1.)

  def test_householder_adjoint_type(self):
    reflection_axis = [1., 3., 5., 8.]
    operator = householder.LinearOperatorHouseholder(reflection_axis)
    self.assertIsInstance(
        operator.adjoint(), householder.LinearOperatorHouseholder)

  def test_householder_inverse_type(self):
    reflection_axis = [1., 3., 5., 8.]
    operator = householder.LinearOperatorHouseholder(reflection_axis)
    self.assertIsInstance(
        operator.inverse(), householder.LinearOperatorHouseholder)


if __name__ == "__main__":
  linear_operator_test_util.add_tests(LinearOperatorHouseholderTest)
  test.main()
    lin_op_matrix = matrix

    if use_placeholder:
      lin_op_matrix = array_ops.placeholder_with_default(matrix, shape=None)

    operator = linalg.LinearOperatorFullMatrix(lin_op_matrix, is_square=True)

    return operator, matrix

  def test_is_x_flags(self):
    matrix = [[3., 2., 1.], [1., 1., 1.]]
    operator = linalg.LinearOperatorFullMatrix(
        matrix,
        is_self_adjoint=False)
    self.assertEqual(operator.is_positive_definite, None)
    self.assertEqual(operator.is_non_singular, None)
    self.assertFalse(operator.is_self_adjoint)
    self.assertFalse(operator.is_square)

  def test_matrix_must_have_at_least_two_dims_or_raises(self):
    with self.assertRaisesRegexp(ValueError, "at least 2 dimensions"):
      linalg.LinearOperatorFullMatrix([1.])


if __name__ == "__main__":
  linear_operator_test_util.add_tests(SquareLinearOperatorFullMatrixTest)
  linear_operator_test_util.add_tests(NonSquareLinearOperatorFullMatrixTest)
  linear_operator_test_util.add_tests(
      SquareLinearOperatorFullMatrixSymmetricPositiveDefiniteTest)
  test.main()
        is_self_adjoint=True if ensure_self_adjoint_and_pd else None,
        is_positive_definite=True if ensure_self_adjoint_and_pd else None)

    flattened_row = np.reshape(row, (-1, shape[-1]))
    flattened_col = np.reshape(col, (-1, shape[-1]))
    flattened_toeplitz = np.zeros(
        [flattened_row.shape[0], shape[-1], shape[-1]])
    for i in range(flattened_row.shape[0]):
      flattened_toeplitz[i] = scipy.linalg.toeplitz(
          flattened_col[i],
          flattened_row[i])
    matrix = np.reshape(flattened_toeplitz, shape)
    matrix = math_ops.cast(matrix, dtype=dtype)

    return operator, matrix

  def test_scalar_row_col_raises(self):
    with self.assertRaisesRegexp(ValueError, "must have at least 1 dimension"):
      linear_operator_toeplitz.LinearOperatorToeplitz(1., 1.)

    with self.assertRaisesRegexp(ValueError, "must have at least 1 dimension"):
      linear_operator_toeplitz.LinearOperatorToeplitz([1.], 1.)

    with self.assertRaisesRegexp(ValueError, "must have at least 1 dimension"):
      linear_operator_toeplitz.LinearOperatorToeplitz(1., [1.])


if __name__ == "__main__":
  linear_operator_test_util.add_tests(LinearOperatorToeplitzTest)
  test.main()
            # Just to test the theory, get S2 as well.
            # This should create an imaginary operator.
            # S2 is anti-Hermitian ==> operator is imaginary.
            # S2 is real ==> operator is self-adjoint.
            imag_ifft_s = math_ops.imag(ifft_s)
            fft_imag_ifft_s = fft_ops.fft3d(
                1j * math_ops.cast(imag_ifft_s, dtypes.complex64))
            operator_imag = linalg.LinearOperatorCirculant3D(fft_imag_ifft_s)

            matrix, matrix_h = self.evaluate([
                operator_imag.to_dense(),
                array_ops.matrix_transpose(
                    math_ops.conj(operator_imag.to_dense()))
            ])
            self.assertAllClose(matrix, matrix_h)
            np.testing.assert_allclose(0, np.real(matrix), atol=1e-7)


if __name__ == "__main__":
    linear_operator_test_util.add_tests(
        LinearOperatorCirculantTestSelfAdjointOperator)
    linear_operator_test_util.add_tests(
        LinearOperatorCirculantTestHermitianSpectrum)
    linear_operator_test_util.add_tests(
        LinearOperatorCirculantTestNonHermitianSpectrum)
    linear_operator_test_util.add_tests(
        LinearOperatorCirculant2DTestHermitianSpectrum)
    linear_operator_test_util.add_tests(
        LinearOperatorCirculant2DTestNonHermitianSpectrum)
    test.main()
    operators = [
        linalg.LinearOperatorFullMatrix(rng.rand(2, 3, 4)),
        linalg.LinearOperatorFullMatrix(rng.rand(2, 4, 5))
    ]
    operator = linalg.LinearOperatorComposition(operators)
    with self.cached_session():
      self.assertAllEqual((2, 3, 5), operator.shape_tensor().eval())

  @test_util.run_deprecated_v1
  def test_shape_tensors_when_only_dynamically_available(self):
    mat_1 = rng.rand(1, 2, 3, 4)
    mat_2 = rng.rand(1, 2, 4, 5)
    mat_ph_1 = array_ops.placeholder(dtypes.float64)
    mat_ph_2 = array_ops.placeholder(dtypes.float64)
    feed_dict = {mat_ph_1: mat_1, mat_ph_2: mat_2}

    operators = [
        linalg.LinearOperatorFullMatrix(mat_ph_1),
        linalg.LinearOperatorFullMatrix(mat_ph_2)
    ]
    operator = linalg.LinearOperatorComposition(operators)
    with self.cached_session():
      self.assertAllEqual(
          (1, 2, 3, 5), operator.shape_tensor().eval(feed_dict=feed_dict))


if __name__ == "__main__":
  linear_operator_test_util.add_tests(SquareLinearOperatorCompositionTest)
  linear_operator_test_util.add_tests(NonSquareLinearOperatorCompositionTest)
  test.main()
Exemplo n.º 17
0
            [
                linalg.LinearOperatorFullMatrix(matrix_1,
                                                is_non_singular=True),
                linalg.LinearOperatorFullMatrix(matrix_2,
                                                is_non_singular=True),
            ],
            is_non_singular=True,
        )
        self.check_tape_safe(operator)

    def test_convert_variables_to_tensors(self):
        matrix_1 = variables_module.Variable([[1., 0.], [0., 1.]])
        matrix_2 = variables_module.Variable([[2., 0.], [0., 2.]])
        operator = kronecker.LinearOperatorKronecker(
            [
                linalg.LinearOperatorFullMatrix(matrix_1,
                                                is_non_singular=True),
                linalg.LinearOperatorFullMatrix(matrix_2,
                                                is_non_singular=True),
            ],
            is_non_singular=True,
        )
        with self.cached_session() as sess:
            sess.run([x.initializer for x in operator.variables])
            self.check_convert_variables_to_tensors(operator)


if __name__ == "__main__":
    linear_operator_test_util.add_tests(SquareLinearOperatorKroneckerTest)
    test.main()
Exemplo n.º 18
0
        config.enable_tensor_float_32_execution(False)

    def operator_and_matrix(self,
                            build_info,
                            dtype,
                            use_placeholder,
                            ensure_self_adjoint_and_pd=False):
        return self.build_operator_and_matrix(
            build_info,
            dtype,
            use_placeholder,
            ensure_self_adjoint_and_pd=ensure_self_adjoint_and_pd,
            diagonals_format='matrix')

    @test_util.disable_xla(
        'Current implementation does not yet support pivoting')
    def test_tape_safe(self):
        matrix = variables_module.Variable([[3., 2., 0.], [1., 6., 4.],
                                            [0., 2, 2]])
        operator = linalg_lib.LinearOperatorTridiag(matrix,
                                                    diagonals_format='matrix')
        self.check_tape_safe(operator)


if __name__ == '__main__':
    if not test_util.is_xla_enabled():
        linear_operator_test_util.add_tests(LinearOperatorTriDiagCompactTest)
        linear_operator_test_util.add_tests(LinearOperatorTriDiagSequenceTest)
        linear_operator_test_util.add_tests(LinearOperatorTriDiagMatrixTest)
    test.main()
Exemplo n.º 19
0
                operators)

    def test_incompatible_input_blocks_raises(self):
        matrix_1 = array_ops.placeholder_with_default(rng.rand(4, 4),
                                                      shape=None)
        matrix_2 = array_ops.placeholder_with_default(rng.rand(3, 4),
                                                      shape=None)
        matrix_3 = array_ops.placeholder_with_default(rng.rand(3, 3),
                                                      shape=None)
        operators = [[
            linalg.LinearOperatorFullMatrix(matrix_1, is_square=True)
        ],
                     [
                         linalg.LinearOperatorFullMatrix(matrix_2),
                         linalg.LinearOperatorFullMatrix(matrix_3,
                                                         is_square=True)
                     ]]
        operator = block_lower_triangular.LinearOperatorBlockLowerTriangular(
            operators)
        x = np.random.rand(2, 4, 5).tolist()
        msg = ("dimension does not match" if context.executing_eagerly() else
               "input structure is ambiguous")
        with self.assertRaisesRegex(ValueError, msg):
            operator.matmul(x)


if __name__ == "__main__":
    linear_operator_test_util.add_tests(
        SquareLinearOperatorBlockLowerTriangularTest)
    test.main()
      # Just to test the theory, get S2 as well.
      # This should create an imaginary operator.
      # S2 is anti-Hermitian ==> operator is imaginary.
      # S2 is real ==> operator is self-adjoint.
      imag_ifft_s = math_ops.imag(ifft_s)
      fft_imag_ifft_s = fft_ops.fft3d(
          1j * math_ops.cast(imag_ifft_s, dtypes.complex64))
      operator_imag = linalg.LinearOperatorCirculant3D(fft_imag_ifft_s)

      matrix, matrix_h = sess.run([
          operator_imag.to_dense(),
          array_ops.matrix_transpose(math_ops.conj(operator_imag.to_dense()))
      ])
      self.assertAllClose(matrix, matrix_h)
      np.testing.assert_allclose(0, np.real(matrix), atol=1e-7)


if __name__ == "__main__":
  linear_operator_test_util.add_tests(
      LinearOperatorCirculantTestSelfAdjointOperator)
  linear_operator_test_util.add_tests(
      LinearOperatorCirculantTestHermitianSpectrum)
  linear_operator_test_util.add_tests(
      LinearOperatorCirculantTestNonHermitianSpectrum)
  linear_operator_test_util.add_tests(
      LinearOperatorCirculant2DTestHermitianSpectrum)
  linear_operator_test_util.add_tests(
      LinearOperatorCirculant2DTestNonHermitianSpectrum)
  test.main()
Exemplo n.º 21
0
                array_ops.placeholder_with_default(matrix, shape=None)
                for matrix in matrices
            ]

        blocks = []
        for l in lin_op_matrices:
            blocks.append(
                linalg.LinearOperatorFullMatrix(l,
                                                is_square=False,
                                                is_self_adjoint=False,
                                                is_positive_definite=False))
        operator = block_diag.LinearOperatorBlockDiag(blocks)

        # Broadcast the shapes.
        expected_shape = list(shape_info.shape)

        matrices = linear_operator_util.broadcast_matrix_batch_dims(matrices)

        block_diag_dense = _block_diag_dense(expected_shape, matrices)

        if not use_placeholder:
            block_diag_dense.set_shape(expected_shape)

        return operator, block_diag_dense


if __name__ == "__main__":
    linear_operator_test_util.add_tests(SquareLinearOperatorBlockDiagTest)
    linear_operator_test_util.add_tests(NonSquareLinearOperatorBlockDiagTest)
    test.main()
        operator_solve,
        linalg_lib.LinearOperatorScaledIdentity))
    self.assertAllClose(3., self.evaluate(operator_solve.multiplier))

  def test_scaled_identity_cholesky_type(self):
    operator = linalg_lib.LinearOperatorScaledIdentity(
        num_rows=2,
        multiplier=3.,
        is_positive_definite=True,
        is_self_adjoint=True,
    )
    self.assertIsInstance(
        operator.cholesky(),
        linalg_lib.LinearOperatorScaledIdentity)

  def test_scaled_identity_inverse_type(self):
    operator = linalg_lib.LinearOperatorScaledIdentity(
        num_rows=2,
        multiplier=3.,
        is_non_singular=True,
    )
    self.assertIsInstance(
        operator.inverse(),
        linalg_lib.LinearOperatorScaledIdentity)


if __name__ == "__main__":
  linear_operator_test_util.add_tests(LinearOperatorIdentityTest)
  linear_operator_test_util.add_tests(LinearOperatorScaledIdentityTest)
  test.main()
    operators = [
        linalg.LinearOperatorFullMatrix(rng.rand(2, 3, 4)),
        linalg.LinearOperatorFullMatrix(rng.rand(2, 4, 5))
    ]
    operator = linalg.LinearOperatorComposition(operators)
    with self.cached_session():
      self.assertAllEqual((2, 3, 5), operator.shape_tensor())

  @test_util.run_deprecated_v1
  def test_shape_tensors_when_only_dynamically_available(self):
    mat_1 = rng.rand(1, 2, 3, 4)
    mat_2 = rng.rand(1, 2, 4, 5)
    mat_ph_1 = array_ops.placeholder(dtypes.float64)
    mat_ph_2 = array_ops.placeholder(dtypes.float64)
    feed_dict = {mat_ph_1: mat_1, mat_ph_2: mat_2}

    operators = [
        linalg.LinearOperatorFullMatrix(mat_ph_1),
        linalg.LinearOperatorFullMatrix(mat_ph_2)
    ]
    operator = linalg.LinearOperatorComposition(operators)
    with self.cached_session():
      self.assertAllEqual(
          (1, 2, 3, 5), operator.shape_tensor().eval(feed_dict=feed_dict))


if __name__ == "__main__":
  linear_operator_test_util.add_tests(SquareLinearOperatorCompositionTest)
  linear_operator_test_util.add_tests(NonSquareLinearOperatorCompositionTest)
  test.main()
Exemplo n.º 24
0
            is_self_adjoint=True,
        )
        self.assertIsInstance(operator.cholesky(),
                              linalg_lib.LinearOperatorScaledIdentity)

    def test_scaled_identity_inverse_type(self):
        operator = linalg_lib.LinearOperatorScaledIdentity(
            num_rows=2,
            multiplier=3.,
            is_non_singular=True,
        )
        self.assertIsInstance(operator.inverse(),
                              linalg_lib.LinearOperatorScaledIdentity)

    def test_ref_type_shape_args_raises(self):
        with self.assertRaisesRegexp(TypeError, "num_rows.*reference"):
            linalg_lib.LinearOperatorScaledIdentity(
                num_rows=variables_module.Variable(2), multiplier=1.23)

    def test_tape_safe(self):
        multiplier = variables_module.Variable(1.23)
        operator = linalg_lib.LinearOperatorScaledIdentity(
            num_rows=2, multiplier=multiplier)
        self.check_tape_safe(operator)


if __name__ == "__main__":
    linear_operator_test_util.add_tests(LinearOperatorIdentityTest)
    linear_operator_test_util.add_tests(LinearOperatorScaledIdentityTest)
    test.main()
        self.assertAllClose([2 / 3., 1.], self.evaluate(operator_solve.diag))

    def test_diag_adjoint_type(self):
        diag = [1., 3., 5., 8.]
        operator = linalg.LinearOperatorDiag(diag, is_non_singular=True)
        self.assertIsInstance(operator.adjoint(), linalg.LinearOperatorDiag)

    def test_diag_cholesky_type(self):
        diag = [1., 3., 5., 8.]
        operator = linalg.LinearOperatorDiag(
            diag,
            is_positive_definite=True,
            is_self_adjoint=True,
        )
        self.assertIsInstance(operator.cholesky(), linalg.LinearOperatorDiag)

    def test_diag_inverse_type(self):
        diag = [1., 3., 5., 8.]
        operator = linalg.LinearOperatorDiag(diag, is_non_singular=True)
        self.assertIsInstance(operator.inverse(), linalg.LinearOperatorDiag)

    def test_tape_safe(self):
        diag = variables_module.Variable([[2.]])
        operator = linalg.LinearOperatorDiag(diag)
        self.check_tape_safe(operator)


if __name__ == "__main__":
    linear_operator_test_util.add_tests(LinearOperatorDiagTest)
    test.main()
        perm = constant_op.constant(0, dtype=dtypes.int32)
        with self.assertRaisesRegex(ValueError,
                                    "must have at least 1 dimension"):
            permutation.LinearOperatorPermutation(perm)
        perm = [0., 1., 2.]
        with self.assertRaisesRegex(TypeError, "must be integer dtype"):
            permutation.LinearOperatorPermutation(perm)
        perm = [-1, 2, 3]
        with self.assertRaisesRegex(ValueError,
                                    "must be a vector of unique integers"):
            permutation.LinearOperatorPermutation(perm)

    def test_to_dense_4x4(self):
        perm = [0, 1, 2, 3]
        self.assertAllClose(
            permutation.LinearOperatorPermutation(perm).to_dense(),
            linalg_ops.eye(4))
        perm = [1, 0, 3, 2]
        self.assertAllClose(
            permutation.LinearOperatorPermutation(perm).to_dense(),
            [[0., 1, 0, 0], [1., 0, 0, 0], [0., 0, 0, 1], [0., 0, 1, 0]])
        perm = [3, 2, 0, 1]
        self.assertAllClose(
            permutation.LinearOperatorPermutation(perm).to_dense(),
            [[0., 0, 0, 1], [0., 0, 1, 0], [1., 0, 0, 0], [0., 1, 0, 0]])


if __name__ == "__main__":
    linear_operator_test_util.add_tests(LinearOperatorPermutationTest)
    test.main()
    operator_2 = linalg.LinearOperatorFullMatrix(matrix, name="right")

    operator = block_diag.LinearOperatorBlockDiag([operator_1, operator_2])

    self.assertEqual("left_ds_right", operator.name)

  def test_different_dtypes_raises(self):
    operators = [
        linalg.LinearOperatorFullMatrix(rng.rand(2, 3, 3)),
        linalg.LinearOperatorFullMatrix(rng.rand(2, 3, 3).astype(np.float32))
    ]
    with self.assertRaisesRegexp(TypeError, "same dtype"):
      block_diag.LinearOperatorBlockDiag(operators)

  def test_non_square_operator_raises(self):
    operators = [
        linalg.LinearOperatorFullMatrix(rng.rand(3, 4), is_square=False),
        linalg.LinearOperatorFullMatrix(rng.rand(3, 3))
    ]
    with self.assertRaisesRegexp(ValueError, "square matrices"):
      block_diag.LinearOperatorBlockDiag(operators)

  def test_empty_operators_raises(self):
    with self.assertRaisesRegexp(ValueError, "non-empty"):
      block_diag.LinearOperatorBlockDiag([])


if __name__ == "__main__":
  linear_operator_test_util.add_tests(SquareLinearOperatorBlockDiagTest)
  test.main()
Exemplo n.º 28
0
        operator = linalg.LinearOperatorFullMatrix(matrix,
                                                   is_non_singular=False)
        with self.assertRaisesRegex(ValueError, "is_non_singular"):
            LinearOperatorInversion(operator)

        operator = linalg.LinearOperatorFullMatrix(matrix)
        with self.assertRaisesRegex(ValueError, "is_non_singular"):
            LinearOperatorInversion(operator, is_non_singular=False)

    def test_name(self):
        matrix = [[11., 0.], [1., 8.]]
        operator = linalg.LinearOperatorFullMatrix(matrix,
                                                   name="my_operator",
                                                   is_non_singular=True)

        operator = LinearOperatorInversion(operator)

        self.assertEqual("my_operator_inv", operator.name)

    def test_tape_safe(self):
        matrix = variables_module.Variable([[1., 2.], [3., 4.]])
        operator = LinearOperatorInversion(
            linalg.LinearOperatorFullMatrix(matrix))
        self.check_tape_safe(operator)


if __name__ == "__main__":
    linear_operator_test_util.add_tests(LinearOperatorInversionTest)
    test.main()
Exemplo n.º 29
0
class LinearOperatorZerosNotSquareTest(
        linear_operator_test_util.NonSquareLinearOperatorDerivedClassTest):
    def operator_and_matrix(self,
                            build_info,
                            dtype,
                            use_placeholder,
                            ensure_self_adjoint_and_pd=False):
        del use_placeholder
        del ensure_self_adjoint_and_pd
        shape = list(build_info.shape)

        batch_shape = shape[:-2]
        num_rows = shape[-2]
        num_columns = shape[-1]

        operator = linalg_lib.LinearOperatorZeros(num_rows,
                                                  num_columns,
                                                  is_square=False,
                                                  is_self_adjoint=False,
                                                  batch_shape=batch_shape,
                                                  dtype=dtype)
        matrix = array_ops.zeros(shape=shape, dtype=dtype)

        return operator, matrix


if __name__ == "__main__":
    linear_operator_test_util.add_tests(LinearOperatorZerosTest)
    linear_operator_test_util.add_tests(LinearOperatorZerosNotSquareTest)
    test.main()
                full_matrix2, adjoint=True, adjoint_arg=True).to_dense()))


class LinearOperatorAdjointNonSquareTest(
    linear_operator_test_util.NonSquareLinearOperatorDerivedClassTest):
  """Tests done in the base class NonSquareLinearOperatorDerivedClassTest."""

  def operator_and_matrix(self, build_info, dtype, use_placeholder):
    shape_before_adjoint = list(build_info.shape)
    # We need to swap the last two dimensions because we are taking the adjoint
    # of this operator
    shape_before_adjoint[-1], shape_before_adjoint[-2] = (
        shape_before_adjoint[-2], shape_before_adjoint[-1])
    matrix = linear_operator_test_util.random_normal(
        shape_before_adjoint, dtype=dtype)

    lin_op_matrix = matrix

    if use_placeholder:
      lin_op_matrix = array_ops.placeholder_with_default(matrix, shape=None)

    operator = LinearOperatorAdjoint(
        linalg.LinearOperatorFullMatrix(lin_op_matrix))

    return operator, linalg.adjoint(matrix)


if __name__ == "__main__":
  linear_operator_test_util.add_tests(LinearOperatorAdjointTest)
  test.main()