Skip to content

Commit

Permalink
Remove deprecated warning from Terra and change our as_dict() to to_d…
Browse files Browse the repository at this point in the history
…ict() (Qiskit#228)

* * Removing deprecation warnings from Terra by using to_dict()
* Deprecating our as_dict() methods in favor of to_dict()

* * Add helpers.py new file
* Add entry in the Changelog

* * Fixing a bad tuple
* Removing a print from a test
  • Loading branch information
atilag authored and gadial committed Jun 11, 2019
1 parent 9ed7a3c commit e79a9a1
Show file tree
Hide file tree
Showing 12 changed files with 79 additions and 18 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ Added

Changed
-------
- Deprecate the use of ".as_dict()" in favor of ".to_dict()" (#228)
- Set simulator seed from "seed_simulator" in qobj (#210)

Removed
Expand Down
6 changes: 3 additions & 3 deletions qiskit/providers/aer/backends/aerbackend.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ def default(self, obj):
return obj.tolist()
if isinstance(obj, complex):
return [obj.real, obj.imag]
if hasattr(obj, "as_dict"):
return obj.as_dict()
if hasattr(obj, "to_dict"):
return obj.to_dict()
return super().default(obj)


Expand Down Expand Up @@ -117,7 +117,7 @@ def _format_qobj_str(self, qobj, backend_options, noise_model):
original_config = qobj.config
# Convert to dictionary and add new parameters
# from noise model and backend options
config = original_config.as_dict()
config = original_config.to_dict()
if backend_options is not None:
for key, val in backend_options.items():
config[key] = val
Expand Down
2 changes: 1 addition & 1 deletion qiskit/providers/aer/backends/qasm_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ def _validate(self, qobj, backend_options, noise_model):

if clifford_noise:
if method != "stabilizer" and noise_model:
for error in noise_model.as_dict()['errors']:
for error in noise_model.to_dict()['errors']:
if error['type'] == 'qerror':
for circ in error["instructions"]:
for instr in circ:
Expand Down
2 changes: 1 addition & 1 deletion qiskit/providers/aer/noise/errors/errorutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ def standard_gate_unitary(name):
np.array([[1, 0], [0, np.exp(-1j * np.pi / 4)]], dtype=complex),
("cx", "CX", "cx_01"):
np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]], dtype=complex),
("cx_10"):
("cx_10",):
np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]], dtype=complex),
("cz", "CZ"):
np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]], dtype=complex),
Expand Down
11 changes: 11 additions & 0 deletions qiskit/providers/aer/noise/errors/quantum_error.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
from .errorutils import circuit2superop
from .errorutils import standard_instruction_channel
from .errorutils import standard_instruction_operator
from ...utils.helpers import deprecation

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -284,6 +285,16 @@ def error_term(self, position):
position) + "of error outcomes {}".format(self.size))

def as_dict(self):
"""
DEPRECATED: Use to_dict()
Returns:
dict: The current error as a dictionary.
"""
deprecation("QuantumError::as_dict() method is deprecated and will be removed after 0.3."
"Use '.to_dict()' instead")
return self.to_dict()

def to_dict(self):
"""Return the current error as a dictionary."""
error = {
"type": "qerror",
Expand Down
11 changes: 11 additions & 0 deletions qiskit/providers/aer/noise/errors/readout_error.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

from ..noiseerror import NoiseError
from .errorutils import qubits_from_mat
from ...utils.helpers import deprecation


class ReadoutError:
Expand Down Expand Up @@ -141,6 +142,16 @@ def ideal(self):
return False

def as_dict(self):
"""
DEPRECATED: Use to_dict()
Returns:
dict: The current error as a dictionary.
"""
deprecation("ReadoutError::as_dict() method is deprecated and will be removed after 0.3."
"Use '.to_dict()' instead")
return self.to_dict()

def to_dict(self):
"""Return the current error as a dictionary."""
error = {
"type": "roerror",
Expand Down
27 changes: 22 additions & 5 deletions qiskit/providers/aer/noise/noise_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from .noiseerror import NoiseError
from .errors.quantum_error import QuantumError
from .errors.readout_error import ReadoutError
from ..utils.helpers import deprecation

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -550,6 +551,22 @@ def add_readout_error(self, error, qubits, warnings=True):
self._noise_instructions.add("measure")

def as_dict(self, serializable=False):
"""
DEPRECATED: Use to_dict()
Returns a dictionary for noise model.
Args:
serializable (bool): if `True`, return a dict containing only types
that can be serializable by the stdlib `json` module.
Returns:
dict: a dictionary for a noise model.
"""
deprecation("NoiseModel::as_dict() method is deprecated and will be removed after 0.3."
"Use '.to_dict()' instead")
self.to_dict(serializable)

def to_dict(self, serializable=False):
"""
Return dictionary for noise model.
Expand All @@ -564,14 +581,14 @@ def as_dict(self, serializable=False):

# Add default quantum errors
for name, error in self._default_quantum_errors.items():
error_dict = error.as_dict()
error_dict = error.to_dict()
error_dict["operations"] = [name]
error_list.append(error_dict)

# Add specific qubit errors
for name, qubit_dict in self._local_quantum_errors.items():
for qubits_str, error in qubit_dict.items():
error_dict = error.as_dict()
error_dict = error.to_dict()
error_dict["operations"] = [name]
error_dict["gate_qubits"] = [self._str2qubits(qubits_str)]
error_list.append(error_dict)
Expand All @@ -580,7 +597,7 @@ def as_dict(self, serializable=False):
for name, qubit_dict in self._nonlocal_quantum_errors.items():
for qubits_str, noise_qubit_dict in qubit_dict.items():
for noise_qubits_str, error in noise_qubit_dict.items():
error_dict = error.as_dict()
error_dict = error.to_dict()
error_dict["operations"] = [name]
error_dict["gate_qubits"] = [self._str2qubits(qubits_str)]
error_dict["noise_qubits"] = [
Expand All @@ -590,12 +607,12 @@ def as_dict(self, serializable=False):

# Add default readout error
if self._default_readout_error is not None:
error_dict = self._default_readout_error.as_dict()
error_dict = self._default_readout_error.to_dict()
error_list.append(error_dict)

# Add local readout error
for qubits_str, error in self._local_readout_errors.items():
error_dict = error.as_dict()
error_dict = error.to_dict()
error_dict["gate_qubits"] = [self._str2qubits(qubits_str)]
error_list.append(error_dict)

Expand Down
2 changes: 1 addition & 1 deletion qiskit/providers/aer/noise/utils/noise_remapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def remap_noise_model(noise_model, remapping, discard_qubits=False, warnings=Tru
raise NoiseError('Duplicate qubits in remapping: {}'.format(inv_map))

# Convert noise model to dict
nm_dict = noise_model.as_dict()
nm_dict = noise_model.to_dict()

# Indexes of errors to keep
new_errors = []
Expand Down
10 changes: 5 additions & 5 deletions qiskit/providers/aer/noise/utils/noise_transformation.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ def approximate_noise_model(model, *,
operator_string=operator_string,
operator_dict=operator_dict,
operator_list=operator_list)
error_dict = error.as_dict()
error_dict = error.to_dict()
error_dict["operations"] = [operation]
error_list.append(error_dict)

Expand All @@ -164,7 +164,7 @@ def approximate_noise_model(model, *,
operator_string=operator_string,
operator_dict=operator_dict,
operator_list=operator_list)
error_dict = error.as_dict()
error_dict = error.to_dict()
error_dict["operations"] = [operation]
error_dict["gate_qubits"] = [model._str2qubits(qubits_str)]
error_list.append(error_dict)
Expand All @@ -178,7 +178,7 @@ def approximate_noise_model(model, *,
operator_string=operator_string,
operator_dict=operator_dict,
operator_list=operator_list)
error_dict = error.as_dict()
error_dict = error.to_dict()
error_dict["operations"] = [operation]
error_dict["gate_qubits"] = [model._str2qubits(qubits_str)]
error_dict["noise_qubits"] = [model._str2qubits(noise_str)]
Expand All @@ -191,7 +191,7 @@ def approximate_noise_model(model, *,
operator_string=operator_string,
operator_dict=operator_dict,
operator_list=operator_list)
error_dict = error.as_dict()
error_dict = error.to_dict()
error_list.append(error_dict)

# Add local readout error
Expand All @@ -201,7 +201,7 @@ def approximate_noise_model(model, *,
operator_string=operator_string,
operator_dict=operator_dict,
operator_list=operator_list)
error_dict = error.as_dict()
error_dict = error.to_dict()
error_dict["gate_qubits"] = [model._str2qubits(qubits_str)]
error_list.append(error_dict)

Expand Down
1 change: 1 addition & 0 deletions qiskit/providers/aer/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@
"""Utilities"""

from . import qobj_utils
from . import helpers
22 changes: 22 additions & 0 deletions qiskit/providers/aer/utils/helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

"""
A bunch of usefull helper functions
"""

from warnings import warn


def deprecation(message):
""" Shows a deprecation message to the user """
warn(message, DeprecationWarning, stacklevel=2)
2 changes: 0 additions & 2 deletions test/terra/noise/test_noise_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -756,8 +756,6 @@ def test_noise_models_equal(self):
error1 = pauli_error([['X', 1]], standard_gates=False)
error2 = pauli_error([['X', 1]], standard_gates=True)

print("error1: {}\nerror2: {}".format(error1, error2))

model1 = NoiseModel()
model1.add_all_qubit_quantum_error(error1, ['u3'], False)
model1.add_quantum_error(error1, ['u3'], [2], False)
Expand Down

0 comments on commit e79a9a1

Please sign in to comment.