| 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 "scriptenergy.h" |
| 7 |
|
| 8 |
#include <avogadro/core/molecule.h> |
| 9 |
#include <avogadro/qtgui/packagemanager.h> |
| 10 |
#include <avogadro/qtgui/pythonscript.h> |
| 11 |
|
| 12 |
// formats supported in scripts |
| 13 |
#include <avogadro/io/cjsonformat.h> |
| 14 |
#include <avogadro/io/cmlformat.h> |
| 15 |
#include <avogadro/io/mdlformat.h> |
| 16 |
#include <avogadro/io/pdbformat.h> |
| 17 |
#include <avogadro/io/sdfformat.h> |
| 18 |
#include <avogadro/io/xyzformat.h> |
| 19 |
|
| 20 |
#include <QtCore/QDebug> |
| 21 |
#include <QtCore/QElapsedTimer> |
| 22 |
#include <QtCore/QScopedPointer> |
| 23 |
#include <QtCore/QSysInfo> |
| 24 |
#include <QtCore/QtEndian> |
| 25 |
|
| 26 |
#include <QRegularExpression> |
| 27 |
|
| 28 |
#include <algorithm> |
| 29 |
#include <cstddef> |
| 30 |
#include <cstdlib> |
| 31 |
#include <cstring> |
| 32 |
#include <limits> |
| 33 |
|
| 34 |
#include <qjsonarray.h> |
| 35 |
#include <qjsondocument.h> |
| 36 |
#include <qjsonobject.h> |
| 37 |
#include <qjsonvalue.h> |
| 38 |
|
| 39 |
namespace Avogadro::QtPlugins { |
| 40 |
|
| 41 |
namespace { |
| 42 |
|
| 43 |
constexpr int BINARY_HEADER_SIZE = 16; |
| 44 |
constexpr char BINARY_MAGIC[4] = { 'A', 'V', 'B', '1' }; |
| 45 |
constexpr quint16 BINARY_VERSION = 1; |
| 46 |
|
| 47 |
constexpr quint16 FLAG_RESPONSE_ERROR = 0x8000; |
| 48 |
constexpr quint16 FLAG_REQUEST_GRADIENT = 0x0001; |
| 49 |
constexpr quint16 FLAG_REQUEST_ENERGY_AND_GRADIENT = 0x0004; |
| 50 |
constexpr quint16 FLAG_REQUEST_HESSIAN = 0x0008; |
| 51 |
|
| 52 |
void appendFloat64LE(QByteArray& out, double value) |
| 53 |
{ |
| 54 |
quint64 bits = 0; |
| 55 |
static_assert(sizeof(bits) == sizeof(value), "Unexpected double size"); |
| 56 |
std::memcpy(&bits, &value, sizeof(value)); |
| 57 |
bits = qToLittleEndian(bits); |
| 58 |
out.append(reinterpret_cast<const char*>(&bits), sizeof(bits)); |
| 59 |
} |
| 60 |
|
| 61 |
bool readFloat64LE(const char* src, const char* end, double& value) |
| 62 |
{ |
| 63 |
if (end - src < static_cast<ptrdiff_t>(sizeof(quint64))) |
| 64 |
return false; |
| 65 |
|
| 66 |
quint64 bits = 0; |
| 67 |
std::memcpy(&bits, src, sizeof(bits)); |
| 68 |
bits = qFromLittleEndian(bits); |
| 69 |
std::memcpy(&value, &bits, sizeof(value)); |
| 70 |
return true; |
| 71 |
} |
| 72 |
|
| 73 |
void appendFloatText(QByteArray& out, double value) |
| 74 |
{ |
| 75 |
out.append(QByteArray::number(value, 'g', 17)); |
| 76 |
} |
| 77 |
|
| 78 |
bool readFloatText(const char*& pos, const char* end, double& value) |
| 79 |
{ |
| 80 |
if (pos == nullptr || pos >= end) |
| 81 |
return false; |
| 82 |
|
| 83 |
char* parsedEnd = nullptr; |
| 84 |
value = std::strtod(pos, &parsedEnd); |
| 85 |
if (parsedEnd == pos || parsedEnd == nullptr || parsedEnd > end) |
| 86 |
return false; |
| 87 |
|
| 88 |
pos = parsedEnd; |
| 89 |
return true; |
| 90 |
} |
| 91 |
|
| 92 |
} // namespace |
| 93 |
|
| 94 |
ScriptEnergy::ScriptEnergy(const QString& scriptFileName_) |
| 95 |
: m_interpreter(new QtGui::PythonScript(scriptFileName_)), |
| 96 |
m_inputFormat(NotUsed), m_protocol(Protocol::TextV1), m_molecule(nullptr), |
| 97 |
m_valid(true), m_gradients(false), m_hessians(false), m_ions(false), |
| 98 |
m_radicals(false), m_unitCells(false) |
| 99 |
{ |
| 100 |
m_elements.reset(); |
| 101 |
} |
| 102 |
|
| 103 |
ScriptEnergy::~ScriptEnergy() |
| 104 |
{ |
| 105 |
delete m_interpreter; |
| 106 |
} |
| 107 |
|
| 108 |
void ScriptEnergy::setPackageInfo(const QString& packageDir, |
| 109 |
const QString& command, |
| 110 |
const QString& identifier) |
| 111 |
{ |
| 112 |
m_interpreter->setPackageInfo(packageDir, command, identifier); |
| 113 |
} |
| 114 |
|
| 115 |
void ScriptEnergy::readMetaData(const QVariantMap& metadata) |
| 116 |
{ |
| 117 |
resetMetaData(); |
| 118 |
|
| 119 |
m_identifier = metadata.value("identifier").toString().toStdString(); |
| 120 |
m_name = metadata.value("model-name").toString().toStdString(); |
| 121 |
m_description = metadata.value("description").toString().toStdString(); |
| 122 |
|
| 123 |
QString inputFmt = metadata.value("input-format").toString(); |
| 124 |
m_inputFormat = stringToFormat(inputFmt.toStdString()); |
| 125 |
m_formatString = inputFmt; |
| 126 |
|
| 127 |
QString protocol = metadata.value("protocol").toString(); |
| 128 |
m_protocol = stringToProtocol(protocol.toStdString()); |
| 129 |
|
| 130 |
QVariantMap support = metadata.value("support").toMap(); |
| 131 |
m_gradients = support.value("gradients", false).toBool(); |
| 132 |
m_hessians = support.value("hessians", false).toBool(); |
| 133 |
m_unitCells = support.value("unit-cell", false).toBool(); |
| 134 |
m_ions = support.value("ions", false).toBool(); |
| 135 |
m_radicals = support.value("radicals", false).toBool(); |
| 136 |
|
| 137 |
QString elemStr = support.value("elements").toString(); |
| 138 |
if (!elemStr.isEmpty()) |
| 139 |
processElementString(elemStr); |
| 140 |
|
| 141 |
// Optional package-provided user-options schema. |
| 142 |
m_userOptionsSchema = QJsonObject(); |
| 143 |
const QVariant userOptionsVar = metadata.value("user-options"); |
| 144 |
if (userOptionsVar.typeId() == QMetaType::QVariantMap) { |
| 145 |
m_userOptionsSchema = QJsonObject::fromVariantMap(userOptionsVar.toMap()); |
| 146 |
} else { |
| 147 |
const QString userOptionsRel = userOptionsVar.toString(); |
| 148 |
if (!userOptionsRel.isEmpty()) { |
| 149 |
m_userOptionsSchema = QtGui::PackageManager::resolveUserOptions( |
| 150 |
userOptionsRel, m_interpreter->packageDir(), |
| 151 |
m_interpreter->packageCommand(), m_interpreter->packageIdentifier()); |
| 152 |
} |
| 153 |
} |
| 154 |
|
| 155 |
m_valid = |
| 156 |
!m_identifier.empty() && !m_name.empty() && m_inputFormat != NotUsed; |
| 157 |
} |
| 158 |
|
| 159 |
QString ScriptEnergy::scriptFilePath() const |
| 160 |
{ |
| 161 |
return m_interpreter->scriptFilePath(); |
| 162 |
} |
| 163 |
|
| 164 |
std::string ScriptEnergy::userOptions() const |
| 165 |
{ |
| 166 |
if (m_userOptionsSchema.isEmpty()) |
| 167 |
return std::string(); |
| 168 |
|
| 169 |
return QJsonDocument(m_userOptionsSchema) |
| 170 |
.toJson(QJsonDocument::Compact) |
| 171 |
.toStdString(); |
| 172 |
} |
| 173 |
|
| 174 |
bool ScriptEnergy::setUserOptions(const std::string& optionsJson) |
| 175 |
{ |
| 176 |
if (optionsJson.empty()) { |
| 177 |
m_userOptionsValues = QJsonObject(); |
| 178 |
return true; |
| 179 |
} |
| 180 |
|
| 181 |
QJsonParseError parseError; |
| 182 |
const QJsonDocument doc = QJsonDocument::fromJson( |
| 183 |
QByteArray::fromStdString(optionsJson), &parseError); |
| 184 |
if (parseError.error != QJsonParseError::NoError || !doc.isObject()) |
| 185 |
return false; |
| 186 |
|
| 187 |
m_userOptionsValues = doc.object(); |
| 188 |
return true; |
| 189 |
} |
| 190 |
|
| 191 |
Calc::EnergyCalculator* ScriptEnergy::newInstance() const |
| 192 |
{ |
| 193 |
auto* copy = new ScriptEnergy(); |
| 194 |
copy->m_interpreter->setPackageInfo(m_interpreter->packageDir(), |
| 195 |
m_interpreter->packageCommand(), |
| 196 |
m_interpreter->packageIdentifier()); |
| 197 |
copy->copyMetaDataFrom(*this); |
| 198 |
return copy; |
| 199 |
} |
| 200 |
|
| 201 |
void ScriptEnergy::copyMetaDataFrom(const ScriptEnergy& other) |
| 202 |
{ |
| 203 |
m_identifier = other.m_identifier; |
| 204 |
m_name = other.m_name; |
| 205 |
m_description = other.m_description; |
| 206 |
m_inputFormat = other.m_inputFormat; |
| 207 |
m_formatString = other.m_formatString; |
| 208 |
m_userOptionsSchema = other.m_userOptionsSchema; |
| 209 |
m_userOptionsValues = other.m_userOptionsValues; |
| 210 |
m_protocol = other.m_protocol; |
| 211 |
m_gradients = other.m_gradients; |
| 212 |
m_hessians = other.m_hessians; |
| 213 |
m_unitCells = other.m_unitCells; |
| 214 |
m_ions = other.m_ions; |
| 215 |
m_radicals = other.m_radicals; |
| 216 |
m_elements = other.m_elements; |
| 217 |
m_valid = other.m_valid; |
| 218 |
} |
| 219 |
|
| 220 |
void ScriptEnergy::setMolecule(Core::Molecule* mol) |
| 221 |
{ |
| 222 |
m_molecule = mol; |
| 223 |
|
| 224 |
// should check if the molecule is valid for this script |
| 225 |
// .. this should never happen, but let's be defensive |
| 226 |
if (mol == nullptr || m_interpreter == nullptr) { |
| 227 |
return; // nothing to do |
| 228 |
} |
| 229 |
if (!m_interpreter->isPackageMode()) { |
| 230 |
appendError("Energy scripts must run in package mode."); |
| 231 |
return; |
| 232 |
} |
| 233 |
|
| 234 |
// Always reset the running server before validating/restarting. |
| 235 |
m_interpreter->asyncTerminate(); |
| 236 |
|
| 237 |
if (!m_unitCells && mol->unitCell()) { |
| 238 |
appendError("Unit cell not supported for this script."); |
| 239 |
return; |
| 240 |
} |
| 241 |
if (!m_ions && mol->totalCharge() != 0) { |
| 242 |
appendError("Ionized molecules not supported for this script."); |
| 243 |
return; |
| 244 |
} |
| 245 |
if (!m_radicals && mol->totalSpinMultiplicity() != 1) { |
| 246 |
appendError("Radical molecules not supported for this script."); |
| 247 |
return; |
| 248 |
} |
| 249 |
|
| 250 |
QByteArray bootstrapInput; |
| 251 |
if (!buildBootstrapInput(bootstrapInput)) |
| 252 |
return; |
| 253 |
|
| 254 |
// construct the command line options |
| 255 |
QStringList options; |
| 256 |
if (m_protocol == Protocol::BinaryV1) |
| 257 |
options << "--protocol" |
| 258 |
<< "binary-v1"; |
| 259 |
|
| 260 |
// Start the long-running interpreter and keep stdin open for coordinate |
| 261 |
// requests after bootstrapping the model from JSON. |
| 262 |
m_interpreter->asyncExecute(options, bootstrapInput, false, false); |
| 263 |
} |
| 264 |
|
| 265 |
QByteArray ScriptEnergy::writeCoordinatesText(const Eigen::VectorXd& x) |
| 266 |
{ |
| 267 |
if (x.size() == 0 || (x.size() % 3) != 0) |
| 268 |
return QByteArray(); |
| 269 |
|
| 270 |
QByteArray input; |
| 271 |
input.reserve(static_cast<int>(x.size() / 3) * 80); |
| 272 |
for (Eigen::Index i = 0; i < x.size(); i += 3) { |
| 273 |
appendFloatText(input, x[i]); |
| 274 |
input.append(' '); |
| 275 |
appendFloatText(input, x[i + 1]); |
| 276 |
input.append(' '); |
| 277 |
appendFloatText(input, x[i + 2]); |
| 278 |
input.append('\n'); |
| 279 |
} |
| 280 |
return input; |
| 281 |
} |
| 282 |
|
| 283 |
QByteArray ScriptEnergy::writeCoordinatesBinary(const Eigen::VectorXd& x, |
| 284 |
quint16 requestFlags) const |
| 285 |
{ |
| 286 |
if (x.size() == 0 || (x.size() % 3) != 0) |
| 287 |
return QByteArray(); |
| 288 |
|
| 289 |
const quint16 flags = requestFlags; |
| 290 |
const quint32 atomCount = static_cast<quint32>(x.size() / 3); |
| 291 |
const quint32 payloadBytes = static_cast<quint32>(x.size() * sizeof(double)); |
| 292 |
|
| 293 |
QByteArray input; |
| 294 |
input.reserve(BINARY_HEADER_SIZE + static_cast<int>(payloadBytes)); |
| 295 |
input.append(BINARY_MAGIC, static_cast<int>(sizeof(BINARY_MAGIC))); |
| 296 |
|
| 297 |
quint16 versionLE = qToLittleEndian(BINARY_VERSION); |
| 298 |
quint16 flagsLE = qToLittleEndian(flags); |
| 299 |
quint32 atomCountLE = qToLittleEndian(atomCount); |
| 300 |
quint32 payloadBytesLE = qToLittleEndian(payloadBytes); |
| 301 |
|
| 302 |
input.append(reinterpret_cast<const char*>(&versionLE), sizeof(versionLE)); |
| 303 |
input.append(reinterpret_cast<const char*>(&flagsLE), sizeof(flagsLE)); |
| 304 |
input.append(reinterpret_cast<const char*>(&atomCountLE), |
| 305 |
sizeof(atomCountLE)); |
| 306 |
input.append(reinterpret_cast<const char*>(&payloadBytesLE), |
| 307 |
sizeof(payloadBytesLE)); |
| 308 |
|
| 309 |
if (QSysInfo::ByteOrder == QSysInfo::LittleEndian) { |
| 310 |
input.append(reinterpret_cast<const char*>(x.data()), |
| 311 |
static_cast<int>(payloadBytes)); |
| 312 |
} else { |
| 313 |
for (Eigen::Index i = 0; i < x.size(); ++i) |
| 314 |
appendFloat64LE(input, x[i]); |
| 315 |
} |
| 316 |
|
| 317 |
return input; |
| 318 |
} |
| 319 |
|
| 320 |
bool ScriptEnergy::parseResponseBinary(const QByteArray& response, |
| 321 |
quint16 requestFlags, double* energy, |
| 322 |
Eigen::VectorXd* grad, |
| 323 |
Eigen::MatrixXd* hess) const |
| 324 |
{ |
| 325 |
if (response.size() < BINARY_HEADER_SIZE) |
| 326 |
return false; |
| 327 |
|
| 328 |
const char* raw = response.constData(); |
| 329 |
if (std::memcmp(raw, BINARY_MAGIC, sizeof(BINARY_MAGIC)) != 0) |
| 330 |
return false; |
| 331 |
|
| 332 |
const auto* header = reinterpret_cast<const uchar*>(raw); |
| 333 |
const quint16 version = qFromLittleEndian<quint16>(header + 4); |
| 334 |
const quint16 flags = qFromLittleEndian<quint16>(header + 6); |
| 335 |
const quint32 atomCount = qFromLittleEndian<quint32>(header + 8); |
| 336 |
const quint32 payloadBytes = qFromLittleEndian<quint32>(header + 12); |
| 337 |
if (version != BINARY_VERSION) |
| 338 |
return false; |
| 339 |
|
| 340 |
if (response.size() < BINARY_HEADER_SIZE + static_cast<int>(payloadBytes)) |
| 341 |
return false; |
| 342 |
|
| 343 |
const char* payload = raw + BINARY_HEADER_SIZE; |
| 344 |
const char* payloadEnd = payload + payloadBytes; |
| 345 |
|
| 346 |
if (m_molecule != nullptr && |
| 347 |
atomCount != static_cast<quint32>(m_molecule->atomCount())) |
| 348 |
return false; |
| 349 |
|
| 350 |
if ((flags & FLAG_RESPONSE_ERROR) != 0) { |
| 351 |
appendError(std::string(payload, payloadEnd), false); |
| 352 |
return false; |
| 353 |
} |
| 354 |
|
| 355 |
const auto readDoubles = [](const char* src, const char* srcEnd, double* dest, |
| 356 |
Eigen::Index count) -> bool { |
| 357 |
const auto byteCount = count * static_cast<Eigen::Index>(sizeof(double)); |
| 358 |
if (srcEnd - src < byteCount) |
| 359 |
return false; |
| 360 |
if (QSysInfo::ByteOrder == QSysInfo::LittleEndian) { |
| 361 |
std::memcpy(dest, src, byteCount); |
| 362 |
} else { |
| 363 |
for (Eigen::Index i = 0; i < count; ++i) { |
| 364 |
if (!readFloat64LE(src + i * sizeof(double), srcEnd, dest[i])) |
| 365 |
return false; |
| 366 |
} |
| 367 |
} |
| 368 |
return true; |
| 369 |
}; |
| 370 |
|
| 371 |
// Hessian response: (3N)^2 doubles, row-major on wire |
| 372 |
if ((requestFlags & FLAG_REQUEST_HESSIAN) != 0 && hess != nullptr) { |
| 373 |
const Eigen::Index dim = static_cast<Eigen::Index>(atomCount) * 3; |
| 374 |
const quint32 expectedBytes = |
| 375 |
static_cast<quint32>(dim * dim * sizeof(double)); |
| 376 |
if (payloadBytes != expectedBytes) |
| 377 |
return false; |
| 378 |
if (QSysInfo::ByteOrder == QSysInfo::LittleEndian) { |
| 379 |
// Map row-major wire data directly into column-major Eigen matrix |
| 380 |
Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, |
| 381 |
Eigen::RowMajor>> |
| 382 |
rowMajorMap(reinterpret_cast<const double*>(payload), dim, dim); |
| 383 |
*hess = rowMajorMap; |
| 384 |
} else { |
| 385 |
// Read with byte-swap into a temporary, then transpose |
| 386 |
hess->resize(dim, dim); |
| 387 |
Eigen::MatrixXd rowMajor(dim, dim); |
| 388 |
if (!readDoubles(payload, payloadEnd, rowMajor.data(), dim * dim)) |
| 389 |
return false; |
| 390 |
*hess = rowMajor.transpose(); |
| 391 |
} |
| 392 |
return true; |
| 393 |
} |
| 394 |
|
| 395 |
// Fused energy + gradient response: 1 double energy + 3N doubles gradient |
| 396 |
if ((requestFlags & FLAG_REQUEST_ENERGY_AND_GRADIENT) != 0) { |
| 397 |
if (grad == nullptr || energy == nullptr) |
| 398 |
return false; |
| 399 |
const quint32 gradBytes = |
| 400 |
static_cast<quint32>(grad->size() * sizeof(double)); |
| 401 |
if (payloadBytes != sizeof(double) + gradBytes) |
| 402 |
return false; |
| 403 |
if (!readDoubles(payload, payloadEnd, energy, 1)) |
| 404 |
return false; |
| 405 |
if (!readDoubles(payload + sizeof(double), payloadEnd, grad->data(), |
| 406 |
grad->size())) |
| 407 |
return false; |
| 408 |
return true; |
| 409 |
} |
| 410 |
|
| 411 |
// Gradient-only response |
| 412 |
if ((requestFlags & FLAG_REQUEST_GRADIENT) != 0) { |
| 413 |
if (grad == nullptr) |
| 414 |
return false; |
| 415 |
if (atomCount != static_cast<quint32>(grad->size() / 3)) |
| 416 |
return false; |
| 417 |
if (payloadBytes != static_cast<quint32>(grad->size() * sizeof(double))) |
| 418 |
return false; |
| 419 |
return readDoubles(payload, payloadEnd, grad->data(), grad->size()); |
| 420 |
} |
| 421 |
|
| 422 |
// Energy-only response |
| 423 |
if (energy == nullptr) |
| 424 |
return false; |
| 425 |
if (payloadBytes != sizeof(double)) |
| 426 |
return false; |
| 427 |
return readDoubles(payload, payloadEnd, energy, 1); |
| 428 |
} |
| 429 |
|
| 430 |
bool ScriptEnergy::readBinaryFrame(const QByteArray& input, QByteArray& frame) |
| 431 |
{ |
| 432 |
if (m_interpreter == nullptr) |
| 433 |
return false; |
| 434 |
|
| 435 |
constexpr int timeoutMs = 5000; |
| 436 |
QElapsedTimer timer; |
| 437 |
timer.start(); |
| 438 |
|
| 439 |
frame = m_interpreter->asyncWriteAndResponseRaw(input, timeoutMs); |
| 440 |
if (frame.isEmpty()) { |
| 441 |
appendError("No binary response received from script."); |
| 442 |
return false; |
| 443 |
} |
| 444 |
|
| 445 |
while (frame.size() < BINARY_HEADER_SIZE && timer.elapsed() < timeoutMs) { |
| 446 |
const int remainingMs = |
| 447 |
std::max(1, timeoutMs - static_cast<int>(timer.elapsed())); |
| 448 |
const QByteArray chunk = |
| 449 |
m_interpreter->asyncWriteAndResponseRaw(QByteArray(), remainingMs); |
| 450 |
if (chunk.isEmpty()) |
| 451 |
break; |
| 452 |
frame += chunk; |
| 453 |
} |
| 454 |
|
| 455 |
if (frame.size() < BINARY_HEADER_SIZE) { |
| 456 |
appendError("Truncated binary header from script response."); |
| 457 |
return false; |
| 458 |
} |
| 459 |
|
| 460 |
const auto* header = reinterpret_cast<const uchar*>(frame.constData()); |
| 461 |
if (std::memcmp(frame.constData(), BINARY_MAGIC, sizeof(BINARY_MAGIC)) != 0) { |
| 462 |
appendError("Invalid binary response magic."); |
| 463 |
return false; |
| 464 |
} |
| 465 |
|
| 466 |
const quint16 version = qFromLittleEndian<quint16>(header + 4); |
| 467 |
const quint32 payloadBytes = qFromLittleEndian<quint32>(header + 12); |
| 468 |
if (version != BINARY_VERSION) { |
| 469 |
appendError("Unsupported binary response version."); |
| 470 |
return false; |
| 471 |
} |
| 472 |
|
| 473 |
const qint64 totalBytes = |
| 474 |
BINARY_HEADER_SIZE + static_cast<qint64>(payloadBytes); |
| 475 |
while (frame.size() < totalBytes && timer.elapsed() < timeoutMs) { |
| 476 |
const int remainingMs = |
| 477 |
std::max(1, timeoutMs - static_cast<int>(timer.elapsed())); |
| 478 |
const QByteArray chunk = |
| 479 |
m_interpreter->asyncWriteAndResponseRaw(QByteArray(), remainingMs); |
| 480 |
if (chunk.isEmpty()) |
| 481 |
break; |
| 482 |
frame += chunk; |
| 483 |
} |
| 484 |
|
| 485 |
if (frame.size() < totalBytes) { |
| 486 |
appendError("Truncated binary response payload."); |
| 487 |
return false; |
| 488 |
} |
| 489 |
if (frame.size() > totalBytes) { |
| 490 |
appendError("Binary response contained trailing bytes."); |
| 491 |
return false; |
| 492 |
} |
| 493 |
|
| 494 |
return true; |
| 495 |
} |
| 496 |
|
| 497 |
bool ScriptEnergy::evaluateBinary(const Eigen::VectorXd& x, |
| 498 |
quint16 requestFlags, double* energy, |
| 499 |
Eigen::VectorXd* grad, Eigen::MatrixXd* hess) |
| 500 |
{ |
| 501 |
const QByteArray input = writeCoordinatesBinary(x, requestFlags); |
| 502 |
if (input.isEmpty()) { |
| 503 |
appendError("Invalid coordinates for binary request."); |
| 504 |
return false; |
| 505 |
} |
| 506 |
|
| 507 |
QByteArray response; |
| 508 |
if (!readBinaryFrame(input, response)) |
| 509 |
return false; |
| 510 |
|
| 511 |
return parseResponseBinary(response, requestFlags, energy, grad, hess); |
| 512 |
} |
| 513 |
|
| 514 |
bool ScriptEnergy::buildBootstrapInput(QByteArray& input) const |
| 515 |
{ |
| 516 |
if (m_molecule == nullptr) { |
| 517 |
return false; |
| 518 |
} |
| 519 |
|
| 520 |
QScopedPointer<Io::FileFormat> format(createFileFormat(m_inputFormat)); |
| 521 |
if (format.isNull()) { |
| 522 |
appendError("Invalid input format."); |
| 523 |
return false; |
| 524 |
} |
| 525 |
|
| 526 |
std::string moleculeString; |
| 527 |
if (!format->writeString(moleculeString, *m_molecule)) { |
| 528 |
appendError(format->error(), false); |
| 529 |
return false; |
| 530 |
} |
| 531 |
|
| 532 |
QJsonObject request; |
| 533 |
request.insert(QStringLiteral("charge"), m_molecule->totalCharge()); |
| 534 |
request.insert(QStringLiteral("spin"), m_molecule->totalSpinMultiplicity()); |
| 535 |
|
| 536 |
QJsonArray selectedList; |
| 537 |
for (Index i = 0; i < m_molecule->atomCount(); ++i) { |
| 538 |
if (m_molecule->atomSelected(i)) |
| 539 |
selectedList.append(static_cast<qint64>(i)); |
| 540 |
} |
| 541 |
request.insert(QStringLiteral("selectedAtoms"), selectedList); |
| 542 |
|
| 543 |
if (m_formatString == QLatin1String("cjson")) { |
| 544 |
QJsonParseError parseError; |
| 545 |
const QJsonDocument parsed = QJsonDocument::fromJson( |
| 546 |
QByteArray::fromStdString(moleculeString), &parseError); |
| 547 |
if (parseError.error != QJsonParseError::NoError || !parsed.isObject()) { |
| 548 |
appendError("Failed to serialize cjson bootstrap input."); |
| 549 |
return false; |
| 550 |
} |
| 551 |
request.insert(QStringLiteral("cjson"), parsed.object()); |
| 552 |
} else { |
| 553 |
request.insert(m_formatString, QString::fromStdString(moleculeString)); |
| 554 |
} |
| 555 |
|
| 556 |
// Package energy scripts receive user-selected values under "options". |
| 557 |
request.insert(QStringLiteral("options"), m_userOptionsValues); |
| 558 |
|
| 559 |
input = QJsonDocument(request).toJson(QJsonDocument::Compact); |
| 560 |
input.append('\n'); |
| 561 |
return true; |
| 562 |
} |
| 563 |
|
| 564 |
Real ScriptEnergy::value(const Eigen::VectorXd& x) |
| 565 |
{ |
| 566 |
if (m_molecule == nullptr || m_interpreter == nullptr) |
| 567 |
return 0.0; // nothing to do |
| 568 |
|
| 569 |
double energy = 0.0; |
| 570 |
if (m_protocol == Protocol::BinaryV1) { |
| 571 |
if (!evaluateBinary(x, 0, &energy)) { |
| 572 |
return std::numeric_limits<Real>::quiet_NaN(); |
| 573 |
} |
| 574 |
energy += constraintEnergies(x); |
| 575 |
return energy; |
| 576 |
} |
| 577 |
|
| 578 |
QByteArray input = writeCoordinatesText(x); |
| 579 |
if (input.isEmpty()) { |
| 580 |
appendError("Invalid coordinates for text request."); |
| 581 |
return std::numeric_limits<Real>::quiet_NaN(); |
| 582 |
} |
| 583 |
|
| 584 |
QByteArray result = m_interpreter->asyncWriteAndResponse(input); |
| 585 |
|
| 586 |
// Find "AvogadroEnergy:" and parse the value directly from raw bytes |
| 587 |
const char* data = result.constData(); |
| 588 |
const char* end = data + result.size(); |
| 589 |
constexpr char marker[] = "AvogadroEnergy:"; |
| 590 |
constexpr size_t markerLen = sizeof(marker) - 1; |
| 591 |
|
| 592 |
const char* pos = std::search(data, end, marker, marker + markerLen); |
| 593 |
if (pos != end) { |
| 594 |
pos += markerLen; |
| 595 |
while (pos < end && (*pos == ' ' || *pos == '\t')) |
| 596 |
++pos; |
| 597 |
double parsedEnergy = 0.0; |
| 598 |
if (readFloatText(pos, end, parsedEnergy)) |
| 599 |
energy = parsedEnergy; |
| 600 |
} |
| 601 |
|
| 602 |
energy += constraintEnergies(x); |
| 603 |
return energy; |
| 604 |
} |
| 605 |
|
| 606 |
Real ScriptEnergy::evaluate(const Eigen::VectorXd& x, Eigen::VectorXd* grad) |
| 607 |
{ |
| 608 |
if (grad == nullptr) |
| 609 |
return value(x); |
| 610 |
|
| 611 |
// Optimizers may pass an uninitialized/incorrectly-sized gradient buffer. |
| 612 |
if (grad->rows() != x.rows()) |
| 613 |
grad->resize(x.rows()); |
| 614 |
grad->setZero(); |
| 615 |
|
| 616 |
if (!m_gradients) |
| 617 |
return EnergyCalculator::evaluate(x, grad); |
| 618 |
|
| 619 |
if (m_protocol == Protocol::BinaryV1) { |
| 620 |
double energy = 0.0; |
| 621 |
if (!evaluateBinary(x, FLAG_REQUEST_ENERGY_AND_GRADIENT, &energy, grad)) { |
| 622 |
grad->setConstant(std::numeric_limits<Real>::quiet_NaN()); |
| 623 |
return std::numeric_limits<Real>::quiet_NaN(); |
| 624 |
} |
| 625 |
cleanGradients(*grad); |
| 626 |
constraintGradients(x, *grad); |
| 627 |
energy += constraintEnergies(x); |
| 628 |
return energy; |
| 629 |
} |
| 630 |
|
| 631 |
// Text protocol parsers are currently separate for value and gradient. |
| 632 |
gradient(x, *grad); |
| 633 |
return value(x); |
| 634 |
} |
| 635 |
|
| 636 |
void ScriptEnergy::gradient(const Eigen::VectorXd& x, Eigen::VectorXd& grad) |
| 637 |
{ |
| 638 |
if (grad.rows() != x.rows()) |
| 639 |
grad.resize(x.rows()); |
| 640 |
grad.setZero(); |
| 641 |
|
| 642 |
if (!m_gradients) { |
| 643 |
EnergyCalculator::gradient(x, grad); |
| 644 |
return; |
| 645 |
} |
| 646 |
|
| 647 |
if (m_protocol == Protocol::BinaryV1) { |
| 648 |
if (!evaluateBinary(x, FLAG_REQUEST_GRADIENT, nullptr, &grad)) { |
| 649 |
grad.setConstant(std::numeric_limits<Real>::quiet_NaN()); |
| 650 |
return; |
| 651 |
} |
| 652 |
cleanGradients(grad); |
| 653 |
constraintGradients(x, grad); |
| 654 |
return; |
| 655 |
} |
| 656 |
|
| 657 |
QByteArray input = writeCoordinatesText(x); |
| 658 |
if (input.isEmpty()) { |
| 659 |
appendError("Invalid coordinates for text request."); |
| 660 |
grad.setConstant(std::numeric_limits<Real>::quiet_NaN()); |
| 661 |
return; |
| 662 |
} |
| 663 |
|
| 664 |
QByteArray result = m_interpreter->asyncWriteAndResponse(input); |
| 665 |
|
| 666 |
// Parse directly from raw bytes — no QString/QStringList overhead |
| 667 |
const char* data = result.constData(); |
| 668 |
const char* end = data + result.size(); |
| 669 |
constexpr char marker[] = "AvogadroGradient:"; |
| 670 |
constexpr size_t markerLen = sizeof(marker) - 1; |
| 671 |
|
| 672 |
const char* pos = std::search(data, end, marker, marker + markerLen); |
| 673 |
if (pos != end) { |
| 674 |
// Skip to the next line |
| 675 |
pos = static_cast<const char*>(std::memchr(pos, '\n', end - pos)); |
| 676 |
if (pos) |
| 677 |
++pos; |
| 678 |
|
| 679 |
Eigen::Index i = 0; |
| 680 |
while (pos && pos < end && i + 2 < x.size()) { |
| 681 |
// Skip whitespace |
| 682 |
while (pos < end && (*pos == ' ' || *pos == '\t' || *pos == '\r')) |
| 683 |
++pos; |
| 684 |
if (pos >= end || *pos == '\n') { |
| 685 |
if (pos < end) |
| 686 |
++pos; |
| 687 |
continue; |
| 688 |
} |
| 689 |
|
| 690 |
double gx, gy, gz; |
| 691 |
if (!readFloatText(pos, end, gx)) |
| 692 |
break; |
| 693 |
|
| 694 |
while (pos < end && (*pos == ' ' || *pos == '\t')) |
| 695 |
++pos; |
| 696 |
if (!readFloatText(pos, end, gy)) |
| 697 |
break; |
| 698 |
|
| 699 |
while (pos < end && (*pos == ' ' || *pos == '\t')) |
| 700 |
++pos; |
| 701 |
if (!readFloatText(pos, end, gz)) |
| 702 |
break; |
| 703 |
|
| 704 |
grad[i] = gx; |
| 705 |
grad[i + 1] = gy; |
| 706 |
grad[i + 2] = gz; |
| 707 |
i += 3; |
| 708 |
|
| 709 |
// Skip to next line |
| 710 |
while (pos < end && *pos != '\n') |
| 711 |
++pos; |
| 712 |
if (pos < end) |
| 713 |
++pos; |
| 714 |
} |
| 715 |
} |
| 716 |
|
| 717 |
cleanGradients(grad); |
| 718 |
constraintGradients(x, grad); |
| 719 |
} |
| 720 |
|
| 721 |
void ScriptEnergy::hessian(const Eigen::VectorXd& x, Eigen::MatrixXd& hess) |
| 722 |
{ |
| 723 |
if (!m_hessians || m_protocol != Protocol::BinaryV1) { |
| 724 |
// Fall back to numerical Hessian |
| 725 |
// Text-mode would be really slow anyway |
| 726 |
EnergyCalculator::hessian(x, hess); |
| 727 |
return; |
| 728 |
} |
| 729 |
|
| 730 |
if (!evaluateBinary(x, FLAG_REQUEST_HESSIAN, nullptr, nullptr, &hess)) { |
| 731 |
// something went wrong |
| 732 |
const Eigen::Index dim = x.size(); |
| 733 |
hess = Eigen::MatrixXd::Constant(dim, dim, |
| 734 |
std::numeric_limits<Real>::quiet_NaN()); |
| 735 |
} |
| 736 |
} |
| 737 |
|
| 738 |
ScriptEnergy::Format ScriptEnergy::stringToFormat(const std::string& str) |
| 739 |
{ |
| 740 |
if (str == "cjson") |
| 741 |
return Cjson; |
| 742 |
else if (str == "cml") |
| 743 |
return Cml; |
| 744 |
else if (str == "mdl" || str == "mol") |
| 745 |
return Mdl; |
| 746 |
else if (str == "pdb") |
| 747 |
return Pdb; |
| 748 |
else if (str == "sdf") |
| 749 |
return Sdf; |
| 750 |
else if (str == "xyz") |
| 751 |
return Xyz; |
| 752 |
return NotUsed; |
| 753 |
} |
| 754 |
|
| 755 |
ScriptEnergy::Protocol ScriptEnergy::stringToProtocol(const std::string& str) |
| 756 |
{ |
| 757 |
// Check for "binary" mode |
| 758 |
// this will change if the binary format changes |
| 759 |
if (str.rfind("binary", 0) == 0) |
| 760 |
return Protocol::BinaryV1; |
| 761 |
|
| 762 |
return Protocol::TextV1; |
| 763 |
} |
| 764 |
|
| 765 |
Io::FileFormat* ScriptEnergy::createFileFormat(ScriptEnergy::Format fmt) |
| 766 |
{ |
| 767 |
switch (fmt) { |
| 768 |
case Cjson: |
| 769 |
return new Io::CjsonFormat; |
| 770 |
case Cml: |
| 771 |
return new Io::CmlFormat; |
| 772 |
case Mdl: |
| 773 |
return new Io::MdlFormat; |
| 774 |
case Pdb: |
| 775 |
return new Io::PdbFormat; |
| 776 |
case Sdf: |
| 777 |
return new Io::SdfFormat; |
| 778 |
case Xyz: |
| 779 |
return new Io::XyzFormat; |
| 780 |
default: |
| 781 |
case NotUsed: |
| 782 |
return nullptr; |
| 783 |
} |
| 784 |
} |
| 785 |
|
| 786 |
void ScriptEnergy::resetMetaData() |
| 787 |
{ |
| 788 |
m_valid = false; |
| 789 |
m_gradients = false; |
| 790 |
m_hessians = false; |
| 791 |
m_ions = false; |
| 792 |
m_radicals = false; |
| 793 |
m_unitCells = false; |
| 794 |
m_inputFormat = NotUsed; |
| 795 |
m_protocol = Protocol::TextV1; |
| 796 |
m_identifier.clear(); |
| 797 |
m_name.clear(); |
| 798 |
m_description.clear(); |
| 799 |
m_formatString.clear(); |
| 800 |
m_elements.reset(); |
| 801 |
m_userOptionsSchema = QJsonObject(); |
| 802 |
m_userOptionsValues = QJsonObject(); |
| 803 |
} |
| 804 |
|
| 805 |
void ScriptEnergy::processElementString(const QString& str) |
| 806 |
{ |
| 807 |
// parse the QString |
| 808 |
// first turn any commas into whitespace |
| 809 |
QString str2(str); |
| 810 |
str2.replace(',', ' '); |
| 811 |
// then split on whitespace |
| 812 |
QStringList strList = |
| 813 |
str2.split(QRegularExpression("\\s+"), Qt::SkipEmptyParts); |
| 814 |
foreach (QString sstr, strList) { |
| 815 |
// these should be numbers or ranges (e.g., 1-84) |
| 816 |
if (sstr.contains('-')) { |
| 817 |
// range, so split on the dash |
| 818 |
QStringList strList2 = sstr.split('-'); |
| 819 |
if (strList2.size() != 2) |
| 820 |
return; |
| 821 |
|
| 822 |
// get the two numbers |
| 823 |
bool ok; |
| 824 |
int start = strList2[0].toInt(&ok); |
| 825 |
if (!ok || start < 1 || start > 119) |
| 826 |
return; |
| 827 |
int end = strList2[1].toInt(&ok); |
| 828 |
if (!ok || end < 1 || end > 119) |
| 829 |
return; |
| 830 |
for (int i = start; i <= end; ++i) |
| 831 |
m_elements.set(i); |
| 832 |
continue; |
| 833 |
} |
| 834 |
|
| 835 |
bool ok; |
| 836 |
int i = sstr.toInt(&ok); |
| 837 |
if (!ok || i < 1 || i > 119) |
| 838 |
return; |
| 839 |
|
| 840 |
m_elements.set(i); |
| 841 |
} |
| 842 |
} |
| 843 |
|
| 844 |
} // namespace Avogadro::QtPlugins |