Repository: Qiskit/qiskit

Issue:
the default decimals in get_statevector is too small
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->

### What is the expected enhancement?

The original statevector simulator will return decimals as many as possible; however, the new terra clips it to 8-digits by default, which results in many chemistry simulations fails because the returned statevector is not enough.

For example, 8-digits is not accurate enough for me to reach ground state energy of H2 since the optimizer can not build accurate gradient with such precision. 

I imagine that some users will result in the same situation and it is not easy to find this issue. 
Could we make the default to as many as possible and then if users would like to truncate that they can pass the parameters.






Discussion:

Resolving patch:
diff --git a/qiskit/backends/ibmq/ibmqjob.py b/qiskit/backends/ibmq/ibmqjob.py
--- a/qiskit/backends/ibmq/ibmqjob.py
+++ b/qiskit/backends/ibmq/ibmqjob.py
@@ -470,9 +470,7 @@ def _submit_callback(self):
 
     def _result_from_job_response(self, job_response):
         if self._is_device:
-            # TODO: temporarily disabled for #1373, reenable before 0.7.
-            # _reorder_bits(job_response)
-            pass
+            _reorder_bits(job_response)
 
         experiment_results = []
         for circuit_result in job_response['qasms']:
@@ -528,7 +526,7 @@ def _reorder_bits(job_data):
                            ' bits: bits may be out of order')
             return
         # device_qubit -> device_clbit (how it should have been)
-        measure_dict = {op['qubits'][0]: op['clbits'][0]
+        measure_dict = {op['qubits'][0]: op['memory'][0]
                         for op in circ['operations']
                         if op['name'] == 'measure'}
         counts_dict_new = {}
@@ -545,13 +543,13 @@ def _reorder_bits(job_data):
             reordered_bits.reverse()
 
             # only keep the clbits specified by circuit, not everything on device
-            num_clbits = circ['header']['number_of_clbits']
+            num_clbits = circ['header']['memory_slots']
             compact_key = reordered_bits[-num_clbits:]
             compact_key = "".join([b if b != 'x' else '0'
                                    for b in compact_key])
 
             # insert spaces to signify different classical registers
-            cregs = circ['header']['clbit_labels']
+            cregs = circ['header']['creg_sizes']
             if sum([creg[1] for creg in cregs]) != num_clbits:
                 raise JobError("creg sizes don't add up in result header.")
             creg_begin_pos = []
diff --git a/qiskit/result/postprocess.py b/qiskit/result/postprocess.py
new file mode 100644
--- /dev/null
+++ b/qiskit/result/postprocess.py
@@ -0,0 +1,115 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2018, IBM.
+#
+# This source code is licensed under the Apache License, Version 2.0 found in
+# the LICENSE.txt file in the root directory of this source tree.
+
+"""Post-processing of raw result."""
+
+import numpy as np
+
+
+def _hex_to_bin(hexstring):
+    """Convert hexadecimal readouts (memory) to binary readouts."""
+    return str(bin(int(hexstring, 16)))[2:]
+
+
+def _pad_zeros(bitstring, memory_slots):
+    """If the bitstring is truncated, pad extra zeros to make its
+    length equal to memory_slots"""
+    return format(int(bitstring, 2), '0{}b'.format(memory_slots))
+
+
+def _separate_bitstring(bitstring, creg_sizes):
+    """Separate a bitstring according to the registers defined in the result header."""
+    substrings = []
+    running_index = 0
+    for _, size in reversed(creg_sizes):
+        substrings.append(bitstring[running_index: running_index + size])
+        running_index += size
+    return ' '.join(substrings)
+
+
+def format_memory(memory, header):
+    """
+    Format a single bitstring (memory) from a single shot experiment.
+
+    - The hexadecimals are expanded to bitstrings
+
+    - Spaces are inserted at register divisions.
+
+    Args:
+        memory (str): result of a single experiment.
+        header (dict): the experiment header dictionary containing
+            useful information for postprocessing.
+
+    Returns:
+        dict: a formatted memory
+    """
+    creg_sizes = header.get('creg_sizes')
+    memory_slots = header.get('memory_slots')
+    if memory.startswith('0x'):
+        memory = _hex_to_bin(memory)
+    if memory_slots:
+        memory = _pad_zeros(memory, memory_slots)
+    if creg_sizes:
+        memory = _separate_bitstring(memory, creg_sizes)
+    return memory
+
+
+def format_counts(counts, header):
+    """Format a single experiment result coming from backend to present
+    to the Qiskit user.
+
+    Args:
+        counts (dict): counts histogram of multiple shots
+        header (dict): the experiment header dictionary containing
+            useful information for postprocessing.
+
+    Returns:
+        dict: a formatted counts
+    """
+    counts_dict = {}
+    for key, val in counts.items():
+        key = format_memory(key, header)
+        counts_dict[key] = val
+    return counts_dict
+
+
+def format_statevector(vec, decimals=None):
+    """Format statevector coming from the backend to present to the Qiskit user.
+
+    Args:
+        vec (list): a list of [re, im] complex numbers.
+        decimals (int): the number of decimals in the statevector.
+            If None, no rounding is done.
+
+    Returns:
+        list[complex]: a list of python complex numbers.
+    """
+    num_basis = len(vec)
+    vec_complex = np.zeros(num_basis, dtype=complex)
+    for i in range(num_basis):
+        vec_complex[i] = vec[i][0] + 1j * vec[i][1]
+    if decimals:
+        vec_complex = np.around(vec_complex, decimals=decimals)
+    return vec_complex
+
+
+def format_unitary(mat, decimals=None):
+    """Format unitary coming from the backend to present to the Qiskit user.
+
+    Args:
+        mat (list[list]): a list of list of [re, im] complex numbers
+        decimals (int): the number of decimals in the statevector.
+            If None, no rounding is done.
+
+    Returns:
+        list[list[complex]]: a matrix of complex numbers
+    """
+    num_basis = len(mat)
+    mat_complex = np.zeros((num_basis, num_basis), dtype=complex)
+    for i, vec in enumerate(mat):
+        mat_complex[i] = format_statevector(vec, decimals)
+    return mat_complex
diff --git a/qiskit/result/result.py b/qiskit/result/result.py
--- a/qiskit/result/result.py
+++ b/qiskit/result/result.py
@@ -8,9 +8,9 @@
 """Model for schema-conformant Results."""
 
 import warnings
-import numpy as np
 from qiskit import QiskitError, QuantumCircuit
 from qiskit.validation.base import BaseModel, bind_schema
+from .postprocess import format_counts, format_statevector, format_unitary
 from .models import ResultSchema
 
 
@@ -48,7 +48,7 @@ def data(self, circuit=None):
 
         Note this data will be a single classical and quantum register and in a
         format required by the results schema. We recomened that most users use
-        the get_xxx method and the data will be post processed for the data type.
+        the get_xxx method, and the data will be post-processed for the data type.
 
         Args:
             circuit (str or QuantumCircuit or int or None): the index of the
@@ -103,23 +103,27 @@ def get_counts(self, circuit=None):
 
         Returns:
             dict[str:int]: a dictionary with the counts for each qubit, with
-                the keys containing a string in hex format (``0x123``).
+                the keys containing a string in binary format and separated
+                according to the registers in circuit (e.g. ``0100 1110``).
+                The string is little-endian (cr[0] on the right hand side).
 
         Raises:
             QiskitError: if there are no counts for the experiment.
         """
         try:
-            return self._get_experiment(circuit).data.counts.to_dict()
+            return format_counts(self.data(circuit)['counts'],
+                                 self._get_experiment(circuit).header.to_dict())
         except KeyError:
             raise QiskitError('No counts for circuit "{0}"'.format(circuit))
 
-    def get_statevector(self, circuit=None, decimals=8):
+    def get_statevector(self, circuit=None, decimals=None):
         """Get the final statevector of an experiment.
 
         Args:
             circuit (str or QuantumCircuit or int or None): the index of the
                 experiment, as specified by ``data()``.
-            decimals (int): the number of decimals in the statevector
+            decimals (int): the number of decimals in the statevector.
+                If None, does not round.
 
         Returns:
             list[complex]: list of 2^n_qubits complex amplitudes.
@@ -128,18 +132,19 @@ def get_statevector(self, circuit=None, decimals=8):
             QiskitError: if there is no statevector for the experiment.
         """
         try:
-            return np.around(self._get_experiment(circuit).data.statevector,
-                             decimals=decimals)
+            return format_statevector(self.data(circuit)['statevector'],
+                                      decimals=decimals)
         except KeyError:
             raise QiskitError('No statevector for circuit "{0}"'.format(circuit))
 
-    def get_unitary(self, circuit=None, decimals=8):
+    def get_unitary(self, circuit=None, decimals=None):
         """Get the final unitary of an experiment.
 
         Args:
             circuit (str or QuantumCircuit or int or None): the index of the
                 experiment, as specified by ``data()``.
-            decimals (int): the number of decimals in the unitary
+            decimals (int): the number of decimals in the unitary.
+                If None, does not round.
 
         Returns:
             list[list[complex]]: list of 2^n_qubits x 2^n_qubits complex
@@ -149,13 +154,13 @@ def get_unitary(self, circuit=None, decimals=8):
             QiskitError: if there is no unitary for the experiment.
         """
         try:
-            return np.around(self._get_experiment(circuit).data.unitary,
-                             decimals=decimals)
+            return format_unitary(self.data(circuit)['unitary'],
+                                  decimals=decimals)
         except KeyError:
             raise QiskitError('No unitary for circuit "{0}"'.format(circuit))
 
     def _get_experiment(self, key=None):
-        """Return an experiment from a given key.
+        """Return a single experiment result from a given key.
 
         Args:
             key (str or QuantumCircuit or int or None): the index of the
@@ -188,6 +193,7 @@ def _get_experiment(self, key=None):
         # Key is a QuantumCircuit or str: retrieve result by name.
         if isinstance(key, QuantumCircuit):
             key = key.name
+
         try:
             # Look into `result[x].header.name` for the names.
             return next(result for result in self.results


Test patch:
diff --git a/test/python/aer/test_extensions_simulator.py b/test/python/aer/test_extensions_simulator.py
--- a/test/python/aer/test_extensions_simulator.py
+++ b/test/python/aer/test_extensions_simulator.py
@@ -15,8 +15,9 @@
 import qiskit.extensions.simulator
 from qiskit import Aer
 from qiskit.quantum_info import state_fidelity
+from qiskit.result.postprocess import format_statevector
 from qiskit import execute
-from ..common import QiskitTestCase, requires_cpp_simulator, bin_to_hex_keys
+from ..common import QiskitTestCase, requires_cpp_simulator
 
 
 @requires_cpp_simulator
@@ -62,7 +63,7 @@ def test_snapshot(self):
         result = execute(circuit, sim).result()
         # TODO: rely on Result.get_statevector() postprocessing rather than manual
         snapshots = result.data(0)['snapshots']['statevector']['3']
-        snapshot = np.array([v[0] + 1j * v[1] for v in snapshots[0]], dtype=complex)
+        snapshot = format_statevector(snapshots[0])
         target = [0.70710678 + 0.j, 0. + 0.j, 0. + 0.j, 0.70710678 + 0.j]
         fidelity = state_fidelity(snapshot, target)
         self.assertGreater(
@@ -90,7 +91,7 @@ def test_noise(self):
         shots = 1000
         result = execute(circuit, sim, config=config, shots=shots).result()
         counts = result.get_counts()
-        target = bin_to_hex_keys({'101': shots})
+        target = {'101': shots}
         self.assertEqual(counts, target)
 
 
diff --git a/test/python/aer/test_qasm_simulator.py b/test/python/aer/test_qasm_simulator.py
--- a/test/python/aer/test_qasm_simulator.py
+++ b/test/python/aer/test_qasm_simulator.py
@@ -18,9 +18,11 @@
                                                 cx_error_matrix,
                                                 x90_error_matrix)
 from qiskit.qobj import Qobj
+from qiskit.result.postprocess import format_statevector
+from qiskit.quantum_info import state_fidelity
 from qiskit import compile
 from ..common import QiskitTestCase, Path
-from ..common import requires_cpp_simulator, bin_to_hex_keys
+from ..common import requires_cpp_simulator
 
 
 class TestAerQasmSimulator(QiskitTestCase):
@@ -46,13 +48,6 @@ def setUp(self):
         self.qobj = compile([self.qc1, self.qc2], backend=self.backend,
                             shots=2000, seed=1111)
 
-    def _to_complex_array(self, vec):
-        num_states = len(vec)
-        vec_complex = np.zeros(num_states, dtype=complex)
-        for i in range(num_states):
-            vec_complex[i] = vec[i][0] + 1j * vec[i][1]
-        return vec_complex
-
     def test_x90_coherent_error_matrix(self):
         x90 = np.array([[1, -1j], [-1j, 1]]) / np.sqrt(2)
         u_matrix = x90_error_matrix(0., 0.).dot(x90)
@@ -156,7 +151,7 @@ def test_qobj_measure_opt(self):
         for name in expected_data:
             # Check counts:
             counts = result.get_counts(name)
-            expected_counts = bin_to_hex_keys(expected_data[name]['counts'])
+            expected_counts = expected_data[name]['counts']
             if expected_data[name].get('deterministic', False):
                 self.assertEqual(counts, expected_counts,
                                  msg=name + ' counts')
@@ -170,7 +165,7 @@ def test_qobj_measure_opt(self):
                              msg=name + ' snapshot keys')
             self.assertEqual(len(snapshots['0']), 1,
                              msg=name + ' snapshot length')
-            state = self._to_complex_array(snapshots['0'][0])
+            state = format_statevector(snapshots['0'][0])
             expected_state = expected_data[name]['statevector']
             fidelity = np.abs(expected_state.dot(state.conj())) ** 2
             self.assertAlmostEqual(fidelity, 1.0, places=10,
@@ -228,7 +223,7 @@ def test_qobj_reset(self):
                              msg=name + ' snapshot keys')
             self.assertEqual(len(snapshots['0']), 1,
                              msg=name + ' snapshot length')
-            state = self._to_complex_array(snapshots['0'][0])
+            state = format_statevector(snapshots['0'][0])
             expected_state = expected_data[name]['statevector']
             fidelity = np.abs(expected_state.dot(state.conj())) ** 2
             self.assertAlmostEqual(fidelity, 1.0, places=10,
@@ -243,10 +238,10 @@ def test_qobj_save_load(self):
         snapshots = result.data('save_command')['snapshots']['statevector']
         self.assertEqual(set(snapshots), {'0', '1', '10', '11'},
                          msg='snapshot keys')
-        state0 = self._to_complex_array(snapshots['0'][0])
-        state10 = self._to_complex_array(snapshots['10'][0])
-        state1 = self._to_complex_array(snapshots['1'][0])
-        state11 = self._to_complex_array(snapshots['11'][0])
+        state0 = format_statevector(snapshots['0'][0])
+        state10 = format_statevector(snapshots['10'][0])
+        state1 = format_statevector(snapshots['1'][0])
+        state11 = format_statevector(snapshots['11'][0])
 
         expected_state0 = np.array([1, 0])
         expected_state10 = np.array([1 / np.sqrt(2), 1 / np.sqrt(2)])
@@ -345,7 +340,7 @@ def test_qobj_single_qubit_gates(self):
                              msg=name + ' snapshot keys')
             self.assertEqual(len(snapshots['0']), 1,
                              msg=name + ' snapshot length')
-            state = self._to_complex_array(snapshots['0'][0])
+            state = format_statevector(snapshots['0'][0])
             expected_state = expected_data[name]['statevector']
             inner_product = expected_state.dot(state.conj())
             self.assertAlmostEqual(inner_product, 1.0, places=10,
@@ -402,9 +397,9 @@ def test_qobj_two_qubit_gates(self):
                              msg=name + ' snapshot keys')
             self.assertEqual(len(snapshots['0']), 1,
                              msg=name + ' snapshot length')
-            state = self._to_complex_array(snapshots['0'][0])
+            state = format_statevector(snapshots['0'][0])
             expected_state = expected_data[name]['statevector']
-            fidelity = np.abs(expected_state.dot(state.conj())) ** 2
+            fidelity = state_fidelity(expected_state, state)
             self.assertAlmostEqual(fidelity, 1.0, places=10,
                                    msg=name + ' snapshot fidelity')
 
@@ -431,7 +426,7 @@ def test_conditionals(self):
                              msg=name + ' snapshot keys')
             self.assertEqual(len(snapshots['0']), 1,
                              msg=name + ' snapshot length')
-            state = self._to_complex_array(snapshots['0'][0])
+            state = format_statevector(snapshots['0'][0])
             expected_state = expected_data[name]['statevector']
             fidelity = np.abs(expected_state.dot(state.conj())) ** 2
             self.assertAlmostEqual(fidelity, 1.0, places=10,
diff --git a/test/python/aer/test_qasm_simulator_py.py b/test/python/aer/test_qasm_simulator_py.py
--- a/test/python/aer/test_qasm_simulator_py.py
+++ b/test/python/aer/test_qasm_simulator_py.py
@@ -14,7 +14,7 @@
 from qiskit import compile
 from qiskit.backends.aer.qasm_simulator_py import QasmSimulatorPy
 
-from ..common import QiskitTestCase, bin_to_hex_keys
+from ..common import QiskitTestCase
 
 
 class TestAerQasmSimulatorPy(QiskitTestCase):
@@ -76,8 +76,8 @@ def test_if_statement(self):
         result = self.backend.run(qobj).result()
         counts_if_true = result.get_counts(circuit_if_true)
         counts_if_false = result.get_counts(circuit_if_false)
-        self.assertEqual(counts_if_true, bin_to_hex_keys({'111': 100}))
-        self.assertEqual(counts_if_false, bin_to_hex_keys({'001': 100}))
+        self.assertEqual(counts_if_true, {'111': 100})
+        self.assertEqual(counts_if_false, {'001': 100})
 
     @unittest.skipIf(version_info.minor == 5,
                      "Due to gate ordering issues with Python 3.5 "
@@ -106,15 +106,16 @@ def test_teleport(self):
         qobj = compile(circuit, backend=self.backend, shots=shots, seed=self.seed)
         results = self.backend.run(qobj).result()
         data = results.get_counts('teleport')
+        print(data)
         alice = {
-            '00': data['0x0'] + data['0x4'],
-            '01': data['0x2'] + data['0x6'],
-            '10': data['0x1'] + data['0x5'],
-            '11': data['0x3'] + data['0x7']
+            '00': data['0 0 0'] + data['1 0 0'],
+            '01': data['0 1 0'] + data['1 1 0'],
+            '10': data['0 0 1'] + data['1 0 1'],
+            '11': data['0 1 1'] + data['1 1 1']
         }
         bob = {
-            '0': data['0x0'] + data['0x2'] + data['0x1'] + data['0x3'],
-            '1': data['0x4'] + data['0x6'] + data['0x5'] + data['0x7']
+            '0': data['0 0 0'] + data['0 1 0'] + data['0 0 1'] + data['0 1 1'],
+            '1': data['1 0 0'] + data['1 1 0'] + data['1 0 1'] + data['1 1 1']
         }
         self.log.info('test_teleport: circuit:')
         self.log.info('test_teleport: circuit:')
diff --git a/test/python/circuit/test_circuit_multi_registers.py b/test/python/circuit/test_circuit_multi_registers.py
--- a/test/python/circuit/test_circuit_multi_registers.py
+++ b/test/python/circuit/test_circuit_multi_registers.py
@@ -19,7 +19,7 @@
 from qiskit import compile, execute
 from qiskit import QiskitError
 from qiskit.quantum_info import state_fidelity, process_fidelity, Pauli, basis_state
-from ..common import QiskitTestCase, requires_cpp_simulator, bin_to_hex_keys
+from ..common import QiskitTestCase, requires_cpp_simulator
 
 
 class TestCircuitMultiRegs(QiskitTestCase):
@@ -54,7 +54,7 @@ def test_circuit_multi(self):
         result = backend_sim.run(qobj_qc).result()
         counts_py = result.get_counts(qc)
 
-        target = bin_to_hex_keys({'01 10': 1024})
+        target = {'01 10': 1024}
 
         backend_sim = Aer.get_backend('statevector_simulator')
         result = backend_sim.run(qobj_circ).result()
@@ -110,7 +110,7 @@ def test_circuit_multi_case2(self):
         result = execute(circ2, backend_sim).result()
         unitary = result.get_unitary(circ2)
 
-        target = bin_to_hex_keys({'01 10': 1024})
+        target = {'01 10': 1024}
         self.assertEqual(target, counts)
         self.assertAlmostEqual(state_fidelity(basis_state('0110', 4), state), 1.0, places=7)
         self.assertAlmostEqual(process_fidelity(Pauli(label='IXXI').to_matrix(), unitary),
diff --git a/test/python/circuit/test_circuit_operations.py b/test/python/circuit/test_circuit_operations.py
--- a/test/python/circuit/test_circuit_operations.py
+++ b/test/python/circuit/test_circuit_operations.py
@@ -7,15 +7,15 @@
 
 
 """Test Qiskit's QuantumCircuit class."""
-import numpy as np
 import qiskit.extensions.simulator  # pylint: disable=unused-import
 from qiskit import Aer
 from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
 from qiskit import execute
 from qiskit import QiskitError
 from qiskit.quantum_info import state_fidelity
+from qiskit.result.postprocess import format_statevector
 
-from ..common import QiskitTestCase, bin_to_hex_keys, requires_cpp_simulator
+from ..common import QiskitTestCase, requires_cpp_simulator
 
 
 class TestCircuitOperations(QiskitTestCase):
@@ -54,7 +54,7 @@ def test_combine_circuit_different(self):
         shots = 1024
         result = execute(new_circuit, backend=backend, shots=shots, seed=78).result()
         counts = result.get_counts()
-        target = bin_to_hex_keys({'11': shots})
+        target = {'11': shots}
         self.assertEqual(counts, target)
 
     def test_combine_circuit_fail(self):
@@ -91,7 +91,7 @@ def test_combine_circuit_extension_instructions(self):
         shots = 1024
         result = execute(new_circuit, backend=backend, shots=shots, seed=78).result()
         snapshot_vectors = result.data(0)['snapshots']['statevector']['1']
-        snapshot = np.array([v[0] + 1j * v[1] for v in snapshot_vectors[0]], dtype=complex)
+        snapshot = format_statevector(snapshot_vectors[0])
         fidelity = state_fidelity(snapshot, desired_vector)
         self.assertGreater(fidelity, 0.99)
 
@@ -133,7 +133,7 @@ def test_extend_circuit_different_registers(self):
         shots = 1024
         result = execute(qc1, backend=backend, shots=shots, seed=78).result()
         counts = result.get_counts()
-        target = bin_to_hex_keys({'11': shots})
+        target = {'11': shots}
         self.assertEqual(counts, target)
 
     def test_extend_circuit_fail(self):
diff --git a/test/python/common.py b/test/python/common.py
--- a/test/python/common.py
+++ b/test/python/common.py
@@ -131,15 +131,6 @@ def assertDictAlmostEqual(self, dict1, dict2, delta=None, msg=None,
         if delta is not None and places is not None:
             raise TypeError("specify delta or places not both")
 
-        # TODO: remove when all tests adjust to counts being hex
-        try:
-            dict1 = bin_to_hex_keys(dict1)
-        except ValueError:
-            try:
-                dict2 = bin_to_hex_keys(dict2)
-            except ValueError:
-                pass
-
         if places is not None:
             success = True
             standard_msg = ''
@@ -388,17 +379,6 @@ def _wrapper(self, *args, **kwargs):
     return _wrapper
 
 
-def bin_to_hex_keys(dict_):
-    """Replace the keys of a dict from bin to hex."""
-    # TODO: remove when all the tests are updated to the new counts format.
-    keys = list(dict_.keys())
-    for key in keys:
-        key_as_hex = hex(int(key.replace(' ', ''), 2))
-        dict_[key_as_hex] = dict_.pop(key)
-
-    return dict_
-
-
 def _get_http_recorder(test_options):
     vcr_mode = 'none'
     if test_options['rec']:
diff --git a/test/python/ibmq/test_ibmq_qasm_simulator.py b/test/python/ibmq/test_ibmq_qasm_simulator.py
--- a/test/python/ibmq/test_ibmq_qasm_simulator.py
+++ b/test/python/ibmq/test_ibmq_qasm_simulator.py
@@ -14,7 +14,7 @@
 # pylint: disable=redefined-builtin
 from qiskit import compile
 from qiskit import IBMQ
-from ..common import requires_qe_access, QiskitTestCase, bin_to_hex_keys
+from ..common import requires_qe_access, QiskitTestCase
 
 
 class TestIbmqQasmSimulator(QiskitTestCase):
@@ -107,5 +107,5 @@ def test_online_qasm_simulator_two_registers(self, qe_token, qe_url):
         result = job.result()
         result1 = result.get_counts(qcr1)
         result2 = result.get_counts(qcr2)
-        self.assertEqual(result1, bin_to_hex_keys({'00 01': 1024}))
-        self.assertEqual(result2, bin_to_hex_keys({'10 00': 1024}))
+        self.assertEqual(result1, {'00 01': 1024})
+        self.assertEqual(result2, {'10 00': 1024})
diff --git a/test/python/ibmq/test_ibmqjob.py b/test/python/ibmq/test_ibmqjob.py
--- a/test/python/ibmq/test_ibmqjob.py
+++ b/test/python/ibmq/test_ibmqjob.py
@@ -27,7 +27,7 @@
 from qiskit.backends.ibmq.ibmqjob import IBMQJob
 from qiskit.backends.ibmq import least_busy
 
-from ..common import requires_qe_access, JobTestCase, slow_test, bin_to_hex_keys
+from ..common import requires_qe_access, JobTestCase, slow_test
 
 
 class TestIBMQJob(JobTestCase):
@@ -55,9 +55,8 @@ def test_run_simulator(self, qe_token, qe_url):
         result = job.result()
         counts_qx1 = result.get_counts(0)
         counts_qx2 = result.get_counts(1)
-        counts_ex1 = bin_to_hex_keys({'00': shots/2, '11': shots/2})
-        counts_ex2 = bin_to_hex_keys({'00': shots/4, '11': shots/4,
-                                      '10': shots/4, '01': shots/4})
+        counts_ex1 = {'00': shots/2, '11': shots/2}
+        counts_ex2 = {'00': shots/4, '11': shots/4, '10': shots/4, '01': shots/4}
         states1 = counts_qx1.keys() | counts_ex1.keys()
         states2 = counts_qx2.keys() | counts_ex2.keys()
         # contingency table
@@ -94,7 +93,7 @@ def test_run_device(self, qe_token, qe_url):
         self.log.info(job.status)
         result = job.result()
         counts_qx = result.get_counts(0)
-        counts_ex = bin_to_hex_keys({'00': shots/2, '11': shots/2})
+        counts_ex = {'00': shots/2, '11': shots/2}
         states = counts_qx.keys() | counts_ex.keys()
         # contingency table
         ctable = numpy.array([[counts_qx.get(key, 0) for key in states],
diff --git a/test/python/ibmq/test_ibmqjob_states.py b/test/python/ibmq/test_ibmqjob_states.py
--- a/test/python/ibmq/test_ibmqjob_states.py
+++ b/test/python/ibmq/test_ibmqjob_states.py
@@ -258,9 +258,9 @@ def test_qobj_result(self):
         result = job.result()
         self.assertEqual(result.success, True)
         self.assertEqual(result.get_counts('Bell state'),
-                         {'0x0': 480, '0x3': 490, '0x1': 20, '0x2': 34})
+                         {'00': 480, '11': 490, '01': 20, '10': 34})
         self.assertEqual(result.get_counts('Bell state XY'),
-                         {'0x0': 29, '0x3': 15, '0x1': 510, '0x2': 480})
+                         {'00': 29, '11': 15, '01': 510, '10': 480})
         self.assertEqual(len(result.results), 2)
 
     def run_with_api(self, api, job_class=IBMQJobPreQobj):
@@ -514,7 +514,13 @@ class QObjResultAPI(BaseFakeAPI):
                 'status': 'COMPLETED',
                 'results': [
                     {
-                        'header': {'name': 'Bell state'},
+                        'header': {
+                            'name': 'Bell state',
+                            'memory_slots': 2,
+                            'creg_sizes': [['c', 2]],
+                            'clbit_labels': [['c', 0], ['c', 1]],
+                            'qubit_labels': [['q', 0], ['q', 1]]
+                        },
                         'shots': 1024,
                         'status': 'DONE',
                         'success': True,
@@ -525,7 +531,13 @@ class QObjResultAPI(BaseFakeAPI):
                         }
                     },
                     {
-                        'header': {'name': 'Bell state XY'},
+                        'header': {
+                            'name': 'Bell state XY',
+                            'memory_slots': 2,
+                            'creg_sizes': [['c', 2]],
+                            'clbit_labels': [['c', 0], ['c', 1]],
+                            'qubit_labels': [['q', 0], ['q', 1]]
+                        },
                         'shots': 1024,
                         'status': 'DONE',
                         'success': True,
diff --git a/test/python/qobj/cpp_measure_opt.json b/test/python/qobj/cpp_measure_opt.json
--- a/test/python/qobj/cpp_measure_opt.json
+++ b/test/python/qobj/cpp_measure_opt.json
@@ -16,7 +16,9 @@
         {
             "header": {
                 "name": "measure (opt)",
-                "clbit_labels": [["c", 2]],
+                "memory_slots": 2,
+                "creg_sizes": [["c", 2]],
+                "clbit_labels": [["c", 0], ["c", 1]],
                 "qubit_labels": [["q", 0], ["q", 1]]
             },
             "config": {
@@ -32,7 +34,9 @@
         {
             "header": {
                 "name": "x0 measure (opt)",
-                "clbit_labels": [["c", 2]],
+                "memory_slots": 2,
+                "creg_sizes": [["c", 2]],
+                "clbit_labels": [["c", 0], ["c", 1]],
                 "qubit_labels": [["q", 0], ["q", 1]]
             },
             "config": {
@@ -49,7 +53,9 @@
         {
             "header": {
                 "name": "x1 measure (opt)",
-                "clbit_labels": [["c", 2]],
+                "memory_slots": 2,
+                "creg_sizes": [["c", 2]],
+                "clbit_labels": [["c", 0], ["c", 1]],
                 "qubit_labels": [["q", 0], ["q", 1]]
             },
             "config": {
@@ -66,7 +72,9 @@
         {
             "header": {
                 "name": "x0 x1 measure (opt)",
-                "clbit_labels": [["c", 2]],
+                "memory_slots": 2,
+                "creg_sizes": [["c", 2]],
+                "clbit_labels": [["c", 0], ["c", 1]],
                 "qubit_labels": [["q", 0], ["q", 1]]
             },
             "config": {
@@ -84,7 +92,9 @@
         {
             "header": {
                 "name": "y0 measure (opt)",
-                "clbit_labels": [["c", 2]],
+                "memory_slots": 2,
+                "creg_sizes": [["c", 2]],
+                "clbit_labels": [["c", 0], ["c", 1]],
                 "qubit_labels": [["q", 0], ["q", 1]]
             },
             "config": {
@@ -101,7 +111,9 @@
         {
             "header": {
                 "name": "y1 measure (opt)",
-                "clbit_labels": [["c", 2]],
+                "memory_slots": 2,
+                "creg_sizes": [["c", 2]],
+                "clbit_labels": [["c", 0], ["c", 1]],
                 "qubit_labels": [["q", 0], ["q", 1]]
             },
             "config": {
@@ -118,7 +130,9 @@
         {
             "header": {
                 "name": "y0 y1 measure (opt)",
-                "clbit_labels": [["c", 2]],
+                "memory_slots": 2,
+                "creg_sizes": [["c", 2]],
+                "clbit_labels": [["c", 0], ["c", 1]],
                 "qubit_labels": [["q", 0], ["q", 1]]
             },
             "config": {
@@ -136,7 +150,9 @@
         {
             "header": {
                 "name": "h0 measure (opt)",
-                "clbit_labels": [["c", 2]],
+                "memory_slots": 2,
+                "creg_sizes": [["c", 2]],
+                "clbit_labels": [["c", 0], ["c", 1]],
                 "qubit_labels": [["q", 0], ["q", 1]]
             },
             "config": {
@@ -153,7 +169,9 @@
         {
             "header": {
                 "name": "h1 measure (opt)",
-                "clbit_labels": [["c", 2]],
+                "memory_slots": 2,
+                "creg_sizes": [["c", 2]],
+                "clbit_labels": [["c", 0], ["c", 1]],
                 "qubit_labels": [["q", 0], ["q", 1]]
             },
             "config": {
@@ -170,7 +188,9 @@
         {
             "header": {
                 "name": "h0 h1 measure (opt)",
-                "clbit_labels": [["c", 2]],
+                "memory_slots": 2,
+                "creg_sizes": [["c", 2]],
+                "clbit_labels": [["c", 0], ["c", 1]],
                 "qubit_labels": [["q", 0], ["q", 1]]
             },
             "config": {
@@ -188,7 +208,9 @@
         {
             "header": {
                 "name": "bell measure (opt)",
-                "clbit_labels": [["c", 2]],
+                "memory_slots": 2,
+                "creg_sizes": [["c", 2]],
+                "clbit_labels": [["c", 0], ["c", 1]],
                 "qubit_labels": [["q", 0], ["q", 1]]
             },
             "config": {
diff --git a/test/python/quantum_info/test_analyzation.py b/test/python/quantum_info/test_analyzation.py
--- a/test/python/quantum_info/test_analyzation.py
+++ b/test/python/quantum_info/test_analyzation.py
@@ -12,7 +12,7 @@
 import qiskit
 from qiskit import Aer
 from qiskit.quantum_info.analyzation.average import average_data
-from ..common import QiskitTestCase, bin_to_hex_keys
+from ..common import QiskitTestCase
 
 
 class TestAnalyzation(QiskitTestCase):
@@ -31,11 +31,11 @@ def test_average_data(self):
         backend = Aer.get_backend('qasm_simulator_py')
         result = qiskit.execute(qc, backend, shots=shots).result()
         counts = result.get_counts(qc)
-        observable = bin_to_hex_keys({"00": 1, "11": 1, "01": -1, "10": -1})
+        observable = {"00": 1, "11": 1, "01": -1, "10": -1}
         mean_zz = average_data(counts=counts, observable=observable)
-        observable = bin_to_hex_keys({"00": 1, "11": -1, "01": 1, "10": -1})
+        observable = {"00": 1, "11": -1, "01": 1, "10": -1}
         mean_zi = average_data(counts, observable)
-        observable = bin_to_hex_keys({"00": 1, "11": -1, "01": -1, "10": 1})
+        observable = {"00": 1, "11": -1, "01": -1, "10": 1}
         mean_iz = average_data(counts, observable)
         self.assertAlmostEqual(mean_zz, 1, places=1)
         self.assertAlmostEqual(mean_zi, 0, places=1)
diff --git a/test/python/test_reordering.py b/test/python/test_reordering.py
--- a/test/python/test_reordering.py
+++ b/test/python/test_reordering.py
@@ -50,6 +50,8 @@ def test_basic_reordering(self, qe_token, qe_url):
         threshold = 0.1 * shots
         self.assertDictAlmostEqual(counts_real, counts_sim, threshold)
 
+    @unittest.skip("Temporary skipping")
+    # skipping temporarily due to mapping wire fragment bug.
     @slow_test
     @requires_qe_access
     def test_multi_register_reordering(self, qe_token, qe_url):
diff --git a/test/python/test_unroller.py b/test/python/test_unroller.py
--- a/test/python/test_unroller.py
+++ b/test/python/test_unroller.py
@@ -155,9 +155,9 @@ def test_dag_to_json(self):
                 ],
             'header':
                 {
-                    'number_of_clbits': 6,
+                    'memory_slots': 6,
                     'qubit_labels': [['r', 0], ['r', 1], ['r', 2], ['q', 0], ['q', 1], ['q', 2]],
-                    'number_of_qubits': 6, 'clbit_labels': [['d', 3], ['c', 3]]
+                    'n_qubits': 6, 'clbit_labels': [['d', 3], ['c', 3]]
                 }
         }
 
diff --git a/test/python/tools/test_compiler.py b/test/python/tools/test_compiler.py
--- a/test/python/tools/test_compiler.py
+++ b/test/python/tools/test_compiler.py
@@ -22,7 +22,7 @@
 from qiskit import execute
 from qiskit._qiskiterror import QiskitError
 from qiskit.backends.ibmq import least_busy
-from ..common import QiskitTestCase, bin_to_hex_keys
+from ..common import QiskitTestCase
 from ..common import requires_qe_access, requires_cpp_simulator
 
 
@@ -539,14 +539,12 @@ def test_example_swap_bits(self):
         result = execute(qc, backend=backend,
                          coupling_map=None, shots=1024,
                          seed=14).result()
-        self.assertEqual(result.get_counts(qc),
-                         bin_to_hex_keys({'010000': 1024}))
+        self.assertEqual(result.get_counts(qc), {'010000': 1024})
         # Second version: map to coupling graph
         result = execute(qc, backend=backend,
                          coupling_map=coupling_map, shots=1024,
                          seed=14).result()
-        self.assertEqual(result.get_counts(qc),
-                         bin_to_hex_keys({'010000': 1024}))
+        self.assertEqual(result.get_counts(qc), {'010000': 1024})
 
     def test_parallel_compile(self):
         """Trigger parallel routines in compile.