Debian Codegraph @

avogadro/qtplugins/propertytables/propertymodel.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 "propertymodel.h"
7
8 #include <avogadro/calc/chargemanager.h>
9 #include <avogadro/core/array.h>
10 #include <avogadro/core/atom.h>
11 #include <avogadro/core/bond.h>
12 #include <avogadro/core/elements.h>
13 #include <avogadro/core/residue.h>
14 #include <avogadro/qtgui/molecule.h>
15
16 #include <avogadro/core/angleiterator.h>
17 #include <avogadro/core/angletools.h>
18 #include <avogadro/core/dihedraliterator.h>
19
20 #include <QtCore/QDebug>
21 #include <QtGui/QColor>
22 #include <QtWidgets/QColorDialog>
23
24 #include <limits>
25
26 #include <Eigen/Geometry>
27
28 namespace Avogadro {
29
30 using Avogadro::Core::Array;
31 using Avogadro::QtGui::Molecule;
32 using QtGui::Molecule;
33 using QtGui::RWAtom;
34 using QtGui::RWBond;
35 using std::numeric_limits;
36 using std::pair;
37 using std::vector;
38
39 using SecondaryStructure = Avogadro::Core::Residue::SecondaryStructure;
40
41 // element, valence, formal charge, partial charge, x, y, z, label, isotope,
42 // color
43 const int AtomColumns = 10;
44 // type, atom 1, atom 2, bond order, length, label
45 const int BondColumns = 6;
46 // type, atom 1, atom 2, atom 3, angle
47 const int AngleColumns = 5;
48 // type, atom 1, atom 2, atom 3, atom 4, dihedral
49 const int TorsionColumns = 6;
50 // name, number, chain, secondary structure, label, heterogen, color
51 const int ResidueColumns = 7;
52 // number, rmsd, energy or more depending on available properties
53 const int ConformerColumns = 1;
54
55 // compute the RMSD between the two sets of coordinates
56 inline double calculateRMSD(const Array<Vector3>& v1, const Array<Vector3>& v2)
57 {
58 // if they're not the same length, it's an error
59 if (v1.size() != v2.size())
60 return numeric_limits<double>::quiet_NaN();
61
62 double sum = 0.0;
63 for (size_t i = 0; i < v1.size(); ++i) {
64 Vector3 diff = v1[i] - v2[i];
65 sum += diff.squaredNorm();
66 }
67 return sqrt(sum / v1.size());
68 }
69
70 inline double distance(Vector3 v1, Vector3 v2)
71 {
72 Vector3 v3 = v1 - v2;
73 return v3.norm();
74 }
75
76 inline QString angleTypeString(unsigned char a, unsigned char b,
77 unsigned char c)
78 {
79 return QString("%1%2%3")
80 .arg(Core::Elements::symbol(a))
81 .arg(Core::Elements::symbol(b))
82 .arg(Core::Elements::symbol(c));
83 }
84
85 inline QString torsionTypeString(unsigned char a, unsigned char b,
86 unsigned char c, unsigned char d)
87 {
88 return QString("%1%2%3%4")
89 .arg(Core::Elements::symbol(a))
90 .arg(Core::Elements::symbol(b))
91 .arg(Core::Elements::symbol(c))
92 .arg(Core::Elements::symbol(d));
93 }
94
95 PropertyModel::PropertyModel(PropertyType type, QObject* parent)
96 : QAbstractTableModel(parent), m_type(type), m_molecule(nullptr)
97 {
98 }
99
100 int PropertyModel::rowCount(const QModelIndex& parent) const
101 {
102 Q_UNUSED(parent);
103
104 if (!m_validCache)
105 updateCache();
106
107 switch (m_type) {
108 case AtomType:
109 return m_molecule->atomCount();
110 case BondType:
111 return m_molecule->bondCount();
112 case ResidueType:
113 return m_molecule->residueCount();
114 case AngleType:
115 return m_angles.size();
116 case TorsionType:
117 return m_torsions.size();
118 case ConformerType:
119 return m_molecule->coordinate3dCount();
120 default:
121 return 0;
122 }
123
124 return 0;
125 }
126
127 int PropertyModel::columnCount(const QModelIndex& parent) const
128 {
129 Q_UNUSED(parent);
130 switch (m_type) {
131 case AtomType:
132 return AtomColumns; // see above
133 case BondType:
134 return BondColumns; // see above
135 case AngleType:
136 return AngleColumns; // see above
137 case TorsionType:
138 return TorsionColumns;
139 case ResidueType:
140 return ResidueColumns;
141 case ConformerType: {
142 if (m_molecule->hasData("energies"))
143 return ConformerColumns + 1;
144 else
145 return ConformerColumns;
146 }
147 default:
148 return 0;
149 }
150 return 0;
151 }
152
153 QString partialChargeType(Molecule* molecule)
154 {
155 QString type;
156
157 std::set<std::string> types = molecule->partialChargeTypes();
158
159 if (types.size() > 0) {
160 type = QString(types.cbegin()->c_str());
161 } else {
162 // find something
163 const auto options =
164 Calc::ChargeManager::instance().identifiersForMolecule(*molecule);
165 if (options.size() > 0) {
166 // look for GFN2 or AM1BCC, then MMFF94 then Gasteiger
167 if (options.find("GFN2") != options.end())
168 type = "GFN2";
169 else if (options.find("am1bcc") != options.end())
170 type = "am1bcc";
171 else if (options.find("mmff94") != options.end())
172 type = "mmff94";
173 else if (options.find("gasteiger") != options.end())
174 type = "gasteiger";
175 else
176 type = *options.begin()->c_str();
177 }
178 }
179
180 return type;
181 }
182
183 QString formatChargeType(QString type)
184 {
185 if (type == "gfn2")
186 return "GFN2";
187 else if (type == "am1bcc")
188 return "AM1BCC";
189 else if (type == "mmff94")
190 return "MMFF94";
191 else if (type == "gasteiger")
192 return "Gasteiger";
193 else if (type.startsWith("eem"))
194 return "EEM";
195 else if (type == "qeq")
196 return "QEq";
197 else if (type.toLower() == "mulliken")
198 return "Mulliken";
199 else if (type.toLower() == "lowdin")
200 return "Löwdin";
201 else if (type.toLower() == "loewdin")
202 return "Löwdin";
203 else if (type.toLower() == "chelpg")
204 return "CHELPG";
205 else if (type.toLower() == "hirshfeld")
206 return "Hirshfeld";
207 else if (type.toLower() == "resp")
208 return "RESP";
209 else if (type.toLower() == "mbis")
210 return "MBIS";
211 else if (type.toLower() == "abcg2")
212 return "ABCG2";
213 else if (type.toLower() == "cm5")
214 return "CM5";
215 else
216 return type;
217 }
218
219 QString partialCharge(Molecule* molecule, int atom, const QString& overrideType)
220 {
221 float charge = 0.0;
222 std::string type = overrideType.isEmpty()
223 ? partialChargeType(molecule).toStdString()
224 : overrideType.toStdString();
225
226 // first check if the molecule already has this charge type
227 // (e.g., read from a file like Mulliken charges)
228 // we need to use the original case from the molecule
229 std::set<std::string> types = molecule->partialChargeTypes();
230 if (types.find(type) != types.end()) {
231 MatrixX charges = molecule->partialCharges(type);
232 charge = charges(atom, 0);
233 } else {
234 MatrixX charges =
235 Calc::ChargeManager::instance().partialCharges(type, *molecule);
236 charge = charges(atom, 0);
237 }
238
239 return QString("%L1").arg(charge, 0, 'f', 3);
240 }
241
242 // Qt calls this for multiple "roles" across row / columns in the index
243 // we also combine multiple types into this class, so lots of special cases
244 QVariant PropertyModel::data(const QModelIndex& index, int role) const
245 {
246 if (!index.isValid())
247 return QVariant();
248
249 int row = index.row();
250 int col = index.column();
251
252 // Simple lambda to convert QFlags to variant as in Qt 6 this needs help.
253 auto toVariant = [&](auto flags) {
254 return static_cast<Qt::Alignment::Int>(flags);
255 };
256
257 // handle text alignments
258 if (role == Qt::TextAlignmentRole) {
259 if (m_type == ConformerType) {
260 return toVariant(Qt::AlignRight | Qt::AlignVCenter); // energies
261 } else if (m_type == AtomType) {
262 if (index.column() == AtomDataColor)
263 return toVariant(Qt::AlignRight | Qt::AlignVCenter);
264 else
265 return toVariant(Qt::AlignHCenter | Qt::AlignVCenter);
266 } else if (m_type == BondType) {
267 if (index.column() == BondDataLength)
268 return toVariant(Qt::AlignRight | Qt::AlignVCenter); // bond length
269 else
270 return toVariant(Qt::AlignHCenter | Qt::AlignVCenter);
271 } else if (m_type == AngleType) {
272 if (index.column() == AngleDataValue)
273 return toVariant(Qt::AlignRight | Qt::AlignVCenter); // angle
274 else
275 return toVariant(Qt::AlignHCenter | Qt::AlignVCenter);
276 } else if (m_type == TorsionType) {
277 if (index.column() == TorsionDataValue)
278 return toVariant(Qt::AlignRight | Qt::AlignVCenter); // dihedral angle
279 else
280 return toVariant(Qt::AlignHCenter | Qt::AlignVCenter);
281 } else if (m_type == ResidueType) {
282 return toVariant(Qt::AlignHCenter | Qt::AlignVCenter);
283 } else if (m_type == ConformerType) {
284 return toVariant(Qt::AlignRight |
285 Qt::AlignVCenter); // RMSD or other properties
286 }
287 }
288
289 if (role == Qt::DecorationRole) {
290 // color for atom and residue
291 if (m_type == AtomType && col == AtomDataColor &&
292 row < static_cast<int>(m_molecule->atomCount())) {
293
294 auto c = m_molecule->color(row);
295 QColor color(c[0], c[1], c[2]);
296 return color;
297 } else if (m_type == ResidueType && col == ResidueDataColor &&
298 row < static_cast<int>(m_molecule->residueCount())) {
299
300 auto c = m_molecule->residue(row).color();
301 QColor color(c[0], c[1], c[2]);
302 return color;
303 }
304 }
305
306 if (role == Qt::ToolTipRole && isColorIndex(index))
307 return tr("Click to change color");
308
309 if (role != Qt::UserRole && role != Qt::DisplayRole && role != Qt::EditRole)
310 return QVariant();
311
312 if (m_type == AtomType) {
313 auto column = static_cast<AtomColumn>(index.column());
314
315 if (row >= static_cast<int>(m_molecule->atomCount()) ||
316 column > AtomColumns) {
317 return QVariant(); // invalid index
318 }
319
320 QString format("%L1");
321
322 // Return Data
323 switch (column) {
324 case AtomDataElement:
325 return Core::Elements::symbol(m_molecule->atomicNumber(row));
326 case AtomDataValence:
327 return QVariant::fromValue(m_molecule->bonds(row).size());
328 case AtomDataFormalCharge:
329 return m_molecule->formalCharge(row);
330 case AtomDataPartialCharge:
331 return partialCharge(m_molecule, row, m_chargeType);
332 case AtomDataX:
333 if (role == Qt::UserRole)
334 // Return the x coordinate as a double for sorting
335 return m_molecule->atomPosition3d(row).x();
336 else // format fixed to 4 decimals
337 {
338 auto formatted =
339 QString("%L1").arg(m_molecule->atomPosition3d(row).x(), 0, 'f', 4);
340 if (m_molecule->frozenAtom(row) || m_molecule->frozenAtomAxis(row, 0))
341 formatted += "🔒";
342 return formatted;
343 }
344
345 case AtomDataY:
346 if (role == Qt::UserRole)
347 // Return the y coordinate as a double for sorting
348 return m_molecule->atomPosition3d(row).y();
349 else // format fixed to 4 decimals
350 {
351 auto formatted =
352 QString("%L1").arg(m_molecule->atomPosition3d(row).y(), 0, 'f', 4);
353 if (m_molecule->frozenAtom(row) || m_molecule->frozenAtomAxis(row, 1))
354 formatted += "🔒";
355 return formatted;
356 }
357 case AtomDataZ:
358 if (role == Qt::UserRole)
359 // Return the z coordinate as a double for sorting
360 return m_molecule->atomPosition3d(row).z();
361 else // format fixed to 4 decimals
362 {
363 auto formatted =
364 QString("%L1").arg(m_molecule->atomPosition3d(row).z(), 0, 'f', 4);
365 if (m_molecule->frozenAtom(row) || m_molecule->frozenAtomAxis(row, 2))
366 formatted += "🔒";
367 return formatted;
368 }
369 case AtomDataLabel:
370 return m_molecule->atomLabel(row).c_str();
371 case AtomDataIsotope: {
372 int isotope = m_molecule->isotope(row);
373 if (isotope > 0)
374 return isotope;
375 else
376 return QVariant();
377 }
378 case AtomDataColor:
379 default:
380 return QVariant(); // nothing to show
381 }
382
383 } else if (m_type == BondType) {
384
385 auto column = static_cast<BondColumn>(index.column());
386
387 if (row >= static_cast<int>(m_molecule->bondCount()) ||
388 column > BondColumns) {
389 return QVariant(); // invalid index
390 }
391
392 auto bond = m_molecule->bond(row);
393 auto atom1 = bond.atom1();
394 auto atom2 = bond.atom2();
395 bool isConstrained = false;
396
397 // check constraints for this bond
398 for (auto& constraint : m_molecule->constraints()) {
399 if (constraint.aIndex() == atom1.index() &&
400 constraint.bIndex() == atom2.index()) {
401 isConstrained = true;
402 break;
403 }
404 }
405
406 switch (column) {
407 case BondDataType:
408 return QString("%1-%2")
409 .arg(Core::Elements::symbol(atom1.atomicNumber()))
410 .arg(Core::Elements::symbol(atom2.atomicNumber()));
411 case BondDataAtom1:
412 return QVariant::fromValue(atom1.index() + 1);
413 case BondDataAtom2:
414 return QVariant::fromValue(atom2.index() + 1);
415 case BondDataOrder:
416 return bond.order();
417 case BondDataLabel:
418 return m_molecule->bondLabel(row).c_str();
419 default: // length, rounded to 4 decimals
420 if (role == Qt::UserRole)
421 // Return the bond length as a double for sorting
422 return distance(atom1.position3d(), atom2.position3d());
423 else {
424 QString formatted = QString("%L1").arg(
425 distance(atom1.position3d(), atom2.position3d()), 0, 'f', 3);
426 if (isConstrained)
427 formatted += "🔒";
428 return formatted;
429 }
430 }
431 } else if (m_type == ResidueType) {
432
433 auto column = static_cast<ResidueColumn>(index.column());
434
435 if (row >= static_cast<int>(m_molecule->residueCount()) ||
436 column > ResidueColumns) {
437 return QVariant(); // invalid index
438 }
439
440 auto residue = m_molecule->residue(row);
441 // name, number, chain, secondary structure
442 // color is handled above
443 switch (column) {
444 case ResidueDataName:
445 return residue.residueName().c_str();
446 case ResidueDataID:
447 return QVariant::fromValue(residue.residueId());
448 case ResidueDataChain:
449 return QString(residue.chainId());
450 case ResidueDataSecStructure:
451 return secStructure(residue.secondaryStructure());
452 case ResidueDataLabel:
453 return m_molecule->residueLabel(row).c_str();
454 case ResidueDataHeterogen:
455 return QString(residue.isHeterogen() ? "X" : "");
456 default:
457 return QVariant();
458 }
459 } else if (m_type == AngleType) {
460
461 auto column = static_cast<AngleColumn>(index.column());
462 if (row > static_cast<int>(m_angles.size()) || column > AngleColumns)
463 return QVariant(); // invalid index
464
465 auto angle = m_angles[row];
466 auto atomNumber1 = m_molecule->atomicNumber(std::get<0>(angle));
467 auto atomNumber2 = m_molecule->atomicNumber(std::get<1>(angle));
468 auto atomNumber3 = m_molecule->atomicNumber(std::get<2>(angle));
469
470 Vector3 a1 = m_molecule->atomPosition3d(std::get<0>(angle));
471 Vector3 a2 = m_molecule->atomPosition3d(std::get<1>(angle));
472 Vector3 a3 = m_molecule->atomPosition3d(std::get<2>(angle));
473
474 bool isConstrained = false;
475
476 // check constraints for this angle
477 for (auto& constraint : m_molecule->constraints()) {
478 if (constraint.aIndex() == std::get<0>(angle) &&
479 constraint.bIndex() == std::get<1>(angle) &&
480 constraint.cIndex() == std::get<2>(angle)) {
481 isConstrained = true;
482 break;
483 }
484 }
485
486 switch (column) {
487 case AngleDataType:
488 return angleTypeString(atomNumber1, atomNumber2, atomNumber3);
489 case AngleDataAtom1:
490 return QVariant::fromValue(std::get<0>(angle) + 1);
491 case AngleDataAtom2:
492 return QVariant::fromValue(std::get<1>(angle) + 1);
493 case AngleDataAtom3:
494 return QVariant::fromValue(std::get<2>(angle) + 1);
495 case AngleDataValue:
496 if (role == Qt::UserRole)
497 // Return the angle as a double for sorting
498 return calculateAngle(a1, a2, a3);
499 else { // format fixed to 3 decimals
500 QString formatted =
501 QString("%L1").arg(calculateAngle(a1, a2, a3), 0, 'f', 3);
502 if (isConstrained)
503 formatted += "🔒";
504 return formatted;
505 }
506 default:
507 return QVariant();
508 }
509
510 } else if (m_type == TorsionType) {
511
512 auto column = static_cast<TorsionColumn>(index.column());
513 if (row > static_cast<int>(m_torsions.size()) || column > TorsionColumns)
514 return QVariant(); // invalid index
515
516 auto torsion = m_torsions[row];
517 auto atomNumber1 = m_molecule->atomicNumber(std::get<0>(torsion));
518 auto atomNumber2 = m_molecule->atomicNumber(std::get<1>(torsion));
519 auto atomNumber3 = m_molecule->atomicNumber(std::get<2>(torsion));
520 auto atomNumber4 = m_molecule->atomicNumber(std::get<3>(torsion));
521
522 Vector3 a1 = m_molecule->atomPosition3d(std::get<0>(torsion));
523 Vector3 a2 = m_molecule->atomPosition3d(std::get<1>(torsion));
524 Vector3 a3 = m_molecule->atomPosition3d(std::get<2>(torsion));
525 Vector3 a4 = m_molecule->atomPosition3d(std::get<3>(torsion));
526
527 bool isConstrained = false;
528
529 // check constraints for this torsion
530 for (auto& constraint : m_molecule->constraints()) {
531 if (constraint.aIndex() == std::get<0>(torsion) &&
532 constraint.bIndex() == std::get<1>(torsion) &&
533 constraint.cIndex() == std::get<2>(torsion) &&
534 constraint.dIndex() == std::get<3>(torsion)) {
535 isConstrained = true;
536 break;
537 }
538 }
539
540 switch (column) {
541 case TorsionDataType:
542 return torsionTypeString(atomNumber1, atomNumber2, atomNumber3,
543 atomNumber4);
544
545 case TorsionDataAtom1:
546 return QVariant::fromValue(std::get<0>(torsion) + 1);
547 case TorsionDataAtom2:
548 return QVariant::fromValue(std::get<1>(torsion) + 1);
549 case TorsionDataAtom3:
550 return QVariant::fromValue(std::get<2>(torsion) + 1);
551 case TorsionDataAtom4:
552 return QVariant::fromValue(std::get<3>(torsion) + 1);
553 case TorsionDataValue:
554 if (role == Qt::UserRole)
555 // Return the dihedral angle as a double for sorting
556 return calculateDihedral(a1, a2, a3, a4);
557 else { // format fixed to 3 decimals
558 QString format =
559 QString("%L1").arg(calculateDihedral(a1, a2, a3, a4), 0, 'f', 3);
560 if (isConstrained)
561 format += "🔒";
562 return format;
563 }
564 default:
565 return QVariant();
566 }
567 } else if (m_type == ConformerType) {
568 auto column = static_cast<ConformerColumn>(index.column());
569 if (row >= static_cast<int>(m_molecule->coordinate3dCount()) ||
570 column > ConformerColumns) {
571 return QVariant(); // invalid index
572 }
573
574 switch (column) {
575 case ConformerDataRMSD: { // rmsd
576 double rmsd = 0.0;
577 if (row > 0) {
578 rmsd = calculateRMSD(m_molecule->coordinate3d(row),
579 m_molecule->coordinate3d(0));
580 }
581 if (role == Qt::UserRole)
582 // Return the RMSD as a double for sorting
583 return rmsd;
584 else // format fixed to 3 decimals
585 return QString("%L1 Å").arg(rmsd, 0, 'f', 3);
586 }
587 case ConformerDataEnergy: {
588 double energy = 0.0;
589 if (m_molecule->hasData("energies")) {
590 std::vector<double> energies = m_molecule->data("energies").toList();
591 // calculate the minimum
592 double minEnergy = std::numeric_limits<double>::max();
593 for (double e : energies) {
594 minEnergy = std::min(minEnergy, e);
595 }
596 if (row < static_cast<int>(energies.size()))
597 energy = energies[row] - minEnergy;
598 }
599 if (role == Qt::UserRole)
600 // Return the energy as a double for sorting
601 return energy;
602 else // format fixed to 4 decimals
603 return QString("%L1").arg(energy, 0, 'f', 4);
604 }
605 }
606 }
607
608 return QVariant();
609 }
610
611 QVariant PropertyModel::headerData(int section, Qt::Orientation orientation,
612 int role) const
613 {
614 // handle text alignments
615 if (role == Qt::TextAlignmentRole) {
616 if (orientation == Qt::Vertical) {
617 return Qt::AlignHCenter; // XYZ coordinates
618 }
619 }
620
621 if (role != Qt::DisplayRole)
622 return QVariant();
623
624 if (m_type == AtomType) {
625 if (orientation == Qt::Horizontal) {
626
627 unsigned int column = static_cast<AtomColumn>(section);
628 switch (column) {
629 case AtomDataElement:
630 return tr("Element");
631 case AtomDataValence:
632 return tr("Valence");
633 case AtomDataFormalCharge:
634 return tr("Formal Charge");
635 case AtomDataPartialCharge: {
636 QString charge =
637 tr("%1 Partial Charge", "e.g. MMFF94 Partial Charge or "
638 "Gasteiger Partial Charge");
639 QString type = m_chargeType.isEmpty() ? partialChargeType(m_molecule)
640 : m_chargeType;
641 return charge.arg(formatChargeType(type));
642 }
643 case AtomDataX:
644 return tr("X (Å)");
645 case AtomDataY:
646 return tr("Y (Å)");
647 case AtomDataZ:
648 return tr("Z (Å)");
649 case AtomDataLabel:
650 return tr("Label");
651 case AtomDataIsotope:
652 return tr("Isotope");
653 case AtomDataColor:
654 return tr("Color");
655 }
656 } else
657 return tr("Atom") + QString(" %1").arg(section + 1);
658
659 } else if (m_type == BondType) {
660 if (orientation == Qt::Horizontal) {
661 unsigned int column = static_cast<BondColumn>(section);
662 switch (column) {
663 case BondDataType:
664 return tr("Type");
665 case BondDataAtom1:
666 return tr("Start Atom");
667 case BondDataAtom2:
668 return tr("End Atom");
669 case BondDataOrder:
670 return tr("Bond Order");
671 case BondDataLabel:
672 return tr("Label");
673 default: // A bond length
674 return tr("Length (Å)", "in Angstrom");
675 }
676 } else
677 // Bond ordering starts at 0
678 return tr("Bond") + QString(" %1").arg(section + 1);
679 } else if (m_type == ResidueType) {
680
681 if (orientation == Qt::Horizontal) {
682 unsigned int column = static_cast<ResidueColumn>(section);
683 switch (column) {
684 case ResidueDataName:
685 return tr("Name");
686 case ResidueDataID:
687 return tr("ID");
688 case ResidueDataChain:
689 return tr("Chain");
690 case ResidueDataSecStructure:
691 return tr("Secondary Structure");
692 case ResidueDataHeterogen:
693 return tr("Heterogen");
694 case ResidueDataLabel:
695 return tr("Label");
696 case ResidueDataColor:
697 return tr("Color");
698 }
699 } else // row headers
700 return QString("%L1").arg(section + 1);
701 } else if (m_type == AngleType) {
702
703 if (orientation == Qt::Horizontal) {
704 unsigned int column = static_cast<AngleColumn>(section);
705 switch (column) {
706 case AngleDataType:
707 return tr("Type");
708 case AngleDataAtom1:
709 return tr("Atom 1");
710 case AngleDataAtom2:
711 return tr("Vertex");
712 case AngleDataAtom3:
713 return tr("Atom 3");
714 case AngleDataValue:
715 return tr("Angle (°)");
716 }
717 } else // row headers
718 return QString("%L1").arg(section + 1);
719 } else if (m_type == TorsionType) {
720 if (orientation == Qt::Horizontal) {
721 unsigned int column = static_cast<TorsionColumn>(section);
722 switch (column) {
723 case TorsionDataType:
724 return tr("Type");
725 case TorsionDataAtom1:
726 return tr("Atom 1");
727 case TorsionDataAtom2:
728 return tr("Atom 2");
729 case TorsionDataAtom3:
730 return tr("Atom 3");
731 case TorsionDataAtom4:
732 return tr("Atom 4");
733 case TorsionDataValue:
734 return tr("Angle (°)");
735 }
736 } else // row headers
737 return QString("%L1").arg(section + 1);
738 } else if (m_type == ConformerType) {
739 // check if we have energies
740 bool hasEnergies = (m_molecule->hasData("energies"));
741 if (orientation == Qt::Horizontal) {
742 unsigned int column = static_cast<ConformerColumn>(section);
743 switch (column) {
744 case ConformerDataRMSD:
745 return tr("RMSD (Å)", "root mean squared displacement in Angstrom");
746 case ConformerDataEnergy:
747 // should only hit this if we have energies anyway
748 return hasEnergies ? tr("Energy (kcal/mol)") : tr("Property");
749 }
750 } else // row headers
751 return QString("%L1").arg(section + 1);
752 }
753
754 return QVariant();
755 }
756
757 Qt::ItemFlags PropertyModel::flags(const QModelIndex& index) const
758 {
759 if (!index.isValid())
760 return Qt::ItemIsEnabled;
761
762 // return QAbstractItemModel::flags(index) | Qt::ItemIsEditable
763 // for the types and columns that can be edited
764 auto editable = Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;
765 if (m_type == AtomType) {
766 if (index.column() == AtomDataElement ||
767 index.column() == AtomDataFormalCharge || index.column() == AtomDataX ||
768 index.column() == AtomDataY || index.column() == AtomDataZ ||
769 index.column() == AtomDataLabel || index.column() == AtomDataIsotope ||
770 index.column() == AtomDataColor)
771 return editable;
772 } else if (m_type == BondType) {
773 if (index.column() == BondDataOrder || index.column() == BondDataLength ||
774 index.column() == BondDataLabel)
775 return editable;
776 } else if (m_type == ResidueType) {
777 if (index.column() == ResidueDataLabel ||
778 index.column() == ResidueDataColor)
779 return editable;
780 } else if (m_type == AngleType) {
781 if (index.column() == AngleDataValue)
782 return editable;
783 } else if (m_type == TorsionType) {
784 if (index.column() == TorsionDataValue)
785 return editable;
786 }
787
788 return QAbstractItemModel::flags(index);
789 }
790
791 bool PropertyModel::setData(const QModelIndex& index, const QVariant& value,
792 int role)
793 {
794 if (!index.isValid())
795 return false;
796
797 if (role != Qt::EditRole)
798 return false;
799
800 // If an item is actually editable, we should invalidate the cache
801 // We can still use the cached data -- we just invalidate now
802 // So that we can call "return" and have the cache invalid when we leave
803 m_validCache = false;
804 auto* undoMolecule = m_molecule->undoMolecule();
805
806 if (m_type == AtomType) {
807 Vector3 v = m_molecule->atomPosition3d(index.row());
808
809 switch (static_cast<AtomColumn>(index.column())) {
810 case AtomDataFormalCharge: {
811 bool ok;
812 int charge = value.toInt(&ok);
813 if (ok) {
814 undoMolecule->setFormalCharge(index.row(), charge);
815 }
816 break;
817 }
818 case AtomDataElement: { // atomic number
819 // Try first as a number
820 bool ok;
821 int atomicNumber = value.toInt(&ok);
822 if (ok)
823 undoMolecule->setAtomicNumber(index.row(), atomicNumber);
824 else {
825 // try a symbol
826 atomicNumber = Core::Elements::atomicNumberFromSymbol(
827 value.toString().toStdString());
828
829 if (atomicNumber != Avogadro::InvalidElement) {
830 undoMolecule->setAtomicNumber(index.row(), atomicNumber);
831 } else
832 return false;
833 } // not a number
834 break;
835 }
836 case AtomDataX: {
837 bool ok;
838 double x = value.toDouble(&ok);
839 if (ok) {
840 v[0] = x;
841 }
842 break;
843 }
844 case AtomDataY: {
845 bool ok;
846 double y = value.toDouble(&ok);
847 if (ok) {
848 v[1] = y;
849 }
850 break;
851 }
852 case AtomDataZ: {
853 bool ok;
854 double z = value.toDouble(&ok);
855 if (ok) {
856 v[2] = z;
857 }
858 break;
859 }
860 case AtomDataLabel:
861 undoMolecule->setAtomLabel(index.row(), value.toString().toStdString());
862 break;
863 case AtomDataIsotope: {
864 bool ok;
865 int isotope = value.toInt(&ok);
866 if (ok) {
867 m_molecule->setIsotope(index.row(), isotope);
868 }
869 break;
870 }
871 case AtomDataColor: {
872 // get the current color for the dialog
873 Vector3ub currentColor = m_molecule->color(index.row());
874 QColor currentQColor(currentColor[0], currentColor[1], currentColor[2]);
875 QColor newQColor = QColorDialog::getColor(currentQColor, nullptr,
876 "Select Color for Atom");
877 if (newQColor.isValid()) {
878 Vector3ub newColor;
879 newColor[0] = static_cast<unsigned char>(newQColor.red());
880 newColor[1] = static_cast<unsigned char>(newQColor.green());
881 newColor[2] = static_cast<unsigned char>(newQColor.blue());
882 undoMolecule->setColor(index.row(), newColor);
883 }
884 break;
885 }
886 default:
887 return false;
888 }
889 undoMolecule->setAtomPosition3d(index.row(), v);
890
891 // cleanup atom changes
892 emit dataChanged(index, index);
893 m_molecule->emitChanged(Molecule::Atoms);
894 return true;
895 } else if (m_type == BondType) {
896 switch (static_cast<BondColumn>(index.column())) {
897 case BondDataOrder: {
898 bool ok;
899 int order = value.toInt(&ok);
900 if (ok && order > 0 && order <= 6) {
901 undoMolecule->setBondOrder(index.row(), value.toInt());
902 }
903 break;
904 }
905 case BondDataLength: {
906 bool ok;
907 double length = value.toDouble(&ok);
908 if (ok) {
909 setBondLength(index.row(), value.toDouble());
910 }
911 break;
912 }
913 case BondDataLabel:
914 undoMolecule->setBondLabel(index.row(), value.toString().toStdString());
915 break;
916 default:
917 return false;
918 }
919
920 emit dataChanged(index, index);
921 m_molecule->emitChanged(Molecule::Bonds);
922 return true;
923 } else if (m_type == ResidueType) {
924 if (index.column() == ResidueDataLabel) {
925 m_molecule->setResidueLabel(index.row(), value.toString().toStdString());
926 emit dataChanged(index, index);
927 m_molecule->emitChanged(Molecule::Residues);
928 return true;
929 } else if (index.column() == ResidueDataColor) {
930 // get the current color for the dialog
931 Vector3ub currentColor = m_molecule->residue(index.row()).color();
932 QColor currentQColor(currentColor[0], currentColor[1], currentColor[2]);
933 QColor newQColor = QColorDialog::getColor(currentQColor, nullptr,
934 "Select Color for Residue");
935 if (newQColor.isValid()) {
936 Vector3ub newColor;
937 newColor[0] = static_cast<unsigned char>(newQColor.red());
938 newColor[1] = static_cast<unsigned char>(newQColor.green());
939 newColor[2] = static_cast<unsigned char>(newQColor.blue());
940 undoMolecule->setResidueColor(index.row(), newColor);
941 emit dataChanged(index, index);
942 m_molecule->emitChanged(Molecule::Residues);
943 return true;
944 }
945 } // end editing residues
946 } else if (m_type == AngleType) {
947 if (index.column() == AngleDataValue) {
948 bool ok;
949 double angle = value.toDouble(&ok);
950 if (!ok)
951 return false;
952 setAngle(index.row(), angle);
953 emit dataChanged(index, index);
954 m_molecule->emitChanged(Molecule::Atoms);
955 return true;
956 }
957 } else if (m_type == TorsionType) {
958 if (index.column() == TorsionDataValue) {
959 bool ok;
960 double angle = value.toDouble(&ok);
961 if (!ok)
962 return false;
963 setTorsion(index.row(), angle);
964 emit dataChanged(index, index);
965 m_molecule->emitChanged(Molecule::Atoms);
966 return true;
967 }
968 }
969
970 return false;
971 }
972
973 bool PropertyModel::isColorIndex(const QModelIndex& index) const
974 {
975 if (!index.isValid())
976 return false;
977
978 if (m_type == AtomType)
979 return index.column() == AtomDataColor;
980 if (m_type == ResidueType)
981 return index.column() == ResidueDataColor;
982
983 return false;
984 }
985
986 void PropertyModel::buildFragment(const QtGui::RWBond& bond,
987 const QtGui::RWAtom& startAtom)
988 {
989 m_fragment.clear();
990 if (!fragmentRecurse(bond, startAtom, startAtom)) {
991 // If this returns false, then a cycle has been found. Only move startAtom
992 // in this case.
993 m_fragment.clear();
994 }
995 m_fragment.push_back(m_molecule->undoMolecule()->atomUniqueId(startAtom));
996 }
997
998 bool PropertyModel::fragmentRecurse(const QtGui::RWBond& bond,
999 const QtGui::RWAtom& startAtom,
1000 const QtGui::RWAtom& currentAtom)
1001 {
1002 // does our cycle include both bonded atoms?
1003 const RWAtom bondedAtom(bond.getOtherAtom(startAtom));
1004 auto* undoMolecule = m_molecule->undoMolecule();
1005
1006 Core::Array<RWBond> bonds = undoMolecule->bonds(currentAtom);
1007
1008 for (auto& it : bonds) {
1009 if (it != bond) { // Skip the current bond
1010 const RWAtom nextAtom = it.getOtherAtom(currentAtom);
1011 if (nextAtom != startAtom && nextAtom != bondedAtom) {
1012 // Skip atoms that have already been added. This prevents infinite
1013 // recursion on cycles in the fragments
1014 int uid = undoMolecule->atomUniqueId(nextAtom);
1015 if (!fragmentHasAtom(uid)) {
1016 m_fragment.push_back(uid);
1017 if (!fragmentRecurse(it, startAtom, nextAtom))
1018 return false;
1019 }
1020 } else if (nextAtom == bondedAtom) {
1021 // If we've found the bonded atom, the bond is in a cycle
1022 return false;
1023 }
1024 } // *it != bond
1025 } // foreach bond
1026 return true;
1027 }
1028
1029 inline bool PropertyModel::fragmentHasAtom(int uid) const
1030 {
1031 return std::find(m_fragment.begin(), m_fragment.end(), uid) !=
1032 m_fragment.end();
1033 }
1034
1035 void PropertyModel::transformFragment() const
1036 {
1037 auto* undoMolecule = m_molecule->undoMolecule();
1038 undoMolecule->beginMergeMode(tr("Adjust Fragment"));
1039 for (int it : m_fragment) {
1040 RWAtom atom = m_molecule->undoMolecule()->atomByUniqueId(it);
1041 if (atom.isValid()) {
1042 Vector3 pos = atom.position3d();
1043 pos = m_transform * pos;
1044 atom.setPosition3d(pos);
1045 }
1046 }
1047 undoMolecule->endMergeMode();
1048 }
1049
1050 void PropertyModel::setBondLength(unsigned int index, double length)
1051 {
1052 if (m_molecule == nullptr)
1053 return;
1054
1055 if (index >= m_molecule->bondCount())
1056 return;
1057
1058 // figure out how much to move and the vector of displacement
1059 auto bond = m_molecule->undoMolecule()->bond(index);
1060 Vector3 v1 = bond.atom1().position3d();
1061 Vector3 v2 = bond.atom2().position3d();
1062 Vector3 diff = v2 - v1;
1063 double currentLength = diff.norm();
1064 diff.normalize();
1065 Vector3 delta = diff * (length - currentLength);
1066
1067 buildFragment(bond, bond.atom2());
1068
1069 m_transform.setIdentity();
1070 m_transform.translate(delta);
1071
1072 transformFragment();
1073
1074 m_molecule->emitChanged(QtGui::Molecule::Modified | QtGui::Molecule::Atoms);
1075 }
1076
1077 void PropertyModel::setAngle(unsigned int index, double newValue)
1078 {
1079 // the index refers to the angle
1080
1081 auto angle = m_angles[index];
1082 auto atom1 = m_molecule->undoMolecule()->atom(std::get<0>(angle));
1083 auto atom2 = m_molecule->undoMolecule()->atom(std::get<1>(angle));
1084 auto atom3 = m_molecule->undoMolecule()->atom(std::get<2>(angle));
1085
1086 auto bond = m_molecule->undoMolecule()->bond(atom1, atom2);
1087 Vector3 a = atom1.position3d();
1088 Vector3 b = atom2.position3d();
1089 Vector3 c = atom3.position3d();
1090 const double currentValue = calculateAngle(a, b, c);
1091 Vector3 ab = b - a;
1092 Vector3 bc = c - b;
1093
1094 // Axis of rotation is the cross product of the vectors
1095 const Vector3 axis((ab.cross(bc)).normalized());
1096 // Angle of rotation
1097 const double change = (newValue - currentValue) * M_PI / 180.0;
1098
1099 // Build transform
1100 m_transform.setIdentity();
1101 m_transform.translate(b);
1102 m_transform.rotate(Eigen::AngleAxis(-change, axis));
1103 m_transform.translate(-b);
1104
1105 // Build the fragment if needed:
1106 if (m_fragment.empty())
1107 buildFragment(bond, atom2);
1108
1109 // Perform transformation
1110 transformFragment();
1111 }
1112
1113 void PropertyModel::setTorsion(unsigned int index, double newValue)
1114 {
1115
1116 auto torsion = m_torsions[index];
1117 auto atom1 = m_molecule->undoMolecule()->atom(std::get<0>(torsion));
1118 auto atom2 = m_molecule->undoMolecule()->atom(std::get<1>(torsion));
1119 auto atom3 = m_molecule->undoMolecule()->atom(std::get<2>(torsion));
1120 auto atom4 = m_molecule->undoMolecule()->atom(std::get<3>(torsion));
1121
1122 auto bond = m_molecule->undoMolecule()->bond(atom2, atom3);
1123 Vector3 a = atom1.position3d();
1124 Vector3 b = atom2.position3d();
1125 Vector3 c = atom3.position3d();
1126 Vector3 d = atom4.position3d();
1127 const double currentValue = calculateDihedral(a, b, c, d);
1128
1129 // Axis of rotation
1130 const Vector3 axis((c - b).normalized());
1131 // Angle of rotation
1132 const double change = (newValue - currentValue) * M_PI / 180.0;
1133
1134 // Build transform
1135 m_transform.setIdentity();
1136 m_transform.translate(c);
1137 m_transform.rotate(Eigen::AngleAxis(change, axis));
1138 m_transform.translate(-c);
1139
1140 // Build the fragment if needed:
1141 if (m_fragment.empty())
1142 buildFragment(bond, atom3);
1143
1144 // Perform transformation
1145 transformFragment();
1146 }
1147
1148 QStringList PropertyModel::availableChargeTypes() const
1149 {
1150 QStringList result;
1151 if (m_molecule == nullptr)
1152 return result;
1153
1154 // add types available from charge calculators
1155 const auto options =
1156 Calc::ChargeManager::instance().identifiersForMolecule(*m_molecule);
1157 for (const auto& model : options) {
1158 std::string t = Calc::ChargeManager::instance().nameForModel(model);
1159 QString name = QString::fromStdString(t);
1160 if (!result.contains(name))
1161 result << name;
1162 }
1163
1164 return result;
1165 }
1166
1167 void PropertyModel::setChargeType(const QString& type)
1168 {
1169 m_chargeType = type;
1170 // refresh the partial charge column and header
1171 beginResetModel();
1172 endResetModel();
1173 }
1174
1175 void PropertyModel::setMolecule(QtGui::Molecule* molecule)
1176 {
1177 if (molecule && molecule != m_molecule) {
1178 m_molecule = molecule;
1179
1180 // Initialize structure tracking for change detection
1181 m_lastAtomCount = molecule->atomCount();
1182 m_lastBondCount = molecule->bondCount();
1183
1184 updateCache();
1185
1186 connect(m_molecule, SIGNAL(changed(unsigned int)), this,
1187 SLOT(updateTable(unsigned int)));
1188 }
1189 }
1190
1191 QString PropertyModel::secStructure(unsigned int type) const
1192 {
1193 switch (type) {
1194 case SecondaryStructure::piHelix:
1195 return tr("π Helix", "pi helix");
1196 case SecondaryStructure::bend:
1197 return tr("Bend", "protein bend secondary structure");
1198 case SecondaryStructure::alphaHelix:
1199 return tr("α Helix", "alpha helix");
1200 case SecondaryStructure::betaSheet:
1201 return tr("β Sheet", "beta sheet");
1202 case SecondaryStructure::helix310:
1203 return tr("3-10 helix", "3-10 helix");
1204 case SecondaryStructure::betaBridge:
1205 return tr("β Bridge", "beta bridge");
1206 case SecondaryStructure::turn:
1207 return tr("Turn", "protein turn secondary structure");
1208 case SecondaryStructure::coil:
1209 return tr("Coil", "protein coil secondary structure");
1210 default:
1211 return QString(); // implied unknown
1212 }
1213 }
1214
1215 void PropertyModel::updateTable(unsigned int flags)
1216 {
1217 // During animation/vibration, coordinates change rapidly but the table
1218 // structure (number of atoms, bonds, etc.) remains the same. We can skip
1219 // updates when only coordinates changed (Atoms flag without Added/Removed).
1220 //
1221 // Note: Some code (e.g., vibrations) incorrectly uses Added flag for
1222 // coordinate changes. We detect actual structural changes by checking
1223 // if the counts changed.
1224 bool structureChanged = false;
1225
1226 if (m_molecule != nullptr) {
1227 // Check if the actual structure changed (not just coordinates)
1228 Index currentAtomCount = m_molecule->atomCount();
1229 Index currentBondCount = m_molecule->bondCount();
1230
1231 if (currentAtomCount != m_lastAtomCount ||
1232 currentBondCount != m_lastBondCount) {
1233 structureChanged = true;
1234 m_lastAtomCount = currentAtomCount;
1235 m_lastBondCount = currentBondCount;
1236 }
1237 }
1238
1239 if (!structureChanged) {
1240 // For coordinate-only changes, just invalidate the cache
1241 // This avoids race conditions during rapid animation updates
1242 m_validCache = false;
1243 return;
1244 }
1245
1246 // For structural changes, do a full model reset
1247 // Use beginResetModel/endResetModel to ensure thread-safe updates
1248 updateCache();
1249 beginResetModel();
1250 endResetModel();
1251 }
1252
1253 void PropertyModel::updateCache() const
1254 {
1255 m_validCache = true;
1256 m_angles.clear();
1257 m_torsions.clear();
1258
1259 if (m_molecule == nullptr)
1260 return;
1261
1262 if (m_type == AngleType) {
1263 Core::AngleIterator aIter(m_molecule);
1264 auto angle = aIter.begin();
1265 while (angle != aIter.end()) {
1266 m_angles.push_back(angle);
1267 angle = ++aIter;
1268 }
1269 } else if (m_type == TorsionType) {
1270 Core::DihedralIterator dIter(m_molecule);
1271 auto torsion = dIter.begin();
1272 while (torsion != dIter.end()) {
1273 m_torsions.push_back(torsion);
1274 torsion = ++dIter;
1275 }
1276 }
1277 }
1278
1279 Core::Angle PropertyModel::getAngle(unsigned int angle) const
1280 {
1281 if (angle >= m_angles.size())
1282 return Core::Angle();
1283
1284 return m_angles[angle];
1285 }
1286
1287 Real PropertyModel::getAngleValue(unsigned int angle) const
1288 {
1289 if (angle >= m_angles.size())
1290 return 0.0;
1291
1292 auto a = m_angles[angle];
1293 auto atom1 = m_molecule->undoMolecule()->atom(std::get<0>(a));
1294 auto atom2 = m_molecule->undoMolecule()->atom(std::get<1>(a));
1295 auto atom3 = m_molecule->undoMolecule()->atom(std::get<2>(a));
1296 Vector3 a1 = atom1.position3d();
1297 Vector3 a2 = atom2.position3d();
1298 Vector3 a3 = atom3.position3d();
1299 return calculateAngle(a1, a2, a3);
1300 }
1301
1302 Core::Dihedral PropertyModel::getTorsion(unsigned int torsion) const
1303 {
1304 if (torsion >= m_torsions.size())
1305 return Core::Dihedral();
1306
1307 return m_torsions[torsion];
1308 }
1309
1310 Real PropertyModel::getTorsionValue(unsigned int torsion) const
1311 {
1312 if (torsion >= m_torsions.size())
1313 return 0.0;
1314
1315 auto t = m_torsions[torsion];
1316 auto atom1 = m_molecule->undoMolecule()->atom(std::get<0>(t));
1317 auto atom2 = m_molecule->undoMolecule()->atom(std::get<1>(t));
1318 auto atom3 = m_molecule->undoMolecule()->atom(std::get<2>(t));
1319 auto atom4 = m_molecule->undoMolecule()->atom(std::get<3>(t));
1320 Vector3 a1 = atom1.position3d();
1321 Vector3 a2 = atom2.position3d();
1322 Vector3 a3 = atom3.position3d();
1323 Vector3 a4 = atom4.position3d();
1324 return calculateDihedral(a1, a2, a3, a4);
1325 }
1326
1327 } // end namespace Avogadro