Debian Codegraph @

avogadro/qtplugins/applycolors/applycolors.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 "applycolors.h"
7 #include "ui_chargedialog.h"
8
9 #include <avogadro/calc/chargemanager.h>
10 #include <avogadro/core/residue.h>
11 #include <avogadro/core/residuecolors.h>
12 #include <avogadro/core/vector.h>
13 #include <avogadro/qtgui/molecule.h>
14 #include <avogadro/qtgui/rwmolecule.h>
15
16 #include <QAction>
17 #include <QColorDialog>
18 #include <QInputDialog>
19 #include <QStringList>
20
21 #include <QDebug>
22
23 using namespace tinycolormap;
24
25 namespace Avogadro::QtPlugins {
26
27 const int atomColors = 0;
28 const int bondColors = 1;
29 const int residueColors = 2;
30
31 class ChargeColorDialog : public QDialog, public Ui::ChargeDialog
32 {
33 public:
34 ChargeColorDialog(QWidget* parent = nullptr) : QDialog(parent)
35 {
36 setWindowFlags(Qt::Dialog | Qt::Tool);
37 setupUi(this);
38 }
39 };
40
41 ApplyColors::ApplyColors(QObject* parent_)
42 : Avogadro::QtGui::ExtensionPlugin(parent_), m_molecule(nullptr),
43 m_dialog(nullptr)
44 {
45 QAction* action;
46
47 action = new QAction(tr("By Custom Color…"), this);
48 action->setData(atomColors);
49 connect(action, SIGNAL(triggered()), SLOT(openColorDialog()));
50 m_actions.append(action);
51
52 action = new QAction(tr("By Atomic Index…"), this);
53 action->setData(atomColors);
54 connect(action, SIGNAL(triggered()), SLOT(applyIndexColors()));
55 m_actions.append(action);
56
57 action = new QAction(tr("By Distance…"), this);
58 action->setData(atomColors);
59 connect(action, SIGNAL(triggered()), SLOT(applyDistanceColors()));
60 m_actions.append(action);
61
62 action = new QAction(tr("By Element"), this);
63 action->setData(atomColors);
64 connect(action, SIGNAL(triggered()), SLOT(resetColors()));
65 m_actions.append(action);
66
67 // not sure if we want to color atoms by residue or not...
68 action = new QAction(tr("By Custom Color…"), this);
69 action->setData(residueColors);
70 connect(action, SIGNAL(triggered()), SLOT(openColorDialogResidue()));
71 m_actions.append(action);
72
73 action = new QAction(tr("By Chain"), this);
74 action->setData(residueColors);
75 connect(action, SIGNAL(triggered()), SLOT(resetColorsResidue()));
76 m_actions.append(action);
77
78 action = new QAction(tr("By Partial Charge…"), this);
79 action->setData(atomColors);
80 connect(action, SIGNAL(triggered()), SLOT(applyChargeColors()));
81 m_actions.append(action);
82
83 action = new QAction(tr("By Secondary Structure"), this);
84 action->setData(residueColors);
85 connect(action, SIGNAL(triggered()), SLOT(applySecondaryStructureColors()));
86 m_actions.append(action);
87
88 action = new QAction(tr("By Amino Acid"), this);
89 action->setData(residueColors);
90 connect(action, SIGNAL(triggered()), SLOT(applyAminoColors()));
91 m_actions.append(action);
92
93 action = new QAction(tr("By Shapely Scheme"), this);
94 action->setData(residueColors);
95 connect(action, SIGNAL(triggered()), SLOT(applyShapelyColors()));
96 m_actions.append(action);
97 }
98
99 ApplyColors::~ApplyColors()
100 {
101 if (m_dialog)
102 m_dialog->deleteLater();
103 }
104
105 ColormapType ApplyColors::getColormapFromString(const QString& name) const
106 {
107 // Just do all of them, even though we won't use them all
108 if (name == tr("Parula", "colormap"))
109 return ColormapType::Parula;
110 else if (name == tr("Heat", "colormap"))
111 return ColormapType::Heat;
112 else if (name == tr("Hot", "colormap"))
113 return ColormapType::Hot;
114 else if (name == tr("Gray", "colormap"))
115 return ColormapType::Gray;
116 else if (name == tr("Magma", "colormap"))
117 return ColormapType::Magma;
118 else if (name == tr("Inferno", "colormap"))
119 return ColormapType::Inferno;
120 else if (name == tr("Plasma", "colormap"))
121 return ColormapType::Plasma;
122 else if (name == tr("Viridis", "colormap"))
123 return ColormapType::Viridis;
124 else if (name == tr("Cividis", "colormap"))
125 return ColormapType::Cividis;
126 else if (name == tr("Spectral", "colormap"))
127 return ColormapType::Spectral;
128 else if (name == tr("Coolwarm", "colormap"))
129 return ColormapType::Coolwarm;
130 else if (name == tr("Balance", "colormap"))
131 return ColormapType::Balance;
132 else if (name == tr("Blue-DarkRed", "colormap"))
133 return ColormapType::BlueDkRed;
134 else if (name == tr("Turbo", "colormap"))
135 return ColormapType::Turbo;
136
137 return ColormapType::Turbo;
138 }
139
140 QString ApplyColors::description() const
141 {
142 return tr("Apply color schemes to atoms and residues.");
143 }
144
145 QList<QAction*> ApplyColors::actions() const
146 {
147 return m_actions;
148 }
149
150 QStringList ApplyColors::menuPath(QAction* action) const
151 {
152 if (action->data() == atomColors)
153 return QStringList() << tr("&View") << tr("Color Atoms");
154 else if (action->data() == residueColors)
155 return QStringList() << tr("&View") << tr("Color Residues");
156 else
157 return QStringList();
158 }
159
160 void ApplyColors::setMolecule(QtGui::Molecule* mol)
161 {
162 m_molecule = mol;
163 }
164
165 void ApplyColors::openColorDialog()
166 {
167 if (m_dialog == nullptr) {
168 m_dialog = new QColorDialog(qobject_cast<QWidget*>(parent()));
169 connect(m_dialog, SIGNAL(currentColorChanged(const QColor&)),
170 SLOT(applyCustomColor(const QColor&)));
171 }
172
173 m_dialog->exec();
174 }
175
176 // TODO - read colormap gradients (e.g., turbo)
177 Vector3ub rainbowGradient(const float value,
178 const ColormapType type = ColormapType::Turbo)
179 {
180 auto color = tinycolormap::GetColor(value, type);
181 Vector3ub ci(color.ri(), color.gi(), color.bi());
182
183 return ci;
184 }
185
186 Vector3ub chargeGradient(const float value, const float clamp,
187 const ColormapType type = ColormapType::Coolwarm)
188 {
189 // okay, typically color scales have blue at the bottom, red at the top.
190 // so we need to invert, so blue is positive charge, red is negative charge.
191 // we also need to scale the color to the range of the charge.
192 float scaledValue = value / clamp; // from -1 to 1.0
193 float scaledValue2 =
194 1.0 - ((scaledValue + 1.0) / 2.0); // from 0 to 1.0 red to blue
195
196 auto color = tinycolormap::GetColor(scaledValue2, type);
197 Vector3ub ci(color.ri(), color.gi(), color.bi());
198
199 return ci;
200 }
201
202 void ApplyColors::applyIndexColors()
203 {
204 if (m_molecule == nullptr)
205 return;
206
207 // check on colormap
208 ColormapType type = ColormapType::Turbo;
209 QStringList colormaps;
210 bool ok;
211 colormaps << tr("Parula", "colormap") << tr("Magma", "colormap")
212 << tr("Inferno", "colormap") << tr("Plasma", "colormap")
213 << tr("Viridis", "colormap") << tr("Cividis", "colormap")
214 << tr("Spectral", "colormap") << tr("Turbo", "colormap");
215
216 QString item = QInputDialog::getItem(
217 nullptr, tr("Select Colormap"), tr("Colormap:"), colormaps, 7, false, &ok);
218 if (ok) {
219 type = getColormapFromString(item);
220 }
221
222 bool isSelection = !m_molecule->isSelectionEmpty();
223
224 auto* rwmol = m_molecule->undoMolecule();
225 rwmol->beginMergeMode(tr("Apply Index Colors"));
226 auto numAtoms = rwmol->atomCount();
227 for (Index i = 0; i < numAtoms; ++i) {
228 // if there's a selection and this atom isn't selected, skip it
229 if (isSelection && !m_molecule->atomSelected(i))
230 continue;
231
232 float indexFraction = float(i) / (float(numAtoms) - 1);
233
234 rwmol->setColor(i, rainbowGradient(indexFraction, type));
235 }
236 rwmol->endMergeMode();
237 m_molecule->emitChanged(QtGui::Molecule::Atoms);
238 }
239
240 void ApplyColors::applyChargeColors()
241 {
242 if (m_molecule == nullptr)
243 return;
244
245 bool isSelection = !m_molecule->isSelectionEmpty();
246
247 // get the list of possible models
248 const auto identifiers =
249 Calc::ChargeManager::instance().identifiersForMolecule(*m_molecule);
250 if (identifiers.empty())
251 return;
252
253 // populate the dialog to choose the model and colormap
254 ChargeColorDialog dialog;
255 for (const auto& model : identifiers) {
256 auto name = Calc::ChargeManager::instance().nameForModel(model);
257 dialog.modelCombo->addItem(name.c_str(), model.c_str());
258 }
259 dialog.exec();
260 if (dialog.result() != QDialog::Accepted)
261 return;
262
263 // get the model and colormap
264 const auto model = dialog.modelCombo->currentData().toString().toStdString();
265 const auto colormapName = dialog.colorMapCombo->currentText();
266 const auto type = getColormapFromString(colormapName);
267
268 // first off, get the range of partial charges
269 auto numAtoms = m_molecule->atomCount();
270 float minCharge = 0.0f;
271 float maxCharge = 0.0f;
272 auto charges =
273 Calc::ChargeManager::instance().partialCharges(model, *m_molecule);
274 // check if the model string is already a partial charge type
275 if (m_molecule->partialChargeTypes().find(model) !=
276 m_molecule->partialChargeTypes().end()) {
277 charges = m_molecule->partialCharges(model);
278 }
279
280 for (Index i = 0; i < numAtoms; ++i) {
281 float charge = charges(i, 0);
282 minCharge = std::min(minCharge, charge);
283 maxCharge = std::max(maxCharge, charge);
284 }
285
286 // now apply the colors
287 float clamp = std::max(std::abs(minCharge), std::abs(maxCharge));
288 auto* rwmol = m_molecule->undoMolecule();
289 rwmol->beginMergeMode(tr("Apply Charge Colors"));
290 for (Index i = 0; i < numAtoms; ++i) {
291 // if there's a selection and this atom isn't selected, skip it
292 if (isSelection && !m_molecule->atomSelected(i))
293 continue;
294
295 rwmol->setColor(i, chargeGradient(charges(i, 0), clamp, type));
296 }
297 rwmol->endMergeMode();
298 m_molecule->emitChanged(QtGui::Molecule::Atoms);
299 }
300
301 void ApplyColors::applyDistanceColors()
302 {
303 if (m_molecule == nullptr || m_molecule->atomCount() == 0)
304 return;
305
306 bool isSelection = !m_molecule->isSelectionEmpty();
307
308 // check on colormap
309 ColormapType type = ColormapType::Turbo;
310 QStringList colormaps;
311 bool ok;
312 colormaps << tr("Parula", "colormap") << tr("Magma", "colormap")
313 << tr("Inferno", "colormap") << tr("Plasma", "colormap")
314 << tr("Viridis", "colormap") << tr("Cividis", "colormap")
315 << tr("Spectral", "colormap") << tr("Turbo", "colormap");
316
317 QString item = QInputDialog::getItem(
318 nullptr, tr("Select Colormap"), tr("Colormap:"), colormaps, 7, false, &ok);
319 if (ok) {
320 type = getColormapFromString(item);
321 }
322
323 Vector3 firstPos = m_molecule->atomPosition3d(0);
324 Real size = 2.0 * m_molecule->radius();
325
326 auto* rwmol = m_molecule->undoMolecule();
327 rwmol->beginMergeMode(tr("Apply Distance Colors"));
328 auto numAtoms = rwmol->atomCount();
329 for (Index i = 0; i < numAtoms; ++i) {
330 // if there's a selection and this atom isn't selected, skip it
331 if (isSelection && !m_molecule->atomSelected(i))
332 continue;
333
334 Vector3 currPos = m_molecule->atomPosition3d(i);
335 Vector3 diff = currPos - firstPos;
336 Real distance = diff.norm();
337 Real distanceFraction = distance / size;
338
339 rwmol->setColor(i, rainbowGradient(distanceFraction, type));
340 }
341 rwmol->endMergeMode();
342 m_molecule->emitChanged(QtGui::Molecule::Atoms);
343 }
344
345 void ApplyColors::resetColors()
346 {
347 if (m_molecule == nullptr)
348 return;
349
350 bool isSelection = !m_molecule->isSelectionEmpty();
351
352 auto* rwmol = m_molecule->undoMolecule();
353 rwmol->beginMergeMode(tr("Reset Atom Colors"));
354 for (Index i = 0; i < rwmol->atomCount(); ++i) {
355 // if there's a selection and this atom isn't selected, skip it
356 if (isSelection && !m_molecule->atomSelected(i))
357 continue;
358
359 Vector3ub color(Core::Elements::color(m_molecule->atomicNumber(i)));
360 rwmol->setColor(i, color);
361 }
362 rwmol->endMergeMode();
363 m_molecule->emitChanged(QtGui::Molecule::Atoms);
364 }
365
366 void ApplyColors::applyCustomColor(const QColor& new_color)
367 {
368 if (m_molecule == nullptr)
369 return;
370
371 bool isSelection = !m_molecule->isSelectionEmpty();
372
373 Vector3ub color; // map to our types
374 color[0] = static_cast<unsigned char>(new_color.red());
375 color[1] = static_cast<unsigned char>(new_color.green());
376 color[2] = static_cast<unsigned char>(new_color.blue());
377
378 auto* rwmol = m_molecule->undoMolecule();
379 rwmol->beginMergeMode(tr("Apply Custom Color"));
380 for (Index i = 0; i < rwmol->atomCount(); ++i) {
381 // if there's a selection and this atom isn't selected, skip it
382 if (isSelection && !m_molecule->atomSelected(i))
383 continue;
384
385 rwmol->setColor(i, color);
386 }
387 rwmol->endMergeMode();
388 m_molecule->emitChanged(QtGui::Molecule::Atoms);
389 }
390
391 void ApplyColors::openColorDialogResidue()
392 {
393 if (m_dialog == nullptr) {
394 m_dialog = new QColorDialog(qobject_cast<QWidget*>(parent()));
395 }
396 m_dialog->disconnect();
397 connect(m_dialog, SIGNAL(currentColorChanged(const QColor&)),
398 SLOT(applyCustomColorResidue(const QColor&)));
399
400 m_dialog->exec();
401 }
402
403 void ApplyColors::applyCustomColorResidue(const QColor& new_color)
404 {
405 if (m_molecule == nullptr)
406 return;
407
408 bool isSelection = !m_molecule->isSelectionEmpty();
409
410 Vector3ub color; // map to our types
411 color[0] = static_cast<unsigned char>(new_color.red());
412 color[1] = static_cast<unsigned char>(new_color.green());
413 color[2] = static_cast<unsigned char>(new_color.blue());
414
415 auto* rwmol = m_molecule->undoMolecule();
416 rwmol->beginMergeMode(tr("Apply Custom Residue Color"));
417 for (Index i = 0; i < m_molecule->residueCount(); ++i) {
418 // if there's a selection and this residue isn't selected, skip it
419 auto& residue = m_molecule->residue(i);
420 if (isSelection) {
421 auto caAtom = residue.atomByName("CA");
422 if (!caAtom.isValid() || !m_molecule->atomSelected(caAtom.index()))
423 continue;
424 }
425
426 rwmol->setResidueColor(i, color);
427 }
428 rwmol->endMergeMode();
429 m_molecule->emitChanged(QtGui::Molecule::Atoms);
430 }
431
432 void ApplyColors::resetColorsResidue()
433 {
434 if (m_molecule == nullptr)
435 return;
436
437 bool isSelection = !m_molecule->isSelectionEmpty();
438
439 auto* rwmol = m_molecule->undoMolecule();
440 rwmol->beginMergeMode(tr("Reset Residue Colors"));
441 for (Index i = 0; i < m_molecule->residueCount(); ++i) {
442 // if there's a selection and this residue isn't selected, skip it
443 auto& residue = m_molecule->residue(i);
444 if (isSelection) {
445 auto caAtom = residue.atomByName("CA");
446 if (!caAtom.isValid() || !m_molecule->atomSelected(caAtom.index()))
447 continue;
448 }
449
450 int offset = 0;
451 char chainId = residue.chainId();
452 if (chainId >= 'A' && chainId <= 'Z')
453 offset = chainId - 'A';
454 else if (chainId >= 'a' && chainId <= 'z')
455 offset = chainId - 'a';
456 else if (chainId >= '0' && chainId <= '9')
457 offset = chainId - '0' + 15; // starts at 'P'
458
459 Vector3ub color(Core::chain_color[offset]);
460 rwmol->setResidueColor(i, color);
461 }
462 rwmol->endMergeMode();
463 m_molecule->emitChanged(QtGui::Molecule::Atoms);
464 }
465
466 void ApplyColors::applySecondaryStructureColors()
467 {
468 if (m_molecule == nullptr)
469 return;
470
471 bool isSelection = !m_molecule->isSelectionEmpty();
472
473 auto* rwmol = m_molecule->undoMolecule();
474 rwmol->beginMergeMode(tr("Apply Secondary Structure Colors"));
475 for (Index i = 0; i < m_molecule->residueCount(); ++i) {
476 // if there's a selection and this residue isn't selected, skip it
477 auto& residue = m_molecule->residue(i);
478 if (isSelection) {
479 auto caAtom = residue.atomByName("CA");
480 if (!caAtom.isValid() || !m_molecule->atomSelected(caAtom.index()))
481 continue;
482 }
483
484 Core::Residue::SecondaryStructure type = residue.secondaryStructure();
485 if (type < 0 || type > 7) {
486 type = Core::Residue::SecondaryStructure::coil;
487 }
488 Vector3ub color(Core::secondary_color[type]);
489 rwmol->setResidueColor(i, color);
490 } // end loop
491 rwmol->endMergeMode();
492 m_molecule->emitChanged(QtGui::Molecule::Atoms);
493 }
494
495 int residueNameToOffset(const std::string& name)
496 {
497 std::string residueName(name);
498 // ensure it's always in uppercase
499 for (auto& c : residueName)
500 c = (unsigned char)toupper(c);
501
502 // used for "amino" and "shapely" color schemes
503 int offset = 22; // other
504 if (residueName == "ALA")
505 offset = 0;
506 else if (residueName == "ARG")
507 offset = 1;
508 else if (residueName == "ASN")
509 offset = 2;
510 else if (residueName == "ASP")
511 offset = 3;
512 else if (residueName == "CYS")
513 offset = 4;
514 else if (residueName == "GLN")
515 offset = 5;
516 else if (residueName == "GLU")
517 offset = 6;
518 else if (residueName == "GLY")
519 offset = 7;
520 else if (residueName == "HIS")
521 offset = 8;
522 else if (residueName == "ILE")
523 offset = 9;
524 else if (residueName == "LEU")
525 offset = 10;
526 else if (residueName == "LYS")
527 offset = 11;
528 else if (residueName == "MET")
529 offset = 12;
530 else if (residueName == "PHE")
531 offset = 13;
532 else if (residueName == "PRO")
533 offset = 14;
534 else if (residueName == "SER")
535 offset = 15;
536 else if (residueName == "THR")
537 offset = 16;
538 else if (residueName == "TRP")
539 offset = 17;
540 else if (residueName == "TYR")
541 offset = 18;
542 else if (residueName == "VAL")
543 offset = 19;
544 else if (residueName == "ASX")
545 offset = 20;
546 else if (residueName == "GLX")
547 offset = 21;
548 else
549 offset = 22; // default
550
551 return offset;
552 }
553
554 void ApplyColors::applyAminoColors()
555 {
556 if (m_molecule == nullptr)
557 return;
558
559 bool isSelection = !m_molecule->isSelectionEmpty();
560
561 auto* rwmol = m_molecule->undoMolecule();
562 rwmol->beginMergeMode(tr("Apply Amino Acid Colors"));
563 for (Index i = 0; i < m_molecule->residueCount(); ++i) {
564 // if there's a selection and this residue isn't selected, skip it
565 auto& residue = m_molecule->residue(i);
566 if (isSelection) {
567 auto caAtom = residue.atomByName("CA");
568 if (!caAtom.isValid() || !m_molecule->atomSelected(caAtom.index()))
569 continue;
570 }
571
572 int offset = residueNameToOffset(residue.residueName());
573
574 Vector3ub color(Core::amino_color[offset]);
575 rwmol->setResidueColor(i, color);
576 }
577 rwmol->endMergeMode();
578 m_molecule->emitChanged(QtGui::Molecule::Atoms);
579 }
580
581 void ApplyColors::applyShapelyColors()
582 {
583 if (m_molecule == nullptr)
584 return;
585
586 bool isSelection = !m_molecule->isSelectionEmpty();
587
588 auto* rwmol = m_molecule->undoMolecule();
589 rwmol->beginMergeMode(tr("Apply Shapely Colors"));
590 for (Index i = 0; i < m_molecule->residueCount(); ++i) {
591 // if there's a selection and this residue isn't selected, skip it
592 auto& residue = m_molecule->residue(i);
593 if (isSelection) {
594 auto caAtom = residue.atomByName("CA");
595 if (!caAtom.isValid() || !m_molecule->atomSelected(caAtom.index()))
596 continue;
597 }
598
599 int offset = residueNameToOffset(residue.residueName());
600
601 Vector3ub color(Core::shapely_color[offset]);
602 rwmol->setResidueColor(i, color);
603 }
604 rwmol->endMergeMode();
605 m_molecule->emitChanged(QtGui::Molecule::Atoms);
606 }
607
608 } // namespace Avogadro::QtPlugins