#include "Sundance.h"

/** \example vorticityLDC.cpp
 * Solution of the Navier-Stokes equation on the Sandia thunderbird
 */

int main(int argc, void** argv)
{
  try
    {
      Sundance::init(&argc, &argv);

			
      MeshReader reader = new ShewchukMeshReader("halfCyl_911");
      Mesh mesh = reader.getMesh();

      double H = 2.0;
      double xLeft = -3.0;
      double xRight = 3.0;

      /* define coordinate functions for x and y coordinates */
      Expr x = new CoordExpr(0);
      Expr y = new CoordExpr(1);

			

      CellSet boundary = new BoundaryCellSet();
      CellSet leftInlet = boundary.subset( x == xLeft );
      CellSet rightOutlet = boundary.subset( x == xRight );
			
      CellSet inflow = leftInlet;
      CellSet outflow = rightOutlet;

      CellSet walls = boundary - inflow - outflow;

      Expr uLeft = 0.5*y*(H-y);

      /* specify that we will use Petra vector and matrix objects */
      TSFVectorType petraType = new PetraVectorType();

      BasisFamily lagr2 = new Lagrange(2);
      TSFVectorSpace discreteSpace 
        = new SundanceVectorSpace(mesh, new Lagrange(1), petraType);

      Expr p0 = new DiscreteFunction(discreteSpace, 0.0);
      TSFVectorSpace velSpace 
        = new SundanceVectorSpace(mesh, tuple(lagr2, lagr2), petraType);

      // define variations and unknowns for U, V, and P.
      /* use Taylor-Hood discretization */
      Expr delU = new TestFunction(new Lagrange(2), "delU");
      Expr U = new UnknownFunction(new Lagrange(2), "U");
      Expr delV = new TestFunction(new Lagrange(2), "delV");
      Expr V = new UnknownFunction(new Lagrange(2), "V");
      Expr delP = new TestFunction(new Lagrange(1), "delP");
      Expr P = new UnknownFunction(new Lagrange(1), "P");

      /* define block structure [ (u,v,psi), (p) ] */
      TSFArray<Block> unkBlocks = tuple(Block(List(U, V), petraType), 
                                        Block(P, petraType));

      TSFArray<Block> varBlocks = tuple(Block(List(delU, delV), petraType), 
                                        Block(delP, petraType));

      /* initial velocity */
      Expr zero = List(Expr(0.0), Expr(0.0));
      Expr vel0 = DiscreteFunction::discretize(velSpace, zero);
			
      Expr delVelocity = List(delU, delV);
      Expr velocity = List(U, V);

      // create differential operators for x and y directions, and
      // then form gradient operator.
      Expr dx = new Derivative(0);
      Expr dy = new Derivative(1);
      Expr grad = List(dx, dy);
			
      // momentum continuity 

      Expr reynolds = new ParameterExpr(100.0);
			
      Expr momentumEqn  = delU*(vel0[0]*dx + vel0[1]*dy)*U 
        + (grad*U)*(grad*delU)/reynolds 
        + delV*(vel0[0]*dx + vel0[1]*dy)*V + (grad*V)*(grad*delV)/reynolds
        + P*(dx*delU + dy*delV);

      // incompressibility

      Expr continuityEqn = delP*(dx*U + dy*V);

      Expr eqn = Integral(momentumEqn) + Integral(continuityEqn) ;
			
      /*
       * Boundary conditions: 
       * v=0 on all sides
       * u=1 on top 
       * u=0 elsewehere
       */

      EssentialBC bc = EssentialBC(walls, delU*U + delV*V)
        && EssentialBC(leftInlet, delU*(U-uLeft) + delV*V);


      /* Create solver objects. We'll use a Schur complement solver
       * that takes advantage of our ability to solve the diffusion
       * operator easily. We will use preconditioned BIGCSTAB for the
       * inner solve on the diffusion block and unpreconditioned
       * BICGSTAB for the outer solve. We'll ask for tighter tolerance
       * on the inner solve */
      TSFPreconditionerFactory innerPrecond = new ILUKPreconditionerFactory(2);
      TSFLinearSolver innerSolver = new BICGSTABSolver(innerPrecond, 1.0e-12, 2000);
      innerSolver.setVerbosityLevel(1);

      /*
        TSFPreconditionerFactory outerPrecond 
        = new StokesRightPreconditionerFactory(innerSolver);
        TSFLinearSolver outerSolver = new BICGSTABSolver(outerPrecond, 
        1.0e-10, 2000);
        TSFLinearSolver blockSolver = new SchurComplementSolver(innerSolver, outerSolver);
        outerSolver.setVerbosityLevel(2);
      */
      TSFPreconditionerFactory klPrecond 
        = new KayLoghinPreconditionerFactory(mesh, vel0, reynolds);

      TSFLinearSolver blockSolver = new BICGSTABSolver(klPrecond,
                                                       1.0e-10, 2000);
      blockSolver.setVerbosityLevel(4);

      StaticLinearProblem prob(mesh, eqn, bc, varBlocks, unkBlocks);

      int i=0; 
      int maxiters = 100;
      bool converged = false;
      double picardTol = 1.0e-8;

      while (i < maxiters)
        {
          Expr soln = prob.solve(blockSolver);
          Expr step = (vel0-soln[0])*(vel0-soln[0]);
          double stepSize = step.norm(2);
          stepSize = sqrt(fabs(stepSize));
          vel0[0] = soln[0][0];
          vel0[1] = soln[0][1];
          Expr p0 = soln[1];
          prob.flushMatrixValues();
          TSFOut::printf("oseen iteration %d %g\n", i, stepSize);
          if (stepSize < picardTol) 
            {
              converged = true;
              break;
            }
          i++;
        }

      FieldWriter uWriter = new MatlabVectorWriter("tBirdU.dat");
      uWriter.writeField("u", vel0);
			
    }
  catch(exception& e)
    {
      Sundance::handleError(e, __FILE__);
    }
  Sundance::finalize();
			
}







