source: src/Graph/AdjacencyList.cpp@ 9fd44f

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since 9fd44f was abb641, checked in by Frederik Heber <heber@…>, 11 years ago

FIX: AdjacencyList missed atoms without bonds.

  • this caused an arbitrary number of argon atoms to have just a single fragment.
  • Property mode set to 100644
File size: 9.3 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2010-2012 University of Bonn. All rights reserved.
5 *
6 *
7 * This file is part of MoleCuilder.
8 *
9 * MoleCuilder is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation, either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * MoleCuilder is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with MoleCuilder. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/*
24 * AdjacencyList.cpp
25 *
26 * Created on: Mar 3, 2011
27 * Author: heber
28 */
29
30// include config.h
31#ifdef HAVE_CONFIG_H
32#include <config.h>
33#endif
34
35#include "CodePatterns/MemDebug.hpp"
36
37#include <iostream>
38#include <map>
39#include <set>
40#include <utility>
41
42#include "AdjacencyList.hpp"
43
44#include "Atom/atom.hpp"
45#include "Bond/bond.hpp"
46#include "CodePatterns/Assert.hpp"
47#include "CodePatterns/Log.hpp"
48#include "CodePatterns/Range.hpp"
49#include "Descriptors/AtomIdDescriptor.hpp"
50#include "Helpers/defs.hpp"
51#include "World.hpp"
52
53/** Constructor of class AdjacencyList.
54 *
55 * \param File file to parser
56 */
57AdjacencyList::AdjacencyList(std::istream &File)
58{
59 bool status = ParseFromFile(File);
60// ASSERT( status,
61// "AdjacencyList::AdjacencyList() - File's contents was nor parsable");
62 if (!status) // remove map if failed to parse
63 atombondmap.clear();
64}
65
66/** Constructor of class AdjacencyList.
67 *
68 * \param File file to parser
69 */
70AdjacencyList::AdjacencyList(const atomids_t &atomids)
71{
72 CreateMap(atomids);
73}
74
75AdjacencyList::~AdjacencyList()
76{}
77
78/** Parses the bond partners of each atom from an external file into AdjacencyList::atombondmap.
79 *
80 * @param File file to parse
81 * @return true - everything ok, false - error while parsing
82 */
83bool AdjacencyList::ParseFromFile(std::istream &File)
84{
85 if (File.fail()) {
86 LOG(1, "STATUS: Adjacency file not found." << endl);
87 return false;
88 }
89
90 atombondmap.clear();
91 char buffer[MAXSTRINGSIZE];
92 int tmp;
93 // Parse the file line by line and count the bonds
94 while (File.good()) {
95 File.getline(buffer, MAXSTRINGSIZE);
96 stringstream line;
97 line.str(buffer);
98 int AtomNr = -1;
99 line >> AtomNr;
100 // parse into structure
101 if (AtomNr > 0) {
102 const atomId_t WalkerId = AtomNr-1;
103 // parse bond partner ids associated to AtomNr
104 while (line >> ws >> tmp) {
105 LOG(3, "INFO: Recognized bond partner " << tmp-1 << " for " << WalkerId << ".");
106 atombondmap.insert( std::make_pair(WalkerId, tmp-1) );
107 }
108 } else {
109 if (AtomNr != -1) {
110 ELOG(2, AtomNr << " is negative.");
111 return false;
112 }
113 }
114 }
115 return true;
116}
117
118/** Fills the AdjacencyList::atombondmap from the atoms given by the two iterators.
119 *
120 * @param atomids set of atomic ids to check (must be global ids, i.e. from atom::getId())
121 */
122void AdjacencyList::CreateMap(atomids_t atomids)
123{
124 atombondmap.clear();
125 std::sort(atomids.begin(), atomids.end());
126 // go through each atom in the list
127 for (atomids_t::const_iterator iter = atomids.begin(); iter != atomids.end(); ++iter) {
128 const atomId_t WalkerId = *iter;
129 ASSERT(WalkerId != (size_t)-1,
130 "AdjacencyList::CreateMap() - Walker has no id.");
131 const atom *Walker = World::getInstance().getAtom(AtomById(WalkerId));
132 ASSERT( Walker != NULL,
133 "AdjacencyList::CreateMap() - Walker id "+toString(*iter)
134 +" is not associated to any of World's atoms.");
135 const BondList& ListOfBonds = Walker->getListOfBonds();
136 if (ListOfBonds.size() > 0) {
137 // go through each of its bonds
138 for (BondList::const_iterator Runner = ListOfBonds.begin();
139 Runner != ListOfBonds.end();
140 ++Runner) {
141 const atomId_t id = (*Runner)->GetOtherAtom(Walker)->getId();
142 ASSERT(id != (size_t)-1,
143 "AdjacencyList::CreateMap() - OtherAtom has not id.");
144 if (std::binary_search(atomids.begin(), atomids.end(), id))
145 atombondmap.insert( std::make_pair(WalkerId, id) );
146 }
147 } else {
148 // insert self-bond if atom is lonesome cowboy
149 atombondmap.insert( std::make_pair(WalkerId, WalkerId) );
150 }
151 }
152}
153
154AdjacencyList::KeysSet AdjacencyList::getKeys(const AdjacencyList::AtomBondRange &_range) const
155{
156 KeysSet Keys;
157 for (AtomBondMap::const_iterator iter = _range.first;
158 iter != _range.second;
159 ++iter) {
160 Keys.insert( iter->first );
161 }
162 return Keys;
163}
164
165AdjacencyList::ValuesSet AdjacencyList::getValues(const AdjacencyList::AtomBondRange&_range) const
166{
167 ValuesSet Values;
168 for (AtomBondMap::const_iterator iter = _range.first;
169 iter != _range.second;
170 ++iter) {
171 Values.insert( iter->second );
172 }
173 return Values;
174}
175
176/** Counts the number of items in the second set not present in the first set.
177 *
178 * \note We assume that the sets are sorted.
179 *
180 * @param firstset check set
181 * @param secondset reference set
182 * @return number of items in the first set that are missing in the second
183 */
184template <class T>
185size_t getMissingItems(const T &firstset, const T &secondset)
186{
187 size_t Mismatch = 0;
188 typename T::const_iterator firstiter = firstset.begin();
189 typename T::const_iterator seconditer = secondset.begin();
190 for (; (firstiter != firstset.end()) && (seconditer != secondset.end());) {
191 if (*firstiter > *seconditer)
192 ++seconditer;
193 else {
194 if (*firstiter < *seconditer)
195 ++Mismatch;
196 ++firstiter;
197 }
198 }
199 return Mismatch;
200}
201
202/** Compares whether AdjacencyList::atombondmap in this instance is a subset of
203 * the one in \a other.
204 *
205 * @param other other instance of an adjacency list to compare against
206 * @return true - this atombondmap is subset, false - else
207 */
208bool AdjacencyList::operator<(const AdjacencyList &other) const
209{
210 int NonMatchNumber = 0;
211 // extract keys and check whether they match
212 const AtomBondRange Intrange(atombondmap.begin(), atombondmap.end());
213 const AtomBondRange Extrange(other.atombondmap.begin(), other.atombondmap.end());
214 KeysSet InternalKeys( getKeys(Intrange) );
215 KeysSet ExternalKeys( getKeys(Extrange) );
216
217// std::cout << "InternalKeys: " << InternalKeys << std::endl;
218// std::cout << "ExternalKeys: " << ExternalKeys << std::endl;
219
220 // check amount of keys
221 if (ExternalKeys.size() < InternalKeys.size()) {
222 NonMatchNumber = (int)InternalKeys.size() - (int)ExternalKeys.size();
223 LOG(2, "INFO: Number of internal keys exceeds external one by " << NonMatchNumber << ".");
224 return false;
225 }
226
227 // check which keys are missing in the internal set
228 NonMatchNumber = getMissingItems(InternalKeys, ExternalKeys);
229
230 if (NonMatchNumber != 0) {
231 LOG(2, "INFO: " << NonMatchNumber << " keys are not the same.");
232 return false;
233 }
234
235 // now check each map per key
236 for (KeysSet::const_iterator keyIter = InternalKeys.begin();
237 keyIter != InternalKeys.end();
238 ++keyIter) {
239// std::cout << "Current key is " << *keyIter << std::endl;
240 const AtomBondRange IntRange( atombondmap.equal_range(*keyIter) );
241 const AtomBondRange ExtRange( other.atombondmap.equal_range(*keyIter) );
242 ValuesSet InternalValues( getValues(IntRange) );
243 ValuesSet ExternalValues( getValues(ExtRange) );
244 // throw out all values not present in ExternalKeys
245 ValuesSet ExternalValues_temp( ExternalValues );
246 for(KeysSet::const_iterator iter = InternalKeys.begin();
247 iter != InternalKeys.end(); ++iter)
248 ExternalValues_temp.erase(*iter);
249 // all remaining values must be masked out
250 for (ValuesSet::const_iterator iter = ExternalValues_temp.begin();
251 iter != ExternalValues_temp.end(); ++iter)
252 ExternalValues.erase(*iter);
253// std::cout << "InternalValues: " << InternalValues << std::endl;
254// std::cout << "ExternalValues: " << ExternalValues << std::endl;
255 NonMatchNumber += getMissingItems(InternalValues, ExternalValues);
256 }
257 if (NonMatchNumber != 0) {
258 LOG(2, "INFO: " << NonMatchNumber << " keys are not the same.");
259 return false;
260 } else {
261 LOG(2, "INFO: All keys are the same.");
262 return true;
263 }
264}
265
266/** Storing the bond structure of a molecule to file.
267 * Simply stores Atom::Nr and then the Atom::Nr of all bond partners per line.
268 * @param File output stream to write to
269 * \return true - file written successfully, false - writing failed
270 */
271bool AdjacencyList::StoreToFile(std::ostream &File) const
272{
273 bool status = true;
274 std::stringstream output;
275 output << "Saving adjacency list ... ";
276 if (!File.bad()) {
277 //File << "m\tn" << endl;
278 AtomBondMap::const_iterator advanceiter = atombondmap.begin();
279 for (AtomBondMap::const_iterator iter = atombondmap.begin();
280 iter != atombondmap.end();
281 iter = advanceiter) {
282 advanceiter = atombondmap.upper_bound(iter->first);
283 File << iter->first+1;
284 for (AtomBondMap::const_iterator adjacencyiter = iter;
285 adjacencyiter != advanceiter;
286 ++adjacencyiter)
287 File << " " << adjacencyiter->second+1;
288 File << std::endl;
289 }
290 output << "done.";
291 } else {
292 output << "given stream is not good.";
293 status = false;
294 }
295 LOG(1, output.str());
296
297 return status;
298}
Note: See TracBrowser for help on using the repository browser.