1# Copyright 2016 The TensorFlow Authors. All Rights Reserved. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14# ============================================================================== 15"""`LinearOperator` acting like a diagonal matrix.""" 16 17from __future__ import absolute_import 18from __future__ import division 19from __future__ import print_function 20 21from tensorflow.python.framework import dtypes 22from tensorflow.python.framework import ops 23from tensorflow.python.ops import array_ops 24from tensorflow.python.ops import check_ops 25from tensorflow.python.ops import math_ops 26from tensorflow.python.ops.linalg import linalg_impl as linalg 27from tensorflow.python.ops.linalg import linear_operator 28from tensorflow.python.ops.linalg import linear_operator_util 29from tensorflow.python.util.tf_export import tf_export 30 31__all__ = ["LinearOperatorDiag",] 32 33 34@tf_export("linalg.LinearOperatorDiag") 35class LinearOperatorDiag(linear_operator.LinearOperator): 36 """`LinearOperator` acting like a [batch] square diagonal matrix. 37 38 This operator acts like a [batch] diagonal matrix `A` with shape 39 `[B1,...,Bb, N, N]` for some `b >= 0`. The first `b` indices index a 40 batch member. For every batch index `(i1,...,ib)`, `A[i1,...,ib, : :]` is 41 an `N x N` matrix. This matrix `A` is not materialized, but for 42 purposes of broadcasting this shape will be relevant. 43 44 `LinearOperatorDiag` is initialized with a (batch) vector. 45 46 ```python 47 # Create a 2 x 2 diagonal linear operator. 48 diag = [1., -1.] 49 operator = LinearOperatorDiag(diag) 50 51 operator.to_dense() 52 ==> [[1., 0.] 53 [0., -1.]] 54 55 operator.shape 56 ==> [2, 2] 57 58 operator.log_abs_determinant() 59 ==> scalar Tensor 60 61 x = ... Shape [2, 4] Tensor 62 operator.matmul(x) 63 ==> Shape [2, 4] Tensor 64 65 # Create a [2, 3] batch of 4 x 4 linear operators. 66 diag = tf.random_normal(shape=[2, 3, 4]) 67 operator = LinearOperatorDiag(diag) 68 69 # Create a shape [2, 1, 4, 2] vector. Note that this shape is compatible 70 # since the batch dimensions, [2, 1], are broadcast to 71 # operator.batch_shape = [2, 3]. 72 y = tf.random_normal(shape=[2, 1, 4, 2]) 73 x = operator.solve(y) 74 ==> operator.matmul(x) = y 75 ``` 76 77 #### Shape compatibility 78 79 This operator acts on [batch] matrix with compatible shape. 80 `x` is a batch matrix with compatible shape for `matmul` and `solve` if 81 82 ``` 83 operator.shape = [B1,...,Bb] + [N, N], with b >= 0 84 x.shape = [C1,...,Cc] + [N, R], 85 and [C1,...,Cc] broadcasts with [B1,...,Bb] to [D1,...,Dd] 86 ``` 87 88 #### Performance 89 90 Suppose `operator` is a `LinearOperatorDiag` of shape `[N, N]`, 91 and `x.shape = [N, R]`. Then 92 93 * `operator.matmul(x)` involves `N * R` multiplications. 94 * `operator.solve(x)` involves `N` divisions and `N * R` multiplications. 95 * `operator.determinant()` involves a size `N` `reduce_prod`. 96 97 If instead `operator` and `x` have shape `[B1,...,Bb, N, N]` and 98 `[B1,...,Bb, N, R]`, every operation increases in complexity by `B1*...*Bb`. 99 100 #### Matrix property hints 101 102 This `LinearOperator` is initialized with boolean flags of the form `is_X`, 103 for `X = non_singular, self_adjoint, positive_definite, square`. 104 These have the following meaning: 105 106 * If `is_X == True`, callers should expect the operator to have the 107 property `X`. This is a promise that should be fulfilled, but is *not* a 108 runtime assert. For example, finite floating point precision may result 109 in these promises being violated. 110 * If `is_X == False`, callers should expect the operator to not have `X`. 111 * If `is_X == None` (the default), callers should have no expectation either 112 way. 113 """ 114 115 def __init__(self, 116 diag, 117 is_non_singular=None, 118 is_self_adjoint=None, 119 is_positive_definite=None, 120 is_square=None, 121 name="LinearOperatorDiag"): 122 r"""Initialize a `LinearOperatorDiag`. 123 124 Args: 125 diag: Shape `[B1,...,Bb, N]` `Tensor` with `b >= 0` `N >= 0`. 126 The diagonal of the operator. Allowed dtypes: `float16`, `float32`, 127 `float64`, `complex64`, `complex128`. 128 is_non_singular: Expect that this operator is non-singular. 129 is_self_adjoint: Expect that this operator is equal to its hermitian 130 transpose. If `diag.dtype` is real, this is auto-set to `True`. 131 is_positive_definite: Expect that this operator is positive definite, 132 meaning the quadratic form `x^H A x` has positive real part for all 133 nonzero `x`. Note that we do not require the operator to be 134 self-adjoint to be positive-definite. See: 135 https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices 136 is_square: Expect that this operator acts like square [batch] matrices. 137 name: A name for this `LinearOperator`. 138 139 Raises: 140 TypeError: If `diag.dtype` is not an allowed type. 141 ValueError: If `diag.dtype` is real, and `is_self_adjoint` is not `True`. 142 """ 143 144 with ops.name_scope(name, values=[diag]): 145 self._diag = ops.convert_to_tensor(diag, name="diag") 146 self._check_diag(self._diag) 147 148 # Check and auto-set hints. 149 if not self._diag.dtype.is_complex: 150 if is_self_adjoint is False: 151 raise ValueError("A real diagonal operator is always self adjoint.") 152 else: 153 is_self_adjoint = True 154 155 if is_square is False: 156 raise ValueError("Only square diagonal operators currently supported.") 157 is_square = True 158 159 super(LinearOperatorDiag, self).__init__( 160 dtype=self._diag.dtype, 161 graph_parents=[self._diag], 162 is_non_singular=is_non_singular, 163 is_self_adjoint=is_self_adjoint, 164 is_positive_definite=is_positive_definite, 165 is_square=is_square, 166 name=name) 167 168 def _check_diag(self, diag): 169 """Static check of diag.""" 170 allowed_dtypes = [ 171 dtypes.float16, 172 dtypes.float32, 173 dtypes.float64, 174 dtypes.complex64, 175 dtypes.complex128, 176 ] 177 178 dtype = diag.dtype 179 if dtype not in allowed_dtypes: 180 raise TypeError( 181 "Argument diag must have dtype in %s. Found: %s" 182 % (allowed_dtypes, dtype)) 183 184 if diag.get_shape().ndims is not None and diag.get_shape().ndims < 1: 185 raise ValueError("Argument diag must have at least 1 dimension. " 186 "Found: %s" % diag) 187 188 def _shape(self): 189 # If d_shape = [5, 3], we return [5, 3, 3]. 190 d_shape = self._diag.get_shape() 191 return d_shape.concatenate(d_shape[-1:]) 192 193 def _shape_tensor(self): 194 d_shape = array_ops.shape(self._diag) 195 k = d_shape[-1] 196 return array_ops.concat((d_shape, [k]), 0) 197 198 def _assert_non_singular(self): 199 return linear_operator_util.assert_no_entries_with_modulus_zero( 200 self._diag, 201 message="Singular operator: Diagonal contained zero values.") 202 203 def _assert_positive_definite(self): 204 if self.dtype.is_complex: 205 message = ( 206 "Diagonal operator had diagonal entries with non-positive real part, " 207 "thus was not positive definite.") 208 else: 209 message = ( 210 "Real diagonal operator had non-positive diagonal entries, " 211 "thus was not positive definite.") 212 213 return check_ops.assert_positive( 214 math_ops.real(self._diag), 215 message=message) 216 217 def _assert_self_adjoint(self): 218 return linear_operator_util.assert_zero_imag_part( 219 self._diag, 220 message=( 221 "This diagonal operator contained non-zero imaginary values. " 222 " Thus it was not self-adjoint.")) 223 224 def _matmul(self, x, adjoint=False, adjoint_arg=False): 225 diag_term = math_ops.conj(self._diag) if adjoint else self._diag 226 x = linalg.adjoint(x) if adjoint_arg else x 227 diag_mat = array_ops.expand_dims(diag_term, -1) 228 return diag_mat * x 229 230 def _determinant(self): 231 return math_ops.reduce_prod(self._diag, axis=[-1]) 232 233 def _log_abs_determinant(self): 234 log_det = math_ops.reduce_sum( 235 math_ops.log(math_ops.abs(self._diag)), axis=[-1]) 236 if self.dtype.is_complex: 237 log_det = math_ops.cast(log_det, dtype=self.dtype) 238 return log_det 239 240 def _solve(self, rhs, adjoint=False, adjoint_arg=False): 241 diag_term = math_ops.conj(self._diag) if adjoint else self._diag 242 rhs = linalg.adjoint(rhs) if adjoint_arg else rhs 243 inv_diag_mat = array_ops.expand_dims(1. / diag_term, -1) 244 return rhs * inv_diag_mat 245 246 def _to_dense(self): 247 return array_ops.matrix_diag(self._diag) 248 249 def _diag_part(self): 250 return self.diag 251 252 def _add_to_tensor(self, x): 253 x_diag = array_ops.matrix_diag_part(x) 254 new_diag = self._diag + x_diag 255 return array_ops.matrix_set_diag(x, new_diag) 256 257 @property 258 def diag(self): 259 return self._diag 260