source: src/Graph/AdjacencyList.cpp@ 97a858

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 97a858 was 3aa8a5, checked in by Frederik Heber <heber@…>, 12 years ago

REFACTOR: AdjacencyList now just contains a single internal map.

  • Property mode set to 100644
File size: 9.1 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 // go through each of its bonds
137 for (BondList::const_iterator Runner = ListOfBonds.begin();
138 Runner != ListOfBonds.end();
139 ++Runner) {
140 const atomId_t id = (*Runner)->GetOtherAtom(Walker)->getId();
141 ASSERT(id != (size_t)-1,
142 "AdjacencyList::CreateMap() - OtherAtom has not id.");
143 if (std::binary_search(atomids.begin(), atomids.end(), id))
144 atombondmap.insert( std::make_pair(WalkerId, id) );
145 }
146 }
147}
148
149AdjacencyList::KeysSet AdjacencyList::getKeys(const AdjacencyList::AtomBondRange &_range) const
150{
151 KeysSet Keys;
152 for (AtomBondMap::const_iterator iter = _range.first;
153 iter != _range.second;
154 ++iter) {
155 Keys.insert( iter->first );
156 }
157 return Keys;
158}
159
160AdjacencyList::ValuesSet AdjacencyList::getValues(const AdjacencyList::AtomBondRange&_range) const
161{
162 ValuesSet Values;
163 for (AtomBondMap::const_iterator iter = _range.first;
164 iter != _range.second;
165 ++iter) {
166 Values.insert( iter->second );
167 }
168 return Values;
169}
170
171/** Counts the number of items in the second set not present in the first set.
172 *
173 * \note We assume that the sets are sorted.
174 *
175 * @param firstset check set
176 * @param secondset reference set
177 * @return number of items in the first set that are missing in the second
178 */
179template <class T>
180size_t getMissingItems(const T &firstset, const T &secondset)
181{
182 size_t Mismatch = 0;
183 typename T::const_iterator firstiter = firstset.begin();
184 typename T::const_iterator seconditer = secondset.begin();
185 for (; (firstiter != firstset.end()) && (seconditer != secondset.end());) {
186 if (*firstiter > *seconditer)
187 ++seconditer;
188 else {
189 if (*firstiter < *seconditer)
190 ++Mismatch;
191 ++firstiter;
192 }
193 }
194 return Mismatch;
195}
196
197/** Compares whether AdjacencyList::atombondmap in this instance is a subset of
198 * the one in \a other.
199 *
200 * @param other other instance of an adjacency list to compare against
201 * @return true - this atombondmap is subset, false - else
202 */
203bool AdjacencyList::operator<(const AdjacencyList &other) const
204{
205 int NonMatchNumber = 0;
206 // extract keys and check whether they match
207 const AtomBondRange Intrange(atombondmap.begin(), atombondmap.end());
208 const AtomBondRange Extrange(other.atombondmap.begin(), other.atombondmap.end());
209 KeysSet InternalKeys( getKeys(Intrange) );
210 KeysSet ExternalKeys( getKeys(Extrange) );
211
212// std::cout << "InternalKeys: " << InternalKeys << std::endl;
213// std::cout << "ExternalKeys: " << ExternalKeys << std::endl;
214
215 // check amount of keys
216 if (ExternalKeys.size() < InternalKeys.size()) {
217 NonMatchNumber = (int)InternalKeys.size() - (int)ExternalKeys.size();
218 LOG(2, "INFO: Number of internal keys exceeds external one by " << NonMatchNumber << ".");
219 return false;
220 }
221
222 // check which keys are missing in the internal set
223 NonMatchNumber = getMissingItems(InternalKeys, ExternalKeys);
224
225 if (NonMatchNumber != 0) {
226 LOG(2, "INFO: " << NonMatchNumber << " keys are not the same.");
227 return false;
228 }
229
230 // now check each map per key
231 for (KeysSet::const_iterator keyIter = InternalKeys.begin();
232 keyIter != InternalKeys.end();
233 ++keyIter) {
234// std::cout << "Current key is " << *keyIter << std::endl;
235 const AtomBondRange IntRange( atombondmap.equal_range(*keyIter) );
236 const AtomBondRange ExtRange( other.atombondmap.equal_range(*keyIter) );
237 ValuesSet InternalValues( getValues(IntRange) );
238 ValuesSet ExternalValues( getValues(ExtRange) );
239 // throw out all values not present in ExternalKeys
240 ValuesSet ExternalValues_temp( ExternalValues );
241 for(KeysSet::const_iterator iter = InternalKeys.begin();
242 iter != InternalKeys.end(); ++iter)
243 ExternalValues_temp.erase(*iter);
244 // all remaining values must be masked out
245 for (ValuesSet::const_iterator iter = ExternalValues_temp.begin();
246 iter != ExternalValues_temp.end(); ++iter)
247 ExternalValues.erase(*iter);
248// std::cout << "InternalValues: " << InternalValues << std::endl;
249// std::cout << "ExternalValues: " << ExternalValues << std::endl;
250 NonMatchNumber += getMissingItems(InternalValues, ExternalValues);
251 }
252 if (NonMatchNumber != 0) {
253 LOG(2, "INFO: " << NonMatchNumber << " keys are not the same.");
254 return false;
255 } else {
256 LOG(2, "INFO: All keys are the same.");
257 return true;
258 }
259}
260
261/** Storing the bond structure of a molecule to file.
262 * Simply stores Atom::Nr and then the Atom::Nr of all bond partners per line.
263 * @param File output stream to write to
264 * \return true - file written successfully, false - writing failed
265 */
266bool AdjacencyList::StoreToFile(std::ostream &File) const
267{
268 bool status = true;
269 std::stringstream output;
270 output << "Saving adjacency list ... ";
271 if (!File.bad()) {
272 //File << "m\tn" << endl;
273 AtomBondMap::const_iterator advanceiter = atombondmap.begin();
274 for (AtomBondMap::const_iterator iter = atombondmap.begin();
275 iter != atombondmap.end();
276 iter = advanceiter) {
277 advanceiter = atombondmap.upper_bound(iter->first);
278 File << iter->first+1;
279 for (AtomBondMap::const_iterator adjacencyiter = iter;
280 adjacencyiter != advanceiter;
281 ++adjacencyiter)
282 File << " " << adjacencyiter->second+1;
283 File << std::endl;
284 }
285 output << "done.";
286 } else {
287 output << "given stream is not good.";
288 status = false;
289 }
290 LOG(1, output.str());
291
292 return status;
293}
Note: See TracBrowser for help on using the repository browser.