qcor.cpp 1.99 KB
Newer Older
Mccaskey, Alex's avatar
Mccaskey, Alex committed
1
#include "qcor.hpp"
2
#include "qpu_handler.hpp"
Mccaskey, Alex's avatar
Mccaskey, Alex committed
3

4
#include "AcceleratorBuffer.hpp"
Mccaskey, Alex's avatar
Mccaskey, Alex committed
5
6
#include "IRProvider.hpp"
#include "XACC.hpp"
7
#include <regex>
Mccaskey, Alex's avatar
Mccaskey, Alex committed
8
9
10
11
12

using namespace xacc;

namespace qcor {

13
14
15
16
17
18
19
void Initialize(int argc, char** argv) {
    xacc::Initialize(argc,argv);
}
void Initialize(std::vector<std::string> argv) {
    xacc::Initialize(argv);
}

Mccaskey, Alex's avatar
Mccaskey, Alex committed
20
const std::string persistCompiledCircuit(std::shared_ptr<Function> function) {
21
22
23
24
25
26
27
28
29
30
31
32
33
34
      std::function<char()> randChar = []() -> char {
    const char charset[] = "0123456789"
                           "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                           "abcdefghijklmnopqrstuvwxyz";
    const size_t max_index = (sizeof(charset) - 1);
    return charset[rand() % max_index];
  };

  auto generateRandomString = [&](const int length = 10) -> const std::string {
    std::string str(length, 0);
    std::generate_n(str.begin(), length, randChar);
    return str;
  };

35
36
37
38
39
  auto file_name = generateRandomString();
  auto persistedFunction = xacc::getCompiler("xacc-py")->translate("", function);
  persistedFunction = persistedFunction.substr(7,persistedFunction.length());
  xacc::appendCache(file_name, "compiled", InstructionParameter(persistedFunction), ".qcor_cache");
  return file_name;
Mccaskey, Alex's avatar
Mccaskey, Alex committed
40
41
}

42
std::shared_ptr<Function> loadCompiledCircuit(const std::string& fileName) {
43
44
45
46
  auto cache = xacc::getCache(fileName, ".qcor_cache");
  if (!cache.count("compiled")) {
    xacc::error("Invalid quantum compilation cache.");
  }
47

48
49
  auto compiled = cache["compiled"].as<std::string>();
  return xacc::getCompiler("xacc-py")->compile(compiled)->getKernels()[0];
Mccaskey, Alex's avatar
Mccaskey, Alex committed
50
51
}

52
std::future<std::shared_ptr<AcceleratorBuffer>> submit(HandlerLambda &&totalJob) {
Mccaskey, Alex's avatar
Mccaskey, Alex committed
53
54
55
  // Create the QPU Handler to pass to the given
  // Handler HandlerLambda
  qpu_handler handler;
56
  return std::async(std::launch::async, [&]() {
Mccaskey, Alex's avatar
Mccaskey, Alex committed
57
    totalJob(handler);
58
    return handler.getResults();
Mccaskey, Alex's avatar
Mccaskey, Alex committed
59
60
61
  });
}

62
63
64
65
std::shared_ptr<Optimizer> getOptimizer(const std::string& name) {
    return xacc::getService<qcor::Optimizer>(name);
}

Mccaskey, Alex's avatar
Mccaskey, Alex committed
66
} // namespace qcor