Debian Codegraph @

avogadro/qtplugins/insertpeptide/insertpeptide.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 "insertpeptide.h"
7 #include "ui_insertpeptidedialog.h"
8
9 #include <avogadro/core/array.h>
10 #include <avogadro/core/residue.h>
11 #include <avogadro/core/secondarystructure.h>
12
13 #include <avogadro/qtgui/molecule.h>
14 #include <avogadro/qtgui/rwmolecule.h>
15 #include <avogadro/qtgui/utilities.h>
16
17 #include <QtCore/QDebug>
18 #include <QtCore/QSettings>
19 #include <QtCore/QStandardPaths>
20 #include <QtCore/QDir>
21 #include <QtCore/QFile>
22 #include <QRegularExpression>
23
24 #include <QAction>
25
26 using Avogadro::Core::Array;
27 using Avogadro::Core::InternalCoordinate;
28 using Avogadro::QtGui::Molecule;
29
30 namespace Avogadro::QtPlugins {
31
32 const std::map<char, std::string> threeLetterCodes = {
33 // map single letter codes to three letter codes
34 // e.g. https://en.wikipedia.org/wiki/Amino_acid
35 { 'A', "ALA" }, { 'R', "ARG" }, { 'N', "ASN" }, { 'D', "ASP" },
36 { 'C', "CYS" }, { 'Q', "GLN" }, { 'E', "GLU" }, { 'G', "GLY" },
37 { 'H', "HIS" }, { 'I', "ILE" }, { 'L', "LEU" }, { 'K', "LYS" },
38 { 'M', "MET" }, { 'F', "PHE" }, { 'P', "PRO" }, { 'S', "SER" },
39 { 'T', "THR" }, { 'W', "TRP" }, { 'Y', "TYR" }, { 'V', "VAL" },
40 { 'O', "PYL" }, { 'U', "SEC" }
41 };
42
43 class InsertPeptideDialog : public QDialog, public Ui::InsertPeptideDialog
44 {
45 public:
46 InsertPeptideDialog(QWidget* parent = 0) : QDialog(parent)
47 {
48 setWindowFlags(Qt::Dialog | Qt::Tool);
49 setupUi(this);
50 }
51 };
52
53 InsertPeptide::InsertPeptide(QObject* parent_)
54 : Avogadro::QtGui::ExtensionPlugin(parent_), m_dialog(nullptr)
55 {
56 auto* action = new QAction(tr("Peptide…"), this);
57 action->setProperty("menu priority", 880);
58 connect(action, SIGNAL(triggered()), SLOT(showDialog()));
59 m_actions.append(action);
60 }
61
62 InsertPeptide::~InsertPeptide() {}
63
64 QList<QAction*> InsertPeptide::actions() const
65 {
66 return m_actions;
67 }
68
69 QStringList InsertPeptide::menuPath(QAction* action) const
70 {
71 return QStringList() << tr("&Build") << tr("&Insert");
72 }
73
74 void InsertPeptide::setMolecule(QtGui::Molecule* mol)
75 {
76 m_molecule = mol;
77 }
78
79 void InsertPeptide::showDialog()
80 {
81 if (m_molecule == nullptr)
82 return;
83
84 if (m_dialog == nullptr) {
85 m_dialog = new InsertPeptideDialog(qobject_cast<QWidget*>(parent()));
86 }
87
88 QSettings settings;
89
90 m_dialog->phiSpin->setValue(settings.value("peptide/phi", 180.0).toDouble());
91 m_dialog->psiSpin->setValue(settings.value("peptide/psi", 180.0).toDouble());
92 m_dialog->structureCombo->setCurrentIndex(
93 settings.value("peptide/structure", 0).toInt());
94
95 connect(m_dialog->insertButton, SIGNAL(clicked()), this,
96 SLOT(performInsert()));
97
98 // Set the amino buttons to update the sequence
99 foreach (const QToolButton* child, m_dialog->findChildren<QToolButton*>()) {
100 connect(child, SIGNAL(clicked()), this, SLOT(updateText()));
101 }
102
103 // connect the structure menu to set the phi / psi
104 connect(m_dialog->structureCombo, SIGNAL(currentIndexChanged(int)), this,
105 SLOT(setStructureType(int)));
106
107 m_dialog->show();
108 m_dialog->raise();
109 m_dialog->activateWindow();
110
111 // deduce the directory for the fragments
112 QString directory = "fragments/amino";
113 QStringList dirs;
114 QStringList stdPaths =
115 QStandardPaths::standardLocations(QStandardPaths::AppLocalDataLocation);
116 foreach (const QString& dirStr, stdPaths) {
117 QString path = dirStr + "/data";
118 dirs << path; // we'll check if these exist below
119 }
120
121 // add in paths relative to the binary (e.g. for development)
122 dirs << QCoreApplication::applicationDirPath() + "/../" +
123 QtGui::Utilities::dataDirectory() + "/avogadro2";
124
125 #ifdef Q_WS_X11
126 dirs << QString(INSTALL_PREFIX) + "/share/avogadro2/";
127 #else
128 // Mac and Windows use relative path from application location
129 dirs << QCoreApplication::applicationDirPath() + "/../share/avogadro2";
130 #endif
131
132 QDir dir;
133
134 foreach (const QString& dirStr, dirs) {
135 qDebug() << "Checking for " << directory << " data in" << dirStr;
136 QDir testdir(dirStr + '/' + directory);
137 if (testdir.exists() && testdir.isReadable()) {
138 m_directory = testdir.absolutePath();
139 break;
140 }
141 }
142 }
143
144 void InsertPeptide::setStructureType(int index)
145 {
146 if (m_dialog == nullptr)
147 return;
148
149 switch (index) {
150 case 0: // straight chain
151 m_dialog->phiSpin->setValue(180.0);
152 m_dialog->psiSpin->setValue(180.0);
153 break;
154 case 1: // alpha helix
155 m_dialog->phiSpin->setValue(-60.0);
156 m_dialog->psiSpin->setValue(-40.0);
157 break;
158 case 2: // beta sheet
159 m_dialog->phiSpin->setValue(-135.0);
160 m_dialog->psiSpin->setValue(135.0);
161 break;
162 case 3: // 3-10 helix
163 m_dialog->phiSpin->setValue(-74.0);
164 m_dialog->psiSpin->setValue(-4.0);
165 break;
166 case 4: // pi helix
167 m_dialog->phiSpin->setValue(-57.0);
168 m_dialog->psiSpin->setValue(-70.0);
169 break;
170 case 5: // other
171 default:
172 break;
173 }
174
175 QSettings settings;
176 settings.setValue("peptide/phi", m_dialog->phiSpin->value());
177 settings.setValue("peptide/psi", m_dialog->psiSpin->value());
178 settings.setValue("peptide/structure", index);
179 }
180
181 void InsertPeptide::updateText()
182 {
183 QToolButton* button = qobject_cast<QToolButton*>(sender());
184 if (button) {
185 QString sequenceText = m_dialog->sequenceText->toPlainText();
186 sequenceText += '-' + button->text();
187 // remove any final or initial dash
188 if (sequenceText.endsWith('-'))
189 sequenceText.chop(1);
190 if (sequenceText.startsWith('-'))
191 sequenceText.remove(0, 1);
192
193 m_dialog->sequenceText->setPlainText(sequenceText);
194 }
195 }
196
197 AminoAcid InsertPeptide::readAminoAcid(const QString& threeLetterCode)
198 {
199 AminoAcid aa;
200
201 // Construct the filename (e.g., "ALA.zmat")
202 QString filename =
203 QString(m_directory + "/%1.zmat").arg(threeLetterCode.toUpper());
204
205 // Try opening the file
206 QFile file(filename);
207 if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
208 qDebug() << "Failed to open amino acid file:" << filename;
209 return aa;
210 }
211
212 QTextStream in(&file);
213
214 while (!in.atEnd()) {
215 QString line = in.readLine().trimmed();
216
217 // Skip empty lines
218 if (line.isEmpty())
219 continue;
220
221 // Parse the line
222 QStringList parts =
223 line.split(QRegularExpression("\\s+"), Qt::SkipEmptyParts);
224
225 // Need at least: Element AtomName Distance Angle Dihedral RefAtom1 RefAtom2
226 // RefAtom3
227 if (parts.size() < 8)
228 continue;
229
230 QString element = parts[0];
231 QString atomName = parts[1];
232 double distance = parts[2].toDouble();
233 double angle = parts[3].toDouble();
234 double dihedral = parts[4].toDouble();
235 int refAtom1 = parts[5].toInt();
236 int refAtom2 = parts[6].toInt();
237 int refAtom3 = parts[7].toInt();
238
239 // Get atomic number from element symbol
240 unsigned char atomicNum =
241 Avogadro::Core::Elements::atomicNumberFromSymbol(element.toStdString());
242 aa.atomicNumbers.push_back(atomicNum);
243 aa.atomNames.push_back(atomName.toStdString());
244
245 // Create internal coordinate
246 Avogadro::Core::InternalCoordinate coord;
247
248 // Convert 1-based indices to 0-based (but keep special cases)
249 // 0 means no reference, keep as is
250 coord.a = (refAtom1 > 0) ? refAtom1 - 1 : MaxIndex;
251 coord.b = (refAtom2 > 0) ? refAtom2 - 1 : MaxIndex;
252 coord.c = (refAtom3 > 0) ? refAtom3 - 1 : MaxIndex;
253
254 coord.length = distance;
255 // Keep in degrees as used in InternalCoordinate
256 coord.angle = angle;
257 coord.dihedral = dihedral;
258
259 aa.internalCoords.push_back(coord);
260 }
261
262 file.close();
263
264 #ifndef NDEBUG
265 qDebug() << "Read" << aa.atomicNumbers.size() << "atoms for"
266 << threeLetterCode;
267 #endif
268
269 return aa;
270 }
271
272 void AddTerminus(unsigned char element, QString atomID, Index a,
273 double distance, Index b, double angle, Index c,
274 double dihedral, Molecule& molecule,
275 Array<InternalCoordinate>& coords)
276 {
277 if (molecule.residueCount() == 0)
278 return; // can't do anything -- we're in a weird state
279
280 auto residue = molecule.residue(molecule.residueCount() - 1);
281
282 auto atom = molecule.addAtom(element);
283 residue.addResidueAtom(atomID.toStdString(), atom);
284
285 InternalCoordinate coord;
286 coord.a = a;
287 coord.b = b;
288 coord.c = c;
289 coord.length = distance;
290 coord.angle = angle;
291 coord.dihedral = dihedral;
292 coords.push_back(coord);
293
294 // Add a bond between the recently created atom and our "a"
295 molecule.addBond(molecule.atomCount() - 1, a, 1);
296 }
297
298 void InsertPeptide::performInsert()
299 {
300 if (m_molecule == nullptr || m_dialog == nullptr)
301 return;
302
303 // get the sequence
304 QString sequenceText = m_dialog->sequenceText->toPlainText();
305 if (sequenceText.isEmpty())
306 return;
307
308 // figure out if the sequence has three-letter codes
309 // separated by dashes
310 QStringList sequenceList;
311 sequenceList = sequenceText.split('-');
312
313 // Check if we have single letter codes (no dashes, short strings)
314 if (sequenceList.size() == 1 && sequenceList[0].length() > 3) {
315 // Might be single letter codes like "ACDEFG"
316 QString singleLetters = sequenceList[0];
317 sequenceList.clear();
318 for (int i = 0; i < singleLetters.length(); i++) {
319 char letter = singleLetters[i].toUpper().toLatin1();
320 if (threeLetterCodes.find(letter) != threeLetterCodes.end()) {
321 sequenceList.append(
322 QString::fromStdString(threeLetterCodes.at(letter)));
323 }
324 }
325 }
326
327 QString chain = m_dialog->chainNumberCombo->currentText();
328 if (chain.isEmpty())
329 chain = 'A';
330
331 double phi = m_dialog->phiSpin->value();
332 double psi = m_dialog->psiSpin->value();
333
334 // get the N and C terminus
335 auto nTerm = m_dialog->nGroupCombo->currentIndex();
336 auto cTerm = m_dialog->cGroupCombo->currentIndex();
337
338 char stereo = m_dialog->lStereoButton->isChecked() ? 'L' : 'D';
339
340 // read the file into the new fragment
341 Avogadro::QtGui::Molecule newMol(m_molecule->parent());
342
343 // keep a map of the amino acids (i.e., only read once)
344 std::map<std::string, AminoAcid> aaMap;
345
346 // iterate through sequenceList to read the amino acids
347 Index currentResidueNumber = 0;
348 Array<Core::InternalCoordinate> internalCoords;
349 // Track atom indices across residues
350 Index totalAtomCount = 0;
351 Index previousN = MaxIndex;
352 Index previousCA = MaxIndex;
353 Index previousC = MaxIndex;
354 Index previousO = MaxIndex;
355 Index currentN = MaxIndex;
356 Index currentCA = MaxIndex;
357 Index currentC = MaxIndex;
358 Index currentO = MaxIndex;
359
360 for (int i = 0; i < sequenceList.size(); i++) {
361 QString aaString = sequenceList[i];
362 std::string aaStdString = aaString.toUpper().toStdString();
363
364 // Read amino acid if not already cached
365 if (aaMap.find(aaStdString) == aaMap.end()) {
366 aaMap[aaStdString] = readAminoAcid(aaString);
367 }
368
369 AminoAcid amino = aaMap[aaStdString];
370
371 if (amino.atomicNumbers.empty()) {
372 qDebug() << "Failed to read amino acid:" << aaString;
373 continue;
374 }
375
376 // Create residue
377 auto& residue = newMol.addResidue(aaStdString, ++currentResidueNumber,
378 chain.toLatin1()[0]);
379
380 // Add atoms from this amino acid
381 for (size_t j = 0; j < amino.atomNames.size(); j++) {
382 std::string atomName = amino.atomNames[j];
383
384 // Skip terminal atoms for middle residues
385 bool isLastResidue = (i == sequenceList.size() - 1);
386 bool isFirstResidue = (i == 0);
387
388 // Skip OXT/HXT for non-terminal residues
389 if (!isLastResidue && (atomName == "OXT" || atomName == "HXT"))
390 continue;
391 // if it's the last residue, check the terminus
392 if (isLastResidue && atomName == "HXT" && cTerm == 1) {
393 // CO2- termination
394 continue;
395 }
396
397 // Add atom to molecule
398 auto atom = newMol.addAtom(amino.atomicNumbers[j]);
399 residue.addResidueAtom(atomName, atom);
400
401 // formal charges
402 if (isLastResidue && atomName == "OXT" && cTerm == 1) {
403 atom.setFormalCharge(-1);
404 }
405 if (isFirstResidue && atomName == "N" && nTerm == 1) {
406 atom.setFormalCharge(1);
407 }
408
409 // Handle internal coordinates
410 Core::InternalCoordinate coord = amino.internalCoords[j];
411
412 // TODO : Handle stereochemistry for D- amino acids
413
414 // For residues after the first, we need to adjust references
415 if (i > 0) {
416 // Atoms need to reference previous residue atoms for the peptide bond
417 if (atomName == "N") {
418 // N connects to previous C
419 coord.a = previousC;
420 coord.b = previousCA;
421 coord.c = previousN;
422 coord.length = 1.329; // typical peptide bond length
423 coord.angle = 116.2; // typical C-N-CA angle
424 coord.dihedral = psi;
425 } else if (atomName == "CA") {
426 // CA connects to N (just added)
427 coord.a = currentN; // N we just added
428 coord.b = previousC;
429 coord.c = previousCA;
430 coord.angle = 121.7; // typical N-CA-C angle
431 coord.dihedral = 180.0; // omega
432 } else if (atomName == "C") {
433 coord.a = currentCA; // CA we just added
434 coord.b = currentN; // N we just added
435 coord.c = previousC;
436 coord.dihedral = phi;
437 } else {
438 // Other atoms: adjust their reference indices
439 // Add offset for all atoms from previous residues
440 if (coord.a != MaxIndex)
441 coord.a += totalAtomCount;
442 if (coord.b != MaxIndex)
443 coord.b += totalAtomCount;
444 if (coord.c != MaxIndex)
445 coord.c += totalAtomCount;
446 }
447
448 // adjust the N-H position
449 if (atomName == "H") {
450 coord.angle = 120.0;
451 coord.dihedral = phi + 180.0 + 5.0 * sin(psi * DEG_TO_RAD);
452 }
453 }
454 internalCoords.push_back(coord);
455
456 #ifndef NDEBUG
457 qDebug() << " added " << atomName << " " << atom.index() << " " << coord.a
458 << " " << coord.b << " " << coord.c << " " << coord.length << " "
459 << coord.angle << " " << coord.dihedral;
460 #endif
461
462 // Track key atoms for next residue
463 if (atomName == "N")
464 currentN = newMol.atomCount() - 1;
465 else if (atomName == "CA")
466 currentCA = newMol.atomCount() - 1;
467 else if (atomName == "C")
468 currentC = newMol.atomCount() - 1;
469 else if (atomName == "O")
470 currentO = newMol.atomCount() - 1;
471 }
472
473 if (i == 0) {
474 // fix the N terminus (e.g., NH2 or NH3+)
475 switch (nTerm) {
476 case 0: // NH2
477 AddTerminus(1, "H2", 0, 1.009, 1, 120.0, 2, 175.0, newMol,
478 internalCoords);
479 break;
480 case 1: // NH3+
481 AddTerminus(1, "H2", 0, 1.009, 1, 109.5, 2, 120.0, newMol,
482 internalCoords);
483 AddTerminus(1, "H3", 0, 1.009, 1, 109.5, 2, 60.0, newMol,
484 internalCoords);
485 break;
486 default:
487 break;
488 }
489 }
490
491 totalAtomCount = newMol.atomCount();
492 residue.resolveResidueBonds(newMol);
493 if (i > 0) {
494 // Add peptide bond
495 newMol.addBond(previousC, currentN);
496 // adjust the dihedral of the previous oxygen
497 internalCoords[previousO].dihedral = 180.0 + psi;
498 }
499
500 previousN = currentN;
501 previousCA = currentCA;
502 previousC = currentC;
503 previousO = currentO;
504 }
505
506 // Convert internal coordinates to Cartesian
507 Array<Vector3> positions = internalToCartesian(newMol, internalCoords);
508
509 // Set atom positions
510 for (size_t i = 0; i < positions.size(); i++) {
511 newMol.setAtomPosition3d(i, positions[i]);
512 }
513
514 // okay, make sure we have secondary structure assigned
515 Core::SecondaryStructureAssigner ssa;
516 ssa.assign(&newMol);
517
518 m_molecule->undoMolecule()->appendMolecule(newMol, tr("Insert Peptide"));
519 emit requestActiveTool("Manipulator");
520 }
521
522 } // namespace Avogadro::QtPlugins