Debian Codegraph @

layla/ligand_editor_canvas/model.cpp

raw
1 /* layla/ligand_editor_canvas/model.cpp
2 *
3 * Copyright 2023 by Global Phasing Ltd.
4 * Author: Jakub Smulski
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or (at
9 * your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 * 02110-1301, USA
20 */
21
22 #include "model.hpp"
23 #include "render.hpp"
24 #include "../qed.hpp"
25 #include <exception>
26 #include <iterator>
27 #include <memory>
28 #include <numeric>
29 #include <optional>
30 #include <stdexcept>
31 #include <algorithm>
32 #include <set>
33 #include <rdkit/GraphMol/Depictor/RDDepictor.h>
34 #include <rdkit/GraphMol/Substruct/SubstructMatch.h>
35 #include <rdkit/Geometry/point.h>
36 #include <rdkit/GraphMol/MolOps.h>
37 #include <cmath>
38 #include <boost/range/iterator_range.hpp>
39 #include <string>
40 #include <tuple>
41 #include <utility>
42 #include <cctype>
43 #include <complex>
44 #ifdef __EMSCRIPTEN__
45 #include "../../lhasa/glog_replacement.hpp"
46 #endif
47
48 using namespace coot::ligand_editor_canvas;
49
50 const float CanvasMolecule::ATOM_HITBOX_RADIUS = 12.f;
51 const float CanvasMolecule::BOND_LINE_SEPARATION = 0.3f;
52 const float CanvasMolecule::BOND_DISTANCE_BOUNDARY = 10.f;
53 const float CanvasMolecule::BASE_SCALE_FACTOR = 30.f;
54
55 const char* coot::ligand_editor_canvas::display_mode_to_string(DisplayMode mode) noexcept {
56 switch (mode) {
57 case DisplayMode::AtomIndices:{
58 return "Atom Indices";
59 }
60 case DisplayMode::AtomNames:{
61 return "Atom Names";
62 }
63 default:
64 case DisplayMode::Standard:{
65 return "Standard";
66 }
67 }
68 }
69 std::optional<DisplayMode> coot::ligand_editor_canvas::display_mode_from_string(const char* value_raw) noexcept {
70 std::string value(value_raw);
71 if(value == "Standard") {
72 return DisplayMode::Standard;
73 } else if (value == "Atom Indices") {
74 return DisplayMode::AtomIndices;
75 } else if (value == "Atom Names") {
76 return DisplayMode::AtomNames;
77 } else {
78 return std::nullopt;
79 }
80 }
81
82 float CanvasMolecule::get_scale() const noexcept {
83 return BASE_SCALE_FACTOR * this->canvas_scale;
84 }
85
86 void CanvasMolecule::set_canvas_scale(float scale) {
87 this->canvas_scale = scale;
88 }
89
90 CanvasMolecule::MaybeAtomOrBond CanvasMolecule::resolve_click(int x, int y) const noexcept {
91 float scale = this->get_scale();
92 auto x_offset = this->x_canvas_translation * scale;
93 auto y_offset = this->y_canvas_translation * scale;
94 // atoms first
95 for(const auto& atom: this->atoms) {
96 float atom_x = atom.x * scale + x_offset;
97 float atom_y = atom.y * scale + y_offset;
98 // Circle equation. Checks if click coords are within atom's radius
99 if (ATOM_HITBOX_RADIUS * ATOM_HITBOX_RADIUS >= std::pow(atom_x - x,2.f) + std::pow(atom_y - y,2.f)) {
100 return atom;
101 }
102 }
103 // then bonds
104 for(const auto& bond: this->bonds) {
105 // 1. Find the point lying in the middle of the segment representing the bond
106 float first_atom_x = bond->first_atom_x * scale + x_offset;
107 float first_atom_y = bond->first_atom_y * scale + y_offset;
108 float second_atom_x = bond->second_atom_x * scale + x_offset;
109 float second_atom_y = bond->second_atom_y * scale + y_offset;
110 float bond_center_x = (first_atom_x + second_atom_x) / 2.0f;
111 float bond_center_y = (first_atom_y + second_atom_y) / 2.0f;
112 // 2. Compute its' distance to the edges and let it be the radius of a circle
113 // inside of which the click location has to be found (as a pre-condition)
114 float bounding_circle_radius_squared = std::pow(first_atom_x - bond_center_x,2.f) + std::pow(first_atom_y - bond_center_y,2.f);
115 // If our distance from the bond's center point is greater than the radius
116 // then this means that we're outside of the circle of interest and so the current bond can be skipped.
117 // Operating on squared values saves us from the expensive square root operation.
118 if (bounding_circle_radius_squared < std::pow(bond_center_x - x,2.f) + std::pow(bond_center_y - y,2.f)) {
119 continue;
120 }
121 // 3. Use the formula for distance to a point from a line to determine if
122 // the click location qualifies as matching.
123
124 float distance = std::fabs((second_atom_x - first_atom_x)*(first_atom_y - y) - (first_atom_x - x)*(second_atom_y - first_atom_y))
125 / std::sqrt(std::pow(first_atom_x - second_atom_x,2.f) + std::pow(first_atom_y - second_atom_y,2.f));
126 // We've got a match
127 if (BOND_DISTANCE_BOUNDARY >= distance) {
128 return *bond;
129 }
130 }
131 // nothing matches the click
132 return std::nullopt;
133 }
134
135 void CanvasMolecule::apply_canvas_translation(int delta_x, int delta_y) noexcept {
136 float scale = this->get_scale();
137 this->x_canvas_translation += (float) delta_x / scale;
138 this->y_canvas_translation += (float) delta_y / scale;
139 }
140
141 std::pair<float,float> CanvasMolecule::get_on_screen_coords(float x, float y) const noexcept {
142 float scale = this->get_scale();
143 auto x_offset = this->x_canvas_translation * scale;
144 auto y_offset = this->y_canvas_translation * scale;
145 return std::make_pair(x * scale + x_offset, y * scale + y_offset);
146 }
147
148 std::optional<std::pair<float,float>> CanvasMolecule::get_on_screen_coords_of_atom(unsigned int atom_idx) const noexcept {
149 if(this->atoms.size() <= atom_idx) {
150 return std::nullopt;
151 }
152 const Atom& a = this->atoms[atom_idx];
153 return this->get_on_screen_coords(a.x, a.y);
154 }
155
156 graphene_rect_t CanvasMolecule::get_on_screen_bounding_rect() const noexcept {
157 float scale = this->get_scale();
158 auto x_offset = this->x_canvas_translation * scale;
159 auto y_offset = this->y_canvas_translation * scale;
160 graphene_rect_t ret;
161 ret.origin.x = this->bounding_atom_coords.first.x * scale + x_offset;
162 ret.origin.y = this->bounding_atom_coords.first.y * scale + y_offset;
163 ret.size.width = (this->bounding_atom_coords.second.x - this->bounding_atom_coords.first.x) * scale + x_offset;
164 ret.size.height = (this->bounding_atom_coords.second.y - this->bounding_atom_coords.first.y) * scale + y_offset;
165 return ret;
166 }
167
168 std::optional<CanvasMolecule::QEDInfo> CanvasMolecule::get_qed_info() const noexcept {
169 return this->qed_info;
170 }
171
172
173 void CanvasMolecule::perform_flip(FlipMode flip_mode) {
174 for(auto& atom: this->cached_atom_coordinate_map.value()) {
175 if(flip_mode == FlipMode::Horizontal) {
176 atom.second.x *= -1;
177 } else {
178 atom.second.y *= -1;
179 }
180 }
181 }
182
183 void CanvasMolecule::rotate_by_angle(double radians) {
184 std::complex<double> rotation_mult(std::cos(radians),std::sin(radians));
185 for(auto& atom: this->cached_atom_coordinate_map.value()) {
186 std::complex<double> atom_cn(atom.second.x,atom.second.y);
187 atom_cn *= rotation_mult;
188 atom.second.x = atom_cn.real();
189 atom.second.y = atom_cn.imag();
190 }
191 }
192
193 std::tuple<float,float,float> CanvasMolecule::hightlight_to_rgb(CanvasMolecule::HighlightType htype) noexcept {
194 switch (htype) {
195 case CanvasMolecule::HighlightType::Edition: {
196 return std::make_tuple(1.0, 0.5, 1.0);
197 }
198 case CanvasMolecule::HighlightType::Error: {
199 return std::make_tuple(1.0, 0.0, 0.0);
200 }
201 case CanvasMolecule::HighlightType::Selection: {
202 return std::make_tuple(0.0, 0.75, 1.0);
203 }
204 default:
205 case CanvasMolecule::HighlightType::Hover: {
206 return std::make_tuple(0.0, 1.0, 0.5);
207 }
208 }
209 }
210
211 std::optional<CanvasMolecule::HighlightType> CanvasMolecule::determine_dominant_highlight(CanvasMolecule::highlight_t hcode) noexcept {
212 if (hcode == 0) {
213 return std::nullopt;
214 }
215 auto has_highlight = [hcode](HighlightType h){
216 return hcode & static_cast<highlight_t>(h);
217 };
218
219 if(has_highlight(HighlightType::Hover)) {
220 return HighlightType::Hover;
221 } else if(has_highlight(HighlightType::Edition)) {
222 return HighlightType::Edition;
223 } else if(has_highlight(HighlightType::Selection)) {
224 return HighlightType::Selection;
225 } else if(has_highlight(HighlightType::Error)) {
226 return HighlightType::Error;
227 }
228 return std::nullopt;
229 }
230
231 std::tuple<float,float,float> CanvasMolecule::atom_color_to_rgb(CanvasMolecule::AtomColor color) noexcept {
232 switch (color) {
233 case AtomColor::Green:{
234 return std::make_tuple(0.0,0.75,0.0);
235 }
236 case AtomColor::Blue:{
237 return std::make_tuple(0.0,0.0,1.0);
238 }
239 case AtomColor::Red:{
240 return std::make_tuple(1.0,0.0,0.0);
241 }
242 case AtomColor::Brown:{
243 return std::make_tuple(0.5,0.5,0.0);
244 }
245 case AtomColor::DarkRed:{
246 return std::make_tuple(0.5,0.0,0.0);
247 }
248 case AtomColor::Orange:{
249 return std::make_tuple(1.0,0.5,0.0);
250 }
251 case AtomColor::DarkBlue:{
252 return std::make_tuple(0.0,0.0,0.5);
253 }
254 case AtomColor::Black:
255 default: {
256 return std::make_tuple(0.0,0.0,0.0);
257 }
258 }
259 }
260
261 std::string CanvasMolecule::atom_color_to_html(CanvasMolecule::AtomColor color) noexcept {
262 switch (color) {
263 case AtomColor::Green:{
264 return "#00C000";
265 }
266 case AtomColor::Blue:{
267 return "#0000FF";
268 }
269 case AtomColor::Red:{
270 return "#FF0000";
271 }
272 case AtomColor::Brown:{
273 return "#808000";
274 }
275 case AtomColor::DarkRed:{
276 return "#800000";
277 }
278 case AtomColor::Orange:{
279 return "#FF8000";
280 }
281 case AtomColor::DarkBlue:{
282 return "#000080";
283 }
284 case AtomColor::Black:
285 default: {
286 return "#000000";
287 }
288 }
289 }
290
291 CanvasMolecule::AtomColor CanvasMolecule::atom_color_from_rdkit(const RDKit::Atom * atom) noexcept {
292 auto atomic_number = atom->getAtomicNum();
293 switch(atomic_number) {
294 // Nitrogen
295 case 7: {
296 return AtomColor::Blue;
297 }
298 // Oxygen
299 case 8: {
300 return AtomColor::Red;
301 }
302 // Phosphorus
303 case 15: {
304 return AtomColor::Orange;
305 }
306 // Sulphur
307 case 16: {
308 return AtomColor::Brown;
309 }
310 // Flourine
311 case 9:
312 // Chlorine
313 case 17: {
314 return AtomColor::Green;
315 }
316 // Bromine
317 case 35: {
318 return AtomColor::DarkRed;
319 }
320 // Iodine
321 case 53: {
322 return AtomColor::DarkBlue;
323 }
324 // Carbon
325 case 6:
326 default: {
327 return AtomColor::Black;
328 }
329 }
330 }
331
332 CanvasMolecule::Atom::Appendix::Appendix() noexcept
333 :charge(0),
334 reversed(false) {
335
336 }
337
338 std::pair<float,float> CanvasMolecule::Bond::get_vector() const noexcept {
339 float bond_vector_x = second_atom_x - first_atom_x;
340 float bond_vector_y = second_atom_y - first_atom_y;
341 return std::make_pair(bond_vector_x,bond_vector_y);
342 }
343
344 std::pair<float,float> CanvasMolecule::Bond::get_versor() const noexcept {
345 auto [bond_vector_x, bond_vector_y] = this->get_vector();
346 float bond_vector_len = std::sqrt(std::pow(bond_vector_x,2.f) + std::pow(bond_vector_y,2.f));
347 if (bond_vector_len == 0) {
348 return std::make_pair(0.f, 0.f);
349 } else {
350 return std::make_pair(bond_vector_x/bond_vector_len,bond_vector_y/bond_vector_len);
351 }
352 }
353
354 std::pair<float,float> CanvasMolecule::Bond::get_perpendicular_versor() const noexcept {
355 auto [x, y] = this->get_versor();
356 return std::make_pair(-y,x);
357 }
358
359 float CanvasMolecule::Bond::get_length() const noexcept {
360 auto [bond_vector_x, bond_vector_y] = this->get_vector();
361 return std::sqrt(std::pow(bond_vector_x,2.f) + std::pow(bond_vector_y,2.f));
362 }
363
364 void CanvasMolecule::draw(impl::Renderer& ren, DisplayMode display_mode) const noexcept {
365 impl::MoleculeRenderContext renctx(*this, ren, display_mode);
366 renctx.draw_atoms();
367 renctx.draw_bonds();
368 }
369
370 CanvasMolecule::CanvasMolecule(std::shared_ptr<RDKit::RWMol> rdkit_mol, bool allow_invalid_mol) {
371 this->rdkit_molecule = std::move(rdkit_mol);
372 this->cached_atom_coordinate_map = std::nullopt;
373 this->bounding_atom_coords = std::make_pair(RDGeom::Point2D(0,0),RDGeom::Point2D(0,0));
374 this->lower_from_rdkit(!allow_invalid_mol);
375 this->x_canvas_translation = 0;
376 this->y_canvas_translation = 0;
377 }
378
379 void CanvasMolecule::update_source_molecule(std::shared_ptr<RDKit::RWMol> rdkit_mol) {
380 this->rdkit_molecule = rdkit_mol;
381 }
382
383 CanvasMolecule::BondType CanvasMolecule::bond_type_from_rdkit(RDKit::Bond::BondType rdkit_bond) {
384 switch (rdkit_bond) {
385 case RDKit::Bond::SINGLE: {
386 return BondType::Single;
387 }
388 case RDKit::Bond::DOUBLE: {
389 return BondType::Double;
390 }
391 case RDKit::Bond::TRIPLE: {
392 return BondType::Triple;
393 }
394 case RDKit::Bond::AROMATIC:{
395 throw std::runtime_error("An aromatic bond remained after kekulization!");
396 }
397 case RDKit::Bond::UNSPECIFIED:
398 case RDKit::Bond::QUADRUPLE:
399 case RDKit::Bond::QUINTUPLE:
400 case RDKit::Bond::HEXTUPLE:
401 case RDKit::Bond::ONEANDAHALF:
402 case RDKit::Bond::TWOANDAHALF:
403 case RDKit::Bond::THREEANDAHALF:
404 case RDKit::Bond::FOURANDAHALF:
405 case RDKit::Bond::FIVEANDAHALF:
406 case RDKit::Bond::IONIC:
407 case RDKit::Bond::HYDROGEN:
408 case RDKit::Bond::THREECENTER:
409 case RDKit::Bond::DATIVEONE:
410 case RDKit::Bond::DATIVE:
411 case RDKit::Bond::DATIVEL:
412 case RDKit::Bond::DATIVER:
413 case RDKit::Bond::OTHER:
414 case RDKit::Bond::ZERO:
415 default: {
416 g_warning("Unhandled RDKit bond type: %i", rdkit_bond);
417 return BondType::Single;
418 }
419 }
420 }
421
422 CanvasMolecule::BondGeometry CanvasMolecule::bond_geometry_from_rdkit(RDKit::Bond::BondDir dir) noexcept {
423 //Not handled here: EITHERDOUBLE
424 switch (dir) {
425 default:{
426 g_warning("Unhandled RDKit bond geometry: %i! Falling back to flat.", dir);
427 }
428 case RDKit::Bond::NONE:{
429 return BondGeometry::Flat;
430 }
431 case RDKit::Bond::UNKNOWN:{
432 return BondGeometry::Unspecified;
433 }
434 case RDKit::Bond::BEGINWEDGE:{
435 return BondGeometry::WedgeTowardsSecond;
436 }
437 case RDKit::Bond::BEGINDASH:{
438 return BondGeometry::DashedTowardsSecond;
439 }
440 case RDKit::Bond::ENDDOWNRIGHT:{
441 // todo: make sure that this makes sense
442 return BondGeometry::WedgeTowardsFirst;
443 }
444 case RDKit::Bond::ENDUPRIGHT:{
445 // todo: make sure that this makes sense
446 return BondGeometry::DashedTowardsFirst;
447 }
448 }
449 }
450
451 CanvasMolecule::BondGeometry CanvasMolecule::cycle_bond_geometry(BondGeometry geom) noexcept {
452 switch (geom) {
453 default:
454 case BondGeometry::Flat: {
455 return BondGeometry::WedgeTowardsFirst;
456 }
457 case BondGeometry::Unspecified: {
458 return BondGeometry::Flat;
459 }
460 case BondGeometry::WedgeTowardsFirst: {
461 return BondGeometry::WedgeTowardsSecond;
462 }
463 case BondGeometry::WedgeTowardsSecond: {
464 return BondGeometry::DashedTowardsFirst;
465 }
466 case BondGeometry::DashedTowardsFirst: {
467 return BondGeometry::DashedTowardsSecond;
468 }
469 case BondGeometry::DashedTowardsSecond: {
470 return BondGeometry::Unspecified;
471 }
472 }
473 }
474
475 RDKit::Bond::BondDir CanvasMolecule::bond_geometry_to_rdkit(BondGeometry geom) noexcept {
476 switch (geom) {
477 default:
478 case BondGeometry::Flat: {
479 return RDKit::Bond::BondDir::NONE;
480 }
481 case BondGeometry::Unspecified: {
482 return RDKit::Bond::BondDir::UNKNOWN;
483 }
484 case BondGeometry::WedgeTowardsFirst: {
485 return RDKit::Bond::BondDir::ENDDOWNRIGHT;
486 }
487 case BondGeometry::WedgeTowardsSecond: {
488 return RDKit::Bond::BondDir::BEGINWEDGE;
489 }
490 case BondGeometry::DashedTowardsFirst: {
491 return RDKit::Bond::BondDir::ENDUPRIGHT;
492 }
493 case BondGeometry::DashedTowardsSecond: {
494 return RDKit::Bond::BondDir::BEGINDASH;
495 }
496 }
497 }
498
499
500 RDKit::Bond::BondType CanvasMolecule::bond_type_to_rdkit(CanvasMolecule::BondType ty) noexcept {
501 switch (ty) {
502 default:
503 case BondType::Single:{
504 return RDKit::Bond::SINGLE;
505 }
506 case BondType::Double:{
507 return RDKit::Bond::DOUBLE;
508 }
509 case BondType::Triple:{
510 return RDKit::Bond::TRIPLE;
511 }
512 }
513 }
514
515
516 RDGeom::INT_POINT2D_MAP CanvasMolecule::compute_molecule_geometry() const {
517 // The following code is heavily based on RDKit documentation.
518
519 const RDGeom::INT_POINT2D_MAP* previous_coordinate_map = nullptr;
520
521 // Pruned coordinate map will only be instantiated if the last coordinate map
522 // contains atoms which are no longer in the molecule (and thus need to be removed).
523 std::unique_ptr<RDGeom::INT_POINT2D_MAP> pruned_previous_coordinate_map = nullptr;
524
525 if (this->cached_atom_coordinate_map.has_value()) {
526 // g_debug("Computing 2D coords using a reference");
527 const RDGeom::INT_POINT2D_MAP& prev_coord_map_ref = this->cached_atom_coordinate_map.value();
528 previous_coordinate_map = &prev_coord_map_ref;
529 // We need to make sure that each atom in the last_atom_coordinate_map still exists in the molecule.
530 // If it doesn't, RDDepict::compute2DCoords() throws an exception. We cannot let this happen.
531 for(const auto& [atom_idx,_point]: prev_coord_map_ref) {
532 try {
533 auto* _atom_ptr = this->rdkit_molecule->getAtomWithIdx(atom_idx);
534 // All good.
535 } catch(...) { // Atom does not exist
536 g_info("Atom with id=%u missing in the molecule, but found in 2D coordinate reference. It will be omitted.",atom_idx);
537 // If there's any atom which is no longer there, we need to copy the whole coordinate map
538 // into pruned_previous_coordinate_map and then remove the atom there.
539 if(! pruned_previous_coordinate_map) {
540 // Copy the original coordinate map
541 pruned_previous_coordinate_map = std::make_unique<RDGeom::INT_POINT2D_MAP>(this->cached_atom_coordinate_map.value());
542 // Also we need to update the previous_coordinate_map pointer to refer to our pruned map.
543 previous_coordinate_map = pruned_previous_coordinate_map.get();
544 }
545 pruned_previous_coordinate_map->erase(pruned_previous_coordinate_map->find(atom_idx));
546 }
547 }
548 } else {
549 g_info("Computing fresh 2D coords (without previous reference).");
550 }
551
552 try {
553 RDDepict::compute2DCoords(*this->rdkit_molecule,previous_coordinate_map,true,true);
554 } catch(std::exception& e) {
555 throw std::runtime_error(std::string("Failed to compute 2D coords with RDKit! ")+e.what());
556 }
557
558
559 RDKit::MatchVectType matchVect;
560 if(!RDKit::SubstructMatch(*this->rdkit_molecule, *this->rdkit_molecule, matchVect)) {
561 throw std::runtime_error("SubstractMatch failed.");
562 }
563
564 // Maps atom indices to 2D points
565 RDGeom::INT_POINT2D_MAP coordinate_map;
566
567 RDKit::Conformer& conf = this->rdkit_molecule->getConformer();
568 for(auto mv: matchVect) {
569 RDGeom::Point3D pt3 = conf.getAtomPos( mv.first );
570 RDGeom::Point2D pt2( pt3.x , pt3.y );
571 coordinate_map[mv.second] = pt2;
572 }
573 // what is going on here?
574 // That doesn't seem to change much
575 // RDDepict::compute2DCoords( *this->rdkit_molecule, &coordinate_map, true, true);
576
577 if(coordinate_map.empty()) {
578 throw std::runtime_error("RDKit coordinate mapping is empty");
579 }
580
581 return coordinate_map;
582 }
583
584 void CanvasMolecule::process_alignment_in_rings() {
585 const auto& rings = this->rdkit_molecule->getRingInfo();
586 // g_debug("Number of rings: %lu", rings->atomRings().size());
587
588 for(const auto& ring: rings->atomRings()) {
589
590 float ring_center_x = 0.f;
591 float ring_center_y = 0.f;
592 for(int atom_idx: ring) {
593 ring_center_x += this->atoms.at(atom_idx).x;
594 ring_center_y += this->atoms.at(atom_idx).y;
595 }
596 ring_center_x /= ring.size();
597 ring_center_y /= ring.size();
598
599 int i = 0;
600 int j = 1;
601
602 // Go over every bond
603 int ring_size = ring.size();
604 while (i != ring_size) {
605 unsigned int atom_one_idx = ring[i];
606 unsigned int atom_two_idx = ring[j];
607 auto bonds_of_atom_one = this->bond_map.find(atom_one_idx);
608 if(bonds_of_atom_one == this->bond_map.end()) {
609 throw std::runtime_error("Critical internal error: Could not find a bond while processing rings.");
610 }
611 // Find iterator pointing to the bond
612 auto bond = std::find_if(bonds_of_atom_one->second.begin(),bonds_of_atom_one->second.end(),[=](const auto bond){
613 return (bond->first_atom_idx == atom_one_idx && bond->second_atom_idx == atom_two_idx)
614 || (bond->first_atom_idx == atom_two_idx && bond->second_atom_idx == atom_one_idx);
615 });
616 if (bond == bonds_of_atom_one->second.end()) {
617 throw std::runtime_error("Critical internal error: Could not find a bond while processing rings.");
618 }
619 auto bond_ptr = *bond;
620 if (bond_ptr->type == BondType::Double) {
621 float x_offset_from_center = (bond_ptr->first_atom_x + bond_ptr->second_atom_x) / 2.f - ring_center_x;
622 // negative y on screen is actually "higher" so we need to flip the sign
623 float y_offset_from_center = ring_center_y - (bond_ptr->first_atom_y + bond_ptr->second_atom_y) / 2.f;
624 bool sign_of_x_offset_from_center = x_offset_from_center > 0.f;
625 bool sign_of_y_offset_from_center = y_offset_from_center > 0.f;
626 bool x_requirement = (bond_ptr->second_atom_x > bond_ptr->first_atom_x) == sign_of_y_offset_from_center;
627 // negative y on screen is actually "higher" so we need to flip the sign
628 bool y_requirement = (bond_ptr->second_atom_y <= bond_ptr->first_atom_y) != sign_of_x_offset_from_center;
629 bool bond_direction = x_requirement && y_requirement;
630 // g_debug(
631 // "Bond: %i->%i DeltaX: %f DeltaY: %f CX: %f CY: %f XO: %f SignXO: %i YO: %f SignYO: %i ReqX: %i ReqY: %i DIR: %i",
632 // bond->first_atom_idx,
633 // bond->second_atom_idx,
634 // bond->second_atom_x - bond->first_atom_x,
635 // bond->first_atom_y - bond->second_atom_y,
636 // ring_center_x,ring_center_y,
637 // x_offset_from_center,
638 // sign_of_x_offset_from_center,
639 // y_offset_from_center,
640 // sign_of_y_offset_from_center,
641 // x_requirement,
642 // y_requirement,bond_direction
643 // );
644 bond_ptr->bond_drawing_direction = bond_direction ? DoubleBondDrawingDirection::Primary : DoubleBondDrawingDirection::Secondary;
645 }
646 // Lastly, process appendices' alignment relative to ring center
647 auto& atom = this->atoms.at(atom_one_idx);
648 if (atom.appendix.has_value()) {
649 bool should_reverse = atom.x < ring_center_x;
650 atom.appendix->reversed = should_reverse;
651 }
652 i++;
653 j++;
654 // Process the last bond
655 if (j == ring_size) {
656 // Loop j to point to the first atom in the ring
657 j = 0;
658 }
659 }
660 }
661 }
662
663 void CanvasMolecule::shorten_double_bonds() {
664 typedef std::pair<const Bond*,float> bond_ptr_and_angle;
665 for (auto& bond: this->bonds) {
666 if(bond->type != BondType::Double) {
667 continue;
668 }
669 if(bond->bond_drawing_direction.has_value()) {
670 if(bond->bond_drawing_direction == DoubleBondDrawingDirection::Centered) {
671 continue;
672 }
673 }
674 auto find_angle_between_bonds = [&](const Bond* other_bond, bool flip){
675 // We can find the angle between two bonds
676 // by computing cosinus arcus (reverse cosine)
677 // of ( dot product / (length a) * (length b) )
678 auto [bond_vec_x,bond_vec_y] = bond->get_vector();
679 auto [other_bond_vec_x,other_bond_vec_y] = other_bond->get_vector();
680 if(flip) {
681 other_bond_vec_x *= -1.f;
682 other_bond_vec_y *= -1.f;
683 }
684 auto dot_product = (bond_vec_x*other_bond_vec_x) + (bond_vec_y*other_bond_vec_y);
685 auto bond_length = bond->get_length();
686 auto other_bond_length = other_bond->get_length();
687 auto result = std::acos(dot_product/(bond_length*other_bond_length));
688 return result;
689 };
690 // 1. Find the adjacent bond(s)
691 auto find_adjacent_bonds = [this,&bond,&find_angle_between_bonds]() -> std::pair<std::vector<bond_ptr_and_angle>,std::vector<bond_ptr_and_angle>> {
692 // Adjacent bonds touching the first atom
693 std::vector<bond_ptr_and_angle> first_bonds;
694 // Adjacent bonds touching the second atom
695 std::vector<bond_ptr_and_angle> second_bonds;
696
697 auto first_bonds_iter = this->bond_map.find(bond->first_atom_idx);
698 if(first_bonds_iter != this->bond_map.end()) {
699 // Going over bonds of the first atom in the currently evaluated bond
700 for(const auto &i: first_bonds_iter->second) {
701 if(i->first_atom_idx == bond->first_atom_idx) {
702 if(i->second_atom_idx == bond->second_atom_idx) {
703 // We're looking at the 'bond' itself. We must skip it.
704 continue;
705 }
706 first_bonds.push_back(std::make_pair(i.get(), find_angle_between_bonds(i.get(), false)));
707 } else if(i->second_atom_idx == bond->first_atom_idx) {
708 // i's second atom is bond's first, so we need to flip the sign of the bond vectors
709 // so that we can correctly compute the angle between them.
710 first_bonds.push_back(std::make_pair(i.get(), find_angle_between_bonds(i.get(), true)));
711 } else {
712 throw std::runtime_error("Internal error: bond_map is inconsistent!");
713 }
714 }
715 }
716 auto second_bonds_iter = this->bond_map.find(bond->second_atom_idx);
717 if(second_bonds_iter != this->bond_map.end()) {
718 // Going over bonds of the second atom in the currently evaluated bond
719 for(const auto &i: second_bonds_iter->second) {
720 if(i->first_atom_idx == bond->second_atom_idx) {
721 // i's first atom is bond's second, so we need to flip the sign of the bond vectors
722 // so that we can correctly compute the angle between them.
723 second_bonds.push_back(std::make_pair(i.get(), find_angle_between_bonds(i.get(), true)));
724 } else if(i->second_atom_idx == bond->second_atom_idx) {
725 if(i->first_atom_idx == bond->first_atom_idx) {
726 // We're looking at the 'bond' itself. We must skip it.
727 continue;
728 }
729 second_bonds.push_back(std::make_pair(i.get(), find_angle_between_bonds(i.get(), false)));
730 } else {
731 throw std::runtime_error("Internal error: bond_map is inconsistent!");
732 }
733 }
734 }
735 return std::make_pair(first_bonds,second_bonds);
736 };
737 auto compute_shortening_proportion = [&](const Bond* other_bond, float angle_between_bonds){
738 // 3. Do a little trigonometry to find the length to be shortened
739 auto absolute_shortened_length = BOND_LINE_SEPARATION / std::tan(angle_between_bonds/2.f);
740 // 4. Find the proportion of the shortening
741 auto bond_length = bond->get_length();
742 return absolute_shortened_length / bond_length;
743 };
744 auto [first_bonds, second_bonds] = find_adjacent_bonds();
745
746 auto element_with_smallest_angle_between_bonds = [&](const std::vector<bond_ptr_and_angle>& adjacent_bonds) -> bond_ptr_and_angle {
747 auto min = std::min_element(adjacent_bonds.cbegin(),adjacent_bonds.cend(),[&](const auto& lhs, const auto& rhs){
748 auto [lbond, langle] = lhs;
749 auto [rbond, rangle] = rhs;
750 return langle < rangle;
751 });
752 return std::make_pair(min->first,min->second);
753 };
754 if(!first_bonds.empty()) {
755 auto [adjbond, angle] = element_with_smallest_angle_between_bonds(first_bonds);
756 bond->first_shortening_proportion = compute_shortening_proportion(adjbond, angle);
757 }
758 if(!second_bonds.empty()) {
759 auto [adjbond, angle] = element_with_smallest_angle_between_bonds(second_bonds);
760 bond->second_shortening_proportion = compute_shortening_proportion(adjbond, angle);
761 }
762 }
763 }
764
765 void CanvasMolecule::build_internal_molecule_representation(const RDGeom::INT_POINT2D_MAP &coordinate_map) {
766 // First, clear what we have
767
768 this->atoms.clear();
769 this->bonds.clear();
770 this->bond_map.clear();
771 this->bounding_atom_coords = std::make_pair(RDGeom::Point2D(0,0),RDGeom::Point2D(0,0));
772
773 /// Used to avoid duplicating bonds
774 std::set<unsigned int> processed_atoms_indices;
775
776 // 1. Process atoms and compute bonds
777 for (const auto& [atom_idx_i, plane_point] : coordinate_map) {
778 unsigned int atom_idx = atom_idx_i; // just changing signedness
779 const auto* rdkit_atom = this->rdkit_molecule->getAtomWithIdx(atom_idx);
780 auto canvas_atom = CanvasMolecule::Atom();
781 canvas_atom.color = atom_color_from_rdkit(rdkit_atom);
782 if(rdkit_atom->hasProp("name")) {
783 std::string atom_name;
784 rdkit_atom->getProp("name", atom_name);
785 canvas_atom.name = atom_name;
786 }
787 canvas_atom.highlight = 0;
788 canvas_atom.idx = atom_idx;
789 canvas_atom.symbol = rdkit_atom->getSymbol();
790 canvas_atom.x = plane_point.x;
791 canvas_atom.y = plane_point.y;
792
793 if(canvas_atom.x < bounding_atom_coords.first.x) {
794 bounding_atom_coords.first.x = canvas_atom.x;
795 }
796 if(canvas_atom.x > bounding_atom_coords.second.x) {
797 bounding_atom_coords.second.x = canvas_atom.x;
798 }
799 if(canvas_atom.y < bounding_atom_coords.first.y) {
800 bounding_atom_coords.first.y = canvas_atom.y;
801 }
802 if(canvas_atom.y > bounding_atom_coords.second.y) {
803 bounding_atom_coords.second.y = canvas_atom.y;
804 }
805
806 auto surrounding_hydrogen_count = rdkit_atom->getTotalNumHs(false);
807 auto surrounding_non_hydrogen_count = 0;
808 auto charge = rdkit_atom->getFormalCharge();
809 if (charge != 0) {
810 Atom::Appendix ap;
811 ap.charge = charge;
812 canvas_atom.appendix = ap;
813 }
814
815 // Bond pointers to be stored in the `bond_map`
816 std::vector<std::shared_ptr<Bond>> bonds_to_be_cached;
817 // Used to determine if the 'appendix' should be 'reversed'
818 std::optional<float> x_coordinate_of_bonded_atom;
819
820 for (const auto& bond: boost::make_iterator_range(this->rdkit_molecule->getAtomBonds(rdkit_atom))) {
821 // Based on `getAtomBonds` documentation.
822 // Seems weird but we have to do it that way.
823 const auto* bond_ptr = (*this->rdkit_molecule)[bond];
824 auto first_atom_idx = bond_ptr->getBeginAtomIdx();
825 auto second_atom_idx = bond_ptr->getEndAtomIdx();
826 auto the_other_atom_idx = (first_atom_idx == atom_idx) ? second_atom_idx : first_atom_idx;
827 const auto* the_other_atom = this->rdkit_molecule->getAtomWithIdx(the_other_atom_idx);
828 if(the_other_atom->getSymbol() != "H") {
829 surrounding_non_hydrogen_count++;
830 x_coordinate_of_bonded_atom = coordinate_map.at(the_other_atom_idx).x;
831 }
832 // else {
833 // g_warning("Skipping explicit hydrogen bound to atom with idx=%u!",canvas_atom.idx);
834 // continue;
835 // }
836
837 // We don't want to have duplicate bonds of atoms that we have already processed
838 // so we skip them.
839 if(processed_atoms_indices.find(first_atom_idx) != processed_atoms_indices.end()
840 || processed_atoms_indices.find(second_atom_idx) != processed_atoms_indices.end()) {
841 continue;
842 }
843
844 auto canvas_bond = CanvasMolecule::Bond();
845
846 canvas_bond.first_atom_idx = first_atom_idx;
847 canvas_bond.first_atom_x = coordinate_map.at(first_atom_idx).x;
848 canvas_bond.first_atom_y = coordinate_map.at(first_atom_idx).y;
849
850 canvas_bond.second_atom_idx = second_atom_idx;
851 canvas_bond.second_atom_x = coordinate_map.at(second_atom_idx).x;
852 canvas_bond.second_atom_y = coordinate_map.at(second_atom_idx).y;
853
854 canvas_bond.highlight = 0;
855 canvas_bond.type = bond_type_from_rdkit(bond_ptr->getBondType());
856 canvas_bond.geometry = bond_geometry_from_rdkit(bond_ptr->getBondDir());
857
858 auto canvas_bond_ptr = std::make_shared<Bond>(canvas_bond);
859 this->bonds.push_back(canvas_bond_ptr);
860
861 bonds_to_be_cached.push_back(canvas_bond_ptr);
862 auto cached_bonds_for_other_atom = this->bond_map.find(the_other_atom_idx);
863 if(cached_bonds_for_other_atom == this->bond_map.end()) {
864 std::vector<std::shared_ptr<Bond>> vec;
865 vec.push_back(canvas_bond_ptr);
866 this->bond_map.emplace(std::pair(the_other_atom_idx,std::move(vec)));
867 } else {
868 cached_bonds_for_other_atom->second.push_back(canvas_bond_ptr);
869 }
870 }
871
872 auto cached_bonds_for_this_atom = this->bond_map.find(atom_idx);
873 if (cached_bonds_for_this_atom == this->bond_map.end()) {
874 this->bond_map.emplace(std::pair(atom_idx,std::move(bonds_to_be_cached)));
875 } else {
876 // In the for-loop above,
877 // We skip bonds with atoms that have already been processed.
878 // Therefore just appending the whole vector
879 // should never result in a duplicate.
880 std::move(bonds_to_be_cached.begin(),bonds_to_be_cached.end(),std::back_inserter(cached_bonds_for_this_atom->second));
881 }
882
883 bool terminus = (surrounding_non_hydrogen_count < 2);
884 if (canvas_atom.symbol != "H" && (canvas_atom.symbol != "C" || terminus)) {
885 //todo: oxygens I guess?
886 if(surrounding_hydrogen_count > 0) {
887 Atom::Appendix ap = canvas_atom.appendix.value_or(Atom::Appendix());
888 ap.superatoms = "H";
889 if(surrounding_hydrogen_count > 1) {
890 ap.superatoms += std::to_string(surrounding_hydrogen_count);
891 }
892 if(terminus && x_coordinate_of_bonded_atom.has_value()) {
893 float diff = x_coordinate_of_bonded_atom.value() - canvas_atom.x;
894 ap.reversed = diff > 0.2;
895 }
896 canvas_atom.appendix = ap;
897 }
898 }
899
900 auto setup_potential_centered_double_bond = [&] (const unsigned int &atom_idx) {
901
902 auto bonds_of_this_atom = this->bond_map.find(atom_idx);
903 if (bonds_of_this_atom == this->bond_map.end()) {
904 return;
905 }
906 if (!terminus || bonds_of_this_atom->second.empty()) {
907 return;
908 }
909 // This means that we only have one bond
910 Bond* bond = bonds_of_this_atom->second.front().get();
911 if (bond->type != BondType::Double) {
912 return;
913 }
914 unsigned int the_other_atom_idx = (bond->first_atom_idx == atom_idx) ? bond->second_atom_idx : bond->first_atom_idx;
915 if (this->rdkit_molecule->getAtomWithIdx(the_other_atom_idx)->getAtomicNum() == 6) {
916 // This should always be a valid iterator at this point
917 auto bonds_of_the_other_atom = this->bond_map.find(the_other_atom_idx);
918 if(bonds_of_the_other_atom->second.size() != 3 && bonds_of_the_other_atom->second.size() != 1) {
919 return;
920 }
921 }
922 bond->bond_drawing_direction = DoubleBondDrawingDirection::Centered;
923 };
924 setup_potential_centered_double_bond(atom_idx);
925
926 this->atoms.push_back(std::move(canvas_atom));
927
928 // Mark the atom as processed
929 processed_atoms_indices.insert(atom_idx);
930 }
931 std::sort(this->atoms.begin(),this->atoms.end(),[](const auto& lhs, const auto& rhs){
932 return lhs.idx < rhs.idx;
933 });
934 // Make sure that double bonds are aligned properly
935 this->process_alignment_in_rings();
936 this->shorten_double_bonds();
937 }
938
939 void CanvasMolecule::lower_from_rdkit(bool sanitize_after, bool with_qed) {
940
941 // 2. Do the lowering
942
943 // 2.0 Kekulize
944 if(sanitize_after) {
945 RDKit::MolOps::Kekulize(*this->rdkit_molecule);
946 } else {
947 try {
948 RDKit::MolOps::Kekulize(*this->rdkit_molecule);
949 } catch(std::exception& e) {
950 g_warning("Could not kekulize molecule: %s", e.what());
951 }
952 }
953
954 /// 2.1 Compute geometry
955 auto geometry = this->compute_molecule_geometry();
956
957 // 2.2 Build internal repr
958 this->build_internal_molecule_representation(geometry);
959 this->cached_atom_coordinate_map = std::move(geometry);
960
961 // 2.3 Reverse kekulization on the original molecule after lowering.
962 if (sanitize_after) {
963 RDKit::MolOps::sanitizeMol(*this->rdkit_molecule);
964 }
965
966 // QED update
967 if (with_qed) {
968 if (sanitize_after) {
969 this->update_qed_info();
970 } else {
971 try {
972 this->update_qed_info();
973 } catch(std::exception& e) {
974 g_warning("Could not update QED info: %s", e.what());
975 }
976 }
977
978 }
979 // Process problematic areas
980 this->process_problematic_areas(!sanitize_after);
981 }
982
983 void CanvasMolecule::process_problematic_areas(bool allow_invalid_molecules) {
984 this->clear_highlights(HighlightType::Error);
985 if(!allow_invalid_molecules) {
986 return;
987 }
988 try {
989 auto problems = RDKit::MolOps::detectChemistryProblems(*this->rdkit_molecule);
990 for(const auto& eptr: problems) {
991 auto* raw_eptr = eptr.get();
992 auto* atom_sanitize_exception = dynamic_cast<RDKit::AtomSanitizeException*>(raw_eptr);
993 if(atom_sanitize_exception) {
994
995 this->add_atom_highlight(atom_sanitize_exception->getAtomIdx(), HighlightType::Error);
996 }
997 }
998 } catch(std::exception& e) {
999 g_warning("Could not process problematic areas: %s", e.what());
1000 }
1001 }
1002
1003 void CanvasMolecule::update_qed_info() {
1004
1005 using QED = layla::RDKit::QED;
1006
1007 coot::layla::RDKit::QED::QEDproperties raw_props = QED::properties(*this->rdkit_molecule);
1008 auto qed_score_and_ads = QED::qed(*this->rdkit_molecule, raw_props);
1009 QEDInfo new_info;
1010
1011 new_info.alogp = raw_props.ALOGP;
1012 new_info.molecular_polar_surface_area = raw_props.PSA;
1013 new_info.molecular_weight = raw_props.MW;
1014 new_info.number_of_alerts = raw_props.ALERTS;
1015 new_info.number_of_aromatic_rings = raw_props.AROM;
1016 new_info.number_of_hydrogen_bond_acceptors = raw_props.HBA;
1017 new_info.number_of_hydrogen_bond_donors = raw_props.HBD;
1018 new_info.number_of_rotatable_bonds = raw_props.ROTB;
1019 new_info.qed_score = qed_score_and_ads.qed_score;
1020 new_info.ads_mw = qed_score_and_ads.ads_mw;
1021 new_info.ads_alogp = qed_score_and_ads.ads_alogp;
1022 new_info.ads_hba = qed_score_and_ads.ads_hba;
1023 new_info.ads_hbd = qed_score_and_ads.ads_hbd;
1024 new_info.ads_psa = qed_score_and_ads.ads_psa;
1025 new_info.ads_rotb = qed_score_and_ads.ads_rotb;
1026 new_info.ads_arom = qed_score_and_ads.ads_arom;
1027 new_info.ads_alert = qed_score_and_ads.ads_alerts;
1028
1029 g_debug("Updated QED: ALOGP=%f PSA=%f MW=%f ALERTS=%u AROM=%u HBA=%u HBD=%u ROTB=%u QED=%f",
1030 new_info.alogp,
1031 new_info.molecular_polar_surface_area,
1032 new_info.molecular_weight,
1033 new_info.number_of_alerts,
1034 new_info.number_of_aromatic_rings,
1035 new_info.number_of_hydrogen_bond_acceptors,
1036 new_info.number_of_hydrogen_bond_donors,
1037 new_info.number_of_rotatable_bonds,
1038 new_info.qed_score
1039 );
1040
1041 this->qed_info = new_info;
1042 }
1043
1044 void CanvasMolecule::add_atom_highlight(int atom_idx, HighlightType htype) {
1045 //g_debug("Highlighted atom with idx=%i",atom_idx);
1046 this->atoms.at(atom_idx).highlight |= static_cast<highlight_t>(htype);
1047 }
1048
1049 void CanvasMolecule::add_bond_highlight(unsigned int atom_a, unsigned int atom_b, HighlightType htype) {
1050
1051 //g_debug("Highlighted bond between atoms with indices %i and %i",atom_a,atom_b);
1052 auto bonds_for_atom_a = this->bond_map.find(atom_a);
1053 if (bonds_for_atom_a == this->bond_map.end()) {
1054 throw std::runtime_error("Bond doesn't exist");
1055 }
1056 auto target = std::find_if(bonds_for_atom_a->second.begin(), bonds_for_atom_a->second.end(), [=](const auto& bond) {
1057 return ((bond->second_atom_idx == atom_b) && (bond->first_atom_idx == atom_a))
1058 || ((bond->second_atom_idx == atom_a) && (bond->first_atom_idx == atom_b));
1059 });
1060 if (target == bonds_for_atom_a->second.end()) {
1061 throw std::runtime_error("Bond doesn't exist");
1062 }
1063 (*target)->highlight |= static_cast<highlight_t>(htype);
1064 }
1065
1066 void CanvasMolecule::clear_highlights(HighlightType htype) {
1067 for(auto& bond: this->bonds) {
1068 auto& highlight = bond->highlight;
1069 highlight &= ~static_cast<highlight_t>(htype);
1070 }
1071 for(auto& atom: this->atoms) {
1072 auto& highlight = atom.highlight;
1073 highlight &= ~static_cast<highlight_t>(htype);
1074 }
1075 }
1076
1077 void CanvasMolecule::add_highlight_to_all_bonds(HighlightType htype) {
1078 for(auto& bond: this->bonds) {
1079 auto& highlight = bond->highlight;
1080 highlight |= static_cast<highlight_t>(htype);
1081 }
1082 }
1083
1084 void CanvasMolecule::clear_cached_atom_coordinate_map() {
1085 this->cached_atom_coordinate_map = std::nullopt;
1086 }
1087
1088 void CanvasMolecule::update_cached_atom_coordinate_map_after_atom_removal(unsigned int removed_atom_idx) {
1089 if (this->cached_atom_coordinate_map.has_value()) {
1090 auto& coordinate_map = this->cached_atom_coordinate_map.value();
1091 // There's no point in working with an empty cache.
1092 // Might as well delete it.
1093 if (coordinate_map.empty()) {
1094 this->cached_atom_coordinate_map = std::nullopt;
1095 return;
1096 }
1097 auto to_be_removed = coordinate_map.find(removed_atom_idx);
1098 if (to_be_removed == coordinate_map.end()) {
1099 g_warning("Atom to be removed (idx=%u) does not exist in the cached coordinate map!",removed_atom_idx);
1100 return;
1101 }
1102 // We can now remove the atom from the cache.
1103 coordinate_map.erase(to_be_removed);
1104 // If that was the only atom in the cache, let's get rid of the cache.
1105 if (coordinate_map.empty()) {
1106 this->cached_atom_coordinate_map = std::nullopt;
1107 return;
1108 }
1109 // After the atom has been removed, all of the indices which are
1110 // greater than its' index have to be decremented.
1111 //
1112 // Now, I don't want to mess around with iterator invalidation.
1113 // So the easiest course of action is to just copy away all
1114 // of the affected elements, change them, remove them from the original map
1115 // and put them back there again.
1116 std::vector<std::pair<int,RDGeom::Point2D>> altered_elements;
1117
1118 // This is the highest index AFTER the atom has been removed from the cache.
1119 // The only reason we get it is that we can make a smart allocation for our vector.
1120 auto highest_idx = coordinate_map.crbegin()->first;
1121 // Allocate all the space that we might need
1122 altered_elements.reserve(highest_idx - removed_atom_idx + 1);
1123 // Get the affected elements, copy them over to the vector, with decreased indices
1124 for(auto i = coordinate_map.upper_bound(removed_atom_idx);i != coordinate_map.end(); i++) {
1125 altered_elements.push_back(std::make_pair(i->first - 1,i->second));
1126 }
1127 // Now, remove the original elements from the map
1128 coordinate_map.erase(coordinate_map.upper_bound(removed_atom_idx),coordinate_map.end());
1129 // Then put them back again after they've been modified
1130 for(auto x: std::move(altered_elements)) {
1131 coordinate_map.emplace(x.first,x.second);
1132 }
1133 }
1134 }