
    AVh                         d Z ddlZddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlm	Z	 dd	l
mZ dd
lmZ ddlmZ  ed      ej"                  	 	 	 	 	 dd              Zy)z"Preconditioned Conjugate Gradient.    N)constant_op)dtypes)ops)	array_ops)math_ops)
while_loop)linalg_impl)dispatch)	tf_exportz&linalg.experimental.conjugate_gradientc                 l     j                   r j                  st        d      t        j                  dg d      fd}d  fd}t        j                  |      5  t        j                  t        j                  |      dd  j                               }	$t        j                  |	j                               }	t        j                  |	t        j                  |      d   ggd	      }
t        j                  ||
      }t        j                  |d	      z  |,t        j                  |
|j                   j"                  
      }n|t%        j&                   |      z
  }|}nt%        j&                  |      } ||      }t)        j*                  dt,        j.                  
      } |||||      }t1        j0                  ||||g      \  }} |j2                  |j4                  |j6                  |j8                  |j:                        cddd       S # 1 sw Y   yxY w)a@  Conjugate gradient solver.

  Solves a linear system of equations `A*x = rhs` for self-adjoint, positive
  definite matrix `A` and right-hand side vector `rhs`, using an iterative,
  matrix-free algorithm where the action of the matrix A is represented by
  `operator`. The iteration terminates when either the number of iterations
  exceeds `max_iter` or when the residual norm has been reduced to `tol`
  times its initial value, i.e. \\(||rhs - A x_k|| <= tol ||rhs||\\).

  Args:
    operator: A `LinearOperator` that is self-adjoint and positive definite.
    rhs: A possibly batched vector of shape `[..., N]` containing the right-hand
      size vector.
    preconditioner: A `LinearOperator` that approximates the inverse of `A`.
      An efficient preconditioner could dramatically improve the rate of
      convergence. If `preconditioner` represents matrix `M`(`M` approximates
      `A^{-1}`), the algorithm uses `preconditioner.apply(x)` to estimate
      `A^{-1}x`. For this to be useful, the cost of applying `M` should be
      much lower than computing `A^{-1}` directly.
    x: A possibly batched vector of shape `[..., N]` containing the initial
      guess for the solution.
    tol: A float scalar convergence tolerance.
    max_iter: An integer giving the maximum number of iterations.
    name: A name scope for the operation.

  Returns:
    output: A namedtuple representing the final state with fields:
      - i: A scalar `int32` `Tensor`. Number of iterations executed.
      - x: A rank-1 `Tensor` of shape `[..., N]` containing the computed
          solution.
      - r: A rank-1 `Tensor` of shape `[.., M]` containing the residual vector.
      - p: A rank-1 `Tensor` of shape `[..., N]`. `A`-conjugate basis vector.
      - gamma: \\(r \dot M \dot r\\), equivalent to  \\(||r||_2^2\\) when
        `preconditioner=None`.
  z4Expected a self-adjoint, positive definite operator.CGState)ixrpgammac           	          t        j                  | k  t        j                  t        j                  |j
                  d      kD              S )Naxis)r   logical_and
reduce_anylinalgnormr   )r   statemax_itertols     f/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/ops/linalg/sparse/conjugate_gradient.pystopping_criterionz.conjugate_gradient.<locals>.stopping_criterionO   sA    	HFKKb9C?@B B    c                     t        j                  t        j                  | dt         j                  f   |d      d      S )N.T)	adjoint_ar   r   )r   squeezer   matvecnewaxis)r   ys     r   dotzconjugate_gradient.<locals>.dotT   s<    c9$$$%	%') )r    c                    t        j                  |j                        }|j                   |j                  |      z  }|j                  |dt
        j                  f   |j                  z  z   }|j                  |dt
        j                  f   |z  z
  }|}nj                  |      } ||      }||j                  z  }||dt
        j                  f   |j                  z  z   }	| dz    
| dz   |||	|      fS )N.   )r   r$   r   r   r   r   r%   r   )r   r   zalphar   r   qr   betar   cg_stater'   operatorpreconditioners             r   cg_stepz#conjugate_gradient.<locals>.cg_stepZ   s    %''*AKK#eggq/)E%Y.../%''99A%Y.../!33A
a



"a1IE5;;D	Di'''(57722Aq5(1q5!Q5111r    Nr   r   )dtyper   )r   r   r   r   )is_self_adjointis_positive_definite
ValueErrorcollections
namedtupler   
name_scoper   broadcast_dynamic_shapeshapebatch_shape_tensorconcatbroadcast_tor   r   zerosr2   
base_dtyper   r$   r   constantr   int32r   r   r   r   r   r   )r/   rhsr0   r   r   r   namer   r1   broadcast_shapebroadcast_rhs_shaper0p0gamma0r   r   _r.   r'   s   ` ` ``           @@r   conjugate_gradientrJ      s   X 
"
"x'D'D
K
LL##I/LM(B
)2  ~~d  77Sb!##%'O !!99


+
+
-o $**)//#.r23,5;=?			%8	9B6;;r##Cy
//
SYY%9%9;a 1--bb??>2.bR[FQfll3AqAr8E$$%71e*MHAu
''
''
''kk7     s   (F8H**H3)NNgh㈵>   rJ   )__doc__r6   tensorflow.python.frameworkr   r   r   tensorflow.python.opsr   r   r   tensorflow.python.ops.linalgr	   r   tensorflow.python.utilr
    tensorflow.python.util.tf_exportr   add_dispatch_supportrJ    r    r   <module>rT      sc    )  3 . + + * , > + 6 34	 '+ "0j  5jr    