def _matmul(self, x, adjoint=False, adjoint_arg=False):
        if self._assert_proper_shapes:
            x = linalg.adjoint(x) if adjoint_arg else x
            aps = linear_operator_util.assert_compatible_matrix_dimensions(
                self, x)
            x = distribution_util.with_dependencies([aps], x)
        if self.is_square:
            # Note that adjoint has no effect since this matrix is self-adjoint.
            if adjoint_arg:
                output_shape = array_ops.concat([
                    array_ops.shape(x)[:-2],
                    [array_ops.shape(x)[-1],
                     array_ops.shape(x)[-2]]
                ],
                                                axis=0)
            else:
                output_shape = array_ops.shape(x)

            return self._possibly_broadcast_batch_shape(
                array_ops.zeros(shape=output_shape, dtype=x.dtype))

        x_shape = array_ops.shape(x)
        n = self._num_columns if adjoint else self._num_rows
        m = x_shape[-2] if adjoint_arg else x_shape[-1]

        output_shape = array_ops.concat([x_shape[:-2], [n, m]], axis=0)

        zeros = array_ops.zeros(shape=output_shape, dtype=x.dtype)
        return self._possibly_broadcast_batch_shape(zeros)
 def _to_dense(self):
     product = self.operators[0].to_dense()
     for operator in self.operators[1:]:
         # Product has shape [B, R1, 1, C1, 1].
         product = product[..., :, _ops.newaxis, :, _ops.newaxis]
         # Operator has shape [B, 1, R2, 1, C2].
         op_to_mul = operator.to_dense()[..., _ops.newaxis, :,
                                         _ops.newaxis, :]
         # This is now [B, R1, R2, C1, C2].
         product = product * op_to_mul
         # Now merge together dimensions to get [B, R1 * R2, C1 * C2].
         product = array_ops.reshape(product,
                                     shape=array_ops.concat([
                                         array_ops.shape(product)[:-4],
                                         [
                                             array_ops.shape(product)[-4] *
                                             array_ops.shape(product)[-3],
                                             array_ops.shape(product)[-2] *
                                             array_ops.shape(product)[-1]
                                         ]
                                     ],
                                                            axis=0))
     tensorshape_util.set_shape(product,
                                tensor_shape.TensorShape(self.shape))
     return product
Ejemplo n.º 3
0
    def _to_dense(self):
        num_cols = 0
        rows = []
        broadcasted_blocks = [
            operator.to_dense() for operator in self.operators
        ]
        broadcasted_blocks = linear_operator_util.broadcast_matrix_batch_dims(
            broadcasted_blocks)
        for block in broadcasted_blocks:
            batch_row_shape = array_ops.shape(block)[:-1]

            zeros_to_pad_before_shape = array_ops.concat(
                [batch_row_shape, [num_cols]], axis=-1)
            zeros_to_pad_before = array_ops.zeros(
                shape=zeros_to_pad_before_shape, dtype=block.dtype)
            num_cols += array_ops.shape(block)[-1]
            zeros_to_pad_after_shape = array_ops.concat(
                [batch_row_shape, [self.domain_dimension_tensor() - num_cols]],
                axis=-1)
            zeros_to_pad_after = array_ops.zeros(
                shape=zeros_to_pad_after_shape, dtype=block.dtype)

            rows.append(
                array_ops.concat(
                    [zeros_to_pad_before, block, zeros_to_pad_after], axis=-1))

        mat = array_ops.concat(rows, axis=-2)
        tensorshape_util.set_shape(mat, tensor_shape.TensorShape(self.shape))
        return mat
 def _shape_tensor(self, row=None, col=None):
     row = self.row if row is None else row
     col = self.col if col is None else col
     v_shape = array_ops.broadcast_dynamic_shape(array_ops.shape(row),
                                                 array_ops.shape(col))
     k = v_shape[-1]
     return array_ops.concat((v_shape, [k]), 0)
 def _to_dense(self):
     row = ops.convert_to_tensor(self.row)
     col = ops.convert_to_tensor(self.col)
     total_shape = array_ops.broadcast_dynamic_shape(
         array_ops.shape(row), array_ops.shape(col))
     n = array_ops.shape(row)[-1]
     row = _ops.broadcast_to(row, total_shape)
     col = _ops.broadcast_to(col, total_shape)
     # We concatenate the column in reverse order to the row.
     # This gives us 2*n + 1 elements.
     elements = array_ops.concat(
         [array_ops.reverse(col, axis=[-1]), row[..., 1:]], axis=-1)
     # Given the above vector, the i-th row of the Toeplitz matrix
     # is the last n elements of the above vector shifted i right
     # (hence the first row is just the row vector provided, and
     # the first element of each row will belong to the column vector).
     # We construct these set of indices below.
     indices = math_ops.mod(
         # How much to shift right. This corresponds to `i`.
         math_ops.range(0, n) +
         # Specifies the last `n` indices.
         math_ops.range(n - 1, -1, -1)[..., _ops.newaxis],
         # Mod out by the total number of elements to ensure the index is
         # non-negative (for tf.gather) and < 2 * n - 1.
         2 * n - 1)
     return array_ops.gather(elements, indices, axis=-1)
Ejemplo n.º 6
0
 def _shape_tensor(self):
     batch_shape = array_ops.broadcast_dynamic_shape(
         self.base_operator.batch_shape_tensor(),
         array_ops.shape(self.u)[:-2])
     batch_shape = array_ops.broadcast_dynamic_shape(
         batch_shape,
         array_ops.shape(self.v)[:-2])
     return array_ops.concat(
         [batch_shape, self.base_operator.shape_tensor()[-2:]], axis=0)
Ejemplo n.º 7
0
    def _vectorize_then_blockify(self, matrix):
        """Shape batch matrix to batch vector, then blockify trailing dimensions."""
        # Suppose
        #   tensor_shape.TensorShape(matrix.shape) = [m0, m1, m2, m3],
        # and matrix is a matrix because the final two dimensions are matrix dims.
        #   self.block_depth = 2,
        #   self.block_shape = [b0, b1]  (note b0 * b1 = m2).
        # We will reshape matrix to
        #   [m3, m0, m1, b0, b1].

        # Vectorize: Reshape to batch vector.
        #   [m0, m1, m2, m3] --> [m3, m0, m1, m2]
        # This is called "vectorize" because we have taken the final two matrix dims
        # and turned this into a size m3 batch of vectors.
        vec = distribution_util.rotate_transpose(matrix, shift=1)

        # Blockify: Blockfy trailing dimensions.
        #   [m3, m0, m1, m2] --> [m3, m0, m1, b0, b1]
        if (tensor_shape.TensorShape(vec.shape).is_fully_defined()
                and self.block_shape.is_fully_defined()):
            # vec_leading_shape = [m3, m0, m1],
            # the parts of vec that will not be blockified.
            vec_leading_shape = tensor_shape.TensorShape(vec.shape)[:-1]
            final_shape = vec_leading_shape.concatenate(self.block_shape)
        else:
            vec_leading_shape = array_ops.shape(vec)[:-1]
            final_shape = array_ops.concat(
                (vec_leading_shape, self.block_shape_tensor()), 0)
        return array_ops.reshape(vec, final_shape)
Ejemplo n.º 8
0
  def _unblockify_then_matricize(self, vec):
    """Flatten the block dimensions then reshape to a batch matrix."""
    # Suppose
    #   tensor_shape.TensorShape(vec.shape) = [v0, v1, v2, v3],
    #   self.block_depth = 2.
    # Then
    #   leading shape = [v0, v1]
    #   block shape = [v2, v3].
    # We will reshape vec to
    #   [v1, v2*v3, v0].

    # Un-blockify: Flatten block dimensions.  Reshape
    #   [v0, v1, v2, v3] --> [v0, v1, v2*v3].
    if tensor_shape.TensorShape(vec.shape).is_fully_defined():
      # vec_shape = [v0, v1, v2, v3]
      vec_shape = tensor_shape.TensorShape(vec.shape).as_list()
      # vec_leading_shape = [v0, v1]
      vec_leading_shape = vec_shape[:-self.block_depth]
      # vec_block_shape = [v2, v3]
      vec_block_shape = vec_shape[-self.block_depth:]
      # flat_shape = [v0, v1, v2*v3]
      flat_shape = vec_leading_shape + [np.prod(vec_block_shape)]
    else:
      vec_shape = array_ops.shape(vec)
      vec_leading_shape = vec_shape[:-self.block_depth]
      vec_block_shape = vec_shape[-self.block_depth:]
      flat_shape = array_ops.concat(
          (vec_leading_shape, [math_ops.reduce_prod(vec_block_shape)]), 0)
    vec_flat = array_ops.reshape(vec, flat_shape)

    # Matricize:  Reshape to batch matrix.
    #   [v0, v1, v2*v3] --> [v1, v2*v3, v0],
    # representing a shape [v1] batch of [v2*v3, v0] matrices.
    matrix = distribution_util.rotate_transpose(vec_flat, shift=-1)
    return matrix
Ejemplo n.º 9
0
def assert_compatible_matrix_dimensions(operator, x):
  """Assert that an argument to solve/matmul has proper domain dimension.

  If `tensor_shape.TensorShape(operator.shape)[-2:] = [M, N]`, and `tensor_shape.TensorShape(x.shape)[-2:] = [Q, R]`, then
  `operator.matmul(x)` is defined only if `N = Q`.  This `Op` returns an
  `Assert` that "fires" if this is not the case.  Static checks are already
  done by the base class `LinearOperator`.

  Args:
    operator:  `LinearOperator`.
    x:  `Tensor`.

  Returns:
    `Assert` `Op`.
  """
  # Static checks are done in the base class.  Only tensor asserts here.
  assert_same_dd = check_ops.assert_equal(
      array_ops.shape(x)[-2],
      operator.domain_dimension_tensor(),
      # This error message made to look similar to error raised by static check
      # in the base class.
      message=("Dimensions are not compatible.  "
               "shape[-2] of argument to be the same as this operator"))

  return assert_same_dd
def _unvec_by(y, num_col):
    """Unstack vector to form a matrix, with a specified amount of columns."""
    return _linalg.matrix_transpose(
        array_ops.reshape(
            y,
            array_ops.concat([array_ops.shape(y)[:-1], [num_col, -1]],
                             axis=0)))
Ejemplo n.º 11
0
 def _block_shape_tensor(self, spectrum_shape=None):
     if self.block_shape.is_fully_defined():
         return linear_operator_util.shape_tensor(
             self.block_shape.as_list(), name="block_shape")
     spectrum_shape = (array_ops.shape(self.spectrum)
                       if spectrum_shape is None else spectrum_shape)
     return spectrum_shape[-self.block_depth:]
Ejemplo n.º 12
0
 def _shape_tensor(self):
   # See _ops.TensorShape(self.shape) for explanation of steps
   s_shape = array_ops.shape(self._spectrum)
   batch_shape = s_shape[:-self.block_depth]
   trailing_dims = s_shape[-self.block_depth:]
   n = math_ops.reduce_prod(trailing_dims)
   n_x_n = [n, n]
   return array_ops.concat((batch_shape, n_x_n), 0)
Ejemplo n.º 13
0
 def _shape_tensor(self, spectrum=None):
     spectrum = self.spectrum if spectrum is None else spectrum
     # See tensor_shape.TensorShape(self.shape) for explanation of steps
     s_shape = array_ops.shape(spectrum)
     batch_shape = s_shape[:-self.block_depth]
     trailing_dims = s_shape[-self.block_depth:]
     n = math_ops.reduce_prod(trailing_dims)
     n_x_n = [n, n]
     return array_ops.concat((batch_shape, n_x_n), 0)
Ejemplo n.º 14
0
 def reshape_inv(y):
   # Expand the extra dims hanging off the end, "b_extra_sh".
   # Note we use y_sh[:-1] + [b_main_sh[-1]] rather than b_main_sh, because y
   # Could have different batch dims than a and b, because of broadcasting.
   y_extra_shape = array_ops.concat(
       (array_ops.shape(y)[:-1], [b_main_sh[-1]], b_extra_sh), 0)
   y_extra_on_end = array_ops.reshape(y, y_extra_shape)
   inverse_perm = np.argsort(perm)
   return array_ops.transpose(y_extra_on_end, perm=inverse_perm)
 def _eigvals(self):
   # We have (n - 1) +1 eigenvalues and a single -1 eigenvalue.
   result_shape = array_ops.shape(self.reflection_axis)
   n = result_shape[-1]
   ones_shape = array_ops.concat([result_shape[:-1], [n - 1]], axis=-1)
   neg_shape = array_ops.concat([result_shape[:-1], [1]], axis=-1)
   eigvals = array_ops.ones(shape=ones_shape, dtype=self.dtype)
   eigvals = array_ops.concat(
       [-array_ops.ones(shape=neg_shape, dtype=self.dtype), eigvals], axis=-1)
   return eigvals
Ejemplo n.º 16
0
 def _set_diag_operators(self, diag_update, is_diag_update_positive):
   """Set attributes self._diag_update and self._diag_operator."""
   if diag_update is not None:
     self._diag_operator = linear_operator_diag.LinearOperatorDiag(
         self._diag_update, is_positive_definite=is_diag_update_positive)
   else:
     if tensor_shape.dimension_value(tensor_shape.TensorShape(self.u.shape)[-1]) is not None:
       r = tensor_shape.dimension_value(tensor_shape.TensorShape(self.u.shape)[-1])
     else:
       r = array_ops.shape(self.u)[-1]
     self._diag_operator = linear_operator_identity.LinearOperatorIdentity(
         num_rows=r, dtype=self.dtype)
  def _to_dense(self):
    num_cols = 0
    dense_rows = []
    flat_broadcast_operators = linear_operator_util.broadcast_matrix_batch_dims(
        [op.to_dense() for row in self.operators for op in row])  # pylint: disable=g-complex-comprehension
    broadcast_operators = [
        flat_broadcast_operators[i * (i + 1) // 2:(i + 1) * (i + 2) // 2]
        for i in range(len(self.operators))]
    for row_blocks in broadcast_operators:
      batch_row_shape = array_ops.shape(row_blocks[0])[:-1]
      num_cols += array_ops.shape(row_blocks[-1])[-1]
      zeros_to_pad_after_shape = array_ops.concat(
          [batch_row_shape,
           [self.domain_dimension_tensor() - num_cols]], axis=-1)
      zeros_to_pad_after = array_ops.zeros(
          shape=zeros_to_pad_after_shape, dtype=self.dtype)

      row_blocks.append(zeros_to_pad_after)
      dense_rows.append(array_ops.concat(row_blocks, axis=-1))

    mat = array_ops.concat(dense_rows, axis=-2)
    tensorshape_util.set_shape(mat, tensor_shape.TensorShape(self.shape))
    return mat
Ejemplo n.º 18
0
    def _broadcast_batch_dims(self, x, spectrum):
        """Broadcast batch dims of batch matrix `x` and spectrum."""
        spectrum = ops.convert_to_tensor(spectrum, name="spectrum")
        # tensor_shape.TensorShape(spectrum.shape) = batch_shape + block_shape
        # First make spectrum a batch matrix with
        #   tensor_shape.TensorShape(spectrum.shape) = batch_shape + [prod(block_shape), 1]
        batch_shape = self._batch_shape_tensor(shape=self._shape_tensor(
            spectrum=spectrum))
        spec_mat = array_ops.reshape(
            spectrum, array_ops.concat((batch_shape, [-1, 1]), axis=0))
        # Second, broadcast, possibly requiring an addition of array of zeros.
        x, spec_mat = linear_operator_util.broadcast_matrix_batch_dims(
            (x, spec_mat))
        # Third, put the block shape back into spectrum.
        x_batch_shape = array_ops.shape(x)[:-2]
        spectrum_shape = array_ops.shape(spectrum)
        spectrum = array_ops.reshape(
            spec_mat,
            array_ops.concat(
                (x_batch_shape,
                 self._block_shape_tensor(spectrum_shape=spectrum_shape)),
                axis=0))

        return x, spectrum
 def _diag_part(self):
     diag_part = self.operators[0].diag_part()
     for operator in self.operators[1:]:
         diag_part = diag_part[..., :, array_ops.newaxis]
         op_diag_part = operator.diag_part()[..., array_ops.newaxis, :]
         diag_part *= op_diag_part
         diag_part = array_ops.reshape(
             diag_part,
             shape=array_ops.concat([array_ops.shape(diag_part)[:-2], [-1]],
                                    axis=0))
     if self.range_dimension > self.domain_dimension:
         diag_dimension = self.domain_dimension
     else:
         diag_dimension = self.range_dimension
     diag_part.set_shape(self.batch_shape.concatenate(diag_dimension))
     return diag_part
Ejemplo n.º 20
0
  def _shape_tensor(self):
    # Avoid messy broadcasting if possible.
    if tensor_shape.TensorShape(self.shape).is_fully_defined():
      return ops.convert_to_tensor(
          tensor_shape.TensorShape(self.shape).as_list(), dtype=dtypes.int32, name="shape")

    domain_dimension = sum(self._block_domain_dimension_tensors())
    range_dimension = sum(self._block_range_dimension_tensors())
    matrix_shape = array_ops.stack([domain_dimension, range_dimension])

    # Dummy Tensor of zeros.  Will never be materialized.
    zeros = array_ops.zeros(shape=self.operators[0].batch_shape_tensor())
    for operator in self.operators[1:]:
      zeros = zeros + array_ops.zeros(shape=operator.batch_shape_tensor())
    batch_shape = array_ops.shape(zeros)

    return array_ops.concat((batch_shape, matrix_shape), 0)
 def _eigvals(self):
   # This will be the kronecker product of all the eigenvalues.
   # Note: It doesn't matter which kronecker product it is, since every
   # kronecker product of the same matrices are similar.
   eigvals = [operator.eigvals() for operator in self.operators]
   # Now compute the kronecker product
   product = eigvals[0]
   for eigval in eigvals[1:]:
     # Product has shape [B, R1, 1].
     product = product[..., _ops.newaxis]
     # Eigval has shape [B, 1, R2]. Produces shape [B, R1, R2].
     product *= eigval[..., _ops.newaxis, :]
     # Reshape to [B, R1 * R2]
     product = array_ops.reshape(
         product,
         shape=array_ops.concat([array_ops.shape(product)[:-2], [-1]], axis=0))
   tensorshape_util.set_shape(product, tensor_shape.TensorShape(self.shape)[:-1])
   return product
  def _shape_tensor(self):
    # Avoid messy broadcasting if possible.
    if tensor_shape.TensorShape(self.shape).is_fully_defined():
      return ops.convert_to_tensor(
          tensor_shape.TensorShape(self.shape).as_list(), dtype=dtypes.int32, name="shape")

    # Don't check the matrix dimensions.  That would add unnecessary Asserts to
    # the graph.  Things will fail at runtime naturally if shapes are
    # incompatible.
    matrix_shape = array_ops.stack([
        self.operators[0].range_dimension_tensor(),
        self.operators[-1].domain_dimension_tensor()
    ])

    # Dummy Tensor of zeros.  Will never be materialized.
    zeros = array_ops.zeros(shape=self.operators[0].batch_shape_tensor())
    for operator in self.operators[1:]:
      zeros += array_ops.zeros(shape=operator.batch_shape_tensor())
    batch_shape = array_ops.shape(zeros)

    return array_ops.concat((batch_shape, matrix_shape), 0)
Ejemplo n.º 23
0
def broadcast_matrix_batch_dims(batch_matrices, name=None):
  """Broadcast leading dimensions of zero or more [batch] matrices.

  Example broadcasting one batch dim of two simple matrices.

  ```python
  x = [[1, 2],
       [3, 4]]  # Shape [2, 2], no batch dims

  y = [[[1]]]   # Shape [1, 1, 1], 1 batch dim of shape [1]

  x_bc, y_bc = broadcast_matrix_batch_dims([x, y])

  x_bc
  ==> [[[1, 2],
        [3, 4]]]  # Shape [1, 2, 2], 1 batch dim of shape [1].

  y_bc
  ==> same as y
  ```

  Example broadcasting many batch dims

  ```python
  x = tf.random.normal(shape=(2, 3, 1, 4, 4))
  y = tf.random.normal(shape=(1, 3, 2, 5, 5))
  x_bc, y_bc = broadcast_matrix_batch_dims([x, y])

  tensor_shape.TensorShape(x_bc.shape)
  ==> (2, 3, 2, 4, 4)

  tensor_shape.TensorShape(y_bc.shape)
  ==> (2, 3, 2, 5, 5)
  ```

  Args:
    batch_matrices:  Iterable of `Tensor`s, each having two or more dimensions.
    name:  A string name to prepend to created ops.

  Returns:
    bcast_matrices: List of `Tensor`s, with `bcast_matrices[i]` containing
      the values from `batch_matrices[i]`, with possibly broadcast batch dims.

  Raises:
    ValueError:  If any input `Tensor` is statically determined to have less
      than two dimensions.
  """
  with ops.name_scope(
      name or "broadcast_matrix_batch_dims", values=batch_matrices):
    check_ops.assert_proper_iterable(batch_matrices)
    batch_matrices = list(batch_matrices)

    for i, mat in enumerate(batch_matrices):
      batch_matrices[i] = ops.convert_to_tensor(mat)
      assert_is_batch_matrix(batch_matrices[i])

    if len(batch_matrices) < 2:
      return batch_matrices

    # Try static broadcasting.
    # bcast_batch_shape is the broadcast batch shape of ALL matrices.
    # E.g. if batch_matrices = [x, y], with
    # tensor_shape.TensorShape(x.shape) =    [2, j, k]  (batch shape =    [2])
    # tensor_shape.TensorShape(y.shape) = [3, 1, l, m]  (batch shape = [3, 1])
    # ==> bcast_batch_shape = [3, 2]
    bcast_batch_shape = tensor_shape.TensorShape(batch_matrices[0].shape)[:-2]
    for mat in batch_matrices[1:]:
      bcast_batch_shape = _ops.broadcast_static_shape(
          bcast_batch_shape,
          tensor_shape.TensorShape(mat.shape)[:-2])
    if bcast_batch_shape.is_fully_defined():
      for i, mat in enumerate(batch_matrices):
        if tensor_shape.TensorShape(mat.shape)[:-2] != bcast_batch_shape:
          bcast_shape = array_ops.concat(
              [bcast_batch_shape.as_list(), array_ops.shape(mat)[-2:]], axis=0)
          batch_matrices[i] = _ops.broadcast_to(mat, bcast_shape)
      return batch_matrices

    # Since static didn't work, do dynamic, which always copies data.
    bcast_batch_shape = array_ops.shape(batch_matrices[0])[:-2]
    for mat in batch_matrices[1:]:
      bcast_batch_shape = array_ops.broadcast_dynamic_shape(
          bcast_batch_shape,
          array_ops.shape(mat)[:-2])
    for i, mat in enumerate(batch_matrices):
      batch_matrices[i] = _ops.broadcast_to(
          mat,
          array_ops.concat(
              [bcast_batch_shape, array_ops.shape(mat)[-2:]], axis=0))

    return batch_matrices
 def _shape_tensor(self):
     return array_ops.shape(self._matrix)
Ejemplo n.º 25
0
 def _shape_tensor(self):
     v_shape = array_ops.broadcast_dynamic_shape(array_ops.shape(self.row),
                                                 array_ops.shape(self.col))
     k = v_shape[-1]
     return array_ops.concat((v_shape, [k]), 0)
def _vec(x):
    """Stacks column of matrix to form a single column."""
    return array_ops.reshape(
        _linalg.matrix_transpose(x),
        array_ops.concat([array_ops.shape(x)[:-2], [-1]], axis=0))
 def _shape_tensor(self):
   d_shape = array_ops.shape(self._reflection_axis)
   k = d_shape[-1]
   return array_ops.concat((d_shape, [k]), 0)
Ejemplo n.º 28
0
def _reshape_for_efficiency(a,
                            b,
                            transpose_a=False,
                            transpose_b=False,
                            adjoint_a=False,
                            adjoint_b=False):
  """Maybe reshape a, b, and return an inverse map.  For matmul/solve."""
  def identity(x):
    return x

  # At this point, we have not taken transpose/adjoint of a/b.
  still_need_to_transpose = True

  if tensor_shape.TensorShape(a.shape).ndims is None or tensor_shape.TensorShape(b.shape).ndims is None:
    return a, b, identity, still_need_to_transpose

  # This could be handled in the future, but seems less common.
  if tensor_shape.TensorShape(a.shape).ndims >= tensor_shape.TensorShape(b.shape).ndims:
    return a, b, identity, still_need_to_transpose

  # From now on, we might modify b, but will not modify a.

  # Suppose:
  #   tensor_shape.TensorShape(a.shape) =     C + [m, n], tensor_shape.TensorShape(b.shape) =
  #   tensor_shape.TensorShape(b.shape) = S + C + [n, r]
  b_extra_ndims = tensor_shape.TensorShape(b.shape).ndims - tensor_shape.TensorShape(a.shape).ndims

  # b_extra_sh = S, b_main_sh = C + [n, r]
  b_extra_sh = array_ops.shape(b)[:b_extra_ndims]
  b_main_sh = array_ops.shape(b)[b_extra_ndims:]

  # No reason to flip unless the extra dims of b are big enough.  Why?
  # Assume adjoint/transpose = False.  Then...
  # By not flipping, we have to replicate a to shape
  #   b_extra_sh + tensor_shape.TensorShape(a.shape),
  # which could use extra memory.  But in all cases, the final output has shape
  #   b_extra_sh + tensor_shape.TensorShape(a.shape)[:-1] + tensor_shape.TensorShape([b.shape)[-1]]
  # So we only end up creating a larger object if the end dim of b is smaller
  # than the end dim of a.  This often happens, e.g. if b was a vector that was
  # expanded to a matrix (by appending a singleton).

  # Since adjoint/transpose may not be False, we must make adjustments here.
  # The dim of b that holds the multiple equations.
  a_domain_sz_ = tensor_shape.TensorShape(a.shape)[-2 if adjoint_a or transpose_a else -1]
  b_eq_sz_ = tensor_shape.TensorShape(b.shape)[-2 if adjoint_b or transpose_b else -1]
  b_extra_sz_ = (
      np.prod(tensor_shape.TensorShape(b.shape)[:b_extra_ndims].as_list())
      if tensor_shape.TensorShape(b.shape)[:b_extra_ndims].is_fully_defined() else None)
  if (a_domain_sz_ is not None and b_eq_sz_ is not None and
      b_extra_sz_ is not None):
    if b_extra_sz_ < 2 or a_domain_sz_ <= b_eq_sz_:
      return a, b, identity, still_need_to_transpose

  # At this point, we're flipping for sure!
  # Any transposes/adjoints will happen here explicitly, rather than in calling
  # code.  Why?  To avoid having to write separate complex code for each case.
  if adjoint_a:
    a = _linalg.matrix_transpose(a, conjugate=True)
  elif transpose_a:
    a = _linalg.matrix_transpose(a, conjugate=False)
  if adjoint_b:
    b = _linalg.matrix_transpose(b, conjugate=True)
  elif transpose_a:
    b = _linalg.matrix_transpose(b, conjugate=False)
  still_need_to_transpose = False

  # Recompute shapes, since the transpose/adjoint may have changed them.
  b_extra_sh = array_ops.shape(b)[:b_extra_ndims]
  b_main_sh = array_ops.shape(b)[b_extra_ndims:]

  # Permutation to put the extra dims at the end.
  perm = (
      np.concatenate(
          (np.arange(b_extra_ndims, tensor_shape.TensorShape(b.shape).ndims),
           np.arange(0, b_extra_ndims)), 0))
  b_extra_on_end = array_ops.transpose(b, perm=perm)

  # Now squash this end into one long dim.
  b_squashed_end = array_ops.reshape(
      b_extra_on_end, array_ops.concat((b_main_sh[:-1], [-1]), 0))

  def reshape_inv(y):
    # Expand the extra dims hanging off the end, "b_extra_sh".
    # Note we use y_sh[:-1] + [b_main_sh[-1]] rather than b_main_sh, because y
    # Could have different batch dims than a and b, because of broadcasting.
    y_extra_shape = array_ops.concat(
        (array_ops.shape(y)[:-1], [b_main_sh[-1]], b_extra_sh), 0)
    y_extra_on_end = array_ops.reshape(y, y_extra_shape)
    inverse_perm = np.argsort(perm)
    return array_ops.transpose(y_extra_on_end, perm=inverse_perm)

  return a, b_squashed_end, reshape_inv, still_need_to_transpose
Ejemplo n.º 29
0
 def _shape_tensor(self):
     d_shape = array_ops.shape(self._diag)
     k = d_shape[-1]
     return array_ops.concat((d_shape, [k]), 0)
    def _shape_tensor(self):
        matrix_shape = array_ops.stack((self._num_rows, self._num_rows),
                                       axis=0)

        batch_shape = array_ops.shape(self.multiplier)
        return array_ops.concat((batch_shape, matrix_shape), 0)