qite.cpp 20.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*******************************************************************************
 * 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:
 *   Thien Nguyen - initial API and implementation
 *******************************************************************************/
#include "qite.hpp"

#include "Observable.hpp"
#include "xacc.hpp"
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
17
18
19
#include "xacc_service.hpp"
#include "PauliOperator.hpp"
#include "Circuit.hpp"
20
#include <memory>
21
22
#include <armadillo>
#include <cassert>
23

24
25
namespace {
const std::complex<double> I{ 0.0, 1.0};
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
int findMatchingPauliIndex(const std::vector<std::string>& in_OpList, const std::string& in_obsStr)
{
  // Returns true if the *operators* of the two terms are identical
  // e.g. a Z0X1 and b Z0X1 -> true 
  const auto comparePauliString = [](const std::string& in_a, const std::string& in_b) -> bool {
    // Strip the coefficient part
    auto opA = in_a.substr(in_a.find_last_of(")") + 1);
    auto opB = in_b.substr(in_b.find_last_of(")") + 1);
    opA.erase(std::remove(opA.begin(), opA.end(), ' '), opA.end()); 
    opB.erase(std::remove(opB.begin(), opB.end(), ' '), opB.end()); 
    return opA == opB;
  };

  for (int i = 0; i < in_OpList.size(); ++i)
  {
    std::shared_ptr<xacc::Observable> obs = std::make_shared<xacc::quantum::PauliOperator>();
    const std::string pauliObsStr = "1.0 " + in_OpList[i];
    obs->fromString(pauliObsStr);
    
    if (comparePauliString(obs->toString(), in_obsStr))
    {
      return i;
    }
  }
  // Failed!
  return -1;
52
53
}

Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// Project/flatten the target observable into the full list of all
// possible Pauli operator combinations.
// e.g. H = a X + b Z (1 qubit)
// -> { 0.0, a, 0.0, b } (the ordering is I, X, Y, Z)
std::vector<double> observableToVec(std::shared_ptr<xacc::Observable> in_observable, const std::vector<std::string>& in_pauliObsList) 
{
  std::vector<double> obsProjCoeffs(in_pauliObsList.size(), 0.0);
  for (const auto& term: in_observable->getNonIdentitySubTerms())
  {
    const auto index = findMatchingPauliIndex(in_pauliObsList, term->toString());
    assert(index >= 0);
    obsProjCoeffs[index] = term->coefficient().real();
  }
  return obsProjCoeffs;
};

// Helper to generate all permutation of Pauli observables:
// e.g.
// 1-qubit: I, X, Y, Z
// 2-qubit: II, IX, IY, IZ, XI, XX, XY, XZ, YI, YX, YY, YZ, ZI, ZX, ZY, ZZ
std::vector<std::string> generatePauliPermutation(int in_nbQubits)
{
  assert(in_nbQubits > 0);
  const int nbPermutations = std::pow(4, in_nbQubits);
  std::vector<std::string> opsList;
  opsList.reserve(nbPermutations);
  
  const std::vector<std::string> pauliOps { "X", "Y", "Z" };
  const auto addQubitPauli = [&opsList, &pauliOps](int in_qubitIdx){
    const auto currentOpListSize = opsList.size();
    for (int i = 0; i < currentOpListSize; ++i)
    {
      auto& currentOp = opsList[i];
      for (const auto& pauliOp : pauliOps)
      {
        const auto newOp = currentOp + pauliOp + std::to_string(in_qubitIdx);
        opsList.emplace_back(newOp);
      }
    }
  };
  
  opsList = { "", "X0", "Y0", "Z0" };
  for (int i = 1; i < in_nbQubits; ++i) 
  {
    addQubitPauli(i);
  }

  assert(opsList.size() == nbPermutations);
  std::sort(opsList.begin(), opsList.end());
103

Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
104
105
  return opsList;
};
106
107
108
109
110
111
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

arma::cx_mat createSMatrix(const std::vector<std::string>& in_pauliOps, const std::vector<double>& in_tomoExp) 
{
  const auto sMatDim = in_pauliOps.size();
  arma::cx_mat S_Mat(sMatDim, sMatDim, arma::fill::zeros);
  arma::cx_vec b_Vec(sMatDim, arma::fill::zeros); 
  
  const auto calcSmatEntry = [&](int in_row, int in_col) -> std::complex<double> {
    // Map the tomography expectation to the S matrix
    // S(i, j) = <psi|sigma_dagger(i)sigma(j)|psi>
    // sigma_dagger(i)sigma(j) will produce another Pauli operator with an additional coefficient.
    // e.g. sigma_x * sigma_y = i*sigma_z
    const auto leftOp = "1.0 " + in_pauliOps[in_row];
    const auto rightOp = "1.0 " + in_pauliOps[in_col];
    xacc::quantum::PauliOperator left(leftOp);
    xacc::quantum::PauliOperator right(rightOp);
    auto product = left * right;
    // std::cout << left.toString() << " * " << right.toString() << " = " << product.toString() << "\n";
    const auto index = findMatchingPauliIndex(in_pauliOps, product.toString());
    return in_tomoExp[index]*product.coefficient();
  };

  // S matrix:
  for (int i = 0; i < sMatDim; ++i)
  {
    for (int j = 0; j < sMatDim; ++j)
    {
      S_Mat(i, j) = calcSmatEntry(i, j);
    }
  }
  return S_Mat;
}
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
138
139
140
}

using namespace xacc;
141
142
143
144
namespace xacc {
namespace algorithm {
bool QITE::initialize(const HeterogeneousMap &parameters) 
{
145
146
147
148
149
150
  bool initializeOk = true;
  if (!parameters.pointerLikeExists<Accelerator>("accelerator")) 
  {
    std::cout << "'accelerator' is required.\n";
    initializeOk = false;
  }
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
151

152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
  if (!parameters.keyExists<int>("steps")) 
  {
    std::cout << "'steps' is required.\n";
    initializeOk = false;
  }

  if (!parameters.keyExists<double>("step-size")) 
  {
    std::cout << "'step-size' is required.\n";
    initializeOk = false;
  }

  if (!parameters.pointerLikeExists<Observable>("observable")) 
  {
    std::cout << "'observable' is required.\n";
    initializeOk = false;
  }
  
  if (initializeOk)
  {
    m_accelerator = xacc::as_shared_ptr(parameters.getPointerLike<Accelerator>("accelerator"));
    m_nbSteps = parameters.get<int>("steps");
    m_dBeta = parameters.get<double>("step-size");
    m_observable = xacc::as_shared_ptr(parameters.getPointerLike<Observable>("observable"));
  }

178
  m_analytical = true;
179
180
181
182
183
  if (parameters.keyExists<bool>("analytical")) 
  {
    m_analytical = parameters.get<bool>("analytical");
  }

184
185
  m_approxOps.clear();
  m_energyAtStep.clear();
186
  
187
  return initializeOk;
188
189
190
191
}

const std::vector<std::string> QITE::requiredParameters() const 
{
192
  return { "accelerator", "steps", "step-size", "observable" };
193
194
}

Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
std::shared_ptr<CompositeInstruction> QITE::constructPropagateCircuit() const
{
  auto gateRegistry = xacc::getService<xacc::IRProvider>("quantum");
  auto propagateKernel = gateRegistry->createComposite("statePropCircuit");

  // Adds ansatz if provided
  if (m_ansatz)
  {
    propagateKernel->addInstructions(m_ansatz->getInstructions());
  } 

  const auto pauliTermToString = [](const std::shared_ptr<xacc::Observable>& in_term){
    std::string pauliTermStr = in_term->toString();
    std::stringstream s;
    s.precision(12);
    s << std::fixed << in_term->coefficient();
    // Find the parenthesis
    const auto startPosition = pauliTermStr.find("(");
    const auto endPosition = pauliTermStr.find(")");

    if (startPosition != std::string::npos && endPosition != std::string::npos)
    {
      const auto length = endPosition - startPosition + 1;
      pauliTermStr.replace(startPosition, length, s.str());
    }
    return pauliTermStr;
  };

  // Progagates by Trotter steps
  // Using those A operators that have been 
  // optimized up to this point.
  for (const auto& aObs : m_approxOps)
  {
    // Circuit is: exp(-idt*A),
    // i.e. regular evolution which approximates the imaginary time evolution.
    for (const auto& term : aObs->getNonIdentitySubTerms())
    {
      const auto pauliStr = pauliTermToString(term);
      auto expCirc = std::dynamic_pointer_cast<xacc::quantum::Circuit>(xacc::getService<Instruction>("exp_i_theta"));
234
235
      const bool expandOk = expCirc->expand({ std::make_pair("pauli", pauliStr) });
      assert(expandOk);
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
236
237
238
239
240
      auto evaled = expCirc->operator()({ m_dBeta });
      propagateKernel->addInstructions(evaled->getInstructions());
    }
  }

241
  // std::cout << "Progagated kernel:\n" << propagateKernel->toString() << "\n";
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
242
243
244
  return propagateKernel;
}

245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
double QITE::calcCurrentEnergy(int in_nbQubits) const
{
  // Trotter kernel up to this point
  auto propagateKernel = constructPropagateCircuit();
  auto kernels = m_observable->observe(propagateKernel);
  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;
260
    if (f->nInstructions() > 0 && f->getInstruction(0)->isComposite()) 
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
    {
      nFunctionInstructions = propagateKernel->nInstructions() + f->nInstructions() - 1;
    } 
    else 
    {
      nFunctionInstructions = f->nInstructions();
    }

    if (nFunctionInstructions > propagateKernel->nInstructions()) 
    {
      fsToExec.push_back(f);
      coefficients.push_back(std::real(coeff));
    } 
    else 
    {
      identityCoeff += std::real(coeff);
    }
  }

  auto tmpBuffer = xacc::qalloc(in_nbQubits);
  m_accelerator->execute(tmpBuffer, fsToExec);
  auto buffers = tmpBuffer->getChildren();

  double energy = identityCoeff;
  for (int i = 0; i < buffers.size(); ++i) 
  {
    auto expval = buffers[i]->getExpectationValueZ();
    energy += expval * coefficients[i];
  }
  std::cout << "Energy = " << energy << "\n";
  return energy;
}
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
293

Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
294
std::shared_ptr<Observable> QITE::calcAOps(const std::shared_ptr<AcceleratorBuffer>& in_buffer, std::shared_ptr<CompositeInstruction> in_kernel, std::shared_ptr<Observable> in_hmTerm) const
295
{
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
  const auto pauliOps = generatePauliPermutation(in_buffer->size());
  assert(in_hmTerm->getSubTerms().size() == 1);
  assert(in_hmTerm->getNonIdentitySubTerms().size() == 1);

  // Step 1: Observe the kernels using the various Pauli
  // operators to calculate S and b.
  std::vector<double> sigmaExpectation(pauliOps.size());
  sigmaExpectation[0] = 1.0;
  for (int i = 1; i < pauliOps.size(); ++i)
  {
    std::shared_ptr<Observable> tomoObservable = std::make_shared<xacc::quantum::PauliOperator>();
    const std::string pauliObsStr = "1.0 " + pauliOps[i];
    tomoObservable->fromString(pauliObsStr);
    assert(tomoObservable->getSubTerms().size() == 1);
    assert(tomoObservable->getNonIdentitySubTerms().size() == 1);
    auto obsKernel = tomoObservable->observe(in_kernel).front();
    auto tmpBuffer = xacc::qalloc(in_buffer->size());
    m_accelerator->execute(tmpBuffer, obsKernel);
    const auto expval = tmpBuffer->getExpectationValueZ();
    sigmaExpectation[i] = expval;
  }
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
317

Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
318
319
320
321
322
  // Step 2: Calculate S matrix and b vector
  // i.e. set up the linear equation Sa = b
  const auto sMatDim = pauliOps.size();
  arma::cx_mat S_Mat(sMatDim, sMatDim, arma::fill::zeros);
  arma::cx_vec b_Vec(sMatDim, arma::fill::zeros); 
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
323
  
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
324
325
  const auto calcSmatEntry = [&](const std::vector<double>& in_tomoExp, int in_row, int in_col) -> std::complex<double> {
    // Map the tomography expectation to the S matrix
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
326
    // S(i, j) = <psi|sigma_dagger(i)sigma(j)|psi>
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
    // sigma_dagger(i)sigma(j) will produce another Pauli operator with an additional coefficient.
    // e.g. sigma_x * sigma_y = i*sigma_z
    const auto leftOp = "1.0 " + pauliOps[in_row];
    const auto rightOp = "1.0 " + pauliOps[in_col];
    xacc::quantum::PauliOperator left(leftOp);
    xacc::quantum::PauliOperator right(rightOp);
    auto product = left * right;
    const auto index = findMatchingPauliIndex(pauliOps, product.toString());
    return in_tomoExp[index]*product.coefficient();
  };

  // S matrix:
  for (int i = 0; i < sMatDim; ++i)
  {
    for (int j = 0; j < sMatDim; ++j)
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
342
    {
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
343
      S_Mat(i, j) = calcSmatEntry(sigmaExpectation, i, j);
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
344
    }
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
345
  }
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
346

Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
  // b vector:
  const auto obsProjCoeffs = observableToVec(in_hmTerm, pauliOps);
  // std::cout << "Observable Pauli Vec: [";
  // for (const auto& elem: obsProjCoeffs)
  // {
  //   std::cout << elem << ", ";
  // }
  // std::cout << "]\n";

  // Calculate c: Eq. 3 in https://arxiv.org/pdf/1901.07653.pdf
  double c = 1.0;
  for (int i = 0; i < obsProjCoeffs.size(); ++i)
  {
    c -= 2.0 * m_dBeta * obsProjCoeffs[i] * sigmaExpectation[i];
  }
  
  // std::cout << "c = " << c << "\n";
  for (int i = 0; i < sMatDim; ++i)
  {
    std::complex<double> b = (sigmaExpectation[i]/ std::sqrt(c) - sigmaExpectation[i])/ m_dBeta;
    for (int j = 0; j < obsProjCoeffs.size(); ++j)
368
    {
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
369
370
371
372
      // The expectation of the pauli product of the Hamiltonian term
      // and the sweeping pauli term.
      const auto expectVal = calcSmatEntry(sigmaExpectation, i, j);
      b -= obsProjCoeffs[j] * expectVal / std::sqrt(c);
373
    }
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
    b = I*b - I*std::conj(b);
    // Set b_Vec
    b_Vec(i) = b;
  }

  // std::cout << "S Matrix: \n" << S_Mat << "\n"; 
  // std::cout << "B Vector: \n" << b_Vec << "\n"; 
  // Add regularizer
  arma::cx_mat dalpha(sMatDim, sMatDim, arma::fill::eye); 
  dalpha = 0.1 * dalpha;

  auto lhs = S_Mat + S_Mat.st() + dalpha;
  auto rhs = -b_Vec;

  // std::cout << "LHS Matrix: \n" << lhs << "\n"; 
  // std::cout << "RHS Vector: \n" << rhs << "\n"; 
  arma::cx_vec a_Vec = arma::solve(lhs, rhs);
  // std::cout << "Result A Vector: \n" << a_Vec << "\n"; 

  // Now, we have the decomposition of A observable in the basis of
  // all possible Pauli combinations.
  assert(a_Vec.n_elem == pauliOps.size());
  const std::string aObsStr = [&](){
    std::stringstream s;
    s.precision(12);
    s << std::fixed << a_Vec(0);
400
    
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
401
    for (int i = 1; i < pauliOps.size(); ++i)
402
    {
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
403
      s << " + " << (-2.0 * a_Vec(i)) << " " << pauliOps[i];
404
    }
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
405

Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
406
407
    return s.str();
  }(); 
408

Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
409
410
411
412
413
414
415
  // Step 3: compute the approximate A observable/Hamiltonian.
  // This operator will drive the exp_i_theta evolution
  // which emulate the imaginary time evolution of the original observable.
  std::shared_ptr<Observable> updatedAham = std::make_shared<xacc::quantum::PauliOperator>();
  updatedAham->fromString(aObsStr);
  return updatedAham; 
}
416

Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
417
418
void QITE::execute(const std::shared_ptr<AcceleratorBuffer> buffer) const 
{
419
  if(!m_analytical)
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
420
  {
421
422
423
424
425
426
    // Run on hardware/simulator using quantum gates/measure
    // Initial energy
    m_energyAtStep.emplace_back(calcCurrentEnergy(buffer->size()));
    
    // Time stepping:
    for (int i = 0; i < m_nbSteps; ++i)
427
    {
428
429
430
431
432
433
434
435
436
437
      for (const auto& hamTerm : m_observable->getNonIdentitySubTerms())
      {
        // Propagates the state via Trotter steps:
        auto kernel = constructPropagateCircuit();
        // Optimizes/calculates next A ops
        auto nextAOps = calcAOps(buffer, kernel, hamTerm);
        m_approxOps.emplace_back(nextAOps);
      }

      m_energyAtStep.emplace_back(calcCurrentEnergy(buffer->size()));
438
    }
439
440
441
442
443
444
    assert(m_energyAtStep.size() == m_nbSteps + 1);
    // Last energy value
    buffer->addExtraInfo("opt-val", ExtraInfo(m_energyAtStep.back()));
    // Also returns the full list of energy values 
    // at each Trotter step.
    buffer->addExtraInfo("exp-vals", ExtraInfo(m_energyAtStep));
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
445
  }
446
447
448
449
450
451
452
  else
  {
    // Analytical run:
    // This serves two purposes:
    // (1) Validate the convergence (e.g. Trotter step size) before running via gates.
    // (2) Derive the circuit analytically for running.
    // exp(-dtH)
453
    const auto expMinusHamTerm = [](const arma::cx_mat& in_hMat, const arma::cx_vec& in_psi, double in_dt) {
454
455
456
457
458
459
460
461
462
      assert(in_hMat.n_rows == in_hMat.n_cols);
      assert(in_hMat.n_rows == in_psi.n_elem);
      arma::cx_mat hMatExp = arma::expmat(-in_dt*in_hMat);
      arma::cx_vec result = hMatExp * in_psi;
      const double norm = arma::norm(result, 2);
      result = result / norm;
      return std::make_pair(result, norm);
    };
    
463
    const auto getTomographyExpVec = [](int in_nbQubits, const arma::cx_vec& in_psi, const arma::cx_vec& in_delta) {
464
      const auto pauliOps = generatePauliPermutation(in_nbQubits);
465
466
467
      std::vector<std::complex<double>> sigmaExpectation(pauliOps.size());
      std::vector<std::complex<double>> bVec(pauliOps.size());

468
      sigmaExpectation[0] = 1.0;
469
470
      bVec[0] = arma::cdot(in_delta, in_psi);

471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
      for (int i = 1; i < pauliOps.size(); ++i)
      {
        auto tomoObservable = std::make_shared<xacc::quantum::PauliOperator>();
        const std::string pauliObsStr = "1.0 " + pauliOps[i];
        tomoObservable->fromString(pauliObsStr);
        assert(tomoObservable->getSubTerms().size() == 1);
        assert(tomoObservable->getNonIdentitySubTerms().size() == 1);
        arma::cx_mat hMat(1 << in_nbQubits, 1 << in_nbQubits, arma::fill::zeros);
        const auto hamMat = tomoObservable->toDenseMatrix(in_nbQubits);
        for (int i = 0; i < hMat.n_rows; ++i)
        {
          for (int j = 0; j < hMat.n_cols; ++j)
          {
            const int index = i*hMat.n_rows + j;
            hMat(i, j) = hamMat[index];
          }
        }
488
489
490
491

        arma::cx_vec pauliApplied = hMat*in_psi;
        sigmaExpectation[i] = arma::cdot(in_psi, pauliApplied);
        bVec[i] = arma::cdot(in_delta, pauliApplied);
492
493
      }

494
      return std::make_pair(sigmaExpectation, bVec);
495
    };
496

497
498
    // Initial state
    arma::cx_vec psiVec(1 << buffer->size(), arma::fill::zeros);
499
    psiVec(1) = 1.0;
500
501
502
503
    // Time stepping:
    for (int i = 0; i < m_nbSteps; ++i)
    {
      arma::cx_mat hMat(1 << buffer->size(), 1 << buffer->size(), arma::fill::zeros);
504
505
506
507
508
509
510
511
      
      auto identityTerm = m_observable->getIdentitySubTerm();
      if (identityTerm)
      {
        arma::cx_mat idTerm(1 << buffer->size(), 1 << buffer->size(), arma::fill::eye);
        hMat += identityTerm->coefficient() * idTerm;
      }

512
513
514
515
516
517
518
519
520
521
522
      double stateVecNorm = 1.0;
      for (const auto& hamTerm : m_observable->getNonIdentitySubTerms())
      {
        auto pauliCast = std::dynamic_pointer_cast<xacc::quantum::PauliOperator>(hamTerm);
        const auto hamMat = pauliCast->toDenseMatrix(buffer->size());
      
        for (int i = 0; i < hMat.n_rows; ++i)
        {
          for (int j = 0; j < hMat.n_cols; ++j)
          {
            const int index = i*hMat.n_rows + j;
523
            hMat(i, j) += hamMat[index];
524
525
          }
        }
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
      }
      double normAfter = 0.0;
      arma::cx_vec dPsiVec(1 << buffer->size(), arma::fill::zeros);
      std::tie(dPsiVec, normAfter) = expMinusHamTerm(hMat, psiVec, m_dBeta);
      stateVecNorm *= normAfter;
      // Eq. 8, SI of https://arxiv.org/pdf/1901.07653.pdf
      dPsiVec = dPsiVec - psiVec;
      std::vector<std::complex<double>> pauliExp;
      std::vector<std::complex<double>> bVec;
      std::tie(pauliExp, bVec) = getTomographyExpVec(buffer->size(), psiVec, dPsiVec);
      std::vector<double> pauliExpValues;
      for (const auto& val: pauliExp)
      {
        pauliExpValues.emplace_back(val.real());
      }
541

542
543
544
545
546
      arma::cx_mat sMat = createSMatrix(generatePauliPermutation(buffer->size()), pauliExpValues);
      arma::cx_vec b_Vec(bVec.size(), arma::fill::zeros); 
      for (int i = 0; i < bVec.size(); ++i)
      {
        b_Vec(i) = -I*bVec[i] + I*std::conj(bVec[i]);
547
      }
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
      
      auto lhs = sMat + sMat.st();
      auto rhs = b_Vec;
      arma::cx_vec a_Vec = arma::solve(lhs, rhs);
      const auto pauliOps = generatePauliPermutation(buffer->size());
      const std::string aObsStr = [&](){
        std::stringstream s;
        s.precision(12);
        s << std::fixed << a_Vec(0);
        
        for (int i = 1; i < pauliOps.size(); ++i)
        {
          s << " + " << a_Vec(i) << " " << pauliOps[i];
        }

        return s.str();
      }(); 

      std::shared_ptr<xacc::quantum::PauliOperator> updatedAham = std::make_shared<xacc::quantum::PauliOperator>();
      updatedAham->fromString(aObsStr);
      const auto aHamMat = updatedAham->toDenseMatrix(buffer->size());
      arma::cx_mat aMat(1 << buffer->size(), 1 << buffer->size(), arma::fill::zeros);

      for (int i = 0; i < aMat.n_rows; ++i)
      {
        for (int j = 0; j < aMat.n_cols; ++j)
        {
          const int index = i*aMat.n_rows + j;
          aMat(i, j) = aHamMat[index];
        }
      }

      // Evolve exp(-iAt)
      arma::cx_mat aMatExp = arma::expmat(-I*aMat);
      arma::cx_mat psiUpdate = aMatExp*psiVec;
      psiVec = psiUpdate;
      const std::complex<double> energyRaw = arma::cdot(psiUpdate, hMat*psiUpdate);
      std::cout << "Energy = " << energyRaw << "\n";
      m_energyAtStep.emplace_back(energyRaw.real());
587
588
589
590
591
592
593
      // First step: add the approximate operator info to the buffer.
      // Users can use this analytical solver to compute the A operator:
      // e.g. for deuteron problems, we can recover the UCC ansatz by QITE. 
      if (i==0)
      {
        buffer->addExtraInfo("A-op", updatedAham->toString());
      }
594
    }
595
596
597
598
599
600
601
602

    m_energyAtStep.emplace_back(m_energyAtStep.back());
    assert(m_energyAtStep.size() == m_nbSteps + 1);
    // Last energy value
    buffer->addExtraInfo("opt-val", ExtraInfo(m_energyAtStep.back()));
    // Also returns the full list of energy values 
    // at each Trotter step.
    buffer->addExtraInfo("exp-vals", ExtraInfo(m_energyAtStep));
603
  } 
604
605
606
607
}

std::vector<double> QITE::execute(const std::shared_ptr<AcceleratorBuffer> buffer, const std::vector<double>& x) 
{
608
609
610
  // We don't do any parameter optimization here,
  // hence don't support this!
  xacc::error("This method is unsupported!");
611
612
613
614
  return {};
}
} // namespace algorithm
} // namespace xacc