PauliOperator.cpp 20.2 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
16
17
#include "PauliOperator.hpp"
#include "IRProvider.hpp"
#include <regex>
#include <set>
#include <iostream>
18
#include "Observable.hpp"
19
#include "xacc.hpp"
20
21
22
23
24
25
26
#include "xacc_service.hpp"

#include <Eigen/Core>

#include "PauliOperatorLexer.h"
#include "PauliListenerImpl.hpp"

27
28
#include <armadillo>

29
30
namespace xacc {
namespace quantum {
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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
103
104
105
106
107
108
109
110
111
112

std::vector<SparseTriplet> PauliOperator::to_sparse_matrix() {
  auto n_qubits = nQubits();
  auto n_hilbert = std::pow(2, n_qubits);
  using SparseMatrix = arma::SpMat<std::complex<double>>;

  SparseMatrix x(2, 2), y(2, 2), z(2, 2);
  x(0, 1) = 1.0;
  x(1, 0) = 1.0;
  y(0, 1) = std::complex<double>(0, -1);
  y(1, 0) = std::complex<double>(0, 1);
  z(0, 0) = 1.;
  z(1, 1) = -1.;

  SparseMatrix i = arma::speye<SparseMatrix>(2, 2);

  std::map<std::string, SparseMatrix> mat_map{
      {"I", i}, {"X", x}, {"Y", y}, {"Z", z}};

  auto kron_ops = [](std::vector<SparseMatrix> &ops) {
    auto first = ops[0];
    for (int i = 1; i < ops.size(); i++) {
      first = arma::kron(first, ops[i]);
    }
    return first;
  };

  SparseMatrix total(n_hilbert, n_hilbert);
  for (auto &term : terms) {
    auto tensor_factor = 0;
    auto coeff = term.second.coeff();

    std::vector<SparseMatrix> sparse_mats;

    if (term.second.ops().empty()) {
      // this was I term
      auto id = arma::speye<SparseMatrix>(n_hilbert, n_hilbert);
      sparse_mats.push_back(id);
    } else {
      for (auto &pauli : term.second.ops()) {
        if (pauli.first > tensor_factor) {

          auto id_qbits = pauli.first - tensor_factor;
          auto id = arma::speye<SparseMatrix>((int)std::pow(2, id_qbits),
                                              (int)std::pow(2, id_qbits));
          sparse_mats.push_back(id);
        }

        sparse_mats.push_back(mat_map[pauli.second]);
        tensor_factor = pauli.first + 1;
      }

      for (int i = tensor_factor; i < n_qubits; i++) {
        auto id = arma::speye<SparseMatrix>(2, 2);
        sparse_mats.push_back(id);
      }
    }

    
    auto sp_matrix = kron_ops(sparse_mats);
    sp_matrix *= coeff;
    total += sp_matrix;
  }

//   arma::vec eigval;
//   arma::mat eigvec;

//   arma::sp_mat test(total.n_rows, total.n_cols);
//   for (auto i = total.begin(); i != total.end(); ++i) {
//     test(i.row(), i.col()) = (*i).real();
//   }

//   arma::eigs_sym(eigval, eigvec, test, 1);

//   std::cout << "EIGS:\n" << eigval << "\n";

  std::vector<SparseTriplet> trips;
  for (auto iter = total.begin(); iter != total.end(); ++iter) {
    trips.emplace_back(iter.row(), iter.col(), *iter);
  }
  return trips;
}
113
114
115
116
117
118
119
120
121
122
123

PauliOperator::PauliOperator() {}

PauliOperator::PauliOperator(std::complex<double> c) {
  terms.emplace(std::make_pair("I", c));
}

PauliOperator::PauliOperator(double c) {
  terms.emplace(std::make_pair("I", c));
}

124
PauliOperator::PauliOperator(std::string fromStr) { fromString(fromStr); }
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173

PauliOperator::PauliOperator(std::complex<double> c, std::string var) {
  terms.emplace(std::piecewise_construct, std::forward_as_tuple("I"),
                std::forward_as_tuple(c, var));
}

PauliOperator::PauliOperator(const PauliOperator &i) : terms(i.terms) {}

/**
 * The Constructor, takes a vector of
 * qubit-gatename pairs. Initializes coefficient to 1
 *
 * @param operators The pauli operators making up this SpinInstruction
 */
PauliOperator::PauliOperator(std::map<int, std::string> operators) {
  terms.emplace(std::make_pair(Term::id(operators), operators));
}

PauliOperator::PauliOperator(std::map<int, std::string> operators,
                             std::string var) {
  terms.emplace(std::piecewise_construct,
                std::forward_as_tuple(Term::id(operators, var)),
                std::forward_as_tuple(var, operators));
}

/**
 * The Constructor, takes a vector of
 * qubit-gatename pairs and this instruction's coefficient
 *
 * @param operators
 * @param coeff
 */
PauliOperator::PauliOperator(std::map<int, std::string> operators,
                             std::complex<double> coeff) {
  terms.emplace(std::piecewise_construct,
                std::forward_as_tuple(Term::id(operators)),
                std::forward_as_tuple(coeff, operators));
}

PauliOperator::PauliOperator(std::map<int, std::string> operators, double coeff)
    : PauliOperator(operators, std::complex<double>(coeff, 0)) {}

PauliOperator::PauliOperator(std::map<int, std::string> operators,
                             std::complex<double> coeff, std::string var) {
  terms.emplace(std::piecewise_construct,
                std::forward_as_tuple(Term::id(operators, var)),
                std::forward_as_tuple(coeff, var, operators));
}

174
175
176
177
178
179
180
std::complex<double> PauliOperator::coefficient() {
  if (terms.size() > 1) {
    xacc::error("Cannot call PauliOperator::coefficient on operator with more "
                "than 1 term.");
  }
  return terms.begin()->second.coeff();
}
181
182
183
std::vector<std::shared_ptr<CompositeInstruction>>
PauliOperator::observe(std::shared_ptr<CompositeInstruction> function) {

184
  // Create a new GateQIR to hold the spin based terms
185
186
187
  auto gateRegistry = xacc::getService<IRProvider>("quantum");
  std::vector<std::shared_ptr<CompositeInstruction>> observed;
  int counter = 0;
188
  auto pi = xacc::constants::pi;
189
190
191
192
193
194

  // Populate GateQIR now...
  for (auto &inst : terms) {

    Term spinInst = inst.second;

195
196
    auto gateFunction =
        gateRegistry->createComposite(inst.first, function->getVariables());
197
198
199
200

    gateFunction->setCoefficient(spinInst.coeff());

    if (function->hasChildren()) {
201
      gateFunction->addInstruction(function->clone());
202
203
    }

204
    for (auto arg : function->getArguments()) {
205
      gateFunction->addArgument(arg, 0);
206
    }
207

208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
    // Loop over all terms in the Spin Instruction
    // and create instructions to run on the Gate QPU.
    std::vector<std::shared_ptr<xacc::Instruction>> measurements;
    auto termsMap = spinInst.ops();

    std::vector<std::pair<int, std::string>> terms;
    for (auto &kv : termsMap) {
      if (kv.second != "I" && !kv.second.empty()) {
        terms.push_back({kv.first, kv.second});
      }
    }

    for (int i = terms.size() - 1; i >= 0; i--) {
      auto qbit = terms[i].first;
      int t = qbit;
      std::size_t tt = t;
      auto gateName = terms[i].second;
225
226
      auto meas = gateRegistry->createInstruction("Measure",
                                                  std::vector<std::size_t>{tt});
227
228
229
230
231
232
233
234
235
      xacc::InstructionParameter classicalIdx(qbit);
      meas->setParameter(0, classicalIdx);
      measurements.push_back(meas);

      if (gateName == "X") {
        auto hadamard =
            gateRegistry->createInstruction("H", std::vector<std::size_t>{tt});
        gateFunction->addInstruction(hadamard);
      } else if (gateName == "Y") {
236
237
        auto rx =
            gateRegistry->createInstruction("Rx", std::vector<std::size_t>{tt});
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
        InstructionParameter p(pi / 2.0);
        rx->setParameter(0, p);
        gateFunction->addInstruction(rx);
      }
    }

    if (!spinInst.isIdentity()) {
      for (auto m : measurements) {
        gateFunction->addInstruction(m);
      }
    }

    observed.push_back(gateFunction);
    counter++;
  }
  return observed;
}

std::pair<std::vector<int>, std::vector<int>>
Term::toBinaryVector(const int nQubits) {
  // return v,w
  std::vector<int> v(nQubits), w(nQubits);

  for (auto &kv : ops()) {
    auto site = kv.first;
    auto pauli = kv.second;
    if (pauli == "X") {
      w[site] = 1;
    } else if (pauli == "Z") {
      v[site] = 1;
    } else if (pauli == "Y") {
      v[site] = 1;
      w[site] = 1;
    }
  }

  return {v, w};
}

ActionResult Term::action(const std::string &bitString, ActionType type) {

  auto _coeff = coeff();
  auto newBits = bitString;
  c i(0, 1);

  for (auto &t : ops()) {
    auto idx = t.first;
    auto gate = t.second;

    if (gate == "Z") {
      _coeff *= newBits[idx] == '1' ? -1 : 1;
    } else if (gate == "X") {
      newBits[idx] = (newBits[idx] == '1' ? '0' : '1');
    } else if (gate == "Y") {
      if (type == ActionType::Bra) {
        _coeff *= newBits[idx] == '1' ? i : -i;
      } else {
        _coeff *= newBits[idx] == '1' ? -i : i;
      }
      newBits[idx] = (newBits[idx] == '1' ? '0' : '1');
    }
  }

  return {newBits, _coeff};
}

const std::vector<std::pair<std::string, std::complex<double>>>
PauliOperator::computeActionOnKet(const std::string &bitString) {

  std::vector<std::pair<std::string, std::complex<double>>> ret;
  std::string newBits = bitString;
  std::complex<double> newCoeff(1, 0), i(0, 1);

  for (auto &kv : terms) {
    ret.push_back(kv.second.action(bitString, ActionType::Ket));
  }
  return ret;
}

const std::vector<std::pair<std::string, std::complex<double>>>
PauliOperator::computeActionOnBra(const std::string &bitString) {
  std::vector<std::pair<std::string, std::complex<double>>> ret;

  for (auto &kv : terms) {
    ret.push_back(kv.second.action(bitString, ActionType::Bra));
  }

  return ret;
}

std::vector<std::complex<double>> PauliOperator::toDenseMatrix(const int n) {
  std::size_t dim = 1;
  std::size_t two = 2;
  for (int i = 0; i < n; i++)
    dim *= two;
  auto getBitStrForIdx = [&](std::uint64_t i) {
    std::stringstream s;
    for (int k = n - 1; k >= 0; k--)
      s << ((i >> k) & 1);
    return s.str();
  };

  Eigen::MatrixXcd A(dim, dim);
  A.setZero();
  for (std::uint64_t myRow = 0; myRow < dim; myRow++) {
    auto rowBitStr = getBitStrForIdx(myRow);
    auto results = computeActionOnBra(rowBitStr);
    for (auto &result : results) {
      std::uint64_t k = std::stol(result.first, nullptr, 2);
      A(myRow, k) += result.second;
    }
  }

351
352
  std::vector<std::complex<double>> retv(dim * dim);
  Eigen::MatrixXcd::Map(&retv.data()[0], A.rows(), A.cols()) = A;
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505

  return retv;
}

const int PauliOperator::nTerms() { return terms.size(); }

bool PauliOperator::isClose(PauliOperator &other) {
  if (!operator==(other)) {
    return false;
  }

  // These are equal, check their coeffs
  for (auto &kv : terms) {
    Term otherTerm = other.terms[kv.first];
    if (std::abs(kv.second.coeff() - otherTerm.coeff()) > 1e-6) {
      return false;
    }
  }

  return true;
}

/**
 * Persist this Instruction to an assembly-like
 * string.
 *
 * @param bufferVarName The name of the AcceleratorBuffer
 * @return str The assembly-like string.
 */
const std::string PauliOperator::toString() {
  std::stringstream s;
  for (auto &kv : terms) {
    std::complex<double> c = std::get<0>(kv.second);
    std::string v = std::get<1>(kv.second);
    std::map<int, std::string> ops = std::get<2>(kv.second);

    s << c << " ";
    if (!v.empty()) {
      s << v << " ";
    }

    for (auto &kv2 : ops) {
      if (kv2.second == "I") {
        s << "I ";
      } else {
        s << kv2.second << kv2.first << " ";
      }
    }

    s << "+ ";
  }

  auto r = s.str().substr(0, s.str().size() - 2);
  xacc::trim(r);
  return r;
}

void PauliOperator::fromString(const std::string str) {
  using namespace antlr4;
  using namespace pauli;

  ANTLRInputStream input(str);
  PauliOperatorLexer lexer(&input);
  lexer.removeErrorListeners();
  lexer.addErrorListener(new PauliOperatorErrorListener());

  CommonTokenStream tokens(&lexer);
  PauliOperatorParser parser(&tokens);
  parser.removeErrorListeners();
  parser.addErrorListener(new PauliOperatorErrorListener());

  // Walk the Abstract Syntax Tree
  tree::ParseTree *tree = parser.pauliSrc();

  PauliListenerImpl listener;
  tree::ParseTreeWalker::DEFAULT.walk(&listener, tree);

  clear();

  operator+=(listener.getOperator());
}

bool PauliOperator::contains(PauliOperator &op) {
  if (op.nTerms() > 1)
    xacc::error("Cannot check PauliOperator.contains for more than 1 term.");
  for (auto &term : getTerms()) {
    if (op.terms.count(term.first)) {
      return true;
    }
  }
  return false;
}

bool PauliOperator::commutes(PauliOperator &op) {
  return (op * (*this) - (*this) * op).nTerms() == 0;
}

void PauliOperator::clear() { terms.clear(); }

PauliOperator &PauliOperator::operator+=(const PauliOperator &v) noexcept {
  for (auto &kv : v.terms) {

    auto termId = kv.first;
    auto otherTerm = kv.second;

    if (terms.count(termId)) {
      terms.at(termId).coeff() += otherTerm.coeff();
    } else {
      terms.insert({termId, otherTerm});
    }

    if (std::abs(terms[termId].coeff()) < 1e-12) {
      terms.erase(termId);
    }
  }

  return *this;
}

PauliOperator &PauliOperator::operator-=(const PauliOperator &v) noexcept {
  return operator+=(-1.0 * v);
}

PauliOperator &PauliOperator::operator*=(const PauliOperator &v) noexcept {

  std::unordered_map<std::string, Term> newTerms;
  for (auto &kv : terms) {
    for (auto &vkv : v.terms) {
      auto multTerm = kv.second * vkv.second;
      auto id = multTerm.id();

      if (!newTerms.insert({id, multTerm}).second) {
        newTerms.at(id).coeff() += multTerm.coeff();
      }

      if (std::abs(newTerms.at(id).coeff()) < 1e-12) {
        newTerms.erase(id);
      }
    }
  }
  terms = newTerms;
  return *this;
}

bool PauliOperator::operator==(const PauliOperator &v) noexcept {
  if (terms.size() != v.terms.size()) {
    return false;
  }

  for (auto &kv : terms) {
    bool found = false;
    for (auto &vkv : v.terms) {

506
507
      if (kv.second.operator==(vkv.second) |
          (kv.second.id() == "I" && vkv.second.id() == "I")) {
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
        found = true;
        break;
      }
    }

    if (!found) {
      return false;
    }
  }

  return true;
}

PauliOperator &PauliOperator::operator*=(const double v) noexcept {
  return operator*=(std::complex<double>(v, 0));
}

PauliOperator &
PauliOperator::operator*=(const std::complex<double> v) noexcept {
  for (auto &kv : terms) {
    std::get<0>(kv.second) *= v;
  }
  return *this;
}

533
std::vector<SparseTriplet> Term::getSparseMatrixElements(const int nQubits) {
534
535
536
537
538
539
540
541
542
543
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
584
585
586
587
588
589
590
591
592
593
594

  // X = |1><0| + |0><1|
  // Y = -i|1><0| + i|0><1|
  // Z = |0><0| - |1><1|

  auto comb = [](int N, int K) -> std::vector<std::vector<int>> {
    std::string bitmask(K, 1); // K leading 1's
    bitmask.resize(N, 0);      // N-K trailing 0's

    std::vector<std::vector<int>> allCombinations;
    // print integers and permute bitmask
    do {
      std::vector<int> bits;
      for (int i = 0; i < N; ++i) {
        if (bitmask[i]) {
          bits.push_back(i);
        }

        //					if (bitmask[i]) std::cout << " "
        //<< i;
      }

      bool add = true;
      for (int i = 1; i < bits.size(); i++) {
        if (bits[i] % 2 != 0 && std::abs(bits[i] - bits[i - 1]) == 1) {
          add = false;
          break;
        }
      }

      if (add) {
        allCombinations.push_back(bits);
      }
    } while (std::prev_permutation(bitmask.begin(), bitmask.end()));

    // for (auto a : allCombinations) {
    //   for (auto b : a) {
    //     std::cout << b << " ";
    //   }
    //   std::cout << "\n";
    // }

    // std::cout << (3 / 2) << "\n";
    return allCombinations;
  };

  auto nSites = ops().size();
  auto termCombinations = comb(2 * nSites, nSites);

  std::map<std::string, std::vector<std::pair<int, int>>> subterms;
  subterms["X"] = {{1, 0}, {0, 1}};
  subterms["Y"] = {{1, 0}, {0, 1}};
  subterms["Z"] = {{0, 0}, {1, 1}};

  std::string zeroStr = "";
  for (int i = 0; i < nQubits; i++)
    zeroStr += "0";

  auto ket = zeroStr;
  auto bra = zeroStr;

595
  std::vector<SparseTriplet> triplets;
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
  for (auto &combo : termCombinations) {

    std::complex<double> coeff(1, 0), i(0, 1);
    for (auto &c : combo) {

      auto iter = ops().begin();
      std::advance(iter, c / 2);
      auto ithOp = iter->second;
      auto ithOpSite = iter->first;
      auto x = (c % 2);

      //			Now I know the Operator and whether this is hte
      // 0 or 1st term for that op

      auto term = subterms[ithOp][x];

      ket[ithOpSite] = term.first ? '1' : '0';
      bra[ithOpSite] = term.second ? '1' : '0';

      if (ithOp == "Y") {
        if (x) {
          coeff *= i;
        } else {
          coeff *= -i;
        }
      } else if (ithOp == "Z") {
        if (x) {
          coeff *= -1;
        }
      }
    }

    // now convert bra and ket into integers
    auto row = std::stol(bra, nullptr, 2);
    auto col = std::stol(ket, nullptr, 2);

    triplets.emplace_back(row, col, coeff);
  }

  return triplets;
}

Term &Term::operator*=(const Term &v) noexcept {

  coeff() *= std::get<0>(v);

  std::string ss;
  std::string myVar = std::get<1>(*this);
  std::string otherVar = std::get<1>(v);
  if (!myVar.empty()) {
    if (!otherVar.empty()) {
      ss = myVar + " " + otherVar;
    } else {
      ss = myVar;
    }
  } else {
    if (!otherVar.empty()) {
      ss = otherVar;
    }
  }

  std::get<1>(*this) = ss;

  auto otherOps = std::get<2>(v);
  for (auto &kv : otherOps) {
    auto qubit = kv.first;
    auto gate = kv.second;
    if (ops().count(qubit)) {
      // This means, we have a op on same qubit in both
      // so we need to check its product
      auto myGate = ops().at(qubit);
      auto gate_coeff = pauliProducts.at(myGate + gate);
      if (gate_coeff.second != "I") {
        ops().at(kv.first) = gate_coeff.second;
      } else {
        ops().erase(kv.first);
      }
      coeff() *= gate_coeff.first;
    } else if (gate != "I") {
      ops().emplace(std::make_pair(qubit, gate));
    }
  }

  return *this;
}

PauliOperator PauliOperator::eval(
    const std::map<std::string, std::complex<double>> varToValMap) {
  PauliOperator ret;

  for (auto &kv : terms) {

    auto id = kv.first;
    auto term = kv.second;

    for (auto &varVal : varToValMap) {
      if (varVal.first == term.var()) {
        term.var() = "";
        term.coeff() *= varVal.second;
      }
    }

    ret.terms.insert({id, term});
  }

  return ret;
}

std::shared_ptr<IR> PauliOperator::toXACCIR() {
  // Create a new GateQIR to hold the spin based terms

  auto gateRegistry = xacc::getService<IRProvider>("quantum");
  auto tmp = gateRegistry->createComposite("tmp");
  auto kernels = observe(tmp);
  auto newIr = gateRegistry->createIR();
711
712
  for (auto &k : kernels)
    newIr->addComposite(k);
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
  return newIr;
}

int PauliOperator::nQubits() {
  auto maxInt = 0;
  if (terms.empty())
    return 0;

  for (auto &kv : terms) {
    auto ops = kv.second.ops();
    for (auto &kv2 : ops) {
      if (maxInt < kv2.first) {
        maxInt = kv2.first;
      }
    }
  }
  return maxInt + 1;
}

void PauliOperator::fromXACCIR(std::shared_ptr<IR> ir) {

  terms.clear();

  for (auto &kernel : ir->getComposites()) {
    std::map<int, std::string> pauliTerm;
    for (auto inst : kernel->getInstructions()) {

      if (!inst->isComposite()) {

        if (inst->name() == "H") {
          pauliTerm.insert({inst->bits()[0], "X"});
        } else if (inst->name() == "Rx") {
          pauliTerm.insert({inst->bits()[0], "Y"});
        }

        if (pauliTerm.count(inst->bits()[0]) == 0) {
          pauliTerm.insert({inst->bits()[0], "Z"});
        }
      }
    }
    std::complex<double> c = kernel->getCoefficient();

    if (pauliTerm.empty())
      pauliTerm.insert({0, "I"});

    Term t(c, pauliTerm);
    terms.insert({t.id(), t});
  }
}

763
764
765
766
std::shared_ptr<Observable> PauliOperator::commutator(std::shared_ptr<Observable> op) {

  PauliOperator& A = *std::dynamic_pointer_cast<PauliOperator>(op);
  std::shared_ptr<PauliOperator> commutatorHA =  std::make_shared<PauliOperator>((*this) * A - A * (*this));
767
  return commutatorHA;
768
769
770

}

771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
} // namespace quantum
} // namespace xacc

bool operator==(const xacc::quantum::PauliOperator &lhs,
                const xacc::quantum::PauliOperator &rhs) {
  if (lhs.getTerms().size() != rhs.getTerms().size()) {
    return false;
  }
  for (auto &kv : lhs.getTerms()) {
    bool found = false;
    for (auto &vkv : rhs.getTerms()) {

      if (kv.second.operator==(vkv.second)) {
        found = true;
        break;
      }
    }

    if (!found) {
      return false;
    }
  }

  return true;
}