/* * Attempt to place an atom. */ bool Generator::attemptPlaceAtom(Atom& atom, const DArray<double>& diameters, CellList& cellList) { // Shift atom position to primary image within boundary boundary().shift(atom.position()); Vector& pos = atom.position(); // Loop over neighbors, check distance to each. // Return false immediately if any neighbor is too close. CellList::NeighborArray neighbors; cellList.getNeighbors(pos, neighbors); double di = diameters[atom.typeId()]; double rSq, dj, dSq; Atom* neighborPtr; int n = neighbors.size(); for (int j = 0; j < n; ++j) { neighborPtr = neighbors[j]; rSq = boundary().distanceSq(neighborPtr->position(), pos); dj = diameters[neighborPtr->typeId()]; dSq = 0.5*(di + dj); dSq *= dSq; if (rSq < dSq) { return false; } } // If all neighbors are allowed, add atom to cellList cellList.addAtom(atom); return true; }
void MainWindow::addRandomDir(CellList& list) { Cell* cell = list.first(); Cell* ucell = uCell(cell); Cell* rcell = rCell(cell); Cell* dcell = dCell(cell); Cell* lcell = lCell(cell); typedef QMap<Cell::Dirs, Cell*> CellMap; CellMap freecells; if(ucell && ucell->dirs() == Cell::Free) freecells[Cell::U] = ucell; if(rcell && rcell->dirs() == Cell::Free) freecells[Cell::R] = rcell; if(dcell && dcell->dirs() == Cell::Free) freecells[Cell::D] = dcell; if(lcell && lcell->dirs() == Cell::Free) freecells[Cell::L] = lcell; if(freecells.isEmpty()) return; CellMap::ConstIterator it = freecells.constBegin(); for(int i = rand() % freecells.count(); i > 0; --i) ++it; cell->setDirs(Cell::Dirs(cell->dirs() | it.key())); it.value()->setDirs(contrdirs[it.key()]); list.append(it.value()); }
void visitModules() { // Loop on all modules left to process // Hitting a cell adds to the appropriate level of this level-sorted list, // so since cells originally exist top->bottom we process in top->bottom order too. while (!m_todoModps.empty()) { LevelModMap::iterator it = m_todoModps.begin(); AstNodeModule* nodep = it->second; m_todoModps.erase(it); if (!nodep->user5SetOnce()) { // Process once; note clone() must clear so we do it again UINFO(4," MOD "<<nodep<<endl); nodep->iterateChildren(*this); // Note above iterate may add to m_todoModps // // Process interface cells, then non-interface which may ref an interface cell for (int nonIf=0; nonIf<2; ++nonIf) { for (CellList::iterator it=m_cellps.begin(); it!=m_cellps.end(); ++it) { AstCell* nodep = *it; if ((nonIf==0 && nodep->modp()->castIface()) || (nonIf==1 && !nodep->modp()->castIface())) { visitCell(nodep); } } } m_cellps.clear(); } } }
// Return the list of cells crossed when moving from the start point // to the end point. CellList emit() { CellList cells; int gridX = xcell(m_xstart); int gridY = ycell(m_ystart); int xlast = xcell(m_xend); int ylast = ycell(m_yend); cells.push_back( {gridX, gridY} ); while (gridX != xlast || gridY != ylast) { if (m_tMaxX < m_tMaxY) { m_tMaxX += m_tDeltaX; gridX += m_stepX; } else { m_tMaxY += m_tDeltaY; gridY += m_stepY; } cells.push_back( { gridX, gridY } ); } return cells; }
/*! \brief populate the Cell-list with particles non symmetric case * * \tparam dim dimensionality of the space * \tparam T type of the space * \tparam CellList type of cell-list * * \param pos vector of positions * \param cli Cell-list * \param g_m marker (particle below this marker must be inside the domain, particles outside this marker must be outside the domain) * */ template<unsigned int dim, typename T, typename CellList> void populate_cell_list_no_sym(openfpm::vector<Point<dim,T>> & pos, CellList & cli, size_t g_m) { cli.clear(); for (size_t i = 0; i < pos.size() ; i++) { cli.add(pos.get(i), i); } }
bool MainWindow::updateConnections() { bool newconnection[MasterBoardSize * MasterBoardSize]; for(int i = 0; i < MasterBoardSize * MasterBoardSize; i++) newconnection[i] = false; CellList list; if(!root->isRotated()) { newconnection[root->index()] = true; list.append(root); } while(!list.isEmpty()) { Cell* cell = list.first(); Cell* ucell = uCell(cell); Cell* rcell = rCell(cell); Cell* dcell = dCell(cell); Cell* lcell = lCell(cell); if((cell->dirs() & Cell::U) && ucell && (ucell->dirs() & Cell::D) && !newconnection[ucell->index()] && !ucell->isRotated()) { newconnection[ucell->index()] = true; list.append(ucell); } if((cell->dirs() & Cell::R) && rcell && (rcell->dirs() & Cell::L) && !newconnection[rcell->index()] && !rcell->isRotated()) { newconnection[rcell->index()] = true; list.append(rcell); } if((cell->dirs() & Cell::D) && dcell && (dcell->dirs() & Cell::U) && !newconnection[dcell->index()] && !dcell->isRotated()) { newconnection[dcell->index()] = true; list.append(dcell); } if((cell->dirs() & Cell::L) && lcell && (lcell->dirs() & Cell::R) && !newconnection[lcell->index()] && !lcell->isRotated()) { newconnection[lcell->index()] = true; list.append(lcell); } list.remove(list.begin()); } bool isnewconnection = false; for(int i = 0; i < MasterBoardSize * MasterBoardSize; i++) { if(!board[i]->isConnected() && newconnection[i]) isnewconnection = true; board[i]->setConnected(newconnection[i]); } return isnewconnection; }
SqlitePage::CellList SqlitePage::cellList() { CellList cellList; CellPointers cellPtrs = cellPointers(); for (CellPointers::iterator pos = cellPtrs.begin(); pos != cellPtrs.end(); ++pos) { CellInfo cellInfo; cellInfo.offset = *pos; base::varint_t vint_playload = parseVarint(page_.begin() + *pos, page_.end()); base::varint_t vint_rowid = parseVarint(page_.begin() + *pos + vint_playload.length, page_.end()); cellInfo.length = vint_playload.value + vint_playload.length + vint_rowid.length; cellList.push_back(cellInfo); } return cellList; }
SplitState filterGraph(PartitionStack* ps, const GraphType& points, const CellList& cells, int path_length) { // Would not normally go this low level, but it is important this is fast memset(&(mset.front()), 0, mset.size() * sizeof(mset[0])); edgesconsidered = 0; MonoSet monoset(ps->cellCount()); debug_out(3, "EdgeGraph", "filtering: " << cells.size() << " cells out of " << ps->cellCount()); if(path_length == 1) { for(int c : cells) { hashCellSimple(ps, points, monoset, c); } } else { MonoSet hitvertices(ps->domainSize()); for(int c : cells) { hashRangeDeep(ps, points, monoset, hitvertices, ps->cellRange(c)); } memset(&(msetspare.front()), 0, msetspare.size() * sizeof(msetspare[0])); hashRangeDeep2(ps, points, monoset, hitvertices.getMembers()); for(int i : range1(mset.size())) { mset[i] += msetspare[i] * 71; } } debug_out(3, "EdgeGraph", "filtering " << mset << " : " << monoset); return filterPartitionStackByFunctionWithCells(ps, SquareBrackToFunction(&mset), monoset); }
void VerletListTriple::rebuild(){ cutVerlet = cut + getSystem() -> getSkin(); cutsq = cutVerlet * cutVerlet; vlTriples.clear(); // add particles to adress zone CellList cl = getSystem()->storage->getRealCells(); LOG4ESPP_DEBUG(theLogger, "local cell list size = " << cl.size()); for (CellListAllTriplesIterator it(cl); it.isValid(); ++it) { checkTriple(*it->first, *it->second, *it->third); } builds++; LOG4ESPP_DEBUG(theLogger, "rebuilt VerletList (count=" << builds << "), cutsq = " << cutsq << " local size = " << vlTriples.size()); }
CellList* makeCellList(SsProject* proj) { // セルデータの出力と、全てセルデータを集約したリストを作る CellList* cellList = new std::map<const SsCell*, int>(); int cellListIndex = 0; for (size_t mapIndex = 0; mapIndex < proj->cellmapList.size(); mapIndex++) { const SsCellMap* cellMap = proj->cellmapList[mapIndex]; for (size_t cellIndex = 0; cellIndex < cellMap->cells.size(); cellIndex++) { const SsCell* cell = cellMap->cells[cellIndex]; cellList->insert(CellList::value_type(cell, cellListIndex++)); } } return cellList; }
void ForestTechniqueManager::Cell::bin() { // put trees in appropriate cells. TreeList treesNotAssigned; for(TreeList::iterator titr=_trees.begin(); titr!=_trees.end(); ++titr) { Tree* tree = titr->get(); bool assigned = false; for(CellList::iterator citr=_cells.begin(); citr!=_cells.end() && !assigned; ++citr) { if ((*citr)->contains(tree->_position)) { (*citr)->addTree(tree); assigned = true; } } if (!assigned) treesNotAssigned.push_back(tree); } // put the unassigned trees back into the original local tree list. _trees.swap(treesNotAssigned); // prune empty cells. CellList cellsNotEmpty; for(CellList::iterator citr=_cells.begin(); citr!=_cells.end(); ++citr) { if (!((*citr)->_trees.empty())) { cellsNotEmpty.push_back(*citr); } } _cells.swap(cellsNotEmpty); }
/* * Setup cell list for use. */ void Generator::setupCellList(int atomCapacity, Boundary& boundary, const DArray<double>& diameters, CellList& cellList) { // Set maximum atom id = atomCapacity - 1, and allocate // arrays in cellList that are indexed by atom id cellList.setAtomCapacity(atomCapacity); // Compute maximum exclusion diameter double maxDiameter = 0.0; for (int iType = 0; iType < diameters.capacity(); iType++) { if (diameters[iType] > maxDiameter) { maxDiameter = diameters[iType]; } } // Setup grid of empty cells cellList.setup(boundary, maxDiameter); }
SqlitePage::BlockAreas SqlitePage::freeBlocks() { BlockAreas freeBlockAreaList; CellList cellList = this->cellList(); // FIXIT if (cellList.empty()) { return freeBlockAreaList; } BlockArea firstBlock; PageHeader header = pageHeader(); // FIXIT: 8 is not good firstBlock.begin = header.numOfCells * 2 + 8; firstBlock.end = cellList[cellList.size() - 1].offset - 1; freeBlockAreaList.push_back(firstBlock); if (cellList.size() > 1) { // Cell List 是自底向上增长的,所以这里使用反向迭代器遍历 CellList::reverse_iterator rpos; for (rpos = cellList.rbegin(); rpos != cellList.rend(); ++rpos) { BlockArea block; block.begin = rpos->offset; block.end = rpos->offset + rpos->length; CellList::reverse_iterator tmp_rpos = rpos + 1; if (block.end < tmp_rpos->offset - kMinFreeBlockSize && block.end < page_.size() - kMinFreeBlockSize) { freeBlockAreaList.push_back(block); } } } return freeBlockAreaList; }
CellList DistanceToAtom::buildCellList(const QVector<QVector3D> &points, float size, float cutoff, float &cellSize) { CellList cellList; cellSize = cutoff; int numCells = size / cutoff; cellSize = size / numCells; cellList.resize(numCells, vector<vector<vector<QVector3D> > >(numCells, vector<vector<QVector3D> >(numCells))); for(int i=0; i<points.size(); i++) { const QVector3D &p = points[i]; int ci = p[0] / cellSize; int cj = p[1] / cellSize; int ck = p[2] / cellSize; if(ci==numCells) ci = numCells-1; if(cj==numCells) cj = numCells-1; if(ck==numCells) ck = numCells-1; if(!checkRange<int>(ci, 0, numCells-1) || !checkRange<int>(cj, 0, numCells-1) || !checkRange<int>(ck, 0, numCells-1)) { qFatal("DistanceToAtom::buildCellList() error: particle %d is out of cell list bounds.", i); exit(1); } cellList[ci][cj][ck].push_back(p); } return cellList; }
System get_system() { CellList list (1, RVec {0.0, 0.0, 0.0}, RVec {2.0, 2.0, 2.0}); list.add_atom(0.0, 0.0, 0.0); list.add_atom(0.9, 1.0, 1.1); list.add_atom(1.9, 1.9, 1.9); // mean_vx: 3.0, mean_vy: 4.0, mean_vz: 5.0 const vector<double> velocities = { 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0 }; list.vs = velocities; const std::string title {"title of system"}; const RVec box_size {2.0, 2.0, 2.0}; System system {title, box_size}; system.cell_lists.push_back(list); return system; }
void add2cluster_recursive(int i, int n, std::vector<int>& cluster, std::vector<bool>& counted, CellList& cell_list, clstrrule_t cluster_function, arg_t args) { counted[i] = true; cluster.push_back(i); std::vector<int> nbr; cell_list.getNeighborsOf(i, nbr); for (unsigned int j=0; j<nbr.size(); j++) { if(!(counted[nbr[j]])) { if (cluster_function(i, nbr[j], args)) { add2cluster_recursive( nbr[j], n, cluster, counted, cell_list, cluster_function, args); } } } }
/* * Generate random molecules */ bool Generator::generate(int nMolecule, const DArray<double>& diameters, CellList& cellList) { // Preconditions UTIL_CHECK(nMolecule <= species().capacity()); UTIL_CHECK(cellList.atomCapacity() == simulation().atomCapacity()); // Attempt to place all molecules in Species int speciesId = species().id(); int maxAttempt = 200; int iAttempt; bool success; bool isMutable; Species* speciesPtr; for (int iMol = 0; iMol < nMolecule; ++iMol) { Molecule &newMolecule= simulation().getMolecule(speciesId); system().addMolecule(newMolecule); speciesPtr = &system().simulation().species(speciesId); isMutable = speciesPtr->isMutable(); if (isMutable) { speciesPtr->mutator().setMoleculeState(newMolecule, 0); } success = false; iAttempt = 0; while (!success && iAttempt < maxAttempt) { success = attemptPlaceMolecule(newMolecule, diameters, cellList); ++iAttempt; } if (!success) { system().removeMolecule(newMolecule); Log::file() << "Failed to insert Linear molecule " << iMol << "\n"; return false; } } return true; }
virtual void visit(AstCell* nodep, AstNUser*) { // Must do ifaces first, so push to list and do in proper order m_cellps.push_back(nodep); }
/* * Build the PairList, i.e., populate it with atom pairs. */ void PairList::build(CellList& cellList, bool reverseUpdateFlag) { // Precondition assert(isAllocated()); Cell::NeighborArray neighbors; double cutoffSq; const Cell* cellPtr; CellAtom* atom1Ptr; CellAtom* atom2Ptr; Mask* maskPtr; Vector dr; int na; // number of atoms in this cell int nn; // number of neighbors for a cell int i, j; bool hasNeighbor; // Set maximum squared-separation for pairs in Pairlist cutoffSq = cutoff_*cutoff_; // Initialize counters for primary atoms and neighbors atom1Ptrs_.clear(); atom2Ptrs_.clear(); first_.clear(); first_.append(0); // Copy positions and ids into cell list cellList.update(); // Find all neighbors (cell list) cellPtr = cellList.begin(); while (cellPtr) { na = cellPtr->nAtom(); // # of atoms in cell if (na) { cellPtr->getNeighbors(neighbors, reverseUpdateFlag); nn = neighbors.size(); // Loop over primary atoms (atom1) in primary cell for (i = 0; i < na; ++i) { atom1Ptr = neighbors[i]; maskPtr = atom1Ptr->maskPtr(); // Loop over secondary atoms hasNeighbor = false; for (j = i + 1; j < nn; ++j) { atom2Ptr = neighbors[j]; dr.subtract(atom2Ptr->position(), atom1Ptr->position()); if (dr.square() < cutoffSq && !maskPtr->isMasked(atom2Ptr->id())) { atom2Ptrs_.append(atom2Ptr->ptr()); hasNeighbor = true; } } // Complete processing of atom1. if (hasNeighbor) { atom1Ptrs_.append(atom1Ptr->ptr()); first_.append(atom2Ptrs_.size()); } } // for ia } // if (na) // Advance to next cell in a linked list cellPtr = cellPtr->nextCellPtr(); } // Postconditions if (atom1Ptrs_.size()) { if (first_.size() != atom1Ptrs_.size() + 1) { UTIL_THROW("Array size problem"); } if (first_[0] != 0) { UTIL_THROW("Incorrect first element of first_"); } if (first_[atom1Ptrs_.size()] != atom2Ptrs_.size()) { UTIL_THROW("Incorrect last element of first_"); } } // Increment buildCounter_= number of times the list has been built. ++buildCounter_; // Increment maxima if (atom1Ptrs_.size() > maxNAtomLocal_) { maxNAtomLocal_ = atom1Ptrs_.size(); } if (atom2Ptrs_.size() > maxNPairLocal_) { maxNPairLocal_ = atom2Ptrs_.size(); } }
/* * Build the PairList, i.e., populate it with atom pairs. */ void PairList::build(CellList& cellList, bool reverseUpdateFlag) { // Precondition assert(isAllocated()); Cell::NeighborArray neighbors; double dRSq, cutoffSq; const Cell* cellPtr; Atom* atom1Ptr; Atom* atom2Ptr; Mask* maskPtr; Vector dr; int na; // number of atoms in this cell int nn; // number of neighbors for a cell int atom2Id; // atom Id for second atom int i, j; bool foundNeighbor; // Set maximum squared-separation for pairs in Pairlist cutoffSq = cutoff_*cutoff_; // Initialize counters for primary atoms and neighbors atom1Ptrs_.clear(); atom2Ptrs_.clear(); first_.clear(); first_.append(0); // Find all neighbors (cell list) cellPtr = cellList.begin(); while (cellPtr) { cellPtr->getNeighbors(neighbors, reverseUpdateFlag); na = cellPtr->nAtom(); nn = neighbors.size(); // Loop over primary atoms (atom1) in primary cell for (i = 0; i < na; ++i) { atom1Ptr = neighbors[i]; maskPtr = &(atom1Ptr->mask()); foundNeighbor = false; // Loop over secondary atoms (atom2) in primary cell for (j = 0; j < na; ++j) { atom2Ptr = neighbors[j]; if (atom2Ptr > atom1Ptr) { atom2Id = atom2Ptr->id(); if (!maskPtr->isMasked(atom2Id)) { dr.subtract(atom2Ptr->position(), atom1Ptr->position()); dRSq = dr.square(); if (dRSq < cutoffSq) { // If first neighbor of atom1, add atom1 to atom1Ptrs_ if (!foundNeighbor) { atom1Ptrs_.append(atom1Ptr); foundNeighbor = true; } // Append 2nd atom to atom2Ptrs_[] atom2Ptrs_.append(atom2Ptr); } } } } // Atoms in neighboring cells for (j = na; j < nn; ++j) { atom2Ptr = neighbors[j]; atom2Id = atom2Ptr->id(); if (!maskPtr->isMasked(atom2Id)) { dr.subtract(atom2Ptr->position(), atom1Ptr->position()); dRSq = dr.square(); if (dRSq < cutoffSq) { // If first_ neighbor, record iAtomId in atom1Ptrs_ if (!foundNeighbor) { atom1Ptrs_.append(atom1Ptr); foundNeighbor = true; } // Append Id of 2nd atom in pair to atom2Ptrs_[] atom2Ptrs_.append(atom2Ptr); } } } // When finished with atom1, set next element of first_ array. if (foundNeighbor) { first_.append(atom2Ptrs_.size()); } } // Advance to next cell in a linked list cellPtr = cellPtr->nextCellPtr(); } // Postconditions if (atom1Ptrs_.size()) { if (first_.size() != atom1Ptrs_.size() + 1) { UTIL_THROW("Array size problem"); } if (first_[0] != 0) { UTIL_THROW("Incorrect first element of first_"); } if (first_[atom1Ptrs_.size()] != atom2Ptrs_.size()) { UTIL_THROW("Incorrect last element of first_"); } } // Increment buildCounter_= number of times the list has been built. ++buildCounter_; // Increment maxima if (atom1Ptrs_.size() > maxNAtomLocal_) { maxNAtomLocal_ = atom1Ptrs_.size(); } if (atom2Ptrs_.size() > maxNPairLocal_) { maxNPairLocal_ = atom2Ptrs_.size(); } }
void MainWindow::newGame(int sk) { if (sk==Settings::EnumSkill::Novice || sk==Settings::EnumSkill::Normal || sk==Settings::EnumSkill::Expert || sk==Settings::EnumSkill::Master) { Settings::setSkill(sk); } if(Settings::skill() == Settings::EnumSkill::Master) wrapped = true; else wrapped = false; KExtHighscore::setGameType(Settings::skill()); Settings::writeConfig(); m_clickcount = 0; QString clicks = i18n("Click: %1"); statusBar()->changeItem(clicks.arg(QString::number(m_clickcount)),1); KNotifyClient::event(winId(), "startsound", i18n("New Game")); for(int i = 0; i < MasterBoardSize * MasterBoardSize; i++) { board[i]->setDirs(Cell::None); board[i]->setConnected(false); board[i]->setRoot(false); board[i]->setLocked(false); } const int size = (Settings::skill() == Settings::EnumSkill::Novice) ? NoviceBoardSize : (Settings::skill() == Settings::EnumSkill::Normal) ? NormalBoardSize : (Settings::skill() == Settings::EnumSkill::Expert) ? ExpertBoardSize : MasterBoardSize; const int start = (MasterBoardSize - size) / 2; const int rootrow = rand() % size; const int rootcol = rand() % size; root = board[(start + rootrow) * MasterBoardSize + start + rootcol]; root->setConnected(true); root->setRoot(true); while(true) { for(int row = start; row < start + size; row++) for(int col = start; col < start + size; col++) board[row * MasterBoardSize + col]->setDirs(Cell::Free); CellList list; list.append(root); if(rand() % 2) addRandomDir(list); while(!list.isEmpty()) { if(rand() % 2) { addRandomDir(list); if(rand() % 2) addRandomDir(list); list.remove(list.begin()); } else { list.append(list.first()); list.remove(list.begin()); } } int cells = 0; for(int i = 0; i < MasterBoardSize * MasterBoardSize; i++) { Cell::Dirs d = board[i]->dirs(); if((d != Cell::Free) && (d != Cell::None)) cells++; } if(cells >= MinimumNumCells) break; } for(int i = 0; i < MasterBoardSize * MasterBoardSize; i++) board[i]->rotate((rand() % 4) * 90); updateConnections(); }
/** * Generate random molecules */ void Linear::generateMolecules(int nMolecule, DArray<double> exclusionRadius, System& system, BondPotential *bondPotentialPtr, const Boundary &boundary) { int iMol; // Set up a cell list with twice the maxium exclusion radius as the // cell size double maxExclusionRadius = 0.0; for (int iType = 0; iType < system.simulation().nAtomType(); iType++) { if (exclusionRadius[iType] > maxExclusionRadius) maxExclusionRadius = exclusionRadius[iType]; } // the minimum cell size is twice the maxExclusionRadius, // but to save memory, we take 2 times that value CellList cellList; cellList.allocate(system.simulation().atomCapacity(), boundary, 2.0*2.0*maxExclusionRadius); if (nMolecule > capacity()) UTIL_THROW("nMolecule > Species.capacity()!"); Simulation& sim = system.simulation(); for (iMol = 0; iMol < nMolecule; ++iMol) { // Add a new molecule to the system Molecule &newMolecule= sim.getMolecule(id()); system.addMolecule(newMolecule); // Try placing atoms bool moleculeHasBeenPlaced = false; for (int iAttempt = 0; iAttempt< maxPlacementAttempts_; iAttempt++) { // Place first atom Vector pos; system.boundary().randomPosition(system.simulation().random(),pos); Atom &thisAtom = newMolecule.atom(0); // check if the first atom can be placed at the new position CellList::NeighborArray neighbors; cellList.getNeighbors(pos, neighbors); int nNeighbor = neighbors.size(); bool canBePlaced = true; for (int j = 0; j < nNeighbor; ++j) { Atom *jAtomPtr = neighbors[j]; double r = sqrt(system.boundary().distanceSq( jAtomPtr->position(), pos)); if (r < (exclusionRadius[thisAtom.typeId()] + exclusionRadius[jAtomPtr->typeId()])) { canBePlaced = false; break; } } if (canBePlaced) { thisAtom.position() = pos; cellList.addAtom(thisAtom); // Try to recursively place other atoms if (tryPlaceAtom(newMolecule, 0, exclusionRadius, system, cellList, bondPotentialPtr, system.boundary())) { moleculeHasBeenPlaced = true; break; } else { cellList.deleteAtom(thisAtom); } } } if (! moleculeHasBeenPlaced) { std::ostringstream oss; oss << "Failed to place molecule " << newMolecule.id(); UTIL_THROW(oss.str().c_str()); } } #if 0 // Check for (int iMol =0; iMol < nMolecule; ++iMol) { Molecule::AtomIterator atomIter; system.molecule(id(),iMol).begin(atomIter); for (; atomIter.notEnd(); ++atomIter) { for (int jMol =0; jMol < nMolecule; ++jMol) { Molecule::AtomIterator atomIter2; system.molecule(id(),jMol).begin(atomIter2); for (; atomIter2.notEnd(); ++atomIter2 ) { if (atomIter2->id() != atomIter->id()) { double r = sqrt(boundary.distanceSq( atomIter->position(),atomIter2->position())); if (r < (exclusionRadius[atomIter->typeId()]+ exclusionRadius[atomIter2->typeId()])) { std::cout << r << std::endl; UTIL_THROW("ERROR"); } } } } } } #endif }
/** * Recursive function to try to place an atom. */ bool Linear::tryPlaceAtom(Molecule& molecule, int atomId, DArray<double> exclusionRadius, System& system, CellList &cellList, BondPotential *bondPotentialPtr, const Boundary &boundary) { Atom& lastAtom = molecule.atom(atomId); Atom& thisAtom = molecule.atom(++atomId); Random& random = system.simulation().random(); bool hasBeenPlaced = false; for (int iAttempt = 0; iAttempt < maxPlacementAttempts_; iAttempt++) { // draw a random bond vector int beta = 1; Vector v; random.unitVector(v); v *= bondPotentialPtr->randomBondLength(&random, beta, calculateBondTypeId(lastAtom.indexInMolecule())); Vector newPos; newPos = lastAtom.position(); newPos += v; // shift into simulation cell boundary.shift(newPos); // check if the atom can be placed at the new position CellList::NeighborArray neighbors; cellList.getNeighbors(newPos, neighbors); int nNeighbor = neighbors.size(); bool canBePlaced = true; for (int j = 0; j < nNeighbor; ++j) { Atom *jAtomPtr = neighbors[j]; double r = sqrt(boundary.distanceSq( jAtomPtr->position(), newPos)); if (r < (exclusionRadius[thisAtom.typeId()] + exclusionRadius[jAtomPtr->typeId()])) { canBePlaced = false; break; } } if (canBePlaced) { // place the particle thisAtom.position() = newPos; // add to cell list cellList.addAtom(thisAtom); // are we add the end of the chain? if (atomId == molecule.nAtom()-1) return true; // recursion step if (! tryPlaceAtom(molecule, atomId, exclusionRadius, system, cellList, bondPotentialPtr, boundary) ) { // If the next monomer cannot be inserted, delete this monomer // again cellList.deleteAtom(thisAtom); } else { hasBeenPlaced = true; break; } } } return hasBeenPlaced; }
int main(int argc, char * argv[]) { ValueType begin, end, rup, refh, cellSize; std::string ifile, ofile, method; ValueType x0, x1; po::options_description desc ("Allow options"); desc.add_options() ("help,h", "print this message") ("begin,b", po::value<ValueType > (&begin)->default_value(0.f), "start time") ("end,e", po::value<ValueType > (&end )->default_value(0.f), "end time") ("x0", po::value<ValueType > (&x0)->default_value(0.f), "lower bound of the interval") ("x1", po::value<ValueType > (&x1)->default_value(1.f), "upper bound of the interval, if x1 == 0, use the whole box") ("rup,u", po::value<ValueType > (&rup)->default_value(3.f), "max r to make rdf") ("refh", po::value<ValueType > (&refh)->default_value(0.01f), "bin size") ("cell-size,c", po::value<ValueType > (&cellSize)->default_value(1.f), "cell list radius") ("method,m", po::value<std::string > (&method)->default_value ("adress"), "type of simulation to analyze") ("input,f", po::value<std::string > (&ifile)->default_value ("traj.xtc"), "the input .xtc file") ("output,o", po::value<std::string > (&ofile)->default_value ("rdf.out"), "the output file"); po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify (vm); if (vm.count("help")){ std::cout << desc<< "\n"; return 0; } if (x0 > x1) { ValueType tmpx = x0; x0 = x1; x1 = tmpx; } std::cout << "###################################################" << std::endl; std::cout << "# begin->end: " << begin << " " << end << std::endl; std::cout << "# [x0, x1 ]: " << x0 << " " << x1 << std::endl; std::cout << "# rup: " << rup << std::endl; std::cout << "# refh: " << refh << std::endl; std::cout << "# method: " << method << std::endl; std::cout << "# input: " << ifile << std::endl; std::cout << "###################################################" << std::endl; XDRFILE *fp; int natoms, step; float time; matrix box; rvec * xx; float prec = 1000; float time_prec = .01; char tmpfname[1024]; strncpy (tmpfname, ifile.c_str(), 1023); int c; if ((c = read_xtc_natoms (tmpfname, &natoms)) == 0) { // printf ("%d %d\n", c, natoms); xx = (rvec *) malloc (sizeof(rvec) * natoms); } else { // printf ("%d %d\n", c, natoms); fprintf (stderr, "error read_xtc_natoms"); exit (1); } fp = xdrfile_open (ifile.c_str(), "r"); if (fp == NULL){ std::cerr << "cannot open file " << ifile << std::endl; exit (1); } if (read_xtc (fp, natoms, &step, &time, box, xx, &prec) != 0) { std::cerr << "error reading file " << ifile << std::endl; return 1; } int nmolecules = 0; if (method == std::string("adress")){ nmolecules = natoms / 4; } else if (method == std::string("atom")){ nmolecules = natoms / 3; } else if (method == std::string("cg")){ nmolecules = natoms; } else { std::cerr << "wrong method" << std::endl; return 1; } VectorType vbox; vbox.x = box[0][0]; vbox.y = box[1][1]; vbox.z = box[2][2]; if (cellSize >= .5 * vbox.x){ std::cerr << "the cell size should be less than half of the box size" << std::endl; return 1; } std::vector<std::vector<ValueType > > coms; coms.reserve (nmolecules); CellList clist (nmolecules, vbox, cellSize); Rdf myrdf; myrdf.reinit (rup, refh, x0, x1); int countread = 0; while (read_xtc (fp, natoms, &step, &time, box, xx, &prec) == 0){ if (end != 0.f) { if (time < begin - time_prec){ continue; } else if (time > end + time_prec) { break; } } else { if (time < begin - time_prec) continue; } if (countread++ % 1 == 0){ printf ("# load frame at time: %.1f ps\r", time); fflush (stdout); } coms.clear (); if (method == std::string ("adress")){ int nmol = natoms / 4; for (int i = 0; i < nmol; ++i){ if (xx[i*4+3][0] < 0 ) xx[i*4+3][0] += box[0][0]; else if (xx[i*4+3][0] >= box[0][0]) xx[i*4+3][0] -= box[0][0]; if (xx[i*4+3][1] < 0 ) xx[i*4+3][1] += box[1][1]; else if (xx[i*4+3][1] >= box[1][1]) xx[i*4+3][1] -= box[1][1]; if (xx[i*4+3][2] < 0 ) xx[i*4+3][2] += box[2][2]; else if (xx[i*4+3][2] >= box[2][2]) xx[i*4+3][2] -= box[2][2]; std::vector<ValueType > tmp(3); tmp[0] = xx[i*4+3][0]; tmp[1] = xx[i*4+3][1]; tmp[2] = xx[i*4+3][2]; coms.push_back(tmp); } } else if (method == std::string ("atom")){ int nmol = natoms / 3; for (int i = 0; i < nmol; ++i){ std::vector<ValueType > com(3, 0.); for (int dd = 0; dd < 3; ++dd){ ValueType dx1, dx2; dx1 = xx[i*3+1][dd] - xx[i*3+0][dd]; dx2 = xx[i*3+2][dd] - xx[i*3+0][dd]; if (dx1 > 0.5 * box[dd][dd]) {dx1 -= box[dd][dd]; printf ("hit\n");} if (dx1 <-0.5 * box[dd][dd]) {dx1 += box[dd][dd]; printf ("hit\n");} if (dx2 > 0.5 * box[dd][dd]) {dx2 -= box[dd][dd]; printf ("hit\n");} if (dx2 <-0.5 * box[dd][dd]) {dx2 += box[dd][dd]; printf ("hit\n");} com[dd] = 16. * xx[i*3+0][dd] + 1. * (xx[i*3+0][dd] + dx1) + 1. * (xx[i*3+0][dd] + dx2); com[dd] /= 18.; if (com[dd] < 0 ) com[dd] += box[dd][dd]; else if (com[dd] >= box[dd][dd]) com[dd] -= box[dd][dd]; } coms.push_back (com); } } else if (method == std::string ("cg")){ int nmol = natoms; for (int i = 0; i < nmol; ++i){ if (xx[i][0] < 0 ) xx[i][0] += box[0][0]; else if (xx[i][0] >= box[0][0]) xx[i][0] -= box[0][0]; if (xx[i][1] < 0 ) xx[i][1] += box[1][1]; else if (xx[i][1] >= box[1][1]) xx[i][1] -= box[1][1]; if (xx[i][2] < 0 ) xx[i][2] += box[2][2]; else if (xx[i][2] >= box[2][2]) xx[i][2] -= box[2][2]; std::vector<ValueType > tmp(3); tmp[0] = xx[i][0]; tmp[1] = xx[i][1]; tmp[2] = xx[i][2]; coms.push_back(tmp); } } clist.rebuild (coms); myrdf.deposit (coms, vbox, clist); } printf ("\n"); xdrfile_close (fp); free (xx); myrdf.calculate(); FILE *fout = fopen (ofile.c_str(), "w"); if (fout == NULL){ std::cerr << "cannot open file " << ofile << std::endl; exit (1); } fprintf (fout, "%f %f\n", 0., myrdf.getValue(0)); for (unsigned i = 1; i < myrdf.getN(); ++i){ fprintf (fout, "%f %f\n", (i) * refh, myrdf.getValue(i)); } fclose (fout); return 0; }
int main(int argc, char * argv[]) { double begin, end, cellSize; string ifile, ofile, odir; int func_numb_threads; int numb_mol_atom; int max_ring; double rcut, acut; bool p_def_ring (false), p_mol_dist(false); po::options_description desc ("Allow options"); desc.add_options() ("help,h", "print this message") ("begin,b", po::value<double > (&begin)->default_value(0.f), "start time") ("end,e", po::value<double > (&end )->default_value(0.f), "end time") ("r-cut,r", po::value<double > (&rcut)->default_value(0.35), "the cut-off of O-O dist") ("angle-cut,a", po::value<double > (&acut)->default_value(30), "the cut-off of O-H .. O angle") ("max-ring,m", po::value<int > (&max_ring)->default_value(10), "the maximum size of rings") ("def-ring,D", "print the non 6-ring at each step") ("mol-dist,M", "print the molecular ring distribution") ("numb-mol-atom", po::value<int > (&numb_mol_atom)->default_value(4), "number of sites in the water molecule") ("numb-threads,t", po::value<int > (&func_numb_threads)->default_value(1), "number of threads") ("input,f", po::value<string > (&ifile)->default_value ("traj.xtc"), "the input .xtc file") ("output,o", po::value<string > (&ofile)->default_value ("hbring.out"), "the output file") ("output-dir", po::value<string > (&odir)->default_value ("hbring"), "the output directory of H-bond detailed information"); po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify (vm); if (vm.count("help")){ cout << desc<< "\n"; return 0; } if (vm.count("def-ring")){ p_def_ring = true; } if (vm.count("mol-dist")){ p_mol_dist = true; } cellSize = rcut + 1e-6; cout << "###################################################" << endl; cout << "# computes the H-bond" << endl; cout << "# begin->end: " << begin << " " << end << endl; cout << "# numb sites in water: " << numb_mol_atom << endl; cout << "# input: " << ifile << endl; cout << "# output: " << ofile << endl; if (p_def_ring){ cout << "# output dir: " << odir << endl; } cout << "# rcut: " << rcut << endl; cout << "# acut: " << acut << endl; cout << "###################################################" << endl; XDRFILE *fp; int natoms, step; float time; matrix box; rvec * xx; float prec = 1000; float time_prec = .01; char tmpfname[1024]; strncpy (tmpfname, ifile.c_str(), 1023); { int c; if ((c = read_xtc_natoms (tmpfname, &natoms)) == 0) { xx = (rvec *) malloc (sizeof(rvec) * natoms); } else { fprintf (stderr, "error read_xtc_natoms\n"); exit (1); } } fp = xdrfile_open (ifile.c_str(), "r"); if (fp == NULL){ cerr << "cannot open file " << ifile << endl; exit (1); } if (read_xtc (fp, natoms, &step, &time, box, xx, &prec) != 0) { cerr << "error reading file " << ifile << endl; return 1; } xdrfile_close (fp); int nmolecules = 0; nmolecules = natoms / numb_mol_atom; VectorType vbox; vbox.x = box[0][0]; vbox.y = box[1][1]; vbox.z = box[2][2]; if (cellSize >= .5 * vbox.x){ cerr << "the cell size should be less than half of the box size" << endl; return 1; } vector<vector<double > > coms; coms.reserve (nmolecules); vector<vector<vector<double > > > waters; waters.reserve (nmolecules * 3); CellList clist (nmolecules, vbox, cellSize); HydrogenBond_Geo_1::Parameters param (rcut, acut); HydrogenBondAnalysis<HydrogenBond_Geo_1> hba (param, nmolecules, func_numb_threads); RingStats rs (nmolecules, max_ring); int countread = 0; ofstream fout (ofile.c_str()); rs.print_head (fout); if (p_def_ring || p_mol_dist){ if (access (odir.c_str(), 0) == -1) { cout << "# dir " << odir << " does not exist, create." << endl; if (mkdir (odir.c_str(), 0755)){ cerr << "# dir " << odir << " creation failed." << endl; return 1; } } } fp = xdrfile_open (ifile.c_str(), "r"); if (fp == NULL){ cerr << "cannot open file " << ifile << endl; exit (1); } if (p_mol_dist) { // open_mol_defect (odir, nmolecules); } while (read_xtc (fp, natoms, &step, &time, box, xx, &prec) == 0){ if (end != 0.f) { if (time < begin - time_prec){ continue; } else if (time > end + time_prec) { break; } } else { if (time < begin - time_prec) continue; } if (((countread++)) % 1 == 0){ printf ("# load frame at time: %.1f ps\r", time); fflush (stdout); } coms.clear (); waters.clear (); int nmol = natoms / numb_mol_atom; vector<double > read_com(3, 0.); vector<vector<double > > read_water(3); for (int ii = 0; ii < 3; ++ii) read_water[ii].resize(3, 0.); for (int ii = 0; ii < nmol; ++ii){ for (int dd = 0; dd < 3; ++dd){ read_com[dd] = xx[ii*numb_mol_atom][dd]; if (read_com[dd] < 0 ) read_com[dd] += box[dd][dd]; else if (read_com[dd] >= box[dd][dd]) read_com[dd] -= box[dd][dd]; } for (int jj = 0; jj < 3; ++jj){ for (int dd = 0; dd < 3; ++dd){ read_water[jj][dd] = xx[ii*numb_mol_atom + jj][dd]; } } for (int dd = 0; dd < 3; ++dd){ if (read_water[0][dd] < 0 ) read_water[0][dd] += box[dd][dd]; else if (read_water[0][dd] >= box[dd][dd]) read_water[0][dd] -= box[dd][dd]; } align_water (box, read_water); coms.push_back (read_com); waters.push_back (read_water); } vbox.x = box[0][0]; vbox.y = box[1][1]; vbox.z = box[2][2]; clist.reinit (nmolecules, vbox, cellSize); clist.rebuild (coms); vector<double > vect_box(3); for (int dd = 0; dd < 3; ++dd) vect_box[dd] = box[dd][dd]; vector<vector<int > > h_list; hba.computeBondList (h_list, clist, vect_box, waters); // for (unsigned ii = 0; ii < h_list.size(); ++ii){ // cout << ii << " \t " << h_list[ii].size() << " \t "; // for (unsigned jj = 0; jj < h_list[ii].size(); ++jj){ // cout << h_list[ii][jj] << " " ; // } // cout << endl; // } RingAnalysis ra; vector<vector<vector<int > > > r_list; ra.compute (r_list, h_list, max_ring, func_numb_threads); vector<vector<int > > ur_list; ra.unique_list (ur_list, r_list); rs.mol_deposite (r_list); rs.sys_deposite (ur_list); rs.print_frame (fout, time); // for (unsigned jj = 0; jj < r_list[0].size(); ++jj){ // cout << "ring " << jj << " " ; // for (unsigned kk = 0; kk < r_list[0][jj].size(); ++kk){ // cout << r_list[0][jj][kk] << " "; // } // cout << endl; // } // for (unsigned tt = 0; tt < r_list.size(); ++tt){ // cout << " atom " << tt << endl; // for (unsigned jj = 0; jj < r_list[tt].size(); ++jj){ // cout << "ring " << jj << " " ; // for (unsigned kk = 0; kk < r_list[tt][jj].size(); ++kk){ // cout << r_list[tt][jj][kk] << " "; // } // cout << endl; // } // // break; // } // for (unsigned tt = 0; tt < ur_list.size(); ++tt){ // cout << tt << " \t " ; // for (unsigned kk = 0; kk < ur_list[tt].size(); ++kk){ // cout << ur_list[tt][kk] << " "; // } // cout << endl; // } if (p_def_ring){ print_step (odir, step, time, ur_list); } if (p_mol_dist){ print_mol_dist (odir, step, time, rs.get_frame_mol_dist()); } } printf ("\n"); free (xx); xdrfile_close (fp); return 0; }
void Corr3:: deposit (const std::vector<std::vector<ValueType> > & coord, const VectorType & box, const CellList & clist) { int xiter = rup / clist.getCellSize().x; if (xiter * clist.getCellSize().x < rup) xiter ++; int yiter = rup / clist.getCellSize().y; if (yiter * clist.getCellSize().y < rup) yiter ++; int ziter = rup / clist.getCellSize().z; if (ziter * clist.getCellSize().z < rup) ziter ++; IntVectorType nCell = clist.getNumCell(); ValueType myNatom = 0.; printf ("\n"); for (unsigned iCellIndex = 0; iCellIndex < unsigned(nCell.x * nCell.y * nCell.z); ++iCellIndex){ // myNatom += clist.getList()[iCellIndex].size(); printf ("## calculating cell %d in %d \r", iCellIndex, unsigned(nCell.x * nCell.y * nCell.z)); fflush (stdout); std::vector<unsigned > neighborCellIndex = clist.neighboringCellIndex (iCellIndex, IntVectorType (xiter, yiter, ziter)); for (unsigned iNeighborCellIndex = 0; iNeighborCellIndex < neighborCellIndex.size(); ++iNeighborCellIndex){ unsigned jCellIndex = neighborCellIndex[iNeighborCellIndex]; for (unsigned ii = 0; ii < clist.getList()[iCellIndex].size(); ++ii){ VectorType icoord; icoord.x = coord[clist.getList()[iCellIndex][ii]][0]; if (x1 != 0. && (!(icoord.x >= x0 && icoord.x < x1))) continue; if (iNeighborCellIndex == 0) myNatom += 1.; icoord.y = coord[clist.getList()[iCellIndex][ii]][1]; icoord.z = coord[clist.getList()[iCellIndex][ii]][2]; bool sameCell (iCellIndex == jCellIndex); for (unsigned jj = 0; jj < clist.getList()[jCellIndex].size(); ++jj){ if (sameCell && ii == jj) continue; VectorType jcoord; jcoord.x = coord[clist.getList()[jCellIndex][jj]][0]; jcoord.y = coord[clist.getList()[jCellIndex][jj]][1]; jcoord.z = coord[clist.getList()[jCellIndex][jj]][2]; VectorType diff; diff.x = - icoord.x + jcoord.x; diff.y = - icoord.y + jcoord.y; diff.z = - icoord.z + jcoord.z; if (diff.x < -.5 * box.x) diff.x += box.x; else if (diff.x >= .5 * box.x) diff.x -= box.x; if (diff.y < -.5 * box.y) diff.y += box.y; else if (diff.y >= .5 * box.y) diff.y -= box.y; if (diff.z < -.5 * box.z) diff.z += box.z; else if (diff.z >= .5 * box.z) diff.z -= box.z; ValueType dr = diff.x * diff.x + diff.y * diff.y + diff.z * diff.z; dr = sqrt (dr); unsigned index = (dr + offset) / binSize; if (dr < rup){ if (index >= unsigned(nbins)){ // printf ("# dr: %f, index: %d, rup: %f, nbins: %d\n", // dr, index, rup, nbins); index = nbins - 1; } hist[index] += 1.; double tmpx = h1extend + rup; // if (tmpx < rup) tmpx = rup; double body3range = sqrt(tmpx * tmpx + h2extend * h2extend); int body3xiter = body3range / clist.getCellSize().x; if (body3xiter * clist.getCellSize().x < body3range) body3xiter ++; int body3yiter = body3range / clist.getCellSize().y; if (body3yiter * clist.getCellSize().y < body3range) body3yiter ++; int body3ziter = body3range / clist.getCellSize().z; if (body3ziter * clist.getCellSize().z < body3range) body3ziter ++; std::vector<unsigned > body3NeighborCellIndex = clist.neighboringCellIndex (iCellIndex, IntVectorType (body3xiter, body3yiter, body3ziter)); for (unsigned ibody3Cell = 0; ibody3Cell < body3NeighborCellIndex.size(); ++ibody3Cell){ unsigned kCellIndex = body3NeighborCellIndex[ibody3Cell]; for (unsigned kk = 0; kk < clist.getList()[kCellIndex].size(); ++kk){ if (clist.getList()[iCellIndex][ii] == clist.getList()[kCellIndex][kk] || clist.getList()[jCellIndex][jj] == clist.getList()[kCellIndex][kk] ) continue; VectorType kcoord; kcoord.x = coord[clist.getList()[kCellIndex][kk]][0]; kcoord.y = coord[clist.getList()[kCellIndex][kk]][1]; kcoord.z = coord[clist.getList()[kCellIndex][kk]][2]; VectorType diff2; diff2.x = - icoord.x + kcoord.x; diff2.y = - icoord.y + kcoord.y; diff2.z = - icoord.z + kcoord.z; if (diff2.x < -.5 * box.x) diff2.x += box.x; else if (diff2.x >= .5 * box.x) diff2.x -= box.x; if (diff2.y < -.5 * box.y) diff2.y += box.y; else if (diff2.y >= .5 * box.y) diff2.y -= box.y; if (diff2.z < -.5 * box.z) diff2.z += box.z; else if (diff2.z >= .5 * box.z) diff2.z -= box.z; double h1 = (diff.x * diff2.x + diff.y * diff2.y + diff.z * diff2.z ) / dr; if (h1 <= h1low || h1 >= h1up) continue; double dr22 = (diff2.x * diff2.x + diff2.y * diff2.y + diff2.z * diff2.z); double h2 = sqrt(dr22 - h1 * h1); if (h2 >= h2extend) continue; dists[index].deposit (h1, h2); } } } } } } } printf ("\n"); nframe ++; if (x1 == x0){ rho += myNatom / (box.x * box.y * box.z); } else { rho += myNatom / ((x1 - x0) * box.y * box.z); } natom += myNatom; }
int main(int argc, char * argv[]) { std::string ifile, ofile; double qh, qo; double mh, mo; float begin, end; float time_prec = .01; unsigned every, nDataBlock; double rup, refh, cellSize; po::options_description desc ("Program of calculating the dielectric constant.\nAllow options"); desc.add_options() ("help,h", "print this message") ("change-h,q", po::value<double > (&qh)->default_value (0.417), "the charge of hydrogen atom") ("mass-h", po::value<double > (&mh)->default_value (1.008000), "the mass of hydrogen atom") ("mass-o", po::value<double > (&mo)->default_value (15.999400), "the mass of hydrogen atom") ("begin,b", po::value<float > (&begin)->default_value(0.f), "start time") ("end,e", po::value<float > (&end )->default_value(0.f), "end time") ("every", po::value<unsigned > (&every)->default_value(1), "every frame") ("num-data-block", po::value<unsigned > (&nDataBlock)->default_value(1), "number of data in each block") ("rup,u", po::value<double > (&rup)->default_value(3.f), "max r to make rdf") ("refh", po::value<double > (&refh)->default_value(0.01f), "bin size") ("cell-size,c", po::value<double > (&cellSize)->default_value(1.f), "cell list radius") ("input,f", po::value<std::string > (&ifile)->default_value ("traj.xtc"), "the input .xtc file") ("output,o", po::value<std::string > (&ofile)->default_value ("gkr.out"), "the output file"); po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify (vm); if (vm.count("help")){ std::cout << desc<< "\n"; return 0; } qo = - 2. * qh; int countread = 0; int realcountread = 0; XtcLoader tjl (ifile.c_str()); if (rup * 2. > tjl.getBox()[0]) { cerr << "to large rup, set to half box size" << endl; rup = 0.5 * tjl.getBox()[0]; } int nmols = tjl.getNAtoms()/3; VectorType vbox; vbox.x = tjl.getBox()[0]; vbox.y = tjl.getBox()[1]; vbox.z = tjl.getBox()[2]; CellList clist (nmols, vbox, cellSize); KirkwoodFactor gkr; gkr.reinit (rup, refh, nDataBlock); std::vector<std::vector<ValueType > > coms; coms.resize (nmols); std::vector<std::vector<ValueType > > dipoles; dipoles.resize (nmols); while (true == tjl.load()){ countread ++; if ((countread-1) % every != 0) continue; float time = tjl.getTime(); if (end != 0.f) { if (time < begin - time_prec){ continue; } else if (time > end + time_prec) { break; } } else { if (time < begin - time_prec) continue; } if ((realcountread++) % 1 == 0){ printf ("# load frame at time: %.1f ps\r", time); fflush (stdout); } vector<vector<double > > frame; tjl.getFrame (frame); // we assume here the tip3p water for (int ii = 0; ii < nmols; ++ii){ vector<double > moment (3, 0.); vector<double > com (3, 0.); double totmi = 1./(mh * 2. + mo); for (int dd = 0; dd < 3; ++dd){ moment[dd] += frame[ii*3+0][dd] * qo; moment[dd] += frame[ii*3+1][dd] * qh; moment[dd] += frame[ii*3+2][dd] * qh; // com[dd] += frame[ii*3+0][dd] * mo * totmi; // com[dd] += frame[ii*3+1][dd] * mh * totmi; // com[dd] += frame[ii*3+2][dd] * mh * totmi; } for (int dd = 0; dd < 3; ++dd){ // ValueType dx1, dx2; // dx1 = frame[ii*3+1][dd] - frame[ii*3+0][dd]; // dx2 = frame[ii*3+2][dd] - frame[ii*3+0][dd]; // if (dx1 > 0.5 * tjl.getBox()[dd]) {dx1 -= tjl.getBox()[dd]; printf ("hit\n");} // if (dx1 <-0.5 * tjl.getBox()[dd]) {dx1 += tjl.getBox()[dd]; printf ("hit\n");} // if (dx2 > 0.5 * tjl.getBox()[dd]) {dx2 -= tjl.getBox()[dd]; printf ("hit\n");} // if (dx2 <-0.5 * tjl.getBox()[dd]) {dx2 += tjl.getBox()[dd]; printf ("hit\n");} // com[dd] = mo * totmi * frame[ii*3+0][dd] + mh * totmi * (frame[ii*3+0][dd] + dx1) + mh * totmi * (frame[ii*3+0][dd] + dx2); com[dd] = frame[ii*3+0][dd]; if (com[dd] < 0 ) com[dd] += tjl.getBox()[dd]; else if (com[dd] >= tjl.getBox()[dd]) com[dd] -= tjl.getBox()[dd]; } coms[ii] = com; dipoles[ii] = moment; } clist.rebuild (coms); gkr.deposit (coms, clist, dipoles, vbox); } printf ("\n"); gkr.calculate (); FILE *fout = fopen (ofile.c_str(), "w"); if (fout == NULL){ std::cerr << "cannot open file " << ofile << std::endl; exit (1); } for (unsigned i = 1; i < gkr.getN(); ++i){ fprintf (fout, "%f %f %e\n", (i) * refh, gkr.getAvg(i), gkr.getAvgError(i)); } fclose (fout); return 0; }
void DistanceToAtom::compute(const QVector<QVector3D> &pointsOriginal, float cutoff) { if(pointsOriginal.size() == 0) { qDebug() << "DistanceToAtom::compute WARNING: input vector is empty."; return; } QElapsedTimer timer; timer.start(); float min = 1e90; float max = -1e90; for(const QVector3D &point : pointsOriginal) { min = std::min(min, point[0]); min = std::min(min, point[1]); min = std::min(min, point[2]); max = std::max(max, point[0]); max = std::max(max, point[1]); max = std::max(max, point[2]); } max += 1e-5; const float systemSize = max - min; // Now translate all points QVector<QVector3D> points = pointsOriginal; for(QVector3D &point : points) { point[0] -= min; point[1] -= min; point[2] -= min; } float cellSize; CellList cellList = buildCellList(points, systemSize, cutoff, cellSize); const int numCells = cellList.size(); // Each index should be identical m_values.clear(); m_values.resize(m_numberOfRandomVectors); m_randomNumbers.resize(3*m_numberOfRandomVectors); for(int i=0; i<3*m_numberOfRandomVectors; i++) { m_randomNumbers[i] = floatRandom(0, systemSize); } const float oneOverCellSize = 1.0/cellSize; #pragma omp parallel for num_threads(8) for(int i=0; i<m_numberOfRandomVectors; i++) { const float x = m_randomNumbers[3*i+0]; const float y = m_randomNumbers[3*i+1]; const float z = m_randomNumbers[3*i+2]; const int cx = x * oneOverCellSize; const int cy = y * oneOverCellSize; const int cz = z * oneOverCellSize; float minimumDistanceSquared = 1e10; const float minimumDistanceSquared0 = minimumDistanceSquared; // Loop through all 27 cells with size=cutoff for(int dx=-1; dx<=1; dx++) { for(int dy=-1; dy<=1; dy++) { for(int dz=-1; dz<=1; dz++) { const vector<QVector3D> &pointsInCell = cellList[periodic(cx+dx, numCells)][periodic(cy+dy, numCells)][periodic(cz+dz, numCells)]; const int numberOfPointsInCell = pointsInCell.size(); for(int j=0; j<numberOfPointsInCell; j++) { // const QVector3D &point = points[pointIndex]; const QVector3D &point = pointsInCell[j]; float dx = x - point[0]; float dy = y - point[1]; float dz = z - point[2]; if(dx < -0.5*systemSize) dx += systemSize; else if(dx > 0.5*systemSize) dx -= systemSize; if(dy < -0.5*systemSize) dy += systemSize; else if(dy > 0.5*systemSize) dy -= systemSize; if(dz < -0.5*systemSize) dz += systemSize; else if(dz > 0.5*systemSize) dz -= systemSize; const float distanceSquared = dx*dx + dy*dy + dz*dz; if(distanceSquared < minimumDistanceSquared) minimumDistanceSquared = distanceSquared; } } } } if(minimumDistanceSquared == minimumDistanceSquared0) { minimumDistanceSquared = -1; } m_values[i] = float(minimumDistanceSquared); } m_randomNumbers.clear(); points.clear(); // qDebug() << "DTO finished after " << timer.elapsed() << " ms."; m_isValid = true; // if(pointsOriginal.size() == 0) { // qDebug() << "DistanceToAtom::compute WARNING: input vector is empty."; // return; // } // float min = 1e90; // float max = -1e90; // for(const QVector3D &point : pointsOriginal) { // min = std::min(min, point[0]); // min = std::min(min, point[1]); // min = std::min(min, point[2]); // max = std::max(max, point[0]); // max = std::max(max, point[1]); // max = std::max(max, point[2]); // } // max += 1e-5; // const float systemSize = max - min; // // Now translate all points // QVector<QVector3D> points = pointsOriginal; // for(QVector3D &point : points) { // point[0] -= min; // point[1] -= min; // point[2] -= min; // } // float cellSize; // CellList cellList = buildCellList(points, systemSize, cutoff, cellSize); // const int numCells = cellList.size(); // Each index should be identical // const float voxelSize = systemSize / m_size; // for(int i=0; i<m_size; i++) { // for(int j=0; j<m_size; j++) { // for(int k=0; k<m_size; k++) { // const QVector3D voxelCenter((i+0.5)*voxelSize, (j+0.5)*voxelSize, (k+0.5)*voxelSize); // float minimumDistanceSquared0 = 1e10; // float minimumDistanceSquared = 1e10; // // Find the cell list where this position belongs and loop through all cells around // const int cx = voxelCenter[0] / cellSize; // const int cy = voxelCenter[1] / cellSize; // const int cz = voxelCenter[2] / cellSize; // // Loop through all 27 cells with size=cutoff // for(int dx=-1; dx<=1; dx++) { // for(int dy=-1; dy<=1; dy++) { // for(int dz=-1; dz<=1; dz++) { // const vector<int> &pointsInCell = cellList[periodic(cx+dx, numCells)][periodic(cy+dy, numCells)][periodic(cz+dz, numCells)]; // for(const int &pointIndex : pointsInCell) { // const QVector3D &point = points[pointIndex]; // const float distanceSquared = periodicDistanceSquared(point, voxelCenter, systemSize); // minimumDistanceSquared = std::min(minimumDistanceSquared, distanceSquared); // } // } // } // } // if(minimumDistanceSquared == minimumDistanceSquared0) { // minimumDistanceSquared = -1; // } // setValue(i,j,k,float(minimumDistanceSquared)); // } // } // } // m_isValid = true; }