qite.cpp 20.8 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's avatar
Nguyen, Thien committed
17
18
19
#include "xacc_service.hpp"
#include "PauliOperator.hpp"
#include "Circuit.hpp"
20
#include <memory>
21
22
#include <armadillo>
#include <cassert>
23

Nguyen, Thien's avatar
Nguyen, Thien committed
24
25
namespace {
const std::complex<double> I{ 0.0, 1.0};
Nguyen, Thien's avatar
Nguyen, Thien 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;
Nguyen, Thien's avatar
Nguyen, Thien committed
52
53
}

Nguyen, Thien's avatar
Nguyen, Thien 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's avatar
Nguyen, Thien 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

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;
    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's avatar
Nguyen, Thien committed
137
138
139
}

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

Nguyen, Thien's avatar
Nguyen, Thien 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
  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"));
  }

Nguyen, Thien's avatar
Nguyen, Thien committed
177
  m_analytical = false;
178
179
180
  if (parameters.keyExists<bool>("analytical")) 
  {
    m_analytical = parameters.get<bool>("analytical");
Nguyen, Thien's avatar
Nguyen, Thien committed
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
    if (m_analytical)
    {
      // Default initial state is 0
      m_initialState = 0;
      if (parameters.keyExists<int>("initial-state"))
      {
        m_initialState = parameters.get<int>("initial-state");
      } 
    }
  }

  m_ansatz = nullptr;
  // Ansatz here is just a state preparation circuit:
  // e.g. if we want to start in state |01>, not |00>
  if (parameters.pointerLikeExists<CompositeInstruction>("ansatz")) 
  {
    m_ansatz = parameters.getPointerLike<CompositeInstruction>("ansatz");
198
199
  }

200
201
  m_approxOps.clear();
  m_energyAtStep.clear();
202
  
Nguyen, Thien's avatar
Nguyen, Thien committed
203
  return initializeOk;
204
205
206
207
}

const std::vector<std::string> QITE::requiredParameters() const 
{
Nguyen, Thien's avatar
Nguyen, Thien committed
208
  return { "accelerator", "steps", "step-size", "observable" };
209
210
}

Nguyen, Thien's avatar
Nguyen, Thien committed
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
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"));
Nguyen, Thien's avatar
Nguyen, Thien committed
250
251
      const bool expandOk = expCirc->expand({ std::make_pair("pauli", pauliStr) });
      assert(expandOk);
Nguyen, Thien's avatar
Nguyen, Thien committed
252
253
254
255
256
      auto evaled = expCirc->operator()({ m_dBeta });
      propagateKernel->addInstructions(evaled->getInstructions());
    }
  }

257
  // std::cout << "Progagated kernel:\n" << propagateKernel->toString() << "\n";
Nguyen, Thien's avatar
Nguyen, Thien committed
258
259
260
  return propagateKernel;
}

261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
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;
276
    if (f->nInstructions() > 0 && f->getInstruction(0)->isComposite()) 
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
    {
      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's avatar
Nguyen, Thien committed
309

Nguyen, Thien's avatar
Nguyen, Thien committed
310
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
311
{
Nguyen, Thien's avatar
Nguyen, Thien committed
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
  const auto pauliOps = generatePauliPermutation(in_buffer->size());

  // 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's avatar
Nguyen, Thien committed
331

Nguyen, Thien's avatar
Nguyen, Thien committed
332
333
334
335
336
  // 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's avatar
Nguyen, Thien committed
337
  
Nguyen, Thien's avatar
Nguyen, Thien committed
338
339
  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's avatar
Nguyen, Thien committed
340
    // S(i, j) = <psi|sigma_dagger(i)sigma(j)|psi>
Nguyen, Thien's avatar
Nguyen, Thien committed
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
    // 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's avatar
Nguyen, Thien committed
356
    {
Nguyen, Thien's avatar
Nguyen, Thien committed
357
358
      const auto entry = calcSmatEntry(sigmaExpectation, i, j);
      S_Mat(i, j) = std::abs(entry) > 1e-12 ? entry : 0.0;
Nguyen, Thien's avatar
Nguyen, Thien committed
359
    }
Nguyen, Thien's avatar
Nguyen, Thien committed
360
  }
Nguyen, Thien's avatar
Nguyen, Thien committed
361

Nguyen, Thien's avatar
Nguyen, Thien committed
362
363
364
365
366
367
368
369
370
371
372
373
374
375
  // b vector:
  const auto obsProjCoeffs = observableToVec(in_hmTerm, pauliOps);

  // 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];
  }
  
  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)
Nguyen, Thien's avatar
Nguyen, Thien committed
376
    {
Nguyen, Thien's avatar
Nguyen, Thien committed
377
378
379
380
      // 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);
Nguyen, Thien's avatar
Nguyen, Thien committed
381
    }
Nguyen, Thien's avatar
Nguyen, Thien committed
382
383
    b = I*b - I*std::conj(b);
    // Set b_Vec
Nguyen, Thien's avatar
Nguyen, Thien committed
384
    b_Vec(i) = std::abs(b) > 1e-12 ? b : 0.0;
Nguyen, Thien's avatar
Nguyen, Thien committed
385
  }
Nguyen, Thien's avatar
Nguyen, Thien committed
386
387
  
  auto lhs = S_Mat + S_Mat.st();
Nguyen, Thien's avatar
Nguyen, Thien committed
388
389
390
391
392
393
394
395
396
397
  auto rhs = -b_Vec;
  arma::cx_vec a_Vec = arma::solve(lhs, rhs);

  // 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);
Nguyen, Thien's avatar
Nguyen, Thien committed
398
    
Nguyen, Thien's avatar
Nguyen, Thien committed
399
    for (int i = 1; i < pauliOps.size(); ++i)
Nguyen, Thien's avatar
Nguyen, Thien committed
400
    {
Nguyen, Thien's avatar
Nguyen, Thien committed
401
      s << " + " << (-2.0 * a_Vec(i)) << " " << pauliOps[i];
Nguyen, Thien's avatar
Nguyen, Thien committed
402
    }
Nguyen, Thien's avatar
Nguyen, Thien committed
403

Nguyen, Thien's avatar
Nguyen, Thien committed
404
405
    return s.str();
  }(); 
406

Nguyen, Thien's avatar
Nguyen, Thien committed
407
408
409
410
411
412
413
  // 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; 
}
414

Nguyen, Thien's avatar
Nguyen, Thien committed
415
416
void QITE::execute(const std::shared_ptr<AcceleratorBuffer> buffer) const 
{
417
  if(!m_analytical)
Nguyen, Thien's avatar
Nguyen, Thien committed
418
  {
419
420
421
    // Run on hardware/simulator using quantum gates/measure
    // Initial energy
    m_energyAtStep.emplace_back(calcCurrentEnergy(buffer->size()));
Nguyen, Thien's avatar
Nguyen, Thien committed
422
423
424
425
426
427
    auto hamOp = std::make_shared<xacc::quantum::PauliOperator>();
    for (const auto& hamTerm : m_observable->getNonIdentitySubTerms())
    {
      *hamOp = *hamOp + *(std::dynamic_pointer_cast<xacc::quantum::PauliOperator>(hamTerm));
    }

428
429
    // Time stepping:
    for (int i = 0; i < m_nbSteps; ++i)
430
    {
Nguyen, Thien's avatar
Nguyen, Thien committed
431
432
433
434
435
      // Propagates the state via Trotter steps:
      auto kernel = constructPropagateCircuit();
      // Optimizes/calculates next A ops
      auto nextAOps = calcAOps(buffer, kernel, hamOp);
      m_approxOps.emplace_back(nextAOps); 
436
      m_energyAtStep.emplace_back(calcCurrentEnergy(buffer->size()));
437
    }
438
439
440
441
442
443
    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's avatar
Nguyen, Thien committed
444
  }
445
446
447
448
449
450
451
  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)
452
    const auto expMinusHamTerm = [](const arma::cx_mat& in_hMat, const arma::cx_vec& in_psi, double in_dt) {
453
454
455
456
457
458
459
460
461
      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);
    };
    
462
    const auto getTomographyExpVec = [](int in_nbQubits, const arma::cx_vec& in_psi, const arma::cx_vec& in_delta) {
463
      const auto pauliOps = generatePauliPermutation(in_nbQubits);
464
465
466
      std::vector<std::complex<double>> sigmaExpectation(pauliOps.size());
      std::vector<std::complex<double>> bVec(pauliOps.size());

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

470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
      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];
          }
        }
487
488
489
490

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

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

496
497
    // Initial state
    arma::cx_vec psiVec(1 << buffer->size(), arma::fill::zeros);
Nguyen, Thien's avatar
Nguyen, Thien committed
498
499
500
501
    psiVec(m_initialState) = 1.0;
    arma::cx_mat hMat(1 << buffer->size(), 1 << buffer->size(), arma::fill::zeros);
    auto identityTerm = m_observable->getIdentitySubTerm();
    if (identityTerm)
502
    {
Nguyen, Thien's avatar
Nguyen, Thien committed
503
504
505
      arma::cx_mat idTerm(1 << buffer->size(), 1 << buffer->size(), arma::fill::eye);
      hMat += identityTerm->coefficient() * idTerm;
    }
506

Nguyen, Thien's avatar
Nguyen, Thien committed
507
508
509
510
511
512
    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)
513
      {
Nguyen, Thien's avatar
Nguyen, Thien committed
514
        for (int j = 0; j < hMat.n_cols; ++j)
515
        {
Nguyen, Thien's avatar
Nguyen, Thien committed
516
517
          const int index = i*hMat.n_rows + j;
          hMat(i, j) += hamMat[index];
518
        }
519
      }
Nguyen, Thien's avatar
Nguyen, Thien committed
520
521
522
523
524
    }    

    // Time stepping:
    for (int i = 0; i < m_nbSteps; ++i)
    {
525
526
527
528
529
530
531
532
533
534
535
536
537
      double normAfter = 0.0;
      arma::cx_vec dPsiVec(1 << buffer->size(), arma::fill::zeros);
      std::tie(dPsiVec, normAfter) = expMinusHamTerm(hMat, psiVec, m_dBeta);
      // 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());
      }
538

539
540
541
542
543
      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]);
544
      }
545
546
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
      
      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());
584
585
586
587
588
589
590
      // 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());
      }
591
    }
592
593
594
595
596
597
598
599

    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));
600
  } 
601
602
603
604
}

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