vqe.cpp 7.55 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
/*******************************************************************************
 * 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
 *******************************************************************************/
13
14
15
#include "vqe.hpp"

#include "Observable.hpp"
16
#include "xacc.hpp"
17
18
19
20
21
22
23
24
25

#include <memory>
#include <iomanip>

using namespace xacc;

namespace xacc {
namespace algorithm {
bool VQE::initialize(const HeterogeneousMap &parameters) {
26
  if (!parameters.pointerLikeExists<Observable>("observable")) {
27
28
    std::cout << "Obs was false\n";
    return false;
29
  } else if (!parameters.pointerLikeExists<CompositeInstruction>("ansatz")) {
30
31
    std::cout << "Ansatz was false\n";
    return false;
32
  } else if (!parameters.pointerLikeExists<Accelerator>("accelerator")) {
33
34
35
    std::cout << "Acc was false\n";
    return false;
  }
36

37
  observable = parameters.getPointerLike<Observable>("observable");
38
39
40
  if (parameters.pointerLikeExists<Optimizer>("optimizer")) {
    optimizer = parameters.getPointerLike<Optimizer>("optimizer");
  }
41
42
43
  accelerator = parameters.getPointerLike<Accelerator>("accelerator");
  kernel = parameters.getPointerLike<CompositeInstruction>("ansatz");

44
45
46
47
48
49
50
51
52
  return true;
}

const std::vector<std::string> VQE::requiredParameters() const {
  return {"observable", "optimizer", "accelerator", "ansatz"};
}

void VQE::execute(const std::shared_ptr<AcceleratorBuffer> buffer) const {

53
54
55
56
57
  if (!optimizer) {
    xacc::error("VQE Algorithm Error - Optimizer was null. Please provide a "
                "valid Optimizer.");
  }

58
  auto kernels = observable->observe(xacc::as_shared_ptr(kernel));
59
60
61
62

  // Here we just need to make a lambda kernel
  // to optimize that makes calls to the targeted QPU.
  OptFunction f(
63
      [&, this](const std::vector<double> &x, std::vector<double> &dx) {
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
        std::vector<double> coefficients;
        std::vector<std::string> kernelNames;
        std::vector<std::shared_ptr<CompositeInstruction>> fsToExec;

        double identityCoeff = 0.0;
        for (auto &f : kernels) {
          kernelNames.push_back(f->name());
          std::complex<double> coeff = f->getCoefficient();

          int nFunctionInstructions = 0;
          if (f->getInstruction(0)->isComposite()) {
            nFunctionInstructions =
                kernel->nInstructions() + f->nInstructions() - 1;
          } else {
            nFunctionInstructions = f->nInstructions();
          }

          if (nFunctionInstructions > kernel->nInstructions()) {
82
83
            auto evaled = f->operator()(x);
            fsToExec.push_back(evaled);
84
85
86
87
88
89
90
91
92
93
94
            coefficients.push_back(std::real(coeff));
          } else {
            identityCoeff += std::real(coeff);
          }
        }

        auto tmpBuffer = xacc::qalloc(buffer->size());
        accelerator->execute(tmpBuffer, fsToExec);
        auto buffers = tmpBuffer->getChildren();

        double energy = identityCoeff;
95
96
97
98
99
100
101
        auto idBuffer = xacc::qalloc(buffer->size());
        idBuffer->addExtraInfo("coefficient", identityCoeff);
        idBuffer->setName("I");
        idBuffer->addExtraInfo("kernel", "I");
        idBuffer->addExtraInfo("parameters", x);
        idBuffer->addExtraInfo("exp-val-z", 1.0);
        if (accelerator->name() == "ro-error")
102
          idBuffer->addExtraInfo("ro-fixed-exp-val-z", 1.0);
103
104
        buffer->appendChild("I", idBuffer);

105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
        if (buffers[0]->hasExtraInfoKey(
                "purified-energy")) { // FIXME Hack for now...
          energy = buffers[0]->getInformation("purified-energy").as<double>();
          for (auto &b : buffers) {
            b->addExtraInfo("parameters", initial_params);
            buffer->appendChild(b->name(), b);
          }
        } else {
          for (int i = 0; i < buffers.size(); i++) {
            auto expval = buffers[i]->getExpectationValueZ();
            energy += expval * coefficients[i];
            buffers[i]->addExtraInfo("coefficient", coefficients[i]);
            buffers[i]->addExtraInfo("kernel", fsToExec[i]->name());
            buffers[i]->addExtraInfo("exp-val-z", expval);
            buffers[i]->addExtraInfo("parameters", x);
            buffer->appendChild(fsToExec[i]->name(), buffers[i]);
          }
122
123
124
        }

        std::stringstream ss;
125
        ss << "E(" << (!x.empty() ? std::to_string(x[0]) : "");
126
127
128
129
130
131
132
133
134
135
136
137
138
139
        for (int i = 1; i < x.size(); i++)
          ss << "," << x[i];
        ss << ") = " << std::setprecision(12) << energy;
        xacc::info(ss.str());
        return energy;
      },
      kernel->nVariables());

  auto result = optimizer->optimize(f);

  buffer->addExtraInfo("opt-val", ExtraInfo(result.first));
  buffer->addExtraInfo("opt-params", ExtraInfo(result.second));
  return;
}
140
141
142
143

std::vector<double>
VQE::execute(const std::shared_ptr<AcceleratorBuffer> buffer,
             const std::vector<double> &x) {
144

145
  auto kernels = observable->observe(xacc::as_shared_ptr(kernel));
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
  std::vector<double> coefficients;
  std::vector<std::string> kernelNames;
  std::vector<std::shared_ptr<CompositeInstruction>> fsToExec;

  double identityCoeff = 0.0;
  for (auto &f : kernels) {
    kernelNames.push_back(f->name());
    std::complex<double> coeff = f->getCoefficient();

    int nFunctionInstructions = 0;
    if (f->getInstruction(0)->isComposite()) {
      nFunctionInstructions = kernel->nInstructions() + f->nInstructions() - 1;
    } else {
      nFunctionInstructions = f->nInstructions();
    }

    if (nFunctionInstructions > kernel->nInstructions()) {
163
164
      auto evaled = f->operator()(x);
      fsToExec.push_back(evaled);
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
      coefficients.push_back(std::real(coeff));
    } else {
      identityCoeff += std::real(coeff);
    }
  }

  auto tmpBuffer = xacc::qalloc(buffer->size());
  accelerator->execute(tmpBuffer, fsToExec);
  auto buffers = tmpBuffer->getChildren();

  double energy = identityCoeff;
  auto idBuffer = xacc::qalloc(buffer->size());
  idBuffer->addExtraInfo("coefficient", identityCoeff);
  idBuffer->setName("I");
  idBuffer->addExtraInfo("kernel", "I");
  idBuffer->addExtraInfo("parameters", x);
  idBuffer->addExtraInfo("exp-val-z", 1.0);
  if (accelerator->name() == "ro-error")
    idBuffer->addExtraInfo("ro-fixed-exp-val-z", 1.0);
  buffer->appendChild("I", idBuffer);

  if (buffers[0]->hasExtraInfoKey("purified-energy")) { // FIXME Hack for now...
    energy = buffers[0]->getInformation("purified-energy").as<double>();
    for (auto &b : buffers) {
      b->addExtraInfo("parameters", initial_params);
      buffer->appendChild(b->name(), b);
    }
  } else {
    for (int i = 0; i < buffers.size(); i++) {
      auto expval = buffers[i]->getExpectationValueZ();
      energy += expval * coefficients[i];
      buffers[i]->addExtraInfo("coefficient", coefficients[i]);
      buffers[i]->addExtraInfo("kernel", fsToExec[i]->name());
      buffers[i]->addExtraInfo("exp-val-z", expval);
      buffers[i]->addExtraInfo("parameters", x);
      buffer->appendChild(fsToExec[i]->name(), buffers[i]);
    }
  }

  std::stringstream ss;
205

206
  ss << "E(" << (!x.empty() ? std::to_string(x[0]) : "");
207
208
209
210
211
212
213
  for (int i = 1; i < x.size(); i++)
    ss << "," << x[i];
  ss << ") = " << std::setprecision(12) << energy;
  xacc::info(ss.str());
  return {energy};
}

214
215
} // namespace algorithm
} // namespace xacc