Debian Codegraph @

avogadro/qtplugins/autoopt/autoopt.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 "autoopt.h"
7 #include "csvrthermostat.h"
8
9 #include <avogadro/calc/energymanager.h>
10 #include <avogadro/calc/energyoptimizer.h>
11 #include <avogadro/calc/lennardjones.h>
12
13 #include <avogadro/core/contrastcolor.h>
14 #include <avogadro/core/vector.h>
15
16 #include <avogadro/qtgui/calcworker.h>
17 #include <avogadro/qtgui/molecule.h>
18 #include <avogadro/qtgui/rwmolecule.h>
19
20 #include <avogadro/qtopengl/glwidget.h>
21
22 #include <avogadro/rendering/camera.h>
23 #include <avogadro/rendering/geometrynode.h>
24 #include <avogadro/rendering/glrenderer.h>
25 #include <avogadro/rendering/groupnode.h>
26 #include <avogadro/rendering/textlabel2d.h>
27 #include <avogadro/rendering/textlabel3d.h>
28 #include <avogadro/rendering/textproperties.h>
29
30 #include <QAction>
31 #include <QFormLayout>
32 #include <QComboBox>
33 #include <QDoubleSpinBox>
34 #include <QPushButton>
35 #include <QSettings>
36 #include <QElapsedTimer>
37 #include <QThread>
38 #include <QTimer>
39
40 #include <QtGui/QIcon>
41 #include <QtGui/QKeyEvent>
42 #include <QtGui/QMouseEvent>
43 #include <QtGui/QWheelEvent>
44
45 #include <QDebug>
46
47 using Avogadro::QtGui::Molecule;
48 using Avogadro::Rendering::GeometryNode;
49 using Avogadro::Rendering::GroupNode;
50 using Avogadro::Rendering::Identifier;
51 using Avogadro::Rendering::TextLabel2D;
52 using Avogadro::Rendering::TextLabel3D;
53 using Avogadro::Rendering::TextProperties;
54
55 namespace Avogadro::QtPlugins {
56
57 using QtGui::Molecule;
58 using QtGui::RWAtom;
59
60 #define ROTATION_SPEED 0.5
61
62 AutoOpt::AutoOpt(QObject* parent_)
63 : QtGui::ToolPlugin(parent_), m_activateAction(new QAction(this)),
64 m_molecule(nullptr), m_renderer(nullptr), m_pressedButtons(Qt::NoButton),
65 m_toolWidget(nullptr), m_currentMethod("LJ")
66 {
67 QString shortcut = tr("Ctrl+7", "control-key 7");
68 m_activateAction->setText(tr("Auto Optimize"));
69 m_activateAction->setToolTip(
70 tr("Auto Optimize Tool\t(%1)\n\n"
71 "Navigation Functions when clicking in empty space.\n"
72 "Left Mouse:\tRotate Space\n"
73 "Middle Mouse:\tZoom Space\n"
74 "Right Mouse:\tMove Space\n"
75 "Double-Click:\tReset View\n\n"
76 "When running:\n"
77 "Left Mouse:\tClick and drag atoms to move them.\n"
78 "Right Mouse:\tClick and drag to rotate atoms.")
79 .arg(shortcut));
80 setIcon();
81
82 // used to run the optimization step
83 connect(&m_timer, &QTimer::timeout, this, &AutoOpt::optimizeStep);
84
85 // set up the the thermostat
86 m_thermostat =
87 new CSVRThermostat(m_temperature, m_timeStep, m_timeStep * 200.0);
88 }
89
90 AutoOpt::~AutoOpt()
91 {
92 cleanupWorker();
93 delete m_thermostat;
94 }
95
96 void AutoOpt::cleanupWorker()
97 {
98 if (m_workerThread) {
99 m_workerThread->quit();
100 m_workerThread->wait(5000);
101 m_workerThread = nullptr;
102 m_worker = nullptr;
103 }
104 m_computePending = false;
105 }
106
107 void AutoOpt::startWorker()
108 {
109 cleanupWorker();
110
111 auto n = m_molecule->atomCount();
112 auto mask = m_molecule->molecule().frozenAtomMask();
113 if (mask.rows() != static_cast<Eigen::Index>(3 * n))
114 mask = Eigen::VectorXd::Ones(3 * n);
115
116 auto constraints = m_molecule->molecule().constraints();
117
118 auto* calc = Calc::EnergyManager::instance().model(m_currentMethod);
119 if (calc == nullptr)
120 return;
121
122 Core::Molecule snapshot =
123 static_cast<const Core::Molecule&>(m_molecule->molecule());
124
125 m_workerThread = new QThread(this);
126 m_worker = new QtGui::CalcWorker();
127 m_worker->moveToThread(m_workerThread);
128
129 connect(m_workerThread, &QThread::finished, m_worker, &QObject::deleteLater);
130 m_workerThread->start();
131
132 // Connect signals based on task
133 if (m_task == 0) {
134 connect(m_worker, &QtGui::CalcWorker::optimizeFinished, this,
135 &AutoOpt::onOptimizeStepDone);
136 } else {
137 connect(m_worker, &QtGui::CalcWorker::evaluateFinished, this,
138 &AutoOpt::onGradientDone);
139 }
140 connect(m_worker, &QtGui::CalcWorker::calculatorReady, this,
141 &AutoOpt::onWorkerReady);
142
143 // Now invoke initCalculator after connections are established
144 QMetaObject::invokeMethod(
145 m_worker, "initCalculator", Qt::QueuedConnection,
146 Q_ARG(Avogadro::Calc::EnergyCalculator*, calc),
147 Q_ARG(Avogadro::Core::Molecule, snapshot), Q_ARG(Eigen::VectorXd, mask),
148 Q_ARG(std::vector<Avogadro::Core::Constraint>, constraints));
149 }
150
151 void AutoOpt::setIcon(bool darkTheme)
152 {
153 Q_UNUSED(darkTheme);
154 m_activateAction->setIcon(QIcon(":/icons/autoopt.svg"));
155 }
156
157 void setMasses(Eigen::ArrayXd& masses, const QtGui::Molecule* mol)
158 {
159 masses.resize(mol->atomCount() * 3); // 3N to match coordinates
160 for (unsigned int i = 0; i < mol->atomCount(); i++) {
161 Real mass = mol->atom(i).mass();
162 if (mass < 0.5)
163 mass = 1.0; // for dummy atoms
164
165 masses[i * 3] = mass;
166 masses[i * 3 + 1] = mass;
167 masses[i * 3 + 2] = mass;
168 }
169 }
170
171 void AutoOpt::setMolecule(QtGui::Molecule* mol)
172 {
173 if (mol != nullptr) {
174 m_molecule = mol->undoMolecule();
175 // connect to any molecule changes
176 connect(mol, SIGNAL(changed(unsigned int)),
177 SLOT(moleculeChanged(unsigned int)));
178
179 setMasses(m_masses, mol);
180 }
181 }
182
183 void AutoOpt::moleculeChanged(unsigned int changes)
184 {
185 // qDebug() << "molecule changed" << changes;
186 if (m_running && (changes != (Molecule::Atoms | Molecule::Moved))) {
187 // restart
188 stop();
189 start();
190 }
191 }
192
193 QWidget* AutoOpt::toolWidget() const
194 {
195 QSettings settings;
196 if (!m_toolWidget && m_molecule) {
197 m_toolWidget = new QWidget();
198 m_toolWidget->setWindowTitle("AutoOptimization");
199
200 // set up a form layout
201 QFormLayout* form = new QFormLayout(m_toolWidget);
202
203 QComboBox* taskComboBox = new QComboBox();
204 taskComboBox->setObjectName("taskComboBox");
205 taskComboBox->addItem(tr("Optimize"));
206 taskComboBox->addItem(tr("Dynamics"));
207 taskComboBox->setCurrentIndex(0);
208 connect(taskComboBox, &QComboBox::currentIndexChanged, this,
209 &AutoOpt::taskChanged);
210 form->addRow(tr("Task:"), taskComboBox);
211
212 // method combo box
213 QComboBox* methodComboBox = new QComboBox();
214 methodComboBox->setObjectName("methodComboBox");
215 // check the methods for this molecule
216 auto mol = m_molecule->molecule();
217 auto list = Calc::EnergyManager::instance().identifiersForMolecule(mol);
218 for (auto option : list) {
219 methodComboBox->addItem(option.c_str());
220 }
221
222 // check for the previous saved method
223 auto recommended = Calc::EnergyManager::instance().recommendedModel(mol);
224 QString currentMethod =
225 settings.value("autoopt/method", recommended.c_str()).toString();
226
227 // check to make sure currentMethod is in the list
228 // otherwise use recommended
229 if (!methodComboBox->findText(currentMethod))
230 currentMethod = recommended.c_str();
231 methodComboBox->setCurrentIndex(methodComboBox->findText(currentMethod));
232
233 connect(methodComboBox, &QComboBox::currentTextChanged, this,
234 &AutoOpt::methodChanged);
235 form->addRow(tr("Method:"), methodComboBox);
236
237 // add a temperature double spin box for dynamics
238 QDoubleSpinBox* temperatureSpinBox = new QDoubleSpinBox();
239 temperatureSpinBox->setObjectName("temperatureSpinBox");
240 temperatureSpinBox->setRange(0.0, 1000.0);
241 temperatureSpinBox->setSingleStep(1.0);
242 temperatureSpinBox->setDecimals(1);
243 temperatureSpinBox->setSuffix(" K"); // don't translate units
244 temperatureSpinBox->setValue(300.0);
245 connect(temperatureSpinBox, &QDoubleSpinBox::valueChanged, this,
246 &AutoOpt::temperatureChanged);
247 form->addRow(tr("Temperature:"), temperatureSpinBox);
248
249 // add a timestep double spin box for dynamics
250 QDoubleSpinBox* timeStepSpinBox = new QDoubleSpinBox();
251 timeStepSpinBox->setObjectName("timeStepSpinBox");
252 timeStepSpinBox->setRange(0.1, 10.0);
253 timeStepSpinBox->setSingleStep(0.5);
254 timeStepSpinBox->setDecimals(1);
255 timeStepSpinBox->setSuffix(" fs"); // don't translate units
256 timeStepSpinBox->setValue(1.0);
257 connect(timeStepSpinBox, &QDoubleSpinBox::valueChanged, this,
258 &AutoOpt::timeStepChanged);
259 form->addRow(tr("Timestep:"), timeStepSpinBox);
260
261 // disable the temperature and timestep for now
262 temperatureSpinBox->setEnabled(false);
263 timeStepSpinBox->setEnabled(false);
264
265 // start stop button
266 QPushButton* startStopButton = new QPushButton(tr("Start"));
267 startStopButton->setObjectName("startStopButton");
268 startStopButton->setIcon(QIcon::fromTheme("go-down"));
269 connect(startStopButton, &QPushButton::clicked, this, &AutoOpt::startStop);
270 form->addRow(startStopButton);
271
272 m_toolWidget->setLayout(form);
273 }
274 return m_toolWidget;
275 }
276
277 void AutoOpt::taskChanged(int index)
278 {
279 m_task = index;
280
281 auto temperatureSpinBox =
282 m_toolWidget->findChild<QDoubleSpinBox*>("temperatureSpinBox");
283 auto timeStepSpinBox =
284 m_toolWidget->findChild<QDoubleSpinBox*>("timeStepSpinBox");
285
286 bool enabled = (index == 1);
287 temperatureSpinBox->setEnabled(enabled);
288 timeStepSpinBox->setEnabled(enabled);
289
290 if (index == 1) { // dynamics
291 // enable the temperature and timestep
292 disconnect(&m_timer, &QTimer::timeout, this, &AutoOpt::optimizeStep);
293 connect(&m_timer, &QTimer::timeout, this, &AutoOpt::dynamicsStep);
294 } else {
295 // disable the temperature and timestep
296 disconnect(&m_timer, &QTimer::timeout, this, &AutoOpt::dynamicsStep);
297 connect(&m_timer, &QTimer::timeout, this, &AutoOpt::optimizeStep);
298 }
299 }
300
301 void AutoOpt::temperatureChanged(double temp)
302 {
303 m_temperature = temp;
304 }
305
306 void AutoOpt::timeStepChanged(double timeStep)
307 {
308 m_timeStep = timeStep;
309 }
310
311 void AutoOpt::startStop()
312 {
313 if (m_running)
314 stop();
315 else
316 start();
317 }
318
319 void AutoOpt::start()
320 {
321 // get the button from the widget
322 QPushButton* startStopButton =
323 m_toolWidget->findChild<QPushButton*>("startStopButton");
324 startStopButton->setText(tr("Stop"));
325 startStopButton->setIcon(QIcon::fromTheme("process-stop"));
326 m_running = true;
327
328 // make sure method is set
329 if (m_toolWidget) {
330 auto comboBox = m_toolWidget->findChild<QComboBox*>("methodComboBox");
331 QString currentMethod = comboBox->currentText();
332 m_currentMethod = currentMethod.toStdString();
333 }
334
335 m_molecule->beginMergeMode("AutoOpt");
336
337 m_energy = 0.0;
338 m_deltaE = 0.0;
339
340 // set up masses first (needed for velocity initialization)
341 setMasses(m_masses, &m_molecule->molecule());
342
343 // set the initial velocities
344 m_velocities.resize(m_molecule->atomCount() * 3);
345 m_acceleration.resize(m_molecule->atomCount() * 3);
346 m_acceleration.setZero();
347 m_firstStep = true; // reset for Velocity Verlet
348 if (m_task == 1) {
349 // For dynamics, initialize to Maxwell-Boltzmann distribution
350 m_thermostat->setTargetTemperature(m_temperature);
351
352 // Count free coordinates from the frozen atom mask
353 auto mask = m_molecule->molecule().frozenAtomMask();
354 int freeDOF = 3 * m_molecule->atomCount();
355 if (mask.rows() == freeDOF)
356 freeDOF = static_cast<int>(mask.sum());
357 // Subtract 3 for overall translation unless periodic (unit cell)
358 if (m_molecule->molecule().unitCell() == nullptr)
359 freeDOF -= 3;
360 m_thermostat->setDegreesOfFreedom(std::max(freeDOF, 1));
361
362 m_thermostat->initializeVelocities(m_velocities, m_masses);
363 } else {
364 m_velocities.setZero();
365 }
366
367 // Start the worker thread — timer begins in onWorkerReady
368 startWorker();
369
370 emit drawablesChanged();
371 }
372
373 void AutoOpt::onWorkerReady()
374 {
375 if (!m_running)
376 return;
377
378 // Now that the worker is ready, start the timer
379 qint64 minimumStep = 33; // 30 fps
380 m_oneStepTime = minimumStep;
381 m_timer.start(m_oneStepTime);
382 }
383
384 void AutoOpt::stop()
385 {
386 m_timer.stop();
387 m_running = false;
388
389 cleanupWorker();
390
391 // get the button from the widget
392 QPushButton* startStopButton =
393 m_toolWidget->findChild<QPushButton*>("startStopButton");
394 startStopButton->setText(tr("Start"));
395 startStopButton->setIcon(QIcon::fromTheme("go-down"));
396
397 m_molecule->endMergeMode();
398
399 emit drawablesChanged();
400 }
401
402 void AutoOpt::methodChanged(const QString& method)
403 {
404 m_currentMethod = method.toStdString();
405 // save the choice for next time
406 QSettings settings;
407 settings.setValue("autoopt/method", method);
408
409 // need to stop the current optimization,
410 // then restart after a brief pause
411 if (m_running) {
412 stop();
413 start();
414 }
415 }
416
417 void AutoOpt::optimizeStep()
418 {
419 if (!m_running) {
420 m_timer.stop();
421 return;
422 }
423
424 // Skip if a previous computation is still in progress
425 if (m_computePending || !m_worker)
426 return;
427
428 int n = m_molecule->atomCount();
429 Core::Array<Vector3> pos = m_molecule->atomPositions3d();
430 Eigen::Map<Eigen::VectorXd> map(pos[0].data(), 3 * n);
431 Eigen::VectorXd positions = map;
432
433 Calc::OptimizationOptions options;
434 options.algorithm = Calc::OptimizationAlgorithm::Lbfgs;
435 options.chunkIterations = 2;
436
437 m_computePending = true;
438 QMetaObject::invokeMethod(
439 m_worker, "runOptimizeChunk", Qt::QueuedConnection,
440 Q_ARG(Eigen::VectorXd, positions),
441 Q_ARG(Avogadro::Calc::OptimizationOptions, options));
442 }
443
444 void AutoOpt::onOptimizeStepDone(Eigen::VectorXd positions,
445 Eigen::VectorXd gradient, double energy,
446 bool converged)
447 {
448 Q_UNUSED(gradient);
449 Q_UNUSED(converged);
450 m_computePending = false;
451
452 if (!m_running || m_molecule == nullptr)
453 return;
454
455 int n = m_molecule->atomCount();
456
457 if (std::isfinite(energy) && positions.allFinite()) {
458 m_deltaE = energy - m_energy;
459 m_energy = energy;
460
461 Core::Array<Vector3> pos(n);
462 Eigen::Map<Eigen::VectorXd>(pos[0].data(), 3 * n) = positions;
463
464 m_molecule->setAtomPositions3d(pos, tr("Optimize Geometry"));
465 Molecule::MoleculeChanges changes = Molecule::Atoms | Molecule::Moved;
466 m_molecule->emitChanged(changes);
467 }
468 }
469
470 void AutoOpt::dynamicsStep()
471 {
472 if (!m_running) {
473 m_timer.stop();
474 return;
475 }
476
477 // Skip if a previous computation is still in progress
478 if (m_computePending || !m_worker)
479 return;
480
481 int n = m_molecule->atomCount();
482 double dt = m_timeStep;
483
484 Core::Array<Vector3> pos = m_molecule->atomPositions3d();
485 Eigen::Map<Eigen::VectorXd> map(pos[0].data(), 3 * n);
486 Eigen::VectorXd positions = map;
487
488 // get the frozen atoms
489 auto mask = m_molecule->molecule().frozenAtomMask();
490 if (mask.rows() != 3 * n)
491 mask = Eigen::VectorXd::Ones(3 * n);
492
493 // check m_masses
494 if (m_masses.rows() != 3 * n)
495 setMasses(m_masses, &(m_molecule->molecule()));
496
497 // Velocity Verlet Step 1: Update positions
498 // x(t+dt) = x(t) + v(t)*dt + 0.5*a(t)*dt^2
499 Eigen::VectorXd velocityTerm = m_velocities * dt;
500 Eigen::VectorXd accelTerm = 0.5 * m_acceleration * dt * dt;
501
502 // zero out frozen atoms from the mask
503 velocityTerm = velocityTerm.array() * mask.array();
504 accelTerm = accelTerm.array() * mask.array();
505
506 Eigen::VectorXd newPositions = positions + velocityTerm + accelTerm;
507
508 // Limit maximum displacement per atom to prevent instability.
509 const double baseDisplacement = 0.33 * std::sqrt(12.0 / 300.0);
510 Eigen::ArrayXd maxDisplacements =
511 baseDisplacement * (m_temperature / m_masses).sqrt();
512 Eigen::VectorXd displacement = newPositions - positions;
513 for (int i = 0; i < n; ++i) {
514 double dist = displacement.segment<3>(3 * i).norm();
515 double limit = maxDisplacements[3 * i];
516 if (dist > limit) {
517 double scale = limit / dist;
518 displacement.segment<3>(3 * i) *= scale;
519 m_velocities.segment<3>(3 * i) *= scale;
520 }
521 }
522 newPositions = positions + displacement;
523
524 // Update molecule positions immediately (visual feedback)
525 if (newPositions.allFinite()) {
526 Core::Array<Vector3> newPos(n);
527 Eigen::Map<Eigen::VectorXd>(newPos[0].data(), 3 * n) = newPositions;
528 m_molecule->setAtomPositions3d(newPos, tr("Molecular Dynamics"));
529 Molecule::MoleculeChanges changes = Molecule::Atoms | Molecule::Moved;
530 m_molecule->emitChanged(changes);
531 }
532
533 // Send newPositions to worker for gradient computation (Verlet Step 2)
534 m_computePending = true;
535 QMetaObject::invokeMethod(m_worker, "runGradient", Qt::QueuedConnection,
536 Q_ARG(Eigen::VectorXd, newPositions));
537 }
538
539 void AutoOpt::onGradientDone(Eigen::VectorXd gradient, double energy)
540 {
541 Q_UNUSED(energy);
542 m_computePending = false;
543
544 if (!m_running || m_molecule == nullptr)
545 return;
546
547 int n = m_molecule->atomCount();
548 double dt = m_timeStep;
549
550 auto mask = m_molecule->molecule().frozenAtomMask();
551 if (mask.rows() != 3 * n)
552 mask = Eigen::VectorXd::Ones(3 * n);
553
554 // update the thermostat settings
555 int freeDOF = static_cast<int>(mask.sum());
556 if (m_molecule->molecule().unitCell() == nullptr)
557 freeDOF -= 3;
558 m_thermostat->setTargetTemperature(m_temperature);
559 m_thermostat->setTimeStep(m_timeStep);
560 m_thermostat->setDegreesOfFreedom(std::max(freeDOF, 1));
561
562 // Guard against NaN/Inf from the gradient
563 if (!gradient.allFinite())
564 gradient.setZero();
565
566 Eigen::VectorXd newAcceleration =
567 -units::FORCE_CONVERSION * gradient.array() / m_masses.array();
568
569 if (m_firstStep) {
570 m_acceleration = newAcceleration;
571 m_firstStep = false;
572 }
573
574 // Velocity Verlet Step 3: Update velocities
575 // v(t+dt) = v(t) + 0.5*(a(t) + a(t+dt))*dt
576 m_velocities += 0.5 * (m_acceleration + newAcceleration) * dt;
577
578 // zero out frozen coords from the mask
579 m_velocities = m_velocities.array() * mask.array();
580 newAcceleration = newAcceleration.array() * mask.array();
581
582 // Store new acceleration for next step
583 m_acceleration = newAcceleration;
584
585 // Apply thermostat
586 m_thermostat->apply(m_velocities, m_masses);
587
588 #ifndef NDEBUG
589 qDebug() << " temperature "
590 << m_thermostat->compute_temperature(m_velocities, m_masses);
591 #endif
592 }
593
594 void AutoOpt::draw(Rendering::GroupNode& node)
595 {
596 if (!m_running)
597 return; // nothing to draw
598
599 QString overlayText;
600 if (m_task == 1) {
601 // dynamics step
602 double temp = m_thermostat->compute_temperature(m_velocities, m_masses);
603 overlayText = tr("%1 T = %L2", "temperature in Kelvin")
604 .arg(m_currentMethod.c_str())
605 .arg(temp, 0, 'f', 1) +
606 " K";
607 } else {
608 overlayText = tr("%1 ΔE = %L2", "change in energy in kJ/mol")
609 .arg(m_currentMethod.c_str())
610 .arg(m_deltaE, 0, 'f', 2) +
611 " kJ/mol";
612 }
613
614 auto* geo = new GeometryNode;
615 node.addChild(geo);
616
617 TextProperties overlayTProp;
618 overlayTProp.setFontFamily(TextProperties::Mono);
619
620 // black text as a default
621 Vector3ub color(0, 0, 0);
622 if (m_renderer) {
623 auto backgroundColor = m_renderer->scene().backgroundColor();
624 color = Core::contrastColor(
625 Vector3ub(backgroundColor[0], backgroundColor[1], backgroundColor[2]));
626 }
627
628 overlayTProp.setColorRgb(color[0], color[1], color[2]);
629 overlayTProp.setAlign(TextProperties::HLeft, TextProperties::VTop);
630
631 auto* label = new TextLabel2D;
632 label->setText(overlayText.toStdString());
633 label->setTextProperties(overlayTProp);
634 label->setRenderPass(Rendering::Overlay2DPass);
635 // align to the top left so get the viewport height
636 int height = m_renderer->camera().height();
637 label->setAnchor(Vector2i(10, height - 10));
638
639 geo->addDrawable(label);
640 }
641
642 QUndoCommand* AutoOpt::keyPressEvent(QKeyEvent* e)
643 {
644 switch (e->key()) {
645 case Qt::Key_Left:
646 case Qt::Key_H:
647 case Qt::Key_A:
648 translate(Vector3(-0.1, 0.0, 0.0));
649 e->accept();
650 break;
651 case Qt::Key_Right:
652 case Qt::Key_L:
653 case Qt::Key_D:
654 translate(Vector3(+0.1, 0.0, 0.0));
655 e->accept();
656 break;
657 case Qt::Key_Up:
658 case Qt::Key_K:
659 case Qt::Key_W:
660 translate(Vector3(0.0, +0.1, 0.0));
661 e->accept();
662 break;
663 case Qt::Key_Down:
664 case Qt::Key_J:
665 case Qt::Key_S:
666 translate(Vector3(0.0, -0.1, 0.0));
667 e->accept();
668 break;
669 default:
670 e->ignore();
671 }
672 m_molecule->emitChanged(Molecule::Atoms | Molecule::Modified);
673 return nullptr;
674 }
675
676 QUndoCommand* AutoOpt::mousePressEvent(QMouseEvent* e)
677 {
678 if (!m_renderer)
679 return nullptr;
680
681 updatePressedButtons(e, false);
682 m_lastMousePosition = e->pos();
683 Vector2f windowPos(e->localPos().x(), e->localPos().y());
684 m_lastMouse3D = m_renderer->camera().unProject(windowPos);
685
686 if (m_molecule) {
687 m_molecule->setInteractive(true);
688 }
689
690 if (m_pressedButtons & Qt::LeftButton) {
691 m_object = m_renderer->hit(e->pos().x(), e->pos().y());
692
693 switch (m_object.type) {
694 case Rendering::AtomType:
695 e->accept();
696 return nullptr;
697 default:
698 break;
699 }
700 }
701
702 return nullptr;
703 }
704
705 QUndoCommand* AutoOpt::mouseReleaseEvent(QMouseEvent* e)
706 {
707 if (!m_renderer)
708 return nullptr;
709
710 updatePressedButtons(e, true);
711
712 if (m_object.type == Rendering::InvalidType)
713 return nullptr;
714
715 if (m_molecule) {
716 m_molecule->setInteractive(false);
717 }
718
719 switch (e->button()) {
720 case Qt::LeftButton:
721 case Qt::RightButton:
722 resetObject();
723 e->accept();
724 break;
725 default:
726 break;
727 }
728
729 return nullptr;
730 }
731
732 QUndoCommand* AutoOpt::mouseMoveEvent(QMouseEvent* e)
733 {
734 // if we're dragging through empty space, just return and ignore
735 // (e.g., fall back to the navigate tool)
736 const Core::Molecule* mol = &m_molecule->molecule();
737 if (mol->isSelectionEmpty() && m_object.type == Rendering::InvalidType) {
738 e->ignore();
739 return nullptr;
740 }
741
742 updatePressedButtons(e, false);
743 e->ignore();
744
745 Vector2f windowPos(e->localPos().x(), e->localPos().y());
746
747 if (mol->isSelectionEmpty() && m_object.type == Rendering::AtomType &&
748 m_object.molecule == &m_molecule->molecule()) {
749 // translate single atom position
750 RWAtom atom = m_molecule->atom(m_object.index);
751 Vector3f oldPos(atom.position3d().cast<float>());
752 Vector3f newPos = m_renderer->camera().unProject(windowPos, oldPos);
753 atom.setPosition3d(newPos.cast<double>());
754 } else if (!mol->isSelectionEmpty()) {
755 // update all selected atoms
756 Vector3f newPos = m_renderer->camera().unProject(windowPos);
757 Vector3 delta = (newPos - m_lastMouse3D).cast<double>();
758
759 if (m_currentAction == Translation) {
760 translate(delta);
761 } else {
762 // get the center of the selected atoms
763 Vector3 centroid(0.0, 0.0, 0.0);
764 unsigned long selectedAtomCount = 0;
765 for (Index i = 0; i < m_molecule->atomCount(); ++i) {
766 if (!m_molecule->atomSelected(i))
767 continue;
768
769 centroid += m_molecule->atomPosition3d(i);
770 selectedAtomCount++;
771 }
772 if (selectedAtomCount > 0)
773 centroid /= selectedAtomCount;
774
775 if (m_currentAction == Rotation) {
776 rotate(delta, centroid);
777 } else if (m_currentAction == ZoomTilt) {
778 tilt(delta, centroid);
779 }
780 }
781
782 // now that we've moved things, save the position
783 m_lastMouse3D = newPos;
784 }
785
786 m_molecule->emitChanged(Molecule::Atoms | Molecule::Modified);
787 e->accept();
788 return nullptr;
789 }
790
791 void AutoOpt::translate(Vector3 delta, bool moveSelected)
792 {
793 for (Index i = 0; i < m_molecule->atomCount(); ++i) {
794 if (moveSelected && !m_molecule->atomSelected(i))
795 continue;
796 else if (!moveSelected && m_molecule->atomSelected(i))
797 continue;
798
799 Vector3 currentPos = m_molecule->atomPosition3d(i);
800 m_molecule->setAtomPosition3d(i, currentPos + delta.cast<double>());
801 }
802 }
803
804 void AutoOpt::rotate(Vector3 delta, Vector3 centroid, bool moveSelected)
805 {
806 // Rotate the selected atoms about the center
807 // rotate only selected primitives
808 Rendering::Camera* camera = &m_renderer->camera();
809 Eigen::Vector3d backTransformX =
810 camera->modelView().cast<double>().linear().row(0).transpose().normalized();
811 Eigen::Vector3d backTransformY =
812 camera->modelView().cast<double>().linear().row(1).transpose().normalized();
813
814 Eigen::Projective3d fragmentRotation;
815 fragmentRotation.matrix().setIdentity();
816 fragmentRotation.translation() = centroid;
817 fragmentRotation.rotate(
818 Eigen::AngleAxisd(delta[1] * ROTATION_SPEED, backTransformX));
819 fragmentRotation.rotate(
820 Eigen::AngleAxisd(delta[0] * ROTATION_SPEED, backTransformY));
821 fragmentRotation.translate(-centroid);
822
823 for (Index i = 0; i < m_molecule->atomCount(); ++i) {
824 if (moveSelected && !m_molecule->atomSelected(i))
825 continue;
826 else if (!moveSelected && m_molecule->atomSelected(i))
827 continue;
828
829 Vector3 currentPos = m_molecule->atomPosition3d(i);
830 m_molecule->setAtomPosition3d(
831 i, (fragmentRotation * currentPos.homogeneous()).head<3>());
832 }
833 }
834
835 void AutoOpt::axisRotate(Vector3 delta, Vector3 centroid, bool moveSelected)
836 {
837 // rotate by the x, y, z axes by delta[0], delta[1], delta[2]
838 // (in radians)
839 for (Index i = 0; i < m_molecule->atomCount(); ++i) {
840 if (moveSelected && !m_molecule->atomSelected(i))
841 continue;
842 else if (!moveSelected && m_molecule->atomSelected(i))
843 continue;
844
845 Vector3 currentPos = m_molecule->atomPosition3d(i);
846 Eigen::Projective3d fragmentRotation;
847 fragmentRotation.matrix().setIdentity();
848 fragmentRotation.translation() = centroid;
849
850 // Rotate around the x-axis
851 fragmentRotation.rotate(
852 Eigen::AngleAxisd(delta[0], Vector3(1.0, 0.0, 0.0)));
853 // Rotate around the y-axis
854 fragmentRotation.rotate(
855 Eigen::AngleAxisd(delta[1], Vector3(0.0, 1.0, 0.0)));
856 // Rotate around the z-axis
857 fragmentRotation.rotate(
858 Eigen::AngleAxisd(delta[2], Vector3(0.0, 0.0, 1.0)));
859
860 fragmentRotation.translate(-centroid);
861 m_molecule->setAtomPosition3d(
862 i, (fragmentRotation * currentPos.homogeneous()).head<3>());
863 }
864 }
865
866 void AutoOpt::tilt(Vector3 delta, Vector3 centroid)
867 {
868 // Rotate the selected atoms about the center
869 // rotate only selected primitives
870 Rendering::Camera* camera = &m_renderer->camera();
871 Eigen::Vector3d backTransformZ =
872 camera->modelView().cast<double>().linear().row(2).transpose().normalized();
873
874 Eigen::Projective3d fragmentRotation;
875 fragmentRotation.matrix().setIdentity();
876 fragmentRotation.translation() = centroid;
877 fragmentRotation.rotate(
878 Eigen::AngleAxisd(delta[0] * ROTATION_SPEED, backTransformZ));
879 fragmentRotation.translate(-centroid);
880
881 for (Index i = 0; i < m_molecule->atomCount(); ++i) {
882 if (!m_molecule->atomSelected(i))
883 continue;
884
885 Vector3 currentPos = m_molecule->atomPosition3d(i);
886 m_molecule->setAtomPosition3d(
887 i, (fragmentRotation * currentPos.homogeneous()).head<3>());
888 }
889 }
890
891 void AutoOpt::updatePressedButtons(QMouseEvent* e, bool release)
892 {
893 if (release)
894 m_pressedButtons &= e->buttons();
895 else
896 m_pressedButtons |= e->buttons();
897
898 // check for modifier keys (e.g., Mac)
899 if (e->buttons() & Qt::LeftButton && e->modifiers() == Qt::NoModifier) {
900 m_currentAction = Translation;
901 } else if (e->buttons() & Qt::MiddleButton ||
902 (e->buttons() & Qt::LeftButton &&
903 e->modifiers() == Qt::ShiftModifier)) {
904 m_currentAction = ZoomTilt;
905 } else if (e->buttons() & Qt::RightButton ||
906 (e->buttons() & Qt::LeftButton &&
907 (e->modifiers() == Qt::ControlModifier ||
908 e->modifiers() == Qt::MetaModifier))) {
909 m_currentAction = Rotation;
910 }
911 }
912
913 } // namespace Avogadro::QtPlugins