Esempio n. 1
0
int main(int argc, char* argv[])
{
  if (argc < 2) error("Missing mesh file name parameter.");

  // load the mesh
  Mesh mesh;
  mesh.load(argv[1]);

  // uniform mesh refinements
  mesh.refine_all_elements();
  mesh.refine_all_elements();
  mesh.refine_all_elements();
  mesh.refine_all_elements();

  // initialize the shapeset and the cache
  L2Shapeset shapeset;
  PrecalcShapeset pss(&shapeset);

  // create the L2 space
  L2Space space(&mesh, &shapeset);
  space.set_bc_types(bc_types);

  // set uniform polynomial degrees
  space.set_uniform_order(P_INIT);

  // enumerate basis functions
  space.assign_dofs();

/*  BaseView bview;
  bview.show(&space);
  bview.wait_for_close();
*/

  Solution sln;

  // matrix solver
  UmfpackSolver umfpack;

  // initialize the weak formulation
  WeakForm wf(1);
  wf.add_biform(0, 0, callback(bilinear_form));
  wf.add_liform(0, callback(linear_form));

  // assemble and solve the finite element problem
  LinSystem sys(&wf, &umfpack);
  sys.set_spaces(1, &space);
  sys.set_pss(1, &pss);
  sys.assemble();
  sys.solve(1, &sln);

  // visualize the solution
  ScalarView view1("Solution 1");
  view1.show(&sln);
  view1.wait_for_keypress();

  // wait for keyboard or mouse input
  View::wait("Waiting for keyboard or mouse input.");
  return 0;
}
Esempio n. 2
0
void test_reverse_close(Range const& range, std::string const& expected)
{
    typedef typename bg::closeable_view<Range const, Closure>::type cview;
    typedef typename bg::reversible_view<cview const, Direction>::type rview;

    cview view1(range);
    rview view2(view1);
    test_option(view2, expected);
}
Esempio n. 3
0
void test_close_close(Range const& range, std::string const& expected)
{
    typedef typename bg::closeable_view<Range const, Closure1>::type cview1;
    typedef typename bg::closeable_view<cview1 const, Closure2>::type cview2;

    cview1 view1(range);
    cview2 view2(view1);
    test_option(view2, expected);
}
Esempio n. 4
0
void test_reverse_reverse(Range const& range, std::string const& expected)
{
    typedef typename bg::reversible_view<Range const, Direction1>::type rview1;
    typedef typename bg::reversible_view<rview1 const, Direction2>::type rview2;

    rview1 view1(range);
    rview2 view2(view1);
    test_option(view2, expected);
}
Esempio n. 5
0
// The test checks invokers specialized on a single attribute value type
BOOST_AUTO_TEST_CASE_TEMPLATE(single_type, CharT, char_types)
{
    typedef logging::basic_attribute_set< CharT > attr_set;
    typedef logging::basic_attribute_values_view< CharT > values_view;
    typedef test_data< CharT > data;

    attrs::constant< int > attr1(10);
    attrs::constant< double > attr2(5.5);
    attrs::constant< std::string > attr3("Hello, world!");

    attr_set set1, set2, set3;
    set1[data::attr1()] = attr1;
    set1[data::attr2()] = attr2;

    values_view view1(set1, set2, set3);
    view1.freeze();

    my_receiver recv;

    logging::value_visitor_invoker< CharT, int > invoker1(data::attr1());
    logging::value_visitor_invoker< CharT, double > invoker2(data::attr2());
    logging::value_visitor_invoker< CharT, std::string > invoker3(data::attr3());
    logging::value_visitor_invoker< CharT, char > invoker4(data::attr1());
    logging::value_visitor_invoker< CharT, int > invoker5(data::attr2());

    // These two extractors will find their values in the view
    recv.set_expected(10);
    BOOST_CHECK(invoker1(view1, recv));

    recv.set_expected(5.5);
    BOOST_CHECK(invoker2(view1, recv));

    // This one will not
    recv.set_expected();
    BOOST_CHECK(!invoker3(view1, recv));

    // But it will find it in this view
    set1[data::attr3()] = attr3;

    values_view view2(set1, set2, set3);
    view2.freeze();

    recv.set_expected("Hello, world!");
    BOOST_CHECK(invoker3(view2, recv));

    // This one will find the sought attribute value, but it will have an incorrect type
    recv.set_expected();
    BOOST_CHECK(!invoker4(view1, recv));

    // This one is the same, but there is a value of the requested type in the view
    BOOST_CHECK(!invoker5(view1, recv));
}
void GraphicsObject::showEvent(QShowEvent *) {
    if (!goinitialized) {
        //Under X11, we need to flush the commands sent to the server to ensure that
        //SFML will get an updated view of the windows
            #ifdef Q_WS_X11
        XFlush(QX11Info::display());
        #endif
        #ifdef __APPLE__
        sf::RenderWindow::create(reinterpret_cast<sf::WindowHandle>(winId()));
        #elif __linux__
        sf::RenderWindow::create((sf::WindowHandle)winId());
        #elif __unix__ // all unices not caught above
        sf::RenderWindow::create((sf::WindowHandle)winId());
        #elif _WIN32
        sf::RenderWindow::create(reinterpret_cast<sf::WindowHandle>(winId()));
        #endif
        #ifdef __APPLE__
        sf::Vector2u dimensions(1600, 1200);
//            sf::Vector2u dimensions(1600,1200);
//            sf::Vector2u dimensions(800,600);
        sf::RenderWindow::setSize(dimensions);
        #elif __linux__
        sf::Vector2u dimensions(800, 600);
        sf::RenderWindow::setSize(dimensions);
        #elif __unix__ // all unices not caught above
        sf::Vector2u dimensions(800, 600);
        sf::RenderWindow::setSize(dimensions);
        #elif _WIN32
        sf::Vector2u dimensions(800, 600);
        sf::RenderWindow::setSize(dimensions);
        //set up size?
        #endif

        sf::View view1(sf::FloatRect(0, 0, 800, 600));
        this->setView(view1);

        sf::RenderWindow::display();
        //   QWidget::setFixedSize(800, 600);
        QWidget::showNormal();

        OnInit();
        connect(&gotimer, SIGNAL(timeout()), this, SLOT(repaint()));
        gotimer.start();
        goinitialized = true;
    }
}
Esempio n. 7
0
TEST(ImageKeyTest, Equality) {
    srand(2000);
    // coverity[dont_call]
    int randomHashKey1 = rand();
    SequenceTime time1 = 0;
    ViewIdx view1(0);
    ImageKey key1(std::string(), randomHashKey1, time1, view1, false);
    U64 keyHash1 = key1.getHash();


    ///make a second ImageKey equal to the first
    int randomHashKey2 = randomHashKey1;
    SequenceTime time2 = time1;
    ViewIdx view2(view1);
    ImageKey key2(std::string(), randomHashKey2, time2, view2, false);
    U64 keyHash2 = key2.getHash();
    ASSERT_TRUE(keyHash1 == keyHash2);
}
Esempio n. 8
0
int main(int argc, char* argv[])
{
  // Load the mesh.
  Mesh mesh;
  H2DReader mloader;
  mloader.load("square.mesh", &mesh);

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

  // Create an L2 space with default shapeset.
  L2Space space(&mesh, P_INIT);

  // View basis functions.
  BaseView bview("BaseView", 0, 0, 600, 500);

  // Assemble and solve the finite element problem.
  WeakForm wf_dummy;

  // Initialize the exact and projected solution.
  Solution sln;
  Solution sln_exact(&mesh, F);

  OGProjection::project_global(&space, &sln_exact, &sln, matrix_solver, HERMES_L2_NORM);

  // Visualize the solution.
  ScalarView view1("Projection", 610, 0, 600, 500);

  // It will "Exception: SegFault" if we do not use View::wait() or View::close(). 
  view1.close();

  bool success = true;

#define ERROR_SUCCESS                               0
#define ERROR_FAILURE                               -1
  if (success == true) {
    printf("Success!\n");
    return ERROR_SUCCESS;
  }
  else {
    printf("Failure!\n");
    return ERROR_FAILURE;
  }
}
Esempio n. 9
0
// The test checks invokers specialized with type lists
BOOST_AUTO_TEST_CASE_TEMPLATE(multiple_types, CharT, char_types)
{
    typedef logging::basic_attribute_set< CharT > attr_set;
    typedef logging::basic_attribute_values_view< CharT > values_view;
    typedef test_data< CharT > data;
    typedef mpl::vector< int, double, std::string, char >::type types;

    attrs::constant< int > attr1(10);
    attrs::constant< double > attr2(5.5);
    attrs::constant< std::string > attr3("Hello, world!");

    attr_set set1, set2, set3;
    set1[data::attr1()] = attr1;
    set1[data::attr2()] = attr2;

    values_view view1(set1, set2, set3);
    view1.freeze();

    my_receiver recv;

    logging::value_visitor_invoker< CharT, types > invoker1(data::attr1());
    logging::value_visitor_invoker< CharT, types > invoker2(data::attr2());
    logging::value_visitor_invoker< CharT, types > invoker3(data::attr3());

    // These two extractors will find their values in the view
    recv.set_expected(10);
    BOOST_CHECK(invoker1(view1, recv));

    recv.set_expected(5.5);
    BOOST_CHECK(invoker2(view1, recv));

    // This one will not
    recv.set_expected();
    BOOST_CHECK(!invoker3(view1, recv));

    // But it will find it in this view
    set1[data::attr3()] = attr3;

    values_view view2(set1, set2, set3);
    view2.freeze();

    recv.set_expected("Hello, world!");
    BOOST_CHECK(invoker3(view2, recv));
}
Esempio n. 10
0
/**
 * Wooden Monkey Scene 1
 */
void refraction_scene_1()
{
    printf("REFRACTION SCENE : 1 ----------------------------------\n\n");
    Raytracer rt;
    int width = 16 * 20 * 2;
    int height = 12 * 20 * 2;

    // Camera parameters.
    Point3D eye1(0, 0, 1), eye2(4, 2, 1);
    Vector3D view1(0, 0, -1), view2(-4, -2, -6);
    Vector3D up(0, 1, 0);
    double fov = 60;

    // Defines a material for shading.
    Material gold( Colour(0.3, 0.3, 0.3), Colour(0.75164, 0.60648, 0.22648),
                   Colour(0.628281, 0.555802, 0.366065),
                   51.2, LARGE_SPH_REFLECT, LARGE_SPH_REFRAC_INDX, LARGE_SPH_REFRACT);
    Material jade( Colour(0, 0, 0), Colour(0.54, 0.89, 0.63),
                   Colour(0.316228, 0.316228, 0.316228),
                   12.8);
    // Defines a material for shading.
    Material gold_nonRefract( Colour(0.3, 0.3, 0.3), Colour(0.75164, 0.60648, 0.22648),
                              Colour(0.628281, 0.555802, 0.366065),
                              51.2, 0.8 );

    // Defines a point light source.
    double l0c = 0.5;
    PointLight * light0 = new PointLight(
        Point3D(-2, 2, 5),
        Colour(l0c, l0c, l0c),
        0.2);
    rt.addLightSource(light0);

    // Add a unit square into the scene with material mat.
    SceneDagNode* sphere = rt.addObject( new UnitSphere(), &gold );
    SceneDagNode* sphere2 = rt.addObject( new UnitSphere(), &gold_nonRefract );
    SceneDagNode* plane = rt.addObject( new UnitSquare(), &jade );
    SceneDagNode* sphere3 = rt.addObject( new UnitSphere(), &RED);
    SceneDagNode* sphere4 = rt.addObject( new UnitSphere(), &GREEN_TRANSP);
    SceneDagNode* plane2 = rt.addObject( new UnitSquare(), &jade );
//    SceneDagNode* plane3 = rt.addObject( new UnitSquare(), &jade );
//    SceneDagNode* plane4 = rt.addObject( new UnitSquare(), &jade );

    // Apply some transformations to the unit square.
    double factor1[3] = { 1.0, 2.0, 1.0 };
    double factor2[3] = { 6.0, 6.0, 6.0 };
    rt.translate(sphere, Vector3D(0, 0, -5));
    rt.rotate(sphere, 'x', -45);
    rt.rotate(sphere, 'z', 45);
    rt.scale(sphere, Point3D(0, 0, 0), factor1);

    rt.translate(plane, Vector3D(0, 0, -7));
    rt.rotate(plane, 'z', 45);
    rt.scale(plane, Point3D(0, 0, 0), factor2);

    double f[3] = { 0.5, 0.5, 0.5 };
    rt.translate(sphere2, Vector3D(3, 0, -5));
    rt.scale(sphere2, Point3D(0, 0, 0), f);

    rt.translate(sphere3, Vector3D(0, 2, -5));
    rt.scale(sphere3, Point3D(0, 0, 0), f);

    double f2[3] = { 0.6, 0.6, 0.6 };
    rt.translate(sphere4, Vector3D(-2, 1, -3));
    rt.scale(sphere4, Point3D(0, 0, 0), f2);

    double fp2[3] = { 3.0, 3.0, 3.0 };
    rt.translate(plane2,Vector3D(-4,1,-5));
    rt.rotate(plane2, 'z', 45);
    rt.rotate(plane2, 'y', 45);
    rt.scale(plane2, Point3D(0, 0, 0), fp2);

//    rt.translate(plane3,Vector3D(-2,0,-5));
//    rt.rotate(plane2, 'z', 45);
//    rt.rotate(plane3, 'x', 90);
//	rt.scale(plane3, Point3D(0, 0, 0), fp2);
//
//    rt.translate(plane4,Vector3D(-2,1,-5));
//    rt.rotate(plane2, 'z', 45);
//    rt.rotate(plane4, 'y', 90);
//	rt.scale(plane4, Point3D(0, 0, 0), fp2);

    rt.setAAMode(Raytracer::AA_SUPER_SAMPLING);
    rt.setShadingMode(Raytracer::SCENE_MODE_PHONG);
    rt.setShadows(Raytracer::SHADOW_CAST);
    rt.setEnvMapMode(Raytracer::ENV_MAP_CUBE_SKYBOX);
    rt.setColorSpaceMode(Raytracer::COLOR_ENC_SRGB_GAMMA_CORRECT);
    rt.setReflDepth(4);

    //set the texture map for the objects of interest in the scene if texture map flag is ON
    if (TEXTURE_MAP_FLAG) {
        // load texture image
        TextureMap txtmp;
        txtmp = TextureMap(TEXTURE_IMG);
        TextureMap txtmp2 = TextureMap(TEXTURE_IMG2);
        TextureMap txtmp3 = TextureMap(TEXTURE_IMG3);

        //for now, we are only using texture map for sphere
        sphere->useTextureMapping = true;
        sphere->obj->setTextureMap(txtmp);

        sphere2->useTextureMapping = false;

        sphere4->useTextureMapping = true;
        sphere4->setTextMapOfObject(txtmp2);

        plane2->useTextureMapping = true;
        plane2->setTextMapOfObject(txtmp3);

//        plane3->useTextureMapping = true;
//        plane3->setTextMapOfObject(txtmp3);
//
//        plane4->useTextureMapping = true;
//        plane4->setTextMapOfObject(txtmp3);
    }
    // refraction if it's turned on
    if (REFRACTION_FLAG) {
        rt.setRefractionMode(REFRACTION_FLAG);
    }

    if ( rt.getEnvMapMode() != Raytracer::NONE ) {
        // load images
        EnvMap env;
        if ( _DEBUG ) {
            env = EnvMap(
                      "EnvMaps/DebugMaps/posx.bmp",
                      "EnvMaps/DebugMaps/posy.bmp",
                      "EnvMaps/DebugMaps/posz.bmp",
                      "EnvMaps/DebugMaps/negx.bmp",
                      "EnvMaps/DebugMaps/negy.bmp",
                      "EnvMaps/DebugMaps/negz.bmp"
                  );
        } else {
            env = EnvMap(
                      "EnvMaps/SaintLazarusChurch/posx.bmp",
                      "EnvMaps/SaintLazarusChurch/posy.bmp",
                      "EnvMaps/SaintLazarusChurch/posz.bmp",
                      "EnvMaps/SaintLazarusChurch/negx.bmp",
                      "EnvMaps/SaintLazarusChurch/negy.bmp",
                      "EnvMaps/SaintLazarusChurch/negz.bmp"
                  );
        }

        rt.setEnvMap(env);
    }

    printf("REFRACTION SCENE : 1 :: Rendering...\n");
    rt.render(width, height, eye2, view2, up, fov, "refraction_2.bmp");
    Point3D eye3(0, 0, 1);
    Vector3D view3(0, 0, -1);
    printf("REFRACTION SCENE : 2 :: Rendering...\n");
    rt.render(width, height, eye3, view3, up, fov, "refraction_1.bmp");

    printf("REFRACTION SCENE : 1 :: Done!\n");
}
Esempio n. 11
0
int main(int argc, char* argv[])
{
  // Load the mesh.
  Mesh mesh;
  MeshReaderH2D mloader;
  mloader.load(mesh_file.c_str(), &mesh);

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

  // Solution variables.
  Solution<double> sln1, sln2, sln3, sln4;
  Hermes::vector<Solution<double>*> solutions(&sln1, &sln2, &sln3, &sln4);
  
  // Define initial conditions.
  Hermes::Mixins::Loggable::Static::info("Setting initial conditions.");
  ConstantSolution<double> iter1(&mesh, 1.00), iter2(&mesh, 1.00), iter3(&mesh, 1.00), iter4(&mesh, 1.00);

  Hermes::vector<MeshFunction<double>*> iterates(&iter1, &iter2, &iter3, &iter4);

  // Create H1 spaces with default shapesets.
  H1Space<double> space1(&mesh, P_INIT_1);
  H1Space<double> space2(&mesh, P_INIT_2);
  H1Space<double> space3(&mesh, P_INIT_3);
  H1Space<double> space4(&mesh, P_INIT_4);
  Hermes::vector<const Space<double>* > spaces(&space1, &space2, &space3, &space4);
  int ndof = Space<double>::get_num_dofs(spaces);
  Hermes::Mixins::Loggable::Static::info("ndof = %d", ndof);

  // Initialize views.
  ScalarView view1("Neutron flux 1", new WinGeom(0, 0, 320, 600));
  ScalarView view2("Neutron flux 2", new WinGeom(350, 0, 320, 600));
  ScalarView view3("Neutron flux 3", new WinGeom(700, 0, 320, 600));
  ScalarView view4("Neutron flux 4", new WinGeom(1050, 0, 320, 600));
  
  // Do not show meshes, set 3D mode.
  view1.show_mesh(false); view1.set_3d_mode(true);
  view2.show_mesh(false); view2.set_3d_mode(true);
  view3.show_mesh(false); view3.set_3d_mode(true);
  view4.show_mesh(false); view4.set_3d_mode(true);
  
  // Load physical data of the problem for the 4 energy groups.
  Hermes::Hermes2D::WeakFormsNeutronics::Multigroup::MaterialProperties::Diffusion::MaterialPropertyMaps matprop(4);
  matprop.set_D(D);
  matprop.set_Sigma_r(Sr);
  matprop.set_Sigma_s(Ss);
  matprop.set_Sigma_a(Sa);
  matprop.set_Sigma_f(Sf);
  matprop.set_nu(nu);
  matprop.set_chi(chi);
  matprop.validate();
  
  // Printing table of material properties.
  std::cout << matprop;
  
  // Initialize the weak formulation.
  CustomWeakForm wf(matprop, iterates, k_eff, bdy_vacuum);

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

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

  // Time measurement.
  Hermes::Mixins::TimeMeasurable cpu_time;
      
  // Main power iteration loop:
  int it = 1; bool done = false;
  do
  {
    Hermes::Mixins::Loggable::Static::info("------------ Power iteration %d:", it);
    
    Hermes::Mixins::Loggable::Static::info("Newton's method.");
    
    // Perform Newton's iteration.
    try
    {
      newton.set_newton_max_iter(NEWTON_MAX_ITER);
      newton.set_newton_tol(NEWTON_TOL);
      newton.solve_keep_jacobian();
    }
    catch(Hermes::Exceptions::Exception e)
    {
      e.printMsg();
      throw Hermes::Exceptions::Exception("Newton's iteration failed.");
    }
       
    // Debug.
    //printf("\n=================================================\n");
    //for (int d = 0; d < ndof; d++) printf("%g ", newton.get_sln_vector()[d]);

    // Translate the resulting coefficient vector into a Solution.
    Solution<double>::vector_to_solutions(newton.get_sln_vector(), spaces, solutions);
    
    // Show intermediate solutions.
    view1.show(&sln1);    
    view2.show(&sln2);
    view3.show(&sln3);    
    view4.show(&sln4);
    
    // Compute eigenvalue.
    SourceFilter source(solutions, &matprop, core);
    SourceFilter source_prev(iterates, &matprop, core);
    
    double k_new = k_eff * (integrate(&source, core) / integrate(&source_prev, core));
    Hermes::Mixins::Loggable::Static::info("Largest eigenvalue: %.8g, rel. difference from previous it.: %g", k_new, fabs((k_eff - k_new) / k_new));
    
    // Stopping criterion.
    if (fabs((k_eff - k_new) / k_new) < ERROR_STOP) done = true;

    // Update eigenvalue.
    k_eff = k_new;
    wf.update_keff(k_eff);
    
    if (!done)
    {
      // Save solutions for the next iteration.
      iter1.copy(&sln1);    
      iter2.copy(&sln2);
      iter3.copy(&sln3);    
      iter4.copy(&sln4);
      
      it++;
    }
  }
  while (!done);
  
  // Time measurement.
  cpu_time.tick();
  
  // Show solutions.
  view1.show(&sln1);
  view2.show(&sln2);
  view3.show(&sln3);    
  view4.show(&sln4);
  
  // Skip visualization time.
  cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);

  // 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;
}
Esempio n. 12
0
int main(int argc, char* argv[])
{
  // Load the mesh.
  Mesh mesh;
  H2DReader mloader;
  mloader.load("reactor.mesh", &mesh);

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

  // Solution variables.
  Solution sln1, sln2, sln3, sln4;
  Solution iter1, iter2, iter3, iter4;
  Hermes::Tuple<Solution*> solutions(&sln1, &sln2, &sln3, &sln4);

  // Define initial conditions.
  info("Setting initial conditions.");
  iter1.set_const(&mesh, 1.00);
  iter2.set_const(&mesh, 1.00);
  iter3.set_const(&mesh, 1.00);
  iter4.set_const(&mesh, 1.00);

  // Enter boundary markers.
  BCTypes bc_types;
  bc_types.add_bc_neumann(BDY_SYM);
  bc_types.add_bc_newton(BDY_VACUUM);

  // Create H1 spaces with default shapesets.
  H1Space space1(&mesh, &bc_types, P_INIT_1);
  H1Space space2(&mesh, &bc_types, P_INIT_2);
  H1Space space3(&mesh, &bc_types, P_INIT_3);
  H1Space space4(&mesh, &bc_types, P_INIT_4);
  Hermes::Tuple<Space*> spaces(&space1, &space2, &space3, &space4);
  
  int ndof = Space::get_num_dofs(Hermes::Tuple<Space*>(&space1, &space2, &space3, &space4));
  info("ndof = %d.", ndof);
  
  // Initialize views.
  ScalarView view1("Neutron flux 1", new WinGeom(0, 0, 320, 600));
  ScalarView view2("Neutron flux 2", new WinGeom(350, 0, 320, 600));
  ScalarView view3("Neutron flux 3", new WinGeom(700, 0, 320, 600));
  ScalarView view4("Neutron flux 4", new WinGeom(1050, 0, 320, 600));
  
  // Do not show meshes.
  view1.show_mesh(false); view1.set_3d_mode(true);
  view2.show_mesh(false); view2.set_3d_mode(true);
  view3.show_mesh(false); view3.set_3d_mode(true);
  view4.show_mesh(false); view4.set_3d_mode(true);
  
  // Initialize the weak formulation.
  WeakForm wf(4);
  wf.add_matrix_form(0, 0, callback(biform_0_0), HERMES_SYM);
  wf.add_matrix_form(1, 1, callback(biform_1_1), HERMES_SYM);
  wf.add_matrix_form(1, 0, callback(biform_1_0));
  wf.add_matrix_form(2, 2, callback(biform_2_2), HERMES_SYM);
  wf.add_matrix_form(2, 1, callback(biform_2_1));
  wf.add_matrix_form(3, 3, callback(biform_3_3), HERMES_SYM);
  wf.add_matrix_form(3, 2, callback(biform_3_2));
  wf.add_vector_form(0, callback(liform_0), marker_core, Hermes::Tuple<MeshFunction*>(&iter1, &iter2, &iter3, &iter4));
  wf.add_vector_form(1, callback(liform_1), marker_core, Hermes::Tuple<MeshFunction*>(&iter1, &iter2, &iter3, &iter4));
  wf.add_vector_form(2, callback(liform_2), marker_core, Hermes::Tuple<MeshFunction*>(&iter1, &iter2, &iter3, &iter4));
  wf.add_vector_form(3, callback(liform_3), marker_core, Hermes::Tuple<MeshFunction*>(&iter1, &iter2, &iter3, &iter4));
  wf.add_matrix_form_surf(0, 0, callback(biform_surf_0_0), BDY_VACUUM);
  wf.add_matrix_form_surf(1, 1, callback(biform_surf_1_1), BDY_VACUUM);
  wf.add_matrix_form_surf(2, 2, callback(biform_surf_2_2), BDY_VACUUM);
  wf.add_matrix_form_surf(3, 3, callback(biform_surf_3_3), BDY_VACUUM);

  // Initialize the FE problem.
  bool is_linear = true;
  DiscreteProblem dp(&wf, spaces, is_linear);
  
  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).
  }
  
  // Time measurement.
  TimePeriod cpu_time, solver_time;
  
  // Main power iteration loop:
  int iter = 1; bool done = false;
  bool rhs_only = false;
  
  solver->set_factorization_scheme(HERMES_REUSE_FACTORIZATION_COMPLETELY);
  do
  {
    info("------------ Power iteration %d:", iter);
    
    info("Assembling the stiffness matrix and right-hand side vector.");
    dp.assemble(matrix, rhs, rhs_only);
    
    /* 
    // Testing the factorization reuse schemes for direct solvers.
    if (iter == 10)  
      solver->set_factorization_scheme(HERMES_REUSE_MATRIX_REORDERING);
    if (iter == 20)
      solver->set_factorization_scheme(HERMES_REUSE_MATRIX_REORDERING_AND_SCALING);
    if (iter == 30) 
      solver->set_factorization_scheme(HERMES_REUSE_FACTORIZATION_COMPLETELY);
    */
 
    info("Solving the matrix problem by %s.", MatrixSolverNames[matrix_solver].c_str());
    solver_time.tick(HERMES_SKIP);  
    bool solved = solver->solve();  
    solver_time.tick();
    
    if(solved)
      Solution::vector_to_solutions(solver->get_solution(), spaces, solutions);
    else
      error ("Matrix solver failed.\n");

    // Show intermediate solutions.
    // view1.show(&sln1);    
    // view2.show(&sln2);
    // view3.show(&sln3);    
    // view4.show(&sln4);

    SimpleFilter source(source_fn, Hermes::Tuple<MeshFunction*>(&sln1, &sln2, &sln3, &sln4));
    SimpleFilter source_prev(source_fn, Hermes::Tuple<MeshFunction*>(&iter1, &iter2, &iter3, &iter4));

    // Compute eigenvalue.
    double k_new = k_eff * (integrate(&source, marker_core) / integrate(&source_prev, marker_core));
    info("Largest eigenvalue: %.8g, rel. difference from previous it.: %g", k_new, fabs((k_eff - k_new) / k_new));
    
    // Stopping criterion.
    if (fabs((k_eff - k_new) / k_new) < ERROR_STOP) done = true;

    // Update eigenvalue.
    k_eff = k_new;
    
    if (!done)
    {
      // Save solutions for the next iteration.
      iter1.copy(&sln1);    
      iter2.copy(&sln2);
      iter3.copy(&sln3);    
      iter4.copy(&sln4);
      
      // Don't need to reassemble the system matrix in further iterations,
      // only the rhs changes to reflect the progressively updated source.
      rhs_only = true;

      iter++;
    }
  }
  while (!done);
  
  // Time measurement.
  cpu_time.tick();
  solver_time.tick(HERMES_SKIP);
  
  // Print timing information.
  verbose("Average solver time for one power iteration: %g s", solver_time.accumulated() / iter);
  
  // Clean up.
  delete matrix;
  delete rhs;
  delete solver;

  // Show solutions.
  view1.show(&sln1);
  view2.show(&sln2);
  view3.show(&sln3);    
  view4.show(&sln4);
  
  // 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;
}
Esempio n. 13
0
int main(int argc, char* argv[])
{
  // Time measurement.
  Hermes::Mixins::TimeMeasurable cpu_time;
  cpu_time.tick();
  
  // Load physical data of the problem.
  MaterialPropertyMaps matprop(N_GROUPS);
  matprop.set_D(D);
  matprop.set_Sigma_r(Sr);
  matprop.set_Sigma_s(Ss);
  matprop.set_Sigma_a(Sa);
  matprop.set_Sigma_f(Sf);
  matprop.set_nu(nu);
  matprop.set_chi(chi);
  matprop.validate();
  
  std::cout << matprop;

  // Use multimesh, i.e. create one mesh for each energy group.
  Hermes::vector<Mesh *> meshes;
  for (unsigned int g = 0; g < matprop.get_G(); g++) 
    meshes.push_back(new Mesh());
  
  // Load the mesh for the 1st group.
  MeshReaderH2D mloader;
  mloader.load(mesh_file.c_str(), meshes[0]);
 
  for (unsigned int g = 1; g < matprop.get_G(); g++) 
  {
    // Obtain meshes for the 2nd to 4th group by cloning the mesh loaded for the 1st group.
    meshes[g]->copy(meshes[0]);
    // Initial uniform refinements.
    for (int i = 0; i < INIT_REF_NUM[g]; i++) 
      meshes[g]->refine_all_elements();
  }
  for (int i = 0; i < INIT_REF_NUM[0]; i++) 
    meshes[0]->refine_all_elements();
  
  // Create pointers to solutions on coarse and fine meshes and from the latest power iteration, respectively.
  Hermes::vector<Solution<double>*> coarse_solutions, fine_solutions;
  Hermes::vector<MeshFunction<double>*> power_iterates;

  // Initialize all the new solution variables.
  for (unsigned int g = 0; g < matprop.get_G(); g++) 
  {
    coarse_solutions.push_back(new Solution<double>());
    fine_solutions.push_back(new Solution<double>());
    power_iterates.push_back(new ConstantSolution<double>(meshes[g], 1.0));   
  }
  
  // Create the approximation spaces with the default shapeset.
  H1Space<double> space1(meshes[0], P_INIT[0]);
  H1Space<double> space2(meshes[1], P_INIT[1]);
  H1Space<double> space3(meshes[2], P_INIT[2]);
  H1Space<double> space4(meshes[3], P_INIT[3]);
  Hermes::vector<const Space<double>*> const_spaces(&space1, &space2, &space3, &space4);
  Hermes::vector<Space<double>*> spaces(&space1, &space2, &space3, &space4);

  // Initialize the weak formulation.
  CustomWeakForm wf(matprop, power_iterates, k_eff, bdy_vacuum);
    
  // Initialize the discrete algebraic representation of the problem and its solver.
  //
  // Create the matrix and right-hand side vector for the solver.
  SparseMatrix<double>* mat = create_matrix<double>();
  Vector<double>* rhs = create_vector<double>();
  // Instantiate the solver itself.
  LinearMatrixSolver<double>* solver = create_linear_solver<double>( mat, rhs);

  // Initialize views.
  /* for 1280x800 display */
  ScalarView view1("Neutron flux 1", new WinGeom(0, 0, 320, 400));
  ScalarView view2("Neutron flux 2", new WinGeom(330, 0, 320, 400));
  ScalarView view3("Neutron flux 3", new WinGeom(660, 0, 320, 400));
  ScalarView view4("Neutron flux 4", new WinGeom(990, 0, 320, 400));
  OrderView oview1("Mesh for group 1", new WinGeom(0, 450, 320, 500));
  OrderView oview2("Mesh for group 2", new WinGeom(330, 450, 320, 500));
  OrderView oview3("Mesh for group 3", new WinGeom(660, 450, 320, 500));
  OrderView oview4("Mesh for group 4", new WinGeom(990, 450, 320, 500));

  /* for adjacent 1280x800 and 1680x1050 displays
  ScalarView view1("Neutron flux 1", new WinGeom(0, 0, 640, 480));
  ScalarView view2("Neutron flux 2", new WinGeom(650, 0, 640, 480));
  ScalarView view3("Neutron flux 3", new WinGeom(1300, 0, 640, 480));
  ScalarView view4("Neutron flux 4", new WinGeom(1950, 0, 640, 480));
  OrderView oview1("Mesh for group 1", new WinGeom(1300, 500, 340, 500));
  OrderView oview2("Mesh for group 2", new WinGeom(1650, 500, 340, 500));
  OrderView oview3("Mesh for group 3", new WinGeom(2000, 500, 340, 500));
  OrderView oview4("Mesh for group 4", new WinGeom(2350, 500, 340, 500));
  */

  Hermes::vector<ScalarView *> sviews(&view1, &view2, &view3, &view4);
  Hermes::vector<OrderView *> oviews(&oview1, &oview2, &oview3, &oview4); 
  for (unsigned int g = 0; g < matprop.get_G(); g++) 
  { 
    sviews[g]->show_mesh(false);
    sviews[g]->set_3d_mode(true);
  }
  
  // DOF and CPU convergence graphs
  GnuplotGraph graph_dof("Error convergence", "NDOF", "log(error)");
  graph_dof.add_row("H1 err. est. [%]", "r", "-", "o");
  graph_dof.add_row("L2 err. est. [%]", "g", "-", "s");
  graph_dof.add_row("Keff err. est. [milli-%]", "b", "-", "d");
  graph_dof.set_log_y();
  graph_dof.show_legend();
  graph_dof.show_grid();

  GnuplotGraph graph_dof_evol("Evolution of NDOF", "Adaptation step", "NDOF");
  graph_dof_evol.add_row("group 1", "r", "-", "o");
  graph_dof_evol.add_row("group 2", "g", "-", "x");
  graph_dof_evol.add_row("group 3", "b", "-", "+");
  graph_dof_evol.add_row("group 4", "m", "-", "*");
  graph_dof_evol.set_log_y();
  graph_dof_evol.set_legend_pos("bottom right");
  graph_dof_evol.show_grid();

  GnuplotGraph graph_cpu("Error convergence", "CPU time [s]", "log(error)");
  graph_cpu.add_row("H1 err. est. [%]", "r", "-", "o");
  graph_cpu.add_row("L2 err. est. [%]", "g", "-", "s");
  graph_cpu.add_row("Keff err. est. [milli-%]", "b", "-", "d");
  graph_cpu.set_log_y();
  graph_cpu.show_legend();
  graph_cpu.show_grid();

  // Initialize the refinement selectors.
  H1ProjBasedSelector<double> selector(CAND_LIST, CONV_EXP, H2DRS_DEFAULT_ORDER);
  Hermes::vector<RefinementSelectors::Selector<double>*> selectors;
  for (unsigned int g = 0; g < matprop.get_G(); g++) 
    selectors.push_back(&selector);
  
  Hermes::vector<MatrixFormVol<double>*> projection_jacobian;
  Hermes::vector<VectorFormVol<double>*> projection_residual;
  for (unsigned int g = 0; g < matprop.get_G(); g++) 
  {
    projection_jacobian.push_back(new H1AxisymProjectionJacobian(g));
    projection_residual.push_back(new H1AxisymProjectionResidual(g, power_iterates[g]));
  }
  
  Hermes::vector<ProjNormType> proj_norms_h1, proj_norms_l2;
  for (unsigned int g = 0; g < matprop.get_G(); g++)
  {
    proj_norms_h1.push_back(HERMES_H1_NORM);
    proj_norms_l2.push_back(HERMES_L2_NORM);
  }
  
  // Initial power iteration to obtain a coarse estimate of the eigenvalue and the fission source.
  Hermes::Mixins::Loggable::Static::info("Coarse mesh power iteration, %d + %d + %d + %d = %d ndof:", report_num_dofs(spaces));
  power_iteration(matprop, const_spaces, &wf, power_iterates, core, TOL_PIT_CM, matrix_solver);
  
  // Adaptivity loop:
  int as = 1; bool done = false;
  do 
  {
    Hermes::Mixins::Loggable::Static::info("---- Adaptivity step %d:", as);
    
    // Construct globally refined meshes and setup reference spaces on them.
    Hermes::vector<const Space<double>*> ref_spaces_const;
    Hermes::vector<Mesh *> ref_meshes;
    for (unsigned int g = 0; g < matprop.get_G(); g++) 
    { 
      ref_meshes.push_back(new Mesh());
      Mesh *ref_mesh = ref_meshes.back();      
      ref_mesh->copy(spaces[g]->get_mesh());
      ref_mesh->refine_all_elements();
      
      int order_increase = 1;
      ref_spaces_const.push_back(spaces[g]->dup(ref_mesh, order_increase));
    }

#ifdef WITH_PETSC    
    // PETSc assembling is currently slow for larger matrices, so we switch to 
    // UMFPACK when matrices of order >8000 start to appear.
    if (Space<double>::get_num_dofs(ref_spaces_const) > 8000 && matrix_solver == SOLVER_PETSC)
    {
      // Delete the old solver.
      delete mat;
      delete rhs;
      delete solver;
      
      // Create a new one.
      matrix_solver = SOLVER_UMFPACK;
      mat = create_matrix<double>();
      rhs = create_vector<double>();
      solver = create_linear_solver<double>( mat, rhs);
    }
#endif    

    // Solve the fine mesh problem.
    Hermes::Mixins::Loggable::Static::info("Fine mesh power iteration, %d + %d + %d + %d = %d ndof:", report_num_dofs(ref_spaces_const));
    power_iteration(matprop, ref_spaces_const, &wf, power_iterates, core, TOL_PIT_RM, matrix_solver);
    
    // Store the results.
    for (unsigned int g = 0; g < matprop.get_G(); g++) 
      fine_solutions[g]->copy((static_cast<Solution<double>*>(power_iterates[g])));

    Hermes::Mixins::Loggable::Static::info("Projecting fine mesh solutions on coarse meshes.");
    // This is commented out as the appropriate method was deleted in the commit
    // "Cleaning global projections" (b282194946225014faa1de37f20112a5a5d7ab5a).
    //OGProjection<double> ogProjection; ogProjection.project_global(spaces, projection_jacobian, projection_residual, coarse_solutions);

    // Time measurement.
    cpu_time.tick();

    // View the coarse mesh solution and meshes.
    for (unsigned int g = 0; g < matprop.get_G(); g++) 
    { 
      sviews[g]->show(coarse_solutions[g]); 
      oviews[g]->show(spaces[g]);
    }

    // Skip visualization time.
    cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);

    // Report the number of negative eigenfunction values.
    Hermes::Mixins::Loggable::Static::info("Num. of negative values: %d, %d, %d, %d",
         get_num_of_neg(coarse_solutions[0]), get_num_of_neg(coarse_solutions[1]),
         get_num_of_neg(coarse_solutions[2]), get_num_of_neg(coarse_solutions[3]));

    // Calculate element errors and total error estimate.
    Adapt<double> adapt_h1(spaces);
    Adapt<double> adapt_l2(spaces);    
    for (unsigned int g = 0; g < matprop.get_G(); g++)
    {
      adapt_h1.set_error_form(g, g, new ErrorForm(proj_norms_h1[g]));
      adapt_l2.set_error_form(g, g, new ErrorForm(proj_norms_l2[g]));
    }
    
    // Calculate element errors and error estimates in H1 and L2 norms. Use the H1 estimate to drive adaptivity.
    Hermes::Mixins::Loggable::Static::info("Calculating errors.");
    Hermes::vector<double> h1_group_errors, l2_group_errors;
    double h1_err_est = adapt_h1.calc_err_est(coarse_solutions, fine_solutions, &h1_group_errors) * 100;
    double l2_err_est = adapt_l2.calc_err_est(coarse_solutions, fine_solutions, &l2_group_errors, false) * 100;

    // Time measurement.
    cpu_time.tick();
    double cta = cpu_time.accumulated();
    
    // Report results.
    Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d + %d + %d + %d = %d", report_num_dofs(spaces));

    // Millipercent eigenvalue error w.r.t. the reference value (see physical_parameters.cpp). 
    double keff_err = 1e5*fabs(wf.get_keff() - REF_K_EFF)/REF_K_EFF;

    Hermes::Mixins::Loggable::Static::info("per-group err_est_coarse (H1): %g%%, %g%%, %g%%, %g%%", report_errors(h1_group_errors));
    Hermes::Mixins::Loggable::Static::info("per-group err_est_coarse (L2): %g%%, %g%%, %g%%, %g%%", report_errors(l2_group_errors));
    Hermes::Mixins::Loggable::Static::info("total err_est_coarse (H1): %g%%", h1_err_est);
    Hermes::Mixins::Loggable::Static::info("total err_est_coarse (L2): %g%%", l2_err_est);
    Hermes::Mixins::Loggable::Static::info("k_eff err: %g milli-percent", keff_err);

    // Add entry to DOF convergence graph.
    int ndof_coarse = spaces[0]->get_num_dofs() + spaces[1]->get_num_dofs() 
      + spaces[2]->get_num_dofs() + spaces[3]->get_num_dofs();
    graph_dof.add_values(0, ndof_coarse, h1_err_est);
    graph_dof.add_values(1, ndof_coarse, l2_err_est);
    graph_dof.add_values(2, ndof_coarse, keff_err);

    // Add entry to CPU convergence graph.
    graph_cpu.add_values(0, cta, h1_err_est);
    graph_cpu.add_values(1, cta, l2_err_est);
    graph_cpu.add_values(2, cta, keff_err);

    for (unsigned int g = 0; g < matprop.get_G(); g++)
      graph_dof_evol.add_values(g, as, Space<double>::get_num_dofs(spaces[g]));

    cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP);

    // If err_est too large, adapt the mesh (L2 norm chosen since (weighted integrals of) solution values
    // are more important for further analyses than the derivatives. 
    if (l2_err_est < ERR_STOP) 
      done = true;
    else 
    {
      Hermes::Mixins::Loggable::Static::info("Adapting the coarse mesh.");
      done = adapt_h1.adapt(selectors, THRESHOLD, STRATEGY, MESH_REGULARITY);
      if (spaces[0]->get_num_dofs() + spaces[1]->get_num_dofs() 
          + spaces[2]->get_num_dofs() + spaces[3]->get_num_dofs() >= NDOF_STOP) 
        done = true;
    }

    // Free reference meshes and spaces.
    for (unsigned int g = 0; g < matprop.get_G(); g++) 
    {
      delete ref_spaces_const[g];
      delete ref_meshes[g];
    }

    as++;
        
    if (as >= MAX_ADAPT_NUM) done = true;
  }
  while(done == false);

  Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated());
  
  for (unsigned int g = 0; g < matprop.get_G(); g++) 
  {
    delete spaces[g]; delete meshes[g];
    delete coarse_solutions[g], delete fine_solutions[g]; delete power_iterates[g];
  }
  
  delete mat;
  delete rhs;
  delete solver;

  graph_dof.save("conv_dof.gp");
  graph_cpu.save("conv_cpu.gp");
  graph_dof_evol.save("dof_evol.gp");

  // Wait for all views to be closed.
  View::wait();
  return 0;
}
Esempio n. 14
0
 exposed_view_type view2() const { return view1(bool_constant<is_amv_value_or_view_class<DataType>::value>()); }
Esempio n. 15
0
int main(int argc, char* args[])
{
  // Load the mesh.
  MeshSharedPtr mesh(new Mesh);
  MeshReaderH2D mloader;
  mloader.load("square.mesh", mesh);

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

  // Create an L2 space.
  SpaceSharedPtr<double> fine_space(new L2Space<double>(mesh, USE_TAYLOR_SHAPESET ? std::max(P_INIT, 2) : P_INIT, (USE_TAYLOR_SHAPESET ? (Shapeset*)(new L2ShapesetTaylor) : (Shapeset*)(new L2ShapesetLegendre))));

  // Initialize refinement selector.
  L2ProjBasedSelector<double> selector(CAND_LIST);
  selector.set_error_weights(1., 1., 1.);

  MeshFunctionSharedPtr<double> sln(new Solution<double>);
  MeshFunctionSharedPtr<double> refsln(new Solution<double>);

  // Initialize the weak formulation.
  WeakFormSharedPtr<double> wf(new CustomWeakForm("Bdy_bottom_left", mesh));
  ScalarView view1("Solution", new WinGeom(900, 0, 450, 350));
  view1.fix_scale_width(60);

  // Initialize linear solver.
  Hermes::Hermes2D::LinearSolver<double> linear_solver;
  linear_solver.set_weak_formulation(wf);

  adaptivity.set_space(fine_space);

  int as = 1; bool done = false;
  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<double>::ReferenceSpaceCreator refspace_creator(fine_space, ref_mesh, 0);
    SpaceSharedPtr<double> refspace = refspace_creator.create_ref_space();

    try
    {
      linear_solver.set_space(refspace);
      linear_solver.solve();

      if (USE_TAYLOR_SHAPESET)
      {
        PostProcessing::VertexBasedLimiter limiter(refspace, linear_solver.get_sln_vector(), P_INIT);
        refsln = limiter.get_solution();
      }
      else
      {
        Solution<double>::vector_to_solution(linear_solver.get_sln_vector(), refspace, refsln);
      }

      view1.show(refsln);
      OGProjection<double>::project_global(fine_space, refsln, sln, HERMES_L2_NORM);
    }
    catch (Exceptions::Exception& e)
    {
      std::cout << e.info();
    }
    catch (std::exception& e)
    {
      std::cout << e.what();
    }

    // Calculate element errors and total error estimate.
    errorCalculator.calculate_errors(sln, refsln);
    double err_est_rel = errorCalculator.get_total_error_squared() * 100;

    std::cout << "Error: " << err_est_rel << "%." << std::endl;

    // If err_est_rel too large, adapt the mesh.
    if (err_est_rel < ERR_STOP)
      done = true;
    else
      done = adaptivity.adapt(&selector);
    as++;
  } while (done == false);

  // Wait for keyboard or mouse input.
  View::wait();
  return 0;
}
Esempio n. 16
0
int main(int argc, char* args[])
{
    // Load the mesh.
    Mesh mesh;
    MeshReaderH2D mloader;
    mloader.load("square.mesh", &mesh);

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

    mesh.refine_by_criterion(criterion, INIT_REF_CRITERION);

    MeshView m;
    m.show(&mesh);

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

    ScalarView view1("Solution - Discontinuous Galerkin FEM", new WinGeom(900, 0, 450, 350));
    ScalarView view2("Solution - Standard continuous FEM", new WinGeom(900, 400, 450, 350));

    if(WANT_DG)
    {
        // Create an L2 space.
        L2Space<double> space_l2(&mesh, P_INIT);

        // Initialize the solution.
        Solution<double> sln_l2;

        // Initialize the weak formulation.
        CustomWeakForm wf_l2(BDY_BOTTOM_LEFT);


        // Initialize the FE problem.
        DiscreteProblem<double> dp_l2(&wf_l2, &space_l2);

        info("Assembling Discontinuous Galerkin (nelem: %d, ndof: %d).", mesh.get_num_active_elements(), space_l2.get_num_dofs());
        dp_l2.assemble(matrix, rhs);

        // Solve the linear system. If successful, obtain the solution.
        info("Solving Discontinuous Galerkin.");
        if(solver->solve())
            if(DG_SHOCK_CAPTURING)
            {
                FluxLimiter flux_limiter(FluxLimiter::Kuzmin, solver->get_sln_vector(), &space_l2, true);

                flux_limiter.limit_second_orders_according_to_detector();

                flux_limiter.limit_according_to_detector();

                flux_limiter.get_limited_solution(&sln_l2);

                view1.set_title("Solution - limited Discontinuous Galerkin FEM");
            }
            else
                Solution<double>::vector_to_solution(solver->get_sln_vector(), &space_l2, &sln_l2);
        else
            error ("Matrix solver failed.\n");

        // View the solution.
        view1.show(&sln_l2);
    }
    if(WANT_FEM)
    {
        // Create an H1 space.
        H1Space<double> space_h1(&mesh, P_INIT);

        // Initialize the solution.
        Solution<double> sln_h1;

        // Initialize the weak formulation.
        CustomWeakForm wf_h1(BDY_BOTTOM_LEFT, false);


        // Initialize the FE problem.
        DiscreteProblem<double> dp_h1(&wf_h1, &space_h1);

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

        info("Assembling Continuous FEM (nelem: %d, ndof: %d).", mesh.get_num_active_elements(), space_h1.get_num_dofs());
        dp_h1.assemble(matrix, rhs);

        // Solve the linear system. If successful, obtain the solution.
        info("Solving Continuous FEM.");
        if(solver->solve())
            Solution<double>::vector_to_solution(solver->get_sln_vector(), &space_h1, &sln_h1);
        else
            error ("Matrix solver failed.\n");

        // View the solution.
        view2.show(&sln_h1);
    }

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

    // Wait for keyboard or mouse input.
    View::wait();
    return 0;
}
Esempio n. 17
0
int main(){

    sf::RenderWindow window(sf::VideoMode(800, 600), "Particles");
    sf::RectangleShape rectangle, rectangle2, nexus;

    ParticleSystem particles(1000);
    sf::Clock clock;

    sf::Vector2i screenDimensions(800, 600);
    sf::Vector2i blockDimensions(10, 10);

    sf::View view1(sf::FloatRect(0, 0, 800, 600));
    sf::View view2(sf::FloatRect(800, 0, 800, 600));

    sf::View standard = window.getView();
    unsigned int size = 100;
    sf::View minimap(sf::FloatRect(0, 0, 800, 600));
    //sf::View minimap(sf::FloatRect(view1.getCenter().x, view1.getCenter().y, size, window.getSize().y*size/window.getSize().x));
    //minimap.setViewport(sf::FloatRect(1.f-(1.f*minimap.getSize().x)/window.getSize().x-0.02f, 1.f-(1.f*minimap.getSize().y)/window.getSize().y-0.02f, (1.f*minimap.getSize().x)/window.getSize().x, (1.f*minimap.getSize().y)/window.getSize().y));
    minimap.setViewport(sf::FloatRect(0.75f, 0, 0.25f, 0.25f));
    minimap.zoom(2.f);
    //view1.setViewport(sf::FloatRect(0, 0, 0.5f, 1));

    // joueur 2 (côté droit de l'écran)
    //view2.setViewport(sf::FloatRect(0.5f, 0, 0.5f, 1));


    rectangle.setOutlineThickness(3);
    rectangle.setOutlineColor(sf::Color(0, 0, 0, 255));
    rectangle.setSize({50.f, 50.f});
    rectangle.setPosition({400.f, 300.f});
    rectangle.setFillColor(sf::Color::Red);

    rectangle2.setOutlineThickness(3);
    rectangle2.setOutlineColor(sf::Color(0, 0, 0, 255));
    rectangle2.setSize({500.f, 500.f});
    rectangle2.setPosition({800.f, 0.f});
    rectangle2.setFillColor(sf::Color::Blue);

    int x = rand()%(800-800*2)+800;
    int y = rand()%(600-0)+0;
    nexus.setSize({100.f, 100.f});
     std::cout << x << " , " << y << std::endl;
    nexus.setPosition({400.f, 300.f});

    sf::Vector2f mouse;
    //view1.setCenter(rectangle.getPosition());

    while (window.isOpen()){
        sf::Event event;
        while (window.pollEvent(event)){
            if(event.type == sf::Event::Closed){
                window.close();
            }

            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
                rectangle.move(-7, 0);
                mouse = {rectangle.getPosition().x+(rectangle.getSize().x/2), rectangle.getPosition().y+(rectangle.getSize().y/2)};

                view1.setCenter(rectangle.getPosition());
                std::cout << rectangle.getPosition().x << " , " << rectangle.getPosition().y << std::endl;
            }
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
                mouse = {rectangle.getPosition().x+(rectangle.getSize().x/2), rectangle.getPosition().y+(rectangle.getSize().y/2)};
                rectangle.move(+7,0);
                view1.setCenter(rectangle.getPosition());
                std::cout << rectangle.getPosition().x << " , " << rectangle.getPosition().y << std::endl;
            }
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
                mouse = {rectangle.getPosition().x+(rectangle.getSize().x/2), rectangle.getPosition().y+(rectangle.getSize().y/2)};
                rectangle.move(0,-7);
                view1.setCenter(rectangle.getPosition());
                std::cout << rectangle.getPosition().x << " , " << rectangle.getPosition().y << std::endl;
            }
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
                mouse = {rectangle.getPosition().x+(rectangle.getSize().x/2), rectangle.getPosition().y+(rectangle.getSize().y/2)};
                rectangle.move(0,+7);
                view1.setCenter(rectangle.getPosition());
                std::cout << rectangle.getPosition().x << " , " << rectangle.getPosition().y << std::endl;
            }
        }

        particles.setEmitter(mouse);
        //particles.setEmitter(window.mapPixelToCoords((sf::Vector2i)mouse));

        sf::Time elapsed = clock.restart();
        particles.update(elapsed);


        window.clear();
        window.setView(view1);

        for(int i = 0;i<nexus.getSize().x/blockDimensions.x; i++){
            for(int j = 0;j<nexus.getSize().y/blockDimensions.y;j++){
                sf::VertexArray vArray(sf::PrimitiveType::Quads, 4);
                vArray[0].position = sf::Vector2f(i*blockDimensions.x+nexus.getPosition().x, j*blockDimensions.y+nexus.getPosition().y);
                vArray[1].position = sf::Vector2f(i*blockDimensions.x+blockDimensions.x+nexus.getPosition().x, j*blockDimensions.y+nexus.getPosition().y);
                vArray[2].position = sf::Vector2f(i*blockDimensions.x+blockDimensions.x+nexus.getPosition().x, j*blockDimensions.y+blockDimensions.y+nexus.getPosition().y);
                vArray[3].position = sf::Vector2f(i*blockDimensions.x+nexus.getPosition().x, j*blockDimensions.y+blockDimensions.y+nexus.getPosition().y);

                for(int k=0;k<4;k++){
                    int red = rand() % 255;
                    int green = rand() % 255;
                    int blue = rand() % 255;

                    vArray[k].color = sf::Color(red, green, blue);
                }
                window.draw(vArray);
            }
        }


        //window.clear();

        window.setView(standard);
        window.draw(particles);
        window.draw(rectangle);

        //window.draw(rectangle2);
        //window.setView(view2);
        //window.draw(rectangle2);

        window.setView(minimap);
        window.draw(particles);
        window.draw(rectangle);

        window.display();
    }

    return 0;
}
Esempio n. 18
0
int main(int argc, char* argv[])
{
    // Build your scene and setup your camera here, by calling
    // functions from Raytracer.  The code here sets up an example
    // scene and renders it from two different view points, DO NOT
    // change this if you're just implementing part one of the
    // assignment.
    Raytracer raytracer;
    int width = 16 * 20 * 2;
    int height = 12 * 20 * 2;

    if (argc == 3) {
        width = atoi(argv[1]);
        height = atoi(argv[2]);
    }

    // Camera parameters.
    Point3D eye1(0, 0, 1), eye2(4, 2, 1);
    Vector3D view1(0, 0, -1), view2(-4, -2, -6);
//	Point3D eye1(0, 0, 1), eye2(4, 2, -6);
//	Vector3D view1(0, 0, -1), view2(-4, -2, 1);
    Vector3D up(0, 1, 0);
    double fov = 60;

    // Defines a material for shading.
    Material gold( Colour(0.3, 0.3, 0.3), Colour(0.75164, 0.60648, 0.22648),
                   Colour(0.628281, 0.555802, 0.366065),
                   51.2, LARGE_SPH_REFLECT, LARGE_SPH_REFRAC_INDX, LARGE_SPH_REFRACT);
    Material jade( Colour(0, 0, 0), Colour(0.54, 0.89, 0.63),
                   Colour(0.316228, 0.316228, 0.316228),
                   12.8);

    Material red( Colour(0, 0, 0), Colour(0.9, 0.05, 0.05),
                  Colour(0.4, 0.2, 0.2),
                  12.8);

    // Defines a point light source.
    Point3D light_pos;
    if (LIGHT_DEFAULT) {
        light_pos = Point3D(0, 0, 5);
    } else {
        light_pos = LIGHT_POS_TEST;
    }

    PointLight * light0 = new PointLight(
        light_pos,
        Colour(0.9, 0.9, 0.9),
        0.1);
    raytracer.addLightSource(light0);

    // Add a unit square into the scene with material mat.
    SceneDagNode* sphere = raytracer.addObject( new UnitSphere(), &gold );
    SceneDagNode* sphere2 = raytracer.addObject( new UnitSphere(), &gold );
    SceneDagNode* plane = raytracer.addObject( new UnitSquare(), &jade );

    //set the texture map for the objects of interest in the scene if texture map flag is ON
    if (TEXTURE_MAP_FLAG) {
        // load texture image
        TextureMap txtmp;
        txtmp = TextureMap(TEXTURE_IMG);
        raytracer.setTextureMap(txtmp);

        //for now, we are only using texture map for sphere
        sphere->useTextureMapping = true;
        sphere->obj->setTextureMap(txtmp);
    }


    // Apply some transformations to the unit square.
    double factor1[3] = { 1.0, 2.0, 1.0 };
    double factor2[3] = { 6.0, 6.0, 6.0 };
    raytracer.translate(sphere, Vector3D(0, 0, -5));
    raytracer.rotate(sphere, 'x', -45);
    raytracer.rotate(sphere, 'z', 45);
    raytracer.scale(sphere, Point3D(0, 0, 0), factor1);

    raytracer.translate(plane, Vector3D(0, 0, -7));
    raytracer.rotate(plane, 'z', 45);
    raytracer.scale(plane, Point3D(0, 0, 0), factor2);

    double f[3] = { 0.5, 0.5, 0.5 };
    raytracer.translate(sphere2, Vector3D(0, 0, -8));
    raytracer.scale(sphere2, Point3D(0, 0, 0), f);


    bool DO_SIGNATURE 				= false;
    bool DO_SIGNATURE_SS 			= false;
    bool DO_DIFFUSE 				= false;
    bool DO_PHONG 					= false;
    bool DO_PHONG_SS 				= false;
    bool DO_FULL_FEATURED 			= false;
    bool DO_WOODEN_MONKEY_SCENES 	= true;
    bool DO_REFRACTION_SCENE 		= false;

    bool RENDER_FIRST_VIEW = true;
    bool RENDER_SECOND_VIEW = true;


    raytracer.setReflDepth(0);
    raytracer.setEnvMapMode(Raytracer::NONE);

    // render signature
    if ( DO_SIGNATURE ) {
        raytracer.setAAMode(Raytracer::NONE);
        raytracer.setShadingMode(Raytracer::SCENE_MODE_SIGNATURE);

        if ( RENDER_FIRST_VIEW )
            raytracer.render(width, height, eye1, view1, up, fov, "sig1.bmp");
        if ( RENDER_SECOND_VIEW )
            raytracer.render(width, height, eye2, view2, up, fov, "sig2.bmp");
    }

    // render signature with SS AA
    if ( DO_SIGNATURE_SS ) {
        raytracer.setAAMode(Raytracer::AA_SUPER_SAMPLING);
        raytracer.setShadingMode(Raytracer::SCENE_MODE_SIGNATURE);

        if ( RENDER_FIRST_VIEW )
            raytracer.render(width, height, eye1, view1, up, fov, "sigSS1.bmp");
        if ( RENDER_SECOND_VIEW )
            raytracer.render(width, height, eye2, view2, up, fov, "sigSS2.bmp");
    }

    // render diffuse
    if ( DO_DIFFUSE ) {
        raytracer.setAAMode(Raytracer::NONE);
        raytracer.setShadingMode(Raytracer::SCENE_MODE_DIFFUSE);

        if ( RENDER_FIRST_VIEW )
            raytracer.render(width, height, eye1, view1, up, fov, "diffuse1.bmp");
        if ( RENDER_SECOND_VIEW )
            raytracer.render(width, height, eye2, view2, up, fov, "diffuse2.bmp");
    }

    // render phong
    if ( DO_PHONG ) {
        raytracer.setAAMode(Raytracer::NONE);
        raytracer.setShadingMode(Raytracer::SCENE_MODE_PHONG);

        if ( RENDER_FIRST_VIEW )
            raytracer.render(width, height, eye1, view1, up, fov, "phong1.bmp");
        if ( RENDER_SECOND_VIEW )
            raytracer.render(width, height, eye2, view2, up, fov, "phong2.bmp");
    }

    // phong with super sampling AA
    if ( DO_PHONG_SS ) {
        raytracer.setAAMode(Raytracer::AA_SUPER_SAMPLING);
        raytracer.setShadingMode(Raytracer::SCENE_MODE_PHONG);

        if ( RENDER_FIRST_VIEW )
            raytracer.render(width, height, eye1, view1, up, fov, "phongSS1.bmp");
        if ( RENDER_SECOND_VIEW )
            raytracer.render(width, height, eye2, view2, up, fov, "phongSS2.bmp");
    }

    // refraction if it's turned on
    if (REFRACTION_FLAG) {
        raytracer.setRefractionMode(REFRACTION_FLAG);
    }

    // all features enabled or turned to max
    if ( DO_FULL_FEATURED ) {
        raytracer.setAAMode(Raytracer::NONE);
        raytracer.setAAMode(Raytracer::AA_SUPER_SAMPLING);
        raytracer.setShadingMode(Raytracer::SCENE_MODE_PHONG);
        raytracer.setShadows(Raytracer::SHADOW_CAST);
//		raytracer.setShadows(Raytracer::NONE);
        raytracer.setEnvMapMode(Raytracer::ENV_MAP_CUBE_SKYBOX);
//		raytracer.setEnvMapMode(Raytracer::NONE);
        raytracer.setReflDepth(4);

        if ( raytracer.getEnvMapMode() != Raytracer::NONE ) {
            // load images

            EnvMap env;
            if ( _DEBUG ) {
                env = EnvMap(
                          "EnvMaps/DebugMaps/posx.bmp",
                          "EnvMaps/DebugMaps/posy.bmp",
                          "EnvMaps/DebugMaps/posz.bmp",
                          "EnvMaps/DebugMaps/negx.bmp",
                          "EnvMaps/DebugMaps/negy.bmp",
                          "EnvMaps/DebugMaps/negz.bmp"
                      );
            } else {
                env = EnvMap(
                          "EnvMaps/SaintLazarusChurch/posx.bmp",
                          "EnvMaps/SaintLazarusChurch/posy.bmp",
                          "EnvMaps/SaintLazarusChurch/posz.bmp",
                          "EnvMaps/SaintLazarusChurch/negx.bmp",
                          "EnvMaps/SaintLazarusChurch/negy.bmp",
                          "EnvMaps/SaintLazarusChurch/negz.bmp"
                      );
            }

            raytracer.setEnvMap(env);
        }

        // adjust lighting?
        if ( raytracer.getReflDepth() > 0 ) {
            double l0i = 0.5;
            light0->setAmbient(Colour(l0i, l0i, l0i));
        }

        if ( RENDER_FIRST_VIEW )
            raytracer.render(width, height, eye1, view1, up, fov, "all1.bmp");
        if ( RENDER_SECOND_VIEW )
            raytracer.render(width, height, eye2, view2, up, fov, "all2.bmp");
    }

    // different scenes just for the wooden monkey thing
    if ( DO_WOODEN_MONKEY_SCENES ) {
//		wmonkey_scene_1();
        wmonkey_scene_2();
        // TODO add more scenes here as required...
    }

    //render the 2nd refraction scene
    if ( REFRACTION_FLAG && DO_REFRACTION_SCENE ) {
        refraction_scene_1();
    }

    printf("Press enter to terminate...\n");
    std::string s;
    std::getline(std::cin, s);

    return 0;
}
Esempio n. 19
0
/**
 * Wooden Monkey Scene 1
 */
void wmonkey_scene_1()
{
    printf("WOODEN MONKEY SCENE : 1 ----------------------------------\n\n");
    Raytracer rt;
    int width = 16 * 20 * 2;
    int height = 12 * 20 * 2;

    // Camera parameters.
    Point3D eye1(0, 0, 1), eye2(4, 2, 1);
    Vector3D view1(0, 0, -1), view2(-4, -2, -6);
    Vector3D up(0, 1, 0);
    double fov = 60;

    // Defines a material for shading.
    Material gold( Colour(0.3, 0.3, 0.3), Colour(0.75164, 0.60648, 0.22648),
                   Colour(0.628281, 0.555802, 0.366065),
                   51.2, 0.8 );
    Material jade( Colour(0, 0, 0), Colour(0.54, 0.89, 0.63),
                   Colour(0.316228, 0.316228, 0.316228),
                   12.8);

    // Defines a point light source.
    double l0c = 0.5;
    PointLight * light0 = new PointLight(
        Point3D(-2, 2, 5),
        Colour(l0c, l0c, l0c),
        0.2);
    rt.addLightSource(light0);

    // Add a unit square into the scene with material mat.
    SceneDagNode* sphere = rt.addObject( new UnitSphere(), &gold );
    SceneDagNode* sphere2 = rt.addObject( new UnitSphere(), &gold );
    SceneDagNode* plane = rt.addObject( new UnitSquare(), &jade );

    // Apply some transformations to the unit square.
    double factor1[3] = { 1.0, 2.0, 1.0 };
    double factor2[3] = { 6.0, 6.0, 6.0 };
    rt.translate(sphere, Vector3D(0, 0, -5));
    rt.rotate(sphere, 'x', -45);
    rt.rotate(sphere, 'z', 45);
    rt.scale(sphere, Point3D(0, 0, 0), factor1);

    rt.translate(plane, Vector3D(0, 0, -7));
    rt.rotate(plane, 'z', 45);
    rt.scale(plane, Point3D(0, 0, 0), factor2);

    double f[3] = { 0.5, 0.5, 0.5 };
    rt.translate(sphere2, Vector3D(3, 0, -5));
    rt.scale(sphere2, Point3D(0, 0, 0), f);

    rt.setAAMode(Raytracer::AA_SUPER_SAMPLING);
    rt.setShadingMode(Raytracer::SCENE_MODE_PHONG);
    rt.setShadows(Raytracer::SHADOW_CAST);
    rt.setEnvMapMode(Raytracer::ENV_MAP_CUBE_SKYBOX);
    rt.setColorSpaceMode(Raytracer::COLOR_ENC_SRGB_GAMMA_CORRECT);
    rt.setReflDepth(4);

    if ( rt.getEnvMapMode() != Raytracer::NONE ) {
        // load images
        EnvMap env;
        if ( _DEBUG ) {
            env = EnvMap(
                      "EnvMaps/DebugMaps/posx.bmp",
                      "EnvMaps/DebugMaps/posy.bmp",
                      "EnvMaps/DebugMaps/posz.bmp",
                      "EnvMaps/DebugMaps/negx.bmp",
                      "EnvMaps/DebugMaps/negy.bmp",
                      "EnvMaps/DebugMaps/negz.bmp"
                  );
        } else {
            env = EnvMap(
                      "EnvMaps/SaintLazarusChurch/posx.bmp",
                      "EnvMaps/SaintLazarusChurch/posy.bmp",
                      "EnvMaps/SaintLazarusChurch/posz.bmp",
                      "EnvMaps/SaintLazarusChurch/negx.bmp",
                      "EnvMaps/SaintLazarusChurch/negy.bmp",
                      "EnvMaps/SaintLazarusChurch/negz.bmp"
                  );
        }

        rt.setEnvMap(env);
    }

    printf("WOODEN MONKEY SCENE : 1 :: Rendering...\n");
    rt.render(width, height, eye2, view2, up, fov, "wmonkey_1.bmp");
    printf("WOODEN MONKEY SCENE : 1 :: Done!\n");
}
Esempio n. 20
0
  int main(int argc, char* args[])
  {
    // Load the mesh.
    MeshSharedPtr mesh(new Mesh);
    MeshReaderH2D mloader;
    mloader.load("square.mesh", mesh);

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

    // Create an L2 space->
    SpaceSharedPtr<double> space(new L2Space<double>(mesh, P_INIT));

    // Initialize refinement selector.
    L2ProjBasedSelector<double> selector(CAND_LIST);

    // Display the mesh.
#ifdef SHOW_OUTPUT
    OrderView oview("Coarse mesh", new WinGeom(0, 0, 440, 350));
    oview.show(space);
#endif

    MeshFunctionSharedPtr<double> sln(new Solution<double>);
    MeshFunctionSharedPtr<double> ref_sln(new Solution<double>);

    // Initialize the weak formulation.
    CustomWeakForm wf("Bdy_bottom_left", mesh);

#ifdef SHOW_OUTPUT
    ScalarView view1("Solution", new WinGeom(900, 0, 450, 350));
    view1.fix_scale_width(60);
#endif

    // Initialize linear solver.
    Hermes::Hermes2D::LinearSolver<double> linear_solver(&wf, space);

    int as = 1; bool done = false;
    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<double>::ReferenceSpaceCreator ref_space_creator(space, ref_mesh);
      SpaceSharedPtr<double> ref_space = ref_space_creator.create_ref_space();

      ref_space->save("space-real.xml");
      ref_space->free();
      ref_space->load("space-real.xml");
#ifdef WITH_BSON
      ref_space->save_bson("space-real.bson");
      ref_space->free();
      ref_space->load_bson("space-real.bson");
#endif

      linear_solver.set_space(ref_space);

      // Solve the linear system. If successful, obtain the solution.
      linear_solver.solve();
      Solution<double>::vector_to_solution(linear_solver.get_sln_vector(), ref_space, ref_sln);
      
      // Project the fine mesh solution onto the coarse mesh.
      OGProjection<double> ogProjection;
      ogProjection.project_global(space, ref_sln, sln, HERMES_L2_NORM);

#ifdef SHOW_OUTPUT
      MeshFunctionSharedPtr<double> val_filter(new ValFilter(ref_sln, 0.0, 1.0));

      // View the coarse mesh solution.
      view1.show(val_filter);
      oview.show(space);
#endif

      // Calculate element errors and total error estimate.
      errorCalculator.calculate_errors(sln, ref_sln);
      double err_est_rel = errorCalculator.get_total_error_squared() * 100;

      adaptivity.set_space(space);
#ifdef SHOW_OUTPUT
      std::cout << "Error: " << err_est_rel << "%." << std::endl;
#endif
      // If err_est_rel too large, adapt the mesh->
      if(err_est_rel < ERR_STOP)
        done = true;
      else
        done = adaptivity.adapt(&selector);
      as++;
    }
    while (done == false);

    // Wait for keyboard or mouse input.
#ifdef SHOW_OUTPUT
    View::wait();
#endif
    return as;
  }
Esempio n. 21
0
int main(int argc, char* argv[])
{
    // Time measurement.
    TimePeriod cpu_time;
    cpu_time.tick();

    // Load the mesh.
    Mesh mesh;
    H2DReader mloader;
    mloader.load("square.mesh", &mesh);
    //mloader.load("square-tri.mesh", &mesh);

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

    // Create an L2 space with default shapeset.
    L2Space space(&mesh, bc_types, NULL, Ord2(P_H, P_V));
    int ndof = Space::get_num_dofs(&space);
    info("ndof = %d", ndof);

    // Initialize the weak formulation.
    WeakForm wf;
    wf.add_matrix_form(callback(bilinear_form));
    wf.add_vector_form(callback(linear_form));
    wf.add_matrix_form_surf(callback(bilinear_form_boundary), H2D_DG_BOUNDARY_EDGE);
    wf.add_vector_form_surf(callback(linear_form_boundary), H2D_DG_BOUNDARY_EDGE);
    wf.add_matrix_form_surf(callback(bilinear_form_interface), H2D_DG_INNER_EDGE);

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

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

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

    // Initialize the solution.
    Solution 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 solution.
    info("Solving the matrix problem.");
    if(solver->solve())
        Solution::vector_to_solution(solver->get_solution(), &space, &sln);
    else
        error ("Matrix solver failed.\n");

    // Time measurement.
    cpu_time.tick();

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

    // Visualize the solution.
    ScalarView view1("Solution", new WinGeom(860, 0, 400, 350));
    view1.show(&sln);

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

    return 0;
}
Esempio n. 22
0
int main(int argc, char* argv[])
{
  // Instantiate a class with global functions.
  Hermes2D hermes2d;
  
  // Load the mesh.
  Mesh mesh;
  H2DReader mloader;
  mloader.load("reactor.mesh", &mesh);

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

  // Solution variables.
  Solution sln1, sln2, sln3, sln4;
  Hermes::vector<Solution*> solutions(&sln1, &sln2, &sln3, &sln4);
  
  // Define initial conditions.
  info("Setting initial conditions.");
  Solution iter1, iter2, iter3, iter4;
  iter1.set_const(&mesh, 1.00);
  iter2.set_const(&mesh, 1.00);
  iter3.set_const(&mesh, 1.00);
  iter4.set_const(&mesh, 1.00);
  Hermes::vector<MeshFunction*> iterates(&iter1, &iter2, &iter3, &iter4);

  // Create H1 spaces with default shapesets.
  H1Space space1(&mesh, P_INIT_1);
  H1Space space2(&mesh, P_INIT_2);
  H1Space space3(&mesh, P_INIT_3);
  H1Space space4(&mesh, P_INIT_4);
  Hermes::vector<Space*> spaces(&space1, &space2, &space3, &space4);
  
  int ndof = Space::get_num_dofs(spaces);
  info("ndof = %d.", ndof);
  
  // Initialize views.
  ScalarView view1("Neutron flux 1", new WinGeom(0, 0, 320, 600));
  ScalarView view2("Neutron flux 2", new WinGeom(350, 0, 320, 600));
  ScalarView view3("Neutron flux 3", new WinGeom(700, 0, 320, 600));
  ScalarView view4("Neutron flux 4", new WinGeom(1050, 0, 320, 600));
  
  // Do not show meshes.
  view1.show_mesh(false); view1.set_3d_mode(true);
  view2.show_mesh(false); view2.set_3d_mode(true);
  view3.show_mesh(false); view3.set_3d_mode(true);
  view4.show_mesh(false); view4.set_3d_mode(true);
  
  // Load physical data of the problem for the 4 energy groups.
  MaterialPropertyMaps matprop(4);
  matprop.set_D(D);
  matprop.set_Sigma_r(Sr);
  matprop.set_Sigma_s(Ss);
  matprop.set_Sigma_s_nnz_structure(Ss_nnz);
  matprop.set_Sigma_a(Sa);
  matprop.set_Sigma_f(Sf);
  matprop.set_nu(nu);
  matprop.set_chi(chi);
  matprop.validate();
  
  std::cout << matprop;
  
  // Initialize the weak formulation.
  CustomWeakForm wf(matprop, iterates, k_eff, bdy_vacuum);

  // Initialize the FE problem.
  DiscreteProblem dp(&wf, spaces);
  
  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).
  }
   
  // Time measurement.
  TimePeriod cpu_time, solver_time;
  
  // Initial coefficient vector for the Newton's method.
  scalar* coeff_vec = new scalar[ndof];
  
  // Force the Jacobian assembling in the first iteration.
  bool Jacobian_changed = true;
  
  // In the following iterations, Jacobian will not be changing; its LU factorization
  // may be reused.
  solver->set_factorization_scheme(HERMES_REUSE_FACTORIZATION_COMPLETELY);
  
  // Main power iteration loop:
  int it = 1; bool done = false;
  do
  {
    info("------------ Power iteration %d:", it);
    
    info("Newton's method (matrix problem solved by %s).", MatrixSolverNames[matrix_solver].c_str());
    
    memset(coeff_vec, 0.0, ndof*sizeof(scalar)); //TODO: Why it doesn't work without zeroing coeff_vec in each iteration?
    
    solver_time.tick(HERMES_SKIP);      
    if (!hermes2d.solve_newton(coeff_vec, &dp, solver, matrix, rhs, Jacobian_changed, 1e-8, 10, true)) 
      error("Newton's iteration failed.");
    solver_time.tick();
    
    Solution::vector_to_solutions(solver->get_solution(), spaces, solutions);
    
    // Show intermediate solutions.
    view1.show(&sln1);    
    view2.show(&sln2);
    view3.show(&sln3);    
    view4.show(&sln4);
    
    // Compute eigenvalue.
    
    SourceFilter source(solutions, matprop);
    SourceFilter source_prev(iterates, matprop);
    
    double k_new = k_eff * (integrate(&source, core) / integrate(&source_prev, core));
    info("Largest eigenvalue: %.8g, rel. difference from previous it.: %g", k_new, fabs((k_eff - k_new) / k_new));
    
    // Stopping criterion.
    if (fabs((k_eff - k_new) / k_new) < ERROR_STOP) done = true;

    // Update eigenvalue.
    k_eff = k_new;
    wf.update_keff(k_eff);
    
    if (!done)
    {
      // Save solutions for the next iteration.
      iter1.copy(&sln1);    
      iter2.copy(&sln2);
      iter3.copy(&sln3);    
      iter4.copy(&sln4);
      
      // Don't need to reassemble the system matrix in further iterations,
      // only the rhs changes to reflect the progressively updated source.
      Jacobian_changed = false;

      it++;
    }
  }
  while (!done);
  
  delete [] coeff_vec;
  
  // Time measurement.
  cpu_time.tick();
  solver_time.tick(HERMES_SKIP);
  
  // Print timing information.
  verbose("Average solver time for one power iteration: %g s", solver_time.accumulated() / it);
  
  // Clean up.
  delete matrix;
  delete rhs;
  delete solver;

  // Show solutions.
  view1.show(&sln1);
  view2.show(&sln2);
  view3.show(&sln3);    
  view4.show(&sln4);
  
  // 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;
}
Esempio n. 23
0
void GameBase::SetZoom(){
	sf::View view1(sf::FloatRect(0.0f,0.0f,ancho/4.0f,alto/4.0f));
	view1.zoom(1.0f);
	wnd->setView(view1);
}
Esempio n. 24
0
int main(int argc, char* args[])
{
    // Load the mesh.
    MeshSharedPtr mesh(new Mesh);
    MeshReaderH2D mloader;
    mloader.load("square.mesh", mesh);

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

    mesh->refine_by_criterion(criterion, INIT_REF_CRITERION);

    ScalarView view1("Solution - Discontinuous Galerkin FEM", new WinGeom(900, 0, 450, 350));
    ScalarView view2("Solution - Standard continuous FEM", new WinGeom(900, 400, 450, 350));

    if(WANT_DG)
    {
        // Create an L2 space.
        SpaceSharedPtr<double> space_l2(new L2Space<double>(mesh, P_INIT));

        // Initialize the solution.
        MeshFunctionSharedPtr<double> sln_l2(new Solution<double>);

        // Initialize the weak formulation.
        CustomWeakForm wf_l2(BDY_BOTTOM_LEFT);

        // Initialize the FE problem.
        DiscreteProblem<double> dp_l2(&wf_l2, space_l2);
        dp_l2.set_linear();

        // Initialize linear solver.
        Hermes::Hermes2D::LinearSolver<double> linear_solver(&dp_l2);

        Hermes::Mixins::Loggable::Static::info("Assembling Discontinuous Galerkin (nelem: %d, ndof: %d).", mesh->get_num_active_elements(), space_l2->get_num_dofs());

        // Solve the linear system. If successful, obtain the solution.
        Hermes::Mixins::Loggable::Static::info("Solving Discontinuous Galerkin.");
        try
        {
            linear_solver.solve();
            if(DG_SHOCK_CAPTURING)
            {
                FluxLimiter flux_limiter(FluxLimiter::Kuzmin, linear_solver.get_sln_vector(), space_l2, true);

                flux_limiter.limit_second_orders_according_to_detector();

                flux_limiter.limit_according_to_detector();

                flux_limiter.get_limited_solution(sln_l2);

                view1.set_title("Solution - limited Discontinuous Galerkin FEM");
            }
            else
                Solution<double>::vector_to_solution(linear_solver.get_sln_vector(), space_l2, sln_l2);

            // View the solution.
            view1.show(sln_l2);
        }
        catch(std::exception& e)
        {
            std::cout << e.what();

        }
    }
    if(WANT_FEM)
    {
        // Create an H1 space.
        SpaceSharedPtr<double> space_h1(new H1Space<double>(mesh, P_INIT));

        // Initialize the solution.
        MeshFunctionSharedPtr<double> sln_h1(new Solution<double>);

        // Initialize the weak formulation.
        CustomWeakForm wf_h1(BDY_BOTTOM_LEFT, false);

        // Initialize the FE problem.
        DiscreteProblem<double> dp_h1(&wf_h1, space_h1);
        dp_h1.set_linear();

        Hermes::Mixins::Loggable::Static::info("Assembling Continuous FEM (nelem: %d, ndof: %d).", mesh->get_num_active_elements(), space_h1->get_num_dofs());

        // Initialize linear solver.
        Hermes::Hermes2D::LinearSolver<double> linear_solver(&dp_h1);

        // Solve the linear system. If successful, obtain the solution.
        Hermes::Mixins::Loggable::Static::info("Solving Continuous FEM.");
        try
        {
            linear_solver.solve();
            Solution<double>::vector_to_solution(linear_solver.get_sln_vector(), space_h1, sln_h1);

            // View the solution.
            view2.show(sln_h1);
        }
        catch(std::exception& e)
        {
            std::cout << e.what();
        }
    }

    // Wait for keyboard or mouse input.
    View::wait();
    return 0;
}