Commit 4c7333ff authored by Mccaskey, Alex's avatar Mccaskey, Alex
Browse files

Merge branch 'xacc-devel' into mccaskey/dwave

parents bb7fd18f 408cdf66
......@@ -42,3 +42,7 @@
compile_commands.json
/docs/doxygen/html**
**/*.dat
# IDE files
.vscode/*
.theia/*
\ No newline at end of file
......@@ -113,6 +113,11 @@ set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-attributes")
include_directories(${CMAKE_BINARY_DIR}/tpls/cppmicroservices/include)
add_subdirectory(tpls)
IF(CMAKE_BUILD_TYPE MATCHES "Debug" OR CMAKE_BUILD_TYPE MATCHES "DEBUG")
message(STATUS "${BoldYellow}Adding _XACC_DEBUG compiler flag${ColorReset}")
add_compile_definitions(_XACC_DEBUG)
ENDIF()
add_subdirectory(xacc)
add_subdirectory(quantum)
......@@ -126,7 +131,7 @@ if(Python_FOUND)
if (PELIX_EXISTS EQUAL "1")
# if not, check we have pip
execute_process(COMMAND ${Python_EXECUTABLE} -c "import pip" RESULT_VARIABLE PIP_EXISTS)
if (PIP_EXISTS EQUAL "0")
if (PIP_EXISTS EQUAL "0")
# we have pip, son just install ipopo
message(STATUS "${BoldGreen}Installing Pelix OSGi framework.${ColorReset}")
execute_process(COMMAND ${Python_EXECUTABLE} -m pip install ipopo)
......
......@@ -49,7 +49,6 @@ class AerAccelerator(xacc.Accelerator):
return 'aer'
def execute_one_qasm(self, buffer, program):
print(program.toString())
qobjStr = self.qobj_compiler.translate(program)
import json
from qiskit import Aer
......@@ -65,7 +64,7 @@ class AerAccelerator(xacc.Accelerator):
qobj = QasmQobjSchema().load(qobj_json['qObject'])
exps = qobj.experiments
measures = {}
qobj.experiments[0].config.n_qubits = 8
qobj.experiments[0].config.n_qubits = buffer.size()
for i in exps[0].instructions:
if i.name == "measure":
measures[i.memory[0]] =i.qubits[0]
......@@ -84,7 +83,8 @@ class AerAccelerator(xacc.Accelerator):
if len(b) < buffer.size():
tmp = ['0' for i in range(buffer.size())]
for bit_loc, qubit in measures.items():
tmp[len(tmp)-1-qubit] = list(b)[bit_loc]
lb = list(b)
tmp[len(tmp)-1-qubit] = lb[len(b)-bit_loc-1]
bitstring = ''.join(tmp)
buffer.appendMeasurement(bitstring,c)
......
......@@ -22,7 +22,7 @@ namespace external {
class PythonPluginLoader : public ExternalLanguagePluginLoader {
protected:
std::shared_ptr<py::scoped_interpreter> guard;
py::scoped_interpreter* guard;
void* libpython_handle;
public:
const std::string name() const override { return "python"; }
......
......@@ -18,12 +18,15 @@ namespace xacc {
namespace external {
bool PythonPluginLoader::load() {
xacc::debug("[PyPluginLoader] Loading all contributed Python plugins.");
if (!XACC_IS_APPLE){
libpython_handle = dlopen("@PYTHON_LIB_NAME@", RTLD_LAZY | RTLD_GLOBAL);
}
guard = std::make_shared<py::scoped_interpreter>();
py::scoped_interpreter * guard = new py::scoped_interpreter();
try {
py::module sys = py::module::import("xacc");
sys.attr("loaded_from_cpp_dont_finalize") = true;
} catch(std::exception& e) {
std::cout << "Could not import " << e.what() << "\n";
return false;
......@@ -34,6 +37,8 @@ bool PythonPluginLoader::load() {
bool PythonPluginLoader::unload() {
if (!XACC_IS_APPLE) {
xacc::debug("[PyPluginLoader] Unloading Python plugins");
delete guard;
int i = dlclose(libpython_handle);
if (i != 0) {
std::cout << "error closing python lib: " << i << "\n";
......
......@@ -99,6 +99,8 @@ PYBIND11_MODULE(_pyxacc, m) {
"");
m.def(
"info", [](const std::string s) { xacc::info(s); }, "");
m.def(
"debug", [](const std::string s) { xacc::debug(s); }, "");
m.def(
"error", [](const std::string s) { xacc::error(s); }, "");
m.def("setOption", &xacc::setOption, "Set an XACC framework option.");
......
......@@ -303,12 +303,16 @@ class PyServiceRegistry(object):
self.get_algorithm_services(servType)
for accName, acc in self.registry['accelerator'].items():
debug("[xacc-py] Contributing "+accName+" Accelerator")
contributeService(accName, acc)
for irtName, irt in self.registry['irtransformation'].items():
debug("[xacc-py] Contributing "+irtName+" IRTransformation")
contributeService(irtName, irt)
for obsName, obs in self.registry['observable'].items():
debug("[xacc-py] Contributing "+obsName+" Observable")
contributeService(obsName, obs)
for optName, opt in self.registry['optimizer'].items():
debug("[xacc-py] Contributing "+optName+" Optimizer")
contributeService(optName, opt)
def get_algorithm_services(self, serviceType):
......@@ -423,9 +427,13 @@ def main(argv=None):
initialize()
loaded_from_cpp_dont_finalize = False
def _finalize():
Finalize()
if not loaded_from_cpp_dont_finalize:
Finalize()
else:
debug("THIS WAS LOADED FROM CPP DONT FINALIZE")
atexit.register(_finalize)
......
......@@ -88,7 +88,8 @@ public:
void removeDisabled() override {
}
void setBitExpression(const std::size_t bit_idx, const std::string expr) override {}
std::string getBitExpression(const std::size_t bit_idx) override {return "";}
const int nRequiredBits() const override {
return 0;
}
......@@ -133,7 +134,7 @@ InstPtr getInstruction(const std::size_t idx) override {
void clear() override {
instructions.clear();
}
const std::string persistGraph() override {
std::stringstream s;
toGraph()->write(s);
......@@ -174,6 +175,10 @@ InstPtr getInstruction(const std::size_t idx) override {
return biases;
}
std::string getBufferName(const std::size_t bitIdx) override {return "";}
void setBufferNames(const std::vector<std::string> bufferNamesPerIdx) override {}
std::vector<std::string> getBufferNames() override {return {};}
std::vector<double> getAllCouplers() {
std::vector<double> weights;
for (auto i : instructions) {
......
......@@ -55,7 +55,8 @@ public:
ss << bits()[0] << " " << bits()[1] << " " << getParameter(0).toString();
return ss.str();
}
void setBitExpression(const std::size_t bit_idx, const std::string expr) override {}
std::string getBitExpression(const std::size_t bit_idx) override {return "";}
const std::vector<std::size_t> bits() override { return qubits; }
const InstructionParameter getParameter(const std::size_t idx) const override {
......@@ -77,6 +78,10 @@ public:
void disable() override { enabled = false; }
void enable() override { enabled = true; }
std::string getBufferName(const std::size_t bitIdx) override {return "";}
void setBufferNames(const std::vector<std::string> bufferNamesPerIdx) override {}
std::vector<std::string> getBufferNames() override {return {};}
std::shared_ptr<Instruction> clone() override {
return std::make_shared<DWQMI>();
}
......
......@@ -11,4 +11,5 @@
# Alexander J. McCaskey - initial API and implementation
# *******************************************************************************/
add_subdirectory(base_api)
add_subdirectory(qasm)
\ No newline at end of file
add_subdirectory(qasm)
add_subdirectory(qst-publication)
\ No newline at end of file
......@@ -22,3 +22,6 @@ target_link_libraries(deuteron_2qbit_xasm_X0X1 PRIVATE xacc)
add_executable(deuteron_2qbit_ir_api_X0X1 deuteron_2qbit_ir_api_X0X1.cpp)
target_link_libraries(deuteron_2qbit_ir_api_X0X1 PRIVATE xacc)
add_executable(circuit_optimization circuit_optimization.cpp)
target_link_libraries(circuit_optimization PRIVATE xacc)
/*******************************************************************************
* Copyright (c) 2019 UT-Battelle, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v1.0 which accompanies this
* distribution. The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution
*License is available at https://eclipse.org/org/documents/edl-v10.php
*
* Contributors:
* Alexander J. McCaskey - initial API and implementation
*******************************************************************************/
#include "xacc.hpp"
#include "xacc_service.hpp"
#include "IRTransformation.hpp"
namespace {
const std::string testXGateReductionSrc =
R"(__qpu__ void test(qbit q) {
X(q[1]);
CX(q[0], q[1]);
H(q[0]);
I(q[1]);
X(q[1]);
X(q[0]);
H(q[0]);
X(q[0]);
X(q[1]);
X(q[0]);
Measure(q[1]);
})";
const std::string testHadamardGateReductionSrc =
R"(__qpu__ void test(qbit q) {
X(q[0]);
H(q[0]);
Rz(q[0], 1.57079632679489661923);
H(q[0]);
Z(q[0]);
H(q[0]);
Z(q[0]);
X(q[1]);
H(q[2]);
CX(q[1], q[2]);
H(q[0]);
Rz(q[0], 1.57079632679489661923);
CX(q[1], q[0]);
CX(q[2], q[0]);
Rz(q[0], -1.57079632679489661923);
H(q[0]);
X(q[0]);
Z(q[2]);
H(q[0]);
X(q[1]);
CX(q[1], q[2]);
H(q[2]);
CX(q[0], q[2]);
H(q[1]);
H(q[0]);
H(q[2]);
CX(q[0], q[2]);
CX(q[0], q[2]);
})";
} // end anon namespace
int main(int argc, char **argv) {
xacc::Initialize(argc, argv);
auto xasmCompiler = xacc::getCompiler("xasm");
auto optimizer = xacc::getService<xacc::IRTransformation>("circuit-optimizer");
auto ir = xasmCompiler->compile(testHadamardGateReductionSrc);
auto circuitComposite = ir->getComposites()[0];
std::cout << "Number of instructions before optimization is: " << circuitComposite->nInstructions() << "\n";
// Run the IRTransformation optimizer
optimizer->apply(circuitComposite, nullptr);
std::cout << "Number of instructions after optimization is: " << circuitComposite->nInstructions() << "\n";
xacc::Finalize();
return 0;
}
\ No newline at end of file
......@@ -12,16 +12,6 @@
*******************************************************************************/
#include "xacc.hpp"
template <typename T> std::vector<T> linspace(T a, T b, size_t N) {
T h = (b - a) / static_cast<T>(N - 1);
std::vector<T> xs(N);
typename std::vector<T>::iterator x;
T val;
for (x = xs.begin(), val = a; x != xs.end(); ++x, val += h)
*x = val;
return xs;
}
int main(int argc, char **argv) {
xacc::Initialize(argc, argv);
......@@ -40,7 +30,7 @@ int main(int argc, char **argv) {
program->addInstructions({x,ry,cx,h0,h1,m0,m1});
std::cout << "P:\n" << program->toString() << "\n";
auto angles = linspace(-xacc::constants::pi, xacc::constants::pi, 20);
auto angles = xacc::linspace(-xacc::constants::pi, xacc::constants::pi, 20);
for (auto &a : angles) {
auto buffer = xacc::qalloc(2);
auto evaled = program->operator()({a});
......
......@@ -12,16 +12,6 @@
*******************************************************************************/
#include "xacc.hpp"
template <typename T> std::vector<T> linspace(T a, T b, size_t N) {
T h = (b - a) / static_cast<T>(N - 1);
std::vector<T> xs(N);
typename std::vector<T>::iterator x;
T val;
for (x = xs.begin(), val = a; x != xs.end(); ++x, val += h)
*x = val;
return xs;
}
int main(int argc, char **argv) {
xacc::Initialize(argc, argv);
......@@ -41,7 +31,7 @@ int main(int argc, char **argv) {
auto program = ir->getComposite("ansatz");
auto angles = linspace(-xacc::constants::pi, xacc::constants::pi, 20);
auto angles = xacc::linspace(-xacc::constants::pi, xacc::constants::pi, 20);
for (auto &a : angles) {
auto buffer = xacc::qalloc(2);
auto evaled = program->operator()({a});
......
# *******************************************************************************
# Copyright (c) 2019 UT-Battelle, LLC.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# and Eclipse Distribution License v.10 which accompany this distribution.
# The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
# and the Eclipse Distribution License is available at
# https://eclipse.org/org/documents/edl-v10.php
#
# Contributors:
# Alexander J. McCaskey - initial API and implementation
# *******************************************************************************/
add_executable(base_api base_api.cpp)
target_link_libraries(base_api PRIVATE xacc)
add_executable(kernel_compilation kernel_compilation.cpp)
target_link_libraries(kernel_compilation PRIVATE xacc)
add_executable(hybrid_deuteron hybrid_deuteron.cpp)
target_link_libraries(hybrid_deuteron PRIVATE xacc xacc-quantum-gate)
add_executable(hybrid_ddcl hybrid_ddcl.cpp)
target_link_libraries(hybrid_ddcl PRIVATE xacc)
#include "xacc.hpp"
int main(int argc, char **argv) {
xacc::Initialize(argc, argv);
// Get reference to the Accelerator
auto accelerator = xacc::getAccelerator("tnqvm");
// Get the IRProvider and create an
// empty CompositeInstruction
auto provider = xacc::getIRProvider("quantum");
auto program = provider->createComposite("foo", {"t"});
// Create X, Ry, CX, and Measure gates
auto x = provider->createInstruction("X", {0});
auto ry = provider->createInstruction("Ry", {1}, {"t"});
auto cx = provider->createInstruction("CNOT", {1, 0});
auto m0 = provider->createInstruction("Measure", {0});
// Add them to the CompositeInstruction
program->addInstructions({x, ry, cx, m0});
// Loop over [-pi, pi] and compute <Z0>
auto angles = xacc::linspace(-xacc::constants::pi, xacc::constants::pi, 20);
for (auto &a : angles) {
auto buffer = xacc::qalloc(2);
auto evaled = program->operator()({a});
accelerator->execute(buffer, evaled);
std::cout << "<Z0>(" << a << ") = " << buffer->getExpectationValueZ()
<< "\n";
}
xacc::Finalize();
return 0;
}
#include "xacc.hpp"
int main(int argc, char **argv) {
xacc::Initialize(argc, argv);
// Get reference to the Accelerator
auto qpu =
xacc::getAccelerator("local-ibm");
auto opt =
xacc::getOptimizer("mlpack");
xacc::qasm(R"(
.compiler xasm
.circuit ansatz
.parameters x
.qbit q
U(q[0], x[0], -pi/2, pi/2 );
U(q[0], 0, 0, x[1]);
U(q[1], x[2], -pi/2, pi/2);
U(q[1], 0, 0, x[3]);
CNOT(q[0], q[1]);
U(q[0], 0, 0, x[4]);
U(q[0], x[5], -pi/2, pi/2);
U(q[1], 0, 0, x[6]);
U(q[1], x[7], -pi/2, pi/2);
)");
auto ansatz = xacc::getCompiled("ansatz");
std::vector<double> target_distribution
{.5, .5, .5, .5};
auto ddcl = xacc::getAlgorithm("ddcl");
ddcl->initialize({
std::make_pair("ansatz", ansatz),
std::make_pair("target_dist",
target_distribution),
std::make_pair("accelerator", qpu),
std::make_pair("loss", "js"),
std::make_pair("gradient",
"js-parameter-shift"),
std::make_pair("optimizer", opt)});
// Allocate some qubits and execute
auto buffer = xacc::qalloc(2);
ddcl->execute(buffer);
// Print the result
std::cout << "Loss: " <<
(*buffer)["opt-val"].as<double>()
<< "\n";
}
\ No newline at end of file
#include "xacc.hpp"
#include "xacc_observable.hpp"
int main(int argc, char **argv) {
xacc::Initialize(argc, argv);
// Get the desired Accelerator and Optimizer
auto qpu =
xacc::getAccelerator("qpp");
auto optimizer = xacc::getOptimizer("nlopt");
// Create the N=3 deuteron Hamiltonian
auto H_N_3 = xacc::quantum::getObservable(
"pauli",
std::string("15.531709 - 2.1433 X0X1 - "
"2.1433 Y0Y1 + .21829 Z0 - 6.125 Z1 - "
"9.625 Z2 - 3.91 X1 X2 - 3.91 Y1 Y2"));
// JIT map Quil QASM Ansatz to IR
xacc::qasm(R"(
.compiler xasm
.circuit ansatz
.parameters t0, t1
.qbit q
X(q[0]);
exp_i_theta(q, t0,
{{"pauli", "X0 Y1 - Y0 X1"}});
exp_i_theta(q, t1,
{{"pauli", "X0 Z1 Y2 - X2 Z1 Y0"}});
)");
auto ansatz = xacc::getCompiled("ansatz");
// Get the VQE Algorithm and initialize it
auto vqe = xacc::getAlgorithm("vqe");
vqe->initialize({
std::make_pair("ansatz", ansatz),
std::make_pair("observable", H_N_3),
std::make_pair("accelerator", qpu),
std::make_pair("optimizer", optimizer)
});
// Allocate some qubits and execute
auto buffer = xacc::qalloc(3);
vqe->execute(buffer);
// Get the result
auto energy =
(*buffer)["opt-val"].as<double>();
std::cout << "Energy: " << energy << "\n";
xacc::Finalize();
return 0;
}
\ No newline at end of file
#include "xacc.hpp"
int main(int argc, char **argv) {
xacc::Initialize(argc, argv);
// Get reference to the Accelerator
auto accelerator =
xacc::getAccelerator("local-ibm");
// Allocate some qubits
auto buffer = xacc::qalloc(2);
// Compile
auto quil = xacc::getCompiler("quil");
auto ir = quil->compile(
R"(__qpu__ void bell(qbit q) {
H 0
CX 0 1
MEASURE 0 [0]
MEASURE 1 [1]
})", accelerator);
// Execute
accelerator->execute(buffer,
ir->getComposites()[0]);
// View results
buffer->print();
xacc::Finalize();
return 0;
}
\ No newline at end of file
......@@ -60,9 +60,11 @@ public:
auto crz= std::make_shared<xacc::quantum::CRZ>();
auto ch = std::make_shared<xacc::quantum::CH>();
auto ifstmt = std::make_shared<xacc::quantum::IfStmt>();
auto scheduler = std::make_shared<xacc::quantum::PulseScheduler>();
context.RegisterService<xacc::Scheduler>(scheduler);
context.RegisterService<xacc::Instruction>(h);
context.RegisterService<xacc::Instruction>(cn);
context.RegisterService<xacc::Instruction>(cp);
......@@ -77,6 +79,7 @@ public:
context.RegisterService<xacc::Instruction>(z);
context.RegisterService<xacc::Instruction>(sw);
context.RegisterService<xacc::Instruction>(u);
context.RegisterService<xacc::Instruction>(ifstmt);
context.RegisterService<xacc::Instruction>(s);
context.RegisterService<xacc::Instruction>(sdg);
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment