Commit 46e82e89 authored by Mccaskey, Alex's avatar Mccaskey, Alex
Browse files

Merge branch 'master' into mc-vqe-devel

parents b757d3ee 1d88e375
image: xacc/gitpod-base
tasks:
- init: mkdir build && cd build && cmake .. -DXACC_BUILD_EXAMPLES=TRUE && make -j12 install && cd .. && mkdir plugins && cd plugins && git clone https://github.com/ornl-qci/tnqvm && cd tnqvm && mkdir build && cd build && cmake .. && make -j12 install
- init: mkdir build && cd build && CC=gcc-8 CXX=g++-8 cmake .. -DXACC_BUILD_EXAMPLES=TRUE && make -j12 install && cd .. && mkdir plugins && cd plugins && git clone https://github.com/ornl-qci/tnqvm && cd tnqvm && mkdir build && cd build && cmake .. && make -j12 install
- command: make -j4 -C build/ install && make -j4 -C plugins/tnqvm/build install && echo "export PYTHONPATH=$PYTHONPATH:$HOME/.xacc:/home/gitpod/.local/lib/python3.7/site-packages/psi4/lib" >> $HOME/.bashrc && source $HOME/.bashrc
vscode:
extensions:
......
......@@ -166,3 +166,72 @@ install( DIRECTORY "${CMAKE_SOURCE_DIR}/tpls/exprtk" DESTINATION include )
install( DIRECTORY "${CMAKE_SOURCE_DIR}/tpls/eigen" DESTINATION include )
install( DIRECTORY "${CMAKE_SOURCE_DIR}/tpls/rapidjson" DESTINATION include )
install( DIRECTORY "${CMAKE_SOURCE_DIR}/tpls/pybind11" DESTINATION include )
if (XACC_CPACK_DEB_PLATFORM)
message(STATUS "CPack DEB Build Enabled.")
set(CPACK_SET_DESTDIR "on")
set(CPACK_PACKAGING_INSTALL_PREFIX "/tmp")
set(CPACK_GENERATOR "DEB")
set(MAJOR_VERSION 1)
set(MINOR_VERSION 0)
set(PATCH_VERSION 0)
set(CPACK_PACKAGE_DESCRIPTION "xacc quantum programming framework")
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "xacc provides a service-oriented architecture enabling the programming, compilation, and execution of quantum code on quantum co-processors.")
set(CPACK_PACKAGE_VENDOR "ORNL")
set(CPACK_PACKAGE_CONTACT "mccaskeyaj@ornl.gov")
set(CPACK_PACKAGE_VERSION_MAJOR "${MAJOR_VERSION}")
set(CPACK_PACKAGE_VERSION_MINOR "${MINOR_VERSION}")
set(CPACK_PACKAGE_VERSION_PATCH "${PATCH_VERSION}")
set(CPACK_PACKAGE_FILE_NAME "${CMAKE_PROJECT_NAME}-${MAJOR_VERSION}.${MINOR_VERSION}.${PATCH_VERSION}")
set(CPACK_SOURCE_PACKAGE_FILE_NAME "${CMAKE_PROJECT_NAME}-${MAJOR_VERSION}.${MINOR_VERSION}.${PATCH_VERSION}")
set(CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA "${CMAKE_SOURCE_DIR}/scripts/debian/postinst")
#dependencies for this service menu
if (${XACC_CPACK_DEB_PLATFORM} STREQUAL "bionic")
set(CPACK_DEBIAN_PACKAGE_DEPENDS "gcc-8, g++-8, libblas-dev, liblapack-dev, python3, python3-pip, libpython3-dev, libcurl4-openssl-dev, libssl-dev")
elseif(${XACC_CPACK_DEB_PLATFORM} STREQUAL "focal")
set(CPACK_DEBIAN_PACKAGE_DEPENDS "gcc-10, g++-10, libblas-dev, liblapack-dev, python3, python3-pip, libpython3-dev, libcurl4-openssl-dev, libssl-dev")
endif()
set(CPACK_DEBIAN_PACKAGE_PRIORITY "optional")
set(CPACK_DEBIAN_PACKAGE_SECTION "base")
set(CPACK_DEBIAN_ARCHITECTURE ${CMAKE_SYSTEM_PROCESSOR})
include(CPack)
endif()
if (XACC_CPACK_RPM_PLATFORM)
message(STATUS "CPack RPM Build Enabled.")
set(CPACK_SET_DESTDIR "on")
set(CPACK_PACKAGING_INSTALL_PREFIX "/tmp")
set(CPACK_GENERATOR "RPM")
set(CPACK_COMPONENTS_ALL DIST DEVEL)
set(CPACK_COMPONENTS_GROUPING ONE_PER_GROUP)
set(CPACK_COMPONENTS_IGNORE_GROUPS 1)
SET(CPACK_RPM_PACKAGE_GROUP "Development/Libraries")
set(CPACK_RPM_DIST_POST_INSTALL_SCRIPT_FILE ${CMAKE_SOURCE_DIR}/scripts/debian/postinst)
set(MAJOR_VERSION 1)
set(MINOR_VERSION 0)
set(PATCH_VERSION 0)
set(CPACK_PACKAGE_DESCRIPTION "xacc quantum programming framework")
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "xacc provides a service-oriented architecture enabling the programming, compilation, and execution of quantum code on quantum co-processors.")
set(CPACK_PACKAGE_VENDOR "ORNL")
set(CPACK_PACKAGE_CONTACT "mccaskeyaj@ornl.gov")
set(CPACK_PACKAGE_VERSION_MAJOR "${MAJOR_VERSION}")
set(CPACK_PACKAGE_VERSION_MINOR "${MINOR_VERSION}")
set(CPACK_PACKAGE_VERSION_PATCH "${PATCH_VERSION}")
set(CPACK_PACKAGE_FILE_NAME "${CMAKE_PROJECT_NAME}-${MAJOR_VERSION}.${MINOR_VERSION}.${PATCH_VERSION}")
set(CPACK_SOURCE_PACKAGE_FILE_NAME "${CMAKE_PROJECT_NAME}-${MAJOR_VERSION}.${MINOR_VERSION}.${PATCH_VERSION}")
#dependencies for this service menu
if (${XACC_CPACK_RPM_PLATFORM} STREQUAL "fedora31")
set(CPACK_RPM_PACKAGE_REQUIRES "gcc-c++, gcc-gfortran, blas-devel, lapack-devel, git, python3-devel, libcurl-devel, openssl-devel")
elseif(${XACC_CPACK_RPM_PLATFORM} STREQUAL "focal")
endif()
include(CPack)
endif()
\ No newline at end of file
......@@ -19,9 +19,9 @@ If you don’t, you need to [register](https://dev.eclipse.org/site_login/create
* Login to the [projects portal](https://projects.eclipse.org/), select “My Account”, and then the “Eclipse ECA” tab.
* Add your GitHub ID in your Eclipse Foundation account. Find this option in the "Account Settings" tab.
* Add your GitHub ID in your Eclipse Foundation account. Find this option in the "Personal Information" tab under "Edit Your Account".
* "Sign-off" your commits
* "Sign-off" your commits!
Every commit you make in your patch or pull request MUST be "signed off".
......
......@@ -451,6 +451,98 @@ You can also use this simulator from C++, just make sure you load the Python ext
xacc::external::unload_external_language_plugins();
xacc::Finalize();
TNQVM
+++++
`TNQVM <https://github.com/ORNL-QCI/tnqvm>`_ provides an Accelerator implementation that leverages tensor network theory to simulate quantum circuits.
TNQVM implements a few tensor-based quantum circuit simulators that can be specified by the `tnqvm-visitor` configuration key.
The list of visitors and their descriptions are:
+--------------------+------------------------------------------------------------------------+
| `tnqvm-visitor` | Description |
+====================+========================================================================+
| `itensor-mps` | MPS simulator based on itensor library. |
+--------------------+------------------------------------------------------------------------+
| `exatn` | Full tensor contraction simulator based on ExaTN library. |
| | Tensor element type (`float` or `double`) can also specified |
| | after a '`:`' separator, |
| | e.g., `exatn:double` (default) or `exatn:float` |
+--------------------+------------------------------------------------------------------------+
| `exatn-mps` | MPS simulator based on ExaTN library. |
+--------------------+------------------------------------------------------------------------+
| `exatn-pmps` | Purified-MPS (density matrix) simulator based on ExaTN library. |
+--------------------+------------------------------------------------------------------------+
.. code:: cpp
auto qpu = xacc::getAccelerator("tnqvm", {{"tnqvm-visitor", "exatn"}});
For the `exatn` simulator, there are additional options that users can set during initialization:
+-----------------------------+------------------------------------------------------------------------+-------------+--------------------------+
| Initialization Parameter | Parameter Description | type | default |
+=============================+========================================================================+=============+==========================+
| exatn-buffer-size-gb | ExaTN's host memory buffer size (in GB) | int | 8 (GB) |
+-----------------------------+------------------------------------------------------------------------+-------------+--------------------------+
| exatn-contract-seq-optimizer| ExaTN's contraction sequence optimizer to use. | string | metis |
+-----------------------------+------------------------------------------------------------------------+-------------+--------------------------+
| calc-contract-cost-flops | Estimate the Flops and Memory requirements only (no tensor contraction)| bool | false |
| | | | |
| | If true, the following info will be added to the AcceleratorBuffer: | | |
| | | | |
| | - `contract-flops`: Flops count. | | |
| | | | |
| | - `max-node-bytes`: Max intermediate tensor size in memory. | | |
| | | | |
| | - `optimizer-elapsed-time-ms`: optimization walltime. | | |
+-----------------------------+------------------------------------------------------------------------+-------------+--------------------------+
| bitstring | If provided, the output amplitude/partial state vector associated with | vector<int> | <unused> |
| | that `bitstring` will be computed. | | |
| | | | |
| | The length of the input `bitstring` must match the number of qubits. | | |
| | Non-projected bits (partial state vector) are indicated by `-1` values.| | |
| | | | |
| | Returned values in the AcceleratorBuffer: | | |
| | | | |
| | - `amplitude-real`/`amplitude-real-vec`: Real part of the result. | | |
| | | | |
| | - `amplitude-imag`/`amplitude-imag-vec`: Imaginary part of the result. | | |
+-----------------------------+------------------------------------------------------------------------+-------------+--------------------------+
| contract-with-conjugate | If true, we append the conjugate of the input circuit. | bool | false |
| | This is used to validate internal tensor contraction. | | |
| | `contract-with-conjugate-result` key in the AcceleratorBuffer will be | | |
| | set to `true` if the validation is successful. | | |
+-----------------------------+------------------------------------------------------------------------+-------------+--------------------------+
| mpi-communicator | The MPI communicator to initialize ExaTN runtime with. | void* | <unused> |
| | If not provided, by default, ExaTN will use `MPI_COMM_WORLD`. | | |
+-----------------------------+------------------------------------------------------------------------+-------------+--------------------------+
For the `exatn-mps` simulator, there are additional options that users can set during initialization:
+-----------------------------+------------------------------------------------------------------------+-------------+--------------------------+
| Initialization Parameter | Parameter Description | type | default |
+=============================+========================================================================+=============+==========================+
| svd-cutoff | SVD cut-off limit. | double | numeric_limits::min |
+-----------------------------+------------------------------------------------------------------------+-------------+--------------------------+
| max-bond-dim | Max bond dimension to keep. | int | no limit |
+-----------------------------+------------------------------------------------------------------------+-------------+--------------------------+
| mpi-communicator | The MPI communicator to initialize ExaTN runtime with. | void* | <unused> |
| | If not provided, by default, ExaTN will use `MPI_COMM_WORLD`. | | |
+-----------------------------+------------------------------------------------------------------------+-------------+--------------------------+
For the `exatn-pmps` simulator, there are additional options that users can set during initialization:
+-----------------------------+------------------------------------------------------------------------+-------------+--------------------------+
| Initialization Parameter | Parameter Description | type | default |
+=============================+========================================================================+=============+==========================+
| backend-json | Backend configuration JSON to estimate the noise model from. | string | None |
+-----------------------------+------------------------------------------------------------------------+-------------+--------------------------+
| backend | Name of the IBMQ backend to query the backend configuration. | string | None |
+-----------------------------+------------------------------------------------------------------------+-------------+--------------------------+
If either `backend-json` or `backend` is provided, the `exatn-pmps` simulator will simulate the backend noise associated with each quantum gate.
QuaC
++++
The `QuaC <https://github.com/ORNL-QCI/QuaC/tree/xacc-integration>`_ accelerator is a pulse-level accelerator (simulation only) that can execute quantum circuits at both gate and pulse (analog) level.
......@@ -985,6 +1077,12 @@ The QAOA Algorithm requires the following input information:
| steps | The number of timesteps. Corresponds to 'p' in the literature. | int |
| | This is optional, default = 1 if not provided. | |
+------------------------+-----------------------------------------------------------------+--------------------------------------+
| parameter-scheme | The QAOA parameterization scheme ('Extended' or 'Standard'). | string |
| | This is optional, default = 'Extended' if not provided. | |
+------------------------+-----------------------------------------------------------------+--------------------------------------+
| graph | The MaxCut graph problem. | std::shared_ptr<Graph> |
| | If provided, the cost Hamiltonian is constructed automatically. | |
+------------------------+-----------------------------------------------------------------+--------------------------------------+
This Algorithm will add ``opt-val`` (``double``) and ``opt-params`` (``std::vector<double>``) to the provided ``AcceleratorBuffer``.
The results of the algorithm are therefore retrieved via these keys (see snippet below). Note you can
......
......@@ -15,7 +15,7 @@ set(LIBRARY_NAME xacc-py-plugin-loader)
get_filename_component(PYTHON_LIB_NAME ${Python_LIBRARIES} NAME)
configure_file(py_plugin_loader.in.cpp
${CMAKE_BINARY_DIR}/python/plugins/py_plugin_loader.cpp)
message(STATUS " PYTHON: ${PYTHON_LIB_NAME}")
file (GLOB SRC ${CMAKE_BINARY_DIR}/python/plugins/py_plugin_loader.cpp py_plugin_loader_activator.cpp)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-deprecated-declarations")
......@@ -50,3 +50,5 @@ else()
endif()
install(TARGETS ${LIBRARY_NAME} DESTINATION ${CMAKE_INSTALL_PREFIX}/plugins)
add_subdirectory(mitiq)
\ No newline at end of file
# *******************************************************************************
# 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
# *******************************************************************************/
set(LIBRARY_NAME xacc-mitiq-zne)
configure_file(mitiq_zne_decorator.in.cpp
${CMAKE_BINARY_DIR}/python/plugins/mitiq/mitiq_zne_decorator.cpp)
file(GLOB SRC ${CMAKE_BINARY_DIR}/python/plugins/mitiq/mitiq_zne_decorator.cpp)
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-strict-aliasing -O2 -g -pipe -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wformat -fexceptions --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=native -D_GNU_SOURCE -fPIC -fwrapv")
usfunctiongetresourcesource(TARGET ${LIBRARY_NAME} OUT SRC)
usfunctiongeneratebundleinit(TARGET ${LIBRARY_NAME} OUT SRC)
add_library(${LIBRARY_NAME} SHARED ${SRC})
target_include_directories(
${LIBRARY_NAME}
PUBLIC . ${Python_INCLUDE_DIRS} ${CMAKE_SOURCE_DIR}/tpls/pybind11/include)
target_link_libraries(${LIBRARY_NAME} PUBLIC xacc Python::Python)
set(_bundle_name xacc_mitiq_zne)
set_target_properties(${LIBRARY_NAME}
PROPERTIES COMPILE_DEFINITIONS
US_BUNDLE_NAME=${_bundle_name}
US_BUNDLE_NAME
${_bundle_name})
usfunctionembedresources(TARGET
${LIBRARY_NAME}
WORKING_DIRECTORY
${CMAKE_CURRENT_SOURCE_DIR}
FILES
manifest.json)
if(APPLE)
set_target_properties(${LIBRARY_NAME}
PROPERTIES INSTALL_RPATH "@loader_path/../lib")
set_target_properties(${LIBRARY_NAME}
PROPERTIES LINK_FLAGS "-undefined dynamic_lookup")
else()
set_target_properties(${LIBRARY_NAME}
PROPERTIES INSTALL_RPATH "$ORIGIN/../lib")
set_target_properties(${LIBRARY_NAME} PROPERTIES LINK_FLAGS "-rdynamic -shared")
endif()
if (XACC_BUILD_TESTS)
#add_subdirectory(tests)
endif()
install(TARGETS ${LIBRARY_NAME} DESTINATION ${CMAKE_INSTALL_PREFIX}/plugins)
{
"bundle.symbolic_name" : "xacc_mitiq_zne",
"bundle.activator" : true,
"bundle.name" : "Mitiq ZNE Decorator",
"bundle.description" : ""
}
......@@ -27,18 +27,16 @@ class MitiqDecorator(xacc.AcceleratorDecorator):
def noisy_sim(circ : QuantumCircuit):
# Convert circ to a CompositeInstruction
out_src = circ.qasm()
# print('hello src:\n', out_src)
out_prog = self.openqasm_compiler.compile(out_src).getComposites()[0]
# print('after compile:\n', out_prog.toString())
# Execute on a tmp buffer
tmp_buffer = xacc.qalloc(buffer.size())
self.decoratedAccelerator.execute(tmp_buffer, out_prog)
# tmp_buffer.addExtraInfo('exp-val-z', tmp_buffer.getExpectationValueZ())
# record the noisy exp val
buffer.addExtraInfo('noisy-exp-val-z', tmp_buffer.getExpectationValueZ())
buffer.appendChild('mitiq-noisy-exec-'+buffer.name(), tmp_buffer)
# buffer.appendChild('mitiq-noisy-exec-'+buffer.name(), tmp_buffer)
return tmp_buffer.getExpectationValueZ()
# easiest thing to do is map to Qiskit
......@@ -47,22 +45,27 @@ class MitiqDecorator(xacc.AcceleratorDecorator):
# Create a QuantumCircuit
circuit = QuantumCircuit.from_qasm_str(src)
# print(circuit.qasm())
# print('New Circuit:\n', circuit.qasm())
fixed_exp = mitiq.execute_with_zne(circuit, noisy_sim)
# print(fixed_exp)
buffer.addExtraInfo('exp-val-z', fixed_exp)
return
def execute(self, buffer, programs):
print('[mitiq] executing Mitiq')
# Translate IR to a Qobj Json String
if isinstance(programs, list) and len(programs) > 1:
for p in programs:
tmpBuffer = xacc.qalloc(buffer.size())
tmpBuffer.setName(p.name())
self.execute_single(tmpBuffer, p)
print('\t[mitiq] <', p.name(), '>_noisy = ', tmpBuffer['noisy-exp-val-z'] ,' -> <', p.name(), '>_fixed = ', tmpBuffer['exp-val-z'])
buffer.appendChild(p.name(),tmpBuffer)
# print(tmpBuffer)
else:
if isinstance(programs, list):
programs = programs[0]
self.execute_single(buffer, programs)
# print('returning from mitiq')
return
/*******************************************************************************
* Copyright (c) 2018 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
*******************************************************************************/
#ifndef XACC_MITIQZNEDECORATOR_HPP_
#define XACC_MITIQZNEDECORATOR_HPP_
#include "AcceleratorDecorator.hpp"
#include <pybind11/embed.h>
namespace py = pybind11;
namespace xacc {
namespace python {
class MitiqZNE : public AcceleratorDecorator {
protected:
std::unique_ptr<py::scoped_interpreter> guard;
void * libpython_handle;
py::module xacc;
py::module qiskit;
py::module mitiq;
public:
void initialize(const HeterogeneousMap &params = {}) override;
void updateConfiguration(const HeterogeneousMap &config) override {
decoratedAccelerator->updateConfiguration(config);
}
const std::vector<std::string> configurationKeys() override { return {}; }
void execute(std::shared_ptr<AcceleratorBuffer> buffer,
const std::shared_ptr<CompositeInstruction> function) override;
void execute(std::shared_ptr<AcceleratorBuffer> buffer,
const std::vector<std::shared_ptr<CompositeInstruction>>
functions) override;
const std::string name() const override { return "mitiq-zne"; }
const std::string description() const override { return ""; }
~MitiqZNE();
};
} // namespace python
} // namespace xacc
#endif
/*******************************************************************************
* 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 "mitiq_zne_decorator.hpp"
#include "Utils.hpp"
#include "xacc.hpp"
#include <fstream>
#include <pylifecycle.h>
#include <set>
#include "cppmicroservices/BundleActivator.h"
#include "cppmicroservices/BundleContext.h"
#include "cppmicroservices/ServiceProperties.h"
#include <dlfcn.h>
using namespace cppmicroservices;
namespace py = pybind11;
using namespace py::literals;
namespace xacc {
namespace python {
MitiqZNE::~MitiqZNE() {
if (libpython_handle) {
int i = dlclose(libpython_handle);
if (i != 0) {
std::cout << "error closing python lib in mitiq: " << i << "\n";
std::cout << dlerror() << "\n";
}
}
}
void MitiqZNE::initialize(const HeterogeneousMap &params) {
if (!guard && !Py_IsInitialized()) {
guard = std::make_unique<py::scoped_interpreter>();
libpython_handle = dlopen("@PYTHON_LIB_NAME@", RTLD_LAZY | RTLD_GLOBAL);
}
if (Py_IsInitialized()) {
xacc = py::module::import("xacc");
mitiq = py::module::import("mitiq");
qiskit = py::module::import("qiskit");
}
}
void MitiqZNE::execute(std::shared_ptr<AcceleratorBuffer> buffer,
const std::shared_ptr<CompositeInstruction> function) {
// Map to OpenQasm
auto compiler = xacc::getCompiler("staq");
compiler->setExtraOptions({{"no-optimize", true}});
auto circuit_src = compiler->translate(function);
// Pass the necessary variables through the globals() map
auto globals = py::globals();
globals["global_qpu"] = decoratedAccelerator;
globals["global_circuit_src"] = circuit_src;
globals["global_staq_compiler"] = compiler;
globals["global_buffer"] = buffer;
globals["global_xacc_allocator"] = xacc.attr("qalloc");
globals["global_mitiq_executor"] = mitiq.attr("execute_with_zne");
globals["global_qk_from_qasm"] =
qiskit.attr("QuantumCircuit").attr("from_qasm_str");
auto py_src = R"#(
def noisy_exec(circ):
buffer = globals()['global_buffer']
program = globals()['global_staq_compiler'].compile(circ.qasm()).getComposites()[0]
tmp = globals()['global_xacc_allocator'](buffer.size())
globals()['global_qpu'].execute(tmp, program)
tmp.addExtraInfo('exp-val-z', tmp.getExpectationValueZ())
buffer.appendChild('mitiq-'+buffer.name(), tmp)
return tmp.getExpectationValueZ()
circuit = globals()['global_qk_from_qasm'](globals()['global_circuit_src'])
fixed_exp = globals()['global_mitiq_executor'](circuit, noisy_exec)
)#";
// Execute and get the fixed expectation value.
auto locals = py::dict();
py::exec(py_src, py::globals(), locals);
buffer->addExtraInfo("exp-val-z", locals["fixed_exp"].cast<double>());
}
void MitiqZNE::execute(
std::shared_ptr<AcceleratorBuffer> buffer,
const std::vector<std::shared_ptr<CompositeInstruction>> functions) {
for (auto &f : functions) {
auto tmpBuffer =
std::make_shared<xacc::AcceleratorBuffer>(f->name(), buffer->size());
execute(tmpBuffer, f);
buffer->appendChild(f->name(), tmpBuffer);
}
}
} // namespace python
} // namespace xacc
namespace {
/**
*/
class US_ABI_LOCAL MitiqZNEActivator : public BundleActivator {
public:
MitiqZNEActivator() {}
/**
*/
void Start(BundleContext context) {
auto xt = std::make_shared<xacc::python::MitiqZNE>();
context.RegisterService<xacc::AcceleratorDecorator>(xt);
}
/**
*/
void Stop(BundleContext /*context*/) {}
};
} // namespace
CPPMICROSERVICES_EXPORT_BUNDLE_ACTIVATOR(MitiqZNEActivator)
# *******************************************************************************
# 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_xacc_test(MitiqZNE)
target_link_libraries(MitiqZNETester xacc Python::Python)
\ No newline at end of file
/*******************************************************************************
* 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 <gtest/gtest.h>
#include "xacc.hpp"
#include "xacc_service.hpp"
const std::string noiseModelJson =
R"#({"errors": [{"type": "qerror", "operations": ["u1"], "instructions": [[{"name": "x", "qubits": [0]}], [{"name": "y", "qubits": [0]}], [{"name": "z", "qubits": [0]}], [{"name": "id", "qubits": [0]}]], "probabilities": [0.00025, 0.00025, 0.00025, 0.99925]}, {"type": "qerror", "operations": ["u2"], "instructions": [[{"name": "x", "qubits": [0]}], [{"name": "y", "qubits": [0]}], [{"name": "z", "qubits": [0]}], [{"name": "id", "qubits": [0]}]], "probabilities": [0.00025, 0.00025, 0.00025, 0.99925]}, {"type": "qerror", "operations": ["u3"], "instructions": [[{"name": "x", "qubits": [0]}], [{"name": "y", "qubits": [0]}], [{"name": "z", "qubits": [0]}], [{"name": "id", "qubits": [0]}]], "probabilities": [0.00025, 0.00025, 0.00025, 0.99925]}], "x90_gates": []})#";
TEST(MitiqZNETester, checkSimple) {
auto qpu = xacc::getAccelerator(
"aer", {{"noise-model", noiseModelJson}, {"shots", 4096}});
qpu = xacc::getAcceleratorDecorator("mitiq-zne", qpu);
auto q = xacc::qalloc(1);
xacc::qasm(R"#(.compiler xasm
.circuit foo
.parameters x
.qbit q
for (int i = 0; i < 50; i++) {
X(q[0]);
}
Measure(q[0]);
)#");
auto program = xacc::getCompiled("foo");
qpu->execute(q, program);
q->print(std::cout);
xacc::qasm(R"#(.compiler xasm
.circuit foo2
.parameters x
.qbit q
for (int i = 0; i < 50; i++) {
H(q[0]);
}
Measure(q[0]);
)#");
auto program2 = xacc::getCompiled("foo2");