Example #1
0
int main(int argc, char **args) 
{
  // Time measurement.
  TimePeriod cpu_time;
  cpu_time.tick();

  // Load the mesh. 
  Mesh mesh;

  //CTUReader mloader;
  H3DReader mloader;

  info("Loading mesh...");
  mloader.load("bridge.mesh3d", &mesh);

  // Create H1 space with default shapeset.
  H1Space space(&mesh, bc_types, essential_bc_values, Ord3(P_INIT_X, P_INIT_Y, P_INIT_Z));

  // Initialize weak formulation. 
  WeakForm wf;
  wf.add_matrix_form(bilinear_form<double, scalar>, bilinear_form<Ord, Ord>, HERMES_SYM);
  wf.add_vector_form(linear_form<double, scalar>, linear_form<Ord, Ord>, HERMES_ANY_INT);

  // Initialize discrete problem.
  bool is_linear = true;
  DiscreteProblem dp(&wf, &space, is_linear);

  // Set up the solver, matrix, and rhs according to the solver selection.
  SparseMatrix* matrix = create_matrix(matrix_solver);
  Vector* rhs = create_vector(matrix_solver);
  Solver* solver = create_linear_solver(matrix_solver, matrix, rhs);

  // Assemble stiffness matrix and load vector.
  info("Assembling the linear problem (ndof: %d).", Space::get_num_dofs(&space));
  dp.assemble(matrix, rhs);

  // Solve the linear system. If successful, obtain the solution.
  info("Solving the linear problem.");
  Solution sln(&mesh);
  if(solver->solve()) Solution::vector_to_solution(solver->get_solution(), &space, &sln);
  else error ("Matrix solver failed.\n");

  // Output the solution for Paraview.
  if (solution_output) out_fn_vtk(&sln, "sln");

  // Time measurement.
  cpu_time.tick();

  // Print timing information.
  info("Solutions and mesh with polynomial orders saved. Total running time: %g s", 
       cpu_time.accumulated());

  // Clean up.
  delete matrix;
  delete rhs;
  delete solver;

  return 0;
}
Example #2
0
// Tests themselves.
int test_mesh3d_loader(char *file_name)
{
  _F_
  Mesh mesh;
  H3DReader mloader;
  if (mloader.load(file_name, &mesh)) {
    mesh.dump();
    return ERR_SUCCESS;
  }
  else {
  printf("failed\n");
  return ERR_FAILURE;
  }
}
Example #3
0
int main(int argc, char **args)
{
    // Test variable.
    int success_test = 1;

    if (argc < 2) error("Not enough parameters.");

    ECopyType copy_type = parse_copy_type(args[1]);
    if (copy_type == CT_NONE) error("Unknown copy type (%s).\n", args[1]);

    Mesh mesh;
    H3DReader mloader;
    if (!mloader.load(args[2], &mesh)) error("Loading mesh file '%s'.", args[2]);

    // Apply refinements.
    bool ok = true;
    for (int k = 3; k < argc && ok; k += 2) {
        int elem_id, reft_id;
        sscanf(args[k], "%d", &elem_id);
        reft_id = parse_reft(args[k + 1]);
        ok = mesh.refine_element(elem_id, reft_id);
    }

    if (ok) {
        Mesh dup;
        switch (copy_type) {
        case CT_COPY:
            dup.copy(mesh);
            break;
        case CT_COPY_BASE:
            dup.copy_base(mesh);
            break;
        default:
            break;
        }
        dup.dump();
    }
    else {
        warning("Unable to refine a mesh.");
        success_test = 0;
    }

    if (success_test) {
        return ERR_SUCCESS;
    }
    else {
        return ERR_FAILURE;
    }
}
Example #4
0
int main(int argc, char **args) 
{
  // Test variable.
  int success_test = 1;

	if (argc < 3) error("Not enough parameters.");

  // Load the mesh.
	Mesh mesh;
  H3DReader mloader;
  if (!mloader.load(args[1], &mesh)) error("Loading mesh file '%s'.", args[1]);

  // Initialize the space according to the
  // command-line parameters passed.
	int o = 4;
	sscanf(args[2], "%d", &o);
	H1Space space(&mesh, bc_types, NULL, o);
 
  // Initialize the weak formulation.
	WeakForm wf;
	wf.add_matrix_form(bilinear_form<double, scalar>, bilinear_form<Ord, Ord>, HERMES_SYM);
	wf.add_matrix_form_surf(bilinear_form_surf<double, scalar>, bilinear_form_surf<Ord, Ord>);
	wf.add_vector_form(linear_form<double, scalar>, linear_form<Ord, Ord>);
	wf.add_vector_form_surf(linear_form_surf<double, scalar>, linear_form_surf<Ord, Ord>);

  // Initialize the FE problem.
  bool is_linear = true;
  DiscreteProblem dp(&wf, &space, is_linear);

  // Set up the solver, matrix, and rhs according to the solver selection.
  SparseMatrix* matrix = create_matrix(matrix_solver);
  Vector* rhs = create_vector(matrix_solver);
  Solver* solver = create_linear_solver(matrix_solver, matrix, rhs);

  // Initialize the preconditioner in the case of SOLVER_AZTECOO.
  if (matrix_solver == SOLVER_AZTECOO) 
  {
    ((AztecOOSolver*) solver)->set_solver(iterative_method);
    ((AztecOOSolver*) solver)->set_precond(preconditioner);
    // Using default iteration parameters (see solver/aztecoo.h).
  }
  
  // Assemble the linear problem.
  info("Assembling (ndof: %d).", Space::get_num_dofs(&space));
  dp.assemble(matrix, rhs);
    
  // Solve the linear system. If successful, obtain the solution.
  info("Solving.");
		Solution sln(&mesh);
  if(solver->solve()) Solution::vector_to_solution(solver->get_solution(), &space, &sln);
  else error ("Matrix solver failed.\n");

	ExactSolution ex_sln(&mesh, exact_solution);

  // Calculate exact error.
  info("Calculating exact error.");
  Adapt *adaptivity = new Adapt(&space, HERMES_H1_NORM);
  bool solutions_for_adapt = false;
  double err_exact = adaptivity->calc_err_exact(&sln, &ex_sln, solutions_for_adapt, HERMES_TOTAL_ERROR_ABS);

  if (err_exact > EPS)
		// Calculated solution is not precise enough.
		success_test = 0;

  // Clean up.
  delete matrix;
  delete rhs;
  delete solver;
  delete adaptivity;
  
  if (success_test) {
    info("Success!");
    return ERR_SUCCESS;
	}
	else {
    info("Failure!");
    return ERR_FAILURE;
	}
}
Example #5
0
int main(int argc, char **args) 
{
  // Test variable.
  int success_test = 1;

	if (argc < 2) error("Not enough parameters.");

  // Load the mesh.
	Mesh mesh;
  H3DReader mloader;
  if (!mloader.load(args[1], &mesh)) error("Loading mesh file '%s'.", args[1]);

  // Initialize the space 1.
	Ord3 o1(2, 2, 2);
	H1Space space1(&mesh, bc_types, NULL, o1);

	// Initialize the space 2.
	Ord3 o2(4, 4, 4);
	H1Space space2(&mesh, bc_types, NULL, o2);

	WeakForm wf(2);
	wf.add_matrix_form(0, 0, bilinear_form_1_1<double, scalar>, bilinear_form_1_1<Ord, Ord>, HERMES_SYM);
	wf.add_matrix_form(0, 1, bilinear_form_1_2<double, scalar>, bilinear_form_1_2<Ord, Ord>, HERMES_SYM);
	wf.add_vector_form(0, linear_form_1<double, scalar>, linear_form_1<Ord, Ord>);
	wf.add_matrix_form(1, 1, bilinear_form_2_2<double, scalar>, bilinear_form_2_2<Ord, Ord>, HERMES_SYM);
	wf.add_vector_form(1, linear_form_2<double, scalar>, linear_form_2<Ord, Ord>);

  // Initialize the FE problem.
  bool is_linear = true;
  DiscreteProblem dp(&wf, Tuple<Space *>(&space1, &space2), is_linear);

  // Initialize the solver in the case of SOLVER_PETSC or SOLVER_MUMPS.
  initialize_solution_environment(matrix_solver, argc, args);

  // Set up the solver, matrix, and rhs according to the solver selection.
  SparseMatrix* matrix = create_matrix(matrix_solver);
  Vector* rhs = create_vector(matrix_solver);
  Solver* solver = create_linear_solver(matrix_solver, matrix, rhs);

  // Initialize the preconditioner in the case of SOLVER_AZTECOO.
  if (matrix_solver == SOLVER_AZTECOO) 
  {
    ((AztecOOSolver*) solver)->set_solver(iterative_method);
    ((AztecOOSolver*) solver)->set_precond(preconditioner);
    // Using default iteration parameters (see solver/aztecoo.h).
  }

  // Assemble the linear problem.
  info("Assembling (ndof: %d).", Space::get_num_dofs(Tuple<Space *>(&space1, &space2)));
  dp.assemble(matrix, rhs);

  // Solve the linear system. If successful, obtain the solution.
  info("Solving.");
	Solution sln1(&mesh);
	Solution sln2(&mesh);
  if(solver->solve()) Solution::vector_to_solutions(solver->get_solution(), Tuple<Space *>(&space1, &space2), Tuple<Solution *>(&sln1, &sln2));
  else error ("Matrix solver failed.\n");

  ExactSolution ex_sln1(&mesh, exact_sln_fn_1);
  ExactSolution ex_sln2(&mesh, exact_sln_fn_2);

  // Calculate exact error.
  info("Calculating exact error.");
  Adapt *adaptivity = new Adapt(Tuple<Space *>(&space1, &space2), Tuple<ProjNormType>(HERMES_H1_NORM, HERMES_H1_NORM));
  bool solutions_for_adapt = false;
  double err_exact = adaptivity->calc_err_exact(Tuple<Solution *>(&sln1, &sln2), Tuple<Solution *>(&ex_sln1, &ex_sln2), solutions_for_adapt, HERMES_TOTAL_ERROR_ABS);

  if (err_exact > EPS)
		// Calculated solution is not precise enough.
		success_test = 0;

  // Clean up.
  delete matrix;
  delete rhs;
  delete solver;
  delete adaptivity;

  // Properly terminate the solver in the case of SOLVER_PETSC or SOLVER_MUMPS.
  finalize_solution_environment(matrix_solver);
  
  if (success_test) {
    info("Success!");
    return ERR_SUCCESS;
	}
	else {
    info("Failure!");
    return ERR_FAILURE;
	}
}
Example #6
0
int main(int argc, char **args) 
{
  // Test variable.
  int success_test = 1;

  if (argc < 2) error("Not enough parameters.");

  // Load the mesh.
	Mesh mesh;
  H3DReader mloader;
  if (!mloader.load(args[1], &mesh)) error("Loading mesh file '%s'.", args[1]);

	// Initialize the space.
	int mx = 2;
	Ord3 order(mx, mx, mx);
	H1Space space(&mesh, bc_types, NULL, order);
#if defined LIN_DIRICHLET || defined NLN_DIRICHLET
	space.set_essential_bc_values(essential_bc_values);
#endif
	// Initialize the weak formulation.
	WeakForm wf;
	wf.add_vector_form(form_0<double, scalar>, form_0<Ord, Ord>);
#if defined LIN_NEUMANN || defined LIN_NEWTON
	wf.add_vector_form_surf(form_0_surf<double, scalar>, form_0_surf<Ord, Ord>);
#endif
#if defined LIN_DIRICHLET || defined NLN_DIRICHLET
	// preconditioner
	wf.add_matrix_form(precond_0_0<double, scalar>, precond_0_0<Ord, Ord>, HERMES_SYM);
#endif

	// Initialize the FE problem.
	DiscreteProblem fep(&wf, &space);

#if defined LIN_DIRICHLET || defined NLN_DIRICHLET
	// use ML preconditioner to speed-up things
	MlPrecond pc("sa");
	pc.set_param("max levels", 6);
	pc.set_param("increasing or decreasing", "decreasing");
	pc.set_param("aggregation: type", "MIS");
	pc.set_param("coarse: type", "Amesos-KLU");
#endif

	NoxSolver solver(&fep);
#if defined LIN_DIRICHLET || defined NLN_DIRICHLET
//	solver.set_precond(&pc);
#endif

	info("Solving.");
	Solution sln(&mesh);
	if(solver.solve()) Solution::vector_to_solution(solver.get_solution(), &space, &sln);
  else error ("Matrix solver failed.\n");
	

		Solution ex_sln(&mesh);
		ex_sln.set_exact(exact_solution);

		// Calculate exact error.
  info("Calculating exact error.");
  Adapt *adaptivity = new Adapt(&space, HERMES_H1_NORM);
  bool solutions_for_adapt = false;
  double err_exact = adaptivity->calc_err_exact(&sln, &ex_sln, solutions_for_adapt, HERMES_TOTAL_ERROR_ABS);

  if (err_exact > EPS)
		// Calculated solution is not precise enough.
		success_test = 0;

  if (success_test) {
    info("Success!");
    return ERR_SUCCESS;
  }
  else {
    info("Failure!");
    return ERR_FAILURE;
  }
}
Example #7
0
int main(int argc, char **args)
{
  // Test variable.
  int success_test = 1;

  if (argc < 2) error("Not enough parameters.");

  // Load the mesh.
	Mesh mesh;
  H3DReader mloader;
  if (!mloader.load(args[1], &mesh)) error("Loading mesh file '%s'.", args[1]);

	// Initialize the space.
#if defined NONLIN1
	Ord3 order(1, 1, 1);
#else
	Ord3 order(2, 2, 2);
#endif
	H1Space space(&mesh, bc_types, essential_bc_values, order);

#if defined NONLIN2
	// Do L2 projection of zero function.
	WeakForm proj_wf;
	proj_wf.add_matrix_form(biproj_form<double, scalar>, biproj_form<Ord, Ord>, HERMES_SYM);
	proj_wf.add_vector_form(liproj_form<double, scalar>, liproj_form<Ord, Ord>);

	bool is_linear = true;
	DiscreteProblem lp(&proj_wf, &space, is_linear);

  // Set up the solver, matrix, and rhs according to the solver selection.
  SparseMatrix* matrix = create_matrix(matrix_solver);
  Vector* rhs = create_vector(matrix_solver);
  Solver* solver_proj = create_linear_solver(matrix_solver, matrix, rhs);
  
  // Initialize the preconditioner in the case of SOLVER_AZTECOO.
  if (matrix_solver == SOLVER_AZTECOO) 
  {
    ((AztecOOSolver*) solver_proj)->set_solver(iterative_method);
    ((AztecOOSolver*) solver_proj)->set_precond(preconditioner);
    // Using default iteration parameters (see solver/aztecoo.h).
  }
  
  // Assemble the linear problem.
  info("Assembling (ndof: %d).", Space::get_num_dofs(&space));
  lp.assemble(matrix, rhs);
    
  // Solve the linear system.
  info("Solving.");
  if(!solver_proj->solve()) error ("Matrix solver failed.\n");

  delete matrix;
  delete rhs;
#endif

	// Initialize the weak formulation.
	WeakForm wf(1);
	wf.add_matrix_form(0, 0, jacobi_form<double, scalar>, jacobi_form<Ord, Ord>, HERMES_NONSYM);
	wf.add_vector_form(0, resid_form<double, scalar>, resid_form<Ord, Ord>);

	// Initialize the FE problem.
#if defined NONLIN2
  is_linear = false;
#else
  bool is_linear = false;
#endif
	DiscreteProblem dp(&wf, &space, is_linear);

	NoxSolver solver(&dp);

#if defined NONLIN2
solver.set_init_sln(solver_proj->get_solution());
delete solver_proj;
#endif

solver.set_conv_iters(10);
	info("Solving.");
	Solution sln(&mesh);
	if(solver.solve()) Solution::vector_to_solution(solver.get_solution(), &space, &sln);
  else error ("Matrix solver failed.\n");

		Solution ex_sln(&mesh);
#ifdef NONLIN1
		ex_sln.set_const(100.0);
#else
		ex_sln.set_exact(exact_solution);
#endif
		// Calculate exact error.
  info("Calculating exact error.");
  Adapt *adaptivity = new Adapt(&space, HERMES_H1_NORM);
  bool solutions_for_adapt = false;
  double err_exact = adaptivity->calc_err_exact(&sln, &ex_sln, solutions_for_adapt, HERMES_TOTAL_ERROR_ABS);

  if (err_exact > EPS)
		// Calculated solution is not precise enough.
		success_test = 0;

  if (success_test) {
    info("Success!");
    return ERR_SUCCESS;
  }
  else {
    info("Failure!");
    return ERR_FAILURE;
  }
}
Example #8
0
int main(int argc, char **args)
{
    // Load the mesh.
    Mesh mesh;
    H3DReader mloader;
    mloader.load("fichera-corner.mesh3d", &mesh);

    // Perform initial mesh refinement.
    for (int i=0; i < INIT_REF_NUM; i++) mesh.refine_all_elements(H3D_H3D_H3D_REFT_HEX_XYZ);

    // Create an H1 space with default shapeset.
    H1Space space(&mesh, bc_types, essential_bc_values, Ord3(P_INIT_X, P_INIT_Y, P_INIT_Z));

    // Initialize weak formulation.
    WeakForm wf;
    wf.add_matrix_form(bilinear_form<double, double>, bilinear_form<Ord, Ord>, HERMES_SYM, HERMES_ANY);
    wf.add_vector_form(linear_form<double, double>, linear_form<Ord, Ord>, HERMES_ANY);

    // Set exact solution.
    ExactSolution exact(&mesh, fndd);

    // DOF and CPU convergence graphs.
    SimpleGraph graph_dof_est, graph_cpu_est, graph_dof_exact, graph_cpu_exact;

    // Time measurement.
    TimePeriod cpu_time;
    cpu_time.tick();

    // Adaptivity loop.
    int as = 1;
    bool done = false;
    do
    {
        info("---- Adaptivity step %d:", as);

        // Construct globally refined reference mesh and setup reference space.
        Space* ref_space = construct_refined_space(&space,1 , H3D_H3D_H3D_REFT_HEX_XYZ);

        // Initialize discrete problem.
        bool is_linear = true;
        DiscreteProblem dp(&wf, ref_space, is_linear);

        // Set up the solver, matrix, and rhs according to the solver selection.
        SparseMatrix* matrix = create_matrix(matrix_solver);
        Vector* rhs = create_vector(matrix_solver);
        Solver* solver = create_linear_solver(matrix_solver, matrix, rhs);

        // Initialize the preconditioner in the case of SOLVER_AZTECOO.
        if (matrix_solver == SOLVER_AZTECOO)
        {
            ((AztecOOSolver*) solver)->set_solver(iterative_method);
            ((AztecOOSolver*) solver)->set_precond(preconditioner);
            // Using default iteration parameters (see solver/aztecoo.h).
        }

        // Assemble the reference problem.
        info("Assembling on reference mesh (ndof: %d).", Space::get_num_dofs(ref_space));
        dp.assemble(matrix, rhs);

        // Time measurement.
        cpu_time.tick();

        // Solve the linear system on reference mesh. If successful, obtain the solution.
        info("Solving on reference mesh.");
        Solution ref_sln(ref_space->get_mesh());
        if(solver->solve()) Solution::vector_to_solution(solver->get_solution(), ref_space, &ref_sln);
        else error ("Matrix solver failed.\n");

        // Time measurement.
        cpu_time.tick();

        // Project the reference solution on the coarse mesh.
        Solution sln(space.get_mesh());
        info("Projecting reference solution on coarse mesh.");
        OGProjection::project_global(&space, &ref_sln, &sln, matrix_solver);

        // Time measurement.
        cpu_time.tick();

        // Output solution and mesh with polynomial orders.
        if (solution_output)
        {
            out_fn_vtk(&sln, "sln", as);
            out_orders_vtk(&space, "order", as);
        }

        // Skip the visualization time.
        cpu_time.tick(HERMES_SKIP);

        // Calculate element errors and total error estimate.
        info("Calculating error estimate and exact error.");
        Adapt *adaptivity = new Adapt(&space, HERMES_H1_NORM);
        bool solutions_for_adapt = true;
        double err_est_rel = adaptivity->calc_err_est(&sln, &ref_sln, solutions_for_adapt) * 100;

        // Calculate exact error.
        solutions_for_adapt = false;
        double err_exact_rel = adaptivity->calc_err_exact(&sln, &exact, solutions_for_adapt) * 100;

        // Report results.
        info("ndof_coarse: %d, ndof_fine: %d.", Space::get_num_dofs(&space), Space::get_num_dofs(ref_space));
        info("err_est_rel: %g%%, err_exact_rel: %g%%.", err_est_rel, err_exact_rel);

        // Add entry to DOF and CPU convergence graphs.
        graph_dof_est.add_values(Space::get_num_dofs(&space), err_est_rel);
        graph_dof_est.save("conv_dof_est.dat");
        graph_cpu_est.add_values(cpu_time.accumulated(), err_est_rel);
        graph_cpu_est.save("conv_cpu_est.dat");
        graph_dof_exact.add_values(Space::get_num_dofs(&space), err_exact_rel);
        graph_dof_exact.save("conv_dof_exact.dat");
        graph_cpu_exact.add_values(cpu_time.accumulated(), err_exact_rel);
        graph_cpu_exact.save("conv_cpu_exact.dat");

        // If err_est_rel is too large, adapt the mesh.
        if (err_est_rel < ERR_STOP) done = true;
        else
        {
            info("Adapting coarse mesh.");
            adaptivity->adapt(THRESHOLD);
        }
        if (Space::get_num_dofs(&space) >= NDOF_STOP) done = true;

        // Clean up.
        delete ref_space->get_mesh();
        delete ref_space;
        delete matrix;
        delete rhs;
        delete solver;
        delete adaptivity;

        // Increase the counter of performed adaptivity steps.
        as++;
    } while (!done);

    return 0;
}
Example #9
0
int main(int argc, char **args)
{
  // Test variable.
  int success_test = 1;

  // Check the number of command-line parameters.
  if (argc < 2) {
    info("Use x, y, z, xy, xz, yz, or xyz as a command-line parameter.");
    error("Not enough command-line parameters.");
  }

  // Determine anisotropy type from the command-line parameter.
  ANISO_TYPE = parse_aniso_type(args[1]);

  // Load the mesh.
  Mesh mesh;
  H3DReader mloader;
  mloader.load("hex-0-1.mesh3d", &mesh);

  // Assign the lowest possible directional polynomial degrees so that the problem's NDOF >= 1.
  assign_poly_degrees();

  // Create an H1 space with default shapeset.
  info("Setting directional polynomial degrees %d, %d, %d.", P_INIT_X, P_INIT_Y, P_INIT_Z);
  H1Space space(&mesh, bc_types, essential_bc_values, Ord3(P_INIT_X, P_INIT_Y, P_INIT_Z));

  // Initialize weak formulation.
  WeakForm wf;
  wf.add_matrix_form(bilinear_form<double, scalar>, bilinear_form<Ord, Ord>, HERMES_SYM, HERMES_ANY);
  wf.add_vector_form(linear_form<double, scalar>, linear_form<Ord, Ord>, HERMES_ANY);

  // Set exact solution.
  ExactSolution exact(&mesh, fndd);

  // Time measurement.
  TimePeriod cpu_time;
  cpu_time.tick();

  // Initialize the solver in the case of SOLVER_PETSC or SOLVER_MUMPS.
  initialize_solution_environment(matrix_solver, argc, args);

  // Adaptivity loop. 
  int as = 1; 
  bool done = false;
  do 
  {
    info("---- Adaptivity step %d:", as);

    // Construct globally refined reference mesh and setup reference space.
    Space* ref_space = construct_refined_space(&space,1 , H3D_H3D_H3D_REFT_HEX_XYZ);

    // Initialize the FE problem.
    bool is_linear = true;
    DiscreteProblem dp(&wf, ref_space, is_linear);

    // Set up the solver, matrix, and rhs according to the solver selection.
    SparseMatrix* matrix = create_matrix(matrix_solver);
    Vector* rhs = create_vector(matrix_solver);
    Solver* solver = create_linear_solver(matrix_solver, matrix, rhs);
    
    // Initialize the preconditioner in the case of SOLVER_AZTECOO.
    if (matrix_solver == SOLVER_AZTECOO) 
    {
      ((AztecOOSolver*) solver)->set_solver(iterative_method);
      ((AztecOOSolver*) solver)->set_precond(preconditioner);
      // Using default iteration parameters (see solver/aztecoo.h).
    }
  
    // Assemble the reference problem.
    info("Assembling on reference mesh (ndof: %d).", Space::get_num_dofs(ref_space));
    dp.assemble(matrix, rhs);

    // Time measurement.
    cpu_time.tick();

    // Solve the linear system on reference mesh. If successful, obtain the solution.
    info("Solving on reference mesh.");
    Solution ref_sln(ref_space->get_mesh());
    if(solver->solve()) Solution::vector_to_solution(solver->get_solution(), ref_space, &ref_sln);
    else {
		  printf("Matrix solver failed.\n");
		  success_test = 0;
	  }

    // Time measurement.
    cpu_time.tick();

    // Project the reference solution on the coarse mesh.
    Solution sln(space.get_mesh());
    info("Projecting reference solution on coarse mesh.");
    OGProjection::project_global(&space, &ref_sln, &sln, matrix_solver);

    // Time measurement.
    cpu_time.tick();

    // Output solution and mesh with polynomial orders.
    if (solution_output) 
    {
      out_fn_vtk(&sln, "sln", as);
      out_orders_vtk(&space, "order", as);
    }

    // Skip the visualization time.
    cpu_time.tick(HERMES_SKIP);

    // Calculate element errors and total error estimate.
    info("Calculating error estimate and exact error.");
    Adapt *adaptivity = new Adapt(&space, HERMES_H1_NORM);
    bool solutions_for_adapt = true;
    double err_est_rel = adaptivity->calc_err_est(&sln, &ref_sln, solutions_for_adapt) * 100;

    // Calculate exact error.
    solutions_for_adapt = false;
    double err_exact_rel = adaptivity->calc_err_exact(&sln, &exact, solutions_for_adapt) * 100;

    // Report results.
    info("ndof_coarse: %d, ndof_fine: %d.", Space::get_num_dofs(&space), Space::get_num_dofs(ref_space));
    info("err_est_rel: %g%%, err_exact_rel: %g%%.", err_est_rel, err_exact_rel);

    // If err_est_rel is too large, adapt the mesh. 
    if (err_est_rel < ERR_STOP) done = true;
    else 
    {
      info("Adapting coarse mesh.");
      adaptivity->adapt(THRESHOLD);
    }
    if (Space::get_num_dofs(&space) >= NDOF_STOP) done = true;

    // Clean up.
    delete ref_space->get_mesh();
    delete ref_space;
    delete matrix;
    delete rhs;
    delete solver;
    delete adaptivity;

    // Increase the counter of performed adaptivity steps.
    as++;
  } while (!done);

  // Properly terminate the solver in the case of SOLVER_PETSC or SOLVER_MUMPS.
  finalize_solution_environment(matrix_solver);

  // This is the actual test.
#define ERROR_SUCCESS                               0
#define ERROR_FAILURE                               -1
  int ndof_allowed;
  switch (ANISO_TYPE) {
  case ANISO_X: ndof_allowed = 28; break;
    case ANISO_Y: ndof_allowed = 28; break;
    case ANISO_Z: ndof_allowed = 28; break;
    case ANISO_X | ANISO_Y: ndof_allowed = 98; break;
    case ANISO_X | ANISO_Z: ndof_allowed = 98; break;
    case ANISO_Y | ANISO_Z: ndof_allowed = 98; break;
  case ANISO_X | ANISO_Y | ANISO_Z: ndof_allowed = 343; break; 
    default: error("Admissible command-line options are x, y, x, xy, xz, yz, xyz.");
  }

  int ndof = Space::get_num_dofs(&space);

  info("ndof_actual = %d", ndof);
  info("ndof_allowed = %d", ndof_allowed); 
  if (ndof > ndof_allowed)
    success_test = 0;
  
  if (success_test) {
    info("Success!");
    return ERR_SUCCESS;
  }
  else {
    info("Failure!");
    return ERR_FAILURE;
  }
}
Example #10
0
int main(int argc, char **args) 
{
  // Test variable.
  int success_test = 1;

  if (argc < 3) error("Not enough parameters.");

  if (strcmp(args[1], "h1") != 0 && strcmp(args[1], "h1-ipol"))
    error("Unknown type of the projection.");

	// Load the mesh.
  Mesh mesh;
  H3DReader mloader;
  if (!mloader.load(args[2], &mesh)) error("Loading mesh file '%s'.", args[1]);

	// Refine the mesh.
  mesh.refine_all_elements(H3D_H3D_H3D_REFT_HEX_XYZ);

	// Initialize the space.
#if defined X2_Y2_Z2
  Ord3 order(2, 2, 2);
#elif defined X3_Y3_Z3
  Ord3 order(3, 3, 3);
#elif defined XN_YM_ZO
  Ord3 order(2, 3, 4);
#endif
  H1Space space(&mesh, bc_types, essential_bc_values, order);

  // Initialize the weak formulation.
  WeakForm wf;
  wf.add_matrix_form(bilinear_form<double, scalar>, bilinear_form<Ord, Ord>, HERMES_SYM, HERMES_ANY_INT);
  wf.add_vector_form(linear_form<double, scalar>, linear_form<Ord, Ord>, HERMES_ANY_INT);

  // Initialize the FE problem.
  bool is_linear = true;
  DiscreteProblem dp(&wf, &space, is_linear);

  // Set up the solver, matrix, and rhs according to the solver selection.
  SparseMatrix* matrix = create_matrix(matrix_solver);
  Vector* rhs = create_vector(matrix_solver);
  Solver* solver = create_linear_solver(matrix_solver, matrix, rhs);

  // Initialize the preconditioner in the case of SOLVER_AZTECOO.
  if (matrix_solver == SOLVER_AZTECOO) 
  {
    ((AztecOOSolver*) solver)->set_solver(iterative_method);
    ((AztecOOSolver*) solver)->set_precond(preconditioner);
    // Using default iteration parameters (see solver/aztecoo.h).
  }

  // Assemble the linear problem.
  dp.assemble(matrix, rhs);

  // Solve the linear system. If successful, obtain the solution.
  info("Solving the linear problem.");
  Solution sln(&mesh);
  if(solver->solve()) Solution::vector_to_solution(solver->get_solution(), &space, &sln);
  else {
	  info("Matrix solver failed.");
	  success_test = 0;
  }

  unsigned int ne = mesh.get_num_base_elements();
  for(std::map<unsigned int, Element*>::iterator it = mesh.elements.begin(); it != mesh.elements.end(); it++) {
    // We are done with base elements.
    if(it->first > ne)
      break;
    Element *e = it->second;
    
    Ord3 order(4, 4, 4);
    double error;

    Projection *proj;
    if (strcmp(args[1], "h1") == 0) proj = new H1Projection(&sln, e, space.get_shapeset());
    else if (strcmp(args[1], "h1-ipol") == 0) proj = new H1ProjectionIpol(&sln, e, space.get_shapeset());
    else success_test = 0;

    error = 0.0;
    error += proj->get_error(H3D_REFT_HEX_NONE, -1, order);
    error = sqrt(error);
    
    if (error > EPS)
		    // Calculated solution is not precise enough.
		    success_test = 0;

    //
    error = 0.0;
    error += proj->get_error(H3D_REFT_HEX_X, 20, order);
    error += proj->get_error(H3D_REFT_HEX_X, 21, order);
    error = sqrt(error);
    if (error > EPS)
		    // Calculated solution is not precise enough.
		    success_test = 0;

    //
    error = 0.0;
    error += proj->get_error(H3D_REFT_HEX_Y, 22, order);
    error += proj->get_error(H3D_REFT_HEX_Y, 23, order);
    error = sqrt(error);
    if (error > EPS)
		    // Calculated solution is not precise enough.
		    success_test = 0;

    //
    error = 0.0;
    error += proj->get_error(H3D_REFT_HEX_Z, 24, order);
    error += proj->get_error(H3D_REFT_HEX_Z, 25, order);
    error = sqrt(error);
    if (error > EPS)
		    // Calculated solution is not precise enough.
		    success_test = 0;

    //
    error = 0.0;
    error += proj->get_error(H3D_H3D_REFT_HEX_XY,  8, order);
    error += proj->get_error(H3D_H3D_REFT_HEX_XY,  9, order);
    error += proj->get_error(H3D_H3D_REFT_HEX_XY, 10, order);
    error += proj->get_error(H3D_H3D_REFT_HEX_XY, 11, order);
    error = sqrt(error);
    if (error > EPS)
		    // Calculated solution is not precise enough.
		    success_test = 0;

    //
    error = 0.0;
    error += proj->get_error(H3D_H3D_REFT_HEX_XZ, 12, order);
    error += proj->get_error(H3D_H3D_REFT_HEX_XZ, 13, order);
    error += proj->get_error(H3D_H3D_REFT_HEX_XZ, 14, order);
    error += proj->get_error(H3D_H3D_REFT_HEX_XZ, 15, order);
    error = sqrt(error);
    if (error > EPS)
		    // Calculated solution is not precise enough.
		    success_test = 0;

    //
    error = 0.0;
    error += proj->get_error(H3D_H3D_REFT_HEX_YZ, 16, order);
    error += proj->get_error(H3D_H3D_REFT_HEX_YZ, 17, order);
    error += proj->get_error(H3D_H3D_REFT_HEX_YZ, 18, order);
    error += proj->get_error(H3D_H3D_REFT_HEX_YZ, 19, order);
    error = sqrt(error);
    if (error > EPS)
		    // Calculated solution is not precise enough.
		    success_test = 0;

    //
    error = 0.0;
    for (int j = 0; j < 8; j++)
      error += proj->get_error(H3D_H3D_H3D_REFT_HEX_XYZ, j, order);
    error = sqrt(error);

    delete proj;
    
    if (error > EPS)
		    // Calculated solution is not precise enough.
		    success_test = 0;
  }

  if (success_test) {
    info("Success!");
    return ERR_SUCCESS;
  }
  else {
    info("Failure!");
    return ERR_FAILURE;
  }
}
Example #11
0
int main(int argc, char **args) 
{
  // Test variable.
  int success_test = 1;

	if (argc < 5) error("Not enough parameters.");

  // Load the mesh.
	Mesh mesh;
	H3DReader mloader;
	if (!mloader.load(args[1], &mesh)) error("Loading mesh file '%s'.", args[1]);
  
  // Initialize the space according to the
  // command-line parameters passed.
  sscanf(args[2], "%d", &P_INIT_X);
	sscanf(args[3], "%d", &P_INIT_Y);
	sscanf(args[4], "%d", &P_INIT_Z);
	Ord3 order(P_INIT_X, P_INIT_Y, P_INIT_Z);
  H1Space space(&mesh, bc_types, essential_bc_values, order);

  // Initialize the weak formulation.
	WeakForm wf;
	wf.add_matrix_form(bilinear_form<double, scalar>, bilinear_form<Ord, Ord>, HERMES_SYM, HERMES_ANY);
	wf.add_vector_form(linear_form<double, scalar>, linear_form<Ord, Ord>, HERMES_ANY);

	// Time measurement.
	TimePeriod cpu_time;
	cpu_time.tick();
  
	// Initialize the solver in the case of SOLVER_PETSC or SOLVER_MUMPS.
	initialize_solution_environment(matrix_solver, argc, args);

	// Adaptivity loop.
  int as = 1; 
	bool done = false;
	do {
    info("---- Adaptivity step %d:", as);

    // Construct globally refined reference mesh and setup reference space.
  	Space* ref_space = construct_refined_space(&space,1 , H3D_H3D_H3D_REFT_HEX_XYZ);
  
    out_orders_vtk(ref_space, "space", as);
	
	  // Initialize the FE problem.
	  bool is_linear = true;
	  DiscreteProblem lp(&wf, ref_space, is_linear);
		
	  // Set up the solver, matrix, and rhs according to the solver selection.
    SparseMatrix* matrix = create_matrix(matrix_solver);
    Vector* rhs = create_vector(matrix_solver);
    Solver* solver = create_linear_solver(matrix_solver, matrix, rhs);

    // Initialize the preconditioner in the case of SOLVER_AZTECOO.
    if (matrix_solver == SOLVER_AZTECOO) 
    {
      ((AztecOOSolver*) solver)->set_solver(iterative_method);
      ((AztecOOSolver*) solver)->set_precond(preconditioner);
      // Using default iteration parameters (see solver/aztecoo.h).
    }

    // Assemble the reference problem.
    info("Assembling on reference mesh (ndof: %d).", Space::get_num_dofs(ref_space));
    lp.assemble(matrix, rhs);

    // Time measurement.
    cpu_time.tick();

    // Solve the linear system on reference mesh. If successful, obtain the solution.
    info("Solving on reference mesh.");
    Solution ref_sln(ref_space->get_mesh());
    if(solver->solve()) Solution::vector_to_solution(solver->get_solution(), ref_space, &ref_sln);
    else {
		  printf("Matrix solver failed.\n");
		  success_test = 0;
	  }
    
    // Time measurement.
    cpu_time.tick();

    // Project the reference solution on the coarse mesh.
    Solution sln(space.get_mesh());
    info("Projecting reference solution on coarse mesh.");
    OGProjection::project_global(&space, &ref_sln, &sln, matrix_solver);

    // Time measurement.
    cpu_time.tick();

	  // Calculate element errors and total error estimate.
    info("Calculating error estimate and exact error.");
    Adapt *adaptivity = new Adapt(&space, HERMES_H1_NORM);
    bool solutions_for_adapt = true;
    double err_est_rel = adaptivity->calc_err_est(&sln, &ref_sln, solutions_for_adapt) * 100;

    // Report results.
    info("ndof_coarse: %d, ndof_fine: %d.", Space::get_num_dofs(&space), Space::get_num_dofs(ref_space));
    info("err_est_rel: %g%%.", err_est_rel);

	  // If err_est_rel is too large, adapt the mesh. 
    if (err_est_rel < ERR_STOP) {
		  done = true;
      ExactSolution ex_sln(&mesh, exact_solution);
		  
      // Calculate exact error.
      info("Calculating exact error.");
      Adapt *adaptivity = new Adapt(&space, HERMES_H1_NORM);
      bool solutions_for_adapt = false;
      double err_exact = adaptivity->calc_err_exact(&sln, &ex_sln, solutions_for_adapt, HERMES_TOTAL_ERROR_ABS);

      if (err_exact > EPS)
		    // Calculated solution is not precise enough.
		    success_test = 0;
	 
      break;
	  }	
    else {
      info("Adapting coarse mesh.");
      adaptivity->adapt(THRESHOLD);
    }

    // If we reached the maximum allowed number of degrees of freedom, set the return flag to failure.
    if (Space::get_num_dofs(&space) >= NDOF_STOP)
    {
      done = true;
      success_test = 0;
    }

	  // Clean up.
    delete ref_space->get_mesh();
    delete ref_space;
    delete matrix;
    delete rhs;
    delete solver;
    delete adaptivity;

    // Increase the counter of performed adaptivity steps.
    as++;
	} while (!done);

  // Properly terminate the solver in the case of SOLVER_PETSC or SOLVER_MUMPS.
  finalize_solution_environment(matrix_solver);
  
  if (success_test) {
    info("Success!");
    return ERR_SUCCESS;
  }
  else {
    info("Failure!");
    return ERR_FAILURE;
  }
}
Example #12
0
int main(int argc, char* argv[])
{
  info("Desired number of eigenvalues: %d.", NUMBER_OF_EIGENVALUES);

  // Load the mesh.
  info("Loading and refining mesh...");
  Mesh mesh;
  H3DReader mloader;
  mloader.load("hexahedron.mesh3d", &mesh);

  // Perform initial mesh refinements (optional).
  for (int i = 0; i < INIT_REF_NUM; i++) mesh.refine_all_elements(H3D_H3D_H3D_REFT_HEX_XYZ);

  // Create an H1 space with default shapeset.
  H1Space space(&mesh, bc_types, essential_bc_values, Ord3(P_INIT_X, P_INIT_Y, P_INIT_Z));
  int ndof = Space::get_num_dofs(&space);
  info("ndof: %d.", ndof);

  // Initialize the weak formulation for the left hand side, i.e., H.
  info("Initializing weak form...");
  WeakForm wf_left, wf_right;
  wf_left.add_matrix_form(bilinear_form_left, bilinear_form_left_ord, HERMES_SYM, HERMES_ANY );
  wf_right.add_matrix_form(callback(bilinear_form_right), HERMES_SYM, HERMES_ANY );

  // Initialize matrices and matrix solver.
  SparseMatrix* matrix_left = create_matrix(matrix_solver);
  SparseMatrix* matrix_right = create_matrix(matrix_solver);
  Solver* solver = create_linear_solver(matrix_solver, matrix_left);

  // Assemble the matrices.
  info("Assembling matrices...");
  bool is_linear = true;
  DiscreteProblem dp_left(&wf_left, &space, is_linear);
  dp_left.assemble(matrix_left);
  DiscreteProblem dp_right(&wf_right, &space, is_linear);
  dp_right.assemble(matrix_right);

  // Write matrix_left in MatrixMarket format.
  write_matrix_mm("mat_left.mtx", matrix_left);

  // Write matrix_right in MatrixMarket format.
  write_matrix_mm("mat_right.mtx", matrix_right);

  // Calling Python eigensolver. Solution will be written to "eivecs.dat".
  info("Using eigensolver...");
  char call_cmd[255];
  sprintf(call_cmd, "python solveGenEigenFromMtx.py mat_left.mtx mat_right.mtx %g %d %g %d", 
	  TARGET_VALUE, NUMBER_OF_EIGENVALUES, TOL, MAX_ITER);
  system(call_cmd);

  // Initializing solution vector, solution and ScalarView.
  info("Initializing solution vector...");
  double* coeff_vec = new double[ndof];
  Solution sln(space.get_mesh());


  // Reading solution vectors from file and visualizing.
  info("Reading solution vectors from file and saving as solutions in paraview format...");
  FILE *file = fopen("eivecs.dat", "r");
  char line [64];                  // Maximum line size.
  fgets(line, sizeof line, file);  // ndof
  int n = atoi(line);            
  if (n != ndof) error("Mismatched ndof in the eigensolver output file.");  
  fgets(line, sizeof line, file);  // Number of eigenvectors in the file.
  int neig = atoi(line);
  if (neig != NUMBER_OF_EIGENVALUES) error("Mismatched number of eigenvectors in the eigensolver output file.");  
  for (int ieig = 0; ieig < neig; ieig++) {
    // Get next eigenvector from the file.
    for (int i = 0; i < ndof; i++) {  
      fgets(line, sizeof line, file);
      coeff_vec[i] = atof(line);
    }

    // Convert coefficient vector into a Solution.
    Solution::vector_to_solution(coeff_vec, &space, &sln);

    out_fn_vtk(&sln, "sln", ieig );
  }  
  fclose(file);

  delete [] coeff_vec;

  return 0; 
};
Example #13
0
int main(int argc, char **args) 
{
  // Time measurement.
  TimePeriod cpu_time;
  cpu_time.tick();

  // Load the mesh. 
  Mesh mesh;
  H3DReader mloader;
  mloader.load("lshape_hex.mesh3d", &mesh);

  // Perform initial mesh refinement.
  for (int i=0; i < INIT_REF_NUM; i++) mesh.refine_all_elements(H3D_H3D_H3D_REFT_HEX_XYZ);

  // Create an Hcurl space with default shapeset.
  HcurlSpace space(&mesh, bc_types, essential_bc_values, Ord3(P_INIT_X, P_INIT_Y, P_INIT_Z));

  // Initialize weak formulation.
  WeakForm wf;
  wf.add_matrix_form(biform<double, scalar>, biform<Ord, Ord>, HERMES_SYM);
  wf.add_matrix_form_surf(biform_surf, biform_surf_ord);
  wf.add_vector_form_surf(liform_surf, liform_surf_ord);

  // Initialize discrete problem.
  bool is_linear = true;
  DiscreteProblem dp(&wf, &space, is_linear);

  // Initialize the solver in the case of SOLVER_PETSC or SOLVER_MUMPS.
  initialize_solution_environment(matrix_solver, argc, args);
  
  // Set up the solver, matrix, and rhs according to the solver selection.
  SparseMatrix* matrix = create_matrix(matrix_solver);
  Vector* rhs = create_vector(matrix_solver);
  Solver* solver = create_linear_solver(matrix_solver, matrix, rhs);

  // Initialize the preconditioner in the case of SOLVER_AZTECOO.
  if (matrix_solver == SOLVER_AZTECOO) 
  {
    ((AztecOOSolver*) solver)->set_solver(iterative_method);
    ((AztecOOSolver*) solver)->set_precond(preconditioner);
    // Using default iteration parameters (see solver/aztecoo.h).
  }

  // Assemble stiffness matrix and load vector.
  info("Assembling the linear problem (ndof: %d).", Space::get_num_dofs(&space));
  dp.assemble(matrix, rhs);

  // Solve the linear system. If successful, obtain the solution.
  info("Solving the linear problem.");
  Solution sln(space.get_mesh());
  if(solver->solve()) Solution::vector_to_solution(solver->get_solution(), &space, &sln);
  else error ("Matrix solver failed.\n");

  // Output solution and mesh with polynomial orders.
  if (solution_output) 
  {
    out_fn_vtk(&sln, "sln");
    out_orders_vtk(&space, "order");
  }
  
  // Time measurement.
  cpu_time.tick();

  // Print timing information.
  info("Solution and mesh with polynomial orders saved. Total running time: %g s", cpu_time.accumulated());

  // Clean up.
  delete matrix;
  delete rhs;
  delete solver;

  // Properly terminate the solver in the case of SOLVER_PETSC or SOLVER_MUMPS.
  finalize_solution_environment(matrix_solver);

  return 0;
}
Example #14
0
int main(int argc, char **args)
{
  // Time measurement.
  TimePeriod cpu_time;
  cpu_time.tick();

  // Load the mesh. 
  Mesh mesh;
  H3DReader mloader;
	mloader.load("lshape_hex.mesh3d", &mesh);

	// rough surface handler
	roughSurface r1 ;
	r1.setFilneName(std::string("1.surf")) ;
	r1.loadSurface() ;
	r1.findMinMax();

	columnList myCols ;
	bool further =true ;
	for(int iter=0 ; iter < 7 && further == true ; iter++)
	{
		std::cout << "Performing Refinement Level: " << iter << std::endl ;
		further = false ;
		for ( unsigned int idx = mesh.elements.first(), _max = mesh.elements.count(); idx <= _max && idx != INVALID_IDX; idx = mesh.elements.next(idx) )
		if ( mesh.elements[idx]->used) if (mesh.elements[idx]->active)
		{
			std::vector<unsigned int> vtcs(mesh.elements[idx]->get_num_vertices()) ;
			//unsigned int vtcs[mesh.elements[idx]->get_num_vertices()] ;
			mesh.elements[idx]->get_vertices(&vtcs[0]) ;
			//mesh.vertices[vtcs[0]]->dump() ;
			double minX=+std::numeric_limits<double>::max() ;
			double maxX=-std::numeric_limits<double>::max() ; 
			double minY=+std::numeric_limits<double>::max() ;
			double maxY=-std::numeric_limits<double>::max() ; 
			double minZ=+std::numeric_limits<double>::max() ;
			double maxZ=-std::numeric_limits<double>::max() ; 

			for( int i=0 ; i<vtcs.size() ; i++)
			{
				double x = mesh.vertices[vtcs[i]]->x ;
				double y = mesh.vertices[vtcs[i]]->y ;
				if(minX > x) minX = x ;
				if(maxX < x) maxX = x ;      
				if(minY > y) minY = y ;
				if(maxY < y) maxY = y ;
			}

			double sX = 0.05e-6;
			double sY = 0.05e-6;
			double deltaX = (maxX-minX) ;
			double deltaY = (maxY-minY) ;
			int nX = (int)floor(deltaX/sX) ;
			int nY = (int)floor(deltaY/sY) ;
			for( int u=0 ; u<=nX ; u++) for( int v=0 ; v<nY ; v++)
			{
				double x = minX + u*sX ;
				double y = minY + v*sY ;
				double z = r1.interpolate(x, y) ;
				if(minZ > z) minZ = z ;
				if(maxZ < z) maxZ = z ;
			}
			myCols[corner(minX,minY)].elements.insert(idx) ;
			myCols[corner(minX,minY)].lo = minZ ;
			myCols[corner(minX,minY)].hi = maxZ ;

			double deltaZ = std::abs(maxZ - minZ) ;
			if( deltaZ > 2.e-6)
			{
				//std::cout << "\n Iter., element, A.R., deltaZ: " << iter << " " << idx << " " << 2.*3.e-6/deltaX << " " << deltaZ ;
				if(mesh.can_refine_element(idx, H3D_H3D_REFT_HEX_XY)) mesh.refine_element(idx, H3D_H3D_REFT_HEX_XY) ;
				further = true ;
			}
			//mesh.elements[idx]->dump() ;
		}  
	}


	for ( unsigned int idx = mesh.vertices.first(), _max = mesh.vertices.count(); idx <= _max && idx != INVALID_IDX; idx = mesh.vertices.next(idx) )
		if( std::abs(mesh.vertices[idx]->z - 0.) < 1e-32 ) mesh.vertices[idx]->z = r1.interpolate(mesh.vertices[idx]->x,mesh.vertices[idx]->y) ;	

	for ( unsigned int idx = mesh.elements.first(), _max = mesh.elements.count(); idx <= _max && idx != INVALID_IDX; idx = mesh.elements.next(idx) )
		if ( mesh.elements[idx]->used) if (mesh.elements[idx]->active)
		{
			std::vector<unsigned int> vtcs(mesh.elements[idx]->get_num_vertices()) ;
			mesh.elements[idx]->get_vertices(&vtcs[0]) ;
			double minZ=+std::numeric_limits<double>::max() ;
			double maxZ=-std::numeric_limits<double>::max() ;
			double deltaZ=-std::numeric_limits<double>::max() ;

			for(std::vector<unsigned int>::iterator i=vtcs.begin() ; i!=vtcs.end() ; i++)
			{
				double z = mesh.vertices[*i]->z ;
				if(minZ > z) minZ = z ;
				if(maxZ < z) maxZ = z ;
				deltaZ = std::abs(maxZ - minZ) ;
			}
			//std::cout << std::endl ;
			if(deltaZ > 4e-6)
			{
				if( mesh.can_refine_element(idx, H3D_REFT_HEX_Z) ) mesh.refine_element(idx, H3D_REFT_HEX_Z) ;
				//else if( mesh.can_refine_element(idx, H3D_H3D_H3D_REFT_HEX_XYZ) ) mesh.refine_element(idx, H3D_H3D_H3D_REFT_HEX_XYZ) ;
				//mesh.refine_element(idx, H3D_H3D_H3D_REFT_HEX_XYZ) ;
			}
		}

	out_mesh_vtk(&mesh, "mesh");
	return 0;
}
Example #15
0
int main(int argc, char* argv[])
{
  TimePeriod cpu_time;
  // Load the mesh.
  info("Loading mesh...");
  Mesh mesh;
  H3DReader mloader;
  cpu_time.reset();
  mloader.load("box.mesh3d", &mesh);
  cpu_time.tick();
  info("time taken for loading mesh : %g s", cpu_time.accumulated());
  cpu_time.reset();
  // Perform initial mesh refinements
  cpu_time.tick();
  for (int i = 0; i < INIT_REF_NUM; i++) mesh.refine_all_elements(H3D_H3D_H3D_REFT_HEX_XYZ);
  int NUM_ELEMS=mesh.get_num_active_elements();
  info("NUM_ELEMS=%d",NUM_ELEMS);
  // iterate over all elements to find those including the origin!
  // There are at most 8 active elements that have the origin 
  // as a vertex  at every step of the refinement
  int list_of_ids[8];
  int io,ir=0;
  while(ir<REF_ORIGIN){
    io=0;
    for(std::map<unsigned int, Element*>::const_iterator it=mesh.elements.begin(); it != mesh.elements.end(); it++) {
      Element *e=it->second;
      if (e->active) {
	info("element id= %d",it->first);
	for(int i=0;i<8;i++){
	  unsigned int vtx = e->get_vertex(i);    
	  double xx=mesh.vertices[vtx]->x; 
	  double yy=mesh.vertices[vtx]->y; 
	  double zz=mesh.vertices[vtx]->z;
	  if ( xx == 0.0 and yy == 0.0 and zz== 0.0 ){
	    list_of_ids[io]=it->first;
	    io++;
	  }
	}
      }
    }
    for (int i=0;i<8;i++) {
      info("%d %d\n",i,list_of_ids[i]);
      mesh.refine_element(list_of_ids[i], H3D_H3D_H3D_REFT_HEX_XYZ);
    }
    ir++;
    int NUM_ELEMS=mesh.get_max_element_id();
    info("NUM_ELEMS=%d",NUM_ELEMS);
  }
  cpu_time.reset();
  FILE *out = fopen("mesh.gmsh", "w" );
  GmshOutputEngine *gout = new GmshOutputEngine(out);
  gout->out( &mesh);
  fclose(out);
  // setting up space for eigen value calculation with zero boundary conditions
  H1Space space(&mesh, bc_types, essential_bc_values, Ord3(P_INIT_X, P_INIT_Y, P_INIT_Z));
  bool is_linear = true;
  int ndof = Space::get_num_dofs(&space);
  info("ndof=%d",ndof);
  ExactSolution pot_exact(&mesh,hopot);
  // Initialize the weak formulation for left hand side and right hand side , i.e., H and U.
  info("Initializing weak forms...");
  WeakForm wf_left, wf_right;
  wf_left.add_matrix_form(bilinear_form_left, bilinear_form_ord, HERMES_SYM, HERMES_ANY_INT, Hermes::vector<MeshFunction*>(&pot_exact));
  wf_right.add_matrix_form(bilinear_form_right,bilinear_form_ord, HERMES_SYM, HERMES_ANY_INT);   
  // Initialize matrices and matrix solver.
  RCP<CSCMatrix>  matrix_right = rcp(new CSCMatrix());
  info("Assembling RHS matrix....");
  DiscreteProblem dp_right(&wf_right, &space, is_linear);
  cpu_time.reset();
  dp_right.assemble(matrix_right.get());
  cpu_time.tick();
  info("time taken to assemble RHS matrix: %g s", cpu_time.accumulated());
  Solution sln(&mesh);
  fflush(stdout);
  DiscreteProblem dp_left(&wf_left, &space, is_linear);
  RCP<CSCMatrix> matrix_left = rcp(new CSCMatrix());
  Solver* solver = create_linear_solver(matrix_solver, matrix_left.get());
  cpu_time.reset();
  dp_left.assemble(matrix_left.get());
  cpu_time.tick();
  info("time taken for assembling LHS matrix : %g", cpu_time.accumulated());
  // Initialize eigensolver
  cpu_time.reset();
  EigenSolver es(matrix_left, matrix_right);
  cpu_time.tick();
  info("Total running time for preparing generalized eigenvalue problem: %g s\n", cpu_time.accumulated());
  info("Using eigensolver...");
  cpu_time.reset();
  es.solve(NUMBER_OF_EIGENVALUES, TARGET_VALUE, TOL, MAX_ITER);
  cpu_time.tick();
  info("Total running time for solving generalized eigenvalue problem: %g s", cpu_time.accumulated());
  double* coeff_vec;
  double coulomb_energy;
  int neig = es.get_n_eigs();
  double *eival = new double[neig]; 
  if (neig != NUMBER_OF_EIGENVALUES) error("Mismatched number of eigenvectors in eigensolver");  
  for (int ieig = 0; ieig < neig; ieig++) {
    int n;
    es.get_eigenvector(ieig, &coeff_vec, &n);
    // Convert coefficient vector into a Solution.
    Solution::vector_to_solution(coeff_vec, &space, &sln);
    eival[ieig]=es.get_eigenvalue(ieig);
    info("eival[%d]=%24.15E",ieig,eival[ieig]);
    out_fn_vtk(&sln, "phi", ieig );
    }  
  return 0; 
};
Example #16
0
int main(int argc, char* argv[])
{
  // Time measurement.
  TimePeriod cpu_time;

  // Load the mesh.
  info("Loading mesh...");
  Mesh mesh;
  H3DReader mloader;
  cpu_time.reset();
  mloader.load("mol.mesh3d", &mesh);
  cpu_time.tick();
  info("Time taken for loading mesh : %g s", cpu_time.accumulated());
  cpu_time.reset();

  // Perform initial mesh refinements.
  for (int i = 0; i < INIT_REF_NUM; i++) mesh.refine_all_elements(H3D_H3D_H3D_REFT_HEX_XYZ);
  int NUM_ELEMS = mesh.get_max_element_id();
  info("NUM_ELEMS = %d", NUM_ELEMS);
  cpu_time.tick();
  info("Time for refining mesh: %g s", cpu_time.accumulated());
  cpu_time.reset();

  // Setting up space for eigen value calculation with zero boundary conditions.
  H1Space space(&mesh, bc_types, essential_bc_values_eigen, Ord3(P_INIT_X, P_INIT_Y, P_INIT_Z));

  // Setting up space for solution of  Poisson equation with (approximate) boundary conditions 2*N/sqrt(x*x+y*y+z*z).
  H1Space space_poisson(&mesh, bc_types, essential_bc_values_poisson, Ord3(P_INIT_X, P_INIT_Y, P_INIT_Z));
  bool is_linear = true;

  // Setting up Laplace matrix for solving the Poisson equation. 
  WeakForm wf_poisson;
  wf_poisson.add_matrix_form(bilinear_form_laplace, bilinear_form_ord1, HERMES_SYM, HERMES_ANY_INT);
  RCP<SparseMatrix> matrix_Laplace = rcp(new CSCMatrix());
  Solver* solver = create_linear_solver(matrix_solver, matrix_Laplace.get());
  DiscreteProblem dp_poisson(&wf_poisson, &space, is_linear);
  dp_poisson.assemble(matrix_Laplace.get());
  int ndof = Space::get_num_dofs(&space);
  info("ndof = %d", ndof);
  ExactSolution pot_exact(&mesh, pot);
  ExactSolution wfun_exact(&mesh, wfun);
  Solution coul_pot(space.get_mesh());
  coul_pot.set_zero();                 // coul_pot zero at the beginning.

  // Initialize the weak formulation for the left hand side, i.e., H.
  info("Initializing weak form...");
  WeakForm wf_left, wf_right;
  wf_left.add_matrix_form(bilinear_form_left, bilinear_form_ord, HERMES_SYM, HERMES_ANY_INT,
                          Hermes::vector<MeshFunction*>(&pot_exact, &wfun_exact,&coul_pot ));
  wf_right.add_matrix_form(bilinear_form_right, bilinear_form_ord, HERMES_SYM, HERMES_ANY_INT, &wfun_exact);   
  DiscreteProblem dp(&wf_left, &space, is_linear);

  // Initialize matrices and matrix solver.
  RCP<SparseMatrix> matrix_left = rcp(new CSCMatrix());
  RCP<SparseMatrix> matrix_right = rcp(new CSCMatrix());
  cpu_time.reset();
  info("Assembling RHS matrix....");
  DiscreteProblem dp_left(&wf_left, &space, is_linear);
  DiscreteProblem dp_right(&wf_right, &space, is_linear);
  dp_right.assemble(matrix_right.get());
  cpu_time.tick();
  info("time taken to assemble RHS matrix: %g s", cpu_time.accumulated());
  WeakForm wf_coulomb;
  wf_coulomb.add_matrix_form(bilinear_form_coul_pot, bilinear_form_ord1, HERMES_SYM, HERMES_ANY_INT,
                             Hermes::vector<MeshFunction*>(&wfun_exact,&coul_pot ));
  RCP<SparseMatrix> matrix_coulomb = rcp(new CSCMatrix());
  DiscreteProblem dp_coulomb(&wf_coulomb, &space, is_linear);
  Solution sln(space.get_mesh());
  RCP<SparseMatrix> matrix_U = rcp(new CSCMatrix());
  bool DONE=false;
  int iter=0;
  info("SELF CONSISTENT LOOP BEGINS:");
  fflush(stdout);

  // Now follows the self consistent loop:
  while (!DONE){
    WeakForm  wf;
    Vector* rhs=create_vector(matrix_solver);
    Solver* solver = create_linear_solver(matrix_solver, matrix_left.get());
    dp_left.assemble(matrix_left.get());
    cpu_time.tick();
    info("time taken for assembling LHS matrix : %g", cpu_time.accumulated());
    cpu_time.reset();
    dp_coulomb.assemble(matrix_coulomb.get());
    cpu_time.tick();
    info("time for assembling  matrix_coulomb: %g  " , cpu_time.accumulated());

    // Initialize eigensolver.
    cpu_time.reset();
    EigenSolver es(matrix_left, matrix_right);
    cpu_time.tick();
    info("Total running time for preparing generalized eigenvalue problem: %g s\n", cpu_time.accumulated());

    cpu_time.reset();
    info("Using eigensolver...");
    es.solve(NUMBER_OF_EIGENVALUES, TARGET_VALUE, TOL, MAX_ITER);
    info("Total running time for solving generalized eigenvalue problem: %g s", cpu_time.accumulated());
    double* coeff_vec;
    double coulomb_energy;
    int neig = es.get_n_eigs();
    double *eival = new double[neig]; 
    if (neig != NUMBER_OF_EIGENVALUES) error("Mismatched number of eigenvectors in eigensolver");  
    for (int ieig = 0; ieig < neig; ieig++) {
      int n;
      es.get_eigenvector(ieig, &coeff_vec, &n);

      // Convert coefficient vector into a Solution.
      Solution::vector_to_solution(coeff_vec, &space, &sln);
      double norm2=expectation_value(coeff_vec, matrix_right.get(),ndof);
      coulomb_energy=expectation_value(coeff_vec,matrix_coulomb.get(),ndof);
      eival[ieig]=es.get_eigenvalue(ieig);
      info("eigenvector %d : norm=%25.16f \n eigenvalue=%25.16f \n coulomb_energy=%25.16f ",
           ieig, pow(norm2, 0.5), eival[ieig], coulomb_energy);
      wf.add_vector_form(linear_form_poisson, linear_form_poisson_ord, HERMES_ANY_INT,
                         Hermes::vector<MeshFunction*>(&sln, &wfun_exact)); 
      out_fn_vtk(&sln, "phi", ieig);
    }  
    double HFenergy = 2*eival[0] - coulomb_energy;
    info("HF energy for two electrons=%25.16f", HFenergy);
    DiscreteProblem dp_density(&wf, &space, is_linear);
    dp_density.assemble(matrix_U.get(), rhs);
    Solver* solver_poisson = create_linear_solver(matrix_solver, matrix_Laplace.get(),rhs);
    info("Solving the matrix problem.");
    fflush(stdout);
    if(solver_poisson->solve())
	Solution::vector_to_solution(solver_poisson->get_solution(), &space_poisson, &coul_pot);
    else
      error ("Matrix solver failed.\n");
    out_fn_vtk(&coul_pot, "coul_pot", 0);
    iter++; 
    if (iter > MAX_SCF_ITER){ 
      delete [] coeff_vec;
      DONE=true;    
    } 
  }

  // missing mesh file mol.mesh3d, supposed to fail temporary.
  return ERR_FAILURE;
};