#include "TSFDefs.h"
#include "Sundance.h"
#include "LAPACKGeneralMatrix.h"
#include "DenseSerialVectorType.h"
#include "TSFTimer.h"
#include "PetraVector.h"
#include "PetraMatrix.h"
#include "IfpackOperator.h"

#include "StokesRightPreconditionerFactory.h"
#include "MaximalCellSet.h"
#include "RCMCellReorderer.h"
#include "TSFCommandLine.h"

using namespace Sundance;

using namespace TSF;


int main(int argc, void** argv)
{
  try
    {
      MPIComm::init(&argc, &argv);
      Timer::start();

      TSFCommandLine::init(&argc, &argv);

      double Re = 1.0;
      if (!TSFCommandLine::findDouble("-r", Re)) Re = 1.0;

      int nx = 3;
      int ny = 3;
      Mesh mesh = rectMesh(0.0, 1.0, nx, 0.0, 1.0, ny);

      MaximalCellSet::setReorderer(new RCMCellReorderer());

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

      /* define cells sets for each of the four sides of the rectangle */
      CellSet boundary = new BoundaryCellSet();
      CellSet left = boundary.subset( x == 0.0 );
      CellSet right = boundary.subset( x == 1.0 );
      CellSet bottom = boundary.subset( y == 0.0 );
      CellSet top = boundary.subset( y == 1.0 );

      /* 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);

      TSFVectorSpace velSpace 
        = new SundanceVectorSpace(mesh, tuple(lagr2, lagr2), petraType);

      Expr uExact = DiscreteFunction::discretize(velSpace,
                                                 List( x*x - y*y, -x*x - 2.0*x*y ));

      Expr force = List(2.0*y*(x*x + 2.0*x*y) + 2.0*x*(x*x-y*y),
                        2.0/Re + 2.0*x*(x*x + 2.0*x*y) - 2.0*(x+y)*(x*x-y*y));


      // 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 vel0 = DiscreteFunction::discretize(velSpace, 0.1*uExact);
			
      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 momentumEqn  = delU*(vel0*grad)*U + 1/Re*(grad*U)*(grad*delU) 
        + delV*(vel0*grad)*V + 1.0/Re*(grad*V)*(grad*delV) - delVelocity*force
        + P*(dx*delU + dy*delV);

      // incompressibility

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

      Expr eqn = Integral(momentumEqn) + Integral(continuityEqn) ;
			
      /*
       * Boundary conditions: 
       * u=uExact 
       */

      EssentialBC bc(boundary, delVelocity*(velocity - uExact));


      /* 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-13, 2000);
      outerSolver.setVerbosityLevel(1);

      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(outerSolver);
          Expr step = (vel0-soln[0])*(vel0-soln[0]);
          double stepSize = definiteIntegral(mesh, step);
          stepSize = sqrt(fabs(stepSize));
          vel0[0] = soln[0][0];
          vel0[1] = soln[0][1];
          Expr p0 = soln[1];
          ofstream uFile(string("u." + TSF::toString(i) + ".dat").c_str());
          ofstream vFile(string("v." + TSF::toString(i) + ".dat").c_str());
          vel0[0].matlabDump(uFile);
          vel0[1].matlabDump(vFile);
          prob.flushMatrixValues();
          TSFOut::printf("oseen iteration %d %g\n", i, stepSize);
          if (stepSize < picardTol) 
            {
              converged = true;
              break;
            }
          i++;
        }

      Expr velErrorExpr = DiscreteFunction::discretize(velSpace, 
                                                       uExact - vel0);
      double velErrorNorm = velErrorExpr[0].norm();

      cerr << "error in velocity = " << velErrorNorm << endl;

      PetraMatrix::showTimings();
      IfpackOperator::showTimings();
      PetraVector::showTimings();
      TSFVectorTraits<DenseSerialVector>::showTimings();
      TSFVector::showTimings();

      double tolerance = 1.0e-6;

      //			Timer::report();

      /*
        decide if the error is within tolerance
      */
      Testing::passFailCheck(__FILE__, velErrorNorm, tolerance);
      Testing::timeStamp(__FILE__, __DATE__, __TIME__);
    }
  catch(exception& e)
    {
      TSFOut::println(e.what());
      Testing::crash(__FILE__);
      Testing::timeStamp(__FILE__, __DATE__, __TIME__);
    }
  MPIComm::finalize();
}







