Maestro 0.1.0
Unified interface for quantum circuit simulation
Loading...
Searching...
No Matches
AerState.h
Go to the documentation of this file.
1
13#pragma once
14
15#ifndef _AER_STATE_H_
16#define _AER_STATE_H_
17
18#ifndef NO_QISKIT_AER
19
20#ifdef INCLUDED_BY_FACTORY
21
22#include <algorithm>
23
24#include "QubitRegister.h"
25#include "Simulator.h"
26
27#include "QiskitAerState.h"
28
29namespace Simulators {
30// TODO: Maybe use the pimpl idiom
31// https://en.cppreference.com/w/cpp/language/pimpl to hide the implementation
32// for good but during development this should be good enough
33namespace Private {
34
35class IndividualSimulator;
36
47class AerState : public ISimulator {
48 friend class IndividualSimulator;
50 public:
57 AerState() {
58 std::random_device rd;
59
60 rng.seed(rd());
61 Configure("method", "statevector");
62 }
63
71 void Initialize() override {
72 SetMultithreading(enableMultithreading);
73 if (simulationType == SimulationType::kMatrixProductState)
74 Configure("mps_sample_measure_algorithm", useMPSMeasureNoCollapse
75 ? "mps_probabilities"
76 : "mps_apply_measure");
77 state->initialize();
78 }
79
91 void InitializeState(size_t num_qubits,
92 std::vector<std::complex<double>> &amplitudes) override {
93 Clear();
94 state->initialize_statevector(num_qubits, amplitudes.data(), true);
95 }
96
108 /*
109 void InitializeState(size_t num_qubits, std::vector<std::complex<double>,
110 avoid_init_allocator<std::complex<double>>>& amplitudes) override
111 {
112 Clear();
113 state->initialize_statevector(num_qubits, amplitudes.data(), true);
114 }
115 */
116
128 void InitializeState(size_t num_qubits,
129 AER::Vector<std::complex<double>> &amplitudes) override {
130 Clear();
131 state->initialize_statevector(num_qubits, amplitudes.move_to_buffer(),
132 false);
133 }
134
146 void InitializeState(size_t num_qubits,
147 Eigen::VectorXcd &amplitudes) override {
148 Clear();
149 state->initialize_statevector(num_qubits, amplitudes.data(), true);
150 }
151
158 void Reset() override {
159 const auto numQubits = GetNumberOfQubits();
160 Clear();
161 AllocateQubits(numQubits);
162 state->initialize();
163 }
164
173 void Configure(const char *key, const char *value) override {
174 if (std::string("method") == key) {
175 if (std::string("statevector") == value)
176 simulationType = SimulationType::kStatevector;
177 else if (std::string("matrix_product_state") == value)
178 simulationType = SimulationType::kMatrixProductState;
179 else if (std::string("stabilizer") == value)
180 simulationType = SimulationType::kStabilizer;
181 else if (std::string("tensor_network") == value)
182 simulationType = SimulationType::kTensorNetwork;
183 else if (std::string("extended_stabilizer") == value)
184 simulationType = SimulationType::kExtendedStabilizer;
185 else
186 simulationType = SimulationType::kOther;
187 } else if (std::string("matrix_product_state_truncation_threshold") ==
188 key) {
189 singularValueThreshold = std::stod(value);
190 if (singularValueThreshold > 0.)
191 limitEntanglement = true;
192 else
193 limitEntanglement = false;
194 } else if (std::string("matrix_product_state_max_bond_dimension") == key) {
195 chi = std::stoi(value);
196 if (chi > 0)
197 limitSize = true;
198 else
199 limitSize = false;
200 } else if (std::string("mps_sample_measure_algorithm") == key)
201 useMPSMeasureNoCollapse = std::string("mps_probabilities") == value;
202
203 state->configure(key, value);
204 }
205
213 std::string GetConfiguration(const char *key) const override {
214 if (std::string("method") == key) {
215 switch (simulationType) {
216 case SimulationType::kStatevector:
217 return "statevector";
218 case SimulationType::kMatrixProductState:
219 return "matrix_product_state";
220 case SimulationType::kStabilizer:
221 return "stabilizer";
222 case SimulationType::kTensorNetwork:
223 return "tensor_network";
224 case SimulationType::kExtendedStabilizer:
225 return "extended_stabilizer";
226 default:
227 return "other";
228 }
229 } else if (std::string("matrix_product_state_truncation_threshold") ==
230 key) {
231 if (limitEntanglement && singularValueThreshold > 0.)
232 return std::to_string(singularValueThreshold);
233 } else if (std::string("matrix_product_state_max_bond_dimension") == key) {
234 if (limitSize && limitSize > 0) return std::to_string(chi);
235 } else if (std::string("mps_sample_measure_algorithm") == key) {
236 return useMPSMeasureNoCollapse ? "mps_probabilities"
237 : "mps_apply_measure";
238 }
239
240 return "";
241 }
242
250 size_t AllocateQubits(size_t num_qubits) override {
251 const auto ids = state->allocate_qubits(num_qubits);
252 return ids[0];
253 }
254
261 size_t GetNumberOfQubits() const override {
262 if (state->is_initialized()) return state->num_of_qubits();
263
264 return 0;
265 }
266
274 void Clear() override {
275 state->clear();
276 SetMultithreading(enableMultithreading);
277
278 if (simulationType == SimulationType::kMatrixProductState)
279 Configure("mps_sample_measure_algorithm", useMPSMeasureNoCollapse
280 ? "mps_probabilities"
281 : "mps_apply_measure");
282 }
283
291 size_t Measure(const Types::qubits_vector &qubits) override {
292 const size_t res = state->apply_measure(qubits);
293
294 NotifyObservers(qubits);
295
296 return res;
297 }
298
305 void ApplyReset(const Types::qubits_vector &qubits) override {
306 state->apply_reset(qubits);
307
308 NotifyObservers(qubits);
309 }
310
322 double Probability(Types::qubit_t outcome) override {
323 return state->probability(outcome);
324 }
325
336 std::complex<double> Amplitude(Types::qubit_t outcome) override {
337 return state->amplitude(outcome);
338 }
339
350 std::vector<double> AllProbabilities() override {
351 return state->probabilities();
352 }
353
365 std::vector<double> Probabilities(
366 const Types::qubits_vector &qubits) override {
367 return state->probabilities(qubits);
368 }
369
386 std::unordered_map<Types::qubit_t, Types::qubit_t> SampleCounts(
387 const Types::qubits_vector &qubits, size_t shots = 1000) override {
388 if (qubits.empty() || shots == 0) return {};
389
390 const std::unordered_map<Types::qubit_t, Types::qubit_t> res =
391 state->sample_counts(qubits, shots);
392
393 NotifyObservers(qubits);
394
395 return res;
396 }
397
409 double ExpectationValue(const std::string &pauliStringOrig) override {
410 if (pauliStringOrig.empty()) return 1.0;
411
412 std::string pauliString = pauliStringOrig;
413 if (pauliString.size() > GetNumberOfQubits()) {
414 for (size_t i = GetNumberOfQubits(); i < pauliString.size(); ++i) {
415 const auto pauliOp = toupper(pauliString[i]);
416 if (pauliOp != 'I' && pauliOp != 'Z') return 0.0;
417 }
418
419 pauliString.resize(GetNumberOfQubits());
420 }
421
422 AER::reg_t qubits;
423 std::string pauli;
424
425 pauli.reserve(pauliString.size());
426 qubits.reserve(pauliString.size());
427
428 for (size_t q = 0; q < pauliString.size(); ++q) {
429 const char p = toupper(pauliString[q]);
430 if (p == 'I') continue;
431
432 pauli.push_back(p);
433 qubits.push_back(q);
434 }
435
436 if (qubits.empty()) return 1.0;
437
438 // qiskit aer expects the pauli string in reverse order
439 std::reverse(pauli.begin(), pauli.end());
440
441 return state->expval_pauli(qubits, pauli);
442 }
443
451 SimulatorType GetType() const override { return SimulatorType::kQiskitAer; }
452
461 SimulationType GetSimulationType() const override { return simulationType; }
462
471 void Flush() override {
472 state->flush_ops();
473 // state->set_random_seed(); // avoid reusing the old seed
474 }
475
485 void SaveStateToInternalDestructive() override {
486 savedAmplitudes = state->move_to_vector();
487 }
488
496 const size_t numQubits = static_cast<size_t>(log2(savedAmplitudes.size()));
497 state->initialize_statevector(numQubits, savedAmplitudes.move_to_buffer(),
498 false);
499 }
500
509 void SaveState() override {
510 if (!state) return;
511
512 const auto numQubits = GetNumberOfQubits();
513
514 if (simulationType == SimulationType::kStatevector) {
516 state->initialize_statevector(numQubits, savedAmplitudes.data(), true);
517 return;
518 }
519
520 bool saved = false;
521
522 if (state->is_initialized()) {
523 AER::Operations::Op op;
524
525 op.type = AER::Operations::OpType::save_state;
526 op.name = "save_state";
527 op.save_type = AER::Operations::DataSubType::single;
528 op.string_params.push_back("s");
529
530 for (size_t q = 0; q < numQubits; ++q) op.qubits.push_back(q);
531
532 state->buffer_op(std::move(op));
533 Flush();
534
535 // get the state from the last result
536 AER::ExperimentResult &last_result = state->last_result();
537 // state should be in last_result.data
538 if (last_result.status == AER::ExperimentResult::Status::completed) {
539 savedState = std::move(last_result.data);
540 saved = true;
541 }
542 } else {
543 // try get the state from the last result
544 AER::ExperimentResult &last_result_prev = state->last_result();
545 // state should be in last_result.data
546 if (last_result_prev.status == AER::ExperimentResult::Status::completed) {
547 savedState = std::move(last_result_prev.data);
548 saved = true;
549 }
550 }
551
552 // this is a hack, for statevector and matrix product state if the last op
553 // is executed, it can destroy the state! see also the workaround for
554 // statevector for the stabilizer at least for now it doesn't seem to do
555 // that
556 // TODO: check everything!!!!
557 if (saved && simulationType == SimulationType::kMatrixProductState)
558 RestoreState();
559 }
560
569 void RestoreState() override {
570 auto numQubits = GetNumberOfQubits();
571
572 AER::Operations::Op op;
573
574 switch (simulationType) {
575 case SimulationType::kStatevector: {
576 // op.type = AER::Operations::OpType::set_statevec;
577 // op.name = "set_statevec";
578
579 // const auto& vec = static_cast<AER::DataMap<AER::SingleData,
580 // AER::Vector<complex_t>>>(savedState).value()["s"].value();
581
582 // this is a hack until I figure it out
583 Clear();
584 numQubits = static_cast<size_t>(log2(savedAmplitudes.size()));
585 state->initialize_statevector(numQubits, savedAmplitudes.data(), true);
586
587 return;
588 } break;
589 case SimulationType::kMatrixProductState:
590 op.type = AER::Operations::OpType::set_mps;
591 op.name = "set_mps";
592 op.mps =
593 static_cast<AER::DataMap<AER::SingleData, AER::mps_container_t>>(
594 savedState)
595 .value()["s"]
596 .value();
597
598 /*
599 {
600 auto& value = static_cast<AER::DataMap<AER::SingleData,
601 AER::mps_container_t>>(savedState).value(); if (!value.empty())
602 {
603 if (value.find("s") != value.end())
604 op.mps = value["s"].value();
605 else if (value.find("matrix_product_state") !=
606 value.end()) op.mps = value["matrix_product_state"].value();
607 }
608 }
609 */
610
611 numQubits = op.mps.first.size();
612 break;
613 case SimulationType::kStabilizer:
614 op.type = AER::Operations::OpType::set_stabilizer;
615 op.name = "set_stabilizer";
616 op.clifford =
617 static_cast<AER::DataMap<AER::SingleData, json_t>>(savedState)
618 .value()["s"]
619 .value();
620
621 /*
622 {
623 auto& value = static_cast<AER::DataMap<AER::SingleData,
624 json_t>>(savedState).value(); if (!value.empty())
625 {
626 if (value.find("s") != value.end())
627 op.clifford = value["s"].value();
628 else if (value.find("stabilizer") != value.end())
629 op.clifford = value["stabilizer"].value();
630 }
631 }
632 */
633
634 numQubits = op.clifford.num_qubits();
635 break;
636 case SimulationType::kTensorNetwork:
637 default:
638 throw std::runtime_error(
639 "AerState::RestoreState: not implemented yet "
640 "for this type of simulator.");
641 }
642
643 op.save_type = AER::Operations::DataSubType::single;
644 op.string_params.push_back("s");
645
646 for (size_t q = 0; q < numQubits; ++q) op.qubits.push_back(q);
647
648 // WHY?
649 if (!state->is_initialized()) {
650 Clear();
651 AllocateQubits(numQubits);
652 state->initialize();
653 }
654
655 state->buffer_op(std::move(op));
656 Flush();
657 }
658
666 std::complex<double> AmplitudeRaw(Types::qubit_t outcome) override {
667 return savedAmplitudes[outcome];
668 }
669
678 void SetMultithreading(bool multithreading = true) override {
679 enableMultithreading = multithreading;
680 if (state && !state->is_initialized()) {
681 const std::string nrThreads =
682 std::to_string(enableMultithreading
683 ? 0
684 : 1); // 0 means auto/all available, 1 limits to 1
685 state->configure("max_parallel_threads", nrThreads);
686 state->configure("parallel_state_update", nrThreads);
687 const std::string threadsLimit =
688 std::to_string(12); // set one less, multithreading is started if the
689 // value is bigger than this
690 state->configure("statevector_parallel_threshold", threadsLimit);
691 }
692 }
693
701 bool GetMultithreading() const override { return enableMultithreading; }
702
713 bool IsQcsim() const override { return false; }
714
728 Types::qubit_t MeasureNoCollapse() override {
729 if (simulationType == SimulationType::kStatevector) {
730 const double prob =
731 1. - uniformZeroOne(rng); // this excludes 0 as probabiliy
732 double accum = 0;
733 Types::qubit_t state = 0;
734 for (Types::qubit_t i = 0; i < savedAmplitudes.size(); ++i) {
735 accum += std::norm(savedAmplitudes[i]);
736 if (prob <= accum) {
737 state = i;
738 break;
739 }
740 }
741
742 return state;
743 }
744
745 throw std::runtime_error(
746 "AerState::MeasureNoCollapse: Invalid simulation type for measuring "
747 "all the qubits without collapsing the state.");
748
749 return 0;
750 }
751
752 protected:
753 SimulationType simulationType =
754 SimulationType::kStatevector;
755 std::unique_ptr<QiskitAerState> state =
756 std::make_unique<QiskitAerState>();
757 AER::Vector<complex_t> savedAmplitudes;
758 bool limitSize = false;
759 bool limitEntanglement = false;
760 Eigen::Index chi = 10; // if limitSize is true
761 double singularValueThreshold = 0.; // if limitEntanglement is true
762 bool enableMultithreading = true;
763 AER::Data savedState;
765 std::mt19937_64 rng;
766 std::uniform_real_distribution<double> uniformZeroOne{0., 1.};
767 bool useMPSMeasureNoCollapse =
768 true;
769};
770
771} // namespace Private
772} // namespace Simulators
773
774#endif
775
776#endif
777
778#endif // !_AER_STATE_H_
double Probability(void *sim, unsigned long long int outcome)
char * GetConfiguration(void *sim, const char *key)
int RestoreState(void *sim)
int ApplyReset(void *sim, const unsigned long int *qubits, unsigned long int nrQubits)
unsigned long int AllocateQubits(void *sim, unsigned long int nrQubits)
unsigned long int GetNumberOfQubits(void *sim)
double * AllProbabilities(void *sim)
unsigned long long int MeasureNoCollapse(void *sim)
int GetMultithreading(void *sim)
unsigned long long int Measure(void *sim, const unsigned long int *qubits, unsigned long int nrQubits)
double * Amplitude(void *sim, unsigned long long int outcome)
double * Probabilities(void *sim, const unsigned long long int *qubits, unsigned long int nrQubits)
int SetMultithreading(void *sim, int multithreading)
int SaveStateToInternalDestructive(void *sim)
int GetSimulationType(void *sim)
unsigned long long int * SampleCounts(void *sim, const unsigned long long int *qubits, unsigned long int nrQubits, unsigned long int shots)
int RestoreInternalDestructiveSavedState(void *sim)
int IsQcsim(void *sim)
int SaveState(void *sim)