void IBFEPostProcessor::interpolateVariables(const double data_time) { Pointer<PatchHierarchy<NDIM> > hierarchy = d_fe_data_manager->getPatchHierarchy(); const std::pair<int, int> patch_level_range = d_fe_data_manager->getPatchLevels(); const int coarsest_ln = patch_level_range.first; const int finest_ln = patch_level_range.second - 1; const unsigned int num_eulerian_vars = d_scalar_interp_var_systems.size(); // Set up Eulerian scratch space and fill ghost cell values. Pointer<RefineAlgorithm<NDIM> > refine_alg = new RefineAlgorithm<NDIM>(); Pointer<RefineOperator<NDIM> > refine_op = NULL; std::set<int> scratch_idxs; for (unsigned int k = 0; k < num_eulerian_vars; ++k) { int& data_idx = d_scalar_interp_data_idxs[k]; int& scratch_idx = d_scalar_interp_scratch_idxs[k]; if (data_idx < 0 || scratch_idx < 0) { TBOX_ASSERT(data_idx < 0 || scratch_idx < 0); VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase(); Pointer<hier::Variable<NDIM> > data_var = d_scalar_interp_vars[k]; Pointer<VariableContext> data_ctx = d_scalar_interp_ctxs[k]; data_idx = var_db->mapVariableAndContextToIndex(data_var, data_ctx); TBOX_ASSERT(data_idx >= 0); Pointer<VariableContext> scratch_ctx = var_db->getContext(d_name + "::SCRATCH"); const FEDataManager::InterpSpec& interp_spec = d_scalar_interp_specs[k]; const int ghost_width = LEInteractor::getMinimumGhostWidth(interp_spec.kernel_fcn); scratch_idx = var_db->registerVariableAndContext(data_var, scratch_ctx, ghost_width); scratch_idxs.insert(scratch_idx); } refine_alg->registerRefine(scratch_idx, data_idx, scratch_idx, refine_op); } CartExtrapPhysBdryOp refine_phys_bdry_op(scratch_idxs); for (int ln = coarsest_ln; ln <= finest_ln; ++ln) { Pointer<PatchLevel<NDIM> > level = hierarchy->getPatchLevel(ln); for (unsigned int k = 0; k < num_eulerian_vars; ++k) { const int scratch_idx = d_scalar_interp_scratch_idxs[k]; if (!level->checkAllocated(scratch_idx)) level->allocatePatchData(scratch_idx, data_time); } refine_alg->createSchedule(level, ln - 1, hierarchy, &refine_phys_bdry_op) ->fillData(data_time); } // Interpolate variables. NumericVector<double>* X_ghost_vec = d_fe_data_manager->buildGhostedCoordsVector(/*localize_data*/ true); for (unsigned int k = 0; k < num_eulerian_vars; ++k) { System* system = d_scalar_interp_var_systems[k]; const std::string& system_name = system->name(); const int scratch_idx = d_scalar_interp_scratch_idxs[k]; d_fe_data_manager->interp(scratch_idx, *system->solution, *X_ghost_vec, system_name, d_scalar_interp_specs[k]); } // Deallocate Eulerian scratch space. for (int ln = coarsest_ln; ln <= finest_ln; ++ln) { Pointer<PatchLevel<NDIM> > level = hierarchy->getPatchLevel(ln); for (unsigned int k = 0; k < num_eulerian_vars; ++k) { const int scratch_idx = d_scalar_interp_scratch_idxs[k]; level->deallocatePatchData(scratch_idx); } } return; } // interpolateVariables
void testGBVI(GBVIForce::NonbondedMethod gbviMethod, CustomGBForce::NonbondedMethod customGbviMethod, std::string molecule) { const int numMolecules = 1; const double boxSize = 10.0; ReferencePlatform platform; GBVIForce* gbvi = new GBVIForce(); std::vector<Vec3> positions; // select molecule if( molecule == "Monomer" ){ buildMonomer( gbvi, positions ); } else if( molecule == "Dimer" ){ buildDimer( gbvi, positions ); } else { buildEthane( gbvi, positions ); } int numParticles = gbvi->getNumParticles(); System standardSystem; System customGbviSystem; for (int i = 0; i < numParticles; i++) { standardSystem.addParticle(1.0); customGbviSystem.addParticle(1.0); } standardSystem.setDefaultPeriodicBoxVectors(Vec3(boxSize, 0.0, 0.0), Vec3(0.0, boxSize, 0.0), Vec3(0.0, 0.0, boxSize)); customGbviSystem.setDefaultPeriodicBoxVectors(Vec3(boxSize, 0.0, 0.0), Vec3(0.0, boxSize, 0.0), Vec3(0.0, 0.0, boxSize)); gbvi->setCutoffDistance(2.0); // create customGbviForce GBVI force CustomGBForce* customGbviForce = createCustomGBVI( gbvi->getSolventDielectric(), gbvi->getSoluteDielectric() ); customGbviForce->setCutoffDistance(2.0); // load parameters from gbvi to customGbviForce loadGbviParameters( gbvi, customGbviForce ); OpenMM_SFMT::SFMT sfmt; init_gen_rand(0, sfmt); vector<Vec3> velocities(numParticles); for (int ii = 0; ii < numParticles; ii++) { velocities[ii] = Vec3(genrand_real2(sfmt), genrand_real2(sfmt), genrand_real2(sfmt)); } gbvi->setNonbondedMethod(gbviMethod); customGbviForce->setNonbondedMethod(customGbviMethod); standardSystem.addForce(gbvi); customGbviSystem.addForce(customGbviForce); VerletIntegrator integrator1(0.01); VerletIntegrator integrator2(0.01); Context context1(standardSystem, integrator1, platform); context1.setPositions(positions); context1.setVelocities(velocities); State state1 = context1.getState(State::Forces | State::Energy); Context context2(customGbviSystem, integrator2, platform); context2.setPositions(positions); context2.setVelocities(velocities); State state2 = context2.getState(State::Forces | State::Energy); ASSERT_EQUAL_TOL(state1.getPotentialEnergy(), state2.getPotentialEnergy(), 1e-4); for (int i = 0; i < numParticles; i++) { ASSERT_EQUAL_VEC(state1.getForces()[i], state2.getForces()[i], 1e-4); } }
void DFFWidget::reloadHighLevelFile() { setCurrentGeometry(NULL); if (frameModel) delete frameModel; if (geomModel) delete geomModel; if (mesh) delete mesh; DFFLoader dff; File file = dfile->getFile(); try { mesh = dff.loadMesh(file); setEnabled(true); } catch (DFFException ex) { System::getInstance()->log(LogEntry::error(QString(tr("Error opening the DFF file: %1")) .arg(ex.getMessage().get()), &ex)); mesh = NULL; setEnabled(false); //ui.hlWidget->setEnabled(false); //ui.tabWidget->setTabEnabled(ui.tabWidget->indexOf(ui.hlWidget), false); } // Load the frame tree frameModel = new DFFFrameItemModel(mesh); ui.frameTree->setModel(frameModel); connect(ui.frameTree->selectionModel(), SIGNAL(currentChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(frameSelected(const QModelIndex&, const QModelIndex&))); System* sys = System::getInstance(); DFFMesh::GeometryIterator git; if (mesh) { geomModel = new DFFGeometryItemModel(mesh); ui.geometryTree->setModel(geomModel); renderWidget->displayMesh(mesh); connect(ui.geometryTree->selectionModel(), SIGNAL(currentChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(geometryTreeItemSelected(const QModelIndex&, const QModelIndex&))); connect(geomModel, SIGNAL(geometryDisplayStateChanged(DFFGeometry*, bool)), this, SLOT(geometryDisplayStateChanged(DFFGeometry*, bool))); connect(geomModel, SIGNAL(geometryPartDisplayStateChanged(DFFGeometryPart*, bool)), this, SLOT(geometryPartDisplayStateChanged(DFFGeometryPart*, bool))); // Search for the mesh texture char* meshName = new char[file.getPath().getFileName().length() + 1]; strtolower(meshName, file.getPath().getFileName().get()); meshName[strlen(meshName)-4] = '\0'; SystemQuery query("FindMeshTextures"); query["meshName"] = meshName; QList<SystemQueryResult> results = sys->sendSystemQuery(query); QStringList texes; for (unsigned int i = 0 ; i < results.size() ; i++) { SystemQueryResult res = results[i]; QStringList subTexes = res["textures"].toStringList(); texes.append(subTexes); } for (QStringList::iterator it = texes.begin() ; it != texes.end() ; it++) { QString tex = *it; ui.texSourceBox->addItem(tex, false); } if (texes.size() > 0) texSrcChanged(0); delete[] meshName; } }
void testMembrane() { const int numMolecules = 70; const int numParticles = numMolecules*2; const double boxSize = 10.0; ReferencePlatform platform; // Create a system with an implicit membrane. System system; for (int i = 0; i < numParticles; i++) { system.addParticle(1.0); } system.setDefaultPeriodicBoxVectors(Vec3(boxSize, 0.0, 0.0), Vec3(0.0, boxSize, 0.0), Vec3(0.0, 0.0, boxSize)); CustomGBForce* custom = new CustomGBForce(); custom->setCutoffDistance(2.0); custom->addPerParticleParameter("q"); custom->addPerParticleParameter("radius"); custom->addPerParticleParameter("scale"); custom->addGlobalParameter("thickness", 3); custom->addGlobalParameter("solventDielectric", 78.3); custom->addGlobalParameter("soluteDielectric", 1); custom->addComputedValue("Imol", "step(r+sr2-or1)*0.5*(1/L-1/U+0.25*(1/U^2-1/L^2)*(r-sr2*sr2/r)+0.5*log(L/U)/r+C);" "U=r+sr2;" "C=2*(1/or1-1/L)*step(sr2-r-or1);" "L=max(or1, D);" "D=abs(r-sr2);" "sr2 = scale2*or2;" "or1 = radius1-0.009; or2 = radius2-0.009", CustomGBForce::ParticlePairNoExclusions); custom->addComputedValue("Imem", "(1/radius+2*log(2)/thickness)/(1+exp(7.2*(abs(z)+radius-0.5*thickness)))", CustomGBForce::SingleParticle); custom->addComputedValue("B", "1/(1/or-tanh(1*psi-0.8*psi^2+4.85*psi^3)/radius);" "psi=max(Imol,Imem)*or; or=radius-0.009", CustomGBForce::SingleParticle); custom->addEnergyTerm("28.3919551*(radius+0.14)^2*(radius/B)^6-0.5*138.935456*(1/soluteDielectric-1/solventDielectric)*q^2/B", CustomGBForce::SingleParticle); custom->addEnergyTerm("-138.935456*(1/soluteDielectric-1/solventDielectric)*q1*q2/f;" "f=sqrt(r^2+B1*B2*exp(-r^2/(4*B1*B2)))", CustomGBForce::ParticlePairNoExclusions); vector<Vec3> positions(numParticles); vector<Vec3> velocities(numParticles); OpenMM_SFMT::SFMT sfmt; init_gen_rand(0, sfmt); vector<double> params(3); for (int i = 0; i < numMolecules; i++) { if (i < numMolecules/2) { params[0] = 1.0; params[1] = 0.2; params[2] = 0.5; custom->addParticle(params); params[0] = -1.0; params[1] = 0.1; custom->addParticle(params); } else { params[0] = 1.0; params[1] = 0.2; params[2] = 0.8; custom->addParticle(params); params[0] = -1.0; params[1] = 0.1; custom->addParticle(params); } positions[2*i] = Vec3(boxSize*genrand_real2(sfmt), boxSize*genrand_real2(sfmt), boxSize*genrand_real2(sfmt)); positions[2*i+1] = Vec3(positions[2*i][0]+1.0, positions[2*i][1], positions[2*i][2]); velocities[2*i] = Vec3(genrand_real2(sfmt), genrand_real2(sfmt), genrand_real2(sfmt)); velocities[2*i+1] = Vec3(genrand_real2(sfmt), genrand_real2(sfmt), genrand_real2(sfmt)); } system.addForce(custom); VerletIntegrator integrator(0.01); Context context(system, integrator, platform); context.setPositions(positions); context.setVelocities(velocities); State state = context.getState(State::Forces | State::Energy); const vector<Vec3>& forces = state.getForces(); // Take a small step in the direction of the energy gradient and see whether the potential energy changes by the expected amount. double norm = 0.0; for (int i = 0; i < (int) forces.size(); ++i) norm += forces[i].dot(forces[i]); norm = std::sqrt(norm); const double stepSize = 1e-3; double step = 0.5*stepSize/norm; vector<Vec3> positions2(numParticles), positions3(numParticles); for (int i = 0; i < (int) positions.size(); ++i) { Vec3 p = positions[i]; Vec3 f = forces[i]; positions2[i] = Vec3(p[0]-f[0]*step, p[1]-f[1]*step, p[2]-f[2]*step); positions3[i] = Vec3(p[0]+f[0]*step, p[1]+f[1]*step, p[2]+f[2]*step); } context.setPositions(positions2); State state2 = context.getState(State::Energy); context.setPositions(positions3); State state3 = context.getState(State::Energy); ASSERT_EQUAL_TOL(norm, (state2.getPotentialEnergy()-state3.getPotentialEnergy())/stepSize, 1e-3); }
void testExclusions() { ReferencePlatform platform; for (int i = 3; i < 4; i++) { System system; system.addParticle(1.0); system.addParticle(1.0); VerletIntegrator integrator(0.01); CustomGBForce* force = new CustomGBForce(); force->addComputedValue("a", "r", i < 2 ? CustomGBForce::ParticlePair : CustomGBForce::ParticlePairNoExclusions); force->addEnergyTerm("a", CustomGBForce::SingleParticle); force->addEnergyTerm("(1+a1+a2)*r", i%2 == 0 ? CustomGBForce::ParticlePair : CustomGBForce::ParticlePairNoExclusions); force->addParticle(vector<double>()); force->addParticle(vector<double>()); force->addExclusion(0, 1); system.addForce(force); Context context(system, integrator, platform); vector<Vec3> positions(2); positions[0] = Vec3(0, 0, 0); positions[1] = Vec3(1, 0, 0); context.setPositions(positions); State state = context.getState(State::Forces | State::Energy); const vector<Vec3>& forces = state.getForces(); double f, energy; switch (i) { case 0: // e = 0 f = 0; energy = 0; break; case 1: // e = r f = 1; energy = 1; break; case 2: // e = 2r f = 2; energy = 2; break; case 3: // e = 3r + 2r^2 f = 7; energy = 5; break; default: ASSERT(false); } ASSERT_EQUAL_VEC(Vec3(f, 0, 0), forces[0], 1e-4); ASSERT_EQUAL_VEC(Vec3(-f, 0, 0), forces[1], 1e-4); ASSERT_EQUAL_TOL(energy, state.getPotentialEnergy(), 1e-4); // Take a small step in the direction of the energy gradient and see whether the potential energy changes by the expected amount. double norm = 0.0; for (int i = 0; i < (int) forces.size(); ++i) norm += forces[i].dot(forces[i]); norm = std::sqrt(norm); const double stepSize = 1e-3; double step = stepSize/norm; for (int i = 0; i < (int) positions.size(); ++i) { Vec3 p = positions[i]; Vec3 f = forces[i]; positions[i] = Vec3(p[0]-f[0]*step, p[1]-f[1]*step, p[2]-f[2]*step); } context.setPositions(positions); State state2 = context.getState(State::Energy); ASSERT_EQUAL_TOL(norm, (state2.getPotentialEnergy()-state.getPotentialEnergy())/stepSize, 1e-3*abs(state.getPotentialEnergy())); } }
void JumpErrorEstimator::estimate_error (const System& system, ErrorVector& error_per_cell, const NumericVector<Number>* solution_vector, bool estimate_parent_error) { START_LOG("estimate_error()", "JumpErrorEstimator"); /* Conventions for assigning the direction of the normal: - e & f are global element ids Case (1.) Elements are at the same level, e<f Compute the flux jump on the face and add it as a contribution to error_per_cell[e] and error_per_cell[f] ---------------------- | | | | | f | | | | | e |---> n | | | | | | | ---------------------- Case (2.) The neighbor is at a higher level. Compute the flux jump on e's face and add it as a contribution to error_per_cell[e] and error_per_cell[f] ---------------------- | | | | | | e |---> n | | | | | |-----------| f | | | | | | | | | | | | | ---------------------- */ // The current mesh const MeshBase& mesh = system.get_mesh(); // The number of variables in the system const unsigned int n_vars = system.n_vars(); // The DofMap for this system const DofMap& dof_map = system.get_dof_map(); // Resize the error_per_cell vector to be // the number of elements, initialize it to 0. error_per_cell.resize (mesh.max_elem_id()); std::fill (error_per_cell.begin(), error_per_cell.end(), 0.); // Declare a vector of floats which is as long as // error_per_cell above, and fill with zeros. This vector will be // used to keep track of the number of edges (faces) on each active // element which are either: // 1) an internal edge // 2) an edge on a Neumann boundary for which a boundary condition // function has been specified. // The error estimator can be scaled by the number of flux edges (faces) // which the element actually has to obtain a more uniform measure // of the error. Use floats instead of ints since in case 2 (above) // f gets 1/2 of a flux face contribution from each of his // neighbors std::vector<float> n_flux_faces; if (scale_by_n_flux_faces) n_flux_faces.resize(error_per_cell.size(), 0); // Prepare current_local_solution to localize a non-standard // solution vector if necessary if (solution_vector && solution_vector != system.solution.get()) { NumericVector<Number>* newsol = const_cast<NumericVector<Number>*>(solution_vector); System &sys = const_cast<System&>(system); newsol->swap(*sys.solution); sys.update(); } fine_context.reset(new FEMContext(system)); coarse_context.reset(new FEMContext(system)); // Loop over all the variables we've been requested to find jumps in, to // pre-request for (var=0; var<n_vars; var++) { // Possibly skip this variable if (error_norm.weight(var) == 0.0) continue; // FIXME: Need to generalize this to vector-valued elements. [PB] FEBase* side_fe = NULL; const std::set<unsigned char>& elem_dims = fine_context->elem_dimensions(); for (std::set<unsigned char>::const_iterator dim_it = elem_dims.begin(); dim_it != elem_dims.end(); ++dim_it) { const unsigned char dim = *dim_it; fine_context->get_side_fe( var, side_fe, dim ); libmesh_assert_not_equal_to(side_fe->get_fe_type().family, SCALAR); side_fe->get_xyz(); } } this->init_context(*fine_context); this->init_context(*coarse_context); // Iterate over all the active elements in the mesh // that live on this processor. MeshBase::const_element_iterator elem_it = mesh.active_local_elements_begin(); const MeshBase::const_element_iterator elem_end = mesh.active_local_elements_end(); for (; elem_it != elem_end; ++elem_it) { // e is necessarily an active element on the local processor const Elem* e = *elem_it; const dof_id_type e_id = e->id(); #ifdef LIBMESH_ENABLE_AMR // See if the parent of element e has been examined yet; // if not, we may want to compute the estimator on it const Elem* parent = e->parent(); // We only can compute and only need to compute on // parents with all active children bool compute_on_parent = true; if (!parent || !estimate_parent_error) compute_on_parent = false; else for (unsigned int c=0; c != parent->n_children(); ++c) if (!parent->child(c)->active()) compute_on_parent = false; if (compute_on_parent && !error_per_cell[parent->id()]) { // Compute a projection onto the parent DenseVector<Number> Uparent; FEBase::coarsened_dof_values (*(system.solution), dof_map, parent, Uparent, false); // Loop over the neighbors of the parent for (unsigned int n_p=0; n_p<parent->n_neighbors(); n_p++) { if (parent->neighbor(n_p) != NULL) // parent has a neighbor here { // Find the active neighbors in this direction std::vector<const Elem*> active_neighbors; parent->neighbor(n_p)-> active_family_tree_by_neighbor(active_neighbors, parent); // Compute the flux to each active neighbor for (unsigned int a=0; a != active_neighbors.size(); ++a) { const Elem *f = active_neighbors[a]; // FIXME - what about when f->level < // parent->level()?? if (f->level() >= parent->level()) { fine_context->pre_fe_reinit(system, f); coarse_context->pre_fe_reinit(system, parent); libmesh_assert_equal_to (coarse_context->get_elem_solution().size(), Uparent.size()); coarse_context->get_elem_solution() = Uparent; this->reinit_sides(); // Loop over all significant variables in the system for (var=0; var<n_vars; var++) if (error_norm.weight(var) != 0.0) { this->internal_side_integration(); error_per_cell[fine_context->get_elem().id()] += static_cast<ErrorVectorReal>(fine_error); error_per_cell[coarse_context->get_elem().id()] += static_cast<ErrorVectorReal>(coarse_error); } // Keep track of the number of internal flux // sides found on each element if (scale_by_n_flux_faces) { n_flux_faces[fine_context->get_elem().id()]++; n_flux_faces[coarse_context->get_elem().id()] += this->coarse_n_flux_faces_increment(); } } } } else if (integrate_boundary_sides) { fine_context->pre_fe_reinit(system, parent); libmesh_assert_equal_to (fine_context->get_elem_solution().size(), Uparent.size()); fine_context->get_elem_solution() = Uparent; fine_context->side = n_p; fine_context->side_fe_reinit(); // If we find a boundary flux for any variable, // let's just count it as a flux face for all // variables. Otherwise we'd need to keep track of // a separate n_flux_faces and error_per_cell for // every single var. bool found_boundary_flux = false; for (var=0; var<n_vars; var++) if (error_norm.weight(var) != 0.0) { if (this->boundary_side_integration()) { error_per_cell[fine_context->get_elem().id()] += static_cast<ErrorVectorReal>(fine_error); found_boundary_flux = true; } } if (scale_by_n_flux_faces && found_boundary_flux) n_flux_faces[fine_context->get_elem().id()]++; } } } #endif // #ifdef LIBMESH_ENABLE_AMR // If we do any more flux integration, e will be the fine element fine_context->pre_fe_reinit(system, e); // Loop over the neighbors of element e for (unsigned int n_e=0; n_e<e->n_neighbors(); n_e++) { if ((e->neighbor(n_e) != NULL) || integrate_boundary_sides) { fine_context->side = n_e; fine_context->side_fe_reinit(); } if (e->neighbor(n_e) != NULL) // e is not on the boundary { const Elem* f = e->neighbor(n_e); const dof_id_type f_id = f->id(); // Compute flux jumps if we are in case 1 or case 2. if ((f->active() && (f->level() == e->level()) && (e_id < f_id)) || (f->level() < e->level())) { // f is now the coarse element coarse_context->pre_fe_reinit(system, f); this->reinit_sides(); // Loop over all significant variables in the system for (var=0; var<n_vars; var++) if (error_norm.weight(var) != 0.0) { this->internal_side_integration(); error_per_cell[fine_context->get_elem().id()] += static_cast<ErrorVectorReal>(fine_error); error_per_cell[coarse_context->get_elem().id()] += static_cast<ErrorVectorReal>(coarse_error); } // Keep track of the number of internal flux // sides found on each element if (scale_by_n_flux_faces) { n_flux_faces[fine_context->get_elem().id()]++; n_flux_faces[coarse_context->get_elem().id()] += this->coarse_n_flux_faces_increment(); } } // end if (case1 || case2) } // if (e->neigbor(n_e) != NULL) // Otherwise, e is on the boundary. If it happens to // be on a Dirichlet boundary, we need not do anything. // On the other hand, if e is on a Neumann (flux) boundary // with grad(u).n = g, we need to compute the additional residual // (h * \int |g - grad(u_h).n|^2 dS)^(1/2). // We can only do this with some knowledge of the boundary // conditions, i.e. the user must have attached an appropriate // BC function. else if (integrate_boundary_sides) { bool found_boundary_flux = false; for (var=0; var<n_vars; var++) if (error_norm.weight(var) != 0.0) if (this->boundary_side_integration()) { error_per_cell[fine_context->get_elem().id()] += static_cast<ErrorVectorReal>(fine_error); found_boundary_flux = true; } if (scale_by_n_flux_faces && found_boundary_flux) n_flux_faces[fine_context->get_elem().id()]++; } // end if (e->neighbor(n_e) == NULL) } // end loop over neighbors } // End loop over active local elements // Each processor has now computed the error contribuions // for its local elements. We need to sum the vector // and then take the square-root of each component. Note // that we only need to sum if we are running on multiple // processors, and we only need to take the square-root // if the value is nonzero. There will in general be many // zeros for the inactive elements. // First sum the vector of estimated error values this->reduce_error(error_per_cell, system.comm()); // Compute the square-root of each component. for (std::size_t i=0; i<error_per_cell.size(); i++) if (error_per_cell[i] != 0.) error_per_cell[i] = std::sqrt(error_per_cell[i]); if (this->scale_by_n_flux_faces) { // Sum the vector of flux face counts this->reduce_error(n_flux_faces, system.comm()); // Sanity check: Make sure the number of flux faces is // always an integer value #ifdef DEBUG for (unsigned int i=0; i<n_flux_faces.size(); ++i) libmesh_assert_equal_to (n_flux_faces[i], static_cast<float>(static_cast<unsigned int>(n_flux_faces[i])) ); #endif // Scale the error by the number of flux faces for each element for (unsigned int i=0; i<n_flux_faces.size(); ++i) { if (n_flux_faces[i] == 0.0) // inactive or non-local element continue; //libMesh::out << "Element " << i << " has " << n_flux_faces[i] << " flux faces." << std::endl; error_per_cell[i] /= static_cast<ErrorVectorReal>(n_flux_faces[i]); } } // If we used a non-standard solution before, now is the time to fix // the current_local_solution if (solution_vector && solution_vector != system.solution.get()) { NumericVector<Number>* newsol = const_cast<NumericVector<Number>*>(solution_vector); System &sys = const_cast<System&>(system); newsol->swap(*sys.solution); sys.update(); } STOP_LOG("estimate_error()", "JumpErrorEstimator"); }
void StatisticsSampler::sampleTemperature(System &system) { m_temperature = 2.0/3.0 * m_kineticEnergy / system.atoms().size(); system.setTemperature(m_temperature); }
void RBEvaluation::read_in_vectors(System& sys, std::vector<NumericVector<Number>*>& vectors, const std::string& directory_name, const std::string& data_name, const bool read_binary_vectors) { START_LOG("read_in_vectors()", "RBEvaluation"); //libMesh::out << "Reading in the basis functions..." << std::endl; // Make sure processors are synced up before we begin this->comm().barrier(); std::ostringstream file_name; const std::string basis_function_suffix = (read_binary_vectors ? ".xdr" : ".dat"); struct stat stat_info; file_name << directory_name << "/" << data_name << "_header" << basis_function_suffix; Xdr header_data(file_name.str(), read_binary_vectors ? DECODE : READ); // set the version number in header_data from io_version_string // (same code as in EquationSystemsIO::_read_impl) std::string io_version_string = get_io_version_string(); std::string::size_type lm_pos = io_version_string.find("libMesh"); std::istringstream iss(io_version_string.substr(lm_pos + 8)); int ver_major = 0, ver_minor = 0, ver_patch = 0; char dot; iss >> ver_major >> dot >> ver_minor >> dot >> ver_patch; header_data.set_version(LIBMESH_VERSION_ID(ver_major, ver_minor, ver_patch)); // We need to call sys.read_header (e.g. to set _written_var_indices properly), // but by setting the read_header argument to false, it doesn't reinitialize the system sys.read_header(header_data, io_version_string, /*read_header=*/false, /*read_additional_data=*/false); // Following EquationSystemsIO::read, we use a temporary numbering (node major) // before writing out the data MeshTools::Private::globally_renumber_nodes_and_elements(sys.get_mesh()); const bool read_legacy_format = false; if (read_legacy_format) { // Use System::read_serialized_data to read in the basis functions // into this->solution and then swap with the appropriate // of basis function. for(unsigned int i=0; i<vectors.size(); i++) { file_name.str(""); // reset the string file_name << directory_name << "/" << data_name << i << basis_function_suffix; // On processor zero check to be sure the file exists if (this->processor_id() == 0) { int stat_result = stat(file_name.str().c_str(), &stat_info); if (stat_result != 0) { libMesh::out << "File does not exist: " << file_name.str() << std::endl; libmesh_error(); } } Xdr vector_data(file_name.str(), read_binary_vectors ? DECODE : READ); // The bf_data needs to know which version to read. vector_data.set_version(LIBMESH_VERSION_ID(ver_major, ver_minor, ver_patch)); sys.read_serialized_data(vector_data, false); vectors[i] = NumericVector<Number>::build(sys.comm()).release(); vectors[i]->init (sys.n_dofs(), sys.n_local_dofs(), false, libMeshEnums::PARALLEL); // No need to copy, just swap // *vectors[i] = *solution; vectors[i]->swap(*sys.solution); } } //------------------------------------------------------ // new implementation else { // Allocate storage for each vector for(unsigned int i=0; i<vectors.size(); i++) { vectors[i] = NumericVector<Number>::build(sys.comm()).release(); vectors[i]->init (sys.n_dofs(), sys.n_local_dofs(), false, libMeshEnums::PARALLEL); } file_name.str(""); file_name << directory_name << "/" << data_name << "_data" << basis_function_suffix; // On processor zero check to be sure the file exists if (this->processor_id() == 0) { int stat_result = stat(file_name.str().c_str(), &stat_info); if (stat_result != 0) { libMesh::out << "File does not exist: " << file_name.str() << std::endl; libmesh_error(); } } Xdr vector_data(file_name.str(), read_binary_vectors ? DECODE : READ); // The vector_data needs to know which version to read. vector_data.set_version(LIBMESH_VERSION_ID(ver_major, ver_minor, ver_patch)); sys.read_serialized_vectors (vector_data, vectors); } //------------------------------------------------------ // Undo the temporary renumbering sys.get_mesh().fix_broken_node_and_element_numbering(); //libMesh::out << "Finished reading in the basis functions..." << std::endl; STOP_LOG("read_in_vectors()", "RBEvaluation"); }
/*! * \brief Initialize the operator * \param ioSystem Current system */ void HPC::SendDemeToSupervisorOp::init(System& ioSystem) { Beagle_StackTraceBeginM(); mComm = castHandleT<HPC::MPICommunication>(ioSystem.getComponent("MPICommunication")); Beagle_StackTraceEndM("HPC::SendDemeToSupervisorOp::init(System&)"); }
int main(int argc, char* argv[]) { int program = 0; // Get input file from first command line argument if(argc < 2){ // No input file given std::cerr << "Usage: ./main [input_file]\n"; program = -1; } else { std::string ifname = argv[1]; // Input filename std::string ofname = ifname; // Output file prefix std::size_t pos = ofname.find('.'); if (pos != std::string::npos) { // Cut off extension ofname.erase(pos, ofname.length()); } // Open the input file std::ifstream input(ifname); // Check it opened successfully if (!input.is_open()){ std::cerr << "Failed to open input file.\n"; program = -1; } else { // Make the system System sys = makeSystem(input); // Calculate the overlap integrals sys.calcOverlap(); // Open main output file and print system details std::ofstream output(ofname + ".out"); printSystem(sys, output, true); // Do all the optional commands int lastcmd = 0; int flag = 1; int orthog = 0; std::vector<int> currcmd; Eigen::MatrixXd f; while(flag > 0){ currcmd = getNextCmd(input, lastcmd); switch(currcmd[0]){ case 1: { // Print the overlap integrals std::ofstream intout(ofname + ".ints"); printIntegrals(sys, intout); intout.close(); break; } case 2: { // Print the sparse graph data std::ofstream sparseout(ofname + ".sparse"); printSparseGraph(sys, sparseout, currcmd[1]); sparseout.close(); break; } case 3: { // Canonical orthogonalisation f = orthogonalise(sys, currcmd[1], CANONICAL); orthog = 1; break; } case 4: { // Gram-Schmidt orthogonalisation f = orthogonalise(sys, currcmd[1], GRAM_SCHMIDT); orthog = 2; break; } case 5: { // Symmetric Lowdin orthogonalisation f = orthogonalise(sys, currcmd[1], SYM_LOWDIN); orthog = 3; break; } case -1: { // Error output << "\nErroneous command given.\n"; flag = 0; program = -1; break; } default: { // No more commands output << "\nProgram finished.\n"; flag = 0; } } lastcmd++; } // Print orthogonalisation data if needed if (orthog > 0) { std::ofstream orthogout(ofname + ".orthog"); printOrthog(sys, orthogout, f, orthog); orthogout.close(); } output.close(); } } return program; }
void RBEvaluation::write_out_vectors(System& sys, std::vector<NumericVector<Number>*>& vectors, const std::string& directory_name, const std::string& data_name, const bool write_binary_vectors) { START_LOG("write_out_vectors()", "RBEvaluation"); //libMesh::out << "Writing out the basis functions..." << std::endl; if(this->processor_id() == 0) { // Make a directory to store all the data files mkdir(directory_name.c_str(), 0777); } // Make sure processors are synced up before we begin this->comm().barrier(); std::ostringstream file_name; const std::string basis_function_suffix = (write_binary_vectors ? ".xdr" : ".dat"); file_name << directory_name << "/" << data_name << "_header" << basis_function_suffix; Xdr header_data(file_name.str(), write_binary_vectors ? ENCODE : WRITE); sys.write_header(header_data, get_io_version_string(), /*write_additional_data=*/false); // Following EquationSystemsIO::write, we use a temporary numbering (node major) // before writing out the data MeshTools::Private::globally_renumber_nodes_and_elements(sys.get_mesh()); // // Use System::write_serialized_data to write out the basis functions // // by copying them into this->solution one at a time. // for(unsigned int i=0; i<vectors.size(); i++) // { // // No need to copy, just swap // // *solution = *vectors[i]; // vectors[i]->swap(*sys.solution); // file_name.str(""); // reset the string // file_name << directory_name << "/bf" << i << basis_function_suffix; // Xdr bf_data(file_name.str(), // write_binary_vectors ? ENCODE : WRITE); // // set the current version // bf_data.set_version(LIBMESH_VERSION_ID(LIBMESH_MAJOR_VERSION, // LIBMESH_MINOR_VERSION, // LIBMESH_MICRO_VERSION)); // sys.write_serialized_data(bf_data, false); // // Synchronize before moving on // this->comm().barrier(); // // Swap back // vectors[i]->swap(*sys.solution); // } file_name.str(""); file_name << directory_name << "/" << data_name << "_data" << basis_function_suffix; Xdr bf_data(file_name.str(), write_binary_vectors ? ENCODE : WRITE); // Write all vectors at once. { // Note the API wants pointers to constant vectors, hence this... std::vector<const NumericVector<Number>*> bf_out(vectors.begin(), vectors.end()); // for(unsigned int i=0; i<vectors.size(); i++) // bf_out.push_back(vectors[i]); sys.write_serialized_vectors (bf_data, bf_out); } // set the current version bf_data.set_version(LIBMESH_VERSION_ID(LIBMESH_MAJOR_VERSION, LIBMESH_MINOR_VERSION, LIBMESH_MICRO_VERSION)); // Undo the temporary renumbering sys.get_mesh().fix_broken_node_and_element_numbering(); STOP_LOG("write_out_vectors()", "RBEvaluation"); }
void timerFunc() { static unsigned int vertices = 0; static char buf[512]; if ( primitivesQuery->isResultReady() ) { vertices = primitivesQuery->getResult(); updateQuery = true; } sprintf( buf, "Sample1, part%i, mode%i, Fps:%i, vertices: %i / %i", currPart+1, modeIndex+1, sys.getFPS(), gridMesh->getIndexBuffer()->getSize(), vertices ); glutSetWindowTitle( buf ); }
void display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if ( input.isKey(27) ) exit(0); // + - if ( input.isKeyClick('=') ) program->getStates().maxTessLevel++; if ( input.isKeyClick('-') ) program->getStates().maxTessLevel--; // < > if ( input.isKeyClick(',') ) program->getStates().detailLevel--; if ( input.isKeyClick('.') ) program->getStates().detailLevel++; // [ ] if ( input.isKeyClick('[') ) program->getStates().heightScale++; if ( input.isKeyClick(']') ) program->getStates().heightScale--; // left, right if ( input.isSpecKeyClick(GLUT_KEY_LEFT) ) program->getStates().gridScale -= 10.f; if ( input.isSpecKeyClick(GLUT_KEY_RIGHT)) program->getStates().gridScale += 10.f; // up, down if ( input.isSpecKeyClick(GLUT_KEY_UP) ) camSpeed += 0.01f; if ( input.isSpecKeyClick(GLUT_KEY_DOWN) ) camSpeed -= 0.01f; // ( ) if ( input.isKeyClick('9') && modeIndex > 0 ) modeIndex--; if ( input.isKeyClick('0') && modeIndex < 6 ) modeIndex++; if ( input.isKeyClick('r') ) { currentMode->unload(); // reload currentMode->load(); } if ( input.isKeyClick('c') ) viewIndex = VIEW_COLOR; // view color map if ( input.isKeyClick('n') ) viewIndex = VIEW_NORMAL; // view normal map if ( input.isKeyClick('t') ) viewIndex = VIEW_TESS; // view tess level map if ( input.isKeyClick('m') ) viewIndex = VIEW_COLOR_MIX_TESS; if ( input.isKeyClick('f') ) viewIndex = VIEW_FOG; if ( input.isKeyClick('p') ) wireframe = !wireframe; // 1..4 if ( input.isKey('1') ) modeIndex = 0; if ( input.isKey('2') ) modeIndex = 1; if ( input.isKey('3') ) modeIndex = 2; if ( input.isKey('4') ) modeIndex = 3; // F1..F7 if ( input.isSpecKeyClick(GLUT_KEY_F1) ) loadMode( 0 ); if ( input.isSpecKeyClick(GLUT_KEY_F2) ) loadMode( 1 ); if ( input.isSpecKeyClick(GLUT_KEY_F3) ) loadMode( 2 ); if ( input.isSpecKeyClick(GLUT_KEY_F4) ) loadMode( 3 ); if ( input.isSpecKeyClick(GLUT_KEY_F5) ) loadMode( 4 ); if ( input.isSpecKeyClick(GLUT_KEY_F6) ) loadMode( 5 ); if ( input.isSpecKeyClick(GLUT_KEY_F7) ) loadMode( 6 ); cam.rotate( input.mouseDelta() * 0.2f ); const float time_delta = sys.getTimeDelta() * camSpeed; cam.move( (input.isKey('w') - input.isKey('s')) * time_delta, (input.isKey('d') - input.isKey('a')) * time_delta, (input.isKey('q') - input.isKey('e')) * time_delta ); program->getStates().mvp = cam.toMatrix(); currentView->bind(); glPolygonMode( GL_FRONT_AND_BACK, wireframe ? GL_LINE : GL_FILL ); glEnable( GL_CULL_FACE ); if ( updateQuery ) primitivesQuery->begin( GL_PRIMITIVES_GENERATED ); currentMode->draw( modeIndex ); if ( updateQuery ) { primitivesQuery->end(); updateQuery = false; } glDisable( GL_CULL_FACE ); glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); currentView->unbind(); currentView->draw( viewIndex ); }
using namespace framework; class Mode; class View; class Program; Mode * currentMode = NULL; View * currentView = NULL; Mesh * gridMesh = NULL; Mesh * fullScreenQuad = NULL; Texture * diffuseMap = NULL, * heightMap = NULL, * normalMap = NULL; Program * program = NULL; Query * primitivesQuery = NULL; System sys; Input & input = *sys.getInput(); int gridSize = 127; int modeIndex = 0; int currPart = 0; FPSCamera cam; bool wireframe = false; bool updateQuery = true; float camSpeed = 0.025f; #include "program.h" #include "modes.h" int viewIndex = VIEW_COLOR; Mode * allModes[] = { new Part1(), new Part2(), new Part3(), new Part4(), new Part5(), new Part6(), new Part7()
int main(int argc, char** argv) { int round1, index; float round2; System *recSys; sys = new System* [10 * 11]; for(round1 = 1; round1 < 11; round1++) { for(round2 = 1.00; round2 < 1.10; round2+=0.01) { index = ((round1-1) * 11) + ((round2 - 1.00) / 0.01); sys[index] = new System; #ifdef debug3 printf("Round %d\n", round1+1); printf("File name: %s\n", argv[1]); #endif readInputFile(argv[1], sys[index]); setPrecedence(sys[index]); TAMwidthAssign(round1, round2, sys[index]); //sys[index].printPrecedence(); sys[index]->setWaitExtList(); sys[index]->setWaitBistList(); sys[index]->TAMStat.initTAM(sys[index]->getSysTW()); #ifdef debug1 sys[index]->TAMStat.printTAM(); printf("External List Size: %lu\n", sys[index]->ext_list.size()); printf("Wiat External List Size: %lu\n", sys[index]->wait_ext_list.size()); #endif sys[index]->fillTest(); //test this function //sys[index]->printResult(argv[1]); #ifdef debug2 printf("Power Limit: %d\n", sys[index]->getSysPower()); sys[index]->printExtList(); sys[index]->printBistList(); //sys[index]->TAMStat.printPowerStat(); #endif ///* if(round1 == 1 && round2 == 1.00) recSys = sys[index]; else recSys = getFasterSys(sys[index], recSys); //*/ //delete sys; #ifdef debug3 printf("Round1 %d & Round2 %f End!\n", round1, round2); #endif } } recSys->printResult(argv[1]); for(index = 0; index < 110; index++) delete sys[index]; delete [] sys; return 0; }
void ContinuousPanel::paint(const QRect& /*r*/, QPainter& p) { if (!_active) { _visible = false; return; } Measure* measure = _score->tick2measure(0); if (measure == 0){ _visible = false; return; } if (measure->mmRest()) { measure = measure->mmRest(); _mmRestCount = measure->mmRestCount(); } System* system = measure->system(); if (system == 0) { _visible = false; return; } Segment* s = _score->tick2segment(0); double _spatium = _score->spatium(); _x = 0; if (_width <= 0) _width = s->x(); // // Set panel height for whole system // _height = 6 * _spatium; _y = system->staffYpage(0) + system->page()->pos().y(); double y2 = 0.0; for (int i = 0; i < _score->nstaves(); ++i) { SysStaff* ss = system->staff(i); if (!ss->show() || !_score->staff(i)->show()) continue; y2 = ss->y() + ss->bbox().height(); } _height += y2 + 6*_spatium; _y -= 6 * _spatium; // // Check elements at current panel position // _offsetPanel = -(_sv->xoffset()) / _sv->mag(); _rect = QRect(_offsetPanel + _width, _y, 1, _height); //qDebug() << "width=" << _width << "_y="<< _y << "_offsetPanel=" << _offsetPanel << "_sv->xoffset()" << _sv->xoffset() << "_sv->mag()" << _sv->mag() <<"_spatium" << _spatium << "s->canvasPos().x()" << s->canvasPos().x() << "s->x()" << s->x(); Page* page = _score->pages().front(); QList<Element*> elementsCurrent = page->items(_rect); if (elementsCurrent.empty()) { _visible = false; return; } qStableSort(elementsCurrent.begin(), elementsCurrent.end(), elementLessThan); _currentMeasure = nullptr; for (const Element* e : elementsCurrent) { e->itemDiscovered = 0; if (!e->visible()) { if (_score->printing() || !_score->showInvisible()) continue; } if (e->type() == Element::Type::MEASURE) { _currentMeasure = static_cast<const Measure*>(e); _currentTimeSig = _currentMeasure->timesig(); _currentMeasureTick = _currentMeasure->tick(); _currentMeasureNo = _currentMeasure->no(); // Find number of multi measure rests to display in the panel if (_currentMeasure->isMMRest()) _mmRestCount = _currentMeasure->mmRestCount(); else if (_currentMeasure->mmRest()) _mmRestCount = _currentMeasure->mmRest()->mmRestCount(); else _mmRestCount = 0; _xPosMeasure = e->canvasX(); _measureWidth = e->width(); break; } } if (_currentMeasure == nullptr) return; findElementWidths(elementsCurrent); // Don't show panel if staff names are visible if (_sv->xoffset() / _sv->mag() + _xPosMeasure > 0) { _visible = false; return; } //qDebug() << "_sv->xoffset()=" <<_sv->xoffset() << " _sv->mag()="<< _sv->mag() <<" s->x=" << s->x() << " width=" << _width << " currentMeasue=" << _currentMeasure->x() << " _xPosMeasure=" << _xPosMeasure; draw(p, elementsCurrent); _visible = true; }
void AdjointResidualErrorEstimator::estimate_error (const System& _system, ErrorVector& error_per_cell, const NumericVector<Number>* solution_vector, bool estimate_parent_error) { START_LOG("estimate_error()", "AdjointResidualErrorEstimator"); // The current mesh const MeshBase& mesh = _system.get_mesh(); // Resize the error_per_cell vector to be // the number of elements, initialize it to 0. error_per_cell.resize (mesh.max_elem_id()); std::fill (error_per_cell.begin(), error_per_cell.end(), 0.); // Get the number of variables in the system unsigned int n_vars = _system.n_vars(); // We need to make a map of the pointer to the solution vector std::map<const System*, const NumericVector<Number>*>solutionvecs; solutionvecs[&_system] = _system.solution.get(); // Solve the dual problem if we have to if (!adjoint_already_solved) { // FIXME - we'll need to change a lot of APIs to make this trick // work with a const System... System& system = const_cast<System&>(_system); system.adjoint_solve(_qoi_set); } // Flag to check whether we have not been asked to weight the variable error contributions in any specific manner bool error_norm_is_identity = error_norm.is_identity(); // Create an ErrorMap/ErrorVector to store the primal, dual and total_dual variable errors ErrorMap primal_errors_per_cell; ErrorMap dual_errors_per_cell; ErrorMap total_dual_errors_per_cell; // Allocate ErrorVectors to this map if we're going to use it if (!error_norm_is_identity) for(unsigned int v = 0; v < n_vars; v++) { primal_errors_per_cell[std::make_pair(&_system, v)] = new ErrorVector; dual_errors_per_cell[std::make_pair(&_system, v)] = new ErrorVector; total_dual_errors_per_cell[std::make_pair(&_system, v)] = new ErrorVector; } ErrorVector primal_error_per_cell; ErrorVector dual_error_per_cell; ErrorVector total_dual_error_per_cell; // Have we been asked to weight the variable error contributions in any specific manner if(!error_norm_is_identity) // If we do { // Estimate the primal problem error for each variable _primal_error_estimator->estimate_errors (_system.get_equation_systems(), primal_errors_per_cell, &solutionvecs, estimate_parent_error); } else // If not { // Just get the combined error estimate _primal_error_estimator->estimate_error (_system, primal_error_per_cell, solution_vector, estimate_parent_error); } // Sum and weight the dual error estimate based on our QoISet for (unsigned int i = 0; i != _system.qoi.size(); ++i) { if (_qoi_set.has_index(i)) { // Get the weight for the current QoI Real error_weight = _qoi_set.weight(i); // We need to make a map of the pointer to the adjoint solution vector std::map<const System*, const NumericVector<Number>*>adjointsolutionvecs; adjointsolutionvecs[&_system] = &_system.get_adjoint_solution(i); // Have we been asked to weight the variable error contributions in any specific manner if(!error_norm_is_identity) // If we have { _dual_error_estimator->estimate_errors (_system.get_equation_systems(), dual_errors_per_cell, &adjointsolutionvecs, estimate_parent_error); } else // If not { // Just get the combined error estimate _dual_error_estimator->estimate_error (_system, dual_error_per_cell, &(_system.get_adjoint_solution(i)), estimate_parent_error); } unsigned int error_size; // Get the size of the first ErrorMap vector; this will give us the number of elements if(!error_norm_is_identity) // If in non default weights case { error_size = dual_errors_per_cell[std::make_pair(&_system, 0)]->size(); } else // If in the standard default weights case { error_size = dual_error_per_cell.size(); } // Resize the ErrorVector(s) if(!error_norm_is_identity) { // Loop over variables for(unsigned int v = 0; v < n_vars; v++) { libmesh_assert(!total_dual_errors_per_cell[std::make_pair(&_system, v)]->size() || total_dual_errors_per_cell[std::make_pair(&_system, v)]->size() == error_size) ; total_dual_errors_per_cell[std::make_pair(&_system, v)]->resize(error_size); } } else { libmesh_assert(!total_dual_error_per_cell.size() || total_dual_error_per_cell.size() == error_size); total_dual_error_per_cell.resize(error_size); } for (unsigned int e = 0; e != error_size; ++e) { // Have we been asked to weight the variable error contributions in any specific manner if(!error_norm_is_identity) // If we have { // Loop over variables for(unsigned int v = 0; v < n_vars; v++) { // Now fill in total_dual_error ErrorMap with the weight (*total_dual_errors_per_cell[std::make_pair(&_system, v)])[e] += error_weight * (*dual_errors_per_cell[std::make_pair(&_system, v)])[e]; } } else // If not { total_dual_error_per_cell[e] += error_weight * dual_error_per_cell[e]; } } } } // Do some debugging plots if requested if (!error_plot_suffix.empty()) { if(!error_norm_is_identity) // If we have { // Loop over variables for(unsigned int v = 0; v < n_vars; v++) { OStringStream primal_out; OStringStream dual_out; primal_out << "primal_" << error_plot_suffix << "."; dual_out << "dual_" << error_plot_suffix << "."; OSSRealzeroright(primal_out, 1,0,v); OSSRealzeroright(dual_out, 1,0,v); (*primal_errors_per_cell[std::make_pair(&_system, v)]).plot_error(primal_out.str(), _system.get_mesh()); (*total_dual_errors_per_cell[std::make_pair(&_system, v)]).plot_error(dual_out.str(), _system.get_mesh()); primal_out.clear(); dual_out.clear(); } } else // If not { OStringStream primal_out; OStringStream dual_out; primal_out << "primal_" << error_plot_suffix ; dual_out << "dual_" << error_plot_suffix ; primal_error_per_cell.plot_error(primal_out.str(), _system.get_mesh()); total_dual_error_per_cell.plot_error(dual_out.str(), _system.get_mesh()); primal_out.clear(); dual_out.clear(); } } // Weight the primal error by the dual error using the system norm object // FIXME: we ought to thread this for (unsigned int i=0; i != error_per_cell.size(); ++i) { // Have we been asked to weight the variable error contributions in any specific manner if(!error_norm_is_identity) // If we do { // Create Error Vectors to pass to calculate_norm std::vector<Real> cell_primal_error; std::vector<Real> cell_dual_error; for(unsigned int v = 0; v < n_vars; v++) { cell_primal_error.push_back((*primal_errors_per_cell[std::make_pair(&_system, v)])[i]); cell_dual_error.push_back((*total_dual_errors_per_cell[std::make_pair(&_system, v)])[i]); } error_per_cell[i] = error_norm.calculate_norm(cell_primal_error, cell_dual_error); } else // If not { error_per_cell[i] = primal_error_per_cell[i]*total_dual_error_per_cell[i]; } } // Deallocate the ErrorMap contents if we allocated them earlier if (!error_norm_is_identity) for(unsigned int v = 0; v < n_vars; v++) { delete primal_errors_per_cell[std::make_pair(&_system, v)]; delete dual_errors_per_cell[std::make_pair(&_system, v)]; delete total_dual_errors_per_cell[std::make_pair(&_system, v)]; } STOP_LOG("estimate_error()", "AdjointResidualErrorEstimator"); }
CHECK(~ConformationSet()) delete cs; RESULT CHECK(readDCDFile()) ConformationSet cs; cs.readDCDFile(BALL_TEST_DATA_PATH(ConformationSet_test.dcd)); cs.resetScoring(); TEST_EQUAL(cs.size(), 10) RESULT CHECK(writeDCDFile(const String& filename, const Size num = 0)) ConformationSet cs; PDBFile pdb(BALL_TEST_DATA_PATH(ConformationSet_test.pdb)); System sys; pdb.read(sys); cs.setup(sys); cs.readDCDFile(BALL_TEST_DATA_PATH(ConformationSet_test.dcd)); cs.resetScoring(); String tmp_filename; NEW_TMP_FILE(tmp_filename) cs.writeDCDFile(tmp_filename); TEST_FILE(tmp_filename.c_str(), BALL_TEST_DATA_PATH(ConformationSet_test.dcd)) RESULT CHECK(setup()) PDBFile pdb(BALL_TEST_DATA_PATH(ConformationSet_test.pdb)); System sys;
void StatisticsSampler::samplePotentialEnergy(System &system) { m_potentialEnergy = system.potential()->potentialEnergy(); }
QPointF SLine::linePos(int grip, System** sys) { qreal _spatium = spatium(); qreal x = 0.0; switch(anchor()) { case Spanner::ANCHOR_SEGMENT: { Segment* seg = static_cast<Segment*>(grip == 0 ? startElement() : endElement()); Measure* m = seg->measure(); *sys = m->system(); if (*sys == 0) return QPointF(x, 0.0); x = seg->pos().x() + m->pos().x(); if (grip == GRIP_LINE_END) { if (((*sys)->firstMeasure() == m) && (seg->tick() == m->tick())) { m = m->prevMeasure(); if (m) { *sys = m->system(); x = m->pos().x() + m->width(); } } } } break; case Spanner::ANCHOR_MEASURE: { // anchor() == ANCHOR_MEASURE Measure* m; if (grip == GRIP_LINE_START) { Q_ASSERT(startElement()->type() == MEASURE); m = static_cast<Measure*>(startElement()); x = m->pos().x(); } else { Q_ASSERT(endElement()->type() == MEASURE); m = static_cast<Measure*>(endElement()); x = m->pos().x() + m->bbox().right(); if (type() == VOLTA) { Segment* seg = m->last(); if (seg->subtype() == Segment::SegEndBarLine) { Element* e = seg->element(0); if (e && e->type() == BAR_LINE) { if (static_cast<BarLine*>(e)->subtype() == START_REPEAT) x -= e->width() - _spatium * .5; else x -= _spatium * .5; } } } } Q_ASSERT(m->system()); *sys = m->system(); } break; case Spanner::ANCHOR_NOTE: { System* s = static_cast<Note*>(startElement())->chord()->segment()->system(); *sys = s; if (grip == GRIP_LINE_START) return startElement()->pagePos() - s->pagePos(); else return endElement()->pagePos() - s->pagePos(); } case Spanner::ANCHOR_CHORD: qFatal("Sline::linePos(): anchor not implemented\n"); break; } //DEBUG: if ((*sys)->staves()->isEmpty()) return QPointF(x, 0.0); qreal y = (*sys)->staff(staffIdx())->y(); return QPointF(x, y); }
~BasicEnv() { arch->release(); s->dispose(); }
void SLine::layout() { if (parent() == 0) { // // when used in a palette, SLine has no parent and // tick and tick2 has no meaning so no layout is // possible and needed // if (!spannerSegments().isEmpty()) { LineSegment* s = frontSegment(); s->layout(); setbbox(s->bbox()); } return; } if (startElement() == 0 || endElement() == 0) { qDebug("SLine::layout() failed: %s %s", parent()->name(), name()); qDebug(" start %p end %p", startElement(), endElement()); return; } System* s1; System* s2; QPointF p1 = linePos(GRIP_LINE_START, &s1); QPointF p2 = linePos(GRIP_LINE_END, &s2); QList<System*>* systems = score()->systems(); int sysIdx1 = systems->indexOf(s1); int sysIdx2 = systems->indexOf(s2); int segmentsNeeded = 0; for (int i = sysIdx1; i < sysIdx2+1; ++i) { if (systems->at(i)->isVbox()) continue; ++segmentsNeeded; } int segCount = spannerSegments().size(); if (segmentsNeeded != segCount) { if (segmentsNeeded > segCount) { int n = segmentsNeeded - segCount; for (int i = 0; i < n; ++i) { LineSegment* ls = createLineSegment(); add(ls); // set user offset to previous segment's offset if (segCount > 0) ls->setUserOff(QPointF(0, segmentAt(segCount+i-1)->userOff().y())); } } else { int n = segCount - segmentsNeeded; // qDebug("SLine: segments %d needed %d, remove %d", segCount, segmentsNeeded, n); for (int i = 0; i < n; ++i) { if (spannerSegments().isEmpty()) { qDebug("SLine::layout(): no segment %d, %d expected", i, n); break; } else { // LineSegment* seg = takeLastSegment(); // TODO delete seg; } } } } int segIdx = 0; int si = staffIdx(); for (int i = sysIdx1; i <= sysIdx2; ++i) { System* system = systems->at(i); if (system->isVbox()) continue; LineSegment* seg = segmentAt(segIdx++); seg->setTrack(track()); // DEBUG seg->setSystem(system); Measure* m = system->firstMeasure(); Segment* mseg = m->first(Segment::SegChordRest); qreal x1 = (mseg ? mseg->pos().x() : 0) + m->pos().x(); qreal x2 = system->bbox().right(); qreal y = system->staff(si)->y(); if (sysIdx1 == sysIdx2) { // single segment seg->setSubtype(SEGMENT_SINGLE); seg->setPos(p1); // seg->setPos2(QPointF(p2.x() - p1.x(), 0.0)); seg->setPos2(p2 - p1); } else if (i == sysIdx1) { // start segment seg->setSubtype(SEGMENT_BEGIN); seg->setPos(p1); seg->setPos2(QPointF(x2 - p1.x(), 0.0)); } else if (i > 0 && i != sysIdx2) { // middle segment seg->setSubtype(SEGMENT_MIDDLE); seg->setPos(QPointF(x1, y)); seg->setPos2(QPointF(x2 - x1, 0.0)); } else if (i == sysIdx2) { // end segment seg->setSubtype(SEGMENT_END); seg->setPos(QPointF(x1, y)); seg->setPos2(QPointF(p2.x() - x1, 0.0)); } seg->layout(); } }
void testPositionDependence() { ReferencePlatform platform; System system; system.addParticle(1.0); system.addParticle(1.0); VerletIntegrator integrator(0.01); CustomGBForce* force = new CustomGBForce(); force->addComputedValue("a", "r", CustomGBForce::ParticlePair); force->addComputedValue("b", "a+x*y", CustomGBForce::SingleParticle); force->addEnergyTerm("b*z", CustomGBForce::SingleParticle); force->addEnergyTerm("b1+b2", CustomGBForce::ParticlePair); // = 2*r+x1*y1+x2*y2 force->addParticle(vector<double>()); force->addParticle(vector<double>()); system.addForce(force); Context context(system, integrator, platform); vector<Vec3> positions(2); vector<Vec3> forces(2); OpenMM_SFMT::SFMT sfmt; init_gen_rand(0, sfmt); for (int i = 0; i < 5; i++) { positions[0] = Vec3(genrand_real2(sfmt), genrand_real2(sfmt), genrand_real2(sfmt)); positions[1] = Vec3(genrand_real2(sfmt), genrand_real2(sfmt), genrand_real2(sfmt)); context.setPositions(positions); State state = context.getState(State::Forces | State::Energy); const vector<Vec3>& forces = state.getForces(); Vec3 delta = positions[0]-positions[1]; double r = sqrt(delta.dot(delta)); double energy = 2*r+positions[0][0]*positions[0][1]+positions[1][0]*positions[1][1]; for (int j = 0; j < 2; j++) energy += positions[j][2]*(r+positions[j][0]*positions[j][1]); Vec3 force1(-(1+positions[0][2])*delta[0]/r-(1+positions[0][2])*positions[0][1]-(1+positions[1][2])*delta[0]/r, -(1+positions[0][2])*delta[1]/r-(1+positions[0][2])*positions[0][0]-(1+positions[1][2])*delta[1]/r, -(1+positions[0][2])*delta[2]/r-(r+positions[0][0]*positions[0][1])-(1+positions[1][2])*delta[2]/r); Vec3 force2((1+positions[0][2])*delta[0]/r+(1+positions[1][2])*delta[0]/r-(1+positions[1][2])*positions[1][1], (1+positions[0][2])*delta[1]/r+(1+positions[1][2])*delta[1]/r-(1+positions[1][2])*positions[1][0], (1+positions[0][2])*delta[2]/r+(1+positions[1][2])*delta[2]/r-(r+positions[1][0]*positions[1][1])); ASSERT_EQUAL_VEC(force1, forces[0], 1e-4); ASSERT_EQUAL_VEC(force2, forces[1], 1e-4); ASSERT_EQUAL_TOL(energy, state.getPotentialEnergy(), 0.02); // Take a small step in the direction of the energy gradient and see whether the potential energy changes by the expected amount. double norm = 0.0; for (int i = 0; i < (int) forces.size(); ++i) norm += forces[i].dot(forces[i]); norm = std::sqrt(norm); const double stepSize = 1e-3; double step = 0.5*stepSize/norm; vector<Vec3> positions2(2), positions3(2); for (int i = 0; i < (int) positions.size(); ++i) { Vec3 p = positions[i]; Vec3 f = forces[i]; positions2[i] = Vec3(p[0]-f[0]*step, p[1]-f[1]*step, p[2]-f[2]*step); positions3[i] = Vec3(p[0]+f[0]*step, p[1]+f[1]*step, p[2]+f[2]*step); } context.setPositions(positions2); State state2 = context.getState(State::Energy); context.setPositions(positions3); State state3 = context.getState(State::Energy); ASSERT_EQUAL_TOL(norm, (state2.getPotentialEnergy()-state3.getPotentialEnergy())/stepSize, 1e-3); } }
int main(int argc, char* argv[]) { HaarWavelet H; System Sy; Similarity Si; IplImage *first = cvLoadImage("db/s29_10.jpg"); IplImage *sec = cvCreateImage(cvSize(256,256),8,3); IplImage *gray = cvCreateImage(cvSize(256,256),8,1); cvNamedWindow("query Image",1); cvResize(first,sec,CV_INTER_LINEAR); cvShowImage("query Image",sec); cvWaitKey(0); // cvNamedWindow("query_Image",1); //cvShowImage("query_Image",first); /** * Color Decomposition along each channel of color */ RgbImage imgA(first); sec = H.decompose_Image_b(sec); //Decomposition along blue channel cvNamedWindow("Decomposing Image",1); cvShowImage("Decomposing Image",sec); cvWaitKey(0); sec = H.decompose_Image_g(sec); //Decomposition along green channel cvNamedWindow("Decomposing Image",1); cvShowImage("Decomposing Image",sec); cvWaitKey(0); sec = H.decompose_Image_r(sec); //Decomposition along red channel cvNamedWindow("Decomposing Image",1); cvShowImage("Decomposing Image",sec); cvWaitKey(0); RgbImage imgDec(sec); // cvNamedWindow("first",1); // cvShowImage("first",sec); // cvWaitKey(0); /** * storing the wavelet coeffieciens of query image in rgb_pos.txt */ ofstream rgb_pos("rgb_pos.txt",ios::out); int arr_r[65535], arr_g[65535], arr_b[65535]; int k=0; for(int i=0; i<32; i++) { for(int j=0; j<32; j++) { k = i+32*j; arr_r[k] = (int)imgDec[i][j].r; arr_g[k] = (int)imgDec[i][j].g; arr_b[k] = (int)imgDec[i][j].b; rgb_pos<<arr_r[k]<<"\t"<<arr_g[k]<<"\t"<<arr_b[k]<<"\n";//<<i<<" "<<j<<"\n"; } } rgb_pos.close(); /** * Starting decomposition of images in the database * stores wavelet coefficients in respective filenames */ cvCvtColor(sec,gray,CV_BGR2GRAY); //cvShowImage("query_res",gray); //cvWaitKey(0); //gray = H.decompose_Image(gray); //cvShowImage("query_res",gray); //cvWaitKey(0); IplImage *seq_sec = cvCreateImage(cvSize(256,256),8,3); IplImage *seq_gray = cvCreateImage(cvSize(256,256),8,1); float wav = 0; map<float,string> sim; map<float,string> :: iterator mit; list<string> file_na = Sy.file_names("db/"); list<string> :: iterator lit; /** * Uncomment the below in order to initiate storage of wavelet coefficients * in external files * * Also store the filenames of the images in filename demo.txt */ /* char *pch; char *cstr; IplImage* img_seq; for(lit = file_na.begin(); lit!=file_na.end(); lit++) { cout<<(*lit)<<endl; img_seq = cvLoadImage((*lit).c_str()); cvShowImage("test",img_seq); //cvWaitKey(0); cvResize(img_seq,seq_sec,CV_INTER_LINEAR); //RgbImage imgA(first); //cout<<(int)imgA[0][0].b<<" "<<(int)imgA[0][0].g<<" "<<(int)imgA[0][0].r<<endl ; seq_sec = H.decompose_Image_b(seq_sec); cvNamedWindow("Image",1); cvShowImage("Image",seq_sec); //cvWaitKey(0); seq_sec = H.decompose_Image_g(seq_sec); cvNamedWindow("Image",1); cvShowImage("Image",seq_sec); //cvWaitKey(0); seq_sec = H.decompose_Image_r(seq_sec); cvNamedWindow("Image",1); cvShowImage("Image",seq_sec); //cvWaitKey(0); RgbImage SeqImg(seq_sec); //ofstream cout<<(*lit).c_str(); cstr = new char[(*lit).size()+1]; strcpy(cstr, (*lit).c_str()); pch = strtok(cstr,"."); cout<<"\n"<<pch; k=0; ofstream temp_file(pch, ios::out); for(int i=0; i<32; i++) { for(int j=0; j<32; j++) { k = i+32*j; arr_r[k] = (int)SeqImg[i][j].r; arr_g[k] = (int)SeqImg[i][j].g; arr_b[k] = (int)SeqImg[i][j].b; // if(arr_r[k] !=0 || arr_g[k] !=0 || arr_b[k] != 0) temp_file<<arr_r[k]<<"\t"<<arr_g[k]<<"\t"<<arr_b[k]<<"\n";//<<i<<" "<<j<<"\n"; } } temp_file.close(); cvCvtColor(seq_sec,seq_gray,CV_BGR2GRAY); //single channel //seq_gray = H.decompose_Image(seq_gray); wav = Si.wave_coeff_stg(gray,seq_gray); //printf ("It took you %.2lf seconds to type your name.\n", dif ); //cvShowImage("test",seq_gray); //cvWaitKey(0); // end single channel sim[wav] = *lit; cout<<"\n"<<wav<<"\n"; cvReleaseImage(&img_seq); delete [] cstr; } ofstream outfile("demo.txt",ios::out); for(mit = sim.begin();mit!=sim.end(); mit++) { outfile<<((*mit).second).c_str()<<"\n"; } outfile.close();*/ /** * Chromosome Construction using the rgb values of images */ char *cstr_1, *pch_1; string str; ifstream infile("demo.txt", ios::in); while(!infile.eof()) { infile>>str; //cout<<str<<"\n"; cstr_1 = new char[str.size()+1]; strcpy(cstr_1, str.c_str()); pch_1 = strtok(cstr_1,"."); wav = Si.wave_coeff_loc_aware("rgb_pos.txt",pch_1); sim[wav] = str; delete [] cstr_1; } infile.close(); ofstream loc_file("local.txt",ios::out); for(mit = sim.begin();mit!=sim.end(); mit++) { loc_file<<((*mit).second).c_str()<<"\n"; } loc_file.close(); /** End Test Chromosome **/ cvReleaseImage(&seq_sec); cvReleaseImage(&seq_gray); cvReleaseImage(&first); cvReleaseImage(&gray); cvDestroyWindow("Image"); cvDestroyWindow("dbm1"); cvDestroyWindow("dbm2"); cvDestroyWindow("dbm_1"); cvDestroyWindow("dbm_2"); cvDestroyWindow("dbm"); /* Ending openCV code */ cout<<"Hello"; QApplication app(argc, argv); SeqImg *dialog = new SeqImg; dialog->show(); return app.exec(); }
void testOBC(GBSAOBCForce::NonbondedMethod obcMethod, CustomGBForce::NonbondedMethod customMethod) { const int numMolecules = 70; const int numParticles = numMolecules*2; const double boxSize = 10.0; const double cutoff = 2.0; ReferencePlatform platform; // Create two systems: one with a GBSAOBCForce, and one using a CustomGBForce to implement the same interaction. System standardSystem; System customSystem; for (int i = 0; i < numParticles; i++) { standardSystem.addParticle(1.0); customSystem.addParticle(1.0); } standardSystem.setDefaultPeriodicBoxVectors(Vec3(boxSize, 0.0, 0.0), Vec3(0.0, boxSize, 0.0), Vec3(0.0, 0.0, boxSize)); customSystem.setDefaultPeriodicBoxVectors(Vec3(boxSize, 0.0, 0.0), Vec3(0.0, boxSize, 0.0), Vec3(0.0, 0.0, boxSize)); GBSAOBCForce* obc = new GBSAOBCForce(); CustomGBForce* custom = new CustomGBForce(); obc->setCutoffDistance(cutoff); custom->setCutoffDistance(cutoff); custom->addPerParticleParameter("q"); custom->addPerParticleParameter("radius"); custom->addPerParticleParameter("scale"); custom->addGlobalParameter("solventDielectric", obc->getSolventDielectric()); custom->addGlobalParameter("soluteDielectric", obc->getSoluteDielectric()); custom->addComputedValue("I", "step(r+sr2-or1)*0.5*(1/L-1/U+0.25*(1/U^2-1/L^2)*(r-sr2*sr2/r)+0.5*log(L/U)/r+C);" "U=r+sr2;" "C=2*(1/or1-1/L)*step(sr2-r-or1);" "L=max(or1, D);" "D=abs(r-sr2);" "sr2 = scale2*or2;" "or1 = radius1-0.009; or2 = radius2-0.009", CustomGBForce::ParticlePairNoExclusions); custom->addComputedValue("B", "1/(1/or-tanh(1*psi-0.8*psi^2+4.85*psi^3)/radius);" "psi=I*or; or=radius-0.009", CustomGBForce::SingleParticle); custom->addEnergyTerm("28.3919551*(radius+0.14)^2*(radius/B)^6-0.5*138.935485*(1/soluteDielectric-1/solventDielectric)*q^2/B", CustomGBForce::SingleParticle); string invCutoffString = ""; if (obcMethod != GBSAOBCForce::NoCutoff) { stringstream s; s<<(1.0/cutoff); invCutoffString = s.str(); } custom->addEnergyTerm("138.935485*(1/soluteDielectric-1/solventDielectric)*q1*q2*("+invCutoffString+"-1/f);" "f=sqrt(r^2+B1*B2*exp(-r^2/(4*B1*B2)))", CustomGBForce::ParticlePairNoExclusions); vector<Vec3> positions(numParticles); vector<Vec3> velocities(numParticles); OpenMM_SFMT::SFMT sfmt; init_gen_rand(0, sfmt); vector<double> params(3); for (int i = 0; i < numMolecules; i++) { if (i < numMolecules/2) { obc->addParticle(1.0, 0.2, 0.5); params[0] = 1.0; params[1] = 0.2; params[2] = 0.5; custom->addParticle(params); obc->addParticle(-1.0, 0.1, 0.5); params[0] = -1.0; params[1] = 0.1; custom->addParticle(params); } else { obc->addParticle(1.0, 0.2, 0.8); params[0] = 1.0; params[1] = 0.2; params[2] = 0.8; custom->addParticle(params); obc->addParticle(-1.0, 0.1, 0.8); params[0] = -1.0; params[1] = 0.1; custom->addParticle(params); } positions[2*i] = Vec3(boxSize*genrand_real2(sfmt), boxSize*genrand_real2(sfmt), boxSize*genrand_real2(sfmt)); positions[2*i+1] = Vec3(positions[2*i][0]+1.0, positions[2*i][1], positions[2*i][2]); velocities[2*i] = Vec3(genrand_real2(sfmt), genrand_real2(sfmt), genrand_real2(sfmt)); velocities[2*i+1] = Vec3(genrand_real2(sfmt), genrand_real2(sfmt), genrand_real2(sfmt)); } obc->setNonbondedMethod(obcMethod); custom->setNonbondedMethod(customMethod); standardSystem.addForce(obc); customSystem.addForce(custom); VerletIntegrator integrator1(0.01); VerletIntegrator integrator2(0.01); Context context1(standardSystem, integrator1, platform); context1.setPositions(positions); context1.setVelocities(velocities); State state1 = context1.getState(State::Forces | State::Energy); Context context2(customSystem, integrator2, platform); context2.setPositions(positions); context2.setVelocities(velocities); State state2 = context2.getState(State::Forces | State::Energy); ASSERT_EQUAL_TOL(state1.getPotentialEnergy(), state2.getPotentialEnergy(), 1e-4); for (int i = 0; i < numParticles; i++) { ASSERT_EQUAL_VEC(state1.getForces()[i], state2.getForces()[i], 1e-4); } // Try changing the particle parameters and make sure it's still correct. for (int i = 0; i < numMolecules/2; i++) { obc->setParticleParameters(2*i, 1.1, 0.3, 0.6); params[0] = 1.1; params[1] = 0.3; params[2] = 0.6; custom->setParticleParameters(2*i, params); obc->setParticleParameters(2*i+1, -1.1, 0.2, 0.4); params[0] = -1.1; params[1] = 0.2; params[2] = 0.4; custom->setParticleParameters(2*i+1, params); } obc->updateParametersInContext(context1); custom->updateParametersInContext(context2); state1 = context1.getState(State::Forces | State::Energy); state2 = context2.getState(State::Forces | State::Energy); ASSERT_EQUAL_TOL(state1.getPotentialEnergy(), state2.getPotentialEnergy(), 1e-4); for (int i = 0; i < numParticles; i++) { ASSERT_EQUAL_VEC(state1.getForces()[i], state2.getForces()[i], 1e-4); } }
void TextCursor::move(int tick) { QRectF r(bbox()); // // set mark height for whole system // Score* score = _sv->score(); Measure* measure = score->tick2measure(tick); if (measure == 0) return; qreal x; int offset = 0; Segment* s; for (s = measure->first(Segment::SegChordRest); s;) { int t1 = s->tick(); int x1 = s->canvasPos().x(); qreal x2; int t2; Segment* ns = s->next(Segment::SegChordRest); if (ns) { t2 = ns->tick(); x2 = ns->canvasPos().x(); } else { t2 = measure->endTick(); x2 = measure->canvasPos().x() + measure->width(); } t1 += offset; t2 += offset; if (tick >= t1 && tick < t2) { int dt = t2 - t1; qreal dx = x2 - x1; x = x1 + dx * (tick-t1) / dt; break; } s = ns; } if (s == 0) return; System* system = measure->system(); if (system == 0) return; double y = system->staffYpage(0) + system->page()->pos().y(); double _spatium = score->spatium(); qreal mag = _spatium / (MScore::DPI * SPATIUM20); double w = (_spatium * 2.0 + score->scoreFont()->width(SymId::noteheadBlack, mag))/3; double h = 6 * _spatium; // // set cursor height for whole system // double y2 = 0.0; for (int i = 0; i < score->nstaves(); ++i) { SysStaff* ss = system->staff(i); if (!ss->show() || !score->staff(i)->show()) continue; y2 = ss->y() + ss->bbox().height(); } h += y2; y -= 3 * _spatium; if (_type == CursorType::LOOP_IN) { x = x - _spatium + w/1.5; } else { x = x - _spatium * .5; } _tick = tick; _rect = QRectF(x, y, w, h); _sv->update(_sv->matrix().mapRect(r | bbox()).toRect().adjusted(-1,-1,1,1)); }
void compute(const Options& option){ // Start Timer // Timer timer, assemble, solve; timer.start(); // Get Domains // Mesh msh(option.getValue("-msh")[1]); GroupOfElement volume = msh.getFromPhysical(7); GroupOfElement source = msh.getFromPhysical(5); GroupOfElement freeSpace = msh.getFromPhysical(6); // Full Domain // vector<const GroupOfElement*> domain(3); domain[0] = &volume; domain[1] = &source; domain[2] = &freeSpace; // Get Parameters // const double k = atof(option.getValue("-k")[1].c_str()); const size_t order = atoi(option.getValue("-o")[1].c_str()); // Formulation // assemble.start(); FunctionSpaceScalar fs(domain, order); FormulationSteadyWave<complex<double> > wave(volume, fs, k); FormulationSommerfeld sommerfeld(freeSpace, fs, k); // System // System<complex<double> > sys; sys.addFormulation(wave); sys.addFormulation(sommerfeld); SystemHelper<complex<double> >::dirichlet(sys, fs, source, fSourceScal); cout << "Free Space (Order: " << order << " --- Wavenumber: " << k << "): " << sys.getSize() << endl; // Assemble // sys.assemble(); assemble.stop(); cout << "Assembled: " << assemble.time() << assemble.unit() << endl << flush; // Solve // solve.start(); sys.solve(); solve.stop(); cout << "Solved: " << solve.time() << solve.unit() << endl << flush; // Write Sol // try{ option.getValue("-nopos"); } catch(...){ FEMSolution<complex<double> > feSol; sys.getSolution(feSol, fs, volume); feSol.write("free"); } // Timer -- Finalize -- Return // timer.stop(); cout << "Elapsed Time: " << timer.time() << " s" << endl; }
void CudaIntegrateRPMDStepKernel::initialize(const System& system, const RPMDIntegrator& integrator) { cu.getPlatformData().initializeContexts(system); numCopies = integrator.getNumCopies(); numParticles = system.getNumParticles(); workgroupSize = numCopies; if (numCopies != findFFTDimension(numCopies)) throw OpenMMException("RPMDIntegrator: the number of copies must be a multiple of powers of 2, 3, and 5."); int paddedParticles = cu.getPaddedNumAtoms(); bool useDoublePrecision = (cu.getUseDoublePrecision() || cu.getUseMixedPrecision()); int elementSize = (useDoublePrecision ? sizeof(double4) : sizeof(float4)); forces = CudaArray::create<long long>(cu, numCopies*paddedParticles*3, "rpmdForces"); positions = new CudaArray(cu, numCopies*paddedParticles, elementSize, "rpmdPositions"); velocities = new CudaArray(cu, numCopies*paddedParticles, elementSize, "rpmdVelocities"); cu.getIntegrationUtilities().initRandomNumberGenerator((unsigned int) integrator.getRandomNumberSeed()); // Fill in the posq and velm arrays with safe values to avoid a risk of nans. if (useDoublePrecision) { vector<double4> temp(positions->getSize()); for (int i = 0; i < positions->getSize(); i++) temp[i] = make_double4(0, 0, 0, 0); positions->upload(temp); for (int i = 0; i < velocities->getSize(); i++) temp[i] = make_double4(0, 0, 0, 1); velocities->upload(temp); } else { vector<float4> temp(positions->getSize()); for (int i = 0; i < positions->getSize(); i++) temp[i] = make_float4(0, 0, 0, 0); positions->upload(temp); for (int i = 0; i < velocities->getSize(); i++) temp[i] = make_float4(0, 0, 0, 1); velocities->upload(temp); } // Build a list of contractions. groupsNotContracted = -1; const map<int, int>& contractions = integrator.getContractions(); int maxContractedCopies = 0; for (map<int, int>::const_iterator iter = contractions.begin(); iter != contractions.end(); ++iter) { int group = iter->first; int copies = iter->second; if (group < 0 || group > 31) throw OpenMMException("RPMDIntegrator: Force group must be between 0 and 31"); if (copies < 0 || copies > numCopies) throw OpenMMException("RPMDIntegrator: Number of copies for contraction cannot be greater than the total number of copies being simulated"); if (copies != findFFTDimension(copies)) throw OpenMMException("RPMDIntegrator: Number of copies for contraction must be a multiple of powers of 2, 3, and 5."); if (copies != numCopies) { if (groupsByCopies.find(copies) == groupsByCopies.end()) { groupsByCopies[copies] = 1<<group; if (copies > maxContractedCopies) maxContractedCopies = copies; } else groupsByCopies[copies] |= 1<<group; groupsNotContracted -= 1<<group; } } if (maxContractedCopies > 0) { contractedForces = CudaArray::create<long long>(cu, maxContractedCopies*paddedParticles*3, "rpmdContractedForces"); contractedPositions = new CudaArray(cu, maxContractedCopies*paddedParticles, elementSize, "rpmdContractedPositions"); } // Create kernels. map<string, string> defines; defines["NUM_ATOMS"] = cu.intToString(cu.getNumAtoms()); defines["PADDED_NUM_ATOMS"] = cu.intToString(cu.getPaddedNumAtoms()); defines["NUM_COPIES"] = cu.intToString(numCopies); defines["THREAD_BLOCK_SIZE"] = cu.intToString(workgroupSize); defines["HBAR"] = cu.doubleToString(1.054571628e-34*AVOGADRO/(1000*1e-12)); defines["SCALE"] = cu.doubleToString(1.0/sqrt((double) numCopies)); defines["M_PI"] = cu.doubleToString(M_PI); map<string, string> replacements; replacements["FFT_Q_FORWARD"] = createFFT(numCopies, "q", true); replacements["FFT_Q_BACKWARD"] = createFFT(numCopies, "q", false); replacements["FFT_V_FORWARD"] = createFFT(numCopies, "v", true); replacements["FFT_V_BACKWARD"] = createFFT(numCopies, "v", false); CUmodule module = cu.createModule(cu.replaceStrings(CudaKernelSources::vectorOps+CudaRpmdKernelSources::rpmd, replacements), defines, ""); pileKernel = cu.getKernel(module, "applyPileThermostat"); stepKernel = cu.getKernel(module, "integrateStep"); velocitiesKernel = cu.getKernel(module, "advanceVelocities"); copyToContextKernel = cu.getKernel(module, "copyDataToContext"); copyFromContextKernel = cu.getKernel(module, "copyDataFromContext"); translateKernel = cu.getKernel(module, "applyCellTranslations"); // Create kernels for doing contractions. for (map<int, int>::const_iterator iter = groupsByCopies.begin(); iter != groupsByCopies.end(); ++iter) { int copies = iter->first; replacements.clear(); replacements["NUM_CONTRACTED_COPIES"] = cu.intToString(copies); replacements["POS_SCALE"] = cu.doubleToString(1.0/numCopies); replacements["FORCE_SCALE"] = cu.doubleToString(0x100000000/(double) copies); replacements["FFT_Q_FORWARD"] = createFFT(numCopies, "q", true); replacements["FFT_Q_BACKWARD"] = createFFT(copies, "q", false); replacements["FFT_F_FORWARD"] = createFFT(copies, "f", true); replacements["FFT_F_BACKWARD"] = createFFT(numCopies, "f", false); module = cu.createModule(cu.replaceStrings(CudaKernelSources::vectorOps+CudaRpmdKernelSources::rpmdContraction, replacements), defines, ""); positionContractionKernels[copies] = cu.getKernel(module, "contractPositions"); forceContractionKernels[copies] = cu.getKernel(module, "contractForces"); } }
/** * Make sure random numbers are computed correctly when steps get merged. */ void testMergedRandoms() { const int numParticles = 10; const int numSteps = 10; System system; for (int i = 0; i < numParticles; i++) system.addParticle(1.0); CustomIntegrator integrator(0.1); integrator.addPerDofVariable("dofUniform1", 0); integrator.addPerDofVariable("dofUniform2", 0); integrator.addPerDofVariable("dofGaussian1", 0); integrator.addPerDofVariable("dofGaussian2", 0); integrator.addGlobalVariable("globalUniform1", 0); integrator.addGlobalVariable("globalUniform2", 0); integrator.addGlobalVariable("globalGaussian1", 0); integrator.addGlobalVariable("globalGaussian2", 0); integrator.addComputePerDof("dofUniform1", "uniform"); integrator.addComputePerDof("dofUniform2", "uniform"); integrator.addComputePerDof("dofGaussian1", "gaussian"); integrator.addComputePerDof("dofGaussian2", "gaussian"); integrator.addComputeGlobal("globalUniform1", "uniform"); integrator.addComputeGlobal("globalUniform2", "uniform"); integrator.addComputeGlobal("globalGaussian1", "gaussian"); integrator.addComputeGlobal("globalGaussian2", "gaussian"); Context context(system, integrator, platform); // See if the random numbers are computed correctly. vector<Vec3> values1, values2; for (int i = 0; i < numSteps; i++) { integrator.step(1); integrator.getPerDofVariable(0, values1); integrator.getPerDofVariable(1, values2); for (int i = 0; i < numParticles; i++) for (int j = 0; j < 3; j++) { double v1 = values1[i][j]; double v2 = values2[i][j]; ASSERT(v1 >= 0 && v1 < 1); ASSERT(v2 >= 0 && v2 < 1); ASSERT(v1 != v2); } integrator.getPerDofVariable(2, values1); integrator.getPerDofVariable(3, values2); for (int i = 0; i < numParticles; i++) for (int j = 0; j < 3; j++) { double v1 = values1[i][j]; double v2 = values2[i][j]; ASSERT(v1 >= -10 && v1 < 10); ASSERT(v2 >= -10 && v2 < 10); ASSERT(v1 != v2); } double v1 = integrator.getGlobalVariable(0); double v2 = integrator.getGlobalVariable(1); ASSERT(v1 >= 0 && v1 < 1); ASSERT(v2 >= 0 && v2 < 1); ASSERT(v1 != v2); v1 = integrator.getGlobalVariable(2); v2 = integrator.getGlobalVariable(3); ASSERT(v1 >= -10 && v1 < 10); ASSERT(v2 >= -10 && v2 < 10); ASSERT(v1 != v2); } }
/*! * \brief Configure evolver for (1+1)-ES with one fifth rule algorithm. * \param ioEvolver Evolver modified by setting the algorithm. * \param ioSystem Evolutionary system. * */ void ES::AlgoOneFifthRule::configure(Evolver& ioEvolver, System& ioSystem) { Beagle_StackTraceBeginM(); // Get reference to the factory const Factory& lFactory = ioSystem.getFactory(); // Get name and allocator of used operators std::string lEvalOpName = lFactory.getConceptTypeName("EvaluationOp"); EvaluationOp::Alloc::Handle lEvalOpAlloc = castHandleT<EvaluationOp::Alloc>(lFactory.getAllocator(lEvalOpName)); std::string lSelectOpName = "SelectRandomOp"; EC::SelectionOp::Alloc::Handle lSelectOpAlloc = castHandleT<EC::SelectionOp::Alloc>(lFactory.getAllocator(lSelectOpName)); std::string lInitOpName = lFactory.getConceptTypeName("InitializationOp"); EC::InitializationOp::Alloc::Handle lInitOpAlloc = castHandleT<EC::InitializationOp::Alloc>(lFactory.getAllocator(lInitOpName)); std::string lAdaptOpName = "ES-AdaptOneFifthRuleOp"; ES::AdaptOneFifthRuleOp::Alloc::Handle lAdaptOpAlloc = castHandleT<ES::AdaptOneFifthRuleOp::Alloc>(lFactory.getAllocator(lAdaptOpName)); std::string lMutOpName = "FltVec-MutationGaussianOp"; EC::MutationOp::Alloc::Handle lMutOpAlloc = castHandleT<EC::MutationOp::Alloc>(lFactory.getAllocator(lMutOpName)); std::string lMigOpName = lFactory.getConceptTypeName("MigrationOp"); EC::MigrationOp::Alloc::Handle lMigOpAlloc = castHandleT<EC::MigrationOp::Alloc>(lFactory.getAllocator(lMigOpName)); std::string lStatsCalcOpName = lFactory.getConceptTypeName("StatsCalculateOp"); EC::StatsCalculateOp::Alloc::Handle lStatsCalcOpAlloc = castHandleT<EC::StatsCalculateOp::Alloc>(lFactory.getAllocator(lStatsCalcOpName)); std::string lTermOpName = lFactory.getConceptTypeName("TerminationOp"); EC::TerminationOp::Alloc::Handle lTermOpAlloc = castHandleT<EC::TerminationOp::Alloc>(lFactory.getAllocator(lTermOpName)); std::string lMsWriteOpName = "MilestoneWriteOp"; EC::MilestoneWriteOp::Alloc::Handle lMsWriteOpAlloc = castHandleT<EC::MilestoneWriteOp::Alloc>(lFactory.getAllocator(lMsWriteOpName)); std::string lMPLOpName = "EC-MuPlusLambdaOp"; EC::MuPlusLambdaOp::Alloc::Handle lMPLOpAlloc = castHandleT<EC::MuPlusLambdaOp::Alloc>(lFactory.getAllocator(lMPLOpName)); // Clear bootstrap and mainloop sets ioEvolver.getBootStrapSet().clear(); ioEvolver.getMainLoopSet().clear(); // Set the boostrap operator set EC::InitializationOp::Handle lInitOpBS = castHandleT<EC::InitializationOp>(lInitOpAlloc->allocate()); lInitOpBS->setName(lInitOpName); ioEvolver.getBootStrapSet().push_back(lInitOpBS); EvaluationOp::Handle lEvalOpBS = castHandleT<EvaluationOp>(lEvalOpAlloc->allocate()); lEvalOpBS->setName(lEvalOpName); ioEvolver.getBootStrapSet().push_back(lEvalOpBS); EC::StatsCalculateOp::Handle lStatsCalcOpBS = castHandleT<EC::StatsCalculateOp>(lStatsCalcOpAlloc->allocate()); lStatsCalcOpBS->setName(lStatsCalcOpName); ioEvolver.getBootStrapSet().push_back(lStatsCalcOpBS); EC::TerminationOp::Handle lTermOpBS = castHandleT<EC::TerminationOp>(lTermOpAlloc->allocate()); lTermOpBS->setName(lTermOpName); ioEvolver.getBootStrapSet().push_back(lTermOpBS); EC::MilestoneWriteOp::Handle lMsWriteOpBS = castHandleT<EC::MilestoneWriteOp>(lMsWriteOpAlloc->allocate()); lMsWriteOpBS->setName(lMsWriteOpName); ioEvolver.getBootStrapSet().push_back(lMsWriteOpBS); // Set the mainloop operator set EC::MuPlusLambdaOp::Handle lMPLOp = castHandleT<EC::MuPlusLambdaOp>(lMPLOpAlloc->allocate()); lMPLOp->setName(lMPLOpName); // Set breeder tree BreederNode::Handle lAdaptNode = new BreederNode; lMPLOp->setRootNode(lAdaptNode); lAdaptNode->setBreederOp(castHandleT<ES::AdaptOneFifthRuleOp>(lAdaptOpAlloc->allocate())); lAdaptNode->getBreederOp()->setName(lAdaptOpName); BreederNode::Handle lEvalNode = new BreederNode; lAdaptNode->setFirstChild(lEvalNode); lEvalNode->setBreederOp(castHandleT<EvaluationOp>(lEvalOpAlloc->allocate())); lEvalNode->getBreederOp()->setName(lEvalOpName); BreederNode::Handle lMutNode = new BreederNode; lEvalNode->setFirstChild(lMutNode); lMutNode->setBreederOp(castHandleT<EC::MutationOp>(lMutOpAlloc->allocate())); lMutNode->getBreederOp()->setName(lMutOpName); BreederNode::Handle lSelectMutNode = new BreederNode; lMutNode->setFirstChild(lSelectMutNode); lSelectMutNode->setBreederOp(castHandleT<EC::SelectionOp>(lSelectOpAlloc->allocate())); lSelectMutNode->getBreederOp()->setName(lSelectOpName); // Set remaining operators of mainloop EC::MigrationOp::Handle lMigOpML = castHandleT<EC::MigrationOp>(lMigOpAlloc->allocate()); lMigOpML->setName(lMigOpName); ioEvolver.getMainLoopSet().push_back(lMigOpML); EC::StatsCalculateOp::Handle lStatsCalcOpML = castHandleT<EC::StatsCalculateOp>(lStatsCalcOpAlloc->allocate()); lStatsCalcOpML->setName(lStatsCalcOpName); ioEvolver.getMainLoopSet().push_back(lStatsCalcOpML); EC::TerminationOp::Handle lTermOpML = castHandleT<EC::TerminationOp>(lTermOpAlloc->allocate()); lTermOpML->setName(lTermOpName); ioEvolver.getMainLoopSet().push_back(lTermOpML); EC::MilestoneWriteOp::Handle lMsWriteOpML = castHandleT<EC::MilestoneWriteOp>(lMsWriteOpAlloc->allocate()); lMsWriteOpML->setName(lMsWriteOpName); ioEvolver.getMainLoopSet().push_back(lMsWriteOpML); Beagle_StackTraceEndM(); }