std::vector < Derived > lidarBoostEngine::lk_optical_flow( const MatrixBase<Derived>& I1, const MatrixBase<Derived> &I2, int win_sz) { //Instantiate optical flow matrices std::vector < Derived > uv(2); //Create masks Matrix2d robX, robY, robT; robX << -1, 1, -1, 1; robY << -1, -1, 1, 1; robT << -1, -1, -1, -1; Derived Ix, Iy, It, A, solutions, x_block, y_block, t_block; //Apply masks to images and average the result Ix = 0.5 * ( conv2d( I1, robX ) + conv2d( I2, robX ) ); Iy = 0.5 * ( conv2d( I1, robY ) + conv2d( I2, robY ) ); It = 0.5 * ( conv2d( I1, robT ) + conv2d( I2, robT ) ); uv[0] = Derived::Zero( I1.rows(), I1.cols() ); uv[1] = Derived::Zero( I1.rows(), I1.cols() ); int hw = win_sz/2; for( int i = hw+1; i < I1.rows()-hw; i++ ) { for ( int j = hw+1; j < I1.cols()-hw; j++ ) { //Take a small block of window size in the filtered images x_block = Ix.block( i-hw, j-hw, win_sz, win_sz); y_block = Iy.block( i-hw, j-hw, win_sz, win_sz); t_block = It.block( i-hw, j-hw, win_sz, win_sz); //Convert these blocks in vectors Map<Derived> A1( x_block.data(), win_sz*win_sz, 1); Map<Derived> A2( y_block.data(), win_sz*win_sz, 1); Map<Derived> B( t_block.data(), win_sz*win_sz, 1); //Organize the vectors in a matrix A = Derived( win_sz*win_sz, 2 ); A.block(0, 0, win_sz*win_sz, 1) = A1; A.block(0, 1, win_sz*win_sz, 1) = A2; //Solve the linear least square system solutions = (A.transpose() * A).ldlt().solve(A.transpose() * B); //Insert the solutions in the optical flow matrices uv[0](i, j) = solutions(0); uv[1](i, j) = solutions(1); } } return uv; }
int main(void){ int c = 0; for(int n = 1155; n < 1000000; ++n){ if(solutions(n) == 10){ ++c; } } printf("%i\n", c); }
bool solutions(int** a, int n, int col, vector<vector<string> > & result) { if (col >= n) { vector<string> res = printsolution(a, n); result.push_back(res); return true; } for (int i = 0; i < n; i++) { if (isSafe(a, n, i, col)) { a[i][col] = 1; solutions(a, n, col+1, result); a[i][col] = 0; } } return false; }
int main() { int max_p = 120; int max_s = 3; int i; int i_s; for (i = 10; i <= 1000; i++) { i_s = solutions(i); if (i_s > max_s) { max_s = i_s; max_p = i; } } printf("%d\n", max_p); return 0; }
vector<vector<string> > solveNQueens(int n) { vector<vector<string> > result; if (n == 0) return result; int **a = new int*[n]; for (int i = 0; i < n; i++) { a[i] = new int[n]; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = 0; } } solutions(a, n, 0, result); return result; }
Matrix<double> Cylinder::calculate_solutions(const NeuralNetwork& neural_network) const { IndependentParameters* independent_parameters_pointer = neural_network.get_independent_parameters_pointer(); const Vector<double> argument = independent_parameters_pointer->get_parameters(); double x = argument[0]; double y = argument[1]; Matrix<double> solutions(1, 1); if(pow(x,2) + pow(y,2) <= 1.0) { solutions[0][0] = 0.0; } else { solutions[0][0] = pow(x,2) + pow(y,2) - 1.0; } return(solutions); }
void SolveAmbiguity(yvector<COccurrence>& Occurrences, yvector<size_t>& res) { if (Occurrences.size() == 0) return; if (Occurrences.size() == 1) { res.push_back(0); return; } std::sort(Occurrences.begin(), Occurrences.end(), SortByRightBorderPredicate); yvector<CPeriodSolutionWeight> solutions(Occurrences.size()); for (size_t i = 0; i < Occurrences.size(); ++i) { const COccurrence& cur_occurrence = Occurrences[i]; const CPeriodSolutionWeight* best_overlapping_solution = NULL; const CPeriodSolutionWeight* best_non_overlapping_solution = NULL; for (int j = i - 1; j >= 0; --j) if (Occurrences[j].second <= cur_occurrence.first) //does not intersect { best_non_overlapping_solution = &(solutions[j]); break; } else if (best_overlapping_solution == NULL || *best_overlapping_solution < solutions[j]) best_overlapping_solution = &(solutions[j]); CPeriodSolutionWeight& cur_solution = solutions[i]; if (best_non_overlapping_solution == NULL) cur_solution.m_VirtualGroup.SetPair(cur_occurrence.first, cur_occurrence.first); else cur_solution = *best_non_overlapping_solution; // nasty copying! cur_solution.AddOccurrence(cur_occurrence, i); //if overlapped solution is still better if (best_overlapping_solution != NULL && cur_solution < *best_overlapping_solution) cur_solution = *best_overlapping_solution; // nasty copying again! } CPeriodSolutionWeight& best_solution = solutions.back(); res.swap(best_solution.m_Solution); }
int main(int argc, char* argv[]) { // Load the mesh. Mesh mesh; H2DReader mloader; mloader.load("reactor.mesh", &mesh); // Perform initial mesh refinements. for (int i = 0; i < INIT_REF_NUM; i++) mesh.refine_all_elements(); // Solution variables. Solution sln1, sln2, sln3, sln4; Solution iter1, iter2, iter3, iter4; Hermes::Tuple<Solution*> solutions(&sln1, &sln2, &sln3, &sln4); // Define initial conditions. info("Setting initial conditions."); iter1.set_const(&mesh, 1.00); iter2.set_const(&mesh, 1.00); iter3.set_const(&mesh, 1.00); iter4.set_const(&mesh, 1.00); // Enter boundary markers. BCTypes bc_types; bc_types.add_bc_neumann(BDY_SYM); bc_types.add_bc_newton(BDY_VACUUM); // Create H1 spaces with default shapesets. H1Space space1(&mesh, &bc_types, P_INIT_1); H1Space space2(&mesh, &bc_types, P_INIT_2); H1Space space3(&mesh, &bc_types, P_INIT_3); H1Space space4(&mesh, &bc_types, P_INIT_4); Hermes::Tuple<Space*> spaces(&space1, &space2, &space3, &space4); int ndof = Space::get_num_dofs(Hermes::Tuple<Space*>(&space1, &space2, &space3, &space4)); info("ndof = %d.", ndof); // Initialize views. ScalarView view1("Neutron flux 1", new WinGeom(0, 0, 320, 600)); ScalarView view2("Neutron flux 2", new WinGeom(350, 0, 320, 600)); ScalarView view3("Neutron flux 3", new WinGeom(700, 0, 320, 600)); ScalarView view4("Neutron flux 4", new WinGeom(1050, 0, 320, 600)); // Do not show meshes. view1.show_mesh(false); view1.set_3d_mode(true); view2.show_mesh(false); view2.set_3d_mode(true); view3.show_mesh(false); view3.set_3d_mode(true); view4.show_mesh(false); view4.set_3d_mode(true); // Initialize the weak formulation. WeakForm wf(4); wf.add_matrix_form(0, 0, callback(biform_0_0), HERMES_SYM); wf.add_matrix_form(1, 1, callback(biform_1_1), HERMES_SYM); wf.add_matrix_form(1, 0, callback(biform_1_0)); wf.add_matrix_form(2, 2, callback(biform_2_2), HERMES_SYM); wf.add_matrix_form(2, 1, callback(biform_2_1)); wf.add_matrix_form(3, 3, callback(biform_3_3), HERMES_SYM); wf.add_matrix_form(3, 2, callback(biform_3_2)); wf.add_vector_form(0, callback(liform_0), marker_core, Hermes::Tuple<MeshFunction*>(&iter1, &iter2, &iter3, &iter4)); wf.add_vector_form(1, callback(liform_1), marker_core, Hermes::Tuple<MeshFunction*>(&iter1, &iter2, &iter3, &iter4)); wf.add_vector_form(2, callback(liform_2), marker_core, Hermes::Tuple<MeshFunction*>(&iter1, &iter2, &iter3, &iter4)); wf.add_vector_form(3, callback(liform_3), marker_core, Hermes::Tuple<MeshFunction*>(&iter1, &iter2, &iter3, &iter4)); wf.add_matrix_form_surf(0, 0, callback(biform_surf_0_0), BDY_VACUUM); wf.add_matrix_form_surf(1, 1, callback(biform_surf_1_1), BDY_VACUUM); wf.add_matrix_form_surf(2, 2, callback(biform_surf_2_2), BDY_VACUUM); wf.add_matrix_form_surf(3, 3, callback(biform_surf_3_3), BDY_VACUUM); // Initialize the FE problem. bool is_linear = true; DiscreteProblem dp(&wf, spaces, is_linear); SparseMatrix* matrix = create_matrix(matrix_solver); Vector* rhs = create_vector(matrix_solver); Solver* solver = create_linear_solver(matrix_solver, matrix, rhs); if (matrix_solver == SOLVER_AZTECOO) { ((AztecOOSolver*) solver)->set_solver(iterative_method); ((AztecOOSolver*) solver)->set_precond(preconditioner); // Using default iteration parameters (see solver/aztecoo.h). } // Time measurement. TimePeriod cpu_time, solver_time; // Main power iteration loop: int iter = 1; bool done = false; bool rhs_only = false; solver->set_factorization_scheme(HERMES_REUSE_FACTORIZATION_COMPLETELY); do { info("------------ Power iteration %d:", iter); info("Assembling the stiffness matrix and right-hand side vector."); dp.assemble(matrix, rhs, rhs_only); /* // Testing the factorization reuse schemes for direct solvers. if (iter == 10) solver->set_factorization_scheme(HERMES_REUSE_MATRIX_REORDERING); if (iter == 20) solver->set_factorization_scheme(HERMES_REUSE_MATRIX_REORDERING_AND_SCALING); if (iter == 30) solver->set_factorization_scheme(HERMES_REUSE_FACTORIZATION_COMPLETELY); */ info("Solving the matrix problem by %s.", MatrixSolverNames[matrix_solver].c_str()); solver_time.tick(HERMES_SKIP); bool solved = solver->solve(); solver_time.tick(); if(solved) Solution::vector_to_solutions(solver->get_solution(), spaces, solutions); else error ("Matrix solver failed.\n"); // Show intermediate solutions. // view1.show(&sln1); // view2.show(&sln2); // view3.show(&sln3); // view4.show(&sln4); SimpleFilter source(source_fn, Hermes::Tuple<MeshFunction*>(&sln1, &sln2, &sln3, &sln4)); SimpleFilter source_prev(source_fn, Hermes::Tuple<MeshFunction*>(&iter1, &iter2, &iter3, &iter4)); // Compute eigenvalue. double k_new = k_eff * (integrate(&source, marker_core) / integrate(&source_prev, marker_core)); info("Largest eigenvalue: %.8g, rel. difference from previous it.: %g", k_new, fabs((k_eff - k_new) / k_new)); // Stopping criterion. if (fabs((k_eff - k_new) / k_new) < ERROR_STOP) done = true; // Update eigenvalue. k_eff = k_new; if (!done) { // Save solutions for the next iteration. iter1.copy(&sln1); iter2.copy(&sln2); iter3.copy(&sln3); iter4.copy(&sln4); // Don't need to reassemble the system matrix in further iterations, // only the rhs changes to reflect the progressively updated source. rhs_only = true; iter++; } } while (!done); // Time measurement. cpu_time.tick(); solver_time.tick(HERMES_SKIP); // Print timing information. verbose("Average solver time for one power iteration: %g s", solver_time.accumulated() / iter); // Clean up. delete matrix; delete rhs; delete solver; // Show solutions. view1.show(&sln1); view2.show(&sln2); view3.show(&sln3); view4.show(&sln4); // Skip visualization time. cpu_time.tick(HERMES_SKIP); // Print timing information. verbose("Total running time: %g s", cpu_time.accumulated()); // Wait for all views to be closed. View::wait(); return 0; }
void SweepOnepdm::BlockAndDecimate (SweepParams &sweepParams, SpinBlock& system, SpinBlock& newSystem, const bool &useSlater, const bool& dot_with_sys) { //mcheck("at the start of block and decimate"); // figure out if we are going forward or backwards dmrginp.guessgenT -> start(); bool forward = (system.get_sites() [0] == 0); SpinBlock systemDot; SpinBlock envDot; int systemDotStart, systemDotEnd; int systemDotSize = sweepParams.get_sys_add() - 1; if (forward) { systemDotStart = *system.get_sites().rbegin () + 1; systemDotEnd = systemDotStart + systemDotSize; } else { systemDotStart = system.get_sites() [0] - 1; systemDotEnd = systemDotStart - systemDotSize; } vector<int> spindotsites(2); spindotsites[0] = systemDotStart; spindotsites[1] = systemDotEnd; systemDot = SpinBlock(systemDotStart, systemDotEnd); SpinBlock environment, environmentDot, newEnvironment; int environmentDotStart, environmentDotEnd, environmentStart, environmentEnd; const int nexact = forward ? sweepParams.get_forward_starting_size() : sweepParams.get_backward_starting_size(); system.addAdditionalCompOps(); InitBlocks::InitNewSystemBlock(system, systemDot, newSystem, sweepParams.get_sys_add(), dmrginp.direct(), DISTRIBUTED_STORAGE, true, true); InitBlocks::InitNewEnvironmentBlock(environment, systemDot, newEnvironment, system, systemDot, sweepParams.get_sys_add(), sweepParams.get_env_add(), forward, dmrginp.direct(), sweepParams.get_onedot(), nexact, useSlater, true, true, true); SpinBlock big; newSystem.set_loopblock(true); system.set_loopblock(false); newEnvironment.set_loopblock(false); InitBlocks::InitBigBlock(newSystem, newEnvironment, big); const int nroots = dmrginp.nroots(); std::vector<Wavefunction> solutions(nroots); for(int i=0;i<nroots;++i) { StateInfo newInfo; solutions[i].LoadWavefunctionInfo (newInfo, newSystem.get_sites(), i); } #ifndef SERIAL mpi::communicator world; mpi::broadcast(world,solutions,0); #endif #ifdef SERIAL const int numprocs = 1; #endif #ifndef SERIAL const int numprocs = world.size(); #endif compute_onepdm(solutions, system, systemDot, newSystem, newEnvironment, big, numprocs); }
static void clear_solutions() { solutions().clear(); }
static void add_solution(const std::vector<unsigned int>& sol) { // add solution to static member solutions().insert(solutions().end(), sol.begin(), sol.end()); }
bool unique(const boost::array<int, 81>& plain_field) { std::list< boost::array<int, 81> > sols; return solutions(plain_field, 2, sols) == 1; }
Status CachedPlanStage::replan(PlanYieldPolicy* yieldPolicy, bool shouldCache) { // We're going to start over with a new plan. No need for only old buffered results. _results.clear(); // Clear out the working set. We'll start with a fresh working set. _ws->clear(); // Use the query planning module to plan the whole query. std::vector<QuerySolution*> rawSolutions; Status status = QueryPlanner::plan(*_canonicalQuery, _plannerParams, &rawSolutions); if (!status.isOK()) { return Status(ErrorCodes::BadValue, str::stream() << "error processing query: " << _canonicalQuery->toString() << " planner returned error: " << status.reason()); } OwnedPointerVector<QuerySolution> solutions(rawSolutions); // We cannot figure out how to answer the query. Perhaps it requires an index // we do not have? if (0 == solutions.size()) { return Status(ErrorCodes::BadValue, str::stream() << "error processing query: " << _canonicalQuery->toString() << " No query solutions"); } if (1 == solutions.size()) { // If there's only one solution, it won't get cached. Make sure to evict the existing // cache entry if requested by the caller. if (shouldCache) { PlanCache* cache = _collection->infoCache()->getPlanCache(); cache->remove(*_canonicalQuery); } PlanStage* newRoot; // Only one possible plan. Build the stages from the solution. verify(StageBuilder::build(_txn, _collection, *solutions[0], _ws, &newRoot)); _root.reset(newRoot); _replannedQs.reset(solutions.popAndReleaseBack()); return Status::OK(); } // Many solutions. Create a MultiPlanStage to pick the best, update the cache, // and so on. The working set will be shared by all candidate plans. _root.reset(new MultiPlanStage(_txn, _collection, _canonicalQuery, shouldCache)); MultiPlanStage* multiPlanStage = static_cast<MultiPlanStage*>(_root.get()); for (size_t ix = 0; ix < solutions.size(); ++ix) { if (solutions[ix]->cacheData.get()) { solutions[ix]->cacheData->indexFilterApplied = _plannerParams.indexFiltersApplied; } PlanStage* nextPlanRoot; verify(StageBuilder::build(_txn, _collection, *solutions[ix], _ws, &nextPlanRoot)); // Takes ownership of 'solutions[ix]' and 'nextPlanRoot'. multiPlanStage->addPlan(solutions.releaseAt(ix), nextPlanRoot, _ws); } // Delegate to the MultiPlanStage's plan selection facility. return multiPlanStage->pickBestPlan(yieldPolicy); }
int main(int argc, char* argv[]) { // Instantiate a class with global functions. Hermes2D hermes2d; // Load the mesh. Mesh mesh; H2DReader mloader; mloader.load("reactor.mesh", &mesh); // Perform initial mesh refinements. for (int i = 0; i < INIT_REF_NUM; i++) mesh.refine_all_elements(); // Solution variables. Solution sln1, sln2, sln3, sln4; Hermes::vector<Solution*> solutions(&sln1, &sln2, &sln3, &sln4); // Define initial conditions. info("Setting initial conditions."); Solution iter1, iter2, iter3, iter4; iter1.set_const(&mesh, 1.00); iter2.set_const(&mesh, 1.00); iter3.set_const(&mesh, 1.00); iter4.set_const(&mesh, 1.00); Hermes::vector<MeshFunction*> iterates(&iter1, &iter2, &iter3, &iter4); // Create H1 spaces with default shapesets. H1Space space1(&mesh, P_INIT_1); H1Space space2(&mesh, P_INIT_2); H1Space space3(&mesh, P_INIT_3); H1Space space4(&mesh, P_INIT_4); Hermes::vector<Space*> spaces(&space1, &space2, &space3, &space4); int ndof = Space::get_num_dofs(spaces); info("ndof = %d.", ndof); // Initialize views. ScalarView view1("Neutron flux 1", new WinGeom(0, 0, 320, 600)); ScalarView view2("Neutron flux 2", new WinGeom(350, 0, 320, 600)); ScalarView view3("Neutron flux 3", new WinGeom(700, 0, 320, 600)); ScalarView view4("Neutron flux 4", new WinGeom(1050, 0, 320, 600)); // Do not show meshes. view1.show_mesh(false); view1.set_3d_mode(true); view2.show_mesh(false); view2.set_3d_mode(true); view3.show_mesh(false); view3.set_3d_mode(true); view4.show_mesh(false); view4.set_3d_mode(true); // Load physical data of the problem for the 4 energy groups. MaterialPropertyMaps matprop(4); matprop.set_D(D); matprop.set_Sigma_r(Sr); matprop.set_Sigma_s(Ss); matprop.set_Sigma_s_nnz_structure(Ss_nnz); matprop.set_Sigma_a(Sa); matprop.set_Sigma_f(Sf); matprop.set_nu(nu); matprop.set_chi(chi); matprop.validate(); std::cout << matprop; // Initialize the weak formulation. CustomWeakForm wf(matprop, iterates, k_eff, bdy_vacuum); // Initialize the FE problem. DiscreteProblem dp(&wf, spaces); SparseMatrix* matrix = create_matrix(matrix_solver); Vector* rhs = create_vector(matrix_solver); Solver* solver = create_linear_solver(matrix_solver, matrix, rhs); if (matrix_solver == SOLVER_AZTECOO) { ((AztecOOSolver*) solver)->set_solver(iterative_method); ((AztecOOSolver*) solver)->set_precond(preconditioner); // Using default iteration parameters (see solver/aztecoo.h). } // Time measurement. TimePeriod cpu_time, solver_time; // Initial coefficient vector for the Newton's method. scalar* coeff_vec = new scalar[ndof]; // Force the Jacobian assembling in the first iteration. bool Jacobian_changed = true; // In the following iterations, Jacobian will not be changing; its LU factorization // may be reused. solver->set_factorization_scheme(HERMES_REUSE_FACTORIZATION_COMPLETELY); // Main power iteration loop: int it = 1; bool done = false; do { info("------------ Power iteration %d:", it); info("Newton's method (matrix problem solved by %s).", MatrixSolverNames[matrix_solver].c_str()); memset(coeff_vec, 0.0, ndof*sizeof(scalar)); //TODO: Why it doesn't work without zeroing coeff_vec in each iteration? solver_time.tick(HERMES_SKIP); if (!hermes2d.solve_newton(coeff_vec, &dp, solver, matrix, rhs, Jacobian_changed, 1e-8, 10, true)) error("Newton's iteration failed."); solver_time.tick(); Solution::vector_to_solutions(solver->get_solution(), spaces, solutions); // Show intermediate solutions. view1.show(&sln1); view2.show(&sln2); view3.show(&sln3); view4.show(&sln4); // Compute eigenvalue. SourceFilter source(solutions, matprop); SourceFilter source_prev(iterates, matprop); double k_new = k_eff * (integrate(&source, core) / integrate(&source_prev, core)); info("Largest eigenvalue: %.8g, rel. difference from previous it.: %g", k_new, fabs((k_eff - k_new) / k_new)); // Stopping criterion. if (fabs((k_eff - k_new) / k_new) < ERROR_STOP) done = true; // Update eigenvalue. k_eff = k_new; wf.update_keff(k_eff); if (!done) { // Save solutions for the next iteration. iter1.copy(&sln1); iter2.copy(&sln2); iter3.copy(&sln3); iter4.copy(&sln4); // Don't need to reassemble the system matrix in further iterations, // only the rhs changes to reflect the progressively updated source. Jacobian_changed = false; it++; } } while (!done); delete [] coeff_vec; // Time measurement. cpu_time.tick(); solver_time.tick(HERMES_SKIP); // Print timing information. verbose("Average solver time for one power iteration: %g s", solver_time.accumulated() / it); // Clean up. delete matrix; delete rhs; delete solver; // Show solutions. view1.show(&sln1); view2.show(&sln2); view3.show(&sln3); view4.show(&sln4); // Skip visualization time. cpu_time.tick(HERMES_SKIP); // Print timing information. verbose("Total running time: %g s", cpu_time.accumulated()); // Wait for all views to be closed. View::wait(); return 0; }
//_________________________________________________________ void UserAnalysis() { // Debug a particular event. Int_t eventToDebug = -1; if (jsf->GetEventNumber() == eventToDebug) { gDEBUG = kTRUE; cerr << "------------------------------------------" << endl; cerr << "Event " << jsf->GetEventNumber(); cerr << endl; } else { gDEBUG = kFALSE; } Char_t msg[60]; // Analysis starts here. Float_t selid = -0.5; hStat->Fill(++selid); if ( Ngoods == 0 ) strcpy(&cutName[(Int_t)selid][0],"No cut"); // Get event buffer and make combined tracks accessible. JSFSIMDST *sds = (JSFSIMDST*)jsf->FindModule("JSFSIMDST"); JSFSIMDSTBuf *evt = (JSFSIMDSTBuf*)sds->EventBuf(); Int_t ntrks = evt->GetNLTKCLTracks(); // No. of tracks TObjArray *trks = evt->GetLTKCLTracks(); // combined tracks ANL4DVector qsum; TObjArray tracks(500); tracks.SetOwner(); // Select good tracks fNtracks = 0; for ( Int_t i = 0; i < ntrks; i++ ) { JSFLTKCLTrack *t = (JSFLTKCLTrack*)trks->UncheckedAt(i); if ( t->GetE() > xEtrack ) { ANL4DVector *qt = new ANL4DVector(t->GetPV()); tracks.Add(qt); // track 4-momentum qsum += *qt; // total 4-momentum fNtracks++; } // *qt stays. } // Cut on No. of tracks. hNtracks->Fill(fNtracks); if ( fNtracks < xNtracks ) return; hStat->Fill(++selid); if ( Ngoods == 0 ) { sprintf(msg,"N_tracks > %g",xNtracks); strcpy(&cutName[(Int_t)selid][0],msg); } fEvis = qsum.E(); // E_vis fPt = qsum.GetPt(); // P_t fPl = qsum.Pz(); // P_l // Cut on Evis. hEvis->Fill(fEvis); if ( fEvis < xEvis ) return; hStat->Fill(++selid); if ( Ngoods == 0 ) { sprintf(msg,"E_vis > %g",xEvis); strcpy(&cutName[(Int_t)selid][0],msg); } // Cut on Pt. hPt->Fill(fPt); if ( fPt < xPt ) return; hStat->Fill(++selid); if ( Ngoods == 0 ) { sprintf(msg,"Pt > %g",xPt); strcpy(&cutName[(Int_t)selid][0],msg); } // Cut on Pl. if ( TMath::Abs(fPl) > xPl ) return; hStat->Fill(++selid); if ( Ngoods == 0 ) { sprintf(msg,"|Pl| <= %g",xPl); strcpy(&cutName[(Int_t)selid][0],msg); } // Find jets. fYcut = xYcut; ANLJadeEJetFinder jclust(fYcut); jclust.Initialize(tracks); jclust.FindJets(); fYcut = jclust.GetYcut(); fNjets = jclust.GetNjets(); // Cut on No. of jets. hNjets->Fill(fNjets); if ( fNjets < xNjets ) return; hStat->Fill(++selid); if ( Ngoods == 0 ) { sprintf(msg,"Njets >= %i for Ycut = %g",xNjets,xYcut); strcpy(&cutName[(Int_t)selid][0],msg); } // Now force the event to be xNjets. jclust.ForceNJets(xNjets); fNjets = jclust.GetNjets(); fYcut = jclust.GetYcut(); // Make sure that No. of jets is xNjets. if ( fNjets != xNjets ) return; hStat->Fill(++selid); if ( Ngoods == 0 ) { sprintf(msg,"Njets = %i",xNjets); strcpy(&cutName[(Int_t)selid][0],msg); } // Loop over jets and decide Ejet_min and |cos(theta_j)|_max. TObjArray &jets = jclust.GetJets(); // jets is an array of ANLJet's TIter nextjet(&jets); // and nextjet is an iterator for it ANLJet *jetp; Double_t ejetmin = 999999.; Double_t cosjmax = 0.; while ((jetp = (ANLJet *)nextjet())) { ANLJet &jet = *jetp; if (gDEBUG && kFALSE) jet.DebugPrint(); Double_t ejet = jet().E(); if (ejet < ejetmin) ejetmin = ejet; hEjet->Fill(ejet); // Ejet Double_t cosj = jet.CosTheta(); if (TMath::Abs(cosj) > TMath::Abs(cosjmax)) cosjmax = cosj; hCosjet->Fill(cosj); // cos(theta_jet) } // Cut on Ejet_min. if ( ejetmin < xEjet ) return; hStat->Fill(++selid); if ( Ngoods == 0 ) { sprintf(msg,"Ejet > %g",xEjet); strcpy(&cutName[(Int_t)selid][0],msg); } // Cut on |cos(theta_j)|_max. if ( TMath::Abs(cosjmax) > xCosjet ) return; hStat->Fill(++selid); if ( Ngoods == 0 ) { sprintf(msg,"|cos(theta_j)| <= %g",xCosjet); strcpy(&cutName[(Int_t)selid][0],msg); } // Find W candidates in given mass windows. // Avoid using indices since there might be empty slots. TObjArray solutions(10); solutions.SetOwner(); ANLPairCombiner w1candidates(jets,jets); ANLPairCombiner *w2candidp = 0; if (gDEBUG) { cerr << "------------------------------------------" << endl; cerr << "- w1candidates:" << endl; w1candidates.DebugPrint(); } ANLPair *w1p, *w2p; while ((w1p = (ANLPair *)w1candidates())) { w2candidp = 0; ANLPair &w1 = *w1p; Double_t w1mass = w1().GetMass(); if (TMath::Abs(w1mass - kMassW) > xM2j) continue; // w1 candidate found w1.LockChildren(); // now lock w1 daughters w2candidp = new ANLPairCombiner(w1candidates); // w2 after w1 ANLPairCombiner &w2candidates = *w2candidp; while ((w2p = (ANLPair *)w2candidates())) { ANLPair &w2 = *w2p; if (w2.IsLocked()) continue; // skip if locked Double_t w2mass = w2().GetMass(); if (TMath::Abs(w2mass - kMassW) > xM2j) continue; // w2 candidate found Double_t chi2 = TMath::Power((w1mass - kMassW)/kSigmaMw,2.) + TMath::Power((w2mass - kMassW)/kSigmaMw,2.); solutions.Add(new ANLPair(w1p,w2p,chi2)); // hMw1Mw2->Fill(w1mass,w2mass,1.0); } if (w2candidp) delete w2candidp; w1.UnlockChildren(); } // Cut on No. of solutions. if ( !solutions.GetEntries() ) return; hStat->Fill(++selid); if ( Ngoods == 0 ) { sprintf(msg,"|m_jj - m_W| <= %g",xM2j); strcpy(&cutName[(Int_t)selid][0],msg); } if (gDEBUG) { cerr << "------------------------------------------" << endl; cerr << "- w1candidates after 1:" << endl; w1candidates.DebugPrint(); } // Cut on cos(theta_W). TIter nextsol(&solutions); ANLPair *sol; while ((sol = (ANLPair *)nextsol())) { ANL4DVector &ww1 = *(ANL4DVector *)(*sol)[0]; ANL4DVector &ww2 = *(ANL4DVector *)(*sol)[1]; Double_t ew1 = ww1.E(); Double_t ew2 = ww2.E(); hEw1Ew2->Fill(ew1,ew2,1.0); Double_t cosw1 = ww1.CosTheta(); Double_t cosw2 = ww2.CosTheta(); hCosw1Cosw2->Fill(cosw1,cosw2,1.0); if (TMath::Abs(cosw1) > xCosw || TMath::Abs(cosw2) > xCosw) { solutions.Remove(sol); delete sol; } } if ( !solutions.GetEntries() ) return; hStat->Fill(++selid); if ( Ngoods == 0 ) { sprintf(msg,"|cos(theta_w)| <= %g",xCosw); strcpy(&cutName[(Int_t)selid][0],msg); } if (gDEBUG) { cerr << "------------------------------------------" << endl; cerr << "- w1candidates after 2:" << endl; w1candidates.DebugPrint(); } // Cut on Acop. nextsol.Reset(); while ((sol = (ANLPair *)nextsol())) { ANL4DVector &www1 = *(ANL4DVector *)(*sol)[0]; ANL4DVector &www2 = *(ANL4DVector *)(*sol)[1]; Double_t acop = www1.Acop(www2); hAcop->Fill(acop); if (acop < xAcop) { solutions.Remove(sol); delete sol; } } if ( !solutions.GetEntries() ) return; hStat->Fill(++selid); if ( Ngoods == 0 ) { sprintf(msg,"Acop > %g",xAcop); strcpy(&cutName[(Int_t)selid][0],msg); } if (gDEBUG) { cerr << "------------------------------------------" << endl; cerr << "- w1candidates after 3:" << endl; w1candidates.DebugPrint(); } // ------------------------ // End of event selection // ------------------------ if ( Ngoods == 0 ) { selid++; sprintf(msg,"END"); strcpy(&cutName[(Int_t)selid][0],msg); } Ngoods++; cerr << "------------------------------------------" << endl << "Event " << jsf->GetEventNumber() << ": Number of solutions = " << solutions.GetEntries() << endl << "------------------------------------------" << endl; // Sort the solutions in the ascending order of chi2 vlues. solutions.Sort(); // Hists and plots for selected events. if (gDEBUG && kFALSE) { Int_t nj = 0; nextjet.Reset(); while ((jetp = (ANLJet *)nextjet())) { cerr << "------" << endl << "Jet " << ++nj << endl << "------" << endl; jetp->DebugPrint(); } } hNsols->Fill(solutions.GetEntries()); hEvisPl->Fill(fEvis,fPl,1.); nextsol.Reset(); Int_t nsols = 0; while ((sol = (ANLPair *)nextsol())) { if ( nsols++ ) break; // choose the best ANL4DVector &wwww1 = *(ANL4DVector *)(*sol)[0]; ANL4DVector &wwww2 = *(ANL4DVector *)(*sol)[1]; Double_t chi2 = sol->GetQuality(); Double_t w1mass = wwww1.GetMass(); Double_t w2mass = wwww2.GetMass(); hChi2->Fill(chi2); hMw1Mw2->Fill(w1mass,w2mass,1.0); } return; }
int main(int argc, char* argv[]) { // Load the mesh. Mesh mesh; MeshReaderH2D mloader; mloader.load(mesh_file.c_str(), &mesh); // Perform initial mesh refinements. for (int i = 0; i < INIT_REF_NUM; i++) mesh.refine_all_elements(); // Solution variables. Solution<double> sln1, sln2, sln3, sln4; Hermes::vector<Solution<double>*> solutions(&sln1, &sln2, &sln3, &sln4); // Define initial conditions. Hermes::Mixins::Loggable::Static::info("Setting initial conditions."); ConstantSolution<double> iter1(&mesh, 1.00), iter2(&mesh, 1.00), iter3(&mesh, 1.00), iter4(&mesh, 1.00); Hermes::vector<MeshFunction<double>*> iterates(&iter1, &iter2, &iter3, &iter4); // Create H1 spaces with default shapesets. H1Space<double> space1(&mesh, P_INIT_1); H1Space<double> space2(&mesh, P_INIT_2); H1Space<double> space3(&mesh, P_INIT_3); H1Space<double> space4(&mesh, P_INIT_4); Hermes::vector<const Space<double>* > spaces(&space1, &space2, &space3, &space4); int ndof = Space<double>::get_num_dofs(spaces); Hermes::Mixins::Loggable::Static::info("ndof = %d", ndof); // Initialize views. ScalarView view1("Neutron flux 1", new WinGeom(0, 0, 320, 600)); ScalarView view2("Neutron flux 2", new WinGeom(350, 0, 320, 600)); ScalarView view3("Neutron flux 3", new WinGeom(700, 0, 320, 600)); ScalarView view4("Neutron flux 4", new WinGeom(1050, 0, 320, 600)); // Do not show meshes, set 3D mode. view1.show_mesh(false); view1.set_3d_mode(true); view2.show_mesh(false); view2.set_3d_mode(true); view3.show_mesh(false); view3.set_3d_mode(true); view4.show_mesh(false); view4.set_3d_mode(true); // Load physical data of the problem for the 4 energy groups. Hermes::Hermes2D::WeakFormsNeutronics::Multigroup::MaterialProperties::Diffusion::MaterialPropertyMaps matprop(4); matprop.set_D(D); matprop.set_Sigma_r(Sr); matprop.set_Sigma_s(Ss); matprop.set_Sigma_a(Sa); matprop.set_Sigma_f(Sf); matprop.set_nu(nu); matprop.set_chi(chi); matprop.validate(); // Printing table of material properties. std::cout << matprop; // Initialize the weak formulation. CustomWeakForm wf(matprop, iterates, k_eff, bdy_vacuum); // Initialize the FE problem. DiscreteProblem<double> dp(&wf, spaces); // Initialize Newton solver. NewtonSolver<double> newton(&dp); // Time measurement. Hermes::Mixins::TimeMeasurable cpu_time; // Main power iteration loop: int it = 1; bool done = false; do { Hermes::Mixins::Loggable::Static::info("------------ Power iteration %d:", it); Hermes::Mixins::Loggable::Static::info("Newton's method."); // Perform Newton's iteration. try { newton.set_newton_max_iter(NEWTON_MAX_ITER); newton.set_newton_tol(NEWTON_TOL); newton.solve_keep_jacobian(); } catch(Hermes::Exceptions::Exception e) { e.printMsg(); throw Hermes::Exceptions::Exception("Newton's iteration failed."); } // Debug. //printf("\n=================================================\n"); //for (int d = 0; d < ndof; d++) printf("%g ", newton.get_sln_vector()[d]); // Translate the resulting coefficient vector into a Solution. Solution<double>::vector_to_solutions(newton.get_sln_vector(), spaces, solutions); // Show intermediate solutions. view1.show(&sln1); view2.show(&sln2); view3.show(&sln3); view4.show(&sln4); // Compute eigenvalue. SourceFilter source(solutions, &matprop, core); SourceFilter source_prev(iterates, &matprop, core); double k_new = k_eff * (integrate(&source, core) / integrate(&source_prev, core)); Hermes::Mixins::Loggable::Static::info("Largest eigenvalue: %.8g, rel. difference from previous it.: %g", k_new, fabs((k_eff - k_new) / k_new)); // Stopping criterion. if (fabs((k_eff - k_new) / k_new) < ERROR_STOP) done = true; // Update eigenvalue. k_eff = k_new; wf.update_keff(k_eff); if (!done) { // Save solutions for the next iteration. iter1.copy(&sln1); iter2.copy(&sln2); iter3.copy(&sln3); iter4.copy(&sln4); it++; } } while (!done); // Time measurement. cpu_time.tick(); // Show solutions. view1.show(&sln1); view2.show(&sln2); view3.show(&sln3); view4.show(&sln4); // Skip visualization time. cpu_time.tick(Hermes::Mixins::TimeMeasurable::HERMES_SKIP); // Print timing information. Hermes::Mixins::Loggable::Static::info("Total running time: %g s", cpu_time.accumulated()); // Wait for all views to be closed. View::wait(); return 0; }
Status CachedPlanStage::replan(PlanYieldPolicy* yieldPolicy, bool shouldCache) { // We're going to start over with a new plan. Clear out info from our old plan. _results.clear(); _ws->clear(); _children.clear(); // Use the query planning module to plan the whole query. std::vector<QuerySolution*> rawSolutions; Status status = QueryPlanner::plan(*_canonicalQuery, _plannerParams, &rawSolutions); if (!status.isOK()) { return Status(ErrorCodes::BadValue, str::stream() << "error processing query: " << _canonicalQuery->toString() << " planner returned error: " << status.reason()); } OwnedPointerVector<QuerySolution> solutions(rawSolutions); // We cannot figure out how to answer the query. Perhaps it requires an index // we do not have? if (0 == solutions.size()) { return Status(ErrorCodes::BadValue, str::stream() << "error processing query: " << _canonicalQuery->toString() << " No query solutions"); } if (1 == solutions.size()) { // If there's only one solution, it won't get cached. Make sure to evict the existing // cache entry if requested by the caller. if (shouldCache) { PlanCache* cache = _collection->infoCache()->getPlanCache(); cache->remove(*_canonicalQuery); } PlanStage* newRoot; // Only one possible plan. Build the stages from the solution. verify(StageBuilder::build( getOpCtx(), _collection, *_canonicalQuery, *solutions[0], _ws, &newRoot)); _children.emplace_back(newRoot); _replannedQs.reset(solutions.popAndReleaseBack()); LOG(1) << "Replanning of query resulted in single query solution, which will not be cached. " << _canonicalQuery->toStringShort() << " plan summary after replan: " << Explain::getPlanSummary(child().get()) << " previous cache entry evicted: " << (shouldCache ? "yes" : "no"); return Status::OK(); } // Many solutions. Create a MultiPlanStage to pick the best, update the cache, // and so on. The working set will be shared by all candidate plans. auto cachingMode = shouldCache ? MultiPlanStage::CachingMode::AlwaysCache : MultiPlanStage::CachingMode::NeverCache; _children.emplace_back( new MultiPlanStage(getOpCtx(), _collection, _canonicalQuery, cachingMode)); MultiPlanStage* multiPlanStage = static_cast<MultiPlanStage*>(child().get()); for (size_t ix = 0; ix < solutions.size(); ++ix) { if (solutions[ix]->cacheData.get()) { solutions[ix]->cacheData->indexFilterApplied = _plannerParams.indexFiltersApplied; } PlanStage* nextPlanRoot; verify(StageBuilder::build( getOpCtx(), _collection, *_canonicalQuery, *solutions[ix], _ws, &nextPlanRoot)); // Takes ownership of 'solutions[ix]' and 'nextPlanRoot'. multiPlanStage->addPlan(solutions.releaseAt(ix), nextPlanRoot, _ws); } // Delegate to the MultiPlanStage's plan selection facility. Status pickBestPlanStatus = multiPlanStage->pickBestPlan(yieldPolicy); if (!pickBestPlanStatus.isOK()) { return pickBestPlanStatus; } LOG(1) << "Replanning " << _canonicalQuery->toStringShort() << " resulted in plan with summary: " << Explain::getPlanSummary(child().get()) << ", which " << (shouldCache ? "has" : "has not") << " been written to the cache"; return Status::OK(); }
int main(int argc, char* argv[]) { // Load the mesh. MeshSharedPtr mesh(new Mesh), mesh1(new Mesh); if (USE_XML_FORMAT == true) { MeshReaderH2DXML mloader; Hermes::Mixins::Loggable::Static::info("Reading mesh in XML format."); mloader.load("square.xml", mesh); } else { MeshReaderH2D mloader; Hermes::Mixins::Loggable::Static::info("Reading mesh in original format."); mloader.load("square.mesh", mesh); } // Perform uniform mesh refinement. int refinement_type = 0; for (int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements(refinement_type); // Show mesh. MeshView mv("Mesh", new WinGeom(0, 0, 580, 400)); mv.show(mesh); // Exact lambda MeshFunctionSharedPtr<double> exact_lambda(new ExactSolutionLambda(mesh,E,nu)); ScalarView viewLam("lambda [Pa]", new WinGeom(0, 460, 530, 350)); viewLam.show_mesh(false); viewLam.show(exact_lambda); // Exact lambda MeshFunctionSharedPtr<double> exact_mu(new ExactSolutionMu(mesh,E,nu)); ScalarView viewMu("mu [Pa]", new WinGeom(550, 460, 530, 350)); viewMu.show_mesh(false); viewMu.show(exact_mu); // Initialize boundary conditions. DefaultEssentialBCConst<double> disp_bot_top_x(Hermes::vector<std::string>("Bottom","Top"), 0.0); DefaultEssentialBCConst<double> disp_bot_y("Bottom", 0.0); DefaultEssentialBCConst<double> disp_top_y("Top", 0.1); EssentialBCs<double> bcs_x(&disp_bot_top_x); EssentialBCs<double> bcs_y(Hermes::vector<EssentialBoundaryCondition<double> *>(&disp_bot_y, &disp_top_y)); // Create x- and y- displacement space using the default H1 shapeset. SpaceSharedPtr<double> u1_space(new H1Space<double>(mesh, &bcs_x, P_INIT)); SpaceSharedPtr<double> u2_space(new H1Space<double>(mesh, &bcs_y, P_INIT)); Hermes::vector<SpaceSharedPtr<double> > spaces(u1_space, u2_space); int ndof = Space<double>::get_num_dofs(spaces); Hermes::Mixins::Loggable::Static::info("ndof = %d", ndof); // Initialize the weak formulation. CustomWeakFormLinearElasticity wf(E, nu, &lambdaFun, &muFun, rho*g1, "Top", f0, f1); // Initialize Newton solver. NewtonSolver<double> newton(&wf, spaces); newton.set_verbose_output(true); // Perform Newton's iteration. try { newton.solve(); } catch(std::exception& e) { std::cout << e.what(); Hermes::Mixins::Loggable::Static::info("Newton's iteration failed."); } // Translate the resulting coefficient vector into the Solution sln. MeshFunctionSharedPtr<double> u1_sln(new Solution<double>), u2_sln(new Solution<double>); Hermes::vector<MeshFunctionSharedPtr<double> > solutions(u1_sln, u2_sln); Solution<double>::vector_to_solutions(newton.get_sln_vector(), spaces, solutions); // Visualize the solution. ScalarView view("Von Mises stress [Pa]", new WinGeom(590, 0, 700, 400)); // First Lame constant. double lambda = (E * nu) / ((1 + nu) * (1 - 2*nu)); // Second Lame constant. double mu = E / (2*(1 + nu)); MeshFunctionSharedPtr<double> stress(new VonMisesFilter(solutions, lambda, mu)); MeshFunctionSharedPtr<double> S11(new CustomFilterS11(solutions, &muFun, &lambdaFun)); MeshFunctionSharedPtr<double> S12(new CustomFilterS12(solutions, mu)); MeshFunctionSharedPtr<double> S22(new CustomFilterS22(solutions, mu, lambda)); view.show_mesh(false); view.show(stress, HERMES_EPS_HIGH, H2D_FN_VAL_0, u1_sln, u2_sln, 1.0); ScalarView viewS11("S11 [Pa]", new WinGeom(0, 260, 530, 350)); viewS11.show_mesh(false); viewS11.show(S11, HERMES_EPS_HIGH, H2D_FN_VAL_0, u1_sln, u2_sln, 1.0); ScalarView viewS12("S12 [Pa]", new WinGeom(540, 260, 530, 350)); viewS12.show_mesh(false); viewS12.show(S12, HERMES_EPS_HIGH, H2D_FN_VAL_0, u1_sln, u2_sln, 1.0); ScalarView viewS22("S22 [Pa]", new WinGeom(1080, 260, 530, 350)); viewS22.show_mesh(false); viewS22.show(S22, HERMES_EPS_HIGH, H2D_FN_VAL_0, u1_sln, u2_sln, 1.0); // Wait for the view to be closed. View::wait(); return 0; }