int main(int argc, char* argv[]) { // Load the mesh. Mesh mesh; H2DReader 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(BDY_DIRICHLET, INIT_BDY_REF_NUM); // Enter boundary markers. BCTypes bc_types; bc_types.add_bc_dirichlet(BDY_DIRICHLET); // Enter Dirichlet boundary values. BCValues bc_values; bc_values.add_function(BDY_DIRICHLET, essential_bc_values); // Create an H1 space with default shapeset. H1Space space(&mesh, &bc_types, &bc_values, P_INIT); int ndof = Space::get_num_dofs(&space); info("ndof = %d.", ndof); // Previous time level solution (initialized by the initial condition). Solution u_prev_time(&mesh, init_cond); // 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); // Project the initial condition on the FE space to obtain initial // coefficient vector for the Newton's method. info("Projecting initial condition to obtain initial vector for the Newton's method."); scalar* coeff_vec1 = new scalar[ndof]; OGProjection::project_global(&space, &u_prev_time, coeff_vec1, matrix_solver); // Initialize views. ScalarView sview("Solution", new WinGeom(0, 0, 500, 400)); OrderView oview("Mesh", new WinGeom(520, 0, 450, 400)); oview.show(&space); // Initialize the weak formulation and the FE problem. WeakForm wf, wf1, wf2; Solution sdirk_stage_sol; scalar* coeff_vec2; DiscreteProblem *dp, *dp1, *dp2; sdirk_stage_sol.set_exact(&mesh, init_cond); coeff_vec2 = new scalar[ndof]; for (int i = 0; i < ndof; i++) coeff_vec2[i] = coeff_vec1[i]; wf1.add_matrix_form(callback(jac_sdirk)); wf1.add_vector_form(callback(res_sdirk_stage_1), HERMES_ANY, Hermes::vector<MeshFunction*>(&u_prev_time)); wf2.add_matrix_form(callback(jac_sdirk)); wf2.add_vector_form(callback(res_sdirk_stage_2), HERMES_ANY, Hermes::vector<MeshFunction*>(&u_prev_time, &sdirk_stage_sol)); bool is_linear = false; dp1 = new DiscreteProblem(&wf1, &space, is_linear); dp2 = new DiscreteProblem(&wf2, &space, is_linear); // Time stepping loop: int ts = 1; do { // Perform Newton's iteration for sdirk_stage_sol. info("SDIRK-22 time step (t = %g, tau = %g)", TIME, TAU); info("---- Stage I:"); bool verbose = true; if (!solve_newton(coeff_vec1, dp1, solver, matrix, rhs, NEWTON_TOL, NEWTON_MAX_ITER, verbose)) error("Newton's iteration did not converge."); // Convert the vector coeff_vec1 into a Solution. Solution::vector_to_solution(coeff_vec1, &space, &sdirk_stage_sol); // Perform Newton's iteration for the final solution. info("---- Stage II:"); if (!solve_newton(coeff_vec2, dp2, solver, matrix, rhs, NEWTON_TOL, NEWTON_MAX_ITER, verbose)) error("Newton's iteration did not converge."); // Translate Y2 into a Solution. Solution::vector_to_solution(coeff_vec2, &space, &u_prev_time); // Update time. TIME = TIME + TAU; // Show the new time level solution. char title[100]; sprintf(title, "Solution, t = %g", TIME); sview.set_title(title); sview.show(&u_prev_time); ts++; } while (TIME < T_FINAL); // Clean up. delete [] coeff_vec1; delete dp1; delete dp2; delete [] coeff_vec2; delete matrix; delete solver; // Wait for all views to be closed. View::wait(); return 0; }
DLL_HEADER int Ng_GetNSeg_2D (Ng_Mesh * mesh) { Mesh * m = (Mesh*)mesh; return m->GetNSeg(); }
Mesh* FloorBuildingF::toMesh() { //ROOF6_LEFT_UL_X; Mesh* m = new Mesh(); m->addVertex(ul, ROOF6_LEFT_UL_X/divide, ROOF6_LEFT_UL_Y/divide); //0 m->addVertex(ur, ROOF6_RIGHT_UR_X/divide, ROOF6_RIGHT_UR_Y/divide); //1 m->addVertex(dr, ROOF6_RIGHT_DR_X/divide, ROOF6_RIGHT_DR_Y/divide); //2 m->addVertex(dl, ROOF6_LEFT_DL_X/divide, ROOF6_LEFT_DL_Y/divide); //3 Vector border_ul, border_ur, border_dr, border_dl, norm; norm = ur - ul; norm = Normalized(norm); border_ul = ul + norm*BORDER; //border_ul[2] += BORDER; border_dl = border_ul; border_dl[1] = dl[1]; border_ur = ur; //border_ur[2] -= BORDER; border_ur = ur - norm*BORDER; border_dr = border_ur; border_dr[1] = dr[1]; m->addVertex(border_ul, ROOF6_LEFT_UR_X/divide, ROOF6_LEFT_UR_Y/divide); //4 m->addVertex(border_ur, ROOF6_RIGHT_UL_X/divide, ROOF6_RIGHT_UL_Y/divide); //5 m->addVertex(border_dr, ROOF6_RIGHT_DL_X/divide, ROOF6_RIGHT_DL_Y/divide); //6 m->addVertex(border_dl, ROOF6_LEFT_DR_X/divide, ROOF6_LEFT_DR_Y/divide); //7 // m->addVertex(border_ul, ROOF6_MID_UL_X/divide, ROOF6_MID_UL_Y/divide); //8 // m->addVertex(border_ur, ROOF6_MID_UR_X/divide, ROOF6_MID_UR_Y/divide); //9 // m->addVertex(border_dr, ROOF6_MID_DR_X/divide, ROOF6_MID_DR_Y/divide); //10 // m->addVertex(border_dl, ROOF6_MID_DL_X/divide, ROOF6_MID_DL_Y/divide); //11 // m->addFace(0, 1, 3); // m->addFace(1, 2, 3); /* m->addVertex(ul, ROOF6_LEFT_UL_X/divide, ROOF6_LEFT_UL_Y/divide); //0 m->addVertex(ur, ROOF6_RIGHT_UR_X/divide, ROOF6_RIGHT_UR_Y/divide); //1 m->addVertex(dr, ROOF6_RIGHT_DR_X/divide, ROOF6_RIGHT_DR_Y/divide); //2 m->addVertex(dl, ROOF6_LEFT_DL_X/divide, ROOF6_LEFT_DL_Y/divide); //3 m->addVertex(border_ul, ROOF6_LEFT_UR_X/divide, ROOF6_LEFT_UR_Y/divide); //4 m->addVertex(border_ur, ROOF6_RIGHT_UL_X/divide, ROOF6_RIGHT_UL_Y/divide); //5 m->addVertex(border_dr, ROOF6_RIGHT_DL_X/divide, ROOF6_RIGHT_DL_Y/divide); //6 m->addVertex(border_dl, ROOF6_LEFT_DR_X/divide, ROOF6_LEFT_DR_Y/divide); //7 m->addVertex(border_ul, ROOF6_MID_UL_X/divide, ROOF6_MID_UL_Y/divide); //8 m->addVertex(border_ur, ROOF6_MID_UR_X/divide, ROOF6_MID_UR_Y/divide); //9 m->addVertex(border_dr, ROOF6_MID_DR_X/divide, ROOF6_MID_DR_Y/divide); //10 m->addVertex(border_dl, ROOF6_MID_DL_X/divide, ROOF6_MID_DL_Y/divide); //11 */ m->addFace(0, 4, 3);//, ROOF6_LEFT_UL_X/divide, ROOF6_LEFT_UL_Y/divide, ROOF6_LEFT_UR_X/divide, ROOF6_LEFT_UR_Y/divide, ROOF6_LEFT_DL_X/divide, ROOF6_LEFT_DL_Y/divide); m->addFace(3, 4, 7);//, ROOF6_LEFT_DL_X/divide, ROOF6_LEFT_DL_Y/divide, border_ul, ROOF6_LEFT_UR_X/divide, ROOF6_LEFT_UR_Y/divide, ROOF6_LEFT_DR_X/divide, ROOF6_LEFT_DR_Y/divide); m->addFace(5, 1, 6);//, ROOF6_RIGHT_UL_X/divide, ROOF6_RIGHT_UL_Y/divide, ur, ROOF6_RIGHT_UR_X/divide, ROOF6_RIGHT_UR_Y/divide, ROOF6_RIGHT_DL_X/divide, ROOF6_RIGHT_DL_Y/divide); m->addFace(6, 1, 2);//, ROOF6_RIGHT_DL_X/divide, ROOF6_RIGHT_DL_Y/divide, ROOF6_RIGHT_UR_X/divide, ROOF6_RIGHT_UR_Y/divide, ROOF6_RIGHT_DR_X/divide, ROOF6_RIGHT_DR_Y/divide); m->addFace(4, 5, 7);//, ROOF6_MID_UL_X/divide, ROOF6_MID_UL_Y/divide, ROOF6_MID_UR_X/divide, ROOF6_MID_UR_Y/divide, ROOF6_MID_DL_X/divide, ROOF6_MID_DL_Y/divide); m->addFace(7, 5, 6);//, ROOF6_MID_DL_X/divide, ROOF6_MID_DL_Y/divide, ROOF6_MID_UR_X/divide, ROOF6_MID_UR_Y/divide, ROOF6_MID_DR_X/divide, ROOF6_MID_DR_Y/divide); return m; //m->addVertex(0.0, height/2, 0.0); //m->addFace(0, 2+i, 2+i+1); }
int main(int argc, char* argv[]) { // Load the mesh. Mesh mesh; H2DReader mloader; mloader.load("domain.mesh", &mesh); mesh.refine_all_elements(); // Enter boundary markers. BCTypes bc_types; bc_types.add_bc_dirichlet(Hermes::vector<int>(BDY_BOTTOM, BDY_OUTER, BDY_LEFT, BDY_INNER)); // Enter Dirichlet boudnary values. BCValues bc_values; bc_values.add_function(Hermes::vector<int>(BDY_BOTTOM, BDY_OUTER, BDY_LEFT, BDY_INNER), essential_bc_values); // Create an H1 space with default shapeset. H1Space space(&mesh, &bc_types, &bc_values, P_INIT); 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)); // 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.7251) > 1e-3) success = 0; if (p_init == 2 && fabs(sum - 3.79195) > 1e-3) success = 0; if (p_init == 3 && fabs(sum - 3.80206) > 1e-3) success = 0; if (p_init == 4 && fabs(sum - 3.80156) > 1e-3) success = 0; if (p_init == 5 && fabs(sum - 3.80155) > 1e-3) success = 0; if (p_init == 6 && fabs(sum - 3.80154) > 1e-3) success = 0; if (p_init == 7 && fabs(sum - 3.80154) > 1e-3) success = 0; if (p_init == 8 && fabs(sum - 3.80153) > 1e-3) success = 0; if (p_init == 9 && fabs(sum - 3.80152) > 1e-3) success = 0; if (p_init == 10 && fabs(sum - 3.80152) > 1e-3) success = 0; } if (success == 1) { printf("Success!\n"); return ERR_SUCCESS; } else { printf("Failure!\n"); return ERR_FAILURE; } }
//static int iter=0; void cgd(Mesh & m) { int height=11*m.t.size()+6*m.v.size(); // int height=2*m.t.size()+3*m.v.size(); // int width = 3*(m.v.size()); int width = 3*(m.v.size()+m.t.size()); //nvar=m.v.size(); nvar=m.v.size()+m.t.size(); std::vector<Plane>plane; get_plane(m,plane); add_v4(m); std::vector<Mat3>mat; vmat(m,mat); m.adjlist(); CCS ccs; std::vector<double >b; //b for smoothness matrix is 0 //smooth_mat(m,mat,wS,ccs); vert_smooth_mat(m,wS,ccs,b); identity_mat(m, mat, wI, ccs , b); vertex_mat(m,wV0,ccs,b); planar_mat(m,plane,wPt,ccs); b.resize(height,0.0); SparseCCS* s = new SparseCCS(width, height, &ccs.vals[0], &ccs.rowInds[0], &ccs.colPtr[0]); SparseCCS* st = s->transposed(); SparseCCS* sst=s->multiply_LM(*st); SparseMatrixOutline *outline = new SparseMatrixOutline(width); //printAB(ccs,b,0); double * ATb= s->operator* (&b[0]); // int rowcnt=sst->rows_count(); int colcnt=sst->columns_count(); const real * vals=sst->values(); const int * row_indices=sst->row_indices(); const int * col_pointers=sst->column_pointers(); for(int ii=0; ii<colcnt; ii++) { for(int jj=col_pointers[ii]; jj<col_pointers[ii+1]; jj++) { outline->AddEntry(row_indices[jj],ii,vals[jj]); } } // delete s; delete st; delete sst; SparseMatrix A(outline); delete outline; CGSolver solver(&A); double * x=new double [width]; vertex2arr(m,x); double eps = 1E-9; int maxIter = 20; int verbose = 0; int ret = solver.SolveLinearSystemWithJacobiPreconditioner(x, ATb, eps, maxIter, verbose);// if(ret<0) { printf("optimization error\n"); } /* gradient descent double * g = new double[width]; double * Ag=new double[width]; for(int iter=0;iter<maxIter;iter++){ A.MultiplyVector(x, g); subtract(g, ATb,width); real_t alpha = solver.DotProduct(g,g); A.MultiplyVector(g,Ag); alpha /= solver.DotProduct(g,Ag); scale(g,alpha,width); subtract(x, g, width); } */ A.CheckLinearSystemSolution(x,ATb); printf("\n"); array2vertex(x,m); delete []x; delete []ATb; }
int main(int argc, char* argv[]) { // Load the mesh. Mesh mesh; H2DReader mloader; mloader.load("GAMM-channel.mesh", &mesh); // Perform initial mesh refinements. for (int i = 0; i < INIT_REF_NUM; i++) mesh.refine_all_elements(); // Boundary condition types; BCTypes bc_types; // Initialize boundary condition types and spaces with default shapesets. bc_types.add_bc_neumann(Hermes::vector<int>(BDY_SOLID_WALL, BDY_INLET_OUTLET)); L2Space space_rho(&mesh, &bc_types, P_INIT); L2Space space_rho_v_x(&mesh, &bc_types, P_INIT); L2Space space_rho_v_y(&mesh, &bc_types, P_INIT); L2Space space_e(&mesh, &bc_types, P_INIT); // Initialize solutions, set initial conditions. Solution prev_rho, prev_rho_v_x, prev_rho_v_y, prev_e; prev_rho.set_exact(&mesh, ic_density); prev_rho_v_x.set_exact(&mesh, ic_density_vel_x); prev_rho_v_y.set_exact(&mesh, ic_density_vel_y); prev_e.set_exact(&mesh, ic_energy); // Solutions for the time derivative estimate. Solution sln_temp_rho, sln_temp_rho_v_x, sln_temp_rho_v_y, sln_temp_e; // Initialize weak formulation. bool is_matrix_free = true; WeakForm wf(4, is_matrix_free); // Volumetric linear forms. wf.add_vector_form(0, callback(linear_form_0_time)); wf.add_vector_form(1, callback(linear_form_1_time)); wf.add_vector_form(2, callback(linear_form_2_time)); wf.add_vector_form(3, callback(linear_form_3_time)); // Volumetric linear forms. // Linear forms coming from the linearization by taking the Eulerian fluxes' Jacobian matrices // from the previous time step. // Unnecessary for FVM. if(P_INIT.order_h > 0 || P_INIT.order_v > 0) { // First flux. wf.add_vector_form(0, callback(linear_form_0_1), HERMES_ANY); wf.add_vector_form(1, callback(linear_form_1_0_first_flux), HERMES_ANY); wf.add_vector_form(1, callback(linear_form_1_1_first_flux), HERMES_ANY); wf.add_vector_form(1, callback(linear_form_1_2_first_flux), HERMES_ANY); wf.add_vector_form(1, callback(linear_form_1_3_first_flux), HERMES_ANY); wf.add_vector_form(2, callback(linear_form_2_0_first_flux), HERMES_ANY); wf.add_vector_form(2, callback(linear_form_2_1_first_flux), HERMES_ANY); wf.add_vector_form(2, callback(linear_form_2_2_first_flux), HERMES_ANY); wf.add_vector_form(2, callback(linear_form_2_3_first_flux), HERMES_ANY); wf.add_vector_form(3, callback(linear_form_3_0_first_flux), HERMES_ANY); wf.add_vector_form(3, callback(linear_form_3_1_first_flux), HERMES_ANY); wf.add_vector_form(3, callback(linear_form_3_2_first_flux), HERMES_ANY); wf.add_vector_form(3, callback(linear_form_3_3_first_flux), HERMES_ANY); // Second flux. wf.add_vector_form(0, callback(linear_form_0_2), HERMES_ANY); wf.add_vector_form(1, callback(linear_form_1_0_second_flux), HERMES_ANY); wf.add_vector_form(1, callback(linear_form_1_1_second_flux), HERMES_ANY); wf.add_vector_form(1, callback(linear_form_1_2_second_flux), HERMES_ANY); wf.add_vector_form(1, callback(linear_form_1_3_second_flux), HERMES_ANY); wf.add_vector_form(2, callback(linear_form_2_0_second_flux), HERMES_ANY); wf.add_vector_form(2, callback(linear_form_2_1_second_flux), HERMES_ANY); wf.add_vector_form(2, callback(linear_form_2_2_second_flux), HERMES_ANY); wf.add_vector_form(2, callback(linear_form_2_3_second_flux), HERMES_ANY); wf.add_vector_form(3, callback(linear_form_3_0_second_flux), HERMES_ANY); wf.add_vector_form(3, callback(linear_form_3_1_second_flux), HERMES_ANY); wf.add_vector_form(3, callback(linear_form_3_2_second_flux), HERMES_ANY); wf.add_vector_form(3, callback(linear_form_3_3_second_flux), HERMES_ANY); } // Volumetric linear forms coming from the time discretization. wf.add_vector_form(0, linear_form_time, linear_form_order, HERMES_ANY, &prev_rho); wf.add_vector_form(1, linear_form_time, linear_form_order, HERMES_ANY, &prev_rho_v_x); wf.add_vector_form(2, linear_form_time, linear_form_order, HERMES_ANY, &prev_rho_v_y); wf.add_vector_form(3, linear_form_time, linear_form_order, HERMES_ANY, &prev_e); // Surface linear forms - inner edges coming from the DG formulation. wf.add_vector_form_surf(0, linear_form_interface_0, linear_form_order, H2D_DG_INNER_EDGE); wf.add_vector_form_surf(1, linear_form_interface_1, linear_form_order, H2D_DG_INNER_EDGE); wf.add_vector_form_surf(2, linear_form_interface_2, linear_form_order, H2D_DG_INNER_EDGE); wf.add_vector_form_surf(3, linear_form_interface_3, linear_form_order, H2D_DG_INNER_EDGE); // Surface linear forms - inlet / outlet edges. wf.add_vector_form_surf(0, bdy_flux_inlet_outlet_comp_0, linear_form_order, BDY_INLET_OUTLET); wf.add_vector_form_surf(1, bdy_flux_inlet_outlet_comp_1, linear_form_order, BDY_INLET_OUTLET); wf.add_vector_form_surf(2, bdy_flux_inlet_outlet_comp_2, linear_form_order, BDY_INLET_OUTLET); wf.add_vector_form_surf(3, bdy_flux_inlet_outlet_comp_3, linear_form_order, BDY_INLET_OUTLET); // Surface linear forms - Solid wall edges. wf.add_vector_form_surf(0, bdy_flux_solid_wall_comp_0, linear_form_order, BDY_SOLID_WALL); wf.add_vector_form_surf(1, bdy_flux_solid_wall_comp_1, linear_form_order, BDY_SOLID_WALL); wf.add_vector_form_surf(2, bdy_flux_solid_wall_comp_2, linear_form_order, BDY_SOLID_WALL); wf.add_vector_form_surf(3, bdy_flux_solid_wall_comp_3, linear_form_order, BDY_SOLID_WALL); if(PRECONDITIONING) { // Preconditioning forms. wf.add_matrix_form(0, 0, callback(bilinear_form_precon)); wf.add_matrix_form(1, 1, callback(bilinear_form_precon)); wf.add_matrix_form(2, 2, callback(bilinear_form_precon)); wf.add_matrix_form(3, 3, callback(bilinear_form_precon)); } // Initialize the FE problem. bool is_linear = false; DiscreteProblem dp(&wf, Hermes::vector<Space*>(&space_rho, &space_rho_v_x, &space_rho_v_y, &space_e), is_linear); // If the FE problem is in fact a FV problem. if(P_INIT.order_h == 0 && P_INIT.order_v == 0) dp.set_fvm(); // Project the initial solution on the FE space // in order to obtain initial vector for NOX. info("Projecting initial solution on the FE mesh."); scalar* coeff_vec = new scalar[Space::get_num_dofs(Hermes::vector<Space*>(&space_rho, &space_rho_v_x, &space_rho_v_y, &space_e))]; OGProjection::project_global(Hermes::vector<Space*>(&space_rho, &space_rho_v_x, &space_rho_v_y, &space_e), Hermes::vector<MeshFunction*>(&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e), coeff_vec); // Filters for visualization of pressure and the two components of velocity. SimpleFilter pressure(calc_pressure_func, Hermes::vector<MeshFunction*>(&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e)); SimpleFilter u(calc_u_func, Hermes::vector<MeshFunction*>(&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e)); SimpleFilter w(calc_w_func, Hermes::vector<MeshFunction*>(&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e)); SimpleFilter Mach_number(calc_Mach_func, Hermes::vector<MeshFunction*>(&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e)); SimpleFilter entropy_estimate(calc_entropy_estimate_func, Hermes::vector<MeshFunction*>(&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e)); ScalarView pressure_view("Pressure", new WinGeom(0, 0, 600, 300)); ScalarView Mach_number_view("Mach number", new WinGeom(700, 0, 600, 300)); ScalarView entropy_production_view("Entropy estimate", new WinGeom(0, 400, 600, 300)); VectorView vview("Velocity", new WinGeom(700, 400, 600, 300)); // Iteration number. int iteration = 0; // Output of the approximate time derivative. std::ofstream time_der_out("time_der"); // Initialize NOX solver. NoxSolver solver(&dp); solver.set_ls_tolerance(1E-2); // Select preconditioner. RCP<Precond> pc = rcp(new MlPrecond("sa")); solver.set_precond(pc); for(t = 0.0; t < 3.0; t += TAU) { info("---- Time step %d, time %3.5f.", iteration++, t); OGProjection::project_global(Hermes::vector<Space*>(&space_rho, &space_rho_v_x, &space_rho_v_y, &space_e), Hermes::vector<MeshFunction*>(&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e), coeff_vec); info("Assembling by DiscreteProblem, solving by NOX."); solver.set_init_sln(coeff_vec); if (solver.solve()) Solution::vector_to_solutions(solver.get_solution(), Hermes::vector<Space*>(&space_rho, &space_rho_v_x, &space_rho_v_y, &space_e), Hermes::vector<Solution *>(&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e)); else error("NOX failed."); /* // Visualization. pressure.reinit(); u.reinit(); w.reinit(); Mach_number.reinit(); entropy_estimate.reinit(); pressure_view.show(&pressure); entropy_production_view.show(&entropy_estimate); Mach_number_view.show(&Mach_number); vview.show(&u, &w); */ info("Number of nonlin iterations: %d (norm of residual: %g)", solver.get_num_iters(), solver.get_residual()); info("Total number of iterations in linsolver: %d (achieved tolerance in the last step: %g)", solver.get_num_lin_iters(), solver.get_achieved_tol()); } pressure_view.close(); entropy_production_view.close(); Mach_number_view.close(); vview.close(); time_der_out.close(); return 0; }
bool FileSystem::parseObj(const char *path, Model &m) { std::string line; std::ifstream fileStream(path); unsigned int ind = 0; //amout of indices Mesh mesh; std::vector<glm::vec3> v, n; std::vector<glm::vec2> t; if (fileStream.is_open()) { while (fileStream.good()) { getline(fileStream, line); std::vector<std::string> tokens = split(line, ' '); if (line.substr(0, 2) == "v ") { float x = (float)atof(tokens[1].c_str()); float y = (float)atof(tokens[2].c_str()); float z = (float)atof(tokens[3].c_str()); v.push_back(glm::vec3(x, y, z)); } else if (line.substr(0, 2) == "vt") { float x = (float)atof(tokens[1].c_str()); float y = (float)atof(tokens[2].c_str()); t.push_back(glm::vec2(x, y)); } else if (line.substr(0, 2) == "vn") { float x = (float)atof(tokens[1].c_str()); float y = (float)atof(tokens[2].c_str()); float z = (float)atof(tokens[3].c_str()); n.push_back(glm::vec3(x, y, z)); } else if (line.substr(0, 2) == "f ") { glm::vec3 vertex, normal; glm::vec2 texCoord; std::vector<std::string> v1 = split(tokens[1], '/'); int i = atoi(v1[0].c_str()) - 1; vertex.x = v[i].x; vertex.y = v[i].y; vertex.z = v[i].z; i = atoi(v1[1].c_str()) - 1; texCoord.x = t[i].x; texCoord.y = t[i].y; i = atoi(v1[2].c_str()) - 1; normal.x = n[i].x; normal.y = n[i].y; normal.z = n[i].z; mesh.addVertex(vertex, normal, texCoord); std::vector<std::string> v2 = split(tokens[2], '/'); i = atoi(v2[0].c_str()) - 1; vertex.x = v[i].x; vertex.y = v[i].y; vertex.z = v[i].z; i = atoi(v2[1].c_str()) - 1; texCoord.x = t[i].x; texCoord.y = t[i].y; i = atoi(v2[2].c_str()) - 1; normal.x = n[i].x; normal.y = n[i].y; normal.z = n[i].z; mesh.addVertex(vertex, normal, texCoord); std::vector<std::string> v3 = split(tokens[3], '/'); i = atoi(v3[0].c_str()) - 1; vertex.x = v[i].x; vertex.y = v[i].y; vertex.z = v[i].z; i = atoi(v3[1].c_str()) - 1; texCoord.x = t[i].x; texCoord.y = t[i].y; i = atoi(v3[2].c_str()) - 1; normal.x = n[i].x; normal.y = n[i].y; normal.z = n[i].z; mesh.addVertex(vertex, normal, texCoord); } } std::shared_ptr<Material> mat(new Material); Texture tex; if (!loadTexture("resource/white_D.png", tex)) return false; mat->setDifTex(tex); mesh.addMaterial(mat); m.addMesh(std::make_shared<Mesh>(mesh)); fileStream.close(); return true; } std::cout << "Unable to open file " << path << std::endl; return false; }
int main(int argc, char* argv[]) { // Time measurement. TimePeriod cpu_time; cpu_time.tick(); // 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 boundary conditions. BCTypes bc_types; bc_types.add_bc_dirichlet(BDY_LEFT); bc_types.add_bc_neumann(BDY_NEUMANN); bc_types.add_bc_newton(BDY_COOLED); // Enter Dirichlet boundary values. BCValues bc_values_t; bc_values_t.add_const(BDY_LEFT, 1.0); BCValues bc_values_c; bc_values_c.add_zero(BDY_LEFT); // Create H1 spaces with default shapesets. H1Space* t_space = new H1Space(&mesh, &bc_types, &bc_values_t, P_INIT); H1Space* c_space = new H1Space(&mesh, &bc_types, &bc_values_c, P_INIT); int ndof = Space::get_num_dofs(Hermes::vector<Space *>(t_space, c_space)); info("ndof = %d.", ndof); // Define initial conditions. Solution t_prev_time_1, c_prev_time_1, t_prev_time_2, c_prev_time_2, t_iter, c_iter, t_prev_newton, c_prev_newton; t_prev_time_1.set_exact(&mesh, temp_ic); c_prev_time_1.set_exact(&mesh, conc_ic); t_prev_time_2.set_exact(&mesh, temp_ic); c_prev_time_2.set_exact(&mesh, conc_ic); t_iter.set_exact(&mesh, temp_ic); c_iter.set_exact(&mesh, conc_ic); // Filters for the reaction rate omega and its derivatives. DXDYFilter omega(omega_fn, Hermes::vector<MeshFunction*>(&t_prev_time_1, &c_prev_time_1)); DXDYFilter omega_dt(omega_dt_fn, Hermes::vector<MeshFunction*>(&t_prev_time_1, &c_prev_time_1)); DXDYFilter omega_dc(omega_dc_fn, Hermes::vector<MeshFunction*>(&t_prev_time_1, &c_prev_time_1)); // Initialize weak formulation. WeakForm wf(2, JFNK ? true : false); if (!JFNK || (JFNK && PRECOND == 1)) { wf.add_matrix_form(0, 0, callback(newton_bilinear_form_0_0), HERMES_NONSYM, HERMES_ANY, &omega_dt); wf.add_matrix_form_surf(0, 0, callback(newton_bilinear_form_0_0_surf), 3); wf.add_matrix_form(1, 1, callback(newton_bilinear_form_1_1), HERMES_NONSYM, HERMES_ANY, &omega_dc); wf.add_matrix_form(0, 1, callback(newton_bilinear_form_0_1), HERMES_NONSYM, HERMES_ANY, &omega_dc); wf.add_matrix_form(1, 0, callback(newton_bilinear_form_1_0), HERMES_NONSYM, HERMES_ANY, &omega_dt); } else if (PRECOND == 2) { wf.add_matrix_form(0, 0, callback(precond_0_0)); wf.add_matrix_form(1, 1, callback(precond_1_1)); } wf.add_vector_form(0, callback(newton_linear_form_0), HERMES_ANY, Hermes::vector<MeshFunction*>(&t_prev_time_1, &t_prev_time_2, &omega)); wf.add_vector_form_surf(0, callback(newton_linear_form_0_surf), 3); wf.add_vector_form(1, callback(newton_linear_form_1), HERMES_ANY, Hermes::vector<MeshFunction*>(&c_prev_time_1, &c_prev_time_2, &omega)); // Project the functions "t_iter" and "c_iter" on the FE space // in order to obtain initial vector for NOX. info("Projecting initial solutions on the FE meshes."); scalar* coeff_vec = new scalar[ndof]; OGProjection::project_global(Hermes::vector<Space *>(t_space, c_space), Hermes::vector<MeshFunction*>(&t_prev_time_1, &c_prev_time_1), coeff_vec); // Measure the projection time. double proj_time = cpu_time.tick().last(); // Initialize finite element problem. DiscreteProblem dp(&wf, Hermes::vector<Space*>(t_space, c_space)); // Initialize NOX solver and preconditioner. NoxSolver solver(&dp); RCP<Precond> pc = rcp(new MlPrecond("sa")); if (PRECOND) { if (JFNK) solver.set_precond(pc); else solver.set_precond("Ifpack"); } if (TRILINOS_OUTPUT) solver.set_output_flags(NOX::Utils::Error | NOX::Utils::OuterIteration | NOX::Utils::OuterIterationStatusTest | NOX::Utils::LinearSolverDetails); // Time stepping loop: double total_time = 0.0; cpu_time.tick_reset(); for (int ts = 1; total_time <= T_FINAL; ts++) { info("---- Time step %d, t = %g s", ts, total_time + TAU); cpu_time.tick(HERMES_SKIP); solver.set_init_sln(coeff_vec); if (solver.solve()) { Solution::vector_to_solutions(solver.get_solution(), Hermes::vector<Space *>(t_space, c_space), Hermes::vector<Solution *>(&t_prev_newton, &c_prev_newton)); cpu_time.tick(); info("Number of nonlin iterations: %d (norm of residual: %g)", solver.get_num_iters(), solver.get_residual()); info("Total number of iterations in linsolver: %d (achieved tolerance in the last step: %g)", solver.get_num_lin_iters(), solver.get_achieved_tol()); // Time measurement. cpu_time.tick(HERMES_SKIP); // Update global time. total_time += TAU; // Saving solutions for the next time step. t_prev_time_2.copy(&t_prev_time_1); c_prev_time_2.copy(&c_prev_time_1); t_prev_time_1 = t_prev_newton; c_prev_time_1 = c_prev_newton; } else error("NOX failed."); info("Total running time for time level %d: %g s.", ts, cpu_time.tick().last()); } info("T Coordinate ( 0, 8) value = %lf", t_prev_time_1.get_pt_value(0.0, 8.0)); info("T Coordinate ( 8, 8) value = %lf", t_prev_time_1.get_pt_value(8.0, 8.0)); info("T Coordinate ( 15, 8) value = %lf", t_prev_time_1.get_pt_value(15.0, 8.0)); info("T Coordinate ( 24, 8) value = %lf", t_prev_time_1.get_pt_value(24.0, 8.0)); info("T Coordinate ( 30, 8) value = %lf", t_prev_time_1.get_pt_value(30.0, 8.0)); info("T Coordinate ( 40, 8) value = %lf", t_prev_time_1.get_pt_value(40.0, 8.0)); info("T Coordinate ( 50, 8) value = %lf", t_prev_time_1.get_pt_value(50.0, 8.0)); info("T Coordinate ( 60, 8) value = %lf", t_prev_time_1.get_pt_value(60.0, 8.0)); info("C Coordinate ( 0, 8) value = %lf", c_prev_time_1.get_pt_value(0.0, 8.0)); info("C Coordinate ( 8, 8) value = %lf", c_prev_time_1.get_pt_value(8.0, 8.0)); info("C Coordinate ( 15, 8) value = %lf", c_prev_time_1.get_pt_value(15.0, 8.0)); info("C Coordinate ( 24, 8) value = %lf", c_prev_time_1.get_pt_value(24.0, 8.0)); info("C Coordinate ( 30, 8) value = %lf", c_prev_time_1.get_pt_value(30.0, 8.0)); info("C Coordinate ( 40, 8) value = %lf", c_prev_time_1.get_pt_value(40.0, 8.0)); info("C Coordinate ( 50, 8) value = %lf", c_prev_time_1.get_pt_value(50.0, 8.0)); info("C Coordinate ( 60, 8) value = %lf", c_prev_time_1.get_pt_value(60.0, 8.0)); double coor_x[8] = {0.0, 8.0, 15.0, 24.0, 30.0, 40.0, 50.0, 60.0}; double coor_y = 8.0; double t_value[8] = {1.000000, 1.000078, 0.002819, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000}; double c_value[8] = {0.000000, -0.000078, 0.997181, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000}; bool success = true; for (int i = 0; i < 8; i++) { if ((abs(t_value[i] - t_prev_time_1.get_pt_value(coor_x[i], coor_y)) > 1E-4) || (abs(c_value[i] - c_prev_time_1.get_pt_value(coor_x[i], coor_y)) > 1E-4)) success = false; } if (success) { printf("Success!\n"); return ERR_SUCCESS; } else { printf("Failure!\n"); return ERR_FAILURE; } }
bool Adapt::adapt(Tuple<RefinementSelectors::Selector *> refinement_selectors, double thr, int strat, int regularize, double to_be_processed) { error_if(!have_errors, "element errors have to be calculated first, call calc_elem_errors()."); error_if(refinement_selectors == Tuple<RefinementSelectors::Selector *>(), "selector not provided"); if (spaces.size() != refinement_selectors.size()) error("Wrong number of refinement selectors."); TimePeriod cpu_time; //get meshes int max_id = -1; Mesh* meshes[H2D_MAX_COMPONENTS]; for (int j = 0; j < this->neq; j++) { meshes[j] = this->spaces[j]->get_mesh(); rsln[j]->set_quad_2d(&g_quad_2d_std); rsln[j]->enable_transform(false); if (meshes[j]->get_max_element_id() > max_id) max_id = meshes[j]->get_max_element_id(); } //reset element refinement info AUTOLA2_OR(int, idx, max_id + 1, this->neq + 1); for(int j = 0; j < max_id; j++) for(int l = 0; l < this->neq; l++) idx[j][l] = -1; // element not refined double err0_squared = 1000.0; double processed_error_squared = 0.0; vector<ElementToRefine> elem_inx_to_proc; //list of indices of elements that are going to be processed elem_inx_to_proc.reserve(num_act_elems); //adaptivity loop double error_squared_threshod = -1; //an error threshold that breaks the adaptivity loop in a case of strategy 1 int num_exam_elem = 0; //a number of examined elements int num_ignored_elem = 0; //a number of ignored elements int num_not_changed = 0; //a number of element that were not changed int num_priority_elem = 0; //a number of elements that were processed using priority queue bool first_regular_element = true; //true if first regular element was not processed yet int inx_regular_element = 0; while (inx_regular_element < num_act_elems || !priority_queue.empty()) { int id, comp, inx_element; //get element identification if (priority_queue.empty()) { id = regular_queue[inx_regular_element].id; comp = regular_queue[inx_regular_element].comp; inx_element = inx_regular_element; inx_regular_element++; } else { id = priority_queue.front().id; comp = priority_queue.front().comp; inx_element = -1; priority_queue.pop(); num_priority_elem++; } num_exam_elem++; //get info linked with the element double err_squared = errors_squared[comp][id]; Mesh* mesh = meshes[comp]; Element* e = mesh->get_element(id); if (!should_ignore_element(inx_element, mesh, e)) { //check if adaptivity loop should end if (inx_element >= 0) { //prepare error threshold for strategy 1 if (first_regular_element) { error_squared_threshod = thr * err_squared; first_regular_element = false; } // first refinement strategy: // refine elements until prescribed amount of error is processed // if more elements have similar error refine all to keep the mesh symmetric if ((strat == 0) && (processed_error_squared > sqrt(thr) * errors_squared_sum) && fabs((err_squared - err0_squared)/err0_squared) > 1e-3) break; // second refinement strategy: // refine all elements whose error is bigger than some portion of maximal error if ((strat == 1) && (err_squared < error_squared_threshod)) break; if ((strat == 2) && (err_squared < thr)) break; if ((strat == 3) && ( (err_squared < error_squared_threshod) || ( processed_error_squared > 1.5 * to_be_processed )) ) break; } // get refinement suggestion ElementToRefine elem_ref(id, comp); int current = this->spaces[comp]->get_element_order(id); bool refined = refinement_selectors[comp]->select_refinement(e, current, rsln[comp], elem_ref); //add to a list of elements that are going to be refined if (can_refine_element(mesh, e, refined, elem_ref) ) { idx[id][comp] = (int)elem_inx_to_proc.size(); elem_inx_to_proc.push_back(elem_ref); err0_squared = err_squared; processed_error_squared += err_squared; } else { debug_log("Element (id:%d, comp:%d) not changed", e->id, comp); num_not_changed++; } } else { num_ignored_elem++; } } verbose("Examined elements: %d", num_exam_elem); verbose(" Elements taken from priority queue: %d", num_priority_elem); verbose(" Ignored elements: %d", num_ignored_elem); verbose(" Not changed elements: %d", num_not_changed); verbose(" Elements to process: %d", elem_inx_to_proc.size()); bool done = false; if (num_exam_elem == 0) done = true; else if (elem_inx_to_proc.empty()) { warn("None of the elements selected for refinement could be refined. Adaptivity step not successful, returning 'true'."); done = true; } //fix refinement if multimesh is used fix_shared_mesh_refinements(meshes, elem_inx_to_proc, idx, refinement_selectors); //apply refinements apply_refinements(elem_inx_to_proc); // in singlemesh case, impose same orders across meshes homogenize_shared_mesh_orders(meshes); // mesh regularization if (regularize >= 0) { if (regularize == 0) { regularize = 1; warn("Total mesh regularization is not supported in adaptivity. 1-irregular mesh is used instead."); } for (int i = 0; i < this->neq; i++) { int* parents; parents = meshes[i]->regularize(regularize); this->spaces[i]->distribute_orders(meshes[i], parents); delete [] parents; } } for (int j = 0; j < this->neq; j++) rsln[j]->enable_transform(true); verbose("Refined elements: %d", elem_inx_to_proc.size()); report_time("Refined elements in: %g s", cpu_time.tick().last()); //store for the user to retrieve last_refinements.swap(elem_inx_to_proc); have_errors = false; if (strat == 2 && done == true) have_errors = true; // space without changes // since space changed, assign dofs: assign_dofs(this->spaces); return done; }
void SubDomain::apply_markers(std::map<std::size_t, std::size_t>& sub_domains, std::size_t dim, T sub_domain, const Mesh& mesh, bool check_midpoint) const { // FIXME: This function can probably be folded into the above // function operator[] in std::map and MeshFunction. log(TRACE, "Computing sub domain markers for sub domain %d.", sub_domain); // Compute facet - cell connectivity if necessary const std::size_t D = mesh.topology().dim(); if (dim == D - 1) { mesh.init(D - 1); mesh.init(D - 1, D); } // Set geometric dimension (needed for SWIG interface) _geometric_dimension = mesh.geometry().dim(); // Speed up the computation by only checking each vertex once (or // twice if it is on the boundary for some but not all facets). RangedIndexSet boundary_visited(mesh.num_vertices()); RangedIndexSet interior_visited(mesh.num_vertices()); std::vector<bool> boundary_inside(mesh.num_vertices()); std::vector<bool> interior_inside(mesh.num_vertices()); // Always false when not marking facets bool on_boundary = false; // Compute sub domain markers Progress p("Computing sub domain markers", mesh.num_entities(dim)); for (MeshEntityIterator entity(mesh, dim); !entity.end(); ++entity) { // Check if entity is on the boundary if entity is a facet if (dim == D - 1) on_boundary = (entity->num_global_entities(D) == 1); // Select the visited-cache to use for this facet (or entity) RangedIndexSet& is_visited = (on_boundary ? boundary_visited : interior_visited); std::vector<bool>& is_inside = (on_boundary ? boundary_inside : interior_inside); // Start by assuming all points are inside bool all_points_inside = true; // Check all incident vertices if dimension is > 0 (not a vertex) if (entity->dim() > 0) { for (VertexIterator vertex(*entity); !vertex.end(); ++vertex) { if (is_visited.insert(vertex->index())) { Array<double> x(_geometric_dimension, const_cast<double*>(vertex->x())); is_inside[vertex->index()] = inside(x, on_boundary); } if (!is_inside[vertex->index()]) { all_points_inside = false; break; } } } // Check midpoint (works also in the case when we have a single vertex) if (all_points_inside && check_midpoint) { Array<double> x(_geometric_dimension, const_cast<double*>(entity->midpoint().coordinates())); if (!inside(x, on_boundary)) all_points_inside = false; } // Mark entity with all vertices inside if (all_points_inside) sub_domains[entity->index()] = sub_domain; p++; } }
//----------------------------------------------------------------------------- void SubDomain::mark_facets(Mesh& mesh, std::size_t sub_domain, bool check_midpoint) const { mark(mesh, mesh.topology().dim() - 1, sub_domain, check_midpoint); }
// Main function. int main(int argc, char* argv[]) { // Check number of command-line parameters. if (argc < 2) error("Not enough parameters: Provide a Butcher's table type."); int b_type = atoi(argv[1]); info ("%d", b_type); switch (b_type) { case 1: butcher_table_type = Explicit_RK_1; break; case 2: butcher_table_type = Implicit_RK_1; break; case 3: butcher_table_type = Explicit_RK_2; break; case 4: butcher_table_type = Implicit_Crank_Nicolson_2_2; break; case 5: butcher_table_type = Implicit_SDIRK_2_2; break; case 6: butcher_table_type = Implicit_Lobatto_IIIA_2_2; break; case 7: butcher_table_type = Implicit_Lobatto_IIIB_2_2; break; case 8: butcher_table_type = Implicit_Lobatto_IIIC_2_2; break; case 9: butcher_table_type = Explicit_RK_3; break; case 10: butcher_table_type = Explicit_RK_4; break; case 11: butcher_table_type = Implicit_Lobatto_IIIA_3_4; break; case 12: butcher_table_type = Implicit_Lobatto_IIIB_3_4; break; case 13: butcher_table_type = Implicit_Lobatto_IIIC_3_4; break; case 14: butcher_table_type = Implicit_Radau_IIA_3_5; break; default: error("Admissible command-line options are from 1 to 14."); } // Choose a Butcher's table or define your own. ButcherTable bt(butcher_table_type); // Load the mesh. Mesh mesh; H2DReader 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(BDY_DIRICHLET, INIT_BDY_REF_NUM); // Enter boundary markers. BCTypes bc_types; bc_types.add_bc_dirichlet(BDY_DIRICHLET); // Enter Dirichlet boundary values. BCValues bc_values; bc_values.add_function(BDY_DIRICHLET, essential_bc_values); // Create an H1 space with default shapeset. H1Space* space = new H1Space(&mesh, &bc_types, &bc_values, P_INIT); int ndof = Space::get_num_dofs(space); info("ndof = %d.", ndof); // Previous time level solution (initialized by the initial condition). Solution* u_prev_time = new Solution(&mesh, init_cond); // Initialize the weak formulation. WeakForm wf; wf.add_matrix_form(callback(stac_jacobian)); wf.add_vector_form(callback(stac_residual)); // Project the initial condition on the FE space to obtain initial solution coefficient vector. info("Projecting initial condition to translate initial condition into a vector."); scalar* coeff_vec = new scalar[ndof]; OGProjection::project_global(space, u_prev_time, coeff_vec, matrix_solver); // Initialize the FE problem. bool is_linear = false; DiscreteProblem dp(&wf, space, is_linear); // Time stepping loop: double current_time = 0.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, tau = %g, stages: %d).", current_time, time_step, bt.get_size()); bool verbose = true; if (!rk_time_step(current_time, time_step, &bt, coeff_vec, &dp, matrix_solver, verbose, NEWTON_TOL, NEWTON_MAX_ITER)) { error("Runge-Kutta time step failed, try to decrease time step size."); } // Convert coeff_vec into a new time level solution. Solution::vector_to_solution(coeff_vec, space, u_prev_time); // Update time. current_time += time_step; // Increase counter of time steps. ts++; } while (current_time < T_FINAL); info("Coordinate (-8.0, -8.0) value = %lf", u_prev_time->get_pt_value(-8.0, -8.0)); info("Coordinate (-5.0, -5.0) value = %lf", u_prev_time->get_pt_value(-5.0, -5.0)); info("Coordinate (-3.0, -3.0) value = %lf", u_prev_time->get_pt_value(-3.0, -3.0)); info("Coordinate ( 0.0, 0.0) value = %lf", u_prev_time->get_pt_value(0.0, 0.0)); info("Coordinate ( 3.0, 3.0) value = %lf", u_prev_time->get_pt_value(3.0, 3.0)); info("Coordinate ( 5.0, 5.0) value = %lf", u_prev_time->get_pt_value(5.0, 5.0)); info("Coordinate ( 8.0, 8.0) value = %lf", u_prev_time->get_pt_value(8.0, 8.0)); double coor_x_y[7] = {-8.0, -5.0, -3.0, 0.0, 3.0, 5.0, 8.0}; bool success = true; switch (b_type) { case 1: if (fabs(u_prev_time->get_pt_value(coor_x_y[0], coor_x_y[0]) - 0.042560) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[1], coor_x_y[1]) - 0.251886) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[2], coor_x_y[2]) - 0.492025) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[3], coor_x_y[3]) - 1.002150) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[4], coor_x_y[4]) - 1.693363) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[5], coor_x_y[5]) - 2.255564) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[6], coor_x_y[6]) - 3.266989) > 1E-6) success = false; break; case 2: if (fabs(u_prev_time->get_pt_value(coor_x_y[0], coor_x_y[0]) - 0.042559) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[1], coor_x_y[1]) - 0.251887) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[2], coor_x_y[2]) - 0.492024) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[3], coor_x_y[3]) - 1.002152) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[4], coor_x_y[4]) - 1.693351) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[5], coor_x_y[5]) - 2.255921) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[6], coor_x_y[6]) - 3.264214) > 1E-6) success = false; break; case 3: if (fabs(u_prev_time->get_pt_value(coor_x_y[0], coor_x_y[0]) - 0.042559) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[1], coor_x_y[1]) - 0.251887) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[2], coor_x_y[2]) - 0.492024) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[3], coor_x_y[3]) - 1.002151) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[4], coor_x_y[4]) - 1.693354) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[5], coor_x_y[5]) - 2.255822) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[6], coor_x_y[6]) - 3.265515) > 1E-6) success = false; break; case 4: if (fabs(u_prev_time->get_pt_value(coor_x_y[0], coor_x_y[0]) - 0.042559) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[1], coor_x_y[1]) - 0.251886) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[2], coor_x_y[2]) - 0.492024) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[3], coor_x_y[3]) - 1.002151) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[4], coor_x_y[4]) - 1.693356) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[5], coor_x_y[5]) - 2.255784) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[6], coor_x_y[6]) - 3.265491) > 1E-6) success = false; break; case 5: if (fabs(u_prev_time->get_pt_value(coor_x_y[0], coor_x_y[0]) - 0.042559) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[1], coor_x_y[1]) - 0.251886) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[2], coor_x_y[2]) - 0.492024) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[3], coor_x_y[3]) - 1.002151) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[4], coor_x_y[4]) - 1.693355) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[5], coor_x_y[5]) - 2.255791) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[6], coor_x_y[6]) - 3.265487) > 1E-6) success = false; break; case 6: if (fabs(u_prev_time->get_pt_value(coor_x_y[0], coor_x_y[0]) - 0.042559) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[1], coor_x_y[1]) - 0.251886) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[2], coor_x_y[2]) - 0.492024) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[3], coor_x_y[3]) - 1.002151) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[4], coor_x_y[4]) - 1.693356) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[5], coor_x_y[5]) - 2.255784) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[6], coor_x_y[6]) - 3.265491) > 1E-6) success = false; break; case 7: if (fabs(u_prev_time->get_pt_value(coor_x_y[0], coor_x_y[0]) - 0.042559) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[1], coor_x_y[1]) - 0.251886) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[2], coor_x_y[2]) - 0.492024) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[3], coor_x_y[3]) - 1.002151) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[4], coor_x_y[4]) - 1.693356) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[5], coor_x_y[5]) - 2.255784) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[6], coor_x_y[6]) - 3.265491) > 1E-6) success = false; break; case 8: if (fabs(u_prev_time->get_pt_value(coor_x_y[0], coor_x_y[0]) - 0.042559) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[1], coor_x_y[1]) - 0.251887) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[2], coor_x_y[2]) - 0.492024) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[3], coor_x_y[3]) - 1.002151) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[4], coor_x_y[4]) - 1.693354) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[5], coor_x_y[5]) - 2.255819) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[6], coor_x_y[6]) - 3.265435) > 1E-6) success = false; break; case 9: if (fabs(u_prev_time->get_pt_value(coor_x_y[0], coor_x_y[0]) - 0.042559) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[1], coor_x_y[1]) - 0.251886) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[2], coor_x_y[2]) - 0.492024) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[3], coor_x_y[3]) - 1.002151) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[4], coor_x_y[4]) - 1.693355) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[5], coor_x_y[5]) - 2.255795) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[6], coor_x_y[6]) - 3.265458) > 1E-6) success = false; break; case 10: if (fabs(u_prev_time->get_pt_value(coor_x_y[0], coor_x_y[0]) - 0.042559) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[1], coor_x_y[1]) - 0.251886) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[2], coor_x_y[2]) - 0.492024) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[3], coor_x_y[3]) - 1.002151) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[4], coor_x_y[4]) - 1.693355) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[5], coor_x_y[5]) - 2.255797) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[6], coor_x_y[6]) - 3.265487) > 1E-6) success = false; break; case 11: if (fabs(u_prev_time->get_pt_value(coor_x_y[0], coor_x_y[0]) - 0.042559) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[1], coor_x_y[1]) - 0.251886) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[2], coor_x_y[2]) - 0.492024) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[3], coor_x_y[3]) - 1.002151) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[4], coor_x_y[4]) - 1.693355) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[5], coor_x_y[5]) - 2.255798) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[6], coor_x_y[6]) - 3.265482) > 1E-6) success = false; break; case 12: if (fabs(u_prev_time->get_pt_value(coor_x_y[0], coor_x_y[0]) - 0.042559) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[1], coor_x_y[1]) - 0.251886) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[2], coor_x_y[2]) - 0.492024) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[3], coor_x_y[3]) - 1.002151) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[4], coor_x_y[4]) - 1.693355) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[5], coor_x_y[5]) - 2.255798) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[6], coor_x_y[6]) - 3.265482) > 1E-6) success = false; break; case 13: if (fabs(u_prev_time->get_pt_value(coor_x_y[0], coor_x_y[0]) - 0.042559) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[1], coor_x_y[1]) - 0.251886) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[2], coor_x_y[2]) - 0.492024) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[3], coor_x_y[3]) - 1.002151) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[4], coor_x_y[4]) - 1.693355) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[5], coor_x_y[5]) - 2.255798) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[6], coor_x_y[6]) - 3.265482) > 1E-6) success = false; break; case 14: if (fabs(u_prev_time->get_pt_value(coor_x_y[0], coor_x_y[0]) - 0.042559) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[1], coor_x_y[1]) - 0.251886) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[2], coor_x_y[2]) - 0.492024) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[3], coor_x_y[3]) - 1.002151) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[4], coor_x_y[4]) - 1.693355) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[5], coor_x_y[5]) - 2.255798) > 1E-6) success = false; if (fabs(u_prev_time->get_pt_value(coor_x_y[6], coor_x_y[6]) - 3.265482) > 1E-6) success = false; break; default: error("Admissible command-line options are from 1 to 14."); } // Cleanup. delete [] coeff_vec; delete space; delete u_prev_time; if (success) { printf("Success!\n"); return ERR_SUCCESS; } else { printf("Failure!\n"); return ERR_FAILURE; } }
/*! GMSH v2.xx mesh format export function * * This function extends the export capabilities of * Netgen to include the GMSH v2.xx File Format. * * Current features of this function include: * * 1. Exports Triangles, Quadrangles and Tetrahedra \n * 2. Supports upto second order elements of each type * */ void WriteGmsh2Format (const Mesh & mesh, const CSGeometry & geom, const string & filename) { ofstream outfile (filename.c_str()); outfile.precision(6); outfile.setf (ios::fixed, ios::floatfield); outfile.setf (ios::showpoint); int np = mesh.GetNP(); /// number of points in mesh int ne = mesh.GetNE(); /// number of 3D elements in mesh int nse = mesh.GetNSE(); /// number of surface elements (BC) int i, j, k, l; /* * 3D section : Volume elements (currently only tetrahedra) */ if ((ne > 0) && (mesh.VolumeElement(1).GetNP() <= 10) && (mesh.SurfaceElement(1).GetNP() <= 6)) { cout << "Write GMSH v2.xx Format \n"; cout << "The GMSH v2.xx export is currently available for elements upto 2nd Order\n" << endl; int inverttets = mparam.inverttets; int invertsurf = mparam.inverttrigs; /// Prepare GMSH 2.0 file (See GMSH 2.0 Documentation) outfile << "$MeshFormat\n"; outfile << (float)2.0 << " " << (int)0 << " " << (int)sizeof(double) << "\n"; outfile << "$EndMeshFormat\n"; /// Write nodes outfile << "$Nodes\n"; outfile << np << "\n"; for (i = 1; i <= np; i++) { const Point3d & p = mesh.Point(i); outfile << i << " "; /// node number outfile << p.X() << " "; outfile << p.Y() << " "; outfile << p.Z() << "\n"; } outfile << "$EndNodes\n"; /// write elements (both, surface elements and volume elements) outfile << "$Elements\n"; outfile << ne + nse << "\n"; //// number of elements + number of surfaces BC for (i = 1; i <= nse; i++) { int elType = 0; Element2d el = mesh.SurfaceElement(i); if(invertsurf) el.Invert(); if(el.GetNP() == 3) elType = GMSH_TRIG; //// GMSH Type for a 3 node triangle if(el.GetNP() == 6) elType = GMSH_TRIG6; //// GMSH Type for a 6 node triangle if(elType == 0) { cout << " Invalid surface element type for Gmsh 2.0 3D-Mesh Export Format !\n"; return; } outfile << i; outfile << " "; outfile << elType; outfile << " "; outfile << "2"; //// Number of tags (2 => Physical and elementary entities) outfile << " "; outfile << mesh.GetFaceDescriptor (el.GetIndex()).BCProperty() << " "; /// that means that physical entity = elementary entity (arbitrary approach) outfile << mesh.GetFaceDescriptor (el.GetIndex()).BCProperty() << " "; for (j = 1; j <= el.GetNP(); j++) { outfile << " "; outfile << el.PNum(triGmsh[j]); } outfile << "\n"; } for (i = 1; i <= ne; i++) { int elType = 0; Element el = mesh.VolumeElement(i); if (inverttets) el.Invert(); if(el.GetNP() == 4) elType = GMSH_TET; //// GMSH Element type for 4 node tetrahedron if(el.GetNP() == 10) elType = GMSH_TET10; //// GMSH Element type for 10 node tetrahedron if(elType == 0) { cout << " Invalid volume element type for Gmsh 2.0 3D-Mesh Export Format !\n"; return; } outfile << nse + i; //// element number (Remember to add on surface elements) outfile << " "; outfile << elType; outfile << " "; outfile << "2"; //// Number of tags (2 => Physical and elementary entities) outfile << " "; outfile << 100000 + el.GetIndex(); /// that means that physical entity = elementary entity (arbitrary approach) outfile << " "; outfile << 100000 + el.GetIndex(); /// volume number outfile << " "; for (j = 1; j <= el.GetNP(); j++) { outfile << " "; outfile << el.PNum(tetGmsh[j]); } outfile << "\n"; } outfile << "$EndElements\n"; } /* * End of 3D section */ /* * 2D section : available for triangles and quadrangles * upto 2nd Order */ else if(ne == 0) /// means that there's no 3D element { cout << "\n Write Gmsh v2.xx Surface Mesh (triangle and/or quadrangles upto 2nd Order)" << endl; /// Prepare GMSH 2.0 file (See GMSH 2.0 Documentation) outfile << "$MeshFormat\n"; outfile << (float)2.0 << " " << (int)0 << " " << (int)sizeof(double) << "\n"; outfile << "$EndMeshFormat\n"; /// Write nodes outfile << "$Nodes\n"; outfile << np << "\n"; for (i = 1; i <= np; i++) { const Point3d & p = mesh.Point(i); outfile << i << " "; /// node number outfile << p.X() << " "; outfile << p.Y() << " "; outfile << p.Z() << "\n"; } outfile << "$EndNodes\n"; /// write triangles & quadrangles outfile << "$Elements\n"; outfile << nse << "\n"; for (k = 1; k <= nse; k++) { int elType = 0; const Element2d & el = mesh.SurfaceElement(k); if(el.GetNP() == 3) elType = GMSH_TRIG; //// GMSH Type for a 3 node triangle if(el.GetNP() == 6) elType = GMSH_TRIG6; //// GMSH Type for a 6 node triangle if(el.GetNP() == 4) elType = GMSH_QUAD; //// GMSH Type for a 4 node quadrangle if(el.GetNP() == 8) elType = GMSH_QUAD8; //// GMSH Type for an 8 node quadrangle if(elType == 0) { cout << " Invalid surface element type for Gmsh 2.0 2D-Mesh Export Format !\n"; return; } outfile << k; outfile << " "; outfile << elType; outfile << " "; outfile << "2"; outfile << " "; outfile << mesh.GetFaceDescriptor (el.GetIndex()).BCProperty() << " "; /// that means that physical entity = elementary entity (arbitrary approach) outfile << mesh.GetFaceDescriptor (el.GetIndex()).BCProperty() << " "; for (l = 1; l <= el.GetNP(); l++) { outfile << " "; if((elType == GMSH_TRIG) || (elType == GMSH_TRIG6)) { outfile << el.PNum(triGmsh[l]); } else if((elType == GMSH_QUAD) || (elType == GMSH_QUAD8)) { outfile << el.PNum(quadGmsh[l]); } } outfile << "\n"; } outfile << "$EndElements\n"; } /* * End of 2D section */ else { cout << " Invalid element type for Gmsh v2.xx Export Format !\n"; } } // End: WriteGmsh2Format
// Create a new netgen mesh object DLL_HEADER Ng_Mesh * Ng_NewMesh () { Mesh * mesh = new Mesh; mesh->AddFaceDescriptor (FaceDescriptor (1, 1, 0, 1)); return (Ng_Mesh*)(void*)mesh; }
// ***************************************************************** void VertexPaint::fillSelectionColor() { int mci; // Put Data in Undo/Redo List. if(!theHold.Holding()) theHold.Begin(); ModContextList modContexts; INodeTab nodeTab; GetCOREInterface()->GetModContexts(modContexts, nodeTab); for (mci=0; mci<modContexts.Count(); mci++) { ModContext *mc = modContexts[mci]; if(mc && mc->localData) theHold.Put(new VertexPaintRestore((VertexPaintData*)mc->localData, this)); } theHold.Accept(GetString(IDS_RESTORE_FILL)); // Which Component to change?? VertexPaintData::TComponent whichComponent; switch(getEditionType()) { case 0: whichComponent= VertexPaintData::Red; break; case 1: whichComponent= VertexPaintData::Green; break; case 2: whichComponent= VertexPaintData::Blue; break; } // Modify all meshes. for (mci=0; mci<modContexts.Count(); mci++) { ModContext *mc = modContexts[mci]; if(mc && mc->localData) { VertexPaintData* d = (VertexPaintData*)mc->localData; Mesh* mesh = d->GetMesh(); if (mesh && mesh->vertCol) { // For all faces of the mesh for(int fi=0; fi<mesh->getNumFaces(); fi++) { Face* f = &mesh->faces[fi]; for (int i=0; i<3; i++) { // Skip painting because not selected?? if(mesh->selLevel == MESH_VERTEX && !mesh->VertSel()[f->v[i]] ) continue; if(mesh->selLevel == MESH_FACE && !mesh->FaceSel()[fi]) continue; // Also skip if face is hidden. if(f->Hidden()) continue; // Apply painting d->SetColor(f->v[i], 1, GetActiveColor(), whichComponent); } } } } } // refresh NotifyDependents(FOREVER, PART_VERTCOLOR, REFMSG_CHANGE); ip->RedrawViews(ip->GetTime()); }
void run(){ next = old->subdivide(min, max, *wingedEdge); }
// ***************************************************************** void VertexPaint::fillSelectionGradientColor() { int mci; // Put Data in Undo/Redo List. if(!theHold.Holding()) theHold.Begin(); ModContextList modContexts; INodeTab nodeTab; GetCOREInterface()->GetModContexts(modContexts, nodeTab); for (mci=0; mci<modContexts.Count(); mci++) { ModContext *mc = modContexts[mci]; if(mc && mc->localData) theHold.Put(new VertexPaintRestore((VertexPaintData*)mc->localData, this)); } theHold.Accept(GetString(IDS_RESTORE_GRADIENT)); // Which Component to change?? VertexPaintData::TComponent whichComponent; switch(getEditionType()) { case 0: whichComponent= VertexPaintData::Red; break; case 1: whichComponent= VertexPaintData::Green; break; case 2: whichComponent= VertexPaintData::Blue; break; } COLORREF grad0= iColorGradient[0]->GetColor(); COLORREF grad1= iColorGradient[1]->GetColor(); // Get Matrix to viewport. Matrix3 viewMat; { ViewExp *ve = GetCOREInterface()->GetActiveViewport(); // The affine TM transforms from world coords to view coords ve->GetAffineTM(viewMat); GetCOREInterface()->ReleaseViewport(ve); } // Modify all meshes. for (mci=0; mci<modContexts.Count(); mci++) { ModContext *mc = modContexts[mci]; if(mc && mc->localData) { VertexPaintData* d = (VertexPaintData*)mc->localData; Mesh* mesh = d->GetMesh(); if (mesh && mesh->vertCol) { float yMini= FLT_MAX; float yMaxi= -FLT_MAX; // 1st, For all faces of the mesh, comute BBox of selection. int fi; for(fi=0; fi<mesh->getNumFaces(); fi++) { Face* f = &mesh->faces[fi]; for (int i=0; i<3; i++) { // Skip painting because not selected?? if(mesh->selLevel == MESH_VERTEX && !mesh->VertSel()[f->v[i]] ) continue; if(mesh->selLevel == MESH_FACE && !mesh->FaceSel()[fi]) continue; // Also skip if face is hidden. if(f->Hidden()) continue; // Transform to viewSpace. Point3 p= viewMat*mesh->getVert(f->v[i]); // extend bbox. yMini= p.y<yMini?p.y:yMini; yMaxi= p.y>yMaxi?p.y:yMaxi; } } // 2nd, For all faces of the mesh, fill with gradient for(fi=0; fi<mesh->getNumFaces(); fi++) { Face* f = &mesh->faces[fi]; for (int i=0; i<3; i++) { // Skip painting because not selected?? if(mesh->selLevel == MESH_VERTEX && !mesh->VertSel()[f->v[i]] ) continue; if(mesh->selLevel == MESH_FACE && !mesh->FaceSel()[fi]) continue; // Also skip if face is hidden. if(f->Hidden()) continue; // Compute gradientValue. float gradValue; Point3 p= viewMat*mesh->getVert(f->v[i]); gradValue= (p.y-yMini)/(yMaxi-yMini); // Modifie with bendPower. 1->6. float pow= 1 + fGradientBend * 5; gradValue= powf(gradValue, pow); // Apply painting // Reset To 0. d->SetColor(f->v[i], 1, grad0, whichComponent); // Blend with gradientValue. d->SetColor(f->v[i], gradValue, grad1, whichComponent); } } } } } // refresh NotifyDependents(FOREVER, PART_VERTCOLOR, REFMSG_CHANGE); ip->RedrawViews(ip->GetTime()); }
int main(int argc, char* argv[]) { // Load the mesh Mesh mesh; H2DReader mloader; mloader.load("domain.mesh", &mesh); // initial uniform mesh refinement for (int i=0; i < INIT_REF_NUM; i++) mesh.refine_all_elements(); // Initialize the shapeset and the cache H1Shapeset shapeset; PrecalcShapeset pss(&shapeset); // Create finite element space H1Space space(&mesh, &shapeset); space.set_bc_types(bc_types); space.set_bc_values(bc_values); space.set_uniform_order(P_INIT); // Enumerate basis functions space.assign_dofs(); // initialize the weak formulation WeakForm wf(1); wf.add_biform(0, 0, bilinear_form_1, bilinear_form_ord, SYM, 1); wf.add_biform(0, 0, bilinear_form_2, bilinear_form_ord, SYM, 2); wf.add_biform(0, 0, bilinear_form_3, bilinear_form_ord, SYM, 3); wf.add_biform(0, 0, bilinear_form_4, bilinear_form_ord, SYM, 4); wf.add_biform(0, 0, bilinear_form_5, bilinear_form_ord, SYM, 5); wf.add_liform(0, linear_form_1, linear_form_ord, 1); wf.add_liform(0, linear_form_3, linear_form_ord, 3); // Visualize solution and mesh ScalarView sview("Coarse solution", 0, 100, 798, 700); OrderView oview("Polynomial orders", 800, 100, 798, 700); // Matrix solver UmfpackSolver solver; // DOF and CPU convergence graphs SimpleGraph graph_dof, graph_cpu; // prepare selector RefinementSelectors::H1NonUniformHP selector(ISO_ONLY, ADAPT_TYPE, 1.0, H2DRS_DEFAULT_ORDER, &shapeset); // Adaptivity loop int it = 1, ndofs; bool done = false; double cpu = 0.0; Solution sln_coarse, sln_fine; do { info("\n---- Adaptivity step %d ---------------------------------------------\n", it++); // Time measurement begin_time(); // Solve the coarse mesh problem LinSystem ls(&wf, &solver); ls.set_spaces(1, &space); ls.set_pss(1, &pss); ls.assemble(); ls.solve(1, &sln_coarse); // Time measurement cpu += end_time(); // View the solution and mesh sview.show(&sln_coarse); oview.show(&space); // Time measurement begin_time(); // Solve the fine mesh problem RefSystem rs(&ls); rs.assemble(); rs.solve(1, &sln_fine); // Calculate error estimate wrt. fine mesh solution H1AdaptHP hp(1, &space); double err_est = hp.calc_error(&sln_coarse, &sln_fine) * 100; info("Estimate of error: %g%%", err_est); // add entry to DOF convergence graph graph_dof.add_values(space.get_num_dofs(), err_est); graph_dof.save("conv_dof.dat"); // add entry to CPU convergence graph graph_cpu.add_values(cpu, err_est); graph_cpu.save("conv_cpu.dat"); // If err_est too large, adapt the mesh if (err_est < ERR_STOP) done = true; else { hp.adapt(THRESHOLD, STRATEGY, &selector, MESH_REGULARITY); ndofs = space.assign_dofs(); if (ndofs >= NDOF_STOP) done = true; } // Time measurement cpu += end_time(); } while (done == false); verbose("Total running time: %g sec", cpu); // Show the fine solution - this is the final result sview.set_title("Final solution"); sview.show(&sln_fine); oview.set_title("Final orders"); oview.show(&space); // Wait for keyboard or mouse input View::wait(); return 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. Mesh mesh; MeshReaderH2D mloader; mloader.load("square.mesh", &mesh); // 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); Solution<std::complex<double> > psi_time_new(&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(); Hermes::Mixins::Loggable::Static::info("ndof = %d", ndof); // Initialize the FE problem. DiscreteProblem<std::complex<double> > dp(&wf, &space); // Initialize views. ScalarView sview_real("Solution - real part", new WinGeom(0, 0, 600, 500)); ScalarView sview_imag("Solution - imaginary part", new WinGeom(610, 0, 600, 500)); sview_real.fix_scale_width(80); sview_imag.fix_scale_width(80); // Initialize Runge-Kutta time stepping. RungeKutta<std::complex<double> > runge_kutta(&wf, &space, &bt); // Time stepping: int ts = 1; int nstep = (int)(T_FINAL/time_step + 0.5); for(int ts = 1; ts <= nstep; ts++) { // 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, time step = %g s, stages: %d).", current_time, time_step, bt.get_size()); try { runge_kutta.setTime(current_time); runge_kutta.setTimeStep(time_step); runge_kutta.rk_time_step_newton(&psi_time_prev, &psi_time_new); } catch(Exceptions::Exception& e) { e.printMsg(); throw Hermes::Exceptions::Exception("Runge-Kutta time step failed"); } // Show the new time level solution. 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(&psi_time_new); ImagFilter imag(&psi_time_new); sview_real.show(&real); sview_imag.show(&imag); // Copy solution for the new time step. psi_time_prev.copy(&psi_time_new); // Increase current time and time step counter. current_time += time_step; ts++; } // Wait for the view to be closed. View::wait(); return 0; }
int main(int argc, char **argv) { int res = ERR_SUCCESS; #ifdef WITH_PETSC PetscInitialize(&argc, &argv, (char *) PETSC_NULL, PETSC_NULL); #endif set_verbose(false); if (argc < 5) error("Not enough parameters."); H1ShapesetLobattoHex shapeset; printf("* Loading mesh '%s'\n", argv[1]); Mesh mesh; Mesh3DReader mloader; if (!mloader.load(argv[1], &mesh)) error("Loading mesh file '%s'\n", argv[1]); printf("* Setting the space up\n"); H1Space space(&mesh, &shapeset); space.set_bc_types(bc_types); space.set_essential_bc_values(essential_bc_values); int o[3] = { 0, 0, 0 }; sscanf(argv[2], "%d", o + 0); sscanf(argv[3], "%d", o + 1); sscanf(argv[4], "%d", o + 2); order3_t order(o[0], o[1], o[2]); printf(" - Setting uniform order to (%d, %d, %d)\n", order.x, order.y, order.z); space.set_uniform_order(order); WeakForm wf; wf.add_matrix_form(bilinear_form<double, scalar>, bilinear_form<ord_t, ord_t>, SYM, ANY); wf.add_vector_form(linear_form<double, scalar>, linear_form<ord_t, ord_t>, ANY); LinearProblem lp(&wf); lp.set_space(&space); bool done = false; int iter = 0; do { Timer assemble_timer("Assembling stiffness matrix"); Timer solve_timer("Solving stiffness matrix"); printf("\n=== Iter #%d ================================================================\n", iter); printf("\nSolution\n"); #if defined WITH_UMFPACK UMFPackMatrix mat; UMFPackVector rhs; UMFPackLinearSolver solver(&mat, &rhs); #elif defined WITH_PARDISO PardisoMatrix mat; PardisoVector rhs; PardisoLinearSolver solver(&mat, &rhs); #elif defined WITH_PETSC PetscMatrix mat; PetscVector rhs; PetscLinearSolver solver(&mat, &rhs); #elif defined WITH_MUMPS MumpsMatrix mat; MumpsVector rhs; MumpsSolver solver(&mat, &rhs); #endif int ndofs = space.assign_dofs(); printf(" - Number of DOFs: %d\n", ndofs); // assemble stiffness matrix printf(" - Assembling... "); fflush(stdout); assemble_timer.reset(); assemble_timer.start(); lp.assemble(&mat, &rhs); assemble_timer.stop(); printf("done in %s (%lf secs)\n", assemble_timer.get_human_time(), assemble_timer.get_seconds()); // solve the stiffness matrix printf(" - Solving... "); fflush(stdout); solve_timer.reset(); solve_timer.start(); bool solved = solver.solve(); solve_timer.stop(); if (solved) printf("done in %s (%lf secs)\n", solve_timer.get_human_time(), solve_timer.get_seconds()); else { res = ERR_FAILURE; printf("failed\n"); break; } printf("Reference solution\n"); #if defined WITH_UMFPACK UMFPackLinearSolver rsolver(&mat, &rhs); #elif defined WITH_PARDISO PardisoLinearSolver rsolver(&mat, &rhs); #elif defined WITH_PETSC PetscLinearSolver rsolver(&mat, &rhs); #elif defined WITH_MUMPS MumpsSolver rsolver(&mat, &rhs); #endif Mesh rmesh; rmesh.copy(mesh); rmesh.refine_all_elements(H3D_H3D_H3D_REFT_HEX_XYZ); Space *rspace = space.dup(&rmesh); rspace->copy_orders(space, 1); LinearProblem rlp(&wf); rlp.set_space(rspace); int rndofs = rspace->assign_dofs(); printf(" - Number of DOFs: %d\n", rndofs); printf(" - Assembling... "); fflush(stdout); assemble_timer.reset(); assemble_timer.start(); rlp.assemble(&mat, &rhs); assemble_timer.stop(); printf("done in %s (%lf secs)\n", assemble_timer.get_human_time(), assemble_timer.get_seconds()); printf(" - Solving... "); fflush(stdout); solve_timer.reset(); solve_timer.start(); bool rsolved = rsolver.solve(); solve_timer.stop(); if (rsolved) printf("done in %s (%lf secs)\n", solve_timer.get_human_time(), solve_timer.get_seconds()); else { res = ERR_FAILURE; printf("failed\n"); break; } Solution sln(&mesh); sln.set_fe_solution(&space, solver.get_solution()); Solution rsln(&rmesh); rsln.set_fe_solution(rspace, rsolver.get_solution()); printf("Adaptivity:\n"); H1Adapt hp(&space); double tol = hp.calc_error(&sln, &rsln) * 100; printf(" - tolerance: "); fflush(stdout); printf("% lf\n", tol); if (tol < TOLERANCE) { printf("\nDone\n"); ExactSolution ex_sln(&mesh, exact_solution); // norm double h1_sln_norm = h1_norm(&sln); double h1_err_norm = h1_error(&sln, &ex_sln); printf(" - H1 solution norm: % le\n", h1_sln_norm); printf(" - H1 error norm: % le\n", h1_err_norm); double l2_sln_norm = l2_norm(&sln); double l2_err_norm = l2_error(&sln, &ex_sln); printf(" - L2 solution norm: % le\n", l2_sln_norm); printf(" - L2 error norm: % le\n", l2_err_norm); if (h1_err_norm > EPS || l2_err_norm > EPS) { // calculated solution is not enough precise res = ERR_FAILURE; } break; } Timer t(""); printf(" - adapting... "); fflush(stdout); t.start(); hp.adapt(THRESHOLD); t.stop(); printf("done in %lf secs (refined %d element(s))\n", t.get_seconds(), hp.get_num_refined_elements()); iter++; } while (!done); #ifdef WITH_PETSC PetscFinalize(); #endif return res; }
void ETD(MultiLevelProblem& ml_prob) { const unsigned& NLayers = NumberOfLayers; adept::Stack& s = FemusInit::_adeptStack; LinearImplicitSystem* mlPdeSys = &ml_prob.get_system<LinearImplicitSystem> ("SW"); // pointer to the linear implicit system named "Poisson" unsigned level = ml_prob._ml_msh->GetNumberOfLevels() - 1u; Mesh* msh = ml_prob._ml_msh->GetLevel(level); // pointer to the mesh (level) object elem* el = msh->el; // pointer to the elem object in msh (level) MultiLevelSolution* mlSol = ml_prob._ml_sol; // pointer to the multilevel solution object Solution* sol = ml_prob._ml_sol->GetSolutionLevel(level); // pointer to the solution (level) object LinearEquationSolver* pdeSys = mlPdeSys->_LinSolver[level]; // pointer to the equation (level) object SparseMatrix* KK = pdeSys->_KK; // pointer to the global stifness matrix object in pdeSys (level) NumericVector* RES = pdeSys->_RES; // pointer to the global residual vector object in pdeSys (level) NumericVector* EPS = pdeSys->_EPS; // pointer to the global residual vector object in pdeSys (level) const unsigned dim = msh->GetDimension(); // get the domain dimension of the problem unsigned iproc = msh->processor_id(); // get the process_id (for parallel computation) unsigned nprocs = msh->n_processors(); // get the process_id (for parallel computation) //solution variable std::vector < unsigned > solIndexh(NLayers); std::vector < unsigned > solPdeIndexh(NLayers); std::vector < unsigned > solIndexv(NLayers); std::vector < unsigned > solPdeIndexv(NLayers); // std::vector < unsigned > solIndextracer(NLayers); // std::vector < unsigned > solPdeIndextracer(NLayers); vector< int > l2GMap; // local to global mapping for(unsigned i = 0; i < NLayers; i++) { char name[10]; sprintf(name, "h%d", i); solIndexh[i] = mlSol->GetIndex(name); // get the position of "hi" in the sol object solPdeIndexh[i] = mlPdeSys->GetSolPdeIndex(name); // get the position of "hi" in the pdeSys object sprintf(name, "v%d", i); solIndexv[i] = mlSol->GetIndex(name); // get the position of "vi" in the sol object solPdeIndexv[i] = mlPdeSys->GetSolPdeIndex(name); // get the position of "vi" in the pdeSys object // sprintf(name, "tracer%d", i); // solIndextracer[i] = mlSol->GetIndex(name); // get the position of "traceri" in the sol object // solPdeIndextracer[i] = mlPdeSys->GetSolPdeIndex(name); // get the position of "traceri" in the pdeSys object } unsigned solTypeh = mlSol->GetSolutionType(solIndexh[0]); // get the finite element type for "hi" unsigned solTypev = mlSol->GetSolutionType(solIndexv[0]); // get the finite element type for "vi" // unsigned solTypetracer = mlSol->GetSolutionType(solIndextracer[0]); // get the finite element type for "traceri" vector < double > x; // local coordinates vector< vector < adept::adouble > > solh(NLayers); // local coordinates vector< vector < adept::adouble > > solv(NLayers); // local coordinates // vector< vector < adept::adouble > > soltracer(NLayers); // local coordinates vector< vector < bool > > bdch(NLayers); // local coordinates vector< vector < bool > > bdcv(NLayers); // local coordinates // vector< vector < bool > > bdctracer(NLayers); // local coordinates unsigned xType = 2; // get the finite element type for "x", it is always 2 (LAGRANGE QUADRATIC) vector < vector< adept::adouble > > aResh(NLayers); vector < vector< adept::adouble > > aResv(NLayers); // vector < vector< adept::adouble > > aRestracer(NLayers); KK->zero(); RES->zero(); double maxWaveSpeed = 0.; double dx; for(int iel = msh->_elementOffset[iproc]; iel < msh->_elementOffset[iproc + 1]; iel++) { short unsigned ielGeom = msh->GetElementType(iel); unsigned nDofh = msh->GetElementDofNumber(iel, solTypeh); // number of solution element dofs unsigned nDofv = msh->GetElementDofNumber(iel, solTypev); // number of solution element dofs //unsigned nDoftracer = msh->GetElementDofNumber(iel, solTypetracer); // number of coordinate element dofs unsigned nDofx = msh->GetElementDofNumber(iel, xType); // number of coordinate element dofs unsigned nDofs = nDofh + nDofv /*+ nDoftracer*/; // resize local arrays l2GMap.resize(NLayers * (nDofs) ); for(unsigned i = 0; i < NLayers; i++) { solh[i].resize(nDofh); solv[i].resize(nDofv); //soltracer[i].resize(nDofvtracer); bdch[i].resize(nDofh); bdcv[i].resize(nDofv); //bdctracer[i].resize(nDoftracer); aResh[i].resize(nDofh); //resize std::fill(aResh[i].begin(), aResh[i].end(), 0); //set aRes to zero aResv[i].resize(nDofv); //resize std::fill(aResv[i].begin(), aResv[i].end(), 0); //set aRes to zero //aRestracer[i].resize(nDoftracer); //resize //std::fill(aRestracer[i].begin(), aRestracer[i].end(), 0); //set aRes to zero } x.resize(nDofx); //local storage of global mapping and solution for(unsigned i = 0; i < nDofh; i++) { unsigned solDofh = msh->GetSolutionDof(i, iel, solTypeh); // global to global mapping between solution node and solution dof for(unsigned j = 0; j < NLayers; j++) { solh[j][i] = (*sol->_Sol[solIndexh[j]])(solDofh); // global extraction and local storage for the solution bdch[j][i] = ( (*sol->_Bdc[solIndexh[j]])(solDofh) < 1.5) ? true : false; l2GMap[ j * nDofs + i] = pdeSys->GetSystemDof(solIndexh[j], solPdeIndexh[j], i, iel); // global to global mapping between solution node and pdeSys dof } } for(unsigned i = 0; i < nDofv; i++) { unsigned solDofv = msh->GetSolutionDof(i, iel, solTypev); // global to global mapping between solution node and solution dof for(unsigned j = 0; j < NLayers; j++) { solv[j][i] = (*sol->_Sol[solIndexv[j]])(solDofv); // global extraction and local storage for the solution bdcv[j][i] = ( (*sol->_Bdc[solIndexv[j]])(solDofv) < 1.5) ? true : false; l2GMap[ j * nDofs + nDofh + i] = pdeSys->GetSystemDof(solIndexv[j], solPdeIndexv[j], i, iel); // global to global mapping between solution node and pdeSys dof } } // for(unsigned i = 0; i < nDoftracer; i++) { // unsigned solDoftracer = msh->GetSolutionDof(i, iel, solTypetracer); // global to global mapping between solution node and solution dof // for(unsigned j = 0; j < NLayers; j++) { // soltracer[j][i] = (*sol->_Sol[solIndextracer[j]])(solDoftracer); // global extraction and local storage for the solution // bdctracer[j][i] = ( (*sol->_Bdc[solIndextracer[j]])(solDoftracer) < 1.5) ? true : false; // l2GMap[ j * nDofs + nDofh + nDofv + i] = pdeSys->GetSystemDof(solIndextracer[j], solPdeIndextracer[j], i, iel); // global to global mapping between solution node and pdeSys dof // } // } s.new_recording(); for(unsigned i = 0; i < nDofx; i++) { unsigned xDof = msh->GetSolutionDof(i, iel, xType); // global to global mapping between coordinates node and coordinate dof x[i] = (*msh->_topology->_Sol[0])(xDof); // global extraction and local storage for the element coordinates } double xmid = 0.5 * (x[0] + x[1]); //std::cout << xmid << std::endl; double zz = sqrt(aa * aa - xmid * xmid); // z coordinate of points on sphere double dd = aa * acos((zz * z_c) / (aa * aa)); // distance to center point on sphere [m] double hh = 1 - dd * dd / (bb * bb); double b = ( H_shelf + H_0 / 2 * (1 + tanh(hh / phi)) ); std::vector < adept::adouble > eta(NLayers); double hTot = 0.; for(unsigned k = 0; k < NLayers; k++) { hTot += solh[k][0].value(); eta[k] = - b * rho[k]; // bottom topography for( unsigned j = 0; j < NLayers; j++){ double rhoj = (j <= k) ? rho[j] : rho[k]; eta[k] += rhoj * solh[j][0]; } eta[k] /= rho[k]; } std::vector < double > hALE(NLayers, 0.); hALE[0] = hRest[0] + (hTot - b); for(unsigned k = 1; k < NLayers - 1; k++){ hALE[k] = hRest[k]; } hALE[NLayers - 1] = b - hRest[NLayers - 1]; std::vector < double > w(NLayers+1, 0.); dx = x[1] - x[0]; for(unsigned k = NLayers; k>1; k--){ w[k-1] = w[k] - solh[k-1][0].value() * (solv[k-1][1].value() - solv[k-1][0].value() )/dx- ( hALE[k-1] - solh[k-1][0].value()) / dt; //std::cout << hALE[k-1] << " " << w[k-1] << " "; } //std::cout<<std::endl; std::vector < adept::adouble > zMid(NLayers); for(unsigned k = 0; k < NLayers; k++) { zMid[k] = solh[k][0]/2; for(unsigned i = 0; i < k; i++) { zMid[k] += solh[i][0]; } //std::cout << zMid[k] << " "; } //std::cout<<std::endl; // double hTotal = 0.; // for(unsigned i = 0; i<NLayers; i++) hTotal += solh[i][0].value(); double celerity = sqrt( 9.81 * hTot); for(unsigned i = 0; i<NLayers; i++){ double vmid = 0.5 * ( solv[i][0].value() + solv[i][1].value() ); maxWaveSpeed = ( maxWaveSpeed > fabs(vmid) + fabs(celerity) )? maxWaveSpeed : fabs(vmid) + fabs(celerity); } for(unsigned k = 0; k < NLayers; k++) { if(!bdch[k][0]) { for (unsigned j = 0; j < nDofv; j++) { double sign = ( j == 0) ? 1. : -1; aResh[k][0] += sign * solh[k][0] * solv[k][j] / dx; } aResh[k][0] += w[k+1] - w[k]; } adept::adouble vMid = 0.5 * (solv[k][0] + solv[k][1]); adept::adouble fv = 0.5 * vMid * vMid + 9.81 * eta[k]; for (unsigned i = 0; i < nDofv; i++) { if(!bdcv[k][i]) { double sign = ( i == 0) ? -1. : 1; aResv[k][i] += sign * fv / dx; if ( k > 0 ){ aResv[k][i] -= 0.5 * ( w[k] * 0.5 * ( solv[k-1][i] - solv[k][i] ) / (0.5 * ( solh[k-1][0] + solh[k][0] ) ) ); } if (k < NLayers - 1) { aResv[k][i] -= 0.5 * ( w[k+1] * 0.5 * ( solv[k][i] - solv[k+1][i] ) / (0.5 * ( solh[k][0] + solh[k+1][0] ) ) ); } //aResv[k][i] += sign * 9.81 * rho[k] * zMid[k] / dx; } } // if(!bdctracer[k][0]) { // for (unsigned j = 0; j < nDofv; j++) { // double sign = ( j == 0) ? 1. : -1; // aRestracer[k][0] += sign * solh[k][0] * solv[k][j] * soltracer[k][0] / dx; // } // aRestracer[k][0] += w[k+1] * ((soltracer[k][0] + soltracer[k+1][0])/2) - w[k] * ((soltracer[k-1][0] + soltracer[k][0])/2); // } } vector< double > Res(NLayers * nDofs); // local redidual vector unsigned counter = 0; for(unsigned k = 0; k < NLayers; k++) { for(int i = 0; i < nDofh; i++) { Res[counter] = aResh[k][i].value(); counter++; } for(int i = 0; i < nDofv; i++) { Res[counter] = aResv[k][i].value(); counter++; } } RES->add_vector_blocked(Res, l2GMap); for(unsigned k = 0; k < NLayers; k++) { // define the dependent variables s.dependent(&aResh[k][0], nDofh); s.dependent(&aResv[k][0], nDofv); // define the independent variables s.independent(&solh[k][0], nDofh); s.independent(&solv[k][0], nDofv); } // get the jacobian matrix (ordered by row major ) vector < double > Jac(NLayers * nDofs * NLayers * nDofs); s.jacobian(&Jac[0], true); //store K in the global matrix KK KK->add_matrix_blocked(Jac, l2GMap, l2GMap); s.clear_independents(); s.clear_dependents(); } RES->close(); KK->close(); // PetscViewer viewer; // PetscViewerDrawOpen(PETSC_COMM_WORLD,NULL,NULL,0,0,900,900,&viewer); // PetscObjectSetName((PetscObject)viewer,"FSI matrix"); // PetscViewerPushFormat(viewer,PETSC_VIEWER_DRAW_LG); // MatView((static_cast<PetscMatrix*>(KK))->mat(),viewer); // double a; // std::cin>>a; // // abort(); MFN mfn; Mat A = (static_cast<PetscMatrix*>(KK))->mat(); FN f, f1, f2, f3 , f4; std::cout << "dt = " << dt << " dx = "<< dx << " maxWaveSpeed = "<<maxWaveSpeed << std::endl; //dt = 100.; Vec v = (static_cast< PetscVector* >(RES))->vec(); Vec y = (static_cast< PetscVector* >(EPS))->vec(); MFNCreate( PETSC_COMM_WORLD, &mfn ); MFNSetOperator( mfn, A ); MFNGetFN( mfn, &f ); // FNCreate(PETSC_COMM_WORLD, &f1); // FNCreate(PETSC_COMM_WORLD, &f2); // FNCreate(PETSC_COMM_WORLD, &f3); // FNCreate(PETSC_COMM_WORLD, &f4); // // FNSetType(f1, FNEXP); // // FNSetType(f2, FNRATIONAL); // double coeff1[1] = { -1}; // FNRationalSetNumerator(f2, 1, coeff1); // FNRationalSetDenominator(f2, 0, PETSC_NULL); // // FNSetType( f3, FNCOMBINE ); // // FNCombineSetChildren(f3, FN_COMBINE_ADD, f1, f2); // // FNSetType(f4, FNRATIONAL); // double coeff2[2] = {1., 0.}; // FNRationalSetNumerator(f4, 2, coeff2); // FNRationalSetDenominator(f4, 0, PETSC_NULL); // // FNSetType( f, FNCOMBINE ); // // FNCombineSetChildren(f, FN_COMBINE_DIVIDE, f3, f4); FNPhiSetIndex(f,1); FNSetType( f, FNPHI ); // FNView(f,PETSC_VIEWER_STDOUT_WORLD); FNSetScale( f, dt, dt); MFNSetFromOptions( mfn ); MFNSolve( mfn, v, y); MFNDestroy( &mfn ); // FNDestroy(&f1); // FNDestroy(&f2); // FNDestroy(&f3); // FNDestroy(&f4); sol->UpdateSol(mlPdeSys->GetSolPdeIndex(), EPS, pdeSys->KKoffset); unsigned solIndexeta = mlSol->GetIndex("eta"); unsigned solIndexb = mlSol->GetIndex("b"); sol->_Sol[solIndexeta]->zero(); for(unsigned k=0;k<NumberOfLayers;k++){ sol->_Sol[solIndexeta]->add(*sol->_Sol[solIndexh[k]]); } sol->_Sol[solIndexeta]->add(-1,*sol->_Sol[solIndexb]); }
//Renders each object in pObject, then proceeds to get the transform mesh and material for that object //then binds the mesh/material for said object and proceeds to assign locations for each uniform location //which will be needed for the shader files. We then get the Camera and light GameObject so we can access //data for said objects to assign values to variables which will be passed into the shader to calculate //other related stuff. From here it'll then draw the mesh and render each game object. void SplashScreen::renderGameObject(GameObject * pObject) { if (!pObject) return; pObject->render(); Mesh * currentMesh = pObject->getMesh(); Transform * currentTransform = pObject->getTransform(); Material * currentMaterial = (Material*)pObject->getMaterial(); if (currentMesh && currentMaterial && currentTransform) { currentMaterial->bind(); currentMesh->bind(); GLint MVPLocation = currentMaterial->getUniformLocation("MVP"); GLint ModelLocation = currentMaterial->getUniformLocation("Model"); GLint ambientMatLocation = currentMaterial->getUniformLocation("ambientMaterialColour"); GLint ambientLightLocation = currentMaterial->getUniformLocation("ambientLightColour"); GLint diffuseMatLocation = currentMaterial->getUniformLocation("diffuseMaterialColour"); GLint diffuseLightLocation = currentMaterial->getUniformLocation("diffuseLightColour"); GLint lightDirectionLocation = currentMaterial->getUniformLocation("lightDirection"); GLint specularMatLocation = currentMaterial->getUniformLocation("specularMaterialColour"); GLint specularLightLocation = currentMaterial->getUniformLocation("specularLightColour"); GLint specularpowerLocation = currentMaterial->getUniformLocation("specularPower"); GLint cameraPositionLocation = currentMaterial->getUniformLocation("cameraPosition"); GLint diffuseTextureLocation = currentMaterial->getUniformLocation("diffuseMap"); GLint specTextureLocation = currentMaterial->getUniformLocation("specMap"); GLint bumpTextureLocation = currentMaterial->getUniformLocation("bumpMap"); GLint heightTextureLocation = currentMaterial->getUniformLocation("heightMap"); GLint lightPositionLocation = currentMaterial->getUniformLocation("lightPosition"); Camera * cam = mainCamera->getCamera(); Light* light = mainLight->getLight(); mat4 MVP = cam->getProjection()*cam->getView()*currentTransform->getModel(); mat4 Model = currentTransform->getModel(); vec4 ambientMaterialColour = currentMaterial->getAmbientColour(); vec4 diffuseMaterialColour = currentMaterial->getDiffuseColour(); vec4 specularMaterialColour = currentMaterial->getSpecularColour(); float specularPower = currentMaterial->getSpecularPower(); vec4 diffuseLightColour = light->getDiffuseColour(); vec4 specularLightColour = light->getSpecularColour(); vec4 ambientLightColour = light->getAmbientColour(); vec3 lightDirection = light->getDirection(); vec3 cameraPosition = mainCamera->getTransform()->getPosition(); vec3 lightPosition = mainLight->getTransform()->getPosition(); glUniformMatrix4fv(ModelLocation, 1, GL_FALSE, glm::value_ptr(Model)); glUniformMatrix4fv(MVPLocation, 1, GL_FALSE, glm::value_ptr(MVP)); glUniform4fv(ambientMatLocation, 1, glm::value_ptr(ambientMaterialColour)); glUniform4fv(ambientLightLocation, 1, glm::value_ptr(ambientLightColour)); glUniform4fv(diffuseMatLocation, 1, glm::value_ptr(diffuseMaterialColour)); glUniform4fv(diffuseLightLocation, 1, glm::value_ptr(diffuseLightColour)); glUniform3fv(lightDirectionLocation, 1, glm::value_ptr(lightDirection)); glUniform4fv(specularMatLocation, 1, glm::value_ptr(specularMaterialColour)); glUniform4fv(specularLightLocation, 1, glm::value_ptr(specularLightColour)); glUniform3fv(cameraPositionLocation, 1, glm::value_ptr(cameraPosition)); glUniform1f(specularpowerLocation, specularPower); glUniform1i(diffuseTextureLocation, 0); glUniform1i(specTextureLocation, 1); glUniform1i(bumpTextureLocation, 2); glUniform1i(heightTextureLocation, 3); glUniform3fv(lightPositionLocation, 1, glm::value_ptr(lightPosition)); glDrawElements(GL_TRIANGLES, currentMesh->getIndexCount(), GL_UNSIGNED_INT, 0); currentMaterial->unbind(); } for (int i = 0; i < pObject->getChildCount(); i++) { renderGameObject(pObject->getChild(i)); } }
int main(int argc, char* argv[]) { // Load the mesh. Mesh mesh; H2DReader mloader; mloader.load("lshape.mesh", &mesh); // Perform initial mesh refinement. mesh.refine_all_elements(); // Create an H1 space with default shapeset. H1Space space(&mesh, bc_types, essential_bc_values, P_INIT); // Initialize the weak formulation. WeakForm wf; wf.add_matrix_form(callback(bilinear_form), HERMES_SYM); // Initialize refinement selector. H1ProjBasedSelector selector(CAND_LIST, CONV_EXP, H2DRS_DEFAULT_ORDER); // Set exact solution. ExactSolution exact(&mesh, fndd); // DOF and CPU convergence graphs. SimpleGraph graph_dof, graph_cpu, graph_dof_exact, graph_cpu_exact; // Time measurement. TimePeriod cpu_time; cpu_time.tick(); // Adaptivity loop: int as = 1; bool done = false; do { info("---- Adaptivity step %d:", as); // Construct globally refined reference mesh and setup reference space. Space* ref_space = construct_refined_space(&space); // Assemble the reference problem. info("Solving on reference mesh."); bool is_linear = true; DiscreteProblem* dp = new DiscreteProblem(&wf, ref_space, is_linear); SparseMatrix* matrix = create_matrix(matrix_solver); Vector* rhs = create_vector(matrix_solver); Solver* solver = create_linear_solver(matrix_solver, matrix, rhs); dp->assemble(matrix, rhs); // Time measurement. cpu_time.tick(); // Solve the linear system of the reference problem. If successful, obtain the solution. Solution ref_sln; if(solver->solve()) Solution::vector_to_solution(solver->get_solution(), ref_space, &ref_sln); else error ("Matrix solver failed.\n"); // Time measurement. cpu_time.tick(); // Project the fine mesh solution onto the coarse mesh. Solution sln; info("Projecting reference solution on coarse mesh."); OGProjection::project_global(&space, &ref_sln, &sln, matrix_solver); // Calculate element errors and total error estimate. info("Calculating error estimate and exact error."); Adapt* adaptivity = new Adapt(&space, HERMES_H1_NORM); bool solutions_for_adapt = true; double err_est_rel = adaptivity->calc_err_est(&sln, &ref_sln, solutions_for_adapt, HERMES_TOTAL_ERROR_REL | HERMES_ELEMENT_ERROR_REL) * 100; // Calculate exact error. solutions_for_adapt = false; double err_exact_rel = adaptivity->calc_err_exact(&sln, &exact, solutions_for_adapt, HERMES_TOTAL_ERROR_REL | HERMES_ELEMENT_ERROR_REL) * 100; // Report results. info("ndof_coarse: %d, ndof_fine: %d", Space::get_num_dofs(&space), Space::get_num_dofs(ref_space)); info("err_est_rel: %g%%, err_exact_rel: %g%%", err_est_rel, err_exact_rel); // Time measurement. cpu_time.tick(); // Add entry to DOF and CPU convergence graphs. graph_dof.add_values(Space::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"); graph_dof_exact.add_values(Space::get_num_dofs(&space), err_exact_rel); graph_dof_exact.save("conv_dof_exact.dat"); graph_cpu_exact.add_values(cpu_time.accumulated(), err_exact_rel); graph_cpu_exact.save("conv_cpu_exact.dat"); // If err_est too large, adapt the mesh. if (err_est_rel < ERR_STOP) done = true; else { info("Adapting coarse mesh."); done = adaptivity->adapt(&selector, THRESHOLD, STRATEGY, MESH_REGULARITY); // Increase the counter of performed adaptivity steps. if (done == false) as++; } if (Space::get_num_dofs(&space) >= NDOF_STOP) done = true; // Clean up. delete solver; delete matrix; delete rhs; delete adaptivity; if(done == false) delete ref_space->get_mesh(); delete ref_space; delete dp; } while (done == false); verbose("Total running time: %g s", cpu_time.accumulated()); int ndof = Space::get_num_dofs(&space); int n_dof_allowed = 1560; printf("n_dof_actual = %d\n", ndof); printf("n_dof_allowed = %d\n", n_dof_allowed); if (ndof <= n_dof_allowed) { printf("Success!\n"); return ERR_SUCCESS; } else { printf("Failure!\n"); return ERR_FAILURE; } }
//Sets up the appropriate vertice positions for the cube, selects the appropriate indices to form the cube, //then intiailizes the mesh so we can copy the mesh related data(indices/triangledata) to the mesh so we are ready //for setting the material. We set up the position, intialize the material and load in the cube texture then set //the material/mesh and transform then check to make sure no errors occur. void SplashScreen::createSkyBox() { Vertex triangleData[] = { { vec3(-50.0f, 50.0f, 50.0f) },// Top Left { vec3(-50.0f, -50.0f, 50.0f) },// Bottom Left { vec3(50.0f, -50.0f, 50.0f) }, //Bottom Right { vec3(50.0f, 50.0f, 50.0f) },// Top Right { vec3(-50.0f, 50.0f, -50.0f) },// Top Left { vec3(-50.0f, -50.0f, -50.0f) },// Bottom Left { vec3(50.0, -50.0f, -50.0f) }, //Bottom Right { vec3(50.0f, 50.0f, -50.0f) }// Top Right }; GLuint indices[] = { //front 0, 1, 2, 3, 2, 0, //left 3, 2, 6, 6, 7, 3, //right 7, 6, 5, 5, 4, 7, //bottom 4, 5, 1, 1, 0, 4, //top 4, 0, 3, 3, 7, 4, //back 1, 5, 6, 6, 2, 1 }; ////creat mesh and copy in Mesh * pMesh = new Mesh(); pMesh->init(); pMesh->copyVertexData(8, sizeof(Vertex), (void**)triangleData); pMesh->copyIndexData(36, sizeof(int), (void**)indices); Transform *t = new Transform(); t->setPosition(0.0f, 0.0f, 0.0f); //load textures and skybox material + Shaders SkyBox *material = new SkyBox(); material->init(); std::string vsPath = ASSET_PATH + SHADER_PATH + "/skyVS.glsl"; std::string fsPath = ASSET_PATH + SHADER_PATH + "/skyFS.glsl"; material->loadShader(vsPath, fsPath); std::string posZTexturename = ASSET_PATH + TEXTURE_PATH + "CloudyLightRaysFront2048.png"; std::string negZTexturename = ASSET_PATH + TEXTURE_PATH + "CloudyLightRaysBack2048.png"; std::string posXTexturename = ASSET_PATH + TEXTURE_PATH + "CloudyLightRaysLeft2048.png"; std::string negXTexturename = ASSET_PATH + TEXTURE_PATH + "CloudyLightRaysRight2048.png"; std::string posYTexturename = ASSET_PATH + TEXTURE_PATH + "CloudyLightRaysUp2048.png"; std::string negYTexturename = ASSET_PATH + TEXTURE_PATH + "CloudyLightRaysDown2048.png"; material->loadCubeTexture(posZTexturename, negZTexturename, posXTexturename, negXTexturename, posYTexturename, negYTexturename); //create gameobject but don't add to queue! skyBoxObject = new GameObject(); skyBoxObject->setMaterial(material); skyBoxObject->setTransform(t); skyBoxObject->setMesh(pMesh); GLenum error; do{ error = glGetError(); } while (error != GL_NO_ERROR); }
int main(int argc, char* argv[]) { // Load the mesh. Mesh mesh; H2DReader mloader; mloader.load("GAMM-channel.mesh", &mesh); // Perform initial mesh refinements. mesh.refine_towards_boundary(BDY_SOLID_WALL_BOTTOM, 1); for (int i = 0; i < INIT_REF_NUM; i++) mesh.refine_all_elements(); mesh.refine_towards_boundary(BDY_SOLID_WALL_BOTTOM, 1); // Initialize boundary condition types and spaces with default shapesets. L2Space<double>space_rho(&mesh, P_INIT); L2Space<double>space_rho_v_x(&mesh, P_INIT); L2Space<double>space_rho_v_y(&mesh, P_INIT); L2Space<double>space_e(&mesh, P_INIT); int ndof = Space<double>::get_num_dofs(Hermes::vector<Space<double>*>(&space_rho, &space_rho_v_x, &space_rho_v_y, &space_e)); info("ndof: %d", ndof); // Initialize solutions, set initial conditions. InitialSolutionEulerDensity prev_rho(&mesh, RHO_EXT); InitialSolutionEulerDensityVelX prev_rho_v_x(&mesh, RHO_EXT * V1_EXT); InitialSolutionEulerDensityVelY prev_rho_v_y(&mesh, RHO_EXT * V2_EXT); InitialSolutionEulerDensityEnergy prev_e(&mesh, QuantityCalculator::calc_energy(RHO_EXT, RHO_EXT * V1_EXT, RHO_EXT * V2_EXT, P_EXT, KAPPA)); // Numerical flux. OsherSolomonNumericalFlux num_flux(KAPPA); // Initialize weak formulation. EulerEquationsWeakFormImplicitMultiComponent wf(&num_flux, KAPPA, RHO_EXT, V1_EXT, V2_EXT, P_EXT, BDY_SOLID_WALL_BOTTOM, BDY_SOLID_WALL_TOP, BDY_INLET, BDY_OUTLET, &prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e, PRECONDITIONING); wf.set_time_step(time_step); // Initialize the FE problem. bool is_linear = false; DiscreteProblem<double> dp(&wf, Hermes::vector<Space<double>*>(&space_rho, &space_rho_v_x, &space_rho_v_y, &space_e)); // If the FE problem is in fact a FV problem. if(P_INIT == 0) dp.set_fvm(); // Project the initial solution on the FE space // in order to obtain initial vector for NOX. info("Projecting initial solution on the FE mesh."); double* coeff_vec = new double[Space<double>::get_num_dofs(Hermes::vector<Space<double>*>(&space_rho, &space_rho_v_x, &space_rho_v_y, &space_e))]; OGProjection<double>::project_global(Hermes::vector<Space<double>*>(&space_rho, &space_rho_v_x, &space_rho_v_y, &space_e), Hermes::vector<MeshFunction<double>*>(&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e), coeff_vec); // Filters for visualization of Mach number, pressure and entropy. MachNumberFilter Mach_number(Hermes::vector<MeshFunction<double>*>(&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e), KAPPA); PressureFilter pressure(Hermes::vector<MeshFunction<double>*>(&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e), KAPPA); EntropyFilter entropy(Hermes::vector<MeshFunction<double>*>(&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e), KAPPA, RHO_EXT, P_EXT); ScalarView<double> pressure_view("Pressure", new WinGeom(0, 0, 600, 300)); ScalarView<double> Mach_number_view("Mach number", new WinGeom(700, 0, 600, 300)); ScalarView<double> entropy_production_view("Entropy estimate", new WinGeom(0, 400, 600, 300)); /* ScalarView<double> s1("1", new WinGeom(0, 0, 600, 300)); ScalarView<double> s2("2", new WinGeom(700, 0, 600, 300)); ScalarView<double> s3("3", new WinGeom(0, 400, 600, 300)); ScalarView<double> s4("4", new WinGeom(700, 400, 600, 300)); */ // Initialize NOX solver. NoxSolver<double> solver(&dp, NOX_MESSAGE_TYPE); solver.set_ls_tolerance(NOX_LINEAR_TOLERANCE); solver.disable_abs_resid(); solver.set_conv_rel_resid(NOX_NONLINEAR_TOLERANCE); if(PRECONDITIONING) { RCP<Precond<double> > pc = rcp(new Preconditioners::MlPrecond<double>("sa")); solver.set_precond(pc); } int iteration = 0; double t = 0; for(t = 0.0; t < 3.0; t += time_step) { info("---- Time step %d, time %3.5f.", iteration++, t); OGProjection<double>::project_global(Hermes::vector<Space<double>*>(&space_rho, &space_rho_v_x, &space_rho_v_y, &space_e), Hermes::vector<MeshFunction<double>*>(&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e), coeff_vec); info("Assembling by DiscreteProblem, solving by NOX."); if (solver.solve(coeff_vec)) Solution<double>::vector_to_solutions(solver.get_sln_vector(), Hermes::vector<Space<double>*>(&space_rho, &space_rho_v_x, &space_rho_v_y, &space_e), Hermes::vector<Solution<double>*>(&prev_rho, &prev_rho_v_x, &prev_rho_v_y, &prev_e)); else error("NOX failed."); // Visualization. if((iteration - 1) % EVERY_NTH_STEP == 0) { // Hermes visualization. if(HERMES_VISUALIZATION) { Mach_number.reinit(); pressure.reinit(); entropy.reinit(); pressure_view.show(&pressure); entropy_production_view.show(&entropy); Mach_number_view.show(&Mach_number); /* s1.show(&prev_rho); s2.show(&prev_rho_v_x); s3.show(&prev_rho_v_y); s4.show(&prev_e); */ } // Output solution in VTK format. if(VTK_VISUALIZATION) { pressure.reinit(); Mach_number.reinit(); Linearizer<double> lin; char filename[40]; sprintf(filename, "pressure-%i.vtk", iteration - 1); lin.save_solution_vtk(&pressure, filename, "Pressure", false); sprintf(filename, "pressure-3D-%i.vtk", iteration - 1); lin.save_solution_vtk(&pressure, filename, "Pressure", true); sprintf(filename, "Mach number-%i.vtk", iteration - 1); lin.save_solution_vtk(&Mach_number, filename, "MachNumber", false); sprintf(filename, "Mach number-3D-%i.vtk", iteration - 1); lin.save_solution_vtk(&Mach_number, filename, "MachNumber", true); } } info("Number of nonlin iterations: %d (norm of residual: %g)", solver.get_num_iters(), solver.get_residual()); info("Total number of iterations in linsolver: %d (achieved tolerance in the last step: %g)", solver.get_num_lin_iters(), solver.get_achieved_tol()); } pressure_view.close(); entropy_production_view.close(); Mach_number_view.close(); /* s1.close(); s2.close(); s3.close(); s4.close(); */ return 0; }
int main(int argc, char* argv[]) { // Choose a Butcher's table or define your own. ButcherTable bt(butcher_table_type); // Load the mesh. Mesh mesh; H2DReader mloader; mloader.load("cathedral.mesh", &mesh); // Perform initial mesh refinements. for(int i = 0; i < INIT_REF_NUM; i++) mesh.refine_all_elements(); mesh.refine_towards_boundary(BDY_AIR, INIT_REF_NUM_BDY); mesh.refine_towards_boundary(BDY_GROUND, INIT_REF_NUM_BDY); // Enter boundary markers. BCTypes bc_types; bc_types.add_bc_dirichlet(Hermes::vector<std::string>(BDY_GROUND)); bc_types.add_bc_newton(BDY_AIR); // Enter Dirichlet boundary values. BCValues bc_values; bc_values.add_const(BDY_GROUND, TEMP_INIT); // Initialize an H1 space with default shapeset. H1Space space(&mesh, &bc_types, &bc_values, P_INIT); int ndof = Space::get_num_dofs(&space); info("ndof = %d.", ndof); // Previous time level solution (initialized by the external temperature). Solution u_prev_time(&mesh, TEMP_INIT); // Initialize weak formulation. WeakForm wf; wf.add_matrix_form(callback(stac_jacobian)); wf.add_vector_form(callback(stac_residual)); wf.add_matrix_form_surf(callback(bilinear_form_surf), BDY_AIR); wf.add_vector_form_surf(callback(linear_form_surf), BDY_AIR); // Project the initial condition on the FE space to obtain initial solution coefficient vector. info("Projecting initial condition to translate initial condition into a vector."); scalar* coeff_vec = new scalar[ndof]; OGProjection::project_global(&space, &u_prev_time, coeff_vec, matrix_solver); // Initialize the FE problem. bool is_linear = false; DiscreteProblem dp(&wf, &space, is_linear); // Initialize views. ScalarView Tview("Temperature", new WinGeom(0, 0, 450, 600)); //Tview.set_min_max_range(0,20); Tview.fix_scale_width(30); // Time stepping loop: double current_time = 0.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, tau = %g, stages: %d).", current_time, time_step, bt.get_size()); bool verbose = true; bool is_linear = true; if (!rk_time_step(current_time, time_step, &bt, coeff_vec, &dp, matrix_solver, verbose, is_linear)) { error("Runge-Kutta time step failed, try to decrease time step size."); } // Convert coeff_vec into a new time level solution. Solution::vector_to_solution(coeff_vec, &space, &u_prev_time); // Update time. current_time += time_step; // Show the new time level solution. char title[100]; sprintf(title, "Time %3.2f, exterior temperature %3.5f", current_time, temp_ext(current_time)); Tview.set_title(title); Tview.show(&u_prev_time); // Increase counter of time steps. ts++; } while (current_time < T_FINAL); // Cleanup. delete [] coeff_vec; // Wait for the view to be closed. View::wait(); return 0; }
void LightMesh::AddMesh(Mesh *m, Matrix3 basetm, ViewExp *vpt, BOOL buildVNorms) { //copy over the vert and face data vertsViewSpace.SetCount(m->numVerts); for (int i =0; i < m->numVerts; i++) vertsViewSpace[i] = m->verts[i]; vertsWorldSpace = vertsViewSpace; BOOL flip = basetm.Parity();//check to see if the mesh has been mirrored if so flip stuff; faces.SetCount(m->numFaces); for (i =0; i < m->numFaces; i++) { faces[i] = m->faces[i]; if (flip) { int a = faces[i].v[0]; int b = faces[i].v[1]; int c = faces[i].v[2]; faces[i].v[0] = c; faces[i].v[1] = b; faces[i].v[2] = a; } } toWorldSpace = basetm; toLocalSpace = Inverse(basetm); for (i =0; i < m->numVerts; i++) vertsWorldSpace[i] = vertsWorldSpace[i]*basetm; bb.Init(); //build vnorms and fnorms Mesh *mesh; mesh = m; Face *face; Point3 v0, v1, v2; // face = m->faces; face = faces.Addr(0); // fnorms.SetCount(m->getNumFaces()); GraphicsWindow *gw = vpt->getGW(); Matrix3 tm; vpt->GetAffineTM(tm); gw->setTransform(Matrix3(1)); Point3 *verts = vertsViewSpace.Addr(0); int vertCount = vertsViewSpace.Count(); for (i =0; i < vertCount; i++) { Point3 inPoint,outPoint; inPoint = *verts * basetm; DWORD flag = gw->transPoint(&inPoint, &outPoint); inPoint = inPoint * tm; *verts = outPoint ; (*verts).z = inPoint.z; bb += *verts; verts++; } // Compute face and vertex surface normals faceVisible.SetSize(m->getNumFaces()); faceVisible.ClearAll(); for (i = 0; i < m->getNumFaces(); i++, face++) { // Calculate the surface normal Point3 norm; v0 = vertsViewSpace[face->v[0]]; v1 = vertsViewSpace[face->v[1]]; v2 = vertsViewSpace[face->v[2]]; norm = (v1-v0)^(v2-v1); if (norm.z < 0.0f) { if (face->Hidden()) faceVisible.Set(i,FALSE); else faceVisible.Set(i,TRUE); } else faceVisible.Set(i,FALSE); } if (buildVNorms) { face = faces.Addr(0); Tab<int> normCount; normCount.SetCount(m->numVerts); vnorms.SetCount(m->numVerts); for (i = 0; i < m->numVerts; i++) { vnorms[i] = Point3(0.0f,0.0f,0.0f); normCount[i] = 0; } for (i = 0; i < mesh->getNumFaces(); i++, face++) { // Calculate the surface normal v0 = vertsWorldSpace[face->v[0]]; v1 = vertsWorldSpace[face->v[1]]; v2 = vertsWorldSpace[face->v[2]]; for (int j=0; j<3; j++) { vnorms[face->v[j]]+=Normalize((v1-v0)^(v2-v1)); normCount[face->v[j]]++; } } for (i = 0; i < m->numVerts; i++) { if (normCount[i]!=0) vnorms[i] = Normalize(vnorms[i]/(float)normCount[i]); } } else { vnorms.ZeroCount(); vnorms.Resize(0); } }
void VertexPaint::ModifyObject(TimeValue t, ModContext &mc, ObjectState * os, INode *node) { if (!os->obj->IsSubClassOf(triObjectClassID)) return; os->obj->ReadyChannelsForMod(GEOM_CHANNEL|TOPO_CHANNEL|VERTCOLOR_CHANNEL|TEXMAP_CHANNEL); TriObject *tobj = (TriObject*)os->obj; VertexPaintData *d = (VertexPaintData*)mc.localData; Mesh* mesh = &tobj->GetMesh(); if (mesh) { // We don't have any VColors yet, so we allocate the vcfaces // and set all vcolors to black (index 0) if (!mesh->vcFace) { mesh->setNumVCFaces(mesh->getNumFaces()); mesh->setNumVertCol(1); mesh->vertCol[0] = Color(0,0,0); for (int f=0; f<mesh->getNumFaces(); f++) { mesh->vcFace[f].t[0] = 0; mesh->vcFace[f].t[1] = 0; mesh->vcFace[f].t[2] = 0; } } if (!d) mc.localData = d = new VertexPaintData(tobj->GetMesh()); if (!d->GetMesh()) d->SetCache(*mesh); { MeshDelta md(*mesh); //MeshDelta mdc; //if(cache) mdc.InitToMesh(*cache); // If the incoming Mesh had no vertex colors, this will add a default map to start with. // The default map has the same topology as the Mesh (so one color per vertex), // with all colors set to white. if (!mesh->mapSupport(0)) md.AddVertexColors (); //if (cache && !cache->mapSupport(0)) mdc.AddVertexColors (); // We used two routines -- VCreate to add new map vertices, and FRemap to make the // existing map faces use the new verts. frFlags tell FRemap which vertices on a face // should be "remapped", and the ww array contains the new locations. VertColor nvc; int j; for (int v=0; v < d->GetNumColors(); v++) { ColorData cd = d->GetColorData(v); // Edition Mode ?? if(editMod == this) { nvc= Color(cd.color); // change color to view only monochromatic info for this channel; switch(_EditType) { case 0: nvc.y= nvc.z= nvc.x; nvc.y*= 0.7f; nvc.z*= 0.7f; break; case 1: nvc.x= nvc.z= nvc.y; nvc.x*= 0.7f; nvc.z*= 0.7f; break; case 2: nvc.x= nvc.y= nvc.z; nvc.x*= 0.7f; nvc.y*= 0.7f; break; } } else { // replace the VertexColor of the outgoing mesh nvc= Color(cd.color); } DWORD ww[3], frFlags; md.map->VCreate (&nvc); // increase the number of vcol's and set the vcfaces as well for(int i = 0 ; i < d->GetNVert(v).faces.Count() ; i++) { j = d->GetNVert(v).whichVertex[i]; frFlags = (1<<j); ww[j] = md.map->outVNum()-1; md.map->FRemap(d->GetNVert(v).faces[i], frFlags, ww); } } md.Apply(*mesh); } NotifyDependents(FOREVER, PART_VERTCOLOR, REFMSG_CHANGE); os->obj->UpdateValidity(VERT_COLOR_CHAN_NUM, Interval(t,t)); } }
Mesh Mesh::createCube(float width, float height, float depth) { Vector3f min(-width, -height, -depth); Vector3f max(width, height, depth); Mesh mesh; StaticFloat3* vertices = new StaticFloat3(); StaticFloat3* normals = new StaticFloat3(); StaticFloat2* uvs = new StaticFloat2 { { 0.0f, 0.0f}, { 1.0f, 0.0f}, { 1.0f, 1.0f}, { 0.0f, 1.0f}, { 0.0f, 0.0f}, { 1.0f, 0.0f}, { 1.0f, 1.0f}, { 0.0f, 1.0f}, }; StaticUInt* indices = new StaticUInt { 0, 1, 2, 0, 2, 3, 0, 3, 7, 0, 7, 4, 4, 7, 6, 4, 6, 5, 5, 6, 2, 5, 2, 1, 3, 2, 6, 3, 6, 7, 0, 4, 5, 0, 5, 1 }; vertices->getVector().push_back(Vector3f(min.x, min.y, max.z)); vertices->getVector().push_back(Vector3f(max.x, min.y, max.z)); //1 vertices->getVector().push_back(Vector3f(max.x, max.y, max.z)); //2 vertices->getVector().push_back(Vector3f(min.x, max.y, max.z)); //3 vertices->getVector().push_back(Vector3f(min.x, min.y, min.z)); //4 vertices->getVector().push_back(Vector3f(max.x, min.y, min.z)); //5 vertices->getVector().push_back(Vector3f(max.x, max.y, min.z)); //6 vertices->getVector().push_back(Vector3f(min.x, max.y, min.z)); //7 normals->getVector().push_back(Vector3f(min.x, min.y, max.z)); normals->getVector().push_back(Vector3f(max.x, min.y, max.z)); //1 normals->getVector().push_back(Vector3f(max.x, max.y, max.z)); //2 normals->getVector().push_back(Vector3f(min.x, max.y, max.z)); //3 normals->getVector().push_back(Vector3f(min.x, min.y, min.z)); //4 normals->getVector().push_back(Vector3f(max.x, min.y, min.z)); //5 normals->getVector().push_back(Vector3f(max.x, max.y, min.z)); //6 normals->getVector().push_back(Vector3f(min.x, max.y, min.z)); //7 //mesh->setIndexBuffer(&_indices); mesh.set(Vertex_Position, vertices); mesh.set(Vertex_Normal, normals); mesh.set(Vertex_TexCoord, uvs); mesh.addIndexBuffer(indices, PrimitiveSet_Triangles); return std::move(mesh); }
/* ------------------ 2D Meshing Functions ------------------------- */ DLL_HEADER void Ng_AddPoint_2D (Ng_Mesh * mesh, double * x) { Mesh * m = (Mesh*)mesh; m->AddPoint (Point3d (x[0], x[1], 0)); }