Repository: Qiskit/qiskit

Issue:
BasicAer reports incorrect results for multiple measurements
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Information

- **Qiskit Terra version**: master
- **Python version**: 3.7
- **Operating system**: OsX

### What is the current behavior?
BasicAer is outputting the wrong counts for multiple measurements. This was noticed by Fer Grooteman from quantum-inspire.

```python
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, BasicAer, execute

qr1 = QuantumRegister(1, 'q1')
qr2 = QuantumRegister(1, 'q2')
cr = ClassicalRegister(4, 'c')
circuit2 = QuantumCircuit(qr1, qr2, cr)

circuit2.h(qr1)
circuit2.cx(qr1, qr2)
circuit2.measure(qr1, cr[0])
circuit2.measure(qr2, cr[1])
circuit2.measure(qr1, cr[2])
circuit2.measure(qr2, cr[3])

print(circuit2)

print("\nResult from BasicAer simulator:\n")
qk_backend = BasicAer.get_backend("qasm_simulator")
qk_job = execute(circuit2, backend=qk_backend, shots=1024)
qk_result = qk_job.result()
print(qk_result.get_counts(circuit2))

print("\nResult from Aer simulator:\n")
qk_backend = Aer.get_backend("qasm_simulator")
qk_job = execute(circuit2, backend=qk_backend, shots=1024)
qk_result = qk_job.result()
print(qk_result.get_counts(circuit2))
```
Output:
```
         ┌───┐     ┌─┐   ┌─┐   
q1_0: |0>┤ H ├──■──┤M├───┤M├───
         └───┘┌─┴─┐└╥┘┌─┐└╥┘┌─┐
q2_0: |0>─────┤ X ├─╫─┤M├─╫─┤M├
              └───┘ ║ └╥┘ ║ └╥┘
  c_0: 0 ═══════════╩══╬══╬══╬═
                       ║  ║  ║ 
  c_1: 0 ══════════════╩══╬══╬═
                          ║  ║ 
  c_2: 0 ═════════════════╩══╬═
                             ║ 
  c_3: 0 ════════════════════╩═
                               

Result from BasicAer simulator:

{'0000': 501, '0101': 523}

Result from Aer simulator:

{'0000': 493, '1111': 531}
```


### What is the expected behavior?
BasicAer should have the same output as Aer.


### Suggested solutions





Discussion:
Isn't there some random seeding in simulators?
I don't think this is related to the seeding as the output bitstrings are just wrong as can be seen by the example bitstrings above.
Oops. Yes, 0101 impossible output from circuit.
Could it be this? I think this loop assumes that each qubit is only measured once. I'm not quite convinced yet though.

https://github.com/Qiskit/qiskit-terra/blob/master/qiskit/providers/basicaer/qasm_simulator.py#L191
I think its possible, but I don't know enough about how the simulator works. What do you think @chriseclectic?
As @georgesbarron said it looks like a bug in the measure sampling optimization if the same qubit is measured more than once. I can put in a fix

Resolving patch:
diff --git a/qiskit/providers/basicaer/qasm_simulator.py b/qiskit/providers/basicaer/qasm_simulator.py
--- a/qiskit/providers/basicaer/qasm_simulator.py
+++ b/qiskit/providers/basicaer/qasm_simulator.py
@@ -202,8 +202,8 @@ def _add_sample_measure(self, measure_params, num_samples):
         memory = []
         for sample in samples:
             classical_memory = self._classical_memory
-            for count, (qubit, cmembit) in enumerate(sorted(measure_params)):
-                qubit_outcome = int((sample & (1 << count)) >> count)
+            for qubit, cmembit in measure_params:
+                qubit_outcome = int((sample & (1 << qubit)) >> qubit)
                 membit = 1 << cmembit
                 classical_memory = (classical_memory & (~membit)) | (qubit_outcome << cmembit)
             value = bin(classical_memory)[2:]


Test patch:
diff --git a/test/python/basicaer/test_qasm_simulator.py b/test/python/basicaer/test_qasm_simulator.py
--- a/test/python/basicaer/test_qasm_simulator.py
+++ b/test/python/basicaer/test_qasm_simulator.py
@@ -48,6 +48,27 @@ def test_qasm_simulator_single_shot(self):
         result = self.backend.run(self.qobj).result()
         self.assertEqual(result.success, True)
 
+    def test_qasm_simulator_measure_sampler(self):
+        """Test measure sampler if qubits measured more than once."""
+        shots = 100
+        qr = QuantumRegister(2, 'qr')
+        cr = ClassicalRegister(4, 'cr')
+        circuit = QuantumCircuit(qr, cr)
+        circuit.x(qr[1])
+        circuit.measure(qr[0], cr[0])
+        circuit.measure(qr[1], cr[1])
+        circuit.measure(qr[1], cr[2])
+        circuit.measure(qr[0], cr[3])
+        target = {'0110': shots}
+        job = execute(
+            circuit,
+            backend=self.backend,
+            shots=shots,
+            seed_simulator=self.seed)
+        result = job.result()
+        counts = result.get_counts(0)
+        self.assertEqual(counts, target)
+
     def test_qasm_simulator(self):
         """Test data counts output for single circuit run against reference."""
         result = self.backend.run(self.qobj).result()