diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000000..70b44d2f41 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,5 @@ +repos: +- repo: https://github.com/pre-commit/mirrors-clang-format + rev: v14.0.6 + hooks: + - id: clang-format diff --git a/contrib/runtime/aer_runtime.cpp b/contrib/runtime/aer_runtime.cpp index 865fc46513..b3826cfc15 100644 --- a/contrib/runtime/aer_runtime.cpp +++ b/contrib/runtime/aer_runtime.cpp @@ -11,218 +11,224 @@ * copyright notice, and modified files need to carry a notice indicating * that they have been altered from the originals. */ -#include #include "controllers/state_controller.hpp" +#include // initialize and return state extern "C" { -void* aer_state() { - AER::AerState* handler = new AER::AerState(); +void *aer_state() { + AER::AerState *handler = new AER::AerState(); return handler; }; -void* aer_state_initialize(void* handler) { - AER::AerState* state = reinterpret_cast(handler); +void *aer_state_initialize(void *handler) { + AER::AerState *state = reinterpret_cast(handler); state->initialize(); return handler; }; // finalize state -void aer_state_finalize(void* handler) { - AER::AerState* state = reinterpret_cast(handler); - delete(state); +void aer_state_finalize(void *handler) { + AER::AerState *state = reinterpret_cast(handler); + delete (state); }; // configure state -void aer_state_configure(void* handler, char* key, char* value) { - AER::AerState* state = reinterpret_cast(handler); +void aer_state_configure(void *handler, char *key, char *value) { + AER::AerState *state = reinterpret_cast(handler); state->configure(key, value); }; // allocate qubits and return the first qubit index. // following qubits are indexed with incremented indices. -uint_t aer_allocate_qubits(void* handler, uint_t num_qubits) { - AER::AerState* state = reinterpret_cast(handler); +uint_t aer_allocate_qubits(void *handler, uint_t num_qubits) { + AER::AerState *state = reinterpret_cast(handler); auto qubit_ids = state->allocate_qubits(num_qubits); return qubit_ids[0]; }; // measure qubits -uint_t aer_apply_measure(void* handler, uint_t* qubits_, size_t num_qubits) { - AER::AerState* state = reinterpret_cast(handler); +uint_t aer_apply_measure(void *handler, uint_t *qubits_, size_t num_qubits) { + AER::AerState *state = reinterpret_cast(handler); std::vector qubits; qubits.insert(qubits.end(), &(qubits_[0]), &(qubits[num_qubits - 1])); return state->apply_measure(qubits); }; // return probability of a specific bitstring -double aer_probability(void* handler, uint_t outcome) { - AER::AerState* state = reinterpret_cast(handler); +double aer_probability(void *handler, uint_t outcome) { + AER::AerState *state = reinterpret_cast(handler); return state->probability(outcome); }; // return probability amplitude of a specific bitstring -complex_t aer_amplitude(void* handler, uint_t outcome) { - AER::AerState* state = reinterpret_cast(handler); +complex_t aer_amplitude(void *handler, uint_t outcome) { + AER::AerState *state = reinterpret_cast(handler); return state->amplitude(outcome); }; // return probability amplitudes // returned pointer must be freed in the caller -complex_t* aer_release_statevector(void* handler) { - AER::AerState* state = reinterpret_cast(handler); +complex_t *aer_release_statevector(void *handler) { + AER::AerState *state = reinterpret_cast(handler); AER::Vector sv = state->move_to_vector(); return sv.move_to_buffer(); }; // phase gate -void aer_apply_p(void* handler, uint_t qubit, double lambda) { - AER::AerState* state = reinterpret_cast(handler); +void aer_apply_p(void *handler, uint_t qubit, double lambda) { + AER::AerState *state = reinterpret_cast(handler); state->apply_mcphase({qubit}, lambda); }; // Pauli gate: bit-flip or NOT gate -void aer_apply_x(void* handler, uint_t qubit) { - AER::AerState* state = reinterpret_cast(handler); +void aer_apply_x(void *handler, uint_t qubit) { + AER::AerState *state = reinterpret_cast(handler); state->apply_mcx({qubit}); }; // Pauli gate: bit and phase flip -void aer_apply_y(void* handler, uint_t qubit) { - AER::AerState* state = reinterpret_cast(handler); +void aer_apply_y(void *handler, uint_t qubit) { + AER::AerState *state = reinterpret_cast(handler); state->apply_mcy({qubit}); }; // Pauli gate: phase flip -void aer_apply_z(void* handler, uint_t qubit) { - AER::AerState* state = reinterpret_cast(handler); +void aer_apply_z(void *handler, uint_t qubit) { + AER::AerState *state = reinterpret_cast(handler); state->apply_mcz({qubit}); }; // Clifford gate: Hadamard -void aer_apply_h(void* handler, uint_t qubit) { - AER::AerState* state = reinterpret_cast(handler); +void aer_apply_h(void *handler, uint_t qubit) { + AER::AerState *state = reinterpret_cast(handler); state->apply_mcu({qubit}, M_PI / 2.0, 0, M_PI); }; // Clifford gate: sqrt(Z) or S gate -void aer_apply_s(void* handler, uint_t qubit) { - AER::AerState* state = reinterpret_cast(handler); +void aer_apply_s(void *handler, uint_t qubit) { + AER::AerState *state = reinterpret_cast(handler); state->apply_mcu({qubit}, 0, 0, M_PI / 2.0); }; // Clifford gate: inverse of sqrt(Z) -void aer_apply_sdg(void* handler, uint_t qubit) { - AER::AerState* state = reinterpret_cast(handler); - state->apply_mcu({qubit}, 0, 0, - M_PI / 2.0); +void aer_apply_sdg(void *handler, uint_t qubit) { + AER::AerState *state = reinterpret_cast(handler); + state->apply_mcu({qubit}, 0, 0, -M_PI / 2.0); }; // // sqrt(S) or T gate -void aer_apply_t(void* handler, uint_t qubit) { - AER::AerState* state = reinterpret_cast(handler); +void aer_apply_t(void *handler, uint_t qubit) { + AER::AerState *state = reinterpret_cast(handler); state->apply_mcu({qubit}, 0, 0, M_PI / 4.0); }; // inverse of sqrt(S) -void aer_apply_tdg(void* handler, uint_t qubit) { - AER::AerState* state = reinterpret_cast(handler); - state->apply_mcu({qubit}, 0, 0, - M_PI / 4.0); +void aer_apply_tdg(void *handler, uint_t qubit) { + AER::AerState *state = reinterpret_cast(handler); + state->apply_mcu({qubit}, 0, 0, -M_PI / 4.0); }; // sqrt(NOT) gate -void aer_apply_sx(void* handler, uint_t qubit) { - AER::AerState* state = reinterpret_cast(handler); - state->apply_mcrx({qubit}, - M_PI / 4.0); +void aer_apply_sx(void *handler, uint_t qubit) { + AER::AerState *state = reinterpret_cast(handler); + state->apply_mcrx({qubit}, -M_PI / 4.0); }; // Rotation around X-axis -void aer_apply_rx(void* handler, uint_t qubit, double theta) { - AER::AerState* state = reinterpret_cast(handler); +void aer_apply_rx(void *handler, uint_t qubit, double theta) { + AER::AerState *state = reinterpret_cast(handler); state->apply_mcrx({qubit}, theta); }; // rotation around Y-axis -void aer_apply_ry(void* handler, uint_t qubit, double theta) { - AER::AerState* state = reinterpret_cast(handler); +void aer_apply_ry(void *handler, uint_t qubit, double theta) { + AER::AerState *state = reinterpret_cast(handler); state->apply_mcry({qubit}, theta); }; // rotation around Z axis -void aer_apply_rz(void* handler, uint_t qubit, double theta) { - AER::AerState* state = reinterpret_cast(handler); +void aer_apply_rz(void *handler, uint_t qubit, double theta) { + AER::AerState *state = reinterpret_cast(handler); state->apply_mcrz({qubit}, theta); }; // controlled-NOT -void aer_apply_cx(void* handler, uint_t ctrl_qubit, uint_t tgt_qubit) { - AER::AerState* state = reinterpret_cast(handler); +void aer_apply_cx(void *handler, uint_t ctrl_qubit, uint_t tgt_qubit) { + AER::AerState *state = reinterpret_cast(handler); state->apply_mcx({ctrl_qubit, tgt_qubit}); }; // controlled-Y -void aer_apply_cy(void* handler, uint_t ctrl_qubit, uint_t tgt_qubit) { - AER::AerState* state = reinterpret_cast(handler); +void aer_apply_cy(void *handler, uint_t ctrl_qubit, uint_t tgt_qubit) { + AER::AerState *state = reinterpret_cast(handler); state->apply_mcy({ctrl_qubit, tgt_qubit}); }; // controlled-Z -void aer_apply_cz(void* handler, uint_t ctrl_qubit, uint_t tgt_qubit) { - AER::AerState* state = reinterpret_cast(handler); +void aer_apply_cz(void *handler, uint_t ctrl_qubit, uint_t tgt_qubit) { + AER::AerState *state = reinterpret_cast(handler); state->apply_mcz({ctrl_qubit, tgt_qubit}); }; // controlled-phase -void aer_apply_cp(void* handler, uint_t ctrl_qubit, uint_t tgt_qubit, double lambda) { - AER::AerState* state = reinterpret_cast(handler); +void aer_apply_cp(void *handler, uint_t ctrl_qubit, uint_t tgt_qubit, + double lambda) { + AER::AerState *state = reinterpret_cast(handler); state->apply_mcphase({ctrl_qubit, tgt_qubit}, lambda); }; // controlled-rx -void aer_apply_crx(void* handler, uint_t ctrl_qubit, uint_t tgt_qubit, double theta) { - AER::AerState* state = reinterpret_cast(handler); +void aer_apply_crx(void *handler, uint_t ctrl_qubit, uint_t tgt_qubit, + double theta) { + AER::AerState *state = reinterpret_cast(handler); state->apply_mcrx({ctrl_qubit, tgt_qubit}, theta); }; // controlled-ry -void aer_apply_cry(void* handler, uint_t ctrl_qubit, uint_t tgt_qubit, double theta) { - AER::AerState* state = reinterpret_cast(handler); +void aer_apply_cry(void *handler, uint_t ctrl_qubit, uint_t tgt_qubit, + double theta) { + AER::AerState *state = reinterpret_cast(handler); state->apply_mcry({ctrl_qubit, tgt_qubit}, theta); }; // controlled-rz -void aer_apply_crz(void* handler, uint_t ctrl_qubit, uint_t tgt_qubit, double theta) { - AER::AerState* state = reinterpret_cast(handler); +void aer_apply_crz(void *handler, uint_t ctrl_qubit, uint_t tgt_qubit, + double theta) { + AER::AerState *state = reinterpret_cast(handler); state->apply_mcrz({ctrl_qubit, tgt_qubit}, theta); }; // controlled-H -void aer_apply_ch(void* handler, uint_t ctrl_qubit, uint_t tgt_qubit) { - AER::AerState* state = reinterpret_cast(handler); +void aer_apply_ch(void *handler, uint_t ctrl_qubit, uint_t tgt_qubit) { + AER::AerState *state = reinterpret_cast(handler); state->apply_mcu({ctrl_qubit, tgt_qubit}, M_PI / 2.0, 0, M_PI); }; // swap -void aer_apply_swap(void* handler, uint_t qubit0, uint_t qubit1) { - AER::AerState* state = reinterpret_cast(handler); +void aer_apply_swap(void *handler, uint_t qubit0, uint_t qubit1) { + AER::AerState *state = reinterpret_cast(handler); state->apply_mcswap({qubit0, qubit1}); }; // Toffoli -void aer_apply_ccx(void* handler, uint_t qubit0, uint_t qubit1, uint_t qubit2) { - AER::AerState* state = reinterpret_cast(handler); +void aer_apply_ccx(void *handler, uint_t qubit0, uint_t qubit1, uint_t qubit2) { + AER::AerState *state = reinterpret_cast(handler); state->apply_mcx({qubit0, qubit1, qubit2}); }; // // controlled-swap -void aer_apply_cswap(void* handler, uint_t ctrl_qubit, uint_t qubit0, uint_t qubit1) { - AER::AerState* state = reinterpret_cast(handler); +void aer_apply_cswap(void *handler, uint_t ctrl_qubit, uint_t qubit0, + uint_t qubit1) { + AER::AerState *state = reinterpret_cast(handler); state->apply_mcswap({ctrl_qubit, qubit0, qubit1}); }; // four parameter controlled-U gate with relative phase γ -void aer_apply_cu(void* handler, uint_t ctrl_qubit, uint_t tgt_qubit, double theta, double phi, double lambda, double gamma) { - AER::AerState* state = reinterpret_cast(handler); +void aer_apply_cu(void *handler, uint_t ctrl_qubit, uint_t tgt_qubit, + double theta, double phi, double lambda, double gamma) { + AER::AerState *state = reinterpret_cast(handler); state->apply_mcphase({ctrl_qubit}, gamma); state->apply_mcu({ctrl_qubit, tgt_qubit}, theta, phi, lambda); }; diff --git a/contrib/runtime/aer_runtime_api.h b/contrib/runtime/aer_runtime_api.h index 2e27a6fcc0..d08a51c8fd 100644 --- a/contrib/runtime/aer_runtime_api.h +++ b/contrib/runtime/aer_runtime_api.h @@ -14,93 +14,99 @@ #include #include -typedef uint_fast64_t uint_t; +typedef uint_fast64_t uint_t; // construct an aer state -void* aer_state(); +void *aer_state(); // initialize aer state -void* aer_state_initialize(); +void *aer_state_initialize(); // finalize state -void aer_state_finalize(void* state); +void aer_state_finalize(void *state); // configure state -void aer_state_configure(void* state, char* key, char* value); +void aer_state_configure(void *state, char *key, char *value); // allocate qubits and return the first qubit index. // following qubits are indexed with incremented indices. -uint_t aer_allocate_qubits(void* state, uint_t num_qubits); +uint_t aer_allocate_qubits(void *state, uint_t num_qubits); // measure qubits -uint_t aer_apply_measure(void* state, uint_t* qubits, size_t num_qubits); +uint_t aer_apply_measure(void *state, uint_t *qubits, size_t num_qubits); // return probability of a specific bitstring -double aer_probability(void* state, uint_t outcome); +double aer_probability(void *state, uint_t outcome); // return probability amplitude of a specific bitstring -double complex aer_amplitude(void* state, uint_t outcome); +double complex aer_amplitude(void *state, uint_t outcome); // return probability amplitudes // returned pointer must be freed in the caller -double complex* aer_release_statevector(void* state); +double complex *aer_release_statevector(void *state); // phase gate -void aer_apply_p(void* state, uint_t qubit, double lambda); +void aer_apply_p(void *state, uint_t qubit, double lambda); // Pauli gate: bit-flip or NOT gate -void aer_apply_x(void* state, uint_t qubit); +void aer_apply_x(void *state, uint_t qubit); // Pauli gate: bit and phase flip -void aer_apply_y(void* state, uint_t qubit); +void aer_apply_y(void *state, uint_t qubit); // Pauli gate: phase flip -void aer_apply_z(void* state, uint_t qubit); +void aer_apply_z(void *state, uint_t qubit); // Clifford gate: Hadamard -void aer_apply_h(void* state, uint_t qubit); +void aer_apply_h(void *state, uint_t qubit); // Clifford gate: sqrt(Z) or S gate -void aer_apply_s(void* state, uint_t qubit); +void aer_apply_s(void *state, uint_t qubit); // Clifford gate: inverse of sqrt(Z) -void aer_apply_sdg(void* state, uint_t qubit); +void aer_apply_sdg(void *state, uint_t qubit); // sqrt(S) or T gate -void aer_apply_t(void* state, uint_t qubit); +void aer_apply_t(void *state, uint_t qubit); // inverse of sqrt(S) -void aer_apply_tdg(void* state, uint_t qubit); +void aer_apply_tdg(void *state, uint_t qubit); // sqrt(NOT) gate -void aer_apply_sx(void* state, uint_t qubit); +void aer_apply_sx(void *state, uint_t qubit); // Rotation around X-axis -void aer_apply_rx(void* state, uint_t qubit, double theta); +void aer_apply_rx(void *state, uint_t qubit, double theta); // rotation around Y-axis -void aer_apply_ry(void* state, uint_t qubit, double theta); +void aer_apply_ry(void *state, uint_t qubit, double theta); // rotation around Z axis -void aer_apply_rz(void* state, uint_t qubit, double theta); +void aer_apply_rz(void *state, uint_t qubit, double theta); // controlled-NOT -void aer_apply_cx(void* state, uint_t ctrl_qubit, uint_t tgt_qubit); +void aer_apply_cx(void *state, uint_t ctrl_qubit, uint_t tgt_qubit); // controlled-Y -void aer_apply_cy(void* state, uint_t ctrl_qubit, uint_t tgt_qubit); +void aer_apply_cy(void *state, uint_t ctrl_qubit, uint_t tgt_qubit); // controlled-Z -void aer_apply_cz(void* state, uint_t ctrl_qubit, uint_t tgt_qubit); +void aer_apply_cz(void *state, uint_t ctrl_qubit, uint_t tgt_qubit); // controlled-phase -void aer_apply_cp(void* state, uint_t ctrl_qubit, uint_t tgt_qubit, double lambda); +void aer_apply_cp(void *state, uint_t ctrl_qubit, uint_t tgt_qubit, + double lambda); // controlled-rx -void aer_apply_crx(void* state, uint_t ctrl_qubit, uint_t tgt_qubit, double theta); +void aer_apply_crx(void *state, uint_t ctrl_qubit, uint_t tgt_qubit, + double theta); // controlled-ry -void aer_apply_cry(void* state, uint_t ctrl_qubit, uint_t tgt_qubit, double theta); +void aer_apply_cry(void *state, uint_t ctrl_qubit, uint_t tgt_qubit, + double theta); // controlled-rz -void aer_apply_crz(void* state, uint_t ctrl_qubit, uint_t tgt_qubit, double theta); +void aer_apply_crz(void *state, uint_t ctrl_qubit, uint_t tgt_qubit, + double theta); // controlled-H -void aer_apply_ch(void* state, uint_t ctrl_qubit, uint_t tgt_qubit); +void aer_apply_ch(void *state, uint_t ctrl_qubit, uint_t tgt_qubit); // swap -void aer_apply_swap(void* state, uint_t qubit0, uint_t qubit1); +void aer_apply_swap(void *state, uint_t qubit0, uint_t qubit1); // Toffoli -void aer_apply_ccx(void* state, uint_t qubit0, uint_t qubit1, uint_t qubit2); +void aer_apply_ccx(void *state, uint_t qubit0, uint_t qubit1, uint_t qubit2); // controlled-swap -void aer_apply_cswap(void* state, uint_t ctrl_qubit, uint_t qubit0, uint_t qubit1); +void aer_apply_cswap(void *state, uint_t ctrl_qubit, uint_t qubit0, + uint_t qubit1); // four parameter controlled-U gate with relative phase γ -void aer_apply_cu(void* state, uint_t ctrl_qubit, uint_t tgt_qubit, double theta, double phi, double lambda, double gamma); \ No newline at end of file +void aer_apply_cu(void *state, uint_t ctrl_qubit, uint_t tgt_qubit, + double theta, double phi, double lambda, double gamma); \ No newline at end of file diff --git a/contrib/standalone/qasm_simulator.cpp b/contrib/standalone/qasm_simulator.cpp old mode 100755 new mode 100644 index d0b8fa9c0a..fac82cb863 --- a/contrib/standalone/qasm_simulator.cpp +++ b/contrib/standalone/qasm_simulator.cpp @@ -27,32 +27,28 @@ /******************************************************************************* * * EXIT CODES: - * + * * 0: The Qobj was succesfully executed. * Returns full result JSON. - * + * * 1: Command line invalid or Qobj JSON cannot be loaded. * Returns JSON: * {"success": false, "status": "ERROR: Invalid input (error msg)"} - * + * * 2: Qobj failed to load or execute. * Returns JSON: * {"success": false, "status": "ERROR: Failed to execute qobj (error msg)"} - * + * * 3: At least one experiment in Qobj failed to execute successfully. * Returns parial result JSON with failed experiments returning: * "{"success": false, "status": "ERROR: error msg"} * ******************************************************************************/ -enum class CmdArguments { - SHOW_VERSION, - INPUT_CONFIG, - INPUT_DATA -}; +enum class CmdArguments { SHOW_VERSION, INPUT_CONFIG, INPUT_DATA }; -inline CmdArguments parse_cmd_options(const std::string& argv){ - if(argv == "-v" || argv == "--version") +inline CmdArguments parse_cmd_options(const std::string &argv) { + if (argv == "-v" || argv == "--version") return CmdArguments::SHOW_VERSION; if (argv == "-c" || argv == "--config") @@ -61,22 +57,20 @@ inline CmdArguments parse_cmd_options(const std::string& argv){ return CmdArguments::INPUT_DATA; } -inline void show_version(){ - std::cout << "Qiskit Aer: " - << AER_MAJOR_VERSION << "." - << AER_MINOR_VERSION << "." - << AER_PATCH_VERSION << "\n"; +inline void show_version() { + std::cout << "Qiskit Aer: " << AER_MAJOR_VERSION << "." << AER_MINOR_VERSION + << "." << AER_PATCH_VERSION << "\n"; } inline void failed(const std::string &msg, std::ostream &o = std::cout, - int indent = -1){ + int indent = -1) { json_t ret; ret["success"] = false; ret["status"] = std::string("ERROR: ") + msg; o << ret.dump(indent) << std::endl; } -inline void usage(const std::string& command, std::ostream &out){ +inline void usage(const std::string &command, std::ostream &out) { failed("Invalid command line", out); // Print usage message std::cerr << "\n\n"; @@ -85,7 +79,8 @@ inline void usage(const std::string& command, std::ostream &out){ std::cerr << "Usage: \n"; std::cerr << command << " [-v] [-c ] \n"; std::cerr << " -v : Show version\n"; - std::cerr << " -c : Configuration file\n";; + std::cerr << " -c : Configuration file\n"; + ; std::cerr << " file : qobj file\n"; } @@ -95,51 +90,51 @@ int main(int argc, char **argv) { int indent = 4; json_t qobj; json_t config; - int myrank=0; + int myrank = 0; #ifdef AER_MPI int prov; - int nprocs=1; - MPI_Init_thread(&argc,&argv,MPI_THREAD_MULTIPLE,&prov); - MPI_Comm_size(MPI_COMM_WORLD,&nprocs); - MPI_Comm_rank(MPI_COMM_WORLD,&myrank); + int nprocs = 1; + MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &prov); + MPI_Comm_size(MPI_COMM_WORLD, &nprocs); + MPI_Comm_rank(MPI_COMM_WORLD, &myrank); #endif - if(argc == 1){ // NOLINT + if (argc == 1) { // NOLINT usage(std::string(argv[0]), out); // NOLINT return 1; } // Parse command line options - for(auto pos = 1UL; pos < static_cast(argc); ++pos){ // NOLINT - auto option = parse_cmd_options(std::string(argv[pos])); // NOLINT - switch(option){ - case CmdArguments::SHOW_VERSION: - show_version(); - return 0; - case CmdArguments::INPUT_CONFIG: - if (++pos == static_cast(argc)) { - failed("Invalid config (no file is specified.)", out, indent); - return 1; - } - try { - config = JSON::load(std::string(argv[pos])); - }catch(std::exception &e){ - std::string msg = "Invalid config (" + std::string(e.what()) + ")"; - failed(msg, out, indent); - return 1; - } - break; - case CmdArguments::INPUT_DATA: - try { - qobj = JSON::load(std::string(argv[pos])); // NOLINT - pos = argc; //Exit from the loop - }catch(std::exception &e){ - std::string msg = "Invalid input (" + std::string(e.what()) + ")"; - failed(msg, out, indent); - return 1; - } - break; + for (auto pos = 1UL; pos < static_cast(argc); ++pos) { // NOLINT + auto option = parse_cmd_options(std::string(argv[pos])); // NOLINT + switch (option) { + case CmdArguments::SHOW_VERSION: + show_version(); + return 0; + case CmdArguments::INPUT_CONFIG: + if (++pos == static_cast(argc)) { + failed("Invalid config (no file is specified.)", out, indent); + return 1; + } + try { + config = JSON::load(std::string(argv[pos])); + } catch (std::exception &e) { + std::string msg = "Invalid config (" + std::string(e.what()) + ")"; + failed(msg, out, indent); + return 1; + } + break; + case CmdArguments::INPUT_DATA: + try { + qobj = JSON::load(std::string(argv[pos])); // NOLINT + pos = argc; // Exit from the loop + } catch (std::exception &e) { + std::string msg = "Invalid input (" + std::string(e.what()) + ")"; + failed(msg, out, indent); + return 1; + } + break; } } @@ -148,7 +143,7 @@ int main(int argc, char **argv) { // Check for command line config // and if present add to qobj config - json_t& config_all = qobj["config"]; + json_t &config_all = qobj["config"]; if (!config.empty()) // NOLINT config_all.update(config.begin(), config.end()); @@ -166,7 +161,7 @@ int main(int argc, char **argv) { // Initialize simulator AER::Controller sim; auto result = sim.execute(qobj).to_json(); - if(myrank == 0){ + if (myrank == 0) { out << result.dump(4) << std::endl; } @@ -179,9 +174,9 @@ int main(int argc, char **argv) { #ifdef AER_MPI MPI_Finalize(); #endif - if(status == "COMPLETED") + if (status == "COMPLETED") return 3; // The simulation was was completed unsuccesfully. - return 2; // Failed to execute the Qobj + return 2; // Failed to execute the Qobj } } catch (std::exception &e) { std::stringstream msg; diff --git a/qiskit_aer/backends/wrappers/bindings.cc b/qiskit_aer/backends/wrappers/bindings.cc index 448868873a..1d2dfa8f30 100644 --- a/qiskit_aer/backends/wrappers/bindings.cc +++ b/qiskit_aer/backends/wrappers/bindings.cc @@ -9,146 +9,148 @@ DISABLE_WARNING_PUSH #include DISABLE_WARNING_POP #if defined(_MSC_VER) - #undef snprintf +#undef snprintf #endif #include "framework/matrix.hpp" -#include "framework/python_parser.hpp" #include "framework/pybind_casts.hpp" -#include "framework/types.hpp" +#include "framework/python_parser.hpp" #include "framework/results/pybind_result.hpp" +#include "framework/types.hpp" #include "controllers/aer_controller.hpp" #include "controllers/controller_execute.hpp" #include "controllers/state_controller.hpp" -template -class ControllerExecutor { +template class ControllerExecutor { public: - ControllerExecutor() = default; - py::object operator()(const py::handle &qobj) { + ControllerExecutor() = default; + py::object operator()(const py::handle &qobj) { #ifdef TEST_JSON // Convert input qobj to json to test standalone data reading - return AerToPy::to_python(AER::controller_execute(json_t(qobj))); + return AerToPy::to_python(AER::controller_execute(json_t(qobj))); #else - return AerToPy::to_python(AER::controller_execute(qobj)); + return AerToPy::to_python(AER::controller_execute(qobj)); #endif - } + } }; PYBIND11_MODULE(controller_wrappers, m) { #ifdef AER_MPI int prov; - MPI_Init_thread(nullptr,nullptr,MPI_THREAD_MULTIPLE,&prov); + MPI_Init_thread(nullptr, nullptr, MPI_THREAD_MULTIPLE, &prov); #endif - py::class_ > aer_ctrl (m, "aer_controller_execute"); - aer_ctrl.def(py::init<>()); - aer_ctrl.def("__call__", &ControllerExecutor::operator()); - aer_ctrl.def("__reduce__", [aer_ctrl](const ControllerExecutor &self) { - return py::make_tuple(aer_ctrl, py::tuple()); - }); - - py::class_ aer_state(m, "AerStateWrapper"); - - aer_state.def(py::init<>(), "constructor"); - - aer_state.def("__repr__", [](const AER::AerState &state) { - std::stringstream ss; - ss << "AerStateWrapper(" - << "initialized=" << state.is_initialized() - << ", num_of_qubits=" << state.num_of_qubits(); - ss << ")"; - return ss.str(); - }); - - aer_state.def("configure", &AER::AerState::configure); - aer_state.def("allocate_qubits", &AER::AerState::allocate_qubits); - aer_state.def("reallocate_qubits", &AER::AerState::reallocate_qubits); - aer_state.def("clear", &AER::AerState::clear); - aer_state.def("num_of_qubits", &AER::AerState::num_of_qubits); - - aer_state.def("initialize", &AER::AerState::initialize); - aer_state.def("initialize_statevector", [aer_state](AER::AerState &state, - int num_of_qubits, - py::array_t> &values, - bool copy) { - std::complex* data_ptr = reinterpret_cast*>(values.mutable_data(0)); - state.configure("method", "statevector"); - state.initialize_statevector(num_of_qubits, data_ptr, copy); - return true; - }); - - aer_state.def("move_to_buffer", [aer_state](AER::AerState &state) { - return state.move_to_vector().move_to_buffer(); - }); - - aer_state.def("move_to_ndarray", [aer_state](AER::AerState &state) { - auto vec = state.move_to_vector(); - - std::complex* data_ptr = vec.data(); - auto ret = AerToPy::to_numpy(std::move(vec)); - return ret; - }); - - aer_state.def("flush", &AER::AerState::flush_ops); - - aer_state.def("last_result", [aer_state](AER::AerState &state) { - return AerToPy::to_python(state.last_result().to_json()); - }); - - - aer_state.def("apply_initialize", &AER::AerState::apply_initialize); - aer_state.def("apply_global_phase", &AER::AerState::apply_global_phase); - aer_state.def("apply_unitary", [aer_state](AER::AerState &state, - const reg_t &qubits, - const py::array_t> &values) { - size_t mat_len = (1UL << qubits.size()); - auto ptr = values.unchecked<2>(); - AER::cmatrix_t mat(mat_len, mat_len); - for (auto i = 0; i < mat_len; ++i) - for (auto j = 0; j < mat_len; ++j) - mat(i, j) = ptr(i, j); - state.apply_unitary(qubits, mat); - }); - - aer_state.def("apply_multiplexer", [aer_state](AER::AerState &state, - const reg_t &control_qubits, - const reg_t &target_qubits, - const py::array_t> &values) { - size_t mat_len = (1UL << target_qubits.size()); - size_t mat_size = (1UL << control_qubits.size()); - auto ptr = values.unchecked<3>(); - std::vector mats; - for (auto i = 0; i < mat_size; ++i) { - AER::cmatrix_t mat(mat_len, mat_len); - for (auto j = 0; j < mat_len; ++j) - for (auto k = 0; k < mat_len; ++k) - mat(j, k) = ptr(i, j, k); - mats.push_back(mat); - } - state.apply_multiplexer(control_qubits, target_qubits, mats); - }); - - aer_state.def("apply_diagonal", &AER::AerState::apply_diagonal_matrix); - aer_state.def("apply_mcx", &AER::AerState::apply_mcx); - aer_state.def("apply_mcy", &AER::AerState::apply_mcy); - aer_state.def("apply_mcz", &AER::AerState::apply_mcz); - aer_state.def("apply_mcphase", &AER::AerState::apply_mcphase); - aer_state.def("apply_mcu", &AER::AerState::apply_mcu); - aer_state.def("apply_mcswap", &AER::AerState::apply_mcswap); - aer_state.def("apply_measure", &AER::AerState::apply_measure); - aer_state.def("apply_reset", &AER::AerState::apply_reset); - aer_state.def("probability", &AER::AerState::probability); - aer_state.def("probabilities", [aer_state](AER::AerState &state, - const reg_t qubits) { - if (qubits.empty()) - return state.probabilities(); - else - return state.probabilities(qubits); - }, py::arg("qubits") = reg_t()); - aer_state.def("sample_memory", &AER::AerState::sample_memory); - aer_state.def("sample_counts", &AER::AerState::sample_counts); - + py::class_> aer_ctrl( + m, "aer_controller_execute"); + aer_ctrl.def(py::init<>()); + aer_ctrl.def("__call__", &ControllerExecutor::operator()); + aer_ctrl.def("__reduce__", + [aer_ctrl](const ControllerExecutor &self) { + return py::make_tuple(aer_ctrl, py::tuple()); + }); + + py::class_ aer_state(m, "AerStateWrapper"); + + aer_state.def(py::init<>(), "constructor"); + + aer_state.def("__repr__", [](const AER::AerState &state) { + std::stringstream ss; + ss << "AerStateWrapper(" + << "initialized=" << state.is_initialized() + << ", num_of_qubits=" << state.num_of_qubits(); + ss << ")"; + return ss.str(); + }); + + aer_state.def("configure", &AER::AerState::configure); + aer_state.def("allocate_qubits", &AER::AerState::allocate_qubits); + aer_state.def("reallocate_qubits", &AER::AerState::reallocate_qubits); + aer_state.def("clear", &AER::AerState::clear); + aer_state.def("num_of_qubits", &AER::AerState::num_of_qubits); + + aer_state.def("initialize", &AER::AerState::initialize); + aer_state.def( + "initialize_statevector", + [aer_state](AER::AerState &state, int num_of_qubits, + py::array_t> &values, bool copy) { + std::complex *data_ptr = + reinterpret_cast *>(values.mutable_data(0)); + state.configure("method", "statevector"); + state.initialize_statevector(num_of_qubits, data_ptr, copy); + return true; + }); + + aer_state.def("move_to_buffer", [aer_state](AER::AerState &state) { + return state.move_to_vector().move_to_buffer(); + }); + + aer_state.def("move_to_ndarray", [aer_state](AER::AerState &state) { + auto vec = state.move_to_vector(); + + std::complex *data_ptr = vec.data(); + auto ret = AerToPy::to_numpy(std::move(vec)); + return ret; + }); + + aer_state.def("flush", &AER::AerState::flush_ops); + + aer_state.def("last_result", [aer_state](AER::AerState &state) { + return AerToPy::to_python(state.last_result().to_json()); + }); + + aer_state.def("apply_initialize", &AER::AerState::apply_initialize); + aer_state.def("apply_global_phase", &AER::AerState::apply_global_phase); + aer_state.def("apply_unitary", + [aer_state](AER::AerState &state, const reg_t &qubits, + const py::array_t> &values) { + size_t mat_len = (1UL << qubits.size()); + auto ptr = values.unchecked<2>(); + AER::cmatrix_t mat(mat_len, mat_len); + for (auto i = 0; i < mat_len; ++i) + for (auto j = 0; j < mat_len; ++j) + mat(i, j) = ptr(i, j); + state.apply_unitary(qubits, mat); + }); + + aer_state.def("apply_multiplexer", + [aer_state](AER::AerState &state, const reg_t &control_qubits, + const reg_t &target_qubits, + const py::array_t> &values) { + size_t mat_len = (1UL << target_qubits.size()); + size_t mat_size = (1UL << control_qubits.size()); + auto ptr = values.unchecked<3>(); + std::vector mats; + for (auto i = 0; i < mat_size; ++i) { + AER::cmatrix_t mat(mat_len, mat_len); + for (auto j = 0; j < mat_len; ++j) + for (auto k = 0; k < mat_len; ++k) + mat(j, k) = ptr(i, j, k); + mats.push_back(mat); + } + state.apply_multiplexer(control_qubits, target_qubits, mats); + }); + + aer_state.def("apply_diagonal", &AER::AerState::apply_diagonal_matrix); + aer_state.def("apply_mcx", &AER::AerState::apply_mcx); + aer_state.def("apply_mcy", &AER::AerState::apply_mcy); + aer_state.def("apply_mcz", &AER::AerState::apply_mcz); + aer_state.def("apply_mcphase", &AER::AerState::apply_mcphase); + aer_state.def("apply_mcu", &AER::AerState::apply_mcu); + aer_state.def("apply_mcswap", &AER::AerState::apply_mcswap); + aer_state.def("apply_measure", &AER::AerState::apply_measure); + aer_state.def("apply_reset", &AER::AerState::apply_reset); + aer_state.def("probability", &AER::AerState::probability); + aer_state.def( + "probabilities", + [aer_state](AER::AerState &state, const reg_t qubits) { + if (qubits.empty()) + return state.probabilities(); + else + return state.probabilities(qubits); + }, + py::arg("qubits") = reg_t()); + aer_state.def("sample_memory", &AER::AerState::sample_memory); + aer_state.def("sample_counts", &AER::AerState::sample_counts); } diff --git a/src/controllers/aer_controller.hpp b/src/controllers/aer_controller.hpp old mode 100755 new mode 100644 index b1a9880f23..722af89dc4 --- a/src/controllers/aer_controller.hpp +++ b/src/controllers/aer_controller.hpp @@ -80,11 +80,9 @@ class Controller { // Load a QOBJ from a JSON file and execute on the State type // class. - template - Result execute(const inputdata_t &qobj); + template Result execute(const inputdata_t &qobj); - Result execute(std::vector &circuits, - Noise::NoiseModel &noise_model, + Result execute(std::vector &circuits, Noise::NoiseModel &noise_model, const json_t &config); //----------------------------------------------------------------------- @@ -121,15 +119,14 @@ class Controller { enum class Precision { Double, Single }; const std::unordered_map method_names_ = { - {Method::automatic, "automatic"}, - {Method::statevector, "statevector"}, - {Method::density_matrix, "density_matrix"}, - {Method::matrix_product_state, "matrix_product_state"}, - {Method::stabilizer, "stabilizer"}, - {Method::extended_stabilizer, "extended_stabilizer"}, - {Method::unitary, "unitary"}, - {Method::superop, "superop"} - }; + {Method::automatic, "automatic"}, + {Method::statevector, "statevector"}, + {Method::density_matrix, "density_matrix"}, + {Method::matrix_product_state, "matrix_product_state"}, + {Method::stabilizer, "stabilizer"}, + {Method::extended_stabilizer, "extended_stabilizer"}, + {Method::unitary, "unitary"}, + {Method::superop, "superop"}}; //----------------------------------------------------------------------- // Config @@ -165,7 +162,8 @@ class Controller { // This method must initialize a state and return output data for // the required number of shots. void run_circuit(const Circuit &circ, const Noise::NoiseModel &noise, - const Method method,const json_t &config, ExperimentResult &result) const; + const Method method, const json_t &config, + ExperimentResult &result) const; //---------------------------------------------------------------- // Run circuit helpers @@ -174,7 +172,7 @@ class Controller { // Execute n-shots of a circuit on the input state template void run_circuit_helper(const Circuit &circ, const Noise::NoiseModel &noise, - const json_t &config, const Method method, + const json_t &config, const Method method, ExperimentResult &result) const; // Execute a single shot a of circuit by initializing the state vector, @@ -188,12 +186,9 @@ class Controller { // running all ops in circ, and updating data with // simulation output. template - void run_with_sampling(const Circuit &circ, - State_t &state, - ExperimentResult &result, - RngEngine &rng, - const uint_t block_bits, - const uint_t shots) const; + void run_with_sampling(const Circuit &circ, State_t &state, + ExperimentResult &result, RngEngine &rng, + const uint_t block_bits, const uint_t shots) const; // Execute multiple shots a of circuit by initializing the state vector, // running all ops in circ, and updating data with @@ -208,8 +203,7 @@ class Controller { template void run_circuit_with_sampled_noise(const Circuit &circ, const Noise::NoiseModel &noise, - const json_t &config, - const Method method, + const json_t &config, const Method method, ExperimentResult &result) const; //---------------------------------------------------------------- @@ -221,7 +215,7 @@ class Controller { template void measure_sampler(InputIterator first_meas, InputIterator last_meas, uint_t shots, State_t &state, ExperimentResult &result, - RngEngine &rng , int_t shot_index = -1) const; + RngEngine &rng, int_t shot_index = -1) const; // Check if measure sampling optimization is valid for the input circuit // for the given method. This checks if operation types before @@ -239,11 +233,10 @@ class Controller { // If `throw_except` is true an exception will be thrown on the return false // case listing the invalid instructions in the circuit or noise model, or // the required memory. - bool validate_method(Method method, - const Circuit &circ, + bool validate_method(Method method, const Circuit &circ, const Noise::NoiseModel &noise, bool throw_except = false) const; - + template bool validate_state(const state_t &state, const Circuit &circ, const Noise::NoiseModel &noise, @@ -257,7 +250,7 @@ class Controller { //---------------------------------------------------------------- // Utility functions //---------------------------------------------------------------- - + // Return a vector of simulation methods for each circuit. // If the default method is automatic this will be computed based on the // circuit and noise model. @@ -281,14 +274,13 @@ class Controller { // Return cache blocking transpiler pass Transpile::CacheBlocking - transpile_cache_blocking(Controller::Method method, - const Circuit &circ, + transpile_cache_blocking(Controller::Method method, const Circuit &circ, const Noise::NoiseModel &noise, const json_t &config) const; - //return maximum number of qubits for matrix + // return maximum number of qubits for matrix int_t get_max_matrix_qubits(const Circuit &circ) const; - int_t get_matrix_bits(const Operations::Op& op) const; + int_t get_matrix_bits(const Operations::Op &op) const; //----------------------------------------------------------------------- // Parallelization Config @@ -298,10 +290,9 @@ class Controller { void clear_parallelization(); // Set parallelization for experiments - void - set_parallelization_experiments(const std::vector &circuits, - const Noise::NoiseModel &noise, - const std::vector &methods); + void set_parallelization_experiments(const std::vector &circuits, + const Noise::NoiseModel &noise, + const std::vector &methods); // Set circuit parallelization void set_parallelization_circuit(const Circuit &circ, @@ -349,7 +340,8 @@ class Controller { bool parallel_nested_ = false; - //max number of states can be stored on memory for batched multi-shots/experiments optimization + // max number of states can be stored on memory for batched + // multi-shots/experiments optimization int max_batched_states_; // max number of qubits in given circuits @@ -365,15 +357,18 @@ class Controller { uint_t cache_block_qubit_ = 0; - //multi-chunks are required to simulate circuits + // multi-chunks are required to simulate circuits bool multi_chunk_required_ = false; - //config setting for multi-shot parallelization + // config setting for multi-shot parallelization bool batched_shots_gpu_ = true; - int_t batched_shots_gpu_max_qubits_ = 16; //multi-shot parallelization is applied if qubits is less than max qubits - bool enable_batch_multi_shots_ = false; //multi-shot parallelization can be applied + int_t batched_shots_gpu_max_qubits_ = + 16; // multi-shot parallelization is applied if qubits is less than max + // qubits + bool enable_batch_multi_shots_ = + false; // multi-shot parallelization can be applied - //settings for cuStateVec + // settings for cuStateVec bool cuStateVec_enable_ = false; }; @@ -456,17 +451,18 @@ void Controller::set_config(const json_t &config) { JSON::get_value(cache_block_qubit_, "blocking_qubits", config); } - //enable batched multi-shots/experiments optimization - if(JSON::check_key("batched_shots_gpu", config)) { + // enable batched multi-shots/experiments optimization + if (JSON::check_key("batched_shots_gpu", config)) { JSON::get_value(batched_shots_gpu_, "batched_shots_gpu", config); } - if(JSON::check_key("batched_shots_gpu_max_qubits", config)) { - JSON::get_value(batched_shots_gpu_max_qubits_, "batched_shots_gpu_max_qubits", config); + if (JSON::check_key("batched_shots_gpu_max_qubits", config)) { + JSON::get_value(batched_shots_gpu_max_qubits_, + "batched_shots_gpu_max_qubits", config); } - //cuStateVec configs + // cuStateVec configs cuStateVec_enable_ = false; - if(JSON::check_key("cuStateVec_enable", config)) { + if (JSON::check_key("cuStateVec_enable", config)) { JSON::get_value(cuStateVec_enable_, "cuStateVec_enable", config); } @@ -493,7 +489,7 @@ void Controller::set_config(const json_t &config) { } } - if(method_ == Method::density_matrix || method_ == Method::unitary) + if (method_ == Method::density_matrix || method_ == Method::unitary) batched_shots_gpu_max_qubits_ /= 2; // Override automatic simulation method with a fixed method @@ -514,21 +510,20 @@ void Controller::set_config(const json_t &config) { #else #ifndef AER_CUSTATEVEC - if(cuStateVec_enable_){ - //Aer is not built for cuStateVec - throw std::runtime_error( - "Simulation device \"GPU\" does not support cuStateVec on this system"); + if (cuStateVec_enable_) { + // Aer is not built for cuStateVec + throw std::runtime_error("Simulation device \"GPU\" does not support " + "cuStateVec on this system"); } #endif int nDev; if (cudaGetDeviceCount(&nDev) != cudaSuccess) { - cudaGetLastError(); - throw std::runtime_error("No CUDA device available!"); + cudaGetLastError(); + throw std::runtime_error("No CUDA device available!"); } sim_device_ = Device::GPU; #endif - } - else { + } else { throw std::runtime_error(std::string("Invalid simulation device (\"") + sim_device_name_ + std::string("\").")); } @@ -576,40 +571,41 @@ void Controller::clear_parallelization() { } void Controller::set_parallelization_experiments( - const std::vector &circuits, - const Noise::NoiseModel &noise, - const std::vector &methods) -{ + const std::vector &circuits, const Noise::NoiseModel &noise, + const std::vector &methods) { std::vector required_memory_mb_list(circuits.size()); max_qubits_ = 0; for (size_t j = 0; j < circuits.size(); j++) { - if(circuits[j].num_qubits > max_qubits_) + if (circuits[j].num_qubits > max_qubits_) max_qubits_ = circuits[j].num_qubits; - required_memory_mb_list[j] = required_memory_mb(circuits[j], noise, methods[j]); + required_memory_mb_list[j] = + required_memory_mb(circuits[j], noise, methods[j]); } std::sort(required_memory_mb_list.begin(), required_memory_mb_list.end(), std::greater<>()); - //set max batchable number of circuits - if(batched_shots_gpu_){ - if(required_memory_mb_list[0] == 0 || max_qubits_ == 0) + // set max batchable number of circuits + if (batched_shots_gpu_) { + if (required_memory_mb_list[0] == 0 || max_qubits_ == 0) max_batched_states_ = 1; - else{ - if(sim_device_ == Device::GPU){ - max_batched_states_ = ((max_gpu_memory_mb_/num_gpus_*8/10) / required_memory_mb_list[0])*num_gpus_; - } - else{ - max_batched_states_ = (max_memory_mb_*8/10) / required_memory_mb_list[0]; + else { + if (sim_device_ == Device::GPU) { + max_batched_states_ = ((max_gpu_memory_mb_ / num_gpus_ * 8 / 10) / + required_memory_mb_list[0]) * + num_gpus_; + } else { + max_batched_states_ = + (max_memory_mb_ * 8 / 10) / required_memory_mb_list[0]; } } } - if(max_qubits_ == 0) + if (max_qubits_ == 0) max_qubits_ = 1; - if(explicit_parallelization_ ) + if (explicit_parallelization_) return; - if(circuits.size() == 1){ + if (circuits.size() == 1) { parallel_experiments_ = 1; return; } @@ -647,54 +643,55 @@ void Controller::set_parallelization_experiments( void Controller::set_parallelization_circuit(const Circuit &circ, const Noise::NoiseModel &noise, - const Method method) -{ + const Method method) { enable_batch_multi_shots_ = false; - if(batched_shots_gpu_ && sim_device_ == Device::GPU && - circ.shots > 1 && max_batched_states_ >= num_gpus_ && - batched_shots_gpu_max_qubits_ >= circ.num_qubits ){ - enable_batch_multi_shots_ = true; + if (batched_shots_gpu_ && sim_device_ == Device::GPU && circ.shots > 1 && + max_batched_states_ >= num_gpus_ && + batched_shots_gpu_max_qubits_ >= circ.num_qubits) { + enable_batch_multi_shots_ = true; } - if(sim_device_ == Device::GPU && cuStateVec_enable_){ - enable_batch_multi_shots_ = false; //cuStateVec does not support batch execution of multi-shots + if (sim_device_ == Device::GPU && cuStateVec_enable_) { + enable_batch_multi_shots_ = + false; // cuStateVec does not support batch execution of multi-shots return; } - if(explicit_parallelization_) + if (explicit_parallelization_) return; // Check for trivial parallelization conditions switch (method) { - case Method::statevector: - case Method::stabilizer: - case Method::unitary: - case Method::matrix_product_state: { - if (circ.shots == 1 || num_process_per_experiment_ > 1 || - (!noise.has_quantum_errors() && - check_measure_sampling_opt(circ, method))) { - parallel_shots_ = 1; - parallel_state_update_ = - std::max({1, max_parallel_threads_ / parallel_experiments_}); - return; - } - break; + case Method::statevector: + case Method::stabilizer: + case Method::unitary: + case Method::matrix_product_state: { + if (circ.shots == 1 || num_process_per_experiment_ > 1 || + (!noise.has_quantum_errors() && + check_measure_sampling_opt(circ, method))) { + parallel_shots_ = 1; + parallel_state_update_ = + std::max({1, max_parallel_threads_ / parallel_experiments_}); + return; } - case Method::density_matrix: - case Method::superop: { - if (circ.shots == 1 || num_process_per_experiment_ > 1 || - check_measure_sampling_opt(circ, method)) { - parallel_shots_ = 1; - parallel_state_update_ = - std::max({1, max_parallel_threads_ / parallel_experiments_}); - return; - } - break; + break; + } + case Method::density_matrix: + case Method::superop: { + if (circ.shots == 1 || num_process_per_experiment_ > 1 || + check_measure_sampling_opt(circ, method)) { + parallel_shots_ = 1; + parallel_state_update_ = + std::max({1, max_parallel_threads_ / parallel_experiments_}); + return; } - case Method::extended_stabilizer: - break; - default: - throw std::invalid_argument("Cannot set parallelization for unresolved method."); + break; + } + case Method::extended_stabilizer: + break; + default: + throw std::invalid_argument( + "Cannot set parallelization for unresolved method."); } // Use a local variable to not override stored maximum based @@ -714,7 +711,8 @@ void Controller::set_parallelization_circuit(const Circuit &circ, // And assign the remaining threads to state update int circ_memory_mb = required_memory_mb(circ, noise, method) / num_process_per_experiment_; - size_t mem_size = (sim_device_ == Device::GPU) ? max_gpu_memory_mb_ : max_memory_mb_; + size_t mem_size = + (sim_device_ == Device::GPU) ? max_gpu_memory_mb_ : max_memory_mb_; if (mem_size < circ_memory_mb) throw std::runtime_error( "a circuit requires more memory than max_memory_mb."); @@ -723,7 +721,7 @@ void Controller::set_parallelization_circuit(const Circuit &circ, int shots = circ.shots; parallel_shots_ = std::min( - {static_cast(mem_size/(circ_memory_mb*2)), max_shots, shots}); + {static_cast(mem_size / (circ_memory_mb * 2)), max_shots, shots}); } parallel_state_update_ = (parallel_shots_ > 1) @@ -733,21 +731,23 @@ void Controller::set_parallelization_circuit(const Circuit &circ, bool Controller::multiple_chunk_required(const Circuit &circ, const Noise::NoiseModel &noise, - const Method method) const -{ + const Method method) const { if (circ.num_qubits < 3) return false; if (cache_block_qubit_ >= 2 && cache_block_qubit_ < circ.num_qubits) return true; - if(num_process_per_experiment_ == 1 && sim_device_ == Device::GPU && num_gpus_ > 0){ - return (max_gpu_memory_mb_ / num_gpus_ < required_memory_mb(circ, noise, method)); + if (num_process_per_experiment_ == 1 && sim_device_ == Device::GPU && + num_gpus_ > 0) { + return (max_gpu_memory_mb_ / num_gpus_ < + required_memory_mb(circ, noise, method)); } - if(num_process_per_experiment_ > 1){ + if (num_process_per_experiment_ > 1) { size_t total_mem = max_memory_mb_; - if(sim_device_ == Device::GPU) + if (sim_device_ == Device::GPU) total_mem += max_gpu_memory_mb_; - if(total_mem*num_process_per_experiment_ > required_memory_mb(circ, noise, method)) + if (total_mem * num_process_per_experiment_ > + required_memory_mb(circ, noise, method)) return true; } @@ -756,27 +756,24 @@ bool Controller::multiple_chunk_required(const Circuit &circ, bool Controller::multiple_shots_required(const Circuit &circ, const Noise::NoiseModel &noise, - const Method method) const -{ + const Method method) const { if (circ.shots < 2) return false; - if (method == Method::density_matrix || - method == Method::superop || + if (method == Method::density_matrix || method == Method::superop || method == Method::unitary) { return false; } bool can_sample = check_measure_sampling_opt(circ, method); - if (noise.is_ideal()){ - return !can_sample; + if (noise.is_ideal()) { + return !can_sample; } return true; } -size_t Controller::get_system_memory_mb() -{ +size_t Controller::get_system_memory_mb() { size_t total_physical_memory = Utils::get_system_memory_mb(); #ifdef AER_MPI // get minimum memory size per process @@ -820,19 +817,16 @@ size_t Controller::get_gpu_memory_mb() { return total_physical_memory >> 20; } - -Transpile::CacheBlocking -Controller::transpile_cache_blocking(Controller::Method method, const Circuit &circ, - const Noise::NoiseModel &noise, - const json_t &config) const -{ +Transpile::CacheBlocking Controller::transpile_cache_blocking( + Controller::Method method, const Circuit &circ, + const Noise::NoiseModel &noise, const json_t &config) const { Transpile::CacheBlocking cache_block_pass; - const bool is_matrix = (method == Method::density_matrix - || method == Method::unitary); + const bool is_matrix = + (method == Method::density_matrix || method == Method::unitary); const auto complex_size = (sim_precision_ == Precision::Single) - ? sizeof(std::complex) - : sizeof(std::complex); + ? sizeof(std::complex) + : sizeof(std::complex); cache_block_pass.set_num_processes(num_process_per_experiment_); cache_block_pass.set_config(config); @@ -841,7 +835,7 @@ Controller::transpile_cache_blocking(Controller::Method method, const Circuit &c // if blocking is not set by config, automatically set if required if (multiple_chunk_required(circ, noise, method)) { int nplace = num_process_per_experiment_; - if(sim_device_ == Device::GPU && num_gpus_ > 0) + if (sim_device_ == Device::GPU && num_gpus_ > 0) nplace *= num_gpus_; cache_block_pass.set_blocking(circ.num_qubits, get_min_memory_mb() << 20, nplace, complex_size, is_matrix); @@ -907,8 +901,7 @@ Result Controller::execute(const inputdata_t &input_qobj) { Result Controller::execute(std::vector &circuits, Noise::NoiseModel &noise_model, - const json_t &config) -{ + const json_t &config) { // Start QOBJ timer auto timer_start = myclock_t::now(); @@ -921,15 +914,15 @@ Result Controller::execute(std::vector &circuits, // Execute each circuit in a try block try { - //check if multi-chunk distribution is required + // check if multi-chunk distribution is required bool multi_chunk_required_ = false; - for (size_t j = 0; j < circuits.size(); j++){ - if(circuits[j].num_qubits > 0){ - if(multiple_chunk_required(circuits[j], noise_model, methods[j])) + for (size_t j = 0; j < circuits.size(); j++) { + if (circuits[j].num_qubits > 0) { + if (multiple_chunk_required(circuits[j], noise_model, methods[j])) multi_chunk_required_ = true; } } - if(multi_chunk_required_) + if (multi_chunk_required_) num_process_per_experiment_ = num_processes_; else num_process_per_experiment_ = 1; @@ -954,7 +947,8 @@ Result Controller::execute(std::vector &circuits, // store rank and number of processes, if no distribution rank=0 procs=1 is // set - result.metadata.add(num_process_per_experiment_, "num_processes_per_experiments"); + result.metadata.add(num_process_per_experiment_, + "num_processes_per_experiments"); result.metadata.add(num_processes_, "num_mpi_processes"); result.metadata.add(myrank_, "mpi_rank"); @@ -965,7 +959,7 @@ Result Controller::execute(std::vector &circuits, // Nested parallel experiments parallel_nested_ = true; - //nested should be set to zero if num_threads clause will be used + // nested should be set to zero if num_threads clause will be used omp_set_nested(0); result.metadata.add(parallel_nested_, "omp_nested"); @@ -975,33 +969,35 @@ Result Controller::execute(std::vector &circuits, #endif #ifdef AER_MPI - //average random seed to set the same seed to each process (when seed_simulator is not set) - if(num_processes_ > 1){ + // average random seed to set the same seed to each process (when + // seed_simulator is not set) + if (num_processes_ > 1) { reg_t seeds(circuits.size()); reg_t avg_seeds(circuits.size()); - for(int_t i=0;i &circuits, //------------------------------------------------------------------------- // Base class override //------------------------------------------------------------------------- -void Controller::run_circuit(const Circuit &circ, const Noise::NoiseModel &noise, - const Method method,const json_t &config, ExperimentResult &result) const -{ +void Controller::run_circuit(const Circuit &circ, + const Noise::NoiseModel &noise, + const Method method, const json_t &config, + ExperimentResult &result) const { // Run the circuit switch (method) { case Method::statevector: { @@ -1051,13 +1048,11 @@ void Controller::run_circuit(const Circuit &circ, const Noise::NoiseModel &noise // Chunk based simualtion if (sim_precision_ == Precision::Double) { // Double-precision Statevector simulation - return run_circuit_helper< - Statevector::State>>( + return run_circuit_helper>>( circ, noise, config, Method::statevector, result); } else { // Single-precision Statevector simulation - return run_circuit_helper< - Statevector::State>>( + return run_circuit_helper>>( circ, noise, config, Method::statevector, result); } } else { @@ -1149,8 +1144,8 @@ void Controller::run_circuit(const Circuit &circ, const Noise::NoiseModel &noise case Method::stabilizer: // Stabilizer simulation // TODO: Stabilizer doesn't yet support custom state initialization - return run_circuit_helper( - circ, noise, config, Method::stabilizer, result); + return run_circuit_helper(circ, noise, config, + Method::stabilizer, result); case Method::extended_stabilizer: return run_circuit_helper( circ, noise, config, Method::extended_stabilizer, result); @@ -1246,7 +1241,7 @@ Transpile::Fusion Controller::transpile_fusion(Method method, } case Method::matrix_product_state: { fusion_pass.active = false; - return fusion_pass; // Do not allow the config to set active for MPS + return fusion_pass; // Do not allow the config to set active for MPS } case Method::statevector: { if (fusion_pass.allow_kraus) { @@ -1277,10 +1272,8 @@ Transpile::Fusion Controller::transpile_fusion(Method method, template void Controller::run_circuit_helper(const Circuit &circ, const Noise::NoiseModel &noise, - const json_t &config, - const Method method, - ExperimentResult &result) const -{ + const json_t &config, const Method method, + ExperimentResult &result) const { // Start individual circuit timer auto timer_start = myclock_t::now(); // state circuit timer @@ -1316,7 +1309,7 @@ void Controller::run_circuit_helper(const Circuit &circ, result.metadata.add(false, "measure_sampling"); result.metadata.add(false, "batched_shots_optimization"); - if(circ.num_qubits > 0){ //do nothing for query steps + if (circ.num_qubits > 0) { // do nothing for query steps // Choose execution method based on noise and method Circuit opt_circ; bool noise_sampling = false; @@ -1334,33 +1327,36 @@ void Controller::run_circuit_helper(const Circuit &circ, // Superop noise sampling else if (method == Method::density_matrix || method == Method::superop) { // Sample noise using SuperOp method - opt_circ = noise.sample_noise(circ, rng, Noise::NoiseModel::Method::superop); + opt_circ = + noise.sample_noise(circ, rng, Noise::NoiseModel::Method::superop); result.metadata.add("superop", "noise"); } // Kraus noise sampling else if (noise.opset().contains(Operations::OpType::kraus) || noise.opset().contains(Operations::OpType::superop)) { - opt_circ = noise.sample_noise(circ, rng, Noise::NoiseModel::Method::kraus); + opt_circ = + noise.sample_noise(circ, rng, Noise::NoiseModel::Method::kraus); result.metadata.add("kraus", "noise"); } // General circuit noise sampling else { - if(enable_batch_multi_shots_ && !multi_chunk_required_){ - //batched optimization samples noise at runtime - opt_circ = noise.sample_noise(circ, rng, Noise::NoiseModel::Method::circuit, true); - } - else{ + if (enable_batch_multi_shots_ && !multi_chunk_required_) { + // batched optimization samples noise at runtime + opt_circ = noise.sample_noise( + circ, rng, Noise::NoiseModel::Method::circuit, true); + } else { noise_sampling = true; } result.metadata.add("circuit", "noise"); } - if(noise_sampling){ - run_circuit_with_sampled_noise(circ, noise, config, method, result); - } - else{ + if (noise_sampling) { + run_circuit_with_sampled_noise(circ, noise, config, method, + result); + } else { // Run multishot simulation without noise sampling - run_circuit_without_sampled_noise(opt_circ, noise, config, method, result); + run_circuit_without_sampled_noise(opt_circ, noise, config, + method, result); } } @@ -1398,13 +1394,11 @@ void Controller::run_single_shot(const Circuit &circ, State_t &state, } template -void Controller::run_with_sampling(const Circuit &circ, - State_t &state, - ExperimentResult &result, - RngEngine &rng, +void Controller::run_with_sampling(const Circuit &circ, State_t &state, + ExperimentResult &result, RngEngine &rng, const uint_t block_bits, const uint_t shots) const { - auto& ops = circ.ops; + auto &ops = circ.ops; auto first_meas = circ.first_measure_pos; // Position of first measurement op bool final_ops = (first_meas == ops.size()); @@ -1415,22 +1409,22 @@ void Controller::run_with_sampling(const Circuit &circ, state.initialize_qreg(circ.num_qubits); state.initialize_creg(circ.num_memory, circ.num_registers); - state.apply_ops(ops.cbegin(), ops.cbegin() + first_meas, result, rng, final_ops); + state.apply_ops(ops.cbegin(), ops.cbegin() + first_meas, result, rng, + final_ops); // Get measurement operations and set of measured qubits - measure_sampler(circ.ops.begin() + first_meas, circ.ops.end(), shots, state, result, rng); + measure_sampler(circ.ops.begin() + first_meas, circ.ops.end(), shots, state, + result, rng); } template -void Controller::run_circuit_without_sampled_noise(Circuit &circ, - const Noise::NoiseModel &noise, - const json_t &config, - const Method method, - ExperimentResult &result) const -{ +void Controller::run_circuit_without_sampled_noise( + Circuit &circ, const Noise::NoiseModel &noise, const json_t &config, + const Method method, ExperimentResult &result) const { State_t state; - // Validate gateset and memory requirements, raise exception if they're exceeded + // Validate gateset and memory requirements, raise exception if they're + // exceeded validate_state(state, circ, noise, true); // Set state config @@ -1448,8 +1442,9 @@ void Controller::run_circuit_without_sampled_noise(Circuit &circ, // Cache blocking pass uint_t block_bits = circ.num_qubits; - if(state.multi_chunk_distribution_supported()){ - auto cache_block_pass = transpile_cache_blocking(method, circ, dummy_noise, config); + if (state.multi_chunk_distribution_supported()) { + auto cache_block_pass = + transpile_cache_blocking(method, circ, dummy_noise, config); cache_block_pass.set_sample_measure(can_sample); cache_block_pass.optimize_circuit(circ, dummy_noise, state.opset(), result); if (cache_block_pass.enabled()) { @@ -1475,8 +1470,8 @@ void Controller::run_circuit_without_sampled_noise(Circuit &circ, #pragma omp parallel for num_threads(parallel_shots_) for (int i = 0; i < parallel_shots_; i++) { - uint_t i_shot = circ.shots*i/parallel_shots_; - uint_t shot_end = circ.shots*(i+1)/parallel_shots_; + uint_t i_shot = circ.shots * i / parallel_shots_; + uint_t shot_end = circ.shots * (i + 1) / parallel_shots_; uint_t this_shot = shot_end - i_shot; State_t shot_state; @@ -1490,7 +1485,8 @@ void Controller::run_circuit_without_sampled_noise(Circuit &circ, RngEngine rng; rng.set_seed(circ.seed + i); - run_with_sampling(circ, shot_state, par_results[i], rng, block_bits, this_shot); + run_with_sampling(circ, shot_state, par_results[i], rng, block_bits, + this_shot); shot_state.add_metadata(par_results[i]); } @@ -1498,8 +1494,8 @@ void Controller::run_circuit_without_sampled_noise(Circuit &circ, result.combine(std::move(res)); } - if (sim_device_name_ == "GPU"){ - if(parallel_shots_ >= num_gpus_) + if (sim_device_name_ == "GPU") { + if (parallel_shots_ >= num_gpus_) result.metadata.add(num_gpus_, "gpu_parallel_shots_"); else result.metadata.add(parallel_shots_, "gpu_parallel_shots_"); @@ -1508,65 +1504,69 @@ void Controller::run_circuit_without_sampled_noise(Circuit &circ, // Add measure sampling metadata result.metadata.add(true, "measure_sampling"); - } - else{ + } else { // Perform standard execution if we cannot apply the // measurement sampling optimization - if(block_bits == circ.num_qubits && enable_batch_multi_shots_ && state.multi_shot_parallelization_supported()){ - //apply batched multi-shots optimization (currenly only on GPU) + if (block_bits == circ.num_qubits && enable_batch_multi_shots_ && + state.multi_shot_parallelization_supported()) { + // apply batched multi-shots optimization (currenly only on GPU) state.set_max_bached_shots(max_batched_states_); state.set_distribution(num_processes_); state.set_max_matrix_qubits(max_bits); - state.allocate(circ.num_qubits, circ.num_qubits, circ.shots); //allocate multiple-shots + state.allocate(circ.num_qubits, circ.num_qubits, + circ.shots); // allocate multiple-shots - //qreg is initialized inside state class + // qreg is initialized inside state class state.initialize_creg(circ.num_memory, circ.num_registers); - state.apply_ops_multi_shots(circ.ops.cbegin(), circ.ops.cend(), noise, result, circ.seed, true); + state.apply_ops_multi_shots(circ.ops.cbegin(), circ.ops.cend(), noise, + result, circ.seed, true); result.save_count_data(state.cregs(), save_creg_memory_); // Add batched multi-shots optimizaiton metadata result.metadata.add(true, "batched_shots_optimization"); - } - else{ + } else { std::vector par_results(parallel_shots_); int_t par_shots = parallel_shots_; - if(block_bits != circ.num_qubits) + if (block_bits != circ.num_qubits) par_shots = 1; - auto run_circuit_without_sampled_noise_lambda = [this,&par_results,circ,noise,config,method,block_bits,max_bits,par_shots](int_t i){ - uint_t i_shot,shot_end; - i_shot = circ.shots*i/par_shots; - shot_end = circ.shots*(i+1)/par_shots; - - State_t par_state; - // Set state config - par_state.set_config(config); - par_state.set_parallelization(parallel_state_update_); - par_state.set_global_phase(circ.global_phase_angle); - - par_state.set_distribution(num_process_per_experiment_); - par_state.set_max_matrix_qubits(max_bits ); - - // allocate qubit register - par_state.allocate(circ.num_qubits, block_bits); - - for(;i_shot 1),0,par_shots,run_circuit_without_sampled_noise_lambda); + auto run_circuit_without_sampled_noise_lambda = + [this, &par_results, circ, noise, config, method, block_bits, + max_bits, par_shots](int_t i) { + uint_t i_shot, shot_end; + i_shot = circ.shots * i / par_shots; + shot_end = circ.shots * (i + 1) / par_shots; + + State_t par_state; + // Set state config + par_state.set_config(config); + par_state.set_parallelization(parallel_state_update_); + par_state.set_global_phase(circ.global_phase_angle); + + par_state.set_distribution(num_process_per_experiment_); + par_state.set_max_matrix_qubits(max_bits); + + // allocate qubit register + par_state.allocate(circ.num_qubits, block_bits); + + for (; i_shot < shot_end; i_shot++) { + RngEngine rng; + rng.set_seed(circ.seed + i_shot); + run_single_shot(circ, par_state, par_results[i], rng); + } + par_state.add_metadata(par_results[i]); + }; + Utils::apply_omp_parallel_for((par_shots > 1), 0, par_shots, + run_circuit_without_sampled_noise_lambda); for (auto &res : par_results) { result.combine(std::move(res)); } - if (sim_device_name_ == "GPU"){ - if(par_shots >= num_gpus_) + if (sim_device_name_ == "GPU") { + if (par_shots >= num_gpus_) result.metadata.add(num_gpus_, "gpu_parallel_shots_"); else result.metadata.add(par_shots, "gpu_parallel_shots_"); @@ -1579,16 +1579,17 @@ void Controller::run_circuit_without_sampled_noise(Circuit &circ, template void Controller::run_circuit_with_sampled_noise( const Circuit &circ, const Noise::NoiseModel &noise, const json_t &config, - const Method method, ExperimentResult &result) const -{ + const Method method, ExperimentResult &result) const { std::vector par_results(parallel_shots_); - auto run_circuit_with_sampled_noise_lambda = [this,&par_results,circ,noise,config,method](int_t i){ + auto run_circuit_with_sampled_noise_lambda = [this, &par_results, circ, noise, + config, method](int_t i) { State_t state; - uint_t i_shot,shot_end; + uint_t i_shot, shot_end; Noise::NoiseModel dummy_noise; - // Validate gateset and memory requirements, raise exception if they're exceeded + // Validate gateset and memory requirements, raise exception if they're + // exceeded validate_state(state, circ, noise, true); // Set state config @@ -1598,12 +1599,13 @@ void Controller::run_circuit_with_sampled_noise( // Transpilation for circuit noise method auto fusion_pass = transpile_fusion(method, circ.opset(), config); - auto cache_block_pass = transpile_cache_blocking(method, circ, noise, config); + auto cache_block_pass = + transpile_cache_blocking(method, circ, noise, config); - i_shot = circ.shots*i/parallel_shots_; - shot_end = circ.shots*(i+1)/parallel_shots_; + i_shot = circ.shots * i / parallel_shots_; + shot_end = circ.shots * (i + 1) / parallel_shots_; - for(;i_shot 1),0,parallel_shots_,run_circuit_with_sampled_noise_lambda); + Utils::apply_omp_parallel_for((parallel_shots_ > 1), 0, parallel_shots_, + run_circuit_with_sampled_noise_lambda); for (auto &res : par_results) { result.combine(std::move(res)); } - if (sim_device_name_ == "GPU"){ - if(parallel_shots_ >= num_gpus_) + if (sim_device_name_ == "GPU") { + if (parallel_shots_ >= num_gpus_) result.metadata.add(num_gpus_, "gpu_parallel_shots_"); else result.metadata.add(parallel_shots_, "gpu_parallel_shots_"); @@ -1658,12 +1661,11 @@ bool Controller::check_measure_sampling_opt(const Circuit &circ, // If density matrix, unitary, superop method all supported instructions // allow sampling - if (method == Method::density_matrix || - method == Method::superop || + if (method == Method::density_matrix || method == Method::superop || method == Method::unitary) { return true; } - + // If circuit contains a non-initial initialize that is not a full width // instruction we can't sample if (circ.can_sample_initialize == false) { @@ -1679,7 +1681,7 @@ bool Controller::check_measure_sampling_opt(const Circuit &circ, circ.opset().contains(Operations::OpType::kraus) || circ.opset().contains(Operations::OpType::superop) || circ.opset().contains(Operations::OpType::jump) || - circ.opset().contains(Operations::OpType::mark )) { + circ.opset().contains(Operations::OpType::mark)) { return false; } // Otherwise true @@ -1687,10 +1689,10 @@ bool Controller::check_measure_sampling_opt(const Circuit &circ, } template -void Controller::measure_sampler( - InputIterator first_meas, InputIterator last_meas, uint_t shots, - State_t &state, ExperimentResult &result, RngEngine &rng, int_t shot_index) const -{ +void Controller::measure_sampler(InputIterator first_meas, + InputIterator last_meas, uint_t shots, + State_t &state, ExperimentResult &result, + RngEngine &rng, int_t shot_index) const { // Check if meas_circ is empty, and if so return initial creg if (first_meas == last_meas) { while (shots-- > 0) { @@ -1721,7 +1723,7 @@ void Controller::measure_sampler( // Generate the samples uint_t shots_or_index; - if(shot_index < 0) + if (shot_index < 0) shots_or_index = shots; else shots_or_index = shot_index; @@ -1752,8 +1754,10 @@ void Controller::measure_sampler( } // Process samples - uint_t num_memory = (memory_map.empty()) ? 0ULL : 1 + memory_map.rbegin()->first; - uint_t num_registers = (register_map.empty()) ? 0ULL : 1 + register_map.rbegin()->first; + uint_t num_memory = + (memory_map.empty()) ? 0ULL : 1 + memory_map.rbegin()->first; + uint_t num_registers = + (register_map.empty()) ? 0ULL : 1 + register_map.rbegin()->first; ClassicalRegister creg; while (!all_samples.empty()) { auto sample = all_samples.back(); @@ -1776,14 +1780,13 @@ void Controller::measure_sampler( } // Save count data - result.save_count_data(creg, save_creg_memory_); + result.save_count_data(creg, save_creg_memory_); // pop off processed sample all_samples.pop_back(); } } - //------------------------------------------------------------------------- // Validation //------------------------------------------------------------------------- @@ -1792,22 +1795,25 @@ std::vector Controller::simulation_methods(std::vector &circuits, Noise::NoiseModel &noise_model) const { // Does noise model contain kraus noise - bool kraus_noise = (noise_model.opset().contains(Operations::OpType::kraus) || - noise_model.opset().contains(Operations::OpType::superop)); + bool kraus_noise = + (noise_model.opset().contains(Operations::OpType::kraus) || + noise_model.opset().contains(Operations::OpType::superop)); if (method_ == Method::automatic) { // Determine simulation methods for each circuit and noise model std::vector sim_methods; bool superop_enabled = false; bool kraus_enabled = false; - for (const auto& circ: circuits) { + for (const auto &circ : circuits) { auto method = automatic_simulation_method(circ, noise_model); sim_methods.push_back(method); - if (!superop_enabled && (method == Method::density_matrix || method == Method::superop)) { + if (!superop_enabled && + (method == Method::density_matrix || method == Method::superop)) { noise_model.enable_superop_method(max_parallel_threads_); superop_enabled = true; } else if (kraus_noise && !kraus_enabled && - (method == Method::statevector || method == Method::matrix_product_state)) { + (method == Method::statevector || + method == Method::matrix_product_state)) { noise_model.enable_kraus_method(max_parallel_threads_); kraus_enabled = true; } @@ -1819,17 +1825,15 @@ Controller::simulation_methods(std::vector &circuits, std::vector sim_methods(circuits.size(), method_); if (method_ == Method::density_matrix || method_ == Method::superop) { noise_model.enable_superop_method(max_parallel_threads_); - } else if (kraus_noise && ( - method_ == Method::statevector - || method_ == Method::matrix_product_state)) { + } else if (kraus_noise && (method_ == Method::statevector || + method_ == Method::matrix_product_state)) { noise_model.enable_kraus_method(max_parallel_threads_); } return sim_methods; } -Controller::Method -Controller::automatic_simulation_method(const Circuit &circ, - const Noise::NoiseModel &noise_model) const { +Controller::Method Controller::automatic_simulation_method( + const Circuit &circ, const Noise::NoiseModel &noise_model) const { // If circuit and noise model are Clifford run on Stabilizer simulator if (validate_method(Method::stabilizer, circ, noise_model, false)) { return Method::stabilizer; @@ -1851,12 +1855,10 @@ Controller::automatic_simulation_method(const Circuit &circ, // operations only with preference given by memory requirements // statevector > density matrix > matrix product state > unitary > superop // typically any save state instructions will decide the method. - const std::vector methods({Method::statevector, - Method::density_matrix, - Method::matrix_product_state, - Method::unitary, - Method::superop}); - for (const auto& method : methods) { + const std::vector methods( + {Method::statevector, Method::density_matrix, + Method::matrix_product_state, Method::unitary, Method::superop}); + for (const auto &method : methods) { if (validate_method(method, circ, noise_model, false)) return method; } @@ -1868,32 +1870,37 @@ Controller::automatic_simulation_method(const Circuit &circ, return Method::statevector; } -bool Controller::validate_method(Method method, - const Circuit &circ, +bool Controller::validate_method(Method method, const Circuit &circ, const Noise::NoiseModel &noise_model, bool throw_except) const { // Switch wrapper for templated function validate_state switch (method) { - case Method::stabilizer: - return validate_state(Stabilizer::State(), circ, noise_model, throw_except); - case Method::extended_stabilizer: - return validate_state(ExtendedStabilizer::State(), circ, noise_model, throw_except); - case Method::matrix_product_state: - return validate_state(MatrixProductState::State(), circ, noise_model, throw_except); - case Method::statevector: - return validate_state(Statevector::State<>(), circ, noise_model, throw_except); - case Method::density_matrix: - return validate_state(DensityMatrix::State<>(), circ, noise_model, throw_except); - case Method::unitary: - return validate_state(QubitUnitary::State<>(), circ, noise_model, throw_except); - case Method::superop: - return validate_state(QubitSuperoperator::State<>(), circ, noise_model, throw_except); - case Method::automatic: - throw std::runtime_error("Cannot validate circuit for unresolved simulation method."); + case Method::stabilizer: + return validate_state(Stabilizer::State(), circ, noise_model, throw_except); + case Method::extended_stabilizer: + return validate_state(ExtendedStabilizer::State(), circ, noise_model, + throw_except); + case Method::matrix_product_state: + return validate_state(MatrixProductState::State(), circ, noise_model, + throw_except); + case Method::statevector: + return validate_state(Statevector::State<>(), circ, noise_model, + throw_except); + case Method::density_matrix: + return validate_state(DensityMatrix::State<>(), circ, noise_model, + throw_except); + case Method::unitary: + return validate_state(QubitUnitary::State<>(), circ, noise_model, + throw_except); + case Method::superop: + return validate_state(QubitSuperoperator::State<>(), circ, noise_model, + throw_except); + case Method::automatic: + throw std::runtime_error( + "Cannot validate circuit for unresolved simulation method."); } } - template bool Controller::validate_state(const state_t &state, const Circuit &circ, const Noise::NoiseModel &noise, @@ -1921,13 +1928,17 @@ bool Controller::validate_state(const state_t &state, const Circuit &circ, // Validate memory requirements bool memory_valid = true; if (max_memory_mb_ > 0) { - size_t required_mb = state.required_memory_mb(circ.num_qubits, circ.ops) / num_process_per_experiment_; - size_t mem_size = (sim_device_ == Device::GPU) ? max_memory_mb_ + max_gpu_memory_mb_ : max_memory_mb_; + size_t required_mb = state.required_memory_mb(circ.num_qubits, circ.ops) / + num_process_per_experiment_; + size_t mem_size = (sim_device_ == Device::GPU) + ? max_memory_mb_ + max_gpu_memory_mb_ + : max_memory_mb_; memory_valid = (required_mb <= mem_size); if (throw_except && !memory_valid) { error_msg << "Insufficient memory to run circuit " << circ_name; error_msg << " using the " << state.name() << " simulator."; - error_msg << " Required memory: " << required_mb << "M, max memory: " << max_memory_mb_ << "M"; + error_msg << " Required memory: " << required_mb + << "M, max memory: " << max_memory_mb_ << "M"; if (sim_device_ == Device::GPU) { error_msg << " (Host) + " << max_gpu_memory_mb_ << "M (GPU)"; } @@ -1955,13 +1966,15 @@ void Controller::save_exception_to_results(Result &result, } } -int_t Controller::get_matrix_bits(const Operations::Op& op) const -{ +int_t Controller::get_matrix_bits(const Operations::Op &op) const { int_t bit = 1; - if(op.type == Operations::OpType::matrix || op.type == Operations::OpType::diagonal_matrix || op.type == Operations::OpType::initialize) + if (op.type == Operations::OpType::matrix || + op.type == Operations::OpType::diagonal_matrix || + op.type == Operations::OpType::initialize) bit = op.qubits.size(); - else if(op.type == Operations::OpType::kraus || op.type == Operations::OpType::superop){ - if(method_ == Method::density_matrix) + else if (op.type == Operations::OpType::kraus || + op.type == Operations::OpType::superop) { + if (method_ == Method::density_matrix) bit = op.qubits.size() * 2; else bit = op.qubits.size(); @@ -1969,15 +1982,14 @@ int_t Controller::get_matrix_bits(const Operations::Op& op) const return bit; } -int_t Controller::get_max_matrix_qubits(const Circuit &circ) const -{ +int_t Controller::get_max_matrix_qubits(const Circuit &circ) const { int_t max_bits = 0; int_t i; - for(i=0;i -#include "misc/hacks.hpp" #include "framework/results/result.hpp" +#include "misc/hacks.hpp" +#include //========================================================================= // Controller Execute interface @@ -26,20 +26,19 @@ namespace AER { template -Result controller_execute(const inputdata_t& qobj) { +Result controller_execute(const inputdata_t &qobj) { controller_t controller; // Fix for MacOS and OpenMP library double initialization crash. // Issue: https://github.com/Qiskit/qiskit-aer/issues/1 if (Parser::check_key("config", qobj)) { - std::string path; - const auto& config = Parser::get_value("config", qobj); - Parser::get_value(path, "library_dir", config); - Hacks::maybe_load_openmp(path); + std::string path; + const auto &config = Parser::get_value("config", qobj); + Parser::get_value(path, "library_dir", config); + Hacks::maybe_load_openmp(path); } return controller.execute(qobj); } - } // end namespace AER #endif diff --git a/src/controllers/state_controller.hpp b/src/controllers/state_controller.hpp index 60f64ccb19..bbd424e640 100644 --- a/src/controllers/state_controller.hpp +++ b/src/controllers/state_controller.hpp @@ -15,11 +15,11 @@ #ifndef _aer_state_hpp_ #define _aer_state_hpp_ -#include +#include #include +#include #include #include -#include #include "framework/rng.hpp" #include "misc/warnings.hpp" @@ -37,11 +37,11 @@ DISABLE_WARNING_PUSH DISABLE_WARNING_POP #include "framework/creg.hpp" +#include "framework/linalg/vector.hpp" #include "framework/qobj.hpp" #include "framework/results/experiment_result.hpp" #include "framework/results/result.hpp" #include "framework/rng.hpp" -#include "framework/linalg/vector.hpp" #include "noise/noise_model.hpp" @@ -56,8 +56,8 @@ DISABLE_WARNING_POP #include "simulators/statevector/qubitvector.hpp" #include "simulators/statevector/statevector_state.hpp" #include "simulators/superoperator/superoperator_state.hpp" -#include "simulators/unitary/unitarymatrix.hpp" #include "simulators/unitary/unitary_state.hpp" +#include "simulators/unitary/unitarymatrix.hpp" #ifdef AER_THRUST_SUPPORTED #include "simulators/density_matrix/densitymatrix_thrust.hpp" @@ -66,7 +66,7 @@ DISABLE_WARNING_POP #endif using int_t = int_fast64_t; -using uint_t = uint_fast64_t; +using uint_t = uint_fast64_t; using complex_t = std::complex; using complexf_t = std::complex; using cvector_t = std::vector; @@ -103,39 +103,39 @@ class AerState { //----------------------------------------------------------------------- AerState() = default; - virtual ~AerState() { }; + virtual ~AerState(){}; //----------------------------------------------------------------------- // Configuration //----------------------------------------------------------------------- - - // set configuration. + + // set configuration. // All of the configuration must be done before calling any gate operations. - virtual void configure(const std::string& key, const std::string& value); + virtual void configure(const std::string &key, const std::string &value); // configure a method. - virtual bool set_method(const std::string& name); + virtual bool set_method(const std::string &name); // configure a device. - virtual bool set_device(const std::string& name); + virtual bool set_device(const std::string &name); // configure a precision. - virtual bool set_precision(const std::string& name); + virtual bool set_precision(const std::string &name); // configure custatevec enabled or not - virtual bool set_custatevec(const bool& enabled); + virtual bool set_custatevec(const bool &enabled); // configure seed - virtual bool set_seed_simulator(const int& seed); + virtual bool set_seed_simulator(const int &seed); // configure number of threads to update state - virtual bool set_parallel_state_update(const uint_t& parallel_state_update); + virtual bool set_parallel_state_update(const uint_t ¶llel_state_update); // configure max number of qubits for a gate - virtual bool set_max_gate_qubits(const uint_t& max_gate_qubits); + virtual bool set_max_gate_qubits(const uint_t &max_gate_qubits); // configure cache blocking qubits - virtual bool set_blocking_qubits(const uint_t& blocking_qubits); + virtual bool set_blocking_qubits(const uint_t &blocking_qubits); // Return true if gate operations have been performed and no configuration // is permitted. @@ -155,7 +155,7 @@ class AerState { // Clear all the configurations virtual void clear(); - virtual ExperimentResult& last_result() { return last_result_; }; + virtual ExperimentResult &last_result() { return last_result_; }; //----------------------------------------------------------------------- // Initialization @@ -165,9 +165,10 @@ class AerState { void initialize(); // Allocate qubits with inputted complex array - // method must be statevector and the length of the array must be 2^{num_qubits} - // given data will not be freed in this class - virtual reg_t initialize_statevector(uint_t num_qubits, complex_t* data, bool copy); + // method must be statevector and the length of the array must be + // 2^{num_qubits} given data will not be freed in this class + virtual reg_t initialize_statevector(uint_t num_qubits, complex_t *data, + bool copy); // Release internal statevector // The caller must free the returned pointer @@ -190,8 +191,11 @@ class AerState { // Apply a N-qubit matrix to the state vector. virtual void apply_unitary(const reg_t &qubits, const cmatrix_t &mat); - // Apply a stacked set of 2^control_count target_count--qubit matrix to the state vector. - virtual void apply_multiplexer(const reg_t &control_qubits, const reg_t &target_qubits, const std::vector &mats); + // Apply a stacked set of 2^control_count target_count--qubit matrix to the + // state vector. + virtual void apply_multiplexer(const reg_t &control_qubits, + const reg_t &target_qubits, + const std::vector &mats); // Apply a N-qubit diagonal matrix to the state vector. virtual void apply_diagonal_matrix(const reg_t &qubits, const cvector_t &mat); @@ -223,13 +227,15 @@ class AerState { // If N=1 this implements an optimized single-qubit phase gate // If N=2 this implements an optimized CPhase gate // If N=3 this implements an optimized CCPhase gate - virtual void apply_mcphase(const reg_t &qubits, const std::complex phase); + virtual void apply_mcphase(const reg_t &qubits, + const std::complex phase); // Apply a general multi-controlled single-qubit unitary gate // If N=1 this implements an optimized single-qubit U gate // If N=2 this implements an optimized CU gate // If N=3 this implements an optimized CCU gate - virtual void apply_mcu(const reg_t &qubits, const double theta, const double phi, const double lambda); + virtual void apply_mcu(const reg_t &qubits, const double theta, + const double phi, const double lambda); // Apply a general multi-controlled SWAP gate // If N=2 this implements an optimized SWAP gate @@ -293,19 +299,21 @@ class AerState { // The input is a length M list of random reals between [0, 1) used for // generating samples. // The returned value is unordered sampled outcomes - virtual std::vector sample_memory(const reg_t &qubits, uint_t shots); + virtual std::vector sample_memory(const reg_t &qubits, + uint_t shots); // Return M sampled outcomes for Z-basis measurement of specified qubits // The input is a length M list of random reals between [0, 1) used for // generating samples. // The returned value is a map from outcome to its number of samples. - virtual std::unordered_map sample_counts(const reg_t &qubits, uint_t shots); + virtual std::unordered_map sample_counts(const reg_t &qubits, + uint_t shots); //----------------------------------------------------------------------- // Operation management //----------------------------------------------------------------------- // Buffer Operations::Op - virtual void buffer_op(const Operations::Op&& op); + virtual void buffer_op(const Operations::Op &&op); // Flush buffered Operations::Op virtual void flush_ops(); @@ -334,22 +342,20 @@ class AerState { Method method_ = Method::statevector; const std::unordered_map method_names_ = { - {Method::statevector, "statevector"}, - {Method::density_matrix, "density_matrix"}, - {Method::matrix_product_state, "matrix_product_state"}, - {Method::stabilizer, "stabilizer"}, - {Method::extended_stabilizer, "extended_stabilizer"}, - {Method::unitary, "unitary"}, - {Method::superop, "superop"} - }; + {Method::statevector, "statevector"}, + {Method::density_matrix, "density_matrix"}, + {Method::matrix_product_state, "matrix_product_state"}, + {Method::stabilizer, "stabilizer"}, + {Method::extended_stabilizer, "extended_stabilizer"}, + {Method::unitary, "unitary"}, + {Method::superop, "superop"}}; Device device_ = Device::CPU; const std::unordered_map device_names_ = { - {Device::CPU, "CPU"}, - {Device::GPU, "GPU"}, - {Device::ThrustCPU, "ThrustCPU"} - }; + {Device::CPU, "CPU"}, + {Device::GPU, "GPU"}, + {Device::ThrustCPU, "ThrustCPU"}}; Precision precision_ = Precision::Double; @@ -378,27 +384,29 @@ class AerState { bool AerState::is_gpu(bool raise_error) const { #ifndef AER_THRUST_CUDA if (raise_error) - throw std::runtime_error("Simulation device \"GPU\" is not supported on this system"); + throw std::runtime_error( + "Simulation device \"GPU\" is not supported on this system"); else return false; #else int nDev; if (cudaGetDeviceCount(&nDev) != cudaSuccess) { - if (raise_error) { - cudaGetLastError(); - throw std::runtime_error("No CUDA device available!"); - } else return false; + if (raise_error) { + cudaGetLastError(); + throw std::runtime_error("No CUDA device available!"); + } else + return false; } #endif return true; } -void AerState::configure(const std::string& _key, const std::string& _value) { +void AerState::configure(const std::string &_key, const std::string &_value) { std::string key = _key; - std::transform(key.begin(), key.end(), key.begin(), ::tolower); + std::transform(key.begin(), key.end(), key.begin(), ::tolower); std::string value = _value; - std::transform(value.begin(), value.end(), value.begin(), ::tolower); + std::transform(value.begin(), value.end(), value.begin(), ::tolower); bool error = false; if (key == "method") { @@ -425,44 +433,67 @@ void AerState::configure(const std::string& _key, const std::string& _value) { throw std::runtime_error(msg.str()); } - static std::unordered_set str_config = { "method", "device", "precision", "extended_stabilizer_sampling_method", - "mps_sample_measure_algorithm", "mps_log_data", "mps_swap_direction"}; - static std::unordered_set int_config = { "seed_simulator", "max_parallel_threads", "max_memory_mb", "parallel_state_update", - "blocking_qubits", "batched_shots_gpu_max_qubits", "statevector_parallel_threshold", - "statevector_sample_measure_opt", "stabilizer_max_snapshot_probabilities", - "extended_stabilizer_metropolis_mixing_time", "extended_stabilizer_norm_estimation_samples", - "extended_stabilizer_norm_estimation_repetitions", "extended_stabilizer_parallel_threshold", - "extended_stabilizer_probabilities_snapshot_samples", "matrix_product_state_max_bond_dimension", - "fusion_max_qubit", "fusion_threshold"}; - static std::unordered_set double_config = { "extended_stabilizer_approximation_error", "matrix_product_state_truncation_threshold", - }; - static std::unordered_set bool_config = { "custatevec_enable", "blocking_enable", "batched_shots_gpu", "fusion_enable", "fusion_verbose"}; - - if (str_config.find(key) != str_config.end() ) { + static std::unordered_set str_config = { + "method", + "device", + "precision", + "extended_stabilizer_sampling_method", + "mps_sample_measure_algorithm", + "mps_log_data", + "mps_swap_direction"}; + static std::unordered_set int_config = { + "seed_simulator", + "max_parallel_threads", + "max_memory_mb", + "parallel_state_update", + "blocking_qubits", + "batched_shots_gpu_max_qubits", + "statevector_parallel_threshold", + "statevector_sample_measure_opt", + "stabilizer_max_snapshot_probabilities", + "extended_stabilizer_metropolis_mixing_time", + "extended_stabilizer_norm_estimation_samples", + "extended_stabilizer_norm_estimation_repetitions", + "extended_stabilizer_parallel_threshold", + "extended_stabilizer_probabilities_snapshot_samples", + "matrix_product_state_max_bond_dimension", + "fusion_max_qubit", + "fusion_threshold"}; + static std::unordered_set double_config = { + "extended_stabilizer_approximation_error", + "matrix_product_state_truncation_threshold", + }; + static std::unordered_set bool_config = { + "custatevec_enable", "blocking_enable", "batched_shots_gpu", + "fusion_enable", "fusion_verbose"}; + + if (str_config.find(key) != str_config.end()) { configs_[_key] = _value; - } else if (int_config.find(key) != int_config.end() ) { + } else if (int_config.find(key) != int_config.end()) { configs_[_key] = std::stoi(value); - } else if (bool_config.find(key) != bool_config.end() ) { + } else if (bool_config.find(key) != bool_config.end()) { configs_[_key] = "true" == value; - } else if (double_config.find(key) != double_config.end() ) { + } else if (double_config.find(key) != double_config.end()) { configs_[_key] = std::stod(value); } else { std::stringstream msg; msg << "not supported configuration: " << key << "=" << value << std::endl; throw std::runtime_error(msg.str()); } - }; -bool AerState::set_method(const std::string& method_name) { +bool AerState::set_method(const std::string &method_name) { assert_not_initialized(); - auto it = find_if(method_names_.begin(), method_names_.end(), [method_name](const auto& vt) { return vt.second == method_name; }); - if (it == method_names_.end()) return false; + auto it = find_if( + method_names_.begin(), method_names_.end(), + [method_name](const auto &vt) { return vt.second == method_name; }); + if (it == method_names_.end()) + return false; method_ = it->first; return true; }; -bool AerState::set_device(const std::string& device_name) { +bool AerState::set_device(const std::string &device_name) { assert_not_initialized(); if (device_name == "cpu") device_ = Device::CPU; @@ -475,7 +506,7 @@ bool AerState::set_device(const std::string& device_name) { return true; }; -bool AerState::set_precision(const std::string& precision_name) { +bool AerState::set_precision(const std::string &precision_name) { assert_not_initialized(); if (precision_name == "single") precision_ = Precision::Single; @@ -486,32 +517,31 @@ bool AerState::set_precision(const std::string& precision_name) { return true; }; -bool AerState::set_custatevec(const bool& enabled) { +bool AerState::set_custatevec(const bool &enabled) { assert_not_initialized(); cuStateVec_enable_ = enabled; return true; }; -bool AerState::set_seed_simulator(const int& seed) { +bool AerState::set_seed_simulator(const int &seed) { assert_not_initialized(); seed_ = seed; return true; }; -bool AerState::set_parallel_state_update(const uint_t& parallel_state_update) { +bool AerState::set_parallel_state_update(const uint_t ¶llel_state_update) { assert_not_initialized(); parallel_state_update_ = parallel_state_update; return true; }; -bool AerState::set_max_gate_qubits(const uint_t& max_gate_qubits) { +bool AerState::set_max_gate_qubits(const uint_t &max_gate_qubits) { assert_not_initialized(); max_gate_qubits_ = max_gate_qubits; return true; }; -bool AerState::set_blocking_qubits(const uint_t& blocking_qubits) -{ +bool AerState::set_blocking_qubits(const uint_t &blocking_qubits) { assert_not_initialized(); cache_block_qubits_ = blocking_qubits; return true; @@ -545,73 +575,93 @@ void AerState::initialize() { if (method_ == Method::statevector) { if (device_ == Device::CPU) if (precision_ == Precision::Double) - state_ = std::make_shared>>(); + state_ = + std::make_shared>>(); else state_ = std::make_shared>>(); else // if (device_ == Device::GPU) #ifdef AER_THRUST_SUPPORTED - if (precision_ == Precision::Double) - state_ = std::make_shared>>(); - else - state_ = std::make_shared>>(); + if (precision_ == Precision::Double) + state_ = + std::make_shared>>(); + else + state_ = + std::make_shared>>(); #else - throw std::runtime_error("specified method does not support non-CPU device: method=statevector"); + throw std::runtime_error("specified method does not support non-CPU " + "device: method=statevector"); #endif } else if (method_ == Method::density_matrix) { if (device_ == Device::CPU) if (precision_ == Precision::Double) - state_ = std::make_shared>>(); + state_ = + std::make_shared>>(); else - state_ = std::make_shared>>(); + state_ = + std::make_shared>>(); else // if (device_ == Device::GPU) #ifdef AER_THRUST_SUPPORTED - if (precision_ == Precision::Double) - state_ = std::make_shared>>(); - else - state_ = std::make_shared>>(); + if (precision_ == Precision::Double) + state_ = std::make_shared< + DensityMatrix::State>>(); + else + state_ = std::make_shared< + DensityMatrix::State>>(); #else - throw std::runtime_error("specified method does not support non-CPU device: method=density_matrix"); + throw std::runtime_error("specified method does not support non-CPU " + "device: method=density_matrix"); #endif } else if (method_ == Method::unitary) { if (device_ == Device::CPU) if (precision_ == Precision::Double) - state_ = std::make_shared>>(); + state_ = + std::make_shared>>(); else - state_ = std::make_shared>>(); + state_ = + std::make_shared>>(); else // if (device_ == Device::GPU) #ifdef AER_THRUST_SUPPORTED - if (precision_ == Precision::Double) - state_ = std::make_shared>>(); - else - state_ = std::make_shared>>(); + if (precision_ == Precision::Double) + state_ = std::make_shared< + QubitUnitary::State>>(); + else + state_ = std::make_shared< + QubitUnitary::State>>(); #else - throw std::runtime_error("specified method does not support non-CPU device: method=unitary"); + throw std::runtime_error( + "specified method does not support non-CPU device: method=unitary"); #endif } else if (method_ == Method::matrix_product_state) { if (device_ == Device::CPU) state_ = std::make_shared(); else // if (device_ == Device::GPU) - throw std::runtime_error("specified method does not support non-CPU device: method=matrix_product_state"); + throw std::runtime_error("specified method does not support non-CPU " + "device: method=matrix_product_state"); } else if (method_ == Method::stabilizer) { if (device_ == Device::CPU) state_ = std::make_shared(); else // if (device_ == Device::GPU) - throw std::runtime_error("specified method does not support non-CPU device: method=stabilizer"); + throw std::runtime_error("specified method does not support non-CPU " + "device: method=stabilizer"); } else if (method_ == Method::extended_stabilizer) { if (device_ == Device::CPU) state_ = std::make_shared(); else // if (device_ == Device::GPU) - throw std::runtime_error("specified method does not support non-CPU device: method=extended_stabilizer"); + throw std::runtime_error("specified method does not support non-CPU " + "device: method=extended_stabilizer"); } else if (method_ == Method::superop) { if (device_ == Device::CPU) if (precision_ == Precision::Double) - state_ = std::make_shared>>(); + state_ = std::make_shared< + QubitSuperoperator::State>>(); else - state_ = std::make_shared>>(); + state_ = std::make_shared< + QubitSuperoperator::State>>(); else // if (device_ == Device::GPU) - throw std::runtime_error("specified method does not support non-CPU device: method=superop"); + throw std::runtime_error( + "specified method does not support non-CPU device: method=superop"); } else { - throw std::runtime_error("not supported method."); + throw std::runtime_error("not supported method."); } #ifdef _OPENMP @@ -623,7 +673,8 @@ void AerState::initialize() { uint_t block_qubits = cache_block_qubits_; cache_block_pass_.set_num_processes(num_process_per_experiment_); cache_block_pass_.set_config(configs_); - if(!cache_block_pass_.enabled() || !state_->multi_chunk_distribution_supported()) + if (!cache_block_pass_.enabled() || + !state_->multi_chunk_distribution_supported()) block_qubits = num_of_qubits_; state_->set_config(configs_); @@ -645,7 +696,7 @@ reg_t AerState::allocate_qubits(uint_t num_qubits) { assert_not_initialized(); reg_t ret; for (auto i = 0; i < num_qubits; ++i) - ret.push_back(num_of_qubits_++); + ret.push_back(num_of_qubits_++); return ret; }; @@ -655,7 +706,8 @@ reg_t AerState::reallocate_qubits(uint_t num_qubits) { return allocate_qubits(num_qubits); }; -reg_t AerState::initialize_statevector(uint_t num_of_qubits, complex_t* data, bool copy) { +reg_t AerState::initialize_statevector(uint_t num_of_qubits, complex_t *data, + bool copy) { assert_not_initialized(); #ifdef AER_MPI MPI_Comm_size(MPI_COMM_WORLD, &num_processes_); @@ -667,18 +719,21 @@ reg_t AerState::initialize_statevector(uint_t num_of_qubits, complex_t* data, bo cache_block_pass_.set_config(configs_); if (device_ != Device::CPU) - throw std::runtime_error("only CPU device supports initialize_statevector()"); + throw std::runtime_error( + "only CPU device supports initialize_statevector()"); if (precision_ != Precision::Double) - throw std::runtime_error("only Double precision supports initialize_statevector()"); + throw std::runtime_error( + "only Double precision supports initialize_statevector()"); num_of_qubits_ = num_of_qubits; auto state = std::make_shared>>(); state->set_config(configs_); state->set_distribution(num_process_per_experiment_); state->set_max_matrix_qubits(max_gate_qubits_); - - if(!cache_block_pass_.enabled() || !state->multi_chunk_distribution_supported()) + + if (!cache_block_pass_.enabled() || + !state->multi_chunk_distribution_supported()) block_qubits = num_of_qubits_; - + state->allocate(num_of_qubits_, block_qubits); auto qv = QV::QubitVector(num_of_qubits_, data, copy); state->initialize_qreg(num_of_qubits_); @@ -720,7 +775,10 @@ AER::Vector AerState::move_to_vector() { ExperimentResult ret; state_->apply_op(op, ret, rng_, true); - auto sv = std::move(static_cast>>(std::move(ret).data).value()["s"].value()); + auto sv = std::move( + static_cast>>(std::move(ret).data) + .value()["s"] + .value()); clear(); return std::move(sv); @@ -730,7 +788,7 @@ AER::Vector AerState::move_to_vector() { // Apply Initialization //----------------------------------------------------------------------- -void AerState::apply_initialize(const reg_t &qubits, cvector_t && vec) { +void AerState::apply_initialize(const reg_t &qubits, cvector_t &&vec) { assert_initialized(); Operations::Op op; op.type = Operations::OpType::initialize; @@ -763,7 +821,8 @@ void AerState::apply_unitary(const reg_t &qubits, const cmatrix_t &mat) { buffer_op(std::move(op)); } -void AerState::apply_diagonal_matrix(const reg_t &qubits, const cvector_t &mat) { +void AerState::apply_diagonal_matrix(const reg_t &qubits, + const cvector_t &mat) { assert_initialized(); Operations::Op op; op.type = Operations::OpType::diagonal_matrix; @@ -774,7 +833,9 @@ void AerState::apply_diagonal_matrix(const reg_t &qubits, const cvector_t &mat) buffer_op(std::move(op)); } -void AerState::apply_multiplexer(const reg_t &control_qubits, const reg_t &target_qubits, const std::vector &mats) { +void AerState::apply_multiplexer(const reg_t &control_qubits, + const reg_t &target_qubits, + const std::vector &mats) { assert_initialized(); if (mats.empty()) @@ -846,7 +907,8 @@ void AerState::apply_mcz(const reg_t &qubits) { buffer_op(std::move(op)); } -void AerState::apply_mcphase(const reg_t &qubits, const std::complex phase) { +void AerState::apply_mcphase(const reg_t &qubits, + const std::complex phase) { assert_initialized(); Operations::Op op; @@ -858,7 +920,8 @@ void AerState::apply_mcphase(const reg_t &qubits, const std::complex pha buffer_op(std::move(op)); } -void AerState::apply_mcu(const reg_t &qubits, const double theta, const double phi, const double lambda) { +void AerState::apply_mcu(const reg_t &qubits, const double theta, + const double phi, const double lambda) { assert_initialized(); Operations::Op op; @@ -938,7 +1001,7 @@ uint_t AerState::apply_measure(const reg_t &qubits) { uint_t bitstring = 0; uint_t bit = 1; - for (const auto& qubit: qubits) { + for (const auto &qubit : qubits) { if (state_->creg().creg_memory()[qubit] == '1') bitstring |= bit; bit <<= 1; @@ -979,7 +1042,9 @@ double AerState::probability(const uint_t outcome) { last_result_ = ExperimentResult(); state_->apply_op(op, last_result_, rng_); - return ((DataMap)last_result_.data).value()["s"].value()[0][0]; + return ((DataMap)last_result_.data) + .value()["s"] + .value()[0][0]; } // Return the probability amplitude for outcome in [0, 2^num_qubits - 1] @@ -998,7 +1063,9 @@ complex_t AerState::amplitude(const uint_t outcome) { last_result_ = ExperimentResult(); state_->apply_op(op, last_result_, rng_); - return ((DataMap>)last_result_.data).value()["s"].value()[0][0]; + return ((DataMap>)last_result_.data) + .value()["s"] + .value()[0][0]; }; std::vector AerState::probabilities() { @@ -1015,7 +1082,9 @@ std::vector AerState::probabilities() { last_result_ = ExperimentResult(); state_->apply_op(op, last_result_, rng_); - return ((DataMap)last_result_.data).value()["s"].value()[0]; + return ((DataMap)last_result_.data) + .value()["s"] + .value()[0]; } std::vector AerState::probabilities(const reg_t &qubits) { @@ -1033,10 +1102,13 @@ std::vector AerState::probabilities(const reg_t &qubits) { last_result_ = ExperimentResult(); state_->apply_op(op, last_result_, rng_); - return ((DataMap)last_result_.data).value()["s"].value()[0]; + return ((DataMap)last_result_.data) + .value()["s"] + .value()[0]; } -std::vector AerState::sample_memory(const reg_t &qubits, uint_t shots) { +std::vector AerState::sample_memory(const reg_t &qubits, + uint_t shots) { assert_initialized(); flush_ops(); @@ -1044,24 +1116,27 @@ std::vector AerState::sample_memory(const reg_t &qubits, uint_t sho std::vector ret; ret.reserve(shots); std::vector samples = state_->sample_measure(qubits, shots, rng_); - for (auto& sample : samples) { - ret.push_back(Utils::int2string(Utils::reg2int(sample, 2), 2, qubits.size())); + for (auto &sample : samples) { + ret.push_back( + Utils::int2string(Utils::reg2int(sample, 2), 2, qubits.size())); } return ret; } -std::unordered_map AerState::sample_counts(const reg_t &qubits, uint_t shots) { +std::unordered_map AerState::sample_counts(const reg_t &qubits, + uint_t shots) { assert_initialized(); flush_ops(); std::vector samples = state_->sample_measure(qubits, shots, rng_); std::unordered_map ret; - for(const auto & sample: samples) { + for (const auto &sample : samples) { uint_t sample_u = 0ULL; uint_t mask = 1ULL; - for (const auto b: sample) { - if (b) sample_u |= mask; + for (const auto b : sample) { + if (b) + sample_u |= mask; mask <<= 1; } if (ret.find(sample_u) == ret.end()) @@ -1075,7 +1150,7 @@ std::unordered_map AerState::sample_counts(const reg_t &qubits, //----------------------------------------------------------------------- // Operation management //----------------------------------------------------------------------- -void AerState::buffer_op(const Operations::Op&& op) { +void AerState::buffer_op(const Operations::Op &&op) { assert_initialized(); buffer_.ops.push_back(std::move(op)); }; @@ -1085,11 +1160,12 @@ void AerState::initialize_experiment_result() { last_result_.legacy_data.set_config(configs_); last_result_.set_config(configs_); last_result_.metadata.add(method_names_.at(method_), "method"); - if (method_ == Method::statevector || method_ == Method::density_matrix || method_ == Method::unitary) + if (method_ == Method::statevector || method_ == Method::density_matrix || + method_ == Method::unitary) last_result_.metadata.add(device_names_.at(device_), "device"); else last_result_.metadata.add("CPU", "device"); - + last_result_.metadata.add(num_of_qubits_, "num_qubits"); last_result_.header = buffer_.header; last_result_.shots = 1; @@ -1098,14 +1174,16 @@ void AerState::initialize_experiment_result() { }; void AerState::finalize_experiment_result(bool success, double time_taken) { - last_result_.status = success? ExperimentResult::Status::completed : ExperimentResult::Status::error; + last_result_.status = success ? ExperimentResult::Status::completed + : ExperimentResult::Status::error; last_result_.time_taken = time_taken; }; void AerState::flush_ops() { assert_initialized(); - if (buffer_.ops.empty()) return; + if (buffer_.ops.empty()) + return; auto timer_start = myclock_t::now(); @@ -1114,8 +1192,10 @@ void AerState::flush_ops() { buffer_.set_params(false); transpile_ops(); state_->apply_ops(buffer_.ops.begin(), buffer_.ops.end(), last_result_, rng_); - - finalize_experiment_result(true, std::chrono::duration(myclock_t::now() - timer_start).count()); + + finalize_experiment_result( + true, + std::chrono::duration(myclock_t::now() - timer_start).count()); clear_ops(); }; @@ -1126,7 +1206,7 @@ void AerState::clear_ops() { void AerState::transpile_ops() { fusion_pass_ = Transpile::Fusion(); - + fusion_pass_.set_parallelization(parallel_state_update_); if (buffer_.opset().contains(Operations::OpType::superop)) @@ -1163,11 +1243,14 @@ void AerState::transpile_ops() { } // Override default fusion settings with custom config fusion_pass_.set_config(configs_); - fusion_pass_.optimize_circuit(buffer_, noise_model_, state_->opset(), last_result_); - - //cache blocking - if(cache_block_pass_.enabled() && state_->multi_chunk_distribution_supported()){ - cache_block_pass_.optimize_circuit(buffer_, noise_model_, state_->opset(), last_result_); + fusion_pass_.optimize_circuit(buffer_, noise_model_, state_->opset(), + last_result_); + + // cache blocking + if (cache_block_pass_.enabled() && + state_->multi_chunk_distribution_supported()) { + cache_block_pass_.optimize_circuit(buffer_, noise_model_, state_->opset(), + last_result_); } } @@ -1175,5 +1258,3 @@ void AerState::transpile_ops() { } // end namespace AER //------------------------------------------------------------------------- #endif - - diff --git a/src/framework/avx2_detect.hpp b/src/framework/avx2_detect.hpp index 49f5d73955..2287782f38 100644 --- a/src/framework/avx2_detect.hpp +++ b/src/framework/avx2_detect.hpp @@ -16,63 +16,59 @@ #define _aer_controller_avx2_detect_hpp_ #include -#include #include +#include #include "misc/common_macros.hpp" #if defined(_MSC_VER) - #include +#include #elif defined(GNUC_AVX2) - #include +#include #endif - namespace { -inline void ccpuid(int cpu_info[4], int function_id){ +inline void ccpuid(int cpu_info[4], int function_id) { #if defined(_MSC_VER) __cpuid(cpu_info, function_id); #elif defined(GNUC_AVX2) - __cpuid(function_id, - cpu_info[0], - cpu_info[1], - cpu_info[2], - cpu_info[3]); + __cpuid(function_id, cpu_info[0], cpu_info[1], cpu_info[2], cpu_info[3]); #else // We don't support this platform intrinsics cpu_info[0] = cpu_info[1] = cpu_info[2] = cpu_info[3] = 0; #endif } -inline void cpuidex(int cpu_info[4], int function_id, int subfunction_id){ +inline void cpuidex(int cpu_info[4], int function_id, int subfunction_id) { #if defined(_MSC_VER) __cpuidex(cpu_info, function_id, subfunction_id); #elif defined(GNUC_AVX2) - __cpuid_count(function_id, subfunction_id, cpu_info[0], cpu_info[1], cpu_info[2], cpu_info[3]); + __cpuid_count(function_id, subfunction_id, cpu_info[0], cpu_info[1], + cpu_info[2], cpu_info[3]); #else // We don't support this platform intrinsics - cpu_info[0] = cpu_info[1] = cpu_info[2] = cpu_info[3] = 0; + cpu_info[0] = cpu_info[1] = cpu_info[2] = cpu_info[3] = 0; #endif } -} +} // namespace namespace AER { -inline bool is_avx2_supported(){ +inline bool is_avx2_supported() { #if defined(GNUC_AVX2) || defined(_MSC_VER) static bool cached = false; static bool is_supported = false; - if(cached) + if (cached) return is_supported; std::array cpui; ccpuid(cpui.data(), 0); auto num_ids = cpui[0]; - if(num_ids < 7){ + if (num_ids < 7) { cached = true; is_supported = false; return false; } std::vector> data; - for (int i = 0; i <= num_ids; ++i){ + for (int i = 0; i <= num_ids; ++i) { cpuidex(cpui.data(), i, 0); data.push_back(cpui); } @@ -87,11 +83,9 @@ inline bool is_avx2_supported(){ is_supported = is_fma_supported && is_avx2_supported; return is_supported; #else - return false; + return false; #endif } // end namespace AER -} +} // namespace AER #endif - - diff --git a/src/framework/blas_protos.hpp b/src/framework/blas_protos.hpp old mode 100755 new mode 100644 index d2803c66eb..dc17a25ac8 --- a/src/framework/blas_protos.hpp +++ b/src/framework/blas_protos.hpp @@ -19,10 +19,10 @@ #ifndef _aer_framework_blas_protos_hpp #define _aer_framework_blas_protos_hpp +#include #include #include #include -#include #ifdef __cplusplus extern "C" { @@ -79,45 +79,43 @@ void zgemm_(const char *TransA, const char *TransB, const size_t *M, const std::complex *beta, std::complex *C, size_t *ldc); -// Reduces a Single-Precison Complex Hermitian matrix A to real symmetric tridiagonal form -void chetrd_(char *TRANS, int *N, std::complex *A, - int *LDA, float *d, float *e, std::complex *tau, - std::complex *work, int *lwork, int *info); +// Reduces a Single-Precison Complex Hermitian matrix A to real symmetric +// tridiagonal form +void chetrd_(char *TRANS, int *N, std::complex *A, int *LDA, float *d, + float *e, std::complex *tau, std::complex *work, + int *lwork, int *info); -// Reduces a Double-Precison Complex Hermitian matrix A to real symmetric tridiagonal form T -void zhetrd_(char *TRANS, int *N, std::complex *A, - int *LDA, double *d, double *e, std::complex *tau, - std::complex *work, int *lwork, int *info); +// Reduces a Double-Precison Complex Hermitian matrix A to real symmetric +// tridiagonal form T +void zhetrd_(char *TRANS, int *N, std::complex *A, int *LDA, double *d, + double *e, std::complex *tau, std::complex *work, + int *lwork, int *info); // Computes all eigenvalues and, optionally, eigenvectors of a // Single-Precison Complex symmetric positive definite tridiagonal matrix -void cpteqr_(char* compz, int *n, float *d, float *e, - std::complex *z, int* ldz, - std::complex *work, int *info); +void cpteqr_(char *compz, int *n, float *d, float *e, std::complex *z, + int *ldz, std::complex *work, int *info); // Computes all eigenvalues and, optionally, eigenvectors of a // Double-Precison Complex symmetric positive definite tridiagonal matrix -void zpteqr_(char* compz, int *n, double *d, double *e, - std::complex *z, int* ldz, - std::complex *work, int *info); +void zpteqr_(char *compz, int *n, double *d, double *e, std::complex *z, + int *ldz, std::complex *work, int *info); // Computes selected eigenvalues and, optionally, eigenvectors // of a Single-Precison Complex Hermitian matrix A void cheevx_(char *jobz, char *range, char *uplo, int *n, - std::complex *a, int *lda, float *vl, - float *vu, int *il, int *iu, float *abstol, - int *m, float *w, std::complex *z, int *ldz, - std::complex *work, int *lwork, float *rwork, + std::complex *a, int *lda, float *vl, float *vu, int *il, + int *iu, float *abstol, int *m, float *w, std::complex *z, + int *ldz, std::complex *work, int *lwork, float *rwork, int *iwork, int *ifail, int *info); // Computes selected eigenvalues and, optionally, eigenvectors // of a Double-Precison Complex Hermitian matrix A void zheevx_(char *jobz, char *range, char *uplo, int *n, - std::complex *a, int *lda, double *vl, - double *vu, int *il, int *iu, double *abstol, - int *m, double *w, std::complex *z, int *ldz, - std::complex *work, int *lwork, double *rwork, - int *iwork, int *ifail, int *info); + std::complex *a, int *lda, double *vl, double *vu, int *il, + int *iu, double *abstol, int *m, double *w, + std::complex *z, int *ldz, std::complex *work, + int *lwork, double *rwork, int *iwork, int *ifail, int *info); // Determines Single-Precision machine parameters. float slamch_(char *cmach); diff --git a/src/framework/circuit.hpp b/src/framework/circuit.hpp old mode 100755 new mode 100644 index 3ad21966cd..0e8e577d8e --- a/src/framework/circuit.hpp +++ b/src/framework/circuit.hpp @@ -37,59 +37,62 @@ class Circuit { std::vector ops; // Circuit parameters updated by from ops by set_params - uint_t num_qubits = 0; // maximum number of qubits needed for ops - uint_t num_memory = 0; // maximum number of memory clbits needed for ops - uint_t num_registers = 0; // maximum number of registers clbits needed for ops - + uint_t num_qubits = 0; // maximum number of qubits needed for ops + uint_t num_memory = 0; // maximum number of memory clbits needed for ops + uint_t num_registers = 0; // maximum number of registers clbits needed for ops + // Measurement params - bool has_conditional = false; // True if any ops are conditional - bool can_sample = true; // True if circuit tail contains measure, roerror, barrier. - size_t first_measure_pos = 0; // Position of first measure instruction - bool can_sample_initialize = true; // True if circuit contains at most 1 initialize - // and it is the first instruction in the circuit + bool has_conditional = false; // True if any ops are conditional + bool can_sample = + true; // True if circuit tail contains measure, roerror, barrier. + size_t first_measure_pos = 0; // Position of first measure instruction + bool can_sample_initialize = + true; // True if circuit contains at most 1 initialize + // and it is the first instruction in the circuit // Circuit metadata constructed from json QobjExperiment uint_t shots = 1; uint_t seed; json_t header; double global_phase_angle = 0; - bool remapped_qubits = false; // True if qubits have been remapped + bool remapped_qubits = false; // True if qubits have been remapped // Constructor - // The constructor automatically calculates the num_qubits, num_memory, num_registers - // parameters by scanning the input list of ops. - Circuit() {set_random_seed();} + // The constructor automatically calculates the num_qubits, num_memory, + // num_registers parameters by scanning the input list of ops. + Circuit() { set_random_seed(); } Circuit(const std::vector &_ops, bool truncation = false); Circuit(std::vector &&_ops, bool truncation = false); // Construct a circuit from JSON - template - Circuit(const inputdata_t& circ, bool truncation = false); + template + Circuit(const inputdata_t &circ, bool truncation = false); - template - Circuit(const inputdata_t& circ, const json_t& qobj_config, bool truncation = false); + template + Circuit(const inputdata_t &circ, const json_t &qobj_config, + bool truncation = false); //----------------------------------------------------------------------- // Set containers //----------------------------------------------------------------------- // Return the opset for the circuit - inline const auto& opset() const {return opset_;} + inline const auto &opset() const { return opset_; } // Return the used qubits for the circuit - inline const auto& qubits() const {return qubitset_;} + inline const auto &qubits() const { return qubitset_; } // Return the used memory for the circuit - inline const auto& memory() const {return memoryset_;} + inline const auto &memory() const { return memoryset_; } // Return the used registers for the circuit - inline const auto& registers() const {return registerset_;} + inline const auto ®isters() const { return registerset_; } // Return the mapping of input op qubits to circuit qubits - inline const auto& qubit_map() const {return qubitmap_;} + inline const auto &qubit_map() const { return qubitmap_; } //----------------------------------------------------------------------- - // Utility methods + // Utility methods //----------------------------------------------------------------------- // Automatically set the number of qubits, memory, registers, and check @@ -101,7 +104,7 @@ class Circuit { void set_params(bool truncation = false); // Set the circuit rng seed to random value - inline void set_random_seed() {seed = std::random_device()();} + inline void set_random_seed() { seed = std::random_device()(); } private: Operations::OpSet opset_; // Set of operation types contained in circuit @@ -114,23 +117,21 @@ class Circuit { std::unordered_map qubitmap_; // Add type, qubit, memory, conditional metadata information from op - void add_op_metadata(const Op& op); + void add_op_metadata(const Op &op); // Reset circuit metadata void reset_metadata(); // Helper function for optimized set params - bool check_result_ancestor(const Op& op, - std::unordered_set& ancestor_qubits) const; - + bool check_result_ancestor(const Op &op, + std::unordered_set &ancestor_qubits) const; + // Helper function for optimized set params - void remap_qubits(Op& op) const; + void remap_qubits(Op &op) const; }; - // Json conversion function -inline void from_json(const json_t& js, Circuit &circ) {circ = Circuit(js);} - +inline void from_json(const json_t &js, Circuit &circ) { circ = Circuit(js); } //============================================================================ // Implementation: Circuit methods @@ -146,11 +147,14 @@ Circuit::Circuit(std::vector &&_ops, bool truncation) : Circuit() { set_params(truncation); } -template -Circuit::Circuit(const inputdata_t &circ, bool truncation) : Circuit(circ, json_t(), truncation) {} +template +Circuit::Circuit(const inputdata_t &circ, bool truncation) + : Circuit(circ, json_t(), truncation) {} -template -Circuit::Circuit(const inputdata_t &circ, const json_t &qobj_config, bool truncation) : Circuit() { +template +Circuit::Circuit(const inputdata_t &circ, const json_t &qobj_config, + bool truncation) + : Circuit() { // Get config json_t config = qobj_config; if (Parser::check_key("config", circ)) { @@ -160,7 +164,7 @@ Circuit::Circuit(const inputdata_t &circ, const json_t &qobj_config, bool trunca config[it.key()] = it.value(); // overwrite circuit level config values } } - + // Load metadata Parser::get_value(header, "header", circ); Parser::get_value(shots, "shots", config); @@ -168,16 +172,17 @@ Circuit::Circuit(const inputdata_t &circ, const json_t &qobj_config, bool trunca // Load instructions if (Parser::check_key("instructions", circ) == false) { - throw std::invalid_argument("Invalid Qobj experiment: no \"instructions\" field."); + throw std::invalid_argument( + "Invalid Qobj experiment: no \"instructions\" field."); } const auto input_ops = Parser::get_list("instructions", circ); - + // Convert to Ops - // TODO: If parser could support reverse iteration through the list of ops without - // conversion we could call `get_reversed_ops` on the inputdata without first - // converting. + // TODO: If parser could support reverse iteration through the list of ops + // without conversion we could call `get_reversed_ops` on the inputdata + // without first converting. std::vector converted_ops; - for(auto the_op: input_ops){ + for (auto the_op : input_ops) { converted_ops.emplace_back(Operations::input_to_op(the_op)); } ops = std::move(converted_ops); @@ -187,7 +192,8 @@ Circuit::Circuit(const inputdata_t &circ, const json_t &qobj_config, bool trunca uint_t memory_slots = 0; Parser::get_value(memory_slots, "memory_slots", config); if (memory_slots < num_memory) { - throw std::invalid_argument("Invalid Qobj experiment: not enough memory slots."); + throw std::invalid_argument( + "Invalid Qobj experiment: not enough memory slots."); } // override memory slot number num_memory = memory_slots; @@ -198,7 +204,8 @@ Circuit::Circuit(const inputdata_t &circ, const json_t &qobj_config, bool trunca uint_t n_qubits; Parser::get_value(n_qubits, "n_qubits", config); if (n_qubits < num_qubits) { - throw std::invalid_argument("Invalid Qobj experiment: n_qubits < instruction qubits."); + throw std::invalid_argument( + "Invalid Qobj experiment: n_qubits < instruction qubits."); } if (!truncation) { // Override minimal circuit qubit number with qobj number if truncation @@ -224,14 +231,14 @@ void Circuit::reset_metadata() { num_qubits = 0; num_memory = 0; num_registers = 0; - + has_conditional = false; can_sample = true; first_measure_pos = 0; can_sample_initialize = true; } -void Circuit::add_op_metadata(const Op& op) { +void Circuit::add_op_metadata(const Op &op) { has_conditional |= op.conditional; opset_.insert(op); qubitset_.insert(op.qubits.begin(), op.qubits.end()); @@ -248,11 +255,11 @@ void Circuit::add_op_metadata(const Op& op) { } } - void Circuit::set_params(bool truncation) { - // Clear current circuit metadata + // Clear current circuit metadata reset_metadata(); - if (ops.empty()) return; + if (ops.empty()) + return; // Analyze input ops from tail to head to get locations of ancestor, // first measurement position and last initialize position @@ -266,11 +273,11 @@ void Circuit::set_params(bool truncation) { bool ops_to_remove = false; std::unordered_set ancestor_qubits; - for (size_t i = 0; i < size; ++ i) { + for (size_t i = 0; i < size; ++i) { const size_t rpos = size - i - 1; - const auto& op = ops[rpos]; + const auto &op = ops[rpos]; if (op.type == OpType::mark && last_ancestor_pos == 0) - last_ancestor_pos = rpos; + last_ancestor_pos = rpos; if (!truncation || check_result_ancestor(op, ancestor_qubits)) { add_op_metadata(op); ancestor[rpos] = true; @@ -284,7 +291,7 @@ void Circuit::set_params(bool truncation) { if (last_ancestor_pos == 0) { last_ancestor_pos = rpos; } - } else if (truncation && !ops_to_remove){ + } else if (truncation && !ops_to_remove) { ops_to_remove = true; } } @@ -294,7 +301,7 @@ void Circuit::set_params(bool truncation) { if (truncation) { // Generate mapping of original qubits to ancestor set uint_t idx = 0; - for (const auto& qubit: qubitset_) { + for (const auto &qubit : qubitset_) { if (!remapped_qubits && idx != qubit) { // qubits will be remapped remapped_qubits = true; @@ -333,48 +340,47 @@ void Circuit::set_params(bool truncation) { continue; } - const auto& op = ops[pos]; + const auto &op = ops[pos]; if (op.conditional) { can_sample = false; break; } switch (op.type) { - case OpType::measure: - case OpType::roerror: { - meas_qubits.insert(op.qubits.begin(), op.qubits.end()); - tail_meas_ops.push_back(op); - break; - } - case OpType::snapshot: - case OpType::save_state: - case OpType::save_expval: - case OpType::save_expval_var: - case OpType::save_statevec: - case OpType::save_statevec_dict: - case OpType::save_densmat: - case OpType::save_probs: - case OpType::save_probs_ket: - case OpType::save_amps: - case OpType::save_amps_sq: - case OpType::save_stabilizer: - case OpType::save_clifford: - case OpType::save_unitary: - case OpType::save_mps: - case OpType::save_superop: - { - can_sample = false; - break; - } - default: { - for (const auto &qubit : op.qubits) { - if (meas_qubits.find(qubit) != meas_qubits.end()) { - can_sample = false; - break; - } + case OpType::measure: + case OpType::roerror: { + meas_qubits.insert(op.qubits.begin(), op.qubits.end()); + tail_meas_ops.push_back(op); + break; + } + case OpType::snapshot: + case OpType::save_state: + case OpType::save_expval: + case OpType::save_expval_var: + case OpType::save_statevec: + case OpType::save_statevec_dict: + case OpType::save_densmat: + case OpType::save_probs: + case OpType::save_probs_ket: + case OpType::save_amps: + case OpType::save_amps_sq: + case OpType::save_stabilizer: + case OpType::save_clifford: + case OpType::save_unitary: + case OpType::save_mps: + case OpType::save_superop: { + can_sample = false; + break; + } + default: { + for (const auto &qubit : op.qubits) { + if (meas_qubits.find(qubit) != meas_qubits.end()) { + can_sample = false; + break; } - tail_pos.push_back(pos); } + tail_pos.push_back(pos); + } } if (!can_sample) { break; @@ -393,7 +399,8 @@ void Circuit::set_params(bool truncation) { head_end = last_ancestor_pos + 1; } for (size_t pos = 0; pos < head_end; ++pos) { - if (ops_to_remove && !ancestor[pos] && ops[pos].type != OpType::mark && ops[pos].type != OpType::jump) { + if (ops_to_remove && !ancestor[pos] && ops[pos].type != OpType::mark && + ops[pos].type != OpType::jump) { // Skip if not ancestor continue; } @@ -406,10 +413,11 @@ void Circuit::set_params(bool truncation) { if (ops[op_idx].type == OpType::jump) { dests.insert(ops[op_idx].string_params[0]); } else if (ops[op_idx].type == OpType::mark) { - auto& mark_name = ops[op_idx].string_params[0]; + auto &mark_name = ops[op_idx].string_params[0]; if (marks.find(mark_name) != marks.end()) { std::stringstream msg; - msg << "Duplicated mark destination:\"" << mark_name << "\"." << std::endl; + msg << "Duplicated mark destination:\"" << mark_name << "\"." + << std::endl; throw std::runtime_error(msg.str()); } marks.insert(mark_name); @@ -435,7 +443,7 @@ void Circuit::set_params(bool truncation) { if (!ops_to_remove && !ancestor[tpos]) { continue; } - auto& op = ops[tpos]; + auto &op = ops[tpos]; if (remapped_qubits) { remap_qubits(ops[tpos]); } @@ -446,7 +454,7 @@ void Circuit::set_params(bool truncation) { } // Now add remaining delayed measure ops first_measure_pos = op_idx; - for (auto & op : tail_meas_ops) { + for (auto &op : tail_meas_ops) { if (remapped_qubits) { remap_qubits(op); } @@ -461,56 +469,55 @@ void Circuit::set_params(bool truncation) { ops.resize(op_idx); } - -void Circuit::remap_qubits(Op& op) const { +void Circuit::remap_qubits(Op &op) const { reg_t new_qubits; - for (auto& qubit : op.qubits) { + for (auto &qubit : op.qubits) { new_qubits.push_back(qubitmap_.at(qubit)); } op.qubits = std::move(new_qubits); } - -bool Circuit::check_result_ancestor(const Op& op, std::unordered_set& ancestor_qubits) const { +bool Circuit::check_result_ancestor( + const Op &op, std::unordered_set &ancestor_qubits) const { switch (op.type) { - case OpType::barrier: - case OpType::nop: { - return false; - } - case OpType::bfunc: { - return true; - } - // Result generating types - case OpType::measure: - case OpType::roerror: - case OpType::snapshot: - case OpType::save_state: - case OpType::save_expval: - case OpType::save_expval_var: - case OpType::save_statevec: - case OpType::save_statevec_dict: - case OpType::save_densmat: - case OpType::save_probs: - case OpType::save_probs_ket: - case OpType::save_amps: - case OpType::save_amps_sq: - case OpType::save_stabilizer: - case OpType::save_clifford: - case OpType::save_unitary: - case OpType::save_mps: - case OpType::save_superop: { - ancestor_qubits.insert(op.qubits.begin(), op.qubits.end()); - return true; - } - default: { - for (const auto& qubit : op.qubits) { - if (ancestor_qubits.find(qubit) != ancestor_qubits.end()) { - ancestor_qubits.insert(op.qubits.begin(), op.qubits.end()); - return true; - } + case OpType::barrier: + case OpType::nop: { + return false; + } + case OpType::bfunc: { + return true; + } + // Result generating types + case OpType::measure: + case OpType::roerror: + case OpType::snapshot: + case OpType::save_state: + case OpType::save_expval: + case OpType::save_expval_var: + case OpType::save_statevec: + case OpType::save_statevec_dict: + case OpType::save_densmat: + case OpType::save_probs: + case OpType::save_probs_ket: + case OpType::save_amps: + case OpType::save_amps_sq: + case OpType::save_stabilizer: + case OpType::save_clifford: + case OpType::save_unitary: + case OpType::save_mps: + case OpType::save_superop: { + ancestor_qubits.insert(op.qubits.begin(), op.qubits.end()); + return true; + } + default: { + for (const auto &qubit : op.qubits) { + if (ancestor_qubits.find(qubit) != ancestor_qubits.end()) { + ancestor_qubits.insert(op.qubits.begin(), op.qubits.end()); + return true; } - return false; } + return false; + } } } diff --git a/src/framework/creg.hpp b/src/framework/creg.hpp old mode 100755 new mode 100644 index 2a79a0e871..1a0d012865 --- a/src/framework/creg.hpp +++ b/src/framework/creg.hpp @@ -16,8 +16,8 @@ #define _aer_framework_creg_hpp_ #include "framework/operations.hpp" -#include "framework/utils.hpp" #include "framework/rng.hpp" +#include "framework/utils.hpp" namespace AER { @@ -29,39 +29,39 @@ namespace AER { class ClassicalRegister { public: - // Return the current value of the memory as little-endian hex-string - inline std::string memory_hex() const {return Utils::bin2hex(creg_memory_);} + inline std::string memory_hex() const { return Utils::bin2hex(creg_memory_); } // Return the current value of the memory as little-endian bit-string - inline std::string memory_bin() const {return "0b" + creg_memory_;} + inline std::string memory_bin() const { return "0b" + creg_memory_; } // Return the current value of the memory as little-endian hex-string - inline std::string register_hex() const {return Utils::bin2hex(creg_register_);} + inline std::string register_hex() const { + return Utils::bin2hex(creg_register_); + } // Return the current value of the memory as little-endian bit-string - inline std::string register_bin() const {return "0b" + creg_register_;} + inline std::string register_bin() const { return "0b" + creg_register_; } // Return the size of the memory bits - size_t memory_size() const {return creg_memory_.size();} + size_t memory_size() const { return creg_memory_.size(); } // Return the size of the register bits - size_t register_size() const {return creg_register_.size();} + size_t register_size() const { return creg_register_.size(); } // Return a reference to the current value of the memory // this is a bit-string without the "0b" prefix. - inline auto& creg_memory() {return creg_memory_;} + inline auto &creg_memory() { return creg_memory_; } // Return a reference to the current value of the memory // this is a bit-string without the "0b" prefix. - inline auto& creg_register() {return creg_register_;} + inline auto &creg_register() { return creg_register_; } // Initialize the memory and register bits to default values (all 0) void initialize(size_t num_memory, size_t num_registers); // Initialize the memory and register bits to specific values - void initialize(size_t num_memory, - size_t num_registers, + void initialize(size_t num_memory, size_t num_registers, const std::string &memory_hex, const std::string ®ister_hex); @@ -76,17 +76,18 @@ class ClassicalRegister { // Apply readout error instruction to classical registers void apply_roerror(const Operations::Op &op, RngEngine &rng); - // Store a measurement outcome in the specified memory and register bit locations - void store_measure(const reg_t &outcome, const reg_t &memory, const reg_t ®isters); + // Store a measurement outcome in the specified memory and register bit + // locations + void store_measure(const reg_t &outcome, const reg_t &memory, + const reg_t ®isters); protected: - // Classical registers std::string creg_memory_; // standard classical bit memory std::string creg_register_; // optional classical bit register // Measurement config settings - bool return_hex_strings_ = true; // Set to false for bit-string output + bool return_hex_strings_ = true; // Set to false for bit-string output }; //============================================================================ @@ -99,9 +100,7 @@ void ClassicalRegister::initialize(size_t num_memory, size_t num_register) { creg_register_ = std::string(num_register, '0'); } - -void ClassicalRegister::initialize(size_t num_memory, - size_t num_register, +void ClassicalRegister::initialize(size_t num_memory, size_t num_register, const std::string &memory_hex, const std::string ®ister_hex) { // Convert to bit-string for internal storage @@ -109,74 +108,77 @@ void ClassicalRegister::initialize(size_t num_memory, creg_memory_ = std::move(Utils::padleft_inplace(memory_bin, '0', num_memory)); std::string register_bin = Utils::hex2bin(register_hex, false); - creg_register_ = std::move(Utils::padleft_inplace(memory_bin, '0', num_register)); + creg_register_ = + std::move(Utils::padleft_inplace(memory_bin, '0', num_register)); } - -void ClassicalRegister::store_measure(const reg_t &outcome, - const reg_t &memory, +void ClassicalRegister::store_measure(const reg_t &outcome, const reg_t &memory, const reg_t ®isters) { // Assumes memory and registers are either empty or same size as outcome! bool use_mem = !memory.empty(); bool use_reg = !registers.empty(); - for (size_t j=0; j < outcome.size(); j++) { + for (size_t j = 0; j < outcome.size(); j++) { if (use_mem) { // least significant bit first ordering - const size_t pos = creg_memory_.size() - memory[j] - 1; + const size_t pos = creg_memory_.size() - memory[j] - 1; creg_memory_[pos] = std::to_string(outcome[j])[0]; // int->string->char } if (use_reg) { // least significant bit first ordering - const size_t pos = creg_register_.size() - registers[j] - 1; - creg_register_[pos] = std::to_string(outcome[j])[0]; // int->string->char + const size_t pos = creg_register_.size() - registers[j] - 1; + creg_register_[pos] = std::to_string(outcome[j])[0]; // int->string->char } } } - bool ClassicalRegister::check_conditional(const Operations::Op &op) const { // Check if op is conditional if (op.conditional) - return (creg_register_[creg_register_.size() - op.conditional_reg - 1] == '1'); + return (creg_register_[creg_register_.size() - op.conditional_reg - 1] == + '1'); // Op is not conditional return true; } - void ClassicalRegister::apply_bfunc(const Operations::Op &op) { // Check input is boolean function op if (op.type != Operations::OpType::bfunc) { - throw std::invalid_argument("ClassicalRegister::apply_bfunc: Input is not a bfunc op."); + throw std::invalid_argument( + "ClassicalRegister::apply_bfunc: Input is not a bfunc op."); } const std::string &mask = op.string_params[0]; const std::string &target_val = op.string_params[1]; - int_t compared; // if equal this should be 0, if less than -1, if greater than +1 + int_t compared; // if equal this should be 0, if less than -1, if greater than + // +1 // Check if register size fits into a 64-bit integer if (creg_register_.size() <= 64) { - uint_t reg_int = std::stoull(creg_register_, nullptr, 2); // stored as bitstring + uint_t reg_int = + std::stoull(creg_register_, nullptr, 2); // stored as bitstring uint_t mask_int = std::stoull(mask, nullptr, 16); // stored as hexstring - uint_t target_int = std::stoull(target_val, nullptr, 16); // stored as hexstring + uint_t target_int = + std::stoull(target_val, nullptr, 16); // stored as hexstring compared = (reg_int & mask_int) - target_int; } else { - // We need to use big ints so we implement the bit-mask via the binary string - // representation rather than using a big integer class + // We need to use big ints so we implement the bit-mask via the binary + // string representation rather than using a big integer class std::string mask_bin = Utils::hex2bin(mask, false); size_t length = std::min(mask_bin.size(), creg_register_.size()); std::string masked_val = std::string(length, '0'); for (size_t rev_pos = 0; rev_pos < length; rev_pos++) { - masked_val[length - 1 - rev_pos] = (mask_bin[mask_bin.size() - 1 - rev_pos] - & creg_register_[creg_register_.size() - 1 - rev_pos]); + masked_val[length - 1 - rev_pos] = + (mask_bin[mask_bin.size() - 1 - rev_pos] & + creg_register_[creg_register_.size() - 1 - rev_pos]); } // remove leading 0's size_t end_i = masked_val.find('1'); if (end_i == std::string::npos) - masked_val = "0"; + masked_val = "0"; else - masked_val.erase(0, end_i); + masked_val.erase(0, end_i); masked_val = Utils::bin2hex(masked_val); // convert to hex string // Using string comparison to compare to target value @@ -185,51 +187,53 @@ void ClassicalRegister::apply_bfunc(const Operations::Op &op) { // check value of compared integer for different comparison operations bool outcome; switch (op.bfunc) { - case Operations::RegComparison::Equal: - outcome = (compared == 0); - break; - case Operations::RegComparison::NotEqual: - outcome = (compared != 0); - break; - case Operations::RegComparison::Less: - outcome = (compared < 0); - break; - case Operations::RegComparison::LessEqual: - outcome = (compared <= 0); - break; - case Operations::RegComparison::Greater: - outcome = (compared > 0); - break; - case Operations::RegComparison::GreaterEqual: - outcome = (compared >= 0); - break; - default: - // we shouldn't ever get here - throw std::invalid_argument("Invalid boolean function relation."); + case Operations::RegComparison::Equal: + outcome = (compared == 0); + break; + case Operations::RegComparison::NotEqual: + outcome = (compared != 0); + break; + case Operations::RegComparison::Less: + outcome = (compared < 0); + break; + case Operations::RegComparison::LessEqual: + outcome = (compared <= 0); + break; + case Operations::RegComparison::Greater: + outcome = (compared > 0); + break; + case Operations::RegComparison::GreaterEqual: + outcome = (compared >= 0); + break; + default: + // we shouldn't ever get here + throw std::invalid_argument("Invalid boolean function relation."); } // Store outcome in register if (op.registers.size() > 0) { - const size_t pos = creg_register_.size() - op.registers[0] - 1; + const size_t pos = creg_register_.size() - op.registers[0] - 1; creg_register_[pos] = (outcome) ? '1' : '0'; } // Optionally store outcome in memory if (op.memory.size() > 0) { - const size_t pos = creg_memory_.size() - op.memory[0] - 1; + const size_t pos = creg_memory_.size() - op.memory[0] - 1; creg_memory_[pos] = (outcome) ? '1' : '0'; } } // Apply readout error instruction to classical registers -void ClassicalRegister::apply_roerror(const Operations::Op &op, RngEngine &rng) { - +void ClassicalRegister::apply_roerror(const Operations::Op &op, + RngEngine &rng) { + // Check input is readout error op if (op.type != Operations::OpType::roerror) { - throw std::invalid_argument("ClassicalRegister::apply_roerror Input is not a readout error op."); + throw std::invalid_argument( + "ClassicalRegister::apply_roerror Input is not a readout error op."); } - + // Get current classical bit (and optionally register bit) values std::string mem_str; - + // Get values of bits as binary string // We iterate from the end of the list of memory bits for (auto it = op.memory.rbegin(); it < op.memory.rend(); ++it) { @@ -241,12 +245,14 @@ void ClassicalRegister::apply_roerror(const Operations::Op &op, RngEngine &rng) auto noise_str = Utils::int2string(outcome, 2, op.memory.size()); for (size_t pos = 0; pos < op.memory.size(); ++pos) { auto bit = op.memory[pos]; - creg_memory_[creg_memory_.size() - 1 - bit] = noise_str[noise_str.size() - 1 - pos]; + creg_memory_[creg_memory_.size() - 1 - bit] = + noise_str[noise_str.size() - 1 - pos]; } // and the same error to register classical bits if they are used for (size_t pos = 0; pos < op.registers.size(); ++pos) { auto bit = op.registers[pos]; - creg_register_[creg_register_.size() - 1 - bit] = noise_str[noise_str.size() - 1 - pos]; + creg_register_[creg_register_.size() - 1 - bit] = + noise_str[noise_str.size() - 1 - pos]; } } diff --git a/src/framework/json.hpp b/src/framework/json.hpp old mode 100755 new mode 100644 index 945a0aee01..7e5a7e70c2 --- a/src/framework/json.hpp +++ b/src/framework/json.hpp @@ -47,7 +47,7 @@ namespace JSON { * @param name: file name to load. * @returns: the loaded json. */ -inline json_t load(const std::string& name); +inline json_t load(const std::string &name); /** * Check if a key exists in a json_t object. @@ -55,7 +55,7 @@ inline json_t load(const std::string& name); * @param js: the json_t to search for key. * @returns: true if the key exists, false otherwise. */ -inline bool check_key(const std::string& key, const json_t &js); +inline bool check_key(const std::string &key, const json_t &js); /** * Check if all keys exists in a json_t object. @@ -63,7 +63,7 @@ inline bool check_key(const std::string& key, const json_t &js); * @param js: the json_t to search for keys. * @returns: true if all keys exists, false otherwise. */ -inline bool check_keys(const std::vector& keys, const json_t &js); +inline bool check_keys(const std::vector &keys, const json_t &js); /** * Load a json_t object value into a variable if the key name exists. @@ -72,9 +72,10 @@ inline bool check_keys(const std::vector& keys, const json_t &js); * @param js: the json_t to search for key. * @returns: true if the keys exists and val was set, false otherwise. */ -template bool get_value(T &var, const std::string& key, const json_t &js); +template +bool get_value(T &var, const std::string &key, const json_t &js); -const json_t& get_value(const std::string& key, const json_t &js); +const json_t &get_value(const std::string &key, const json_t &js); } // end namespace JSON @@ -140,10 +141,8 @@ void to_json(json_t &js, const std::map &map); * @param js a json_t object to contain converted type. * @param mat a matrix to convert. */ -template -void from_json(const json_t &js, matrix &mat); -template -void to_json(json_t &js, const matrix &mat); +template void from_json(const json_t &js, matrix &mat); +template void to_json(json_t &js, const matrix &mat); /******************************************************************************* * @@ -155,7 +154,7 @@ void to_json(json_t &js, const matrix &mat); // JSON Helper Functions //------------------------------------------------------------------------------ -json_t JSON::load(const std::string& name) { +json_t JSON::load(const std::string &name) { if (name == "") { json_t js; return js; // Return empty node if no config file @@ -176,7 +175,7 @@ json_t JSON::load(const std::string& name) { return js; } -bool JSON::check_key(const std::string& key, const json_t &js) { +bool JSON::check_key(const std::string &key, const json_t &js) { // returns false if the value is 'null' if (js.find(key) != js.end() && !js[key].is_null()) return true; @@ -184,15 +183,15 @@ bool JSON::check_key(const std::string& key, const json_t &js) { return false; } -bool JSON::check_keys(const std::vector& keys, const json_t &js) { +bool JSON::check_keys(const std::vector &keys, const json_t &js) { bool pass = true; - for (const auto& s : keys) + for (const auto &s : keys) pass &= check_key(s, js); return pass; } template -bool JSON::get_value(T &var, const std::string& key, const json_t &js) { +bool JSON::get_value(T &var, const std::string &key, const json_t &js) { if (check_key(key, js)) { var = js[key].get(); return true; @@ -201,8 +200,8 @@ bool JSON::get_value(T &var, const std::string& key, const json_t &js) { } } -const json_t& JSON::get_value(const std::string& key, const json_t &js){ - return js[key]; +const json_t &JSON::get_value(const std::string &key, const json_t &js) { + return js[key]; } //------------------------------------------------------------------------------ @@ -221,8 +220,7 @@ void std::from_json(const json_t &js, std::complex &z) { else if (js.is_array() && js.size() == 2) { z = std::complex{js[0].get(), js[1].get()}; } else { - throw std::invalid_argument( - std::string("JSON: invalid complex number")); + throw std::invalid_argument(std::string("JSON: invalid complex number")); } } @@ -236,16 +234,15 @@ void std::to_json(json_t &js, const std::vector> &vec) { } template -void std::from_json(const json_t &js, std::vector> &vec) { +void std::from_json(const json_t &js, + std::vector> &vec) { std::vector> ret; if (js.is_array()) { for (auto &elt : js) ret.push_back(elt); vec = ret; - } - else { - throw std::invalid_argument( - std::string("JSON: invalid complex vector.")); + } else { + throw std::invalid_argument(std::string("JSON: invalid complex vector.")); } } @@ -286,15 +283,14 @@ template void to_json(json_t &js, const matrix &mat) { } } - template void from_json(const json_t &js, matrix &mat) { // Check JSON is an array - if(!js.is_array()) { + if (!js.is_array()) { throw std::invalid_argument( std::string("JSON: invalid matrix (not array).")); } // Check JSON isn't empty - if(js.empty()) { + if (js.empty()) { throw std::invalid_argument( std::string("JSON: invalid matrix (empty array).")); } @@ -305,7 +301,7 @@ template void from_json(const json_t &js, matrix &mat) { size_t nrows = js.size(); for (auto &row : js) rows_valid &= (row.is_array() && row.size() == ncols); - if(!rows_valid) { + if (!rows_valid) { throw std::invalid_argument( std::string("JSON: invalid matrix (rows different sizes).")); } diff --git a/src/framework/json_parser.hpp b/src/framework/json_parser.hpp index 882af3efe0..68a265536d 100644 --- a/src/framework/json_parser.hpp +++ b/src/framework/json_parser.hpp @@ -17,72 +17,65 @@ #include "json.hpp" - -namespace AER{ +namespace AER { // This structure is to avoid overload resolving to the wron function, // as py::objects can always be implicitly converted to json, though // can break at runtime, or even worse trasnform to json and then to c++ // without notice. -template -struct Parser {}; +template struct Parser {}; -template <> -struct Parser { - Parser() = delete; +template <> struct Parser { + Parser() = delete; - template - static bool get_value(T &var, const std::string& key, const json_t &js){ - return JSON::get_value(var, key, js); - } + template + static bool get_value(T &var, const std::string &key, const json_t &js) { + return JSON::get_value(var, key, js); + } - static bool check_key(const std::string& key, const json_t &js){ - return JSON::check_key(key, js); - } + static bool check_key(const std::string &key, const json_t &js) { + return JSON::check_key(key, js); + } - static const json_t& get_value(const std::string& key, const json_t &js){ - return JSON::get_value(key, js); - } + static const json_t &get_value(const std::string &key, const json_t &js) { + return JSON::get_value(key, js); + } - static bool check_keys(const std::vector& keys, const json_t &js) { - return JSON::check_keys(keys, js); - } + static bool check_keys(const std::vector &keys, + const json_t &js) { + return JSON::check_keys(keys, js); + } - static bool is_array(const json_t &js){ - return js.is_array(); - } + static bool is_array(const json_t &js) { return js.is_array(); } - static bool is_array(const std::string& key, const json_t &js){ - return js[key].is_array(); - } + static bool is_array(const std::string &key, const json_t &js) { + return js[key].is_array(); + } - static const json_t& get_as_list(const json_t& js){ - if(!is_array(js)){ - throw std::runtime_error("Object is not a list!"); - } - return js; + static const json_t &get_as_list(const json_t &js) { + if (!is_array(js)) { + throw std::runtime_error("Object is not a list!"); } + return js; + } - static const json_t& get_list(const std::string& key, const json_t &js){ - if(!is_array(key, js)){ - throw std::runtime_error("Object " + key + "is not a list!"); - } - return JSON::get_value(key, js); + static const json_t &get_list(const std::string &key, const json_t &js) { + if (!is_array(key, js)) { + throw std::runtime_error("Object " + key + "is not a list!"); } + return JSON::get_value(key, js); + } + static bool is_number(const std::string &key, const json_t &js) { + return js[key].is_number(); + } - static bool is_number(const std::string& key, const json_t &js){ - return js[key].is_number(); - } + static std::string dump(const json_t &js) { return js.dump(); } - static std::string dump(const json_t& js){ - return js.dump(); - } - - template - static T get_list_elem(const json_t& js, unsigned int i){ - return js[i]; - } + template + static T get_list_elem(const json_t &js, unsigned int i) { + return js[i]; + } }; -} +} // namespace AER #endif // _aer_framework_json_parser_hpp_ diff --git a/src/framework/linalg/almost_equal.hpp b/src/framework/linalg/almost_equal.hpp old mode 100755 new mode 100644 index 387cd9d3bc..f4a645d455 --- a/src/framework/linalg/almost_equal.hpp +++ b/src/framework/linalg/almost_equal.hpp @@ -29,27 +29,28 @@ namespace Linalg { // If we have numbers closer to 0, then max_diff can be set to a value // way smaller than epsilon. For numbers larger than 1.0, epsilon will // scale (the bigger the number, the bigger the epsilon). -template ::value, T>::type > -bool almost_equal(T f1, T f2, - T max_diff = std::numeric_limits::epsilon(), +template ::value, T>::type> +bool almost_equal(T f1, T f2, T max_diff = std::numeric_limits::epsilon(), T max_relative_diff = std::numeric_limits::epsilon()) { - T diff = std::abs(f1 - f2); - if (diff <= max_diff) return true; + T diff = std::abs(f1 - f2); + if (diff <= max_diff) + return true; - return diff <= max_relative_diff * std::max(std::abs(f1), std::abs(f2)); + return diff <= max_relative_diff * std::max(std::abs(f1), std::abs(f2)); } template -bool almost_equal(const std::complex& f1, const std::complex& f2, +bool almost_equal(const std::complex &f1, const std::complex &f2, T max_diff = std::numeric_limits::epsilon(), T max_relative_diff = std::numeric_limits::epsilon()) { - return almost_equal(f1.real(), f2.real(), max_diff, max_relative_diff) - && almost_equal(f1.imag(), f2.imag(), max_diff, max_relative_diff); + return almost_equal(f1.real(), f2.real(), max_diff, max_relative_diff) && + almost_equal(f1.imag(), f2.imag(), max_diff, max_relative_diff); } //------------------------------------------------------------------------------ -} // namespace Linalg +} // namespace Linalg //------------------------------------------------------------------------------ -} // end namespace AER +} // end namespace AER //------------------------------------------------------------------------------ #endif diff --git a/src/framework/linalg/eigensystem.hpp b/src/framework/linalg/eigensystem.hpp index da0cc10d58..5559006ea1 100644 --- a/src/framework/linalg/eigensystem.hpp +++ b/src/framework/linalg/eigensystem.hpp @@ -15,66 +15,62 @@ #ifndef _aer_framework_linalg_eigensystem_hpp_ #define _aer_framework_linalg_eigensystem_hpp_ -#include #include "framework/blas_protos.hpp" #include "framework/matrix.hpp" - +#include /** * Returns the eigenvalues and eigenvectors * of a Hermitian matrix. * Uses the blas function ?heevx * @param hermitian_matrix: The Hermitian matrix. - * @param eigenvalues: On output: vector with the eignevalues of the matrix (input is overwritten) - * @param eigenvectors: On output: matrix with the eigenvectors stored as columns. + * @param eigenvalues: On output: vector with the eignevalues of the matrix + * (input is overwritten) + * @param eigenvectors: On output: matrix with the eigenvectors stored as + * columns. * * @returns: void */ template -void eigensystem_hermitian(const matrix>& hermitian_matrix, - /* out */ std::vector& eigenvalues, - /* out */ matrix>& eigenvectors); +void eigensystem_hermitian(const matrix> &hermitian_matrix, + /* out */ std::vector &eigenvalues, + /* out */ matrix> &eigenvectors); +template struct HeevxFuncs; -template -struct HeevxFuncs; - -template<> -struct HeevxFuncs{ +template <> struct HeevxFuncs { HeevxFuncs() = delete; - static decltype(zheevx_)& heevx; - static decltype(dlamch_)& lamch; + static decltype(zheevx_) &heevx; + static decltype(dlamch_) &lamch; }; -decltype(zheevx_)& HeevxFuncs::heevx = zheevx_; -decltype(dlamch_)& HeevxFuncs::lamch = dlamch_; +decltype(zheevx_) &HeevxFuncs::heevx = zheevx_; +decltype(dlamch_) &HeevxFuncs::lamch = dlamch_; -template<> -struct HeevxFuncs{ +template <> struct HeevxFuncs { HeevxFuncs() = delete; - static decltype(cheevx_)& heevx; - static decltype(slamch_)& lamch; + static decltype(cheevx_) &heevx; + static decltype(slamch_) &lamch; }; -decltype(cheevx_)& HeevxFuncs::heevx = cheevx_; -decltype(slamch_)& HeevxFuncs::lamch = slamch_; - +decltype(cheevx_) &HeevxFuncs::heevx = cheevx_; +decltype(slamch_) &HeevxFuncs::lamch = slamch_; template -void eigensystem_hermitian(const matrix>& hermitian_matrix, - std::vector& eigenvalues, - matrix>& eigenvectors) { - if ( hermitian_matrix.GetRows() != hermitian_matrix.GetColumns() ) { +void eigensystem_hermitian(const matrix> &hermitian_matrix, + std::vector &eigenvalues, + matrix> &eigenvectors) { + if (hermitian_matrix.GetRows() != hermitian_matrix.GetColumns()) { throw std::runtime_error("Input matrix in eigensystem_hermitian " "function is not a square matrix."); } int n = static_cast(hermitian_matrix.GetLD()); - int ldz{n}, lda{n}, lwork{2*n}; - int il{0}, iu{0}; // not referenced if range='A' + int ldz{n}, lda{n}, lwork{2 * n}; + int il{0}, iu{0}; // not referenced if range='A' T vl{0.0}, vu{0.0}; // not referenced if range='A' char cmach{'S'}; - T abstol{static_cast(2.0*HeevxFuncs::lamch(&cmach))}; + T abstol{static_cast(2.0 * HeevxFuncs::lamch(&cmach))}; int m{0}; // number of eigenvalues found int info{0}; @@ -83,18 +79,20 @@ void eigensystem_hermitian(const matrix>& hermitian_matrix, eigenvalues.resize(n); matrix> heevx_copy{hermitian_matrix}; auto work = std::vector>(lwork, {0.0, 0.0}); - auto rwork = std::vector(7*n, 0.0); - auto iwork = std::vector(5*n, 0); + auto rwork = std::vector(7 * n, 0.0); + auto iwork = std::vector(5 * n, 0); auto ifail = std::vector(n, 0); - HeevxFuncs::heevx(&AerBlas::Jobz[0], &AerBlas::Range[0], &AerBlas::UpLo[0], &n, - heevx_copy.data(), &lda, &vl, &vu, &il, &iu, - &abstol, &m, eigenvalues.data(), eigenvectors.data(), &ldz, work.data(), - &lwork, rwork.data(), iwork.data(), ifail.data(), &info); + HeevxFuncs::heevx(&AerBlas::Jobz[0], &AerBlas::Range[0], &AerBlas::UpLo[0], + &n, heevx_copy.data(), &lda, &vl, &vu, &il, &iu, &abstol, + &m, eigenvalues.data(), eigenvectors.data(), &ldz, + work.data(), &lwork, rwork.data(), iwork.data(), + ifail.data(), &info); - if(info){ - throw std::runtime_error("Something went wrong in heevx call within eigensystem_hermitian funcion. " - "Check that input matrix is really hermitian"); + if (info) { + throw std::runtime_error("Something went wrong in heevx call within " + "eigensystem_hermitian funcion. " + "Check that input matrix is really hermitian"); } } diff --git a/src/framework/linalg/linops/linops_aer_vector.hpp b/src/framework/linalg/linops/linops_aer_vector.hpp old mode 100755 new mode 100644 index ba6ebc190f..708d04cfae --- a/src/framework/linalg/linops/linops_aer_vector.hpp +++ b/src/framework/linalg/linops/linops_aer_vector.hpp @@ -31,23 +31,23 @@ namespace Linalg { // Linear operations //---------------------------------------------------------------------------- template > -Vector add(const Vector& lhs, const Vector& rhs) { +Vector add(const Vector &lhs, const Vector &rhs) { return lhs + rhs; } template > -Vector& iadd(Vector& lhs, const Vector& rhs) { +Vector &iadd(Vector &lhs, const Vector &rhs) { lhs += rhs; return lhs; } template > -Vector sub(const Vector& lhs, const Vector& rhs) { +Vector sub(const Vector &lhs, const Vector &rhs) { return lhs - rhs; } template > -Vector& isub(Vector& lhs, const Vector& rhs) { +Vector &isub(Vector &lhs, const Vector &rhs) { lhs -= rhs; return lhs; } @@ -57,30 +57,29 @@ Vector& isub(Vector& lhs, const Vector& rhs) { //---------------------------------------------------------------------------- template , typename = enable_if_numeric_t> -Vector& iadd(Vector& data, const Scalar& val) { +Vector &iadd(Vector &data, const Scalar &val) { const T cast_val(val); std::for_each(data.data(), data.data() + data.size(), - [&cast_val](T& a)->T{ a += cast_val; }); + [&cast_val](T &a) -> T { a += cast_val; }); return data; } template , typename = enable_if_numeric_t> -Vector add(const Vector& data, const Scalar& val) { +Vector add(const Vector &data, const Scalar &val) { auto ret = data; return iadd(data, val); } - template , typename = enable_if_numeric_t> -Vector sub(const Vector& data, const Scalar& val) { +Vector sub(const Vector &data, const Scalar &val) { return add(data, -val); } template , typename = enable_if_numeric_t> -Vector& isub(Vector& data, const Scalar& val) { +Vector &isub(Vector &data, const Scalar &val) { return iadd(data, -val); } @@ -89,7 +88,7 @@ Vector& isub(Vector& data, const Scalar& val) { //---------------------------------------------------------------------------- template , typename = enable_if_numeric_t> -Vector& imul(Vector& data, const Scalar& val) { +Vector &imul(Vector &data, const Scalar &val) { if (almost_equal(val, 1)) { return data; } @@ -99,14 +98,14 @@ Vector& imul(Vector& data, const Scalar& val) { template , typename = enable_if_numeric_t> -Vector mul(const Vector& data, const Scalar& val) { +Vector mul(const Vector &data, const Scalar &val) { auto ret = data; return imul(ret, val); } template , typename = enable_if_numeric_t> -Vector& idiv(Vector& data, const Scalar& val) { +Vector &idiv(Vector &data, const Scalar &val) { if (almost_equal(val, 1)) { return data; } @@ -114,17 +113,16 @@ Vector& idiv(Vector& data, const Scalar& val) { return data; } - template , typename = enable_if_numeric_t> -Vector div(const Vector& data, const Scalar& val) { +Vector div(const Vector &data, const Scalar &val) { auto ret = data; return idiv(ret, val); } //------------------------------------------------------------------------------ -} // end namespace Linalg +} // end namespace Linalg //------------------------------------------------------------------------------ -} // end namespace AER +} // end namespace AER //------------------------------------------------------------------------------ #endif \ No newline at end of file diff --git a/src/framework/linalg/linops/linops_array.hpp b/src/framework/linalg/linops/linops_array.hpp old mode 100755 new mode 100644 index 1211cb7dbe..4c1df3bac0 --- a/src/framework/linalg/linops/linops_array.hpp +++ b/src/framework/linalg/linops/linops_array.hpp @@ -31,27 +31,27 @@ namespace Linalg { // Linear operations //---------------------------------------------------------------------------- template > -std::array& iadd(std::array& lhs, const std::array& rhs) { +std::array &iadd(std::array &lhs, const std::array &rhs) { std::transform(lhs.begin(), lhs.end(), rhs.begin(), lhs.begin(), std::plus()); return lhs; } template > -std::array add(const std::array& lhs, const std::array& rhs) { +std::array add(const std::array &lhs, const std::array &rhs) { std::array result = lhs; return iadd(result, rhs); } template > -std::array& isub(std::array& lhs, const std::array& rhs) { +std::array &isub(std::array &lhs, const std::array &rhs) { std::transform(lhs.begin(), lhs.end(), rhs.begin(), lhs.begin(), std::minus()); return lhs; } template > -std::array sub(const std::array& lhs, const std::array& rhs) { +std::array sub(const std::array &lhs, const std::array &rhs) { std::array result = lhs; return isub(result, rhs); } @@ -61,7 +61,7 @@ std::array sub(const std::array& lhs, const std::array& rhs) { //---------------------------------------------------------------------------- template , typename = enable_if_numeric_t> -std::array& iadd(std::array& data, const Scalar& val) { +std::array &iadd(std::array &data, const Scalar &val) { std::transform(data.begin(), data.end(), data.begin(), std::bind(std::plus(), std::placeholders::_1, val)); return data; @@ -69,14 +69,14 @@ std::array& iadd(std::array& data, const Scalar& val) { template , typename = enable_if_numeric_t> -std::array add(const std::array& data, const Scalar& val) { +std::array add(const std::array &data, const Scalar &val) { std::array result = data; return iadd(result, val); } template , typename = enable_if_numeric_t> -std::array& isub(std::array& data, const Scalar& val) { +std::array &isub(std::array &data, const Scalar &val) { std::transform(data.begin(), data.end(), data.begin(), std::bind(std::minus(), std::placeholders::_1, val)); return data; @@ -84,7 +84,7 @@ std::array& isub(std::array& data, const Scalar& val) { template , typename = enable_if_numeric_t> -std::array sub(const std::array& data, const Scalar& val) { +std::array sub(const std::array &data, const Scalar &val) { std::array result = data; return isub(result, val); } @@ -94,7 +94,7 @@ std::array sub(const std::array& data, const Scalar& val) { //---------------------------------------------------------------------------- template , typename = enable_if_numeric_t> -std::array& imul(std::array& data, const Scalar& val) { +std::array &imul(std::array &data, const Scalar &val) { std::transform(data.begin(), data.end(), data.begin(), std::bind(std::multiplies(), std::placeholders::_1, val)); return data; @@ -102,14 +102,14 @@ std::array& imul(std::array& data, const Scalar& val) { template , typename = enable_if_numeric_t> -std::array mul(const std::array& data, const Scalar& val) { +std::array mul(const std::array &data, const Scalar &val) { std::array result = data; return imul(result, val); } template , typename = enable_if_numeric_t> -std::array& idiv(std::array& data, const Scalar& val) { +std::array &idiv(std::array &data, const Scalar &val) { std::transform(data.begin(), data.end(), data.begin(), std::bind(std::divides(), std::placeholders::_1, val)); return data; @@ -117,14 +117,14 @@ std::array& idiv(std::array& data, const Scalar& val) { template , typename = enable_if_numeric_t> -std::array div(const std::array& data, const Scalar& val) { +std::array div(const std::array &data, const Scalar &val) { std::array result = data; return idiv(result, val); } //------------------------------------------------------------------------------ -} // end namespace Linalg +} // end namespace Linalg //------------------------------------------------------------------------------ -} // end namespace AER +} // end namespace AER //------------------------------------------------------------------------------ #endif \ No newline at end of file diff --git a/src/framework/linalg/linops/linops_generic.hpp b/src/framework/linalg/linops/linops_generic.hpp old mode 100755 new mode 100644 index f85b04e370..40d24f7493 --- a/src/framework/linalg/linops/linops_generic.hpp +++ b/src/framework/linalg/linops/linops_generic.hpp @@ -29,24 +29,20 @@ namespace Linalg { //---------------------------------------------------------------------------- // Linear operations //---------------------------------------------------------------------------- -template -T add(const T& lhs, const T& rhs) { +template T add(const T &lhs, const T &rhs) { return std::plus()(lhs, rhs); } -template -T& iadd(T& lhs, const T& rhs) { +template T &iadd(T &lhs, const T &rhs) { lhs = std::plus()(lhs, rhs); return lhs; } -template -T sub(const T& lhs, const T& rhs) { +template T sub(const T &lhs, const T &rhs) { return std::minus()(lhs, rhs); } -template -T& isub(T& lhs, const T& rhs) { +template T &isub(T &lhs, const T &rhs) { lhs = std::minus()(lhs, rhs); return lhs; } @@ -55,23 +51,23 @@ T& isub(T& lhs, const T& rhs) { // Affine operations //---------------------------------------------------------------------------- template > -T add(const T& data, const Scalar& val) { +T add(const T &data, const Scalar &val) { return std::plus()(data, val); } template > -T& iadd(T& data, const Scalar& val) { +T &iadd(T &data, const Scalar &val) { data = std::plus()(data, val); return data; } template > -T sub(const T& data, const Scalar& val) { +T sub(const T &data, const Scalar &val) { return std::minus()(data, val); } template > -T& isub(T& data, const Scalar& val) { +T &isub(T &data, const Scalar &val) { data = std::minus()(data, val); return data; } @@ -80,7 +76,7 @@ T& isub(T& data, const Scalar& val) { // Scalar operations //---------------------------------------------------------------------------- template > -T mul(const T& data, const Scalar& val) { +T mul(const T &data, const Scalar &val) { if (almost_equal(val, 1)) { return data; } @@ -88,7 +84,7 @@ T mul(const T& data, const Scalar& val) { } template > -T& imul(T& data, const Scalar& val) { +T &imul(T &data, const Scalar &val) { if (!almost_equal(val, 1)) { data = std::multiplies()(data, val); } @@ -96,7 +92,7 @@ T& imul(T& data, const Scalar& val) { } template > -T div(const T& data, const Scalar& val) { +T div(const T &data, const Scalar &val) { if (almost_equal(val, 1)) { return data; } @@ -104,7 +100,7 @@ T div(const T& data, const Scalar& val) { } template > -T& idiv(T& data, const Scalar& val) { +T &idiv(T &data, const Scalar &val) { if (!almost_equal(val, 1)) { data = std::divides()(data, val); } @@ -112,8 +108,8 @@ T& idiv(T& data, const Scalar& val) { } //------------------------------------------------------------------------------ -} // end namespace Linalg +} // end namespace Linalg //------------------------------------------------------------------------------ -} // end namespace AER +} // end namespace AER //------------------------------------------------------------------------------ #endif \ No newline at end of file diff --git a/src/framework/linalg/linops/linops_json.hpp b/src/framework/linalg/linops/linops_json.hpp old mode 100755 new mode 100644 index 8473bfbb82..cbdcefa604 --- a/src/framework/linalg/linops/linops_json.hpp +++ b/src/framework/linalg/linops/linops_json.hpp @@ -28,7 +28,7 @@ namespace Linalg { //---------------------------------------------------------------------------- // Linear operations //---------------------------------------------------------------------------- -inline json_t& iadd(json_t& lhs, const json_t& rhs) { +inline json_t &iadd(json_t &lhs, const json_t &rhs) { // Null case if (lhs.is_null()) { lhs = rhs; @@ -57,12 +57,12 @@ inline json_t& iadd(json_t& lhs, const json_t& rhs) { return lhs; } -inline json_t add(const json_t& lhs, const json_t& rhs) { +inline json_t add(const json_t &lhs, const json_t &rhs) { json_t result = lhs; return iadd(result, rhs); } -inline json_t& isub(json_t& lhs, const json_t& rhs) { +inline json_t &isub(json_t &lhs, const json_t &rhs) { // Null case if (rhs.is_null()) { return lhs; @@ -87,8 +87,7 @@ inline json_t& isub(json_t& lhs, const json_t& rhs) { return lhs; } -template -json_t sub(const T& lhs, const json_t& rhs) { +template json_t sub(const T &lhs, const json_t &rhs) { json_t result = lhs; return isub(result, rhs); } @@ -97,7 +96,7 @@ json_t sub(const T& lhs, const json_t& rhs) { // Affine operations //---------------------------------------------------------------------------- template > -json_t& iadd(json_t& data, const Scalar& val) { +json_t &iadd(json_t &data, const Scalar &val) { // Null case if (val == 0) { return data; @@ -123,13 +122,13 @@ json_t& iadd(json_t& data, const Scalar& val) { } template > -json_t add(const json_t& data, const Scalar& val) { +json_t add(const json_t &data, const Scalar &val) { json_t result = data; return iadd(result, val); } template > -json_t& isub(json_t& data, const Scalar& val) { +json_t &isub(json_t &data, const Scalar &val) { // Null case if (val == 0) { return data; @@ -156,7 +155,7 @@ json_t& isub(json_t& data, const Scalar& val) { } template > -json_t sub(const json_t& data, const Scalar& val) { +json_t sub(const json_t &data, const Scalar &val) { json_t result = data; return isub(result, val); } @@ -166,7 +165,7 @@ json_t sub(const json_t& data, const Scalar& val) { //---------------------------------------------------------------------------- template > -json_t& imul(json_t& data, const Scalar& val) { +json_t &imul(json_t &data, const Scalar &val) { // Trival case if (almost_equal(val, 1)) { return data; @@ -194,14 +193,14 @@ json_t& imul(json_t& data, const Scalar& val) { } template > -json_t mul(const json_t& data, const Scalar& val) { +json_t mul(const json_t &data, const Scalar &val) { // Null case json_t result = data; return imul(result, val); } template > -json_t& idiv(json_t& data, const Scalar& val) { +json_t &idiv(json_t &data, const Scalar &val) { // Trival case if (almost_equal(val, 1)) { return data; @@ -228,15 +227,15 @@ json_t& idiv(json_t& data, const Scalar& val) { } template > -json_t div(const json_t& data, const Scalar& val) { +json_t div(const json_t &data, const Scalar &val) { // Null case json_t result = data; return idiv(result, val); } //------------------------------------------------------------------------------ -} // end namespace Linalg +} // end namespace Linalg //------------------------------------------------------------------------------ -} // end namespace AER +} // end namespace AER //------------------------------------------------------------------------------ #endif \ No newline at end of file diff --git a/src/framework/linalg/linops/linops_map.hpp b/src/framework/linalg/linops/linops_map.hpp old mode 100755 new mode 100644 index f42cb80c6c..f69c8a675d --- a/src/framework/linalg/linops/linops_map.hpp +++ b/src/framework/linalg/linops/linops_map.hpp @@ -15,10 +15,10 @@ #ifndef _aer_framework_linalg_linops_map_hpp_ #define _aer_framework_linalg_linops_map_hpp_ -#include -#include #include "framework/linalg/almost_equal.hpp" #include "framework/linalg/enable_if_numeric.hpp" +#include +#include namespace AER { namespace Linalg { @@ -31,8 +31,8 @@ namespace Linalg { //---------------------------------------------------------------------------- template > -std::map add(const std::map& lhs, - const std::map& rhs) { +std::map add(const std::map &lhs, + const std::map &rhs) { std::map result = lhs; for (const auto &pair : rhs) { result[pair.first] = std::plus()(result[pair.first], pair.second); @@ -42,8 +42,8 @@ std::map add(const std::map& lhs, template > -std::map& iadd(std::map& lhs, - const std::map& rhs) { +std::map &iadd(std::map &lhs, + const std::map &rhs) { for (const auto &pair : rhs) { lhs[pair.first] = std::plus()(lhs[pair.first], pair.second); } @@ -52,8 +52,8 @@ std::map& iadd(std::map& lhs, template > -std::map sub(const std::map& lhs, - const std::map& rhs) { +std::map sub(const std::map &lhs, + const std::map &rhs) { std::map result = lhs; for (const auto &pair : rhs) { result[pair.first] = std::minus()(result[pair.first], pair.second); @@ -63,8 +63,8 @@ std::map sub(const std::map& lhs, template > -std::map& isub(std::map& lhs, - const std::map& rhs) { +std::map &isub(std::map &lhs, + const std::map &rhs) { for (const auto &pair : rhs) { lhs[pair.first] = std::minus()(lhs[pair.first], pair.second); } @@ -77,8 +77,8 @@ std::map& isub(std::map& lhs, template , typename = enable_if_numeric_t> -std::map add(const std::map& data, - const Scalar& val) { +std::map add(const std::map &data, + const Scalar &val) { std::map result; for (const auto &pair : data) { result[pair.first] = std::plus()(pair.second, val); @@ -89,8 +89,8 @@ std::map add(const std::map& data, template , typename = enable_if_numeric_t> -std::map& iadd(std::map& data, - const Scalar& val) { +std::map &iadd(std::map &data, + const Scalar &val) { for (const auto &pair : data) { data[pair.first] = std::plus()(data[pair.first], val); } @@ -100,8 +100,8 @@ std::map& iadd(std::map& data, template , typename = enable_if_numeric_t> -std::map sub(const std::map& data, - const Scalar& val) { +std::map sub(const std::map &data, + const Scalar &val) { std::map result; for (const auto &pair : data) { result[pair.first] = std::minus()(pair.second, val); @@ -112,8 +112,8 @@ std::map sub(const std::map& data, template , typename = enable_if_numeric_t> -std::map& isub(std::map& data, - const Scalar& val) { +std::map &isub(std::map &data, + const Scalar &val) { for (const auto &pair : data) { data[pair.first] = std::plus()(data[pair.first], val); } @@ -127,8 +127,8 @@ std::map& isub(std::map& data, template , typename = enable_if_numeric_t> -std::map mul(const std::map& data, - const Scalar& val) { +std::map mul(const std::map &data, + const Scalar &val) { if (almost_equal(val, 1)) { return data; } @@ -142,8 +142,8 @@ std::map mul(const std::map& data, template , typename = enable_if_numeric_t> -std::map& imul(std::map& data, - const Scalar& val) { +std::map &imul(std::map &data, + const Scalar &val) { if (almost_equal(val, 1)) { return data; } @@ -156,8 +156,8 @@ std::map& imul(std::map& data, template , typename = enable_if_numeric_t> -std::map div(const std::map& data, - const Scalar& val) { +std::map div(const std::map &data, + const Scalar &val) { if (almost_equal(val, 1)) { return data; } @@ -171,8 +171,8 @@ std::map div(const std::map& data, template , typename = enable_if_numeric_t> -std::map& idiv(std::map& data, - const Scalar& val) { +std::map &idiv(std::map &data, + const Scalar &val) { if (almost_equal(val, 1)) { return data; } @@ -183,8 +183,8 @@ std::map& idiv(std::map& data, } //------------------------------------------------------------------------------ -} // end namespace Linalg +} // end namespace Linalg //------------------------------------------------------------------------------ -} // end namespace AER +} // end namespace AER //------------------------------------------------------------------------------ #endif \ No newline at end of file diff --git a/src/framework/linalg/linops/linops_matrix.hpp b/src/framework/linalg/linops/linops_matrix.hpp old mode 100755 new mode 100644 index 4b510389c3..7fdac60fd7 --- a/src/framework/linalg/linops/linops_matrix.hpp +++ b/src/framework/linalg/linops/linops_matrix.hpp @@ -31,23 +31,23 @@ namespace Linalg { // Linear operations //---------------------------------------------------------------------------- template > -matrix add(const matrix& lhs, const matrix& rhs) { +matrix add(const matrix &lhs, const matrix &rhs) { return lhs + rhs; } template > -matrix& iadd(matrix& lhs, const matrix& rhs) { +matrix &iadd(matrix &lhs, const matrix &rhs) { lhs = lhs + rhs; return lhs; } template > -matrix sub(const matrix& lhs, const matrix& rhs) { +matrix sub(const matrix &lhs, const matrix &rhs) { return lhs - rhs; } template > -matrix& isub(matrix& lhs, const matrix& rhs) { +matrix &isub(matrix &lhs, const matrix &rhs) { lhs = lhs - rhs; return lhs; } @@ -57,7 +57,7 @@ matrix& isub(matrix& lhs, const matrix& rhs) { //---------------------------------------------------------------------------- template , typename = enable_if_numeric_t> -matrix& iadd(matrix& data, const Scalar& val) { +matrix &iadd(matrix &data, const Scalar &val) { if (val == 0) { return data; } @@ -69,20 +69,20 @@ matrix& iadd(matrix& data, const Scalar& val) { template , typename = enable_if_numeric_t> -matrix add(const matrix& data, const Scalar& val) { +matrix add(const matrix &data, const Scalar &val) { matrix result(data); return iadd(result, val); } template , typename = enable_if_numeric_t> -matrix sub(const matrix& data, const Scalar& val) { +matrix sub(const matrix &data, const Scalar &val) { return add(data, -val); } template , typename = enable_if_numeric_t> -matrix& isub(matrix& data, const Scalar& val) { +matrix &isub(matrix &data, const Scalar &val) { return iadd(data, -val); } @@ -92,7 +92,7 @@ matrix& isub(matrix& data, const Scalar& val) { template , typename = enable_if_numeric_t> -matrix& imul(matrix& data, const Scalar& val) { +matrix &imul(matrix &data, const Scalar &val) { if (almost_equal(val, 1)) { return data; } @@ -104,7 +104,7 @@ matrix& imul(matrix& data, const Scalar& val) { template , typename = enable_if_numeric_t> -matrix mul(const matrix& data, const Scalar& val) { +matrix mul(const matrix &data, const Scalar &val) { if (almost_equal(val, 1)) { return data; } @@ -115,7 +115,7 @@ matrix mul(const matrix& data, const Scalar& val) { template , typename = enable_if_numeric_t> -matrix& idiv(matrix& data, const Scalar& val) { +matrix &idiv(matrix &data, const Scalar &val) { if (almost_equal(val, 1)) { return data; } @@ -127,7 +127,7 @@ matrix& idiv(matrix& data, const Scalar& val) { template , typename = enable_if_numeric_t> -matrix div(const matrix& data, const Scalar& val) { +matrix div(const matrix &data, const Scalar &val) { if (almost_equal(val, 1)) { return data; } @@ -137,8 +137,8 @@ matrix div(const matrix& data, const Scalar& val) { } //------------------------------------------------------------------------------ -} // end namespace Linalg +} // end namespace Linalg //------------------------------------------------------------------------------ -} // end namespace AER +} // end namespace AER //------------------------------------------------------------------------------ #endif \ No newline at end of file diff --git a/src/framework/linalg/linops/linops_unordered_map.hpp b/src/framework/linalg/linops/linops_unordered_map.hpp old mode 100755 new mode 100644 index 7df754b5de..2245172f0c --- a/src/framework/linalg/linops/linops_unordered_map.hpp +++ b/src/framework/linalg/linops/linops_unordered_map.hpp @@ -31,9 +31,9 @@ namespace Linalg { //---------------------------------------------------------------------------- template > -std::unordered_map add( - const std::unordered_map& lhs, - const std::unordered_map& rhs) { +std::unordered_map +add(const std::unordered_map &lhs, + const std::unordered_map &rhs) { std::unordered_map result = lhs; for (const auto &pair : rhs) { result[pair.first] = std::plus()(result[pair.first], pair.second); @@ -43,9 +43,9 @@ std::unordered_map add( template > -std::unordered_map& iadd( - std::unordered_map& lhs, - const std::unordered_map& rhs) { +std::unordered_map & +iadd(std::unordered_map &lhs, + const std::unordered_map &rhs) { for (const auto &pair : rhs) { lhs[pair.first] = std::plus()(lhs[pair.first], pair.second); } @@ -54,9 +54,9 @@ std::unordered_map& iadd( template > -std::unordered_map sub( - const std::unordered_map& lhs, - const std::unordered_map& rhs) { +std::unordered_map +sub(const std::unordered_map &lhs, + const std::unordered_map &rhs) { std::unordered_map result = lhs; for (const auto &pair : rhs) { result[pair.first] = std::minus()(result[pair.first], pair.second); @@ -66,9 +66,9 @@ std::unordered_map sub( template > -std::unordered_map& isub( - std::unordered_map& lhs, - const std::unordered_map& rhs) { +std::unordered_map & +isub(std::unordered_map &lhs, + const std::unordered_map &rhs) { for (const auto &pair : rhs) { lhs[pair.first] = std::minus()(lhs[pair.first], pair.second); } @@ -81,8 +81,8 @@ std::unordered_map& isub( template , typename = enable_if_numeric_t> -std::unordered_map add( - const std::unordered_map& data, const Scalar& val) { +std::unordered_map +add(const std::unordered_map &data, const Scalar &val) { std::unordered_map result; for (const auto &pair : data) { result[pair.first] = std::plus()(pair.second, val); @@ -93,8 +93,8 @@ std::unordered_map add( template , typename = enable_if_numeric_t> -std::unordered_map& iadd( - std::unordered_map& data, const Scalar& val) { +std::unordered_map & +iadd(std::unordered_map &data, const Scalar &val) { for (const auto &pair : data) { data[pair.first] = std::plus()(data[pair.first], val); } @@ -104,8 +104,8 @@ std::unordered_map& iadd( template , typename = enable_if_numeric_t> -std::unordered_map sub( - const std::unordered_map& data, const Scalar& val) { +std::unordered_map +sub(const std::unordered_map &data, const Scalar &val) { std::unordered_map result; for (const auto &pair : data) { result[pair.first] = std::minus()(pair.second, val); @@ -116,8 +116,8 @@ std::unordered_map sub( template , typename = enable_if_numeric_t> -std::unordered_map& isub( - std::unordered_map& data, const Scalar& val) { +std::unordered_map & +isub(std::unordered_map &data, const Scalar &val) { for (const auto &pair : data) { data[pair.first] = std::plus()(data[pair.first], val); } @@ -131,8 +131,8 @@ std::unordered_map& isub( template , typename = enable_if_numeric_t> -std::unordered_map mul( - const std::unordered_map& data, const Scalar& val) { +std::unordered_map +mul(const std::unordered_map &data, const Scalar &val) { if (almost_equal(val, 1)) { return data; } @@ -146,8 +146,8 @@ std::unordered_map mul( template , typename = enable_if_numeric_t> -std::unordered_map& imul( - std::unordered_map& data, const Scalar& val) { +std::unordered_map & +imul(std::unordered_map &data, const Scalar &val) { if (almost_equal(val, 1)) { return data; } @@ -160,8 +160,8 @@ std::unordered_map& imul( template , typename = enable_if_numeric_t> -std::unordered_map div( - const std::unordered_map& data, const Scalar& val) { +std::unordered_map +div(const std::unordered_map &data, const Scalar &val) { if (almost_equal(val, 1)) { return data; } @@ -175,8 +175,8 @@ std::unordered_map div( template , typename = enable_if_numeric_t> -std::unordered_map& idiv( - std::unordered_map& data, const Scalar& val) { +std::unordered_map & +idiv(std::unordered_map &data, const Scalar &val) { if (almost_equal(val, 1)) { return data; } @@ -187,8 +187,8 @@ std::unordered_map& idiv( } //------------------------------------------------------------------------------ -} // end namespace Linalg +} // end namespace Linalg //------------------------------------------------------------------------------ -} // end namespace AER +} // end namespace AER //------------------------------------------------------------------------------ #endif \ No newline at end of file diff --git a/src/framework/linalg/linops/linops_vector.hpp b/src/framework/linalg/linops/linops_vector.hpp old mode 100755 new mode 100644 index 759442d9f4..c1b86d79d8 --- a/src/framework/linalg/linops/linops_vector.hpp +++ b/src/framework/linalg/linops/linops_vector.hpp @@ -31,7 +31,7 @@ namespace Linalg { // Linear operations //---------------------------------------------------------------------------- template > -std::vector add(const std::vector& lhs, const std::vector& rhs) { +std::vector add(const std::vector &lhs, const std::vector &rhs) { if (lhs.size() != rhs.size()) { throw std::runtime_error("Cannot add two vectors of different sizes."); } @@ -43,7 +43,7 @@ std::vector add(const std::vector& lhs, const std::vector& rhs) { } template > -std::vector& iadd(std::vector& lhs, const std::vector& rhs) { +std::vector &iadd(std::vector &lhs, const std::vector &rhs) { if (lhs.size() != rhs.size()) { throw std::runtime_error("Cannot add two vectors of different sizes."); } @@ -53,7 +53,7 @@ std::vector& iadd(std::vector& lhs, const std::vector& rhs) { } template > -std::vector sub(const std::vector& lhs, const std::vector& rhs) { +std::vector sub(const std::vector &lhs, const std::vector &rhs) { if (lhs.size() != rhs.size()) { throw std::runtime_error("Cannot add two vectors of different sizes."); } @@ -65,7 +65,7 @@ std::vector sub(const std::vector& lhs, const std::vector& rhs) { } template > -std::vector& isub(std::vector& lhs, const std::vector& rhs) { +std::vector &isub(std::vector &lhs, const std::vector &rhs) { if (lhs.size() != rhs.size()) { throw std::runtime_error("Cannot add two vectors of different sizes."); } @@ -79,7 +79,7 @@ std::vector& isub(std::vector& lhs, const std::vector& rhs) { //---------------------------------------------------------------------------- template , typename = enable_if_numeric_t> -std::vector add(const std::vector& data, const Scalar& val) { +std::vector add(const std::vector &data, const Scalar &val) { std::vector result; result.reserve(data.size()); std::transform(data.begin(), data.end(), std::back_inserter(result), @@ -89,7 +89,7 @@ std::vector add(const std::vector& data, const Scalar& val) { template , typename = enable_if_numeric_t> -std::vector& iadd(std::vector& data, const Scalar& val) { +std::vector &iadd(std::vector &data, const Scalar &val) { std::transform(data.begin(), data.end(), data.begin(), std::bind(std::plus(), std::placeholders::_1, val)); return data; @@ -97,7 +97,7 @@ std::vector& iadd(std::vector& data, const Scalar& val) { template , typename = enable_if_numeric_t> -std::vector sub(const std::vector& data, const Scalar& val) { +std::vector sub(const std::vector &data, const Scalar &val) { std::vector result; result.reserve(data.size()); std::transform(data.begin(), data.end(), std::back_inserter(result), @@ -107,7 +107,7 @@ std::vector sub(const std::vector& data, const Scalar& val) { template , typename = enable_if_numeric_t> -std::vector& isub(std::vector& data, const Scalar& val) { +std::vector &isub(std::vector &data, const Scalar &val) { std::transform(data.begin(), data.end(), data.begin(), std::bind(std::minus(), std::placeholders::_1, val)); return data; @@ -118,7 +118,7 @@ std::vector& isub(std::vector& data, const Scalar& val) { //---------------------------------------------------------------------------- template , typename = enable_if_numeric_t> -std::vector mul(const std::vector& data, const Scalar& val) { +std::vector mul(const std::vector &data, const Scalar &val) { if (almost_equal(val, 1)) { return data; } @@ -131,7 +131,7 @@ std::vector mul(const std::vector& data, const Scalar& val) { template , typename = enable_if_numeric_t> -std::vector& imul(std::vector& data, const Scalar& val) { +std::vector &imul(std::vector &data, const Scalar &val) { if (almost_equal(val, 1)) { return data; } @@ -142,7 +142,7 @@ std::vector& imul(std::vector& data, const Scalar& val) { template , typename = enable_if_numeric_t> -std::vector div(const std::vector& data, const Scalar& val) { +std::vector div(const std::vector &data, const Scalar &val) { if (almost_equal(val, 1)) { return data; } @@ -155,7 +155,7 @@ std::vector div(const std::vector& data, const Scalar& val) { template , typename = enable_if_numeric_t> -std::vector& idiv(std::vector& data, const Scalar& val) { +std::vector &idiv(std::vector &data, const Scalar &val) { if (almost_equal(val, 1)) { return data; } @@ -165,8 +165,8 @@ std::vector& idiv(std::vector& data, const Scalar& val) { } //------------------------------------------------------------------------------ -} // end namespace Linalg +} // end namespace Linalg //------------------------------------------------------------------------------ -} // end namespace AER +} // end namespace AER //------------------------------------------------------------------------------ #endif \ No newline at end of file diff --git a/src/framework/linalg/matrix_utils.hpp b/src/framework/linalg/matrix_utils.hpp old mode 100755 new mode 100644 index bd6903dde4..d557abd898 --- a/src/framework/linalg/matrix_utils.hpp +++ b/src/framework/linalg/matrix_utils.hpp @@ -16,7 +16,7 @@ #define _aer_framework_linalg_matrix_utils_hpp_ #include "framework/linalg/matrix_utils/matrix_defs.hpp" -#include "framework/linalg/matrix_utils/vmatrix_defs.hpp" #include "framework/linalg/matrix_utils/smatrix_defs.hpp" +#include "framework/linalg/matrix_utils/vmatrix_defs.hpp" #endif \ No newline at end of file diff --git a/src/framework/linalg/matrix_utils/matrix_defs.hpp b/src/framework/linalg/matrix_utils/matrix_defs.hpp old mode 100755 new mode 100644 index 4b356399b5..aecae03d1b --- a/src/framework/linalg/matrix_utils/matrix_defs.hpp +++ b/src/framework/linalg/matrix_utils/matrix_defs.hpp @@ -33,18 +33,18 @@ namespace Linalg { class Matrix { public: // Single-qubit gates - const static cmatrix_t I; // name: "id" - const static cmatrix_t X; // name: "x" - const static cmatrix_t Y; // name: "y" - const static cmatrix_t Z; // name: "z" - const static cmatrix_t H; // name: "h" - const static cmatrix_t S; // name: "s" - const static cmatrix_t SDG; // name: "sdg" - const static cmatrix_t T; // name: "t" - const static cmatrix_t TDG; // name: "tdg" - const static cmatrix_t SX; // name: "sx" - const static cmatrix_t SXDG;// name: "sxdg" - const static cmatrix_t X90; // name: "x90" + const static cmatrix_t I; // name: "id" + const static cmatrix_t X; // name: "x" + const static cmatrix_t Y; // name: "y" + const static cmatrix_t Z; // name: "z" + const static cmatrix_t H; // name: "h" + const static cmatrix_t S; // name: "s" + const static cmatrix_t SDG; // name: "sdg" + const static cmatrix_t T; // name: "t" + const static cmatrix_t TDG; // name: "tdg" + const static cmatrix_t SX; // name: "sx" + const static cmatrix_t SXDG; // name: "sxdg" + const static cmatrix_t X90; // name: "x90" // Two-qubit gates const static cmatrix_t CX; // name: "cx" @@ -91,8 +91,10 @@ class Matrix { static cmatrix_t u3(complex_t theta, complex_t phi, complex_t lam) { return u3(std::real(theta), std::real(phi), std::real(lam)); }; - static cmatrix_t u4(complex_t theta, complex_t phi, complex_t lam, complex_t gamma) { - return u4(std::real(theta), std::real(phi), std::real(lam), std::real(gamma)); + static cmatrix_t u4(complex_t theta, complex_t phi, complex_t lam, + complex_t gamma) { + return u4(std::real(theta), std::real(phi), std::real(lam), + std::real(gamma)); }; static cmatrix_t r(complex_t theta, complex_t phi) { return r(std::real(theta), std::real(phi)); @@ -105,11 +107,17 @@ class Matrix { static cmatrix_t rzz(complex_t theta) { return rzz(std::real(theta)); } static cmatrix_t rzx(complex_t theta) { return rzx(std::real(theta)); } static cmatrix_t phase(complex_t theta) { return phase(std::real(theta)); } - static cmatrix_t phase_diag(complex_t theta) { return phase_diag(std::real(theta)); } + static cmatrix_t phase_diag(complex_t theta) { + return phase_diag(std::real(theta)); + } static cmatrix_t cphase(complex_t theta) { return cphase(std::real(theta)); } - static cmatrix_t cphase_diag(complex_t theta) { return cphase_diag(std::real(theta)); } - static cmatrix_t cu(complex_t theta, complex_t phi, complex_t lam, complex_t gamma) { - return cu(std::real(theta), std::real(phi), std::real(lam), std::real(gamma)); + static cmatrix_t cphase_diag(complex_t theta) { + return cphase_diag(std::real(theta)); + } + static cmatrix_t cu(complex_t theta, complex_t phi, complex_t lam, + complex_t gamma) { + return cu(std::real(theta), std::real(phi), std::real(lam), + std::real(gamma)); } // Return the matrix for a named matrix string @@ -182,7 +190,7 @@ const cmatrix_t Matrix::CY = {{0, 0}, {0, 0}, {0, 0}, {0, -1}}, {{0, 0}, {0, 0}, {1, 0}, {0, 0}}, {{0, 0}, {0, 1}, {0, 0}, {0, 0}}}); - + const cmatrix_t Matrix::CZ = Utils::make_matrix({{{1, 0}, {0, 0}, {0, 0}, {0, 0}}, {{0, 0}, {1, 0}, {0, 0}, {0, 0}}, @@ -197,12 +205,12 @@ const cmatrix_t Matrix::SWAP = // Lookup table const stringmap_t Matrix::label_map_ = { - {"id", &Matrix::I}, {"x", &Matrix::X}, {"y", &Matrix::Y}, - {"z", &Matrix::Z}, {"h", &Matrix::H}, {"s", &Matrix::S}, - {"sdg", &Matrix::SDG}, {"t", &Matrix::T}, {"tdg", &Matrix::TDG}, - {"x90", &Matrix::X90}, {"cx", &Matrix::CX}, {"cy", &Matrix::CY}, - {"cz", &Matrix::CZ}, {"swap", &Matrix::SWAP}, {"sx", &Matrix::SX}, - {"sxdg", &Matrix::SXDG}, {"delay", &Matrix::I}}; + {"id", &Matrix::I}, {"x", &Matrix::X}, {"y", &Matrix::Y}, + {"z", &Matrix::Z}, {"h", &Matrix::H}, {"s", &Matrix::S}, + {"sdg", &Matrix::SDG}, {"t", &Matrix::T}, {"tdg", &Matrix::TDG}, + {"x90", &Matrix::X90}, {"cx", &Matrix::CX}, {"cy", &Matrix::CY}, + {"cz", &Matrix::CZ}, {"swap", &Matrix::SWAP}, {"sx", &Matrix::SX}, + {"sxdg", &Matrix::SXDG}, {"delay", &Matrix::I}}; cmatrix_t Matrix::identity(size_t dim) { cmatrix_t mat(dim, dim); @@ -211,9 +219,7 @@ cmatrix_t Matrix::identity(size_t dim) { return mat; } -cmatrix_t Matrix::u1(double lambda) { - return phase(lambda); -} +cmatrix_t Matrix::u1(double lambda) { return phase(lambda); } cmatrix_t Matrix::u2(double phi, double lambda) { cmatrix_t mat(2, 2); diff --git a/src/framework/linalg/matrix_utils/smatrix_defs.hpp b/src/framework/linalg/matrix_utils/smatrix_defs.hpp old mode 100755 new mode 100644 index 2d3a73cc46..1f8a34260b --- a/src/framework/linalg/matrix_utils/smatrix_defs.hpp +++ b/src/framework/linalg/matrix_utils/smatrix_defs.hpp @@ -34,18 +34,18 @@ namespace Linalg { class SMatrix { public: // Single-qubit gates - const static cmatrix_t I; // name: "id" - const static cmatrix_t X; // name: "x" - const static cmatrix_t Y; // name: "y" - const static cmatrix_t Z; // name: "z" - const static cmatrix_t H; // name: "h" - const static cmatrix_t S; // name: "s" - const static cmatrix_t SDG; // name: "sdg" - const static cmatrix_t T; // name: "t" - const static cmatrix_t TDG; // name: "tdg" - const static cmatrix_t SX; // name: "sx" - const static cmatrix_t SXDG;// name: "sxdg" - const static cmatrix_t X90; // name: "x90" + const static cmatrix_t I; // name: "id" + const static cmatrix_t X; // name: "x" + const static cmatrix_t Y; // name: "y" + const static cmatrix_t Z; // name: "z" + const static cmatrix_t H; // name: "h" + const static cmatrix_t S; // name: "s" + const static cmatrix_t SDG; // name: "sdg" + const static cmatrix_t T; // name: "t" + const static cmatrix_t TDG; // name: "tdg" + const static cmatrix_t SX; // name: "sx" + const static cmatrix_t SXDG; // name: "sxdg" + const static cmatrix_t X90; // name: "x90" // Two-qubit gates const static cmatrix_t CX; // name: "cx" @@ -92,8 +92,10 @@ class SMatrix { static cmatrix_t u3(complex_t theta, complex_t phi, complex_t lam) { return u3(std::real(theta), std::real(phi), std::real(lam)); }; - static cmatrix_t u4(complex_t theta, complex_t phi, complex_t lam, complex_t gamma) { - return u4(std::real(theta), std::real(phi), std::real(lam), std::real(gamma)); + static cmatrix_t u4(complex_t theta, complex_t phi, complex_t lam, + complex_t gamma) { + return u4(std::real(theta), std::real(phi), std::real(lam), + std::real(gamma)); } static cmatrix_t r(complex_t theta, complex_t phi) { return r(std::real(theta), std::real(phi)); @@ -106,11 +108,17 @@ class SMatrix { static cmatrix_t rzz(complex_t theta) { return rzz(std::real(theta)); } static cmatrix_t rzx(complex_t theta) { return rzx(std::real(theta)); } static cmatrix_t phase(complex_t theta) { return phase(std::real(theta)); } - static cmatrix_t phase_diag(complex_t theta) { return phase_diag(std::real(theta)); } + static cmatrix_t phase_diag(complex_t theta) { + return phase_diag(std::real(theta)); + } static cmatrix_t cphase(complex_t theta) { return cphase(std::real(theta)); } - static cmatrix_t cphase_diag(complex_t theta) { return cphase_diag(std::real(theta)); } - static cmatrix_t cu(complex_t theta, complex_t phi, complex_t lam, complex_t gamma) { - return cu(std::real(theta), std::real(phi), std::real(lam), std::real(gamma)); + static cmatrix_t cphase_diag(complex_t theta) { + return cphase_diag(std::real(theta)); + } + static cmatrix_t cu(complex_t theta, complex_t phi, complex_t lam, + complex_t gamma) { + return cu(std::real(theta), std::real(phi), std::real(lam), + std::real(gamma)); } // Return superoperator matrix for reset instruction @@ -173,18 +181,16 @@ const cmatrix_t SMatrix::SWAP = Utils::unitary_superop(Matrix::SWAP); // Lookup table const stringmap_t SMatrix::label_map_ = { - {"id", &SMatrix::I}, {"x", &SMatrix::X}, {"y", &SMatrix::Y}, - {"z", &SMatrix::Z}, {"h", &SMatrix::H}, {"s", &SMatrix::S}, - {"sdg", &SMatrix::SDG}, {"t", &SMatrix::T}, {"tdg", &SMatrix::TDG}, - {"x90", &SMatrix::X90}, {"cx", &SMatrix::CX}, {"cy", &SMatrix::CY}, - {"cz", &SMatrix::CZ}, {"swap", &SMatrix::SWAP}, {"sx", &SMatrix::SX}, + {"id", &SMatrix::I}, {"x", &SMatrix::X}, {"y", &SMatrix::Y}, + {"z", &SMatrix::Z}, {"h", &SMatrix::H}, {"s", &SMatrix::S}, + {"sdg", &SMatrix::SDG}, {"t", &SMatrix::T}, {"tdg", &SMatrix::TDG}, + {"x90", &SMatrix::X90}, {"cx", &SMatrix::CX}, {"cy", &SMatrix::CY}, + {"cz", &SMatrix::CZ}, {"swap", &SMatrix::SWAP}, {"sx", &SMatrix::SX}, {"sxdg", &SMatrix::SXDG}, {"delay", &SMatrix::I}}; cmatrix_t SMatrix::identity(size_t dim) { return Matrix::identity(dim * dim); } -cmatrix_t SMatrix::u1(double lambda) { - return phase(lambda); -} +cmatrix_t SMatrix::u1(double lambda) { return phase(lambda); } cmatrix_t SMatrix::u2(double phi, double lambda) { return Utils::tensor_product(Matrix::u2(-phi, -lambda), diff --git a/src/framework/linalg/matrix_utils/vmatrix_defs.hpp b/src/framework/linalg/matrix_utils/vmatrix_defs.hpp old mode 100755 new mode 100644 index bc4e68c617..cef6a69308 --- a/src/framework/linalg/matrix_utils/vmatrix_defs.hpp +++ b/src/framework/linalg/matrix_utils/vmatrix_defs.hpp @@ -34,18 +34,18 @@ namespace Linalg { class VMatrix { public: // Single-qubit gates - const static cvector_t I; // name: "id" - const static cvector_t X; // name: "x" - const static cvector_t Y; // name: "y" - const static cvector_t Z; // name: "z" - const static cvector_t H; // name: "h" - const static cvector_t S; // name: "s" - const static cvector_t SDG; // name: "sdg" - const static cvector_t T; // name: "t" - const static cvector_t TDG; // name: "tdg" - const static cvector_t SX; // name: "sx" - const static cvector_t SXDG;// name: "sxdg" - const static cvector_t X90; // name: "x90" + const static cvector_t I; // name: "id" + const static cvector_t X; // name: "x" + const static cvector_t Y; // name: "y" + const static cvector_t Z; // name: "z" + const static cvector_t H; // name: "h" + const static cvector_t S; // name: "s" + const static cvector_t SDG; // name: "sdg" + const static cvector_t T; // name: "t" + const static cvector_t TDG; // name: "tdg" + const static cvector_t SX; // name: "sx" + const static cvector_t SXDG; // name: "sxdg" + const static cvector_t X90; // name: "x90" // Two-qubit gates const static cvector_t CX; // name: "cx" @@ -73,7 +73,7 @@ class VMatrix { static cvector_t rxx(double theta); static cvector_t ryy(double theta); static cvector_t rzz(double theta); - static cvector_t rzx(double theta); // rotation around Tensor(X, Z) + static cvector_t rzx(double theta); // rotation around Tensor(X, Z) static cvector_t rzz_diag(double theta); // return the matrix diagonal // Phase Gates @@ -94,8 +94,10 @@ class VMatrix { static cvector_t u3(complex_t theta, complex_t phi, complex_t lam) { return u3(std::real(theta), std::real(phi), std::real(lam)); }; - static cvector_t u4(complex_t theta, complex_t phi, complex_t lam, complex_t gamma) { - return u4(std::real(theta), std::real(phi), std::real(lam), std::real(gamma)); + static cvector_t u4(complex_t theta, complex_t phi, complex_t lam, + complex_t gamma) { + return u4(std::real(theta), std::real(phi), std::real(lam), + std::real(gamma)); }; static cvector_t r(complex_t theta, complex_t phi) { return r(std::real(theta), std::real(phi)); @@ -103,18 +105,28 @@ class VMatrix { static cvector_t rx(complex_t theta) { return rx(std::real(theta)); } static cvector_t ry(complex_t theta) { return ry(std::real(theta)); } static cvector_t rz(complex_t theta) { return rz(std::real(theta)); } - static cvector_t rz_diag(complex_t theta) { return rz_diag(std::real(theta)); } + static cvector_t rz_diag(complex_t theta) { + return rz_diag(std::real(theta)); + } static cvector_t rxx(complex_t theta) { return rxx(std::real(theta)); } static cvector_t ryy(complex_t theta) { return ryy(std::real(theta)); } static cvector_t rzz(complex_t theta) { return rzz(std::real(theta)); } - static cvector_t rzz_diag(complex_t theta) { return rzz_diag(std::real(theta)); } + static cvector_t rzz_diag(complex_t theta) { + return rzz_diag(std::real(theta)); + } static cvector_t rzx(complex_t theta) { return rzx(std::real(theta)); } static cvector_t phase(complex_t theta) { return phase(std::real(theta)); } - static cvector_t phase_diag(complex_t theta) { return phase_diag(std::real(theta)); } + static cvector_t phase_diag(complex_t theta) { + return phase_diag(std::real(theta)); + } static cvector_t cphase(complex_t theta) { return cphase(std::real(theta)); } - static cvector_t cphase_diag(complex_t theta) { return cphase_diag(std::real(theta)); } - static cvector_t cu(complex_t theta, complex_t phi, complex_t lam, complex_t gamma) { - return cu(std::real(theta), std::real(phi), std::real(lam), std::real(gamma)); + static cvector_t cphase_diag(complex_t theta) { + return cphase_diag(std::real(theta)); + } + static cvector_t cu(complex_t theta, complex_t phi, complex_t lam, + complex_t gamma) { + return cu(std::real(theta), std::real(phi), std::real(lam), + std::real(gamma)); } // Return the matrix for a named matrix string @@ -172,12 +184,12 @@ const cvector_t VMatrix::SWAP = Utils::vectorize_matrix(Matrix::SWAP); // Lookup table const stringmap_t VMatrix::label_map_ = { - {"id", &VMatrix::I}, {"x", &VMatrix::X}, {"y", &VMatrix::Y}, - {"z", &VMatrix::Z}, {"h", &VMatrix::H}, {"s", &VMatrix::S}, - {"sdg", &VMatrix::SDG}, {"t", &VMatrix::T}, {"tdg", &VMatrix::TDG}, - {"x90", &VMatrix::X90}, {"cx", &VMatrix::CX}, {"cy", &VMatrix::CY}, - {"cz", &VMatrix::CZ}, {"swap", &VMatrix::SWAP}, {"sx", &VMatrix::SX}, - {"sxdg", &VMatrix::SXDG}, {"delay", &VMatrix::I}}; + {"id", &VMatrix::I}, {"x", &VMatrix::X}, {"y", &VMatrix::Y}, + {"z", &VMatrix::Z}, {"h", &VMatrix::H}, {"s", &VMatrix::S}, + {"sdg", &VMatrix::SDG}, {"t", &VMatrix::T}, {"tdg", &VMatrix::TDG}, + {"x90", &VMatrix::X90}, {"cx", &VMatrix::CX}, {"cy", &VMatrix::CY}, + {"cz", &VMatrix::CZ}, {"swap", &VMatrix::SWAP}, {"sx", &VMatrix::SX}, + {"sxdg", &VMatrix::SXDG}, {"delay", &VMatrix::I}}; cvector_t VMatrix::identity(size_t dim) { cvector_t mat(dim * dim); @@ -186,9 +198,7 @@ cvector_t VMatrix::identity(size_t dim) { return mat; } -cvector_t VMatrix::u1(double lambda) { - return phase(lambda); -} +cvector_t VMatrix::u1(double lambda) { return phase(lambda); } cvector_t VMatrix::u2(double phi, double lambda) { cvector_t mat(2 * 2); @@ -312,7 +322,7 @@ cvector_t VMatrix::rzz_diag(double theta) { const complex_t i(0., 1.); const complex_t exp_p = std::exp(i * 0.5 * theta); const complex_t exp_m = std::exp(-i * 0.5 * theta); - return cvector_t({exp_m, exp_p, exp_p, exp_m}); + return cvector_t({exp_m, exp_p, exp_p, exp_m}); } cvector_t VMatrix::rzx(double theta) { diff --git a/src/framework/linalg/square.hpp b/src/framework/linalg/square.hpp old mode 100755 new mode 100644 index 6baae7054f..9760fe442c --- a/src/framework/linalg/square.hpp +++ b/src/framework/linalg/square.hpp @@ -22,10 +22,10 @@ #include #include "framework/json.hpp" -#include "framework/matrix.hpp" +#include "framework/linalg/enable_if_numeric.hpp" #include "framework/linalg/vector.hpp" +#include "framework/matrix.hpp" #include "framework/types.hpp" -#include "framework/linalg/enable_if_numeric.hpp" namespace AER { namespace Linalg { @@ -39,14 +39,14 @@ namespace Linalg { // Return entrywise square of a vector template > -std::array square(const std::array& data) { +std::array square(const std::array &data) { std::array result = data; return isquare(result); } // Return inplace entrywise square of a vector template > -std::array& isquare(std::array& data) { +std::array &isquare(std::array &data) { std::transform(data.begin(), data.end(), data.begin(), data.begin(), std::multiplies()); return data; @@ -58,17 +58,17 @@ std::array& isquare(std::array& data) { // Return entrywise square of a vector template > -std::vector square(const std::vector& data) { +std::vector square(const std::vector &data) { std::vector result; result.reserve(data.size()); - std::transform(data.begin(), data.end(), data.begin(), std::back_inserter(result), - std::multiplies()); + std::transform(data.begin(), data.end(), data.begin(), + std::back_inserter(result), std::multiplies()); return result; } // Return inplace entrywise square of a vector template > -std::vector& isquare(std::vector& data) { +std::vector &isquare(std::vector &data) { std::transform(data.begin(), data.end(), data.begin(), data.begin(), std::multiplies()); return data; @@ -78,18 +78,20 @@ std::vector& isquare(std::vector& data) { // Entrywise square of std::map //---------------------------------------------------------------------------- -template > -std::map square(const std::map& data) { +template > +std::map square(const std::map &data) { std::map result; - for (const auto& pair : data) { + for (const auto &pair : data) { result[pair.first] = pair.second * pair.second; } return result; } -template > -std::map& isquare(std::map& data) { - for (auto& pair : data) { +template > +std::map &isquare(std::map &data) { + for (auto &pair : data) { pair.second *= pair.second; } return data; @@ -99,19 +101,22 @@ std::map& isquare(std::map& data) { // Entrywise square of std::unordered_map //---------------------------------------------------------------------------- -template > -std::unordered_map square( - const std::unordered_map& data) { +template > +std::unordered_map +square(const std::unordered_map &data) { std::unordered_map result; - for (const auto& pair : data) { + for (const auto &pair : data) { result[pair.first] = pair.second * pair.second; } return result; } -template > -std::unordered_map& isquare(std::unordered_map& data) { - for (auto& pair : data) { +template > +std::unordered_map & +isquare(std::unordered_map &data) { + for (auto &pair : data) { pair.second *= pair.second; } return data; @@ -122,7 +127,7 @@ std::unordered_map& isquare(std::unordered_map> -matrix& isquare(matrix& data) { +matrix &isquare(matrix &data) { for (size_t j = 0; j < data.size(); j++) { data[j] *= data[j]; } @@ -130,7 +135,7 @@ matrix& isquare(matrix& data) { } template > -matrix square(const matrix& data) { +matrix square(const matrix &data) { matrix result = data; return isquare(result); } @@ -140,16 +145,17 @@ matrix square(const matrix& data) { //---------------------------------------------------------------------------- template > -Vector& isquare(Vector& vec) { - std::for_each(vec.data(), vec.data() + vec.size(), [](T&val) { val *= val; }); +Vector &isquare(Vector &vec) { + std::for_each(vec.data(), vec.data() + vec.size(), + [](T &val) { val *= val; }); return vec; } template > -Vector square(const Vector& vec) { +Vector square(const Vector &vec) { Vector ret(vec.size(), false); std::transform(vec.data(), vec.data() + vec.size(), ret.data(), - [](const T&val) { return val * val; }); + [](const T &val) { return val * val; }); return ret; } @@ -157,7 +163,7 @@ Vector square(const Vector& vec) { // Entrywise square of JSON //---------------------------------------------------------------------------- -inline json_t& isquare(json_t& data) { +inline json_t &isquare(json_t &data) { // Terminating case if (data.is_number()) { double val = data; @@ -170,7 +176,7 @@ inline json_t& isquare(json_t& data) { isquare(data[pos]); } return data; - } + } if (data.is_object()) { for (auto it = data.begin(); it != data.end(); ++it) { isquare(data[it.key()]); @@ -180,7 +186,7 @@ inline json_t& isquare(json_t& data) { throw std::invalid_argument("Input JSONs cannot be squared."); } -inline json_t square(const json_t& data) { +inline json_t square(const json_t &data) { json_t result = data; return isquare(result); } @@ -189,20 +195,16 @@ inline json_t square(const json_t& data) { // Square of general type //---------------------------------------------------------------------------- -template -T square(const T& data) { - return data * data; -} +template T square(const T &data) { return data * data; } -template -T& isquare(T& data) { +template T &isquare(T &data) { data *= data; return data; } //------------------------------------------------------------------------------ -} // end namespace Linalg +} // end namespace Linalg //------------------------------------------------------------------------------ -} // end namespace AER +} // end namespace AER //------------------------------------------------------------------------------ #endif \ No newline at end of file diff --git a/src/framework/linalg/vector.hpp b/src/framework/linalg/vector.hpp old mode 100755 new mode 100644 index e5f0d59e01..59fe4ba1b9 --- a/src/framework/linalg/vector.hpp +++ b/src/framework/linalg/vector.hpp @@ -60,8 +60,7 @@ template class Vector { Vector(Vector &&other) noexcept; // Destructor - virtual ~Vector() { - free(data_); } + virtual ~Vector() { free(data_); } //----------------------------------------------------------------------- // Assignment @@ -192,7 +191,8 @@ template class Vector { template Vector::Vector(size_t sz, bool fill) - : size_(sz), data_((fill) ? calloc_array(size_) : malloc_array(size_)) {} + : size_(sz), + data_((fill) ? calloc_array(size_) : malloc_array(size_)) {} template Vector::Vector(const Vector &other) @@ -257,8 +257,7 @@ Vector Vector::copy_from_buffer(size_t sz, const T *buffer) { return ret; } -template -Vector Vector::move_from_buffer(size_t sz, T *buffer) { +template Vector Vector::move_from_buffer(size_t sz, T *buffer) { Vector ret; ret.size_ = sz; ret.data_ = buffer; @@ -364,8 +363,7 @@ template Vector Vector::operator*(const T &other) const { } template Vector &Vector::operator*=(const T &other) { - std::for_each(data_, data_ + size_, - [&other](T &a) { a *= other; }); + std::for_each(data_, data_ + size_, [&other](T &a) { a *= other; }); return *this; } @@ -383,7 +381,6 @@ template Vector &Vector::operator/=(const T &other) { return *this; } - //------------------------------------------------------------------------------ } // end Namespace AER //------------------------------------------------------------------------------ diff --git a/src/framework/linalg/vector_json.hpp b/src/framework/linalg/vector_json.hpp old mode 100755 new mode 100644 index 8f3f8d2a67..11f2e50e76 --- a/src/framework/linalg/vector_json.hpp +++ b/src/framework/linalg/vector_json.hpp @@ -24,7 +24,6 @@ namespace AER { // Implementation: JSON Conversion //------------------------------------------------------------------------------ - template void to_json(nlohmann::json &js, const Vector &vec) { js = nlohmann::json(); for (size_t i = 0; i < vec.size(); i++) { @@ -32,15 +31,14 @@ template void to_json(nlohmann::json &js, const Vector &vec) { } } - template void from_json(const nlohmann::json &js, Vector &vec) { // Check JSON is an array - if(!js.is_array()) { + if (!js.is_array()) { throw std::invalid_argument( std::string("JSON: invalid Vector (not array).")); } // Check if JSON is empty - if(js.empty()) { + if (js.empty()) { return; } diff --git a/src/framework/matrix.hpp b/src/framework/matrix.hpp old mode 100755 new mode 100644 index 54a8365950..ab5a0b23c3 --- a/src/framework/matrix.hpp +++ b/src/framework/matrix.hpp @@ -31,10 +31,10 @@ Multiplication is done with the C wrapper of the fortran blas library. #ifndef _aer_framework_matrix_hpp #define _aer_framework_matrix_hpp +#include #include #include #include -#include #include "framework/blas_protos.hpp" #include "framework/linalg/enable_if_numeric.hpp" @@ -45,17 +45,14 @@ Multiplication is done with the C wrapper of the fortran blas library. * ******************************************************************************/ -template -T* malloc_array(size_t size) { - return reinterpret_cast(malloc(sizeof(T) * size)); +template T *malloc_array(size_t size) { + return reinterpret_cast(malloc(sizeof(T) * size)); } -template -T* calloc_array(size_t size) { - return reinterpret_cast(calloc(size, sizeof(T))); +template T *calloc_array(size_t size) { + return reinterpret_cast(calloc(size, sizeof(T))); } - template // define a class template class matrix { // friend functions get to use the private variables of the class as well as @@ -139,7 +136,7 @@ class matrix { matrix(const matrix &other); // Move construct a matrix - matrix(matrix&& other) noexcept; + matrix(matrix &&other) noexcept; // Destructor virtual ~matrix() { free(data_); } @@ -155,8 +152,7 @@ class matrix { matrix &operator=(matrix &&other) noexcept; // Copy and cast assignment - template - matrix &operator=(const matrix &other); + template matrix &operator=(const matrix &other); //----------------------------------------------------------------------- // Buffer conversion @@ -164,33 +160,33 @@ class matrix { // Copy construct a matrix from C-array buffer // The buffer should have size = rows * cols. - static matrix copy_from_buffer(size_t rows, size_t cols, const T* buffer); + static matrix copy_from_buffer(size_t rows, size_t cols, const T *buffer); // Move construct a matrix from C-array buffer // The buffer should have size = rows * cols. - static matrix move_from_buffer(size_t rows, size_t cols, T* buffer); + static matrix move_from_buffer(size_t rows, size_t cols, T *buffer); // Copy matrix to a new C-array - T* copy_to_buffer() const; + T *copy_to_buffer() const; // Move matrix to a C-array - T* move_to_buffer(); + T *move_to_buffer(); //----------------------------------------------------------------------- // Element access //----------------------------------------------------------------------- // Addressing elements by vector representation - T& operator[](size_t element); - const T& operator[](size_t element) const; + T &operator[](size_t element); + const T &operator[](size_t element) const; // Addressing elements by matrix representation - T& operator()(size_t row, size_t col); - const T& operator()(size_t row, size_t col) const; + T &operator()(size_t row, size_t col); + const T &operator()(size_t row, size_t col) const; // Access the array data pointer - const T* data() const noexcept { return data_; } - T* data() noexcept { return data_; } + const T *data() const noexcept { return data_; } + T *data() noexcept { return data_; } //----------------------------------------------------------------------- // Other methods @@ -206,7 +202,7 @@ class matrix { void clear(); // Fill with constant value - void fill(const T& val); + void fill(const T &val); // Resize the matrix and reset to zero if different size void initialize(size_t row, size_t col); @@ -242,7 +238,7 @@ class matrix { // to rows // the ptr to the vector containing the matrix - T* data_ = nullptr; + T *data_ = nullptr; }; /******************************************************************************* @@ -261,14 +257,15 @@ matrix::matrix(size_t rows, size_t cols, bool fill) data_((fill) ? calloc_array(size_) : malloc_array(size_)) {} template -matrix::matrix(const matrix &other) : matrix(other.rows_, other.cols_, false) { +matrix::matrix(const matrix &other) + : matrix(other.rows_, other.cols_, false) { std::copy(other.data_, other.data_ + other.size_, data_); } template -matrix::matrix(matrix&& other) noexcept - : rows_(other.rows_), cols_(other.cols_), size_(other.size_), LD_(rows_), - data_(other.data_) { +matrix::matrix(matrix &&other) noexcept + : rows_(other.rows_), cols_(other.cols_), size_(other.size_), LD_(rows_), + data_(other.data_) { other.data_ = nullptr; } @@ -276,8 +273,7 @@ matrix::matrix(matrix&& other) noexcept // Assignment //----------------------------------------------------------------------- -template -matrix& matrix::operator=(matrix&& other) noexcept { +template matrix &matrix::operator=(matrix &&other) noexcept { free(data_); rows_ = other.rows_; cols_ = other.cols_; @@ -288,8 +284,7 @@ matrix& matrix::operator=(matrix&& other) noexcept { return *this; } -template -matrix &matrix::operator=(const matrix &other) { +template matrix &matrix::operator=(const matrix &other) { if (rows_ != other.rows_ || cols_ != other.cols_) { // size delete re-construct // the matrix @@ -308,8 +303,7 @@ template template inline matrix &matrix::operator=(const matrix &other) { - if (rows_ != other.GetRows() || - cols_ != other.GetColumns()) { + if (rows_ != other.GetRows() || cols_ != other.GetColumns()) { free(data_); rows_ = other.GetRows(); cols_ = other.GetColumns(); @@ -328,7 +322,8 @@ inline matrix &matrix::operator=(const matrix &other) { //----------------------------------------------------------------------- template -matrix matrix::copy_from_buffer(size_t rows, size_t cols, const T* buffer) { +matrix matrix::copy_from_buffer(size_t rows, size_t cols, + const T *buffer) { matrix ret; ret.size_ = rows * cols; ret.rows_ = rows; @@ -340,7 +335,7 @@ matrix matrix::copy_from_buffer(size_t rows, size_t cols, const T* buffer) } template -matrix matrix::move_from_buffer(size_t rows, size_t cols, T* buffer) { +matrix matrix::move_from_buffer(size_t rows, size_t cols, T *buffer) { matrix ret; ret.size_ = rows * cols; ret.rows_ = rows; @@ -350,16 +345,14 @@ matrix matrix::move_from_buffer(size_t rows, size_t cols, T* buffer) { return ret; } -template -T* matrix::copy_to_buffer() const { - T* buffer = malloc_array(size_); +template T *matrix::copy_to_buffer() const { + T *buffer = malloc_array(size_); std::copy(data_, data_ + size_, buffer); return buffer; } -template -T* matrix::move_to_buffer() { - T* buffer = data_; +template T *matrix::move_to_buffer() { + T *buffer = data_; data_ = nullptr; size_ = 0; rows_ = 0; @@ -371,8 +364,7 @@ T* matrix::move_to_buffer() { // Element access //----------------------------------------------------------------------- -template -T& matrix::operator[](size_t p) { +template T &matrix::operator[](size_t p) { #ifdef DEBUG if (p >= size_) { std::cerr @@ -383,8 +375,7 @@ T& matrix::operator[](size_t p) { #endif return data_[p]; } -template -const T& matrix::operator[](size_t p) const { +template const T &matrix::operator[](size_t p) const { #ifdef DEBUG if (p >= size_) { std::cerr << "Error: matrix class operator [] const: Matrix subscript out " @@ -396,8 +387,7 @@ const T& matrix::operator[](size_t p) const { return data_[p]; } -template -T& matrix::operator()(size_t i, size_t j) { +template T &matrix::operator()(size_t i, size_t j) { #ifdef DEBUG if (i >= rows_ || j >= cols_) { std::cerr @@ -409,8 +399,7 @@ T& matrix::operator()(size_t i, size_t j) { return data_[j * rows_ + i]; } -template -const T& matrix::operator()(size_t i, size_t j) const { +template const T &matrix::operator()(size_t i, size_t j) const { #ifdef DEBUG if (i >= rows_ || j >= cols_) { std::cerr << "Error: matrix class operator () const: Matrices subscript " @@ -422,8 +411,7 @@ const T& matrix::operator()(size_t i, size_t j) const { return data_[j * rows_ + i]; } -template -void matrix::clear() { +template void matrix::clear() { if (!data_ || !size_) return; rows_ = cols_ = size_ = 0; @@ -441,13 +429,11 @@ template inline void matrix::initialize(size_t rows, size_t cols) { } } -template -void matrix::fill(const T& val) { +template void matrix::fill(const T &val) { std::fill(data_, data_ + size_, val); } -template -void matrix::resize(size_t rows, size_t cols) { +template void matrix::resize(size_t rows, size_t cols) { if (rows_ == rows && cols_ == cols) return; size_ = rows * cols; @@ -465,33 +451,35 @@ void matrix::resize(size_t rows, size_t cols) { } // Addressing elements by row or column -template inline std::vector matrix::row_index(size_t row) const { +template +inline std::vector matrix::row_index(size_t row) const { #ifdef DEBUG if (row >= rows_) { - std::cerr << "Error: matrix class operator row_index out of bounds " - << row << " >= " << rows_ << std::endl; + std::cerr << "Error: matrix class operator row_index out of bounds " << row + << " >= " << rows_ << std::endl; exit(1); } #endif std::vector ret; ret.reserve(cols_); - for(size_t i = 0; i < cols_; i++) + for (size_t i = 0; i < cols_; i++) ret.emplace_back(data_[i * rows_ + row]); // Allow for Named Return Value Optimization (NRVO) by not using std::move return ret; } -template inline std::vector matrix::col_index(size_t col) const { +template +inline std::vector matrix::col_index(size_t col) const { #ifdef DEBUG if (col >= cols_) { - std::cerr << "Error: matrix class operator col_index out of bounds " - << col << " >= " << cols_ << std::endl; + std::cerr << "Error: matrix class operator col_index out of bounds " << col + << " >= " << cols_ << std::endl; exit(1); } #endif std::vector ret; ret.reserve(rows_); // we want the elements for all rows i..rows_ and column col - for(size_t i = 0; i < rows_; i++) + for (size_t i = 0; i < rows_; i++) ret.emplace_back(data_[col * rows_ + i]); // Allow for Named Return Value Optimization (NRVO) by not using std::move return ret; @@ -678,8 +666,8 @@ inline matrix operator*(const matrix &A, // C-> alpha*op(A)*op(B) +beta C matrix C(A.rows_, B.cols_); double alpha = 1.0, beta = 0.0; - dgemm_(&AerBlas::Trans[0], &AerBlas::Trans[0], &A.rows_, &B.cols_, &A.cols_, &alpha, A.data_, - &A.LD_, B.data_, &B.LD_, &beta, C.data_, &C.LD_); + dgemm_(&AerBlas::Trans[0], &AerBlas::Trans[0], &A.rows_, &B.cols_, &A.cols_, + &alpha, A.data_, &A.LD_, B.data_, &B.LD_, &beta, C.data_, &C.LD_); // cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, A.rows_, B.cols_, // A.cols_, 1.0, A.data_, A.LD_, B.data_, B.LD_, 0.0, C.data_, C.LD_); return C; @@ -690,8 +678,8 @@ inline matrix operator*(const matrix &A, const matrix &B) { // C-> alpha*op(A)*op(B) +beta C matrix C(A.rows_, B.cols_); float alpha = 1.0, beta = 0.0; - sgemm_(&AerBlas::Trans[0], &AerBlas::Trans[0], &A.rows_, &B.cols_, &A.cols_, &alpha, A.data_, - &A.LD_, B.data_, &B.LD_, &beta, C.data_, &C.LD_); + sgemm_(&AerBlas::Trans[0], &AerBlas::Trans[0], &A.rows_, &B.cols_, &A.cols_, + &alpha, A.data_, &A.LD_, B.data_, &B.LD_, &beta, C.data_, &C.LD_); // cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, A.rows_, B.cols_, // A.cols_, 1.0, A.data_, A.LD_, B.data_, B.LD_, 0.0, C.data_, C.LD_); return C; @@ -704,8 +692,8 @@ operator*(const matrix> &A, // C-> alpha*op(A)*op(B) +beta C matrix> C(A.rows_, B.cols_); std::complex alpha = 1.0, beta = 0.0; - cgemm_(&AerBlas::Trans[0], &AerBlas::Trans[0], &A.rows_, &B.cols_, &A.cols_, &alpha, A.data_, - &A.LD_, B.data_, &B.LD_, &beta, C.data_, &C.LD_); + cgemm_(&AerBlas::Trans[0], &AerBlas::Trans[0], &A.rows_, &B.cols_, &A.cols_, + &alpha, A.data_, &A.LD_, B.data_, &B.LD_, &beta, C.data_, &C.LD_); // cblas_zgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, A.rows_, B.cols_, // A.cols_, &alpha, A.data_, A.LD_, B.data_, B.LD_, &beta, C.data_, C.LD_); return C; @@ -718,8 +706,8 @@ operator*(const matrix> &A, // C-> alpha*op(A)*op(B) +beta C matrix> C(A.rows_, B.cols_); std::complex alpha = 1.0, beta = 0.0; - zgemm_(&AerBlas::Trans[0], &AerBlas::Trans[0], &A.rows_, &B.cols_, &A.cols_, &alpha, A.data_, - &A.LD_, B.data_, &B.LD_, &beta, C.data_, &C.LD_); + zgemm_(&AerBlas::Trans[0], &AerBlas::Trans[0], &A.rows_, &B.cols_, &A.cols_, + &alpha, A.data_, &A.LD_, B.data_, &B.LD_, &beta, C.data_, &C.LD_); // cblas_zgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, A.rows_, B.cols_, // A.cols_, &alpha, A.data_, A.LD_, B.data_, B.LD_, &beta, C.data_, C.LD_); return C; @@ -732,8 +720,8 @@ operator*(const matrix &A, const matrix> &B) { matrix> C(A.rows_, B.cols_), Ac(A.rows_, A.cols_); Ac = A; std::complex alpha = 1.0, beta = 0.0; - cgemm_(&AerBlas::Trans[0], &AerBlas::Trans[0], &Ac.rows_, &B.cols_, &Ac.cols_, &alpha, Ac.data_, - &Ac.LD_, B.data_, &B.LD_, &beta, C.data_, &C.LD_); + cgemm_(&AerBlas::Trans[0], &AerBlas::Trans[0], &Ac.rows_, &B.cols_, &Ac.cols_, + &alpha, Ac.data_, &Ac.LD_, B.data_, &B.LD_, &beta, C.data_, &C.LD_); // cblas_zgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, Ac.rows_, B.cols_, // Ac.cols_, &alpha, Ac.data_, Ac.LD_, B.data_, B.LD_, &beta, C.data_, C.LD_); return C; @@ -746,8 +734,8 @@ operator*(const matrix &A, const matrix> &B) { matrix> C(A.rows_, B.cols_), Ac(A.rows_, A.cols_); Ac = A; std::complex alpha = 1.0, beta = 0.0; - zgemm_(&AerBlas::Trans[0], &AerBlas::Trans[0], &Ac.rows_, &B.cols_, &Ac.cols_, &alpha, Ac.data_, - &Ac.LD_, B.data_, &B.LD_, &beta, C.data_, &C.LD_); + zgemm_(&AerBlas::Trans[0], &AerBlas::Trans[0], &Ac.rows_, &B.cols_, &Ac.cols_, + &alpha, Ac.data_, &Ac.LD_, B.data_, &B.LD_, &beta, C.data_, &C.LD_); // cblas_zgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, Ac.rows_, B.cols_, // Ac.cols_, &alpha, Ac.data_, Ac.LD_, B.data_, B.LD_, &beta, C.data_, C.LD_); return C; @@ -760,8 +748,8 @@ operator*(const matrix> &A, const matrix &B) { matrix> C(A.rows_, B.cols_), Bc(B.rows_, B.cols_); Bc = B; std::complex alpha = 1.0, beta = 0.0; - cgemm_(&AerBlas::Trans[0], &AerBlas::Trans[0], &A.rows_, &Bc.cols_, &A.cols_, &alpha, A.data_, - &A.LD_, Bc.data_, &Bc.LD_, &beta, C.data_, &C.LD_); + cgemm_(&AerBlas::Trans[0], &AerBlas::Trans[0], &A.rows_, &Bc.cols_, &A.cols_, + &alpha, A.data_, &A.LD_, Bc.data_, &Bc.LD_, &beta, C.data_, &C.LD_); // cblas_zgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, A.rows_, Bc.cols_, // A.cols_, &alpha, A.data_, A.LD_, Bc.data_, Bc.LD_, &beta, C.data_, C.LD_); return C; @@ -774,8 +762,8 @@ operator*(const matrix> &A, const matrix &B) { matrix> C(A.rows_, B.cols_), Bc(B.rows_, B.cols_); Bc = B; std::complex alpha = 1.0, beta = 0.0; - zgemm_(&AerBlas::Trans[0], &AerBlas::Trans[0], &A.rows_, &Bc.cols_, &A.cols_, &alpha, A.data_, - &A.LD_, Bc.data_, &Bc.LD_, &beta, C.data_, &C.LD_); + zgemm_(&AerBlas::Trans[0], &AerBlas::Trans[0], &A.rows_, &Bc.cols_, &A.cols_, + &alpha, A.data_, &A.LD_, Bc.data_, &Bc.LD_, &beta, C.data_, &C.LD_); // cblas_zgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, A.rows_, Bc.cols_, // A.cols_, &alpha, A.data_, A.LD_, Bc.data_, Bc.LD_, &beta, C.data_, C.LD_); return C; @@ -788,8 +776,8 @@ inline std::vector operator*(const matrix &A, std::vector y(A.rows_); float alpha = 1.0, beta = 0.0; const size_t incx = 1, incy = 1; - sgemv_(&AerBlas::Trans[0], &A.rows_, &A.cols_, &alpha, A.data_, &A.LD_, x.data(), &incx, - &beta, y.data(), &incy); + sgemv_(&AerBlas::Trans[0], &A.rows_, &A.cols_, &alpha, A.data_, &A.LD_, + x.data(), &incx, &beta, y.data(), &incy); return y; } // Double-Precision Real @@ -799,8 +787,8 @@ inline std::vector operator*(const matrix &A, std::vector y(A.rows_); double alpha = 1.0, beta = 0.0; const size_t incx = 1, incy = 1; - dgemv_(&AerBlas::Trans[0], &A.rows_, &A.cols_, &alpha, A.data_, &A.LD_, x.data(), &incx, - &beta, y.data(), &incy); + dgemv_(&AerBlas::Trans[0], &A.rows_, &A.cols_, &alpha, A.data_, &A.LD_, + x.data(), &incx, &beta, y.data(), &incy); return y; } // Single-Precision Complex @@ -811,8 +799,8 @@ operator*(const matrix> &A, std::vector> y(A.rows_); std::complex alpha = 1.0, beta = 0.0; const size_t incx = 1, incy = 1; - cgemv_(&AerBlas::Trans[0], &A.rows_, &A.cols_, &alpha, A.data_, &A.LD_, x.data(), &incx, - &beta, y.data(), &incy); + cgemv_(&AerBlas::Trans[0], &A.rows_, &A.cols_, &alpha, A.data_, &A.LD_, + x.data(), &incx, &beta, y.data(), &incy); return y; } // Double-Precision Complex @@ -823,8 +811,8 @@ operator*(const matrix> &A, std::vector> y(A.rows_); std::complex alpha = 1.0, beta = 0.0; const size_t incx = 1, incy = 1; - zgemv_(&AerBlas::Trans[0], &A.rows_, &A.cols_, &alpha, A.data_, &A.LD_, x.data(), &incx, - &beta, y.data(), &incy); + zgemv_(&AerBlas::Trans[0], &A.rows_, &A.cols_, &alpha, A.data_, &A.LD_, + x.data(), &incx, &beta, y.data(), &incy); return y; } diff --git a/src/framework/noise_utils.hpp b/src/framework/noise_utils.hpp index eb3947fbd3..3a2bc4fbe4 100644 --- a/src/framework/noise_utils.hpp +++ b/src/framework/noise_utils.hpp @@ -25,29 +25,29 @@ namespace Utils { //========================================================================= // Transform a superoperator matrix to a Choi matrix -template -matrix superop2choi(const matrix& superop, size_t dim); +template matrix superop2choi(const matrix &superop, size_t dim); // Transform a superoperator matrix to a set of Kraus matrices template -std::vector> superop2kraus(const matrix& superop, size_t dim, double threshold = 1e-10); +std::vector> superop2kraus(const matrix &superop, size_t dim, + double threshold = 1e-10); // Transform a Choi matrix to a superoperator matrix -template -matrix choi2superop(const matrix& choi, size_t dim); +template matrix choi2superop(const matrix &choi, size_t dim); // Transform a Choi matrix to a set of Kraus matrices template std::vector>> -choi2kraus(const matrix>& choi, size_t dim, double threshold = 1e-10); +choi2kraus(const matrix> &choi, size_t dim, + double threshold = 1e-10); // Transform a set of Kraus matrices to a Choi matrix template -matrix kraus2choi(const std::vector>& kraus, size_t dim); +matrix kraus2choi(const std::vector> &kraus, size_t dim); // Transform a set of Kraus matrices to a superoperator matrix template -matrix kraus2superop(const std::vector>& kraus, size_t dim); +matrix kraus2superop(const std::vector> &kraus, size_t dim); // Reshuffle transformation // Transforms a matrix with dimension (d0 * d1, d2 * d3) @@ -55,15 +55,15 @@ matrix kraus2superop(const std::vector>& kraus, size_t dim); // by transposition of bipartite indices // M[(i, j), (k, l)] -> M[(i, j), (k, i)] template -matrix reshuffle(const matrix &mat, size_t d0, size_t d1, size_t d2, size_t d3); - +matrix reshuffle(const matrix &mat, size_t d0, size_t d1, size_t d2, + size_t d3); //========================================================================= // Implementations //========================================================================= template -matrix kraus2superop(const std::vector>& kraus, size_t dim) { +matrix kraus2superop(const std::vector> &kraus, size_t dim) { matrix superop(dim * dim, dim * dim); for (const auto mat : kraus) { superop += Utils::tensor_product(Utils::conjugate(mat), mat); @@ -72,28 +72,28 @@ matrix kraus2superop(const std::vector>& kraus, size_t dim) { } template -matrix kraus2choi(const std::vector>& kraus, size_t dim) { +matrix kraus2choi(const std::vector> &kraus, size_t dim) { return superop2choi(kraus2superop(kraus, dim), dim); } template -matrix superop2choi(const matrix& superop, size_t dim) { +matrix superop2choi(const matrix &superop, size_t dim) { return reshuffle(superop, dim, dim, dim, dim); } template -std::vector> superop2kraus(const matrix& superop, size_t dim, double threshold) { +std::vector> superop2kraus(const matrix &superop, size_t dim, + double threshold) { return choi2kraus(superop2choi(superop, dim), dim, threshold); } -template -matrix choi2superop(const matrix& choi, size_t dim) { +template matrix choi2superop(const matrix &choi, size_t dim) { return reshuffle(choi, dim, dim, dim, dim); } template std::vector>> -choi2kraus(const matrix>& choi, size_t dim, double threshold) { +choi2kraus(const matrix> &choi, size_t dim, double threshold) { size_t dim2 = dim * dim; std::vector evals; @@ -108,7 +108,7 @@ choi2kraus(const matrix>& choi, size_t dim, double threshold) { const size_t idx = dim2 - 1 - i; const T eval = evals[idx]; if (eval > 0.0 && !Linalg::almost_equal(eval, 0.0, threshold)) { - std::complex coeff(std::sqrt(eval), 0.0); + std::complex coeff(std::sqrt(eval), 0.0); matrix> kmat(dim, dim); for (size_t col = 0; col < dim; col++) for (size_t row = 0; row < dim; row++) { @@ -121,19 +121,20 @@ choi2kraus(const matrix>& choi, size_t dim, double threshold) { } template -matrix reshuffle(const matrix &mat, size_t d0, size_t d1, size_t d2, size_t d3) { +matrix reshuffle(const matrix &mat, size_t d0, size_t d1, size_t d2, + size_t d3) { matrix ret(d1 * d3, d0 * d2); for (size_t i0 = 0; i0 < d0; ++i0) for (size_t i1 = 0; i1 < d1; ++i1) for (size_t i2 = 0; i2 < d2; ++i2) for (size_t i3 = 0; i3 < d3; ++i3) { - ret(d1 * i3 + i1, d0 * i2 + i0) = mat(d1 * i0 + i1, d3 * i2 + i3); + ret(d1 * i3 + i1, d0 * i2 + i0) = mat(d1 * i0 + i1, d3 * i2 + i3); } return ret; } //------------------------------------------------------------------------- -} // end namespace Noise +} // namespace Utils //------------------------------------------------------------------------- } // end namespace AER //------------------------------------------------------------------------- diff --git a/src/framework/operations.hpp b/src/framework/operations.hpp old mode 100755 new mode 100644 index 8069931a41..07f89a2c33 --- a/src/framework/operations.hpp +++ b/src/framework/operations.hpp @@ -16,15 +16,15 @@ #define _aer_framework_operations_hpp_ #include -#include #include #include +#include #include -#include "framework/types.hpp" #include "framework/json_parser.hpp" -#include "framework/utils.hpp" #include "framework/linalg/almost_equal.hpp" +#include "framework/types.hpp" +#include "framework/utils.hpp" #include "simulators/stabilizer/clifford.hpp" namespace AER { @@ -33,39 +33,82 @@ namespace Operations { // Comparisons enum class used for Boolean function operation. // these are used to compare two hexadecimal strings and return a bool // for now we only have one comparison Equal, but others will be added -enum class RegComparison {Equal, NotEqual, Less, LessEqual, Greater, GreaterEqual}; +enum class RegComparison { + Equal, + NotEqual, + Less, + LessEqual, + Greater, + GreaterEqual +}; // Enum class for operation types enum class OpType { - gate, measure, reset, bfunc, barrier, qerror_loc, snapshot, - matrix, diagonal_matrix, multiplexer, initialize, sim_op, nop, + gate, + measure, + reset, + bfunc, + barrier, + qerror_loc, + snapshot, + matrix, + diagonal_matrix, + multiplexer, + initialize, + sim_op, + nop, // Noise instructions - kraus, superop, roerror, noise_switch, + kraus, + superop, + roerror, + noise_switch, // Save instructions - save_state, save_expval, save_expval_var, save_statevec, save_statevec_dict, - save_densmat, save_probs, save_probs_ket, save_amps, save_amps_sq, - save_stabilizer, save_clifford, save_unitary, save_mps, save_superop, + save_state, + save_expval, + save_expval_var, + save_statevec, + save_statevec_dict, + save_densmat, + save_probs, + save_probs_ket, + save_amps, + save_amps_sq, + save_stabilizer, + save_clifford, + save_unitary, + save_mps, + save_superop, // Set instructions - set_statevec, set_densmat, set_unitary, set_superop, - set_stabilizer, set_mps, + set_statevec, + set_densmat, + set_unitary, + set_superop, + set_stabilizer, + set_mps, // Control Flow - jump, mark + jump, + mark }; enum class DataSubType { - single, c_single, list, c_list, accum, c_accum, average, c_average + single, + c_single, + list, + c_list, + accum, + c_accum, + average, + c_average }; static const std::unordered_set SAVE_TYPES = { - OpType::save_state, OpType::save_expval, OpType::save_expval_var, - OpType::save_statevec, OpType::save_statevec_dict, - OpType::save_densmat, OpType::save_probs, OpType::save_probs_ket, - OpType::save_amps, OpType::save_amps_sq, OpType::save_stabilizer, - OpType::save_clifford, - OpType::save_unitary, OpType::save_mps, OpType::save_superop -}; + OpType::save_state, OpType::save_expval, OpType::save_expval_var, + OpType::save_statevec, OpType::save_statevec_dict, OpType::save_densmat, + OpType::save_probs, OpType::save_probs_ket, OpType::save_amps, + OpType::save_amps_sq, OpType::save_stabilizer, OpType::save_clifford, + OpType::save_unitary, OpType::save_mps, OpType::save_superop}; -inline std::ostream& operator<<(std::ostream& stream, const OpType& type) { +inline std::ostream &operator<<(std::ostream &stream, const OpType &type) { switch (type) { case OpType::gate: stream << "gate"; @@ -192,40 +235,39 @@ inline std::ostream& operator<<(std::ostream& stream, const OpType& type) { return stream; } - -inline std::ostream& operator<<(std::ostream& stream, const DataSubType& subtype) { +inline std::ostream &operator<<(std::ostream &stream, + const DataSubType &subtype) { switch (subtype) { - case DataSubType::single: - stream << "single"; - break; - case DataSubType::c_single: - stream << "c_single"; - break; - case DataSubType::list: - stream << "list"; - break; - case DataSubType::c_list: - stream << "c_list"; - break; - case DataSubType::accum: - stream << "accum"; - break; - case DataSubType::c_accum: - stream << "c_accum"; - break; - case DataSubType::average: - stream << "average"; - break; - case DataSubType::c_average: - stream << "c_average"; - break; - default: - stream << "unknown"; + case DataSubType::single: + stream << "single"; + break; + case DataSubType::c_single: + stream << "c_single"; + break; + case DataSubType::list: + stream << "list"; + break; + case DataSubType::c_list: + stream << "c_list"; + break; + case DataSubType::accum: + stream << "accum"; + break; + case DataSubType::c_accum: + stream << "c_accum"; + break; + case DataSubType::average: + stream << "average"; + break; + case DataSubType::c_average: + stream << "c_average"; + break; + default: + stream << "unknown"; } return stream; } - //------------------------------------------------------------------------------ // Op Class //------------------------------------------------------------------------------ @@ -237,17 +279,19 @@ struct Op { reg_t qubits; // qubits operation acts on std::vector regs; // list of qubits for matrixes std::vector params; // real or complex params for gates - std::vector int_params; // integer parameters - std::vector string_params; // used for snapshot label, and boolean functions + std::vector int_params; // integer parameters + std::vector + string_params; // used for snapshot label, and boolean functions // Conditional Operations bool conditional = false; // is gate conditional gate - uint_t conditional_reg; // (opt) the (single) register location to look up for conditional - RegComparison bfunc; // (opt) boolean function relation + uint_t conditional_reg; // (opt) the (single) register location to look up for + // conditional + RegComparison bfunc; // (opt) boolean function relation // Measurement - reg_t memory; // (opt) register operation it acts on (measure) - reg_t registers; // (opt) register locations it acts on (measure, conditional) + reg_t memory; // (opt) register operation it acts on (measure) + reg_t registers; // (opt) register locations it acts on (measure, conditional) // Mat and Kraus std::vector mats; @@ -264,31 +308,41 @@ struct Op { // Legacy Snapshots DataSubType save_type = DataSubType::single; - using pauli_component_t = std::pair; // Pair (coeff, label_string) - using matrix_component_t = std::pair>>; // vector of Pair(qubits, matrix), combined with coefficient + using pauli_component_t = + std::pair; // Pair (coeff, label_string) + using matrix_component_t = + std::pair>>; // vector of + // Pair(qubits, + // matrix), combined + // with coefficient std::vector params_expval_pauli; - std::vector params_expval_matrix; // note that diagonal matrices are stored as - // 1 x M row-matrices - // Projector vectors are stored as - // M x 1 column-matrices + std::vector + params_expval_matrix; // note that diagonal matrices are stored as + // 1 x M row-matrices + // Projector vectors are stored as + // M x 1 column-matrices }; -inline std::ostream& operator<<(std::ostream& s, const Op& op) { +inline std::ostream &operator<<(std::ostream &s, const Op &op) { s << op.name << "["; bool first = true; - for (size_t qubit: op.qubits) { - if (!first) s << ","; + for (size_t qubit : op.qubits) { + if (!first) + s << ","; s << qubit; first = false; } s << "],["; first = true; - for (reg_t reg: op.regs) { - if (!first) s << ","; + for (reg_t reg : op.regs) { + if (!first) + s << ","; s << "["; bool first0 = true; - for (size_t qubit: reg) { - if (!first0) s << ","; + for (size_t qubit : reg) { + if (!first0) + s << ","; s << qubit; first0 = false; } @@ -306,7 +360,8 @@ inline std::ostream& operator<<(std::ostream& s, const Op& op) { // Raise an exception if name string is empty inline void check_empty_name(const Op &op) { if (op.name.empty()) - throw std::invalid_argument(R"(Invalid qobj instruction ("name" is empty).)"); + throw std::invalid_argument( + R"(Invalid qobj instruction ("name" is empty).)"); } // Raise an exception if qubits list is empty @@ -326,8 +381,9 @@ inline void check_empty_params(const Op &op) { // Raise an exception if params is empty inline void check_length_params(const Op &op, const size_t size) { if (op.params.size() != size) - throw std::invalid_argument(R"(Invalid qobj ")" + op.name + - R"(" instruction ("params" is incorrect length).)"); + throw std::invalid_argument( + R"(Invalid qobj ")" + op.name + + R"(" instruction ("params" is incorrect length).)"); } // Raise an exception if qubits list contains duplications @@ -343,7 +399,8 @@ inline void check_duplicate_qubits(const Op &op) { // Generator functions //------------------------------------------------------------------------------ -inline Op make_unitary(const reg_t &qubits, const cmatrix_t &mat, std::string label = "") { +inline Op make_unitary(const reg_t &qubits, const cmatrix_t &mat, + std::string label = "") { Op op; op.type = OpType::matrix; op.name = "unitary"; @@ -354,7 +411,8 @@ inline Op make_unitary(const reg_t &qubits, const cmatrix_t &mat, std::string la return op; } -inline Op make_unitary(const reg_t &qubits, cmatrix_t &&mat, std::string label = "") { +inline Op make_unitary(const reg_t &qubits, cmatrix_t &&mat, + std::string label = "") { Op op; op.type = OpType::matrix; op.name = "unitary"; @@ -366,7 +424,8 @@ inline Op make_unitary(const reg_t &qubits, cmatrix_t &&mat, std::string label = return op; } -inline Op make_diagonal(const reg_t &qubits, cvector_t &&vec, std::string label = "") { +inline Op make_diagonal(const reg_t &qubits, cvector_t &&vec, + std::string label = "") { Op op; op.type = OpType::diagonal_matrix; op.name = "diagonal"; @@ -416,7 +475,8 @@ inline Op make_kraus(const reg_t &qubits, std::vector &&mats) { return op; } -inline Op make_roerror(const reg_t &memory, const std::vector &probs) { +inline Op make_roerror(const reg_t &memory, + const std::vector &probs) { Op op; op.type = OpType::roerror; op.name = "roerror"; @@ -467,7 +527,7 @@ inline Op make_u3(uint_t qubit, T theta, T phi, T lam) { return op; } -inline Op make_reset(const reg_t & qubits, uint_t state = 0) { +inline Op make_reset(const reg_t &qubits, uint_t state = 0) { Op op; op.type = OpType::reset; op.name = "reset"; @@ -533,103 +593,94 @@ inline Op make_multiplexer(const reg_t &qubits, //------------------------------------------------------------------------------ // Main deserialization functions -template -Op input_to_op(const inputdata_t& input); // Partial TODO -json_t op_to_json(const Op &op); // Partial TODO +template +Op input_to_op(const inputdata_t &input); // Partial TODO +json_t op_to_json(const Op &op); // Partial TODO -inline void from_json(const json_t &js, Op &op) {op = input_to_op(js);} +inline void from_json(const json_t &js, Op &op) { op = input_to_op(js); } -inline void to_json(json_t &js, const Op &op) { js = op_to_json(op);} +inline void to_json(json_t &js, const Op &op) { js = op_to_json(op); } -void to_json(json_t &js, const DataSubType& type); +void to_json(json_t &js, const DataSubType &type); // Standard operations -template -Op input_to_op_gate(const inputdata_t& input); -template -Op input_to_op_barrier(const inputdata_t& input); -template -Op input_to_op_measure(const inputdata_t& input); -template -Op input_to_op_reset(const inputdata_t& input); -template -Op input_to_op_bfunc(const inputdata_t& input); -template -Op input_to_op_initialize(const inputdata_t& input); -template -Op input_to_op_pauli(const inputdata_t& input); +template Op input_to_op_gate(const inputdata_t &input); +template +Op input_to_op_barrier(const inputdata_t &input); +template +Op input_to_op_measure(const inputdata_t &input); +template Op input_to_op_reset(const inputdata_t &input); +template Op input_to_op_bfunc(const inputdata_t &input); +template +Op input_to_op_initialize(const inputdata_t &input); +template Op input_to_op_pauli(const inputdata_t &input); // Set state -template -Op input_to_op_set_vector(const inputdata_t& input, OpType op_type); +template +Op input_to_op_set_vector(const inputdata_t &input, OpType op_type); -template -Op input_to_op_set_matrix(const inputdata_t& input, OpType op_type); +template +Op input_to_op_set_matrix(const inputdata_t &input, OpType op_type); -template -Op input_to_op_set_clifford(const inputdata_t& input, OpType op_type); +template +Op input_to_op_set_clifford(const inputdata_t &input, OpType op_type); -template -Op input_to_op_set_mps(const inputdata_t& input, OpType op_type); +template +Op input_to_op_set_mps(const inputdata_t &input, OpType op_type); // Save data -template -Op input_to_op_save_default(const inputdata_t& input, OpType op_type); -template -Op input_to_op_save_expval(const inputdata_t& input, bool variance); -template -Op input_to_op_save_amps(const inputdata_t& input, bool squared); +template +Op input_to_op_save_default(const inputdata_t &input, OpType op_type); +template +Op input_to_op_save_expval(const inputdata_t &input, bool variance); +template +Op input_to_op_save_amps(const inputdata_t &input, bool squared); // Snapshots -template -Op input_to_op_snapshot(const inputdata_t& input); -template -Op input_to_op_snapshot_default(const inputdata_t& input); -template -Op input_to_op_snapshot_matrix(const inputdata_t& input); -template -Op input_to_op_snapshot_pauli(const inputdata_t& input); +template +Op input_to_op_snapshot(const inputdata_t &input); +template +Op input_to_op_snapshot_default(const inputdata_t &input); +template +Op input_to_op_snapshot_matrix(const inputdata_t &input); +template +Op input_to_op_snapshot_pauli(const inputdata_t &input); // Control-Flow -template -Op input_to_op_jump(const inputdata_t& input); -template -Op input_to_op_mark(const inputdata_t& input); +template Op input_to_op_jump(const inputdata_t &input); +template Op input_to_op_mark(const inputdata_t &input); // Matrices -template -Op input_to_op_unitary(const inputdata_t& input); -template -Op input_to_op_diagonal(const inputdata_t& input); -template -Op input_to_op_superop(const inputdata_t& input); -template -Op input_to_op_multiplexer(const inputdata_t& input); -template -Op input_to_op_kraus(const inputdata_t& input); -template -Op input_to_op_noise_switch(const inputdata_t& input); -template -Op input_to_op_qerror_loc(const inputdata_t& input); +template +Op input_to_op_unitary(const inputdata_t &input); +template +Op input_to_op_diagonal(const inputdata_t &input); +template +Op input_to_op_superop(const inputdata_t &input); +template +Op input_to_op_multiplexer(const inputdata_t &input); +template Op input_to_op_kraus(const inputdata_t &input); +template +Op input_to_op_noise_switch(const inputdata_t &input); +template +Op input_to_op_qerror_loc(const inputdata_t &input); // Classical bits -template -Op input_to_op_roerror(const inputdata_t& input); +template +Op input_to_op_roerror(const inputdata_t &input); // Optional instruction parameters -enum class Allowed {Yes, No}; - -template -void add_conditional(const Allowed val, Op& op, const inputdata_t& input); +enum class Allowed { Yes, No }; +template +void add_conditional(const Allowed val, Op &op, const inputdata_t &input); //------------------------------------------------------------------------------ // Implementation: JSON deserialization //------------------------------------------------------------------------------ // TODO: convert if-else to switch -template -Op input_to_op(const inputdata_t& input) { +template Op input_to_op(const inputdata_t &input) { // load operation identifier std::string name; Parser::get_value(name, "name", input); @@ -715,7 +766,7 @@ Op input_to_op(const inputdata_t& input) { if (name == "pauli") return input_to_op_pauli(input); - //Control-flow + // Control-flow if (name == "jump") return input_to_op_jump(input); if (name == "mark") @@ -746,32 +797,30 @@ json_t op_to_json(const Op &op) { return ret; } - -void to_json(json_t &js, const OpType& type) { +void to_json(json_t &js, const OpType &type) { std::stringstream ss; ss << type; js = ss.str(); } - -void to_json(json_t &js, const DataSubType& subtype) { +void to_json(json_t &js, const DataSubType &subtype) { std::stringstream ss; ss << subtype; js = ss.str(); } - //------------------------------------------------------------------------------ // Implementation: Gates, measure, reset deserialization //------------------------------------------------------------------------------ -template -void add_conditional(const Allowed allowed, Op& op, const inputdata_t& input) { +template +void add_conditional(const Allowed allowed, Op &op, const inputdata_t &input) { // Check conditional if (Parser::check_key("conditional", input)) { // If instruction isn't allow to be conditional throw an exception if (allowed == Allowed::No) { - throw std::invalid_argument("Invalid instruction: \"" + op.name + "\" cannot be conditional."); + throw std::invalid_argument("Invalid instruction: \"" + op.name + + "\" cannot be conditional."); } // If instruction is allowed to be conditional add parameters Parser::get_value(op.conditional_reg, "conditional", input); @@ -779,8 +828,7 @@ void add_conditional(const Allowed allowed, Op& op, const inputdata_t& input) { } } -template -Op input_to_op_gate(const inputdata_t& input) { +template Op input_to_op_gate(const inputdata_t &input) { Op op; op.type = OpType::gate; Parser::get_value(op.name, "name", input); @@ -791,7 +839,7 @@ Op input_to_op_gate(const inputdata_t& input) { // If label is not specified record the gate name as the label std::string label; Parser::get_value(label, "label", input); - if (label != "") + if (label != "") op.string_params = {label}; else op.string_params = {op.name}; @@ -812,8 +860,8 @@ Op input_to_op_gate(const inputdata_t& input) { return op; } -template -Op input_to_op_qerror_loc(const inputdata_t& input) { +template +Op input_to_op_qerror_loc(const inputdata_t &input) { Op op; op.type = OpType::qerror_loc; Parser::get_value(op.name, "label", input); @@ -822,7 +870,7 @@ Op input_to_op_qerror_loc(const inputdata_t& input) { return op; } -template +template Op input_to_op_barrier(const inputdata_t &input) { Op op; op.type = OpType::barrier; @@ -833,8 +881,8 @@ Op input_to_op_barrier(const inputdata_t &input) { return op; } -template -Op input_to_op_measure(const inputdata_t& input) { +template +Op input_to_op_measure(const inputdata_t &input) { Op op; op.type = OpType::measure; op.name = "measure"; @@ -849,16 +897,18 @@ Op input_to_op_measure(const inputdata_t& input) { check_empty_qubits(op); check_duplicate_qubits(op); if (op.memory.empty() == false && op.memory.size() != op.qubits.size()) { - throw std::invalid_argument(R"(Invalid measure operation: "memory" and "qubits" are different lengths.)"); + throw std::invalid_argument( + R"(Invalid measure operation: "memory" and "qubits" are different lengths.)"); } - if (op.registers.empty() == false && op.registers.size() != op.qubits.size()) { - throw std::invalid_argument(R"(Invalid measure operation: "register" and "qubits" are different lengths.)"); + if (op.registers.empty() == false && + op.registers.size() != op.qubits.size()) { + throw std::invalid_argument( + R"(Invalid measure operation: "register" and "qubits" are different lengths.)"); } return op; } -template -Op input_to_op_reset(const inputdata_t& input) { +template Op input_to_op_reset(const inputdata_t &input) { Op op; op.type = OpType::reset; op.name = "reset"; @@ -873,8 +923,8 @@ Op input_to_op_reset(const inputdata_t& input) { return op; } -template -Op input_to_op_initialize(const inputdata_t& input) { +template +Op input_to_op_initialize(const inputdata_t &input) { Op op; op.type = OpType::initialize; op.name = "initialize"; @@ -890,8 +940,7 @@ Op input_to_op_initialize(const inputdata_t& input) { check_length_params(op, 1ULL << op.qubits.size()); return op; } -template -Op input_to_op_pauli(const inputdata_t& input){ +template Op input_to_op_pauli(const inputdata_t &input) { Op op; op.type = OpType::gate; op.name = "pauli"; @@ -902,7 +951,7 @@ Op input_to_op_pauli(const inputdata_t& input){ // If label is not specified record the gate name as the label std::string label; Parser::get_value(label, "label", input); - if (label != "") + if (label != "") op.string_params.push_back(label); else op.string_params.push_back(op.name); @@ -920,16 +969,18 @@ Op input_to_op_pauli(const inputdata_t& input){ //------------------------------------------------------------------------------ // Implementation: Boolean Functions //------------------------------------------------------------------------------ -template -Op input_to_op_bfunc(const inputdata_t& input) { +template Op input_to_op_bfunc(const inputdata_t &input) { Op op; op.type = OpType::bfunc; op.name = "bfunc"; op.string_params.resize(2); std::string relation; - Parser::get_value(op.string_params[0], "mask", input); // mask hexadecimal string - Parser::get_value(op.string_params[1], "val", input); // value hexadecimal string - Parser::get_value(relation, "relation", input); // relation string + Parser::get_value(op.string_params[0], "mask", + input); // mask hexadecimal string + Parser::get_value(op.string_params[1], "val", + input); // value hexadecimal string + Parser::get_value(relation, "relation", + input); // relation string // Load single register / memory bit for storing result uint_t tmp; if (Parser::get_value(tmp, "register", input)) { @@ -938,24 +989,25 @@ Op input_to_op_bfunc(const inputdata_t& input) { if (Parser::get_value(tmp, "memory", input)) { op.memory.push_back(tmp); } - + // Format hex strings Utils::format_hex_inplace(op.string_params[0]); Utils::format_hex_inplace(op.string_params[1]); const stringmap_t comp_table({ - {"==", RegComparison::Equal}, - {"!=", RegComparison::NotEqual}, - {"<", RegComparison::Less}, - {"<=", RegComparison::LessEqual}, - {">", RegComparison::Greater}, - {">=", RegComparison::GreaterEqual}, + {"==", RegComparison::Equal}, + {"!=", RegComparison::NotEqual}, + {"<", RegComparison::Less}, + {"<=", RegComparison::LessEqual}, + {">", RegComparison::Greater}, + {">=", RegComparison::GreaterEqual}, }); auto it = comp_table.find(relation); if (it == comp_table.end()) { std::stringstream msg; - msg << "Invalid bfunc relation string :\"" << it->first << "\"." << std::endl; + msg << "Invalid bfunc relation string :\"" << it->first << "\"." + << std::endl; throw std::invalid_argument(msg.str()); } else { op.bfunc = it->second; @@ -966,13 +1018,14 @@ Op input_to_op_bfunc(const inputdata_t& input) { // Validation if (op.registers.empty()) { - throw std::invalid_argument("Invalid measure operation: \"register\" is empty."); + throw std::invalid_argument( + "Invalid measure operation: \"register\" is empty."); } return op; } -template -Op input_to_op_roerror(const inputdata_t& input) { +template +Op input_to_op_roerror(const inputdata_t &input) { Op op; op.type = OpType::roerror; op.name = "roerror"; @@ -987,8 +1040,8 @@ Op input_to_op_roerror(const inputdata_t& input) { //------------------------------------------------------------------------------ // Implementation: Matrix and Kraus deserialization //------------------------------------------------------------------------------ -template -Op input_to_op_unitary(const inputdata_t& input) { +template +Op input_to_op_unitary(const inputdata_t &input) { Op op; op.type = OpType::matrix; op.name = "unitary"; @@ -1014,8 +1067,8 @@ Op input_to_op_unitary(const inputdata_t& input) { add_conditional(Allowed::Yes, op, input); return op; } -template -Op input_to_op_diagonal(const inputdata_t& input) { +template +Op input_to_op_diagonal(const inputdata_t &input) { Op op; op.type = OpType::diagonal_matrix; op.name = "diagonal"; @@ -1043,8 +1096,8 @@ Op input_to_op_diagonal(const inputdata_t& input) { add_conditional(Allowed::Yes, op, input); return op; } -template -Op input_to_op_superop(const inputdata_t& input) { +template +Op input_to_op_superop(const inputdata_t &input) { // Warning: we don't check superoperator is valid! Op op; op.type = OpType::superop; @@ -1061,8 +1114,8 @@ Op input_to_op_superop(const inputdata_t& input) { } return op; } -template -Op input_to_op_multiplexer(const inputdata_t& input) { +template +Op input_to_op_multiplexer(const inputdata_t &input) { // Parse parameters reg_t qubits; std::vector mats; @@ -1076,8 +1129,7 @@ Op input_to_op_multiplexer(const inputdata_t& input) { add_conditional(Allowed::Yes, op, input); return op; } -template -Op input_to_op_kraus(const inputdata_t& input) { +template Op input_to_op_kraus(const inputdata_t &input) { Op op; op.type = OpType::kraus; op.name = "kraus"; @@ -1092,8 +1144,8 @@ Op input_to_op_kraus(const inputdata_t& input) { return op; } -template -Op input_to_op_noise_switch(const inputdata_t& input) { +template +Op input_to_op_noise_switch(const inputdata_t &input) { Op op; op.type = OpType::noise_switch; op.name = "noise_switch"; @@ -1106,48 +1158,53 @@ Op input_to_op_noise_switch(const inputdata_t& input) { //------------------------------------------------------------------------------ // Implementation: Set state //------------------------------------------------------------------------------ -template +template Op input_to_op_set_vector(const inputdata_t &input, OpType op_type) { Op op; op.type = op_type; - const inputdata_t& params = Parser::get_value("params", input); - op.params = Parser::template get_list_elem>(params, 0); + const inputdata_t ¶ms = Parser::get_value("params", input); + op.params = + Parser::template get_list_elem>( + params, 0); Parser::get_value(op.name, "name", input); Parser::get_value(op.qubits, "qubits", input); add_conditional(Allowed::No, op, input); return op; } -template +template Op input_to_op_set_matrix(const inputdata_t &input, OpType op_type) { Op op; op.type = op_type; - const inputdata_t& params = Parser::get_value("params", input); - op.mats.push_back(Parser::template get_list_elem(params, 0)); + const inputdata_t ¶ms = Parser::get_value("params", input); + op.mats.push_back( + Parser::template get_list_elem(params, 0)); Parser::get_value(op.name, "name", input); Parser::get_value(op.qubits, "qubits", input); add_conditional(Allowed::No, op, input); return op; } -template +template Op input_to_op_set_clifford(const inputdata_t &input, OpType op_type) { Op op; op.type = op_type; - const inputdata_t& params = Parser::get_value("params", input); - op.clifford = Parser::template get_list_elem(params, 0); + const inputdata_t ¶ms = Parser::get_value("params", input); + op.clifford = Parser::template get_list_elem( + params, 0); Parser::get_value(op.name, "name", input); Parser::get_value(op.qubits, "qubits", input); add_conditional(Allowed::No, op, input); return op; } -template +template Op input_to_op_set_mps(const inputdata_t &input, OpType op_type) { Op op; op.type = op_type; - const inputdata_t& params = Parser::get_value("params", input); - op.mps = Parser::template get_list_elem(params, 0); + const inputdata_t ¶ms = Parser::get_value("params", input); + op.mps = + Parser::template get_list_elem(params, 0); Parser::get_value(op.name, "name", input); Parser::get_value(op.qubits, "qubits", input); @@ -1158,22 +1215,18 @@ Op input_to_op_set_mps(const inputdata_t &input, OpType op_type) { //------------------------------------------------------------------------------ // Implementation: Save data deserialization //------------------------------------------------------------------------------ -template -Op input_to_op_save_default(const inputdata_t& input, OpType op_type) { +template +Op input_to_op_save_default(const inputdata_t &input, OpType op_type) { Op op; op.type = op_type; Parser::get_value(op.name, "name", input); // Get subtype - static const std::unordered_map subtypes { - {"single", DataSubType::single}, - {"c_single", DataSubType::c_single}, - {"average", DataSubType::average}, - {"c_average", DataSubType::c_average}, - {"list", DataSubType::list}, - {"c_list", DataSubType::c_list}, - {"accum", DataSubType::accum}, - {"c_accum", DataSubType::c_accum}, + static const std::unordered_map subtypes{ + {"single", DataSubType::single}, {"c_single", DataSubType::c_single}, + {"average", DataSubType::average}, {"c_average", DataSubType::c_average}, + {"list", DataSubType::list}, {"c_list", DataSubType::c_list}, + {"accum", DataSubType::accum}, {"c_accum", DataSubType::c_accum}, }; std::string subtype; Parser::get_value(subtype, "snapshot_type", input); @@ -1183,7 +1236,7 @@ Op input_to_op_save_default(const inputdata_t& input, OpType op_type) { "\" in save data instruction."); } op.save_type = subtype_it->second; - + // Get data key op.string_params.emplace_back(""); Parser::get_value(op.string_params[0], "label", input); @@ -1192,26 +1245,30 @@ Op input_to_op_save_default(const inputdata_t& input, OpType op_type) { Parser::get_value(op.qubits, "qubits", input); return op; } -template -Op input_to_op_save_expval(const inputdata_t& input, bool variance) { +template +Op input_to_op_save_expval(const inputdata_t &input, bool variance) { // Initialized default save instruction params - auto op_type = (variance) ? OpType::save_expval_var - : OpType::save_expval; + auto op_type = (variance) ? OpType::save_expval_var : OpType::save_expval; Op op = input_to_op_save_default(input, op_type); // Parse Pauli operator components const auto threshold = 1e-12; // drop small components // Get components - if (Parser::check_key("params", input) && Parser::is_array("params", input)) { + if (Parser::check_key("params", input) && + Parser::is_array("params", input)) { for (const auto &comp_ : Parser::get_value("params", input)) { - const auto& comp = Parser::get_as_list(comp_); + const auto &comp = Parser::get_as_list(comp_); // Get complex coefficient - std::vector coeffs = Parser::template get_list_elem>(comp, 1); + std::vector coeffs = + Parser::template get_list_elem>(comp, + 1); if (std::abs(coeffs[0]) > threshold || std::abs(coeffs[1]) > threshold) { - std::string pauli = Parser::template get_list_elem(comp, 0); + std::string pauli = + Parser::template get_list_elem(comp, 0); if (pauli.size() != op.qubits.size()) { - throw std::invalid_argument(std::string("Invalid expectation value save instruction ") + - "(Pauli label does not match qubit number.)."); + throw std::invalid_argument( + std::string("Invalid expectation value save instruction ") + + "(Pauli label does not match qubit number.)."); } op.expval_params.emplace_back(pauli, coeffs[0], coeffs[1]); } @@ -1230,11 +1287,10 @@ Op input_to_op_save_expval(const inputdata_t& input, bool variance) { return op; } -template -Op input_to_op_save_amps(const inputdata_t& input, bool squared) { +template +Op input_to_op_save_amps(const inputdata_t &input, bool squared) { // Initialized default save instruction params - auto op_type = (squared) ? OpType::save_amps_sq - : OpType::save_amps; + auto op_type = (squared) ? OpType::save_amps_sq : OpType::save_amps; Op op = input_to_op_save_default(input, op_type); Parser::get_value(op.int_params, "params", input); return op; @@ -1243,10 +1299,11 @@ Op input_to_op_save_amps(const inputdata_t& input, bool squared) { //------------------------------------------------------------------------------ // Implementation: Snapshot deserialization //------------------------------------------------------------------------------ -template -Op input_to_op_snapshot(const inputdata_t& input) { +template +Op input_to_op_snapshot(const inputdata_t &input) { std::string snapshot_type; - Parser::get_value(snapshot_type, "snapshot_type", input); // LEGACY: to remove in 0.3 + Parser::get_value(snapshot_type, "snapshot_type", + input); // LEGACY: to remove in 0.3 Parser::get_value(snapshot_type, "type", input); if (snapshot_type.find("expectation_value_pauli") != std::string::npos) return input_to_op_snapshot_pauli(input); @@ -1259,11 +1316,12 @@ Op input_to_op_snapshot(const inputdata_t& input) { return op; } -template -Op input_to_op_snapshot_default(const inputdata_t& input) { +template +Op input_to_op_snapshot_default(const inputdata_t &input) { Op op; op.type = OpType::snapshot; - Parser::get_value(op.name, "type", input); // LEGACY: to remove in 0.3 + Parser::get_value(op.name, "type", + input); // LEGACY: to remove in 0.3 Parser::get_value(op.name, "snapshot_type", input); // If missing use "default" for label op.string_params.emplace_back("default"); @@ -1275,39 +1333,46 @@ Op input_to_op_snapshot_default(const inputdata_t& input) { return op; } -template -Op input_to_op_snapshot_pauli(const inputdata_t& input) { +template +Op input_to_op_snapshot_pauli(const inputdata_t &input) { Op op = input_to_op_snapshot_default(input); const auto threshold = 1e-15; // drop small components // Get components - if (Parser::check_key("params", input) && Parser::is_array("params", input)) { + if (Parser::check_key("params", input) && + Parser::is_array("params", input)) { for (const auto &comp_ : Parser::get_value("params", input)) { // Check component is length-2 array - const auto& comp = Parser::get_as_list(comp_); + const auto &comp = Parser::get_as_list(comp_); if (comp.size() != 2) - throw std::invalid_argument("Invalid Pauli expval params (param component " + - Parser::dump(comp) + " invalid)."); + throw std::invalid_argument( + "Invalid Pauli expval params (param component " + + Parser::dump(comp) + " invalid)."); // Get complex coefficient - complex_t coeff = Parser::template get_list_elem(comp, 0); + complex_t coeff = + Parser::template get_list_elem(comp, 0); // If coefficient is above threshold, get the Pauli operator string // This string may contain I, X, Y, Z // qubits are stored as a list where position is qubit number: // eq op.qubits = [a, b, c], a is qubit-0, b is qubit-1, c is qubit-2 // Pauli string labels are stored in little-endian ordering: - // eg label = "CBA", A is the Pauli for qubit-0, B for qubit-1, C for qubit-2 + // eg label = "CBA", A is the Pauli for qubit-0, B for qubit-1, C for + // qubit-2 if (std::abs(coeff) > threshold) { - std::string pauli = Parser::template get_list_elem(comp, 1); + std::string pauli = + Parser::template get_list_elem(comp, 1); if (pauli.size() != op.qubits.size()) { - throw std::invalid_argument(std::string("Invalid Pauli expectation value snapshot ") + - "(Pauli label does not match qubit number.)."); + throw std::invalid_argument( + std::string("Invalid Pauli expectation value snapshot ") + + "(Pauli label does not match qubit number.)."); } // make tuple and add to components op.params_expval_pauli.emplace_back(coeff, pauli); } // end if > threshold - } // end component loop + } // end component loop } else { - throw std::invalid_argument("Invalid Pauli expectation value value snapshot \"params\"."); + throw std::invalid_argument( + "Invalid Pauli expectation value value snapshot \"params\"."); } // Check edge case of all coefficients being empty // In this case the operator had all coefficients zero, or sufficiently close @@ -1322,45 +1387,56 @@ Op input_to_op_snapshot_pauli(const inputdata_t& input) { return op; } -template -Op input_to_op_snapshot_matrix(const inputdata_t& input) { +template +Op input_to_op_snapshot_matrix(const inputdata_t &input) { // Load default snapshot parameters Op op = input_to_op_snapshot_default(input); const auto threshold = 1e-10; // drop small components // Get matrix operator components // TODO: fix repeated throw string - if (Parser::check_key("params", input) && Parser::is_array("params", input)) { + if (Parser::check_key("params", input) && + Parser::is_array("params", input)) { for (const auto &comp_ : Parser::get_value("params", input)) { - const auto& comp = Parser::get_as_list(comp_); + const auto &comp = Parser::get_as_list(comp_); // Check component is length-2 array if (comp.size() != 2) { - throw std::invalid_argument("Invalid matrix expval snapshot (param component " + - Parser::dump(comp) + " invalid)."); + throw std::invalid_argument( + "Invalid matrix expval snapshot (param component " + + Parser::dump(comp) + " invalid)."); } // Get complex coefficient - complex_t coeff = Parser::template get_list_elem(comp, 0); + complex_t coeff = + Parser::template get_list_elem(comp, 0); std::vector> mats; if (std::abs(coeff) > threshold) { - const inputdata_t& comp_list = comp[1]; + const inputdata_t &comp_list = comp[1]; if (!Parser::is_array(comp_list)) { - throw std::invalid_argument("Invalid matrix expval snapshot (param component " + - Parser::dump(comp) + " invalid)."); + throw std::invalid_argument( + "Invalid matrix expval snapshot (param component " + + Parser::dump(comp) + " invalid)."); } for (const auto &subcomp_ : comp_list) { - const auto& subcomp = Parser::get_as_list(subcomp_); + const auto &subcomp = Parser::get_as_list(subcomp_); if (subcomp.size() != 2) { - throw std::invalid_argument("Invalid matrix expval snapshot (param component " + - Parser::dump(comp) + " invalid)."); + throw std::invalid_argument( + "Invalid matrix expval snapshot (param component " + + Parser::dump(comp) + " invalid)."); } - reg_t comp_qubits = Parser::template get_list_elem(subcomp, 0); - cmatrix_t comp_matrix = Parser::template get_list_elem(subcomp, 1); + reg_t comp_qubits = + Parser::template get_list_elem(subcomp, 0); + cmatrix_t comp_matrix = + Parser::template get_list_elem(subcomp, + 1); // Check qubits are ok - // TODO: check that qubits are in range from 0 to Num of Qubits - 1 for instr - std::unordered_set unique = {comp_qubits.begin(), comp_qubits.end()}; + // TODO: check that qubits are in range from 0 to Num of Qubits - 1 + // for instr + std::unordered_set unique = {comp_qubits.begin(), + comp_qubits.end()}; if (unique.size() != comp_qubits.size()) { - throw std::invalid_argument("Invalid matrix expval snapshot (param component " + - Parser::dump(comp) + " invalid)."); + throw std::invalid_argument( + "Invalid matrix expval snapshot (param component " + + Parser::dump(comp) + " invalid)."); } mats.emplace_back(comp_qubits, comp_matrix); } @@ -1368,21 +1444,22 @@ Op input_to_op_snapshot_matrix(const inputdata_t& input) { } } // end component loop } else { - throw std::invalid_argument(std::string("Invalid matrix expectation value snapshot ") + - "(\"params\" field missing)."); + throw std::invalid_argument( + std::string("Invalid matrix expectation value snapshot ") + + "(\"params\" field missing)."); } return op; } -template -Op input_to_op_jump(const inputdata_t &input) { +template Op input_to_op_jump(const inputdata_t &input) { Op op; op.type = OpType::jump; op.name = "jump"; Parser::get_value(op.qubits, "qubits", input); Parser::get_value(op.string_params, "params", input); if (op.string_params.empty()) - throw std::invalid_argument(std::string("Invalid jump (\"params\" field missing).")); + throw std::invalid_argument( + std::string("Invalid jump (\"params\" field missing).")); // Conditional add_conditional(Allowed::Yes, op, input); @@ -1390,15 +1467,15 @@ Op input_to_op_jump(const inputdata_t &input) { return op; } -template -Op input_to_op_mark(const inputdata_t &input) { +template Op input_to_op_mark(const inputdata_t &input) { Op op; op.type = OpType::mark; op.name = "mark"; Parser::get_value(op.qubits, "qubits", input); Parser::get_value(op.string_params, "params", input); if (op.string_params.empty()) - throw std::invalid_argument(std::string("Invalid mark (\"params\" field missing).")); + throw std::invalid_argument( + std::string("Invalid mark (\"params\" field missing).")); // Conditional add_conditional(Allowed::No, op, input); @@ -1406,7 +1483,6 @@ Op input_to_op_mark(const inputdata_t &input) { return op; } - //------------------------------------------------------------------------------ } // end namespace Operations //------------------------------------------------------------------------------ diff --git a/src/framework/opset.hpp b/src/framework/opset.hpp old mode 100755 new mode 100644 index 850b1e6bfd..c0d793647a --- a/src/framework/opset.hpp +++ b/src/framework/opset.hpp @@ -15,8 +15,8 @@ #ifndef _aer_framework_opset_hpp_ #define _aer_framework_opset_hpp_ -#include #include "framework/operations.hpp" +#include namespace AER { namespace Operations { diff --git a/src/framework/pybind_basics.hpp b/src/framework/pybind_basics.hpp old mode 100755 new mode 100644 index e32f214482..a27d9f7e0f --- a/src/framework/pybind_basics.hpp +++ b/src/framework/pybind_basics.hpp @@ -44,14 +44,15 @@ template py::object to_python(AER::Vector &&obj); // Move a Vector to Python via recusivly calling to_python on elements template py::object to_python(std::vector &&obj); -// Move an Unordered string map to Python object by calling to_python on elements -template py::object to_python(std::unordered_map &&obj); +// Move an Unordered string map to Python object by calling to_python on +// elements +template +py::object to_python(std::unordered_map &&obj); // Move an Unordered string map into an existing Python dict template void add_to_python(py::dict &pydata, std::unordered_map &&obj); - // Template specialization for moving numeric std::vectors to Numpy arrays template <> py::object to_python(std::vector &&obj); template <> py::object to_python(std::vector &&obj); @@ -73,12 +74,10 @@ template py::array_t to_numpy(matrix &&obj); // Convert a Vector to a 1D Numpy array -template -py::array_t to_numpy(AER::Vector &&obj); +template py::array_t to_numpy(AER::Vector &&obj); // Convert a vector to a 1D Numpy array -template -py::array_t to_numpy(std::vector &&obj); +template py::array_t to_numpy(std::vector &&obj); //============================================================================ // Implementation @@ -88,13 +87,11 @@ py::array_t to_numpy(std::vector &&obj); // Basic Types //------------------------------------------------------------------------------ -template -py::object to_python(T &&obj) { +template py::object to_python(T &&obj) { return py::cast(obj, py::return_value_policy::move); } -template <> -py::object to_python(json_t &&obj) { +template <> py::object to_python(json_t &&obj) { py::object pydata; from_json(obj, pydata); return pydata; @@ -109,57 +106,48 @@ py::object to_python(std::unordered_map &&obj) { template void add_to_python(py::dict &pydata, std::unordered_map &&obj) { - for(auto& elt : obj) { + for (auto &elt : obj) { pydata[elt.first.data()] = to_python(std::move(elt.second)); } } -template -py::object to_python(std::vector &&obj) { +template py::object to_python(std::vector &&obj) { py::list pydata; - for(auto& elt : obj) { + for (auto &elt : obj) { pydata.append(to_python(std::move(elt))); } return std::move(pydata); } -template -py::object to_python(matrix &&obj) { +template py::object to_python(matrix &&obj) { return to_numpy(std::move(obj)); } -template -py::object to_python(AER::Vector &&obj) { +template py::object to_python(AER::Vector &&obj) { return to_numpy(std::move(obj)); } -template <> -py::object to_python(std::vector &&obj) { +template <> py::object to_python(std::vector &&obj) { return to_numpy(std::move(obj)); } -template <> -py::object to_python(std::vector &&obj) { +template <> py::object to_python(std::vector &&obj) { return to_numpy(std::move(obj)); } -template <> -py::object to_python(std::vector &&obj) { +template <> py::object to_python(std::vector &&obj) { return to_numpy(std::move(obj)); } -template <> -py::object to_python(std::vector &&obj) { +template <> py::object to_python(std::vector &&obj) { return to_numpy(std::move(obj)); } -template <> -py::object to_python(std::vector> &&obj) { +template <> py::object to_python(std::vector> &&obj) { return to_numpy(std::move(obj)); } -template <> -py::object to_python(std::vector> &&obj) { +template <> py::object to_python(std::vector> &&obj) { return to_numpy(std::move(obj)); } @@ -169,39 +157,37 @@ py::object to_python(std::vector> &&obj) { template py::array_t to_numpy(matrix &&src) { - std::array shape {static_cast(src.GetRows()), - static_cast(src.GetColumns())}; - matrix* src_ptr = new matrix(std::move(src)); - auto capsule = py::capsule(src_ptr, [](void* p) { delete reinterpret_cast*>(p); }); + std::array shape{static_cast(src.GetRows()), + static_cast(src.GetColumns())}; + matrix *src_ptr = new matrix(std::move(src)); + auto capsule = py::capsule( + src_ptr, [](void *p) { delete reinterpret_cast *>(p); }); return py::array_t(shape, src_ptr->data(), capsule); } -template -py::array_t to_numpy(AER::Vector &&src) { - AER::Vector* src_ptr = new AER::Vector(std::move(src)); - auto capsule = py::capsule(src_ptr, [](void* p) { - delete reinterpret_cast*>(p); - }); +template py::array_t to_numpy(AER::Vector &&src) { + AER::Vector *src_ptr = new AER::Vector(std::move(src)); + auto capsule = py::capsule( + src_ptr, [](void *p) { delete reinterpret_cast *>(p); }); return py::array_t( - src_ptr->size(), // shape of array - src_ptr->data(), // c-style contiguous strides for vector - capsule // numpy array references this parent + src_ptr->size(), // shape of array + src_ptr->data(), // c-style contiguous strides for vector + capsule // numpy array references this parent ); } - -template -py::array_t to_numpy(std::vector &&src) { - std::vector* src_ptr = new std::vector(std::move(src)); - auto capsule = py::capsule(src_ptr, [](void* p) { delete reinterpret_cast*>(p); }); +template py::array_t to_numpy(std::vector &&src) { + std::vector *src_ptr = new std::vector(std::move(src)); + auto capsule = py::capsule( + src_ptr, [](void *p) { delete reinterpret_cast *>(p); }); return py::array_t( - src_ptr->size(), // shape of array - src_ptr->data(), // c-style contiguous strides for vector - capsule // numpy array references this parent + src_ptr->size(), // shape of array + src_ptr->data(), // c-style contiguous strides for vector + capsule // numpy array references this parent ); } //------------------------------------------------------------------------------ -} // end namespace AerToPy +} // end namespace AerToPy //------------------------------------------------------------------------------ #endif diff --git a/src/framework/pybind_casts.hpp b/src/framework/pybind_casts.hpp index de59f6de37..49119a6917 100644 --- a/src/framework/pybind_casts.hpp +++ b/src/framework/pybind_casts.hpp @@ -16,60 +16,67 @@ #define _aer_framework_pybind_casts_hpp_ #include "../simulators/stabilizer/clifford.hpp" +#include namespace py = pybind11; namespace pybind11 { namespace detail { -template struct type_caster>{ +template struct type_caster> { using base = type_caster_base>; + public: PYBIND11_TYPE_CASTER(matrix, _("matrix_t")); // Conversion part 1 (Python->C++): - bool load(py::handle src, bool convert){ - // TODO: Check if make sense have to flavors of matrix: F-style and C-style - auto py_matrix = py::cast>(src); - auto c_order = py_matrix.attr("flags").attr("carray").template cast(); - if(py_matrix.ndim() != 2){ - throw std::invalid_argument(std::string("Python: invalid matrix (empty array).")); - } - size_t nrows = py_matrix.shape(0); - size_t ncols = py_matrix.shape(1); - // Matrix looks ok, now we parse it - auto raw_mat = py_matrix.template unchecked<2>(); - if(c_order){ - value = matrix(nrows, ncols, false); - for (size_t r = 0; r < nrows; r++) { - for (size_t c = 0; c < ncols; c++) { - value(r, c) = raw_mat(r, c); - } - } - } else { - value = matrix::copy_from_buffer(nrows, ncols, static_cast(py_matrix.request().ptr)); + bool load(py::handle src, bool convert) { + // TODO: Check if make sense have to flavors of matrix: F-style and C-style + auto py_matrix = py::cast>(src); + auto c_order = py_matrix.attr("flags").attr("carray").template cast(); + if (py_matrix.ndim() != 2) { + throw std::invalid_argument( + std::string("Python: invalid matrix (empty array).")); + } + size_t nrows = py_matrix.shape(0); + size_t ncols = py_matrix.shape(1); + // Matrix looks ok, now we parse it + auto raw_mat = py_matrix.template unchecked<2>(); + if (c_order) { + value = matrix(nrows, ncols, false); + for (size_t r = 0; r < nrows; r++) { + for (size_t c = 0; c < ncols; c++) { + value(r, c) = raw_mat(r, c); + } } - return true; + } else { + value = matrix::copy_from_buffer( + nrows, ncols, static_cast(py_matrix.request().ptr)); + } + return true; } // Conversion part 2 (C++ -> Python): - static py::handle cast(matrix, py::return_value_policy policy, py::handle parent){ - throw std::runtime_error("Casting from matrix to python not supported."); + static py::handle cast(matrix, py::return_value_policy policy, + py::handle parent) { + throw std::runtime_error("Casting from matrix to python not supported."); } }; -template <> struct type_caster{ - using base = type_caster_base; +template <> struct type_caster { + using base = type_caster_base; + public: - PYBIND11_TYPE_CASTER(Clifford::Clifford, _("clifford")); - // Conversion part 1 (Python->C++): - bool load(py::handle src, bool convert){ - Clifford::build_from(src, value); - return true; - } - // Conversion part 2 (C++ -> Python): - static py::handle cast(Clifford::Clifford, py::return_value_policy policy, py::handle parent){ - throw std::runtime_error("Casting from Clifford to python not supported."); - } + PYBIND11_TYPE_CASTER(Clifford::Clifford, _("clifford")); + // Conversion part 1 (Python->C++): + bool load(py::handle src, bool convert) { + Clifford::build_from(src, value); + return true; + } + // Conversion part 2 (C++ -> Python): + static py::handle cast(Clifford::Clifford, py::return_value_policy policy, + py::handle parent) { + throw std::runtime_error("Casting from Clifford to python not supported."); + } }; -} -} +} // namespace detail +} // namespace pybind11 #endif // _aer_framework_pybind_casts_hpp_ \ No newline at end of file diff --git a/src/framework/pybind_json.hpp b/src/framework/pybind_json.hpp old mode 100755 new mode 100644 index de06755d73..b747e75dc4 --- a/src/framework/pybind_json.hpp +++ b/src/framework/pybind_json.hpp @@ -26,18 +26,17 @@ #include #include #include -#include #include -#include #include +#include #include "misc/warnings.hpp" DISABLE_WARNING_PUSH -#include #include -#include #include #include +#include +#include #include DISABLE_WARNING_POP @@ -109,9 +108,9 @@ json_t numpy_to_json_2d(py::array_t arr); template json_t numpy_to_json_3d(py::array_t arr); -json_t iterable_to_json_list(const py::handle& obj); +json_t iterable_to_json_list(const py::handle &obj); -} //end namespace JSON +} // end namespace JSON /******************************************************************************* * @@ -125,187 +124,191 @@ json_t iterable_to_json_list(const py::handle& obj); template json_t JSON::numpy_to_json_1d(py::array_t arr) { - py::buffer_info buf = arr.request(); - if (buf.ndim != 1) { - throw std::runtime_error("Number of dims must be 1"); - } + py::buffer_info buf = arr.request(); + if (buf.ndim != 1) { + throw std::runtime_error("Number of dims must be 1"); + } - T *ptr = (T *) buf.ptr; - size_t D0 = buf.shape[0]; + T *ptr = (T *)buf.ptr; + size_t D0 = buf.shape[0]; - std::vector tbr; // to be returned - for (size_t n0 = 0; n0 < D0; n0++) - tbr.push_back(ptr[n0]); + std::vector tbr; // to be returned + for (size_t n0 = 0; n0 < D0; n0++) + tbr.push_back(ptr[n0]); - return std::move(tbr); + return std::move(tbr); } template json_t JSON::numpy_to_json_2d(py::array_t arr) { - py::buffer_info buf = arr.request(); - if (buf.ndim != 2) { - throw std::runtime_error("Number of dims must be 2"); - } - - T *ptr = (T *) buf.ptr; - size_t D0 = buf.shape[0]; - size_t D1 = buf.shape[1]; - - std::vector > tbr; // to be returned - for (size_t n0 = 0; n0 < D0; n0++) { - std::vector tbr1; - for (size_t n1 = 0; n1 < D1; n1++) { - tbr1.push_back(ptr[n1 + D1*n0]); - } - tbr.push_back(tbr1); + py::buffer_info buf = arr.request(); + if (buf.ndim != 2) { + throw std::runtime_error("Number of dims must be 2"); + } + + T *ptr = (T *)buf.ptr; + size_t D0 = buf.shape[0]; + size_t D1 = buf.shape[1]; + + std::vector> tbr; // to be returned + for (size_t n0 = 0; n0 < D0; n0++) { + std::vector tbr1; + for (size_t n1 = 0; n1 < D1; n1++) { + tbr1.push_back(ptr[n1 + D1 * n0]); } + tbr.push_back(tbr1); + } - return std::move(tbr); - + return std::move(tbr); } template json_t JSON::numpy_to_json_3d(py::array_t arr) { - py::buffer_info buf = arr.request(); - if (buf.ndim != 3) { - throw std::runtime_error("Number of dims must be 3"); - } - T *ptr = (T *) buf.ptr; - size_t D0 = buf.shape[0]; - size_t D1 = buf.shape[1]; - size_t D2 = buf.shape[2]; - - // to be returned - std::vector > > tbr; - for (size_t n0 = 0; n0 < D0; n0++) { - std::vector > tbr1; - for (size_t n1 = 0; n1 < D1; n1++) { - std::vector tbr2; - for (size_t n2 = 0; n2 < D2; n2++) { - tbr2.push_back(ptr[n2 + D2*(n1 + D1*n0)]); - } - tbr1.push_back(tbr2); - } - tbr.push_back(tbr1); + py::buffer_info buf = arr.request(); + if (buf.ndim != 3) { + throw std::runtime_error("Number of dims must be 3"); + } + T *ptr = (T *)buf.ptr; + size_t D0 = buf.shape[0]; + size_t D1 = buf.shape[1]; + size_t D2 = buf.shape[2]; + + // to be returned + std::vector>> tbr; + for (size_t n0 = 0; n0 < D0; n0++) { + std::vector> tbr1; + for (size_t n1 = 0; n1 < D1; n1++) { + std::vector tbr2; + for (size_t n2 = 0; n2 < D2; n2++) { + tbr2.push_back(ptr[n2 + D2 * (n1 + D1 * n0)]); + } + tbr1.push_back(tbr2); } + tbr.push_back(tbr1); + } - return std::move(tbr); - + return std::move(tbr); } template json_t JSON::numpy_to_json(py::array_t arr) { - py::buffer_info buf = arr.request(); - - if (buf.ndim == 1) { - return JSON::numpy_to_json_1d(arr); - } else if (buf.ndim == 2) { - return JSON::numpy_to_json_2d(arr); - } else if (buf.ndim == 3) { - return JSON::numpy_to_json_3d(arr); - } else { - throw std::runtime_error("Invalid number of dimensions!"); - } - json_t tbr; - return tbr; + py::buffer_info buf = arr.request(); + + if (buf.ndim == 1) { + return JSON::numpy_to_json_1d(arr); + } else if (buf.ndim == 2) { + return JSON::numpy_to_json_2d(arr); + } else if (buf.ndim == 3) { + return JSON::numpy_to_json_3d(arr); + } else { + throw std::runtime_error("Invalid number of dimensions!"); + } + json_t tbr; + return tbr; } -json_t JSON::iterable_to_json_list(const py::handle& obj){ - json_t js = nl::json::array(); - for (py::handle value: obj) { - js.push_back(value); - } - return js; +json_t JSON::iterable_to_json_list(const py::handle &obj) { + json_t js = nl::json::array(); + for (py::handle value : obj) { + js.push_back(value); + } + return js; } void std::to_json(json_t &js, const py::handle &obj) { - static py::object PyNoiseModel = py::module::import("qiskit_aer.noise.noise_model").attr("NoiseModel"); - static py::object PyQasmQobj = py::module::import("qiskit.qobj.qasm_qobj").attr("QasmQobj"); - if (py::isinstance(obj)) { - js = obj.cast(); - } else if (py::isinstance(obj)) { - js = obj.cast(); - } else if (py::isinstance(obj)) { - js = obj.cast(); - } else if (py::isinstance(obj)) { - js = obj.cast(); - } else if (py::isinstance(obj) || py::isinstance(obj)) { - js = JSON::iterable_to_json_list(obj); - } else if (py::isinstance(obj)) { - for (auto item : py::cast(obj)) { - js[item.first.cast()] = item.second; - } - } else if (py::isinstance >(obj)) { - js = JSON::numpy_to_json(obj.cast >()); - } else if (py::isinstance > >(obj)) { - js = JSON::numpy_to_json(obj.cast, py::array::c_style> >()); - } else if (obj.is_none()) { - return; - } else if (py::isinstance(obj, PyNoiseModel)){ - std::to_json(js, obj.attr("to_dict")()); - } else if (py::isinstance(obj, PyQasmQobj)){ - std::to_json(js, obj.attr("to_dict")()); + static py::object PyNoiseModel = + py::module::import("qiskit_aer.noise.noise_model").attr("NoiseModel"); + static py::object PyQasmQobj = + py::module::import("qiskit.qobj.qasm_qobj").attr("QasmQobj"); + if (py::isinstance(obj)) { + js = obj.cast(); + } else if (py::isinstance(obj)) { + js = obj.cast(); + } else if (py::isinstance(obj)) { + js = obj.cast(); + } else if (py::isinstance(obj)) { + js = obj.cast(); + } else if (py::isinstance(obj) || py::isinstance(obj)) { + js = JSON::iterable_to_json_list(obj); + } else if (py::isinstance(obj)) { + for (auto item : py::cast(obj)) { + js[item.first.cast()] = item.second; + } + } else if (py::isinstance>(obj)) { + js = JSON::numpy_to_json( + obj.cast>()); + } else if (py::isinstance>>(obj)) { + js = JSON::numpy_to_json( + obj.cast, py::array::c_style>>()); + } else if (obj.is_none()) { + return; + } else if (py::isinstance(obj, PyNoiseModel)) { + std::to_json(js, obj.attr("to_dict")()); + } else if (py::isinstance(obj, PyQasmQobj)) { + std::to_json(js, obj.attr("to_dict")()); + } else { + auto type_str = std::string(py::str(obj.get_type())); + if (type_str == "" || + type_str == "" || + type_str == "" || + type_str == "") { + auto tmp = obj.cast>(); + js.push_back(tmp.real()); + js.push_back(tmp.imag()); + } else if (type_str == "" || + type_str == "" || + type_str == "" || + type_str == "") { + js = obj.cast(); + } else if (type_str == "" || + type_str == "") { + js = obj.cast(); + } else if (py::isinstance( + obj)) { // last one to avoid intercepting numpy arrays, etc + js = JSON::iterable_to_json_list(obj); } else { - auto type_str = std::string(py::str(obj.get_type())); - if ( type_str == "" - || type_str == "" - || type_str == "" - || type_str == "" ) { - auto tmp = obj.cast>(); - js.push_back(tmp.real()); - js.push_back(tmp.imag()); - } else if ( type_str == "" - || type_str == "" - || type_str == "" - || type_str == "" ) { - js = obj.cast(); - } else if ( type_str == "" - || type_str == "" ) { - js = obj.cast(); - } else if ( py::isinstance(obj) ){ // last one to avoid intercepting numpy arrays, etc - js = JSON::iterable_to_json_list(obj); - } else { - throw std::runtime_error("to_json not implemented for this type of object: " + std::string(py::str(obj.get_type()))); - } + throw std::runtime_error( + "to_json not implemented for this type of object: " + + std::string(py::str(obj.get_type()))); } + } } void std::from_json(const json_t &js, py::object &o) { - if (js.is_boolean()) { - o = py::bool_(js.get()); - } else if (js.is_number()) { - if (js.is_number_float()) { - o = py::float_(js.get()); - } else if (js.is_number_unsigned()) { - o = py::int_(js.get()); - } else { - o = py::int_(js.get()); - } - } else if (js.is_string()) { - o = py::str(js.get()); - } else if (js.is_array()) { - std::vector obj(js.size()); - for (auto i = 0; i < js.size(); i++) - { - py::object tmp; - from_json(js[i], tmp); - obj[i] = tmp; - } - o = py::cast(obj); - } else if (js.is_object()) { - py::dict obj; - for (json_t::const_iterator it = js.cbegin(); it != js.cend(); ++it) - { - py::object tmp; - from_json(it.value(), tmp); - obj[py::str(it.key())] = tmp; - } - o = std::move(obj); - } else if (js.is_null()) { - o = py::none(); + if (js.is_boolean()) { + o = py::bool_(js.get()); + } else if (js.is_number()) { + if (js.is_number_float()) { + o = py::float_(js.get()); + } else if (js.is_number_unsigned()) { + o = py::int_(js.get()); } else { - throw std::runtime_error("from_json not implemented for this json::type: " + js.dump()); + o = py::int_(js.get()); + } + } else if (js.is_string()) { + o = py::str(js.get()); + } else if (js.is_array()) { + std::vector obj(js.size()); + for (auto i = 0; i < js.size(); i++) { + py::object tmp; + from_json(js[i], tmp); + obj[i] = tmp; + } + o = py::cast(obj); + } else if (js.is_object()) { + py::dict obj; + for (json_t::const_iterator it = js.cbegin(); it != js.cend(); ++it) { + py::object tmp; + from_json(it.value(), tmp); + obj[py::str(it.key())] = tmp; } + o = std::move(obj); + } else if (js.is_null()) { + o = py::none(); + } else { + throw std::runtime_error("from_json not implemented for this json::type: " + + js.dump()); + } } //------------------------------------------------------------------------------ diff --git a/src/framework/python_parser.hpp b/src/framework/python_parser.hpp index e2867a8a0c..73f647a367 100644 --- a/src/framework/python_parser.hpp +++ b/src/framework/python_parser.hpp @@ -19,136 +19,138 @@ #include "json_parser.hpp" #include "pybind_json.hpp" -namespace AER{ - -template <> -struct Parser { - Parser() = delete; - - static bool check_key(const std::string& key, const py::handle& po){ - if(py::isinstance(po)){ - return !py::cast(po)[key.c_str()].is_none(); - } - return py::hasattr(po, key.c_str()); - } - - static bool check_keys(const std::vector& keys, const py::handle& po) { - bool pass = true; - for (const auto &s : keys){ - pass &= check_key(s, po); - } - return pass; - } - - static py::object get_py_value(const std::string& key, const py::handle& po){ - if(py::isinstance(po)){ - return py::cast(po)[key.c_str()]; - } - return po.attr(key.c_str()); - } - - static bool get_value(py::object& var, const std::string& key, const py::handle& po) { - if(check_key(key, po)) { - var = get_py_value(key, po); - return true; - } else { - return false; - } - } - - template - static bool get_value(T &var, const std::string& key, const py::handle& po){ - if(check_key(key, po)) { - var = get_py_value(key, po).cast(); - return true; - } else { - return false; - } - } - - static void convert_to_json(json_t &var, const py::handle& po){ - if(py::hasattr(po, "to_dict")){ - std::to_json(var, po.attr("to_dict")()); - }else if(py::isinstance(po)){ - var = nl::json::array(); - for(auto item: po){ - json_t item_js; - convert_to_json(item_js, item); - var.push_back(item_js); - } - }else{ - std::to_json(var, po); - } - } - - static py::object get_value(const std::string& key, const py::handle& po){ - return get_py_value(key, po); - } - - static bool is_array(const py::handle& po){ - return py::isinstance(po) || py::isinstance(po); - } - - static bool is_array(const std::string& key, const py::handle& po) { - py::object the_list = get_py_value(key, po); - return is_array(the_list); - } - - static bool is_list_like(const py::handle& po){ - return is_array(po) || py::isinstance(po); - } - - static py::list get_as_list(const py::handle& po){ - if(!is_list_like(po)){ - throw std::runtime_error("Object is not list like!"); - } - return py::cast(po); - } - - static py::list get_list(const std::string& key, const py::handle& po){ - py::object the_list = get_py_value(key, po); - if(!is_array(the_list)){ - throw std::runtime_error("Object " + key + "is not a list!"); - } - return py::cast(the_list); - } - - static bool is_number(const py::handle& po){ - return py::isinstance(po) || py::isinstance(po); - } - - static bool is_number(const std::string& key, const py::handle& po) { - py::object key_po = get_py_value(key, po); - return is_number(key_po); - } - - template - static T get_list_elem(const py::list& po, unsigned int i){ - return py::cast(po[i]).cast(); - } - - template - static T get_list_elem(const py::handle& po, unsigned int i){ - auto py_list = get_as_list(po); - return get_list_elem(py_list, i); - } - - static std::string dump(const py::handle& po){ - json_t js; - convert_to_json(js, po); - return js.dump(); - } +namespace AER { + +template <> struct Parser { + Parser() = delete; + + static bool check_key(const std::string &key, const py::handle &po) { + if (py::isinstance(po)) { + return !py::cast(po)[key.c_str()].is_none(); + } + return py::hasattr(po, key.c_str()); + } + + static bool check_keys(const std::vector &keys, + const py::handle &po) { + bool pass = true; + for (const auto &s : keys) { + pass &= check_key(s, po); + } + return pass; + } + + static py::object get_py_value(const std::string &key, const py::handle &po) { + if (py::isinstance(po)) { + return py::cast(po)[key.c_str()]; + } + return po.attr(key.c_str()); + } + + static bool get_value(py::object &var, const std::string &key, + const py::handle &po) { + if (check_key(key, po)) { + var = get_py_value(key, po); + return true; + } else { + return false; + } + } + + template + static bool get_value(T &var, const std::string &key, const py::handle &po) { + if (check_key(key, po)) { + var = get_py_value(key, po).cast(); + return true; + } else { + return false; + } + } + + static void convert_to_json(json_t &var, const py::handle &po) { + if (py::hasattr(po, "to_dict")) { + std::to_json(var, po.attr("to_dict")()); + } else if (py::isinstance(po)) { + var = nl::json::array(); + for (auto item : po) { + json_t item_js; + convert_to_json(item_js, item); + var.push_back(item_js); + } + } else { + std::to_json(var, po); + } + } + + static py::object get_value(const std::string &key, const py::handle &po) { + return get_py_value(key, po); + } + + static bool is_array(const py::handle &po) { + return py::isinstance(po) || py::isinstance(po); + } + + static bool is_array(const std::string &key, const py::handle &po) { + py::object the_list = get_py_value(key, po); + return is_array(the_list); + } + + static bool is_list_like(const py::handle &po) { + return is_array(po) || py::isinstance(po); + } + + static py::list get_as_list(const py::handle &po) { + if (!is_list_like(po)) { + throw std::runtime_error("Object is not list like!"); + } + return py::cast(po); + } + + static py::list get_list(const std::string &key, const py::handle &po) { + py::object the_list = get_py_value(key, po); + if (!is_array(the_list)) { + throw std::runtime_error("Object " + key + "is not a list!"); + } + return py::cast(the_list); + } + + static bool is_number(const py::handle &po) { + return py::isinstance(po) || py::isinstance(po); + } + + static bool is_number(const std::string &key, const py::handle &po) { + py::object key_po = get_py_value(key, po); + return is_number(key_po); + } + + template + static T get_list_elem(const py::list &po, unsigned int i) { + return py::cast(po[i]).cast(); + } + + template + static T get_list_elem(const py::handle &po, unsigned int i) { + auto py_list = get_as_list(po); + return get_list_elem(py_list, i); + } + + static std::string dump(const py::handle &po) { + json_t js; + convert_to_json(js, po); + return js.dump(); + } }; template <> -bool Parser::get_value(json_t &var, const std::string& key, const py::handle& po){ - py::object ret_po; - auto success = get_value(ret_po, key, po); - if(success){ - convert_to_json(var, ret_po); - } - return success; -} +bool Parser::get_value(json_t &var, const std::string &key, + const py::handle &po) { + py::object ret_po; + auto success = get_value(ret_po, key, po); + if (success) { + convert_to_json(var, ret_po); + } + return success; } +} // namespace AER #endif // _aer_framework_python_parser_hpp_ diff --git a/src/framework/qobj.hpp b/src/framework/qobj.hpp old mode 100755 new mode 100644 index 7eb7313a1b..00133af16f --- a/src/framework/qobj.hpp +++ b/src/framework/qobj.hpp @@ -30,7 +30,7 @@ namespace AER { //============================================================================ class Qobj { - public: +public: //---------------------------------------------------------------- // Constructors //---------------------------------------------------------------- @@ -40,18 +40,17 @@ class Qobj { virtual ~Qobj() = default; // Deserialization constructor - template - Qobj(const inputdata_t &input); + template Qobj(const inputdata_t &input); //---------------------------------------------------------------- // Data //---------------------------------------------------------------- - std::string id; // qobj identifier passed to result - std::string type = "QASM"; // currently we only support QASM - std::vector circuits; // List of circuits - json_t header; // (optional) passed through to result - json_t config; // (optional) qobj level config data - Noise::NoiseModel noise_model; // (optional) noise model + std::string id; // qobj identifier passed to result + std::string type = "QASM"; // currently we only support QASM + std::vector circuits; // List of circuits + json_t header; // (optional) passed through to result + json_t config; // (optional) qobj level config data + Noise::NoiseModel noise_model; // (optional) noise model }; //============================================================================ @@ -61,13 +60,12 @@ class Qobj { // JSON deserialization inline void from_json(const json_t &js, Qobj &qobj) { qobj = Qobj(js); } -template -Qobj::Qobj(const inputdata_t &input) { +template Qobj::Qobj(const inputdata_t &input) { // Check required fields if (Parser::get_value(id, "qobj_id", input) == false) { throw std::invalid_argument(R"(Invalid qobj: no "qobj_id" field)"); }; - Parser::get_value(type, "type", input); + Parser::get_value(type, "type", input); if (type != "QASM") { throw std::invalid_argument(R"(Invalid qobj: "type" != "QASM".)"); }; @@ -100,12 +98,13 @@ Qobj::Qobj(const inputdata_t &input) { } // Check for fixed simulator seed - // If simulator seed is set, each experiment will be set to a fixed (but different) seed - // Otherwise a random seed will be chosen for each experiment + // If simulator seed is set, each experiment will be set to a fixed (but + // different) seed Otherwise a random seed will be chosen for each experiment int_t seed = -1; uint_t seed_shift = 0; - bool has_simulator_seed = Parser::get_value(seed, "seed_simulator", config); // config always json - const auto& circs = Parser::get_list("experiments", input); + bool has_simulator_seed = Parser::get_value( + seed, "seed_simulator", config); // config always json + const auto &circs = Parser::get_list("experiments", input); const size_t num_circs = circs.size(); // Check if parameterized qobj @@ -128,7 +127,7 @@ Qobj::Qobj(const inputdata_t &input) { } // Load circuits - for (size_t i=0; i(circs[i]), config, truncation); @@ -141,7 +140,7 @@ Qobj::Qobj(const inputdata_t &input) { const auto circ_params = param_table[i]; const size_t num_params = circ_params[0].second.size(); const size_t num_instr = circuit.ops.size(); - for (size_t j=0; j= num_instr) { - throw std::invalid_argument(R"(Invalid parameterized qobj: instruction position out of range)"); + throw std::invalid_argument( + R"(Invalid parameterized qobj: instruction position out of range)"); } auto &op = param_circuit.ops[instr_pos]; if (param_pos >= op.params.size()) { - throw std::invalid_argument(R"(Invalid parameterized qobj: instruction param position out of range)"); + throw std::invalid_argument( + R"(Invalid parameterized qobj: instruction param position out of range)"); } if (j >= params.second.size()) { - throw std::invalid_argument(R"(Invalid parameterized qobj: parameterization value out of range)"); + throw std::invalid_argument( + R"(Invalid parameterized qobj: parameterization value out of range)"); } // Update the param op.params[param_pos] = params.second[j]; } // Run truncation. - // TODO: Truncation should be performed and parameters should be resolved after it. - // However, parameters are associated with indices of instructions, which can be changed in truncation. - // Therefore, current implementation performs truncation for each parameter set. + // TODO: Truncation should be performed and parameters should be + // resolved after it. However, parameters are associated with indices of + // instructions, which can be changed in truncation. Therefore, current + // implementation performs truncation for each parameter set. if (truncation) param_circuit.set_params(true); circuits.push_back(std::move(param_circuit)); @@ -177,13 +180,13 @@ Qobj::Qobj(const inputdata_t &input) { if (!has_simulator_seed) { seed = circuits[0].seed; } - for (auto& circuit : circuits) { + for (auto &circuit : circuits) { circuit.seed = seed + seed_shift; - seed_shift += 2113; // Shift the seed + seed_shift += 2113; // Shift the seed } } //------------------------------------------------------------------------------ -} // namespace AER +} // namespace AER //------------------------------------------------------------------------------ #endif diff --git a/src/framework/results/data/data.hpp b/src/framework/results/data/data.hpp index 878c117af0..82ccdd8650 100644 --- a/src/framework/results/data/data.hpp +++ b/src/framework/results/data/data.hpp @@ -16,22 +16,22 @@ #define _aer_framework_results_data_hpp_ // Data primatives -#include "framework/results/data/subtypes/data_map.hpp" #include "framework/results/data/subtypes/accum_data.hpp" #include "framework/results/data/subtypes/average_data.hpp" +#include "framework/results/data/subtypes/data_map.hpp" #include "framework/results/data/subtypes/list_data.hpp" #include "framework/results/data/subtypes/single_data.hpp" // Data Containers -#include "framework/results/data/mixins/data_creg.hpp" -#include "framework/results/data/mixins/data_rvalue.hpp" -#include "framework/results/data/mixins/data_rvector.hpp" -#include "framework/results/data/mixins/data_rdict.hpp" +#include "framework/results/data/mixins/data_cdict.hpp" #include "framework/results/data/mixins/data_cmatrix.hpp" +#include "framework/results/data/mixins/data_creg.hpp" #include "framework/results/data/mixins/data_cvector.hpp" -#include "framework/results/data/mixins/data_cdict.hpp" #include "framework/results/data/mixins/data_json.hpp" #include "framework/results/data/mixins/data_mps.hpp" +#include "framework/results/data/mixins/data_rdict.hpp" +#include "framework/results/data/mixins/data_rvalue.hpp" +#include "framework/results/data/mixins/data_rvector.hpp" namespace AER { @@ -65,60 +65,60 @@ struct Data : public DataCreg, //---------------------------------------------------------------- template void add_single(const T &data, const std::string &outer_key, - const Args &... inner_keys); + const Args &...inner_keys); template void add_single(T &data, const std::string &outer_key, - const Args &... inner_keys); + const Args &...inner_keys); template void add_single(T &&data, const std::string &outer_key, - const Args &... inner_keys); + const Args &...inner_keys); //---------------------------------------------------------------- // Add list data //---------------------------------------------------------------- template void add_list(const T &data, const std::string &outer_key, - const Args &... inner_keys); + const Args &...inner_keys); template void add_list(T &data, const std::string &outer_key, - const Args &... inner_keys); + const Args &...inner_keys); template void add_list(T &&data, const std::string &outer_key, - const Args &... inner_keys); + const Args &...inner_keys); //---------------------------------------------------------------- // Add accum data //---------------------------------------------------------------- template void add_accum(const T &data, const std::string &outer_key, - const Args &... inner_keys); + const Args &...inner_keys); template void add_accum(T &data, const std::string &outer_key, - const Args &... inner_keys); + const Args &...inner_keys); template void add_accum(T &&data, const std::string &outer_key, - const Args &... inner_keys); + const Args &...inner_keys); //---------------------------------------------------------------- // Add average data //---------------------------------------------------------------- template void add_average(const T &data, const std::string &outer_key, - const Args &... inner_keys); + const Args &...inner_keys); template void add_average(T &data, const std::string &outer_key, - const Args &... inner_keys); + const Args &...inner_keys); template void add_average(T &&data, const std::string &outer_key, - const Args &... inner_keys); + const Args &...inner_keys); //---------------------------------------------------------------- // Utility and config @@ -162,87 +162,86 @@ json_t Data::to_json() { return result; } - template void Data::add_single(const T &data, const std::string &outer_key, - const Args &... inner_keys) { + const Args &...inner_keys) { DataMap::add(data, outer_key, inner_keys...); } template void Data::add_single(T &data, const std::string &outer_key, - const Args &... inner_keys) { + const Args &...inner_keys) { DataMap::add(data, outer_key, inner_keys...); } template void Data::add_single(T &&data, const std::string &outer_key, - const Args &... inner_keys) { + const Args &...inner_keys) { DataMap::add(std::move(data), outer_key, inner_keys...); } template void Data::add_list(const T &data, const std::string &outer_key, - const Args &... inner_keys) { + const Args &...inner_keys) { DataMap::add(data, outer_key, inner_keys...); } template void Data::add_list(T &data, const std::string &outer_key, - const Args &... inner_keys) { + const Args &...inner_keys) { DataMap::add(data, outer_key, inner_keys...); } template void Data::add_list(T &&data, const std::string &outer_key, - const Args &... inner_keys) { + const Args &...inner_keys) { DataMap::add(std::move(data), outer_key, inner_keys...); } template void Data::add_accum(const T &data, const std::string &outer_key, - const Args &... inner_keys) { + const Args &...inner_keys) { DataMap::add(data, outer_key, inner_keys...); } template void Data::add_accum(T &data, const std::string &outer_key, - const Args &... inner_keys) { + const Args &...inner_keys) { DataMap::add(data, outer_key, inner_keys...); } template void Data::add_accum(T &&data, const std::string &outer_key, - const Args &... inner_keys) { + const Args &...inner_keys) { DataMap::add(std::move(data), outer_key, inner_keys...); } template void Data::add_average(const T &data, const std::string &outer_key, - const Args &... inner_keys) { + const Args &...inner_keys) { DataMap::add(data, outer_key, inner_keys...); } template void Data::add_average(T &data, const std::string &outer_key, - const Args &... inner_keys) { + const Args &...inner_keys) { DataMap::add(data, outer_key, inner_keys...); } template void Data::add_average(T &&data, const std::string &outer_key, - const Args &... inner_keys) { + const Args &...inner_keys) { DataMap::add(std::move(data), outer_key, inner_keys...); } diff --git a/src/framework/results/data/metadata.hpp b/src/framework/results/data/metadata.hpp index 969179ca3a..cf7cb39bb1 100644 --- a/src/framework/results/data/metadata.hpp +++ b/src/framework/results/data/metadata.hpp @@ -33,15 +33,15 @@ struct Metadata : public DataMap, //---------------------------------------------------------------- template void add(const json_t &data, const std::string &outer_key, - const Args &... inner_keys); + const Args &...inner_keys); template void add(json_t &data, const std::string &outer_key, - const Args &... inner_keys); + const Args &...inner_keys); template void add(json_t &&data, const std::string &outer_key, - const Args &... inner_keys); + const Args &...inner_keys); //---------------------------------------------------------------- // Add general metadata @@ -51,13 +51,13 @@ struct Metadata : public DataMap, //---------------------------------------------------------------- template void add(const T &data, const std::string &outer_key, - const Args &... inner_keys); + const Args &...inner_keys); template - void add(T &data, const std::string &outer_key, const Args &... inner_keys); + void add(T &data, const std::string &outer_key, const Args &...inner_keys); template - void add(T &&data, const std::string &outer_key, const Args &... inner_keys); + void add(T &&data, const std::string &outer_key, const Args &...inner_keys); // Serialize engine data to JSON json_t to_json(); @@ -87,7 +87,7 @@ json_t Metadata::to_json() { template void Metadata::add(const T &data, const std::string &outer_key, - const Args &... inner_keys) { + const Args &...inner_keys) { json_t tmp = data; DataMap::add( std::move(tmp), outer_key, inner_keys...); @@ -95,7 +95,7 @@ void Metadata::add(const T &data, const std::string &outer_key, template void Metadata::add(T &data, const std::string &outer_key, - const Args &... inner_keys) { + const Args &...inner_keys) { json_t tmp = data; DataMap::add( std::move(tmp), outer_key, inner_keys...); @@ -103,7 +103,7 @@ void Metadata::add(T &data, const std::string &outer_key, template void Metadata::add(T &&data, const std::string &outer_key, - const Args &... inner_keys) { + const Args &...inner_keys) { json_t tmp = data; DataMap::add( std::move(tmp), outer_key, inner_keys...); @@ -111,21 +111,21 @@ void Metadata::add(T &&data, const std::string &outer_key, template void Metadata::add(const json_t &data, const std::string &outer_key, - const Args &... inner_keys) { + const Args &...inner_keys) { DataMap::add(data, outer_key, inner_keys...); } template void Metadata::add(json_t &data, const std::string &outer_key, - const Args &... inner_keys) { + const Args &...inner_keys) { DataMap::add(data, outer_key, inner_keys...); } template void Metadata::add(json_t &&data, const std::string &outer_key, - const Args &... inner_keys) { + const Args &...inner_keys) { DataMap::add( std::move(data), outer_key, inner_keys...); } diff --git a/src/framework/results/data/mixins/data_cdict.hpp b/src/framework/results/data/mixins/data_cdict.hpp index 16d1e3b8d7..69b4670c3b 100644 --- a/src/framework/results/data/mixins/data_cdict.hpp +++ b/src/framework/results/data/mixins/data_cdict.hpp @@ -29,10 +29,11 @@ namespace AER { // Result container for Qiskit-Aer //============================================================================ -struct DataCDict : public DataMap, 1>, - public DataMap, 2>, - public DataMap, 1>, - public DataMap, 2> { +struct DataCDict + : public DataMap, 1>, + public DataMap, 2>, + public DataMap, 1>, + public DataMap, 2> { // Serialize engine data to JSON void add_to_json(json_t &result); @@ -46,10 +47,14 @@ struct DataCDict : public DataMap, //------------------------------------------------------------------------------ DataCDict &DataCDict::combine(DataCDict &&other) { - DataMap, 1>::combine(std::move(other)); - DataMap, 2>::combine(std::move(other)); - DataMap, 1>::combine(std::move(other)); - DataMap, 2>::combine(std::move(other)); + DataMap, 1>::combine( + std::move(other)); + DataMap, 2>::combine( + std::move(other)); + DataMap, 1>::combine( + std::move(other)); + DataMap, 2>::combine( + std::move(other)); return *this; } diff --git a/src/framework/results/data/mixins/data_cmatrix.hpp b/src/framework/results/data/mixins/data_cmatrix.hpp index 0aa1920603..f1e23b6707 100644 --- a/src/framework/results/data/mixins/data_cmatrix.hpp +++ b/src/framework/results/data/mixins/data_cmatrix.hpp @@ -15,9 +15,9 @@ #ifndef _aer_framework_results_data_cmatrix_hpp_ #define _aer_framework_results_data_cmatrix_hpp_ -#include "framework/results/data/subtypes/data_map.hpp" #include "framework/results/data/subtypes/accum_data.hpp" #include "framework/results/data/subtypes/average_data.hpp" +#include "framework/results/data/subtypes/data_map.hpp" #include "framework/results/data/subtypes/list_data.hpp" #include "framework/results/data/subtypes/single_data.hpp" #include "framework/types.hpp" @@ -28,23 +28,22 @@ namespace AER { // Result container for Qiskit-Aer //============================================================================ -struct DataCMatrix : - public DataMap, 1>, - public DataMap, 1>, - public DataMap, 2>, - public DataMap, 2>, - public DataMap, 1>, - public DataMap, 1>, - public DataMap, 2>, - public DataMap, 2>, - public DataMap, 1>, - public DataMap, 1>, - public DataMap, 2>, - public DataMap, 2>, - public DataMap, 1>, - public DataMap, 1>, - public DataMap, 2>, - public DataMap, 2> { +struct DataCMatrix : public DataMap, 1>, + public DataMap, 1>, + public DataMap, 2>, + public DataMap, 2>, + public DataMap, 1>, + public DataMap, 1>, + public DataMap, 2>, + public DataMap, 2>, + public DataMap, 1>, + public DataMap, 1>, + public DataMap, 2>, + public DataMap, 2>, + public DataMap, 1>, + public DataMap, 1>, + public DataMap, 2>, + public DataMap, 2> { // Serialize engine data to JSON void add_to_json(json_t &result); diff --git a/src/framework/results/data/mixins/data_creg.hpp b/src/framework/results/data/mixins/data_creg.hpp index 73a68acb11..f97b769ce6 100644 --- a/src/framework/results/data/mixins/data_creg.hpp +++ b/src/framework/results/data/mixins/data_creg.hpp @@ -26,8 +26,8 @@ namespace AER { // Result container for Qiskit-Aer //============================================================================ -struct DataCreg : public DataMap, // Counts - public DataMap // Memory +struct DataCreg : public DataMap, // Counts + public DataMap // Memory { // Serialize engine data to JSON void add_to_json(json_t &result); diff --git a/src/framework/results/data/mixins/data_mps.hpp b/src/framework/results/data/mixins/data_mps.hpp index 21e20619c6..281a91bf70 100644 --- a/src/framework/results/data/mixins/data_mps.hpp +++ b/src/framework/results/data/mixins/data_mps.hpp @@ -25,7 +25,7 @@ namespace AER { //============================================================================ // Result container for Qiskit-Aer //============================================================================ -//using cmat = std::vector>; +// using cmat = std::vector>; struct DataMPS : public DataMap, public DataMap, public DataMap, diff --git a/src/framework/results/data/mixins/data_rdict.hpp b/src/framework/results/data/mixins/data_rdict.hpp index 8f9e0f55a2..9e470267b4 100644 --- a/src/framework/results/data/mixins/data_rdict.hpp +++ b/src/framework/results/data/mixins/data_rdict.hpp @@ -15,12 +15,12 @@ #ifndef _aer_framework_results_data_rdict_hpp_ #define _aer_framework_results_data_rdict_hpp_ -#include -#include "framework/results/data/subtypes/data_map.hpp" -#include "framework/results/data/subtypes/list_data.hpp" #include "framework/results/data/subtypes/accum_data.hpp" #include "framework/results/data/subtypes/average_data.hpp" +#include "framework/results/data/subtypes/data_map.hpp" +#include "framework/results/data/subtypes/list_data.hpp" #include "framework/types.hpp" +#include namespace AER { @@ -28,12 +28,13 @@ namespace AER { // Result container for Qiskit-Aer //============================================================================ -struct DataRDict : public DataMap, 1>, - public DataMap, 2>, - public DataMap, 1>, - public DataMap, 2>, - public DataMap, 1>, - public DataMap, 2> { +struct DataRDict + : public DataMap, 1>, + public DataMap, 2>, + public DataMap, 1>, + public DataMap, 2>, + public DataMap, 1>, + public DataMap, 2> { // Serialize engine data to JSON void add_to_json(json_t &result); @@ -47,12 +48,18 @@ struct DataRDict : public DataMap, 1>, //------------------------------------------------------------------------------ DataRDict &DataRDict::combine(DataRDict &&other) { - DataMap, 1>::combine(std::move(other)); - DataMap, 2>::combine(std::move(other)); - DataMap, 1>::combine(std::move(other)); - DataMap, 2>::combine(std::move(other)); - DataMap, 1>::combine(std::move(other)); - DataMap, 2>::combine(std::move(other)); + DataMap, 1>::combine( + std::move(other)); + DataMap, 2>::combine( + std::move(other)); + DataMap, 1>::combine( + std::move(other)); + DataMap, 2>::combine( + std::move(other)); + DataMap, 1>::combine( + std::move(other)); + DataMap, 2>::combine( + std::move(other)); return *this; } diff --git a/src/framework/results/data/mixins/data_rvalue.hpp b/src/framework/results/data/mixins/data_rvalue.hpp index 901c84eb30..8f89412ea4 100644 --- a/src/framework/results/data/mixins/data_rvalue.hpp +++ b/src/framework/results/data/mixins/data_rvalue.hpp @@ -15,9 +15,9 @@ #ifndef _aer_framework_results_data_rvalue_hpp_ #define _aer_framework_results_data_rvalue_hpp_ -#include "framework/results/data/subtypes/data_map.hpp" #include "framework/results/data/subtypes/accum_data.hpp" #include "framework/results/data/subtypes/average_data.hpp" +#include "framework/results/data/subtypes/data_map.hpp" #include "framework/results/data/subtypes/list_data.hpp" #include "framework/results/data/subtypes/single_data.hpp" #include "framework/types.hpp" @@ -28,13 +28,12 @@ namespace AER { // Result container for Qiskit-Aer //============================================================================ -struct DataRValue : - public DataMap, - public DataMap, - public DataMap, - public DataMap, - public DataMap, - public DataMap { +struct DataRValue : public DataMap, + public DataMap, + public DataMap, + public DataMap, + public DataMap, + public DataMap { // Serialize engine data to JSON void add_to_json(json_t &result); diff --git a/src/framework/results/data/mixins/data_rvector.hpp b/src/framework/results/data/mixins/data_rvector.hpp index ab283f7ac1..6688b80db1 100644 --- a/src/framework/results/data/mixins/data_rvector.hpp +++ b/src/framework/results/data/mixins/data_rvector.hpp @@ -15,11 +15,11 @@ #ifndef _aer_framework_results_data_rvector_hpp_ #define _aer_framework_results_data_rvector_hpp_ +#include "framework/results/data/subtypes/accum_data.hpp" +#include "framework/results/data/subtypes/average_data.hpp" #include "framework/results/data/subtypes/data_map.hpp" #include "framework/results/data/subtypes/list_data.hpp" #include "framework/results/data/subtypes/single_data.hpp" -#include "framework/results/data/subtypes/accum_data.hpp" -#include "framework/results/data/subtypes/average_data.hpp" #include "framework/types.hpp" namespace AER { diff --git a/src/framework/results/data/mixins/pybind_data_cdict.hpp b/src/framework/results/data/mixins/pybind_data_cdict.hpp old mode 100755 new mode 100644 index 7bcddf3cdc..9f025e39b2 --- a/src/framework/results/data/mixins/pybind_data_cdict.hpp +++ b/src/framework/results/data/mixins/pybind_data_cdict.hpp @@ -30,8 +30,7 @@ py::object to_python(AER::DataCDict &&data); // Move an DataCDict container object to an existing new Python dict void add_to_python(py::dict &pydata, AER::DataCDict &&data); -} //end namespace AerToPy - +} // end namespace AerToPy //============================================================================ // Implementations @@ -44,10 +43,26 @@ py::object AerToPy::to_python(AER::DataCDict &&data) { } void AerToPy::add_to_python(py::dict &pydata, AER::DataCDict &&data) { - AerToPy::add_to_python(pydata, static_cast, 1>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 2>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 1>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 2>&&>(data)); + AerToPy::add_to_python( + pydata, + static_cast, 1> &&>( + data)); + AerToPy::add_to_python( + pydata, + static_cast, 2> &&>( + data)); + AerToPy::add_to_python( + pydata, + static_cast, 1> &&>( + data)); + AerToPy::add_to_python( + pydata, + static_cast, 2> &&>( + data)); } #endif diff --git a/src/framework/results/data/mixins/pybind_data_cmatrix.hpp b/src/framework/results/data/mixins/pybind_data_cmatrix.hpp old mode 100755 new mode 100644 index 4b53de3c8a..994adc2e8b --- a/src/framework/results/data/mixins/pybind_data_cmatrix.hpp +++ b/src/framework/results/data/mixins/pybind_data_cmatrix.hpp @@ -30,8 +30,7 @@ py::object to_python(AER::DataCMatrix &&data); // Move an DataCMatrix container object to an existing new Python dict void add_to_python(py::dict &pydata, AER::DataCMatrix &&data); -} //end namespace AerToPy - +} // end namespace AerToPy //============================================================================ // Implementations @@ -44,22 +43,70 @@ py::object AerToPy::to_python(AER::DataCMatrix &&data) { } void AerToPy::add_to_python(py::dict &pydata, AER::DataCMatrix &&data) { - AerToPy::add_to_python(pydata, static_cast, 1>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 1>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 2>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 2>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 1>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 1>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 2>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 2>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 1>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 1>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 2>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 2>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 1>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 1>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 2>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 2>&&>(data)); + AerToPy::add_to_python( + pydata, + static_cast, 1> &&>( + data)); + AerToPy::add_to_python( + pydata, + static_cast, 1> &&>( + data)); + AerToPy::add_to_python( + pydata, + static_cast, 2> &&>( + data)); + AerToPy::add_to_python( + pydata, + static_cast, 2> &&>( + data)); + AerToPy::add_to_python( + pydata, + static_cast, 1> &&>( + data)); + AerToPy::add_to_python( + pydata, + static_cast, 1> &&>( + data)); + AerToPy::add_to_python( + pydata, + static_cast, 2> &&>( + data)); + AerToPy::add_to_python( + pydata, + static_cast, 2> &&>( + data)); + AerToPy::add_to_python( + pydata, + static_cast, 1> &&>( + data)); + AerToPy::add_to_python( + pydata, + static_cast, 1> &&>( + data)); + AerToPy::add_to_python( + pydata, + static_cast, 2> &&>( + data)); + AerToPy::add_to_python( + pydata, + static_cast, 2> &&>( + data)); + AerToPy::add_to_python( + pydata, + static_cast, 1> &&>( + data)); + AerToPy::add_to_python( + pydata, + static_cast< + AER::DataMap, 1> &&>(data)); + AerToPy::add_to_python( + pydata, + static_cast, 2> &&>( + data)); + AerToPy::add_to_python( + pydata, + static_cast< + AER::DataMap, 2> &&>(data)); } #endif diff --git a/src/framework/results/data/mixins/pybind_data_creg.hpp b/src/framework/results/data/mixins/pybind_data_creg.hpp old mode 100755 new mode 100644 index 9585154c42..2156dd1d9b --- a/src/framework/results/data/mixins/pybind_data_creg.hpp +++ b/src/framework/results/data/mixins/pybind_data_creg.hpp @@ -30,8 +30,7 @@ py::object to_python(AER::DataCreg &&data); // Move an DataCreg container object to an existing new Python dict void add_to_python(py::dict &pydata, AER::DataCreg &&data); -} //end namespace AerToPy - +} // end namespace AerToPy //============================================================================ // Implementations @@ -44,8 +43,12 @@ py::object AerToPy::to_python(AER::DataCreg &&data) { } void AerToPy::add_to_python(py::dict &pydata, AER::DataCreg &&data) { - AerToPy::add_to_python(pydata, static_cast&&>(data)); - AerToPy::add_to_python(pydata, static_cast&&>(data)); + AerToPy::add_to_python( + pydata, + static_cast &&>(data)); + AerToPy::add_to_python( + pydata, + static_cast &&>(data)); } #endif diff --git a/src/framework/results/data/mixins/pybind_data_cvector.hpp b/src/framework/results/data/mixins/pybind_data_cvector.hpp old mode 100755 new mode 100644 index 3115cc8b09..15c7991780 --- a/src/framework/results/data/mixins/pybind_data_cvector.hpp +++ b/src/framework/results/data/mixins/pybind_data_cvector.hpp @@ -30,8 +30,7 @@ py::object to_python(AER::DataCVector &&data); // Move an DataCVector container object to an existing new Python dict void add_to_python(py::dict &pydata, AER::DataCVector &&data); -} //end namespace AerToPy - +} // end namespace AerToPy //============================================================================ // Implementations @@ -44,14 +43,38 @@ py::object AerToPy::to_python(AER::DataCVector &&data) { } void AerToPy::add_to_python(py::dict &pydata, AER::DataCVector &&data) { - AerToPy::add_to_python(pydata, static_cast, 1>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 1>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 2>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 2>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 1>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 1>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 2>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 2>&&>(data)); + AerToPy::add_to_python( + pydata, + static_cast, 1> + &&>(data)); + AerToPy::add_to_python( + pydata, + static_cast, 1> + &&>(data)); + AerToPy::add_to_python( + pydata, + static_cast, 2> + &&>(data)); + AerToPy::add_to_python( + pydata, + static_cast, 2> + &&>(data)); + AerToPy::add_to_python( + pydata, + static_cast, 1> + &&>(data)); + AerToPy::add_to_python( + pydata, + static_cast, 1> + &&>(data)); + AerToPy::add_to_python( + pydata, + static_cast, 2> + &&>(data)); + AerToPy::add_to_python( + pydata, + static_cast, 2> + &&>(data)); } #endif diff --git a/src/framework/results/data/mixins/pybind_data_json.hpp b/src/framework/results/data/mixins/pybind_data_json.hpp old mode 100755 new mode 100644 index 89759ed3ce..51bebb049b --- a/src/framework/results/data/mixins/pybind_data_json.hpp +++ b/src/framework/results/data/mixins/pybind_data_json.hpp @@ -30,8 +30,7 @@ py::object to_python(AER::DataJSON &&data); // Move an DataJSON container object to an existing new Python dict void add_to_python(py::dict &pydata, AER::DataJSON &&data); -} //end namespace AerToPy - +} // end namespace AerToPy //============================================================================ // Implementations @@ -44,10 +43,14 @@ py::object AerToPy::to_python(AER::DataJSON &&data) { } void AerToPy::add_to_python(py::dict &pydata, AER::DataJSON &&data) { - AerToPy::add_to_python(pydata, static_cast&&>(data)); - AerToPy::add_to_python(pydata, static_cast&&>(data)); - AerToPy::add_to_python(pydata, static_cast&&>(data)); - AerToPy::add_to_python(pydata, static_cast&&>(data)); + AerToPy::add_to_python( + pydata, static_cast &&>(data)); + AerToPy::add_to_python( + pydata, static_cast &&>(data)); + AerToPy::add_to_python( + pydata, static_cast &&>(data)); + AerToPy::add_to_python( + pydata, static_cast &&>(data)); } #endif diff --git a/src/framework/results/data/mixins/pybind_data_mps.hpp b/src/framework/results/data/mixins/pybind_data_mps.hpp old mode 100755 new mode 100644 index 7196d884a4..758166f087 --- a/src/framework/results/data/mixins/pybind_data_mps.hpp +++ b/src/framework/results/data/mixins/pybind_data_mps.hpp @@ -33,8 +33,7 @@ py::object to_python(AER::DataMPS &&data); // Move an DataMPS container object to an existing new Python dict void add_to_python(py::dict &pydata, AER::DataMPS &&data); -} //end namespace AerToPy - +} // end namespace AerToPy //============================================================================ // Implementations @@ -42,12 +41,12 @@ void add_to_python(py::dict &pydata, AER::DataMPS &&data); template <> py::object AerToPy::to_python(AER::mps_container_t &&data) { py::list mats; - for (auto& pair: data.first) { + for (auto &pair : data.first) { mats.append(py::make_tuple(AerToPy::to_python(std::move(pair.first)), AerToPy::to_python(std::move(pair.second)))); } py::list vecs; - for (auto&& vec: data.second) { + for (auto &&vec : data.second) { vecs.append(AerToPy::to_python(std::move(vec))); } return py::make_tuple(std::move(mats), std::move(vecs)); @@ -60,10 +59,22 @@ py::object AerToPy::to_python(AER::DataMPS &&data) { } void AerToPy::add_to_python(py::dict &pydata, AER::DataMPS &&data) { - AerToPy::add_to_python(pydata, static_cast&&>(data)); - AerToPy::add_to_python(pydata, static_cast&&>(data)); - AerToPy::add_to_python(pydata, static_cast&&>(data)); - AerToPy::add_to_python(pydata, static_cast&&>(data)); + AerToPy::add_to_python( + pydata, + static_cast &&>( + data)); + AerToPy::add_to_python( + pydata, + static_cast &&>( + data)); + AerToPy::add_to_python( + pydata, + static_cast &&>( + data)); + AerToPy::add_to_python( + pydata, + static_cast &&>( + data)); } #endif diff --git a/src/framework/results/data/mixins/pybind_data_rdict.hpp b/src/framework/results/data/mixins/pybind_data_rdict.hpp old mode 100755 new mode 100644 index 03e2a0a30c..1a92571c63 --- a/src/framework/results/data/mixins/pybind_data_rdict.hpp +++ b/src/framework/results/data/mixins/pybind_data_rdict.hpp @@ -30,8 +30,7 @@ py::object to_python(AER::DataRDict &&data); // Move an DataRDict container object to an existing new Python dict void add_to_python(py::dict &pydata, AER::DataRDict &&data); -} //end namespace AerToPy - +} // end namespace AerToPy //============================================================================ // Implementations @@ -44,12 +43,32 @@ py::object AerToPy::to_python(AER::DataRDict &&data) { } void AerToPy::add_to_python(py::dict &pydata, AER::DataRDict &&data) { - AerToPy::add_to_python(pydata, static_cast, 1>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 2>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 1>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 2>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 1>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 2>&&>(data)); + AerToPy::add_to_python( + pydata, + static_cast, 1> + &&>(data)); + AerToPy::add_to_python( + pydata, + static_cast, 2> + &&>(data)); + AerToPy::add_to_python( + pydata, + static_cast, 1> + &&>(data)); + AerToPy::add_to_python( + pydata, + static_cast, 2> + &&>(data)); + AerToPy::add_to_python( + pydata, + static_cast< + AER::DataMap, 1> &&>( + data)); + AerToPy::add_to_python( + pydata, + static_cast< + AER::DataMap, 2> &&>( + data)); } #endif diff --git a/src/framework/results/data/mixins/pybind_data_rvalue.hpp b/src/framework/results/data/mixins/pybind_data_rvalue.hpp old mode 100755 new mode 100644 index 15d9f18469..dfed06ea4c --- a/src/framework/results/data/mixins/pybind_data_rvalue.hpp +++ b/src/framework/results/data/mixins/pybind_data_rvalue.hpp @@ -30,8 +30,7 @@ py::object to_python(AER::DataRValue &&data); // Move an DataRValue container object to an existing new Python dict void add_to_python(py::dict &pydata, AER::DataRValue &&data); -} //end namespace AerToPy - +} // end namespace AerToPy //============================================================================ // Implementations @@ -44,12 +43,18 @@ py::object AerToPy::to_python(AER::DataRValue &&data) { } void AerToPy::add_to_python(py::dict &pydata, AER::DataRValue &&data) { - AerToPy::add_to_python(pydata, static_cast&&>(data)); - AerToPy::add_to_python(pydata, static_cast&&>(data)); - AerToPy::add_to_python(pydata, static_cast&&>(data)); - AerToPy::add_to_python(pydata, static_cast&&>(data)); - AerToPy::add_to_python(pydata, static_cast&&>(data)); - AerToPy::add_to_python(pydata, static_cast&&>(data)); + AerToPy::add_to_python( + pydata, static_cast &&>(data)); + AerToPy::add_to_python( + pydata, static_cast &&>(data)); + AerToPy::add_to_python( + pydata, static_cast &&>(data)); + AerToPy::add_to_python( + pydata, static_cast &&>(data)); + AerToPy::add_to_python( + pydata, static_cast &&>(data)); + AerToPy::add_to_python( + pydata, static_cast &&>(data)); } #endif diff --git a/src/framework/results/data/mixins/pybind_data_rvector.hpp b/src/framework/results/data/mixins/pybind_data_rvector.hpp old mode 100755 new mode 100644 index 58ca61ec9d..212bef99bb --- a/src/framework/results/data/mixins/pybind_data_rvector.hpp +++ b/src/framework/results/data/mixins/pybind_data_rvector.hpp @@ -30,8 +30,7 @@ py::object to_python(AER::DataRVector &&data); // Move an DataRVector container object to an existing new Python dict void add_to_python(py::dict &pydata, AER::DataRVector &&data); -} //end namespace AerToPy - +} // end namespace AerToPy //============================================================================ // Implementations @@ -44,12 +43,30 @@ py::object AerToPy::to_python(AER::DataRVector &&data) { } void AerToPy::add_to_python(py::dict &pydata, AER::DataRVector &&data) { - AerToPy::add_to_python(pydata, static_cast, 1>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 2>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 1>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 2>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 1>&&>(data)); - AerToPy::add_to_python(pydata, static_cast, 2>&&>(data)); + AerToPy::add_to_python( + pydata, + static_cast, 1> &&>( + data)); + AerToPy::add_to_python( + pydata, + static_cast, 2> &&>( + data)); + AerToPy::add_to_python( + pydata, + static_cast, 1> &&>( + data)); + AerToPy::add_to_python( + pydata, + static_cast, 2> &&>( + data)); + AerToPy::add_to_python( + pydata, + static_cast, 1> &&>( + data)); + AerToPy::add_to_python( + pydata, + static_cast, 2> &&>( + data)); } #endif diff --git a/src/framework/results/data/pybind_data.hpp b/src/framework/results/data/pybind_data.hpp old mode 100755 new mode 100644 index dcd25fb17f..23b617b4bd --- a/src/framework/results/data/pybind_data.hpp +++ b/src/framework/results/data/pybind_data.hpp @@ -16,40 +16,38 @@ #define _aer_framework_result_data_pybind_data_hpp_ #include "framework/results/data/data.hpp" -#include "framework/results/data/mixins/pybind_data_creg.hpp" -#include "framework/results/data/mixins/pybind_data_rdict.hpp" -#include "framework/results/data/mixins/pybind_data_rvalue.hpp" -#include "framework/results/data/mixins/pybind_data_rvector.hpp" +#include "framework/results/data/mixins/pybind_data_cdict.hpp" #include "framework/results/data/mixins/pybind_data_cmatrix.hpp" +#include "framework/results/data/mixins/pybind_data_creg.hpp" #include "framework/results/data/mixins/pybind_data_cvector.hpp" -#include "framework/results/data/mixins/pybind_data_cdict.hpp" #include "framework/results/data/mixins/pybind_data_json.hpp" #include "framework/results/data/mixins/pybind_data_mps.hpp" +#include "framework/results/data/mixins/pybind_data_rdict.hpp" +#include "framework/results/data/mixins/pybind_data_rvalue.hpp" +#include "framework/results/data/mixins/pybind_data_rvector.hpp" namespace AerToPy { // Move an ExperimentResult data object to a Python dict template <> py::object to_python(AER::Data &&data); -} //end namespace AerToPy - +} // end namespace AerToPy //============================================================================ // Implementations //============================================================================ -template <> -py::object AerToPy::to_python(AER::Data &&data) { +template <> py::object AerToPy::to_python(AER::Data &&data) { py::dict pydata; - AerToPy::add_to_python(pydata, static_cast(data)); - AerToPy::add_to_python(pydata, static_cast(data)); - AerToPy::add_to_python(pydata, static_cast(data)); - AerToPy::add_to_python(pydata, static_cast(data)); - AerToPy::add_to_python(pydata, static_cast(data)); - AerToPy::add_to_python(pydata, static_cast(data)); - AerToPy::add_to_python(pydata, static_cast(data)); - AerToPy::add_to_python(pydata, static_cast(data)); - AerToPy::add_to_python(pydata, static_cast(data)); + AerToPy::add_to_python(pydata, static_cast(data)); + AerToPy::add_to_python(pydata, static_cast(data)); + AerToPy::add_to_python(pydata, static_cast(data)); + AerToPy::add_to_python(pydata, static_cast(data)); + AerToPy::add_to_python(pydata, static_cast(data)); + AerToPy::add_to_python(pydata, static_cast(data)); + AerToPy::add_to_python(pydata, static_cast(data)); + AerToPy::add_to_python(pydata, static_cast(data)); + AerToPy::add_to_python(pydata, static_cast(data)); return std::move(pydata); } diff --git a/src/framework/results/data/pybind_metadata.hpp b/src/framework/results/data/pybind_metadata.hpp old mode 100755 new mode 100644 index 244083d931..24c47a2c45 --- a/src/framework/results/data/pybind_metadata.hpp +++ b/src/framework/results/data/pybind_metadata.hpp @@ -23,19 +23,23 @@ namespace AerToPy { // Move an ExperimentResult metdata object to a Python dict template <> py::object to_python(AER::Metadata &&metadata); -} //end namespace AerToPy - +} // end namespace AerToPy //============================================================================ // Implementations //============================================================================ -template <> -py::object AerToPy::to_python(AER::Metadata &&metadata) { +template <> py::object AerToPy::to_python(AER::Metadata &&metadata) { py::dict pydata; - add_to_python(pydata, static_cast&&>(metadata)); - add_to_python(pydata, static_cast&&>(metadata)); - add_to_python(pydata, static_cast&&>(metadata)); + add_to_python( + pydata, + static_cast &&>(metadata)); + add_to_python( + pydata, + static_cast &&>(metadata)); + add_to_python( + pydata, + static_cast &&>(metadata)); return std::move(pydata); } diff --git a/src/framework/results/data/subtypes/accum_data.hpp b/src/framework/results/data/subtypes/accum_data.hpp old mode 100755 new mode 100644 index a424f8a107..a53063068b --- a/src/framework/results/data/subtypes/accum_data.hpp +++ b/src/framework/results/data/subtypes/accum_data.hpp @@ -20,18 +20,18 @@ namespace AER { -template -class AccumData : public SingleData { -using Base = SingleData; +template class AccumData : public SingleData { + using Base = SingleData; + public: // Add data (copy) - void add(const T& data); + void add(const T &data); // Add data (move) - void add(T&& data); + void add(T &&data); // Combine data (move) - void combine(AccumData&& other); + void combine(AccumData &&other); // Clear all stored data void clear(); @@ -44,8 +44,7 @@ using Base = SingleData; // Implementation //------------------------------------------------------------------------------ -template -void AccumData::add(const T& data) { +template void AccumData::add(const T &data) { if (empty_) { Base::data_ = data; empty_ = false; @@ -54,8 +53,7 @@ void AccumData::add(const T& data) { } } -template -void AccumData::add(T&& data) { +template void AccumData::add(T &&data) { if (empty_) { Base::data_ = std::move(data); empty_ = false; @@ -64,18 +62,16 @@ void AccumData::add(T&& data) { } } -template -void AccumData::combine(AccumData&& other) { +template void AccumData::combine(AccumData &&other) { add(std::move(other.data_)); } -template -void AccumData::clear() { +template void AccumData::clear() { Base::clear(); empty_ = true; } //------------------------------------------------------------------------------ -} // end namespace AER +} // end namespace AER //------------------------------------------------------------------------------ #endif diff --git a/src/framework/results/data/subtypes/average_data.hpp b/src/framework/results/data/subtypes/average_data.hpp old mode 100755 new mode 100644 index fea9a7c858..ceff37e462 --- a/src/framework/results/data/subtypes/average_data.hpp +++ b/src/framework/results/data/subtypes/average_data.hpp @@ -19,21 +19,21 @@ namespace AER { -template -class AverageData : public AccumData { -using Base = AccumData; +template class AverageData : public AccumData { + using Base = AccumData; + public: // Access data - T& value(); + T &value(); // Add data (copy) - void add(const T& data); + void add(const T &data); // Add data (move) - void add(T&& data); + void add(T &&data); // Add data - void combine(AverageData&& other); + void combine(AverageData &&other); // Clear all stored data void clear(); @@ -57,58 +57,51 @@ using Base = AccumData; // Implementation //------------------------------------------------------------------------------ -template -void AverageData::add(const T& data) { +template void AverageData::add(const T &data) { denormalize(); Base::add(data); count_ += 1; } -template -void AverageData::add(T&& data) { +template void AverageData::add(T &&data) { denormalize(); Base::add(std::move(data)); count_ += 1; } -template -void AverageData::combine(AverageData&& other) { +template void AverageData::combine(AverageData &&other) { denormalize(); other.denormalize(); Base::combine(std::move(other)); count_ += other.count_; } -template -void AverageData::clear() { +template void AverageData::clear() { Base::clear(); count_ = 0; normalized_ = false; } -template -void AverageData::normalize() { +template void AverageData::normalize() { if (normalized_) return; Linalg::idiv(Base::data_, double(count_)); normalized_ = true; } -template -void AverageData::denormalize() { +template void AverageData::denormalize() { if (!normalized_) return; Linalg::imul(Base::data_, double(count_)); normalized_ = false; } -template -T& AverageData::value() { +template T &AverageData::value() { normalize(); return Base::data_; } //------------------------------------------------------------------------------ -} // end namespace AER +} // end namespace AER //------------------------------------------------------------------------------ #endif diff --git a/src/framework/results/data/subtypes/data_map.hpp b/src/framework/results/data/subtypes/data_map.hpp old mode 100755 new mode 100644 index 7f0d4fb0a6..8edd20f47d --- a/src/framework/results/data/subtypes/data_map.hpp +++ b/src/framework/results/data/subtypes/data_map.hpp @@ -21,27 +21,26 @@ namespace AER { // Recursive nested data template class -template