source: src/Actions/AtomAction/BondifyAction.cpp@ ad0929

Candidate_v1.7.0 stable
Last change on this file since ad0929 was 5fa1e86, checked in by Frederik Heber <frederik.heber@…>, 5 years ago

Added BondifyAction.

  • this allows to add non-hydrogen bonds and is complementary to saturate bonds where hydrogens are added.
  • we generate all possible candidate sets taken from non-hydrogen atoms in vicinity with hydrogens and pick one at random.
  • DOCU: added to userguide.
  • TEST: added regression test case.
  • Property mode set to 100644
File size: 12.0 KB
RevLine 
[5fa1e86]1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2020 Frederik Heber. 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 * BondifyAction.cpp
25 *
26 * Created on: Oct 07, 2020
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 "CodePatterns/Assert.hpp"
38#include "CodePatterns/Log.hpp"
39
40#include <string>
41
42#include "Actions/AtomAction/BondifyAction.hpp"
43//#include "Actions/UndoRedoHelpers.hpp"
44#include "Atom/atom.hpp"
45#include "Bond/bond.hpp"
46#include "Descriptors/AtomsWithinDistanceOfDescriptor.hpp"
47#include "Graph/BondGraph.hpp"
48#include "RandomNumbers/RandomNumberDistributionFactory.hpp"
49#include "RandomNumbers/RandomNumberDistribution.hpp"
50#include "RandomNumbers/RandomNumberGenerator.hpp"
51#include "RandomNumbers/RandomNumberGeneratorFactory.hpp"
52#include "World.hpp"
53
54using namespace MoleCuilder;
55
56// and construct the stuff
57#include "BondifyAction.def"
58#include "Action_impl_pre.hpp"
59
60typedef std::vector< std::pair<atom *, int> > candidates_t;
61
62static int getNumberOfHydrogenAtoms(
63 const atom *Walker)
64{
65 int num_hydrogens = 0;
66 const BondList& ListOfBonds = Walker->getListOfBonds();
67 for (BondList::const_iterator bonditer = ListOfBonds.begin();
68 bonditer != ListOfBonds.end(); ++bonditer) {
69 num_hydrogens += (int)((*bonditer)->GetOtherAtom(Walker)->getElementNo() == 1);
70 }
71 return num_hydrogens;
72}
73
74static candidates_t getCandidatesInVicinity(
75 const BondGraph &BG,
76 const atom * const Walker)
77{
78 const std::vector< atom *> atoms_in_vicinity = World::getInstance().getAllAtoms(
79 AtomsWithinDistanceOf(5., Walker->getPosition()));
80 candidates_t candidates;
81 for (std::vector<atom *>::const_iterator iter = atoms_in_vicinity.begin();
82 iter != atoms_in_vicinity.end(); ++iter) {
83 const atom *OtherWalker = *iter;
84 // skip hydrogens
85 if (OtherWalker->getElementNo() == 1)
86 continue;
87 // skip atoms that are bonded already
88 if (OtherWalker->IsBondedTo(Walker))
89 continue;
90 double distance = OtherWalker->getPosition().distance(Walker->getPosition());
91 range<double> typical_distance = BG.getMinMaxDistance(Walker, OtherWalker);
92 if (typical_distance.isInRange(distance)) {
93 int num_hydrogens = getNumberOfHydrogenAtoms(OtherWalker);
94 candidates.push_back( std::make_pair(const_cast<atom *>(OtherWalker), num_hydrogens));
95 }
96 }
97 return candidates;
98}
99
100static int getTotalBondDegree(
101 const atom * Walker)
102{
103 int num_degreed_bonds = 0;
104 const BondList& ListOfBonds = Walker->getListOfBonds();
105 for (BondList::const_iterator bonditer = ListOfBonds.begin();
106 bonditer != ListOfBonds.end(); ++bonditer) {
107 num_degreed_bonds += (*bonditer)->getDegree();
108 }
109 return num_degreed_bonds;
110}
111
112class CandidatesAtValence {
113public:
114 typedef std::multimap<int, atom*> num_hydrogens_atom_map_t;
115 typedef std::vector< std::pair<atom *, int> > candidates_hydrogens_to_remove_t;
116 typedef std::vector<candidates_hydrogens_to_remove_t> all_candidates_t;
117
118 int max_hydrogens;
119
120 CandidatesAtValence(const int _max_hydrogens) : max_hydrogens(_max_hydrogens) {}
121
122 void setMaxHydrogens(const int _max_hydrogens) {
123 max_hydrogens = _max_hydrogens;
124 }
125
126 all_candidates_t operator()(
127 const int open_valence,
128 const std::multimap<int, atom*>& sorted_candidates) const
129 {
130 all_candidates_t all_candidates;
131 if (sorted_candidates.empty())
132 return all_candidates;
133
134
135 /* pick from beginning (i.e. smallest valence first) and gather all
136 * possible candidate sets.
137 */
138 int remaining_valence = open_valence;
139 std::multimap<int, atom*>::const_iterator iter = sorted_candidates.begin();
140 candidates_hydrogens_to_remove_t candidate_set;
141 exploreCandidateSetRecursively(
142 iter, sorted_candidates.end(),
143 candidate_set, remaining_valence,
144 all_candidates);
145
146 for (all_candidates_t::const_iterator all_iter = all_candidates.begin();
147 all_iter != all_candidates.end(); ++all_iter) {
148 LOG(2, "DEBUG: Candidate set is " << candidateToString(*all_iter));
149 }
150
151 return all_candidates;
152 }
153
154 void exploreCandidateSetRecursively(
155 num_hydrogens_atom_map_t::const_iterator iter,
156 num_hydrogens_atom_map_t::const_iterator iter_end,
157 candidates_hydrogens_to_remove_t candidate_set,
158 int remaining_valence,
159 all_candidates_t& all_candidates
160 ) const
161 {
162 const int & num_hydrogens = iter->first;
163 atom * const walker = iter->second;
164 ++iter;
165 const int usable_valence =
166 std::min(
167 std::min(num_hydrogens, remaining_valence),
168 max_hydrogens
169 );
170 candidate_set.push_back(
171 std::make_pair(walker, 0)
172 );
173 for (int i=0;i<= usable_valence; ++i) {
174 candidate_set.back().second = i;
175 // check whether we are complete with the candidate_set
176 if (remaining_valence - i <= 0) {
177 // we have a complete set
178 ASSERT(remaining_valence -i == 0,
179 "exploreCandidateSetRecursively() - usable valence "+toString(i)
180 +" must always be less or equal remaining valence "+toString(remaining_valence));
181 all_candidates.push_back(candidate_set);
182 } else {
183 // not complete, need to recurse further if we can
184 if (iter != iter_end)
185 exploreCandidateSetRecursively(
186 iter,
187 iter_end,
188 candidate_set,
189 remaining_valence-i,
190 all_candidates);
191 }
192 }
193 }
194
195 static std::string candidateToString(
196 const candidates_hydrogens_to_remove_t &candidates)
197 {
198 std::stringstream output;
199 for (candidates_hydrogens_to_remove_t::const_iterator iter = candidates.begin();
200 iter != candidates.end(); ++iter)
201 output << "[" << *iter->first << "," << iter->second << "], ";
202 return output.str();
203 }
204
205
206};
207
208/** =========== define the function ====================== */
209ActionState::ptr AtomBondifyAction::performCall() {
210 // ensure we have one selected atom
211 World &world = World::getInstance();
212 const BondGraph &BG = *world.getBondGraph();
213
214 // check precondition
215 const std::vector<atom *> atoms = world.getSelectedAtoms();
216 if (atoms.size() != 1) {
217 STATUS("Exactly one atom must be selected for bondify.");
218 return Action::failure;
219 }
220 atom *Walker = atoms[0];
221
222 // check whether atom has unoccupied valence orbitals
223 const int num_valence = Walker->getType()->getNoValenceOrbitals();
224
225 // Look at all bond neighbors
226 const int num_degreed_bonds = getTotalBondDegree(Walker);
227 int open_valence = num_valence - num_degreed_bonds;
228 LOG(1, "INFO: We have " << open_valence << " unoccupied valence");
229
230 if (open_valence <= 0) {
231 STATUS("Nothing selected, we need some unoccupied valence orbitals to have something to work on.");
232 return Action::success;
233 }
234
235 // gather all atoms in vicinity
236 candidates_t candidates = getCandidatesInVicinity(BG, Walker);
237
238
239 /** We revert the map's key and values, as we want the entries
240 * sorted by the valence.
241 */
242 std::multimap<int, atom*> sorted_candidates;
243 for (candidates_t::const_iterator iter = candidates.begin();
244 iter != candidates.end(); ++iter) {
245 if (iter->second > 0) {
246 sorted_candidates.insert( std::make_pair(iter->second, iter->first) );
247 }
248 }
249
250 /**
251 * Try to find the maximum number of bonds to use instead of having to
252 * add hydrogens in the end.
253 */
254 CandidatesAtValence::all_candidates_t all_candidates;
255 CandidatesAtValence candidateGetter(params.max_hydrogens.get());
256 ++open_valence;
257 while ((all_candidates.size() == 0) && (--open_valence > 0)) {
258 all_candidates = candidateGetter(open_valence, sorted_candidates);
259 }
260 if (all_candidates.empty()) {
261 STATUS("Could not find any suitable candidate sets.");
262 return Action::success;
263 }
264
265 // pick one set at random
266 const std::string oldtype = RandomNumberDistributionFactory::getConstInstance().getCurrentTypeName();
267 RandomNumberDistributionFactory::getInstance().setCurrentType("uniform_01");
268 const RandomNumberGenerator& rng = RandomNumberGeneratorFactory::getConstInstance().makeRandomNumberGenerator();
269 int id = (int)(rng()*(all_candidates.size()-1));
270 RandomNumberDistributionFactory::getInstance().setCurrentType(oldtype);
271 CandidatesAtValence::candidates_hydrogens_to_remove_t &picked_set = all_candidates[id];
272 LOG(1, "INFO: Picked candidate set is " << CandidatesAtValence::candidateToString(picked_set));
273
274 // execute that
275 int removed_hydrogens = 0;
276 int added_bonds = 0;
277 for (CandidatesAtValence::candidates_hydrogens_to_remove_t::iterator iter = picked_set.begin();
278 iter != picked_set.end(); ++iter) {
279 atom * const other_walker = iter->first;
280 const int &num_hydrogens = iter->second;
281
282 // remove the hydrogens closest to Walker
283 typedef std::map<double, atom *> closest_map_t;
284 closest_map_t closest_map;
285 const BondList& ListOfBonds = other_walker->getListOfBonds();
286 for (BondList::const_iterator bonditer = ListOfBonds.begin();
287 bonditer != ListOfBonds.end(); ++bonditer) {
288 atom * const hydrogen = (*bonditer)->GetOtherAtom(other_walker);
289 if (hydrogen->getElementNo() != 1)
290 continue;
291 closest_map.insert(
292 std::make_pair(
293 Walker->getPosition().distance(hydrogen->getPosition()),
294 hydrogen
295 )
296 );
297 }
298 ASSERT( closest_map.size() >= (size_t)num_hydrogens,
299 "AtomBondifyAction::performCall() - Atom "+toString(*other_walker)
300 +" has less hydrogens "+toString(closest_map.size())
301 +" than expected "+toString(num_hydrogens));
302 closest_map_t::iterator removeiter = closest_map.begin();
303 for (int i=0;i<num_hydrogens; ++i) {
304 ASSERT( removeiter != closest_map.end(),
305 "AtomBondifyAction::performCall() - already at end of closest map?");
306 LOG(2, "DEBUG: Removing hydrogen at distance " << removeiter->first
307 << " to Walker at " << Walker->getPosition());
308 world.destroyAtom(removeiter->second);
309 removeiter->second = NULL;
310 ++removeiter;
311 ++removed_hydrogens;
312 }
313
314 // add the bond
315 bond::ptr new_bond = Walker->addBond(other_walker);
316 new_bond->setDegree(num_hydrogens);
317 ++added_bonds;
318 LOG(2, "DEBUG: Added new bond " << *new_bond);
319 }
320 ASSERT( removed_hydrogens == open_valence,
321 "AtomBondifyAction::performCall() - candidate set has not the number of hydrogens "
322 +toString(removed_hydrogens)+" to match the unoccupied valence "+toString(open_valence));
323
324 LOG(1, "INFO: Removed " << removed_hydrogens << " hydrogen atoms and added "
325 << added_bonds << " new bonds.");
326
327 return Action::success;
328// return ActionState::ptr(new AtomBondifyState(addedHydrogens, params));
329}
330
331ActionState::ptr AtomBondifyAction::performUndo(ActionState::ptr _state) {
332// AtomBondifyState *state = assert_cast<AtomBondifyState*>(_state.get());
333
334 // remove all added hydrogen atoms
335// RemoveAtomsFromAtomicInfo(state->addedHydrogens);
336
337// return ActionState::ptr(_state);
338 return Action::success;
339}
340
341ActionState::ptr AtomBondifyAction::performRedo(ActionState::ptr _state){
342// AtomBondifyState *state = assert_cast<AtomBondifyState*>(_state.get());
343
344 // re-add all added hydrogen atoms
345// AddAtomsFromAtomicInfo(state->addedHydrogens);
346
347// return ActionState::ptr(_state);
348 return Action::success;
349}
350
351bool AtomBondifyAction::canUndo() {
352 return false;
353}
354
355bool AtomBondifyAction::shouldUndo() {
356 return false;
357}
358/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.