instead of HMatrix's `linearSolve`, we need a solver that works with Repa arrays.
%% Cell type:markdown id: tags:
## conjugate gradient solver
CG is a simple, efficient iterative solver for linear systems $A x = y$ with positive definite matrix A (i.e. $x^T A x \geq 0$ for all $x$).
%% Cell type:code id: tags:
``` haskell
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ScopedTypeVariables #-}
importControl.Monad.Identity
importData.Array.RepaasRhiding((++))
dataCGStatesh=CGState{cgx::ArrayUshDouble
,cgp::ArrayUshDouble
,cgr::ArrayUshDouble
,cgr2::Double
}
```
%% Cell type:markdown id: tags:
`Arr` is a type alias for convenience, `CGState` is the state of a CG iteration.
`CGState` is the state of a CG iteration.
CG takes a function implementing a linear operator (type `Arr sh U -> Arr sh D`), a right hand side and an initial guess and returns the (lazy, infinte) list of the `CGState`s of all iterations.
CG takes a function implementing a linear operator (type `Array U sh -> Array D sh `), a right hand side and an initial guess and returns the (lazy, infinte) list of the `CGState`s of all iterations.
Computations use Repa's parallel computation in a straight-forward way and needs to be performed in a monad. We use the `Identity` monad which does essentially nothing except for providing the sequencing. All operations are performed strictly using `BangPatterns`.
-`takeUntil` is like `takeWhile`, but also returns the final iterate (why waste it?).
-`process` runs over a list, performs a monadic action on each element and returns the last element. It does not retain the start of the list while iterating, so it gets garbage collected properly.
-`runCG` executes `cg` with initial guess 0, a stopping rule based on residuals relative to the first initial guess, and outputs the residual while iterating.
Operators like `poissonOperator` are a frequent pattern: each element of the resulting array is a linear combination of the surrounding elements of the input array.
Repa has special means for constructing such operations in 2-d: Stencils.