Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

enable sampling for readout error #222

Merged
merged 6 commits into from
Aug 1, 2019
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/noise/noise_model.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,22 @@ class NoiseModel {
return !(local_quantum_errors_ || nonlocal_quantum_errors_) && readout_errors_.empty();
}

inline bool has_readout_errors() const {
return !readout_errors_.empty();
}

inline bool has_quantum_errors() const {
return local_quantum_errors_ || nonlocal_quantum_errors_;
}

inline bool has_local_quantum_errors() const {
return local_quantum_errors_;
}

inline bool has_nonlocal_quantum_errors() const {
return nonlocal_quantum_errors_;
}

// Set which single qubit gates should use the X90 waltz error model
inline void set_x90_gates(const stringset_t &x90_gates) {
x90_gates_ = x90_gates;
Expand Down
50 changes: 37 additions & 13 deletions src/simulators/qasm/qasm_controller.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -450,7 +450,8 @@ void QasmController::set_parallelization_circuit(const Circuit& circ) {
switch (simulation_method(circ)) {
case Method::statevector:
case Method::tensor_network: {
if (noise_model_.ideal() && check_measure_sampling_opt(circ).first) {
if ((noise_model_.ideal() || !noise_model_.has_quantum_errors()) &&
check_measure_sampling_opt(circ).first) {
parallel_shots_ = 1;
parallel_state_update_ = max_parallel_threads_;
return;
Expand Down Expand Up @@ -495,6 +496,9 @@ OutputData QasmController::run_circuit_helper(const Circuit &circ,
// Check if there is noise for the implementation
if (noise_model_.ideal()) {
run_circuit_without_noise(circ, shots, state, initial_state, data, rng);
} else if (!noise_model_.has_quantum_errors()) {
run_circuit_without_noise(noise_model_.sample_noise(circ, rng),
shots, state, initial_state, data, rng);
} else {
run_circuit_with_noise(circ, shots, state, initial_state, data, rng);
}
Expand Down Expand Up @@ -565,6 +569,8 @@ void QasmController::run_circuit_without_noise(const Circuit &circ,
// Get measurement operations and set of measured qubits
ops = std::vector<Operations::Op>(opt_circ.ops.begin() + pos, opt_circ.ops.end());
measure_sampler(ops, shots, state, data, rng);
data.add_additional_data("metadata",
json_t::object({{"measure", "sampling"}}));
}
}

Expand All @@ -585,20 +591,22 @@ QasmController::check_measure_sampling_opt(const Circuit &circ) const {
while (start != circ.ops.end()) {
const auto type = start->type;
if (type == Operations::OpType::reset ||
type == Operations::OpType::initialize ||
type == Operations::OpType::kraus ||
type == Operations::OpType::roerror) {
type == Operations::OpType::initialize ||
type == Operations::OpType::kraus) {
return std::make_pair(false, 0);
}
if (type == Operations::OpType::measure)
if (type == Operations::OpType::measure ||
type == Operations::OpType::roerror)
break;
++start;
}
// Record position for if optimization passes
auto start_meas = start;
// Check all remaining operations are measurements
while (start != circ.ops.end()) {
if (start->type != Operations::OpType::measure || start->conditional) {
if ((start->type != Operations::OpType::measure
&& start->type != Operations::OpType::roerror) ||
start->conditional) {
return std::make_pair(false, 0);
}
++start;
Expand All @@ -611,18 +619,28 @@ QasmController::check_measure_sampling_opt(const Circuit &circ) const {


template <class State_t>
void QasmController::measure_sampler(const std::vector<Operations::Op> &meas_ops,
void QasmController::measure_sampler(const std::vector<Operations::Op> &meas_roerror_ops,
uint_t shots,
State_t &state,
OutputData &data,
RngEngine &rng) const {

// Check if meas_circ is empty, and if so return initial creg
if (meas_ops.empty()) {
if (meas_roerror_ops.empty()) {
while (shots-- > 0) {
state.add_creg_to_data(data);
}
return;
}

std::vector<Operations::Op> meas_ops;
std::vector<Operations::Op> roerror_ops;
for (const Operations::Op& op: meas_roerror_ops)
if (op.type == Operations::OpType::roerror)
roerror_ops.push_back(op);
else /*(op.type == Operations::OpType::measure) */
meas_ops.push_back(op);

// Get measured qubits from circuit sort and delete duplicates
std::vector<uint_t> meas_qubits; // measured qubits
for (const auto &op : meas_ops) {
Expand Down Expand Up @@ -656,7 +674,7 @@ void QasmController::measure_sampler(const std::vector<Operations::Op> &meas_ops
// Process samples
// Convert opts to circuit so we can get the needed creg sizes
// NB: this function could probably be moved somewhere else like Utils or Ops
Circuit meas_circ(meas_ops);
Circuit meas_circ(meas_roerror_ops);
ClassicalRegister creg;
while (!all_samples.empty()) {
auto sample = all_samples.back();
Expand All @@ -666,14 +684,20 @@ void QasmController::measure_sampler(const std::vector<Operations::Op> &meas_ops
for (const auto &pair : memory_map) {
creg.store_measure(reg_t({sample[pair.second]}), reg_t({pair.first}), reg_t());
}
auto memory = creg.memory_hex();
data.add_memory_count(memory);
data.add_memory_singleshot(memory);

// process register bit measurements
for (const auto &pair : register_map) {
creg.store_measure(reg_t({sample[pair.second]}), reg_t(), reg_t({pair.first}));
}

// process read out errors for memory and registers
for (const Operations::Op& roerror: roerror_ops) {
creg.apply_roerror(roerror, rng);
}

auto memory = creg.memory_hex();
data.add_memory_count(memory);
data.add_memory_singleshot(memory);

data.add_register_singleshot(creg.register_hex());

// pop off processed sample
Expand Down
61 changes: 60 additions & 1 deletion test/terra/backends/qasm_simulator/qasm_measure.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
from test.terra.reference import ref_measure
from qiskit.compiler import assemble
from qiskit.providers.aer import QasmSimulator

from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors import ReadoutError, depolarizing_error

class QasmMeasureTests:
"""QasmSimulator measure tests."""
Expand Down Expand Up @@ -129,3 +130,61 @@ def test_measure_nondeterministic_multi_qubit_without_sampling(self):
qobj, backend_options=self.BACKEND_OPTS).result()
self.is_completed(result)
self.compare_counts(result, circuits, targets, delta=0.05 * shots)

# ---------------------------------------------------------------------
# Test measure with noise model
# ---------------------------------------------------------------------
def sampling_enabled(self, result):
"""Check sampling is enabled"""
for r in result.as_dict()['results']:
self.assertTrue('metadata' in r)
if 'measure' not in r['metadata']:
return False
if r['metadata']['measure'] != 'sampling':
return False
return True

def test_measure_sampling_with_readouterror(self):
"""Test QasmSimulator measure with deterministic counts with sampling and readout-error"""
readout_error = [0.01, 0.1]
noise_model = NoiseModel()
readout = [[1.0 - readout_error[0], readout_error[0]],
[readout_error[1], 1.0 - readout_error[1]]]
noise_model.add_all_qubit_readout_error(ReadoutError(readout))

shots = 1000
circuits = ref_measure.measure_circuits_deterministic(
allow_sampling=True)
targets = ref_measure.measure_counts_deterministic(shots)
qobj = assemble(circuits, self.SIMULATOR, shots=shots)
result = self.SIMULATOR.run(
qobj,
noise_model=noise_model,
backend_options=self.BACKEND_OPTS).result()
self.is_completed(result)
self.assertTrue(self.sampling_enabled(result))

def test_measure_sampling_with_quantum_noise(self):
"""Test QasmSimulator measure with deterministic counts with sampling and readout-error"""
readout_error = [0.01, 0.1]
noise_model = NoiseModel()
depolarizing = {'u3': (1, 0.001), 'cx': (2, 0.02)}
readout = [[1.0 - readout_error[0], readout_error[0]],
[readout_error[1], 1.0 - readout_error[1]]]
noise_model.add_all_qubit_readout_error(ReadoutError(readout))
for gate, (num_qubits, gate_error) in depolarizing.items():
noise_model.add_all_qubit_quantum_error(
depolarizing_error(gate_error, num_qubits), gate)

shots = 1000
circuits = ref_measure.measure_circuits_deterministic(
allow_sampling=True)
targets = ref_measure.measure_counts_deterministic(shots)
qobj = assemble(circuits, self.SIMULATOR, shots=shots)
result = self.SIMULATOR.run(
qobj,
noise_model=noise_model,
backend_options=self.BACKEND_OPTS).result()
self.is_completed(result)
self.assertFalse(self.sampling_enabled(result))