Commit 7c53b151 authored by Mccaskey, Alex's avatar Mccaskey, Alex
Browse files

updates to latest PR


Signed-off-by: Mccaskey, Alex's avatarAlex McCaskey <mccaskeyaj@ornl.gov>
parent 698850df
Pipeline #58783 passed with stages
in 10 minutes and 58 seconds
# Installation management script for XACC benchmark plugin installation
#
import sys
import argparse
import os
import configparser
from shutil import copy
import xacc
MASTER_DIRS = ['vqe']
MASTER_PACKAGES = {}
TOP_PATH = os.path.dirname(os.path.realpath(__file__))
XACC_PYTHON_PLUGIN_PATH = "/root/.xacc/py-plugins/"
PLUGIN_INSTALLATIONS = {}
def parse_args(args):
parser = argparse.ArgumentParser(description="Installation manager for XACC benchmark plugins.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
fromfile_prefix_chars='@')
parser.add_argument("-i", "--install", type=str, help="Install a plugin package to the XACC plugin directory.", required=False)
parser.add_argument("-l", "--list", help="List all available plugin packages for installation.", required=False, action='store_true')
parser.add_argument("-p", "--path", help="Set the XACC Python Plugin path (default = /root/.xacc/py-plugins)", required=False)
opts = parser.parse_args(args)
return opts
def install_package(install_name):
try:
package_path = PLUGIN_INSTALLATIONS[install_name]
except KeyError as ex:
xacc.info("There is no '{}' XACC Python plugin package available.".format(install_name))
exit(1)
install_directive = os.path.join(package_path+"/install.ini") if os.path.isfile(package_path+"/install.ini") else None
plugin_files = []
if not install_directive:
plugin_files += [package_path+"/"+f for f in os.listdir(
package_path) if os.path.isfile(os.path.join(package_path, f)) and f.endswith(".py")]
else:
plugin_dict, plugin_list = read_install_directive(install_directive, package_path)
for k,v in plugin_dict.items():
mini_package_path = v
plugin_files += [v+"/"+f for f in os.listdir(v) if os.path.isfile(os.path.join(v, f)) and f.endswith(".py")]
n_plugins = len(plugin_files)
for plugin in plugin_files:
copy(os.path.join(plugin), XACC_PYTHON_PLUGIN_PATH)
xacc.info("Installed {} plugins from the '{}' package to the {} directory.".format(n_plugins, install_name, XACC_PYTHON_PLUGIN_PATH))
def set_plugin_path(path):
global XACC_PYTHON_PLUGIN_PATH
XACC_PYTHON_PLUGIN_PATH = path
def read_install_directive(install_file, parent):
config = configparser.RawConfigParser()
config.read(install_file)
results = {}
packages_here = []
for section in config.sections():
for installation in config.items(section):
name, folder = installation
packages_here.append(name)
folder = parent+folder
results.update(dict([(name, folder)]))
return results, packages_here
def get_packages():
for mdir in MASTER_DIRS:
plugins_path = os.path.join(TOP_PATH, mdir)
install_directives = plugins_path+"/install.ini"
package_dict, package_list = read_install_directive(install_directives, plugins_path)
PLUGIN_INSTALLATIONS.update(package_dict)
if mdir not in MASTER_PACKAGES:
MASTER_PACKAGES[mdir] = package_list
else:
MASTER_PACKAGES[mdir] += package_list
def main(argv=None):
opts = parse_args(sys.argv[1:])
get_packages()
if opts.path:
set_plugin_path(opts.path)
if opts.install:
install_package(opts.install)
if opts.list:
xacc.info("Available XACC Python plugin packages:")
for k, v in MASTER_PACKAGES.items():
xacc.info("{:5}: {!s}".format(k, v))
if __name__ == "__main__":
sys.exit(main())
......@@ -371,8 +371,8 @@ class PyServiceRegistry(object):
service = available_services[name]
except KeyError:
info("""There is no '{0}' with the name '{1}' available.
{2:28}1. Install the '{1}' '{0}' to the Python plugin directory.
{2:28}2. Make sure all required services for '{1}' are installed.\n""".format(serviceName, name, ""))
1. Install the '{1}' '{0}' to the Python plugin directory.
2. Make sure all required services for '{1}' are installed.\n""".format(serviceName, name, ""))
if serviceName == "benchmark_algorithm":
self.get_benchmark_requirements(name)
exit(1)
......
......@@ -118,7 +118,6 @@ std::vector<std::shared_ptr<AcceleratorBuffer>> ROErrorDecorator::execute(
auto bits = nextInst->bits();
for (auto &b : bits) {
supportSet.insert(b);
xacc::info(std::to_string(b));
}
}
}
......@@ -174,30 +173,21 @@ std::vector<std::shared_ptr<AcceleratorBuffer>> ROErrorDecorator::execute(
auto f = nameToFunction[functionName];
auto fSupports = supportSets[functionName];
auto exp_val = b->getExpectationValueZ();
auto bitMap = b->bit2IndexMap;
auto fixedExp = 0.0;
for (auto &kv : counts) {
auto prod = 1.0;
std::string bitString = kv.first;
auto count = kv.second;
for (auto& j : fSupports) {
xacc::info(functionName);
xacc::info(bitString);
xacc::info("bit: " + std::to_string(j) + " map: " + std::to_string(b->bit2IndexMap[j]));
std::stringstream s;
auto denom = (1.0 - piplus[j]);
auto numerator =
(bitString[bitString.length() - 1 - bitMap[j]] == '1' ? -1 : 1) - piminus[j];
(bitString[bitString.length() - 1 - j] == '1' ? -1 : 1) - piminus[j];
prod *= (numerator / denom);
}
fixedExp += ((double)count / (double)nShots) * prod;
}
xacc::info("exp val: " + std::to_string(fixedExp));
// Correct in case our shift has gone outside physical bounds
if (fixedExp > 1.0) { fixedExp = 1.0; }
if (fixedExp < -1.0) { fixedExp = -1.0; }
xacc::info("raw: " + std::to_string(exp_val));
xacc::info("fix: " + std::to_string(fixedExp));
b->addExtraInfo("ro-fixed-exp-val-z", ExtraInfo(fixedExp));
counter++;
......
......@@ -15,6 +15,7 @@
#include "XACC.hpp"
#include "xacc_config.hpp"
#include "PauliOperator.hpp"
#include <fstream>
using namespace xacc;
......
This diff is collapsed.
......@@ -316,11 +316,9 @@ IBMAccelerator::processInput(std::shared_ptr<AcceleratorBuffer> buffer,
int maxMemSlots = 0;
for (auto &kernel : functions) {
auto uniqueBits = kernel->bits();
auto visitor =
std::make_shared<QObjectExperimentVisitor>(kernel->name(), uniqueBits);
name2QubitMap.insert(std::make_pair(kernel->name(), visitor->qubit2MemorySlot));
std::make_shared<QObjectExperimentVisitor>(kernel->name(), chosenBackend.nQubits);
InstructionIterator it(kernel);
int memSlots = 0;
while (it.hasNext()) {
......@@ -474,7 +472,6 @@ IBMAccelerator::processResponse(std::shared_ptr<AcceleratorBuffer> buffer,
currentJobId = "";
d.Parse(getResponse);
// xacc::info(getResponse);
auto &qobjNode = d["qObject"];
auto &qobjResultNode = d["qObjectResult"];
......@@ -516,10 +513,7 @@ IBMAccelerator::processResponse(std::shared_ptr<AcceleratorBuffer> buffer,
auto currentExperiment = experiments[i];
auto tmpBuffer =
createBuffer(currentExperiment.get_header().get_name(), buffer->size());
tmpBuffer->setBitIndexMap(name2QubitMap[currentExperiment.get_header().get_name()]);
for (auto &kv : tmpBuffer->bit2IndexMap){
xacc::info("bit: " + std::to_string(kv.first) + ", mapped: " + std::to_string(kv.second));
}
auto counts = resultsArray[i].get_data().get_counts();
for (auto &kv : counts) {
......
......@@ -51,7 +51,7 @@ protected:
public:
int maxMemorySlots = 0;
std::map<int, int> qubit2MemorySlot;
// std::map<int, int> qubit2MemorySlot;
const std::string name() const override { return "qobject-visitor"; }
......@@ -59,13 +59,13 @@ public:
return "Map XACC IR to QObject.";
}
QObjectExperimentVisitor(const std::string expName, std::vector<int> qubits)
: experimentName(expName), nTotalQubits(qubits.size()) {
int counter = 0;
for (auto &b : qubits) {
qubit2MemorySlot.insert({b, counter});
counter++;
}
QObjectExperimentVisitor(const std::string expName, const int nQubits)
: experimentName(expName), nTotalQubits(nQubits) {
// int counter = 0;
// for (auto &b : qubits) {
// qubit2MemorySlot.insert({b, counter});
// counter++;
// }
}
const std::string toString() override {
......@@ -251,15 +251,16 @@ public:
"IBM: Invalid classical bit index for measurement, already used.");
}
auto classicalBit = m.getParameter(0).as<int>();
xacc::ibm::Instruction inst;
inst.get_mutable_qubits().push_back(m.bits()[0]);
inst.get_mutable_name() = "measure";
inst.set_memory({qubit2MemorySlot[m.bits()[0]]});
inst.set_memory({classicalBit});
instructions.push_back(inst);
if (qubit2MemorySlot[m.bits()[0]] > maxMemorySlots) {
maxMemorySlots = qubit2MemorySlot[m.bits()[0]];
if (classicalBit > maxMemorySlots) {
maxMemorySlots = classicalBit;//qubit2MemorySlot[m.bits()[0]];
}
}
......
......@@ -99,7 +99,7 @@ QObjectCompiler::translate(const std::string &bufferVariable,
auto uniqueBits = function->bits();
auto visitor =
std::make_shared<QObjectExperimentVisitor>(function->name(), uniqueBits);
std::make_shared<QObjectExperimentVisitor>(function->name(), uniqueBits.size());
InstructionIterator it(function);
int memSlots = 0;
......
......@@ -13,8 +13,6 @@
#ifndef XACC_XACC_HPP_
#define XACC_XACC_HPP_
#include <iostream>
#include <memory>
#include "Compiler.hpp"
#include "RemoteAccelerator.hpp"
......
......@@ -13,9 +13,6 @@
#ifndef XACC_ACCELERATOR_HPP_
#define XACC_ACCELERATOR_HPP_
#include <memory>
#include <string>
#include <vector>
#include "AcceleratorBuffer.hpp"
#include "IRTransformation.hpp"
#include "Function.hpp"
......@@ -113,7 +110,7 @@ public:
const std::vector<std::shared_ptr<Function>> functions) = 0;
virtual void cancel() {};
/**
* Create, store, and return an AcceleratorBuffer with the given
* variable id string. This method returns all available
......
......@@ -49,21 +49,20 @@ bool CheckEqualVisitor::operator()(const std::vector<std::string> &i) const {
mpark::get<std::vector<std::string>>(extraInfo).begin());
}
bool CheckEqualVisitor::
operator()(const std::map<int, std::vector<int>> &i) const {
bool CheckEqualVisitor::operator()(
const std::map<int, std::vector<int>> &i) const {
return std::equal(
i.begin(), i.end(),
mpark::get<std::map<int, std::vector<int>>>(extraInfo).begin());
}
bool CheckEqualVisitor::
operator()(const std::map<int, int> &i) const {
return std::equal(i.begin(), i.end(),
mpark::get<std::map<int, int>>(extraInfo).begin());
bool CheckEqualVisitor::operator()(const std::map<int, int> &i) const {
return std::equal(i.begin(), i.end(),
mpark::get<std::map<int, int>>(extraInfo).begin());
}
bool CheckEqualVisitor::
operator()(const std::vector<std::pair<double, double>> &i) const {
bool CheckEqualVisitor::operator()(
const std::vector<std::pair<double, double>> &i) const {
return std::equal(
i.begin(), i.end(),
mpark::get<std::vector<std::pair<double, double>>>(extraInfo).begin(),
......@@ -74,29 +73,39 @@ operator()(const std::vector<std::pair<double, double>> &i) const {
});
}
template<class T> void ToJsonVisitor<T>::operator()(const int &i) { writer.Int(i); }
template<class T> void ToJsonVisitor<T>::operator()(const double &i) { writer.Double(i); }
template<class T> void ToJsonVisitor<T>::operator()(const std::string &i) { writer.String(i); }
template<class T> void ToJsonVisitor<T>::operator()(const std::vector<int> &i) {
template <class T> void ToJsonVisitor<T>::operator()(const int &i) {
writer.Int(i);
}
template <class T> void ToJsonVisitor<T>::operator()(const double &i) {
writer.Double(i);
}
template <class T> void ToJsonVisitor<T>::operator()(const std::string &i) {
writer.String(i);
}
template <class T>
void ToJsonVisitor<T>::operator()(const std::vector<int> &i) {
writer.StartArray();
for (auto &v : i)
writer.Int(v);
writer.EndArray();
}
template<class T> void ToJsonVisitor<T>::operator()(const std::vector<double> &i) {
template <class T>
void ToJsonVisitor<T>::operator()(const std::vector<double> &i) {
writer.StartArray();
for (auto &v : i)
writer.Double(v);
writer.EndArray();
}
template<class T> void ToJsonVisitor<T>::operator()(const std::vector<std::string> &i) {
template <class T>
void ToJsonVisitor<T>::operator()(const std::vector<std::string> &i) {
writer.StartArray();
for (auto &v : i)
writer.String(v);
writer.EndArray();
}
template<class T> void ToJsonVisitor<T>::operator()(const std::map<int, std::vector<int>> &i) {
template <class T>
void ToJsonVisitor<T>::operator()(const std::map<int, std::vector<int>> &i) {
writer.StartObject();
for (auto &kv : i) {
writer.Key(std::to_string(kv.first));
......@@ -109,17 +118,19 @@ template<class T> void ToJsonVisitor<T>::operator()(const std::map<int, std::vec
writer.EndObject();
}
template<class T> void ToJsonVisitor<T>::operator()(const std::map<int, int> &i) const {
writer.StartObject();
for (auto &kv : i){
writer.Key(std::to_string(kv.first));
writer.Int(kv.second);
}
writer.EndObject();
template <class T>
void ToJsonVisitor<T>::operator()(const std::map<int, int> &i) const {
writer.StartObject();
for (auto &kv : i) {
writer.Key(std::to_string(kv.first));
writer.Int(kv.second);
}
writer.EndObject();
}
template<class T> void ToJsonVisitor<T>::
operator()(const std::vector<std::pair<double, double>> &i) const {
template <class T>
void ToJsonVisitor<T>::operator()(
const std::vector<std::pair<double, double>> &i) const {
writer.StartArray();
for (auto &v : i) {
writer.StartArray();
......@@ -226,8 +237,7 @@ AcceleratorBuffer::getChildren(const std::string infoName, ExtraInfo i) {
if (child.second->hasExtraInfoKey(infoName)) {
auto childExtraInfo = child.second->getInformation(infoName);
if (i.index() == childExtraInfo.index()) {
auto isEqual =
mpark::visit(CheckEqualVisitor(i), childExtraInfo);
auto isEqual = mpark::visit(CheckEqualVisitor(i), childExtraInfo);
if (isEqual) {
childrenWithExtraInfo.push_back(child.second);
}
......@@ -286,7 +296,7 @@ const std::string AcceleratorBuffer::name() const { return bufferId; }
* Reset the stored measured bit strings.
*/
void AcceleratorBuffer::resetBuffer() {
// measurements.clear();
// measurements.clear();
bitStringToCounts.clear();
children.clear();
info.clear();
......@@ -306,7 +316,12 @@ void AcceleratorBuffer::appendMeasurement(const std::string measurement,
double
AcceleratorBuffer::computeMeasurementProbability(const std::string &bitStr) {
return (double)bitStringToCounts[bitStr] / std::accumulate(bitStringToCounts.begin(), bitStringToCounts.end(), 0, [](int value, const std::map<std::string, int>::value_type& p){return value + p.second;});
return (double)bitStringToCounts[bitStr] /
std::accumulate(
bitStringToCounts.begin(), bitStringToCounts.end(), 0,
[](int value, const std::map<std::string, int>::value_type &p) {
return value + p.second;
});
}
std::shared_ptr<AcceleratorBuffer> AcceleratorBuffer::clone() {
......@@ -360,7 +375,6 @@ void AcceleratorBuffer::setExpectationValueZ(const double exp) {
"implemented. This method is intended for subclasses.");
}
/**
* Return all measurements as bit strings.
*
......@@ -422,16 +436,13 @@ void AcceleratorBuffer::print(std::ostream &stream) {
writer.Int(kv.second);
}
writer.EndObject();
}
if (!cacheFile) {
writer.Key("Bitmap");
writer.StartObject();
for (auto &kv : bit2IndexMap){
writer.Key(std::to_string(kv.first));
writer.Int(kv.second);
}
writer.EndObject();
writer.Key("Bitmap");
writer.StartObject();
for (auto &kv : bit2IndexMap) {
writer.Key(std::to_string(kv.first));
writer.Int(kv.second);
}
writer.EndObject();
}
if (!children.empty()) {
......@@ -451,19 +462,19 @@ void AcceleratorBuffer::print(std::ostream &stream) {
}
// end information object
writer.EndObject();
writer.Key("Measurements");
writer.StartObject();
for (auto &kv : pair.second->getMeasurementCounts()) {
writer.Key(kv.first);
writer.Int(kv.second);
}
// end measurement object
writer.EndObject();
writer.Key("Measurements");
writer.StartObject();
for (auto &kv : pair.second->getMeasurementCounts()) {
writer.Key(kv.first);
writer.Int(kv.second);
}
// end measurement object
writer.EndObject();
writer.Key("Bitmap");
writer.StartObject();
for (auto &kv : pair.second->getBitMap()){
writer.Key(std::to_string(kv.first));
writer.Int(kv.second);
for (auto &kv : pair.second->getBitMap()) {
writer.Key(std::to_string(kv.first));
writer.Int(kv.second);
}
writer.EndObject();
// End child object
......@@ -474,7 +485,8 @@ void AcceleratorBuffer::print(std::ostream &stream) {
}
// end AB object
if (!cacheFile) writer.EndObject();
if (!cacheFile)
writer.EndObject();
// end root object
writer.EndObject();
......@@ -528,11 +540,14 @@ void AcceleratorBuffer::load(std::istream &stream) {
for (int i = 0; i < arr.Size(); i++)
childValues.push_back(arr[i].GetString());
addExtraInfo(itr->name.GetString(), ExtraInfo(childValues));
} else if (firstVal.IsArray() && !firstVal.GetArray().Empty() && firstVal.GetArray().Size() == 2) {
std::vector<std::pair<double,double>> v;
for (int i = 0; i < arr.Size(); i++) v.push_back({arr[i].GetArray()[0].GetDouble(), arr[i].GetArray()[1].GetDouble()});
} else if (firstVal.IsArray() && !firstVal.GetArray().Empty() &&
firstVal.GetArray().Size() == 2) {
std::vector<std::pair<double, double>> v;
for (int i = 0; i < arr.Size(); i++)
v.push_back({arr[i].GetArray()[0].GetDouble(),
arr[i].GetArray()[1].GetDouble()});
addExtraInfo(itr->name.GetString(), ExtraInfo(v));
addExtraInfo(itr->name.GetString(), ExtraInfo(v));
}
} else {
// Here we have the case of an object([key:value])
......@@ -556,17 +571,17 @@ void AcceleratorBuffer::load(std::istream &stream) {
vec.push_back(arr[i].GetInt());
map.insert({key, vec});
} else if (itr2->value.IsInt() && keyIsInt) {
auto val = itr2->value.GetInt();
map2.insert({key, val});
auto val = itr2->value.GetInt();
map2.insert({key, val});
} else {
break;
break;
}
}
if (!map.empty()){
addExtraInfo(itr->name.GetString(), ExtraInfo(map));
if (!map.empty()) {
addExtraInfo(itr->name.GetString(), ExtraInfo(map));
}
if (!map2.empty()){
addExtraInfo(itr->name.GetString(), ExtraInfo(map2));
if (!map2.empty()) {
addExtraInfo(itr->name.GetString(), ExtraInfo(map2));
}
}
}
......@@ -581,13 +596,13 @@ void AcceleratorBuffer::load(std::istream &stream) {
}
}
if (!cacheFile){
auto &bitMap = doc["AcceleratorBuffer"]["Bitmap"];
std::map<int, int> tmpMap;
for (auto itr = bitMap.MemberBegin(); itr != bitMap.MemberEnd(); ++ itr) {
tmpMap.insert({std::stoi(itr->name.GetString()), itr->value.GetInt()});
}
setBitIndexMap(tmpMap);
if (!cacheFile) {
auto &bitMap = doc["AcceleratorBuffer"]["Bitmap"];
std::map<int, int> tmpMap;
for (auto itr = bitMap.MemberBegin(); itr != bitMap.MemberEnd(); ++itr) {
tmpMap.insert({std::stoi(itr->name.GetString()), itr->value.GetInt()});
}
setBitIndexMap(tmpMap);
}
auto children = doc["AcceleratorBuffer"]["Children"].GetArray();
......@@ -630,8 +645,8 @@ void AcceleratorBuffer::load(std::istream &stream) {
childBuffer->addExtraInfo(itr->name.GetString(),
ExtraInfo(childValues));
} else {
xacc::info("HELLO EXTRA: " +
std::string(itr->name.GetString())); // << "\n";
// xacc::info("HELLO EXTRA: " +
// std::string(itr->name.GetString())); // << "\n";
}
// FIXME Handle Map<int, [int*]>
}
......@@ -645,8 +660,8 @@ void AcceleratorBuffer::load(std::istream &stream) {
}
auto &bitMap = c["Bitmap"];
std::map<int, int> tmpMap;
for (auto itr = bitMap.MemberBegin(); itr != bitMap.MemberEnd(); ++itr){
tmpMap.insert({std::stoi(itr->name.GetString()), itr->value.GetInt()});
for (auto itr = bitMap.MemberBegin(); itr != bitMap.MemberEnd(); ++itr) {
tmpMap.insert({std::stoi(itr->name.GetString()), itr->value.GetInt()});
}
childBuffer->setBitIndexMap(tmpMap);
......
......@@ -137,11 +137,7 @@ public:
"Cannot cast vector<int, int> InstructionParameter to ExtraInfo.");
return ExtraInfo(0);
}
// ExtraInfo operator()(const std::map<int, int> &i) const {
// XACCLogger::instance()->error(
// "Cannot cast map<int, int> InstructionParameter to ExtraInfo.");
// return ExtraInfo(0);
// }