Commit aaa0b772 authored by Mccaskey, Alex's avatar Mccaskey, Alex
Browse files

Improving InstructionParameter. Adding general Instruction options map of...


Improving InstructionParameter. Adding general Instruction options map of string to InstructionParameter

Signed-off-by: Mccaskey, Alex's avatarAlex McCaskey <mccaskeyaj@ornl.gov>
parent e7d7f321
......@@ -16,16 +16,6 @@ set(CMAKE_STANDARD_REQUIRED ON)
set(CMAKE_CXX_STANDARD 11)
message(STATUS "C++ version ${CXX_STANDARD} configured.")
#find_package(Git QUIET)
#if(GIT_FOUND AND EXISTS "${PROJECT_SOURCE_DIR}/.git")
# execute_process(COMMAND ${GIT_EXECUTABLE} submodule update --init --recursive
# WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
# RESULT_VARIABLE GIT_SUBMOD_RESULT)
# if(NOT GIT_SUBMOD_RESULT EQUAL "0")
# message(FATAL_ERROR "git submodule update --init failed with ${GIT_SUBMOD_RESULT}, please checkout submodules")
# endif()
#endif()
option(XACC_BUILD_TESTS "Build test programs" OFF)
if (FROM_SETUP_PY AND NOT APPLE)
......@@ -36,6 +26,7 @@ endif()
set(CMAKE_SKIP_INSTALL_RPATH OFF)
set(CMAKE_SKIP_RPATH OFF)
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH ON)
set(CMAKE_EXPORT_COMPILE_COMMANDS TRUE)
LIST(FIND CMAKE_PLATFORM_IMPLICIT_LINK_DIRECTORIES "${CMAKE_INSTALL_PREFIX}/lib" isSystemDir)
IF("${isSystemDir}" STREQUAL "-1")
......
......@@ -41,6 +41,7 @@ PyXACCListener::PyXACCListener(std::shared_ptr<Accelerator> acc)
: accelerator(acc) {
provider = xacc::getService<IRProvider>("gate");
}
PyXACCListener::PyXACCListener(bool _useDw, std::shared_ptr<Accelerator> acc)
: useDW(_useDw), accelerator(acc) {
if (_useDw)
......@@ -64,9 +65,9 @@ void PyXACCListener::enterXacckernel(PyXACCIRParser::XacckernelContext *ctx) {
for (int i = 1; i < ctx->param().size(); i++) {
if (!boost::contains(ctx->param(i)->getText(), "*")) {
params.push_back(
InstructionParameter(ctx->param(static_cast<size_t>(i))->getText()));
InstructionParameter(ctx->param(i)->getText()));
functionVariableNames.push_back(
ctx->param(static_cast<size_t>(i))->getText());
ctx->param(i)->getText());
}
}
f = provider->createFunction(ctx->kernelname->getText(), {}, params);
......
......@@ -17,10 +17,9 @@ protected:
public:
PyXACCVisitor(std::vector<InstructionParameter> functionParams) {
pyxaccStr += "@qpu()\ndef foo(" +
boost::lexical_cast<std::string>(functionParams[0]);
pyxaccStr += "@qpu()\ndef foo(" +functionParams[0].toString();
for (int i = 1; i < functionParams.size(); i++) {
pyxaccStr += "," + boost::lexical_cast<std::string>(functionParams[i]);
pyxaccStr += "," + functionParams[i].toString();
}
pyxaccStr += "):\n";
}
......@@ -87,25 +86,25 @@ public:
}
void visit(Rx &rx) {
auto angleStr = boost::lexical_cast<std::string>(rx.getParameter(0));
auto angleStr = rx.getParameter(0).toString();
pyxaccStr +=
" Rx(" + angleStr + ", " + std::to_string(rx.bits()[0]) + ")\n";
}
void visit(Ry &ry) {
auto angleStr = boost::lexical_cast<std::string>(ry.getParameter(0));
auto angleStr = ry.getParameter(0).toString();
pyxaccStr +=
" Ry(" + angleStr + ", " + std::to_string(ry.bits()[0]) + ")\n";
}
void visit(Rz &rz) {
auto angleStr = boost::lexical_cast<std::string>(rz.getParameter(0));
auto angleStr = rz.getParameter(0).toString();
pyxaccStr +=
" Rz(" + angleStr + ", " + std::to_string(rz.bits()[0]) + ")\n";
}
void visit(CPhase &cp) {
auto angleStr = boost::lexical_cast<std::string>(cp.getParameter(0));
auto angleStr = cp.getParameter(0).toString();
pyxaccStr += " CPhase(" + angleStr + ", " + std::to_string(cp.bits()[0]) +
", " + std::to_string(cp.bits()[1]) + ")\n";
}
......@@ -116,9 +115,9 @@ public:
}
void visit(U& u) {
auto t = boost::lexical_cast<std::string>(u.getParameter(0));
auto p = boost::lexical_cast<std::string>(u.getParameter(1));
auto l = boost::lexical_cast<std::string>(u.getParameter(2));
auto t = u.getParameter(0).toString();
auto p = u.getParameter(1).toString();
auto l = u.getParameter(2).toString();
// if (u.getParameter(0).which() != 3 && u.getParameter(1).which() != 3 && u.getParameter(2).which() != 3) {
// // We have concrete values here
......
......@@ -16,6 +16,7 @@
#include "InstructionIterator.hpp"
#include "AcceleratorBuffer.hpp"
#include "AcceleratorDecorator.hpp"
#include "InstructionParameter.hpp"
#include <pybind11/complex.h>
#include <pybind11/numpy.h>
......@@ -31,6 +32,18 @@ using namespace xacc;
// `boost::variant` as an example -- can be any `std::variant`-like container
namespace pybind11 {
namespace detail {
template <typename... Ts>
struct type_caster<Variant<Ts...>> : variant_caster<Variant<Ts...>> {};
// Specifies the function used to visit the variant -- `apply_visitor` instead
// of `visit`
template <> struct visit_helper<Variant> {
template <typename... Args>
static auto call(Args &&... args) -> decltype(boost::apply_visitor(args...)) {
return boost::apply_visitor(args...);
}
};
template <typename... Ts>
struct type_caster<boost::variant<Ts...>>
: variant_caster<boost::variant<Ts...>> {};
......@@ -107,13 +120,19 @@ PYBIND11_MODULE(_pyxacc, m) {
.def(py::init<int>(), "Construct as an int.")
.def(py::init<double>(), "Construct as a double.")
.def(py::init<std::string>(), "Construct as a string.")
.def(py::init<std::complex<double>>(), "Construct as a complex double.")
.def(py::init<float>(), "Construct as a float.");
.def(py::init<std::complex<double>>(), "Construct as a complex double.");
py::class_<xacc::Instruction, std::shared_ptr<xacc::Instruction>>(
m, "Instruction", "")
.def("nParameters", &xacc::Instruction::nParameters, "")
.def("toString", &xacc::Instruction::toString, "")
.def("toString",
(const std::string (xacc::Instruction::*)()) &
xacc::Instruction::toString,
"")
.def("toString",
(const std::string (xacc::Instruction::*)(const std::string &)) &
xacc::Instruction::toString,
"")
.def("isEnabled", &xacc::Instruction::isEnabled, "")
.def("isComposite", &xacc::Instruction::isComposite, "")
.def("bits", &xacc::Instruction::bits, "")
......@@ -121,7 +140,6 @@ PYBIND11_MODULE(_pyxacc, m) {
.def("getParameters", &xacc::Instruction::getParameters, "")
.def("setParameter", &xacc::Instruction::setParameter, "")
.def("mapBits", &xacc::Instruction::mapBits, "")
.def("getTag", &xacc::Instruction::getTag, "")
.def("name", &xacc::Instruction::name, "")
.def("description", &xacc::Instruction::description, "");
......@@ -139,13 +157,18 @@ PYBIND11_MODULE(_pyxacc, m) {
.def("name", &xacc::Function::name, "")
.def("description", &xacc::Function::description, "")
.def("nParameters", &xacc::Function::nParameters, "")
.def("toString", &xacc::Function::toString, "")
.def("toString",
(const std::string (xacc::Function::*)()) & xacc::Function::toString,
"")
.def("toString",
(const std::string (xacc::Function::*)(const std::string &)) &
xacc::Function::toString,
"")
.def("enabledView", &xacc::Function::enabledView, "")
.def("enable", &xacc::Function::enable, "")
.def("getParameter", &xacc::Function::getParameter, "")
.def("getParameters", &xacc::Function::getParameters, "")
.def("setParameter", &xacc::Function::setParameter, "")
.def("getTag", &xacc::Function::getTag, "")
.def("depth", &xacc::Function::depth, "")
.def("persistGraph", &xacc::Function::persistGraph, "")
.def("mapBits", &xacc::Function::mapBits, "");
......@@ -231,11 +254,12 @@ PYBIND11_MODULE(_pyxacc, m) {
kl[i] = v;
})
.def("__len__", &xacc::KernelList<>::size)
.def("__iter__",
[](const xacc::KernelList<> &kl) {
return py::make_iterator(kl.begin(), kl.end());
},
py::keep_alive<0, 1>())
.def(
"__iter__",
[](const xacc::KernelList<> &kl) {
return py::make_iterator(kl.begin(), kl.end());
},
py::keep_alive<0, 1>())
.def("__getitem__",
[](xacc::KernelList<> &s, py::slice slice) -> xacc::KernelList<> * {
size_t start, stop, step, slicelength;
......@@ -459,30 +483,33 @@ PYBIND11_MODULE(_pyxacc, m) {
m.def("translate", &xacc::translate,
"Translate the provided IR Function to the given language.");
m.def("setOption", [](const std::string s, InstructionParameter p) {
xacc::setOption(s, boost::lexical_cast<std::string>(p));
xacc::setOption(s, p.toString());
});
m.def("info", [](const std::string s) { xacc::info(s); }, "");
m.def("error", [](const std::string s) { xacc::error(s); }, "");
m.def(
"info", [](const std::string s) { xacc::info(s); }, "");
m.def(
"error", [](const std::string s) { xacc::error(s); }, "");
m.def("setOption", &xacc::setOption, "Set an XACC framework option.");
m.def("setOptions",
[](std::map<std::string, std::string> options) {
for (auto &kv : options)
xacc::setOption(kv.first, kv.second);
},
"Set a number of options at once.");
m.def(
"setOptions",
[](std::map<std::string, std::string> options) {
for (auto &kv : options)
xacc::setOption(kv.first, kv.second);
},
"Set a number of options at once.");
m.def("getAcceleratorDecorator",
[](const std::string name, std::shared_ptr<Accelerator> acc) {
auto accd = xacc::getService<AcceleratorDecorator>(name);
accd->setDecorated(acc);
return accd;
});
m.def("setOptions",
[](std::map<std::string, InstructionParameter> options) {
for (auto &kv : options)
xacc::setOption(kv.first,
boost::lexical_cast<std::string>(kv.second));
},
"Set a number of options at once.");
m.def(
"setOptions",
[](std::map<std::string, InstructionParameter> options) {
for (auto &kv : options)
xacc::setOption(kv.first, kv.second.toString());
},
"Set a number of options at once.");
m.def("unsetOption", &xacc::unsetOption, "");
m.def("getOption",
(const std::string (*)(const std::string &)) & xacc::getOption,
......@@ -500,46 +527,49 @@ PYBIND11_MODULE(_pyxacc, m) {
(void (*)(std::shared_ptr<AcceleratorBuffer>)) & xacc::analyzeBuffer,
"Analyze the AcceleratorBuffer to produce problem-specific results.");
m.def("Finalize", &xacc::Finalize, "Finalize the framework");
m.def("loadBuffer",
[](const std::string json) {
std::istringstream s(json);
auto buffer = std::make_shared<AcceleratorBuffer>();
buffer->load(s);
return buffer;
},
"");
m.def("compileKernel",
[](std::shared_ptr<Accelerator> acc, const std::string &src,
const std::string &compilerName = "") -> std::shared_ptr<Function> {
if (!compilerName.empty())
xacc::setOption("compiler", compilerName);
xacc::Program p(acc, src);
p.build();
return p.getRuntimeKernels()[0].getIRFunction();
},
py::arg("acc"), py::arg("src"),
py::arg("compilerName") = std::string(""),
py::return_value_policy::move, "");
m.def("functionToInstruction",
[](std::shared_ptr<Function> f) {
return std::dynamic_pointer_cast<Instruction>(f);
},
py::return_value_policy::copy);
m.def(
"loadBuffer",
[](const std::string json) {
std::istringstream s(json);
auto buffer = std::make_shared<AcceleratorBuffer>();
buffer->load(s);
return buffer;
},
"");
m.def(
"compileKernel",
[](std::shared_ptr<Accelerator> acc, const std::string &src,
const std::string &compilerName = "") -> std::shared_ptr<Function> {
if (!compilerName.empty())
xacc::setOption("compiler", compilerName);
xacc::Program p(acc, src);
p.build();
return p.getRuntimeKernels()[0].getIRFunction();
},
py::arg("acc"), py::arg("src"), py::arg("compilerName") = std::string(""),
py::return_value_policy::move, "");
m.def(
"functionToInstruction",
[](std::shared_ptr<Function> f) {
return std::dynamic_pointer_cast<Instruction>(f);
},
py::return_value_policy::copy);
py::module gatesub =
m.def_submodule("gate", "Gate model quantum computing data structures.");
gatesub.def("create",
[](const std::string &name, std::vector<int> qbits,
std::vector<InstructionParameter> params =
std::vector<InstructionParameter>{})
-> std::shared_ptr<Instruction> {
return xacc::getService<IRProvider>("gate")->createInstruction(
name, qbits, params);
},
"Convenience function for creating a new GateInstruction.",
py::arg("name"), py::arg("qbits"),
py::arg("params") = std::vector<InstructionParameter>{});
gatesub.def(
"create",
[](const std::string &name, std::vector<int> qbits,
std::vector<InstructionParameter> params =
std::vector<InstructionParameter>{})
-> std::shared_ptr<Instruction> {
return xacc::getService<IRProvider>("gate")->createInstruction(
name, qbits, params);
},
"Convenience function for creating a new GateInstruction.",
py::arg("name"), py::arg("qbits"),
py::arg("params") = std::vector<InstructionParameter>{});
gatesub.def(
"createFunction",
[](const std::string &name, std::vector<int> qbits,
......@@ -551,11 +581,12 @@ PYBIND11_MODULE(_pyxacc, m) {
"Convenience function for creating a new GateFunction.", py::arg("name"),
py::arg("qbits"),
py::arg("params") = std::vector<InstructionParameter>{});
gatesub.def("createIR",
[]() -> std::shared_ptr<IR> {
return xacc::getService<IRProvider>("gate")->createIR();
},
"Convenience function for creating a new GateIR.");
gatesub.def(
"createIR",
[]() -> std::shared_ptr<IR> {
return xacc::getService<IRProvider>("gate")->createIR();
},
"Convenience function for creating a new GateIR.");
gatesub.def(
"getState",
......
......@@ -346,7 +346,6 @@ class PyServiceRegistry(object):
pluginFiles = [f for f in os.listdir(
pluginDir) if os.path.isfile(os.path.join(pluginDir, f))]
for f in pluginFiles:
bundle_name = os.path.splitext(f)[0].strip()
print(bundle_name, f)
......@@ -355,7 +354,7 @@ class PyServiceRegistry(object):
services = self.context.get_all_service_references(
'xacc_algorithm_service')
if services is None:
print("No XACC benchmark algorithm bundles found.")
print("No XACC benchmark algorithm bundles found in " + pluginDir + ".")
exit(1)
for s in services:
info('[XACC-Benchmark] Algorithm Service: %s is installed.' % s.get_properties()['name'])
......
......@@ -57,12 +57,12 @@ public:
virtual bool kernelExists(const std::string &name) {
return std::any_of(
kernels.cbegin(), kernels.cend(),
[=](std::shared_ptr<Function> i) { return i->getName() == name; });
[=](std::shared_ptr<Function> i) { return i->name() == name; });
}
virtual std::shared_ptr<Function> getKernel(const std::string &name) {
for (auto f : kernels) {
if (f->getName() == name) {
if (f->name() == name) {
return f;
}
}
......
......@@ -85,8 +85,6 @@ public:
instructions.remove(getInstruction(idx));
}
const std::string getTag() override { return ""; }
void mapBits(std::vector<int> bitMap) override {
xacc::error("DWKernel.mapBits not implemented");
}
......@@ -168,6 +166,28 @@ public:
return ss.str();
}
const std::string toString() override {
return toString("");
}
/**
* Return the number of logical qubits.
*
* @return nLogical The number of logical qubits.
*/
const int nLogicalBits() override {
return 0;
}
/**
* Return the number of physical qubits.
*
* @return nPhysical The number of physical qubits.
*/
const int nPhysicalBits() override {
return 0;
}
std::vector<double> getAllBiases() {
std::vector<double> biases;
for (auto i : instructions) {
......@@ -290,6 +310,48 @@ public:
return evaluatedFunction;
}
/**
* Return true if this Instruction has
* customizable options.
*
* @return hasOptions
*/
bool hasOptions() override {
return false;
}
/**
* Set the value of an option with the given name.
*
* @param optName The name of the option.
* @param option The value of the option
*/
void setOption(const std::string optName,
InstructionParameter option) override {
XACCLogger::instance()->error("setOption not implemented for DWKernel.");
return;
}
/**
* Get the value of an option with the given name.
*
* @param optName Then name of the option.
* @return option The value of the option.
*/
InstructionParameter getOption(const std::string optName) override {
XACCLogger::instance()->error("getOption not implemented for DWKernel.");
return InstructionParameter(0);
}
/**
* Return all the Instructions options as a map.
*
* @return optMap The options map.
*/
std::map<std::string, InstructionParameter> getOptions() override {
XACCLogger::instance()->error("getOptions not implemented for DWKernel.");
return std::map<std::string,InstructionParameter>();
}
EMPTY_DEFINE_VISITABLE()
};
......
......@@ -94,13 +94,11 @@ public:
*
* @return name The name of this Instruction
*/
virtual const std::string name() const { return "dw-qmi"; }
const std::string name() const override { return "dw-qmi"; }
virtual const std::string description() const { return ""; }
const std::string description() const override { return ""; }
virtual const std::string getTag() { return ""; }
virtual void mapBits(std::vector<int> bitMap) {}
void mapBits(std::vector<int> bitMap) override {}
/**
* Persist this Instruction to an assembly-like
......@@ -109,19 +107,23 @@ public:
* @param bufferVarName The name of the AcceleratorBuffer
* @return str The assembly-like string.
*/
virtual const std::string toString(const std::string &bufferVarName) {
const std::string toString(const std::string &bufferVarName) override {
std::stringstream ss;
ss << bits()[0] << " " << bits()[1] << " " << getParameter(0);
ss << bits()[0] << " " << bits()[1] << " " << getParameter(0).toString();
return ss.str();
}
const std::string toString() override {
return toString("");
}
/**
* Return the indices of the bits that this Instruction
* operates on.
*
* @return bits The bits this Instruction operates on.
*/
virtual const std::vector<int> bits() { return qubits; }
const std::vector<int> bits() override { return qubits; }
/**
* Return this Instruction's parameter at the given index.
......@@ -129,7 +131,7 @@ public:
* @param idx The index of the parameter.
* @return param The InstructionParameter at the given index.
*/
virtual InstructionParameter getParameter(const int idx) const {
InstructionParameter getParameter(const int idx) const override {
return parameter;
}
......@@ -138,7 +140,7 @@ public:
*
* @return params This instructions parameters.
*/
virtual std::vector<InstructionParameter> getParameters() {
std::vector<InstructionParameter> getParameters() override {
return std::vector<InstructionParameter>{parameter};
}
......@@ -148,7 +150,7 @@ public:
* @param idx The index of the parameter
* @param inst The instruction.
*/
virtual void setParameter(const int idx, InstructionParameter &inst) {
void setParameter(const int idx, InstructionParameter &inst) override {
parameter = inst;
}
......@@ -157,39 +159,83 @@ public:
*
* @return nInsts The number of instructions.
*/
virtual const int nParameters() { return 1; }
const int nParameters() override { return 1; }
/**
* Return true if this Instruction is parameterized.
*
* @return parameterized True if this Instruction has parameters.
*/
virtual bool isParameterized() { return true; }
bool isParameterized() override { return true; }
/**
* Returns true if this Instruction is composite,
* ie, contains other Instructions.
*
* @return isComposite True if this is a composite Instruction
*/
virtual bool isComposite() { return false; }
bool isComposite() override { return false; }
/**
* Returns true if this Instruction is enabled
*
* @return enabled True if this Instruction is enabled.
*/
virtual bool isEnabled() { return enabled; }
bool isEnabled() override { return enabled; }
/**
* Disable this Instruction
*/
virtual void disable() { enabled = false; }
void disable() override { enabled = false; }
/**
* Enable this Instruction.
*/
virtual void enable() { enabled = true; }
void enable() override { enabled = true; }
/**
* Return true if this Instruction has
* customizable options.
*
* @return hasOptions
*/
bool hasOptions() override {
return false;
}
/**
* Set the value of an option with the given name.
*
* @param optName The name of the option.
* @param option The value of the option
*/