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

Updating staq support to translate XACC IR to Cirq python, added cirq...


Updating staq support to translate XACC IR to Cirq python, added cirq accelerator targeting local simulator

Signed-off-by: Mccaskey, Alex's avatarAlex McCaskey <mccaskeyaj@ornl.gov>
parent e980988e
......@@ -43,6 +43,7 @@ install(DIRECTORY benchmark DESTINATION ${CMAKE_INSTALL_PREFIX})
file(GLOB PYDECORATORS benchmark/chemistry/*.py
plugins/aer/*.py
plugins/dwave/*.py
plugins/cirq/*.py
plugins/qiskit/*.py
plugins/observables/*.py
plugins/optimizers/*.py)
......
import xacc
from pelix.ipopo.decorators import ComponentFactory, Property, Requires, Provides, \
Validate, Invalidate, Instantiate
@ComponentFactory("cirq_accelerator_factory")
@Provides("accelerator")
@Property("_accelerator", "accelerator", "cirq")
@Property("_name", "name", "cirq")
@Instantiate("cirq_accelerator_instance")
class CirqAccelerator(xacc.Accelerator):
def __init__(self):
xacc.Accelerator.__init__(self)
self.shots = 1024
self.backend = 'simulator'
def initialize(self, options):
if 'shots' in options:
self.shots = options['shots']
if 'backend' in options:
self.backend = options['backend']
def name(self):
return 'cirq'
def execute_one_qasm(self, buffer, program):
import cirq
staq = xacc.getCompiler('staq')
cirq_code = staq.translate(program, {'lang-type':'cirq'})
cirq_code = cirq_code[0:len(cirq_code)-15]
exec(cirq_code, globals(), globals())
# Now we have a circuit variable for execution with Cirq
simulator = cirq.Simulator()
result = simulator.run(circuit, repetitions=self.shots)
import re
qbit2keys = {}
for qq in q:
m = re.search(r"\[([0-9_]+)\]", str(qq))
qbit2keys[int(m.group(1))] = str(qq).replace('[', '_c[')
bs = []
for i in range(self.shots):
b = [0 for i in range(buffer.size())]
for k,v in qbit2keys.items():
b[k] = result._measurements[v][i][0]
bs.append(''.join([str(bb) for bb in b]))
[buffer.appendMeasurement(bb) for bb in bs]
def execute(self, buffer, programs):
# 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_one_qasm(tmpBuffer, p)
buffer.appendChild(p.name(),tmpBuffer)
else:
if isinstance(programs, list):
programs = programs[0]
self.execute_one_qasm(buffer, programs)
......@@ -11,6 +11,7 @@
* Alexander J. McCaskey - initial API and implementation
*******************************************************************************/
#include "py_compiler.hpp"
#include "py_heterogeneous_map.hpp"
void bind_compiler(py::module &m) {
......@@ -32,7 +33,22 @@ void bind_compiler(py::module &m) {
xacc::Compiler::compile,
"Compile the "
"given source code.")
.def("translate", &xacc::Compiler::translate,
.def("translate",
(const std::string (xacc::Compiler::*)(
std::shared_ptr<CompositeInstruction>)) &
xacc::Compiler::translate,
"Translate the given IR Function instance to source code in this "
"Compiler's language.");
"Compiler's language.")
.def(
"translate",
[](xacc::Compiler &c, std::shared_ptr<CompositeInstruction> prog,
const PyHeterogeneousMap &opts) {
xacc::HeterogeneousMap m;
for (auto &item : opts) {
PyHeterogeneousMap2HeterogeneousMap vis(m, item.first);
mpark::visit(vis, item.second);
}
return c.translate(prog, m);
},
"");
}
\ No newline at end of file
......@@ -103,6 +103,7 @@ void bind_ir(py::module &m) {
return c.expand(m);
},
"")
.def("__str__", &xacc::CompositeInstruction::toString, "")
.def("eval", &xacc::CompositeInstruction::operator(), "")
.def("name", &xacc::CompositeInstruction::name, "")
.def("description", &xacc::CompositeInstruction::description, "")
......
......@@ -25,6 +25,8 @@
#include "transformations/oracle_synthesizer.hpp"
#include "optimization/simplify.hpp"
#include "output/cirq.hpp"
using namespace staq::ast;
namespace xacc {
......@@ -94,7 +96,7 @@ std::shared_ptr<IR> StaqCompiler::compile(const std::string &src,
_src = "OPENQASM 2.0;\n" + _src;
}
// std::cout << " HELLO:\n" << _src << "\n";
// std::cout << " HELLO:\n" << _src << "\n";
using namespace staq;
auto prog = parser::parse_string(_src);
transformations::desugar(*prog);
......@@ -176,15 +178,15 @@ std::shared_ptr<IR> StaqCompiler::compile(const std::string &src) {
const std::string
StaqCompiler::translate(std::shared_ptr<xacc::CompositeInstruction> function) {
std::map<std::string,int> bufNamesToSize;
std::map<std::string, int> bufNamesToSize;
InstructionIterator iter(function);
// First search buffer names and see if we have
while(iter.hasNext()) {
while (iter.hasNext()) {
auto &next = *iter.next();
if (next.isEnabled()) {
for (int i = 0; i < next.nRequiredBits(); i++) {
auto bufName = next.getBufferName(i);
int size = next.bits()[i]+1;
int size = next.bits()[i] + 1;
if (bufNamesToSize.count(bufName)) {
if (bufNamesToSize[bufName] < size) {
bufNamesToSize[bufName] = size;
......@@ -196,9 +198,10 @@ StaqCompiler::translate(std::shared_ptr<xacc::CompositeInstruction> function) {
}
}
auto translate = std::make_shared<internal_staq::XACCToStaqOpenQasm>(bufNamesToSize);
auto translate =
std::make_shared<internal_staq::XACCToStaqOpenQasm>(bufNamesToSize);
InstructionIterator iter2(function);
while(iter2.hasNext()) {
while (iter2.hasNext()) {
auto &next = *iter2.next();
if (next.isEnabled()) {
next.accept(translate);
......@@ -207,4 +210,61 @@ StaqCompiler::translate(std::shared_ptr<xacc::CompositeInstruction> function) {
return translate->ss.str();
}
const std::string
StaqCompiler::translate(std::shared_ptr<CompositeInstruction> program,
const HeterogeneousMap &options) {
if (options.stringExists("lang-type")) {
auto langType = options.getString("lang-type");
// map xacc to staq program
std::map<std::string, int> bufNamesToSize;
InstructionIterator iter(program);
// First search buffer names and see if we have
while (iter.hasNext()) {
auto &next = *iter.next();
if (next.isEnabled()) {
for (int i = 0; i < next.nRequiredBits(); i++) {
auto bufName = next.getBufferName(i);
int size = next.bits()[i] + 1;
if (bufNamesToSize.count(bufName)) {
if (bufNamesToSize[bufName] < size) {
bufNamesToSize[bufName] = size;
}
} else {
bufNamesToSize.insert({bufName, size});
}
}
}
}
auto translate =
std::make_shared<internal_staq::XACCToStaqOpenQasm>(bufNamesToSize);
InstructionIterator iter2(program);
while (iter2.hasNext()) {
auto &next = *iter2.next();
if (next.isEnabled()) {
next.accept(translate);
}
}
// std::cout << "HELLO:\n" << translate->ss.str() << "\n";
using namespace staq;
auto prog = parser::parse_string(translate->ss.str());
transformations::desugar(*prog);
transformations::synthesize_oracles(*prog);
optimization::simplify(*prog);
std::stringstream ss;
if (langType == "cirq") {
staq::output::CirqOutputter outputter(ss);
outputter.run(*prog);
}
return ss.str();
} else {
return translate(program);
}
}
} // namespace xacc
......@@ -5,7 +5,7 @@
* 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
* License is available at https://eclipse.org/org/documents/edl-v10.php
*
* Contributors:
* Alexander J. McCaskey - initial API and implementation
......@@ -18,6 +18,7 @@
namespace xacc {
class StaqCompiler : public xacc::Compiler {
public:
StaqCompiler();
......@@ -29,6 +30,9 @@ public:
const std::string
translate(std::shared_ptr<CompositeInstruction> function) override;
const std::string translate(std::shared_ptr<CompositeInstruction> program,
const HeterogeneousMap &options) override;
const std::string name() const override { return "staq"; }
const std::string description() const override { return ""; }
......
......@@ -150,6 +150,24 @@ measure c -> result;
// std::cout << hello->toString() << "\n";
}
TEST(StaqCompilerTester, checkCirq) {
auto compiler = xacc::getCompiler("staq");
auto IR = compiler->compile(R"(
qreg q[2];
creg c[2];
U(0,0,0) q[0];
CX q[0],q[1];
rx(3.3) q[0];
measure q -> c;
)");
auto hello = IR->getComposites()[0];
std::cout << "HELLO:\n" << hello->toString() << "\n";
auto c = compiler->translate(hello, {std::make_pair("lang-type", "cirq")});
std::cout << "CIRQ: " << c << "\n";
}
int main(int argc, char **argv) {
xacc::Initialize(argc, argv);
xacc::set_verbose(true);
......
......@@ -29,7 +29,13 @@ public:
virtual std::shared_ptr<IR> compile(const std::string &src) = 0;
virtual const std::string
translate(std::shared_ptr<CompositeInstruction> CompositeInstruction) = 0;
translate(std::shared_ptr<CompositeInstruction> program) = 0;
virtual const std::string
translate(std::shared_ptr<CompositeInstruction> program, const HeterogeneousMap& options) {
// default just call translate
return translate(program);
}
virtual const std::shared_ptr<CompositeInstruction>
compile(std::shared_ptr<CompositeInstruction> f,
......
Supports Markdown
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