Debian Codegraph @

layla/ligand_editor_canvas/model.hpp

raw
1 /* layla/ligand_editor_canvas/model.hpp
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 #ifndef COOT_LIGAND_EDITOR_CANVAS_MODEL_HPP
23 #define COOT_LIGAND_EDITOR_CANVAS_MODEL_HPP
24 #include <memory>
25 #include <vector>
26 #include <variant>
27 #include <optional>
28 #include <rdkit/GraphMol/RWMol.h>
29 // Forward declaration of types defined at "render.hpp"
30 namespace coot::ligand_editor_canvas::impl {
31 struct Renderer;
32 class MoleculeRenderContext;
33 }
34
35 #ifndef __EMSCRIPTEN__
36 #include <gtk/gtk.h>
37 #else // __EMSCRIPTEN__ defined
38 // Lhasa-specific includes/definitions
39 #include <graphene.h>
40 #endif
41
42 namespace coot {
43 namespace ligand_editor_canvas {
44
45 struct CurrentlyCreatedBond {
46 float first_atom_x;
47 float first_atom_y;
48 //unsigned int first_atom_idx;
49 float second_atom_x;
50 float second_atom_y;
51 };
52
53 enum class FlipMode: unsigned char {
54 /// Along the X axis
55 Horizontal,
56 /// Along the Y axis
57 Vertical
58 };
59
60 enum class DisplayMode: unsigned char {
61 Standard,
62 AtomIndices,
63 AtomNames
64 };
65
66 typedef std::map<unsigned int, std::string> SmilesMap;
67
68 const char* display_mode_to_string(DisplayMode mode) noexcept;
69 std::optional<DisplayMode> display_mode_from_string(const char*) noexcept;
70
71 /// Drawing-friendly representation of RDKit molecule
72 class CanvasMolecule {
73 // Rendering is done via a separate class
74 // for the sake of code organization
75 friend class impl::MoleculeRenderContext;
76 public:
77 enum class AtomColor: unsigned char {
78 /// Carbon and hydrogens
79 Black,
80 /// For Chlorine and Flourine
81 Green,
82 /// For Nitrogen
83 Blue,
84 /// For Oxygen
85 Red,
86 /// For Sulphur
87 Brown,
88 /// For Bromine
89 DarkRed,
90 /// For Phosphorus
91 Orange,
92 /// For Iodine
93 DarkBlue
94 // are there more colors?
95 };
96
97 typedef unsigned char highlight_t;
98 enum class HighlightType: highlight_t {
99 Hover = 1,
100 Edition = 2,
101 Error = 4,
102 // A concept for the future
103 Selection = 8
104 };
105
106 struct Atom {
107 std::string symbol;
108 std::optional<std::string> name;
109
110 /// Appendix represents optional elements that appear after atom's symbol,
111 /// e.g. charge, hydrogens
112 struct Appendix {
113 /// Ionization
114 int charge;
115 /// For CH4, remainder would be "H4".
116 ///
117 /// todo: Should I just change it to an int
118 /// representing the number of hydrogens?
119 std::string superatoms;
120 /// NH2 VS H2N, CH3 VS H3C, etc.
121 bool reversed;
122 Appendix() noexcept;
123 };
124 /// Appendix is set when we draw groups.
125 /// For SO2-, the appendix would be "O2-"
126 std::optional<Appendix> appendix;
127 AtomColor color;
128 /// Position on canvas (x axis)
129 float x;
130 /// Position on canvas (y axis)
131 float y;
132 /// Corresponds to RDKit atom index
133 unsigned int idx;
134 /// Highlight bitmask
135 highlight_t highlight;
136 };
137 enum class BondType: unsigned char {
138 Single,
139 Double,
140 Triple
141 };
142 enum class BondGeometry: unsigned char {
143 Flat,
144 DashedTowardsFirst,
145 DashedTowardsSecond,
146 WedgeTowardsFirst,
147 WedgeTowardsSecond,
148 /// Wavy
149 Unspecified
150 };
151
152 enum class DoubleBondDrawingDirection: unsigned char {
153 Primary,
154 Secondary,
155 Centered
156 };
157
158 struct Bond {
159 BondType type;
160 BondGeometry geometry;
161 /// Set for double bonds.
162 /// It's the proportion of the bond's original length
163 /// by which the parallel segment of the bond
164 /// has to be shortend from the "first" side.
165 std::optional<float> first_shortening_proportion;
166 /// Set for double bonds.
167 /// It's the proportion of the bond's original length
168 /// by which the parallel segment of the bond
169 /// has to be shortend from the "second" side.
170 std::optional<float> second_shortening_proportion;
171 /// For double bonds
172 std::optional<DoubleBondDrawingDirection> bond_drawing_direction;
173 float first_atom_x;
174 float first_atom_y;
175 unsigned int first_atom_idx;
176 float second_atom_x;
177 float second_atom_y;
178 unsigned int second_atom_idx;
179 /// Highlight bitmask
180 highlight_t highlight;
181
182 /// Returns an [x,y] pair of numbers
183 std::pair<float,float> get_perpendicular_versor() const noexcept;
184 /// Returns an [x,y] pair of numbers
185 std::pair<float,float> get_versor() const noexcept;
186 /// Returns an [x,y] pair of numbers
187 std::pair<float,float> get_vector() const noexcept;
188
189 float get_length() const noexcept;
190 };
191
192 struct QEDInfo {
193 unsigned int number_of_hydrogen_bond_acceptors;
194 unsigned int number_of_hydrogen_bond_donors;
195 unsigned int number_of_rotatable_bonds;
196 unsigned int number_of_aromatic_rings;
197 unsigned int number_of_alerts;
198 double molecular_weight;
199 double alogp; /// Hydrophobicity
200 double molecular_polar_surface_area;
201 double ads_mw;
202 double ads_alogp;
203 double ads_hba;
204 double ads_hbd;
205 double ads_psa;
206 double ads_rotb;
207 double ads_arom;
208 double ads_alert;
209 double qed_score;
210 };
211
212 typedef std::variant<CanvasMolecule::Atom,CanvasMolecule::Bond> AtomOrBond;
213 typedef std::optional<AtomOrBond> MaybeAtomOrBond;
214 private:
215
216 static const float BOND_DISTANCE_BOUNDARY;
217 static const float ATOM_HITBOX_RADIUS;
218 static const float BASE_SCALE_FACTOR;
219 static const float BOND_LINE_SEPARATION;
220
221 static BondType bond_type_from_rdkit(RDKit::Bond::BondType);
222 static AtomColor atom_color_from_rdkit(const RDKit::Atom *) noexcept;
223 static std::tuple<float,float,float> atom_color_to_rgb(AtomColor) noexcept;
224 static std::tuple<float,float,float> hightlight_to_rgb(HighlightType) noexcept;
225 static std::string atom_color_to_html(AtomColor) noexcept;
226 static std::optional<HighlightType> determine_dominant_highlight(highlight_t) noexcept;
227
228 std::shared_ptr<RDKit::RWMol> rdkit_molecule;
229 std::vector<Atom> atoms;
230 std::vector<std::shared_ptr<Bond>> bonds;
231
232 /// X offset due to translation.
233 /// Has to be multiplied by scale to get on-screen coordinates
234 float x_canvas_translation;
235 /// Y offset due to translation.
236 /// Has to be multiplied by scale to get on-screen coordinates
237 float y_canvas_translation;
238
239 /// Scale used by the widget
240 float canvas_scale;
241
242 /// The top-left and bottom-right points, in between which the molecule lies.
243 /// The coordinates are in "RDKit space".
244 /// They have to be multiplied by scale and added to the offsets to get on-screen coordinates
245 std::pair<RDGeom::Point2D,RDGeom::Point2D> bounding_atom_coords;
246
247 /// Coordinate map built in the previous call
248 /// to `compute_molecule_geometry()`
249 /// stored for reference to maintain alignment
250 /// when recomputing molecule geometry
251 std::optional<RDGeom::INT_POINT2D_MAP> cached_atom_coordinate_map;
252
253 /// Cached bond map, computed while lowering from RDKit.
254 /// Associates atom indices with lists of bonds (the pointers are shared with the `bonds` vector).
255 /// Used for various lookups: while drawing, in the lowering process itself, etc.
256 std::map<unsigned int,std::vector<std::shared_ptr<Bond>>> bond_map;
257
258 /// QED info is updated while lowering from RDKit.
259 std::optional<QEDInfo> qed_info;
260
261
262 /// Computes the scale used for drawing
263 /// And interfacing with screen coordinates
264 float get_scale() const noexcept;
265
266 /// Uses RDDepict to get molecule depiction & geometry info
267 ///
268 /// Part of the lowering process.
269 RDGeom::INT_POINT2D_MAP compute_molecule_geometry() const;
270
271 /// Builds the drawing-friendly 2D molecule representation
272 /// based on geometry computed by RDKit.
273 ///
274 /// Part of the lowering process.
275 void build_internal_molecule_representation(const RDGeom::INT_POINT2D_MAP& coordinate_map);
276
277 /// Iterates over rings and sets the right alignment for double bonds and atom symbols inside of rings
278 ///
279 /// Part of the lowering process.
280 void process_alignment_in_rings();
281
282 /// Computes length proportions by which
283 /// the parallel segments of double bonds have to be shortened
284 /// to main aesthetic proportions.
285 ///
286 /// Part of the lowering process.
287 void shorten_double_bonds();
288
289 void update_qed_info();
290
291 /// Manages error highlights
292 /// Part of the lowering process.
293 void process_problematic_areas(bool allow_invalid_molecules);
294
295 public:
296
297 CanvasMolecule(std::shared_ptr<RDKit::RWMol> rdkit_mol, bool allow_invalid_mol);
298
299 /// Replaces the inner shared_ptr to the molecule
300 /// from which the CanvasMolecule is lowered.
301 ///
302 /// Meant to be called when performing a deep-copy
303 void update_source_molecule(std::shared_ptr<RDKit::RWMol> rdkit_mol);
304
305 /// Clears the drawing-friendly 2D representation data
306 /// and re-creates it from the internal RDKit::RWMol
307 ///
308 /// If `sanitize_after` is true, the molecule will get sanitized
309 /// after lowering.
310 /// QED gets recomputed and updated if `with_qed` is true
311 void lower_from_rdkit(bool sanitize_after, bool with_qed = true);
312
313 /// Clears `cached_atom_coordinate_map`,
314 /// forcing the subsequent call to `compute_molecule_geometry()`
315 /// to determine the shape of the molecule from scratch.
316 ///
317 /// This is what makes the "Format" tool work.
318 void clear_cached_atom_coordinate_map();
319
320 /// Updates the `cached_atom_coordinate_map` after an atom has been removed
321 /// in such a way as to prevent the cached molecule geometry from being broken
322 void update_cached_atom_coordinate_map_after_atom_removal(unsigned int removed_atom_idx);
323
324 /// Sets the scale for drawing
325 void set_canvas_scale(float scale);
326
327 void apply_canvas_translation(int delta_x, int delta_y) noexcept;
328 std::pair<float,float> get_on_screen_coords(float x, float y) const noexcept;
329 std::optional<std::pair<float,float>> get_on_screen_coords_of_atom(unsigned int atom_idx) const noexcept;
330 graphene_rect_t get_on_screen_bounding_rect() const noexcept;
331 std::optional<QEDInfo> get_qed_info() const noexcept;
332 void perform_flip(FlipMode flip_mode);
333 void rotate_by_angle(double radians);
334
335 /// Draws the molecule using the renderer
336 void draw(impl::Renderer& ren, DisplayMode display_mode) const noexcept;
337
338 /// Checks if any object matches the click coordinates passed as arguments.
339 /// Returns the thing that was clicked on (or nullopt if there's no match).
340 MaybeAtomOrBond resolve_click(int x, int y) const noexcept;
341
342 void add_atom_highlight(int atom_idx, HighlightType htype);
343 void add_bond_highlight(unsigned int atom_a, unsigned int atom_b, HighlightType htype);
344 void add_highlight_to_all_bonds(HighlightType htype);
345 /// Clears the highlight flag of the given type (for both atoms and bonds)
346 void clear_highlights(HighlightType htype = HighlightType::Hover);
347
348 static RDKit::Bond::BondType bond_type_to_rdkit(BondType) noexcept;
349 static BondGeometry bond_geometry_from_rdkit(RDKit::Bond::BondDir) noexcept;
350 static BondGeometry cycle_bond_geometry(BondGeometry) noexcept;
351 static RDKit::Bond::BondDir bond_geometry_to_rdkit(BondGeometry) noexcept;
352
353 };
354
355
356 } // namespace ligand_editor_canvas
357 } // namesapce coot
358
359 #endif // COOT_LIGAND_EDITOR_CANVAS_MODEL_HPP