Debian Codegraph @

avogadro/qtplugins/surfaces/orbitals.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 "orbitals.h"
7 #include "orbitalwidget.h"
8
9 #include <avogadro/core/array.h>
10 #include <avogadro/core/basisset.h>
11 #include <avogadro/core/cube.h>
12 #include <avogadro/core/gaussianset.h>
13 #include <avogadro/core/variant.h>
14 #include <avogadro/core/vector.h>
15 #include <avogadro/qtgui/gaussiansetconcurrent.h>
16 #include <avogadro/qtgui/meshgenerator.h>
17 #include <avogadro/qtgui/molecule.h>
18 #include <avogadro/qtgui/slatersetconcurrent.h>
19
20 #include <QAction>
21 #include <QDebug>
22 #include <QtCore/QTimer>
23 #include <QtWidgets/QFileDialog>
24
25 namespace Avogadro::QtPlugins {
26
27 const double cubePadding = 5.0;
28 const int smoothingPasses = 1;
29
30 Orbitals::Orbitals(QObject* p)
31 : ExtensionPlugin(p), m_action(new QAction(this)), m_molecule(nullptr),
32 m_dialog(nullptr)
33 {
34 m_action->setEnabled(false);
35 m_action->setText(tr("Molecular Orbitals…"));
36 connect(m_action, SIGNAL(triggered()), SLOT(openDialog()));
37 }
38
39 Orbitals::~Orbitals()
40 {
41 // cancel the current running calculation
42 if (m_gaussianConcurrent) {
43 qDebug() << "Cancelling current calculation";
44 auto* watcher = &m_gaussianConcurrent->watcher();
45 if (watcher != nullptr && watcher->isRunning())
46 watcher->cancel();
47 }
48
49 if (m_dialog)
50 m_dialog->deleteLater();
51 // molecule and basis are freed elsewhere
52 }
53
54 QList<QAction*> Orbitals::actions() const
55 {
56 return QList<QAction*>() << m_action;
57 }
58
59 QStringList Orbitals::menuPath(QAction*) const
60 {
61 QStringList path;
62 path << tr("&Analyze");
63 return path;
64 }
65
66 void Orbitals::setMolecule(QtGui::Molecule* mol)
67 {
68 if (mol == nullptr)
69 return;
70
71 if (m_molecule != nullptr)
72 m_molecule->disconnect(this);
73
74 m_molecule = mol;
75 // check if it has basis set data
76 bool hasOrbitals = (m_molecule->basisSet() != nullptr);
77 // sanity check if there are actually mo coefficients
78 auto* basis = dynamic_cast<Core::GaussianSet*>(m_molecule->basisSet());
79 if (basis == nullptr || basis->moMatrix().size() == 0)
80 hasOrbitals = false;
81
82 if (hasOrbitals)
83 m_action->setEnabled(true);
84 else {
85 m_action->setEnabled(false);
86 if (m_dialog)
87 m_dialog->hide();
88 }
89
90 connect(m_molecule, SIGNAL(changed(unsigned int)),
91 SLOT(moleculeChanged(unsigned int)));
92
93 // Stuff we manage that will not be valid any longer
94 m_queue.clear();
95 m_currentRunningCalculation = -1;
96 m_currentMeshCalculation = -1;
97
98 loadBasis();
99
100 if (!m_basis || m_basis->electronCount() == 0 || !hasOrbitals)
101 return; // no electrons, no orbitals
102
103 loadOrbitals();
104 precalculateOrbitals();
105 }
106
107 void Orbitals::loadBasis()
108 {
109 if (m_molecule != nullptr) {
110 m_basis = m_molecule->basisSet();
111 }
112 }
113
114 void Orbitals::loadOrbitals()
115 {
116 if (m_basis == nullptr || m_molecule == nullptr)
117 return;
118
119 auto* basis = dynamic_cast<Core::GaussianSet*>(m_molecule->basisSet());
120 if (basis == nullptr || basis->moMatrix().size() == 0)
121 return;
122
123 if (!m_dialog) {
124 m_dialog = new OrbitalWidget(qobject_cast<QWidget*>(parent()), Qt::Window);
125 connect(m_dialog,
126 SIGNAL(orbitalSelected(unsigned int, Core::BasisSet::ElectronType)),
127 this,
128 SLOT(renderOrbital(unsigned int, Core::BasisSet::ElectronType)));
129 connect(m_dialog,
130 SIGNAL(renderRequested(unsigned int, double,
131 Core::BasisSet::ElectronType)),
132 this,
133 SLOT(calculateOrbitalFromWidget(unsigned int, double,
134 Core::BasisSet::ElectronType)));
135 connect(m_dialog, SIGNAL(calculateAll()), this,
136 SLOT(precalculateOrbitals()));
137 }
138
139 m_dialog->fillTable(m_basis);
140 m_dialog->show();
141 m_dialog->raise();
142 m_dialog->activateWindow();
143 }
144
145 void Orbitals::moleculeChanged([[maybe_unused]] unsigned int changes)
146 {
147 if (m_molecule == nullptr)
148 return;
149
150 bool isEnabled = m_action->isEnabled();
151 bool hasOrbitals = (m_molecule->basisSet() != nullptr);
152
153 // sanity check if there are actually mo coefficients
154 auto* basis = dynamic_cast<Core::GaussianSet*>(m_molecule->basisSet());
155 if (basis == nullptr || basis->moMatrix().size() == 0)
156 hasOrbitals = false;
157
158 if (isEnabled != hasOrbitals) {
159 m_action->setEnabled(hasOrbitals);
160 if (hasOrbitals) {
161 loadBasis(); // update m_basis from the new basisSet
162 loadOrbitals(); // fill the orbital table and show the dialog
163 }
164 }
165 }
166
167 void Orbitals::openDialog()
168 {
169 if (!m_dialog) {
170 m_dialog = new OrbitalWidget(qobject_cast<QWidget*>(parent()), Qt::Window);
171 connect(m_dialog,
172 SIGNAL(orbitalSelected(unsigned int, Core::BasisSet::ElectronType)),
173 this,
174 SLOT(renderOrbital(unsigned int, Core::BasisSet::ElectronType)));
175 connect(m_dialog,
176 SIGNAL(renderRequested(unsigned int, double,
177 Core::BasisSet::ElectronType)),
178 this,
179 SLOT(calculateOrbitalFromWidget(unsigned int, double,
180 Core::BasisSet::ElectronType)));
181 connect(m_dialog, SIGNAL(calculateAll()), this,
182 SLOT(precalculateOrbitals()));
183 }
184
185 m_dialog->show();
186 m_dialog->raise();
187 m_dialog->activateWindow();
188 }
189
190 void Orbitals::calculateOrbitalFromWidget(
191 unsigned int orbital, double resolution,
192 Core::BasisSet::ElectronType electronType)
193 {
194 m_updateMesh = true;
195
196 // check if the orbital is already in the queue (with same electron type)
197 bool found = false;
198 for (int i = 0; i < m_queue.size(); i++) {
199 if (m_queue[i].orbital == orbital && m_queue[i].resolution == resolution &&
200 m_queue[i].electronType == electronType) {
201 // change the priority to the highest
202 m_queue[i].priority = 0;
203 found = true;
204 break;
205 }
206 }
207
208 if (!found) {
209 addCalculationToQueue(orbital, resolution, m_dialog->isovalue(),
210 electronType, 0);
211 }
212 checkQueue();
213 }
214
215 void Orbitals::precalculateOrbitals()
216 {
217 if (m_basis == nullptr)
218 return;
219
220 m_updateMesh = false;
221
222 // Determine HOMO
223 unsigned int homo = m_basis->homo();
224
225 // Initialize prioritizer at HOMO's index
226 int priority = homo;
227
228 // Loop through all MOs, submitting calculations with increasing
229 // priority until HOMO is reached, submit both HOMO and LUMO at
230 // priority=1, then start increasing for orbitals above LUMO.
231 // E.g,
232 // .... HOMO-2 HOMO-1 HOMO LUMO LUMO+1 LUMO+2 ... << orbitals
233 // .... 3 2 1 1 2 3 ... << priorities
234
235 // Determine range of precalculated orbitals
236 unsigned int startIndex =
237 (m_dialog->precalcLimit()) ? homo - (m_dialog->precalcRange() / 2) : 0;
238 if (startIndex > homo) { // overflow check
239 startIndex = 0;
240 }
241 unsigned int endIndex = (m_dialog->precalcLimit())
242 ? homo + (m_dialog->precalcRange() / 2) - 1
243 : m_basis->molecularOrbitalCount();
244 if (endIndex >= m_basis->molecularOrbitalCount()) {
245 endIndex = m_basis->molecularOrbitalCount() - 1;
246 }
247
248 // For now, precalculate paired/alpha orbitals only
249 // TODO: For open-shell, could precalculate both alpha and beta
250 for (unsigned int i = startIndex; i <= endIndex; i++) {
251 #ifndef NDEBUG
252 qDebug() << " precalculate " << i << " priority " << priority;
253 #endif
254 addCalculationToQueue(
255 i, // orbital
256 OrbitalWidget::OrbitalQualityToDouble(m_dialog->defaultQuality()),
257 m_dialog->isovalue(), Core::BasisSet::Paired, priority);
258
259 // Update priority. Stays the same when i = homo.
260 if (i + 1 < homo)
261 priority--;
262 else if (i + 1 > homo)
263 priority++;
264 }
265 checkQueue();
266 }
267
268 void Orbitals::addCalculationToQueue(unsigned int orbital, double resolution,
269 double isovalue,
270 Core::BasisSet::ElectronType electronType,
271 unsigned int priority)
272 {
273 // Create new queue entry
274 calcInfo newCalc;
275 newCalc.orbital = orbital;
276 newCalc.electronType = electronType;
277 newCalc.resolution = resolution;
278 newCalc.isovalue = isovalue;
279 newCalc.priority = priority;
280 newCalc.state = NotStarted;
281
282 // Add new calculation
283 m_queue.append(newCalc);
284 }
285
286 void Orbitals::checkQueue()
287 {
288 if (m_runningCube)
289 return;
290 m_runningCube = true;
291
292 // Create a hash: keys=priority, values=indices
293
294 QHash<int, int> hash;
295 CalcState state;
296
297 for (int i = 0; i < m_queue.size(); i++) {
298 state = m_queue.at(i).state;
299
300 // If there is already a running cube, return.
301 if (state == Running) {
302 return;
303 }
304
305 if (state == NotStarted) {
306 hash.insert(m_queue[i].priority, i);
307 }
308 }
309
310 // Do nothing if all calcs are finished.
311 if (hash.size() == 0) {
312 m_runningCube = false;
313 #ifndef NDEBUG
314 qDebug() << "Finished queue.";
315 #endif
316 return;
317 }
318
319 QList<int> priorities = hash.keys();
320 std::sort(priorities.begin(), priorities.end());
321 startCalculation(hash.value(priorities.first()));
322 }
323
324 void Orbitals::startCalculation(unsigned int queueIndex)
325 {
326 // This will launch calculateMesh when finished.
327 m_currentRunningCalculation = queueIndex;
328
329 calcInfo* info = &m_queue[m_currentRunningCalculation];
330
331 #ifndef NDEBUG
332 qDebug() << info->orbital << " startCalculation() called";
333 #endif
334
335 switch (info->state) {
336 case NotStarted: // Start calculation
337 calculateCube();
338 break;
339 case Running: // Nothing below should happen...
340 qWarning() << "startCalculation called on a running calc...";
341 break;
342 case Completed:
343 qWarning() << "startCalculation called on a completed calc...";
344 break;
345 case Canceled:
346 qWarning() << "startCalculation called on a canceled calc...";
347 break;
348 }
349 }
350
351 void Orbitals::calculateCube()
352 {
353 if (m_currentRunningCalculation == -1)
354 return;
355
356 calcInfo* info = &m_queue[m_currentRunningCalculation];
357
358 info->state = Running;
359
360 // Check if the cube we want already exists (must match electron type too)
361 for (int i = 0; i < m_queue.size(); i++) {
362 calcInfo* cI = &m_queue[i];
363 if (cI->state == Completed && cI->orbital == info->orbital &&
364 cI->resolution == info->resolution &&
365 cI->electronType == info->electronType) {
366 info->cube = cI->cube;
367 #ifndef NDEBUG
368 qDebug() << "Reusing cube from calculation " << i << ":\n"
369 << "\tOrbital " << cI->orbital << "\n"
370 << "\tResolution " << cI->resolution;
371 #endif
372 // Set this cube as the active cube for volume rendering
373 for (Index j = 0; j < m_molecule->cubeCount(); ++j) {
374 if (m_molecule->cube(j) == cI->cube) {
375 m_molecule->setActiveCubeIndex(j);
376 break;
377 }
378 }
379 m_currentMeshCalculation = m_currentRunningCalculation;
380 calculatePosMesh();
381 calculationComplete();
382 return;
383 }
384 }
385
386 // Create new cube
387 Core::Cube* cube = m_molecule->addCube();
388 info->cube = cube;
389 cube->setLimits(*m_molecule, info->resolution, cubePadding);
390 cube->setName("Molecular Orbital " + std::to_string(info->orbital + 1));
391 cube->setCubeType(Core::Cube::Type::MO);
392
393 // Set this cube as the active cube for volume rendering
394 m_molecule->setActiveCubeIndex(m_molecule->cubeCount() - 1);
395
396 if (!m_gaussianConcurrent) {
397 m_gaussianConcurrent = new QtGui::GaussianSetConcurrent(this);
398 }
399 m_gaussianConcurrent->setMolecule(m_molecule);
400
401 auto* watcher = &m_gaussianConcurrent->watcher();
402 connect(watcher, SIGNAL(finished()), this, SLOT(calculateCubeDone()));
403
404 #ifndef NDEBUG
405 qDebug() << info->orbital << " Cube calculation started.";
406 #endif
407 bool beta = (info->electronType == Core::BasisSet::Beta);
408 m_gaussianConcurrent->calculateMolecularOrbital(cube, info->orbital, beta);
409 }
410
411 void Orbitals::calculateCubeDone()
412 {
413 auto* watcher = &m_gaussianConcurrent->watcher();
414 watcher->disconnect(this);
415
416 if (m_updateMesh) {
417 if (m_currentMeshCalculation == -1) {
418 m_currentMeshCalculation = m_currentRunningCalculation;
419 calculatePosMesh();
420 } else {
421 m_nextMeshCalculation = m_currentRunningCalculation;
422 }
423 }
424 calculationComplete();
425 }
426
427 void Orbitals::calculatePosMesh()
428 {
429 if (m_currentMeshCalculation == -1)
430 return;
431
432 calcInfo* info = &m_queue[m_currentMeshCalculation];
433
434 m_molecule->clearMeshes();
435 auto posMesh = m_molecule->addMesh();
436 auto cube = info->cube;
437
438 if (!m_meshGenerator) {
439 m_meshGenerator = new QtGui::MeshGenerator;
440 }
441 connect(m_meshGenerator, SIGNAL(finished()), SLOT(calculatePosMeshDone()));
442 m_meshGenerator->initialize(cube, posMesh, m_isoValue, smoothingPasses);
443 m_meshGenerator->start();
444 }
445
446 void Orbitals::calculatePosMeshDone()
447 {
448 disconnect(m_meshGenerator, nullptr, this, nullptr);
449 calculateNegMesh();
450 }
451
452 void Orbitals::calculateNegMesh()
453 {
454 if (m_currentMeshCalculation == -1)
455 return;
456
457 calcInfo* info = &m_queue[m_currentMeshCalculation];
458
459 auto negMesh = m_molecule->addMesh();
460 auto cube = info->cube;
461
462 if (!m_meshGenerator) {
463 // shouldn't happen, but better to be careful
464 m_meshGenerator = new QtGui::MeshGenerator;
465 }
466 connect(m_meshGenerator, SIGNAL(finished()), SLOT(calculateNegMeshDone()));
467 // true indicates that we want to reverse the surface
468 m_meshGenerator->initialize(cube, negMesh, -m_isoValue, smoothingPasses,
469 true);
470 m_meshGenerator->start();
471 }
472
473 void Orbitals::calculateNegMeshDone()
474 {
475 disconnect(m_meshGenerator, nullptr, this, nullptr);
476
477 meshComplete();
478 // make sure the display type is turned on
479 QStringList displayTypes;
480 displayTypes << tr("Surfaces");
481 emit requestActiveDisplayTypes(displayTypes);
482
483 // ask for a repaint
484 m_molecule->emitChanged(QtGui::Molecule::Added);
485 }
486
487 void Orbitals::meshComplete()
488 {
489 if (m_currentMeshCalculation == -1)
490 return;
491
492 if (m_nextMeshCalculation != -1) {
493 // start the next mesh calculation
494 m_currentMeshCalculation = m_nextMeshCalculation;
495 m_nextMeshCalculation = -1;
496 calculatePosMesh();
497 return;
498 } else
499 m_currentMeshCalculation = -1;
500 }
501
502 void Orbitals::calculationComplete()
503 {
504 if (m_currentRunningCalculation == -1)
505 return;
506
507 calcInfo* info = &m_queue[m_currentRunningCalculation];
508
509 info->state = Completed;
510 m_currentRunningCalculation = -1;
511 m_runningCube = false;
512
513 #ifndef NDEBUG
514 qDebug() << info->orbital << " all calculations complete.";
515 #endif
516 checkQueue();
517 }
518
519 void Orbitals::renderOrbital(unsigned int orbital,
520 Core::BasisSet::ElectronType electronType)
521 {
522 #ifndef NDEBUG
523 qDebug() << "Rendering orbital " << orbital
524 << " electronType: " << static_cast<int>(electronType);
525 #endif
526
527 // Find the most recent calc matching the selected orbital and electron type:
528 calcInfo calc;
529 int index = -1;
530 // in the event of ties, pick the best resolution
531 double resolution = OrbitalWidget::OrbitalQualityToDouble(0);
532 for (int i = 0; i < m_queue.size(); i++) {
533 calc = m_queue[i];
534 if (calc.orbital == orbital && calc.electronType == electronType &&
535 calc.state == Completed) {
536 if (calc.resolution <= resolution) {
537 resolution = calc.resolution;
538 index = i;
539 }
540 }
541 }
542
543 // calculate the meshes
544 if (index == -1) {
545 // need to calculate the cube first
546 calculateOrbitalFromWidget(
547 orbital,
548 OrbitalWidget::OrbitalQualityToDouble(m_dialog->defaultQuality()),
549 electronType);
550 } else {
551 // Set this cube as the active cube for volume rendering
552 Core::Cube* activeCube = m_queue[index].cube;
553 for (Index j = 0; j < m_molecule->cubeCount(); ++j) {
554 if (m_molecule->cube(j) == activeCube) {
555 m_molecule->setActiveCubeIndex(j);
556 break;
557 }
558 }
559
560 // just need to update the meshes
561 if (m_currentMeshCalculation == -1) {
562 m_currentMeshCalculation = index;
563 calculatePosMesh(); // will eventually call negMesh too
564 } else {
565 // queue it up
566 m_nextMeshCalculation = index;
567 }
568 }
569
570 // add the orbital to the renderer
571 QStringList displayTypes;
572 displayTypes << tr("Surfaces");
573 emit requestActiveDisplayTypes(displayTypes);
574 }
575
576 } // namespace Avogadro::QtPlugins