#include "Sundance.h"

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

      /* create a simple mesh on the rectangle */
      int nx = 8;
      int ny = 8;
      MeshGenerator mesher = new RectangleMesher(-1.0, 1.0, nx, -1.0, 1.0, ny);
      Mesh mesh = mesher.getMesh();

      /* 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 == -1.0 );
      CellSet right = boundary.subset( x == 1.0 );
      CellSet bottom = boundary.subset( y == -1.0 );
      CellSet top = boundary.subset( y == 1.0 );

      /* 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");
			
      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 equation */
      Expr momentumEqn  = -(grad*U)*(grad*delU) - (grad*V)*(grad*delV)
        + P*(dx*delU + dy*delV);

      /* incompressibility equation */
      Expr continuityEqn = -delP*(dx*U + dy*V);

      Expr eqn = Integral(momentumEqn) + Integral(continuityEqn);




      /*
       * Boundary conditions: 
       * v=0 on top, bottom, and left.
       * u=0 on top and bottom.
       * u=1/2 (1-y^2) on left.
       * Natural BCs on right.
       */

      Expr ULeft = 0.5*(1.0-y*y);
			
      EssentialBC bc
        = EssentialBC(top, delU*U + delV*V)
        && EssentialBC(bottom, delU*U + delV*V)
        && EssentialBC(left, delU*(U-ULeft));


      /*
        Create a solver object: stablized biconjugate gradient solver
      */
      TSFPreconditionerFactory prec = new ILUKPreconditionerFactory(2);
      TSFLinearSolver solver = new BICGSTABSolver(prec, 1.0e-14, 3000);
      //			solver.setVerbosityLevel(2);

      StaticLinearProblem prob(mesh, eqn, bc, List(delU, delV, delP),
                               List(U, V, P), new PetraVectorType());

      Expr soln = prob.solve(solver);



      Expr U0 = soln[0];
      Expr V0 = soln[1];
      Expr P0 = soln[2];

      /* write to matlab */
      FieldWriter uWriter = new MatlabWriter("stokesU.dat");
      uWriter.writeField(U0);
      FieldWriter vWriter = new MatlabWriter("stokesV.dat");
      vWriter.writeField(V0);
      FieldWriter pWriter = new MatlabWriter("stokesP.dat");
      pWriter.writeField(P0);

      /*
       * Exact solution is 
       * u = 1/2 (1-y^2)
       * v = 0
       * P = -x
       */
      Expr exactSoln = List( 0.5*(1-y*y), 0.0, 1.0 - x );

      BasisFamily lag1 = new Lagrange(1);
      BasisFamily lag2 = new Lagrange(2);
      TSFVectorSpace discreteSpace
        = new SundanceVectorSpace(mesh, tuple(lag2, lag2, lag1), 
                                  new PetraVectorType());

      Expr errorExpr = DiscreteFunction::discretize(discreteSpace, soln-exactSoln);
			
      /*
        compute the norm of the error
      */
      double uErrorNorm = (U0 - exactSoln[0]).norm(2);
      double vErrorNorm = (V0 - exactSoln[1]).norm(2);
      double pErrorNorm = (P0 - exactSoln[2]).norm(2);
      double errorNorm = uErrorNorm + vErrorNorm + pErrorNorm;

      cerr << "error in u = " << uErrorNorm << endl;
      cerr << "error in v = " << vErrorNorm << endl;
      cerr << "error in p = " << pErrorNorm << endl;
      double tolerance = 1.0e-4;

      /*
        decide if the error is within tolerance
      */
      Testing::passFailCheck(__FILE__, errorNorm, tolerance);
    }
  catch(exception& e)
    {
      Sundance::handleError(e, __FILE__);
    }
  Sundance::finalize();
}







