Skip to content

Commit

Permalink
Merge pull request #31 from danclaudino/optimizers_error_handling
Browse files Browse the repository at this point in the history
Optimizer plugins can ignore optimizer failure
  • Loading branch information
danclaudino authored Aug 5, 2024
2 parents 2e09a57 + fc26536 commit f24fa36
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
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

0 comments on commit f24fa36

Please sign in to comment.