Skip to content

Commit

Permalink
Add set state python instructions
Browse files Browse the repository at this point in the history
Move default_qubits to separate file

Move instructions to subfolders

Add set instructions to backends
  • Loading branch information
chriseclectic committed Mar 18, 2021
1 parent 8bf41d0 commit 587239a
Show file tree
Hide file tree
Showing 23 changed files with 500 additions and 83 deletions.
1 change: 1 addition & 0 deletions qiskit/providers/aer/backends/aerbackend.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ def __init__(self,
"""
# Init configuration and provider in BaseBackend
configuration.simulator = True
configuration.local = True
super().__init__(configuration, provider=provider)

# Initialize backend properties and pulse defaults.
Expand Down
27 changes: 17 additions & 10 deletions qiskit/providers/aer/backends/qasm_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,17 +293,13 @@ class QasmSimulator(AerBackend):
'mcphase', 'mcu1', 'mcu2', 'mcu3', 'mcrx', 'mcry', 'mcrz',
'mcr', 'mcswap', 'unitary', 'diagonal', 'multiplexer',
'initialize', 'delay', 'pauli', 'mcx_gray',
# Custom instructions
'kraus', 'roerror', 'snapshot', 'save_expval', 'save_expval_var',
'save_probabilities', 'save_probabilities_dict', 'save_state',
'save_density_matrix', 'save_statevector',
'save_amplitudes', 'save_amplitudes_sq', 'save_stabilizer'
]),
'custom_instructions': sorted([
'roerror', 'kraus', 'snapshot', 'save_expval', 'save_expval_var',
'save_probabilities', 'save_probabilities_dict',
'save_state', 'save_density_matrix', 'save_statevector',
'save_amplitudes', 'save_amplitudes_sq', 'save_stabilizer']),
'save_amplitudes', 'save_amplitudes_sq', 'save_stabilizer',
'set_statevector', 'set_density_matrix', 'set_stabilizer']),
'gates': []
}

Expand Down Expand Up @@ -467,10 +463,20 @@ def _method_configuration(method=None):
# Default configuration
config = QasmBackendConfiguration.from_dict(
QasmSimulator._DEFAULT_CONFIGURATION)
if method is None or method == 'automatic':
config.basis_gates = sorted(
config.basis_gates + config.custom_instructions)

# Statevector methods
if method in ['statevector', 'statevector_gpu', 'statevector_thrust']:
elif method in ['statevector', 'statevector_gpu', 'statevector_thrust']:
config.description = 'A C++ QasmQobj statevector simulator with noise'
config.custom_instructions = sorted([
'roerror', 'kraus', 'snapshot', 'save_expval', 'save_expval_var',
'save_probabilities', 'save_probabilities_dict',
'save_state', 'save_density_matrix', 'save_statevector',
'save_amplitudes', 'save_amplitudes_sq', 'set_statevector'])
config.basis_gates = sorted(
config.basis_gates + config.custom_instructions)

# Density Matrix methods
elif method in [
Expand All @@ -481,7 +487,7 @@ def _method_configuration(method=None):
config.custom_instructions = sorted([
'roerror', 'snapshot', 'kraus', 'superop', 'save_expval', 'save_expval_var',
'save_probabilities', 'save_probabilities_dict', 'save_density_matrix',
'save_amplitudes_sq', 'save_state'])
'save_amplitudes_sq', 'save_state', 'set_statevector', 'set_density_matrix'])
config.basis_gates = sorted([
'u1', 'u2', 'u3', 'u', 'p', 'r', 'rx', 'ry', 'rz', 'id', 'x',
'y', 'z', 'h', 's', 'sdg', 'sx', 't', 'tdg', 'swap', 'cx',
Expand All @@ -495,7 +501,7 @@ def _method_configuration(method=None):
config.custom_instructions = sorted([
'roerror', 'snapshot', 'kraus', 'save_expval', 'save_expval_var',
'save_probabilities', 'save_probabilities_dict',
'save_density_matrix', 'save_statevector',
'save_state', 'save_density_matrix', 'save_statevector',
'save_amplitudes', 'save_amplitudes_sq'])
config.basis_gates = sorted([
'u1', 'u2', 'u3', 'u', 'p', 'cp', 'cx', 'cy', 'cz', 'id', 'x', 'y', 'z', 'h', 's',
Expand All @@ -511,7 +517,8 @@ def _method_configuration(method=None):
config.custom_instructions = sorted([
'roerror', 'snapshot', 'save_expval', 'save_expval_var',
'save_probabilities', 'save_probabilities_dict',
'save_amplitudes_sq', 'save_stabilizer', 'save_state'])
'save_amplitudes_sq', 'save_stabilizer', 'save_state',
'set_stabilizer'])
config.basis_gates = sorted([
'id', 'x', 'y', 'z', 'h', 's', 'sdg', 'sx', 'cx', 'cy', 'cz',
'swap', 'delay',
Expand Down
2 changes: 1 addition & 1 deletion qiskit/providers/aer/backends/statevector_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ class StatevectorSimulator(AerBackend):
'initialize', 'kraus', 'roerror', 'delay', 'pauli',
'save_expval', 'save_density_matrix', 'save_statevector',
'save_probs', 'save_probs_ket', 'save_amplitudes',
'save_amplitudes_sq', 'save_state'
'save_amplitudes_sq', 'save_state', 'set_statevector'
],
'gates': []
}
Expand Down
2 changes: 1 addition & 1 deletion qiskit/providers/aer/backends/unitary_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ class UnitarySimulator(AerBackend):
'rzz', 'rzx', 'ccx', 'cswap', 'mcx', 'mcy', 'mcz', 'mcsx',
'mcp', 'mcu1', 'mcu2', 'mcu3', 'mcrx', 'mcry', 'mcrz',
'mcr', 'mcswap', 'unitary', 'diagonal', 'multiplexer', 'delay', 'pauli',
'save_unitary', 'save_state'
'save_unitary', 'save_state', 'set_unitary'
],
'gates': []
}
Expand Down
71 changes: 50 additions & 21 deletions qiskit/providers/aer/library/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
# 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.

"""
=========================================================
Instruction Library (:mod:`qiskit.providers.aer.library`)
Expand All @@ -21,6 +20,39 @@
:class:`~qiskit.circuit.Instruction` subclasses that can be used
with the Aer circuit simulator backends.
Setting a Custom Simulator State
================================
The following instruction classes can be used to set the specific
simulator methods to a custom state. Note that these instructions
are only valid when applied to all qubits in a circuit. Applying
to a subset of qubits will raise an exception during execution.
Instruction Classes
-------------------
.. autosummary::
:toctree: ../stubs/
SetStatevector
SetDensityMatrix
SetStabilizer
SetUnitary
Then can also be used using custom QuantumCircuit methods
QuantumCircuit Methods
----------------------
.. autosummary::
:toctree: ../stubs/
set_statevector
set_density_matrix
set_stabilizer
set_unitary
Saving Simulator Data
=====================
Expand Down Expand Up @@ -97,23 +129,20 @@
state.
"""

__all__ = ['SaveState',
'SaveExpectationValue', 'SaveExpectationValueVariance',
'SaveProbabilities', 'SaveProbabilitiesDict',
'SaveStatevector', 'SaveStatevectorDict', 'SaveDensityMatrix',
'SaveAmplitudes', 'SaveAmplitudesSquared', 'SaveUnitary',
'SaveStabilizer']

from .save_state import SaveState, save_state
from .save_expectation_value import (
SaveExpectationValue, save_expectation_value,
SaveExpectationValueVariance, save_expectation_value_variance)
from .save_probabilities import (SaveProbabilities, save_probabilities,
SaveProbabilitiesDict, save_probabilities_dict)
from .save_statevector import (SaveStatevector, save_statevector,
SaveStatevectorDict, save_statevector_dict)
from .save_density_matrix import SaveDensityMatrix, save_density_matrix
from .save_amplitudes import (SaveAmplitudes, save_amplitudes,
SaveAmplitudesSquared, save_amplitudes_squared)
from .save_stabilizer import SaveStabilizer, save_stabilizer
from .save_unitary import SaveUnitary, save_unitary
__all__ = [
'SaveState',
'SaveExpectationValue',
'SaveExpectationValueVariance',
'SaveProbabilities',
'SaveProbabilitiesDict',
'SaveStatevector',
'SaveStatevectorDict',
'SaveDensityMatrix',
'SaveAmplitudes',
'SaveAmplitudesSquared',
'SaveUnitary',
'SaveStabilizer',
]

from .save_instructions import *
from .set_instructions import *
55 changes: 55 additions & 0 deletions qiskit/providers/aer/library/default_qubits.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2021.
#
# 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.
"""
Helper function
"""

from qiskit.circuit import QuantumCircuit, QuantumRegister
from qiskit.extensions.exceptions import ExtensionError


def default_qubits(circuit, qubits=None):
"""Helper method to return list of qubits.
Args:
circuit (QuantumCircuit): a quantum circuit.
qubits (list or QuantumRegister): Optional, qubits argument,
If None the returned list will be all qubits in the circuit.
[Default: None]
Raises:
ExtensionError: if default qubits fails.
Returns:
list: qubits list.
"""
# Convert label to string for backwards compatibility
# If no qubits are specified we add all qubits so it acts as a barrier
# This is needed for full register snapshots like statevector
if isinstance(qubits, QuantumRegister):
qubits = qubits[:]
if not qubits:
tuples = []
if isinstance(circuit, QuantumCircuit):
for register in circuit.qregs:
tuples.append(register)
if not tuples:
raise ExtensionError('no qubits for snapshot')
qubits = []
for tuple_element in tuples:
if isinstance(tuple_element, QuantumRegister):
for j in range(tuple_element.size):
qubits.append(tuple_element[j])
else:
qubits.append(tuple_element)

return qubits
28 changes: 28 additions & 0 deletions qiskit/providers/aer/library/save_instructions/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2021.
#
# 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.
"""Save directive instructions for the Aer simulator"""

from .save_state import (SaveState, save_state)
from .save_expectation_value import (SaveExpectationValue,
save_expectation_value,
SaveExpectationValueVariance,
save_expectation_value_variance)
from .save_probabilities import (SaveProbabilities, save_probabilities,
SaveProbabilitiesDict,
save_probabilities_dict)
from .save_statevector import (SaveStatevector, save_statevector,
SaveStatevectorDict, save_statevector_dict)
from .save_density_matrix import SaveDensityMatrix, save_density_matrix
from .save_amplitudes import (SaveAmplitudes, save_amplitudes,
SaveAmplitudesSquared, save_amplitudes_squared)
from .save_stabilizer import (SaveStabilizer, save_stabilizer)
from .save_unitary import (SaveUnitary, save_unitary)
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@

from qiskit.circuit import QuantumCircuit
from qiskit.extensions.exceptions import ExtensionError
from .save_data import SaveSingleData, SaveAverageData, default_qubits
from .save_data import SaveSingleData, SaveAverageData
from ..default_qubits import default_qubits


class SaveAmplitudes(SaveSingleData):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@

import copy

from qiskit.circuit import QuantumCircuit, QuantumRegister
from qiskit.circuit import Instruction
from qiskit.extensions.exceptions import ExtensionError

Expand Down Expand Up @@ -143,41 +142,3 @@ def __init__(self,
if conditional:
subtype = 'c_' + subtype
super().__init__(name, num_qubits, label, subtype=subtype, params=params)


def default_qubits(circuit, qubits=None):
"""Helper method to return list of qubits.
Args:
circuit (QuantumCircuit): a quantum circuit.
qubits (list or QuantumRegister): Optional, qubits argument,
If None the returned list will be all qubits in the circuit.
[Default: None]
Raises:
ExtensionError: if default qubits fails.
Returns:
list: qubits list.
"""
# Convert label to string for backwards compatibility
# If no qubits are specified we add all qubits so it acts as a barrier
# This is needed for full register snapshots like statevector
if isinstance(qubits, QuantumRegister):
qubits = qubits[:]
if not qubits:
tuples = []
if isinstance(circuit, QuantumCircuit):
for register in circuit.qregs:
tuples.append(register)
if not tuples:
raise ExtensionError('no qubits for snapshot')
qubits = []
for tuple_element in tuples:
if isinstance(tuple_element, QuantumRegister):
for j in range(tuple_element.size):
qubits.append(tuple_element[j])
else:
qubits.append(tuple_element)

return qubits
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
"""

from qiskit.circuit import QuantumCircuit
from .save_data import SaveAverageData, default_qubits
from .save_data import SaveAverageData
from ..default_qubits import default_qubits


class SaveDensityMatrix(SaveAverageData):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
"""

from qiskit.circuit import QuantumCircuit
from .save_data import SaveAverageData, default_qubits
from .save_data import SaveAverageData
from ..default_qubits import default_qubits


class SaveProbabilities(SaveAverageData):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
"""

from qiskit.circuit import QuantumCircuit
from .save_data import SaveSingleData, default_qubits
from .save_data import SaveSingleData
from ..default_qubits import default_qubits


class SaveStabilizer(SaveSingleData):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
"""

from qiskit.circuit import QuantumCircuit
from .save_data import SaveSingleData, default_qubits
from .save_data import SaveSingleData
from ..default_qubits import default_qubits


class SaveState(SaveSingleData):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
"""

from qiskit.circuit import QuantumCircuit
from .save_data import SaveSingleData, default_qubits
from .save_data import SaveSingleData
from ..default_qubits import default_qubits


class SaveStatevector(SaveSingleData):
Expand All @@ -23,7 +24,7 @@ def __init__(self, num_qubits,
label="statevector",
pershot=False,
conditional=False):
"""Create new instruction to save the simualtor statevector.
"""Create new instruction to save the simulator statevector.
Args:
num_qubits (int): the number of qubits of the
Expand Down Expand Up @@ -51,7 +52,7 @@ def __init__(self, num_qubits,
label="statevector_dict",
pershot=False,
conditional=False):
"""Create new instruction to save the simualtor statevector as a dict.
"""Create new instruction to save the simulator statevector as a dict.
Args:
num_qubits (int): the number of qubits of the
Expand Down
Loading

0 comments on commit 587239a

Please sign in to comment.