Boundary conditions in conjugate gradient method for poisson's equation

I want to use the conjugate gradient method to solve poisson's equation in an electrostatic setup: \begin{align} \rho=-\nabla^2\phi \end{align} I am however a little confused when it comes to the boundary conditions. For the dirichlet boundaries $\phi(0)=D$ it is pretty easy because i can implement the condition in the initial guess of the solution. However, when using either neumann $\frac{\partial \phi}{\partial x}=C$ or periodic $\phi(0)=\phi(L)$, no values are known which can be implemented in the initial guess. And so i'm not sure where the b.c should be imposed during the iterative process..?

• First of all, what's your discretization? Are you using finite elements, finite differences, ... ? How you incorporate the BCs into the matrix you're solving with CG depends on the discretization you use. – fpnick Aug 12 '16 at 21:38
• I'm using finite difference. So I suppose it means putting in the right entries in the matrix, which I presume would still make it symmetric positive definite..? – Rasmus Aug 13 '16 at 11:55
• You can think of it as putting extra rows for the BCs in the matrix, which you can then eliminate by adding them onto another equation. If you do that in a clever way, the matrix remains spd and the rhs changes as Wolfgang pointed out. Note that in case of Neumann BCs you will need to discretize the BCs as well as the interior PDE. For periodic BCs just add an extra set of equations of the form x_0 = x_L (in 1D) to the matrix, which will change its properties. – fpnick Aug 13 '16 at 12:56

Periodic boundary conditions ultimately affect the structure of the matrix. You can choose any value for $\phi(0)$ in your initial starting guess for your solution vector. It is probably useful to choose the same value for $\phi(L)$, but the iterative solver should also figure this equality out just based on the matrix.
You can think of it as putting extra rows for the BCs in the matrix, which you can then eliminate by adding them onto another equation. If you do that in a clever way, the matrix remains spd and the rhs changes as Wolfgang pointed out. Note that in case of Neumann BCs you will need to discretize the BCs as well as the interior PDE. For periodic BCs just add an extra set of equations of the form $x_0 = x_L$ (in 1D) to the matrix, which will change its properties.