示例#1
0
int main(int argc, char* argv[])
{
    // Load the mesh.
    Hermes::Hermes2D::Mesh mesh;
    Hermes::Hermes2D::H2DReader mloader;
    mloader.load("domain.mesh", &mesh);

    // Perform initial mesh refinements (optional).
    int refinement_type = 2;            // Split elements vertically.
    for (int i = 0; i < INIT_REF_NUM; i++) mesh.refine_all_elements(refinement_type);

    // Show the mesh.
    Hermes::Hermes2D::Views::MeshView mview("Mesh", new Hermes::Hermes2D::Views::WinGeom(0, 0, 900, 250));
    if (HERMES_VISUALIZATION) {
        mview.show(&mesh);
        //mview.wait();
    }

    // Initialize the weak formulation.
    CustomWeakFormPoisson wf("Al", new Hermes::Hermes1DFunction<double>(LAMBDA_AL), "Cu",
                             new Hermes::Hermes1DFunction<double>(LAMBDA_CU), new Hermes::Hermes2DFunction<double>(-VOLUME_HEAT_SRC));

    // Initialize essential boundary conditions.
    Hermes::Hermes2D::DefaultEssentialBCConst<double> bc_essential(Hermes::vector<std::string>("Left", "Right"),
            FIXED_BDY_TEMP);
    Hermes::Hermes2D::EssentialBCs<double> bcs(&bc_essential);

    // Create an H1 space with default shapeset.
    Hermes::Hermes2D::H1Space<double> space(&mesh, &bcs, P_INIT);
    int ndof = space.get_num_dofs();
    info("ndof = %d", ndof);

    // Initialize the FE problem.
    Hermes::Hermes2D::DiscreteProblem<double> dp(&wf, &space);

    // Initial coefficient vector for the Newton's method.
    double* coeff_vec = new double[ndof];
    memset(coeff_vec, 0, ndof*sizeof(double));

    // Perform Newton's iteration and translate the resulting coefficient vector into a Solution.
    Hermes::Hermes2D::Solution<double> sln;
    Hermes::Hermes2D::NewtonSolver<double> newton(&dp, matrix_solver_type);
    if (!newton.solve(coeff_vec))
        error("Newton's iteration failed.");
    else
        Hermes::Hermes2D::Solution<double>::vector_to_solution(newton.get_sln_vector(), &space, &sln);

    // Get info about time spent during assembling in its respective parts.
    dp.get_all_profiling_output(std::cout);

    // VTK output.
    if (VTK_VISUALIZATION)
    {
        // Output solution in VTK format.
        Hermes::Hermes2D::Views::Linearizer<double> lin;
        bool mode_3D = true;
        lin.save_solution_vtk(&sln, "sln.vtk", "Temperature", mode_3D);
        info("Solution in VTK format saved to file %s.", "sln.vtk");

        // Output mesh and element orders in VTK format.
        Hermes::Hermes2D::Views::Orderizer ord;
        ord.save_orders_vtk(&space, "ord.vtk");
        info("Element orders in VTK format saved to file %s.", "ord.vtk");
    }

    // Visualize the solution.
    if (HERMES_VISUALIZATION)
    {
        Hermes::Hermes2D::Views::ScalarView<double> view("Solution", new Hermes::Hermes2D::Views::WinGeom(0, 300, 900, 350));
        // Hermes uses adaptive FEM to approximate higher-order FE solutions with linear
        // triangles for OpenGL. The second parameter of View::show() sets the error
        // tolerance for that. Options are HERMES_EPS_LOW, HERMES_EPS_NORMAL (default),
        // HERMES_EPS_HIGH and HERMES_EPS_VERYHIGH. The size of the graphics file grows
        // considerably with more accurate representation, so use it wisely.
        view.show(&sln, Hermes::Hermes2D::Views::HERMES_EPS_HIGH);
        Hermes::Hermes2D::Views::View::wait();
    }

    // Clean up.
    delete [] coeff_vec;

    return 0;
}
示例#2
0
int main(int argc, char* argv[])
{
  // Load the mesh.
  Mesh mesh;
  H2DReader mloader;
  mloader.load("../domain.mesh", &mesh);

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

  // Initialize boundary conditions
  EssentialBCNonConst bc_essential(BDY_HORIZONTAL);
  EssentialBCs bcs(&bc_essential);

  // Create an H1 space with default shapeset.
  H1Space space(&mesh, &bcs, P_INIT);
  int ndof = space.get_num_dofs();
  info("ndof = %d", ndof);

  // Initialize the weak formulation.
  CustomWeakFormGeneral wf;

  // Testing n_dof and correctness of solution vector
  // for p_init = 1, 2, ..., 10
  int success = 1;
  Solution sln;
  for (int p_init = 1; p_init <= 10; p_init++) {

    printf("********* p_init = %d *********\n", p_init);
    space.set_uniform_order(p_init);

    // 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 solution.
    Solution sln;

    // Assemble the stiffness matrix and right-hand side vector.  
    info("Assembling the stiffness matrix and right-hand side vector.");
    bool rhsonly = false;
    dp.assemble(matrix, rhs, rhsonly);

    // Solve the linear system and if successful, obtain the solution.
    info("Solving the matrix problem.");
    if(solver->solve())
      Solution::vector_to_solution(solver->get_solution(), &space, &sln);
    else
      error ("Matrix solver failed.\n");
  
    int ndof = Space::get_num_dofs(&space);
    printf("ndof = %d\n", ndof);
    double sum = 0;
    for (int i=0; i < ndof; i++) sum += solver->get_solution()[i];
    printf("coefficient sum = %g\n", sum);

    // Actual test. The values of 'sum' depend on the
    // current shapeset. If you change the shapeset,
    // you need to correct these numbers.
    if (p_init == 1 && fabs(sum - 1.72173) > 1e-2) success = 0;
    if (p_init == 2 && fabs(sum - 0.639908) > 1e-2) success = 0;
    if (p_init == 3 && fabs(sum - 0.826367) > 1e-2) success = 0;
    if (p_init == 4 && fabs(sum - 0.629395) > 1e-2) success = 0;
    if (p_init == 5 && fabs(sum - 0.574235) > 1e-2) success = 0;
    if (p_init == 6 && fabs(sum - 0.62792) > 1e-2) success = 0;
    if (p_init == 7 && fabs(sum - 0.701982) > 1e-2) success = 0;
    if (p_init == 8 && fabs(sum - 0.7982) > 1e-2) success = 0;
    if (p_init == 9 && fabs(sum - 0.895069) > 1e-2) success = 0;
    if (p_init == 10 && fabs(sum - 1.03031) > 1e-2) success = 0;
  }

  if (success == 1) {
    printf("Success!\n");
    return ERR_SUCCESS;
  }
  else {
    printf("Failure!\n");
    return ERR_FAILURE;
  }
}
示例#3
0
int main(int argc, char* argv[])
{
  // Define problem parameters: (x_loc, y_loc) is the center of the circular wave front, R_ZERO is the distance from the 
  // wave front to the center of the circle, and alpha gives the steepness of the wave front.
  double alpha, x_loc, y_loc, r_zero;
  switch(PARAM) {
  case 0:
    alpha = 20;
    x_loc = -0.05;
    y_loc = -0.05;
    r_zero = 0.7;
    break;
  case 1:
    alpha = 1000;
    x_loc = -0.05;
    y_loc = -0.05;
    r_zero = 0.7;
    break;
  case 2:
    alpha = 1000;
    x_loc = 1.5;
    y_loc = 0.25;
    r_zero = 0.92;
    break;
  case 3:
    alpha = 50;
    x_loc = 0.5;
    y_loc = 0.5;
    r_zero = 0.25;
    break;
  default:   
    // The same as 0.
    alpha = 20;
    x_loc = -0.05;
    y_loc = -0.05;
    r_zero = 0.7;
    break;
  }
  
  // Set adaptivity options according to the command line argument.
  int refinement_mode;
  if (argc != 2)
    refinement_mode = 0;
  else
  {
    refinement_mode = atoi(argv[1]);
    if (refinement_mode < 1 || refinement_mode > 12)
      throw Hermes::Exceptions::Exception("Invalid run case: %d (valid range is [1,12])", refinement_mode);
  }
  
  double threshold = 0.3;                     
  // strategy = 0 ... Refine elements until sqrt(threshold) times total error is processed. 
  //                  If more elements have similar errors, refine all to keep the mesh symmetric.
  int strategy = 0;       
  // strategy = 1 ... Refine all elements whose error is larger than threshold times max. element error.
  // Add also the norm of the residual to the error estimate of each element.
  bool use_residual_estimator = false;        
  // Use energy norm for error estimate normalization and measuring of exact error.
  bool use_energy_norm_normalization = false; 
  
  switch (refinement_mode)
  {
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
    {
      strategy = 0;
      break;
    }
    
    case 7 :
    case 8 :
    case 9 :
    case 10:
    case 11:
    case 12:
    {
      strategy = 1;
      break;
    }
  }
  
  switch (refinement_mode)
  {
    case 1:
    case 2:
    case 3:
    case 7:
    case 8:
    case 9:
    {
      threshold = 0.3;
      break;
    }
    
    case 4:
    case 5:
    case 6:
    case 10:
    case 11:
    case 12:
    {
      threshold = 0.3*0.3;
      break;
    }
  }
  
  switch (refinement_mode)
  {
    case 2:
    case 3:
    case 5:
    case 6:
    case 8:
    case 9:
    case 11:
    case 12:
    {
      use_residual_estimator = true;
      break;
    }
  }
  
  switch (refinement_mode)
  {
    case 3:
    case 6:
    case 9:
    case 12:
    {
      use_energy_norm_normalization = true;
      break;
    }
  }
  
  double setup_time = 0, assemble_time = 0, solve_time = 0, adapt_time = 0;
  
  // Time measurement.
  Hermes::Mixins::TimeMeasurable wall_clock;
  // Stop counting time for adaptation.
  wall_clock.tick(); 

  // Load the mesh.
  Mesh mesh;
  MeshReaderH2D mloader;
  mloader.load("square_quad.mesh", &mesh);    

  // Perform initial mesh refinement.
  for (int i = 0; i < INIT_REF_NUM; i++) mesh.refine_all_elements();
  
  // Stop counting time for adaptation.
  wall_clock.tick(); 
  adapt_time += wall_clock.last();
  
  // Set exact solution.
  CustomExactSolution exact(&mesh, alpha, x_loc, y_loc, r_zero);

  // Define right-hand side.
  CustomRightHandSide rhs(alpha, x_loc, y_loc, r_zero);

  // Initialize the weak formulation.
  CustomWeakForm wf(&rhs);
  // Equivalent, but slower:
  // DefaultWeakFormPoisson<double> wf(Hermes::HERMES_ANY, HERMES_ONE, &rhs);

  // Initialize boundary conditions.
  DefaultEssentialBCNonConst<double> bc("Bdy", &exact);
  EssentialBCs<double> bcs(&bc);

  // Create an H1 space with default shapeset.
  H1Space<double> space(&mesh, &bcs, P_INIT);
  
  // Initialize approximate solution.
  Solution<double> sln;
  
  // Initialize views.
  Views::ScalarView sview("Solution", new Views::WinGeom(800, 0, 400, 400));
  sview.show_mesh(false);
  sview.set_3d_mode();
  sview.set_palette(Views::H2DV_PT_HUESCALE);
  sview.fix_scale_width(50);
  Views::OrderView  oview("Mesh", new Views::WinGeom(0, 0, 800, 800));
  oview.set_palette(Views::H2DV_PT_INVGRAYSCALE);

  // DOF and CPU convergence graphs.
  ConvergenceTable conv_table;
  conv_table.add_column(" cycle ", "%6d ");
  conv_table.add_column("  H1 error ", " %.4e ");
  conv_table.add_column("   ndof  ", " %6d ");
  conv_table.add_column(" total time ", " %8.3f  ");
  conv_table.add_column(" setup time ", "  %8.3f  ");
  conv_table.add_column(" assem time ", "  %8.3f  ");
  conv_table.add_column(" solve time ", "  %8.3f  ");
  conv_table.add_column(" adapt time ", "  %8.3f  ");
  
  wall_clock.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);

  // Adaptivity loop:
  int as = 0; bool done = false;
  do
  {
    // Start counting setup time.
    wall_clock.tick(); 
    
    // Assemble the discrete problem.    
    DiscreteProblem<double> dp(&wf, &space);

    // Actual ndof.
    int ndof = space.get_num_dofs();
    
    NewtonSolver<double> newton(&dp);
    newton.set_verbose_output(false);

    // Setup time continues in NewtonSolver::solve().
    try
    {
      newton.solve();
    }
    catch(Hermes::Exceptions::Exception e)
    {
      e.printMsg();
      throw Hermes::Exceptions::Exception("Newton's iteration failed.");
    };

    setup_time += newton.get_setup_time();
    assemble_time += newton.get_assemble_time();
    solve_time += newton.get_solve_time();
     
    // Start counting time for adaptation.
    wall_clock.tick();  
    Solution<double>::vector_to_solution(newton.get_sln_vector(), &space, &sln);
    
    double err_exact = Global<double>::calc_abs_error(&sln, &exact, HERMES_H1_NORM);
   
    // Report results.
    Hermes::Mixins::Loggable::Static::info(" Cycle %d:", as);
    Hermes::Mixins::Loggable::Static::info("    Number of degrees of freedom: %d", ndof);
    Hermes::Mixins::Loggable::Static::info("    H1 error w.r.t. exact soln.:  %g", err_exact);
    
    // Stop counting time for adaptation.
    wall_clock.tick(); 
    double accum_time = wall_clock.accumulated();
    adapt_time += wall_clock.last();
    
    // View the approximate solution and polynomial orders.
    //sview.show(&sln);
    //oview.show(&space);
    //Views::View::wait(Views::HERMES_WAIT_KEYPRESS);
    
    conv_table.add_value(0, as);
    conv_table.add_value(1, err_exact);
    conv_table.add_value(2, ndof);
    conv_table.add_value(3, accum_time);
    conv_table.add_value(4, setup_time);
    conv_table.add_value(5, assemble_time);
    conv_table.add_value(6, solve_time);
    conv_table.add_value(7, adapt_time);
    
    // Start counting time for adaptation.
    wall_clock.tick(); 
    
    if (err_exact < ERR_STOP) 
      done = true;
    else
    {
      // Calculate element errors and total error estimate.
      Hermes::Hermes2D::BasicKellyAdapt<double> adaptivity(&space);
      
      unsigned int error_flags = HERMES_TOTAL_ERROR_ABS;
      
      if (use_energy_norm_normalization)
      {
        error_flags |= HERMES_ELEMENT_ERROR_REL;
        adaptivity.set_error_form(new EnergyErrorForm(&wf));
      }
      else
        error_flags |= HERMES_ELEMENT_ERROR_ABS;
      
      if (use_residual_estimator) 
        adaptivity.add_error_estimator_vol(new ResidualErrorForm(&rhs));
      
      double err_est_rel = adaptivity.calc_err_est(&sln, error_flags);  
      
      done = adaptivity.adapt(threshold, strategy, MESH_REGULARITY);
      
      // Stop counting time for adaptation.
      wall_clock.tick(); 
      adapt_time += wall_clock.last();
    }
        
    // Increase the counter of performed adaptivity steps.
    if (done == false)  
      as++;
    else
    {
      Hermes::Mixins::Loggable::Static::info("Total running time:  %g s", wall_clock.accumulated());
      Hermes::Mixins::Loggable::Static::info("   Setup:            %g s", setup_time);
      Hermes::Mixins::Loggable::Static::info("   Assemble:         %g s", assemble_time);
      Hermes::Mixins::Loggable::Static::info("   Solve:            %g s", solve_time);
      Hermes::Mixins::Loggable::Static::info("   Adapt:            %g s", adapt_time);
      
      //sview.show(&sln);
      oview.show(&space);
      oview.save_screenshot(("final_mesh-"+itos(refinement_mode)+".bmp").c_str());
      oview.close();
      conv_table.save(("conv_table-"+itos(refinement_mode)+".dat").c_str());
    }
  }
  while (done == false);

  // Wait for all views to be closed.
  //Views::View::wait();
  return 0;
}
示例#4
0
int main(int argc, char* argv[])
{
  // Load the mesh.
  Mesh mesh;
  if (USE_XML_FORMAT == true)
  {
    MeshReaderH2DXML mloader;  
    info("Reading mesh in XML format.");
    mloader.load("domain.xml", &mesh);
  }
  else 
  {
    MeshReaderH2D mloader;
    info("Reading mesh in original format.");
    mloader.load("domain.mesh", &mesh);
  }

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

  // Initialize the weak formulation.
  CustomWeakFormPoisson wf("Aluminum", new Hermes1DFunction<double>(LAMBDA_AL), 
                           "Copper", new Hermes1DFunction<double>(LAMBDA_CU), 
                           new Hermes2DFunction<double>(-VOLUME_HEAT_SRC));
  
  // Initialize essential boundary conditions.
  DefaultEssentialBCConst<double> bc_essential(
      Hermes::vector<std::string>("Bottom", "Inner", "Outer", "Left"), FIXED_BDY_TEMP);
  EssentialBCs<double> bcs(&bc_essential);

  // Create an H1 space with default shapeset.
  H1Space<double> space(&mesh, &bcs, P_INIT);
  int ndof = space.get_num_dofs();
  info("ndof = %d", ndof);

  // Initialize the FE problem.
  DiscreteProblem<double> dp(&wf, &space);

  // Initial coefficient vector for the Newton's method.  
  double* coeff_vec = new double[ndof];
  memset(coeff_vec, 0, ndof*sizeof(double));

  // Initialize Newton solver.
  NewtonSolver<double> newton(&dp, matrix_solver);

  // Perform Newton's iteration.
  try
  {
    newton.solve(coeff_vec);
  }
  catch(Hermes::Exceptions::Exception e)
  {
    e.printMsg();
    error("Newton's iteration failed.");
  }

  // Translate the resulting coefficient vector into a Solution.
  Solution<double> sln;
  Solution<double>::vector_to_solution(newton.get_sln_vector(), &space, &sln);

  // Get info about time spent during assembling in its respective parts.
  dp.get_all_profiling_output(std::cout);

  // VTK output.
  if (VTK_VISUALIZATION) 
  {
    // Output solution in VTK format.
    Linearizer lin;
    bool mode_3D = true;
    lin.save_solution_vtk(&sln, "sln.vtk", "Temperature", mode_3D);
    info("Solution in VTK format saved to file %s.", "sln.vtk");

    // Output mesh and element orders in VTK format.
    Orderizer ord;
    ord.save_orders_vtk(&space, "ord.vtk");
    info("Element orders in VTK format saved to file %s.", "ord.vtk");
  }

  // Visualize the solution.
  if (HERMES_VISUALIZATION) 
  {
    ScalarView view("Solution", new WinGeom(0, 0, 440, 350));
    // Hermes uses adaptive FEM to approximate higher-order FE solutions with linear
    // triangles for OpenGL. The second parameter of View::show() sets the error 
    // tolerance for that. Options are HERMES_EPS_LOW, HERMES_EPS_NORMAL (default), 
    // HERMES_EPS_HIGH and HERMES_EPS_VERYHIGH. The size of the graphics file grows 
    // considerably with more accurate representation, so use it wisely.
    view.show(&sln, HERMES_EPS_HIGH);
    View::wait();
  }

  // Clean up.
  delete [] coeff_vec;

  return 0;
}
示例#5
0
        void FilterAeroForces::v_Initialise(
            const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields,
            const NekDouble &time)
        {
            // Parse the boundary regions into a list.
            std::string::size_type FirstInd =
                                    m_BoundaryString.find_first_of('[') + 1;
            std::string::size_type LastInd =
                                    m_BoundaryString.find_last_of(']') - 1;

            ASSERTL0(FirstInd <= LastInd,
                    (std::string("Error reading boundary region definition:") +
                     m_BoundaryString).c_str());

            std::string IndString =
                    m_BoundaryString.substr(FirstInd, LastInd - FirstInd + 1);
            bool parseGood = ParseUtils::GenerateSeqVector(IndString.c_str(),
                                                       m_boundaryRegionsIdList);
            ASSERTL0(parseGood && !m_boundaryRegionsIdList.empty(),
                     (std::string("Unable to read boundary regions index "
                      "range for FilterAeroForces: ") + IndString).c_str());

            // determine what boundary regions need to be considered
            int cnt;
            unsigned int numBoundaryRegions =
                                pFields[0]->GetBndConditions().num_elements();
            m_boundaryRegionIsInList.insert(m_boundaryRegionIsInList.end(),
                                            numBoundaryRegions, 0);

            SpatialDomains::BoundaryConditions bcs(m_session,
                                                    pFields[0]->GetGraph());
            const SpatialDomains::BoundaryRegionCollection &bregions =
                                                    bcs.GetBoundaryRegions();
            SpatialDomains::BoundaryRegionCollection::const_iterator it;

            for (cnt = 0, it = bregions.begin(); it != bregions.end();
                    ++it, cnt++)
            {
                if ( std::find(m_boundaryRegionsIdList.begin(),
                               m_boundaryRegionsIdList.end(), it->first) !=
                        m_boundaryRegionsIdList.end() )
                {
                    m_boundaryRegionIsInList[cnt] = 1;
                }
            }

            LibUtilities::CommSharedPtr vComm = pFields[0]->GetComm();

            if (vComm->GetRank() == 0)
            {
                // Open output stream
                m_outputStream.open(m_outputFile.c_str());
                m_outputStream << "#";
                m_outputStream.width(7);
                m_outputStream << "Time";
                m_outputStream.width(25);
                m_outputStream << "Fx (press)";
                m_outputStream.width(25);
                m_outputStream << "Fx (visc)";
                m_outputStream.width(25);
                m_outputStream << "Fx (tot)";
                m_outputStream.width(25);
                m_outputStream << "Fy (press)";
                m_outputStream.width(25);
                m_outputStream << "Fy (visc)";
                m_outputStream.width(25);
                m_outputStream << "Fy (tot)";
                m_outputStream.width(25);
                m_outputStream << "Fz (press)";
                m_outputStream.width(25);
                m_outputStream << "Fz (visc)";
                m_outputStream.width(25);
                m_outputStream << "Fz (tot)";
                m_outputStream << endl;
            }

            v_Update(pFields, time);
        }
示例#6
0
/* Generate interrupts */
static void Interrupt(void)
{
	/* the 6805 latches interrupt requests internally, so we don't clear */
	/* pending_interrupts until the interrupt is taken, no matter what the */
	/* external IRQ pin does. */

#if (1) //HAS_HD63705)
	if( (m6805.pending_interrupts & (1<<HD63705_INT_NMI)) != 0)
	{
		PUSHWORD(m6805.pc);
		PUSHBYTE(m6805.x);
		PUSHBYTE(m6805.a);
		PUSHBYTE(m6805.cc);
        SEI;
		/* no vectors supported, just do the callback to clear irq_state if needed */
		if (m6805.irq_callback)
			(*m6805.irq_callback)(0);

		RM16( 0x1ffc, &pPC);
		change_pc(PC);
		m6805.pending_interrupts &= ~(1<<HD63705_INT_NMI);

		m6805_ICount -= 11;

	}
	else if( (m6805.pending_interrupts & ((1<<M6805_IRQ_LINE)|HD63705_INT_MASK)) != 0 ) {
		if ( (CC & IFLAG) == 0 ) {
#else
	if( (m6805.pending_interrupts & (1<<M6805_IRQ_LINE)) != 0 ) {
		if ( (CC & IFLAG) == 0 ) {
#endif
	{
        /* standard IRQ */
//#if (HAS_HD63705)
//      if(SUBTYPE!=SUBTYPE_HD63705)
//#endif
//          PC |= ~AMASK;
		PUSHWORD(m6805.pc);
		PUSHBYTE(m6805.x);
		PUSHBYTE(m6805.a);
		PUSHBYTE(m6805.cc);
        SEI;
		/* no vectors supported, just do the callback to clear irq_state if needed */
		if (m6805.irq_callback)
			(*m6805.irq_callback)(0);


//#if (HAS_HD63705)
		if(SUBTYPE==SUBTYPE_HD63705)
		{
			/* Need to add emulation of other interrupt sources here KW-2/4/99 */
			/* This is just a quick patch for Namco System 2 operation         */

			if((m6805.pending_interrupts&(1<<HD63705_INT_IRQ1))!=0)
			{
				m6805.pending_interrupts &= ~(1<<HD63705_INT_IRQ1);
				RM16( 0x1ff8, &pPC);
				change_pc(PC);
			}
			else if((m6805.pending_interrupts&(1<<HD63705_INT_IRQ2))!=0)
			{
				m6805.pending_interrupts &= ~(1<<HD63705_INT_IRQ2);
				RM16( 0x1fec, &pPC);
				change_pc(PC);
			}
			else if((m6805.pending_interrupts&(1<<HD63705_INT_ADCONV))!=0)
			{
				m6805.pending_interrupts &= ~(1<<HD63705_INT_ADCONV);
				RM16( 0x1fea, &pPC);
				change_pc(PC);
			}
			else if((m6805.pending_interrupts&(1<<HD63705_INT_TIMER1))!=0)
			{
				m6805.pending_interrupts &= ~(1<<HD63705_INT_TIMER1);
				RM16( 0x1ff6, &pPC);
				change_pc(PC);
			}
			else if((m6805.pending_interrupts&(1<<HD63705_INT_TIMER2))!=0)
			{
				m6805.pending_interrupts &= ~(1<<HD63705_INT_TIMER2);
				RM16( 0x1ff4, &pPC);
				change_pc(PC);
			}
			else if((m6805.pending_interrupts&(1<<HD63705_INT_TIMER3))!=0)
			{
				m6805.pending_interrupts &= ~(1<<HD63705_INT_TIMER3);
				RM16( 0x1ff2, &pPC);
				change_pc(PC);
			}
			else if((m6805.pending_interrupts&(1<<HD63705_INT_PCI))!=0)
			{
				m6805.pending_interrupts &= ~(1<<HD63705_INT_PCI);
				RM16( 0x1ff0, &pPC);
				change_pc(PC);
			}
			else if((m6805.pending_interrupts&(1<<HD63705_INT_SCI))!=0)
			{
				m6805.pending_interrupts &= ~(1<<HD63705_INT_SCI);
				RM16( 0x1fee, &pPC);
				change_pc(PC);
			}
		}
		else
//#endif
		{
			RM16( 0xffff - 5, &pPC );
			change_pc(PC);
		}

		}	// CC & IFLAG
			m6805.pending_interrupts &= ~(1<<M6805_IRQ_LINE);
		}
		m6805_ICount -= 11;
	}
}

static void m6805_reset()
{
	int (*save_irqcallback)(int) = m6805.irq_callback;
	memset(&m6805, 0, sizeof(m6805));
	m6805.irq_callback = save_irqcallback;
	/* Force CPU sub-type and relevant masks */
	m6805.subtype	= SUBTYPE_M6805;
	SP_MASK = 0x07f;
	SP_LOW	= 0x060;
	/* Initial stack pointer */
	S = SP_MASK;
	/* IRQ disabled */
    SEI;
	RM16( 0xfffe , &pPC );
	change_pc(PC);
}

void m6805Reset() {
	m6805_reset();
}

//static void m6805_init(int ) //int (*irqcallback)(int))
//{
//	m6805.irq_callback = irqcallback;
//}

//static void m6805_exit(void)
//{
//	/* nothing to do */
//}


void m6805SetIrqLine(int , int state)
{
	/* Basic 6805 only has one IRQ line */
	/* See HD63705 specific version     */
	if (m6805.irq_state[0] == state) return;

	m6805.irq_state[0] = state;
	if (state != CLEAR_LINE)
		m6805.pending_interrupts |= 1<<M6805_IRQ_LINE;
}


#include "6805ops.c"


/* execute instructions on this CPU until icount expires */
int m6805Run(int cycles)
{
	UINT8 ireg;
	m6805_ICount = cycles;

	do
	{
		if (m6805.pending_interrupts != 0)
		{
			if (SUBTYPE==SUBTYPE_M68705)
			{
				m68705_Interrupt();
			}
			else
			{
				Interrupt();
			}
		}

		ireg=M_RDOP(PC++);

		switch( ireg )
		{
			case 0x00: brset(0x01); break;
			case 0x01: brclr(0x01); break;
			case 0x02: brset(0x02); break;
			case 0x03: brclr(0x02); break;
			case 0x04: brset(0x04); break;
			case 0x05: brclr(0x04); break;
			case 0x06: brset(0x08); break;
			case 0x07: brclr(0x08); break;
			case 0x08: brset(0x10); break;
			case 0x09: brclr(0x10); break;
			case 0x0A: brset(0x20); break;
			case 0x0B: brclr(0x20); break;
			case 0x0C: brset(0x40); break;
			case 0x0D: brclr(0x40); break;
			case 0x0E: brset(0x80); break;
			case 0x0F: brclr(0x80); break;
			case 0x10: bset(0x01); break;
			case 0x11: bclr(0x01); break;
			case 0x12: bset(0x02); break;
			case 0x13: bclr(0x02); break;
			case 0x14: bset(0x04); break;
			case 0x15: bclr(0x04); break;
			case 0x16: bset(0x08); break;
			case 0x17: bclr(0x08); break;
			case 0x18: bset(0x10); break;
			case 0x19: bclr(0x10); break;
			case 0x1a: bset(0x20); break;
			case 0x1b: bclr(0x20); break;
			case 0x1c: bset(0x40); break;
			case 0x1d: bclr(0x40); break;
			case 0x1e: bset(0x80); break;
			case 0x1f: bclr(0x80); break;
			case 0x20: bra(); break;
			case 0x21: brn(); break;
			case 0x22: bhi(); break;
			case 0x23: bls(); break;
			case 0x24: bcc(); break;
			case 0x25: bcs(); break;
			case 0x26: bne(); break;
			case 0x27: beq(); break;
			case 0x28: bhcc(); break;
			case 0x29: bhcs(); break;
			case 0x2a: bpl(); break;
			case 0x2b: bmi(); break;
			case 0x2c: bmc(); break;
			case 0x2d: bms(); break;
			case 0x2e: bil(); break;
			case 0x2f: bih(); break;
			case 0x30: neg_di(); break;
			case 0x31: illegal(); break;
			case 0x32: illegal(); break;
			case 0x33: com_di(); break;
			case 0x34: lsr_di(); break;
			case 0x35: illegal(); break;
			case 0x36: ror_di(); break;
			case 0x37: asr_di(); break;
			case 0x38: lsl_di(); break;
			case 0x39: rol_di(); break;
			case 0x3a: dec_di(); break;
			case 0x3b: illegal(); break;
			case 0x3c: inc_di(); break;
			case 0x3d: tst_di(); break;
			case 0x3e: illegal(); break;
			case 0x3f: clr_di(); break;
			case 0x40: nega(); break;
			case 0x41: illegal(); break;
			case 0x42: illegal(); break;
			case 0x43: coma(); break;
			case 0x44: lsra(); break;
			case 0x45: illegal(); break;
			case 0x46: rora(); break;
			case 0x47: asra(); break;
			case 0x48: lsla(); break;
			case 0x49: rola(); break;
			case 0x4a: deca(); break;
			case 0x4b: illegal(); break;
			case 0x4c: inca(); break;
			case 0x4d: tsta(); break;
			case 0x4e: illegal(); break;
			case 0x4f: clra(); break;
			case 0x50: negx(); break;
			case 0x51: illegal(); break;
			case 0x52: illegal(); break;
			case 0x53: comx(); break;
			case 0x54: lsrx(); break;
			case 0x55: illegal(); break;
			case 0x56: rorx(); break;
			case 0x57: asrx(); break;
			case 0x58: aslx(); break;
			case 0x59: rolx(); break;
			case 0x5a: decx(); break;
			case 0x5b: illegal(); break;
			case 0x5c: incx(); break;
			case 0x5d: tstx(); break;
			case 0x5e: illegal(); break;
			case 0x5f: clrx(); break;
			case 0x60: neg_ix1(); break;
			case 0x61: illegal(); break;
			case 0x62: illegal(); break;
			case 0x63: com_ix1(); break;
			case 0x64: lsr_ix1(); break;
			case 0x65: illegal(); break;
			case 0x66: ror_ix1(); break;
			case 0x67: asr_ix1(); break;
			case 0x68: lsl_ix1(); break;
			case 0x69: rol_ix1(); break;
			case 0x6a: dec_ix1(); break;
			case 0x6b: illegal(); break;
			case 0x6c: inc_ix1(); break;
			case 0x6d: tst_ix1(); break;
			case 0x6e: illegal(); break;
			case 0x6f: clr_ix1(); break;
			case 0x70: neg_ix(); break;
			case 0x71: illegal(); break;
			case 0x72: illegal(); break;
			case 0x73: com_ix(); break;
			case 0x74: lsr_ix(); break;
			case 0x75: illegal(); break;
			case 0x76: ror_ix(); break;
			case 0x77: asr_ix(); break;
			case 0x78: lsl_ix(); break;
			case 0x79: rol_ix(); break;
			case 0x7a: dec_ix(); break;
			case 0x7b: illegal(); break;
			case 0x7c: inc_ix(); break;
			case 0x7d: tst_ix(); break;
			case 0x7e: illegal(); break;
			case 0x7f: clr_ix(); break;
			case 0x80: rti(); break;
			case 0x81: rts(); break;
			case 0x82: illegal(); break;
			case 0x83: swi(); break;
			case 0x84: illegal(); break;
			case 0x85: illegal(); break;
			case 0x86: illegal(); break;
			case 0x87: illegal(); break;
			case 0x88: illegal(); break;
			case 0x89: illegal(); break;
			case 0x8a: illegal(); break;
			case 0x8b: illegal(); break;
			case 0x8c: illegal(); break;
			case 0x8d: illegal(); break;
			case 0x8e: illegal(); break;
			case 0x8f: illegal(); break;
			case 0x90: illegal(); break;
			case 0x91: illegal(); break;
			case 0x92: illegal(); break;
			case 0x93: illegal(); break;
			case 0x94: illegal(); break;
			case 0x95: illegal(); break;
			case 0x96: illegal(); break;
			case 0x97: tax(); break;
			case 0x98: CLC; break;
			case 0x99: SEC; break;
#if IRQ_LEVEL_DETECT
			case 0x9a: CLI; if (m6805.irq_state != CLEAR_LINE) m6805.pending_interrupts |= 1<<M6805_IRQ_LINE; break;
#else
			case 0x9a: CLI; break;
#endif
			case 0x9b: SEI; break;
			case 0x9c: rsp(); break;
			case 0x9d: nop(); break;
			case 0x9e: illegal(); break;
			case 0x9f: txa(); break;
			case 0xa0: suba_im(); break;
			case 0xa1: cmpa_im(); break;
			case 0xa2: sbca_im(); break;
			case 0xa3: cpx_im(); break;
			case 0xa4: anda_im(); break;
			case 0xa5: bita_im(); break;
			case 0xa6: lda_im(); break;
			case 0xa7: illegal(); break;
			case 0xa8: eora_im(); break;
			case 0xa9: adca_im(); break;
			case 0xaa: ora_im(); break;
			case 0xab: adda_im(); break;
			case 0xac: illegal(); break;
			case 0xad: bsr(); break;
			case 0xae: ldx_im(); break;
			case 0xaf: illegal(); break;
			case 0xb0: suba_di(); break;
			case 0xb1: cmpa_di(); break;
			case 0xb2: sbca_di(); break;
			case 0xb3: cpx_di(); break;
			case 0xb4: anda_di(); break;
			case 0xb5: bita_di(); break;
			case 0xb6: lda_di(); break;
			case 0xb7: sta_di(); break;
			case 0xb8: eora_di(); break;
			case 0xb9: adca_di(); break;
			case 0xba: ora_di(); break;
			case 0xbb: adda_di(); break;
			case 0xbc: jmp_di(); break;
			case 0xbd: jsr_di(); break;
			case 0xbe: ldx_di(); break;
			case 0xbf: stx_di(); break;
			case 0xc0: suba_ex(); break;
			case 0xc1: cmpa_ex(); break;
			case 0xc2: sbca_ex(); break;
			case 0xc3: cpx_ex(); break;
			case 0xc4: anda_ex(); break;
			case 0xc5: bita_ex(); break;
			case 0xc6: lda_ex(); break;
			case 0xc7: sta_ex(); break;
			case 0xc8: eora_ex(); break;
			case 0xc9: adca_ex(); break;
			case 0xca: ora_ex(); break;
			case 0xcb: adda_ex(); break;
			case 0xcc: jmp_ex(); break;
			case 0xcd: jsr_ex(); break;
			case 0xce: ldx_ex(); break;
			case 0xcf: stx_ex(); break;
			case 0xd0: suba_ix2(); break;
			case 0xd1: cmpa_ix2(); break;
			case 0xd2: sbca_ix2(); break;
			case 0xd3: cpx_ix2(); break;
			case 0xd4: anda_ix2(); break;
			case 0xd5: bita_ix2(); break;
			case 0xd6: lda_ix2(); break;
			case 0xd7: sta_ix2(); break;
			case 0xd8: eora_ix2(); break;
			case 0xd9: adca_ix2(); break;
			case 0xda: ora_ix2(); break;
			case 0xdb: adda_ix2(); break;
			case 0xdc: jmp_ix2(); break;
			case 0xdd: jsr_ix2(); break;
			case 0xde: ldx_ix2(); break;
			case 0xdf: stx_ix2(); break;
			case 0xe0: suba_ix1(); break;
			case 0xe1: cmpa_ix1(); break;
			case 0xe2: sbca_ix1(); break;
			case 0xe3: cpx_ix1(); break;
			case 0xe4: anda_ix1(); break;
			case 0xe5: bita_ix1(); break;
			case 0xe6: lda_ix1(); break;
			case 0xe7: sta_ix1(); break;
			case 0xe8: eora_ix1(); break;
			case 0xe9: adca_ix1(); break;
			case 0xea: ora_ix1(); break;
			case 0xeb: adda_ix1(); break;
			case 0xec: jmp_ix1(); break;
			case 0xed: jsr_ix1(); break;
			case 0xee: ldx_ix1(); break;
			case 0xef: stx_ix1(); break;
			case 0xf0: suba_ix(); break;
			case 0xf1: cmpa_ix(); break;
			case 0xf2: sbca_ix(); break;
			case 0xf3: cpx_ix(); break;
			case 0xf4: anda_ix(); break;
			case 0xf5: bita_ix(); break;
			case 0xf6: lda_ix(); break;
			case 0xf7: sta_ix(); break;
			case 0xf8: eora_ix(); break;
			case 0xf9: adca_ix(); break;
			case 0xfa: ora_ix(); break;
			case 0xfb: adda_ix(); break;
			case 0xfc: jmp_ix(); break;
			case 0xfd: jsr_ix(); break;
			case 0xfe: ldx_ix(); break;
			case 0xff: stx_ix(); break;
		}
		m6805_ICount -= cycles1[ireg];
		m6805.nTotalCycles += cycles1[ireg];
	} while( m6805_ICount > 0 );

	return cycles - m6805_ICount;
}
示例#7
0
int main(int argc, char* argv[])
{
  // Instantiate a class with global functions.
  Hermes2D hermes2d;

  // Load the mesh.
  Mesh mesh;
  H2DReader mloader;
  mloader.load("../domain.mesh", &mesh);

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

  // Initialize the weak formulation.
  CustomWeakFormPoisson wf("Aluminum", new HermesFunction(LAMBDA_AL), "Copper", 
                           new HermesFunction(LAMBDA_CU), new HermesFunction(-VOLUME_HEAT_SRC));
  
  // Initialize boundary conditions.
  DefaultEssentialBCConst bc_essential(Hermes::vector<std::string>("Bottom", "Inner", "Outer", "Left"), 
                                       FIXED_BDY_TEMP);
  EssentialBCs bcs(&bc_essential);

  // Create an H1 space with default shapeset.
  H1Space space(&mesh, &bcs, P_INIT);
  int ndof = space.get_num_dofs();
  info("ndof = %d", ndof);

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

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

  // Initial coefficient vector for the Newton's method.  
  scalar* coeff_vec = new scalar[ndof];
  memset(coeff_vec, 0, ndof*sizeof(scalar));

  // Perform Newton's iteration.
  if (!hermes2d.solve_newton(coeff_vec, &dp, solver, matrix, rhs)) error("Newton's iteration failed.");

  // Translate the resulting coefficient vector into the Solution sln.
  Solution sln;
  Solution::vector_to_solution(coeff_vec, &space, &sln);

  // Actual test. The values of 'sum' depend on the
  // current shapeset. If you change the shapeset,
  // you need to correct these numbers.
  double sum = 0;
  for (int i=0; i < ndof; i++) sum += coeff_vec[i];
  printf("coefficient sum = %g\n", sum);

  bool success = true;
  if (std::abs(sum + 0.357318) > 1e-4) success = false;

  if (success == true) {
    printf("Success!\n");
    return ERR_SUCCESS;
  }
  else {
    printf("Failure!\n");
    return ERR_FAILURE;
  }
}
示例#8
0
/* execute instructions on this CPU until icount expires */
static CPU_EXECUTE( m6809 )	/* NS 970908 */
{
	m68_state_t *m68_state = get_safe_token(device);

    m68_state->icount = cycles - m68_state->extra_cycles;
	m68_state->extra_cycles = 0;

	check_irq_lines(m68_state);

	if (m68_state->int_state & (M6809_CWAI | M6809_SYNC))
	{
		debugger_instruction_hook(device, PCD);
		m68_state->icount = 0;
	}
	else
	{
		do
		{
			pPPC = pPC;

			debugger_instruction_hook(device, PCD);

			m68_state->ireg = ROP(PCD);
			PC++;
#if BIG_SWITCH
            switch( m68_state->ireg )
			{
			case 0x00: neg_di(m68_state);    break;
			case 0x01: neg_di(m68_state);    break;	/* undocumented */
			case 0x02: IIError(m68_state);   break;
			case 0x03: com_di(m68_state);    break;
			case 0x04: lsr_di(m68_state);    break;
			case 0x05: IIError(m68_state);   break;
			case 0x06: ror_di(m68_state);    break;
			case 0x07: asr_di(m68_state);    break;
			case 0x08: asl_di(m68_state);    break;
			case 0x09: rol_di(m68_state);    break;
			case 0x0a: dec_di(m68_state);    break;
			case 0x0b: IIError(m68_state);   break;
			case 0x0c: inc_di(m68_state);    break;
			case 0x0d: tst_di(m68_state);    break;
			case 0x0e: jmp_di(m68_state);    break;
			case 0x0f: clr_di(m68_state);    break;
			case 0x10: pref10(m68_state);					 break;
			case 0x11: pref11(m68_state);					 break;
			case 0x12: nop(m68_state);	    break;
			case 0x13: sync(m68_state);	    break;
			case 0x14: IIError(m68_state);   break;
			case 0x15: IIError(m68_state);   break;
			case 0x16: lbra(m68_state);	    break;
			case 0x17: lbsr(m68_state);	    break;
			case 0x18: IIError(m68_state);   break;
			case 0x19: daa(m68_state);	    break;
			case 0x1a: orcc(m68_state);	    break;
			case 0x1b: IIError(m68_state);   break;
			case 0x1c: andcc(m68_state);     break;
			case 0x1d: sex(m68_state);	    break;
			case 0x1e: exg(m68_state);	    break;
			case 0x1f: tfr(m68_state);	    break;
			case 0x20: bra(m68_state);	    break;
			case 0x21: brn(m68_state);	    break;
			case 0x22: bhi(m68_state);	    break;
			case 0x23: bls(m68_state);	    break;
			case 0x24: bcc(m68_state);	    break;
			case 0x25: bcs(m68_state);	    break;
			case 0x26: bne(m68_state);	    break;
			case 0x27: beq(m68_state);	    break;
			case 0x28: bvc(m68_state);	    break;
			case 0x29: bvs(m68_state);	    break;
			case 0x2a: bpl(m68_state);	    break;
			case 0x2b: bmi(m68_state);	    break;
			case 0x2c: bge(m68_state);	    break;
			case 0x2d: blt(m68_state);	    break;
			case 0x2e: bgt(m68_state);	    break;
			case 0x2f: ble(m68_state);	    break;
			case 0x30: leax(m68_state);	    break;
			case 0x31: leay(m68_state);	    break;
			case 0x32: leas(m68_state);	    break;
			case 0x33: leau(m68_state);	    break;
			case 0x34: pshs(m68_state);	    break;
			case 0x35: puls(m68_state);	    break;
			case 0x36: pshu(m68_state);	    break;
			case 0x37: pulu(m68_state);	    break;
			case 0x38: IIError(m68_state);   break;
			case 0x39: rts(m68_state);	    break;
			case 0x3a: abx(m68_state);	    break;
			case 0x3b: rti(m68_state);	    break;
			case 0x3c: cwai(m68_state);	    break;
			case 0x3d: mul(m68_state);	    break;
			case 0x3e: IIError(m68_state);   break;
			case 0x3f: swi(m68_state);	    break;
			case 0x40: nega(m68_state);	    break;
			case 0x41: IIError(m68_state);   break;
			case 0x42: IIError(m68_state);   break;
			case 0x43: coma(m68_state);	    break;
			case 0x44: lsra(m68_state);	    break;
			case 0x45: IIError(m68_state);   break;
			case 0x46: rora(m68_state);	    break;
			case 0x47: asra(m68_state);	    break;
			case 0x48: asla(m68_state);	    break;
			case 0x49: rola(m68_state);	    break;
			case 0x4a: deca(m68_state);	    break;
			case 0x4b: IIError(m68_state);   break;
			case 0x4c: inca(m68_state);	    break;
			case 0x4d: tsta(m68_state);	    break;
			case 0x4e: IIError(m68_state);   break;
			case 0x4f: clra(m68_state);	    break;
			case 0x50: negb(m68_state);	    break;
			case 0x51: IIError(m68_state);   break;
			case 0x52: IIError(m68_state);   break;
			case 0x53: comb(m68_state);	    break;
			case 0x54: lsrb(m68_state);	    break;
			case 0x55: IIError(m68_state);   break;
			case 0x56: rorb(m68_state);	    break;
			case 0x57: asrb(m68_state);	    break;
			case 0x58: aslb(m68_state);	    break;
			case 0x59: rolb(m68_state);	    break;
			case 0x5a: decb(m68_state);	    break;
			case 0x5b: IIError(m68_state);   break;
			case 0x5c: incb(m68_state);	    break;
			case 0x5d: tstb(m68_state);	    break;
			case 0x5e: IIError(m68_state);   break;
			case 0x5f: clrb(m68_state);	    break;
			case 0x60: neg_ix(m68_state);    break;
			case 0x61: IIError(m68_state);   break;
			case 0x62: IIError(m68_state);   break;
			case 0x63: com_ix(m68_state);    break;
			case 0x64: lsr_ix(m68_state);    break;
			case 0x65: IIError(m68_state);   break;
			case 0x66: ror_ix(m68_state);    break;
			case 0x67: asr_ix(m68_state);    break;
			case 0x68: asl_ix(m68_state);    break;
			case 0x69: rol_ix(m68_state);    break;
			case 0x6a: dec_ix(m68_state);    break;
			case 0x6b: IIError(m68_state);   break;
			case 0x6c: inc_ix(m68_state);    break;
			case 0x6d: tst_ix(m68_state);    break;
			case 0x6e: jmp_ix(m68_state);    break;
			case 0x6f: clr_ix(m68_state);    break;
			case 0x70: neg_ex(m68_state);    break;
			case 0x71: IIError(m68_state);   break;
			case 0x72: IIError(m68_state);   break;
			case 0x73: com_ex(m68_state);    break;
			case 0x74: lsr_ex(m68_state);    break;
			case 0x75: IIError(m68_state);   break;
			case 0x76: ror_ex(m68_state);    break;
			case 0x77: asr_ex(m68_state);    break;
			case 0x78: asl_ex(m68_state);    break;
			case 0x79: rol_ex(m68_state);    break;
			case 0x7a: dec_ex(m68_state);    break;
			case 0x7b: IIError(m68_state);   break;
			case 0x7c: inc_ex(m68_state);    break;
			case 0x7d: tst_ex(m68_state);    break;
			case 0x7e: jmp_ex(m68_state);    break;
			case 0x7f: clr_ex(m68_state);    break;
			case 0x80: suba_im(m68_state);   break;
			case 0x81: cmpa_im(m68_state);   break;
			case 0x82: sbca_im(m68_state);   break;
			case 0x83: subd_im(m68_state);   break;
			case 0x84: anda_im(m68_state);   break;
			case 0x85: bita_im(m68_state);   break;
			case 0x86: lda_im(m68_state);    break;
			case 0x87: sta_im(m68_state);    break;
			case 0x88: eora_im(m68_state);   break;
			case 0x89: adca_im(m68_state);   break;
			case 0x8a: ora_im(m68_state);    break;
			case 0x8b: adda_im(m68_state);   break;
			case 0x8c: cmpx_im(m68_state);   break;
			case 0x8d: bsr(m68_state);	    break;
			case 0x8e: ldx_im(m68_state);    break;
			case 0x8f: stx_im(m68_state);    break;
			case 0x90: suba_di(m68_state);   break;
			case 0x91: cmpa_di(m68_state);   break;
			case 0x92: sbca_di(m68_state);   break;
			case 0x93: subd_di(m68_state);   break;
			case 0x94: anda_di(m68_state);   break;
			case 0x95: bita_di(m68_state);   break;
			case 0x96: lda_di(m68_state);    break;
			case 0x97: sta_di(m68_state);    break;
			case 0x98: eora_di(m68_state);   break;
			case 0x99: adca_di(m68_state);   break;
			case 0x9a: ora_di(m68_state);    break;
			case 0x9b: adda_di(m68_state);   break;
			case 0x9c: cmpx_di(m68_state);   break;
			case 0x9d: jsr_di(m68_state);    break;
			case 0x9e: ldx_di(m68_state);    break;
			case 0x9f: stx_di(m68_state);    break;
			case 0xa0: suba_ix(m68_state);   break;
			case 0xa1: cmpa_ix(m68_state);   break;
			case 0xa2: sbca_ix(m68_state);   break;
			case 0xa3: subd_ix(m68_state);   break;
			case 0xa4: anda_ix(m68_state);   break;
			case 0xa5: bita_ix(m68_state);   break;
			case 0xa6: lda_ix(m68_state);    break;
			case 0xa7: sta_ix(m68_state);    break;
			case 0xa8: eora_ix(m68_state);   break;
			case 0xa9: adca_ix(m68_state);   break;
			case 0xaa: ora_ix(m68_state);    break;
			case 0xab: adda_ix(m68_state);   break;
			case 0xac: cmpx_ix(m68_state);   break;
			case 0xad: jsr_ix(m68_state);    break;
			case 0xae: ldx_ix(m68_state);    break;
			case 0xaf: stx_ix(m68_state);    break;
			case 0xb0: suba_ex(m68_state);   break;
			case 0xb1: cmpa_ex(m68_state);   break;
			case 0xb2: sbca_ex(m68_state);   break;
			case 0xb3: subd_ex(m68_state);   break;
			case 0xb4: anda_ex(m68_state);   break;
			case 0xb5: bita_ex(m68_state);   break;
			case 0xb6: lda_ex(m68_state);    break;
			case 0xb7: sta_ex(m68_state);    break;
			case 0xb8: eora_ex(m68_state);   break;
			case 0xb9: adca_ex(m68_state);   break;
			case 0xba: ora_ex(m68_state);    break;
			case 0xbb: adda_ex(m68_state);   break;
			case 0xbc: cmpx_ex(m68_state);   break;
			case 0xbd: jsr_ex(m68_state);    break;
			case 0xbe: ldx_ex(m68_state);    break;
			case 0xbf: stx_ex(m68_state);    break;
			case 0xc0: subb_im(m68_state);   break;
			case 0xc1: cmpb_im(m68_state);   break;
			case 0xc2: sbcb_im(m68_state);   break;
			case 0xc3: addd_im(m68_state);   break;
			case 0xc4: andb_im(m68_state);   break;
			case 0xc5: bitb_im(m68_state);   break;
			case 0xc6: ldb_im(m68_state);    break;
			case 0xc7: stb_im(m68_state);    break;
			case 0xc8: eorb_im(m68_state);   break;
			case 0xc9: adcb_im(m68_state);   break;
			case 0xca: orb_im(m68_state);    break;
			case 0xcb: addb_im(m68_state);   break;
			case 0xcc: ldd_im(m68_state);    break;
			case 0xcd: std_im(m68_state);    break;
			case 0xce: ldu_im(m68_state);    break;
			case 0xcf: stu_im(m68_state);    break;
			case 0xd0: subb_di(m68_state);   break;
			case 0xd1: cmpb_di(m68_state);   break;
			case 0xd2: sbcb_di(m68_state);   break;
			case 0xd3: addd_di(m68_state);   break;
			case 0xd4: andb_di(m68_state);   break;
			case 0xd5: bitb_di(m68_state);   break;
			case 0xd6: ldb_di(m68_state);    break;
			case 0xd7: stb_di(m68_state);    break;
			case 0xd8: eorb_di(m68_state);   break;
			case 0xd9: adcb_di(m68_state);   break;
			case 0xda: orb_di(m68_state);    break;
			case 0xdb: addb_di(m68_state);   break;
			case 0xdc: ldd_di(m68_state);    break;
			case 0xdd: std_di(m68_state);    break;
			case 0xde: ldu_di(m68_state);    break;
			case 0xdf: stu_di(m68_state);    break;
			case 0xe0: subb_ix(m68_state);   break;
			case 0xe1: cmpb_ix(m68_state);   break;
			case 0xe2: sbcb_ix(m68_state);   break;
			case 0xe3: addd_ix(m68_state);   break;
			case 0xe4: andb_ix(m68_state);   break;
			case 0xe5: bitb_ix(m68_state);   break;
			case 0xe6: ldb_ix(m68_state);    break;
			case 0xe7: stb_ix(m68_state);    break;
			case 0xe8: eorb_ix(m68_state);   break;
			case 0xe9: adcb_ix(m68_state);   break;
			case 0xea: orb_ix(m68_state);    break;
			case 0xeb: addb_ix(m68_state);   break;
			case 0xec: ldd_ix(m68_state);    break;
			case 0xed: std_ix(m68_state);    break;
			case 0xee: ldu_ix(m68_state);    break;
			case 0xef: stu_ix(m68_state);    break;
			case 0xf0: subb_ex(m68_state);   break;
			case 0xf1: cmpb_ex(m68_state);   break;
			case 0xf2: sbcb_ex(m68_state);   break;
			case 0xf3: addd_ex(m68_state);   break;
			case 0xf4: andb_ex(m68_state);   break;
			case 0xf5: bitb_ex(m68_state);   break;
			case 0xf6: ldb_ex(m68_state);    break;
			case 0xf7: stb_ex(m68_state);    break;
			case 0xf8: eorb_ex(m68_state);   break;
			case 0xf9: adcb_ex(m68_state);   break;
			case 0xfa: orb_ex(m68_state);    break;
			case 0xfb: addb_ex(m68_state);   break;
			case 0xfc: ldd_ex(m68_state);    break;
			case 0xfd: std_ex(m68_state);    break;
			case 0xfe: ldu_ex(m68_state);    break;
			case 0xff: stu_ex(m68_state);    break;
			}
#else
            		(*m6809_main[m68_state->ireg])(m68_state);
#endif    /* BIG_SWITCH */
        		m68_state->icount -= cycles1[m68_state->ireg];

		} while( m68_state->icount > 0 );

        m68_state->icount -= m68_state->extra_cycles;
		m68_state->extra_cycles = 0;
    }

    return cycles - m68_state->icount;   /* NS 970908 */
}
示例#9
0
/* Creates the rubinius object universe from scratch. */
void cpu_bootstrap(STATE) {
  OBJECT cls, obj, tmp, tmp2;
  int i;

  /* Class is created first by hand, and twittle to setup the internal
     recursion. */
  cls = NEW_OBJECT(Qnil, CLASS_FIELDS);
  cls->klass = cls;
  class_set_instance_fields(cls, I2N(CLASS_FIELDS));
  class_set_has_ivars(cls, Qtrue);
  class_set_object_type(cls, I2N(ClassType));
  cls->obj_type = ClassType;
  
  BC(class) = cls;
  obj = _object_basic_class(state, Qnil);
  BC(object) = obj;
  BC(module) = _module_basic_class(state, obj);
  class_set_superclass(cls, BC(module));
  BC(metaclass) = _metaclass_basic_class(state, cls);
  class_set_object_type(BC(metaclass), I2N(MetaclassType));
  
  BC(tuple) = _tuple_basic_class(state, obj);
  BC(hash) =  _hash_basic_class(state, obj);
  BC(lookuptable) = _lookuptable_basic_class(state, obj);
  BC(methtbl) = _methtbl_basic_class(state, BC(lookuptable));
  
  object_create_metaclass(state, obj, cls);
  object_create_metaclass(state, BC(module), object_metaclass(state, obj));
  object_create_metaclass(state, BC(class), object_metaclass(state, BC(module)));
  
  object_create_metaclass(state, BC(tuple), (OBJECT)0);
  object_create_metaclass(state, BC(hash), (OBJECT)0);
  object_create_metaclass(state, BC(lookuptable), (OBJECT)0);
  object_create_metaclass(state, BC(methtbl), (OBJECT)0);
  
  module_setup_fields(state, object_metaclass(state, obj));
  module_setup_fields(state, object_metaclass(state, BC(module)));
  module_setup_fields(state, object_metaclass(state, BC(class)));
  module_setup_fields(state, object_metaclass(state, BC(tuple)));
  module_setup_fields(state, object_metaclass(state, BC(hash)));
  module_setup_fields(state, object_metaclass(state, BC(lookuptable)));
  module_setup_fields(state, object_metaclass(state, BC(methtbl)));
  BC(symbol) = _symbol_class(state, obj);
  BC(array) = _array_class(state, obj);
  BC(bytearray) = _bytearray_class(state, obj);
  BC(string) = _string_class(state, obj);
  BC(symtbl) = _symtbl_class(state, obj);
  BC(cmethod) = _cmethod_class(state, obj);
  BC(io) = _io_class(state, obj);
  BC(blokenv) = _blokenv_class(state, obj);
  BC(icache) = _icache_class(state, obj);
  BC(staticscope) = _staticscope_class(state, obj);
 
  class_set_object_type(BC(bytearray), I2N(ByteArrayType));
  class_set_object_type(BC(string), I2N(StringType));
  class_set_object_type(BC(methtbl), I2N(MTType));
  class_set_object_type(BC(tuple), I2N(TupleType));
  class_set_object_type(BC(hash), I2N(HashType));
  class_set_object_type(BC(lookuptable), I2N(LookupTableType));
  
  /* The symbol table */
  state->global->symbols = symtbl_new(state);
  
  module_setup(state, obj, "Object");
  module_setup(state, cls, "Class");
  module_setup(state, BC(module), "Module");
  module_setup(state, BC(metaclass), "MetaClass");
  module_setup(state, BC(symbol), "Symbol");
  module_setup(state, BC(tuple), "Tuple");
  module_setup(state, BC(array), "Array");
  module_setup(state, BC(bytearray), "ByteArray");
  module_setup(state, BC(hash), "Hash");
  module_setup(state, BC(lookuptable), "LookupTable");
  module_setup(state, BC(string), "String");
  module_setup(state, BC(symtbl), "SymbolTable");
  module_setup(state, BC(methtbl), "MethodTable");
  module_setup(state, BC(cmethod), "CompiledMethod");
  module_setup(state, BC(io), "IO");
  module_setup(state, BC(blokenv), "BlockEnvironment");
  module_setup(state, BC(icache), "InlineCache");
  module_setup(state, BC(staticscope), "StaticScope");
 
  class_set_object_type(BC(array), I2N(ArrayType));
  class_set_object_type(BC(cmethod), I2N(CMethodType));
  class_set_object_type(BC(blokenv), I2N(BlockEnvType));
    
  rbs_const_set(state, obj, "Symbols", state->global->symbols);
  BC(nil_class) = rbs_class_new(state, "NilClass", 0, obj);
  BC(true_class) = rbs_class_new(state, "TrueClass", 0, obj);
  BC(false_class) = rbs_class_new(state, "FalseClass", 0, obj);
  tmp = rbs_class_new(state, "Numeric", 0, obj);
  tmp2 = rbs_class_new(state, "Integer", 0, tmp);
  BC(fixnum_class) = rbs_class_new(state, "Fixnum", 0, tmp2);
  class_set_object_type(BC(fixnum_class), I2N(FixnumType));
  
  BC(bignum) = rbs_class_new(state, "Bignum", 0, tmp2);
  class_set_object_type(BC(bignum), I2N(BignumType));
  bignum_init(state);
  
  BC(floatpoint) = rbs_class_new(state, "Float", 0, tmp);
  class_set_object_type(BC(floatpoint), I2N(FloatType));
  
  BC(undef_class) = rbs_class_new(state, "UndefClass", 0, obj);
  BC(fastctx) = rbs_class_new(state, "MethodContext", 0, obj);
  BC(methctx) = BC(fastctx);
  BC(blokctx) = rbs_class_new(state, "BlockContext", 0, BC(fastctx));
  
  BC(task) = rbs_class_new(state, "Task", 0, obj);
  class_set_object_type(BC(task), I2N(TaskType));
  
  BC(iseq) = rbs_class_new(state, "InstructionSequence", 0, BC(bytearray));
  class_set_object_type(BC(iseq), I2N(ISeqType));

  #define bcs(name, sup, string) BC(name) = _ ## name ## _class(state, sup); \
    module_setup(state, BC(name), string);
  
  /* the special_classes C array is use do quickly calculate the class
     of an immediate by just indexing into the array using (obj & 0x1f) */
  
  /* fixnum, symbol, and custom can have a number of patterns below
     0x1f, so we fill them all. */
     
  for(i = 0; i < SPECIAL_CLASS_SIZE; i += 4) {
    state->global->special_classes[i + 0] = Qnil;
    state->global->special_classes[i + 1] = BC(fixnum_class);
    state->global->special_classes[i + 2] = Qnil;
    if(((i + 3) & 0x7) == 0x3) {
      state->global->special_classes[i + 3] = BC(symbol);
    } else {
      state->global->special_classes[i + 3] = CUSTOM_CLASS;
    }
  }
  
  /* These only have one value, so they only need one spot in
     the array */
  state->global->special_classes[(intptr_t)Qundef] = BC(undef_class);
  state->global->special_classes[(intptr_t)Qfalse] = BC(false_class);
  state->global->special_classes[(intptr_t)Qnil  ] = BC(nil_class);
  state->global->special_classes[(intptr_t)Qtrue ] = BC(true_class);
    
  bcs(regexp, obj, "Regexp");
  class_set_object_type(BC(regexp), I2N(RegexpType));
  bcs(regexpdata, obj, "RegexpData");
  class_set_object_type(BC(regexpdata), I2N(RegexpDataType));
  bcs(matchdata, obj, "MatchData");
      
  cpu_bootstrap_exceptions(state);
  
  rbs_module_new(state, "Rubinius", BC(object));
  
  Init_list(state);
  Init_cpu_task(state);
  Init_ffi(state);
  regexp_init(state);
  selector_init(state);
  send_site_init(state);
    
  rbs_const_set(state, 
        rbs_const_get(state, BASIC_CLASS(object), "Rubinius"),
        "Primitives",
        cpu_populate_prim_names(state));
  
  state->global->external_ivars = lookuptable_new(state);

}
示例#10
0
文件: call_dslash.C 项目: paboyle/BFM
void test_solver(BfmSolver solver,LatticeFermion &src)
{

  g5dParams parms;

  int Ls=8;
  double M5=1.8;
  double mq=0.01;
  double wilson_lo = 0.05;
  double wilson_hi = 6.8;
  double shamir_lo = 0.025;
  double shamir_hi = 1.7;
  double ht_scale=2.0;
  double hw_scale=1.0;

  if ( solver == HtCayleyTanh ) { 
    Printf("Testing HtCayleyTanh aka DWF\n");
    parms.ShamirCayleyTanh(mq,M5,Ls);
  } else if ( solver == HmCayleyTanh ) { 
    parms.ScaledShamirCayleyTanh(mq,M5,Ls,ht_scale);
    Printf("Testing HmCayleyTanh Moebius\n");
  } else if ( solver == HwCayleyTanh ) { 
    parms.WilsonCayleyTanh(mq,M5,Ls,hw_scale);
    Printf("Testing HwCayleyTanh aka Borici\n");
  } else { 
    exit(-1);
  }

  multi1d<LatticeColorMatrix> u(4);
  HotSt(u);

  multi1d<LatticeFermion> X(Ls);
  multi1d<LatticeFermion> Y(Ls);
  for(int s=0;s<Ls;s++){
    gaussian(X[s]);
    gaussian(Y[s]);
  }

  multi1d<LatticeColorMatrix> Fb(4);
  multi1d<LatticeColorMatrix> F (4);

  int lx = QDP::Layout::subgridLattSize()[0];
  int ly = QDP::Layout::subgridLattSize()[1];
  int lz = QDP::Layout::subgridLattSize()[2];
  int lt = QDP::Layout::subgridLattSize()[3];

  multi1d<int> procs = QDP::Layout::logicalSize();
  /********************************************************
   * Setup DWF operator
   ********************************************************
   */
  bfmarg  dwfa;
  dwfa.node_latt[0]  = lx;
  dwfa.node_latt[1]  = ly;
  dwfa.node_latt[2]  = lz;
  dwfa.node_latt[3]  = lt;
  for(int mu=0;mu<4;mu++){
    if ( procs[mu]>1 ) {
      dwfa.local_comm[mu] = 0;
    } else { 
      dwfa.local_comm[mu] = 1;
    }
  }

  bfm_qmp dwf_qmp;

  dwfa.mass = parms.mass;
  dwfa.M5   = parms.M5;
  dwfa.Csw = 0.0;
  dwfa.precon_5d=0;
  dwfa.residual=1.0e-5;
  dwfa.max_iter=5000;
  dwfa.Ls = parms.Ls;
  dwfa.solver= parms.solver;
  dwfa.zolo_lo   = parms.zolo_lo;
  dwfa.zolo_hi   = parms.zolo_hi;
  dwfa.mobius_scale = parms.mobius_scale;

  dwf_qmp.init(dwfa);
  dwf_qmp.importGauge(u);

  Fermion_t X_t;
  Fermion_t Y_t;
  Matrix_t  Force_t[2];

  X_t     = dwf_qmp.allocFermion();
  Y_t     = dwf_qmp.allocFermion();
  for(int cb=0;cb<2;cb++){
    Force_t[cb] = dwf_qmp.allocMatrix();
    printf("Force_t pointer %lx\n",Force_t[cb]);
  }


  multi1d<int> bcs(Nd); bcs[0] = bcs[1] = bcs[2] = bcs[3] = 1;
  Handle<FermBC<T,U,U> > fbc(new SimpleFermBC< T, U, U >(bcs));
  Handle<CreateFermState<T,U,U> > cfs( new CreateSimpleFermState<T,U,U>(fbc));
  Handle<FermState<T,U,U> > fs ((*cfs)(u));


  //! Params for NEFF
  EvenOddPrecKNOFermActArrayParams kparams;

  Real scale = dwf_qmp.mobius_scale;
  kparams.OverMass = dwf_qmp.M5;
  kparams.Mass     = dwf_qmp.mass;
  kparams.a5       = 1.0;
  kparams.coefs.resize(Ls);
  for(int s=0;s<Ls;s++)
    kparams.coefs[s] = scale;
  kparams.N5       = dwf_qmp.Ls;

  EvenOddPrecKNOFermActArray FA(cfs,kparams);
  Handle< DiffLinearOperatorArray<Phi,P,Q> > M(FA.linOp(fs));
  
  for( int dag=0;dag<2;dag++){

    Fb=zero;
    F=zero;

    dwf_qmp.importFermion(X,X_t,1);
    dwf_qmp.importFermion(Y,Y_t,1);

    dwf_qmp.zeroMatrix(Force_t[0]);
    dwf_qmp.zeroMatrix(Force_t[1]);


    dwf_qmp.MprecDeriv(X_t,Y_t,Force_t,dag);

    for(int cb=0;cb<2;cb++)
      dwf_qmp.exportForce(Force_t[cb],Fb,cb);
    
    Printf("Calling S_f deriv\n");
    if( dag==1 ) 
      M->deriv(F, X, Y, MINUS);
    else
      M->deriv(F, X, Y, PLUS);
      
    for(int mu=0;mu<4;mu++){
      QDPIO::cout << "dag "<< dag<<"mu "<<mu<<" n2diff " << norm2(Fb[mu]-F[mu])<<endl;
    }

#if 0
    QDPIO::cout << "Calling force term" << endl;
    dwf_qmp.zeroMatrix(Force_t[0]);
    dwf_qmp.zeroMatrix(Force_t[1]);
    dwf_qmp.TwoFlavorRatioForce(X_t,Force_t,1.0,dwf_qmp.mass);
    for(int cb=0;cb<2;cb++)
      dwf_qmp.exportForce(Force_t[cb],Fb,cb);
    for(int mu=0;mu<4;mu++){
      QDPIO::cout << "dag "<< dag<<"mu "<<mu<<" TwoFlavorForce " << norm2(Fb[mu])<<endl;
    }
#endif

    //    { 
    // EvenOddPrecConstDetTwoFlavorRatioConvConvWilsonTypeFermMonomial5D Monomial();
    //    }

  }

    dwf_qmp.freeMatrix(Force_t[0]);
    dwf_qmp.freeMatrix(Force_t[1]);
    exit(0);


}
示例#11
0
int main(int argc, char* argv[])
{
    // Load the mesh.
    Mesh mesh;
    H2DReader mloader;
    mloader.load("domain.mesh", &mesh);

    // Perform uniform mesh refinement.
    for(int i = 0; i < INIT_REF_NUM; i++) mesh.refine_all_elements(2); // 2 is for vertical split.

    // Initialize boundary conditions
    DefaultEssentialBCConst bc1(BDY_PERFECT, 0.0);
    EssentialBCNonConst bc2(BDY_LEFT);
    EssentialBCs bcs(Hermes::vector<EssentialBoundaryCondition *>(&bc1, &bc2));

    // Create an H1 space with default shapeset.
    H1Space e_r_space(&mesh, &bcs, P_INIT);
    H1Space e_i_space(&mesh, &bcs, P_INIT);
    int ndof = Space::get_num_dofs(&e_r_space);
    info("ndof = %d", ndof);

    // Initialize the weak formulation
    // Weak forms for real and imaginary parts

    // Initialize the weak formulation.
    WeakFormHelmholtz wf(eps, mu, omega, sigma, beta, E0, h);

    // Initialize the FE problem.
    bool is_linear = true;
    DiscreteProblem dp(&wf, Hermes::vector<Space *>(&e_r_space, &e_i_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 solutions.
    Solution e_r_sln, e_i_sln;

    // Assemble the stiffness matrix and right-hand side vector.
    info("Assembling the stiffness matrix and right-hand side vector.");
    dp.assemble(matrix, rhs);

    // Solve the linear system and if successful, obtain the solutions.
    info("Solving the matrix problem.");
    if(solver->solve())
        Solution::vector_to_solutions(solver->get_solution(),
                                      Hermes::vector<Space *>(&e_r_space, &e_i_space),
                                      Hermes::vector<Solution *>(&e_r_sln, &e_i_sln));
    else
        error ("Matrix solver failed.\n");

    // Visualize the solution.
    ScalarView viewEr("Er [V/m]", new WinGeom(0, 0, 800, 400));
    viewEr.show(&e_r_sln);
    // viewEr.save_screenshot("real_part.bmp");

    ScalarView viewEi("Ei [V/m]", new WinGeom(0, 450, 800, 400));
    viewEi.show(&e_i_sln);
    // viewEi.save_screenshot("imaginary_part.bmp");

    // Wait for the view to be closed.
    View::wait();

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

    return 0;
}
示例#12
0
int main(int argc, char **argv)
{
  // Time measurement.
  TimePeriod cpu_time;
  cpu_time.tick();

  // Load the mesh.
  Mesh mesh;
  MeshReaderH2D mloader;
  mloader.load("square.mesh", &mesh);

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

  // Set exact solution.
  CustomExactSolution exact(&mesh);

  // Initialize boundary conditions
  DefaultEssentialBCNonConst<double> bc_essential("Bdy", &exact);
  EssentialBCs<double> bcs(&bc_essential);
  
  // Initialize the weak formulation.
  CustomWeakFormPoisson wf1;
 
  // Create an H1 space with default shapeset.
  H1Space<double> space(&mesh, &bcs, P_INIT);
  int ndof = Space<double>::get_num_dofs(&space);
  info("ndof: %d", ndof);

  info("---- Assembling by DiscreteProblem, solving by %s:", 
       MatrixSolverNames[matrix_solver].c_str());

  // Initialize the linear discrete problem.
  DiscreteProblem<double> dp1(&wf1, &space);
    
  // Set up the solver, matrix, and rhs according to the solver selection.
  SparseMatrix<double>* matrix = create_matrix<double>(matrix_solver);
  Vector<double>* rhs = create_vector<double>(matrix_solver);
  LinearSolver<double>* solver = create_linear_solver<double>(matrix_solver, matrix, rhs);
  
#ifdef HAVE_AZTECOO
    if (matrix_solver == SOLVER_AZTECOO) 
    {
      (dynamic_cast<AztecOOSolver<double>*>(solver))->set_solver(iterative_method);
      (dynamic_cast<AztecOOSolver<double>*>(solver))->set_precond(preconditioner);
      // Using default iteration parameters (see solver/aztecoo.h).
    }    
#endif
  
  // Begin time measurement of assembly.
  cpu_time.tick(HERMES_SKIP);

  // Initial coefficient vector for the Newton's method.  
  double* coeff_vec = new double[ndof];
  memset(coeff_vec, 0, ndof*sizeof(double));

  // Initialize the Newton solver.
  Hermes::Hermes2D::NewtonSolver<double> newton(&dp1, matrix_solver);

  // Perform Newton's iteration and translate the resulting coefficient vector into a Solution.
  Hermes::Hermes2D::Solution<double> sln1;
  try
  {
    newton.solve(coeff_vec);
  }
  catch(Hermes::Exceptions::Exception e)
  {
    e.printMsg();
    error("Newton's iteration failed.");
  }

  Hermes::Hermes2D::Solution<double>::vector_to_solution(newton.get_sln_vector(), &space, &sln1);

  // CPU time measurement.
  double time = cpu_time.tick().last();

  // Calculate errors.
  double rel_err_1 = Global<double>::calc_rel_error(&sln1, &exact, HERMES_H1_NORM) * 100;
  info("CPU time: %g s.", time);
  info("Exact H1 error: %g%%.", rel_err_1);

  delete(matrix);
  delete(rhs);
  delete(solver);
    
  // View the solution and mesh.
  ScalarView sview("Solution", new WinGeom(0, 0, 440, 350));
  sview.show(&sln1);
  //OrderView  oview("Polynomial orders", new WinGeom(450, 0, 400, 350));
  //oview.show(&space);
  
  // TRILINOS PART:

  info("---- Assembling by DiscreteProblem, solving by NOX:");

  // Initialize the weak formulation for Trilinos.
  CustomWeakFormPoisson wf2(TRILINOS_JFNK);
  
  // Initialize DiscreteProblem.
  DiscreteProblem<double> dp2(&wf2, &space);
  
  // Time measurement.
  cpu_time.tick(HERMES_SKIP);

  // Set initial vector for NOX.
  // NOTE: Using zero vector was causing convergence problems.
  info("Projecting to obtain initial vector for the Newton's method.");
  ZeroSolution init_sln(&mesh);

  // Initialize the NOX solver with the vector "coeff_vec".
  info("Initializing NOX.");
  NewtonSolverNOX<double> nox_solver(&dp2);
  nox_solver.set_output_flags(message_type);

  nox_solver.set_ls_type(iterative_method);
  nox_solver.set_ls_tolerance(ls_tolerance);

  nox_solver.set_conv_iters(max_iters);
  if (flag_absresid)
    nox_solver.set_conv_abs_resid(abs_resid);
  if (flag_relresid)
    nox_solver.set_conv_rel_resid(rel_resid);

  // Choose preconditioning.
  MlPrecond<double> pc("sa");
  if (PRECOND)
  {
    if (TRILINOS_JFNK) nox_solver.set_precond(pc);
    else nox_solver.set_precond(preconditioner);
  }

  // Assemble and solve using NOX.
  Solution<double> sln2;
  OGProjection<double>::project_global(&space, &init_sln, coeff_vec);
  try
  {
    nox_solver.solve(coeff_vec);
  }
  catch(Hermes::Exceptions::Exception e)
  {
    e.printMsg();
    error("NOX failed.");
  }

  Solution<double>::vector_to_solution(nox_solver.get_sln_vector(), &space, &sln2);

  info("Number of nonlin iterations: %d (norm of residual: %g)", 
    nox_solver.get_num_iters(), nox_solver.get_residual());
  info("Total number of iterations in linsolver: %d (achieved tolerance in the last step: %g)", 
    nox_solver.get_num_lin_iters(), nox_solver.get_achieved_tol());

  // CPU time needed by NOX.
  time = cpu_time.tick().last();

  // Show the NOX solution.
  ScalarView view2("Solution<double> 2", new WinGeom(450, 0, 460, 350));
  view2.show(&sln2);
  //view2.show(&exact);

  // Calculate errors.
  double rel_err_2 = Global<double>::calc_rel_error(&sln2, &exact, HERMES_H1_NORM) * 100;
  info("CPU time: %g s.", time);
  info("Exact H1 error: %g%%.", rel_err_2);
 
  // Wait for all views to be closed.
  View::wait();
  
  return 0;
}
示例#13
0
int main(int argc, char* argv[])
{
  // Choose a Butcher's table or define your own.
  ButcherTable bt(butcher_table_type);
  if (bt.is_explicit()) info("Using a %d-stage explicit R-K method.", bt.get_size());
  if (bt.is_diagonally_implicit()) info("Using a %d-stage diagonally implicit R-K method.", bt.get_size());
  if (bt.is_fully_implicit()) info("Using a %d-stage fully implicit R-K method.", bt.get_size());

  // Load the mesh.
  Mesh mesh;
  H2DReader mloader;
  mloader.load("../domain.mesh", &mesh);

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

  // Initialize solutions.
  CustomInitialConditionWave E_sln(&mesh);
  Solution F_sln(&mesh, 0.0, 0.0);
  Hermes::vector<Solution*> slns(&E_sln, &F_sln);

  // Initialize the weak formulation.
  CustomWeakFormWave wf(C_SQUARED);
  
  // Initialize boundary conditions
  DefaultEssentialBCConst bc_essential(BDY, 0.0);
  EssentialBCs bcs(&bc_essential);

  // Create x- and y- displacement space using the default H1 shapeset.
  HcurlSpace E_space(&mesh, &bcs, P_INIT);
  HcurlSpace F_space(&mesh, &bcs, P_INIT);
  Hermes::vector<Space *> spaces = Hermes::vector<Space *>(&E_space, &F_space);
  info("ndof = %d.", Space::get_num_dofs(spaces));

  // Initialize the FE problem.
  DiscreteProblem dp(&wf, spaces);

  // Initialize Runge-Kutta time stepping.
  RungeKutta runge_kutta(&dp, &bt, matrix_solver);

  // Time stepping loop.
  double current_time = 0; int ts = 1;
  do
  {
    // Perform one Runge-Kutta time step according to the selected Butcher's table.
    info("Runge-Kutta time step (t = %g s, time_step = %g s, stages: %d).", 
         current_time, time_step, bt.get_size());
    bool verbose = true;
    bool jacobian_changed = true;
    if (!runge_kutta.rk_time_step(current_time, time_step, slns, slns, jacobian_changed, verbose))
      error("Runge-Kutta time step failed, try to decrease time step size.");

    // Update time.
    current_time += time_step;
  
  } while (current_time < T_FINAL);

  double coord_x[4] = {0.3, 0.6, 0.9, 1.4};
  double coord_y[4] = {0, 0.3, 0.5, 0.7};

  info("Coordinate (0.3, 0.0) value = %lf", F_sln.get_pt_value(coord_x[0], coord_y[0]));
  info("Coordinate (0.6, 0.3) value = %lf", F_sln.get_pt_value(coord_x[1], coord_y[1]));
  info("Coordinate (0.9, 0.5) value = %lf", F_sln.get_pt_value(coord_x[2], coord_y[2]));
  info("Coordinate (1.4, 0.7) value = %lf", F_sln.get_pt_value(coord_x[3], coord_y[3]));

  double t_value[4] = {-0.144673, -0.264077, -0.336536, -0.368983};
  bool success = true;

  for (int i = 0; i < 4; i++)
  {
    if (fabs(t_value[i] - F_sln.get_pt_value(coord_x[i], coord_y[i])) > 1E-6) success = false;
  }

  if (success) {
    printf("Success!\n");
    return ERR_SUCCESS;
  }
  else {
    printf("Failure!\n");
    return ERR_FAILURE;
  }
}
示例#14
0
int main(int argc, char* argv[])
{
  // Initialize refinement selector.
  MySelector selector(hORpSelectionBasedOnDOFs);

  HermesCommonApi.set_integral_param_value(Hermes::showInternalWarnings, false);

  // Time measurement.
  Hermes::Mixins::TimeMeasurable cpu_time;
  cpu_time.tick();

  // Load the mesh.
  MeshSharedPtr mesh(new Mesh);
  MeshReaderH2D mloader;
  mloader.load("domain.mesh", mesh);

  // Error calculation & adaptivity.
  DefaultErrorCalculator<complex, HERMES_H1_NORM> errorCalculator(RelativeErrorToGlobalNorm, 1);
  // Stopping criterion for an adaptivity step.
  AdaptStoppingCriterionSingleElement<complex> stoppingCriterion(THRESHOLD);
  // Adaptivity processor class.
  Adapt<complex> adaptivity(&errorCalculator, &stoppingCriterion);

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

  // Initialize boundary conditions.
  DefaultEssentialBCConst<complex> bc_essential("Source", P_SOURCE);
  EssentialBCs<complex> bcs(&bc_essential);

  // Create an H1 space with default shapeset.
  SpaceSharedPtr<complex> space(new H1Space<complex> (mesh, &bcs, P_INIT));
  int ndof = Space<complex>::get_num_dofs(space);
  //Hermes::Mixins::Loggable::Static::info("ndof = %d", ndof);

  // Initialize the weak formulation.
  CustomWeakFormAcoustics wf("Wall", RHO, SOUND_SPEED, OMEGA);

  // Initialize coarse and reference mesh solution.
  MeshFunctionSharedPtr<complex>  sln(new Solution<complex>), ref_sln(new Solution<complex>);

  // Initialize views.
  ScalarView sview("Acoustic pressure", new WinGeom(600, 0, 600, 350));
  sview.show_contours(.2);
  ScalarView eview("Error", new WinGeom(600, 377, 600, 350));
  sview.show_mesh(false);
  sview.fix_scale_width(50);
  OrderView  oview("Polynomial orders", new WinGeom(1208, 0, 600, 350));
  ScalarView ref_view("Refined elements", new WinGeom(1208, 377, 600, 350));
  ref_view.show_scale(false);
  ref_view.set_min_max_range(0, 2);

  // DOF and CPU convergence graphs initialization.
  SimpleGraph graph_dof, graph_cpu;

  //Hermes::Mixins::Loggable::Static::info("Solving on reference mesh.");
  // Time measurement.
  cpu_time.tick();

  // Perform Newton's iteration.
  Hermes::Hermes2D::NewtonSolver<complex> newton(&wf, space);
  newton.set_verbose_output(false);

  // Adaptivity loop:
  int as = 1;
  adaptivity.set_space(space);
  bool done = false;
  do
  {
    //Hermes::Mixins::Loggable::Static::info("---- Adaptivity step %d:", as);

    // Construct globally refined reference mesh and setup reference space.
    Mesh::ReferenceMeshCreator refMeshCreator(mesh);
    MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh();

    Space<complex>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh);
    SpaceSharedPtr<complex> ref_space = refSpaceCreator.create_ref_space();

    int ndof_ref = Space<complex>::get_num_dofs(ref_space);
    wf.set_verbose_output(false);
    newton.set_space(ref_space);

    // Assemble the reference problem.
    try
    {
      newton.solve();
    }
    catch(Hermes::Exceptions::Exception e)
    {
      e.print_msg();
      throw Hermes::Exceptions::Exception("Newton's iteration failed.");
    };
    // Translate the resulting coefficient vector into the Solution<complex> sln->
    Hermes::Hermes2D::Solution<complex>::vector_to_solution(newton.get_sln_vector(), ref_space, ref_sln);

    // Project the fine mesh solution onto the coarse mesh.
    //Hermes::Mixins::Loggable::Static::info("Projecting reference solution on coarse mesh.");
    OGProjection<complex> ogProjection; ogProjection.project_global(space, ref_sln, sln);

    // Time measurement.
    cpu_time.tick();

    // View the coarse mesh solution and polynomial orders.
    MeshFunctionSharedPtr<double> acoustic_pressure(new RealFilter(sln));
    sview.show(acoustic_pressure);
    oview.show(space);

    // Calculate element errors and total error estimate.
    //Hermes::Mixins::Loggable::Static::info("Calculating error estimate.");
    errorCalculator.calculate_errors(sln, ref_sln);
    double err_est_rel = errorCalculator.get_total_error_squared() * 100;

    eview.show(errorCalculator.get_errorMeshFunction());

    // Report results.
    //Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_fine: %d, err_est_rel: %g%%", Space<complex>::get_num_dofs(space), Space<complex>::get_num_dofs(ref_space), err_est_rel);

    // Time measurement.
    cpu_time.tick();

    // Add entry to DOF and CPU convergence graphs.
    graph_dof.add_values(Space<complex>::get_num_dofs(space), err_est_rel);
    graph_dof.save("conv_dof_est.dat");
    graph_cpu.add_values(cpu_time.accumulated(), err_est_rel);
    graph_cpu.save("conv_cpu_est.dat");

    // If err_est too large, adapt the mesh.
    if (err_est_rel < ERR_STOP) done = true;
    else
    {
      //Hermes::Mixins::Loggable::Static::info("Adapting coarse mesh.");
      done = adaptivity.adapt(&selector);
      ref_view.show(adaptivity.get_refinementInfoMeshFunction());
      cpu_time.tick();
      std::cout << "Adaptivity step: " << as << ", running CPU time: " << cpu_time.accumulated_str() << std::endl;
    }

    // Increase counter.
    as++;
  }
  while (done == false);

  //Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());

  // Show the reference solution - the final result.
  sview.set_title("Fine mesh solution magnitude");

  MeshFunctionSharedPtr<double>  ref_mag(new RealFilter(ref_sln));
  sview.show(ref_mag);

  // Output solution in VTK format.
  Linearizer lin(FileExport);
  bool mode_3D = true;
  lin.save_solution_vtk(ref_mag, "sln.vtk", "Acoustic pressure", mode_3D);
  //Hermes::Mixins::Loggable::Static::info("Solution in VTK format saved to file %s.", "sln.vtk");

  // Wait for all views to be closed.
  View::wait();
  return 0;
}
示例#15
0
int main(int argc, char* argv[])
{
#ifdef WITH_PARALUTION
  HermesCommonApi.set_integral_param_value(matrixSolverType, SOLVER_PARALUTION_AMG);

  // Load the mesh.
  MeshSharedPtr mesh(new Mesh);
  MeshReaderH2D mloader;
  mloader.load("domain.mesh", mesh);

  // Perform initial mesh refinements.
  for(int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements();
  mesh->refine_towards_boundary("Boundary air", INIT_REF_NUM_BDY);
  mesh->refine_towards_boundary("Boundary ground", INIT_REF_NUM_BDY);

  // Previous time level solution (initialized by the external temperature).
  MeshFunctionSharedPtr<double> tsln(new ConstantSolution<double> (mesh, TEMP_INIT));

  // Initialize the weak formulation.
  double current_time = 0;
  CustomWeakFormHeatRK1 wf("Boundary air", ALPHA, LAMBDA, HEATCAP, RHO, time_step, 
                           &current_time, TEMP_INIT, T_FINAL, tsln);
  
  // Initialize boundary conditions.
  DefaultEssentialBCConst<double> bc_essential("Boundary ground", TEMP_INIT);
  EssentialBCs<double> bcs(&bc_essential);

  // Create an H1 space with default shapeset.
  SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
  int ndof = space->get_num_dofs();
  Hermes::Mixins::Loggable::Static::info("ndof = %d", ndof);
 
  // Initialize Newton solver.
  NewtonSolver<double> newton(&wf, space);
#ifdef SHOW_OUTPUT
  newton.set_verbose_output(true);
#else
  newton.set_verbose_output(false);
#endif
  newton.set_jacobian_constant();
  newton.get_linear_matrix_solver()->as_AMGSolver()->set_smoother(Solvers::GMRES, Preconditioners::ILU);
  newton.get_linear_matrix_solver()->as_LoopSolver()->set_tolerance(1e-1, RelativeTolerance);

#ifdef SHOW_OUTPUT
  // Initialize views.
  ScalarView Tview("Temperature", new WinGeom(0, 0, 450, 600));
  Tview.set_min_max_range(0,20);
  Tview.fix_scale_width(30);
#endif

  // Time stepping:
  int ts = 1;
  do 
  {
    Hermes::Mixins::Loggable::Static::info("---- Time step %d, time %3.5f s", ts, current_time);

    newton.solve();

    // Translate the resulting coefficient vector into the Solution sln.
    Solution<double>::vector_to_solution(newton.get_sln_vector(), space, tsln);

#ifdef SHOW_OUTPUT
    // Visualize the solution.
    char title[100];
    sprintf(title, "Time %3.2f s", current_time);
    Tview.set_title(title);
    Tview.show(tsln);
#endif

    // Increase current time and time step counter.
    current_time += time_step;
    ts++;
  }
  while (current_time < T_FINAL);

  // Wait for the view to be closed.
#ifdef SHOW_OUTPUT
  View::wait();
#endif
  return 0;
#endif
  return 0;
}
示例#16
0
int main(int argc, char* argv[])
{
  // Choose a Butcher's table or define your own.
  ButcherTable bt(butcher_table_type);
  if (bt.is_explicit()) info("Using a %d-stage explicit R-K method.", bt.get_size());
  if (bt.is_diagonally_implicit()) info("Using a %d-stage diagonally implicit R-K method.", bt.get_size());
  if (bt.is_fully_implicit()) info("Using a %d-stage fully implicit R-K method.", bt.get_size());

  // Load the mesh.
  Mesh mesh, basemesh;
  MeshReaderH2D mloader;
  mloader.load("square.mesh", &basemesh);
  mesh.copy(&basemesh);

  // Initial mesh refinements.
  for(int i = 0; i < INIT_GLOB_REF_NUM; i++) mesh.refine_all_elements();
  mesh.refine_towards_boundary("Top", INIT_REF_NUM_BDY);

  // Initialize boundary conditions.
  CustomEssentialBCNonConst bc_essential(Hermes::vector<std::string>("Bottom", "Right", "Top", "Left"));
  EssentialBCs<double> bcs(&bc_essential);

  // Create an H1 space with default shapeset.
  H1Space<double> space(&mesh, &bcs, P_INIT);
  int ndof_coarse = Space<double>::get_num_dofs(&space);
  info("ndof_coarse = %d.", ndof_coarse);

  // Zero initial solution. This is why we use H_OFFSET.
  ZeroSolution h_time_prev(&mesh), h_time_new(&mesh);

  // Initialize the constitutive relations.
  ConstitutiveRelations* constitutive_relations;
  if(constitutive_relations_type == CONSTITUTIVE_GENUCHTEN)
    constitutive_relations = new ConstitutiveRelationsGenuchten(ALPHA, M, N, THETA_S, THETA_R, K_S, STORATIVITY);
  else
    constitutive_relations = new ConstitutiveRelationsGardner(ALPHA, THETA_S, THETA_R, K_S);

  // Initialize the weak formulation.
  CustomWeakFormRichardsRK wf(constitutive_relations);

  // Initialize the FE problem.
  DiscreteProblem<double> dp(&wf, &space);

  // Create a refinement selector.
  H1ProjBasedSelector<double> selector(CAND_LIST, CONV_EXP, H2DRS_DEFAULT_ORDER);

  // Visualize initial condition.
  char title[100];
  ScalarView view("Initial condition", new WinGeom(0, 0, 440, 350));
  OrderView ordview("Initial mesh", new WinGeom(445, 0, 440, 350));
  view.show(&h_time_prev);
  ordview.show(&space);

  // DOF and CPU convergence graphs initialization.
  SimpleGraph graph_dof, graph_cpu;
  
  // Time measurement.
  TimePeriod cpu_time;
  cpu_time.tick();
  
  // Time stepping loop.
  double current_time = 0; int ts = 1;
  do 
  {
    // Periodic global derefinement.
    if (ts > 1 && ts % UNREF_FREQ == 0) 
    {
      info("Global mesh derefinement.");
      switch (UNREF_METHOD) {
        case 1: mesh.copy(&basemesh);
                space.set_uniform_order(P_INIT);
                break;
        case 2: mesh.unrefine_all_elements();
                space.set_uniform_order(P_INIT);
                break;
        case 3: space.unrefine_all_mesh_elements();
                space.adjust_element_order(-1, -1, P_INIT, P_INIT);
                break;
        default: error("Wrong global derefinement method.");
      }

      ndof_coarse = Space<double>::get_num_dofs(&space);
    }

    // Spatial adaptivity loop. Note: h_time_prev must not be changed 
    // during spatial adaptivity. 
    bool done = false; int as = 1;
    double err_est;
    do {
      info("Time step %d, adaptivity step %d:", ts, as);

      // Construct globally refined reference mesh and setup reference space.
      Space<double>* ref_space = Space<double>::construct_refined_space(&space);
      int ndof_ref = Space<double>::get_num_dofs(ref_space);

      // Time measurement.
      cpu_time.tick();

      // Initialize Runge-Kutta time stepping.
      RungeKutta<double> runge_kutta(&wf, ref_space, &bt, matrix_solver);

      // Perform one Runge-Kutta time step according to the selected Butcher's table.
      info("Runge-Kutta time step (t = %g s, tau = %g s, stages: %d).",
           current_time, time_step, bt.get_size());
      bool freeze_jacobian = false;
      bool block_diagonal_jacobian = false;
      bool verbose = true;
      double damping_coeff = 1.0;
      double max_allowed_residual_norm = 1e10;

      try
      {
        runge_kutta.rk_time_step_newton(current_time, time_step, &h_time_prev, 
            &h_time_new, freeze_jacobian, block_diagonal_jacobian, verbose,
            NEWTON_TOL, NEWTON_MAX_ITER, damping_coeff, max_allowed_residual_norm);
      }
      catch(Exceptions::Exception& e)
      {
        e.printMsg();
        error("Runge-Kutta time step failed");
      }

      // Project the fine mesh solution onto the coarse mesh.
      Solution<double> sln_coarse;
      info("Projecting fine mesh solution on coarse mesh for error estimation.");
      OGProjection<double>::project_global(&space, &h_time_new, &sln_coarse, matrix_solver); 

      // Calculate element errors and total error estimate.
      info("Calculating error estimate.");
      Adapt<double>* adaptivity = new Adapt<double>(&space);
      double err_est_rel_total = adaptivity->calc_err_est(&sln_coarse, &h_time_new) * 100;

      // Report results.
      info("ndof_coarse: %d, ndof_ref: %d, err_est_rel: %g%%", 
           Space<double>::get_num_dofs(&space), Space<double>::get_num_dofs(ref_space), err_est_rel_total);

      // Time measurement.
      cpu_time.tick();

      // If err_est too large, adapt the mesh.
      if (err_est_rel_total < ERR_STOP) done = true;
      else 
      {
        info("Adapting the coarse mesh.");
        done = adaptivity->adapt(&selector, THRESHOLD, STRATEGY, MESH_REGULARITY);

        if (Space<double>::get_num_dofs(&space) >= NDOF_STOP) 
          done = true;
        else
          // Increase the counter of performed adaptivity steps.
          as++;
      }
      
      // Clean up.
      delete adaptivity;
      if(!done)
      {
        delete h_time_new.get_space();
        delete h_time_new.get_mesh();
      }
    }
    while (done == false);

    // Add entry to DOF and CPU convergence graphs.
    graph_dof.add_values(current_time, Space<double>::get_num_dofs(&space));
    graph_dof.save("conv_dof_est.dat");
    graph_cpu.add_values(current_time, cpu_time.accumulated());
    graph_cpu.save("conv_cpu_est.dat");

    // Visualize the solution and mesh.
    char title[100];
    sprintf(title, "Solution, time %g", current_time);
    view.set_title(title);
    view.show_mesh(false);
    view.show(&h_time_new);
    sprintf(title, "Mesh, time %g", current_time);
    ordview.set_title(title);
    ordview.show(&space);

    // Copy last reference solution into h_time_prev.
    h_time_prev.copy(&h_time_new);
    delete h_time_new.get_mesh();

    // Increase current time and counter of time steps.
    current_time += time_step;
    ts++;
  }
  while (current_time < T_FINAL);

  // Wait for all views to be closed.
  View::wait();
  return 0;
}
示例#17
0
int main(int argc, char* argv[])
{
    // Choose a Butcher's table or define your own.
    ButcherTable bt(butcher_table_type);
    if (bt.is_explicit()) info("Using a %d-stage explicit R-K method.", bt.get_size());
    if (bt.is_diagonally_implicit()) info("Using a %d-stage diagonally implicit R-K method.", bt.get_size());
    if (bt.is_fully_implicit()) info("Using a %d-stage fully implicit R-K method.", bt.get_size());

    // Load the mesh.
    Mesh mesh;
    MeshReaderH2D mloader;
    mloader.load("domain.mesh", &mesh);

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

    // Initialize solutions.
    CustomInitialConditionWave E_sln(&mesh);
    ZeroSolutionVector F_sln(&mesh);
    Hermes::vector<Solution<double>*> slns(&E_sln, &F_sln);

    // Initialize the weak formulation.
    CustomWeakFormWave wf(C_SQUARED);

    // Initialize boundary conditions
    DefaultEssentialBCConst<double> bc_essential("Perfect conductor", 0.0);
    EssentialBCs<double> bcs(&bc_essential);

    // Create x- and y- displacement space using the default H1 shapeset.
    HcurlSpace<double> E_space(&mesh, &bcs, P_INIT);
    HcurlSpace<double> F_space(&mesh, &bcs, P_INIT);
    Hermes::vector<Space<double> *> spaces = Hermes::vector<Space<double> *>(&E_space, &F_space);
    info("ndof = %d.", Space<double>::get_num_dofs(spaces));

    // Initialize the FE problem.
    DiscreteProblem<double> dp(&wf, spaces);

    // Initialize views.
    ScalarView E1_view("Solution E1", new WinGeom(0, 0, 400, 350));
    E1_view.fix_scale_width(50);
    ScalarView E2_view("Solution E2", new WinGeom(410, 0, 400, 350));
    E2_view.fix_scale_width(50);

    // Initialize Runge-Kutta time stepping.
    RungeKutta<double> runge_kutta(&dp, &bt, matrix_solver_type);

    // Time stepping loop.
    double current_time = 0;
    int ts = 1;
    do
    {
        // Perform one Runge-Kutta time step according to the selected Butcher's table.
        info("Runge-Kutta time step (t = %g s, time_step = %g s, stages: %d).",
             current_time, time_step, bt.get_size());
        bool verbose = true;
        bool jacobian_changed = true;

        try
        {
            runge_kutta.rk_time_step_newton(current_time, time_step, slns, slns, jacobian_changed, verbose);
        }
        catch(Exceptions::Exception& e)
        {
            e.printMsg();
            error("Runge-Kutta time step failed");
        }

        // Visualize the solutions.
        char title[100];
        sprintf(title, "E1, t = %g", current_time);
        E1_view.set_title(title);
        E1_view.show(&E_sln, HERMES_EPS_NORMAL, H2D_FN_VAL_0);
        sprintf(title, "E2, t = %g", current_time);
        E2_view.set_title(title);
        E2_view.show(&E_sln, HERMES_EPS_NORMAL, H2D_FN_VAL_1);

        // Update time.
        current_time += time_step;

    } while (current_time < T_FINAL);

    // Wait for the view to be closed.
    View::wait();

    return 0;
}
示例#18
0
int main(int argc, char* argv[])
{
  // Instantiate a class with global functions.
  Hermes2D hermes2d;

  // Load the mesh.
  Mesh mesh, mesh1;
  H2DReader mloader;
  mloader.load("domain.mesh", &mesh);

  // Perform uniform mesh refinement.
  mesh.refine_all_elements();

  // Initialize boundary conditions.
  DefaultEssentialBCConst zero_disp("Bottom", 0.0);
  EssentialBCs bcs(&zero_disp);

  // Create x- and y- displacement space using the default H1 shapeset.
  H1Space u1_space(&mesh, &bcs, P_INIT);
  H1Space u2_space(&mesh, &bcs, P_INIT);
  int ndof = Space::get_num_dofs(Hermes::vector<Space *>(&u1_space, &u2_space));
  info("ndof = %d", ndof);

  // Initialize the weak formulation.
  CustomWeakFormLinearElasticity wf(E, nu, rho*g1, "Top", f0, f1);

  // Initialize the FE problem.
  DiscreteProblem dp(&wf, Hermes::vector<Space *>(&u1_space, &u2_space));

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

  // Initial coefficient vector for the Newton's method.  
  scalar* coeff_vec = new scalar[ndof];
  memset(coeff_vec, 0, ndof*sizeof(scalar));

  // Perform Newton's iteration.
  bool verbose = true;
  bool jacobian_changed = true;
  if (!hermes2d.solve_newton(coeff_vec, &dp, solver, matrix, rhs, jacobian_changed,
      NEWTON_TOL, NEWTON_MAX_ITER, verbose)) error("Newton's iteration failed.");

  // Translate the resulting coefficient vector into the Solution sln.
  Solution u1_sln, u2_sln;
  Solution::vector_to_solutions(coeff_vec, Hermes::vector<Space *>(&u1_space, &u2_space), 
                                Hermes::vector<Solution *>(&u1_sln, &u2_sln));
  
  // Visualize the solution.
  ScalarView view("Von Mises stress [Pa]", new WinGeom(0, 0, 800, 400));
  double lambda = (E * nu) / ((1 + nu) * (1 - 2*nu));  // First Lame constant.
  double mu = E / (2*(1 + nu));                        // Second Lame constant.
  VonMisesFilter stress(Hermes::vector<MeshFunction *>(&u1_sln, &u2_sln), lambda, mu);
  view.show_mesh(false);
  view.show(&stress, HERMES_EPS_HIGH, H2D_FN_VAL_0, &u1_sln, &u2_sln, 1.5e5);

  // Wait for the view to be closed.
  View::wait();

  // Clean up.
  delete [] coeff_vec;
  delete solver;
  delete matrix;
  delete rhs;

  return 0;
}
示例#19
0
int main(int argc, char* argv[])
{
    // Load the mesh.
    MeshSharedPtr mesh(new Mesh);
    MeshReaderH2D mloader;
    mloader.load("domain.mesh", mesh);

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

    // Initialize boundary conditions.
    Hermes::Hermes2D::DefaultEssentialBCConst<complex> bc_essential("Dirichlet", complex(0.0, 0.0));
    EssentialBCs<complex> bcs(&bc_essential);

    // Create an H1 space with default shapeset.
    SpaceSharedPtr<complex> space(new H1Space<complex>(mesh, &bcs, P_INIT));

    // Initialize the weak formulation.
    CustomWeakForm wf("Air", MU_0, "Iron", MU_IRON, GAMMA_IRON,
                      "Wire", MU_0, complex(J_EXT, 0.0), OMEGA);

    // Initialize coarse and reference mesh solution.
    MeshFunctionSharedPtr<complex> sln(new Hermes::Hermes2D::Solution<complex>());
    MeshFunctionSharedPtr<complex> ref_sln(new Hermes::Hermes2D::Solution<complex>());

    // Initialize refinement selector.
    H1ProjBasedSelector<complex> selector(CAND_LIST);

    // DOF and CPU convergence graphs initialization.
    SimpleGraph graph_dof, graph_cpu;

    DiscreteProblem<complex> dp(&wf, space);

    // Perform Newton's iteration and translate the resulting coefficient vector into a Solution.
    Hermes::Hermes2D::NewtonSolver<complex> newton(&dp);

    // Adaptivity loop:
    int as = 1;
    bool done = false;
    adaptivity.set_space(space);
    do
    {
        // Construct globally refined reference mesh and setup reference space->
        Mesh::ReferenceMeshCreator ref_mesh_creator(mesh);
        MeshSharedPtr ref_mesh = ref_mesh_creator.create_ref_mesh();
        Space<complex>::ReferenceSpaceCreator ref_space_creator(space, ref_mesh);
        SpaceSharedPtr<complex> ref_space = ref_space_creator.create_ref_space();

        newton.set_space(ref_space);

        int ndof_ref = ref_space->get_num_dofs();

        // Initialize reference problem.

        // Initial coefficient vector for the Newton's method.
        complex* coeff_vec = new complex[ndof_ref];
        memset(coeff_vec, 0, ndof_ref * sizeof(complex));

        // Perform Newton's iteration and translate the resulting coefficient vector into a Solution.
        try
        {
            newton.solve(coeff_vec);
        }
        catch(Hermes::Exceptions::Exception& e)
        {
            e.print_msg();
        }

        Hermes::Hermes2D::Solution<complex>::vector_to_solution(newton.get_sln_vector(), ref_space, ref_sln);

        // Project the fine mesh solution onto the coarse mesh.
        OGProjection<complex> ogProjection;
        ogProjection.project_global(space, ref_sln, sln);

        // Calculate element errors and total error estimate.
        errorCalculator.calculate_errors(sln, ref_sln);

        // If err_est too large, adapt the mesh->
        if(errorCalculator.get_total_error_squared()  * 100. < ERR_STOP)
            done = true;
        else
        {
            adaptivity.adapt(&selector);
        }

        // Clean up.
        delete [] coeff_vec;

        // Increase counter.
        as++;
    }
    while (done == false);

    complex sum = 0;
    for (int i = 0; i < space->get_num_dofs(); i++)
        sum += newton.get_sln_vector()[i];
    printf("coefficient sum = %f\n", sum);

    complex expected_sum;
    expected_sum.real(1.4685364e-005);
    expected_sum.imag(-5.45632171e-007);

    bool success = true;
    if(std::abs(sum - expected_sum) > 1e-6)
        success = false;

    int ndof = space->get_num_dofs();
    if(ndof != 82) // Tested value as of May 2013.
        success = false;

    if(success)
    {
        printf("Success!\n");
        return 0;
    }
    else
    {
        printf("Failure!\n");
        return -1;
    }
}
示例#20
0
int main(int argc, char* argv[])
{
  // Define nonlinear magnetic permeability via a cubic spline.
  Hermes::vector<double> mu_inv_pts(0.0,      0.5,      0.9,      1.0,      1.1,      1.2,      1.3,
                                    1.4,      1.6,      1.7,      1.8,      1.9,      3.0,      5.0,     10.0);
  Hermes::vector<double> mu_inv_val(1/1500.0, 1/1480.0, 1/1440.0, 1/1400.0, 1/1300.0, 1/1150.0, 1/950.0,
                                    1/750.0,  1/250.0,  1/180.0,  1/175.0,  1/150.0,  1/20.0,   1/10.0,  1/5.0);
  /*
  // This is for debugging (iron is assumed linear with mu_r = 300.0
  Hermes::vector<double> mu_inv_pts(0.0,      10.0);
  Hermes::vector<double> mu_inv_val(1/300.0,   1/300.0);
  */

  // Create the cubic spline (and plot it for visual control).
  double bc_left = 0.0;
  double bc_right = 0.0;
  bool first_der_left = false;
  bool first_der_right = false;
  bool extrapolate_der_left = false;
  bool extrapolate_der_right = false;
  CubicSpline mu_inv_iron(mu_inv_pts, mu_inv_val, bc_left, bc_right, first_der_left, first_der_right,
                          extrapolate_der_left, extrapolate_der_right);
  info("Saving cubic spline into a Pylab file spline.dat.");
  // The interval of definition of the spline will be
  // extended by "interval_extension" on both sides.
  double interval_extension = 1.0; 
  bool plot_derivative = false;
  mu_inv_iron.plot("spline.dat", interval_extension, plot_derivative);
  plot_derivative = true;
  mu_inv_iron.plot("spline_der.dat", interval_extension, plot_derivative);

  // Load the mesh.
  Mesh mesh;
  MeshReaderH2D mloader;
  mloader.load("actuator.mesh", &mesh);

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

  //MeshView mv("Mesh", new WinGeom(0, 0, 400, 400));
  //mv.show(&mesh);

  // Initialize boundary conditions.
  DefaultEssentialBCConst<double> bc_essential(BDY_DIRICHLET, 0.0);
  EssentialBCs<double> bcs(&bc_essential);

  // Create an H1 space with default shapeset.
  H1Space<double> space(&mesh, &bcs, P_INIT);
  info("ndof: %d", Space<double>::get_num_dofs(&space));

  // Initialize the weak formulation
  // This determines the increase of integration order
  // for the axisymmetric term containing 1/r. Default is 3.
  int order_inc = 3; 
  CustomWeakFormMagnetostatics wf(MAT_IRON_1, MAT_IRON_2, &mu_inv_iron, MAT_AIR,
                                  MAT_COPPER, MU_VACUUM, CURRENT_DENSITY, order_inc);

  // Initialize the FE problem.
  DiscreteProblem<double> dp(&wf, &space);
  
  // Initialize the solution.
  ConstantSolution<double> sln(&mesh, INIT_COND);

  // Project the initial condition on the FE space to obtain initial
  // coefficient vector for the Newton's method.
  info("Projecting to obtain initial vector for the Newton's method.");
  double* coeff_vec = new double[Space<double>::get_num_dofs(&space)] ;
  OGProjection<double>::project_global(&space, &sln, coeff_vec, matrix_solver_type);

  // Perform Newton's iteration.
  Hermes::Hermes2D::NewtonSolver<double> newton(&dp, matrix_solver_type);
  bool verbose = true;
  newton.set_verbose_output(verbose);
  try
  {
    newton.solve(coeff_vec, NEWTON_TOL, NEWTON_MAX_ITER);
  }
  catch(Hermes::Exceptions::Exception e)
  {
    e.printMsg();
    error("Newton's iteration failed.");
  };

  // Translate the resulting coefficient vector into the Solution sln.
  Solution<double>::vector_to_solution(coeff_vec, &space, &sln);

  // Cleanup.
  delete [] coeff_vec;

  // Visualise the solution and mesh.
  ScalarView s_view1("Vector potencial", new WinGeom(0, 0, 350, 450));
  FilterVectorPotencial vector_potencial(Hermes::vector<MeshFunction<double> *>(&sln, &sln),
                                         Hermes::vector<int>(H2D_FN_VAL, H2D_FN_VAL));
  s_view1.show_mesh(false);
  s_view1.show(&vector_potencial);

  ScalarView s_view2("Flux density", new WinGeom(360, 0, 350, 450));
  FilterFluxDensity flux_density(Hermes::vector<MeshFunction<double> *>(&sln, &sln));
  s_view2.show_mesh(false);
  s_view2.show(&flux_density);

  OrderView o_view("Mesh", new WinGeom(720, 0, 350, 450));
  o_view.show(&space);

  // Wait for all views to be closed.
  View::wait();
  return 0;
}
示例#21
0
int main(int argc, char* argv[])
{
  // Choose a Butcher's table or define your own.
  ButcherTable bt(butcher_table_type);
  if (bt.is_explicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage explicit R-K method.", bt.get_size());
  if (bt.is_diagonally_implicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage diagonally implicit R-K method.", bt.get_size());
  if (bt.is_fully_implicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage fully implicit R-K method.", bt.get_size());

  // Load the mesh.
  MeshSharedPtr mesh(new Mesh), basemesh(new Mesh);
  MeshReaderH2D mloader;
  mloader.load("square.mesh", basemesh);
  mesh->copy(basemesh);

  // Initial mesh refinements.
  for(int i = 0; i < INIT_GLOB_REF_NUM; i++) mesh->refine_all_elements();
  mesh->refine_towards_boundary("Top", INIT_REF_NUM_BDY);

  // Initialize boundary conditions.
  CustomEssentialBCNonConst bc_essential(Hermes::vector<std::string>("Bottom", "Right", "Top", "Left"));
  EssentialBCs<double> bcs(&bc_essential);

  // Create an H1 space with default shapeset.
  SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
  int ndof_coarse = Space<double>::get_num_dofs(space);
  adaptivity.set_space(space);
  Hermes::Mixins::Loggable::Static::info("ndof_coarse = %d.", ndof_coarse);

  // Zero initial solution. This is why we use H_OFFSET.
  MeshFunctionSharedPtr<double> h_time_prev(new ZeroSolution<double>(mesh)), h_time_new(new ZeroSolution<double>(mesh));

  // Initialize the constitutive relations.
  ConstitutiveRelations* constitutive_relations;
  if(constitutive_relations_type == CONSTITUTIVE_GENUCHTEN)
    constitutive_relations = new ConstitutiveRelationsGenuchten(ALPHA, M, N, THETA_S, THETA_R, K_S, STORATIVITY);
  else
    constitutive_relations = new ConstitutiveRelationsGardner(ALPHA, THETA_S, THETA_R, K_S);

  // Initialize the weak formulation.
  CustomWeakFormRichardsRK wf(constitutive_relations);

  // Initialize the FE problem.
  DiscreteProblem<double> dp(&wf, space);

  // Create a refinement selector.
  H1ProjBasedSelector<double> selector(CAND_LIST);

  // Visualize initial condition.
  char title[100];
  ScalarView view("Initial condition", new WinGeom(0, 0, 440, 350));
  OrderView ordview("Initial mesh", new WinGeom(445, 0, 440, 350));
  view.show(h_time_prev);
  ordview.show(space);

  // DOF and CPU convergence graphs initialization.
  SimpleGraph graph_dof, graph_cpu;
  
  // Time measurement.
  Hermes::Mixins::TimeMeasurable cpu_time;
  cpu_time.tick();
  
  // Time stepping loop.
  double current_time = 0; int ts = 1;
  do 
  {
    // Periodic global derefinement.
    if (ts > 1 && ts % UNREF_FREQ == 0) 
    {
      Hermes::Mixins::Loggable::Static::info("Global mesh derefinement.");
      switch (UNREF_METHOD) {
        case 1: mesh->copy(basemesh);
                space->set_uniform_order(P_INIT);
                break;
        case 2: mesh->unrefine_all_elements();
                space->set_uniform_order(P_INIT);
                break;
        case 3: space->unrefine_all_mesh_elements();
                space->adjust_element_order(-1, -1, P_INIT, P_INIT);
                break;
        default: throw Hermes::Exceptions::Exception("Wrong global derefinement method.");
      }

      space->assign_dofs();
      ndof_coarse = Space<double>::get_num_dofs(space);
    }

    // Spatial adaptivity loop. Note: h_time_prev must not be changed 
    // during spatial adaptivity. 
    bool done = false; int as = 1;
    double err_est;
    do {
      Hermes::Mixins::Loggable::Static::info("Time step %d, adaptivity step %d:", ts, as);

      // Construct globally refined reference mesh and setup reference space.
      Mesh::ReferenceMeshCreator refMeshCreator(mesh);
      MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh();

      Space<double>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh);
      SpaceSharedPtr<double> ref_space = refSpaceCreator.create_ref_space();
      int ndof_ref = Space<double>::get_num_dofs(ref_space);

      // Time measurement.
      cpu_time.tick();

      // Initialize Runge-Kutta time stepping.
      RungeKutta<double> runge_kutta(&wf, ref_space, &bt);

      // Perform one Runge-Kutta time step according to the selected Butcher's table.
      Hermes::Mixins::Loggable::Static::info("Runge-Kutta time step (t = %g s, tau = %g s, stages: %d).",
           current_time, time_step, bt.get_size());
      try
      {
        runge_kutta.set_time(current_time);
        runge_kutta.set_time_step(time_step);
        runge_kutta.set_max_allowed_iterations(NEWTON_MAX_ITER);
        runge_kutta.set_tolerance(NEWTON_TOL);
        runge_kutta.rk_time_step_newton(h_time_prev, h_time_new);
      }
      catch(Exceptions::Exception& e)
      {
        e.print_msg();
        throw Hermes::Exceptions::Exception("Runge-Kutta time step failed");
      }

      // Project the fine mesh solution onto the coarse mesh.
      MeshFunctionSharedPtr<double> sln_coarse(new Solution<double>);
      Hermes::Mixins::Loggable::Static::info("Projecting fine mesh solution on coarse mesh for error estimation.");
      OGProjection<double> ogProjection; ogProjection.project_global(space, h_time_new, sln_coarse); 

      // Calculate element errors and total error estimate.
      Hermes::Mixins::Loggable::Static::info("Calculating error estimate.");
      errorCalculator.calculate_errors(sln_coarse, h_time_new, true);
      double err_est_rel_total = errorCalculator.get_total_error_squared() * 100;

      // Report results.
      Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_ref: %d, err_est_rel: %g%%", 
           Space<double>::get_num_dofs(space), Space<double>::get_num_dofs(ref_space), err_est_rel_total);

      // Time measurement.
      cpu_time.tick();

      // If err_est too large, adapt the mesh.
      if (err_est_rel_total < ERR_STOP) done = true;
      else 
      {
        Hermes::Mixins::Loggable::Static::info("Adapting the coarse mesh.");
        done = adaptivity.adapt(&selector);

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

    // Add entry to DOF and CPU convergence graphs.
    graph_dof.add_values(current_time, Space<double>::get_num_dofs(space));
    graph_dof.save("conv_dof_est.dat");
    graph_cpu.add_values(current_time, cpu_time.accumulated());
    graph_cpu.save("conv_cpu_est.dat");

    // Visualize the solution and mesh->
    char title[100];
    sprintf(title, "Solution, time %g", current_time);
    view.set_title(title);
    view.show_mesh(false);
    view.show(h_time_new);
    sprintf(title, "Mesh, time %g", current_time);
    ordview.set_title(title);
    ordview.show(space);

    // Copy last reference solution into h_time_prev.
    h_time_prev->copy(h_time_new);

    // Increase current time and counter of time steps.
    current_time += time_step;
    ts++;
  }
  while (current_time < T_FINAL);

  // Wait for all views to be closed.
  View::wait();
  return 0;
}
示例#22
0
int main(int argc, char* argv[])
{
  // Instantiate a class with global functions.
  Hermes2D hermes2d;

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

  // Load the mesh.
  Mesh mesh;
  H2DReader mloader;
  mloader.load("domain.mesh", &mesh);

  // Perform initial mesh refinements.
  for (int i=0; i < INIT_REF_NUM; i++) mesh.refine_all_elements();
  
  // Initialize boundary conditions
  CustomEssentialBCNonConst bc_essential("Boundary horizontal");
  EssentialBCs bcs(&bc_essential);

  // Create an H1 space with default shapeset.
  H1Space space(&mesh, &bcs, P_INIT);
  int ndof = space.get_num_dofs();
  info("ndof = %d", ndof);

  // Initialize the weak formulation.
  CustomWeakFormGeneral wf("Boundary horizontal");

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

  SparseMatrix* matrix = create_matrix(matrix_solver);
  Vector* rhs = create_vector(matrix_solver);
  Solver* solver = create_linear_solver(matrix_solver, matrix, rhs);

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

  // Initial coefficient vector for the Newton's method.  
  scalar* coeff_vec = new scalar[ndof];
  memset(coeff_vec, 0, ndof*sizeof(scalar));

  // Perform Newton's iteration.
  if (!hermes2d.solve_newton(coeff_vec, &dp, solver, matrix, rhs)) error("Newton's iteration failed.");

  // Translate the resulting coefficient vector into the Solution sln.
  Solution sln;
  Solution::vector_to_solution(coeff_vec, &space, &sln);

  // Time measurement.
  cpu_time.tick();

  // Clean up.
  delete solver;
  delete matrix;
  delete rhs;
  delete [] coeff_vec;

  // View the solution and mesh.
  ScalarView sview("Solution", new WinGeom(0, 0, 440, 350));
  sview.show(&sln);
  OrderView  oview("Polynomial orders", new WinGeom(450, 0, 400, 350));
  oview.show(&space);

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

  // Print timing information.
  verbose("Total running time: %g s", cpu_time.accumulated());

  // Wait for all views to be closed.
  View::wait();

  return 0;
}
示例#23
0
int main(int argc, char* argv[])
{
  try
  {
    // Sanity check for omega.
    double K_squared = Hermes::sqr(OMEGA / M_PI) * (OMEGA - 2) / (1 - OMEGA);
    if (K_squared <= 0) throw Hermes::Exceptions::Exception("Wrong choice of omega, K_squared < 0!");
    double K_norm_coeff = std::sqrt(K_squared) / std::sqrt(Hermes::sqr(K_x) + Hermes::sqr(K_y));
    Hermes::Mixins::Loggable::Static::info("Wave number K = %g", std::sqrt(K_squared));
    K_x *= K_norm_coeff;
    K_y *= K_norm_coeff;

    // Wave number.
    double K = std::sqrt(Hermes::sqr(K_x) + Hermes::sqr(K_y));

    // Choose a Butcher's table or define your own.
    ButcherTable bt(butcher_table);
    if (bt.is_explicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage explicit R-K method.", bt.get_size());
    if (bt.is_diagonally_implicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage diagonally implicit R-K method.", bt.get_size());
    if (bt.is_fully_implicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage fully implicit R-K method.", bt.get_size());

    // Load the mesh.
    MeshSharedPtr E_mesh(new Mesh), H_mesh(new Mesh), P_mesh(new Mesh);
    MeshReaderH2D mloader;
    mloader.load("domain.mesh", E_mesh);
    mloader.load("domain.mesh", H_mesh);
    mloader.load("domain.mesh", P_mesh);

    // Perform initial mesh refinemets.
    for (int i = 0; i < INIT_REF_NUM; i++)
    {
      E_mesh->refine_all_elements();
      H_mesh->refine_all_elements();
      P_mesh->refine_all_elements();
    }

    // Initialize solutions.
    double current_time = 0;
    MeshFunctionSharedPtr<double> E_time_prev(new CustomInitialConditionE(E_mesh, current_time, OMEGA, K_x, K_y));
    MeshFunctionSharedPtr<double> H_time_prev(new CustomInitialConditionH(H_mesh, current_time, OMEGA, K_x, K_y));
    MeshFunctionSharedPtr<double> P_time_prev(new CustomInitialConditionP(P_mesh, current_time, OMEGA, K_x, K_y));
    std::vector<MeshFunctionSharedPtr<double> > slns_time_prev({ E_time_prev, H_time_prev, P_time_prev });
    MeshFunctionSharedPtr<double> E_time_new(new Solution<double>(E_mesh)), H_time_new(new Solution<double>(H_mesh)), P_time_new(new Solution<double>(P_mesh));
    MeshFunctionSharedPtr<double> E_time_new_coarse(new Solution<double>(E_mesh)), H_time_new_coarse(new Solution<double>(H_mesh)), P_time_new_coarse(new Solution<double>(P_mesh));
    std::vector<MeshFunctionSharedPtr<double> > slns_time_new({ E_time_new, H_time_new, P_time_new });

    // Initialize the weak formulation.
    WeakFormSharedPtr<double> wf(new CustomWeakFormMD(OMEGA, K_x, K_y, MU_0, EPS_0, EPS_INF, EPS_Q, TAU));

    // Initialize boundary conditions
    DefaultEssentialBCConst<double> bc_essential("Bdy", 0.0);
    EssentialBCs<double> bcs(&bc_essential);

    SpaceSharedPtr<double> E_space(new HcurlSpace<double>(E_mesh, &bcs, P_INIT));
    SpaceSharedPtr<double> H_space(new H1Space<double>(H_mesh, NULL, P_INIT));
    //L2Space<double> H_space(mesh, P_INIT));
    SpaceSharedPtr<double> P_space(new HcurlSpace<double>(P_mesh, &bcs, P_INIT));

    std::vector<SpaceSharedPtr<double> > spaces = std::vector<SpaceSharedPtr<double> >({ E_space, H_space, P_space });

    // Initialize views.
    ScalarView E1_view("Solution E1", new WinGeom(0, 0, 400, 350));
    E1_view.fix_scale_width(50);
    ScalarView E2_view("Solution E2", new WinGeom(410, 0, 400, 350));
    E2_view.fix_scale_width(50);
    ScalarView H_view("Solution H", new WinGeom(0, 410, 400, 350));
    H_view.fix_scale_width(50);
    ScalarView P1_view("Solution P1", new WinGeom(410, 410, 400, 350));
    P1_view.fix_scale_width(50);
    ScalarView P2_view("Solution P2", new WinGeom(820, 410, 400, 350));
    P2_view.fix_scale_width(50);

    // Visualize initial conditions.
    char title[100];
    sprintf(title, "E1 - Initial Condition");
    E1_view.set_title(title);
    E1_view.show(E_time_prev, H2D_FN_VAL_0);
    sprintf(title, "E2 - Initial Condition");
    E2_view.set_title(title);
    E2_view.show(E_time_prev, H2D_FN_VAL_1);

    sprintf(title, "H - Initial Condition");
    H_view.set_title(title);
    H_view.show(H_time_prev);

    sprintf(title, "P1 - Initial Condition");
    P1_view.set_title(title);
    P1_view.show(P_time_prev, H2D_FN_VAL_0);
    sprintf(title, "P2 - Initial Condition");
    P2_view.set_title(title);
    P2_view.show(P_time_prev, H2D_FN_VAL_1);

    // Initialize Runge-Kutta time stepping.
    RungeKutta<double> runge_kutta(wf, spaces, &bt);
    runge_kutta.set_newton_max_allowed_iterations(NEWTON_MAX_ITER);
    runge_kutta.set_newton_tolerance(NEWTON_TOL);
    runge_kutta.set_verbose_output(true);

    // Initialize refinement selector.
    H1ProjBasedSelector<double> H1selector(CAND_LIST);
    HcurlProjBasedSelector<double> HcurlSelector(CAND_LIST);

    // Time stepping loop.
    int ts = 1;
    do
    {
      // Perform one Runge-Kutta time step according to the selected Butcher's table.
      Hermes::Mixins::Loggable::Static::info("\nRunge-Kutta time step (t = %g s, time_step = %g s, stages: %d).",
        current_time, time_step, bt.get_size());

      // Periodic global derefinements.
      if (ts > 1 && ts % UNREF_FREQ == 0 && REFINEMENT_COUNT > 0)
      {
        Hermes::Mixins::Loggable::Static::info("Global mesh derefinement.");
        REFINEMENT_COUNT = 0;

        E_space->unrefine_all_mesh_elements(true);
        H_space->unrefine_all_mesh_elements(true);
        P_space->unrefine_all_mesh_elements(true);

        E_space->adjust_element_order(-1, P_INIT);
        H_space->adjust_element_order(-1, P_INIT);
        P_space->adjust_element_order(-1, P_INIT);

        E_space->assign_dofs();
        H_space->assign_dofs();
        P_space->assign_dofs();
      }

      // Adaptivity loop:
      int as = 1;
      bool done = false;
      do
      {
        Hermes::Mixins::Loggable::Static::info("Adaptivity step %d:", as);

        // Construct globally refined reference mesh and setup reference space.
        int order_increase = 1;

        Mesh::ReferenceMeshCreator refMeshCreatorE(E_mesh);
        Mesh::ReferenceMeshCreator refMeshCreatorH(H_mesh);
        Mesh::ReferenceMeshCreator refMeshCreatorP(P_mesh);
        MeshSharedPtr ref_mesh_E = refMeshCreatorE.create_ref_mesh();
        MeshSharedPtr ref_mesh_H = refMeshCreatorH.create_ref_mesh();
        MeshSharedPtr ref_mesh_P = refMeshCreatorP.create_ref_mesh();

        Space<double>::ReferenceSpaceCreator refSpaceCreatorE(E_space, ref_mesh_E, order_increase);
        SpaceSharedPtr<double> ref_space_E = refSpaceCreatorE.create_ref_space();
        Space<double>::ReferenceSpaceCreator refSpaceCreatorH(H_space, ref_mesh_H, order_increase);
        SpaceSharedPtr<double> ref_space_H = refSpaceCreatorH.create_ref_space();
        Space<double>::ReferenceSpaceCreator refSpaceCreatorP(P_space, ref_mesh_P, order_increase);
        SpaceSharedPtr<double> ref_space_P = refSpaceCreatorP.create_ref_space();
        std::vector<SpaceSharedPtr<double> > ref_spaces({ ref_space_E, ref_space_H, ref_space_P });

        int ndof = Space<double>::get_num_dofs(ref_spaces);
        Hermes::Mixins::Loggable::Static::info("ndof = %d.", ndof);

        try
        {
          runge_kutta.set_spaces(ref_spaces);
          runge_kutta.set_time(current_time);
          runge_kutta.set_time_step(time_step);
          runge_kutta.rk_time_step_newton(slns_time_prev, slns_time_new);
        }
        catch (Exceptions::Exception& e)
        {
          e.print_msg();
          throw Hermes::Exceptions::Exception("Runge-Kutta time step failed");
        }

        // Visualize the solutions.
        char title[100];
        sprintf(title, "E1, t = %g", current_time + time_step);
        E1_view.set_title(title);
        E1_view.show(E_time_new, H2D_FN_VAL_0);
        sprintf(title, "E2, t = %g", current_time + time_step);
        E2_view.set_title(title);
        E2_view.show(E_time_new, H2D_FN_VAL_1);

        sprintf(title, "H, t = %g", current_time + time_step);
        H_view.set_title(title);
        H_view.show(H_time_new);

        sprintf(title, "P1, t = %g", current_time + time_step);
        P1_view.set_title(title);
        P1_view.show(P_time_new, H2D_FN_VAL_0);
        sprintf(title, "P2, t = %g", current_time + time_step);
        P2_view.set_title(title);
        P2_view.show(P_time_new, H2D_FN_VAL_1);

        // Project the fine mesh solution onto the coarse mesh.
        Hermes::Mixins::Loggable::Static::info("Projecting reference solution on coarse mesh.");
        OGProjection<double>::project_global({ E_space, H_space, P_space }, { E_time_new, H_time_new, P_time_new }, { E_time_new_coarse, H_time_new_coarse, P_time_new_coarse });

        // Calculate element errors and total error estimate.
        Hermes::Mixins::Loggable::Static::info("Calculating error estimate.");
        adaptivity.set_spaces({ E_space, H_space, P_space });
        errorCalculator.calculate_errors({ E_time_new_coarse, H_time_new_coarse, P_time_new_coarse }, { E_time_new, H_time_new, P_time_new });

        double err_est_rel_total = errorCalculator.get_total_error_squared() * 100.;

        // Report results.
        Hermes::Mixins::Loggable::Static::info("Error estimate: %g%%", err_est_rel_total);

        // If err_est too large, adapt the mesh.
        if (err_est_rel_total < ERR_STOP)
        {
          Hermes::Mixins::Loggable::Static::info("Error estimate under the specified threshold -> moving to next time step.");
          done = true;
        }
        else
        {
          Hermes::Mixins::Loggable::Static::info("Adapting coarse mesh.");
          REFINEMENT_COUNT++;
          done = adaptivity.adapt({ &HcurlSelector, &H1selector, &HcurlSelector });

          if (!done)
            as++;
        }
      } while (!done);

      //View::wait();
      E_time_prev->copy(E_time_new);
      H_time_prev->copy(H_time_new);
      P_time_prev->copy(P_time_new);

      // Update time.
      current_time += time_step;
      ts++;
    } while (current_time < T_FINAL);

    // Wait for the view to be closed.
    View::wait();
  }
  catch (std::exception& e)
  {
    std::cout << e.what();
  }

  return 0;
}
示例#24
0
int main(int argc, char* argv[])
{
  // Time measurement.
  Hermes::Mixins::TimeMeasurable cpu_time;
  cpu_time.tick();

  // Load the mesh.
  Mesh mesh;
  if (USE_XML_FORMAT == true)
  {
    MeshReaderH2DXML mloader;  
    Hermes::Mixins::Loggable::Static::info("Reading mesh in XML format.");
    mloader.load("domain.xml", &mesh);
  }
  else 
  {
    MeshReaderH2D mloader;
    Hermes::Mixins::Loggable::Static::info("Reading mesh in original format.");
    mloader.load("domain.mesh", &mesh);
  }

  // Perform initial mesh refinements.
  for (int i = 0; i < INIT_REF_NUM; i++) mesh.refine_all_elements();
  
  // Initialize boundary conditions
  CustomEssentialBCNonConst bc_essential("Horizontal");
  EssentialBCs<double> bcs(&bc_essential);

  // Create an H1 space with default shapeset.
  H1Space<double> space(&mesh, &bcs, P_INIT);
  int ndof = space.get_num_dofs();
  Hermes::Mixins::Loggable::Static::info("ndof = %d", ndof);

  // Initialize the weak formulation.
  CustomWeakFormGeneral wf("Horizontal");

  // Initialize the FE problem.
  DiscreteProblem<double> dp(&wf, &space);

  // Initialize Newton solver.
  NewtonSolver<double> newton(&dp);

  // Perform Newton's iteration.
  try
  {
    newton.solve();
  }
  catch(std::exception& e)
  {
    std::cout << e.what();
    
  }

  // Translate the resulting coefficient vector into a Solution.
  Solution<double> sln;
  Solution<double>::vector_to_solution(newton.get_sln_vector(), &space, &sln);

  // Time measurement.
  cpu_time.tick();

  // View the solution and mesh.
  ScalarView sview("Solution", new WinGeom(0, 0, 440, 350));
  sview.show(&sln);
  OrderView oview("Polynomial orders", new WinGeom(450, 0, 405, 350));
  oview.show(&space);

  // Print timing information.
  Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());

  // Wait for all views to be closed.
  View::wait();

  return 0;
}
示例#25
0
int main(int argc, char* argv[])
{
  // Instantiate a class with global functions.
  

  // Choose a Butcher's table or define your own.
  ButcherTable bt(butcher_table_type);
  if (bt.is_explicit()) info("Using a %d-stage explicit R-K method.", bt.get_size());
  if (bt.is_diagonally_implicit()) info("Using a %d-stage diagonally implicit R-K method.", bt.get_size());
  if (bt.is_fully_implicit()) info("Using a %d-stage fully implicit R-K method.", bt.get_size());

  // Turn off adaptive time stepping if R-K method is not embedded.
  if (bt.is_embedded() == false && ADAPTIVE_TIME_STEP_ON == true) {
    warn("R-K method not embedded, turning off adaptive time stepping.");
    ADAPTIVE_TIME_STEP_ON = false;
  }

  // Load the mesh.
  Mesh mesh, basemesh;
  MeshReaderH2D mloader;
  mloader.load("square.mesh", &basemesh);
  mesh.copy(&basemesh);

  // Initial mesh refinements.
  for(int i = 0; i < INIT_REF_NUM; i++) mesh.refine_all_elements();

  // Convert initial condition into a Solution<std::complex<double> >.
  CustomInitialCondition psi_time_prev(&mesh);

  // Initialize the weak formulation.
  double current_time = 0;

  CustomWeakFormGPRK wf(h, m, g, omega);

  // Initialize boundary conditions.
  DefaultEssentialBCConst<std::complex<double> > bc_essential("Bdy", 0.0);
  EssentialBCs<std::complex<double> > bcs(&bc_essential);

  // Create an H1 space with default shapeset.
  H1Space<std::complex<double> > space(&mesh, &bcs, P_INIT);
  int ndof = space.get_num_dofs();
  info("ndof = %d", ndof);
 
  // Initialize the FE problem.
  DiscreteProblem<std::complex<double> > dp(&wf, &space);

  // Create a refinement selector.
  H1ProjBasedSelector<std::complex<double> > selector(CAND_LIST, CONV_EXP, H2DRS_DEFAULT_ORDER);

  // Visualize initial condition.
  char title[100];

  ScalarView sview_real("Initial condition - real part", new WinGeom(0, 0, 600, 500));
  ScalarView sview_imag("Initial condition - imaginary part", new WinGeom(610, 0, 600, 500));

  sview_real.show_mesh(false);
  sview_imag.show_mesh(false);
  sview_real.fix_scale_width(50);
  sview_imag.fix_scale_width(50);
  OrderView ord_view("Initial mesh", new WinGeom(445, 0, 440, 350));
  ord_view.fix_scale_width(50);
  ScalarView time_error_view("Temporal error", new WinGeom(0, 400, 440, 350));
  time_error_view.fix_scale_width(50);
  time_error_view.fix_scale_width(60);
  ScalarView space_error_view("Spatial error", new WinGeom(445, 400, 440, 350));
  space_error_view.fix_scale_width(50);
  RealFilter real(&psi_time_prev);
  ImagFilter imag(&psi_time_prev);
  sview_real.show(&real);
  sview_imag.show(&imag);
  ord_view.show(&space);

  // Graph for time step history.
  SimpleGraph time_step_graph;
  if (ADAPTIVE_TIME_STEP_ON) info("Time step history will be saved to file time_step_history.dat.");
  
  // Time stepping:
  int num_time_steps = (int)(T_FINAL/time_step + 0.5);
  for(int ts = 1; ts <= num_time_steps; ts++)
  // Time stepping loop.
  double current_time = 0.0; int ts = 1;
  do 
  {
    info("Begin time step %d.", ts);
    // Periodic global derefinement.
    if (ts > 1 && ts % UNREF_FREQ == 0) 
    {
      info("Global mesh derefinement.");
      switch (UNREF_METHOD) {
        case 1: mesh.copy(&basemesh);
                space.set_uniform_order(P_INIT);
                break;
        case 2: mesh.unrefine_all_elements();
                space.set_uniform_order(P_INIT);
                break;
        case 3: mesh.unrefine_all_elements();
                //space.adjust_element_order(-1, P_INIT);
                space.adjust_element_order(-1, -1, P_INIT, P_INIT);
                break;
        default: error("Wrong global derefinement method.");
      }

      ndof = Space<std::complex<double> >::get_num_dofs(&space);
    }
    info("ndof: %d", ndof);

    // Spatial adaptivity loop. Note: psi_time_prev must not be 
    // changed during spatial adaptivity. 
    Solution<std::complex<double> > ref_sln;
    Solution<std::complex<double> >* time_error_fn;
    if (bt.is_embedded() == true) time_error_fn = new Solution<std::complex<double> >(&mesh);
    else time_error_fn = NULL;
    bool done = false; int as = 1;
    double err_est;
    do {
      // Construct globally refined reference mesh and setup reference space.
      Space<std::complex<double> >* ref_space = Space<std::complex<double> >::construct_refined_space(&space);

      // Initialize discrete problem on reference mesh.
      DiscreteProblem<std::complex<double> >* ref_dp = new DiscreteProblem<std::complex<double> >(&wf, ref_space);
      
      RungeKutta<std::complex<double> > runge_kutta(ref_dp, &bt, matrix_solver_type);

      // Runge-Kutta step on the fine mesh.
      info("Runge-Kutta time step on fine mesh (t = %g s, time step = %g s, stages: %d).", 
         current_time, time_step, bt.get_size());
      bool verbose = true;

      try
      {
        runge_kutta.rk_time_step_newton(current_time, time_step, &psi_time_prev, 
                                    &ref_sln, time_error_fn, false, false, verbose, 
                                    NEWTON_TOL_FINE, NEWTON_MAX_ITER);
      }
      catch(Exceptions::Exception& e)
      {
        e.printMsg();
        error("Runge-Kutta time step failed");
      }

      /* If ADAPTIVE_TIME_STEP_ON == true, estimate temporal error. 
         If too large or too small, then adjust it and restart the time step. */

      double rel_err_time = 0;
      if (bt.is_embedded() == true) {
        info("Calculating temporal error estimate.");

        // Show temporal error.
        char title[100];
        sprintf(title, "Temporal error est, spatial adaptivity step %d", as);     
        time_error_view.set_title(title);
        time_error_view.show_mesh(false);
        RealFilter abs_time(time_error_fn);
        AbsFilter abs_tef(&abs_time);
        time_error_view.show(&abs_tef, HERMES_EPS_HIGH);

        rel_err_time = Global<std::complex<double> >::calc_norm(time_error_fn, HERMES_H1_NORM) / 
                       Global<std::complex<double> >::calc_norm(&ref_sln, HERMES_H1_NORM) * 100;
        if (ADAPTIVE_TIME_STEP_ON == false) info("rel_err_time: %g%%", rel_err_time);
      }

      if (ADAPTIVE_TIME_STEP_ON) {
        if (rel_err_time > TIME_ERR_TOL_UPPER) {
          info("rel_err_time %g%% is above upper limit %g%%", rel_err_time, TIME_ERR_TOL_UPPER);
          info("Decreasing time step from %g to %g s and restarting time step.", 
               time_step, time_step * TIME_STEP_DEC_RATIO);
          time_step *= TIME_STEP_DEC_RATIO;
          delete ref_space;
          delete ref_dp;
          continue;
        }
        else if (rel_err_time < TIME_ERR_TOL_LOWER) {
          info("rel_err_time = %g%% is below lower limit %g%%", rel_err_time, TIME_ERR_TOL_LOWER);
          info("Increasing time step from %g to %g s.", time_step, time_step * TIME_STEP_INC_RATIO);
          time_step *= TIME_STEP_INC_RATIO;
          delete ref_space;
          delete ref_dp;
          continue;
        }
        else {
          info("rel_err_time = %g%% is in acceptable interval (%g%%, %g%%)", 
            rel_err_time, TIME_ERR_TOL_LOWER, TIME_ERR_TOL_UPPER);
        }

        // Add entry to time step history graph.
        time_step_graph.add_values(current_time, time_step);
        time_step_graph.save("time_step_history.dat");
      }

      /* Estimate spatial errors and perform mesh refinement */

      info("Spatial adaptivity step %d.", as);

      // Project the fine mesh solution onto the coarse mesh.
      Solution<std::complex<double> > sln;
      info("Projecting fine mesh solution on coarse mesh for error estimation.");
      OGProjection<std::complex<double> >::project_global(&space, &ref_sln, &sln, matrix_solver_type); 

      // Show spatial error.
      sprintf(title, "Spatial error est, spatial adaptivity step %d", as);  
      DiffFilter<std::complex<double> >* space_error_fn = new DiffFilter<std::complex<double> >(Hermes::vector<MeshFunction<std::complex<double> >*>(&ref_sln, &sln));   
      space_error_view.set_title(title);
      space_error_view.show_mesh(false);
      RealFilter abs_space(space_error_fn);
      AbsFilter abs_sef(&abs_space);
      space_error_view.show(&abs_sef);

      // Calculate element errors and spatial error estimate.
      info("Calculating spatial error estimate.");
      Adapt<std::complex<double> >* adaptivity = new Adapt<std::complex<double> >(&space);
      double err_rel_space = adaptivity->calc_err_est(&sln, &ref_sln) * 100;

      // Report results.
      info("ndof: %d, ref_ndof: %d, err_rel_space: %g%%", 
           Space<std::complex<double> >::get_num_dofs(&space), Space<std::complex<double> >::get_num_dofs(ref_space), err_rel_space);

      // If err_est too large, adapt the mesh.
      if (err_rel_space < SPACE_ERR_TOL) done = true;
      else 
      {
        info("Adapting the coarse mesh.");
        done = adaptivity->adapt(&selector, THRESHOLD, STRATEGY, MESH_REGULARITY);

        if (Space<std::complex<double> >::get_num_dofs(&space) >= NDOF_STOP) 
          done = true;
        else
          // Increase the counter of performed adaptivity steps.
          as++;
      }
      
      // Clean up.
      delete adaptivity;
      delete ref_space;
      delete ref_dp;
      delete space_error_fn;
    }
    while (done == false);

    // Clean up.
    if (time_error_fn != NULL) delete time_error_fn;

    // Visualize the solution and mesh.
    char title[100];
    sprintf(title, "Solution - real part, Time %3.2f s", current_time);
    sview_real.set_title(title);
    sprintf(title, "Solution - imaginary part, Time %3.2f s", current_time);
    sview_imag.set_title(title);
    RealFilter real(&ref_sln);
    ImagFilter imag(&ref_sln);
    sview_real.show(&real);
    sview_imag.show(&imag);
    sprintf(title, "Mesh, time %g s", current_time);
    ord_view.set_title(title);
    ord_view.show(&space);

    // Copy last reference solution into psi_time_prev.
    psi_time_prev.copy(&ref_sln);

    // Increase current time and counter of time steps.
    current_time += time_step;
    ts++;
  }
  while (current_time < T_FINAL);

  // Wait for all views to be closed.
  View::wait();
  return 0;
}
示例#26
0
int main(int argc, char* argv[])
{
  // Choose a Butcher's table or define your own.
  ButcherTable bt(butcher_table_type);
  if (bt.is_explicit()) info("Using a %d-stage explicit R-K method.", bt.get_size());
  if (bt.is_diagonally_implicit()) info("Using a %d-stage diagonally implicit R-K method.", bt.get_size());
  if (bt.is_fully_implicit()) info("Using a %d-stage fully implicit R-K method.", bt.get_size());

  // Load the mesh.
  Mesh mesh;
  H2DReader mloader;
  mloader.load("../domain.mesh", &mesh);

  // Convert to quadrilaterals.
  mesh.convert_triangles_to_quads();

  // Refine towards boundary.
  mesh.refine_towards_boundary("Bdy", 1, true);

  // Refine once towards vertex #4.
  mesh.refine_towards_vertex(4, 1);

  // Initialize solutions.
  CustomInitialConditionWave u_sln(&mesh);
  Solution v_sln(&mesh, 0.0);
  Hermes::vector<Solution*> slns(&u_sln, &v_sln);

  // Initialize the weak formulation.
  CustomWeakFormWave wf(time_step, C_SQUARED, &u_sln, &v_sln);
  
  // Initialize boundary conditions
  DefaultEssentialBCConst bc_essential("Bdy", 0.0);
  EssentialBCs bcs(&bc_essential);

  // Create x- and y- displacement space using the default H1 shapeset.
  H1Space u_space(&mesh, &bcs, P_INIT);
  H1Space v_space(&mesh, &bcs, P_INIT);
  info("ndof = %d.", Space::get_num_dofs(Hermes::vector<Space *>(&u_space, &v_space)));

  // Initialize the FE problem.
  DiscreteProblem dp(&wf, Hermes::vector<Space *>(&u_space, &v_space));

  // Initialize Runge-Kutta time stepping.
  RungeKutta runge_kutta(&dp, &bt, matrix_solver);

  // Time stepping loop.
  double current_time = 0; int ts = 1;
  do
  {
    // Perform one Runge-Kutta time step according to the selected Butcher's table.
    info("Runge-Kutta time step (t = %g s, time_step = %g s, stages: %d).", 
         current_time, time_step, bt.get_size());
    bool jacobian_changed = false;
    bool verbose = true;

    if (!runge_kutta.rk_time_step(current_time, time_step, slns, 
                                  slns, jacobian_changed, verbose))
      error("Runge-Kutta time step failed, try to decrease time step size.");

    // Update time.
    current_time += time_step;

  } while (current_time < T_FINAL);

  double coord_x[4] = {1, 3, 5, 7};
  double coord_y[4] = {1, 3, 5, 7};

  info("Coordinate (1.0, 0.0) value = %lf", u_sln.get_pt_value(coord_x[0], coord_y[0]));
  info("Coordinate (3.0, 3.0) value = %lf", u_sln.get_pt_value(coord_x[1], coord_y[1]));
  info("Coordinate (5.0, 5.0) value = %lf", u_sln.get_pt_value(coord_x[2], coord_y[2]));
  info("Coordinate (7.0, 7.0) value = %lf", u_sln.get_pt_value(coord_x[3], coord_y[3]));

  info("Coordinate (1.0, 0.0) value = %lf", v_sln.get_pt_value(coord_x[0], coord_y[0]));
  info("Coordinate (3.0, 3.0) value = %lf", v_sln.get_pt_value(coord_x[1], coord_y[1]));
  info("Coordinate (5.0, 5.0) value = %lf", v_sln.get_pt_value(coord_x[2], coord_y[2]));
  info("Coordinate (7.0, 7.0) value = %lf", v_sln.get_pt_value(coord_x[3], coord_y[3]));

  double t_value[8] = {0.212655, 0.000163, 0.000000, 0.000000, -0.793316, 0.007255, 0.000001, 0.000000};
  bool success = true;

  for (int i = 0; i < 4; i++)
  {
    if (fabs(t_value[i] - u_sln.get_pt_value(coord_x[i], coord_y[i])) > 1E-6) success = false;
  }

  for (int i = 4; i < 8; i++)
  {
    if (fabs(t_value[i] - v_sln.get_pt_value(coord_x[i-4], coord_y[i-4])) > 1E-6) success = false;
  }

  if (success) {
    printf("Success!\n");
    return ERR_SUCCESS;
  }
  else {
    printf("Failure!\n");
    return ERR_FAILURE;
  }

  // Wait for the view to be closed.
  View::wait();

  return 0;
}
示例#27
0
/* execute instructions on this CPU until icount expires */
static CPU_EXECUTE( m6805 )
{
	UINT8 ireg;
	m6805_Regs *cpustate = get_safe_token(device);

	S = SP_ADJUST( S );		/* Taken from CPU_SET_CONTEXT when pointer'afying */

	do
	{
		if (cpustate->pending_interrupts != 0)
		{
			if (SUBTYPE==SUBTYPE_M68705)
			{
				m68705_Interrupt(cpustate);
			}
			else
			{
				Interrupt(cpustate);
			}
		}

		debugger_instruction_hook(device, PC);

		ireg=M_RDOP(PC++);

		switch( ireg )
		{
			case 0x00: brset(cpustate, 0x01); break;
			case 0x01: brclr(cpustate, 0x01); break;
			case 0x02: brset(cpustate, 0x02); break;
			case 0x03: brclr(cpustate, 0x02); break;
			case 0x04: brset(cpustate, 0x04); break;
			case 0x05: brclr(cpustate, 0x04); break;
			case 0x06: brset(cpustate, 0x08); break;
			case 0x07: brclr(cpustate, 0x08); break;
			case 0x08: brset(cpustate, 0x10); break;
			case 0x09: brclr(cpustate, 0x10); break;
			case 0x0A: brset(cpustate, 0x20); break;
			case 0x0B: brclr(cpustate, 0x20); break;
			case 0x0C: brset(cpustate, 0x40); break;
			case 0x0D: brclr(cpustate, 0x40); break;
			case 0x0E: brset(cpustate, 0x80); break;
			case 0x0F: brclr(cpustate, 0x80); break;
			case 0x10: bset(cpustate, 0x01); break;
			case 0x11: bclr(cpustate, 0x01); break;
			case 0x12: bset(cpustate, 0x02); break;
			case 0x13: bclr(cpustate, 0x02); break;
			case 0x14: bset(cpustate, 0x04); break;
			case 0x15: bclr(cpustate, 0x04); break;
			case 0x16: bset(cpustate, 0x08); break;
			case 0x17: bclr(cpustate, 0x08); break;
			case 0x18: bset(cpustate, 0x10); break;
			case 0x19: bclr(cpustate, 0x10); break;
			case 0x1a: bset(cpustate, 0x20); break;
			case 0x1b: bclr(cpustate, 0x20); break;
			case 0x1c: bset(cpustate, 0x40); break;
			case 0x1d: bclr(cpustate, 0x40); break;
			case 0x1e: bset(cpustate, 0x80); break;
			case 0x1f: bclr(cpustate, 0x80); break;
			case 0x20: bra(cpustate); break;
			case 0x21: brn(cpustate); break;
			case 0x22: bhi(cpustate); break;
			case 0x23: bls(cpustate); break;
			case 0x24: bcc(cpustate); break;
			case 0x25: bcs(cpustate); break;
			case 0x26: bne(cpustate); break;
			case 0x27: beq(cpustate); break;
			case 0x28: bhcc(cpustate); break;
			case 0x29: bhcs(cpustate); break;
			case 0x2a: bpl(cpustate); break;
			case 0x2b: bmi(cpustate); break;
			case 0x2c: bmc(cpustate); break;
			case 0x2d: bms(cpustate); break;
			case 0x2e: bil(cpustate); break;
			case 0x2f: bih(cpustate); break;
			case 0x30: neg_di(cpustate); break;
			case 0x31: illegal(cpustate); break;
			case 0x32: illegal(cpustate); break;
			case 0x33: com_di(cpustate); break;
			case 0x34: lsr_di(cpustate); break;
			case 0x35: illegal(cpustate); break;
			case 0x36: ror_di(cpustate); break;
			case 0x37: asr_di(cpustate); break;
			case 0x38: lsl_di(cpustate); break;
			case 0x39: rol_di(cpustate); break;
			case 0x3a: dec_di(cpustate); break;
			case 0x3b: illegal(cpustate); break;
			case 0x3c: inc_di(cpustate); break;
			case 0x3d: tst_di(cpustate); break;
			case 0x3e: illegal(cpustate); break;
			case 0x3f: clr_di(cpustate); break;
			case 0x40: nega(cpustate); break;
			case 0x41: illegal(cpustate); break;
			case 0x42: illegal(cpustate); break;
			case 0x43: coma(cpustate); break;
			case 0x44: lsra(cpustate); break;
			case 0x45: illegal(cpustate); break;
			case 0x46: rora(cpustate); break;
			case 0x47: asra(cpustate); break;
			case 0x48: lsla(cpustate); break;
			case 0x49: rola(cpustate); break;
			case 0x4a: deca(cpustate); break;
			case 0x4b: illegal(cpustate); break;
			case 0x4c: inca(cpustate); break;
			case 0x4d: tsta(cpustate); break;
			case 0x4e: illegal(cpustate); break;
			case 0x4f: clra(cpustate); break;
			case 0x50: negx(cpustate); break;
			case 0x51: illegal(cpustate); break;
			case 0x52: illegal(cpustate); break;
			case 0x53: comx(cpustate); break;
			case 0x54: lsrx(cpustate); break;
			case 0x55: illegal(cpustate); break;
			case 0x56: rorx(cpustate); break;
			case 0x57: asrx(cpustate); break;
			case 0x58: aslx(cpustate); break;
			case 0x59: rolx(cpustate); break;
			case 0x5a: decx(cpustate); break;
			case 0x5b: illegal(cpustate); break;
			case 0x5c: incx(cpustate); break;
			case 0x5d: tstx(cpustate); break;
			case 0x5e: illegal(cpustate); break;
			case 0x5f: clrx(cpustate); break;
			case 0x60: neg_ix1(cpustate); break;
			case 0x61: illegal(cpustate); break;
			case 0x62: illegal(cpustate); break;
			case 0x63: com_ix1(cpustate); break;
			case 0x64: lsr_ix1(cpustate); break;
			case 0x65: illegal(cpustate); break;
			case 0x66: ror_ix1(cpustate); break;
			case 0x67: asr_ix1(cpustate); break;
			case 0x68: lsl_ix1(cpustate); break;
			case 0x69: rol_ix1(cpustate); break;
			case 0x6a: dec_ix1(cpustate); break;
			case 0x6b: illegal(cpustate); break;
			case 0x6c: inc_ix1(cpustate); break;
			case 0x6d: tst_ix1(cpustate); break;
			case 0x6e: illegal(cpustate); break;
			case 0x6f: clr_ix1(cpustate); break;
			case 0x70: neg_ix(cpustate); break;
			case 0x71: illegal(cpustate); break;
			case 0x72: illegal(cpustate); break;
			case 0x73: com_ix(cpustate); break;
			case 0x74: lsr_ix(cpustate); break;
			case 0x75: illegal(cpustate); break;
			case 0x76: ror_ix(cpustate); break;
			case 0x77: asr_ix(cpustate); break;
			case 0x78: lsl_ix(cpustate); break;
			case 0x79: rol_ix(cpustate); break;
			case 0x7a: dec_ix(cpustate); break;
			case 0x7b: illegal(cpustate); break;
			case 0x7c: inc_ix(cpustate); break;
			case 0x7d: tst_ix(cpustate); break;
			case 0x7e: illegal(cpustate); break;
			case 0x7f: clr_ix(cpustate); break;
			case 0x80: rti(cpustate); break;
			case 0x81: rts(cpustate); break;
			case 0x82: illegal(cpustate); break;
			case 0x83: swi(cpustate); break;
			case 0x84: illegal(cpustate); break;
			case 0x85: illegal(cpustate); break;
			case 0x86: illegal(cpustate); break;
			case 0x87: illegal(cpustate); break;
			case 0x88: illegal(cpustate); break;
			case 0x89: illegal(cpustate); break;
			case 0x8a: illegal(cpustate); break;
			case 0x8b: illegal(cpustate); break;
			case 0x8c: illegal(cpustate); break;
			case 0x8d: illegal(cpustate); break;
			case 0x8e: illegal(cpustate); break;
			case 0x8f: illegal(cpustate); break;
			case 0x90: illegal(cpustate); break;
			case 0x91: illegal(cpustate); break;
			case 0x92: illegal(cpustate); break;
			case 0x93: illegal(cpustate); break;
			case 0x94: illegal(cpustate); break;
			case 0x95: illegal(cpustate); break;
			case 0x96: illegal(cpustate); break;
			case 0x97: tax(cpustate); break;
			case 0x98: CLC; break;
			case 0x99: SEC; break;
#if IRQ_LEVEL_DETECT
			case 0x9a: CLI; if (m6805.irq_state != CLEAR_LINE) m6805.pending_interrupts |= 1<<M6805_IRQ_LINE; break;
#else
			case 0x9a: CLI; break;
#endif
			case 0x9b: SEI; break;
			case 0x9c: rsp(cpustate); break;
			case 0x9d: nop(cpustate); break;
			case 0x9e: illegal(cpustate); break;
			case 0x9f: txa(cpustate); break;
			case 0xa0: suba_im(cpustate); break;
			case 0xa1: cmpa_im(cpustate); break;
			case 0xa2: sbca_im(cpustate); break;
			case 0xa3: cpx_im(cpustate); break;
			case 0xa4: anda_im(cpustate); break;
			case 0xa5: bita_im(cpustate); break;
			case 0xa6: lda_im(cpustate); break;
			case 0xa7: illegal(cpustate); break;
			case 0xa8: eora_im(cpustate); break;
			case 0xa9: adca_im(cpustate); break;
			case 0xaa: ora_im(cpustate); break;
			case 0xab: adda_im(cpustate); break;
			case 0xac: illegal(cpustate); break;
			case 0xad: bsr(cpustate); break;
			case 0xae: ldx_im(cpustate); break;
			case 0xaf: illegal(cpustate); break;
			case 0xb0: suba_di(cpustate); break;
			case 0xb1: cmpa_di(cpustate); break;
			case 0xb2: sbca_di(cpustate); break;
			case 0xb3: cpx_di(cpustate); break;
			case 0xb4: anda_di(cpustate); break;
			case 0xb5: bita_di(cpustate); break;
			case 0xb6: lda_di(cpustate); break;
			case 0xb7: sta_di(cpustate); break;
			case 0xb8: eora_di(cpustate); break;
			case 0xb9: adca_di(cpustate); break;
			case 0xba: ora_di(cpustate); break;
			case 0xbb: adda_di(cpustate); break;
			case 0xbc: jmp_di(cpustate); break;
			case 0xbd: jsr_di(cpustate); break;
			case 0xbe: ldx_di(cpustate); break;
			case 0xbf: stx_di(cpustate); break;
			case 0xc0: suba_ex(cpustate); break;
			case 0xc1: cmpa_ex(cpustate); break;
			case 0xc2: sbca_ex(cpustate); break;
			case 0xc3: cpx_ex(cpustate); break;
			case 0xc4: anda_ex(cpustate); break;
			case 0xc5: bita_ex(cpustate); break;
			case 0xc6: lda_ex(cpustate); break;
			case 0xc7: sta_ex(cpustate); break;
			case 0xc8: eora_ex(cpustate); break;
			case 0xc9: adca_ex(cpustate); break;
			case 0xca: ora_ex(cpustate); break;
			case 0xcb: adda_ex(cpustate); break;
			case 0xcc: jmp_ex(cpustate); break;
			case 0xcd: jsr_ex(cpustate); break;
			case 0xce: ldx_ex(cpustate); break;
			case 0xcf: stx_ex(cpustate); break;
			case 0xd0: suba_ix2(cpustate); break;
			case 0xd1: cmpa_ix2(cpustate); break;
			case 0xd2: sbca_ix2(cpustate); break;
			case 0xd3: cpx_ix2(cpustate); break;
			case 0xd4: anda_ix2(cpustate); break;
			case 0xd5: bita_ix2(cpustate); break;
			case 0xd6: lda_ix2(cpustate); break;
			case 0xd7: sta_ix2(cpustate); break;
			case 0xd8: eora_ix2(cpustate); break;
			case 0xd9: adca_ix2(cpustate); break;
			case 0xda: ora_ix2(cpustate); break;
			case 0xdb: adda_ix2(cpustate); break;
			case 0xdc: jmp_ix2(cpustate); break;
			case 0xdd: jsr_ix2(cpustate); break;
			case 0xde: ldx_ix2(cpustate); break;
			case 0xdf: stx_ix2(cpustate); break;
			case 0xe0: suba_ix1(cpustate); break;
			case 0xe1: cmpa_ix1(cpustate); break;
			case 0xe2: sbca_ix1(cpustate); break;
			case 0xe3: cpx_ix1(cpustate); break;
			case 0xe4: anda_ix1(cpustate); break;
			case 0xe5: bita_ix1(cpustate); break;
			case 0xe6: lda_ix1(cpustate); break;
			case 0xe7: sta_ix1(cpustate); break;
			case 0xe8: eora_ix1(cpustate); break;
			case 0xe9: adca_ix1(cpustate); break;
			case 0xea: ora_ix1(cpustate); break;
			case 0xeb: adda_ix1(cpustate); break;
			case 0xec: jmp_ix1(cpustate); break;
			case 0xed: jsr_ix1(cpustate); break;
			case 0xee: ldx_ix1(cpustate); break;
			case 0xef: stx_ix1(cpustate); break;
			case 0xf0: suba_ix(cpustate); break;
			case 0xf1: cmpa_ix(cpustate); break;
			case 0xf2: sbca_ix(cpustate); break;
			case 0xf3: cpx_ix(cpustate); break;
			case 0xf4: anda_ix(cpustate); break;
			case 0xf5: bita_ix(cpustate); break;
			case 0xf6: lda_ix(cpustate); break;
			case 0xf7: sta_ix(cpustate); break;
			case 0xf8: eora_ix(cpustate); break;
			case 0xf9: adca_ix(cpustate); break;
			case 0xfa: ora_ix(cpustate); break;
			case 0xfb: adda_ix(cpustate); break;
			case 0xfc: jmp_ix(cpustate); break;
			case 0xfd: jsr_ix(cpustate); break;
			case 0xfe: ldx_ix(cpustate); break;
			case 0xff: stx_ix(cpustate); break;
		}
		cpustate->iCount -= cycles1[ireg];
	} while( cpustate->iCount > 0 );
}
示例#28
0
int main(int argc, char* argv[])
{
  // Load the mesh.
  MeshSharedPtr mesh(new Mesh);
  MeshReaderH2D mloader;
  mloader.load("square.mesh", mesh);

  // Initial mesh refinements.
  for (int i = 0; i < INIT_GLOB_REF_NUM; i++) mesh->refine_all_elements();
  mesh->refine_towards_boundary("Top", INIT_REF_NUM_BDY);

  // Initialize boundary conditions.
  CustomEssentialBCNonConst bc_essential({ "Bottom", "Right", "Top", "Left" });
  EssentialBCs<double> bcs(&bc_essential);

  // Create an H1 space with default shapeset.
  SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT));
  int ndof = space->get_num_dofs();
  Hermes::Mixins::Loggable::Static::info("ndof = %d.", ndof);

  // Zero initial solutions. This is why we use H_OFFSET.
  MeshFunctionSharedPtr<double> h_time_prev(new ZeroSolution<double>(mesh));

  // Initialize views.
  ScalarView view("Initial condition", new WinGeom(0, 0, 600, 500));
  view.fix_scale_width(80);

  // Visualize the initial condition.
  view.show(h_time_prev);

  // Initialize the constitutive relations.
  ConstitutiveRelations* constitutive_relations;
  if (constitutive_relations_type == CONSTITUTIVE_GENUCHTEN)
    constitutive_relations = new ConstitutiveRelationsGenuchten(ALPHA, M, N, THETA_S, THETA_R, K_S, STORATIVITY);
  else
    constitutive_relations = new ConstitutiveRelationsGardner(ALPHA, THETA_S, THETA_R, K_S);

  // Initialize the weak formulation.
  double current_time = 0;
  WeakFormSharedPtr<double> wf(new CustomWeakFormRichardsIE(time_step, h_time_prev, constitutive_relations));

  // Initialize the FE problem.
  DiscreteProblem<double> dp(wf, space);

  // Initialize Newton solver.
  NewtonSolver<double> newton(&dp);
  newton.set_verbose_output(true);

  // Time stepping:
  int ts = 1;
  do
  {
    Hermes::Mixins::Loggable::Static::info("---- Time step %d, time %3.5f s", ts, current_time);

    // Perform Newton's iteration.
    try
    {
      newton.set_max_allowed_iterations(NEWTON_MAX_ITER);
      newton.solve();
    }
    catch (Hermes::Exceptions::Exception e)
    {
      e.print_msg();
      throw Hermes::Exceptions::Exception("Newton's iteration failed.");
    };

    // Translate the resulting coefficient vector into the Solution<double> sln->
    Solution<double>::vector_to_solution(newton.get_sln_vector(), space, h_time_prev);

    // Visualize the solution.
    char title[100];
    sprintf(title, "Time %g s", current_time);
    view.set_title(title);
    view.show(h_time_prev);

    // Increase current time and time step counter.
    current_time += time_step;
    ts++;
  } while (current_time < T_FINAL);

  // Wait for the view to be closed.
  View::wait();
  return 0;
}
示例#29
0
int main(int argc, char* argv[])
{
  // Instantiate a class with global functions.
  Hermes2D hermes2d;

  // Load the mesh.
  Mesh mesh;
  H2DReader mloader;
  mloader.load("../domain.mesh", &mesh);

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

  // Initialize boundary conditions
  CustomEssentialBCNonConst bc_essential("Horizontal");
  EssentialBCs bcs(&bc_essential);

  // Create an H1 space with default shapeset.
  H1Space space(&mesh, &bcs, P_INIT);

  // Initialize the weak formulation.
  CustomWeakFormGeneral wf("Vertical");

  // Testing n_dof and correctness of solution vector
  // for p_init = 1, 2, ..., 10
  int success = 1;
  for (int p_init = 1; p_init <= 10; p_init++) {

    printf("********* p_init = %d *********\n", p_init);
    space.set_uniform_order(p_init);
    int ndof = space.get_num_dofs();
    info("ndof = %d", ndof);

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

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

    // Initial coefficient vector for the Newton's method.  
    scalar* coeff_vec = new scalar[ndof];
    memset(coeff_vec, 0, ndof*sizeof(scalar));

    // Perform Newton's iteration.
    if (!hermes2d.solve_newton(coeff_vec, &dp, solver, matrix, rhs)) error("Newton's iteration failed.");

    // Translate the resulting coefficient vector into the Solution sln.
    Solution sln;
    Solution::vector_to_solution(coeff_vec, &space, &sln);

    double sum = 0;
    for (int i=0; i < ndof; i++) sum += coeff_vec[i];
    printf("coefficient sum = %g\n", sum);

    // Actual test. The values of 'sum' depend on the
    // current shapeset. If you change the shapeset,
    // you need to correct these numbers.
    if (p_init == 1 && fabs(sum - 1.72173) > 1e-2) success = 0;
    if (p_init == 2 && fabs(sum - 0.639908) > 1e-2) success = 0;
    if (p_init == 3 && fabs(sum - 0.826367) > 1e-2) success = 0;
    if (p_init == 4 && fabs(sum - 0.629395) > 1e-2) success = 0;
    if (p_init == 5 && fabs(sum - 0.574235) > 1e-2) success = 0;
    if (p_init == 6 && fabs(sum - 0.62792) > 1e-2) success = 0;
    if (p_init == 7 && fabs(sum - 0.701982) > 1e-2) success = 0;
    if (p_init == 8 && fabs(sum - 0.7982) > 1e-2) success = 0;
    if (p_init == 9 && fabs(sum - 0.895069) > 1e-2) success = 0;
    if (p_init == 10 && fabs(sum - 1.03031) > 1e-2) success = 0;

    delete [] coeff_vec;
  }

  if (success == 1) {
    printf("Success!\n");
    return ERR_SUCCESS;
  }
  else {
    printf("Failure!\n");
    return ERR_FAILURE;
  }
}
示例#30
0
int main(int argc, char* argv[])
{
  // Load the mesh.
  Mesh mesh;
  MeshReaderH2D mloader;
  mloader.load("domain.mesh", &mesh);

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

  // Initialize solutions.
  CustomInitialConditionWave E_sln(&mesh);
  ZeroSolutionVector F_sln(&mesh);
  Hermes::vector<Solution<double>*> slns(&E_sln, &F_sln);

  // Initialize the weak formulation.
  CustomWeakFormWave wf(time_step, C_SQUARED, &E_sln, &F_sln);
  
  // Initialize boundary conditions
  DefaultEssentialBCConst<double> bc_essential("Perfect conductor", 0.0);
  EssentialBCs<double> bcs(&bc_essential);

  // Create x- and y- displacement space using the default H1 shapeset.
  HcurlSpace<double> E_space(&mesh, &bcs, P_INIT);
  HcurlSpace<double> F_space(&mesh, &bcs, P_INIT);
  Hermes::vector<Space<double> *> spaces = Hermes::vector<Space<double> *>(&E_space, &F_space);

  info("ndof = %d.", Space<double>::get_num_dofs(spaces));

  // Initialize the FE problem.
  DiscreteProblem<double> dp(&wf, spaces);

  // Set up the solver, matrix, and rhs according to the solver selection.
  SparseMatrix<double>* matrix = create_matrix<double>(matrix_solver_type);
  Vector<double>* rhs = create_vector<double>(matrix_solver_type);
  LinearSolver<double>* solver = create_linear_solver<double>(matrix_solver_type, matrix, rhs);
  solver->set_factorization_scheme(HERMES_REUSE_FACTORIZATION_COMPLETELY);

  // Initialize views.
  ScalarView E1_view("Solution E1", new WinGeom(0, 0, 400, 350));
  E1_view.fix_scale_width(50);
  ScalarView E2_view("Solution E2", new WinGeom(410, 0, 400, 350));
  E2_view.fix_scale_width(50);

  // Time stepping loop.
  double current_time = 0; int ts = 1;
  do
  {
    // Perform one implicit Euler time step.
    info("Implicit Euler time step (t = %g s, time_step = %g s).", current_time, time_step);

    // First time assemble both the stiffness matrix and right-hand side vector,
    // then just the right-hand side vector.
    if (ts == 1) {
      info("Assembling the stiffness matrix and right-hand side vector.");
      dp.assemble(matrix, rhs);
      static char file_name[1024];
      sprintf(file_name, "matrix.m");
      FILE *f = fopen(file_name, "w");
      matrix->dump(f, "A");
      fclose(f);
    }
    else {
      info("Assembling the right-hand side vector (only).");
      dp.assemble(rhs);
    }

    // Solve the linear system and if successful, obtain the solution.
    info("Solving the matrix problem.");
    if(solver->solve()) Solution<double>::vector_to_solutions(solver->get_sln_vector(), spaces, slns);
    else error ("Matrix solver failed.\n");

    // Visualize the solutions.
    char title[100];
    sprintf(title, "E1, t = %g", current_time);
    E1_view.set_title(title);
    E1_view.show(&E_sln, HERMES_EPS_NORMAL, H2D_FN_VAL_0);
    sprintf(title, "E2, t = %g", current_time);
    E2_view.set_title(title);
    E2_view.show(&E_sln, HERMES_EPS_NORMAL, H2D_FN_VAL_1);

    // Update time.
    current_time += time_step;
  } while (current_time < T_FINAL);

  // Wait for the view to be closed.
  View::wait();

  return 0;
}