Debian Codegraph @

avogadro/qtplugins/label/label.cpp

raw
1 /******************************************************************************
2 This source file is part of the Avogadro project.
3 This source code is released under the 3-Clause BSD License, (see "LICENSE").
4 ******************************************************************************/
5
6 #include "label.h"
7
8 #include <iomanip>
9 #include <iostream>
10 #include <sstream>
11
12 // for partial charges
13 #include <avogadro/calc/chargemanager.h>
14
15 #include <avogadro/core/contrastcolor.h>
16 #include <avogadro/core/elements.h>
17 #include <avogadro/core/residue.h>
18 #include <avogadro/qtgui/colorbutton.h>
19 #include <avogadro/qtgui/molecule.h>
20 #include <avogadro/rendering/geometrynode.h>
21 #include <avogadro/rendering/scene.h>
22 #include <avogadro/rendering/textlabel3d.h>
23
24 #include <QtCore/QSettings>
25 #include <QtWidgets/QCheckBox>
26 #include <QtWidgets/QComboBox>
27 #include <QtWidgets/QDoubleSpinBox>
28 #include <QtWidgets/QFormLayout>
29 #include <QtWidgets/QVBoxLayout>
30 #include <QtWidgets/QWidget>
31
32 namespace Avogadro::QtPlugins {
33
34 using Avogadro::Rendering::TextLabel3D;
35 using Core::Array;
36 using Core::Atom;
37 using Core::contrastColor;
38 using Core::Elements;
39 using Core::Molecule;
40 using QtGui::PluginLayerManager;
41 using Rendering::GeometryNode;
42 using Rendering::GroupNode;
43 using std::map;
44
45 typedef Array<Molecule::BondType> NeighborListType;
46
47 namespace {
48 TextLabel3D* createLabel(const std::string& text, const Vector3f& pos,
49 float radius, const Vector3ub& color, float scale = 1.0f)
50 {
51 Rendering::TextProperties tprop;
52 tprop.setAlign(Rendering::TextProperties::HCenter,
53 Rendering::TextProperties::VCenter);
54 tprop.setFontFamily(Rendering::TextProperties::SansSerif);
55 tprop.setColorRgb(color.data());
56 // Apply label scale to the default pixel height (24)
57 tprop.setPixelHeight(static_cast<size_t>(24.0f * scale));
58
59 auto* label = new TextLabel3D;
60 label->setText(text);
61 label->setRenderPass(Rendering::TranslucentPass);
62 label->setTextProperties(tprop);
63 label->setRadius(radius);
64 label->setAnchor(pos);
65 return label;
66 }
67 } // namespace
68
69 struct LayerLabel : Core::LayerData
70 {
71 enum LabelOptions
72 {
73 None = 0,
74 Index = 1,
75 Name = 2,
76 Custom = 4,
77 Ordinal = 8,
78 UniqueID = 16,
79 PartialCharge = 32,
80 Length = 64 // for bonds obviously
81 };
82 unsigned short atomOptions;
83 unsigned short residueOptions;
84 unsigned short bondOptions;
85
86 QWidget* widget;
87 float radiusScalar;
88 float labelScale;
89 Vector3ub color;
90
91 LayerLabel()
92 {
93 widget = nullptr;
94 QSettings settings;
95 atomOptions =
96 settings.value("label/atomoptions", LabelOptions::Name).toInt();
97 residueOptions =
98 settings.value("label/residueoptions", LabelOptions::None).toInt();
99 bondOptions =
100 settings.value("label/bondoptions", LabelOptions::None).toInt();
101 radiusScalar = settings.value("label/radiusscalar", 0.5).toDouble();
102 labelScale = settings.value("label/labelscale", 1.0).toDouble();
103
104 auto q_color =
105 settings.value("label/color", QColor(Qt::white)).value<QColor>();
106 color[0] = static_cast<unsigned char>(q_color.red());
107 color[1] = static_cast<unsigned char>(q_color.green());
108 color[2] = static_cast<unsigned char>(q_color.blue());
109 }
110
111 LayerLabel(std::string settings)
112 {
113 widget = nullptr;
114 deserialize(settings);
115 }
116
117 LayerData* clone() final { return new LayerLabel(serialize()); }
118
119 ~LayerLabel() override
120 {
121 if (widget)
122 widget->deleteLater();
123 }
124
125 std::string serialize() final
126 {
127 std::stringstream output;
128 output << atomOptions << " " << residueOptions << " " << radiusScalar << " "
129 << (int)color[0] << " " << (int)color[1] << " " << (int)color[2]
130 << " " << bondOptions << " " << labelScale;
131 return output.str();
132 }
133
134 void deserialize(std::string text) final
135 {
136 std::stringstream ss(text);
137 std::string aux;
138 ss >> aux;
139 atomOptions = std::stoi(aux);
140 ss >> aux;
141 residueOptions = std::stoi(aux);
142 ss >> aux;
143 radiusScalar = std::stof(aux);
144 ss >> aux;
145 color[0] = std::stoi(aux);
146 ss >> aux;
147 color[1] = std::stoi(aux);
148 ss >> aux;
149 color[2] = std::stoi(aux);
150 ss >> aux;
151 if (!aux.empty())
152 bondOptions = std::stoi(aux); // backwards compatibility
153 ss >> aux;
154 if (!aux.empty())
155 labelScale = std::stof(aux); // backwards compatibility
156 }
157
158 void setupWidget(Label* slot)
159 {
160 if (!widget) {
161 widget = new QWidget(qobject_cast<QWidget*>(slot->parent()));
162 auto* v = new QVBoxLayout;
163
164 auto* form = new QFormLayout;
165 // color button
166 auto* colorButton = new QtGui::ColorButton;
167 QObject::connect(colorButton, SIGNAL(colorChanged(const QColor&)), slot,
168 SLOT(setColor(const QColor&)));
169 form->addRow(QObject::tr("Color:"), colorButton);
170
171 // radius scalar
172 auto* spin = new QDoubleSpinBox;
173 spin->setRange(0.0, 1.5);
174 spin->setSingleStep(0.1);
175 spin->setDecimals(1);
176 spin->setValue(radiusScalar);
177 QObject::connect(spin, SIGNAL(valueChanged(double)), slot,
178 SLOT(setRadiusScalar(double)));
179 form->addRow(QObject::tr("Distance from center:"), spin);
180
181 // label scale
182 auto* scaleSpin = new QDoubleSpinBox;
183 scaleSpin->setRange(0.25, 3.0);
184 scaleSpin->setSingleStep(0.1);
185 scaleSpin->setDecimals(2);
186 scaleSpin->setValue(labelScale);
187 QObject::connect(scaleSpin, SIGNAL(valueChanged(double)), slot,
188 SLOT(setLabelScale(double)));
189 form->addRow(QObject::tr("Label scale:"), scaleSpin);
190
191 auto* atom = new QComboBox;
192 atom->setObjectName("atom");
193
194 // set up the various atom options
195 [[maybe_unused]] char val = LabelOptions::None;
196 QStringList text;
197
198 // first add the individual options
199 atom->addItem(QObject::tr("None"), int(LabelOptions::None));
200 atom->addItem(QObject::tr("Index"), int(LabelOptions::Index));
201 atom->addItem(QObject::tr("Unique ID"), int(LabelOptions::UniqueID));
202 atom->addItem(QObject::tr("Element"), int(LabelOptions::Name));
203 atom->addItem(QObject::tr("Element & Number"),
204 int(LabelOptions::Ordinal));
205 atom->addItem(QObject::tr("Element & ID"),
206 int(LabelOptions::Name | LabelOptions::UniqueID));
207 atom->addItem(QObject::tr("Partial Charge", "atomic partial charge"),
208 int(LabelOptions::PartialCharge));
209 atom->addItem(QObject::tr("Custom"), int(LabelOptions::Custom));
210
211 // check for current option based on item data
212 for (int i = 0; i < atom->count(); ++i) {
213 if (atom->itemData(i).toInt() == atomOptions) {
214 atom->setCurrentIndex(i);
215 break;
216 }
217 }
218
219 QObject::connect(atom, SIGNAL(currentIndexChanged(int)), slot,
220 SLOT(atomLabelType(int)));
221
222 form->addRow(QObject::tr("Atom Label:"), atom);
223
224 // bond label
225 auto* bond = new QComboBox;
226 bond->setObjectName("bond");
227
228 // set up the various bond options
229 bond->addItem(QObject::tr("None"), int(LabelOptions::None));
230 bond->addItem(QObject::tr("Length"), int(LabelOptions::Length));
231 bond->addItem(QObject::tr("Index"), int(LabelOptions::Index));
232 bond->addItem(QObject::tr("Custom"), int(LabelOptions::Custom));
233
234 QObject::connect(bond, SIGNAL(currentIndexChanged(int)), slot,
235 SLOT(bondLabelType(int)));
236 form->addRow(QObject::tr("Bond Label:"), bond);
237
238 auto* residue = new QComboBox;
239 residue->setObjectName("residue");
240
241 // set up the various residue options
242 residue->addItem(QObject::tr("None"), int(LabelOptions::None));
243 residue->addItem(QObject::tr("ID"), int(LabelOptions::Index));
244 residue->addItem(QObject::tr("Name"), int(LabelOptions::Name));
245 residue->addItem(QObject::tr("Name & ID"),
246 int(LabelOptions::Index + LabelOptions::Name));
247 residue->addItem(QObject::tr("Custom"), int(LabelOptions::Custom));
248 QObject::connect(residue, SIGNAL(currentIndexChanged(int)), slot,
249 SLOT(residueLabelType(int)));
250
251 // residue->model()->sort(0, Qt::AscendingOrder);
252 form->addRow(QObject::tr("Residue Label:"), residue);
253
254 v->addLayout(form);
255 v->addStretch(1);
256 widget->setLayout(v);
257 }
258 }
259 };
260
261 Label::Label(QObject* parent_) : QtGui::ScenePlugin(parent_)
262 {
263 m_layerManager = PluginLayerManager(m_name);
264 }
265
266 Label::~Label() {}
267
268 void Label::process(const QtGui::Molecule& molecule, Rendering::GroupNode& node)
269 {
270 m_layerManager.load<LayerLabel>();
271 for (size_t layer = 0; layer < m_layerManager.layerCount(); ++layer) {
272 auto* interface = m_layerManager.getSetting<LayerLabel>(layer);
273 if (interface->residueOptions) {
274 processResidue(molecule, node, layer);
275 }
276 if (interface->atomOptions) {
277 processAtom(molecule, node, layer);
278 }
279 if (interface->bondOptions) {
280 processBond(molecule, node, layer);
281 }
282 }
283 }
284
285 void Label::processResidue(const Core::Molecule& molecule,
286 Rendering::GroupNode& node, size_t layer)
287 {
288 auto* geometry = new GeometryNode;
289 node.addChild(geometry);
290
291 for (const auto& residue : molecule.residues()) {
292 Atom caAtom = residue.atomByName("CA");
293 if (!caAtom.isValid() ||
294 !m_layerManager.atomEnabled(layer, caAtom.index())) {
295 continue;
296 }
297 auto name = residue.residueName();
298 const auto atoms = residue.residueAtoms();
299 const std::string customLabel = molecule.residueLabel(residue.residueId());
300 Vector3f pos = Vector3f::Zero();
301 for (const auto& atom : atoms) {
302 pos += atom.position3d().cast<float>();
303 }
304 pos /= static_cast<float>(atoms.size());
305
306 float radius = 0.0f;
307 for (const auto& atom : atoms) {
308 unsigned char atomicNumber = atom.atomicNumber();
309 auto auxR = static_cast<float>(Elements::radiusVDW(atomicNumber));
310 auxR += (atom.position3d().cast<float>() - pos).norm();
311 if (auxR > radius) {
312 auxR = radius;
313 }
314 }
315
316 auto* interface = m_layerManager.getSetting<LayerLabel>(layer);
317 Vector3ub color = interface->color;
318 std::string text = "";
319 if (interface->residueOptions & LayerLabel::LabelOptions::Name) {
320 text = (text == "" ? "" : " / ") + name;
321 }
322 if (interface->residueOptions & LayerLabel::LabelOptions::Index) {
323 text += std::to_string(residue.residueId());
324 }
325 if (interface->residueOptions & LayerLabel::LabelOptions::Custom) {
326 text += (text == "" ? "" : " / ") + customLabel;
327 }
328 TextLabel3D* residueLabel = createLabel(text, pos, radius, color, interface->labelScale);
329 geometry->addDrawable(residueLabel);
330 }
331 }
332
333 QString partialCharge(Molecule* molecule, int atom)
334 {
335 // TODO: we need to track type and/or calling the charge calculator
336 float charge = 0.0;
337 std::set<std::string> types = molecule->partialChargeTypes();
338 if (types.size() > 0) {
339 auto first = types.cbegin();
340 MatrixX charges = molecule->partialCharges((*first));
341 charge = charges(atom, 0);
342 } else {
343 // find something
344 const auto options =
345 Calc::ChargeManager::instance().identifiersForMolecule(*molecule);
346 if (options.size() > 0) {
347 // look for GFN2 or AM1BCC, then MMFF94 then Gasteiger
348 std::string type;
349 if (options.find("GFN2") != options.end())
350 type = "GFN2";
351 else if (options.find("am1bcc") != options.end())
352 type = "am1bcc";
353 else if (options.find("mmff94") != options.end())
354 type = "mmff94";
355 else if (options.find("gasteiger") != options.end())
356 type = "gasteiger";
357 else
358 type = *options.begin();
359
360 MatrixX charges =
361 Calc::ChargeManager::instance().partialCharges(type, *molecule);
362 charge = charges(atom, 0);
363 }
364 }
365 // e.g. '-0.12' => 5 characters
366 return QString("%L1").arg(charge, 5, 'f', 2);
367 }
368
369 void Label::processAtom(const Core::Molecule& molecule,
370 Rendering::GroupNode& node, size_t layer)
371 {
372 auto* geometry = new GeometryNode;
373 node.addChild(geometry);
374 std::map<unsigned char, size_t> atomCount;
375 for (Index i = 0; i < molecule.atomCount(); ++i) {
376 Core::Atom atom = molecule.atom(i);
377
378 unsigned char atomicNumber = atom.atomicNumber();
379 if (atomCount.find(atomicNumber) == atomCount.end()) {
380 atomCount[atomicNumber] = 1;
381 } else {
382 ++atomCount[atomicNumber];
383 }
384
385 if (!m_layerManager.atomEnabled(layer, i)) {
386 continue;
387 }
388
389 auto* interface = m_layerManager.getSetting<LayerLabel>(layer);
390 std::string text = atom.label();
391
392 if (interface->atomOptions & LayerLabel::LabelOptions::PartialCharge) {
393 QString charge = partialCharge(const_cast<Molecule*>(&molecule), i);
394 text += charge.toStdString();
395 }
396 if (interface->atomOptions & LayerLabel::LabelOptions::Custom) {
397 // already set
398 }
399 if (interface->atomOptions & LayerLabel::LabelOptions::Index) {
400 text += (text == "" ? "" : " / ") + std::to_string(atom.index() + 1);
401 }
402 if (interface->atomOptions & LayerLabel::LabelOptions::Name) {
403 std::string name = std::string(Elements::symbol(atomicNumber));
404 // D or T for hydrogen isotopes
405 if (atomicNumber == 1) {
406 if (atom.isotope() == 2) {
407 name = "D";
408 } else if (atom.isotope() == 3) {
409 name = "T";
410 }
411 }
412 text += (text == "" ? "" : " / ") + name;
413 }
414 if (interface->atomOptions & LayerLabel::LabelOptions::Ordinal) {
415 text += (text == "" ? "" : " / ") +
416 std::string(Elements::symbol(atomicNumber) +
417 std::to_string(atomCount[atomicNumber]));
418 }
419 if (interface->atomOptions & LayerLabel::LabelOptions::UniqueID) {
420 text += (text == "" ? "" : " / ") + std::to_string(atom.index());
421 }
422 if (text != "") {
423 const Vector3f pos(atom.position3d().cast<float>());
424 Vector3ub color = atom.color();
425 float radius = static_cast<float>(Elements::radiusVDW(atomicNumber)) *
426 interface->radiusScalar;
427
428 TextLabel3D* atomLabel =
429 createLabel(text, pos, radius, contrastColor(color), interface->labelScale);
430 geometry->addDrawable(atomLabel);
431 }
432 }
433 }
434
435 void Label::processBond(const Core::Molecule& molecule,
436 Rendering::GroupNode& node,
437 [[maybe_unused]] size_t layer)
438 {
439 auto* geometry = new GeometryNode;
440 node.addChild(geometry);
441 std::map<unsigned char, size_t> bondCount;
442 for (Index i = 0; i < molecule.bondCount(); ++i) {
443 Core::Bond bond = molecule.bond(i);
444
445 // check if the bond is enabled in this layer
446 if (!m_layerManager.bondEnabled(bond.atom1().index(),
447 bond.atom2().index())) {
448 continue;
449 }
450
451 // get the options for this bond
452 Core::Atom atom1 = bond.atom1();
453 Core::Atom atom2 = bond.atom2();
454 auto* interface1 = m_layerManager.getSetting<LayerLabel>(
455 m_layerManager.getLayerID(atom1.index()));
456 auto* interface2 = m_layerManager.getSetting<LayerLabel>(
457 m_layerManager.getLayerID(atom2.index()));
458
459 // get the union of the options
460 char options = interface1->bondOptions | interface2->bondOptions;
461 Vector3ub color = interface1->color;
462 unsigned char atomicNumber1 = atom1.atomicNumber();
463 unsigned char atomicNumber2 = atom2.atomicNumber();
464 float radiusVDW1 = static_cast<float>(Elements::radiusVDW(atomicNumber1));
465 float radiusVDW2 = static_cast<float>(Elements::radiusVDW(atomicNumber2));
466 float radius = (radiusVDW1 + radiusVDW2) * interface1->radiusScalar / 2.0f;
467
468 std::stringstream text;
469 // hopefully not all at once
470 if (options & LayerLabel::LabelOptions::Index) {
471 text << bond.index();
472 }
473 if (options & LayerLabel::LabelOptions::Custom) {
474 text << bond.label();
475 }
476 if (options & LayerLabel::LabelOptions::Length) {
477 text << std::fixed << std::setprecision(2) << bond.length();
478 }
479
480 // position will be between the two atoms
481 Vector3f pos =
482 (atom1.position3d().cast<float>() + atom2.position3d().cast<float>()) /
483 2.0f;
484
485 TextLabel3D* bondLabel = createLabel(text.str(), pos, radius, color, interface1->labelScale);
486 geometry->addDrawable(bondLabel);
487 }
488 }
489
490 void Label::setColor(const QColor& color)
491 {
492 auto* interface = m_layerManager.getSetting<LayerLabel>();
493
494 interface->color[0] = static_cast<unsigned char>(color.red());
495 interface->color[1] = static_cast<unsigned char>(color.green());
496 interface->color[2] = static_cast<unsigned char>(color.blue());
497
498 emit drawablesChanged();
499
500 QSettings settings;
501 settings.setValue("label/color", color);
502 }
503
504 void Label::atomLabelType(int index)
505 {
506 auto* interface = m_layerManager.getSetting<LayerLabel>();
507 interface->atomOptions = char(setupWidget()
508 ->findChildren<QComboBox*>("atom")[0]
509 ->itemData(index)
510 .toInt());
511 emit drawablesChanged();
512
513 QSettings settings;
514 settings.setValue("label/atomoptions", interface->atomOptions);
515 }
516
517 void Label::bondLabelType(int index)
518 {
519 auto* interface = m_layerManager.getSetting<LayerLabel>();
520 interface->bondOptions = char(setupWidget()
521 ->findChildren<QComboBox*>("bond")[0]
522 ->itemData(index)
523 .toInt());
524 emit drawablesChanged();
525
526 QSettings settings;
527 settings.setValue("label/bondoptions", interface->bondOptions);
528 }
529
530 void Label::residueLabelType(int index)
531 {
532 auto* interface = m_layerManager.getSetting<LayerLabel>();
533 interface->residueOptions = char(setupWidget()
534 ->findChildren<QComboBox*>("residue")[0]
535 ->itemData(index)
536 .toInt());
537 emit drawablesChanged();
538
539 QSettings settings;
540 settings.setValue("label/residueoptions", interface->residueOptions);
541 }
542
543 void Label::setRadiusScalar(double radius)
544 {
545 auto* interface = m_layerManager.getSetting<LayerLabel>();
546 interface->radiusScalar = float(radius);
547 emit drawablesChanged();
548
549 QSettings settings;
550 settings.setValue("label/radiusscalar", interface->radiusScalar);
551 }
552
553 void Label::setLabelScale(double scale)
554 {
555 auto* interface = m_layerManager.getSetting<LayerLabel>();
556 interface->labelScale = float(scale);
557 emit drawablesChanged();
558
559 QSettings settings;
560 settings.setValue("label/labelscale", interface->labelScale);
561 }
562
563 QWidget* Label::setupWidget()
564 {
565 auto* interface = m_layerManager.getSetting<LayerLabel>();
566 interface->setupWidget(this);
567 return interface->widget;
568 }
569
570 } // namespace Avogadro::QtPlugins