Skip to content

Commit

Permalink
Add instructions to set simulator state (#1163)
Browse files Browse the repository at this point in the history
  • Loading branch information
chriseclectic authored Mar 26, 2021
1 parent 4f615be commit 25a6d91
Show file tree
Hide file tree
Showing 43 changed files with 972 additions and 167 deletions.
18 changes: 15 additions & 3 deletions qiskit/providers/aer/backends/qasm_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,8 @@ class QasmSimulator(AerBackend):
'save_probabilities', 'save_probabilities_dict',
'save_amplitudes', 'save_amplitudes_sq', 'save_state',
'save_density_matrix', 'save_statevector', 'save_statevector_dict',
'save_stabilizer'
'save_stabilizer', 'set_statevector', 'set_density_matrix',
'set_stabilizer'
])

_DEFAULT_CONFIGURATION = {
Expand Down Expand Up @@ -560,15 +561,25 @@ def _method_basis_gates(self):

def _custom_instructions(self):
"""Return method basis gates and custom instructions"""
# pylint: disable = too-many-return-statements
if 'custom_instructions' in self._options_configuration:
return self._options_configuration['custom_instructions']

method = self._options.get('method', None)
if method in ['statevector', 'statevector_gpu', 'statevector_thrust']:
return sorted([
'roerror', 'kraus', 'snapshot', 'save_expval', 'save_expval_var',
'save_probabilities', 'save_probabilities_dict',
'save_amplitudes', 'save_amplitudes_sq', 'save_state',
'save_density_matrix', 'save_statevector', 'save_statevector_dict',
'set_statevector'
])
if method in ['density_matrix', 'density_matrix_gpu', 'density_matrix_thrust']:
return sorted([
'roerror', 'kraus', 'superop', 'snapshot', 'save_expval', 'save_expval_var',
'save_probabilities', 'save_probabilities_dict',
'save_state', 'save_density_matrix', 'save_amplitudes_sq'
'save_state', 'save_density_matrix', 'save_amplitudes_sq',
'set_statevector', 'set_density_matrix'
])
if method == 'matrix_product_state':
return sorted([
Expand All @@ -580,7 +591,8 @@ def _custom_instructions(self):
return sorted([
'roerror', 'snapshot', 'save_expval', 'save_expval_var',
'save_probabilities', 'save_probabilities_dict',
'save_amplitudes_sq', 'save_state', 'save_stabilizer'
'save_amplitudes_sq', 'save_state', 'save_stabilizer',
'set_stabilizer'
])
if method == 'extended_stabilizer':
return sorted(['roerror', 'snapshot', 'save_statevector',
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 @@ -134,7 +134,7 @@ class StatevectorSimulator(AerBackend):
'kraus', 'roerror',
'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 @@ -135,7 +135,7 @@ class UnitarySimulator(AerBackend):
'mcp', 'mcu1', 'mcu2', 'mcu3', 'mcrx', 'mcry', 'mcrz',
'mcr', 'mcswap', 'unitary', 'diagonal', 'multiplexer', 'delay', 'pauli',
]),
'custom_instructions': sorted(['save_unitary', 'save_state']),
'custom_instructions': sorted(['save_unitary', 'save_state', 'set_unitary']),
'gates': []
}

Expand Down
73 changes: 51 additions & 22 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 @@ -99,24 +131,21 @@
state.
"""

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

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
from .save_matrix_product_state import SaveMatrixProductState, save_matrix_product_state
__all__ = [
'SaveState',
'SaveExpectationValue',
'SaveExpectationValueVariance',
'SaveProbabilities',
'SaveProbabilitiesDict',
'SaveStatevector',
'SaveStatevectorDict',
'SaveDensityMatrix',
'SaveAmplitudes',
'SaveAmplitudesSquared',
'SaveUnitary',
'SaveStabilizer',
'SaveMatrixProductState'
]

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
30 changes: 30 additions & 0 deletions qiskit/providers/aer/library/save_instructions/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# 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)
from .save_matrix_product_state import (
SaveMatrixProductState, save_matrix_product_state)
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 SaveSingleData, default_qubits
from .save_data import SaveSingleData
from ..default_qubits import default_qubits


class SaveMatrixProductState(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 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
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 SaveUnitary(SaveSingleData):
Expand Down
17 changes: 17 additions & 0 deletions qiskit/providers/aer/library/set_instructions/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# 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.
"""Set state directive instructions for the Aer simulator"""

from .set_statevector import SetStatevector, set_statevector
from .set_density_matrix import SetDensityMatrix, set_density_matrix
from .set_unitary import SetUnitary, set_unitary
from .set_stabilizer import SetStabilizer, set_stabilizer
Loading

0 comments on commit 25a6d91

Please sign in to comment.