| 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 "forcefield.h" |
| 7 |
#include "forcefielddialog.h" |
| 8 |
#include "obmmenergy.h" |
| 9 |
#include "scriptenergy.h" |
| 10 |
|
| 11 |
#ifdef BUILD_GPL_PLUGINS |
| 12 |
#include "obenergy.h" |
| 13 |
#endif |
| 14 |
|
| 15 |
#include <QtCore/QDebug> |
| 16 |
#include <QtCore/QScopedPointer> |
| 17 |
#include <QtCore/QSettings> |
| 18 |
#include <QtCore/QThread> |
| 19 |
#include <QtCore/QTimer> |
| 20 |
|
| 21 |
#include <QAction> |
| 22 |
#include <QtWidgets/QMessageBox> |
| 23 |
|
| 24 |
#include <QProgressDialog> |
| 25 |
|
| 26 |
#include <avogadro/qtgui/avogadropython.h> |
| 27 |
#include <avogadro/qtgui/calcworker.h> |
| 28 |
#include <avogadro/qtgui/molecule.h> |
| 29 |
#include <avogadro/qtgui/rwmolecule.h> |
| 30 |
#include <avogadro/qtgui/utilities.h> |
| 31 |
|
| 32 |
#include <avogadro/qtgui/packagemanager.h> |
| 33 |
|
| 34 |
#include <avogadro/calc/energymanager.h> |
| 35 |
#include <avogadro/calc/energyoptimizer.h> |
| 36 |
#include <avogadro/calc/lennardjones.h> |
| 37 |
|
| 38 |
namespace Avogadro { |
| 39 |
namespace QtPlugins { |
| 40 |
|
| 41 |
using Avogadro::Calc::EnergyCalculator; |
| 42 |
using Avogadro::QtGui::Molecule; |
| 43 |
using Avogadro::QtGui::RWMolecule; |
| 44 |
|
| 45 |
const int energyAction = 0; |
| 46 |
const int optimizeAction = 1; |
| 47 |
const int configureAction = 2; |
| 48 |
const int freezeAction = 3; |
| 49 |
const int unfreezeAction = 4; |
| 50 |
const int constraintAction = 5; |
| 51 |
const int forcesAction = 6; |
| 52 |
const int fuseAction = 7; |
| 53 |
const int unfuseAction = 8; |
| 54 |
|
| 55 |
Forcefield::Forcefield(QObject* parent_) |
| 56 |
: ExtensionPlugin(parent_), m_method(nullptr) |
| 57 |
{ |
| 58 |
QSettings settings; |
| 59 |
settings.beginGroup("forcefield"); |
| 60 |
m_autodetect = settings.value("autodetect", true).toBool(); |
| 61 |
m_methodName = settings.value("forcefield", "LJ").toString().toStdString(); |
| 62 |
m_nSteps = settings.value("steps", 10).toInt(); |
| 63 |
m_maxSteps = settings.value("maxSteps", 250).toInt(); |
| 64 |
m_tolerance = settings.value("tolerance", 1.0e-4).toDouble(); |
| 65 |
m_gradientTolerance = settings.value("gradientTolerance", 1.0e-4).toDouble(); |
| 66 |
m_modelUserOptions = settings.value("modelUserOptions").toMap(); |
| 67 |
settings.endGroup(); |
| 68 |
|
| 69 |
QAction* action = new QAction(this); |
| 70 |
action->setEnabled(true); |
| 71 |
action->setText(tr("Optimize Geometry")); |
| 72 |
action->setShortcut(QKeySequence("Ctrl+Alt+O")); |
| 73 |
action->setData(optimizeAction); |
| 74 |
action->setProperty("menu priority", 920); |
| 75 |
connect(action, SIGNAL(triggered()), SLOT(optimize())); |
| 76 |
m_actions.push_back(action); |
| 77 |
|
| 78 |
action = new QAction(this); |
| 79 |
action->setEnabled(true); |
| 80 |
action->setText(tr("Energy")); // calculate energy |
| 81 |
action->setData(energyAction); |
| 82 |
action->setProperty("menu priority", 910); |
| 83 |
connect(action, SIGNAL(triggered()), SLOT(energy())); |
| 84 |
m_actions.push_back(action); |
| 85 |
|
| 86 |
action = new QAction(this); |
| 87 |
action->setEnabled(true); |
| 88 |
action->setText(tr("Forces")); // calculate gradients |
| 89 |
action->setData(forcesAction); |
| 90 |
action->setProperty("menu priority", 910); |
| 91 |
connect(action, SIGNAL(triggered()), SLOT(forces())); |
| 92 |
m_actions.push_back(action); |
| 93 |
|
| 94 |
action = new QAction(this); |
| 95 |
action->setEnabled(true); |
| 96 |
action->setText(tr("Configure…")); |
| 97 |
action->setData(configureAction); |
| 98 |
action->setProperty("menu priority", 900); |
| 99 |
connect(action, SIGNAL(triggered()), SLOT(showDialog())); |
| 100 |
m_actions.push_back(action); |
| 101 |
|
| 102 |
action = new QAction(this); |
| 103 |
action->setSeparator(true); |
| 104 |
m_actions.push_back(action); |
| 105 |
|
| 106 |
action = new QAction(this); |
| 107 |
action->setEnabled(true); |
| 108 |
action->setText(tr("Freeze Selected Atoms")); |
| 109 |
action->setData(freezeAction); |
| 110 |
action->setProperty("menu priority", 790); |
| 111 |
connect(action, SIGNAL(triggered()), SLOT(freezeSelected())); |
| 112 |
m_actions.push_back(action); |
| 113 |
|
| 114 |
action = new QAction(this); |
| 115 |
action->setEnabled(true); |
| 116 |
action->setText(tr("Freeze X", "freeze x-axis of selected atoms")); |
| 117 |
action->setData(unfreezeAction); |
| 118 |
action->setProperty("menu priority", 788); |
| 119 |
connect(action, SIGNAL(triggered()), SLOT(freezeX())); |
| 120 |
m_actions.push_back(action); |
| 121 |
|
| 122 |
action = new QAction(this); |
| 123 |
action->setEnabled(true); |
| 124 |
action->setText(tr("Freeze Y", "freeze y-axis of selected atoms")); |
| 125 |
action->setData(unfreezeAction); |
| 126 |
action->setProperty("menu priority", 787); |
| 127 |
connect(action, SIGNAL(triggered()), SLOT(freezeY())); |
| 128 |
m_actions.push_back(action); |
| 129 |
|
| 130 |
action = new QAction(this); |
| 131 |
action->setEnabled(true); |
| 132 |
action->setText(tr("Freeze Z", "freeze z-axis of selected atoms")); |
| 133 |
action->setData(unfreezeAction); |
| 134 |
action->setProperty("menu priority", 786); |
| 135 |
connect(action, SIGNAL(triggered()), SLOT(freezeZ())); |
| 136 |
m_actions.push_back(action); |
| 137 |
|
| 138 |
action = new QAction(this); |
| 139 |
action->setEnabled(true); |
| 140 |
action->setText(tr("Unfreeze Selected Atoms")); |
| 141 |
action->setData(unfreezeAction); |
| 142 |
action->setProperty("menu priority", 780); |
| 143 |
connect(action, SIGNAL(triggered()), SLOT(unfreezeSelected())); |
| 144 |
m_actions.push_back(action); |
| 145 |
|
| 146 |
action = new QAction(this); |
| 147 |
action->setEnabled(true); |
| 148 |
action->setText( |
| 149 |
tr("Fuse Selected Atoms", "freeze atomic distances / glue atoms together")); |
| 150 |
action->setData(fuseAction); |
| 151 |
action->setProperty("menu priority", 770); |
| 152 |
connect(action, SIGNAL(triggered()), SLOT(fuseSelected())); |
| 153 |
m_actions.push_back(action); |
| 154 |
|
| 155 |
action = new QAction(this); |
| 156 |
action->setEnabled(true); |
| 157 |
action->setText(tr("Unfuse Selected Atoms", |
| 158 |
"freeze atomic distances / glue atoms together")); |
| 159 |
action->setData(unfuseAction); |
| 160 |
action->setProperty("menu priority", 760); |
| 161 |
connect(action, SIGNAL(triggered()), SLOT(unfuseSelected())); |
| 162 |
m_actions.push_back(action); |
| 163 |
|
| 164 |
// initialize the calculators |
| 165 |
|
| 166 |
// prefer to use Python interface scripts if available |
| 167 |
refreshScripts(); |
| 168 |
|
| 169 |
// Connect to PackageManager for pyproject.toml-based packages |
| 170 |
auto* pm = QtGui::PackageManager::instance(); |
| 171 |
connect(pm, &QtGui::PackageManager::featureRegistered, this, |
| 172 |
&Forcefield::registerFeature); |
| 173 |
connect(pm, &QtGui::PackageManager::featureRemoved, this, |
| 174 |
&Forcefield::unregisterFeature); |
| 175 |
|
| 176 |
// add the openbabel calculators in case they don't exist |
| 177 |
#ifdef BUILD_GPL_PLUGINS |
| 178 |
// These directly use Open Babel and are fast |
| 179 |
qDebug() << " registering GPL plugins"; |
| 180 |
|
| 181 |
// sanity check, try an energy for a (bad) water molecule |
| 182 |
Molecule water; |
| 183 |
water.addAtom(6); |
| 184 |
water.addAtom(1); |
| 185 |
water.addAtom(1); |
| 186 |
water.addBond(0, 1); |
| 187 |
water.addBond(0, 2); |
| 188 |
|
| 189 |
auto ob = new OBEnergy("MMFF94"); |
| 190 |
ob->setMolecule(&water); |
| 191 |
Eigen::VectorXd positions(3 * 3); |
| 192 |
positions << 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0; |
| 193 |
Real energy = ob->value(positions); |
| 194 |
if (energy != 0.0) { |
| 195 |
Calc::EnergyManager::registerModel(ob); |
| 196 |
} else { |
| 197 |
delete ob; |
| 198 |
} |
| 199 |
|
| 200 |
// check GAFF |
| 201 |
ob = new OBEnergy("GAFF"); |
| 202 |
ob->setMolecule(&water); |
| 203 |
energy = ob->value(positions); |
| 204 |
if (energy != 0.0) { |
| 205 |
Calc::EnergyManager::registerModel(ob); |
| 206 |
} else { |
| 207 |
delete ob; |
| 208 |
} |
| 209 |
#else |
| 210 |
// These call obmm and can be slower |
| 211 |
qDebug() << " registering obmm plugins"; |
| 212 |
Calc::EnergyManager::registerModel(new OBMMEnergy("MMFF94")); |
| 213 |
Calc::EnergyManager::registerModel(new OBMMEnergy("GAFF")); |
| 214 |
#endif |
| 215 |
} |
| 216 |
|
| 217 |
Forcefield::~Forcefield() |
| 218 |
{ |
| 219 |
cleanupWorker(); |
| 220 |
} |
| 221 |
|
| 222 |
QList<QAction*> Forcefield::actions() const |
| 223 |
{ |
| 224 |
return m_actions; |
| 225 |
} |
| 226 |
|
| 227 |
QStringList Forcefield::menuPath(QAction* action) const |
| 228 |
{ |
| 229 |
QStringList path; |
| 230 |
if (action->data().toInt() == optimizeAction) |
| 231 |
path << tr("&Extensions"); |
| 232 |
else |
| 233 |
path << tr("&Extensions") << tr("&Calculate"); |
| 234 |
|
| 235 |
return path; |
| 236 |
} |
| 237 |
|
| 238 |
void Forcefield::showDialog() |
| 239 |
{ |
| 240 |
QStringList forceFields; |
| 241 |
QVariantMap modelUserOptionSchemas; |
| 242 |
auto list = |
| 243 |
Calc::EnergyManager::instance().identifiersForMolecule(*m_molecule); |
| 244 |
for (auto option : list) { |
| 245 |
const QString optionName = option.c_str(); |
| 246 |
forceFields << optionName; |
| 247 |
|
| 248 |
QScopedPointer<EnergyCalculator> model( |
| 249 |
Calc::EnergyManager::instance().model(option)); |
| 250 |
if (model) { |
| 251 |
const std::string schema = model->userOptions(); |
| 252 |
if (!schema.empty()) |
| 253 |
modelUserOptionSchemas.insert(optionName, |
| 254 |
QString::fromStdString(schema)); |
| 255 |
} |
| 256 |
} |
| 257 |
|
| 258 |
QSettings settings; |
| 259 |
QVariantMap options; |
| 260 |
options["forcefield"] = m_methodName.c_str(); |
| 261 |
options["nSteps"] = m_nSteps; |
| 262 |
options["maxSteps"] = m_maxSteps; |
| 263 |
options["tolerance"] = m_tolerance; |
| 264 |
options["gradientTolerance"] = m_gradientTolerance; |
| 265 |
options["autodetect"] = m_autodetect; |
| 266 |
options["modelUserOptions"] = m_modelUserOptions; |
| 267 |
options["modelUserOptionsSchemas"] = modelUserOptionSchemas; |
| 268 |
|
| 269 |
QVariantMap results = ForceFieldDialog::prompt( |
| 270 |
nullptr, forceFields, options, recommendedForceField().c_str()); |
| 271 |
|
| 272 |
if (!results.isEmpty()) { |
| 273 |
// update settings |
| 274 |
settings.beginGroup("forcefield"); |
| 275 |
m_methodName = results["forcefield"].toString().toStdString(); |
| 276 |
settings.setValue("forcefield", m_methodName.c_str()); |
| 277 |
|
| 278 |
m_maxSteps = results["maxSteps"].toInt(); |
| 279 |
settings.setValue("maxSteps", m_maxSteps); |
| 280 |
m_tolerance = results["tolerance"].toDouble(); |
| 281 |
settings.setValue("tolerance", m_tolerance); |
| 282 |
m_gradientTolerance = results["gradientTolerance"].toDouble(); |
| 283 |
settings.setValue("gradientTolerance", m_gradientTolerance); |
| 284 |
m_autodetect = results["autodetect"].toBool(); |
| 285 |
settings.setValue("autodetect", m_autodetect); |
| 286 |
m_modelUserOptions = results["modelUserOptions"].toMap(); |
| 287 |
settings.setValue("modelUserOptions", m_modelUserOptions); |
| 288 |
settings.endGroup(); |
| 289 |
} |
| 290 |
setupMethod(); |
| 291 |
} |
| 292 |
|
| 293 |
void Forcefield::setMolecule(QtGui::Molecule* mol) |
| 294 |
{ |
| 295 |
if (mol == nullptr || m_molecule == mol) |
| 296 |
return; |
| 297 |
|
| 298 |
m_molecule = mol; |
| 299 |
|
| 300 |
// TODO: connect to molecule changes, e.g. selection |
| 301 |
// connect(m_molecule, SIGNAL(changed(uint)), SLOT(updateActions())); |
| 302 |
} |
| 303 |
|
| 304 |
void Forcefield::updateActions() |
| 305 |
{ |
| 306 |
if (m_molecule == nullptr) |
| 307 |
return; |
| 308 |
|
| 309 |
bool noSelection = m_molecule->isSelectionEmpty(); |
| 310 |
foreach (QAction* action, m_actions) { |
| 311 |
switch (action->data().toInt()) { |
| 312 |
case freezeAction: |
| 313 |
case unfreezeAction: |
| 314 |
case fuseAction: |
| 315 |
case unfuseAction: |
| 316 |
action->setEnabled(!noSelection); |
| 317 |
break; |
| 318 |
default: |
| 319 |
break; |
| 320 |
} |
| 321 |
} |
| 322 |
} |
| 323 |
|
| 324 |
void Forcefield::setupMethod() |
| 325 |
{ |
| 326 |
if (m_molecule == nullptr) |
| 327 |
return; // nothing to do until its set |
| 328 |
|
| 329 |
if (m_autodetect) |
| 330 |
m_methodName = recommendedForceField(); |
| 331 |
|
| 332 |
// check if m_methodName even exists (e.g., saved preference) |
| 333 |
// or if that method doesn't work for this (e.g., unit cell, etc.) |
| 334 |
auto list = |
| 335 |
Calc::EnergyManager::instance().identifiersForMolecule(*m_molecule); |
| 336 |
bool found = false; |
| 337 |
for (auto option : list) { |
| 338 |
if (option == m_methodName) { |
| 339 |
found = true; |
| 340 |
break; |
| 341 |
} |
| 342 |
} |
| 343 |
|
| 344 |
// fall back to recommended if not found (LJ will always work) |
| 345 |
if (!found) { |
| 346 |
m_methodName = recommendedForceField(); |
| 347 |
} |
| 348 |
|
| 349 |
if (m_method != nullptr) { |
| 350 |
delete m_method; // delete the previous one |
| 351 |
} |
| 352 |
m_method = Calc::EnergyManager::instance().model(m_methodName); |
| 353 |
|
| 354 |
if (m_method != nullptr) { |
| 355 |
const QString methodId = QString::fromStdString(m_methodName); |
| 356 |
const QString modelOptions = m_modelUserOptions.value(methodId).toString(); |
| 357 |
if (!modelOptions.trimmed().isEmpty() && |
| 358 |
!m_method->setUserOptions(modelOptions.toStdString())) { |
| 359 |
qWarning() << "Failed to parse user options for force field" << methodId; |
| 360 |
} |
| 361 |
m_method->setMolecule(m_molecule); |
| 362 |
} |
| 363 |
} |
| 364 |
|
| 365 |
void Forcefield::setupConstraints() |
| 366 |
{ |
| 367 |
if (m_molecule == nullptr || m_method == nullptr) |
| 368 |
return; // nothing to do |
| 369 |
|
| 370 |
auto n = m_molecule->atomCount(); |
| 371 |
|
| 372 |
// first set the frozen coordinate mask |
| 373 |
auto mask = m_molecule->frozenAtomMask(); |
| 374 |
if (mask.rows() != static_cast<Eigen::Index>(3 * n)) { |
| 375 |
// set the mask to all ones |
| 376 |
mask = Eigen::VectorXd::Ones(static_cast<Eigen::Index>(3 * n)); |
| 377 |
} |
| 378 |
m_method->setMolecule(m_molecule); |
| 379 |
m_method->setMask(mask); |
| 380 |
|
| 381 |
// now set the constraints |
| 382 |
m_method->setConstraints(m_molecule->constraints()); |
| 383 |
} |
| 384 |
|
| 385 |
void Forcefield::cleanupWorker() |
| 386 |
{ |
| 387 |
if (m_workerThread) { |
| 388 |
m_workerThread->quit(); |
| 389 |
m_workerThread->wait(5000); |
| 390 |
// deleteLater handles the worker and thread via finished() connections |
| 391 |
m_workerThread = nullptr; |
| 392 |
m_worker = nullptr; |
| 393 |
} |
| 394 |
if (m_progressDialog) { |
| 395 |
m_progressDialog->hide(); |
| 396 |
m_progressDialog->deleteLater(); |
| 397 |
m_progressDialog = nullptr; |
| 398 |
} |
| 399 |
m_optimizing = false; |
| 400 |
} |
| 401 |
|
| 402 |
void Forcefield::startWorker() |
| 403 |
{ |
| 404 |
cleanupWorker(); |
| 405 |
|
| 406 |
auto n = m_molecule->atomCount(); |
| 407 |
|
| 408 |
// Build the frozen atom mask |
| 409 |
auto mask = m_molecule->frozenAtomMask(); |
| 410 |
if (mask.rows() != static_cast<Eigen::Index>(3 * n)) |
| 411 |
mask = Eigen::VectorXd::Ones(static_cast<Eigen::Index>(3 * n)); |
| 412 |
|
| 413 |
auto constraints = m_molecule->constraints(); |
| 414 |
|
| 415 |
// Create a fresh calculator clone for the worker thread |
| 416 |
auto* calc = Calc::EnergyManager::instance().model(m_methodName); |
| 417 |
if (calc == nullptr) |
| 418 |
return; |
| 419 |
|
| 420 |
// Apply user options to the clone |
| 421 |
const QString methodId = QString::fromStdString(m_methodName); |
| 422 |
const QString modelOptions = m_modelUserOptions.value(methodId).toString(); |
| 423 |
if (!modelOptions.trimmed().isEmpty()) |
| 424 |
calc->setUserOptions(modelOptions.toStdString()); |
| 425 |
|
| 426 |
// Create a molecule snapshot (topology only, positions set separately) |
| 427 |
Core::Molecule snapshot = static_cast<const Core::Molecule&>(*m_molecule); |
| 428 |
|
| 429 |
// Set up the worker thread |
| 430 |
m_workerThread = new QThread(this); |
| 431 |
m_worker = new QtGui::CalcWorker(); |
| 432 |
m_worker->moveToThread(m_workerThread); |
| 433 |
|
| 434 |
connect(m_workerThread, &QThread::finished, m_worker, &QObject::deleteLater); |
| 435 |
m_workerThread->start(); |
| 436 |
|
| 437 |
// Store args for initCalculator — caller must connect signals first, |
| 438 |
// then invoke initCalculator via sendInitCalculator(). |
| 439 |
m_pendingCalc = calc; |
| 440 |
m_pendingSnapshot = snapshot; |
| 441 |
m_pendingMask = mask; |
| 442 |
m_pendingConstraints = constraints; |
| 443 |
} |
| 444 |
|
| 445 |
void Forcefield::sendInitCalculator() |
| 446 |
{ |
| 447 |
if (!m_worker || !m_pendingCalc) |
| 448 |
return; |
| 449 |
|
| 450 |
QMetaObject::invokeMethod( |
| 451 |
m_worker, "initCalculator", Qt::QueuedConnection, |
| 452 |
Q_ARG(Avogadro::Calc::EnergyCalculator*, m_pendingCalc), |
| 453 |
Q_ARG(Avogadro::Core::Molecule, m_pendingSnapshot), |
| 454 |
Q_ARG(Eigen::VectorXd, m_pendingMask), |
| 455 |
Q_ARG(std::vector<Avogadro::Core::Constraint>, m_pendingConstraints)); |
| 456 |
m_pendingCalc = nullptr; |
| 457 |
} |
| 458 |
|
| 459 |
void Forcefield::optimize() |
| 460 |
{ |
| 461 |
if (m_molecule == nullptr || m_optimizing) |
| 462 |
return; |
| 463 |
|
| 464 |
if (m_method == nullptr) |
| 465 |
setupMethod(); |
| 466 |
if (m_method == nullptr) |
| 467 |
return; |
| 468 |
|
| 469 |
if (!m_molecule->atomCount()) { |
| 470 |
QMessageBox::information(nullptr, tr("Avogadro"), |
| 471 |
tr("No atoms provided for optimization")); |
| 472 |
return; |
| 473 |
} |
| 474 |
|
| 475 |
m_currentStep = 0; |
| 476 |
|
| 477 |
// merge all coordinate updates into one undo step |
| 478 |
m_molecule->undoMolecule()->setInteractive(true); |
| 479 |
|
| 480 |
// Set up optimization options |
| 481 |
m_optOptions.algorithm = Calc::OptimizationAlgorithm::Lbfgs; |
| 482 |
m_optOptions.chunkIterations = 5; |
| 483 |
|
| 484 |
// Snapshot current positions |
| 485 |
auto n = m_molecule->atomCount(); |
| 486 |
Core::Array<Vector3> pos = m_molecule->atomPositions3d(); |
| 487 |
Eigen::Map<Eigen::VectorXd> map(pos[0].data(), 3 * n); |
| 488 |
m_lastPositions = map; |
| 489 |
m_lastEnergy = 0.0; |
| 490 |
|
| 491 |
// Start the worker first (calls cleanupWorker() which resets m_optimizing) |
| 492 |
startWorker(); |
| 493 |
|
| 494 |
// Set m_optimizing AFTER startWorker, since cleanupWorker resets it |
| 495 |
m_optimizing = true; |
| 496 |
|
| 497 |
// Create progress dialog |
| 498 |
int totalChunks = static_cast<int>(m_maxSteps / m_optOptions.chunkIterations); |
| 499 |
m_progressDialog = |
| 500 |
new QProgressDialog(qobject_cast<QWidget*>(this->parent())); |
| 501 |
m_progressDialog->setWindowTitle(tr("Optimize Geometry")); |
| 502 |
// cancel button text is set automatically |
| 503 |
m_progressDialog->setRange(0, totalChunks); |
| 504 |
m_progressDialog->setWindowModality(Qt::WindowModal); |
| 505 |
m_progressDialog->setMinimumDuration(0); |
| 506 |
m_progressDialog->show(); |
| 507 |
|
| 508 |
connect(m_progressDialog, &QProgressDialog::canceled, this, [this]() { |
| 509 |
if (m_worker) |
| 510 |
m_worker->cancel(); |
| 511 |
cleanupWorker(); |
| 512 |
if (m_molecule) |
| 513 |
m_molecule->undoMolecule()->setInteractive(false); |
| 514 |
}); |
| 515 |
|
| 516 |
connect(m_worker, &QtGui::CalcWorker::calculatorReady, this, |
| 517 |
&Forcefield::onWorkerReady); |
| 518 |
connect(m_worker, &QtGui::CalcWorker::optimizeFinished, this, |
| 519 |
&Forcefield::onOptimizeChunkDone); |
| 520 |
|
| 521 |
sendInitCalculator(); |
| 522 |
} |
| 523 |
|
| 524 |
void Forcefield::onWorkerReady() |
| 525 |
{ |
| 526 |
if (!m_optimizing || !m_worker) |
| 527 |
return; |
| 528 |
|
| 529 |
// Send the first optimization chunk |
| 530 |
QMetaObject::invokeMethod( |
| 531 |
m_worker, "runOptimizeChunk", Qt::QueuedConnection, |
| 532 |
Q_ARG(Eigen::VectorXd, m_lastPositions), |
| 533 |
Q_ARG(Avogadro::Calc::OptimizationOptions, m_optOptions)); |
| 534 |
} |
| 535 |
|
| 536 |
void Forcefield::onOptimizeChunkDone(Eigen::VectorXd positions, |
| 537 |
Eigen::VectorXd gradient, double energy, |
| 538 |
bool converged) |
| 539 |
{ |
| 540 |
if (!m_optimizing || m_molecule == nullptr) |
| 541 |
return; |
| 542 |
|
| 543 |
auto n = m_molecule->atomCount(); |
| 544 |
m_currentStep++; |
| 545 |
|
| 546 |
if (m_progressDialog) { |
| 547 |
m_progressDialog->setValue(m_currentStep); |
| 548 |
m_progressDialog->setLabelText( |
| 549 |
tr("Energy: %L1", "force field energy").arg(energy, 0, 'f', 3)); |
| 550 |
} |
| 551 |
|
| 552 |
#ifndef NDEBUG |
| 553 |
qDebug() << " optimize " << m_currentStep << energy |
| 554 |
<< " gradNorm: " << gradient.norm(); |
| 555 |
#endif |
| 556 |
|
| 557 |
// Update coordinates if valid |
| 558 |
if (std::isfinite(energy) && positions.allFinite()) { |
| 559 |
Core::Array<Vector3> pos(n); |
| 560 |
Eigen::Map<Eigen::VectorXd>(pos[0].data(), 3 * n) = positions; |
| 561 |
|
| 562 |
Core::Array<Vector3> forces(n); |
| 563 |
if (gradient.size() == 3 * static_cast<Eigen::Index>(n)) |
| 564 |
Eigen::Map<Eigen::VectorXd>(forces[0].data(), 3 * n) = -gradient; |
| 565 |
|
| 566 |
m_molecule->undoMolecule()->setAtomPositions3d(pos, |
| 567 |
tr("Optimize Geometry")); |
| 568 |
m_molecule->setForceVectors(forces); |
| 569 |
Molecule::MoleculeChanges changes = Molecule::Atoms | Molecule::Modified; |
| 570 |
m_molecule->emitChanged(changes); |
| 571 |
|
| 572 |
m_lastPositions = positions; |
| 573 |
} else { |
| 574 |
qDebug() << "Non-finite energy, stopping optimization" << energy; |
| 575 |
converged = true; |
| 576 |
} |
| 577 |
|
| 578 |
// Check convergence criteria |
| 579 |
bool done = converged; |
| 580 |
if (!done && gradient.size() > 0) { |
| 581 |
if (fabs(gradient.maxCoeff()) < m_gradientTolerance) |
| 582 |
done = true; |
| 583 |
if (m_lastEnergy != 0.0 && fabs(energy - m_lastEnergy) < m_tolerance) |
| 584 |
done = true; |
| 585 |
} |
| 586 |
|
| 587 |
int totalChunks = static_cast<int>(m_maxSteps / m_optOptions.chunkIterations); |
| 588 |
if (m_currentStep >= totalChunks) |
| 589 |
done = true; |
| 590 |
|
| 591 |
m_lastEnergy = energy; |
| 592 |
|
| 593 |
if (done || (m_progressDialog && m_progressDialog->wasCanceled())) { |
| 594 |
// Optimization complete |
| 595 |
m_molecule->undoMolecule()->setInteractive(false); |
| 596 |
cleanupWorker(); |
| 597 |
} else { |
| 598 |
// Request next chunk |
| 599 |
QMetaObject::invokeMethod( |
| 600 |
m_worker, "runOptimizeChunk", Qt::QueuedConnection, |
| 601 |
Q_ARG(Eigen::VectorXd, m_lastPositions), |
| 602 |
Q_ARG(Avogadro::Calc::OptimizationOptions, m_optOptions)); |
| 603 |
} |
| 604 |
} |
| 605 |
|
| 606 |
void Forcefield::energy() |
| 607 |
{ |
| 608 |
if (m_molecule == nullptr || m_optimizing) |
| 609 |
return; |
| 610 |
|
| 611 |
if (m_method == nullptr) |
| 612 |
setupMethod(); |
| 613 |
if (m_method == nullptr) |
| 614 |
return; |
| 615 |
|
| 616 |
auto n = m_molecule->atomCount(); |
| 617 |
Core::Array<Vector3> pos = m_molecule->atomPositions3d(); |
| 618 |
Eigen::Map<Eigen::VectorXd> map(pos[0].data(), 3 * n); |
| 619 |
Eigen::VectorXd positions = map; |
| 620 |
|
| 621 |
startWorker(); |
| 622 |
|
| 623 |
connect( |
| 624 |
m_worker, &QtGui::CalcWorker::calculatorReady, this, [this, positions]() { |
| 625 |
QMetaObject::invokeMethod(m_worker, "runEvaluate", Qt::QueuedConnection, |
| 626 |
Q_ARG(Eigen::VectorXd, positions), |
| 627 |
Q_ARG(bool, false)); |
| 628 |
}); |
| 629 |
connect(m_worker, &QtGui::CalcWorker::evaluateFinished, this, |
| 630 |
&Forcefield::onEnergyDone); |
| 631 |
|
| 632 |
sendInitCalculator(); |
| 633 |
} |
| 634 |
|
| 635 |
void Forcefield::onEnergyDone(Eigen::VectorXd gradient, double energy) |
| 636 |
{ |
| 637 |
Q_UNUSED(gradient); |
| 638 |
QString msg(tr("%1 Energy = %L2").arg(m_methodName.c_str()).arg(energy)); |
| 639 |
cleanupWorker(); |
| 640 |
QMessageBox::information(nullptr, tr("Avogadro"), msg); |
| 641 |
} |
| 642 |
|
| 643 |
void Forcefield::forces() |
| 644 |
{ |
| 645 |
if (m_molecule == nullptr || m_optimizing) |
| 646 |
return; |
| 647 |
|
| 648 |
if (m_method == nullptr) |
| 649 |
setupMethod(); |
| 650 |
if (m_method == nullptr) |
| 651 |
return; |
| 652 |
|
| 653 |
auto n = m_molecule->atomCount(); |
| 654 |
Core::Array<Vector3> pos = m_molecule->atomPositions3d(); |
| 655 |
Eigen::Map<Eigen::VectorXd> map(pos[0].data(), 3 * n); |
| 656 |
Eigen::VectorXd positions = map; |
| 657 |
|
| 658 |
startWorker(); |
| 659 |
|
| 660 |
connect( |
| 661 |
m_worker, &QtGui::CalcWorker::calculatorReady, this, [this, positions]() { |
| 662 |
QMetaObject::invokeMethod(m_worker, "runGradient", Qt::QueuedConnection, |
| 663 |
Q_ARG(Eigen::VectorXd, positions)); |
| 664 |
}); |
| 665 |
connect(m_worker, &QtGui::CalcWorker::evaluateFinished, this, |
| 666 |
&Forcefield::onForcesDone); |
| 667 |
|
| 668 |
sendInitCalculator(); |
| 669 |
} |
| 670 |
|
| 671 |
void Forcefield::onForcesDone(Eigen::VectorXd gradient, double energy) |
| 672 |
{ |
| 673 |
Q_UNUSED(energy); |
| 674 |
|
| 675 |
if (m_molecule == nullptr) { |
| 676 |
cleanupWorker(); |
| 677 |
return; |
| 678 |
} |
| 679 |
|
| 680 |
auto n = m_molecule->atomCount(); |
| 681 |
|
| 682 |
Core::Array<Vector3> forces(n); |
| 683 |
if (gradient.size() == 3 * static_cast<Eigen::Index>(n)) |
| 684 |
Eigen::Map<Eigen::VectorXd>(forces[0].data(), 3 * n) = -gradient; |
| 685 |
|
| 686 |
m_molecule->setForceVectors(forces); |
| 687 |
Molecule::MoleculeChanges changes = Molecule::Atoms | Molecule::Modified; |
| 688 |
m_molecule->emitChanged(changes); |
| 689 |
|
| 690 |
QString msg( |
| 691 |
tr("%1 Force Norm = %L2").arg(m_methodName.c_str()).arg(gradient.norm())); |
| 692 |
cleanupWorker(); |
| 693 |
QMessageBox::information(nullptr, tr("Avogadro"), msg); |
| 694 |
} |
| 695 |
|
| 696 |
std::string Forcefield::recommendedForceField() const |
| 697 |
{ |
| 698 |
// if we have a unit cell, we need to use the LJ calculator |
| 699 |
// (implementing something better would be nice) |
| 700 |
if (m_molecule == nullptr || m_molecule->unitCell() != nullptr) |
| 701 |
return "LJ"; |
| 702 |
|
| 703 |
// otherwise, let's see what identifers are returned |
| 704 |
auto list = |
| 705 |
Calc::EnergyManager::instance().identifiersForMolecule(*m_molecule); |
| 706 |
if (list.empty()) |
| 707 |
return "LJ"; // this will always work |
| 708 |
|
| 709 |
// iterate to see what we have |
| 710 |
std::string bestOption; |
| 711 |
for (auto option : list) { |
| 712 |
// GAFF is better than MMFF94 which is better than UFF |
| 713 |
if (option == "UFF" && bestOption != "GAFF" && bestOption != "MMFF94") |
| 714 |
bestOption = option; |
| 715 |
if (option == "MMFF94" && bestOption != "GAFF") |
| 716 |
bestOption = option; |
| 717 |
} |
| 718 |
if (!bestOption.empty()) |
| 719 |
return bestOption; |
| 720 |
else |
| 721 |
return "LJ"; // this will always work |
| 722 |
} |
| 723 |
|
| 724 |
void Forcefield::freezeSelected() |
| 725 |
{ |
| 726 |
if (m_molecule == nullptr || m_molecule->isSelectionEmpty()) |
| 727 |
return; // nothing to do until there's a valid selection |
| 728 |
|
| 729 |
auto numAtoms = m_molecule->atomCount(); |
| 730 |
// now freeze the specified atoms |
| 731 |
for (Index i = 0; i < numAtoms; ++i) { |
| 732 |
if (m_molecule->atomSelected(i)) { |
| 733 |
m_molecule->setFrozenAtom(i, true); |
| 734 |
} |
| 735 |
} |
| 736 |
|
| 737 |
m_molecule->emitChanged(QtGui::Molecule::Constraints); |
| 738 |
} |
| 739 |
|
| 740 |
void Forcefield::freezeAxis(int axis) |
| 741 |
{ |
| 742 |
if (m_molecule == nullptr || m_molecule->isSelectionEmpty()) |
| 743 |
return; // nothing to do until there's a valid selection |
| 744 |
|
| 745 |
auto numAtoms = m_molecule->atomCount(); |
| 746 |
// now freeze the specified atoms |
| 747 |
for (Index i = 0; i < numAtoms; ++i) { |
| 748 |
if (m_molecule->atomSelected(i)) { |
| 749 |
m_molecule->setFrozenAtomAxis(i, axis, true); |
| 750 |
} |
| 751 |
} |
| 752 |
|
| 753 |
m_molecule->emitChanged(QtGui::Molecule::Constraints); |
| 754 |
} |
| 755 |
|
| 756 |
void Forcefield::freezeX() |
| 757 |
{ |
| 758 |
freezeAxis(0); |
| 759 |
} |
| 760 |
void Forcefield::freezeY() |
| 761 |
{ |
| 762 |
freezeAxis(1); |
| 763 |
} |
| 764 |
void Forcefield::freezeZ() |
| 765 |
{ |
| 766 |
freezeAxis(2); |
| 767 |
} |
| 768 |
|
| 769 |
void Forcefield::unfreezeSelected() |
| 770 |
{ |
| 771 |
if (m_molecule == nullptr || m_molecule->isSelectionEmpty()) |
| 772 |
return; // nothing to do until there's a valid selection |
| 773 |
|
| 774 |
auto numAtoms = m_molecule->atomCount(); |
| 775 |
// now freeze the specified atoms |
| 776 |
for (Index i = 0; i < numAtoms; ++i) { |
| 777 |
if (m_molecule->atomSelected(i)) { |
| 778 |
m_molecule->setFrozenAtom(i, false); |
| 779 |
} |
| 780 |
} |
| 781 |
|
| 782 |
m_molecule->emitChanged(QtGui::Molecule::Constraints); |
| 783 |
} |
| 784 |
|
| 785 |
void Forcefield::unfuseSelected() |
| 786 |
{ |
| 787 |
if (m_molecule == nullptr || m_molecule->isSelectionEmpty()) |
| 788 |
return; // nothing to do until there's a valid selection |
| 789 |
|
| 790 |
auto numAtoms = m_molecule->atomCount(); |
| 791 |
// now remove constraints between the specified atoms |
| 792 |
for (Index i = 0; i < numAtoms; ++i) { |
| 793 |
if (m_molecule->atomSelected(i)) { |
| 794 |
for (Index j = i + 1; j < numAtoms; ++j) { |
| 795 |
if (m_molecule->atomSelected(j)) { |
| 796 |
m_molecule->removeConstraint(i, j); |
| 797 |
} |
| 798 |
} |
| 799 |
} |
| 800 |
} |
| 801 |
|
| 802 |
m_molecule->emitChanged(QtGui::Molecule::Constraints); |
| 803 |
} |
| 804 |
|
| 805 |
void Forcefield::fuseSelected() |
| 806 |
{ |
| 807 |
if (m_molecule == nullptr || m_molecule->isSelectionEmpty()) |
| 808 |
return; // nothing to do until there's a valid selection |
| 809 |
|
| 810 |
// loop through all selected atom pairs |
| 811 |
auto numAtoms = m_molecule->atomCount(); |
| 812 |
for (Index i = 0; i < numAtoms; ++i) { |
| 813 |
if (m_molecule->atomSelected(i)) { |
| 814 |
Vector3 iPos = m_molecule->atomPosition3d(i); |
| 815 |
|
| 816 |
for (Index j = i + 1; j < numAtoms; ++j) { |
| 817 |
if (m_molecule->atomSelected(j)) { |
| 818 |
// both selected, set the constraint |
| 819 |
Vector3 jPos = m_molecule->atomPosition3d(j); |
| 820 |
Real distance = (iPos - jPos).norm(); |
| 821 |
Core::Constraint constraint(i, j); |
| 822 |
constraint.setValue(distance); |
| 823 |
|
| 824 |
m_molecule->addConstraint(constraint); |
| 825 |
} |
| 826 |
} |
| 827 |
} |
| 828 |
} |
| 829 |
|
| 830 |
m_molecule->emitChanged(QtGui::Molecule::Constraints); |
| 831 |
} |
| 832 |
|
| 833 |
void Forcefield::refreshScripts() |
| 834 |
{ |
| 835 |
unregisterScripts(); |
| 836 |
qDeleteAll(m_scripts); |
| 837 |
m_scripts.clear(); |
| 838 |
m_packageScripts.clear(); |
| 839 |
registerScripts(); |
| 840 |
} |
| 841 |
|
| 842 |
void Forcefield::unregisterScripts() |
| 843 |
{ |
| 844 |
for (auto* script : m_scripts) |
| 845 |
Calc::EnergyManager::unregisterModel(script->identifier()); |
| 846 |
} |
| 847 |
|
| 848 |
void Forcefield::registerScripts() |
| 849 |
{ |
| 850 |
for (auto* script : m_scripts) { |
| 851 |
qDebug() << " register " << script->identifier().c_str(); |
| 852 |
|
| 853 |
if (!Calc::EnergyManager::registerModel(script->newInstance())) { |
| 854 |
qDebug() << "Could not register model" << script->identifier().c_str() |
| 855 |
<< "due to name conflict."; |
| 856 |
} |
| 857 |
} |
| 858 |
} |
| 859 |
|
| 860 |
void Forcefield::registerFeature(const QString& type, const QString& packageDir, |
| 861 |
const QString& command, |
| 862 |
const QString& identifier, |
| 863 |
const QVariantMap& metadata) |
| 864 |
{ |
| 865 |
if (type != QLatin1String("energy-models")) |
| 866 |
return; |
| 867 |
|
| 868 |
auto* model = new ScriptEnergy(); |
| 869 |
model->setPackageInfo(packageDir, command, identifier); |
| 870 |
model->readMetaData(metadata); |
| 871 |
if (model->isValid()) { |
| 872 |
QString managerId = QString::fromStdString(model->identifier()); |
| 873 |
auto* newModel = model->newInstance(); |
| 874 |
if (!Calc::EnergyManager::registerModel(newModel)) { |
| 875 |
qDebug() << "Could not register energy model" << identifier |
| 876 |
<< "due to name conflict."; |
| 877 |
delete newModel; |
| 878 |
delete model; |
| 879 |
} else { |
| 880 |
m_scripts.push_back(model); |
| 881 |
m_packageScripts.insert(QtGui::PackageManager::packageFeatureKey( |
| 882 |
packageDir, command, identifier), |
| 883 |
managerId); |
| 884 |
} |
| 885 |
} else { |
| 886 |
delete model; |
| 887 |
} |
| 888 |
} |
| 889 |
|
| 890 |
void Forcefield::unregisterFeature(const QString& type, |
| 891 |
const QString& packageDir, |
| 892 |
const QString& command, |
| 893 |
const QString& identifier) |
| 894 |
{ |
| 895 |
if (type != QLatin1String("energy-models")) |
| 896 |
return; |
| 897 |
|
| 898 |
const QString featureKey = |
| 899 |
QtGui::PackageManager::packageFeatureKey(packageDir, command, identifier); |
| 900 |
const QList<QString> managerIds = m_packageScripts.values(featureKey); |
| 901 |
if (managerIds.isEmpty()) |
| 902 |
return; |
| 903 |
|
| 904 |
m_packageScripts.remove(featureKey); |
| 905 |
for (const QString& managerId : managerIds) { |
| 906 |
Calc::EnergyManager::unregisterModel(managerId.toStdString()); |
| 907 |
for (int i = m_scripts.size() - 1; i >= 0; --i) { |
| 908 |
if (QString::fromStdString(m_scripts[i]->identifier()) == managerId) |
| 909 |
delete m_scripts.takeAt(i); |
| 910 |
} |
| 911 |
} |
| 912 |
} |
| 913 |
|
| 914 |
} // namespace QtPlugins |
| 915 |
} // namespace Avogadro |