Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimizer plugins can ignore optimizer failure #31

Merged
merged 1 commit into from
Aug 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions quantum/plugins/optimizers/nlopt-optimizers/nlopt_optimizer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,12 @@ OptResult NLOptimizer::optimize(OptFunction &function) {
upperBounds = options.get<std::vector<double>>("nlopt-upper-bounds");
}

// if fails to find mininum should not throw error
bool throwError = true;
if (options.keyExists<bool>("throw-error")) {
throwError = options.get<bool>("throw-error");
}

_opt.set_lower_bounds(lowerBounds);
_opt.set_upper_bounds(upperBounds);
_opt.set_maxeval(maxeval);
Expand All @@ -171,10 +177,16 @@ OptResult NLOptimizer::optimize(OptFunction &function) {
try {
r = _opt.optimize(x, optF);
} catch (std::exception &e) {
xacc::error("NLOpt failed with error code = " + std::to_string(r) + ", " +

if (throwError) {
xacc::error("NLOpt failed with error code = " + std::to_string(r) + ", " +
std::string(e.what()));
}
} else {
xacc::warning("NLOpt failed with error code = " + std::to_string(r) + ", " +
std::string(e.what()));
}

}
return OptResult{optF, x};
}

Expand Down
23 changes: 19 additions & 4 deletions quantum/plugins/optimizers/scipy/scipy_optimizer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,12 @@ OptResult ScipyOptimizer::optimize(OptFunction &function) {
x = std::vector<double>(tmpx.begin(), tmpx.end());
}

// if fails to find mininum should not throw error
bool throwError = true;
if (options.keyExists<bool>("throw-error")) {
throwError = options.get<bool>("throw-error");
}

// here the python stuff starts
py::list pyInitialParams;
for (const auto &param : x) {
Expand Down Expand Up @@ -152,11 +158,20 @@ OptResult ScipyOptimizer::optimize(OptFunction &function) {

return {optimalValue, optimizedParams};
} catch (const py::error_already_set &e) {
std::cerr << "Python error: " << e.what() << std::endl;
throw;

if (throwError) {
xacc::error("Python error: " + std::string(e.what()));
throw;
}
return {};

} catch (const std::exception &e) {
std::cerr << "Error: " << e.what() << std::endl;
throw;

if (throwError) {
xacc::error("Error: " + std::string(e.what()));
throw;
}
return {};
}
}
} // namespace xacc
Expand Down
Loading