I want to ask how to calculate efficiently coarse grid matrix in each MG iteration?Isn't it a computational cost to calulate RAP every time until you reach the coarsest level?And why in the above code A is not passed as a parameter in the MG function since we need coarse grid matrix in each level?Somewhere I saw that for 1D Poisson model the coefficients of coarse grid matrix is the same with one on the finer multiplied by 1/4h^2,is this holds for every case?
I assume that you mean the algebraic multigrid because you are asking about the Galerkin product.
You typically do not perform the Galerkin product for every iteration as the matrices will not change from iteration to iteration. What you typically do is, you first create all matrices needed for the iterations and then perform the iterations. Even for very large matrices with hundreds of millions of unknowns you do not perform the Galerkin product more than 3 or 4 times. Depending on the method and the parameters. Only the first one or two products are costly as the matrices are quite big but the size reduces quite fast.
For multigrid method you have to pay the extra setup costs but you will save time as you do not need as much iterations compared to CG methods.