Shortcuts

pypose.optim.solver.CG

class pypose.optim.solver.CG(maxiter=None, tol=1e-05)[source]

The batched linear solver with conjugate gradient method.

\[\mathbf{A}_i \bm{x}_i = \mathbf{b}_i, \]

where \(\mathbf{A}_i \in \mathbb{C}^{M \times N}\) and \(\bm{b}_i \in \mathbb{C}^{M \times 1}\) are the \(i\)-th item of batched linear equations.

This function is a 1:1 replica of scipy.sparse.linalg.cg. The solution is consistent with the scipy version up to numerical precision. Variable names are kept the same as the scipy version for easy reference. We recommend using only non-batched or batch size 1 input for this solver, as the batched version was not appeared in the original scipy version. When handling sparse matrices, the batched computation may introduce additional overhead.

Examples

>>> # dense example
>>> import pypose.optim.solver as ppos
>>> A = torch.tensor([[0.1802967, 0.3151198, 0.4548111, 0.3860016, 0.2870615],
                      [0.3151198, 1.4575327, 1.5533425, 1.0540756, 1.0795838],
                      [0.4548111, 1.5533425, 2.3674474, 1.1222278, 1.2365348],
                      [0.3860016, 1.0540756, 1.1222278, 1.3748058, 1.2223261],
                      [0.2870615, 1.0795838, 1.2365348, 1.2223261, 1.2577004]])
>>> b = torch.tensor([[ 2.64306851],
                      [-0.03593633],
                      [ 0.73612658],
                      [ 0.51501254],
                      [-0.26689271]])
>>> solver = ppos.CG()
>>> x = solver(A, b)
tensor([[246.4098],
        [ 22.6997],
        [-56.9239],
        [-161.7914],
        [137.2683]])
>>> # sparse csr example
>>> import pypose.optim.solver as ppos
>>> crow_indices = torch.tensor([0, 2, 4])
>>> col_indices = torch.tensor([0, 1, 0, 1])
>>> values = torch.tensor([1, 2, 3, 4], dtype=torch.float)
>>> A = torch.sparse_csr_tensor(crow_indices, col_indices, values)
>>> A.to_dense()  # visualize
tensor([[1., 2.],
        [3., 4.]])
>>> b = torch.tensor([[1.], [2.]])
>>> solver = ppos.CG()
>>> x = solver(A, b)
tensor([-4.4052e-05,  5.0003e-01])
forward(A, b, x=None, M=None)[source]
Parameters:
  • A (Tensor) – the input tensor. It is assumed to be a symmetric positive-definite matrix. Layout is allowed to be COO, CSR, BSR, or dense.

  • b (Tensor) – the tensor on the right hand side. Layout could be sparse or dense but is only allowed to be a type that is compatible with the layout of A. In other words, A @ b operation must be supported by the layout of A.

  • x (Tensor, optional) – the initial guess for the solution. Default: None.

  • M (Tensor, optional) – the preconditioner for A. Layout is allowed to be COO, CSR, BSR, or dense. Default: None.

Returns:

the solved tensor. Layout is the same as the layout of b.

Return type:

Tensor

Docs

Access documentation for PyPose

View Docs

Tutorials

Get started with tutorials and examples

View Tutorials

Get Started

Find resources and how to start using pypose

View Resources