qcor.cpp 7.64 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
8
#include "xacc_service.hpp"

9
#include "FermionOperator.hpp"
10
#include "PauliOperator.hpp"
11

12
#include <regex>
Mccaskey, Alex's avatar
Mccaskey, Alex committed
13
14
15
16

using namespace xacc;

namespace qcor {
17
std::map<std::string, InstructionParameter> runtimeMap = {};
Mccaskey, Alex's avatar
Mccaskey, Alex committed
18

19
20
21
22
23
24
void Initialize(int argc, char **argv) {
  std::vector<const char *> tmp(argv, argv + argc);
  std::vector<std::string> newargv;
  for (auto &t : tmp)
    newargv.push_back(std::string(t));
  Initialize(newargv);
25
26
}
void Initialize(std::vector<std::string> argv) {
27
28
29
  argv.push_back("--logger-name");
  argv.push_back("qcor");
  xacc::Initialize(argv);
30
31
}

32
33
34
35
const std::string persistCompiledCircuit(std::shared_ptr<Function> function,
                                         std::shared_ptr<Accelerator> acc) {
  srand(time(NULL));
  std::function<char()> randChar = []() -> char {
36
37
38
39
40
41
42
43
44
45
46
47
48
    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;
  };

49
50
51
52
53
54
55
56
57
  std::string file_name;
  if (xacc::optionExists("qcor-compiled-filename")) {
    file_name = xacc::getOption("qcor-compiled-filename");
  } else {

    file_name = generateRandomString();
    // std::cout << "Generating random string " << file_name << "\n";
  }

58
59
60
  std::stringstream ss;
  function->persist(ss);
  auto persistedFunction = ss.str();
61
62
63
64
//   std::cout << "PERSISTED\n" << persistedFunction << "\n";
  //   xacc::getCompiler("xacc-py")->translate("", function);
  //   persistedFunction = persistedFunction.substr(7,
  //   persistedFunction.length());
65
66
67
68
  xacc::appendCache(file_name, "compiled",
                    InstructionParameter(persistedFunction), ".qcor_cache");

  if (acc) {
Mccaskey, Alex's avatar
Mccaskey, Alex committed
69
70
71
72
    auto accName = acc->name();
    if (xacc::optionExists(accName+"-backend")) {
       accName = accName + ":" + xacc::getOption(accName+"-backend");
    }
73
    xacc::appendCache(file_name, "accelerator",
Mccaskey, Alex's avatar
Mccaskey, Alex committed
74
                      InstructionParameter(accName), ".qcor_cache");
75
76
77
78
79
80
81
82
83
84
85
86
87
  } else {
    xacc::appendCache(file_name, "accelerator",
                      InstructionParameter("default-sim"), ".qcor_cache");
  }

  if (function->hasIRGenerators()) {
    xacc::appendCache(file_name, "requires-jit", InstructionParameter("true"),
                      ".qcor_cache");
  } else {
    xacc::appendCache(file_name, "requires-jit", InstructionParameter("false"),
                      ".qcor_cache");
  }

88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
  bool isDw = false;
  for (auto& inst : function->getInstructions()) {
      if (inst->name() == "dw-qmi" || inst->name() == "anneal") {
          isDw = true;
          break;
      }
  }

  if (isDw) {
    xacc::appendCache(file_name, "ir-type", InstructionParameter("anneal"),
                      ".qcor_cache");
  } else {
    xacc::appendCache(file_name, "ir-type", InstructionParameter("gate"),
                      ".qcor_cache");
  }
103
  return file_name;
Mccaskey, Alex's avatar
Mccaskey, Alex committed
104
105
}

106
std::shared_ptr<Function> loadCompiledCircuit(const std::string &fileName) {
107
  //   std::cout << "Loading Circuit " << fileName << "\n";
108
109
110
111
  auto cache = xacc::getCache(fileName, ".qcor_cache");
  if (!cache.count("compiled")) {
    xacc::error("Invalid quantum compilation cache.");
  }
112

113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
  std::shared_ptr<Accelerator> targetAccelerator;
  if (cache["accelerator"] == "default-sim") {
    // First, if this is compiled for simulation,
    // let users set the simulator at the command line
    // if they didnt, check for tnqvm, then local-ibm
    if (xacc::optionExists("accelerator")) {
      targetAccelerator = xacc::getAccelerator();
    } else if (xacc::hasAccelerator("tnqvm")) {
      targetAccelerator = xacc::getAccelerator("tnqvm");
    } else if (xacc::hasAccelerator("local-ibm")) {
      targetAccelerator = xacc::getAccelerator("local-ibm");
    }
  } else {
    auto accStr = cache["accelerator"].as<std::string>();
    if ((accStr == "tnqvm" || accStr == "local-ibm") &&
        xacc::optionExists("accelerator")) {
      targetAccelerator = xacc::getAccelerator();
    } else {
      targetAccelerator =
          xacc::getAccelerator(cache["accelerator"].as<std::string>());
    }
  }

  // If for some reason we still dont have an
  // accelerator, force them to specify at command line
  if (!targetAccelerator) {
    targetAccelerator = xacc::getAccelerator();
  }

  xacc::setAccelerator(targetAccelerator->name());

144
  auto type = cache["ir-type"].as<std::string>();
145
  auto compiled = cache["compiled"].as<std::string>();
146
147
  auto loaded =
      xacc::getService<IRProvider>("quantum")->createFunction("loaded", {}, {InstructionParameter(type)});
148
149
  std::istringstream iss(compiled);
  loaded->load(iss);
150

151
  //   std::cout << "Lodaded: " << loaded->toString() << "\n";
152
153
154
  if (cache["requires-jit"].as<std::string>() == "true") {
    auto runtimeMap = getRuntimeMap();

155
    // for (auto& kv : runtimeMap) {
156
157
    // std::cout << "Runtime: " << kv.first << ", " << kv.second.toString() <<
    // "\n";
158
    // }
159
160
161
162
163
    loaded->expandIRGenerators(runtimeMap);

    // Kick off quantum compilation
    auto qcor = xacc::getCompiler("qcor");
    loaded = qcor->compile(loaded, targetAccelerator);
164
    // std::cout << "NPARAMS: " << loaded->nParameters() << "\n";
165
166
  }

167
  //   std::cout<< "Loaded IR:\n" << loaded->toString() <<"\n";
168
  return loaded;
Mccaskey, Alex's avatar
Mccaskey, Alex committed
169
170
}

171
172
173
void storeRuntimeVariable(const std::string name, InstructionParameter param) {
  //   std::cout << "Storing Runtime Variable " << name << ", " <<
  //   param.toString() << "\n";
174
175
176
177
178
179
180
181
182
  runtimeMap.insert({name, param});
}

std::map<std::string, InstructionParameter> getRuntimeMap() {
  return runtimeMap;
}

std::future<std::shared_ptr<AcceleratorBuffer>>
submit(HandlerLambda &&totalJob) {
Mccaskey, Alex's avatar
Mccaskey, Alex committed
183
184
  // Create the QPU Handler to pass to the given
  // Handler HandlerLambda
185
186
  return std::async(std::launch::async, [=]() { // bug must be by value...
    qpu_handler handler;
Mccaskey, Alex's avatar
Mccaskey, Alex committed
187
    totalJob(handler);
188
    return handler.getResults();
Mccaskey, Alex's avatar
Mccaskey, Alex committed
189
190
191
  });
}

192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
std::shared_ptr<Optimizer> getOptimizer(const std::string &name) {
  return xacc::getService<qcor::Optimizer>(name);
}
std::shared_ptr<Optimizer>
getOptimizer(const std::string &name,
             std::map<std::string, InstructionParameter> &&options) {
  auto opt = getOptimizer(name);
  opt->setOptions(options);
  return opt;
}

std::shared_ptr<Observable> getObservable(const std::string &type,
                                          const std::string &representation) {
  using namespace xacc::quantum;
  if (type == "pauli") {
    return representation.empty()
               ? std::make_shared<PauliOperator>()
               : std::make_shared<PauliOperator>(representation);
210
  } else if (type == "fermion") {
211
    return representation.empty()
212
213
               ? std::make_shared<FermionOperator>()
               : std::make_shared<FermionOperator>(representation);
214
  } else {
215
216
217
218
219
220
221
222
223
224
225
226
    xacc::error("Invalid observable type");
    return std::make_shared<PauliOperator>();
  }
}

std::shared_ptr<Observable> getObservable() {
  return getObservable("pauli", "");
}
std::shared_ptr<Observable> getObservable(const std::string &representation) {
  return getObservable("pauli", representation);
}

227
228
229
230
231
232
std::shared_ptr<Observable>
getObservable(const std::string &type,
              std::map<std::string, InstructionParameter> &&options) {
  auto observable = xacc::getService<Observable>(type);
  observable->fromOptions(options);
  return observable;
233
}
234
235
std::shared_ptr<algorithm::Algorithm> getAlgorithm(const std::string name) {
  return xacc::getService<qcor::algorithm::Algorithm>(name);
236
237
}

238
} // namespace qcor