Debian Codegraph @

avogadro/qtplugins/yaehmop/yaehmop.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 "yaehmop.h"
7
8 #include "banddialog.h"
9 #include "specialkpoints.h"
10 #include "yaehmopout.h"
11
12 #include <avogadro/core/array.h>
13 #include <avogadro/core/elements.h>
14 #include <avogadro/core/unitcell.h>
15 #include <avogadro/core/vector.h>
16 #include <avogadro/qtgui/molecule.h>
17 #include <avogadro/qtgui/chartdialog.h>
18 #include <avogadro/qtgui/chartwidget.h>
19
20 #include <QAction>
21 #include <QByteArray>
22 #include <QCoreApplication>
23 #include <QDebug>
24 #include <QDialog>
25 #include <QFile>
26 #include <QMessageBox>
27 #include <QProcess>
28 #include <QRegularExpression>
29 #include <QSettings>
30 #include <QString>
31 #include <QTextEdit>
32 #include <QVBoxLayout>
33
34 using Avogadro::Vector3;
35 using Avogadro::Vector3i;
36 using Avogadro::Core::Array;
37 using Avogadro::Core::Elements;
38 using Avogadro::Core::UnitCell;
39 using Avogadro::QtGui::Molecule;
40
41 namespace Avogadro::QtPlugins {
42
43 Yaehmop::Yaehmop(QObject* parent_)
44 : Avogadro::QtGui::ExtensionPlugin(parent_), m_actions(QList<QAction*>()),
45 m_molecule(nullptr), m_yaehmopSettings(),
46 m_bandDialog(
47 new BandDialog(qobject_cast<QWidget*>(parent()), m_yaehmopSettings)),
48 m_displayBandDialogAction(new QAction(this))
49 {
50 // first off, look for the program
51 // either as eht_bind or yaehmop
52 bool found = false;
53
54 // If the YAEHMOP_EXECUTABLE environment variable is set, then
55 // use that
56 QByteArray yaehmopExec = qgetenv("YAEHMOP_EXECUTABLE");
57 if (!yaehmopExec.isEmpty()) {
58 m_programPath = yaehmopExec;
59 } else {
60 // otherwise look in the current directory, ../bin and the PATH environment
61
62 #ifdef _WIN32
63 QStringList programs = QStringList() << "eht_bind.exe"
64 << "yaehmop.exe";
65 #else
66 QStringList programs = QStringList() << "eht_bind"
67 << "yaehmop";
68 #endif
69 QStringList paths;
70 paths << QCoreApplication::applicationDirPath()
71 << QCoreApplication::applicationDirPath() + "/../bin";
72
73 // add the PATH environment variable
74 auto environment = QProcessEnvironment::systemEnvironment().value("PATH");
75 paths << environment.split(':');
76
77 foreach (QString binary, programs) {
78 foreach (QString path, paths) {
79 if (QFile::exists(path + "/" + binary)) {
80 m_programPath = path + "/" + binary;
81 found = true;
82 break;
83 }
84 }
85 if (found)
86 break;
87 }
88 }
89
90 m_displayBandDialogAction->setText(tr("Calculate Band Structure…"));
91 m_displayBandDialogAction->setEnabled(found);
92 connect(m_displayBandDialogAction.get(), &QAction::triggered, this,
93 &Yaehmop::displayBandDialog);
94 m_actions.push_back(m_displayBandDialogAction.get());
95 m_displayBandDialogAction->setProperty("menu priority", 90);
96
97 updateActions();
98
99 readSettings();
100 }
101
102 Yaehmop::~Yaehmop() = default;
103
104 QList<QAction*> Yaehmop::actions() const
105 {
106 return m_actions;
107 }
108
109 QStringList Yaehmop::menuPath(QAction*) const
110 {
111 return QStringList() << tr("&Extensions") << tr("&Yaehmop");
112 }
113
114 void Yaehmop::setMolecule(QtGui::Molecule* mol)
115 {
116 if (m_molecule == mol)
117 return;
118
119 if (m_molecule)
120 m_molecule->disconnect(this);
121
122 m_molecule = mol;
123
124 if (m_molecule)
125 connect(m_molecule, SIGNAL(changed(uint)), SLOT(moleculeChanged(uint)));
126
127 updateActions();
128 }
129
130 void Yaehmop::moleculeChanged(unsigned int c)
131 {
132 Q_ASSERT(m_molecule == qobject_cast<Molecule*>(sender()));
133
134 auto changes = static_cast<Molecule::MoleculeChanges>(c);
135
136 if (changes & Molecule::UnitCell) {
137 if (changes & Molecule::Added || changes & Molecule::Removed)
138 updateActions();
139 }
140 }
141
142 void Yaehmop::updateActions()
143 {
144 // Disable everything for nullptr molecules.
145 if (!m_molecule) {
146 foreach (QAction* action, m_actions)
147 action->setEnabled(false);
148 return;
149 }
150
151 // Only display the actions if there is a unit cell
152 if (m_molecule->unitCell()) {
153 foreach (QAction* action, m_actions)
154 action->setEnabled(true);
155 } else {
156 foreach (QAction* action, m_actions)
157 action->setEnabled(false);
158 }
159 }
160
161 void Yaehmop::readSettings()
162 {
163 QSettings settings;
164 m_yaehmopSettings.numBandKPoints =
165 settings.value("yaehmop/bandOptions/numBandKPoints", 40).toUInt();
166 m_yaehmopSettings.displayYaehmopInput =
167 settings.value("yaehmop/general/displayYaehmopInput", false).toBool();
168 m_yaehmopSettings.limitY =
169 settings.value("yaehmop/general/limitY", false).toBool();
170 m_yaehmopSettings.minY =
171 settings.value("yaehmop/general/minY", 0.0).toDouble();
172 m_yaehmopSettings.maxY =
173 settings.value("yaehmop/general/maxY", 0.0).toDouble();
174 m_yaehmopSettings.plotFermi =
175 settings.value("yaehmop/general/plotFermi", false).toBool();
176 m_yaehmopSettings.fermi =
177 settings.value("yaehmop/general/fermi", 0.0).toDouble();
178 m_yaehmopSettings.zeroFermi =
179 settings.value("yaehmop/general/zeroFermi", false).toBool();
180 m_yaehmopSettings.numDim =
181 settings.value("yaehmop/general/numDim", 3).toUInt();
182 }
183
184 void Yaehmop::writeSettings()
185 {
186 QSettings settings;
187 settings.setValue("yaehmop/bandOptions/numBandKPoints",
188 m_yaehmopSettings.numBandKPoints);
189 settings.setValue("yaehmop/general/displayYaehmopInput",
190 m_yaehmopSettings.displayYaehmopInput);
191 settings.setValue("yaehmop/general/limitY", m_yaehmopSettings.limitY);
192 settings.setValue("yaehmop/general/minY", m_yaehmopSettings.minY);
193 settings.setValue("yaehmop/general/maxY", m_yaehmopSettings.maxY);
194 settings.setValue("yaehmop/general/plotFermi", m_yaehmopSettings.plotFermi);
195 settings.setValue("yaehmop/general/fermi", m_yaehmopSettings.fermi);
196 settings.setValue("yaehmop/general/zeroFermi", m_yaehmopSettings.zeroFermi);
197 settings.setValue("yaehmop/general/numDim", m_yaehmopSettings.numDim);
198 }
199
200 void Yaehmop::displayBandDialog()
201 {
202 if (!m_molecule) {
203 qDebug() << "Error in " << __FUNCTION__ << ": the molecule is not set";
204 return;
205 }
206
207 if (!m_molecule->unitCell()) {
208 QMessageBox::warning(nullptr, tr("Avogadro2"),
209 tr("Cannot calculate band structure: no unit cell!"));
210 qDebug() << "Error in " << __FUNCTION__ << ": there is no unit cell";
211 return;
212 }
213
214 // Generate the special k points before displaying the dialog
215 m_yaehmopSettings.specialKPoints =
216 SpecialKPoints::getSpecialKPoints(*m_molecule);
217
218 if (m_yaehmopSettings.specialKPoints.isEmpty())
219 m_yaehmopSettings.specialKPoints = YAEHMOP_DEFAULT_SPECIAL_KPOINTS;
220
221 // Do nothing if the user cancels
222 if (m_bandDialog->exec() != QDialog::Accepted)
223 return;
224
225 // Save the settings for future use
226 writeSettings();
227
228 calculateBandStructure();
229 }
230
231 // Get the distance between two k points
232 double Yaehmop::kpointDistance(const Vector3& a, const Vector3& b)
233 {
234 if (!m_molecule) {
235 qDebug() << "Error in" << __FUNCTION__ << ": the molecule is not set";
236 return -1.0;
237 }
238
239 UnitCell* cell = m_molecule->unitCell();
240 if (!cell) {
241 qDebug() << "Error in " << __FUNCTION__ << ": there is no unit cell";
242 return -1.0;
243 }
244
245 // We need to find the reciprocal space basis vectors, and we
246 // need to find the actual k point location in reciprocal space.
247 const Vector3& aVec = cell->aVector();
248 const Vector3& bVec = cell->bVector();
249 const Vector3& cVec = cell->cVector();
250
251 Vector3 b1 = bVec.cross(cVec);
252 Vector3 b2 = cVec.cross(aVec);
253 Vector3 b3 = aVec.cross(bVec);
254
255 // This is how VASP does it.
256 // If it's good enough for VASP, it's good enough for me!
257 double omega = aVec[0] * b1[0] + aVec[1] * b1[1] + aVec[2] * b1[2];
258
259 b1 /= omega;
260 b2 /= omega;
261 b3 /= omega;
262
263 // Calculate the reciprocal points
264 const Vector3& recA(a[0] * b1 + a[1] * b2 + a[2] * b3);
265 const Vector3& recB(b[0] * b1 + b[1] * b2 + b[2] * b3);
266 return (recA - recB).norm();
267 }
268
269 void Yaehmop::calculateBandStructure()
270 {
271 // First, create the input
272 QString input;
273 input += "Title\n"; // Title
274 input += createGeometryAndLatticeInput();
275
276 // Here we describe the number of k points connecting each special
277 // k point, the number of special k points, and their locations
278 // in reciprocal space. This is something we will let the user change
279 input += "Band\n";
280
281 // This is the number of kpoints connecting each special k point
282 input += (QString::number(m_yaehmopSettings.numBandKPoints) + "\n");
283
284 // Num special k points
285 int numSK = m_yaehmopSettings.specialKPoints
286 .split(QRegularExpression("[\r\n]"), Qt::SkipEmptyParts)
287 .size();
288 input += (QString::number(numSK) + "\n"); // num special k points
289
290 // Add the whole string from user input
291 input += m_yaehmopSettings.specialKPoints;
292
293 // Perform the yaehmop calculation
294 QByteArray output;
295 QString err;
296 if (!executeYaehmop(input.toLocal8Bit(), output, err)) {
297 QMessageBox::warning(
298 nullptr, tr("Avogadro2"),
299 tr("Yaehmop execution failed with the following error:\n%1").arg(err));
300 qDebug() << "Yaehmop execution failed with the following error:\n" << err;
301 return;
302 }
303
304 // Now, read the output
305 QVector<QVector<double>> bands;
306 QVector<Vector3> kpoints;
307 QVector<specialKPoint> specialKPoints;
308 if (!YaehmopOut::readBandData(output, bands, kpoints, specialKPoints)) {
309 QString message = tr("Failed to read band structure output from Yaehmop!");
310 QMessageBox::warning(nullptr, tr("Avogadro2"), message);
311 qDebug() << message;
312 }
313
314 int numKPoints = kpoints.size();
315 int numSpecialKPoints = specialKPoints.size();
316
317 // If there is only one special k point, there is nothing to graph. Just
318 // return.
319 if (numSpecialKPoints <= 1) {
320 QString message =
321 tr("Only one special k point was found in Yaehmop output! Two or more "
322 "are required!");
323 QMessageBox::warning(nullptr, tr("Avogadro2"), message);
324 qDebug() << message;
325 return;
326 }
327
328 // Calculate the k-space distances
329 std::vector<float> xVals{ 0.0 };
330 for (int i = 1; i < numKPoints; ++i)
331 xVals.push_back(kpointDistance(kpoints[i - 1], kpoints[i]) + xVals.back());
332
333 // Calculate the special k point distances
334 std::vector<float> specialKPointVals{ 0.0 };
335 for (int i = 1; i < numSpecialKPoints; ++i) {
336 specialKPointVals.push_back(
337 kpointDistance(specialKPoints[i - 1].coords, specialKPoints[i].coords) +
338 specialKPointVals.back());
339 }
340
341 // This is to make sure vtk shows the symbols on the far left and right
342 specialKPointVals.front() += 0.0001;
343 specialKPointVals.back() -= 0.0001;
344
345 // Make a vector of labels for the special k points
346 QStringList specialKPointLabels;
347 for (int i = 0; i < numSpecialKPoints; ++i) {
348 specialKPointLabels.push_back(specialKPoints[i].label);
349 }
350
351 // Now generate a plot with the data
352 std::vector<std::vector<float>> data;
353 data.push_back(xVals);
354
355 // Make some labels
356 QStringList lineLabels;
357 lineLabels.push_back(tr("k-space"));
358
359 // Set the color
360 std::array<double, 4> color = { 255, 0, 0, 255 };
361 std::vector<std::array<double, 4>> lineColors;
362
363 size_t curBandNum = 1;
364 for (const auto& band : bands) {
365 std::vector<float> tmp(band.begin(), band.end());
366 data.push_back(tmp);
367 lineLabels.push_back(tr("Band %1").arg(curBandNum));
368 lineColors.push_back(color);
369 ++curBandNum;
370 }
371
372 // Should we plot the fermi level?
373 if (m_yaehmopSettings.plotFermi) {
374 // Adjust all the energies if we are to zero the fermi level
375 double fermi = m_yaehmopSettings.fermi;
376 if (m_yaehmopSettings.zeroFermi) {
377 // Skip the first vector because that is the x values
378 for (size_t i = 1; i < data.size(); ++i) {
379 for (auto& datum : data[i])
380 datum -= fermi;
381 }
382 // Fermi is now zero
383 fermi = 0.0;
384 }
385
386 // Create a horizontal, black, dashed line for the fermi level
387 lineLabels.push_back(tr("Fermi Level"));
388 lineColors.push_back({ 0, 0, 0, 255 });
389
390 std::vector<float> fermiVals(xVals.size(), fermi);
391 data.push_back(std::move(fermiVals));
392 }
393
394 const char* xTitle = "";
395 const char* yTitle = "Energy (eV)";
396 const char* windowName = "YAeHMOP Band Structure";
397
398 if (!m_chartDialog) {
399 m_chartDialog.reset(
400 new QtGui::ChartDialog(qobject_cast<QWidget*>(this->parent())));
401 }
402
403 m_chartDialog->setWindowTitle(windowName);
404 auto* chart = m_chartDialog->chartWidget();
405 chart->clearPlots();
406 chart->addPlots(data, QtGui::color4ub{ 255, 0, 0, 255 }, lineLabels);
407 chart->setXAxisTitle(xTitle);
408 chart->setYAxisTitle(yTitle);
409 chart->setTickLabels(QtGui::ChartWidget::Axis::x, specialKPointVals,
410 specialKPointLabels);
411 chart->setAxisLimits(QtGui::ChartWidget::Axis::x, xVals.front(),
412 xVals.back());
413 if (m_yaehmopSettings.limitY) {
414 chart->setAxisLimits(QtGui::ChartWidget::Axis::y, m_yaehmopSettings.minY,
415 m_yaehmopSettings.maxY);
416 }
417 m_chartDialog->show();
418
419 // Show the yaehmop input if we are to do so
420 if (m_yaehmopSettings.displayYaehmopInput)
421 showYaehmopInput(input);
422 }
423
424 QString Yaehmop::createGeometryAndLatticeInput() const
425 {
426 if (!m_molecule) {
427 qDebug() << "Error in " << __FUNCTION__ << ": the molecule is not set";
428 return "";
429 }
430
431 UnitCell* cell = m_molecule->unitCell();
432 if (!cell) {
433 QMessageBox::warning(nullptr, tr("Avogadro2"),
434 tr("Cannot calculate band structure: no unit cell!"));
435 qDebug() << "Error in " << __FUNCTION__ << ": there is no unit cell";
436 return "";
437 }
438
439 const Array<unsigned char>& atomicNumbers = m_molecule->atomicNumbers();
440 const Array<Vector3>& atomicPositions = m_molecule->atomPositions3d();
441
442 // This is the minimum number we allow doubles. If a number's float
443 // absolute value is smaller than this, we will round it to 0.
444 double minNum = 1e-8;
445
446 QString input;
447 input += "Geometry\n"; // Begin geometry section
448 int numAtoms = atomicNumbers.size();
449 // Num atoms plus (numDimensions + 1) dummies.
450 // Dummies are for defining the lattice
451 unsigned short numDim = m_yaehmopSettings.numDim;
452 input += (QString::number(numAtoms + numDim + 1) + QString("\n"));
453
454 // Now loop through atom positions and add them
455 for (int i = 0; i < numAtoms; ++i) {
456 QString symbol = Elements::symbol(atomicNumbers[i]);
457 const Vector3& pos = atomicPositions[i];
458 input += (QString::number(i + 1) + " ");
459 input += (symbol + " ");
460 for (size_t j = 0; j < 3; ++j)
461 // If the position is small, just use 0
462 input += (QString::number((fabs(pos[j]) > 1e-8 ? pos[j] : 0)) + " ");
463 input += "\n";
464 }
465
466 // Get the cell matrix
467 const Matrix3& cellMatrix = cell->cellMatrix();
468
469 // Add the dummy atoms - these tell the program where the lattice is
470 for (unsigned short i = 0; i <= numDim; ++i) {
471 input += (QString::number(numAtoms + i + 1) + " ");
472 // Symbol for dummy atoms
473 input += "& ";
474 // First dummy is at 0,0,0, the other dummies are at the ends of the
475 // lattice
476 if (i == 0) {
477 input += "0 0 0\n";
478 } else {
479 // We only get here if i > 0.
480 // i - 1 is equal to the index of the vector we are looking at.
481 for (unsigned short j = 0; j < 3; ++j) {
482 double val = cellMatrix(i - 1, j);
483 if (fabs(val) < minNum)
484 val = 0.0;
485 input += (QString::number(val) + " ");
486 }
487 input += "\n";
488 }
489 }
490
491 // Let's calculate the number of overlaps to use
492 // The manual says that numOverlaps * latticeVecLength should be between
493 // 10 and 20 Angstroms. Let's always use a numOverlaps of at least 3 and
494 // then use more if numOverlaps * latticeVecLength < 20.
495 Vector3i overlaps(3, 3, 3);
496 Vector3 latticeLengths(cell->a(), cell->b(), cell->c());
497
498 for (unsigned short i = 0; i < 3; ++i) {
499 while (overlaps[i] * latticeLengths[i] < 20)
500 ++overlaps[i];
501 }
502
503 // Lattice section to define the lattice
504 input += "lattice\n";
505 input += QString::number(numDim) + "\n";
506 // Add numbers of overlaps
507 for (size_t i = 0; i < numDim; ++i)
508 input += (QString::number(overlaps[i]) + " ");
509 input += "\n";
510 // If we have "4 5" here, that means the vector is defined
511 // from atom 4 to atom 5. We use dummy atoms for this. The first dummy
512 // atom (numAtoms + 1) is always at the origin, and the other dummy atoms
513 // are at the ends of the a, b, and c axes.
514 for (size_t i = 0; i < numDim; ++i) {
515 input += (QString::number(numAtoms + 1) + " " +
516 QString::number(numAtoms + i + 2) + "\n");
517 }
518
519 return input;
520 }
521
522 // Uncomment this for executeYaehmop debugging
523 // #define AVOGADRO_YAEHMOP_EXECUTE_DEBUG
524
525 bool Yaehmop::executeYaehmop(const QByteArray& input, QByteArray& output,
526 QString& err)
527 {
528 #ifdef AVOGADRO_YAEHMOP_EXECUTE_DEBUG
529 qDebug() << "executeYaehmop() input is:\n" << qPrintable(input);
530 #endif
531
532 QString program = m_programPath;
533 if (program.isEmpty()) {
534 QMessageBox::warning(nullptr, tr("Avogadro"), tr("Cannot find Yaehmop"));
535 return false;
536 }
537
538 QStringList args;
539 args << "--use_stdin_stdout";
540
541 QProcess p;
542 p.start(program, args);
543
544 if (!p.waitForStarted()) {
545 qDebug() << tr("Error: %1 failed to start").arg(program);
546 return false;
547 }
548
549 // Give it the input!
550 p.write(input.data());
551
552 // Close the write channel
553 p.closeWriteChannel();
554
555 if (!p.waitForFinished()) {
556 err = tr("Error: " + program.toLocal8Bit() + " failed to finish");
557 qDebug() << err;
558 output = p.readAllStandardOutput();
559 qDebug() << "Output is as follows:\n" << qPrintable(output);
560 return false;
561 }
562
563 int exitStatus = p.exitStatus();
564 output = p.readAllStandardOutput();
565
566 if (exitStatus == QProcess::CrashExit) {
567 qDebug() << "Error: Yahemop crashed!";
568 qDebug() << "Output is as follows:\n" << qPrintable(output);
569 return false;
570 }
571
572 if (exitStatus != QProcess::NormalExit) {
573 qDebug() << "Error: Yahemop finished abnormally with exit code "
574 << exitStatus;
575 qDebug() << "Output is as follows:\n" << qPrintable(output);
576 return false;
577 }
578
579 #ifdef AVOGADRO_YAEHMOP_EXECUTE_DEBUG
580 qDebug() << "executeYaehmop() output is:\n" << qPrintable(output);
581 #endif
582
583 // We did it!
584 return true;
585 }
586
587 void Yaehmop::showYaehmopInput(const QString& input)
588 {
589 auto* dialog = new QDialog(qobject_cast<QWidget*>(this->parent()));
590
591 // Make sure this gets deleted upon closing
592 dialog->setAttribute(Qt::WA_DeleteOnClose);
593
594 auto* layout = new QVBoxLayout(dialog);
595 dialog->setLayout(layout);
596 dialog->setWindowTitle(tr("Yaehmop Input"));
597 auto* edit = new QTextEdit(dialog);
598 layout->addWidget(edit);
599 dialog->resize(500, 500);
600
601 edit->setText(input);
602
603 dialog->show();
604 }
605
606 } // namespace Avogadro::QtPlugins