text
stringlengths
4
4.46M
id
stringlengths
13
126
metadata
dict
__index_level_0__
int64
0
415
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Unit tests for tape expansion stopping criteria and expansion functions. """ # pylint: disable=too-few-public-methods, invalid-unary-operand-type, no-member, # pylint: disable=arguments-differ, arguments-renamed, import warnings import numpy as np import pytest import pennylane as qml from pennylane.wires import Wires class TestCreateExpandFn: """Test creating expansion functions from stopping criteria.""" crit_0 = (~qml.operation.is_trainable) | (qml.operation.has_gen & qml.operation.is_trainable) doc_0 = "Test docstring." with qml.queuing.AnnotatedQueue() as q: qml.RX(0.2, wires=0) qml.RY(qml.numpy.array(2.1, requires_grad=True), wires=1) qml.Rot(*qml.numpy.array([0.5, 0.2, -0.1], requires_grad=True), wires=0) tape = qml.tape.QuantumScript.from_queue(q) def test_create_expand_fn(self): """Test creation of expand_fn.""" expand_fn = qml.transforms.create_expand_fn( depth=10, stop_at=self.crit_0, docstring=self.doc_0, ) assert expand_fn.__doc__ == "Test docstring." def test_create_expand_fn_expansion(self): """Test expansion with created expand_fn.""" expand_fn = qml.transforms.create_expand_fn(depth=10, stop_at=self.crit_0) new_tape = expand_fn(self.tape) assert new_tape.operations[0] == self.tape.operations[0] assert new_tape.operations[1] == self.tape.operations[1] assert [op.name for op in new_tape.operations[2:]] == ["RZ", "RY", "RZ"] assert np.allclose([op.data for op in new_tape.operations[2:]], [[0.5], [0.2], [-0.1]]) assert [op.wires for op in new_tape.operations[2:]] == [qml.wires.Wires(0)] * 3 def test_create_expand_fn_dont_expand(self): """Test expansion is skipped with depth=0.""" expand_fn = qml.transforms.create_expand_fn(depth=0, stop_at=self.crit_0) new_tape = expand_fn(self.tape) assert new_tape.operations == self.tape.operations def test_device_and_stopping_expansion(self): """Test that passing a device alongside a stopping condition ensures that all operations are expanded to match the devices default gate set""" dev = qml.device("default.qubit.legacy", wires=1) expand_fn = qml.transforms.create_expand_fn(device=dev, depth=10, stop_at=self.crit_0) with qml.queuing.AnnotatedQueue() as q: qml.U1(0.2, wires=0) qml.Rot(*qml.numpy.array([0.5, 0.2, -0.1], requires_grad=True), wires=0) tape = qml.tape.QuantumScript.from_queue(q) new_tape = expand_fn(tape) assert new_tape.operations[0].name == "U1" assert [op.name for op in new_tape.operations[1:]] == ["RZ", "RY", "RZ"] def test_device_only_expansion(self): """Test that passing a device ensures that all operations are expanded to match the devices default gate set""" dev = qml.device("default.qubit.legacy", wires=1) expand_fn = qml.transforms.create_expand_fn(device=dev, depth=10) with qml.queuing.AnnotatedQueue() as q: qml.U1(0.2, wires=0) qml.Rot(*qml.numpy.array([0.5, 0.2, -0.1], requires_grad=True), wires=0) tape = qml.tape.QuantumScript.from_queue(q) new_tape = expand_fn(tape) assert len(new_tape.operations) == 2 assert new_tape.operations[0].name == "U1" assert new_tape.operations[1].name == "Rot" def test_depth_only_expansion(self): """Test that passing a depth simply expands to that depth""" with qml.queuing.AnnotatedQueue() as q: qml.RX(0.2, wires=0) qml.RY(qml.numpy.array(2.1, requires_grad=True), wires=1) qml.Rot(*qml.numpy.array([0.5, 0.2, -0.1], requires_grad=True), wires=0) qml.templates.StronglyEntanglingLayers( qml.numpy.ones([2, 2, 3], requires_grad=True), wires=[0, 1] ) tape = qml.tape.QuantumScript.from_queue(q) expand_fn = qml.transforms.create_expand_fn(depth=0) new_tape = expand_fn(tape) assert new_tape is tape expand_fn = qml.transforms.create_expand_fn(depth=10) new_tape = expand_fn(tape) assert new_tape.operations[0] == tape.operations[0] assert new_tape.operations[1] == tape.operations[1] assert [op.name for op in new_tape.operations[2:5]] == ["RZ", "RY", "RZ"] assert len(new_tape.operations[6:]) == 15 class TestExpandMultipar: """Test the expansion of multi-parameter gates.""" def test_expand_multipar(self): """Test that a multi-parameter gate is decomposed correctly. And that single-parameter gates are not decomposed.""" class _CRX(qml.CRX): name = "_CRX" @staticmethod def decomposition(theta, wires): raise NotImplementedError() with qml.queuing.AnnotatedQueue() as q: qml.RX(1.5, wires=0) qml.Rot(-2.1, 0.2, -0.418, wires=1) _CRX(1.5, wires=[0, 2]) tape = qml.tape.QuantumScript.from_queue(q) new_tape = qml.transforms.expand_multipar(tape) new_ops = new_tape.operations assert [op.name for op in new_ops] == ["RX", "RZ", "RY", "RZ", "_CRX"] def test_no_generator_expansion(self): """Test that a gate is decomposed correctly if it has generator[0]==None.""" # pylint: disable=invalid-overridden-method class _CRX(qml.CRX): @property def has_generator(self): return False def generator(self): raise qml.operations.GeneratorUndefinedError() with qml.queuing.AnnotatedQueue() as q: qml.RX(1.5, wires=0) qml.RZ(-2.1, wires=1) qml.RY(0.2, wires=1) qml.RZ(-0.418, wires=1) _CRX(1.5, wires=[0, 2]) tape = qml.tape.QuantumScript.from_queue(q) new_tape = qml.transforms.expand_multipar(tape) new_ops = new_tape.operations expected = ["RX", "RZ", "RY", "RZ", "RZ", "RY", "CNOT", "RY", "CNOT", "RZ"] assert [op.name for op in new_ops] == expected class TestExpandNonunitaryGen: """Test the expansion of operations without a unitary generator.""" def test_do_not_expand(self): """Test that a tape with single-parameter operations with unitary generators and non-parametric operations is not touched.""" with qml.queuing.AnnotatedQueue() as q: qml.RX(0.2, wires=0) qml.Hadamard(0) qml.PauliRot(0.9, "XY", wires=[0, 1]) qml.SingleExcitationPlus(-1.2, wires=[1, 0]) tape = qml.tape.QuantumScript.from_queue(q) new_tape = qml.transforms.expand_nonunitary_gen(tape) assert tape.operations == new_tape.operations def test_expand_multi_par(self): """Test that a tape with single-parameter operations with unitary generators and non-parametric operations is not touched.""" with qml.queuing.AnnotatedQueue() as q: qml.RX(0.2, wires=0) qml.Hadamard(0) qml.Rot(0.9, 1.2, -0.6, wires=0) qml.SingleExcitationPlus(-1.2, wires=[1, 0]) tape = qml.tape.QuantumScript.from_queue(q) new_tape = qml.transforms.expand_nonunitary_gen(tape) expanded = [ qml.RZ(0.9, wires=0), qml.RY(1.2, wires=0), qml.RZ(-0.6, wires=0), ] assert tape.operations[:2] == new_tape.operations[:2] assert all(exp.name == new.name for exp, new in zip(expanded, new_tape.operations[2:5])) assert all(exp.data == new.data for exp, new in zip(expanded, new_tape.operations[2:5])) assert all(exp.wires == new.wires for exp, new in zip(expanded, new_tape.operations[2:5])) assert tape.operations[3:] == new_tape.operations[5:] def test_expand_missing_generator(self): """Test that a tape with single-parameter operations with unitary generators and non-parametric operations is not touched.""" class _PhaseShift(qml.PhaseShift): def generator(self): return None with qml.queuing.AnnotatedQueue() as q: qml.RX(0.2, wires=0) qml.Hadamard(0) _PhaseShift(2.1, wires=1) qml.SingleExcitationPlus(-1.2, wires=[1, 0]) tape = qml.tape.QuantumScript.from_queue(q) new_tape = qml.transforms.expand_nonunitary_gen(tape) assert tape.operations[:2] == new_tape.operations[:2] exp_op, gph_op = new_tape.operations[2:4] assert exp_op.name == "RZ" and exp_op.data == (2.1,) and exp_op.wires == qml.wires.Wires(1) assert gph_op.name == "GlobalPhase" and gph_op.data == (-2.1 * 0.5,) assert tape.operations[3:] == new_tape.operations[4:] def test_expand_nonunitary_generator(self): """Test that a tape with single-parameter operations with unitary generators and non-parametric operations is not touched.""" with qml.queuing.AnnotatedQueue() as q: qml.RX(0.2, wires=0) qml.Hadamard(0) qml.PhaseShift(2.1, wires=1) qml.SingleExcitationPlus(-1.2, wires=[1, 0]) tape = qml.tape.QuantumScript.from_queue(q) new_tape = qml.transforms.expand_nonunitary_gen(tape) assert tape.operations[:2] == new_tape.operations[:2] exp_op, gph_op = new_tape.operations[2:4] assert exp_op.name == "RZ" and exp_op.data == (2.1,) and exp_op.wires == qml.wires.Wires(1) assert gph_op.name == "GlobalPhase" and gph_op.data == (-2.1 * 0.5,) assert tape.operations[3:] == new_tape.operations[4:] def test_decompose_all_nonunitary_generator(self): """Test that decompositions actually only contain unitarily generated operators (Bug #4055).""" # Corrected list of unitarily generated operators unitarily_generated = [ "RX", "RY", "RZ", "MultiRZ", "PauliRot", "IsingXX", "IsingYY", "IsingZZ", "SingleExcitationMinus", "SingleExcitationPlus", "DoubleExcitationMinus", "DoubleExcitationPlus", ] with qml.queuing.AnnotatedQueue() as q: # All do not have unitary generator, but previously had this # attribute qml.IsingXY(0.35, wires=[0, 1]) qml.SingleExcitation(1.61, wires=[1, 0]) qml.DoubleExcitation(0.56, wires=[0, 1, 2, 3]) qml.OrbitalRotation(1.15, wires=[1, 0, 3, 2]) qml.FermionicSWAP(0.3, wires=[2, 3]) tape = qml.tape.QuantumScript.from_queue(q) new_tape = qml.transforms.expand_nonunitary_gen(tape) for op in new_tape.operations: assert op.name in unitarily_generated or op.num_params == 0 class TestExpandInvalidTrainable: """Tests for the gradient expand function""" def test_no_expansion(self, mocker): """Test that a circuit with differentiable operations is not expanded""" x = qml.numpy.array(0.2, requires_grad=True) y = qml.numpy.array(0.1, requires_grad=True) with qml.queuing.AnnotatedQueue() as q: qml.RX(x, wires=0) qml.RY(y, wires=1) qml.CNOT(wires=[0, 1]) qml.expval(qml.PauliZ(0)) tape = qml.tape.QuantumScript.from_queue(q) spy = mocker.spy(tape, "expand") new_tape = qml.transforms.expand_invalid_trainable(tape) assert new_tape is tape spy.assert_not_called() def test_trainable_nondiff_expansion(self, mocker): """Test that a circuit with non-differentiable trainable operations is expanded""" x = qml.numpy.array(0.2, requires_grad=True) y = qml.numpy.array(0.1, requires_grad=True) class NonDiffPhaseShift(qml.PhaseShift): grad_method = None with qml.queuing.AnnotatedQueue() as q: NonDiffPhaseShift(x, wires=0) qml.RY(y, wires=1) qml.CNOT(wires=[0, 1]) qml.expval(qml.PauliZ(0)) tape = qml.tape.QuantumScript.from_queue(q) spy = mocker.spy(tape, "expand") new_tape = qml.transforms.expand_invalid_trainable(tape) assert new_tape is not tape spy.assert_called() assert new_tape.operations[0].name == "RZ" assert new_tape.operations[0].grad_method == "A" assert new_tape.operations[1].name == "RY" assert new_tape.operations[2].name == "CNOT" def test_nontrainable_nondiff(self, mocker): """Test that a circuit with non-differentiable non-trainable operations is not expanded""" x = qml.numpy.array(0.2, requires_grad=False) y = qml.numpy.array(0.1, requires_grad=True) class NonDiffPhaseShift(qml.PhaseShift): grad_method = None with qml.queuing.AnnotatedQueue() as q: NonDiffPhaseShift(x, wires=0) qml.RY(y, wires=1) qml.CNOT(wires=[0, 1]) qml.expval(qml.PauliZ(0)) tape = qml.tape.QuantumScript.from_queue(q) params = tape.get_parameters(trainable_only=False) tape.trainable_params = qml.math.get_trainable_indices(params) assert tape.trainable_params == [1] spy = mocker.spy(tape, "expand") new_tape = qml.transforms.expand_invalid_trainable(tape) assert new_tape is tape spy.assert_not_called() def test_trainable_numeric(self, mocker): """Test that a circuit with numeric differentiable trainable operations is *not* expanded""" x = qml.numpy.array(0.2, requires_grad=True) y = qml.numpy.array(0.1, requires_grad=True) class NonDiffPhaseShift(qml.PhaseShift): grad_method = "F" with qml.queuing.AnnotatedQueue() as q: NonDiffPhaseShift(x, wires=0) qml.RY(y, wires=1) qml.CNOT(wires=[0, 1]) qml.expval(qml.PauliZ(0)) tape = qml.tape.QuantumScript.from_queue(q) spy = mocker.spy(tape, "expand") new_tape = qml.transforms.expand_invalid_trainable(tape) assert new_tape is tape spy.assert_not_called() # Custom decomposition functions for testing. def custom_cnot(wires, **_): return [ qml.Hadamard(wires=wires[1]), qml.CZ(wires=[wires[0], wires[1]]), qml.Hadamard(wires=wires[1]), ] def custom_hadamard(wires): return [qml.RZ(np.pi, wires=wires), qml.RY(np.pi / 2, wires=wires)] # Incorrect, for testing purposes only def custom_rx(params, wires): return [qml.RY(params, wires=wires), qml.Hadamard(wires=wires)] # To test the gradient; use circuit identity RY(theta) = X RY(-theta) X def custom_rot(phi, theta, omega, wires): return [ qml.RZ(phi, wires=wires), qml.PauliX(wires=wires), qml.RY(-theta, wires=wires), qml.PauliX(wires=wires), qml.RZ(omega, wires=wires), ] # Decompose a template into another template def custom_basic_entangler_layers(weights, wires, **kwargs): # pylint: disable=unused-argument cnot_broadcast = qml.tape.make_qscript(qml.broadcast)(qml.CNOT, pattern="ring", wires=wires) return [ qml.AngleEmbedding(weights[0], wires=wires), *cnot_broadcast, ] class TestCreateCustomDecompExpandFn: """Tests for the custom_decomps argument for devices""" @pytest.fixture(scope="function", autouse=True) def capture_warnings(self): with pytest.warns( qml.PennyLaneDeprecationWarning, ) as record: yield assert any( "'expansion_strategy' attribute is deprecated" in str(w.message) for w in record ) for w in record: if "'expansion_strategy' attribute is deprecated" not in str(w.message): warnings.warn(w.message, w.category) @pytest.mark.parametrize("device_name", ["default.qubit", "default.qubit.legacy"]) def test_string_and_operator_allowed(self, device_name): """Test that the custom_decomps dictionary accepts both strings and operator classes as keys.""" custom_decomps = {"Hadamard": custom_hadamard, qml.CNOT: custom_cnot} decomp_dev = qml.device(device_name, wires=2, custom_decomps=custom_decomps) @qml.qnode(decomp_dev, expansion_strategy="device") def circuit(): qml.Hadamard(wires=0) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0)) _ = circuit() decomp_ops = circuit.tape.operations assert len(decomp_ops) == 7 for op in decomp_ops: assert op.name != "Hadamard" assert op.name != "CNOT" @pytest.mark.parametrize("device_name", ["default.qubit", "default.qubit.legacy"]) def test_no_custom_decomp(self, device_name): """Test that sending an empty dictionary results in no decompositions.""" def circuit(): qml.Hadamard(wires=0) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0)) original_dev = qml.device(device_name, wires=3) decomp_dev = qml.device(device_name, wires=3, custom_decomps={}) original_qnode = qml.QNode(circuit, original_dev, expansion_strategy="device") decomp_qnode = qml.QNode(circuit, decomp_dev, expansion_strategy="device") original_res = original_qnode() decomp_res = decomp_qnode() assert np.isclose(original_res, decomp_res) assert [ orig_op.name == decomp_op.name for orig_op, decomp_op in zip( original_qnode.qtape.operations, decomp_qnode.qtape.operations ) ] @pytest.mark.parametrize("device_name", ["default.qubit", "default.qubit.legacy"]) def test_no_custom_decomp_template(self, device_name): """Test that sending an empty dictionary results in no decomposition when a template is involved, except the decomposition expected from the device.""" def circuit(): qml.BasicEntanglerLayers([[0.1, 0.2]], wires=[0, 1]) return qml.expval(qml.PauliZ(0)) original_dev = qml.device(device_name, wires=3) decomp_dev = qml.device(device_name, wires=3, custom_decomps={}) original_qnode = qml.QNode(circuit, original_dev, expansion_strategy="device") decomp_qnode = qml.QNode(circuit, decomp_dev, expansion_strategy="device") original_res = original_qnode() decomp_res = decomp_qnode() assert np.isclose(original_res, decomp_res) assert [ orig_op.name == decomp_op.name for orig_op, decomp_op in zip( original_qnode.qtape.operations, decomp_qnode.qtape.operations ) ] @pytest.mark.parametrize( "device_name", ["default.qubit", "default.qubit.legacy", "lightning.qubit"] ) def test_one_custom_decomp(self, device_name): """Test that specifying a single custom decomposition works as expected.""" custom_decomps = {"Hadamard": custom_hadamard} decomp_dev = qml.device(device_name, wires=2, custom_decomps=custom_decomps) @qml.qnode(decomp_dev, expansion_strategy="device") def circuit(): qml.Hadamard(wires=0) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0)) _ = circuit() decomp_ops = circuit.tape.operations assert len(decomp_ops) == 3 assert decomp_ops[0].name == "RZ" assert np.isclose(decomp_ops[0].parameters[0], np.pi) assert decomp_ops[1].name == "RY" assert np.isclose(decomp_ops[1].parameters[0], np.pi / 2) assert decomp_ops[2].name == "CNOT" @pytest.mark.parametrize("device_name", ["default.qubit", "default.qubit.legacy"]) def test_no_decomp_with_depth_zero(self, device_name): """Test that specifying a single custom decomposition works as expected.""" custom_decomps = {"Hadamard": custom_hadamard, "CNOT": custom_cnot} with pytest.warns( qml.PennyLaneDeprecationWarning, match="The decomp_depth argument is deprecated" ): decomp_dev = qml.device( device_name, wires=2, custom_decomps=custom_decomps, decomp_depth=0 ) @qml.qnode(decomp_dev, expansion_strategy="device") def circuit(): qml.Hadamard(wires=0) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0)) _ = circuit() decomp_ops = circuit.tape.operations assert len(decomp_ops) == 2 assert decomp_ops[0].name == "Hadamard" assert decomp_ops[1].name == "CNOT" @pytest.mark.parametrize("device_name", ["default.qubit", "default.qubit.legacy"]) def test_one_custom_decomp_gradient(self, device_name): """Test that gradients are still correctly computed after a decomposition that performs transpilation.""" def circuit(x): qml.Hadamard(wires=0) qml.Rot(x[0], x[1], x[2], wires=0) qml.Hadamard(wires=0) return qml.expval(qml.PauliZ(0)) original_dev = qml.device(device_name, wires=3) decomp_dev = qml.device(device_name, wires=3, custom_decomps={"Rot": custom_rot}) original_qnode = qml.QNode(circuit, original_dev, expansion_strategy="device") decomp_qnode = qml.QNode(circuit, decomp_dev, expansion_strategy="device") x = qml.numpy.array([0.2, 0.3, 0.4], requires_grad=True) original_res = original_qnode(x) decomp_res = decomp_qnode(x) assert np.allclose(original_res, decomp_res) original_grad = qml.grad(original_qnode)(x) decomp_grad = qml.grad(decomp_qnode)(x) assert np.allclose(original_grad, decomp_grad) expected_ops = ["Hadamard", "RZ", "PauliX", "RY", "PauliX", "RZ", "Hadamard"] assert all(op.name == name for op, name in zip(decomp_qnode.qtape.operations, expected_ops)) @pytest.mark.parametrize("device_name", ["default.qubit", "default.qubit.legacy"]) def test_nested_custom_decomp(self, device_name): """Test that specifying two custom decompositions that have interdependence works as expected.""" custom_decomps = {"Hadamard": custom_hadamard, qml.CNOT: custom_cnot} decomp_dev = qml.device(device_name, wires=2, custom_decomps=custom_decomps) @qml.qnode(decomp_dev, expansion_strategy="device") def circuit(): qml.Hadamard(wires=0) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0)) _ = circuit() decomp_ops = circuit.tape.operations assert len(decomp_ops) == 7 # Check the RZ gates are in the correct place for idx in [0, 2, 5]: assert decomp_ops[idx].name == "RZ" assert np.isclose(decomp_ops[idx].parameters[0], np.pi) assert decomp_ops[0].wires == Wires(0) assert decomp_ops[2].wires == Wires(1) assert decomp_ops[5].wires == Wires(1) # Check RY are in the correct place for idx in [1, 3, 6]: assert decomp_ops[idx].name == "RY" assert np.isclose(decomp_ops[idx].parameters[0], np.pi / 2) assert decomp_ops[1].wires == Wires(0) assert decomp_ops[3].wires == Wires(1) assert decomp_ops[6].wires == Wires(1) assert decomp_ops[4].name == "CZ" @pytest.mark.parametrize("device_name", ["default.qubit", "default.qubit.legacy"]) def test_nested_custom_decomp_with_template(self, device_name): """Test that specifying two custom decompositions that have interdependence works as expected even when there is a template.""" custom_decomps = {"Hadamard": custom_hadamard, qml.CNOT: custom_cnot} decomp_dev = qml.device(device_name, wires=2, custom_decomps=custom_decomps) @qml.qnode(decomp_dev, expansion_strategy="device") def circuit(): # -RX(0.1)-C- -> -RX(0.1)---C--- -> -RX(0.1)-----------------C---------------- # -RX(0.2)-X- -> -RX(0.2)-H-Z-H- -> -RX(0.2)-RZ(pi)-RY(pi/2)-Z-RY(pi/2)-RZ(pi)- qml.BasicEntanglerLayers([[0.1, 0.2]], wires=[0, 1]) return qml.expval(qml.PauliZ(0)) _ = circuit() decomp_ops = circuit.tape.operations assert len(decomp_ops) == 7 assert decomp_ops[0].name == "RX" assert decomp_ops[0].parameters[0] == 0.1 assert decomp_ops[0].wires == Wires(0) assert decomp_ops[1].name == "RX" assert decomp_ops[1].parameters[0] == 0.2 assert decomp_ops[1].wires == Wires(1) assert decomp_ops[2].name == "RZ" assert np.isclose(decomp_ops[2].parameters[0], np.pi) assert decomp_ops[2].wires == Wires(1) assert decomp_ops[3].name == "RY" assert np.isclose(decomp_ops[3].parameters[0], np.pi / 2) assert decomp_ops[3].wires == Wires(1) assert decomp_ops[4].name == "CZ" assert decomp_ops[4].wires == Wires([0, 1]) assert decomp_ops[5].name == "RZ" assert np.isclose(decomp_ops[5].parameters[0], np.pi) assert decomp_ops[5].wires == Wires(1) assert decomp_ops[6].name == "RY" assert np.isclose(decomp_ops[6].parameters[0], np.pi / 2) assert decomp_ops[6].wires == Wires(1) @pytest.mark.parametrize("device_name", ["default.qubit", "default.qubit.legacy"]) def test_custom_decomp_template_to_template(self, device_name): """Test that decomposing a template into another template and some gates yields the correct results.""" # BasicEntanglerLayers custom decomposition involves AngleEmbedding custom_decomps = {"BasicEntanglerLayers": custom_basic_entangler_layers, "RX": custom_rx} decomp_dev = qml.device(device_name, wires=2, custom_decomps=custom_decomps) @qml.qnode(decomp_dev, expansion_strategy="device") def circuit(): qml.BasicEntanglerLayers([[0.1, 0.2]], wires=[0, 1]) return qml.expval(qml.PauliZ(0)) _ = circuit() decomp_ops = circuit.tape.operations assert len(decomp_ops) == 5 assert decomp_ops[0].name == "RY" assert decomp_ops[0].parameters[0] == 0.1 assert decomp_ops[0].wires == Wires(0) assert decomp_ops[1].name == "Hadamard" assert decomp_ops[1].wires == Wires(0) assert decomp_ops[2].name == "RY" assert np.isclose(decomp_ops[2].parameters[0], 0.2) assert decomp_ops[2].wires == Wires(1) assert decomp_ops[3].name == "Hadamard" assert decomp_ops[3].wires == Wires(1) assert decomp_ops[4].name == "CNOT" assert decomp_ops[4].wires == Wires([0, 1]) @pytest.mark.parametrize("device_name", ["default.qubit", "default.qubit.legacy"]) def test_custom_decomp_different_depth(self, device_name): """Test that alternative expansion depths can be specified.""" # BasicEntanglerLayers custom decomposition involves AngleEmbedding. If # expansion depth is 2, the AngleEmbedding will still be decomposed into # RX (since it's not a supported operation on the device), but the RX will # not be further decomposed even though the custom decomposition is specified. custom_decomps = {"BasicEntanglerLayers": custom_basic_entangler_layers, "RX": custom_rx} with pytest.warns( qml.PennyLaneDeprecationWarning, match="The decomp_depth argument is deprecated" ): decomp_dev_2 = qml.device( device_name, wires=2, custom_decomps=custom_decomps, decomp_depth=2 ) decomp_dev_3 = qml.device( device_name, wires=2, custom_decomps=custom_decomps, decomp_depth=3 ) def circuit(): qml.BasicEntanglerLayers([[0.1, 0.2]], wires=[0, 1]) return qml.expval(qml.PauliZ(0)) circuit2 = qml.QNode(circuit, decomp_dev_2, expansion_strategy="device") circuit3 = qml.QNode(circuit, decomp_dev_3, expansion_strategy="device") _ = circuit2() _ = circuit3() decomp_ops = circuit2.tape.operations assert len(decomp_ops) == 3 assert decomp_ops[0].name == "RX" assert np.isclose(decomp_ops[0].parameters[0], 0.1) assert decomp_ops[0].wires == Wires(0) assert decomp_ops[1].name == "RX" assert np.isclose(decomp_ops[1].parameters[0], 0.2) assert decomp_ops[1].wires == Wires(1) assert decomp_ops[2].name == "CNOT" assert decomp_ops[2].wires == Wires([0, 1]) decomp_ops = circuit3.tape.operations assert len(decomp_ops) == 5 @pytest.mark.parametrize("device_name", ["default.qubit", "default.qubit.legacy"]) def test_custom_decomp_with_adjoint(self, device_name): """Test that applying an adjoint in the circuit results in the adjoint undergoing the custom decomposition.""" custom_decomps = {qml.RX: custom_rx} decomp_dev = qml.device(device_name, wires="a", custom_decomps=custom_decomps) @qml.qnode(decomp_dev, expansion_strategy="device") def circuit(): # Adjoint is RX(-0.2), so expect RY(-0.2) H qml.adjoint(qml.RX, lazy=False)(0.2, wires="a") return qml.expval(qml.PauliZ("a")) _ = circuit() decomp_ops = circuit.tape.operations assert len(decomp_ops) == 2 assert decomp_ops[0].name == "RY" assert decomp_ops[0].parameters[0] == -0.2 assert decomp_ops[0].wires == Wires("a") assert decomp_ops[1].name == "Hadamard" assert decomp_ops[1].wires == Wires("a") @pytest.mark.parametrize("device_name", ["default.qubit", "default.qubit.legacy"]) def test_custom_decomp_with_control(self, device_name): """Test that decomposing a controlled version of a gate uses the custom decomposition for the base gate.""" class CustomOp(qml.operation.Operation): num_wires = 1 @staticmethod def compute_decomposition(wires): return [qml.S(wires)] original_decomp = CustomOp(0).decomposition() custom_decomps = {CustomOp: lambda wires: [qml.T(wires), qml.T(wires)]} decomp_dev = qml.device(device_name, wires=2, custom_decomps=custom_decomps) @qml.qnode(decomp_dev, expansion_strategy="device") def circuit(): qml.ctrl(CustomOp, control=1)(0) return qml.expval(qml.PauliZ(0)) circuit.construct(tuple(), {}) decomp_ops = circuit.tape.operations assert len(decomp_ops) == 2 for op in decomp_ops: assert isinstance(op, qml.ops.op_math.Controlled) qml.assert_equal(op.base, qml.T(0)) # check that new instances of the operator are not affected by the modifications made to get the decomposition assert [op1 == op2 for op1, op2 in zip(CustomOp(0).decomposition(), original_decomp)] def test_custom_decomp_in_separate_context_legacy_opmath(self): """Test that the set_decomposition context manager works.""" dev = qml.device("default.qubit.legacy", wires=2) @qml.qnode(dev, expansion_strategy="device") def circuit(): qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(wires=0)) # Initial test _ = circuit() assert len(circuit.qtape.operations) == 1 assert circuit.qtape.operations[0].name == "CNOT" assert dev.custom_expand_fn is None # Test within the context manager with qml.transforms.set_decomposition({qml.CNOT: custom_cnot}, dev): _ = circuit() ops_in_context = circuit.qtape.operations assert dev.custom_expand_fn is not None assert len(ops_in_context) == 3 assert ops_in_context[0].name == "Hadamard" assert ops_in_context[1].name == "CZ" assert ops_in_context[2].name == "Hadamard" # Check that afterwards, the device has gone back to normal circuit() assert len(circuit.qtape.operations) == 1 assert circuit.qtape.operations[0].name == "CNOT" assert dev.custom_expand_fn is None def test_custom_decomp_in_separate_context(self, mocker): """Test that the set_decomposition context manager works for the new device API.""" # pylint:disable=protected-access dev = qml.device("default.qubit", wires=2) spy = mocker.spy(dev, "execute") @qml.qnode(dev, expansion_strategy="device") def circuit(): qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(wires=0)) # Initial test _ = circuit() tape = spy.call_args_list[0][0][0][0] assert len(tape.operations) == 1 assert tape.operations[0].name == "CNOT" assert dev.preprocess()[0][2].transform.__name__ == "decompose" assert dev.preprocess()[0][2].kwargs.get("decomposer", None) is None # Test within the context manager with qml.transforms.set_decomposition({qml.CNOT: custom_cnot}, dev): _ = circuit() assert dev.preprocess()[0][2].transform.__name__ == "decompose" assert dev.preprocess()[0][2].kwargs.get("decomposer", None) is not None tape = spy.call_args_list[1][0][0][0] ops_in_context = tape.operations assert len(ops_in_context) == 3 assert ops_in_context[0].name == "Hadamard" assert ops_in_context[1].name == "CZ" assert ops_in_context[2].name == "Hadamard" # Check that afterwards, the device has gone back to normal _ = circuit() tape = spy.call_args_list[2][0][0][0] ops_in_context = tape.operations assert len(tape.operations) == 1 assert tape.operations[0].name == "CNOT" assert dev.preprocess()[0][2].transform.__name__ == "decompose" assert dev.preprocess()[0][2].kwargs.get("decomposer", None) is None # pylint: disable=cell-var-from-loop def test_custom_decomp_used_twice(self): """Test that creating a custom decomposition includes overwriting the correct method under the hood and produces expected results.""" res = [] for _ in range(2): custom_decomps = {"MultiRZ": qml.MultiRZ.compute_decomposition} dev = qml.device("lightning.qubit", wires=2, custom_decomps=custom_decomps) @qml.qnode(dev, diff_method="adjoint", expansion_strategy="gradient") def cost(theta): qml.Hadamard(wires=0) qml.Hadamard(wires=1) qml.MultiRZ(theta, wires=[1, 0]) return qml.expval(qml.PauliX(1)) x = np.array(0.5) res.append(cost(x)) assert res[0] == res[1] @pytest.mark.parametrize("shots", [None, 100]) def test_custom_decomp_with_mcm(self, shots): """Test that specifying a single custom decomposition works as expected.""" custom_decomps = {"Hadamard": custom_hadamard} decomp_dev = qml.device("default.qubit", shots=shots, custom_decomps=custom_decomps) @qml.qnode(decomp_dev, expansion_strategy="device") def circuit(): qml.Hadamard(wires=0) _ = qml.measure(0) qml.CNOT(wires=[0, 1]) _ = qml.measure(1) return qml.expval(qml.PauliZ(0)) _ = circuit() decomp_ops = circuit.tape.operations assert len(decomp_ops) == 4 if shots is None else 5 assert decomp_ops[0].name == "RZ" assert np.isclose(decomp_ops[0].parameters[0], np.pi) assert decomp_ops[1].name == "RY" assert np.isclose(decomp_ops[1].parameters[0], np.pi / 2) if shots: assert decomp_ops[2].name == "MidMeasureMP" assert decomp_ops[3].name == "CNOT" assert decomp_ops[4].name == "MidMeasureMP" else: assert decomp_ops[2].name == "CNOT" assert decomp_ops[3].name == "CNOT"
pennylane/tests/transforms/test_tape_expand.py/0
{ "file_path": "pennylane/tests/transforms/test_tape_expand.py", "repo_id": "pennylane", "token_count": 17178 }
100
[DEFAULT] test_path=./test parallel_class=True
qiskit-experiments/.stestr.conf/0
{ "file_path": "qiskit-experiments/.stestr.conf", "repo_id": "qiskit-experiments", "token_count": 18 }
101
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2023. # # 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. """ Documentation extension for experiment class. """ import copy import re import sys from abc import ABC from typing import Union, List, Dict from qiskit_experiments.framework.base_analysis import BaseAnalysis from qiskit_experiments.framework.base_experiment import BaseExperiment from sphinx.config import Config as SphinxConfig from .formatter import ( ExperimentSectionFormatter, AnalysisSectionFormatter, DocstringSectionFormatter, VisualizationSectionFormatter, ) from .section_parsers import load_standard_section, load_fit_parameters from .utils import ( _generate_analysis_ref, _get_superclass, ) _section_regex = re.compile(r"\s*# section:\s*(?P<section_key>\S+)") class QiskitExperimentDocstring(ABC): """Qiskit Experiment style docstring parser base class.""" # mapping of sections supported by this style to parsing method or function __sections__ = { "header": load_standard_section, } # section formatter __formatter__ = DocstringSectionFormatter def __init__( self, target_cls: object, docstring_lines: Union[str, List[str]], config: SphinxConfig, indent: str = "", **extra_sections: List[str], ): """Create new parser and parse formatted docstring.""" if isinstance(docstring_lines, str): lines = docstring_lines.splitlines() else: lines = docstring_lines self._target_cls = target_cls self._indent = indent self._config = config self._parsed_lines = self._classify(lines, **extra_sections) def _classify( self, docstring_lines: List[str], **extra_sections: List[str], ) -> Dict[str, List[str]]: """Classify formatted docstring into sections.""" sectioned_docstrings = dict() for sec_key, parsed_lines in extra_sections.items(): if sec_key not in self.__sections__: raise KeyError( f"Section key {sec_key} is not a valid Qiskit Experiments extension " f"section keys. Use one of {','.join(self.__sections__.keys())}." ) sectioned_docstrings[sec_key] = parsed_lines current_section = "header" min_indent = sys.maxsize tmp_lines = [] for line in docstring_lines: matched = _section_regex.match(line) if matched: # Process previous section if min_indent < sys.maxsize: tmp_lines = [_line[min_indent:] for _line in tmp_lines] parser = self.__sections__[current_section] sectioned_docstrings[current_section] = parser(tmp_lines) # Start new line sec_key = matched["section_key"] if sec_key not in self.__sections__: raise KeyError( f"Section key {sec_key} is not a valid Qiskit Experiments extension " f"section keys. Use one of {','.join(self.__sections__.keys())}." ) current_section = sec_key tmp_lines.clear() min_indent = sys.maxsize continue # calculate section indent if len(line) > 0 and not line.isspace(): # ignore empty line indent = len(line) - len(line.lstrip()) min_indent = min(indent, min_indent) tmp_lines.append(line) # Process final section if tmp_lines: if min_indent < sys.maxsize: tmp_lines = [_line[min_indent:] for _line in tmp_lines] parser = self.__sections__[current_section] sectioned_docstrings[current_section] = parser(tmp_lines) # add extra section self._extra_sections(sectioned_docstrings) return sectioned_docstrings def _extra_sections(self, sectioned_docstring: Dict[str, List[str]]): """Generate extra sections.""" pass def _format(self) -> Dict[str, List[str]]: """Format each section with predefined formatter.""" formatter = self.__formatter__(self._indent) formatted_sections = {section: None for section in self.__sections__} for section, lines in self._parsed_lines.items(): if not lines: continue section_formatter = getattr(formatter, f"format_{section}", None) if section_formatter: formatted_sections[section] = section_formatter(lines) else: formatted_sections[section] = lines + [""] return formatted_sections def generate_class_docs(self) -> List[List[str]]: """Output formatted experiment class documentation.""" formatted_sections = self._format() classdoc_lines = [] for section_lines in formatted_sections.values(): if section_lines: classdoc_lines.extend(section_lines) return [classdoc_lines] class ExperimentDocstring(QiskitExperimentDocstring): """Documentation parser for the experiment class introduction.""" __sections__ = { "header": load_standard_section, "warning": load_standard_section, "overview": load_standard_section, "reference": load_standard_section, "manual": load_standard_section, "analysis_ref": load_standard_section, "experiment_opts": load_standard_section, "example": load_standard_section, "note": load_standard_section, "see_also": load_standard_section, "init": load_standard_section, } __formatter__ = ExperimentSectionFormatter def _extra_sections(self, sectioned_docstring: Dict[str, List[str]]): """Generate extra sections.""" current_class = self._target_cls # add see also for super classes if "see_also" not in sectioned_docstring: class_refs = _get_superclass(current_class, BaseExperiment) if class_refs: sectioned_docstring["see_also"] = class_refs # add analysis reference, if nothing described, it copies from parent exp_docs_config = copy.copy(self._config) exp_docs_config.napoleon_custom_sections = [("experiment options", "args")] if not sectioned_docstring.get("analysis_ref", None): analysis_desc = _generate_analysis_ref( current_class=current_class, config=exp_docs_config, indent=self._indent, ) sectioned_docstring["analysis_ref"] = analysis_desc class AnalysisDocstring(QiskitExperimentDocstring): """Documentation parser for the analysis class introduction.""" __sections__ = { "header": load_standard_section, "warning": load_standard_section, "overview": load_standard_section, "fit_model": load_standard_section, "fit_parameters": load_fit_parameters, "reference": load_standard_section, "manual": load_standard_section, "analysis_opts": load_standard_section, "example": load_standard_section, "note": load_standard_section, "see_also": load_standard_section, "init": load_standard_section, } __formatter__ = AnalysisSectionFormatter def _extra_sections(self, sectioned_docstring: Dict[str, List[str]]): """Generate extra sections.""" current_class = self._target_cls # add see also for super classes if "see_also" not in sectioned_docstring: class_refs = _get_superclass(current_class, BaseAnalysis) if class_refs: sectioned_docstring["see_also"] = class_refs class VisualizationDocstring(QiskitExperimentDocstring): """Documentation parser for visualization classes' introductions.""" __sections__ = { "header": load_standard_section, "warning": load_standard_section, "overview": load_standard_section, "reference": load_standard_section, "manual": load_standard_section, "opts": load_standard_section, # For standard options "figure_opts": load_standard_section, # For figure options "example": load_standard_section, "note": load_standard_section, "see_also": load_standard_section, "init": load_standard_section, } __formatter__ = VisualizationSectionFormatter
qiskit-experiments/docs/_ext/custom_styles/styles.py/0
{ "file_path": "qiskit-experiments/docs/_ext/custom_styles/styles.py", "repo_id": "qiskit-experiments", "token_count": 3746 }
102
.. _qiskit-experiments-visualization: .. automodule:: qiskit_experiments.visualization :no-members: :no-inherited-members: :no-special-members:
qiskit-experiments/docs/apidocs/visualization.rst/0
{ "file_path": "qiskit-experiments/docs/apidocs/visualization.rst", "repo_id": "qiskit-experiments", "token_count": 58 }
103
T2* Ramsey Characterization =========================== The purpose of the :math:`T_2^*` Ramsey experiment is to determine two of the qubit's properties: *Ramsey* or *detuning frequency* and :math:`T_2^\ast`. In this experiment, we would like to get a more precise estimate of the qubit's frequency given a rough estimate. The difference between the frequency used for the control rotation pulses and the qubit transition frequency is called the *detuning frequency*. This part of the experiment is called a *Ramsey Experiment*. :math:`T_2^\ast` represents the rate of decay toward a mixed state, when the qubit is initialized to the :math:`\left|1\right\rangle` state. It is the dephasing time or the transverse relaxation time of the qubit on the Bloch sphere as a result of both energy relaxation and pure dephasing in the transverse plane. Unlike :math:`T_2`, which is measured by :class:`.T2Hahn`, :math:`T_2^*` is sensitive to inhomogenous broadening. Since the detuning frequency is relatively small, we add a phase gate to the circuit to enable better measurement. The actual frequency measured is the sum of the detuning frequency and the user induced *oscillation frequency* (``osc_freq`` parameter). .. jupyter-execute:: import numpy as np import qiskit from qiskit_experiments.library import T2Ramsey The circuits used for the experiment comprise the following steps: #. Hadamard gate #. Delay #. RZ gate that rotates the qubit in the x-y plane #. Hadamard gate #. Measurement The user provides as input a series of delays (in seconds) and the oscillation frequency (in Hz). During the delay, we expect the qubit to precess about the z-axis. If the p gate and the precession offset each other perfectly, then the qubit will arrive at the :math:`\left|0\right\rangle` state (after the second Hadamard gate). By varying the extension of the delays, we get a series of oscillations of the qubit state between the :math:`\left|0\right\rangle` and :math:`\left|1\right\rangle` states. We can draw the graph of the resulting function, and can analytically extract the desired values. .. jupyter-execute:: qubit = 0 # set the desired delays delays = list(np.arange(1e-6, 50e-6, 2e-6)) .. jupyter-execute:: # Create a T2Ramsey experiment. Print the first circuit as an example exp1 = T2Ramsey((qubit,), delays, osc_freq=1e5) print(exp1.circuits()[0]) We run the experiment on a simulated backend using Qiskit Aer with a pure T1/T2 relaxation noise model. .. note:: This tutorial requires the :external+qiskit_aer:doc:`qiskit-aer <index>` and :external+qiskit_ibm_runtime:doc:`qiskit-ibm-runtime <index>` packages to run simulations. You can install them with ``python -m pip install qiskit-aer qiskit-ibm-runtime``. .. jupyter-execute:: # A T1 simulator from qiskit_ibm_runtime.fake_provider import FakePerth from qiskit_aer import AerSimulator from qiskit_aer.noise import NoiseModel # Create a pure relaxation noise model for AerSimulator noise_model = NoiseModel.from_backend( FakePerth(), thermal_relaxation=True, gate_error=False, readout_error=False ) # Create a fake backend simulator backend = AerSimulator.from_backend(FakePerth(), noise_model=noise_model) The resulting graph will have the form: :math:`f(t) = a^{-t/T_2*} \cdot \cos(2 \pi f t + \phi) + b` where *t* is the delay, :math:`T_2^\ast` is the decay factor, and *f* is the detuning frequency. .. jupyter-execute:: # Set scheduling method so circuit is scheduled for delay noise simulation exp1.set_transpile_options(scheduling_method='asap') # Run experiment expdata1 = exp1.run(backend=backend, shots=2000, seed_simulator=101) expdata1.block_for_results() # Wait for job/analysis to finish. # Display the figure display(expdata1.figure(0)) .. jupyter-execute:: # Print results for result in expdata1.analysis_results(): print(result) Providing initial user estimates ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The user can provide initial estimates for the parameters to help the analysis process. Because the curve is expected to decay toward :math:`0.5`, the natural choice for parameters :math:`A` and :math:`B` is :math:`0.5`. Varying the value of :math:`\phi` will shift the graph along the x-axis. Since this is not of interest to us, we can safely initialize :math:`\phi` to 0. In this experiment, ``t2ramsey`` and ``f`` are the parameters of interest. Good estimates for them are values computed in previous experiments on this qubit or a similar values computed for other qubits. .. jupyter-execute:: user_p0={ "A": 0.5, "T2star": 20e-6, "f": 110000, "phi": 0, "B": 0.5 } exp_with_p0 = T2Ramsey((qubit,), delays, osc_freq=1e5) exp_with_p0.analysis.set_options(p0=user_p0) exp_with_p0.set_transpile_options(scheduling_method='asap') expdata_with_p0 = exp_with_p0.run(backend=backend, shots=2000, seed_simulator=101) expdata_with_p0.block_for_results() # Display fit figure display(expdata_with_p0.figure(0)) .. jupyter-execute:: # Print results for result in expdata_with_p0.analysis_results(): print(result) See also -------- * API documentation: :mod:`~qiskit_experiments.library.characterization.T2Ramsey`
qiskit-experiments/docs/manuals/characterization/t2ramsey.rst/0
{ "file_path": "qiskit-experiments/docs/manuals/characterization/t2ramsey.rst", "repo_id": "qiskit-experiments", "token_count": 1845 }
104
# This code is part of Qiskit. # # (C) Copyright IBM 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. """A helper module to save calibration data to local storage. .. warning:: This module is expected to be internal and is not intended as a stable user-facing API. .. note:: Because a locally saved :class:`.Calibrations` instance may not conform to the data model of the latest Qiskit Experiments implementation, the calibration loader must be aware of the data model version. CalibrationModel classes representing the data model must have the version suffix, e.g., `CalibrationModelV1` and the `schema_version` field. This helps the loader to raise user-friendly error rather than being crashed by incompatible data, and possibly to dispatch the loader function based on the version number. When a developer refactors the :class:`.Calibrations` class to a new data model, the developer must also define a corresponding CalibrationModel class with new version number. Existing CalibrationModel classes should be preserved for backward compatibility. .. note:: We don't guarantee the portability of stored data across different Qiskit Experiments versions. We allow the calibration loader to raise an error for non-supported data models. """ from dataclasses import dataclass, field, asdict from datetime import datetime from typing import List, Dict, Any from qiskit import QuantumCircuit from qiskit.circuit import Instruction from qiskit.pulse import ScheduleBlock from .calibrations import Calibrations from .control_channel_map import ControlChannelMap from .parameter_value import ParameterValue @dataclass(frozen=True) class ParameterModelV1: """A data schema of a single calibrated parameter. .. note:: This is intentionally agnostic to the data structure of Qiskit Experiments Calibrations for portability. """ param_name: str """Name of the parameter.""" qubits: List[int] """List of associated qubits.""" schedule: str = "" """Associated schedule name.""" value: float = 0.0 """Parameter value.""" datetime: datetime = None """A date time at which this value is obtained.""" valid: bool = True """If this parameter is valid.""" exp_id: str = "" """Associated experiment ID which is used to obtain this value.""" group: str = "" """Name of calibration group in which this calibration parameter belongs to.""" @classmethod def apply_schema(cls, data: Dict[str, Any]): """Consume dictionary and returns canonical data model.""" return ParameterModelV1(**data) @dataclass class CalibrationModelV1: """A data schema to represent instances of Calibrations. .. note:: This is intentionally agnostic to the data structure of Qiskit Experiments Calibrations for portability. """ backend_name: str """Name of the backend.""" backend_version: str """Version of the backend.""" device_coupling_graph: List[List[int]] """Qubit coupling graph of the device.""" control_channel_map: ControlChannelMap """Mapping of ControlChannel to qubit index.""" schedules: List[ScheduleBlock] = field(default_factory=list) """Template schedules. It must contain the metadata for qubits and num_qubits.""" parameters: List[ParameterModelV1] = field(default_factory=list) """List of calibrated pulse parameters.""" schedule_free_parameters: QuantumCircuit = field(default_factory=lambda: QuantumCircuit(1)) """Placeholder circuit for parameters not associated with a schedule The circuit contains placeholder instructions which have the Parameter objects attached and operate on the qubits that the parameter is associated with in the calibrations. """ schema_version: str = "1.0" """Version of this data model. This must be static.""" @classmethod def apply_schema(cls, data: Dict[str, Any]): """Consume dictionary and returns canonical data model.""" in_data = {} for key, value in data.items(): if key == "parameters": value = list(map(ParameterModelV1.apply_schema, value)) in_data[key] = value return CalibrationModelV1(**in_data) def calibrations_to_dict( cals: Calibrations, most_recent_only: bool = True, ) -> Dict[str, Any]: """A helper function to convert calibration data into dictionary. Args: cals: A calibration instance to save. most_recent_only: Set True to save calibration parameters with most recent time stamps. Returns: Canonical calibration data in dictionary format. """ schedules = getattr(cals, "_schedules") num_qubits = getattr(cals, "_schedules_qubits") parameters = getattr(cals, "_params") if most_recent_only: # Get values with most recent time stamps. parameters = {k: [max(parameters[k], key=lambda x: x.date_time)] for k in parameters} data_entries = [] for param_key, param_values in parameters.items(): for param_value in param_values: entry = ParameterModelV1( param_name=param_key.parameter, qubits=param_key.qubits, schedule=param_key.schedule, value=param_value.value, datetime=param_value.date_time, valid=param_value.valid, exp_id=param_value.exp_id, group=param_value.group, ) data_entries.append(entry) sched_entries = [] for sched_key, sched_obj in schedules.items(): if "qubits" not in sched_obj.metadata or "num_qubits" not in sched_obj.metadata: qubit_metadata = { "qubits": sched_key.qubits, "num_qubits": num_qubits[sched_key], } sched_obj.metadata.update(qubit_metadata) sched_entries.append(sched_obj) max_qubit = max( (max(k.qubits or (0,)) for k in cals._parameter_map if k.schedule is None), default=0, ) schedule_free_parameters = QuantumCircuit(max_qubit + 1) for sched_key, param in cals._parameter_map.items(): if sched_key.schedule is None: schedule_free_parameters.append( Instruction("parameter_container", len(sched_key.qubits), 0, [param]), sched_key.qubits, ) model = CalibrationModelV1( backend_name=cals.backend_name, backend_version=cals.backend_version, device_coupling_graph=getattr(cals, "_coupling_map"), control_channel_map=ControlChannelMap(getattr(cals, "_control_channel_map")), schedules=sched_entries, parameters=data_entries, schedule_free_parameters=schedule_free_parameters, ) return asdict(model) def calibrations_from_dict( cal_data: Dict[str, Any], ) -> Calibrations: """A helper function to build calibration instance from canonical dictionary. Args: cal_data: Calibration data dictionary which is formatted according to the predefined data schema provided by Qiskit Experiments. This formatting is implicitly performed when the calibration data is dumped into dictionary with the :func:`calibrations_to_dict` function. Returns: Calibration instance. Raises: ValueError: When input data model version is not supported. KeyError: When input data model doesn't conform to data schema. """ # Apply schema for data field validation try: version = cal_data["schema_version"] if version == "1.0": model = CalibrationModelV1.apply_schema(cal_data) else: raise ValueError( f"Loading calibration data with schema version {version} is no longer supported. " "Use the same version of Qiskit Experiments at the time of saving." ) except (KeyError, TypeError) as ex: raise KeyError( "Loaded data doesn't match with the defined data schema. " "Check if this object is dumped from the Calibrations instance." ) from ex # This can dispatch loading mechanism depending on schema version cals = Calibrations( coupling_map=model.device_coupling_graph, control_channel_map=model.control_channel_map.chan_map, backend_name=model.backend_name, backend_version=model.backend_version, ) # Add schedules for sched in model.schedules: qubits = sched.metadata.pop("qubits", tuple()) num_qubits = sched.metadata.pop("num_qubits", None) cals.add_schedule( schedule=sched, qubits=qubits if qubits and len(qubits) != 0 else None, num_qubits=num_qubits, ) # Add parameters for param in model.parameters: param_value = ParameterValue( value=param.value, date_time=param.datetime, valid=param.valid, exp_id=param.exp_id, group=param.group, ) cals.add_parameter_value( value=param_value, param=param.param_name, qubits=tuple(param.qubits), schedule=param.schedule, update_inst_map=False, ) for instruction in model.schedule_free_parameters.data: # For some reason, pylint thinks the items in data are tuples instead # of CircuitInstruction. Remove the following line if it ever stops # thinking that: # pylint: disable=no-member for param in instruction.operation.params: cals._register_parameter(param, instruction.qubits) cals.update_inst_map() return cals
qiskit-experiments/qiskit_experiments/calibration_management/save_utils.py/0
{ "file_path": "qiskit-experiments/qiskit_experiments/calibration_management/save_utils.py", "repo_id": "qiskit-experiments", "token_count": 3799 }
105
# This code is part of Qiskit. # # (C) Copyright IBM 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. """Analyze oscillating data such as a Rabi amplitude experiment.""" from typing import List, Union, Optional import lmfit import numpy as np import qiskit_experiments.curve_analysis as curve class OscillationAnalysis(curve.CurveAnalysis): r"""Oscillation analysis class based on a fit of the data to a cosine function. # section: fit_model Analyse oscillating data by fitting it to a cosine function .. math:: y = {\rm amp} \cos\left(2 \pi\cdot {\rm freq}\cdot x + {\rm phase}\right) + {\rm base} # section: fit_parameters defpar \rm amp: desc: Amplitude of the oscillation. init_guess: Calculated by :func:`~qiskit_experiments.curve_analysis.guess.max_height`. bounds: [-2, 2] scaled to the maximum signal value. defpar \rm base: desc: Base line. init_guess: Calculated by :func:`~qiskit_experiments.curve_analysis.\ guess.constant_sinusoidal_offset`. bounds: [-1, 1] scaled to the maximum signal value. defpar \rm freq: desc: Frequency of the oscillation. This is the fit parameter of interest. init_guess: Calculated by :func:`~qiskit_experiments.curve_analysis.\ guess.frequency`. bounds: [0, inf]. defpar \rm phase: desc: Phase of the oscillation. init_guess: Zero. bounds: [-pi, pi]. """ def __init__( self, name: Optional[str] = None, ): super().__init__( models=[ lmfit.models.ExpressionModel( expr="amp * cos(2 * pi * freq * x + phase) + base", name="cos", ) ], name=name, ) def _generate_fit_guesses( self, user_opt: curve.FitOptions, curve_data: curve.ScatterTable, ) -> Union[curve.FitOptions, List[curve.FitOptions]]: """Create algorithmic initial fit guess from analysis options and curve data. Args: user_opt: Fit options filled with user provided guess and bounds. curve_data: Formatted data collection to fit. Returns: List of fit options that are passed to the fitter function. """ max_abs_y, _ = curve.guess.max_height(curve_data.y, absolute=True) user_opt.bounds.set_if_empty( amp=(-2 * max_abs_y, 2 * max_abs_y), freq=(0, np.inf), phase=(-np.pi, np.pi), base=(-max_abs_y, max_abs_y), ) user_opt.p0.set_if_empty( freq=curve.guess.frequency(curve_data.x, curve_data.y), base=curve.guess.constant_sinusoidal_offset(curve_data.y), ) user_opt.p0.set_if_empty( amp=curve.guess.max_height(curve_data.y - user_opt.p0["base"], absolute=True)[0], ) options = [] for phase_guess in np.linspace(0, np.pi, 5): new_opt = user_opt.copy() new_opt.p0.set_if_empty(phase=phase_guess) options.append(new_opt) return options def _evaluate_quality(self, fit_data: curve.CurveFitResult) -> Union[str, None]: """Algorithmic criteria for whether the fit is good or bad. A good fit has: - a reduced chi-squared lower than three and greater than zero, - more than a quarter of a full period, - less than 10 full periods, and - an error on the fit frequency lower than the fit frequency. """ fit_freq = fit_data.ufloat_params["freq"] criteria = [ 0 < fit_data.reduced_chisq < 3, 1.0 / 4.0 < fit_freq.nominal_value < 10.0, curve.utils.is_error_not_significant(fit_freq), ] if all(criteria): return "good" return "bad" class DampedOscillationAnalysis(curve.CurveAnalysis): r"""A class to analyze general exponential decay curve with sinusoidal oscillation. # section: fit_model This class is based on the fit model of sinusoidal signal with exponential decay. This model is often used for the oscillation signal in the dissipative system. .. math:: F(x) = {\rm amp} \cdot e^{-x/\tau} \cos(2\pi \cdot {\rm freq} \cdot t + \phi) + {\rm base} # section: fit_parameters defpar \rm amp: desc: Amplitude. Height of the decay curve. init_guess: 0.5 bounds: [0, 1.5], defpar \rm base: desc: Offset. Base line of the decay curve. init_guess: Determined by :func:`~qiskit_experiments.curve_analysis.\ guess.constant_sinusoidal_offset` bounds: [0, 1.5] defpar \tau: desc: Represents the rate of decay. init_guess: Determined by :func:`~qiskit_experiments.curve_analysis.\ guess.oscillation_exp_decay` bounds: [0, None] defpar \rm freq: desc: Oscillation frequency. init_guess: Determined by :func:`~qiskit_experiments.curve_analysis.guess.frequency` bounds: [0, 10 freq] defpar \phi: desc: Phase. Relative shift of the sinusoidal function from the origin. init_guess: Set multiple guesses within [-pi, pi] bounds: [-pi, pi] """ def __init__( self, name: Optional[str] = None, ): super().__init__( models=[ lmfit.models.ExpressionModel( expr="amp * exp(-x / tau) * cos(2 * pi * freq * x + phi) + base", name="cos_decay", ) ], name=name, ) def _generate_fit_guesses( self, user_opt: curve.FitOptions, curve_data: curve.ScatterTable, ) -> Union[curve.FitOptions, List[curve.FitOptions]]: """Create algorithmic initial fit guess from analysis options and curve data. Args: user_opt: Fit options filled with user provided guess and bounds. curve_data: Formatted data collection to fit. Returns: List of fit options that are passed to the fitter function. """ user_opt.p0.set_if_empty( amp=0.5, base=curve.guess.constant_sinusoidal_offset(curve_data.y), ) # frequency resolution of this scan df = 1 / ((curve_data.x[1] - curve_data.x[0]) * len(curve_data.x)) if user_opt.p0["freq"] is not None: # If freq guess is provided freq_guess = user_opt.p0["freq"] freqs = [freq_guess] else: freq_guess = curve.guess.frequency(curve_data.x, curve_data.y - user_opt.p0["base"]) # The FFT might be up to 1/2 bin off if freq_guess > df: freqs = [freq_guess - df, freq_guess, freq_guess + df] else: freqs = [0.0, freq_guess] # Set guess for decay parameter based on estimated frequency if freq_guess > df: alpha = curve.guess.oscillation_exp_decay( curve_data.x, curve_data.y - user_opt.p0["base"], freq_guess=freq_guess ) else: # Very low frequency. Assume standard exponential decay alpha = curve.guess.exp_decay(curve_data.x, curve_data.y) if alpha != 0.0: user_opt.p0.set_if_empty(tau=-1 / alpha) else: # Likely there is no slope. Cannot fit constant line with this model. # Set some large enough number against to the scan range. user_opt.p0.set_if_empty(tau=100 * np.max(curve_data.x)) user_opt.bounds.set_if_empty( amp=[0, 1.5], base=[0, 1.5], tau=(0, np.inf), freq=(0, 10 * freq_guess), phi=(-np.pi, np.pi), ) # more robust estimation options = [] for freq in freqs: for phi in np.linspace(-np.pi, np.pi, 5)[:-1]: new_opt = user_opt.copy() new_opt.p0.set_if_empty(freq=freq, phi=phi) options.append(new_opt) return options def _evaluate_quality(self, fit_data: curve.CurveFitResult) -> Union[str, None]: """Algorithmic criteria for whether the fit is good or bad. A good fit has: - a reduced chi-squared lower than three and greater than zero - relative error of tau is less than its value - relative error of freq is less than its value """ tau = fit_data.ufloat_params["tau"] freq = fit_data.ufloat_params["freq"] criteria = [ 0 < fit_data.reduced_chisq < 3, curve.utils.is_error_not_significant(tau), curve.utils.is_error_not_significant(freq), ] if all(criteria): return "good" return "bad"
qiskit-experiments/qiskit_experiments/curve_analysis/standard_analysis/oscillation.py/0
{ "file_path": "qiskit-experiments/qiskit_experiments/curve_analysis/standard_analysis/oscillation.py", "repo_id": "qiskit-experiments", "token_count": 4521 }
106
# This code is part of Qiskit. # # (C) Copyright IBM 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. """ ========================================================== Experiment Framework (:mod:`qiskit_experiments.framework`) ========================================================== .. currentmodule:: qiskit_experiments.framework Overview ======== The experiment framework broadly defines an experiment as the execution of one or more circuits on a device, and analysis of the resulting measurement data to return one or more derived results. The interface for running an experiment is through the ``Experiment`` classes subclassed from :class:`.BaseExperiment`, such as those contained in the :mod:`~qiskit_experiments.library`. The following pseudo-code illustrates the typical workflow in Qiskit Experiments for - Initializing a new experiment - Running the experiment on a backend - Saving result to an online database (for compatible providers) - Viewing analysis results .. code-block:: python # Import an experiment from qiskit_experiments.library import SomeExperiment # Initialize with desired qubits and options exp = SomeExperiment(physical_qubits, **options) # Run on a backend exp_data = exp.run(backend) # Wait for execution and analysis to finish exp_data.block_for_results() # Optionally save results to database exp_data.save() # View analysis results for result in exp_data.analysis_results(): print(result) The experiment class contains information for generating circuits and analysis of results. These can typically be configured with a variety of options. Once all options are set, you can call the :meth:`.BaseExperiment.run` method to run the experiment on a Qiskit compatible ``backend``. The steps of running an experiment involves generation experimental circuits according to the options you set and submission of a job to the specified ``backend``. Once the job has finished executing an analysis job performs data analysis of the experiment execution results. The result of running an experiment is an :class:`ExperimentData` container which contains the analysis results, any figures generated during analysis, and the raw measurement data. These can each be accessed using the :meth:`.ExperimentData.analysis_results`, :meth:`.ExperimentData.figure` and :meth:`.ExperimentData.data` methods respectively. Additional metadata for the experiment itself can be added via :meth:`.ExperimentData.metadata`. Classes ======= Experiment Data Classes *********************** .. autosummary:: :toctree: ../stubs/ ExperimentData ExperimentStatus AnalysisStatus AnalysisResult AnalysisResultData AnalysisResultTable ExperimentConfig AnalysisConfig ExperimentEncoder ExperimentDecoder ArtifactData FigureData .. _composite-experiment: Composite Experiment Classes **************************** .. autosummary:: :toctree: ../stubs/ CompositeExperiment ParallelExperiment BatchExperiment CompositeAnalysis Base Classes ************ .. autosummary:: :toctree: ../stubs/ BaseExperiment BaseAnalysis Experiment Configuration Helper Classes *************************************** .. autosummary:: :toctree: ../stubs/ BackendData BackendTiming RestlessMixin """ from qiskit.providers.options import Options from qiskit_experiments.framework.backend_data import BackendData from qiskit_experiments.framework.analysis_result import AnalysisResult from qiskit_experiments.framework.status import ( ExperimentStatus, AnalysisStatus, AnalysisCallback, ) from qiskit_experiments.framework.containers import ( ArtifactData, FigureData, FigureType, ) from .base_analysis import BaseAnalysis from .base_experiment import BaseExperiment from .backend_timing import BackendTiming from .configs import ExperimentConfig, AnalysisConfig from .analysis_result_data import AnalysisResultData from .analysis_result_table import AnalysisResultTable from .experiment_data import ExperimentData from .composite import ( ParallelExperiment, BatchExperiment, CompositeExperiment, CompositeAnalysis, ) from .json import ExperimentEncoder, ExperimentDecoder from .restless_mixin import RestlessMixin
qiskit-experiments/qiskit_experiments/framework/__init__.py/0
{ "file_path": "qiskit-experiments/qiskit_experiments/framework/__init__.py", "repo_id": "qiskit-experiments", "token_count": 1267 }
107
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # 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. """Container of experiment data components.""" from __future__ import annotations import copy import io from typing import Dict, Optional, Union, Any from matplotlib.figure import Figure as MatplotlibFigure class FigureData: """A plot data container. .. note:: Raw figure data can be accessed through the :attr:`.FigureData.figure` attribute. """ def __init__( self, figure, name: str | None = None, metadata: dict[str, Any] | None = None, ): """Creates a new figure data object. Args: figure: The raw figure itself. Can be SVG or matplotlib.Figure. name: The name of the figure. metadata: Any metadata to be stored with the figure. """ self.figure = figure self._name = name self.metadata = metadata or {} def __eq__(self, value): """Test equality between two instances of FigureData.""" return vars(self) == vars(value) # name is read only @property def name(self) -> str: """The name of the figure""" return self._name @property def metadata(self) -> dict: """The metadata dictionary stored with the figure""" return self._metadata @metadata.setter def metadata(self, new_metadata: dict): """Set the metadata to new value; must be a dictionary""" if not isinstance(new_metadata, dict): raise ValueError("figure metadata must be a dictionary") self._metadata = new_metadata def copy(self, new_name: Optional[str] = None): """Creates a copy of the figure data""" name = new_name or self.name return FigureData(figure=self.figure, name=name, metadata=copy.deepcopy(self.metadata)) def __json_encode__(self) -> Dict[str, Any]: """Return the json representation of the figure data""" return {"figure": self.figure, "name": self.name, "metadata": self.metadata} @classmethod def __json_decode__(cls, args: Dict[str, Any]) -> "FigureData": """Initialize a figure data from the json representation""" return cls(**args) def _repr_png_(self): if isinstance(self.figure, MatplotlibFigure): b = io.BytesIO() self.figure.savefig(b, format="png", bbox_inches="tight") png = b.getvalue() return png else: return None def _repr_svg_(self): if isinstance(self.figure, str): return self.figure if isinstance(self.figure, bytes): return self.figure.decode("utf-8") return None FigureType = Union[str, bytes, MatplotlibFigure, FigureData]
qiskit-experiments/qiskit_experiments/framework/containers/figure_data.py/0
{ "file_path": "qiskit-experiments/qiskit_experiments/framework/containers/figure_data.py", "repo_id": "qiskit-experiments", "token_count": 1203 }
108
# This code is part of Qiskit. # # (C) Copyright IBM 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. """Rough drag calibration experiment.""" from typing import Dict, Iterable, Optional, Sequence from qiskit.circuit import Parameter, QuantumCircuit from qiskit.providers.backend import Backend from qiskit_experiments.framework import ExperimentData from qiskit_experiments.calibration_management import ( BaseCalibrationExperiment, Calibrations, ) from qiskit_experiments.calibration_management.update_library import BaseUpdater from qiskit_experiments.library.characterization.drag import RoughDrag class RoughDragCal(BaseCalibrationExperiment, RoughDrag): """A calibration version of the :class:`.RoughDrag` experiment. # section: manual :ref:`DRAG Calibration` """ def __init__( self, physical_qubits: Sequence[int], calibrations: Calibrations, backend: Optional[Backend] = None, schedule_name: str = "x", betas: Iterable[float] = None, cal_parameter_name: Optional[str] = "β", auto_update: bool = True, group: str = "default", ): r"""see class :class:`.RoughDrag` for details. Args: physical_qubits: Sequence containing the qubit for which to run the rough DRAG calibration. calibrations: The calibrations instance with the schedules. backend: Optional, the backend to run the experiment on. schedule_name: The name of the schedule to calibrate. Defaults to "x". betas: A list of DRAG parameter values to scan. If None is given 51 betas ranging from -5 to 5 will be scanned. cal_parameter_name: The name of the parameter in the schedule to update. Defaults to "β". auto_update: Whether or not to automatically update the calibrations. By default this variable is set to True. group: The group of calibration parameters to use. The default value is "default". """ qubit = physical_qubits[0] schedule = calibrations.get_schedule( schedule_name, qubit, assign_params={cal_parameter_name: Parameter("β")}, group=group ) self._validate_channels(schedule, [qubit]) self._validate_parameters(schedule, 1) super().__init__( calibrations, physical_qubits, schedule=schedule, betas=betas, backend=backend, schedule_name=schedule_name, cal_parameter_name=cal_parameter_name, auto_update=auto_update, ) def _metadata(self) -> Dict[str, any]: """Add metadata to the experiment data making it more self contained. The following keys are added to each experiment's metadata: cal_param_value: The value of the previous calibrated beta. cal_param_name: The name of the parameter in the calibrations. cal_schedule: The name of the schedule in the calibrations. cal_group: The calibration group to which the parameter belongs. """ metadata = super()._metadata() metadata["cal_param_value"] = self._cals.get_parameter_value( self._param_name, self.physical_qubits, self._sched_name, self.experiment_options.group ) return metadata def _attach_calibrations(self, circuit: QuantumCircuit): """RoughDrag already has the schedules attached in the program circuits.""" pass def update_calibrations(self, experiment_data: ExperimentData): """Update the beta using the value directly reported from the fit. See :class:`.DragCalAnalysis` for details on the fit. """ new_beta = BaseUpdater.get_value( experiment_data, "beta", self.experiment_options.result_index ) BaseUpdater.add_parameter_value( self._cals, experiment_data, new_beta, self._param_name, self._sched_name, self.experiment_options.group, )
qiskit-experiments/qiskit_experiments/library/calibration/rough_drag_cal.py/0
{ "file_path": "qiskit-experiments/qiskit_experiments/library/calibration/rough_drag_cal.py", "repo_id": "qiskit-experiments", "token_count": 1762 }
109
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2022. # # 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. """ Tphi Analysis class. """ from typing import List, Tuple from qiskit_experiments.framework import ExperimentData, AnalysisResultData from qiskit_experiments.framework.composite.composite_analysis import CompositeAnalysis from qiskit_experiments.library.characterization.analysis import ( T1Analysis, T2HahnAnalysis, T2RamseyAnalysis, ) from qiskit_experiments.exceptions import QiskitError class TphiAnalysis(CompositeAnalysis): r"""A class to analyze :math:`T_\phi` experiments. # section: see_also * :py:class:`qiskit_experiments.library.characterization.analysis.T1Analysis` * :py:class:`qiskit_experiments.library.characterization.analysis.T2HahnAnalysis` * :py:class:`qiskit_experiments.library.characterization.analysis.T2RamseyAnalysis` """ def __init__(self, analyses=None): if analyses is None: analyses = [T1Analysis(), T2HahnAnalysis()] # Validate analyses kwarg if ( len(analyses) != 2 or not isinstance(analyses[0], T1Analysis) or not isinstance(analyses[1], (T2RamseyAnalysis, T2HahnAnalysis)) ): raise QiskitError( "Invalid component analyses for Tphi, analyses must be a pair of " "T1Analysis and T2HahnAnalysis or T2RamseyAnalysis instances." ) super().__init__(analyses, flatten_results=True) def _run_analysis( self, experiment_data: ExperimentData ) -> Tuple[List[AnalysisResultData], List["matplotlib.figure.Figure"]]: r"""Run analysis for :math:`T_\phi` experiment. It invokes CompositeAnalysis._run_analysis that will invoke _run_analysis for the two sub-experiments. Based on the results, it computes the result for :math:`T_phi`. """ # Run composite analysis and extract T1 and T2 results analysis_results, figures = super()._run_analysis(experiment_data) t1_result = next(filter(lambda res: res.name == "T1", analysis_results)) t2_result = next(filter(lambda res: res.name in {"T2star", "T2"}, analysis_results)) # Calculate Tphi from T1 and T2 tphi = 1 / (1 / t2_result.value - 1 / (2 * t1_result.value)) quality_tphi = ( "good" if (t1_result.quality == "good" and t2_result.quality == "good") else "bad" ) tphi_result = AnalysisResultData( name="T_phi", value=tphi, chisq=None, quality=quality_tphi, extra={"unit": "s"}, ) # Return combined results analysis_results = [tphi_result] + analysis_results return analysis_results, figures
qiskit-experiments/qiskit_experiments/library/characterization/analysis/tphi_analysis.py/0
{ "file_path": "qiskit-experiments/qiskit_experiments/library/characterization/analysis/tphi_analysis.py", "repo_id": "qiskit-experiments", "token_count": 1244 }
110
# This code is part of Qiskit. # # (C) Copyright IBM 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. """Spectroscopy experiment class for resonators.""" from typing import Iterable, Optional, Sequence, Tuple import numpy as np from qiskit import QuantumCircuit from qiskit import pulse from qiskit.circuit import Parameter from qiskit.exceptions import QiskitError from qiskit.providers import Backend from qiskit_experiments.framework import BackendData, BackendTiming, Options from qiskit_experiments.library.characterization.spectroscopy import Spectroscopy from qiskit_experiments.database_service import Resonator from .analysis.resonator_spectroscopy_analysis import ResonatorSpectroscopyAnalysis class ResonatorSpectroscopy(Spectroscopy): """An experiment to perform frequency spectroscopy of the readout resonator. # section: overview This experiment does spectroscopy on the readout resonator. It applies the following circuit .. parsed-literal:: ┌─┐ q: ┤M├ └╥┘ c: 1/═╩═ 0 where a spectroscopy pulse is attached to the measurement instruction. An initial circuit can be added before the measurement by setting the ``initial_circuit`` experiment option. If set, the experiment applies the following circuit: .. parsed-literal:: ┌─────────────────┐┌─┐ q: ┤ initial_circuit ├┤M├ └─────────────────┘└╥┘ c: 1/════════════════════╩═ 0 Side note 1: when doing readout resonator spectroscopy, each measured IQ point has a frequency dependent phase. Close to the resonance, the IQ points start rotating around in the IQ plan. This effect must be accounted for in the data processing to produce a meaningful signal. The default data processing workflow will therefore reduce the two- dimensional IQ data to one-dimensional data using the magnitude of each IQ point. Side node 2: when running readout resonator spectroscopy in a parallel experiment the user will need to specify the memory slot to use. This can easily be done with the code shown below. .. code:: specs = [] for slot, qubit in enumerate(qubits): specs.append(ResonatorSpectroscopy( physical_qubits=[qubit], backend=backend2, memory_slot=slot, )) exp = ParallelExperiment(specs, backend=backend2) # section: warning Some backends may not have the required functionality to properly support resonator spectroscopy experiments. The experiment may not work or the resulting resonance may not properly reflect the properties of the readout resonator. # section: example The resonator spectroscopy experiment can be run by doing: .. code:: python qubit = 1 spec = ResonatorSpectroscopy([qubit], backend) exp_data = spec.run().block_for_results() exp_data.figure(0) This will measure the resonator attached to qubit 1 and report the resonance frequency as well as the kappa, i.e. the line width, of the resonator. # section: analysis_ref :class:`ResonatorSpectroscopyAnalysis` """ @classmethod def _default_experiment_options(cls) -> Options: """Default option values used for the spectroscopy pulse. All units of the resonator spectroscopy experiment are given in seconds. Experiment Options: amp (float): The amplitude of the spectroscopy pulse. Defaults to 1 and must be between 0 and 1. duration (float): The duration in seconds of the spectroscopy pulse. sigma (float): The standard deviation of the spectroscopy pulse in seconds. width (float): The width of the flat-top part of the GaussianSquare pulse in seconds. initial_circuit (QuantumCircuit): A single-qubit initial circuit to run before the measurement/spectroscopy pulse. The circuit must contain only a single qubit and zero classical bits. If None, no circuit is appended before the measurement. Defaults to None. memory_slot (int): The memory slot that the acquire instruction uses in the pulse schedule. The default value is ``0``. This argument allows the experiment to function in a :class:`.ParallelExperiment`. """ options = super()._default_experiment_options() options.amp = 1 options.duration = 480e-9 options.sigma = 60e-9 options.width = 360e-9 options.initial_circuit = None options.memory_slot = 0 return options def set_experiment_options(self, **fields): # Check that the initial circuit is for a single qubit only. if "initial_circuit" in fields: initial_circuit = fields["initial_circuit"] if ( initial_circuit is not None and initial_circuit.num_qubits != 1 or initial_circuit.num_clbits != 0 ): raise QiskitError( "Initial circuit must be for exactly one qubit and zero classical bits. Got " f"{initial_circuit.num_qubits} qubits and {initial_circuit.num_clbits} " "classical bits instead." ) return super().set_experiment_options(**fields) def __init__( self, physical_qubits: Sequence[int], backend: Optional[Backend] = None, frequencies: Optional[Iterable[float]] = None, absolute: bool = True, **experiment_options, ): """Initialize a resonator spectroscopy experiment. A spectroscopy experiment run by setting the frequency of the readout drive. The parameters of the GaussianSquare spectroscopy pulse can be specified at run-time through the experiment options. Args: physical_qubits: List containing the resonator on which to run readout spectroscopy. backend: Optional, the backend to run the experiment on. frequencies: The frequencies to scan in the experiment, in Hz. The default values range from -20 MHz to 20 MHz in 51 steps. If the ``absolute`` variable is set to True then a center frequency obtained from the backend's defaults is added to each value of this range. absolute: Boolean to specify if the frequencies are absolute or relative to the resonator frequency in the backend. The default value is True. experiment_options: Key word arguments used to set the experiment options. Raises: QiskitError: If no frequencies are given and absolute frequencies are desired and no backend is given or the backend does not have default measurement frequencies. """ analysis = ResonatorSpectroscopyAnalysis() if frequencies is None: frequencies = np.linspace(-20.0e6, 20.0e6, 51) if absolute: frequencies += self._get_backend_meas_freq( BackendData(backend) if backend is not None else None, physical_qubits[0], ) super().__init__( physical_qubits, frequencies, backend, absolute, analysis, **experiment_options ) @staticmethod def _get_backend_meas_freq(backend_data: Optional[BackendData], qubit: int) -> float: """Get backend meas_freq with error checking""" if backend_data is None: raise QiskitError( "Cannot automatically compute absolute frequencies without a backend." ) if len(backend_data.meas_freqs) < qubit + 1: raise QiskitError( "Cannot retrieve default measurement frequencies from backend. " "Please set frequencies explicitly or set `absolute` to `False`." ) return backend_data.meas_freqs[qubit] @property def _backend_center_frequency(self) -> float: """Returns the center frequency of the experiment. Returns: The center frequency of the experiment. Raises: QiskitError: If the experiment does not have a backend set. """ return self._get_backend_meas_freq(self._backend_data, self.physical_qubits[0]) def _template_circuit(self) -> QuantumCircuit: """Return the template quantum circuit.""" circuit = QuantumCircuit(1, 1) if self.experiment_options.initial_circuit is not None: circuit.append(self.experiment_options.initial_circuit, [0]) circuit.measure(0, 0) return circuit def _schedule(self) -> Tuple[pulse.ScheduleBlock, Parameter]: """Create the spectroscopy schedule.""" timing = BackendTiming(self.backend) if timing.dt is None: raise QiskitError(f"{self.__class__.__name__} requires a backend with a dt value.") duration = timing.round_pulse(time=self.experiment_options.duration) sigma = self.experiment_options.sigma / timing.dt width = self.experiment_options.width / timing.dt qubit = self.physical_qubits[0] freq_param = Parameter("frequency") with pulse.build(backend=self.backend, name="spectroscopy") as schedule: pulse.shift_frequency(freq_param, pulse.MeasureChannel(qubit)) pulse.play( pulse.GaussianSquare( duration=duration, amp=self.experiment_options.amp, sigma=sigma, width=width, ), pulse.MeasureChannel(qubit), ) pulse.acquire(duration, qubit, pulse.MemorySlot(self.experiment_options.memory_slot)) return schedule, freq_param def _metadata(self): """Update metadata with the resonator components.""" metadata = super()._metadata() metadata["device_components"] = list(map(Resonator, self.physical_qubits)) return metadata def circuits(self): """Create the circuit for the spectroscopy experiment. The circuits are based on a GaussianSquare pulse and a frequency_shift instruction encapsulated in a measurement instruction. Returns: circuits: The circuits that will run the spectroscopy experiment. """ sched, freq_param = self._schedule() circs = [] for freq in self._frequencies: freq_shift = freq - self._backend_center_frequency if self._absolute else freq freq_shift = np.round(freq_shift, decimals=3) sched_ = sched.assign_parameters({freq_param: freq_shift}, inplace=False) circuit = self._template_circuit() circuit.add_calibration("measure", self.physical_qubits, sched_) self._add_metadata(circuit, freq) circs.append(circuit) return circs
qiskit-experiments/qiskit_experiments/library/characterization/resonator_spectroscopy.py/0
{ "file_path": "qiskit-experiments/qiskit_experiments/library/characterization/resonator_spectroscopy.py", "repo_id": "qiskit-experiments", "token_count": 4685 }
111
# This code is part of Qiskit. # # (C) Copyright IBM 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. """ Quantum Volume Experiment class. """ from typing import Union, Sequence, Optional, List from numpy.random import Generator, default_rng from numpy.random.bit_generator import BitGenerator, SeedSequence from qiskit.utils.optionals import HAS_AER from qiskit import QuantumCircuit from qiskit.circuit.library import QuantumVolume as QuantumVolumeCircuit from qiskit import transpile from qiskit.providers.backend import Backend from qiskit_experiments.framework import BaseExperiment, Options from .qv_analysis import QuantumVolumeAnalysis class QuantumVolume(BaseExperiment): """An experiment to measure the largest random square circuit that can be run on a processor. # section: overview Quantum Volume (QV) is a single-number metric that can be measured using a concrete protocol on near-term quantum computers of modest size. The QV method quantifies the largest random circuit of equal width and depth that the computer successfully implements. Quantum computing systems with high-fidelity operations, high connectivity, large calibrated gate sets, and circuit rewriting toolchains are expected to have higher quantum volumes. The Quantum Volume is determined by the largest circuit depth :math:`d_{max}`, and equals to :math:`2^{d_{max}}`. See the `Qiskit Textbook <https://github.com/Qiskit/textbook/blob/main/notebooks/quantum-hardware/measuring-quantum-volume.ipynb>`_ for an explanation on the QV protocol. In the QV experiment we generate :class:`~qiskit.circuit.library.QuantumVolume` circuits on :math:`d` qubits, which contain :math:`d` layers, where each layer consists of random 2-qubit unitary gates from :math:`SU(4)`, followed by a random permutation on the :math:`d` qubits. Then these circuits run on the quantum backend and on an ideal simulator (either :class:`~qiskit_aer.AerSimulator` or :class:`~qiskit.quantum_info.Statevector`). A depth :math:`d` QV circuit is successful if it has `mean heavy-output probability` > 2/3 with confidence level > 0.977 (corresponding to z_value = 2), and at least 100 trials have been ran. See :class:`QuantumVolumeAnalysis` documentation for additional information on QV experiment analysis. # section: analysis_ref :class:`QuantumVolumeAnalysis` # section: manual :doc:`/manuals/verification/quantum_volume` # section: reference .. ref_arxiv:: 1 1811.12926 .. ref_arxiv:: 2 2008.08571 """ def __init__( self, physical_qubits: Sequence[int], backend: Optional[Backend] = None, trials: Optional[int] = 100, seed: Optional[Union[int, SeedSequence, BitGenerator, Generator]] = None, simulation_backend: Optional[Backend] = None, ): """Initialize a quantum volume experiment. Args: physical_qubits: list of physical qubits for the experiment. backend: Optional, the backend to run the experiment on. trials: The number of trials to run the quantum volume circuit. seed: Optional, seed used to initialize ``numpy.random.default_rng`` when generating circuits. The ``default_rng`` will be initialized with this seed value every time :meth:`circuits` is called. simulation_backend: The simulator backend to use to generate the expected results. the simulator must have a 'save_probabilities' method. If None, the :class:`qiskit_aer.AerSimulator` simulator will be used (in case :external+qiskit_aer:doc:`qiskit-aer <index>` is not installed, :class:`qiskit.quantum_info.Statevector` will be used). """ super().__init__(physical_qubits, analysis=QuantumVolumeAnalysis(), backend=backend) # Set configurable options self.set_experiment_options(trials=trials, seed=seed) if not simulation_backend and HAS_AER: from qiskit_aer import AerSimulator self._simulation_backend = AerSimulator() else: self._simulation_backend = simulation_backend @classmethod def _default_experiment_options(cls) -> Options: """Default experiment options. Experiment Options: trials (int): Optional, number of times to generate new Quantum Volume circuits and calculate their heavy output. seed (None or int or SeedSequence or BitGenerator or Generator): A seed used to initialize ``numpy.random.default_rng`` when generating circuits. The ``default_rng`` will be initialized with this seed value every time :meth:`circuits` is called. """ options = super()._default_experiment_options() options.trials = 100 options.seed = None return options def _get_ideal_data(self, circuit: QuantumCircuit, **run_options) -> List[float]: """Return ideal measurement probabilities. In case the user does not have Aer installed, use Qiskit's quantum info module to calculate the ideal state. Args: circuit: the circuit to extract the ideal data from run_options: backend run options. Returns: list: list of the probabilities for each state in the circuit. """ ideal_circuit = circuit.remove_final_measurements(inplace=False) if self._simulation_backend: ideal_circuit.save_probabilities() # always transpile with optimization_level 0, even if the non ideal circuits will run # with different optimization level, because we need to compare the results to the # exact generated probabilities ideal_circuit = transpile(ideal_circuit, self._simulation_backend, optimization_level=0) ideal_result = self._simulation_backend.run(ideal_circuit, **run_options).result() probabilities = ideal_result.data().get("probabilities") else: from qiskit.quantum_info import Statevector state_vector = Statevector(ideal_circuit) probabilities = state_vector.probabilities() return list(probabilities) def circuits(self) -> List[QuantumCircuit]: """Return a list of Quantum Volume circuits. Returns: A list of :class:`QuantumCircuit`. """ rng = default_rng(seed=self.experiment_options.seed) circuits = [] depth = self._num_qubits # Note: the trials numbering in the metadata is starting from 1 for each new experiment run for trial in range(1, self.experiment_options.trials + 1): qv_circ = QuantumVolumeCircuit(depth, depth, seed=rng) qv_circ.measure_active() qv_circ.metadata = { "depth": depth, "trial": trial, "ideal_probabilities": self._get_ideal_data(qv_circ), } circuits.append(qv_circ) return circuits
qiskit-experiments/qiskit_experiments/library/quantum_volume/qv_experiment.py/0
{ "file_path": "qiskit-experiments/qiskit_experiments/library/quantum_volume/qv_experiment.py", "repo_id": "qiskit-experiments", "token_count": 2851 }
112
# This code is part of Qiskit. # # (C) Copyright IBM 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. """ Standard RB Experiment class. """ import functools import logging from collections import defaultdict from numbers import Integral from typing import Union, Iterable, Optional, List, Sequence, Dict, Any import numpy as np import rustworkx as rx from numpy.random import Generator, default_rng from numpy.random.bit_generator import BitGenerator, SeedSequence from qiskit.circuit import CircuitInstruction, QuantumCircuit, Instruction, Barrier, Gate from qiskit.exceptions import QiskitError from qiskit.providers import BackendV2Converter from qiskit.providers.backend import Backend, BackendV1, BackendV2 from qiskit.pulse.instruction_schedule_map import CalibrationPublisher from qiskit.quantum_info import Clifford from qiskit.quantum_info.random import random_clifford from qiskit.transpiler import CouplingMap from qiskit_experiments.framework import BaseExperiment, Options from qiskit_experiments.framework.restless_mixin import RestlessMixin from .clifford_utils import ( CliffordUtils, DEFAULT_SYNTHESIS_METHOD, compose_1q, compose_2q, inverse_1q, inverse_2q, _clifford_1q_int_to_instruction, _clifford_2q_int_to_instruction, _clifford_to_instruction, _transpile_clifford_circuit, ) from .rb_analysis import RBAnalysis LOG = logging.getLogger(__name__) SequenceElementType = Union[Clifford, Integral, QuantumCircuit] class StandardRB(BaseExperiment, RestlessMixin): """An experiment to characterize the error rate of a gate set on a device. # section: overview Randomized Benchmarking (RB) is an efficient and robust method for estimating the average error rate of a set of quantum gate operations. See `Qiskit Textbook <https://github.com/Qiskit/textbook/blob/main/notebooks/quantum-hardware/randomized-benchmarking.ipynb>`_ for an explanation on the RB method. A standard RB experiment generates sequences of random Cliffords such that the unitary computed by the sequences is the identity. After running the sequences on a backend, it calculates the probabilities to get back to the ground state, fits an exponentially decaying curve, and estimates the Error Per Clifford (EPC), as described in Refs. [1, 2]. .. note:: In 0.5.0, the default value of ``optimization_level`` in ``transpile_options`` changed from ``0`` to ``1`` for RB experiments. That may result in shorter RB circuits hence slower decay curves than before. # section: analysis_ref :class:`RBAnalysis` # section: manual :doc:`/manuals/verification/randomized_benchmarking` # section: reference .. ref_arxiv:: 1 1009.3639 .. ref_arxiv:: 2 1109.6887 """ def __init__( self, physical_qubits: Sequence[int], lengths: Iterable[int], backend: Optional[Backend] = None, num_samples: int = 3, seed: Optional[Union[int, SeedSequence, BitGenerator, Generator]] = None, full_sampling: Optional[bool] = False, ): """Initialize a standard randomized benchmarking experiment. Args: physical_qubits: List of physical qubits for the experiment. lengths: A list of RB sequences lengths. backend: The backend to run the experiment on. num_samples: Number of samples to generate for each sequence length. seed: Optional, seed used to initialize ``numpy.random.default_rng``. when generating circuits. The ``default_rng`` will be initialized with this seed value every time :meth:`circuits` is called. full_sampling: If True all Cliffords are independently sampled for all lengths. If False for sample of lengths longer sequences are constructed by appending additional samples to shorter sequences. The default is False. Raises: QiskitError: If any invalid argument is supplied. """ # Initialize base experiment super().__init__(physical_qubits, analysis=RBAnalysis(), backend=backend) # Verify parameters if any(length <= 0 for length in lengths): raise QiskitError( f"The lengths list {lengths} should only contain " "positive elements." ) if len(set(lengths)) != len(lengths): raise QiskitError( f"The lengths list {lengths} should not contain " "duplicate elements." ) if num_samples <= 0: raise QiskitError(f"The number of samples {num_samples} should " "be positive.") # Set configurable options self.set_experiment_options( lengths=sorted(lengths), num_samples=num_samples, seed=seed, full_sampling=full_sampling ) self.analysis.set_options(outcome="0" * self.num_qubits) @classmethod def _default_experiment_options(cls) -> Options: """Default experiment options. Experiment Options: lengths (List[int]): A list of RB sequences lengths. num_samples (int): Number of samples to generate for each sequence length. seed (None or int or SeedSequence or BitGenerator or Generator): A seed used to initialize ``numpy.random.default_rng`` when generating circuits. The ``default_rng`` will be initialized with this seed value every time :meth:`circuits` is called. full_sampling (bool): If True all Cliffords are independently sampled for all lengths. If False for sample of lengths longer sequences are constructed by appending additional Clifford samples to shorter sequences. clifford_synthesis_method (str): The name of the Clifford synthesis plugin to use for building circuits of RB sequences. """ options = super()._default_experiment_options() options.update_options( lengths=None, num_samples=None, seed=None, full_sampling=None, clifford_synthesis_method=DEFAULT_SYNTHESIS_METHOD, ) return options @classmethod def _default_transpile_options(cls) -> Options: """Default transpiler options for transpiling RB circuits.""" return Options(optimization_level=1) def _set_backend(self, backend: Backend): """Set the backend V2 for RB experiments since RB experiments only support BackendV2 except for simulators. If BackendV1 is provided, it is converted to V2 and stored. """ if isinstance(backend, BackendV1) and "simulator" not in backend.name(): super()._set_backend(BackendV2Converter(backend, add_delay=True)) else: super()._set_backend(backend) def circuits(self) -> List[QuantumCircuit]: """Return a list of RB circuits. Returns: A list of :class:`QuantumCircuit`. """ # Sample random Clifford sequences sequences = self._sample_sequences() # Convert each sequence into circuit and append the inverse to the end. circuits = self._sequences_to_circuits(sequences) # Add metadata for each circuit for circ, seq in zip(circuits, sequences): circ.metadata = { "xval": len(seq), "group": "Clifford", } return circuits def _sample_sequences(self) -> List[Sequence[SequenceElementType]]: """Sample RB sequences Returns: A list of RB sequences. """ rng = default_rng(seed=self.experiment_options.seed) sequences = [] if self.experiment_options.full_sampling: for _ in range(self.experiment_options.num_samples): for length in self.experiment_options.lengths: sequences.append(self.__sample_sequence(length, rng)) else: for _ in range(self.experiment_options.num_samples): longest_seq = self.__sample_sequence(max(self.experiment_options.lengths), rng) for length in self.experiment_options.lengths: sequences.append(longest_seq[:length]) return sequences def _get_synthesis_options(self) -> Dict[str, Optional[Any]]: """Get options for Clifford synthesis from the backend information as a dictionary. The options include: - "basis_gates": Sorted basis gate names. Return None if no basis gates are supplied via ``backend`` or ``transpile_options``. - "coupling_tuple": Reduced coupling map in the form of tuple of edges in the coupling graph. Return None if no coupling map are supplied via ``backend`` or ``transpile_options``. Returns: Synthesis options as a dictionary. """ basis_gates = self.transpile_options.get("basis_gates", []) coupling_map = self.transpile_options.get("coupling_map", None) if coupling_map: coupling_map = coupling_map.reduce(self.physical_qubits) if not (basis_gates and coupling_map) and self.backend: if isinstance(self.backend, BackendV2) and "simulator" in self.backend.name: basis_gates = basis_gates if basis_gates else self.backend.target.operation_names coupling_map = coupling_map if coupling_map else None elif isinstance(self.backend, BackendV2): gate_ops = [op for op in self.backend.target.operations if isinstance(op, Gate)] backend_basis_gates = [op.name for op in gate_ops if op.num_qubits != 2] backend_cmap = None for op in gate_ops: if op.num_qubits != 2: continue cmap = self.backend.target.build_coupling_map(op.name) if cmap is None: backend_basis_gates.append(op.name) else: reduced = cmap.reduce(self.physical_qubits) if rx.is_weakly_connected(reduced.graph): backend_basis_gates.append(op.name) backend_cmap = reduced # take the first non-global 2q gate if backend has multiple 2q gates break basis_gates = basis_gates if basis_gates else backend_basis_gates coupling_map = coupling_map if coupling_map else backend_cmap elif isinstance(self.backend, BackendV1): backend_basis_gates = self.backend.configuration().basis_gates backend_cmap = self.backend.configuration().coupling_map if backend_cmap: backend_cmap = CouplingMap(backend_cmap).reduce(self.physical_qubits) basis_gates = basis_gates if basis_gates else backend_basis_gates coupling_map = coupling_map if coupling_map else backend_cmap return { "basis_gates": tuple(sorted(basis_gates)) if basis_gates else None, "coupling_tuple": tuple(sorted(coupling_map.get_edges())) if coupling_map else None, "synthesis_method": self.experiment_options["clifford_synthesis_method"], } def _sequences_to_circuits( self, sequences: List[Sequence[SequenceElementType]] ) -> List[QuantumCircuit]: """Convert an RB sequence into circuit and append the inverse to the end. Returns: A list of RB circuits. """ synthesis_opts = self._get_synthesis_options() # Circuit generation circuits = [] for i, seq in enumerate(sequences): if ( self.experiment_options.full_sampling or i % len(self.experiment_options.lengths) == 0 ): prev_elem, prev_seq = self.__identity_clifford(), [] circ = QuantumCircuit(self.num_qubits) for elem in seq: circ.append(self._to_instruction(elem, synthesis_opts), circ.qubits) circ._append(CircuitInstruction(Barrier(self.num_qubits), circ.qubits)) # Compute inverse, compute only the difference from the previous shorter sequence prev_elem = self.__compose_clifford_seq(prev_elem, seq[len(prev_seq) :]) prev_seq = seq inv = self.__adjoint_clifford(prev_elem) circ.append(self._to_instruction(inv, synthesis_opts), circ.qubits) circ.measure_all() # includes insertion of the barrier before measurement circuits.append(circ) return circuits def __sample_sequence(self, length: int, rng: Generator) -> Sequence[SequenceElementType]: # Sample an RB sequence with the given length. # Return integer instead of Clifford object for 1 or 2 qubits case for speed if self.num_qubits == 1: return rng.integers(CliffordUtils.NUM_CLIFFORD_1_QUBIT, size=length) if self.num_qubits == 2: return rng.integers(CliffordUtils.NUM_CLIFFORD_2_QUBIT, size=length) # Return Clifford object for 3 or more qubits case return [random_clifford(self.num_qubits, rng) for _ in range(length)] def _to_instruction( self, elem: SequenceElementType, synthesis_options: Dict[str, Optional[Any]], ) -> Instruction: """Return the instruction of a Clifford element. The resulting instruction contains a circuit definition with ``basis_gates`` and it complies with ``coupling_tuple``, which is specified in ``synthesis_options``. Args: elem: a Clifford element to be converted synthesis_options: options for synthesizing the Clifford element Returns: Converted instruction """ # Switching for speed up if isinstance(elem, Integral): if self.num_qubits == 1: return _clifford_1q_int_to_instruction( elem, basis_gates=synthesis_options["basis_gates"], synthesis_method=synthesis_options["synthesis_method"], ) if self.num_qubits == 2: return _clifford_2q_int_to_instruction(elem, **synthesis_options) return _clifford_to_instruction(elem, **synthesis_options) def __identity_clifford(self) -> SequenceElementType: if self.num_qubits <= 2: return 0 return Clifford(np.eye(2 * self.num_qubits)) def __compose_clifford_seq( self, base_elem: SequenceElementType, elements: Sequence[SequenceElementType] ) -> SequenceElementType: if self.num_qubits <= 2: return functools.reduce( compose_1q if self.num_qubits == 1 else compose_2q, elements, base_elem ) # 3 or more qubits res = base_elem for elem in elements: res = res.compose(elem) return res def __adjoint_clifford(self, op: SequenceElementType) -> SequenceElementType: if self.num_qubits == 1: return inverse_1q(op) if self.num_qubits == 2: return inverse_2q(op) if isinstance(op, QuantumCircuit): return Clifford.from_circuit(op).adjoint() return op.adjoint() def _transpiled_circuits(self) -> List[QuantumCircuit]: """Return a list of experiment circuits, transpiled.""" has_custom_transpile_option = ( not set(vars(self.transpile_options)).issubset( {"basis_gates", "coupling_map", "optimization_level"} ) or self.transpile_options.get("optimization_level", 1) != 1 ) if has_custom_transpile_option: transpiled = super()._transpiled_circuits() else: transpiled = [ _transpile_clifford_circuit(circ, physical_qubits=self.physical_qubits) for circ in self.circuits() ] # Set custom calibrations provided in backend (excluding simulators) if isinstance(self.backend, BackendV2) and "simulator" not in self.backend.name: qargs_patterns = [self.physical_qubits] # for 1q or 3q+ case if self.num_qubits == 2: qargs_patterns = [ (self.physical_qubits[0],), (self.physical_qubits[1],), self.physical_qubits, (self.physical_qubits[1], self.physical_qubits[0]), ] qargs_supported = self.backend.target.qargs instructions = [] # (op_name, qargs) for each element where qargs means qubit tuple for qargs in qargs_patterns: if qargs in qargs_supported: for op_name in self.backend.target.operation_names_for_qargs(qargs): instructions.append((op_name, qargs)) common_calibrations = defaultdict(dict) for op_name, qargs in instructions: inst_prop = self.backend.target[op_name].get(qargs, None) if inst_prop is None: continue schedule = inst_prop.calibration if schedule is None: continue publisher = schedule.metadata.get("publisher", CalibrationPublisher.QISKIT) if publisher != CalibrationPublisher.BACKEND_PROVIDER: common_calibrations[op_name][(qargs, tuple())] = schedule for circ in transpiled: # This logic is inefficient in terms of payload size and backend compilation # because this binds every custom pulse to a circuit regardless of # its existence. It works but redundant calibration must be removed -- NK. circ.calibrations = common_calibrations if self.analysis.options.get("gate_error_ratio", None) is None: # Gate errors are not computed, then counting ops is not necessary. return transpiled # Compute average basis gate numbers per Clifford operation # This is probably main source of performance regression. # This should be integrated into transpile pass in future. qubit_indices = {bit: index for index, bit in enumerate(transpiled[0].qubits)} for circ in transpiled: count_ops_result = defaultdict(int) # This is physical circuits, i.e. qargs is physical index for inst, qargs, _ in circ.data: if inst.name in ("measure", "reset", "delay", "barrier", "snapshot"): continue qinds = [qubit_indices[q] for q in qargs] if not set(self.physical_qubits).issuperset(qinds): continue # Not aware of multi-qubit gate direction formatted_key = tuple(sorted(qinds)), inst.name count_ops_result[formatted_key] += 1 circ.metadata["count_ops"] = tuple(count_ops_result.items()) return transpiled def _metadata(self): metadata = super()._metadata() # Store measurement level and meas return if they have been # set for the experiment for run_opt in ["meas_level", "meas_return"]: if hasattr(self.run_options, run_opt): metadata[run_opt] = getattr(self.run_options, run_opt) return metadata
qiskit-experiments/qiskit_experiments/library/randomized_benchmarking/standard_rb.py/0
{ "file_path": "qiskit-experiments/qiskit_experiments/library/randomized_benchmarking/standard_rb.py", "repo_id": "qiskit-experiments", "token_count": 8751 }
113
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # 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. """ Readout error mitigated tomography analysis """ from qiskit_experiments.framework import CompositeAnalysis from qiskit_experiments.library.characterization import LocalReadoutErrorAnalysis from .tomography_analysis import TomographyAnalysis from .basis.pauli_basis import PauliMeasurementBasis class MitigatedTomographyAnalysis(CompositeAnalysis): """Analysis for readout error mitigated tomography experiments. Analysis is performed as a :class:`.CompositeAnalysis` consisting of :class:`.LocalReadoutErrorAnalysis` to determine the local assignment matrices describing single qubit Z-basis readout errors, and then these matrices are used to automatically construct a noisy :class:`~.PauliMeasurementBasis` for use during tomographic fitting with the tomography analysis. """ def __init__(self, roerror_analysis="default", tomography_analysis="default"): """Initialize mitigated tomography analysis""" if roerror_analysis == "default": roerror_analysis = LocalReadoutErrorAnalysis() if tomography_analysis == "default": tomography_analysis = TomographyAnalysis() super().__init__([roerror_analysis, tomography_analysis], flatten_results=True) @classmethod def _default_options(cls): """Default analysis options Analysis Options: fitter (str or Callable): The fitter function to use for reconstruction. This can be a string to select one of the built-in fitters, or a callable to supply a custom fitter function. See the `Fitter Functions` section for additional information. fitter_options (dict): Any addition kwarg options to be supplied to the fitter function. For documentation of available kwargs refer to the fitter function documentation. rescale_positive (bool): If True rescale the state returned by the fitter to be positive-semidefinite. See the `PSD Rescaling` section for additional information (Default: True). rescale_trace (bool): If True rescale the state returned by the fitter have either trace 1 for :class:`~qiskit.quantum_info.DensityMatrix`, or trace dim for :class:`~qiskit.quantum_info.Choi` matrices (Default: True). measurement_qubits (Sequence[int]): Optional, the physical qubits with tomographic measurements. If not specified will be set to ``[0, ..., N-1]`` for N-qubit tomographic measurements. preparation_qubits (Sequence[int]): Optional, the physical qubits with tomographic preparations. If not specified will be set to ``[0, ..., N-1]`` for N-qubit tomographic preparations. unmitigated_fit (bool): If True also run tomography fit without readout error mitigation and include both mitigated and unmitigated analysis results. If False only compute mitigated results (Default: False) target (Any): Optional, target object for fidelity comparison of the fit (Default: None). """ # Override options to be tomography options minus bases options = super()._default_options() options.fitter = "linear_inversion" options.fitter_options = {} options.rescale_positive = True options.rescale_trace = True options.measurement_qubits = None options.preparation_qubits = None options.unmitigated_fit = False options.target = None return options def set_options(self, **fields): # filter fields self_fields = {key: val for key, val in fields.items() if hasattr(self.options, key)} super().set_options(**self_fields) tomo_fields = { key: val for key, val in fields.items() if hasattr(self._analyses[1].options, key) } self._analyses[1].set_options(**tomo_fields) def _run_analysis(self, experiment_data): # Return list of experiment data containers for each component experiment # containing the marginalized data from the composite experiment roerror_analysis, tomo_analysis = self._analyses roerror_data, tomo_data = self._component_experiment_data(experiment_data) # Run readout error analysis roerror_analysis.run(roerror_data, replace_results=True).block_for_results() # Construct noisy measurement basis mitigator = roerror_data.analysis_results("Local Readout Mitigator").value # Run mitigated tomography analysis with noisy mitigated basis # Tomo analysis instance is internally copied by setting option with run. tomo_analysis.run( tomo_data, replace_results=True, measurement_basis=PauliMeasurementBasis(mitigator=mitigator), extra={"mitigated": True}, ).block_for_results() # Combine results so that tomography results are ordered first combined_data = [tomo_data, roerror_data] # Run unmitigated tomography analysis if self.options.unmitigated_fit: nomit_data = tomo_analysis.run( tomo_data, replace_results=False, measurement_basis=PauliMeasurementBasis(), extra={"mitigated": False}, ).block_for_results() combined_data.append(nomit_data) if self._flatten_results: return self._combine_results(combined_data) return [], []
qiskit-experiments/qiskit_experiments/library/tomography/mit_tomography_analysis.py/0
{ "file_path": "qiskit-experiments/qiskit_experiments/library/tomography/mit_tomography_analysis.py", "repo_id": "qiskit-experiments", "token_count": 2257 }
114
--- fixes: - | The gate counting for EPG in the RB analysis code was not including the inverse, so that the total number of operations per Clifford was incorrect, leading to incorrect reporting of EPG from EPC. Fixed by adding +1 for the inverse gate.
qiskit-experiments/releasenotes/notes/0.7/fix-epg-gatecount-60777f7a3f3566bc.yaml/0
{ "file_path": "qiskit-experiments/releasenotes/notes/0.7/fix-epg-gatecount-60777f7a3f3566bc.yaml", "repo_id": "qiskit-experiments", "token_count": 76 }
115
# This code is part of Qiskit. # # (C) Copyright IBM 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. """Tests for base experiment framework.""" from test.base import QiskitExperimentsTestCase from test.fake_experiment import FakeExperiment import ddt import numpy as np from qiskit.circuit import Instruction from qiskit.circuit.library import QuantumVolume, SXGate, RZXGate, Barrier, Measure import qiskit.quantum_info as qi from qiskit_experiments.curve_analysis import CurveFitResult class CustomClass: """Custom class for serialization tests""" def __init__(self, value=None): self._value = value def __eq__(self, other): return other.__class__ == self.__class__ and other._value == self._value @property def settings(self): """Return settings for class""" return {"value": self._value} @staticmethod def static_method(arg): """A static method""" return arg @classmethod def class_method(cls, arg): """A static method""" return arg def custom_function(*args, **kwargs): """Test function for serialization""" return args, kwargs @ddt.ddt class TestJSON(QiskitExperimentsTestCase): """Test JSON encoder and decoder""" def test_roundtrip_experiment(self): """Test serializing an experiment""" obj = FakeExperiment([0]) obj.set_transpile_options(optimization_level=3, basis_gates=["rx", "ry", "cz"]) obj.set_run_options(shots=2000) self.assertRoundTripSerializable(obj) @ddt.data(SXGate(), RZXGate(0.4), Barrier(5), Measure()) def test_roundtrip_gate(self, instruction): """Test round-trip serialization of a gate.""" self.assertRoundTripSerializable(instruction) def test_custom_instruction(self): """Test the serialisation of a custom instruction.""" class CustomInstruction(Instruction): """A custom instruction for testing.""" def __init__(self, param: float): """Initialize the instruction.""" super().__init__("test_inst", 2, 2, [param, 0.6]) def compare_instructions(inst1, inst2): """Soft comparison of two instructions.""" return inst1.soft_compare(inst2) self.assertRoundTripSerializable(CustomInstruction(0.123), check_func=compare_instructions) def test_roundtrip_quantum_circuit(self): """Test round-trip serialization of a circuits""" obj = QuantumVolume(4) self.assertRoundTripSerializable(obj) def test_roundtrip_operator(self): """Test round-trip serialization of an Operator""" obj = qi.random_unitary(4, seed=10) self.assertRoundTripSerializable(obj) def test_roundtrip_statevector(self): """Test round-trip serialization of a Statevector""" obj = qi.random_statevector(4, seed=10) self.assertRoundTripSerializable(obj) def test_roundtrip_density_matrix(self): """Test round-trip serialization of a DensityMatrix""" obj = qi.random_density_matrix(4, seed=10) self.assertRoundTripSerializable(obj) @ddt.data("Choi", "SuperOp", "Kraus", "Stinespring", "PTM", "Chi") def test_roundtrip_quantum_channel(self, rep): """Test round-trip serialization of a DensityMatrix""" chan_cls = { "Choi": qi.Choi, "SuperOp": qi.SuperOp, "Kraus": qi.Kraus, "Stinespring": qi.Stinespring, "PTM": qi.PTM, "Chi": qi.Chi, } obj = chan_cls[rep](qi.random_quantum_channel(2, seed=10)) self.assertRoundTripSerializable(obj) def test_roundtrip_function(self): """Test roundtrip serialization of custom class object""" obj = custom_function self.assertRoundTripSerializable(obj) def test_roundtrip_curvefitresult(self): """Test roundtrip serialization of the ScatterTable class""" obj = CurveFitResult( method="some_method", model_repr={"s1": "par0 * x + par1"}, success=True, params={"par0": 0.3, "par1": 0.4}, var_names=["par0", "par1"], covar=np.array([[2.19188077e-03, 2.19906808e-01], [2.19906808e-01, 2.62351788e01]]), reduced_chisq=1.5, ) self.assertRoundTripSerializable(obj) def test_roundtrip_class_type(self): """Test roundtrip serialization of custom class""" obj = CustomClass self.assertRoundTripSerializable(obj) def test_roundtrip_class_object(self): """Test roundtrip serialization of custom class object""" obj = CustomClass(123) self.assertRoundTripSerializable(obj) def test_roundtrip_class_method(self): """Test roundtrip serialization of custom class object""" obj = CustomClass.class_method self.assertRoundTripSerializable(obj) def test_roundtrip_custom_static_method(self): """Test roundtrip serialization of custom class object""" obj = CustomClass.static_method self.assertRoundTripSerializable(obj) def test_roundtrip_main_function(self): """Test roundtrip serialization of __main__ custom class object""" import __main__ as main_mod main_mod.custom_function = custom_function main_mod.custom_function.__module__ = "__main__" obj = main_mod.custom_function self.assertRoundTripSerializable(obj) def test_roundtrip_main_class_type(self): """Test roundtrip serialization of __main__ custom class""" import __main__ as main_mod main_mod.CustomClass = CustomClass main_mod.CustomClass.__module__ = "__main__" obj = main_mod.CustomClass self.assertRoundTripSerializable(obj) def test_roundtrip_main_class_object(self): """Test roundtrip serialization of __main__ custom class object""" import __main__ as main_mod main_mod.CustomClass = CustomClass main_mod.CustomClass.__module__ = "__main__" obj = main_mod.CustomClass(123) self.assertRoundTripSerializable(obj) def test_roundtrip_main_class_method(self): """Test roundtrip serialization of __main__ custom class object""" import __main__ as main_mod main_mod.CustomClass = CustomClass main_mod.CustomClass.__module__ = "__main__" obj = main_mod.CustomClass.class_method self.assertRoundTripSerializable(obj) def test_roundtrip_main_custom_static_method(self): """Test roundtrip serialization of __main__ custom class object""" import __main__ as main_mod main_mod.CustomClass = CustomClass main_mod.CustomClass.__module__ = "__main__" obj = main_mod.CustomClass.static_method self.assertRoundTripSerializable(obj)
qiskit-experiments/test/database_service/test_json.py/0
{ "file_path": "qiskit-experiments/test/database_service/test_json.py", "repo_id": "qiskit-experiments", "token_count": 2876 }
116
# This code is part of Qiskit. # # (C) Copyright IBM 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. """Test the fine amplitude characterization and calibration experiments.""" from test.base import QiskitExperimentsTestCase import numpy as np from ddt import ddt, data from qiskit import pulse from qiskit.circuit import Gate from qiskit.circuit.library import XGate, SXGate from qiskit.pulse import DriveChannel, Drag from qiskit_ibm_runtime.fake_provider import FakeArmonkV2 from qiskit_experiments.library import ( FineXAmplitude, FineSXAmplitude, FineZXAmplitude, FineXAmplitudeCal, FineSXAmplitudeCal, ) from qiskit_experiments.calibration_management.basis_gate_library import FixedFrequencyTransmon from qiskit_experiments.calibration_management import Calibrations from qiskit_experiments.test.mock_iq_backend import MockIQBackend from qiskit_experiments.test.mock_iq_helpers import MockIQFineAmpHelper as FineAmpHelper @ddt class TestFineAmpEndToEnd(QiskitExperimentsTestCase): """Test the fine amplitude experiment.""" @data(0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08) def test_end_to_end_under_rotation(self, pi_ratio): """Test the experiment end to end.""" amp_exp = FineXAmplitude([0]) error = -np.pi * pi_ratio backend = MockIQBackend(FineAmpHelper(error, np.pi, "x")) backend.target.add_instruction(XGate(), properties={(0,): None}) backend.target.add_instruction(SXGate(), properties={(0,): None}) expdata = amp_exp.run(backend) self.assertExperimentDone(expdata) result = expdata.analysis_results("d_theta") d_theta = result.value.n tol = 0.04 self.assertAlmostEqual(d_theta, error, delta=tol) self.assertEqual(result.quality, "good") @data(0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08) def test_end_to_end_over_rotation(self, pi_ratio): """Test the experiment end to end.""" amp_exp = FineXAmplitude([0]) error = np.pi * pi_ratio backend = MockIQBackend(FineAmpHelper(error, np.pi, "x")) backend.target.add_instruction(XGate(), properties={(0,): None}) backend.target.add_instruction(SXGate(), properties={(0,): None}) expdata = amp_exp.run(backend) self.assertExperimentDone(expdata) result = expdata.analysis_results("d_theta") d_theta = result.value.n tol = 0.04 self.assertAlmostEqual(d_theta, error, delta=tol) self.assertEqual(result.quality, "good") def test_circuits_serialization(self): """Test circuits serialization of the experiment.""" backend = FakeArmonkV2() amp_exp = FineXAmplitude([0], backend=backend) self.assertRoundTripSerializable(amp_exp._transpiled_circuits()) @ddt class TestFineZXAmpEndToEnd(QiskitExperimentsTestCase): """Test the fine amplitude experiment.""" @data(-0.08, -0.03, -0.02, 0.02, 0.06, 0.07) def test_end_to_end(self, pi_ratio): """Test the experiment end to end.""" error = -np.pi * pi_ratio amp_exp = FineZXAmplitude((0, 1)) backend = MockIQBackend(FineAmpHelper(error, np.pi / 2, "szx")) backend.target.add_instruction(Gate("szx", 2, []), properties={(0, 1): None}) expdata = amp_exp.run(backend) self.assertExperimentDone(expdata) result = expdata.analysis_results("d_theta") d_theta = result.value.n tol = 0.04 self.assertAlmostEqual(d_theta, error, delta=tol) self.assertEqual(result.quality, "good") def test_experiment_config(self): """Test converting to and from config works""" exp = FineZXAmplitude((0, 1)) loaded_exp = FineZXAmplitude.from_config(exp.config()) self.assertNotEqual(exp, loaded_exp) self.assertEqualExtended(exp, loaded_exp) class TestFineAmplitudeCircuits(QiskitExperimentsTestCase): """Test the circuits.""" def setUp(self): """Setup some schedules.""" super().setUp() with pulse.build(name="xp") as xp: pulse.play(Drag(duration=160, amp=0.208519, sigma=40, beta=0.0), DriveChannel(0)) with pulse.build(name="x90p") as x90p: pulse.play(Drag(duration=160, amp=0.208519, sigma=40, beta=0.0), DriveChannel(0)) self.x_plus = xp self.x_90_plus = x90p def test_xp(self): """Test a circuit with the x gate.""" amp_cal = FineXAmplitude([0]) circs = amp_cal.circuits() self.assertTrue(circs[0].data[0][0].name == "measure") self.assertTrue(circs[1].data[0][0].name == "x") for idx, circ in enumerate(circs[2:]): self.assertTrue(circ.data[0][0].name == "sx") self.assertEqual(circ.count_ops().get("x", 0), idx + 1) def test_x90p(self): """Test circuits with an x90p pulse.""" amp_cal = FineSXAmplitude([0]) expected = [0, 1, 2, 3, 5, 7, 9, 11, 13, 15, 17, 21, 23, 25] for idx, circ in enumerate(amp_cal.circuits()): self.assertEqual(circ.count_ops().get("sx", 0), expected[idx]) @ddt class TestSpecializations(QiskitExperimentsTestCase): """Test the options of the specialized classes.""" def test_fine_x_amp(self): """Test the fine X amplitude.""" exp = FineXAmplitude([0]) self.assertTrue(exp.experiment_options.add_cal_circuits) self.assertDictEqual( exp.analysis.options.fixed_parameters, {"angle_per_gate": np.pi, "phase_offset": np.pi / 2}, ) self.assertEqual(exp.experiment_options.gate, XGate()) def test_x_roundtrip_serializable(self): """Test round trip JSON serialization""" exp = FineXAmplitude([0]) self.assertRoundTripSerializable(exp) def test_fine_sx_amp(self): """Test the fine SX amplitude.""" exp = FineSXAmplitude([0]) self.assertFalse(exp.experiment_options.add_cal_circuits) expected = [0, 1, 2, 3, 5, 7, 9, 11, 13, 15, 17, 21, 23, 25] self.assertEqual(exp.experiment_options.repetitions, expected) self.assertDictEqual( exp.analysis.options.fixed_parameters, {"angle_per_gate": np.pi / 2, "phase_offset": np.pi}, ) self.assertEqual(exp.experiment_options.gate, SXGate()) def test_sx_roundtrip_serializable(self): """Test round trip JSON serialization""" exp = FineSXAmplitude([0]) self.assertRoundTripSerializable(exp) @data((2, 3), (3, 1), (0, 1)) def test_measure_qubits(self, qubits): """Test that the measurement is on the logical qubits.""" fine_amp = FineZXAmplitude(qubits) for circuit in fine_amp.circuits(): self.assertEqual(circuit.num_qubits, 2) self.assertEqual(circuit.data[-1][0].name, "measure") self.assertEqual(circuit.data[-1][1][0], circuit.qregs[0][1]) class TestFineAmplitudeCal(QiskitExperimentsTestCase): """A class to test the fine amplitude calibration experiments.""" def setUp(self): """Setup the tests""" super().setUp() library = FixedFrequencyTransmon() self.backend = MockIQBackend(FineAmpHelper(-np.pi * 0.07, np.pi, "xp")) self.backend.target.add_instruction(SXGate(), properties={(0,): None}) self.backend.target.add_instruction(XGate(), properties={(0,): None}) self.cals = Calibrations.from_backend(self.backend, libraries=[library]) def test_cal_options(self): """Test that the options are properly propagated.""" # Test the X gate cal amp_cal = FineXAmplitudeCal([0], self.cals, "x") exp_opt = amp_cal.experiment_options self.assertEqual(exp_opt.gate.name, "x") self.assertTrue(exp_opt.add_cal_circuits) self.assertEqual(exp_opt.result_index, -1) self.assertEqual(exp_opt.group, "default") self.assertTrue(np.allclose(exp_opt.target_angle, np.pi)) # Test the SX gate cal amp_cal = FineSXAmplitudeCal([0], self.cals, "sx") exp_opt = amp_cal.experiment_options self.assertEqual(exp_opt.gate.name, "sx") self.assertFalse(exp_opt.add_cal_circuits) self.assertEqual(exp_opt.result_index, -1) self.assertEqual(exp_opt.group, "default") self.assertTrue(np.allclose(exp_opt.target_angle, np.pi / 2)) def test_run_x_cal(self): """Test that we can transpile in the calibrations before and after update. If this test passes then we were successful in running a calibration experiment, updating a pulse parameter, having this parameter propagated to the schedules for use the next time the experiment is run. """ # Initial pulse amplitude init_amp = 0.5 amp_cal = FineXAmplitudeCal([0], self.cals, "x", backend=self.backend) circs = amp_cal._transpiled_circuits() with pulse.build(name="x") as expected_x: pulse.play(pulse.Drag(160, 0.5, 40, 0), pulse.DriveChannel(0)) with pulse.build(name="sx") as expected_sx: pulse.play(pulse.Drag(160, 0.25, 40, 0), pulse.DriveChannel(0)) self.assertEqual(circs[5].calibrations["x"][((0,), ())], expected_x) self.assertEqual(circs[5].calibrations["sx"][((0,), ())], expected_sx) # run the calibration experiment. This should update the amp parameter of x which we test. exp_data = amp_cal.run() self.assertExperimentDone(exp_data) d_theta = exp_data.analysis_results("d_theta").value.n new_amp = init_amp * np.pi / (np.pi + d_theta) circs = amp_cal._transpiled_circuits() x_cal = circs[5].calibrations["x"][((0,), ())] # Requires allclose due to numerical precision. self.assertTrue(np.allclose(x_cal.blocks[0].pulse.amp, new_amp)) self.assertFalse(np.allclose(x_cal.blocks[0].pulse.amp, init_amp)) self.assertEqual(circs[5].calibrations["sx"][((0,), ())], expected_sx) def test_run_sx_cal(self): """Test that we can transpile in the calibrations before and after update. If this test passes then we were successful in running a calibration experiment, updating a pulse parameter, having this parameter propagated to the schedules for use the next time the experiment is run. """ # Initial pulse amplitude init_amp = 0.25 backend = MockIQBackend(FineAmpHelper(-np.pi * 0.07, np.pi / 2, "sx")) amp_cal = FineSXAmplitudeCal([0], self.cals, "sx", backend=backend) circs = amp_cal._transpiled_circuits() with pulse.build(name="sx") as expected_sx: pulse.play(pulse.Drag(160, 0.25, 40, 0), pulse.DriveChannel(0)) self.assertEqual(circs[5].calibrations["sx"][((0,), ())], expected_sx) # run the calibration experiment. This should update the amp parameter of x which we test. exp_data = amp_cal.run() self.assertExperimentDone(exp_data) d_theta = exp_data.analysis_results("d_theta").value.n new_amp = init_amp * (np.pi / 2) / (np.pi / 2 + d_theta) circs = amp_cal._transpiled_circuits() sx_cal = circs[5].calibrations["sx"][((0,), ())] # Requires allclose due to numerical precision. self.assertTrue(np.allclose(sx_cal.blocks[0].pulse.amp, new_amp)) self.assertFalse(np.allclose(sx_cal.blocks[0].pulse.amp, init_amp)) def test_experiment_config(self): """Test converting to and from config works""" exp = FineSXAmplitudeCal([0], self.cals, "sx") loaded_exp = FineSXAmplitudeCal.from_config(exp.config()) self.assertNotEqual(exp, loaded_exp) self.assertEqualExtended(exp, loaded_exp) def test_roundtrip_serializable(self): """Test round trip JSON serialization""" exp = FineSXAmplitudeCal([0], self.cals, "sx") self.assertRoundTripSerializable(exp)
qiskit-experiments/test/library/calibration/test_fine_amplitude.py/0
{ "file_path": "qiskit-experiments/test/library/calibration/test_fine_amplitude.py", "repo_id": "qiskit-experiments", "token_count": 5256 }
117
# This code is part of Qiskit. # # (C) Copyright IBM 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. """ Test T1 experiment """ from test.base import QiskitExperimentsTestCase import numpy as np from qiskit.qobj.utils import MeasLevel from qiskit_ibm_runtime.fake_provider import FakeAthensV2 from qiskit_experiments.test.noisy_delay_aer_simulator import NoisyDelayAerBackend from qiskit_experiments.framework import ExperimentData, ParallelExperiment from qiskit_experiments.library import T1 from qiskit_experiments.library.characterization import T1Analysis, T1KerneledAnalysis from qiskit_experiments.test.mock_iq_backend import MockIQBackend, MockIQParallelBackend from qiskit_experiments.test.mock_iq_helpers import MockIQT1Helper, MockIQParallelExperimentHelper class TestT1(QiskitExperimentsTestCase): """ Test measurement of T1 """ def test_t1_end2end(self): """ Test T1 experiment using a simulator. """ t1 = 25e-6 backend = NoisyDelayAerBackend([t1], [t1 / 2]) delays = np.arange(1e-6, 40e-6, 3e-6) exp = T1([0], delays) exp.analysis.set_options(p0={"amp": 1, "tau": t1, "base": 0}) exp_data = exp.run(backend, shots=10000, seed_simulator=1) self.assertExperimentDone(exp_data) self.assertRoundTripSerializable(exp_data) self.assertRoundTripPickle(exp_data) res = exp_data.analysis_results("T1") self.assertEqual(res.quality, "good") self.assertAlmostEqual(res.value.n, t1, delta=3) self.assertEqual(res.extra["unit"], "s") def test_t1_measurement_level_1(self): """ Test T1 experiment using a simulator. """ ns = 1e-9 mu = 1e-6 t1 = 45 * mu # delays delays = np.logspace(1, 11, num=23, base=np.exp(1)) delays *= ns delays = np.insert(delays, 0, 0) delays = np.append(delays, [t1 * 3]) num_shots = 4096 backend = MockIQBackend( MockIQT1Helper( t1=t1, iq_cluster_centers=[((-5.0, -4.0), (-5.0, 4.0)), ((3.0, 1.0), (5.0, -3.0))], iq_cluster_width=[1.0, 2.0], ) ) # Experiment initialization and analysis options exp0 = T1([0], delays) exp0.analysis = T1KerneledAnalysis() exp0.analysis.set_options(p0={"amp": 1, "tau": t1, "base": 0}) expdata0 = exp0.run( backend=backend, meas_return="avg", meas_level=MeasLevel.KERNELED, shots=num_shots, ) self.assertExperimentDone(expdata0) self.assertRoundTripSerializable(expdata0) self.assertRoundTripPickle(expdata0) res = expdata0.analysis_results("T1") self.assertEqual(res.quality, "good") self.assertAlmostEqual(res.value.n, t1, delta=3) self.assertEqual(res.extra["unit"], "s") def test_t1_parallel(self): """ Test parallel experiments of T1 using a simulator. """ t1 = [25, 20, 15] t2 = [value / 2 for value in t1] delays = list(range(1, 40, 3)) qubit0 = 0 qubit2 = 2 quantum_bit = [qubit0, qubit2] backend = NoisyDelayAerBackend(t1, t2) exp0 = T1(physical_qubits=[qubit0], delays=delays) exp2 = T1(physical_qubits=[qubit2], delays=delays) par_exp = ParallelExperiment([exp0, exp2], flatten_results=False) res = par_exp.run(backend=backend, shots=10000, seed_simulator=1) self.assertExperimentDone(res) for i, qb in enumerate(quantum_bit): sub_res = res.child_data(i).analysis_results("T1") self.assertEqual(sub_res.quality, "good") self.assertAlmostEqual(sub_res.value.n, t1[qb], delta=3) def test_t1_parallel_measurement_level_1(self): """ Test parallel experiments of T1 using a simulator. """ ns = 1e-9 mu = 1e-6 t1s = [25 * mu, 20 * mu] qubits = [0, 1] num_shots = 4096 # Delays delays = np.logspace(1, 11, num=23, base=np.exp(1)) delays *= ns delays = np.insert(delays, 0, 0) delays = np.append(delays, [t1s[0] * 3]) par_exp_list = [] exp_helpers = [] for qidx, t1 in zip(qubits, t1s): # Experiment exp = T1(physical_qubits=[qidx], delays=delays) exp.analysis = T1KerneledAnalysis() par_exp_list.append(exp) # Helper helper = MockIQT1Helper( t1=t1, iq_cluster_centers=[ ((-5.0, -4.0), (-5.0, 4.0)), ((-1.0, -1.0), (1.0, 1.0)), ((4.0, 1.0), (6.0, -3.0)), ], iq_cluster_width=[1.0, 2.0, 1.0], ) exp_helpers.append(helper) par_exp = ParallelExperiment( par_exp_list, flatten_results=False, ) par_helper = MockIQParallelExperimentHelper( exp_list=par_exp_list, exp_helper_list=exp_helpers, ) # Backend backend = MockIQParallelBackend(par_helper, rng_seed=1) # Running experiment res = par_exp.run( backend=backend, shots=num_shots, rng_seed=1, meas_level=MeasLevel.KERNELED, meas_return="avg", ) self.assertExperimentDone(res) # Checking analysis for i, t1 in enumerate(t1s): sub_res = res.child_data(i).analysis_results("T1") self.assertEqual(sub_res.quality, "good") self.assertAlmostEqual(sub_res.value.n, t1, delta=3) def test_t1_analysis(self): """ Test T1Analysis """ data = ExperimentData() data.metadata.update({"meas_level": 2}) numbers = [750, 1800, 2750, 3550, 4250, 4850, 5450, 5900, 6400, 6800, 7000, 7350, 7700] for i, count0 in enumerate(numbers): data.add_data( { "counts": {"0": count0, "1": 10000 - count0}, "metadata": {"xval": (3 * i + 1) * 1e-9}, } ) experiment_data = T1Analysis().run(data, plot=False) result = experiment_data.analysis_results("T1") self.assertEqual(result.quality, "good") self.assertAlmostEqual(result.value.nominal_value, 25e-9, delta=3) def test_t1_metadata(self): """ Test the circuits metadata """ delays = np.arange(1e-3, 40e-3, 3e-3) exp = T1([0], delays) circs = exp.circuits() self.assertEqual(len(circs), len(delays)) for delay, circ in zip(delays, circs): # xval is rounded to nealest granularity value. self.assertAlmostEqual(circ.metadata["xval"], delay) def test_t1_low_quality(self): """ A test where the fit's quality will be low """ data = ExperimentData() data.metadata.update({"meas_level": 2}) for i in range(10): data.add_data( { "counts": {"0": 10, "1": 10}, "metadata": {"xval": i * 1e-9}, } ) experiment_data = T1Analysis().run(data, plot=False) result = experiment_data.analysis_results("T1") self.assertEqual(result.quality, "bad") def test_t1_parallel_exp_transpile(self): """Test parallel transpile options for T1 experiment""" num_qubits = 5 instruction_durations = [] for i in range(num_qubits): instruction_durations += [ ("rx", [i], (i + 1) * 10, "ns"), ("measure", [i], (i + 1) * 1000, "ns"), ] coupling_map = [[i - 1, i] for i in range(1, num_qubits)] basis_gates = ["rx", "delay"] exp1 = T1([1], delays=[50e-9, 100e-9, 160e-9]) exp2 = T1([3], delays=[40e-9, 80e-9, 190e-9]) parexp = ParallelExperiment([exp1, exp2], flatten_results=False) parexp.set_transpile_options( basis_gates=basis_gates, instruction_durations=instruction_durations, coupling_map=coupling_map, scheduling_method="alap", ) circs = parexp.circuits() for circ in circs: self.assertEqual(circ.num_qubits, 2) op_counts = circ.count_ops() self.assertEqual(op_counts.get("rx"), 2) self.assertEqual(op_counts.get("delay"), 2) tcircs = parexp._transpiled_circuits() for circ in tcircs: self.assertEqual(circ.num_qubits, num_qubits) op_counts = circ.count_ops() self.assertEqual(op_counts.get("rx"), 2) self.assertEqual(op_counts.get("delay"), 2) def test_experiment_config(self): """Test converting to and from config works""" exp = T1([0], [1, 2, 3, 4, 5]) loaded_exp = T1.from_config(exp.config()) self.assertNotEqual(exp, loaded_exp) self.assertEqualExtended(exp, loaded_exp) def test_roundtrip_serializable(self): """Test round trip JSON serialization""" exp = T1([0], [1, 2]) self.assertRoundTripSerializable(exp) def test_circuit_roundtrip_serializable(self): """Test circuit round trip JSON serialization""" exp = T1([0], [1, 2, 3, 4, 5]) self.assertRoundTripSerializable(exp._transpiled_circuits()) def test_analysis_config(self): """ "Test converting analysis to and from config works""" analysis = T1Analysis() loaded = T1Analysis.from_config(analysis.config()) self.assertNotEqual(analysis, loaded) self.assertEqual(analysis.config(), loaded.config()) def test_circuits_with_backend(self): """ Test the circuits metadata when passing backend """ backend = FakeAthensV2() delays = np.arange(1e-3, 40e-3, 3e-3) exp = T1([0], delays, backend=backend) circs = exp.circuits() self.assertEqual(len(circs), len(delays)) for delay, circ in zip(delays, circs): # xval is rounded to nealest granularity value. self.assertAlmostEqual(circ.metadata["xval"], delay)
qiskit-experiments/test/library/characterization/test_t1.py/0
{ "file_path": "qiskit-experiments/test/library/characterization/test_t1.py", "repo_id": "qiskit-experiments", "token_count": 5268 }
118
# This code is part of Qiskit. # # (C) Copyright IBM 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. """ Common methods for tomography tests """ import numpy as np from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit_aer.noise import NoiseModel FITTERS = [ None, "linear_inversion", "cvxpy_linear_lstsq", "cvxpy_gaussian_lstsq", ] def filter_results(analysis_results, name): """Filter list of analysis results by result name""" for result in analysis_results: if result.name == name: return result return None def teleport_circuit(flatten_creg=True): """Teleport qubit 0 to qubit 2""" if flatten_creg: teleport = QuantumCircuit(3, 2) creg = teleport.cregs[0] else: qr = QuantumRegister(3) c0 = ClassicalRegister(1, "c0") c1 = ClassicalRegister(1, "c1") teleport = QuantumCircuit(qr, c0, c1) creg = [c0, c1] teleport.h(1) teleport.cx(1, 2) teleport.cx(0, 1) teleport.h(0) teleport.measure(0, creg[0]) teleport.measure(1, creg[1]) # Conditionals teleport.z(2).c_if(creg[0], 1) teleport.x(2).c_if(creg[1], 1) return teleport def teleport_bell_circuit(flatten_creg=True): """Teleport entangled qubit 0 -> 2""" if flatten_creg: teleport = QuantumCircuit(4, 2) creg = teleport.cregs[0] else: qr = QuantumRegister(4) c0 = ClassicalRegister(1) c1 = ClassicalRegister(1) teleport = QuantumCircuit(qr, c0, c1) creg = [c0, c1] teleport.h(0) teleport.cx(0, 3) teleport.h(1) teleport.cx(1, 2) teleport.cx(0, 1) teleport.h(0) teleport.measure(0, creg[0]) teleport.measure(1, creg[1]) teleport.z(2).c_if(creg[0], 1) teleport.x(2).c_if(creg[1], 1) return teleport def readout_noise_model(num_qubits, seed=None): """Generate noise model of random local readout errors""" rng = np.random.default_rng(seed=seed) p1g0s = 0.15 * rng.random(num_qubits) p0g1s = 0.3 * rng.random(num_qubits) amats = np.stack([[1 - p1g0s, p1g0s], [p0g1s, 1 - p0g1s]]).T noise_model = NoiseModel() for i, amat in enumerate(amats): noise_model.add_readout_error(amat.T, [i]) return noise_model
qiskit-experiments/test/library/tomography/tomo_utils.py/0
{ "file_path": "qiskit-experiments/test/library/tomography/tomo_utils.py", "repo_id": "qiskit-experiments", "token_count": 1151 }
119
aa ab acb acknowledgment adjoint aer aij al alanine allclose alzheimer amino aminoacid aminoacids ancilla ancillas ang anharmonic annihilation ansatz ansatze ansätze ansatzes anticommutation antiparallel antisymmetric antisymmetrized ao april arg arginine args arrowheads arrowstyle arxiv asarray asdict asparagine aspartic atol attr autosummary avogadro äquivalenzverbot bac backend backends barkoutsos bb bergholm berlin bitstring bksf bo bogoliubov bohr boltzmann bool boolean bools bopes boson bosons bosonic bosonicop bravais bravyi calcinfo cargs cartesian cbit ccx cdots cfg chc chiral chirality chkfile cholesky chuang ci classmethod clbit clbits clifford cliffords cls cmap cnot codec codeowners coeff coeffs colormap commutativities commutativity computable conda conf config connectionstyle coord coords coul cp creg crx crz csc cswap csx ctrl currentmodule cvar cx cy cysteine cz das dataclass dataclasses dataset dcx de debye deepcopy delocalized deuterium deuteron dft diag diagonalization diagonalize diagonalizes diagonalizing dicts dimens dimensionality dirac discoverable distanceunit distinguishability dll docstring dof doi dok downarrow dt dtype dumitrescu ecp ecr eigen eigenfunctions eigensolution eigensolver eigensolverfactory eigensolvers eigenstate eigenstateresult eigenstates eigenvector eigenvectors einact einsum electronicintegrals electronicstructureproblem endian endianness endif enum eom eq eri et eta eugene excitations extrapolator extrapolator's extrapolators facs fcidump fcompiler fermi fermion fermionic fermionicop fermions feynman filename fmt fock formatter fortran fp fredkin func functionalities für gauopen gaussian gaussiand gcc gcxs getitem getter gfortran github globals glutamic glutamine glycine gss gto hamiltonian hamiltonians hardcoded hartree hartrees hcore hdf heidelberg heisenberg helgaker hermite hermitian hermiticity hijkls hijs hilbert histidine hjo hsplit hstack html https hubbard ia iajb ifdef ifortvars ij ijkl ijlk ik iklj il init initializer initio inplace integrations intel intelvem interatomic internuclear interoperability interpretable ints io ipynb isclose ising iso isoleucine isometry isospectral iswap isym iten iter iterable iteratively itertools ivano iz james jb jcf jcp jernigan ji jk jl jordan jørgensen josé json jupyter jw kagome kanav ket kitaev knowles kohn kron kronecker kwarg kwargs kwds labelled langle lbl lbrace lda ldots leighton len leucine levinthal lexicographically libifcoremd libor libxc lih lijh linewidths linux listordict listordicttype ljik lk logfile lookback lvert lysine macos majorana majoranaop makefile matmul matplotlib maxdepth maxiter maxiters mazzola mcp mcrx mcry mcrz mct mcu mcx mentorship metadata meth methionine microsoft miessen minao mixin miyazawa moc mohij mohijkl mol moller molssi morse mpl mul multi multigraph multinomial mypy møller namelist nan nannichini nao natom nbasis nd ndarray ndim nelec neq networkx neuropeptide neutron nicholas nielsen nisq nmodes noancilla noint nonlocal norb norbs nosignatures np npj ns nucleus num numpy numpyeigensolver observables occupancies ok ollitrault onboarding onee oneeints onsite onwards opflow oppenheimer optimizers orbsym ortho orthonormal otimes outpath overline ovlp pac param parameterized params pauli paulis paulische pca peptide performant perturbative pes phenylalanine phonons physik physrevd plesset pmatrix polynomialtensor polypeptides popovas pos posteriori pqrs pre prebuilt prefactor prepend prepended preprint preprocesses proline protium proton prsq ps pseudorandom pxd py pydata pyquante pyright pyscf qarg qargs qasm qbit qc qcbase qcmatrixio qcschema qeom qfi qiskit qiskit's qj qmolecule qn qregs qs quantization quantized quantumcircuit quartic qubit qubitmapper qubits qutrit radians rangle rcccx rccx rdm readme readthedocs realise rebranding refactor refactored refactoring regs reinstall repr retworkx rgb rgba rhf rhs rk robert rohf rossmannek rtol rtype runtime rustworkx rv rx rxx ry ryy rz rzx rzz scalable scf schroedinger schrödinger schur scikit scipy sd sdg sdt serine setia setted shende siddhartha sklearn sl slater soham somma sp sparsearray sparselabelop sparsepauliop spinop springer spsa squ statevector statevectors stderr stdlib stdout stereochemistry sto stober str stylesheet subcircuits subclasses submatrix submatrices submodule submodules subtest subtype succ sudo superfast superpositions sx sxdg symm sys sysctl tavernelli taylor tb tdg tcoeff tensored tensoring terra th thermostabilization theta threonine timestamp toctree toffoli tol tos traceback tran translational transpilation transpile trotterization tryptophan tuple tuples twoe twoeints tyrosine uc ucc uccd uccs uccsd ucrx ucry ucrz ufuncs uhf ulimit un unary uncompiled undirected unitaries unitstype untransforms uparrow username utils uvcc über valine vals varepsilon variational vdots vec verbatim versa vibrational vibrationalop vibrationalops vibro vienna vmax vmin vqe vscf vsplit vstack vwn vx vy vz watson wavefunction whitespace whitfield wigner wikipedia woerner workflow xcf xcfun xdata xy xyz ydata yx yy zeitschrift zi zmatrix zsh zz
qiskit-nature/.pylintdict/0
{ "file_path": "qiskit-nature/.pylintdict", "repo_id": "qiskit-nature", "token_count": 2263 }
120
.. _qiskit_nature-second_q-formats-fcidump: .. automodule:: qiskit_nature.second_q.formats.fcidump :no-members: :no-inherited-members: :no-special-members:
qiskit-nature/docs/apidocs/qiskit_nature.second_q.formats.fcidump.rst/0
{ "file_path": "qiskit-nature/docs/apidocs/qiskit_nature.second_q.formats.fcidump.rst", "repo_id": "qiskit-nature", "token_count": 76 }
121
.. _qiskit_nature-settings: .. automodule:: qiskit_nature.settings .. rubric:: Classes .. autosummary:: QiskitNatureSettings
qiskit-nature/docs/apidocs/qiskit_nature.settings.rst/0
{ "file_path": "qiskit-nature/docs/apidocs/qiskit_nature.settings.rst", "repo_id": "qiskit-nature", "token_count": 55 }
122
Solving Problems with v0.5 ========================== Overview ~~~~~~~~ The major focus of the Qiskit Nature v0.5 refactoring was the description and representation of second-quantized operators and problems. Nonetheless, the ``algorithms`` module and supporting modules did also receive significant updates. Most importantly all algorithms In Nature are now dependent on the new Qiskit Terra algorithms, and these are now based on `Qiskit Primitives <https://docs.quantum.ibm.com/run/primitives>`__ and were added in Qiskit Terra 0.22. It is not the intention to provide detailed explanations of the primitives in this migration guide. We suggest that you read the `corresponding resources <https://docs.quantum.ibm.com/api/qiskit/primitives>`__ of the Qiskit Terra documentation instead. Further Resources ~~~~~~~~~~~~~~~~~ For more details, please refer to the corresponding tutorials: - `Ground State Solvers <../tutorials/03_ground_state_solvers.ipynb>`__ - `Excited States Solvers <../tutorials/04_excited_states_solvers.ipynb>`__ - `Qubit Mappers <../tutorials/06_qubit_mappers.ipynb>`__ ``qiskit_nature.mappers`` ========================= The mappers of Qiskit Nature did **not** receive any API changes (other than potentially requiring certain arguments to be keywords; see also the `“Too many positional arguments” section <./0.5_a_intro.ipynb>`__). However, the entire module ``qiskit_nature.mappers.second_quantization`` has been moved to ``qiskit_nature.second_q.mappers``. So updating your import is all you need to do here. ``qiskit_nature.converters`` ============================ This module contained a single component: ``QubitConverter``. This has been moved to ``qiskit_nature.second_q.mappers.QubitConverter`` so you can simply update your import path. API changes were again minimal but the operators being translated by this class are no longer the legacy ``SecondQuantizedOp`` but rather the new ``SparseLabelOp`` objects. ``qiskit_nature.circuit`` ========================= The entire ``qiskit_nature.circuit`` module was relocated to ``qiskit_nature.second_q.circuit``. The reason for this, is that the existing circuit were actually only applicable to second-quantized applications, but the API did not reflect this. Updating your imports should fix *most* issues. However, there are two more details to take note of, detailed below. Number of Orbitals ~~~~~~~~~~~~~~~~~~ We have been consistently describing the number of orbitals via ``num_spin_orbitals`` throughout the package. However, what this oftentimes implied (without rigorous checks) was that an **even** number was supplied, since the number of spin orbitals was assumed to equal twice the number of **spatial** orbitals. To be more rigorous and avoid the ill-defined behavior when providing *odd* numbers for ``num_spin_orbitals``, we have switched the entire stack to use ``num_spatial_orbitals`` instead. This is well defined for any positive integer value (and negative values are guarded against). What this means for you in practice, is that whenever you supply the ``num_spin_orbitals`` manually in the past, you now need to supply **half the value** to represent the ``num_spatial_orbitals``. Previously ^^^^^^^^^^ .. code:: ipython3 from qiskit_nature.circuit.library import UCCSD ansatz = UCCSD() ansatz.num_spin_orbitals = 10 New ^^^ .. code:: ipython3 from qiskit_nature.second_q.circuit.library import UCCSD ansatz = UCCSD() ansatz.num_spatial_orbitals = 5 UCC/UVCC ``__init__`` arguments ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The ``UCC`` and ``UVCC`` subclasses used to take the following arguments for their ``__init__``: Previously ^^^^^^^^^^ .. code:: ipython3 from qiskit_nature.circuit.library import UCC, UVCC ucc = UCC(qubit_converter=None, num_particles=None, num_spin_orbitals=None, excitations=None) uvcc = UVCC(qubit_converter=None, num_modals=None, excitations=None) New ^^^ This was mismatching the API of the ``HartreeFock`` and ``VSCF`` initial states. We have aligned these APIs to look like in the following: .. code:: ipython3 from qiskit_nature.second_q.circuit.library import UCC, UVCC ucc = UCC(num_spatial_orbitals=None, num_particles=None, excitations=None, qubit_converter=None) uvcc = UVCC(num_modals=None, excitations=None, qubit_converter=None) HartreeFock/VSCF initial states ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The ``HartreeFock`` and ``VSCF`` initial state circuits are now implemented as ``BlueprintCircuit``. That means, that you can initialize them without any arguments and supply the information later as shown below: Previously ^^^^^^^^^^ .. code:: ipython3 from qiskit_nature.circuit.library import HartreeFock, VSCF from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import DirectMapper, JordanWignerMapper hf = HartreeFock( num_spin_orbitals=4, num_particles=(1, 1), qubit_converter=QubitConverter(JordanWignerMapper()) ) vscf = VSCF(num_modals=[2, 2]) New ^^^ .. code:: ipython3 from qiskit_nature.second_q.circuit.library import HartreeFock, VSCF from qiskit_nature.second_q.mappers import DirectMapper, JordanWignerMapper, QubitConverter hf = HartreeFock() hf.num_spatial_orbitals = 2 hf.num_particles = (1, 1) hf.qubit_converter = QubitConverter(JordanWignerMapper()) vscf = VSCF() vscf.num_modals = [2, 2] ``qiskit_nature.algorithms`` ============================ The algorithms in Qiskit Nature have been updated to use the new ``qiskit.algorithms`` components which are based on the ``qiskit.primitives`` as of Qiskit Terra 0.22. For most changes to take effect, you can once again simply update your import paths from ``qiskit_nature.algorithms`` to ``qiskit_nature.second_q.algorithms``. However, there are some details which you need to pay attention to, due to the change to the primitive-based algorithms of Qiskit Terra being used under the hood. These details are explained below. ``qiskit_nature.algorithms.initial_points`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This module was moved to ``qiskit_nature.second_q.algorithms.initial_points``. All you need to do is update your imports. ``qiskit_nature.algorithms.pes_samplers`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This module was **removed** without a replacement. The reason for that, is that we are working towards a driver-less design of Qiskit Nature, in which case the sampling of the potential energy surface becomes the responsibility of the classical code rather than Qiskit Nature. ``qiskit_nature.algorithms.ground_state_solvers`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This module was moved to ``qiskit_nature.second_q.algorithms.ground_state_solvers``. Besides updating your imports, you need to pay attention to the following: - ``AdaptVQE`` was migrated to Qiskit Terra: ``qiskit.algorithms.minimum_eigensolver.AdaptVQE``. In doing so, this is no longer a ``GroundStateSolver`` but rather became a ``MinimumEigensolver`` which means that you would use it like any other ``VQE`` and inject it **into** a ``GroundStateSolver`` of Qiskit Nature. To see the new ``AdaptVQE`` in action, check out the `How to use the AdaptVQE <../howtos/adapt_vqe.rst>`__. - the API of the ``VQEUCCFactory`` and ``VQEUVCCFactory`` has been matched with the new primitive-based ``VQE`` API Previously ^^^^^^^^^^ .. code:: ipython3 from qiskit.providers.basicaer import BasicAer from qiskit.utils import QuantumInstance from qiskit_nature.algorithms.ground_state_solvers import VQEUCCFactory quantum_instance = QuantumInstance(BasicAer.get_backend("statevector_simulator")) vqe_factory = VQEUCCFactory(quantum_instance=quantum_instance) New ^^^ .. code:: ipython3 from qiskit.algorithms.optimizers import SLSQP from qiskit.primitives import Estimator from qiskit_nature.second_q.circuit.library import UCCSD from qiskit_nature.second_q.algorithms.ground_state_solvers import VQEUCCFactory estimator = Estimator() ansatz = UCCSD() optimizer = SLSQP() vqe_factory = VQEUCCFactory(estimator, ansatz, optimizer) ``qiskit_nature.algorithms.excited_states_solvers`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This module was moved to ``qiskit_nature.second_q.algorithms.excited_states_solvers``. Besides updating your imports, you need to pay attention to the following: - the ``QEOM`` API now also requires an `Estimator primitiver <https://docs.quantum.ibm.com/api/qiskit/qiskit.primitives.BaseEstimator>`__ to be provided Previously ^^^^^^^^^^ .. code:: ipython3 from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver, VQEUCCFactory from qiskit_nature.algorithms.excited_states_solvers import QEOM from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import JordanWignerMapper vqe_factory = VQEUCCFactory() converter = QubitConverter(JordanWignerMapper()) ground_state_solver = GroundStateEigensolver(converter, vqe_factory) qeom = QEOM(ground_state_solver) New ^^^ .. code:: ipython3 from qiskit.algorithms.optimizers import SLSQP from qiskit.primitives import Estimator from qiskit_nature.second_q.circuit.library import UCCSD from qiskit_nature.second_q.algorithms.ground_state_solvers import ( GroundStateEigensolver, VQEUCCFactory, ) from qiskit_nature.second_q.algorithms.excited_states_solvers import QEOM from qiskit_nature.second_q.mappers import JordanWignerMapper, QubitConverter estimator = Estimator() ansatz = UCCSD() optimizer = SLSQP() vqe_factory = VQEUCCFactory(estimator, ansatz, optimizer) converter = QubitConverter(JordanWignerMapper()) ground_state_solver = GroundStateEigensolver(converter, vqe_factory) qeom = QEOM(ground_state_solver, estimator)
qiskit-nature/docs/migration/0.5_b_solving_problems.rst/0
{ "file_path": "qiskit-nature/docs/migration/0.5_b_solving_problems.rst", "repo_id": "qiskit-nature", "token_count": 3290 }
123
<jupyter_start><jupyter_text>Excited states solvers IntroductionIn this tutorial we are going to discuss the excited states calculation interface of Qiskit Nature. The goal is to compute the excited states of a molecular Hamiltonian. This Hamiltonian can be electronic or vibrational. To know more about the preparation of the Hamiltonian, check out the [Electronic structure](01_electronic_structure.ipynb) and [Vibrational structure tutorials](02_vibrational_structure.ipynb).The first step is to define the molecular system. In the following we ask for the electronic part of a hydrogen molecule.<jupyter_code>from qiskit_nature.units import DistanceUnit from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver( atom="H 0 0 0; H 0 0 0.735", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) es_problem = driver.run()<jupyter_output><empty_output><jupyter_text>We will also be sticking to the Jordan-Wigner mapping. To learn more about the various mappers available in Qiskit Nature, check out the [Qubit Mappers tutorial](06_qubit_mappers.ipynb).<jupyter_code>from qiskit_nature.second_q.mappers import JordanWignerMapper mapper = JordanWignerMapper()<jupyter_output><empty_output><jupyter_text>The SolverAfter these steps we need to define a solver. The solver is the algorithm through which the excited states are computed. Let's first start with a purely classical example: the `NumPyEigensolver`. This algorithm exactly diagonalizes the Hamiltonian. Although it scales badly, it can be used on small systems to check the results of the quantum algorithms. Here, we are only interested to look at eigenstates with a given number of particles. To compute only those states a filter function can be passed to the `NumPyEigensolver`. A default filter function is already implemented in Qiskit Nature which you can use for this purpose.We also need to specify the number of eigenvalues to be computed by the `NumPyEigensolver`. For this particular system, we are interested in the ground and first three excited states, so we will set `k=4` (which defaults to 1 so be sure to set this, otherwise you will only obtain the ground state!).<jupyter_code>from qiskit_algorithms import NumPyEigensolver numpy_solver = NumPyEigensolver(k=4, filter_criterion=es_problem.get_default_filter_criterion())<jupyter_output><empty_output><jupyter_text>The excitation energies can also be accessed with the [qEOM algorithm](https://journals.aps.org/prresearch/abstract/10.1103/PhysRevResearch.2.043140). The EOM method finds the excitation energies (differences in energy between the ground state and all $n$th excited states) by solving the following pseudo-eigenvalue problem.$$\begin{pmatrix} \text{M} & \text{Q}\\ \text{Q*} & \text{M*}\end{pmatrix}\begin{pmatrix} \text{X}_n\\ \text{Y}_n\end{pmatrix}= E_{0n}\begin{pmatrix} \text{V} & \text{W}\\ -\text{W*} & -\text{V*}\end{pmatrix}\begin{pmatrix} \text{X}_n\\ \text{Y}_n\end{pmatrix}$$with $$M_{\mu_{\alpha}\nu_{\beta}} = \langle0| [(\hat{\text{E}}_{\mu_{\alpha}}^{(\alpha)})^{\dagger},\hat{\text{H}}, \hat{\text{E}}_{\nu_{\beta}}^{(\beta)}]|0\rangle$$$$Q_{\mu_{\alpha}\nu_{\beta}} = -\langle0| [(\hat{\text{E}}_{\mu_{\alpha}}^{(\alpha)})^{\dagger}, \hat{\text{H}}, (\hat{\text{E}}_{\nu_{\beta}}^{(\beta)})^{\dagger}]|0\rangle$$$$V_{\mu_{\alpha}\nu_{\beta}} = \langle0| [(\hat{\text{E}}_{\mu_{\alpha}}^{(\alpha)})^{\dagger}, \hat{\text{E}}_{\nu_{\beta}}^{(\beta)}]|0\rangle$$$$W_{\mu_{\alpha}\nu_{\beta}} = -\langle0| [(\hat{\text{E}}_{\mu_\alpha}^{(\alpha)})^{\dagger}, (\hat{\text{E}}_{\nu_{\beta}}^{(\beta)})^{\dagger}]|0\rangle$$Although the previous equation can be solved classically, each matrix element must be measured on the quantum computer with the corresponding ground state. To use the qEOM as a solver in Qiskit, we have to define a ground state calculation first, which will provide the required ground state information to the algorithm. With this the qEOM solver can be initialized like so:<jupyter_code>from qiskit_algorithms import VQE from qiskit_algorithms.optimizers import SLSQP from qiskit.primitives import Estimator from qiskit_nature.second_q.algorithms import GroundStateEigensolver, QEOM, EvaluationRule from qiskit_nature.second_q.circuit.library import HartreeFock, UCCSD ansatz = UCCSD( es_problem.num_spatial_orbitals, es_problem.num_particles, mapper, initial_state=HartreeFock( es_problem.num_spatial_orbitals, es_problem.num_particles, mapper, ), ) estimator = Estimator() # This first part sets the ground state solver # see more about this part in the ground state calculation tutorial solver = VQE(estimator, ansatz, SLSQP()) solver.initial_point = [0.0] * ansatz.num_parameters gse = GroundStateEigensolver(mapper, solver) # The qEOM algorithm is simply instantiated with the chosen ground state solver and Estimator primitive qeom_excited_states_solver = QEOM(gse, estimator, "sd", EvaluationRule.ALL)<jupyter_output><empty_output><jupyter_text>The calculation and resultsWe are now ready to compute the results. Below, we are comparing the results obtained by the exact `NumPyEigensolver` with the default filter criterion enabled with the results obtained by the qEOM algorithm.<jupyter_code>from qiskit_nature.second_q.algorithms import ExcitedStatesEigensolver numpy_excited_states_solver = ExcitedStatesEigensolver(mapper, numpy_solver) numpy_results = numpy_excited_states_solver.solve(es_problem) qeom_results = qeom_excited_states_solver.solve(es_problem) print(numpy_results) print("\n\n") print(qeom_results)<jupyter_output>=== GROUND STATE ENERGY === * Electronic ground state energy (Hartree): -1.857275030202 - computed part: -1.857275030202 ~ Nuclear repulsion energy (Hartree): 0.719968994449 > Total ground state energy (Hartree): -1.137306035753 === EXCITED STATE ENERGIES === 1: * Electronic excited state energy (Hartree): -0.882722150245 > Total excited state energy (Hartree): -0.162753155796 2: * Electronic excited state energy (Hartree): -0.224911252831 > Total excited state energy (Hartree): 0.495057741618 === MEASURED OBSERVABLES === 0: # Particles: 2.000 S: 0.000 S^2: 0.000 M: 0.000 1: # Particles: 2.000 S: 0.000 S^2: 0.000 M: 0.000 2: # Particles: 2.000 S: 0.000 S^2: 0.000 M: 0.000 === DIPOLE MOMENTS === ~ Nuclear dipole moment (a.u.): [0.0 0.0 1.3889487] 0: * Electronic dipole moment (a.u.): [0.0 0.0 1.388948701555] - computed part: [0.0 0.0 1.388948701555] > Dipole moment (a.u.): [0.0 0.0 -0.000000001555] Total: 0.000000001555 [...]<jupyter_text>One can see from these results that one state is missing from the NumPy results. The reason for this is because the spin is also used as a filter and only singlet states are shown. In the following we use a custom filter function to check our results consistently and only filter out states with the incorrect number of particles (in this case the number of particle is 2) as well as the wrong magnetization (which we enforce to be 0).<jupyter_code>import numpy as np def filter_criterion(eigenstate, eigenvalue, aux_values): return np.isclose(aux_values["ParticleNumber"][0], 2.0) and np.isclose( aux_values["Magnetization"][0], 0.0 ) new_numpy_solver = NumPyEigensolver(k=4, filter_criterion=filter_criterion) new_numpy_excited_states_solver = ExcitedStatesEigensolver(mapper, new_numpy_solver) new_numpy_results = new_numpy_excited_states_solver.solve(es_problem) print(new_numpy_results) import tutorial_magics %qiskit_version_table %qiskit_copyright<jupyter_output><empty_output>
qiskit-nature/docs/tutorials/04_excited_states_solvers.ipynb/0
{ "file_path": "qiskit-nature/docs/tutorials/04_excited_states_solvers.ipynb", "repo_id": "qiskit-nature", "token_count": 2647 }
124
[mypy] warn_unused_configs = True ignore_missing_imports = True strict_optional = False no_implicit_optional = True warn_redundant_casts = True warn_unused_ignores = True ### Output show_error_codes = True show_error_context = True
qiskit-nature/mypy.ini/0
{ "file_path": "qiskit-nature/mypy.ini", "repo_id": "qiskit-nature", "token_count": 80 }
125
# This code is part of a Qiskit project. # # (C) Copyright IBM 2021, 2024. # # 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. """Utility methods to build vibrational hopping operators.""" from __future__ import annotations from typing import Callable from qiskit.quantum_info import SparsePauliOp from qiskit_nature.second_q.circuit.library import UVCC from qiskit_nature.second_q.operators import VibrationalOp from qiskit_nature.second_q.mappers import QubitMapper, TaperedQubitMapper from qiskit_nature.utils import _parallel_map def build_vibrational_ops( num_modals: list[int], excitations: ( str | int | list[int] | Callable[ [int, tuple[int, int]], list[tuple[tuple[int, ...], tuple[int, ...]]], ] ), qubit_mapper: QubitMapper, ) -> tuple[ dict[str, SparsePauliOp], dict[str, list[bool]], dict[str, tuple[tuple[int, ...], tuple[int, ...]]], ]: # pylint: disable=unused-argument """ Args: num_modals: The number of modals per mode. excitations: The types of excitations to consider. The simple cases for this input are: - a `str` containing any of the following characters: `s`, `d`, `t` or `q`. - a single, positive `int` denoting the excitation type (1 == `s`, etc.). - a list of positive integers. - and finally a callable which can be used to specify a custom list of excitations. For more details on how to write such a function refer to the default method, :meth:`generate_vibrational_excitations`. qubit_mapper: The ``QubitMapper`` to use for mapping. Returns: Dict of hopping operators, dict of commutativity types and dict of excitation indices. """ ansatz = UVCC(num_modals, excitations, qubit_mapper) excitations_list = ansatz._get_excitation_list() size = len(excitations_list) hopping_operators: dict[str, SparsePauliOp] = {} excitation_indices: dict[str, tuple[tuple[int, ...], tuple[int, ...]]] = {} to_be_executed_list = [] for idx in range(size): to_be_executed_list += [excitations_list[idx], excitations_list[idx][::-1]] hopping_operators[f"E_{idx}"] = None hopping_operators[f"Edag_{idx}"] = None excitation_indices[f"E_{idx}"] = excitations_list[idx] excitation_indices[f"Edag_{idx}"] = excitations_list[idx][::-1] result = _parallel_map( _build_single_hopping_operator, to_be_executed_list, task_args=(num_modals, qubit_mapper), ) for key, res in zip(hopping_operators.keys(), result): hopping_operators[key] = res # This variable is required for compatibility with the ElectronicStructureProblem # at the moment we do not have any type of commutativity in the bosonic case. type_of_commutativities: dict[str, list[bool]] = {} return hopping_operators, type_of_commutativities, excitation_indices def _build_single_hopping_operator( excitation: tuple[tuple[int, ...], tuple[int, ...]], num_modals: list[int], qubit_mapper: QubitMapper, ) -> SparsePauliOp: label = [] for occ in excitation[0]: label.append(f"+_{VibrationalOp.build_dual_index(num_modals, occ)}") for unocc in excitation[1]: label.append(f"-_{VibrationalOp.build_dual_index(num_modals, unocc)}") vibrational_op = VibrationalOp({" ".join(label): 1}, num_modals) qubit_op: SparsePauliOp if isinstance(qubit_mapper, TaperedQubitMapper): qubit_op = qubit_mapper.map_clifford(vibrational_op) else: qubit_op = qubit_mapper.map(vibrational_op) return qubit_op
qiskit-nature/qiskit_nature/second_q/algorithms/excited_states_solvers/qeom_vibrational_ops_builder.py/0
{ "file_path": "qiskit-nature/qiskit_nature/second_q/algorithms/excited_states_solvers/qeom_vibrational_ops_builder.py", "repo_id": "qiskit-nature", "token_count": 1599 }
126
# This code is part of a Qiskit project. # # (C) Copyright IBM 2021, 2024. # # 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. """ The Unitary Coupled-Cluster Ansatz. """ from __future__ import annotations import logging from functools import partial from itertools import chain from typing import Callable, Sequence from qiskit.circuit import QuantumCircuit from qiskit.circuit.library import EvolvedOperatorAnsatz from qiskit_nature import QiskitNatureError from qiskit_nature.second_q.mappers import QubitMapper, TaperedQubitMapper from qiskit_nature.second_q.operators import FermionicOp, SparseLabelOp from .utils.fermionic_excitation_generator import generate_fermionic_excitations logger = logging.getLogger(__name__) class UCC(EvolvedOperatorAnsatz): r"""The Unitary Coupled-Cluster Ansatz. For more information, see [1]. This ansatz is an ``EvolvedOperatorAnsatz`` given by :math:`e^{T - T^{\dagger}}` where :math:`T` is the *cluster operator*. This cluster operator generally consists of excitation operators which are generated by :meth:`~qiskit_nature.second_q.circuit.library.ansatzes.utils.generate_fermionic_excitations`. This method constructs the requested excitations based on a :class:`~qiskit_nature.second_q.circuit.library.HartreeFock` reference state by default. When setting up a ``VQE`` algorithm using this ansatz and initial state, it is likely you will also want to use a :class:`~qiskit_nature.second_q.algorithms.initial_points.HFInitialPoint` that has been configured using the corresponding ansatz parameters. This can be done as follows: .. code-block:: python qubit_mapper = JordanWignerMapper() ucc = UCC(4, (2, 2), 'sd', qubit_mapper) hf_initial_point = HFInitialPoint() hf_initial_point.ansatz = ucc initial_point = hf_initial_point.to_numpy_array() vqe = VQE(Estimator(), ucc, SLSQP(), initial_point=initial_point) You can also use a custom excitation generator method by passing a callable to ``excitations``. A utility class :class:`UCCSD` exists, which is equivalent to: .. code-block:: python uccsd = UCC(excitations='sd', alpha_spin=True, beta_spin=True, max_spin_excitation=None) If you want to use a tailored ansatz, you have multiple options to do so. Below, we provide some examples: .. code-block:: python # pure single excitations (equivalent options): uccs = UCC(excitations='s') uccs = UCC(excitations=1) uccs = UCC(excitations=[1]) # pure double excitations (equivalent options): uccd = UCC(excitations='d') uccd = UCC(excitations=2) uccd = UCC(excitations=[2]) # combinations of excitations: custom_ucc_sd = UCC(excitations='sd') # see also the convenience sub-class UCCSD custom_ucc_sd = UCC(excitations=[1, 2]) # see also the convenience sub-class UCCSD custom_ucc_sdt = UCC(excitations='sdt') custom_ucc_sdt = UCC(excitations=[1, 2, 3]) custom_ucc_st = UCC(excitations='st') custom_ucc_st = UCC(excitations=[1, 3]) # you can even define a fully custom list of excitations: def custom_excitation_list(num_spatial_orbitals: int, num_particles: tuple[int, int] ) -> list[tuple[tuple[Any, ...], ...]]: # generate your list of excitations... my_excitation_list = [...] # For more information about the required format of the return statement, please take a # look at the documentation of # `qiskit_nature.second_q.circuit.library.ansatzes.utils.fermionic_excitation_generator` return my_excitation_list my_custom_ucc = UCC(excitations=custom_excitation_list) Keep in mind, that in all of the examples above we have not set any of the following keyword arguments, which must be specified before the ansatz becomes usable: - ``qubit_mapper`` - ``num_particles`` - ``num_spatial_orbitals`` If you are using this ansatz with a Qiskit Nature algorithm, these arguments will be set for you, depending on the rest of the stack. References: [1] `arXiv:1805.04340 <https://arxiv.org/abs/1805.04340>`_ """ _EXCITATION_TYPE = { "s": 1, "d": 2, "t": 3, "q": 4, } def __init__( self, num_spatial_orbitals: int | None = None, num_particles: tuple[int, int] | None = None, excitations: ( str | int | list[int] | Callable[ [int, tuple[int, int]], list[tuple[tuple[int, ...], tuple[int, ...]]], ] | None ) = None, qubit_mapper: QubitMapper | None = None, *, alpha_spin: bool = True, beta_spin: bool = True, max_spin_excitation: int | None = None, generalized: bool = False, preserve_spin: bool = True, include_imaginary: bool = False, reps: int = 1, initial_state: QuantumCircuit | None = None, ) -> None: # pylint: disable=unused-argument """ Args: num_spatial_orbitals: The number of spatial orbitals. num_particles: The tuple of the number of alpha- and beta-spin particles. excitations: This can be any of the following types: :`str`: Contains the types of excitations. Allowed characters are: ``'s'`` for singles, ``'d'`` for doubles, ``'t'`` for triples, and ``'q'`` for quadruples. :`int`: A single, positive integer which denotes the number of excitations (``1 == 's'``, ``2 == 'd'``, etc.) :`list[int]`: A list of positive integers generalizing the above to multiple numbers of excitations (``[1, 2] == 'sd'``, etc.) :`Callable`: A function which is used to generate the excitations. The callable must take the *keyword* arguments ``num_spatial_orbitals`` and ``num_particles`` (with identical types to those explained above) and must return a ``list[tuple[tuple[int, ...], tuple[int, ...]]]``. For more information on how to write such a callable refer to the default method :meth:`~qiskit_nature.second_q.circuit.library.ansatzes.utils.\ generate_fermionic_excitations`. qubit_mapper: The :class:`~qiskit_nature.second_q.mappers.QubitMapper` which takes care of mapping to a qubit operator. alpha_spin: Boolean flag whether to include alpha-spin excitations. beta_spin: Boolean flag whether to include beta-spin excitations. max_spin_excitation: The largest number of excitations within a spin. E.g. you can set this to 1 and ``num_excitations`` to 2 in order to obtain only mixed-spin double excitations (alpha,beta) but no pure-spin double excitations (alpha,alpha or beta,beta). generalized: Boolean flag whether or not to use generalized excitations, which ignore the occupation of the spin orbitals. As such, the set of generalized excitations is only determined from the number of spin orbitals and independent from the number of particles. preserve_spin: Boolean flag whether or not to preserve the particle spins. include_imaginary: Boolean flag which when set to ``True`` expands the ansatz to include imaginary parts using twice the number of free parameters. reps: The number of times to repeat the evolved operators. initial_state: A ``QuantumCircuit`` object to prepend to the circuit. Note that this setting does *not* influence the ``excitations``. When relying on the default generation method (i.e. not providing a ``Callable`` to ``excitations``), these will always be constructed with respect to a :class:`~qiskit_nature.second_q.circuit.library.HartreeFock` reference state. When setting up a ``VQE`` algorithm using this ansatz and initial state, it is likely you will also want to use a :class:`~qiskit_nature.second_q.algorithms.initial_points.HFInitialPoint` that has been configured using the corresponding ansatz parameters. """ self._qubit_mapper = qubit_mapper self._num_particles = num_particles self._num_spatial_orbitals = num_spatial_orbitals self._excitations = excitations self._alpha_spin = alpha_spin self._beta_spin = beta_spin self._max_spin_excitation = max_spin_excitation self._generalized = generalized self._preserve_spin = preserve_spin self._include_imaginary = include_imaginary super().__init__(reps=reps, initial_state=initial_state) # To give read access to the actual excitation list that UCC is using. self._excitation_list: list[tuple[tuple[int, ...], tuple[int, ...]]] | None = None # We cache these, because the generation may be quite expensive (depending on the generator) # and the user may want quick access to inspect these. Also, it speeds up testing for the # same reason! self._excitation_ops: list[SparseLabelOp] = None # Our parent, EvolvedOperatorAnsatz, sets qregs when it knows the # number of qubits, which it gets from the operators. Getting the # operators here will build them if configuration already allows. # This will allow the circuit to be fully built/valid when it's # possible at this stage. _ = self.operators @property def qubit_mapper(self) -> QubitMapper | None: """The qubit operator mapper.""" return self._qubit_mapper @qubit_mapper.setter def qubit_mapper(self, mapper: QubitMapper | None) -> None: """Sets the qubit operator mapper.""" self._operators = None self._invalidate() self._qubit_mapper = mapper @property def num_spatial_orbitals(self) -> int: """The number of spatial orbitals.""" return self._num_spatial_orbitals @num_spatial_orbitals.setter def num_spatial_orbitals(self, n: int) -> None: """Sets the number of spatial orbitals.""" self._operators = None self._invalidate() self._num_spatial_orbitals = n @property def num_particles(self) -> tuple[int, int]: """The number of particles.""" return self._num_particles @num_particles.setter def num_particles(self, n: tuple[int, int]) -> None: """Sets the number of particles.""" self._operators = None self._invalidate() self._num_particles = n @property def excitations(self) -> str | int | list[int] | Callable | None: """The excitations.""" return self._excitations @excitations.setter def excitations(self, exc: str | int | list[int] | Callable | None) -> None: """Sets the excitations.""" self._operators = None self._invalidate() self._excitations = exc @property def excitation_list(self) -> list[tuple[tuple[int, ...], tuple[int, ...]]] | None: """The excitation list that UCC is using. Raises: QiskitNatureError: If private the excitation list is ``None``. """ if self._excitation_list is None: # If the excitation_list is None build it out alongside the operators if the ucc config # checks out ok, otherwise it will be left as None to be built at some later time. _ = self.operators return self._excitation_list @EvolvedOperatorAnsatz.operators.getter def operators(self): # pylint: disable=invalid-overridden-method """The operators that are evolved in this circuit. Returns: list: The operators to be evolved contained in this ansatz or None if the configuration is not complete """ # Overriding the getter to build the operators on demand when they are # requested, if they are still set to None. operators = super(UCC, self.__class__).operators.__get__(self) if operators is None or operators == [None]: # If the operators are None build them out if the ucc config checks out ok, otherwise # they will be left as None to be built at some later time. if self._check_ucc_configuration(raise_on_failure=False): # The qubit operators are cached by `EvolvedOperatorAnsatz` class. We only generate # them from the `SparseLabelOp`s produced by the generators, if they're not # already present. This behavior also enables the adaptive usage of the `UCC` class # by algorithms such as `AdaptVQE`. excitation_ops = self.excitation_ops() logger.debug("Converting second-quantized into qubit operators...") # Convert operators according to saved state in mapper from the conversion of the # main operator since these need to be compatible. If Z2 Symmetry tapering was done # it may be that one or more excitation operators do not commute with the symmetry. # The converted operators are maintained at the same index by the mapper # inserting ``None`` as the result if an operator did not commute. To ensure that # the ``excitation_list`` is transformed identically to the operators, we retain # ``None`` for non-commuting operators in order to manually remove them in unison. if isinstance(self.qubit_mapper, TaperedQubitMapper): operators = self.qubit_mapper.map_clifford(excitation_ops) operators = self.qubit_mapper.taper_clifford(operators, suppress_none=False) else: operators = self.qubit_mapper.map(excitation_ops) if self._include_imaginary: # duplicate each excitation to account for the real and imaginary parts. self._excitation_list = list( chain(*zip(self._excitation_list, self._excitation_list)) ) self._filter_operators(operators=operators) return super(UCC, self.__class__).operators.__get__(self) def _filter_operators(self, operators): valid_operators, valid_excitations = [], [] for op, ex in zip(operators, self._excitation_list): if op is not None: valid_operators.append(op) valid_excitations.append(ex) self._excitation_list = valid_excitations self.operators = valid_operators def _invalidate(self): self._excitation_ops = None super()._invalidate() def _check_configuration(self, raise_on_failure: bool = True) -> bool: # Check our local config is valid first. The super class will check the # operators by getting them, and if we detect they are still None they # will be built so that its valid check will end up passing in that regard. if not self._check_ucc_configuration(raise_on_failure): return False return super()._check_configuration(raise_on_failure) # pylint: disable=too-many-return-statements def _check_ucc_configuration(self, raise_on_failure: bool = True) -> bool: # Check the local config, separated out that it can be checked via build # or ahead of building operators to make sure everything needed is present. if self.num_spatial_orbitals is None: if raise_on_failure: raise ValueError("The number of spatial orbitals cannot be 'None'.") return False if self.num_spatial_orbitals <= 0: if raise_on_failure: raise ValueError( f"The number of spatial orbitals must be > 0 was {self.num_spatial_orbitals}." ) return False if self.num_particles is None: if raise_on_failure: raise ValueError("The number of particles cannot be 'None'.") return False if any(n < 0 for n in self.num_particles): if raise_on_failure: raise ValueError( f"The number of particles cannot be smaller than 0 was {self.num_particles}." ) return False if not self._generalized: if all(n == self.num_spatial_orbitals for n in self.num_particles): if raise_on_failure: raise ValueError( f"UCC calculations for fully occupied alpha and beta orbitals " f"is still not implemented. The current system contains " f"{self.num_spatial_orbitals} orbitals for {self.num_particles} " f"(alpha, beta) particles." ) return False if any(n > self.num_spatial_orbitals for n in self.num_particles): if raise_on_failure: raise ValueError( f"The number of spatial orbitals {self.num_spatial_orbitals} " f"must be greater than number of particles of any spin kind " f"{self.num_particles}." ) return False if self.excitations is None: if raise_on_failure: raise ValueError("The excitations cannot be `None`.") return False if self.qubit_mapper is None: if raise_on_failure: raise ValueError("The qubit_mapper cannot be `None`.") return False return True def excitation_ops(self) -> list[SparseLabelOp]: """Parses the excitations and generates the list of operators. Raises: QiskitNatureError: if invalid excitations are specified. Returns: The list of generated excitation operators. """ if self._excitation_ops is not None: return self._excitation_ops excitation_list = self._get_excitation_list() self._check_excitation_list(excitation_list) logger.debug("Converting excitations into SparseLabelOps...") excitation_ops = self._build_fermionic_excitation_ops(excitation_list) self._excitation_list = excitation_list self._excitation_ops = excitation_ops return excitation_ops def _get_excitation_list(self) -> list[tuple[tuple[int, ...], tuple[int, ...]]]: generators = self._get_excitation_generators() logger.debug("Generating excitation list...") excitations = [] for gen in generators: excitations.extend( gen( # pylint: disable=not-callable num_spatial_orbitals=self.num_spatial_orbitals, num_particles=self.num_particles, ) ) return excitations def _get_excitation_generators(self) -> list[Callable]: logger.debug("Gathering excitation generators...") generators: list[Callable] = [] extra_kwargs = { "alpha_spin": self._alpha_spin, "beta_spin": self._beta_spin, "max_spin_excitation": self._max_spin_excitation, "generalized": self._generalized, "preserve_spin": self._preserve_spin, } if isinstance(self.excitations, str): for exc in self.excitations: generators.append( partial( generate_fermionic_excitations, num_excitations=self._EXCITATION_TYPE[exc], **extra_kwargs, ) ) elif isinstance(self.excitations, int): generators.append( partial( generate_fermionic_excitations, num_excitations=self.excitations, **extra_kwargs ) ) elif isinstance(self.excitations, list): for exc in self.excitations: # type: ignore generators.append( partial(generate_fermionic_excitations, num_excitations=exc, **extra_kwargs) ) elif callable(self.excitations): generators = [self.excitations] else: raise QiskitNatureError(f"Invalid excitation configuration: {self.excitations}") return generators def _check_excitation_list(self, excitations: Sequence) -> None: """Checks the format of the given excitation operators. The following conditions are checked: - the list of excitations consists of pairs of tuples - each pair of excitation indices has the same length - the indices within each excitation pair are unique Args: excitations: the list of excitations Raises: QiskitNatureError: if format of excitations is invalid """ logger.debug("Checking excitation list...") error_message = "{error} in the following UCC excitation: {excitation}" for excitation in excitations: if len(excitation) != 2: raise QiskitNatureError( error_message.format(error="Invalid number of tuples", excitation=excitation) + "; Two tuples are expected, e.g. ((0, 1, 4), (2, 3, 6))" ) if len(excitation[0]) != len(excitation[1]): raise QiskitNatureError( error_message.format( error="Different number of occupied and virtual indices", excitation=excitation, ) ) if any(i in excitation[0] for i in excitation[1]) or any( len(set(indices)) != len(indices) for indices in excitation ): raise QiskitNatureError( error_message.format(error="Duplicated indices", excitation=excitation) ) def _build_fermionic_excitation_ops(self, excitations: Sequence) -> list[FermionicOp]: """Builds all possible excitation operators with the given number of excitations for the specified number of particles distributed in the number of orbitals. Args: excitations: the list of excitations. Returns: The list of excitation operators in the second quantized formalism. """ num_spin_orbitals = 2 * self.num_spatial_orbitals operators = [] for exc in excitations: label = [] for occ in exc[0]: label.append(f"+_{occ}") for unocc in exc[1]: label.append(f"-_{unocc}") op = FermionicOp({" ".join(label): 1}, num_spin_orbitals=num_spin_orbitals) op_adj = op.adjoint() # we need to account for an additional imaginary phase in the exponent accumulated from # the first-order trotterization routine implemented in Qiskit op_minus = 1j * (op - op_adj) operators.append(op_minus) if self._include_imaginary: op_plus = -1 * (op + op_adj) operators.append(op_plus) return operators
qiskit-nature/qiskit_nature/second_q/circuit/library/ansatzes/ucc.py/0
{ "file_path": "qiskit-nature/qiskit_nature/second_q/circuit/library/ansatzes/ucc.py", "repo_id": "qiskit-nature", "token_count": 10335 }
127
# This code is part of a Qiskit project. # # (C) Copyright IBM 2018, 2023. # # 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. """The PySCF Driver.""" from __future__ import annotations import inspect import logging import os import tempfile import warnings from enum import Enum from typing import Any import numpy as np from qiskit_algorithms.utils.validation import validate_min from qiskit_nature.units import DistanceUnit from qiskit_nature.exceptions import QiskitNatureError from qiskit_nature.second_q.formats.molecule_info import MoleculeInfo from qiskit_nature.second_q.formats.qcschema import QCSchema from qiskit_nature.second_q.formats.qcschema_translator import qcschema_to_problem from qiskit_nature.second_q.operators.symmetric_two_body import fold from qiskit_nature.second_q.problems import ElectronicBasis, ElectronicStructureProblem import qiskit_nature.optionals as _optionals from qiskit_nature.utils import get_einsum from ..electronic_structure_driver import ElectronicStructureDriver, MethodType, _QCSchemaData logger = logging.getLogger(__name__) warnings.filterwarnings("ignore", category=DeprecationWarning, module="pyscf") class InitialGuess(Enum): """Initial Guess Enum""" MINAO = "minao" HCORE = "1e" ONE_E = "1e" ATOM = "atom" @_optionals.HAS_PYSCF.require_in_instance class PySCFDriver(ElectronicStructureDriver): """A Second-Quantization driver for Qiskit Nature using the PySCF library. References: https://pyscf.org/ """ def __init__( self, atom: str | list[str] = "H 0.0 0.0 0.0; H 0.0 0.0 0.735", *, unit: DistanceUnit = DistanceUnit.ANGSTROM, charge: int = 0, spin: int = 0, basis: str = "sto3g", method: MethodType = MethodType.RHF, xc_functional: str = "lda,vwn", xcf_library: str = "libxc", conv_tol: float = 1e-9, max_cycle: int = 50, init_guess: InitialGuess = InitialGuess.MINAO, max_memory: int | None = None, chkfile: str | None = None, ) -> None: """ Args: atom: A string (or a list thereof) denoting the elements and coordinates of all atoms in the system. Two formats are allowed; first, the PySCF-style `XYZ` format which is a list of strings formatted as `{element symbol} {x_coord} {y_coord} {z_coord}`. If a single string is given, the list entries should be joined by `;` as in the example: `H 0.0 0.0 0.0; H 0.0 0.0 0.735`. Second, the `Z-Matrix` format which is explained at 1_. The previous example would be written as `H; H 3 0.735`. See also 2_ for more details on geometry specifications supported by PySCF. unit: Denotes the unit of coordinates. Valid values are given by the ``UnitsType`` enum. charge: The charge of the molecule. spin: The spin of the molecule. In accordance with PySCF's definition, the spin equals :math:`2*S`, where :math:`S` is the total spin number of the molecule. basis: A basis set name as recognized by PySCF (3_), e.g. `sto3g` (the default), `321g`, etc. Note, that more advanced configuration options like a Dictionary or custom basis sets are not allowed for the moment. Refer to 4_ for an extensive list of PySCF's valid basis set names. method: The SCF method type to be used for the PySCF calculation. While the name refers to HF methods, the PySCFDriver also supports KS methods. Refer to the ``MethodType`` for a list of the supported methods. xc_functional: One of the predefined Exchange-Correlation functional names as recognized by PySCF (5_). Defaults to PySCF's default: 'lda,vwn'. __Note: this setting only has an effect when a KS method is chosen for `method`.__ xcf_library: The Exchange-Correlation functional library to be used. This can be either 'libxc' (the default) or 'xcfun'. Depending on this value, a different set of values for `xc_functional` will be available. Refer to 5_ for more details. conv_tol: The SCF convergence tolerance. See 6_ for more details. max_cycle: The maximum number of SCF iterations. See 6_ for more details. init_guess: The method to make the initial guess for the SCF starting point. Valid values are given by the ``InitialGuess`` enum. See 6_ for more details. max_memory: The maximum memory that PySCF should use. See 6_ for more details. chkfile: The path to a PySCF checkpoint file from which to load a previously run calculation. The data stored in this file is assumed to be already converged. Refer to 6_ and 7_ for more details. Raises: QiskitNatureError: An invalid input was supplied. .. _1: https://en.wikipedia.org/wiki/Z-matrix_(chemistry) .. _2: https://pyscf.org/user/gto.html#geometry .. _3: https://pyscf.org/user/gto.html#basis-set .. _4: https://pyscf.org/pyscf_api_docs/pyscf.gto.basis.html#module-pyscf.gto.basis .. _5: https://pyscf.org/user/dft.html#predefined-xc-functionals-and-functional-aliases .. _6: https://pyscf.org/pyscf_api_docs/pyscf.scf.html#module-pyscf.scf.hf .. _7: https://pyscf.org/pyscf_api_docs/pyscf.lib.html#module-pyscf.lib.chkfile """ super().__init__() # pylint: disable=import-error from pyscf import gto, scf # First, ensure that PySCF supports the method PySCFDriver.check_method_supported(method) if isinstance(atom, list): atom = ";".join(atom) elif isinstance(atom, str): atom = atom.replace("\n", ";") else: raise QiskitNatureError( f"`atom` must be either a `str` or `list[str]`, but you passed {atom}" ) validate_min("max_cycle", max_cycle, 1) # we use the property-setter to deal with conversion self.atom = atom self._unit = unit self._charge = charge self._spin = spin self._basis = basis self._method = method self._xc_functional = xc_functional self.xcf_library = xcf_library # validate choice in property setter self._conv_tol = conv_tol self._max_cycle = max_cycle self._init_guess = init_guess.value self._max_memory = max_memory self._chkfile = chkfile self._mol: gto.Mole = None self._calc: scf.HF = None @property def atom(self) -> str: """Returns the atom.""" return self._atom @atom.setter def atom(self, atom: str | list[str]) -> None: """Sets the atom.""" if isinstance(atom, list): atom = ";".join(atom) self._atom = atom.replace("\n", ";") @property def unit(self) -> DistanceUnit: """Returns the unit.""" return self._unit @unit.setter def unit(self, unit: DistanceUnit) -> None: """Sets the unit.""" self._unit = unit @property def charge(self) -> int: """Returns the charge.""" return self._charge @charge.setter def charge(self, charge: int) -> None: """Sets the charge.""" self._charge = charge @property def spin(self) -> int: """Returns the spin.""" return self._spin @spin.setter def spin(self, spin: int) -> None: """Sets the spin.""" self._spin = spin @property def basis(self) -> str: """return basis""" return self._basis @basis.setter def basis(self, value: str) -> None: """set basis""" self._basis = value @property def method(self) -> MethodType: """Returns Hartree-Fock/Kohn-Sham method""" return self._method @method.setter def method(self, value: MethodType) -> None: """Sets Hartree-Fock/Kohn-Sham method""" self._method = value @property def xc_functional(self) -> str: """Returns the Exchange-Correlation functional.""" return self._xc_functional @xc_functional.setter def xc_functional(self, xc_functional: str) -> None: """Sets the Exchange-Correlation functional.""" self._xc_functional = xc_functional @property def xcf_library(self) -> str: """Returns the Exchange-Correlation functional library.""" return self._xcf_library @xcf_library.setter def xcf_library(self, xcf_library: str) -> None: """Sets the Exchange-Correlation functional library.""" if xcf_library not in ("libxc", "xcfun"): raise QiskitNatureError( "Invalid XCF library. It can be either 'libxc' or 'xcfun', not " f"'{xcf_library}'" ) self._xcf_library = xcf_library @property def conv_tol(self) -> float: """Returns the SCF convergence tolerance.""" return self._conv_tol @conv_tol.setter def conv_tol(self, conv_tol: float) -> None: """Sets the SCF convergence tolerance.""" self._conv_tol = conv_tol @property def max_cycle(self) -> int: """Returns the maximum number of SCF iterations.""" return self._max_cycle @max_cycle.setter def max_cycle(self, max_cycle: int) -> None: """Sets the maximum number of SCF iterations.""" self._max_cycle = max_cycle @property def init_guess(self) -> str: """Returns the method for the initial guess.""" return self._init_guess @init_guess.setter def init_guess(self, init_guess: str) -> None: """Sets the method for the initial guess.""" self._init_guess = init_guess @property def max_memory(self) -> int: """Returns the maximum memory allowance for the calculation.""" return self._max_memory @max_memory.setter def max_memory(self, max_memory: int) -> None: """Sets the maximum memory allowance for the calculation.""" self._max_memory = max_memory @property def chkfile(self) -> str: """Returns the path to the PySCF checkpoint file.""" return self._chkfile @chkfile.setter def chkfile(self, chkfile: str) -> None: """Sets the path to the PySCF checkpoint file.""" self._chkfile = chkfile @staticmethod def from_molecule( molecule: MoleculeInfo, *, basis: str = "sto3g", method: MethodType = MethodType.RHF, driver_kwargs: dict[str, Any] | None = None, ) -> "PySCFDriver": """Creates a driver from a molecule. Args: molecule: the molecular information. basis: the basis set. method: the SCF method type. driver_kwargs: keyword arguments to be passed to driver. Returns: The constructed driver instance. """ PySCFDriver.check_method_supported(method) kwargs = {} if driver_kwargs: args = inspect.signature(PySCFDriver.__init__).parameters.keys() for key, value in driver_kwargs.items(): if key not in ["self"] and key in args: kwargs[key] = value kwargs["atom"] = [ " ".join(map(str, (name, *coord))) for name, coord in zip(molecule.symbols, molecule.coords) ] kwargs["charge"] = molecule.charge kwargs["spin"] = molecule.multiplicity - 1 kwargs["unit"] = molecule.units kwargs["basis"] = PySCFDriver.to_driver_basis(basis) kwargs["method"] = method return PySCFDriver(**kwargs) @staticmethod def to_driver_basis(basis: str) -> str: """Converts basis to a driver acceptable basis. Args: basis: The basis set to be used. Returns: A driver acceptable basis. """ return basis @staticmethod def check_method_supported(method: MethodType) -> None: """Checks that PySCF supports this method. Args: method: the SCF method type. Raises: UnsupportMethodError: If the method is not supported. """ # supports all methods pass def run(self) -> ElectronicStructureProblem: """Runs the driver to produce a result. Returns: ElectronicStructureProblem produced by the run driver. Raises: QiskitNatureError: if an error during the PySCF setup or calculation occurred. """ self.run_pyscf() return self.to_problem() def _build_molecule(self) -> None: """Builds the PySCF molecule object. Raises: QiskitNatureError: If building the PySCF molecule object failed. """ # Get config from input parameters # molecule is in PySCF atom string format e.g. "H .0 .0 .0; H .0 .0 0.2" # or in Z-Matrix format e.g. "H; O 1 1.08; H 2 1.08 1 107.5" # other parameters are as per PySCF got.Mole format # pylint: disable=import-error from pyscf import gto from pyscf.lib import logger as pylogger from pyscf.lib import param atom = self._check_molecule_format(self.atom) if self._max_memory is None: self._max_memory = param.MAX_MEMORY try: verbose = pylogger.QUIET output = None if logger.isEnabledFor(logging.DEBUG): verbose = pylogger.INFO file, output = tempfile.mkstemp(suffix=".log") os.close(file) self._mol = gto.Mole( atom=atom, unit=self._unit.value, basis=self._basis, max_memory=self._max_memory, verbose=verbose, output=output, ) self._mol.symmetry = False self._mol.charge = self._charge self._mol.spin = self._spin self._mol.build(parse_arg=False) if output is not None: self._process_pyscf_log(output) try: os.remove(output) except Exception: # pylint: disable=broad-except pass except Exception as exc: raise QiskitNatureError("Failed to build the PySCF Molecule object.") from exc @staticmethod def _check_molecule_format(val: str) -> str | list[str]: """Ensures the molecule coordinates are in XYZ format. This utility automatically converts a Z-matrix coordinate format into XYZ coordinates. Args: val: the atomic coordinates. Raises: QiskitNatureError: If the provided coordinate are badly formatted. Returns: The coordinates in XYZ format. """ # pylint: disable=import-error from pyscf import gto atoms = [x.strip() for x in val.split(";")] if atoms is None or len(atoms) < 1: raise QiskitNatureError("Molecule format error: " + val) # An xyz format has 4 parts in each atom, if not then do zmatrix convert # Allows dummy atoms, using symbol 'X' in zmatrix format for coord computation to xyz parts = [x.strip() for x in atoms[0].split()] if len(parts) != 4: try: newval = [] for entry in gto.mole.from_zmatrix(val): if entry[0].upper() != "X": newval.append(entry) return newval except Exception as exc: raise QiskitNatureError("Failed to convert atom string: " + val) from exc return val def run_pyscf(self) -> None: """Runs the PySCF calculation. This method is part of the public interface to allow the user to easily overwrite it in a subclass to further tailor the behavior to some specific use case. Raises: QiskitNatureError: If an invalid HF method type was supplied. """ self._build_molecule() # pylint: disable=import-error from pyscf import dft, scf from pyscf.lib import chkfile as lib_chkfile method_name = None method_cls = None try: # attempt to gather the SCF-method class specified by the MethodType method_name = self.method.value.upper() method_cls = getattr(scf, method_name) except AttributeError as exc: raise QiskitNatureError(f"Failed to load {method_name} HF object.") from exc self._calc = method_cls(self._mol) if method_name in ("RKS", "ROKS", "UKS"): self._calc._numint.libxc = getattr(dft, self.xcf_library) self._calc.xc = self.xc_functional if self._chkfile is not None and os.path.exists(self._chkfile): self._calc.__dict__.update(lib_chkfile.load(self._chkfile, "scf")) logger.info("PySCF loaded from chkfile e(hf): %s", self._calc.e_tot) else: self._calc.conv_tol = self._conv_tol self._calc.max_cycle = self._max_cycle self._calc.init_guess = self._init_guess self._calc.kernel() logger.info( "PySCF kernel() converged: %s, e(hf): %s", self._calc.converged, self._calc.e_tot, ) def to_qcschema(self, *, include_dipole: bool = True) -> QCSchema: # pylint: disable=import-error from pyscf import __version__ as pyscf_version from pyscf import ao2mo, gto from pyscf.tools import dump_mat einsum_func, _ = get_einsum() data = _QCSchemaData() data.overlap = self._calc.get_ovlp() data.mo_coeff, data.mo_coeff_b = self._expand_mo_object( self._calc.mo_coeff, array_dimension=3 ) data.mo_energy, data.mo_energy_b = self._expand_mo_object(self._calc.mo_energy) data.mo_occ, data.mo_occ_b = self._expand_mo_object(self._calc.mo_occ) if logger.isEnabledFor(logging.DEBUG): # Add some more to PySCF output... # First analyze() which prints extra information about MO energy and occupation self._mol.stdout.write("\n") self._calc.analyze() # Now labelled orbitals for contributions to the MOs for s,p,d etc of each atom self._mol.stdout.write("\n\n--- Alpha Molecular Orbitals ---\n\n") dump_mat.dump_mo(self._mol, data.mo_coeff, digits=7, start=1) if data.mo_coeff_b is not None: self._mol.stdout.write("\n--- Beta Molecular Orbitals ---\n\n") dump_mat.dump_mo(self._mol, data.mo_coeff_b, digits=7, start=1) self._mol.stdout.flush() data.hij = self._calc.get_hcore() data.hij_mo = np.dot(np.dot(data.mo_coeff.T, data.hij), data.mo_coeff) if data.mo_coeff_b is not None: data.hij_mo_b = np.dot(np.dot(data.mo_coeff_b.T, data.hij), data.mo_coeff_b) data.eri = self._mol.intor("int2e", aosym=8) data.eri_mo = fold(ao2mo.full(self._mol, data.mo_coeff, aosym=4)) if data.mo_coeff_b is not None: data.eri_mo_bb = fold(ao2mo.full(self._mol, data.mo_coeff_b, aosym=4)) data.eri_mo_ba = fold( ao2mo.general( self._mol, [data.mo_coeff_b, data.mo_coeff_b, data.mo_coeff, data.mo_coeff], aosym=4, ) ) data.e_nuc = gto.mole.energy_nuc(self._mol) data.e_ref = self._calc.e_tot data.symbols = [self._mol.atom_pure_symbol(i) for i in range(self._mol.natm)] data.coords = self._mol.atom_coords(unit="Bohr").ravel().tolist() data.multiplicity = self._spin + 1 data.charge = self._charge data.masses = list(self._mol.atom_mass_list()) data.method = self._method.value.upper() data.basis = self._basis data.creator = "PySCF" data.version = pyscf_version data.nbasis = self._mol.nbas data.nmo = self._mol.nao data.nalpha = self._mol.nelec[0] data.nbeta = self._mol.nelec[1] if include_dipole: self._mol.set_common_orig((0, 0, 0)) ao_dip = self._mol.intor_symmetric("int1e_r", comp=3) d_m = self._calc.make_rdm1(self._calc.mo_coeff, self._calc.mo_occ) if not (isinstance(d_m, np.ndarray) and d_m.ndim == 2): d_m = d_m[0] + d_m[1] elec_dip = np.negative(einsum_func("xij,ji->x", ao_dip, d_m).real) elec_dip = np.round(elec_dip, decimals=8) nucl_dip = einsum_func("i,ix->x", self._mol.atom_charges(), self._mol.atom_coords()) nucl_dip = np.round(nucl_dip, decimals=8) ref_dip = nucl_dip + elec_dip logger.info("HF Electronic dipole moment: %s", elec_dip) logger.info("Nuclear dipole moment: %s", nucl_dip) logger.info("Total dipole moment: %s", ref_dip) data.dip_nuc = nucl_dip data.dip_ref = ref_dip data.dip_x = ao_dip[0] data.dip_y = ao_dip[1] data.dip_z = ao_dip[2] data.dip_mo_x_a = np.dot(np.dot(data.mo_coeff.T, data.dip_x), data.mo_coeff) data.dip_mo_y_a = np.dot(np.dot(data.mo_coeff.T, data.dip_y), data.mo_coeff) data.dip_mo_z_a = np.dot(np.dot(data.mo_coeff.T, data.dip_z), data.mo_coeff) if data.mo_coeff_b is not None: data.dip_mo_x_b = np.dot(np.dot(data.mo_coeff_b.T, data.dip_x), data.mo_coeff_b) data.dip_mo_y_b = np.dot(np.dot(data.mo_coeff_b.T, data.dip_y), data.mo_coeff_b) data.dip_mo_z_b = np.dot(np.dot(data.mo_coeff_b.T, data.dip_z), data.mo_coeff_b) return self._to_qcschema(data, include_dipole=include_dipole) def to_problem( self, *, basis: ElectronicBasis = ElectronicBasis.MO, include_dipole: bool = True, ) -> ElectronicStructureProblem: qcschema = self.to_qcschema(include_dipole=include_dipole) problem = qcschema_to_problem(qcschema, basis=basis, include_dipole=include_dipole) if include_dipole and problem.properties.electronic_dipole_moment is not None: problem.properties.electronic_dipole_moment.reverse_dipole_sign = True return problem def _expand_mo_object( self, mo_object: tuple[np.ndarray | None, np.ndarray | None] | np.ndarray, array_dimension: int = 2, ) -> tuple[np.ndarray, np.ndarray]: """Expands the molecular orbital object into alpha- and beta-spin components. Since PySCF 1.6.2, the alpha and beta components are no longer stored as a tuple but as a multi-dimensional numpy array. This utility takes care of differentiating these cases. Args: mo_object: the molecular orbital object to expand. array_dimension: This argument specifies the dimension of the numpy array (if a tuple is not encountered). Making this configurable permits this function to be used to expand both, MO coefficients (3D array) and MO energies (2D array). Returns: The (alpha, beta) tuple of MO data. """ if isinstance(mo_object, tuple): return mo_object if len(mo_object.shape) == array_dimension: return mo_object[0], mo_object[1] return mo_object, None def _process_pyscf_log(self, logfile: str) -> None: """Processes a PySCF logfile. Args: logfile: the path of the PySCF logfile. """ with open(logfile, "r", encoding="utf8") as file: contents = file.readlines() for i, content in enumerate(contents): if content.startswith("System:"): contents = contents[i:] break logger.debug("PySCF processing messages log:\n%s", "".join(contents))
qiskit-nature/qiskit_nature/second_q/drivers/pyscfd/pyscfdriver.py/0
{ "file_path": "qiskit-nature/qiskit_nature/second_q/drivers/pyscfd/pyscfdriver.py", "repo_id": "qiskit-nature", "token_count": 11293 }
128
# This code is part of a Qiskit project. # # (C) Copyright IBM 2022, 2023. # # 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. """The QCSchema (output) dataclass.""" from __future__ import annotations from dataclasses import dataclass from typing import Any, Sequence, cast # Sphinx is somehow unable to resolve this forward reference which gets inherited from QCSchemaInput # Thus, we import it here manually to ensure the documentation can be built from typing import Mapping # pylint: disable=unused-import import h5py from qiskit_nature.version import __version__ from .qc_error import QCError from .qc_model import QCModel from .qc_schema_input import QCSchemaInput from .qc_properties import QCProperties from .qc_provenance import QCProvenance from .qc_topology import QCTopology from .qc_wavefunction import QCWavefunction @dataclass class QCSchema(QCSchemaInput): """The full QCSchema as a dataclass. For more information refer to [here](https://molssi-qc-schema.readthedocs.io/en/latest/spec_components.html#output-components). """ provenance: QCProvenance """An instance of :class:`QCProvenance`.""" return_result: float | Sequence[float] """The primary result of the computation. Its value depends on the type of computation (see also `driver`).""" success: bool """Whether the computation was successful.""" properties: QCProperties """An instance of :class:`QCProperties`.""" error: QCError | None = None """An instance of :class:`QCError` if the computation was not successful (`success = False`).""" wavefunction: QCWavefunction | None = None """An instance of :class:`QCWavefunction`.""" @classmethod def from_dict(cls, data: dict[str, Any]) -> QCSchema: error: QCError | None = None if "error" in data.keys(): error = QCError(**data.pop("error")) model = QCModel(**data.pop("model")) molecule = QCTopology(**data.pop("molecule")) provenance = QCProvenance(**data.pop("provenance")) properties = QCProperties(**data.pop("properties")) wavefunction: QCWavefunction | None = None if "wavefunction" in data.keys(): wavefunction = QCWavefunction.from_dict(data.pop("wavefunction")) return cls( **data, error=error, model=model, molecule=molecule, provenance=provenance, properties=properties, wavefunction=wavefunction, ) def to_hdf5(self, group: h5py.Group) -> None: group.attrs["schema_name"] = self.schema_name group.attrs["schema_version"] = self.schema_version group.attrs["driver"] = self.driver group.attrs["return_result"] = self.return_result group.attrs["success"] = self.success molecule_group = group.require_group("molecule") self.molecule.to_hdf5(molecule_group) model_group = group.require_group("model") self.model.to_hdf5(model_group) provenance_group = group.require_group("provenance") self.provenance.to_hdf5(provenance_group) properties_group = group.require_group("properties") self.properties.to_hdf5(properties_group) if self.error is not None: error_group = group.require_group("error") self.error.to_hdf5(error_group) if self.wavefunction is not None: wavefunction_group = group.require_group("wavefunction") self.wavefunction.to_hdf5(wavefunction_group) keywords_group = group.require_group("keywords") for key, value in self.keywords.items(): keywords_group.attrs[key] = value @classmethod def _from_hdf5_group(cls, h5py_group: h5py.Group) -> QCSchemaInput: data = dict(h5py_group.attrs.items()) data["molecule"] = cast(QCTopology, QCTopology.from_hdf5(h5py_group["molecule"])) data["model"] = cast(QCModel, QCModel.from_hdf5(h5py_group["model"])) data["provenance"] = cast(QCProvenance, QCProvenance.from_hdf5(h5py_group["provenance"])) data["properties"] = cast(QCProperties, QCProperties.from_hdf5(h5py_group["properties"])) if "error" in h5py_group.keys(): data["error"] = cast(QCError, QCError.from_hdf5(h5py_group["error"])) if "wavefunction" in h5py_group.keys(): data["wavefunction"] = cast( QCWavefunction, QCWavefunction.from_hdf5(h5py_group["wavefunction"]) ) data["keywords"] = dict(h5py_group["keywords"].attrs.items()) return cls(**data)
qiskit-nature/qiskit_nature/second_q/formats/qcschema/qc_schema.py/0
{ "file_path": "qiskit-nature/qiskit_nature/second_q/formats/qcschema/qc_schema.py", "repo_id": "qiskit-nature", "token_count": 1971 }
129
# This code is part of a Qiskit project. # # (C) Copyright IBM 2021, 2024. # # 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. """The Direct Mapper.""" from __future__ import annotations from functools import lru_cache import numpy as np from qiskit.quantum_info.operators import Pauli from .vibrational_mapper import VibrationalMapper from .mode_based_mapper import ModeBasedMapper, PauliType class DirectMapper(VibrationalMapper, ModeBasedMapper): """The Direct mapper. This mapper maps a :class:`~.VibrationalOp` to a qubit operator. In doing so, each modal of the ``VibrationalOp`` gets mapped to a single qubit. """ def pauli_table(self, register_length: int) -> list[tuple[PauliType, PauliType]]: return self._pauli_table(register_length) @staticmethod @lru_cache(maxsize=32) def _pauli_table(register_length: int) -> list[tuple[PauliType, PauliType]]: pauli_table = [] for i in range(register_length): a_z = np.asarray([0] * i + [0] + [0] * (register_length - i - 1), dtype=bool) a_x = np.asarray([0] * i + [1] + [0] * (register_length - i - 1), dtype=bool) b_z = np.asarray([0] * i + [1] + [0] * (register_length - i - 1), dtype=bool) b_x = np.asarray([0] * i + [1] + [0] * (register_length - i - 1), dtype=bool) pauli_table.append((Pauli((a_z, a_x)), Pauli((b_z, b_x)))) return pauli_table
qiskit-nature/qiskit_nature/second_q/mappers/direct_mapper.py/0
{ "file_path": "qiskit-nature/qiskit_nature/second_q/mappers/direct_mapper.py", "repo_id": "qiskit-nature", "token_count": 694 }
130
# This code is part of a Qiskit project. # # (C) Copyright IBM 2022, 2023. # # 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 container class for electronic operator coefficients (a.k.a. electronic integrals).""" from __future__ import annotations from collections.abc import Callable from numbers import Number from typing import Optional, Sequence, Tuple, cast import numpy as np from qiskit.quantum_info.operators.mixins import LinearMixin from qiskit_nature.exceptions import QiskitNatureError import qiskit_nature.optionals as _optionals from .polynomial_tensor import PolynomialTensor from .symmetric_two_body import SymmetricTwoBodyIntegrals from .tensor import Tensor from .tensor_ordering import ( IndexType, find_index_order, to_physicist_ordering, ) if _optionals.HAS_SPARSE: # pylint: disable=import-error from sparse import SparseArray else: class SparseArray: # type: ignore """Empty SparseArray class Replacement if sparse.SparseArray is not present. """ pass class ElectronicIntegrals(LinearMixin): r"""A container class for electronic operator coefficients (a.k.a. electronic integrals). This class contains multiple :class:`qiskit_nature.second_q.operators.PolynomialTensor` instances, dealing with the specific case of storing electronic integrals, where the up- and down-spin electronic interactions need to be handled separately. These two spins are also commonly referred to by :math:`\alpha` and :math:`\beta`, respectively. Specifically, this class stores three :class:`~.PolynomialTensor` instances: - :attr:`alpha`: which stores the up-spin integrals - :attr:`beta`: which stores the down-spin integrals - :attr:`beta_alpha`: which stores beta-alpha-spin two-body integrals These tensors are subject to some expectations, namely: - for ``alpha`` and ``beta`` only the following keys are allowed: ``""``, ``"+-"``, ``"++--"`` - for ``beta_alpha`` the only allowed key is ``"++--"`` - the reported ``register_length`` attributes of all non-empty tensors must match There are two ways of constructing the ``ElectronicIntegrals``: .. code-block:: python # assuming you already have your one- and two-body integrals from somewhere h1_a, h2_aa, h1_b, h2_bb, h2_ba = ... from qiskit_nature.second_q.operators import ElectronicIntegrals, PolynomialTensor alpha = PolynomialTensor({"+-": h1_a, "++--": h2_aa}) beta = PolynomialTensor({"+-": h1_b, "++--": h2_bb}) beta_alpha = PolynomialTensor({"++--": h2_ba}) integrals = ElectronicIntegrals(alpha, beta, beta_alpha) # alternatively, the following achieves the same effect: integrals = ElectronicIntegrals.from_raw_integrals(h1_a, h2_aa, h1_b, h2_bb, h2_ba) This class then exposes common mathematical operations performed on these tensors allowing simple manipulation of the underlying data structures. .. code-block:: python # addition integrals + integrals # scalar multiplication 2.0 * integrals This class will substitute empty ``beta`` and ``beta_alpha`` tensors with the ``alpha`` tensor when necessary. For example, this means the following will happen: .. code-block:: python integrals_pure = ElectronicIntegrals(alpha) integrals_mixed = ElectronicIntegrals(alpha, beta, beta_alpha) sum = integrals_pure + integrals_mixed print(sum.beta.is_empty()) # False print(sum.beta_alpha.is_empty()) # False print(sum.beta.equiv(alpha + beta)) # True print(sum.beta_alpha.equiv(alpha + beta_alpha)) # True The same logic holds for other mathematical operations involving multiple ``ElectronicIntegrals``. You can add a custom offset to be included in the operator generated from these coefficients like so: .. code-block:: python from qiskit_nature.second_q.operators import PolynomialTensor integrals: ElectronicIntegrals offset = 2.5 integrals.alpha += PolynomialTensor({"": offset}) """ _VALID_KEYS = {"", "+-", "++--"} def __init__( self, alpha: PolynomialTensor | None = None, beta: PolynomialTensor | None = None, beta_alpha: PolynomialTensor | None = None, *, validate: bool = True, ) -> None: """ Any ``None``-valued argument will internally be replaced by an empty :class:`~.PolynomialTensor` (see also :meth:`qiskit_nature.second_q.operators.PolynomialTensor.empty`). Args: alpha: the up-spin electronic integrals beta: the down-spin electronic integrals beta_alpha: the beta-alpha-spin two-body electronic integrals. This may *only* contain the ``++--`` key. validate: when set to False, no validation will be performed. Disable this setting with care! Raises: KeyError: if the ``alpha`` tensor contains keys other than ``""``, ``"+-"``, and ``"++--"``. KeyError: if the ``beta`` tensor contains keys other than ``""``, ``"+-"``, and ``"++--"``. KeyError: if the ``beta_alpha`` tensor contains keys other than ``"++--"``. ValueError: if the reported :attr:`~.PolynomialTensor.register_length` attributes of the alpha-, beta-, and beta-alpha-spin tensors do not all match. """ self.alpha = alpha self.beta = beta self.beta_alpha = beta_alpha if validate: self._validate() def _validate(self): """Performs internal validation.""" self._validate_tensor_keys() self._validate_register_lengths() def _validate_tensor_keys(self): """Validates the keys of all internal tensors.""" if not self.alpha.keys() <= ElectronicIntegrals._VALID_KEYS: raise KeyError( "The only allowed keys for the alpha-spin tensor are '', '+-', and '++--', but your" f" tensor has keys: {self.alpha.keys()}" ) if not self.beta.keys() <= ElectronicIntegrals._VALID_KEYS: raise KeyError( "The only allowed keys for the beta-spin tensor are '', '+-', and '++--', but your" f" tensor has keys: {self.beta.keys()}" ) if not self.beta_alpha.keys() <= {"++--"}: raise KeyError( "The only allowed key for the beta-alpha-spin tensor is '++--', but your " f" tensor has keys: {self.beta_alpha.keys()}" ) def _validate_register_lengths(self): """Validates the reported `register_length` attributes of all internal tensors.""" alpha_len = self.alpha.register_length beta_len = self.beta.register_length beta_alpha_len = self.beta_alpha.register_length if alpha_len is None: if beta_len is not None: raise ValueError( f"The reported register_length of your beta-spin tensor, {beta_len}, does not " f"match the alpha-spin tensor one, {alpha_len}." ) if beta_alpha_len is not None: raise ValueError( f"The reported register_length of your beta-alpha-spin tensor, {beta_alpha_len}" f", does not match the alpha-spin tensor one, {alpha_len}." ) else: if beta_len is not None and alpha_len != beta_len: raise ValueError( f"The reported register_length of your beta-spin tensor, {beta_len}, does not " f"match the alpha-spin tensor one, {alpha_len}." ) if beta_alpha_len is not None and alpha_len != beta_alpha_len: raise ValueError( f"The reported register_length of your beta-alpha-spin tensor, {beta_alpha_len}" f", does not match the alpha-spin tensor one, {alpha_len}." ) @property def alpha(self) -> PolynomialTensor: """The up-spin electronic integrals.""" return self._alpha @alpha.setter def alpha(self, alpha: PolynomialTensor | None) -> None: self._alpha = alpha if alpha is not None else PolynomialTensor.empty() @property def beta(self) -> PolynomialTensor: """The down-spin electronic integrals.""" return self._beta @beta.setter def beta(self, beta: PolynomialTensor | None) -> None: self._beta = beta if beta is not None else PolynomialTensor.empty() @property def beta_alpha(self) -> PolynomialTensor: """The beta-alpha-spin two-body electronic integrals.""" return self._beta_alpha @beta_alpha.setter def beta_alpha(self, beta_alpha: PolynomialTensor | None) -> None: if beta_alpha is None: self._beta_alpha = PolynomialTensor.empty() else: keys = set(beta_alpha) if keys and keys != {"++--"}: raise ValueError( f"The beta_alpha tensor may only contain a `++--` key, not {keys}." ) self._beta_alpha = beta_alpha @property def alpha_beta(self) -> PolynomialTensor: """The alpha-beta-spin two-body electronic integrals. These get reconstructed from :attr:`beta_alpha` by transposing in the physicist' ordering convention. """ if self.beta_alpha.is_empty(): return self.beta_alpha two_body_ba = self.beta_alpha["++--"] if isinstance(two_body_ba, SymmetricTwoBodyIntegrals): # NOTE: to ensure proper inter-operability with the symmetry-aware integral containers, # we delegate the conjugation to the objects themselves return PolynomialTensor({"++--": two_body_ba.conjugate()}, validate=False) alpha_beta = cast(Tensor, np.moveaxis(two_body_ba, (0, 1), (2, 3))) return PolynomialTensor({"++--": alpha_beta}, validate=False) @property def one_body(self) -> ElectronicIntegrals: """Returns only the one-body integrals.""" alpha: PolynomialTensor = None if "+-" in self.alpha: alpha = PolynomialTensor( {"+-": self.alpha["+-"]}, validate=False, ) beta: PolynomialTensor = None if "+-" in self.beta: beta = PolynomialTensor( {"+-": self.beta["+-"]}, validate=False, ) return self.__class__(alpha, beta) @property def two_body(self) -> ElectronicIntegrals: """Returns only the two-body integrals.""" alpha: PolynomialTensor = None if "++--" in self.alpha: alpha = PolynomialTensor( {"++--": self.alpha["++--"]}, validate=False, ) beta: PolynomialTensor = None if "++--" in self.beta: beta = PolynomialTensor( {"++--": self.beta["++--"]}, validate=False, ) beta_alpha: PolynomialTensor = None if "++--" in self.beta_alpha: beta_alpha = PolynomialTensor( {"++--": self.beta_alpha["++--"]}, validate=False, ) return self.__class__(alpha, beta, beta_alpha) @property def register_length(self) -> int | None: """The size of the operator that can be generated from these `ElectronicIntegrals`.""" alpha_length = self.alpha.register_length return alpha_length def __eq__(self, other: object) -> bool: """Check equality of first ElectronicIntegrals with other Args: other: second ``ElectronicIntegrals`` object to be compared with the first. Returns: True when ``ElectronicIntegrals`` objects are equal, False when unequal. """ if not isinstance(other, ElectronicIntegrals): return False if ( self.alpha == other.alpha and self.beta == other.beta and self.beta_alpha == other.beta_alpha ): return True return False def equiv(self, other: object) -> bool: """Check equivalence of first ElectronicIntegrals with other Args: other: second ``ElectronicIntegrals`` object to be compared with the first. Returns: True when ``ElectronicIntegrals`` objects are equivalent, False when not. """ if not isinstance(other, ElectronicIntegrals): return False if ( self.alpha.equiv(other.alpha) and self.beta.equiv(other.beta) and self.beta_alpha.equiv(other.beta_alpha) ): return True return False def _multiply(self, other: complex) -> ElectronicIntegrals: if not isinstance(other, Number): raise TypeError(f"other {other} must be a number") return self.__class__( cast(PolynomialTensor, other * self.alpha), cast(PolynomialTensor, other * self.beta), cast(PolynomialTensor, other * self.beta_alpha), ) def _add(self, other: ElectronicIntegrals, qargs=None) -> ElectronicIntegrals: if not isinstance(other, ElectronicIntegrals): raise TypeError("Incorrect argument type: other should be ElectronicIntegrals") # we need to handle beta separately in order to inject alpha where necessary beta: PolynomialTensor = None beta_self_empty = self.beta.is_empty() beta_other_empty = other.beta.is_empty() if not (beta_self_empty and beta_other_empty): beta_self = self.alpha if beta_self_empty else self.beta beta_other = other.alpha if beta_other_empty else other.beta beta = beta_self + beta_other return self.__class__( self.alpha + other.alpha, beta, self.beta_alpha + other.beta_alpha, ) @classmethod def apply( cls, function: Callable[..., np.ndarray | SparseArray | complex], *operands: ElectronicIntegrals, multi: bool = False, validate: bool = True, ) -> ElectronicIntegrals | list[ElectronicIntegrals]: """Exposes the :meth:`qiskit_nature.second_q.operators.PolynomialTensor.apply` method. This behaves identical to the ``apply`` implementation of the ``PolynomialTensor``, applied to the :attr:`alpha`, :attr:`beta`, and :attr:`beta_alpha` attributes of the provided ``ElectronicIntegrals`` operands. This method is special, because it handles the scenario in which any operand has a non-empty :attr:`beta` attribute, in which case the empty-beta attributes of any other operands will be filled with :attr:`alpha` attributes of those operands. The :attr:`beta_alpha` attributes will only be handled if they are non-empty in all supplied operands. Args: function: the function to apply to the internal arrays of the provided operands. This function must take numpy (or sparse) arrays as its positional arguments. The number of arguments must match the number of provided operands. operands: a sequence of ``ElectronicIntegrals`` instances on which to operate. multi: when set to True this indicates that the provided numpy function will return multiple new numpy arrays which will each be wrapped into an ``ElectronicIntegrals`` instance separately. validate: when set to False, no validation will be performed. Disable this setting with care! Returns: A new ``ElectronicIntegrals``. """ alphas = PolynomialTensor.apply( function, *(op.alpha for op in operands), multi=multi, validate=validate ) betas: PolynomialTensor | list[PolynomialTensor] | None = None if any(not op.beta.is_empty() for op in operands): # If any beta-entry is non-empty, we have to perform this computation. # Empty tensors will be populated with their alpha-terms automatically. betas = PolynomialTensor.apply( function, *(op.alpha if op.beta.is_empty() else op.beta for op in operands), multi=multi, validate=validate, ) beta_alphas: PolynomialTensor | list[PolynomialTensor] | None = None if all(not op.beta_alpha.is_empty() for op in operands): # We can only perform this operation, when all beta_alpha tensors are non-empty. beta_alphas = PolynomialTensor.apply( function, *(op.beta_alpha for op in operands), multi=multi, validate=validate ) if multi: if betas is None: betas = [None] * len(alphas) if beta_alphas is None: beta_alphas = [None] * len(alphas) return [ cls(a, b, ba, validate=validate) for a, b, ba in zip(alphas, betas, beta_alphas) ] alphas = cast(PolynomialTensor, alphas) betas = cast(Optional[PolynomialTensor], betas) beta_alphas = cast(Optional[PolynomialTensor], beta_alphas) return cls(alphas, betas, beta_alphas, validate=validate) @classmethod def stack( cls, function: Callable[..., np.ndarray | SparseArray | Number], operands: Sequence[ElectronicIntegrals], *, validate: bool = True, ) -> ElectronicIntegrals: """Exposes the :meth:`qiskit_nature.second_q.operators.PolynomialTensor.stack` method. This behaves identical to the ``stack`` implementation of the ``PolynomialTensor``, applied to the :attr:`alpha`, :attr:`beta`, and :attr:`beta_alpha` attributes of the provided ``ElectronicIntegrals`` operands. This method is special, because it handles the scenario in which any operand has a non-empty :attr:`beta` attribute, in which case the empty-beta attributes of any other operands will be filled with :attr:`alpha` attributes of those operands. The :attr:`beta_alpha` attributes will only be handled if they are non-empty in all supplied operands. .. note:: When stacking arrays this will likely lead to array shapes which would fail the shape validation check. This is considered an advanced use case which is why the user is left to disable this check themselves, to ensure they know what they are doing. Args: function: the stacking function to apply to the internal arrays of the provided operands. This function must take a sequence of numpy (or sparse) arrays as its first argument. You should use :code:`functools.partial` if you need to provide keyword arguments (e.g. :code:`partial(np.stack, axis=-1)`). Common methods to use here are :func:`numpy.hstack` and :func:`numpy.vstack`. operands: a sequence of ``ElectronicIntegrals`` instances on which to operate. validate: when set to False, no validation will be performed. Disable this setting with care! Returns: A new ``ElectronicIntegrals``. """ alpha = PolynomialTensor.stack(function, [op.alpha for op in operands], validate=validate) beta: PolynomialTensor = None if any(not op.beta.is_empty() for op in operands): # If any beta-entry is non-empty, we have to perform this computation. # Empty tensors will be populated with their alpha-terms automatically. beta = PolynomialTensor.stack( function, [op.alpha if op.beta.is_empty() else op.beta for op in operands], validate=validate, ) beta_alpha: PolynomialTensor = None if all(not op.beta_alpha.is_empty() for op in operands): # We can only perform this operation, when all beta_alpha tensors are non-empty. beta_alpha = PolynomialTensor.stack( function, [op.beta_alpha for op in operands], validate=validate ) return cls(alpha, beta, beta_alpha, validate=validate) def split( self, function: Callable[..., np.ndarray | SparseArray | Number], indices_or_sections: int | Sequence[int], *, validate: bool = True, ) -> list[ElectronicIntegrals]: """Exposes the :meth:`qiskit_nature.second_q.operators.PolynomialTensor.split` method. This behaves identical to the ``split`` implementation of the ``PolynomialTensor``, applied to the :attr:`alpha`, :attr:`beta`, and :attr:`beta_alpha` attributes of the provided ``ElectronicIntegrals`` operands. .. note:: When splitting arrays this will likely lead to array shapes which would fail the shape validation check. This is considered an advanced use case which is why the user is left to disable this check themselves, to ensure they know what they are doing. Args: function: the splitting function to use. This function must take a single numpy (or sparse) array as its first input followed by a sequence of indices to split on. You should use :code:`functools.partial` if you need to provide keyword arguments (e.g. :code:`partial(np.split, axis=-1)`). Common methods to use here are :func:`numpy.hsplit` and :func:`numpy.vsplit`. indices_or_sections: a single index or sequence of indices to split on. validate: when set to False, no validation will be performed. Disable this setting with care! Returns: The new ``ElectronicIntegrals`` instances. """ alphas = self.alpha.split(function, indices_or_sections, validate=validate) betas: list[PolynomialTensor | None] if self.beta.is_empty(): betas = [None] * len(alphas) else: betas = self.beta.split(function, indices_or_sections, validate=validate) beta_alphas: list[PolynomialTensor | None] if self.beta_alpha.is_empty(): beta_alphas = [None] * len(alphas) else: beta_alphas = self.beta_alpha.split(function, indices_or_sections, validate=validate) return [ self.__class__(a, b, ba, validate=validate) for a, b, ba in zip(alphas, betas, beta_alphas) ] @classmethod def einsum( cls, einsum_map: dict[str, tuple[str, ...]], *operands: ElectronicIntegrals, validate: bool = True, ) -> ElectronicIntegrals: """Exposes the :meth:`qiskit_nature.second_q.operators.PolynomialTensor.einsum` method. This behaves identical to the ``einsum`` implementation of the ``PolynomialTensor``, applied to the :attr:`alpha`, :attr:`beta`, and :attr:`beta_alpha` attributes of the provided ``ElectronicIntegrals`` operands. This method is special, because it handles the scenario in which any operand has a non-empty :attr:`beta` attribute, in which case the empty-beta attributes of any other operands will be filled with :attr:`alpha` attributes of those operands. The :attr:`beta_alpha` attributes will only be handled if they are non-empty in all supplied operands. Args: einsum_map: a dictionary, mapping from :meth:`numpy.einsum` subscripts to a tuple of strings. These strings correspond to the keys of matrices to be extracted from the provided ``ElectronicIntegrals`` operands. The last string in this tuple indicates the key under which to store the result in the returned ``ElectronicIntegrals``. operands: a sequence of ``ElectronicIntegrals`` instances on which to operate. validate: when set to False, no validation will be performed. Disable this setting with care! Returns: A new ``ElectronicIntegrals``. """ alpha = PolynomialTensor.einsum( einsum_map, *(op.alpha for op in operands), validate=validate ) beta: PolynomialTensor = None if any(not op.beta.is_empty() for op in operands): # If any beta-entry is non-empty, we have to perform this computation. # Empty tensors will be populated with their alpha-terms automatically. beta = PolynomialTensor.einsum( einsum_map, *(op.alpha if op.beta.is_empty() else op.beta for op in operands), validate=validate, ) beta_alpha: PolynomialTensor = None if all(not op.beta_alpha.is_empty() for op in operands): # We can only perform this operation, when all beta_alpha tensors are non-empty. beta_alpha = PolynomialTensor.einsum( einsum_map, *(op.beta_alpha for op in operands), validate=validate ) return cls(alpha, beta, beta_alpha, validate=validate) # pylint: disable=invalid-name @classmethod def from_raw_integrals( cls, h1_a: np.ndarray | SparseArray, h2_aa: np.ndarray | SparseArray | None = None, h1_b: np.ndarray | SparseArray | None = None, h2_bb: np.ndarray | SparseArray | None = None, h2_ba: np.ndarray | SparseArray | None = None, *, validate: bool = True, auto_index_order: bool = True, ) -> ElectronicIntegrals: """Loads the provided integral matrices into an ``ElectronicIntegrals`` instance. When ``auto_index_order`` is enabled, :meth:`qiskit_nature.second_q.operators.tensor_ordering.find_index_order` will be used to determine the index ordering of the ``h2_aa`` matrix, based on which the two-body matrices will automatically be transformed to the physicist' order, which is required by the :class:`qiskit_nature.second_q.operators.PolynomialTensor`. Args: h1_a: the alpha-spin one-body integrals. h2_aa: the alpha-alpha-spin two-body integrals. h1_b: the beta-spin one-body integrals. h2_bb: the beta-beta-spin two-body integrals. h2_ba: the beta-alpha-spin two-body integrals. validate: whether or not to validate the integral matrices. Disable this setting with care! auto_index_order: whether or not to automatically convert the matrices to physicists' order. Raises: QiskitNatureError: if `auto_index_order=True`, upon encountering an invalid :class:`qiskit_nature.second_q.operators.tensor_ordering.IndexType`. Returns: The resulting ``ElectronicIntegrals``. """ alpha_dict = {"+-": h1_a} if h2_aa is not None: if auto_index_order and not isinstance(h2_aa, SymmetricTwoBodyIntegrals): index_order = find_index_order(h2_aa) if index_order == IndexType.UNKNOWN: raise QiskitNatureError( f"The index ordering of the `h2_aa` argument, {index_order}, is invalid.\n" "Provide the two-body matrices in either chemists' or physicists' order, " "or disable the automatic transformation to enforce these matrices to be " "used (`auto_index_order=False`)." ) h2_aa = to_physicist_ordering(h2_aa, index_order=index_order) if h2_bb is not None: h2_bb = to_physicist_ordering(h2_bb, index_order=index_order) if h2_ba is not None: h2_ba = to_physicist_ordering(h2_ba, index_order=index_order) alpha_dict["++--"] = h2_aa alpha = PolynomialTensor(alpha_dict, validate=validate) beta = None beta_dict = {} if h1_b is not None: beta_dict["+-"] = h1_b if h2_bb is not None: beta_dict["++--"] = h2_bb if beta_dict: beta = PolynomialTensor(beta_dict, validate=validate) beta_alpha = None if h2_ba is not None: beta_alpha = PolynomialTensor({"++--": h2_ba}, validate=validate) return cls(alpha, beta, beta_alpha, validate=validate) def second_q_coeffs(self) -> PolynomialTensor: """Constructs the total ``PolynomialTensor`` contained the second-quantized coefficients. This function constructs the spin-orbital basis tensor as a :class:`qiskit_nature.second_q.operators.PolynomialTensor`, by arranging the :attr:`alpha` and :attr:`beta` attributes in a block-ordered fashion (up-spin integrals cover the first part, down-spin integrals the second part of the resulting register space). If the :attr:`beta` and/or :attr:`beta_alpha` attributes are empty, the :attr:`alpha` data will be used in their place. Returns: The ``PolynomialTensor`` representing the entire system. """ beta_empty = self.beta.is_empty() beta_alpha_empty = self.beta_alpha.is_empty() kron_one_body = np.zeros((2, 2)) kron_two_body = np.zeros((2, 2, 2, 2)) kron_tensor = PolynomialTensor({"": 1.0, "+-": kron_one_body, "++--": kron_two_body}) ba_index = (1, 0, 0, 1) ab_index = (0, 1, 1, 0) if beta_empty and beta_alpha_empty: kron_one_body[(0, 0)] = 1 kron_one_body[(1, 1)] = 1 kron_two_body[(0, 0, 0, 0)] = 0.5 kron_two_body[(1, 1, 1, 1)] = 0.5 aa_tensor = self.alpha.get("++--", None) if aa_tensor is not None: if not isinstance(aa_tensor, Tensor): aa_tensor = Tensor(aa_tensor) ba_index = cast( Tuple[int, int, int, int], tuple(aa_tensor._reverse_label_template(ba_index)) ) ab_index = cast( Tuple[int, int, int, int], tuple(aa_tensor._reverse_label_template(ab_index)) ) kron_two_body[ba_index] = 0.5 kron_two_body[ab_index] = 0.5 tensor_blocked_spin_orbitals = PolynomialTensor.apply(np.kron, kron_tensor, self.alpha) return cast(PolynomialTensor, tensor_blocked_spin_orbitals) tensor_blocked_spin_orbitals = PolynomialTensor({}) # pure alpha spin kron_one_body[(0, 0)] = 1 kron_two_body[(0, 0, 0, 0)] = 0.5 tensor_blocked_spin_orbitals += PolynomialTensor.apply(np.kron, kron_tensor, self.alpha) kron_one_body[(0, 0)] = 0 kron_two_body[(0, 0, 0, 0)] = 0 # pure beta spin kron_one_body[(1, 1)] = 1 kron_two_body[(1, 1, 1, 1)] = 0.5 tensor_blocked_spin_orbitals += PolynomialTensor.apply(np.kron, kron_tensor, self.beta) kron_one_body[(1, 1)] = 0 kron_two_body[(1, 1, 1, 1)] = 0 # beta_alpha spin if not beta_alpha_empty: kron_tensor = PolynomialTensor({"++--": kron_two_body}) ba_tensor = self.beta_alpha["++--"] if not isinstance(ba_tensor, Tensor): ba_tensor = Tensor(ba_tensor) ba_index = cast( Tuple[int, int, int, int], tuple(ba_tensor._reverse_label_template(ba_index)) ) ab_index = cast( Tuple[int, int, int, int], tuple(ba_tensor._reverse_label_template(ab_index)) ) kron_two_body[ba_index] = 0.5 tensor_blocked_spin_orbitals += PolynomialTensor.apply( np.kron, kron_tensor, self.beta_alpha ) kron_two_body[ba_index] = 0 # extract transposed beta_alpha term kron_two_body[ab_index] = 0.5 tensor_blocked_spin_orbitals += PolynomialTensor.apply( np.kron, kron_tensor, self.alpha_beta ) kron_two_body[ab_index] = 0 return cast(PolynomialTensor, tensor_blocked_spin_orbitals) def trace_spin(self) -> PolynomialTensor: """Returns a :class:`~.PolynomialTensor` where the spin components have been traced out. This will sum the :attr:`alpha` and :attr:`beta` components, tracing out the spin. Returns: A ``PolynomialTensor`` with the spin traced out. """ beta_empty = self.beta.is_empty() beta_alpha_empty = self.beta_alpha.is_empty() if beta_empty and beta_alpha_empty: return cast(PolynomialTensor, 2.0 * self.alpha) two_body = self.two_body tensor_spin_traced = PolynomialTensor({}) tensor_spin_traced += self.alpha tensor_spin_traced += self.beta if beta_alpha_empty: tensor_spin_traced += two_body.alpha tensor_spin_traced += two_body.beta else: tensor_spin_traced += two_body.beta_alpha tensor_spin_traced += two_body.alpha_beta return tensor_spin_traced
qiskit-nature/qiskit_nature/second_q/operators/electronic_integrals.py/0
{ "file_path": "qiskit-nature/qiskit_nature/second_q/operators/electronic_integrals.py", "repo_id": "qiskit-nature", "token_count": 14585 }
131
# This code is part of a Qiskit project. # # (C) Copyright IBM 2021, 2023. # # 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. """The Electronic Structure Problem class.""" from __future__ import annotations from functools import partial from typing import cast, Callable, List, Optional, Union, TYPE_CHECKING import numpy as np from qiskit_algorithms import EigensolverResult, MinimumEigensolverResult from qiskit.quantum_info.analysis.z2_symmetries import Z2Symmetries from qiskit_nature.exceptions import QiskitNatureError from qiskit_nature.second_q.circuit.library.initial_states.hartree_fock import ( hartree_fock_bitstring_mapped, ) from qiskit_nature.second_q.mappers import QubitMapper from qiskit_nature.second_q.hamiltonians import ElectronicEnergy from qiskit_nature.second_q.properties import Interpretable from .electronic_structure_result import ElectronicStructureResult from .electronic_properties_container import ElectronicPropertiesContainer from .eigenstate_result import EigenstateResult from .base_problem import BaseProblem from .electronic_basis import ElectronicBasis if TYPE_CHECKING: from qiskit_nature.second_q.formats.molecule_info import MoleculeInfo class ElectronicStructureProblem(BaseProblem): r"""The Electronic Structure Problem. This class represents the problem of the electronic Schrödinger equation: .. math:: \hat{H_{el}}|\Psi\rangle = E_{el}|\Psi\rangle, where :math:`\hat{H_{el}}` is the :class:`qiskit_nature.second_q.hamiltonians.ElectronicEnergy` hamiltonian, :math:`\Psi` is the wave function of the system and :math:`E_{el}` is the eigenvalue. When passed to a :class:`qiskit_nature.second_q.algorithms.GroundStateSolver`, you will be solving for the ground-state energy, :math:`E_0`. This class has various attributes (see below) which allow you to add additional information about the problem which you are trying to solve, which can be used by various modules in the stack. For example, specifying the number of particles in the system :attr:`num_particles` is useful (and even required) for many components that interact with this problem instance to make your life easier (for example the :class:`qiskit_nature.second_q.transformers.ActiveSpaceTransformer`). In the fermionic case the default filter ensures that the number of particles is being preserved. .. note:: The default filter_criterion assumes a singlet spin configuration. This means, that the number of alpha-spin electrons is equal to the number of beta-spin electrons. If the :class:`~qiskit_nature.second_q.properties.AngularMomentum` property is available, one can correctly filter a non-singlet spin configuration with a custom `filter_criterion` similar to the following: .. code-block:: python import numpy as np from qiskit_algorithms import NumPyMinimumEigensolver expected_spin = 2 expected_num_electrons = 6 def filter_criterion_custom(eigenstate, eigenvalue, aux_values): num_particles_aux = aux_values["ParticleNumber"][0] total_angular_momentum_aux = aux_values["AngularMomentum"][0] return ( np.isclose(total_angular_momentum_aux, expected_spin) and np.isclose(num_particles_aux, expected_num_electrons) ) solver = NumPyEigensolver() solver.filter_criterion = filter_criterion_custom The following attributes can be read and updated once the ``ElectronicStructureProblem`` object has been constructed. Attributes: properties (ElectronicStructureProblem): a container for additional observable operator factories. molecule (MoleculeInfo | None): a container for molecular system data. basis (ElectronicBasis | None): the electronic basis of all contained orbital coefficients. num_spatial_orbitals (int | tuple[int, int] | None): the number of spatial orbitals in the system. reference_energy (float | None): a reference energy for the ground state of the problem. orbital_energies (np.ndarray | None): the energy values of the alpha-spin orbitals. orbital_energies_b (np.ndarray | None): the energy values of the beta-spin orbitals. """ def __init__(self, hamiltonian: ElectronicEnergy) -> None: """ Args: hamiltonian: the Hamiltonian of this problem. """ super().__init__(hamiltonian) self.properties: ElectronicPropertiesContainer = ElectronicPropertiesContainer() self.molecule: "MoleculeInfo" | None = None self.basis: ElectronicBasis | None = None self._num_particles: int | tuple[int, int] | None = None self.num_spatial_orbitals: int | None = hamiltonian.register_length self._orbital_occupations: np.ndarray | None = None self._orbital_occupations_b: np.ndarray | None = None self.reference_energy: float | None = None self.orbital_energies: np.ndarray | None = None self.orbital_energies_b: np.ndarray | None = None @property def hamiltonian(self) -> ElectronicEnergy: return cast(ElectronicEnergy, self._hamiltonian) @property def nuclear_repulsion_energy(self) -> float | None: """The nuclear repulsion energy. See :attr:`qiskit_nature.second_q.hamiltonians.ElectronicEnergy.nuclear_repulsion_energy` for more details. """ return self.hamiltonian.nuclear_repulsion_energy @property def num_particles(self) -> tuple[int, int] | None: """The number of particles in alpha- and beta-spin.""" if self._num_particles is None: return None if isinstance(self._num_particles, tuple): return self._num_particles num_beta = self._num_particles // 2 num_alpha = self._num_particles - num_beta return (num_alpha, num_beta) @num_particles.setter def num_particles(self, num_particles: int | tuple[int, int] | None) -> None: self._num_particles = num_particles @property def num_alpha(self) -> int | None: """The number of alpha-spin particles.""" if self.num_particles is None: return None return self.num_particles[0] @property def num_beta(self) -> int | None: """The number of beta-spin particles.""" if self.num_particles is None: return None return self.num_particles[1] @property def num_spin_orbitals(self) -> int | None: """The total number of spin orbitals.""" if self.num_spatial_orbitals is None: return None return 2 * self.num_spatial_orbitals @property def orbital_occupations(self) -> np.ndarray | None: """The occupations of the alpha-spin orbitals.""" if self._orbital_occupations is not None: return self._orbital_occupations if self.basis != ElectronicBasis.MO: return None num_orbs = self.num_spatial_orbitals if num_orbs is None: return None num_alpha = self.num_alpha if num_alpha is None: return None return np.asarray([1.0] * num_alpha + [0.0] * (num_orbs - num_alpha)) @orbital_occupations.setter def orbital_occupations(self, occ: np.ndarray | None) -> None: self._orbital_occupations = occ @property def orbital_occupations_b(self) -> np.ndarray | None: """The occupations of the beta-spin orbitals.""" if self._orbital_occupations_b is not None: return self._orbital_occupations_b if self.basis != ElectronicBasis.MO: return None num_orbs = self.num_spatial_orbitals if num_orbs is None: return None num_beta = self.num_beta if num_beta is None: return None return np.asarray([1.0] * num_beta + [0.0] * (num_orbs - num_beta)) @orbital_occupations_b.setter def orbital_occupations_b(self, occ: np.ndarray | None) -> None: self._orbital_occupations_b = occ def interpret( self, raw_result: Union[EigenstateResult, EigensolverResult, MinimumEigensolverResult], ) -> ElectronicStructureResult: """Interprets an EigenstateResult in the context of this problem. Args: raw_result: an eigenstate result object. Returns: An electronic structure result. """ eigenstate_result = super().interpret(raw_result) result = ElectronicStructureResult() result.combine(eigenstate_result) if isinstance(self.hamiltonian, Interpretable): self.hamiltonian.interpret(result) for prop in self.properties: if isinstance(prop, Interpretable): prop.interpret(result) result.computed_energies = np.asarray([e.real for e in eigenstate_result.eigenvalues]) if self.reference_energy is not None: result.hartree_fock_energy = self.reference_energy return result def get_default_filter_criterion( self, ) -> Optional[Callable[[Union[List, np.ndarray], float, Optional[List[float]]], bool]]: """Returns a default filter criterion method to filter the eigenvalues computed by the eigensolver. For more information see also :meth:`~qiskit_algorithms.NumPyEigensolver.filter_criterion`. This particular default ensures that the total number of particles is conserved and that the angular momentum (if computed) evaluates to 0. """ # pylint: disable=unused-argument def filter_criterion(self, eigenstate, eigenvalue, aux_values): eval_num_particles = aux_values.get("ParticleNumber", None) if eval_num_particles is None: return True num_particles_close = np.isclose(eval_num_particles[0], self.num_alpha + self.num_beta) eval_angular_momentum = aux_values.get("AngularMomentum", None) if eval_angular_momentum is None: return num_particles_close angular_momentum_close = np.isclose(eval_angular_momentum[0], 0.0) return num_particles_close and angular_momentum_close return partial(filter_criterion, self) def _symmetry_sector_locator( self, z2_symmetries: Z2Symmetries, mapper: QubitMapper, ) -> Optional[List[int]]: """Given the detected Z2Symmetries this determines the correct sector of the tapered operator that contains the ground state we need and returns that information. Args: z2_symmetries: the z2 symmetries object. mapper: the ``QubitMapper`` used for the operator conversion that symmetries are to be determined for. Raises: QiskitNatureError: if the :attr:`num_particles` attribute is ``None``. Returns: The sector of the tapered operators with the problem solution. """ if self.num_particles is None: raise QiskitNatureError( "Determining the correct symmetry sector for Z2 symmetry reduction requires the " "number of particles to be set on the problem instance. Please set " "ElectronicStructureProblem.num_particles or disable the use of Z2Symmetries to " "fix this." ) num_particles = self.num_particles if not isinstance(num_particles, tuple): num_particles = (self.num_alpha, self.num_beta) hf_bitstr = hartree_fock_bitstring_mapped( num_spatial_orbitals=self.num_spatial_orbitals, num_particles=num_particles, qubit_mapper=mapper, ) sector = ElectronicStructureProblem._pick_sector(z2_symmetries, hf_bitstr) return sector @staticmethod def _pick_sector(z2_symmetries: Z2Symmetries, hf_str: List[bool]) -> List[int]: # Finding all the symmetries using the find_Z2_symmetries: taper_coeff: List[int] = [] for sym in z2_symmetries.symmetries: coeff = -1 if np.logical_xor.reduce(np.logical_and(sym.z, hf_str)) else 1 taper_coeff.append(coeff) return taper_coeff
qiskit-nature/qiskit_nature/second_q/problems/electronic_structure_problem.py/0
{ "file_path": "qiskit-nature/qiskit_nature/second_q/problems/electronic_structure_problem.py", "repo_id": "qiskit-nature", "token_count": 5006 }
132
# This code is part of a Qiskit project. # # (C) Copyright IBM 2021, 2023. # # 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. """The OccupiedModals property.""" from __future__ import annotations from typing import Mapping, Sequence import qiskit_nature # pylint: disable=unused-import from qiskit_nature.second_q.operators import VibrationalOp class OccupiedModals: """The OccupiedModals property. The following attributes can be set via the initializer but can also be read and updated once the ``OccupiedModals`` object has been constructed. Attributes: num_modals (Sequence[int]): the number of modals per mode in the system. """ def __init__(self, num_modals: Sequence[int]) -> None: """ Args: num_modals: the number of modals for each mode. """ self.num_modals = num_modals def second_q_ops(self) -> Mapping[str, VibrationalOp]: """Returns the second quantized operators indicating the occupied modals per mode. Returns: A mapping of strings to `VibrationalOp` objects. """ return {str(mode): self._get_mode_op(mode) for mode in range(len(self.num_modals))} def _get_mode_op(self, mode: int) -> VibrationalOp: """Constructs an operator to evaluate which modal of a given mode is occupied. Args: mode: the mode index. Returns: The operator to evaluate which modal of the given mode is occupied. """ labels: dict[str, complex] = {} for modal in range(self.num_modals[mode]): labels[f"+_{mode}_{modal} -_{mode}_{modal}"] = 1.0 return VibrationalOp(labels, self.num_modals) def interpret( self, result: "qiskit_nature.second_q.problems.EigenstateResult" # type: ignore[name-defined] ) -> None: """Interprets an :class:`~qiskit_nature.second_q.problems.EigenstateResult` in this property's context. Args: result: the result to add meaning to. """ result.num_occupied_modals_per_mode = [] if not isinstance(result.aux_operators_evaluated, list): aux_operators_evaluated = [result.aux_operators_evaluated] else: aux_operators_evaluated = result.aux_operators_evaluated for aux_op_eigenvalues in aux_operators_evaluated: occ_modals = [] for mode, _ in enumerate(self.num_modals): _key = str(mode) if isinstance(aux_op_eigenvalues, dict) else mode if aux_op_eigenvalues[_key] is not None: occ_modals.append(aux_op_eigenvalues[_key].real) else: occ_modals.append(None) result.num_occupied_modals_per_mode.append(occ_modals)
qiskit-nature/qiskit_nature/second_q/properties/occupied_modals.py/0
{ "file_path": "qiskit-nature/qiskit_nature/second_q/properties/occupied_modals.py", "repo_id": "qiskit-nature", "token_count": 1274 }
133
--- deprecations: - | All currently existing drivers have been moved from `qiskit_nature.drivers` to `qiskit_nature.drivers.second_quantization`. This is necessary because future additions to Nature which reside in parallel to the `second_quantization` submodules will not be using these drivers. Making this separation reflects that in the code structure. The same change was necessary for the existing `qiskit_nature.transformers`.
qiskit-nature/releasenotes/notes/0.2/relocate-drivers-fac59a504b5bc986.yaml/0
{ "file_path": "qiskit-nature/releasenotes/notes/0.2/relocate-drivers-fac59a504b5bc986.yaml", "repo_id": "qiskit-nature", "token_count": 124 }
134
--- features: - | Support was added for generalized fermionic excitations. These kinds of excitations are effectively ignoring the orbital occupancies and instead yield all possible excitations within a spin species. Furthermore, another option was added which can be used to enabled spin- flipped excitations.
qiskit-nature/releasenotes/notes/0.3/generalized-fermionic-excitations-1d345d179e097896.yaml/0
{ "file_path": "qiskit-nature/releasenotes/notes/0.3/generalized-fermionic-excitations-1d345d179e097896.yaml", "repo_id": "qiskit-nature", "token_count": 82 }
135
--- features: - | Adds :class:`~.BogoliubovTransform`. This class constructs a circuit that performs a Bogoliubov transform, which is a single-particle basis change that may or may not conserve particle number. See the `Quadratic Hamiltonians and Slater determinants <tutorials/11_quadratic_hamiltonian_and_slater_determinants.ipynb>`_ tutorial for a demonstration of how to use this class.
qiskit-nature/releasenotes/notes/0.4/bogoliubov-transform-885eb6442172c76e.yaml/0
{ "file_path": "qiskit-nature/releasenotes/notes/0.4/bogoliubov-transform-885eb6442172c76e.yaml", "repo_id": "qiskit-nature", "token_count": 131 }
136
--- features: - | Adds a new HDF5-integration to support storing and loading of (mostly) Property objects using HDF5 files. A similar feature existed in the legacy QMolecule object but the new implementation is handled more general to enable leveraging this integration throughout more parts of the stack in the future. To store a driver result of the new drivers in a file you can do: .. code-block:: python from qiskit_nature.hdf5 import save_to_hdf5 my_driver_result = driver.run() save_to_hdf5(my_driver_result, "my_driver_result.hdf5") and to load it again you would do: .. code-block:: python from qiskit_nature.hdf5 import load_from_hdf5 my_driver_result = load_from_hdf5("my_driver_result.hdf5")
qiskit-nature/releasenotes/notes/0.4/hdf5-integration-b08c31426d1fdf9e.yaml/0
{ "file_path": "qiskit-nature/releasenotes/notes/0.4/hdf5-integration-b08c31426d1fdf9e.yaml", "repo_id": "qiskit-nature", "token_count": 278 }
137
--- features: - | :class:`~qiskit_nature.runtime.VQEClient` now extends VariationalAlgorithm, meaning users can now implement :class:`~qiskit_nature.algorithms.pes_samplers.BOPESSampler` using bootstrapping, which works similarly now with VQEClient :class:`~qiskit_nature.runtime.VQEClient` as it did previously with local VQE.
qiskit-nature/releasenotes/notes/0.4/vqeclient-extends-variationalalg-eb5b3f951405fd16.yaml/0
{ "file_path": "qiskit-nature/releasenotes/notes/0.4/vqeclient-extends-variationalalg-eb5b3f951405fd16.yaml", "repo_id": "qiskit-nature", "token_count": 135 }
138
--- fixes: - | Fixes a bug where numpy integer objects were causing integer-based isinstance checks to fail. This also avoids such problems by explicitly converting integer values to Python integers when loading properties from HDF5 files.
qiskit-nature/releasenotes/notes/0.5/fix-isinstance-integer-checks-50f7614393e68e87.yaml/0
{ "file_path": "qiskit-nature/releasenotes/notes/0.5/fix-isinstance-integer-checks-50f7614393e68e87.yaml", "repo_id": "qiskit-nature", "token_count": 62 }
139
--- deprecations: - | Deprecated the :meth:`~qiskit_nature.second_q.operators.FermionicOp.to_matrix` method. The same functionality can be achieved via the qubit-operator after applying the :class:`~qiskit_nature.second_q.mappers.JordanWignerMapper` (one only needs to adapt to the different basis state ordering due to the reversed bitstring endianness). .. code-block:: python import numpy as np from qiskit_nature.second_q.mappers import JordanWignerMapper from qiskit_nature.second_q.operators import FermionicOp from qiskit_nature.settings import settings settings.use_pauli_sum_op = False op = FermionicOp({"+_0": 1, "-_1": 1}) mat = op.to_matrix().todense() jw = JordanWignerMapper().map(op) print(np.allclose(mat, jw.to_matrix(), atol=1e-8)) # prints False for pauli in jw.paulis: pauli.x = pauli.x[::-1] pauli.z = pauli.z[::-1] print(np.allclose(mat, jw.to_matrix(), atol=1e-8)) # prints True
qiskit-nature/releasenotes/notes/0.6/deprecate-fermionic-op-to-matrix-74b182129fbb0171.yaml/0
{ "file_path": "qiskit-nature/releasenotes/notes/0.6/deprecate-fermionic-op-to-matrix-74b182129fbb0171.yaml", "repo_id": "qiskit-nature", "token_count": 447 }
140
--- fixes: - | Fixes the :meth:`~qiskit_nature.second_q.operators.VibrationalOp.normal_order` method, which in turn corrects the commutation relations of this operator type.
qiskit-nature/releasenotes/notes/0.6/fix-vibrational-op-commutation-5cbda6833c0d5232.yaml/0
{ "file_path": "qiskit-nature/releasenotes/notes/0.6/fix-vibrational-op-commutation-5cbda6833c0d5232.yaml", "repo_id": "qiskit-nature", "token_count": 63 }
141
--- features: - | Adds a new lattice class, :class:`~qiskit_nature.second_q.hamiltonians.lattices.HexagonalLattice` for the generation of hexagonal lattices. You construct a hexagonal lattice by specifying the number of rows and columns of hexagons. You can also specify the edge- and on-site-parameters. Below is a simple example to illustrate this: .. code-block:: python from qiskit_nature.second_q.hamiltonians.lattices import HexagonalLattice lattice = HexagonalLattice( 2, 3, edge_parameter=1.0, onsite_parameter=1.5, )
qiskit-nature/releasenotes/notes/0.7/add-hexagonal-lattice-a981f1b5c832a154.yaml/0
{ "file_path": "qiskit-nature/releasenotes/notes/0.7/add-hexagonal-lattice-a981f1b5c832a154.yaml", "repo_id": "qiskit-nature", "token_count": 257 }
142
--- fixes: - | Fixes the behavior of :meth:`.SpinOp.to_matrix` for operators acting on more than a single spin.
qiskit-nature/releasenotes/notes/0.7/fix-spin-op-to-matrix-e84594248fc49fd7.yaml/0
{ "file_path": "qiskit-nature/releasenotes/notes/0.7/fix-spin-op-to-matrix-e84594248fc49fd7.yaml", "repo_id": "qiskit-nature", "token_count": 45 }
143
--- features: - | The class :class:`.second_q.mappers.ModeBasedMapper` has been added to implement mode based mapping via a Pauli table (previously part of :class:`.second_q.mappers.QubitMapper`). upgrade: - | :meth:`.ModeBasedMapper.pauli_table` is now an instance method of all :class:`.ModeBasedMapper` subclasses (previously a class method of :class:`.QubitMapper`) - | Methods ``.pauli_table``, ``.sparse_pauli_operators``, and ``.mode_based_mapping`` have been removed from :class:`.QubitMapper`.
qiskit-nature/releasenotes/notes/improve-mappers-b55cb0ca5fd656e4.yaml/0
{ "file_path": "qiskit-nature/releasenotes/notes/improve-mappers-b55cb0ca5fd656e4.yaml", "repo_id": "qiskit-nature", "token_count": 198 }
144
# This code is part of a Qiskit project. # # (C) Copyright IBM 2020, 2023. # # 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. """ Test Numerical qEOM excited states calculation.""" from __future__ import annotations import unittest from test import QiskitNatureTestCase from ddt import ddt, named_data import numpy as np from qiskit_algorithms import VQE from qiskit_algorithms.optimizers import SLSQP from qiskit_algorithms.utils import algorithm_globals from qiskit.primitives import Estimator from qiskit_nature.units import DistanceUnit from qiskit_nature.second_q.circuit.library import HartreeFock, UCCSD from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.mappers import ( JordanWignerMapper, ParityMapper, ) from qiskit_nature.second_q.mappers import QubitMapper, TaperedQubitMapper from qiskit_nature.second_q.operators.fermionic_op import FermionicOp from qiskit_nature.second_q.algorithms import GroundStateEigensolver, QEOM from qiskit_nature.second_q.algorithms.excited_states_solvers.qeom import EvaluationRule import qiskit_nature.optionals as _optionals from .resources.expected_transition_amplitudes import reference_trans_amps @ddt class TestNumericalQEOMObscalculation(QiskitNatureTestCase): """Test qEOM excited state observables calculation.""" @unittest.skipIf(not _optionals.HAS_PYSCF, "pyscf not available.") def setUp(self): super().setUp() algorithm_globals.random_seed = 8 self.driver = PySCFDriver( atom="H .0 .0 .0; H .0 .0 0.75", unit=DistanceUnit.ANGSTROM, charge=0, spin=0, basis="sto3g", ) self.reference_energies = [ -1.8427016, -1.8427016 + 0.5943372, -1.8427016 + 0.95788352, -1.8427016 + 1.5969296, ] self.reference_trans_amps = reference_trans_amps self.electronic_structure_problem = self.driver.run() self.num_particles = self.electronic_structure_problem.num_particles def _hamiltonian_derivative(self): identity = FermionicOp.one() esp_plus = PySCFDriver( atom="H .0 .0 .0; H .0 .0 0.7501", unit=DistanceUnit.ANGSTROM, charge=0, spin=0, basis="sto3g", ).run() esp_minus = PySCFDriver( atom="H .0 .0 .0; H .0 .0 0.7049", unit=DistanceUnit.ANGSTROM, charge=0, spin=0, basis="sto3g", ).run() hamiltonian_op_plus, _ = esp_plus.second_q_ops() nre_plus = esp_plus.nuclear_repulsion_energy nre_op_plus = identity * nre_plus hamiltonian_op_minus, _ = esp_minus.second_q_ops() nre_minus = esp_minus.nuclear_repulsion_energy nre_op_minus = identity * nre_minus delta_hamiltonian = ( 1 / (2 * 0.0001) * (hamiltonian_op_plus + nre_op_plus - hamiltonian_op_minus - nre_op_minus) ) return delta_hamiltonian.simplify() def _assert_energies(self, computed, references, *, places=4): with self.subTest("same number of energies"): self.assertEqual(len(computed), len(references)) with self.subTest("ground state"): self.assertAlmostEqual(computed[0], references[0], places=places) for i in range(1, len(computed)): with self.subTest(f"{i}. excited state"): self.assertAlmostEqual(computed[i], references[i], places=places) def _assert_transition_amplitudes(self, computed, references, *, places=4): with self.subTest("same number of indices"): self.assertEqual(len(computed), len(references)) with self.subTest("operators computed are reference operators"): self.assertEqual(computed.keys(), references.keys()) with self.subTest("same transition amplitude absolute value"): for key in computed.keys(): for opkey in computed[key].keys(): trans_amp = np.abs(computed[key][opkey][0]) trans_amp_expected = np.abs(references[key][opkey][0]) self.assertAlmostEqual(trans_amp, trans_amp_expected, places=places) def _compute_and_assert_qeom_aux_eigenvalues(self, mapper: QubitMapper): hamiltonian_op, _ = self.electronic_structure_problem.second_q_ops() aux_ops = {"hamiltonian": hamiltonian_op} estimator = Estimator() ansatz = UCCSD( self.electronic_structure_problem.num_spatial_orbitals, self.electronic_structure_problem.num_particles, mapper, initial_state=HartreeFock( self.electronic_structure_problem.num_spatial_orbitals, self.electronic_structure_problem.num_particles, mapper, ), ) solver = VQE(estimator, ansatz, SLSQP()) solver.initial_point = [0] * ansatz.num_parameters gsc = GroundStateEigensolver(mapper, solver) esc = QEOM(gsc, estimator, "sd", aux_eval_rules=EvaluationRule.DIAG) results = esc.solve(self.electronic_structure_problem, aux_operators=aux_ops) energies_recalculated = np.zeros_like(results.computed_energies) for estate, aux_op in enumerate(results.aux_operators_evaluated): energies_recalculated[estate] = aux_op["hamiltonian"] self._assert_energies(results.computed_energies, self.reference_energies) self._assert_energies(energies_recalculated, self.reference_energies) def _compute_and_assert_qeom_trans_amp(self, mapper: QubitMapper): aux_eval_rules = { "hamiltonian_derivative": [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] } aux_ops = {"hamiltonian_derivative": self._hamiltonian_derivative()} estimator = Estimator() ansatz = UCCSD( self.electronic_structure_problem.num_spatial_orbitals, self.electronic_structure_problem.num_particles, mapper, initial_state=HartreeFock( self.electronic_structure_problem.num_spatial_orbitals, self.electronic_structure_problem.num_particles, mapper, ), ) solver = VQE(estimator, ansatz, SLSQP()) solver.initial_point = [0] * ansatz.num_parameters gsc = GroundStateEigensolver(mapper, solver) esc = QEOM(gsc, estimator, excitations="sd", aux_eval_rules=aux_eval_rules) results = esc.solve(self.electronic_structure_problem, aux_operators=aux_ops) transition_amplitudes = results.raw_result.transition_amplitudes self._assert_transition_amplitudes( transition_amplitudes, self.reference_trans_amps, places=3 ) @named_data( ["JWM", JordanWignerMapper()], ["PM", ParityMapper()], ["PM_TQR", ParityMapper(num_particles=(1, 1))], ) def test_aux_ops_qeom(self, mapper: QubitMapper): """Test QEOM evaluation of excited state properties""" self._compute_and_assert_qeom_aux_eigenvalues(mapper) @named_data( ["JW", lambda n, esp: TaperedQubitMapper(JordanWignerMapper())], ["JW_Z2", lambda n, esp: esp.get_tapered_mapper(JordanWignerMapper())], ["PM", lambda n, esp: TaperedQubitMapper(ParityMapper())], ["PM_Z2", lambda n, esp: esp.get_tapered_mapper(ParityMapper())], ["PM_TQR", lambda n, esp: TaperedQubitMapper(ParityMapper(n))], ["PM_TQR_Z2", lambda n, esp: esp.get_tapered_mapper(ParityMapper(n))], ) def test_aux_ops_qeom_taperedmapper(self, tapered_mapper_creator): """Test QEOM evaluation of excited state properties""" tapered_mapper = tapered_mapper_creator( self.num_particles, self.electronic_structure_problem ) self._compute_and_assert_qeom_aux_eigenvalues(tapered_mapper) @named_data( ["JWM", JordanWignerMapper()], ["PM", ParityMapper()], ["PM_TQR", ParityMapper(num_particles=(1, 1))], ) def test_trans_amps_qeom(self, mapper: QubitMapper): """Test QEOM evaluation of transition amplitudes""" self._compute_and_assert_qeom_trans_amp(mapper) @named_data( ["JW", lambda n, esp: TaperedQubitMapper(JordanWignerMapper())], ["JW_Z2", lambda n, esp: esp.get_tapered_mapper(JordanWignerMapper())], ["PM", lambda n, esp: TaperedQubitMapper(ParityMapper())], ["PM_Z2", lambda n, esp: esp.get_tapered_mapper(ParityMapper())], ["PM_TQR", lambda n, esp: TaperedQubitMapper(ParityMapper(n))], ["PM_TQR_Z2", lambda n, esp: esp.get_tapered_mapper(ParityMapper(n))], ) def test_trans_amps_qeom_taperedmapper(self, tapered_mapper_creator): """Test QEOM evaluation of transition amplitudes""" tapered_mapper = tapered_mapper_creator( self.num_particles, self.electronic_structure_problem ) self._compute_and_assert_qeom_trans_amp(tapered_mapper) if __name__ == "__main__": unittest.main()
qiskit-nature/test/second_q/algorithms/excited_state_solvers/test_excited_states_solvers_auxiliaries.py/0
{ "file_path": "qiskit-nature/test/second_q/algorithms/excited_state_solvers/test_excited_states_solvers_auxiliaries.py", "repo_id": "qiskit-nature", "token_count": 4296 }
145
# This code is part of a Qiskit project. # # (C) Copyright IBM 2021, 2023. # # 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. """Test the PUCCD Ansatz.""" from test import QiskitNatureTestCase from test.second_q.circuit.library.ansatzes.test_ucc import assert_ucc_like_ansatz import unittest from ddt import ddt, data, unpack from qiskit_nature import QiskitNatureError from qiskit_nature.second_q.circuit.library import PUCCD from qiskit_nature.second_q.mappers import JordanWignerMapper from qiskit_nature.second_q.operators import FermionicOp @ddt class TestPUCC(QiskitNatureTestCase): """Tests for the PUCCD Ansatz.""" @unpack @data( ( 2, (1, 1), [FermionicOp({"+_0 +_2 -_1 -_3": 1j, "+_3 +_1 -_2 -_0": -1j}, num_spin_orbitals=4)], ), ( 4, (2, 2), [ FermionicOp({"+_0 +_4 -_2 -_6": 1j, "+_6 +_2 -_4 -_0": -1j}, num_spin_orbitals=8), FermionicOp({"+_0 +_4 -_3 -_7": 1j, "+_7 +_3 -_4 -_0": -1j}, num_spin_orbitals=8), FermionicOp({"+_1 +_5 -_2 -_6": 1j, "+_6 +_2 -_5 -_1": -1j}, num_spin_orbitals=8), FermionicOp({"+_1 +_5 -_3 -_7": 1j, "+_7 +_3 -_5 -_1": -1j}, num_spin_orbitals=8), ], ), ) def test_puccd_ansatz(self, num_spatial_orbitals, num_particles, expect): """Tests the PUCCD Ansatz.""" mapper = JordanWignerMapper() ansatz = PUCCD( qubit_mapper=mapper, num_particles=num_particles, num_spatial_orbitals=num_spatial_orbitals, ) assert_ucc_like_ansatz(self, ansatz, num_spatial_orbitals, expect) @unpack @data( ( 2, (1, 1), (True, True), [ FermionicOp({"+_0 -_1": 1j, "+_1 -_0": -1j}, num_spin_orbitals=4), FermionicOp({"+_2 -_3": 1j, "+_3 -_2": -1j}, num_spin_orbitals=4), FermionicOp({"+_0 +_2 -_1 -_3": 1j, "+_3 +_1 -_2 -_0": -1j}, num_spin_orbitals=4), ], ), ( 2, (1, 1), (True, False), [ FermionicOp({"+_0 -_1": 1j, "+_1 -_0": -1j}, num_spin_orbitals=4), FermionicOp({"+_0 +_2 -_1 -_3": 1j, "+_3 +_1 -_2 -_0": -1j}, num_spin_orbitals=4), ], ), ( 2, (1, 1), (False, True), [ FermionicOp({"+_2 -_3": 1j, "+_3 -_2": -1j}, num_spin_orbitals=4), FermionicOp({"+_0 +_2 -_1 -_3": 1j, "+_3 +_1 -_2 -_0": -1j}, num_spin_orbitals=4), ], ), ) def test_puccd_ansatz_with_singles( self, num_spatial_orbitals, num_particles, include_singles, expect ): """Tests the PUCCD Ansatz with included single excitations.""" mapper = JordanWignerMapper() ansatz = PUCCD( qubit_mapper=mapper, num_particles=num_particles, num_spatial_orbitals=num_spatial_orbitals, include_singles=include_singles, ) assert_ucc_like_ansatz(self, ansatz, num_spatial_orbitals, expect) def test_raise_non_singlet(self): """Test an error is raised when the number of alpha and beta electrons differ.""" with self.assertRaises(QiskitNatureError): PUCCD(num_particles=(2, 1)) @unpack @data( ( 3, (1, 1), [ FermionicOp({"+_0 +_3 -_1 -_4": 1j, "+_4 +_1 -_3 -_0": -1j}, num_spin_orbitals=6), FermionicOp({"+_0 +_3 -_2 -_5": 1j, "+_5 +_2 -_3 -_0": -1j}, num_spin_orbitals=6), FermionicOp({"+_1 +_4 -_2 -_5": 1j, "+_5 +_2 -_4 -_1": -1j}, num_spin_orbitals=6), ], ), ( 3, (2, 2), [ FermionicOp({"+_0 +_3 -_1 -_4": 1j, "+_4 +_1 -_3 -_0": -1j}, num_spin_orbitals=6), FermionicOp({"+_0 +_3 -_2 -_5": 1j, "+_5 +_2 -_3 -_0": -1j}, num_spin_orbitals=6), FermionicOp({"+_1 +_4 -_2 -_5": 1j, "+_5 +_2 -_4 -_1": -1j}, num_spin_orbitals=6), ], ), ) def test_puccd_ansatz_generalized(self, num_spatial_orbitals, num_particles, expect): """Tests the generalized PUCCD Ansatz.""" mapper = JordanWignerMapper() ansatz = PUCCD( qubit_mapper=mapper, num_particles=num_particles, num_spatial_orbitals=num_spatial_orbitals, generalized=True, ) assert_ucc_like_ansatz(self, ansatz, num_spatial_orbitals, expect) @unpack @data( ( 3, (1, 1), [ FermionicOp({"+_0 +_3 -_1 -_4": 1j, "+_4 +_1 -_3 -_0": -1j}, num_spin_orbitals=6), FermionicOp({"+_0 +_3 -_1 -_4": -1, "+_4 +_1 -_3 -_0": -1}, num_spin_orbitals=6), FermionicOp({"+_0 +_3 -_2 -_5": 1j, "+_5 +_2 -_3 -_0": -1j}, num_spin_orbitals=6), FermionicOp({"+_0 +_3 -_2 -_5": -1, "+_5 +_2 -_3 -_0": -1}, num_spin_orbitals=6), ], ), ( 3, (2, 2), [ FermionicOp({"+_0 +_3 -_2 -_5": 1j, "+_5 +_2 -_3 -_0": -1j}, num_spin_orbitals=6), FermionicOp({"+_0 +_3 -_2 -_5": -1, "+_5 +_2 -_3 -_0": -1}, num_spin_orbitals=6), FermionicOp({"+_1 +_4 -_2 -_5": 1j, "+_5 +_2 -_4 -_1": -1j}, num_spin_orbitals=6), FermionicOp({"+_1 +_4 -_2 -_5": -1, "+_5 +_2 -_4 -_1": -1}, num_spin_orbitals=6), ], ), ) def test_puccd_ansatz_include_imaginary(self, num_spatial_orbitals, num_particles, expect): """Tests the PUCCD Ansatz with imaginary terms included.""" mapper = JordanWignerMapper() ansatz = PUCCD( qubit_mapper=mapper, num_particles=num_particles, num_spatial_orbitals=num_spatial_orbitals, include_imaginary=True, ) assert_ucc_like_ansatz(self, ansatz, num_spatial_orbitals, expect) if __name__ == "__main__": unittest.main()
qiskit-nature/test/second_q/circuit/library/ansatzes/test_puccd.py/0
{ "file_path": "qiskit-nature/test/second_q/circuit/library/ansatzes/test_puccd.py", "repo_id": "qiskit-nature", "token_count": 3684 }
146
# This code is part of a Qiskit project. # # (C) Copyright IBM 2020, 2023. # # 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. """ Test Driver Psi4 Extra """ import unittest from test import QiskitNatureTestCase import numpy as np from qiskit_nature.second_q.drivers import Psi4Driver from qiskit_nature import QiskitNatureError import qiskit_nature.optionals as _optionals class TestDriverPsi4Extra(QiskitNatureTestCase): """Psi4 Driver extra tests for driver specifics, errors etc""" @unittest.skipIf(not _optionals.HAS_PSI4, "psi4 not available.") def setUp(self): super().setUp() def test_input_format_list(self): """input as a list""" driver = Psi4Driver( [ "molecule h2 {", " 0 1", " H 0.0 0.0 0.0", " H 0.0 0.0 0.735", " no_com", " no_reorient", "}", "", "set {", " basis sto-3g", " scf_type pk", "}", ] ) driver_result = driver.run() with self.subTest("energy"): self.assertAlmostEqual(driver_result.reference_energy, -1.117, places=3) with self.subTest("masses"): np.testing.assert_array_almost_equal( driver_result.molecule.masses, [1.00782503, 1.00782503] ) def test_input_format_string(self): """input as a multi line string""" cfg = """ molecule h2 { 0 1 H 0.0 0.0 0.0 H 0.0 0.0 0.735 no_com no_reorient } set { basis sto-3g scf_type pk } """ driver = Psi4Driver(cfg) driver_result = driver.run() with self.subTest("energy"): self.assertAlmostEqual(driver_result.reference_energy, -1.117, places=3) with self.subTest("masses"): np.testing.assert_array_almost_equal( driver_result.molecule.masses, [1.00782503, 1.00782503] ) def test_input_format_fail(self): """input type failure""" with self.assertRaises(QiskitNatureError): _ = Psi4Driver(1.000) def test_psi4_failure(self): """check we catch psi4 failures (bad scf type used here)""" bad_cfg = """ molecule h2 { 0 1 H 0.0 0.0 0.0 H 0.0 0.0 0.735 no_com no_reorient } set { basis sto-3g scf_type unknown } """ driver = Psi4Driver(bad_cfg) with self.assertRaises(QiskitNatureError) as ctxmgr: _ = driver.run() self.assertTrue(str(ctxmgr.exception).startswith("'psi4 process return code")) if __name__ == "__main__": unittest.main()
qiskit-nature/test/second_q/drivers/psi4d/test_driver_psi4_extra.py/0
{ "file_path": "qiskit-nature/test/second_q/drivers/psi4d/test_driver_psi4_extra.py", "repo_id": "qiskit-nature", "token_count": 1425 }
147
# This code is part of a Qiskit project. # # (C) Copyright IBM 2021, 2024. # # 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. """Test KagomeLattice.""" import unittest from test import QiskitNatureTestCase from numpy.testing import assert_array_equal import numpy as np from rustworkx import PyGraph, is_isomorphic from qiskit_nature.second_q.hamiltonians.lattices import ( BoundaryCondition, KagomeLattice, ) class TestKagomeLattice(QiskitNatureTestCase): """Test KagomeLattice.""" def setUp(self): super().setUp() self.rows = 3 self.cols = 2 self.num_sites_per_cell = 3 self.edge_parameter = 1 - 1j self.onsite_parameter = 0.0 self.weighted_bulk_edges = [ (2, 0, 1 - 1j), (0, 1, 1 - 1j), (1, 2, 1 - 1j), (3, 4, 1 - 1j), (5, 3, 1 - 1j), (4, 5, 1 - 1j), (6, 7, 1 - 1j), (8, 6, 1 - 1j), (7, 8, 1 - 1j), (9, 10, 1 - 1j), (11, 9, 1 - 1j), (10, 11, 1 - 1j), (12, 13, 1 - 1j), (14, 12, 1 - 1j), (13, 14, 1 - 1j), (15, 16, 1 - 1j), (17, 15, 1 - 1j), (16, 17, 1 - 1j), (1, 3, 1 - 1j), (2, 9, 1 - 1j), (5, 10, 1 - 1j), (5, 12, 1 - 1j), (4, 6, 1 - 1j), (8, 13, 1 - 1j), (8, 15, 1 - 1j), (10, 12, 1 - 1j), (13, 15, 1 - 1j), ] self.weighted_self_loops = [(i, i, 0.0) for i in range(18)] self.weighted_boundary_x_edges = [ (7, 0, 1 + 1j), (16, 9, 1 + 1j), ] self.weighted_boundary_y_edges = [ (11, 0, 1 + 1j), (14, 3, 1 + 1j), (17, 6, 1 + 1j), ] self.weighted_boundary_xy_edges = [ (14, 1, 1 + 1j), (17, 4, 1 + 1j), (2, 16, 1 + 1j), (11, 7, 1 + 1j), ] def test_init_open(self): """Test init for the open boundary conditions.""" boundary_condition = BoundaryCondition.OPEN kagome = KagomeLattice( self.rows, self.cols, self.edge_parameter, self.onsite_parameter, boundary_condition ) weighted_list = self.weighted_bulk_edges + self.weighted_self_loops with self.subTest("Check the graph."): target_graph = PyGraph(multigraph=False) target_graph.add_nodes_from(range(self.num_sites_per_cell * 6)) target_graph.add_edges_from(weighted_list) self.assertTrue( is_isomorphic(kagome.graph, target_graph, edge_matcher=lambda x, y: x == y) ) with self.subTest("Check the number of nodes."): self.assertEqual(kagome.num_nodes, self.num_sites_per_cell * 6) with self.subTest("Check the set of nodes."): self.assertSetEqual(set(kagome.node_indexes), set(range(self.num_sites_per_cell * 6))) with self.subTest("Check the set of weights."): target_set = set(weighted_list) self.assertSetEqual(set(kagome.weighted_edge_list), target_set) with self.subTest("Check the adjacency matrix."): target_matrix = np.zeros((kagome.num_nodes, kagome.num_nodes), dtype=np.complex128) # Fill in the edges from the edge list for edge in weighted_list: i, j, weight = edge if j > i: target_matrix[i][j] = weight target_matrix[j][i] = weight.conjugate() elif i > j: target_matrix[j][i] = weight target_matrix[i][j] = weight.conjugate() else: target_matrix[i][i] = weight assert_array_equal(kagome.to_adjacency_matrix(weighted=True), target_matrix) def test_init_periodic(self): """Test init for the periodic boundary conditions.""" boundary_condition = BoundaryCondition.PERIODIC kagome = KagomeLattice( self.rows, self.cols, self.edge_parameter, self.onsite_parameter, boundary_condition ) weighted_list = ( self.weighted_bulk_edges + self.weighted_self_loops + self.weighted_boundary_x_edges + self.weighted_boundary_y_edges + self.weighted_boundary_xy_edges ) with self.subTest("Check the graph."): target_graph = PyGraph(multigraph=False) target_graph.add_nodes_from(range(self.num_sites_per_cell * 6)) target_graph.add_edges_from(weighted_list) self.assertTrue( is_isomorphic(kagome.graph, target_graph, edge_matcher=lambda x, y: x == y) ) with self.subTest("Check the number of nodes."): self.assertEqual(kagome.num_nodes, self.num_sites_per_cell * 6) with self.subTest("Check the set of nodes."): self.assertSetEqual(set(kagome.node_indexes), set(range(self.num_sites_per_cell * 6))) with self.subTest("Check the set of weights."): target_set = set(weighted_list) self.assertSetEqual(set(kagome.weighted_edge_list), target_set) with self.subTest("Check the adjacency matrix."): target_matrix = np.zeros((kagome.num_nodes, kagome.num_nodes), dtype=np.complex128) # Fill in the edges from the edge list for edge in weighted_list: i, j, weight = edge if j > i: target_matrix[i][j] = weight target_matrix[j][i] = weight.conjugate() elif i > j: target_matrix[j][i] = weight target_matrix[i][j] = weight.conjugate() else: target_matrix[i][i] = weight assert_array_equal(kagome.to_adjacency_matrix(weighted=True), target_matrix) def test_init_x_periodic(self): """Test init for the periodic boundary conditions.""" boundary_condition = (BoundaryCondition.PERIODIC, BoundaryCondition.OPEN) kagome = KagomeLattice( self.rows, self.cols, self.edge_parameter, self.onsite_parameter, boundary_condition ) weighted_list = ( self.weighted_bulk_edges + self.weighted_self_loops + self.weighted_boundary_x_edges ) with self.subTest("Check the graph."): target_graph = PyGraph(multigraph=False) target_graph.add_nodes_from(range(self.num_sites_per_cell * 6)) target_graph.add_edges_from(weighted_list) self.assertTrue( is_isomorphic(kagome.graph, target_graph, edge_matcher=lambda x, y: x == y) ) with self.subTest("Check the number of nodes."): self.assertEqual(kagome.num_nodes, self.num_sites_per_cell * 6) with self.subTest("Check the set of nodes."): self.assertSetEqual(set(kagome.node_indexes), set(range(self.num_sites_per_cell * 6))) with self.subTest("Check the set of weights."): target_set = set(weighted_list) self.assertSetEqual(set(kagome.weighted_edge_list), target_set) with self.subTest("Check the adjacency matrix."): target_matrix = np.zeros((kagome.num_nodes, kagome.num_nodes), dtype=np.complex128) # Fill in the edges from the edge list for edge in weighted_list: i, j, weight = edge if j > i: target_matrix[i][j] = weight target_matrix[j][i] = weight.conjugate() elif i > j: target_matrix[j][i] = weight target_matrix[i][j] = weight.conjugate() else: target_matrix[i][i] = weight assert_array_equal(kagome.to_adjacency_matrix(weighted=True), target_matrix) def test_init_y_periodic(self): """Test init for the periodic boundary conditions.""" boundary_condition = (BoundaryCondition.OPEN, BoundaryCondition.PERIODIC) kagome = KagomeLattice( self.rows, self.cols, self.edge_parameter, self.onsite_parameter, boundary_condition ) weighted_list = ( self.weighted_bulk_edges + self.weighted_self_loops + self.weighted_boundary_y_edges ) with self.subTest("Check the graph."): target_graph = PyGraph(multigraph=False) target_graph.add_nodes_from(range(self.num_sites_per_cell * 6)) target_graph.add_edges_from(weighted_list) self.assertTrue( is_isomorphic(kagome.graph, target_graph, edge_matcher=lambda x, y: x == y) ) with self.subTest("Check the number of nodes."): self.assertEqual(kagome.num_nodes, self.num_sites_per_cell * 6) with self.subTest("Check the set of nodes."): self.assertSetEqual(set(kagome.node_indexes), set(range(self.num_sites_per_cell * 6))) with self.subTest("Check the set of weights."): target_set = set(weighted_list) self.assertSetEqual(set(kagome.weighted_edge_list), target_set) with self.subTest("Check the adjacency matrix."): target_matrix = np.zeros((kagome.num_nodes, kagome.num_nodes), dtype=np.complex128) # Fill in the edges from the edge list for edge in weighted_list: i, j, weight = edge if j > i: target_matrix[i][j] = weight target_matrix[j][i] = weight.conjugate() elif i > j: target_matrix[j][i] = weight target_matrix[i][j] = weight.conjugate() else: target_matrix[i][i] = weight assert_array_equal(kagome.to_adjacency_matrix(weighted=True), target_matrix) if __name__ == "__main__": unittest.main()
qiskit-nature/test/second_q/hamiltonians/lattices/test_kagome_lattice.py/0
{ "file_path": "qiskit-nature/test/second_q/hamiltonians/lattices/test_kagome_lattice.py", "repo_id": "qiskit-nature", "token_count": 5296 }
148
# This code is part of a Qiskit project. # # (C) Copyright IBM 2021, 2023. # # 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. """ Test Bravyi-Kitaev Super-Fast Mapper """ import unittest from test import QiskitNatureTestCase from test.second_q.mappers.resources.bksf_lih import ( FERMIONIC_HAMILTONIAN, QUBIT_HAMILTONIAN, ) import numpy as np from qiskit.quantum_info import SparsePauliOp, PauliList from qiskit_nature.second_q.operators import FermionicOp from qiskit_nature.second_q.mappers import BravyiKitaevSuperFastMapper from qiskit_nature.second_q.mappers.bksf import ( _edge_operator_aij, _edge_operator_bi, _bksf_edge_list_fermionic_op, ) def _sort_simplify(sparse_pauli): sparse_pauli = sparse_pauli.simplify() indices = sparse_pauli.paulis.argsort() table = sparse_pauli.paulis[indices] coeffs = sparse_pauli.coeffs[indices] sparse_pauli = SparsePauliOp(table, coeffs) return sparse_pauli class TestBravyiKitaevSuperFastMapper(QiskitNatureTestCase): """Test Bravyi-Kitaev Super-Fast Mapper""" def test_bksf_edge_op_bi(self): """Test BKSF mapping, edge operator bi""" edge_matrix = np.triu(np.ones((4, 4))) edge_list = np.array(np.nonzero(np.triu(edge_matrix) - np.diag(np.diag(edge_matrix)))) qterm_b0 = _edge_operator_bi(edge_list, 0) qterm_b1 = _edge_operator_bi(edge_list, 1) qterm_b2 = _edge_operator_bi(edge_list, 2) qterm_b3 = _edge_operator_bi(edge_list, 3) ref_qterm_b0 = SparsePauliOp("IIIZZZ") ref_qterm_b1 = SparsePauliOp("IZZIIZ") ref_qterm_b2 = SparsePauliOp("ZIZIZI") ref_qterm_b3 = SparsePauliOp("ZZIZII") with self.subTest("Test edge operator b0"): self.assertEqual(qterm_b0, ref_qterm_b0) with self.subTest("Test edge operator b1"): self.assertEqual(qterm_b1, ref_qterm_b1) with self.subTest("Test edge operator b2"): self.assertEqual(qterm_b2, ref_qterm_b2) with self.subTest("Test edge operator b3"): self.assertEqual(qterm_b3, ref_qterm_b3) def test_bksf_edge_op_aij(self): """Test BKSF mapping, edge operator aij""" edge_matrix = np.triu(np.ones((4, 4))) edge_list = np.array(np.nonzero(np.triu(edge_matrix) - np.diag(np.diag(edge_matrix)))) qterm_a01 = _edge_operator_aij(edge_list, 0, 1) qterm_a02 = _edge_operator_aij(edge_list, 0, 2) qterm_a03 = _edge_operator_aij(edge_list, 0, 3) qterm_a12 = _edge_operator_aij(edge_list, 1, 2) qterm_a13 = _edge_operator_aij(edge_list, 1, 3) qterm_a23 = _edge_operator_aij(edge_list, 2, 3) ref_qterm_a01 = SparsePauliOp("IIIIIX") ref_qterm_a02 = SparsePauliOp("IIIIXZ") ref_qterm_a03 = SparsePauliOp("IIIXZZ") ref_qterm_a12 = SparsePauliOp("IIXIZZ") ref_qterm_a13 = SparsePauliOp("IXZZIZ") ref_qterm_a23 = SparsePauliOp("XZZZZI") with self.subTest("Test edge operator a01"): self.assertEqual(qterm_a01, ref_qterm_a01) with self.subTest("Test edge operator a02"): self.assertEqual(qterm_a02, ref_qterm_a02) with self.subTest("Test edge operator a03"): self.assertEqual(qterm_a03, ref_qterm_a03) with self.subTest("Test edge operator a12"): self.assertEqual(qterm_a12, ref_qterm_a12) with self.subTest("Test edge operator a13"): self.assertEqual(qterm_a13, ref_qterm_a13) with self.subTest("Test edge operator a23"): self.assertEqual(qterm_a23, ref_qterm_a23) def test_h2(self): """Test H2 molecule""" with self.subTest("Excitation edges 1"): assert np.alltrue( _bksf_edge_list_fermionic_op( FermionicOp({"+_0 -_1 +_2 -_3": 1}, num_spin_orbitals=4), 4, ) == np.array([[0, 1], [2, 3]]) ) with self.subTest("Excitation edges 2"): assert np.alltrue( _bksf_edge_list_fermionic_op( FermionicOp({"+_0 -_1 -_2 +_3": 1}, num_spin_orbitals=4), 4, ) == np.array([[0, 1], [3, 2]]) ) ## H2 from pyscf with sto-3g basis h2_fop = FermionicOp( { "+_0 -_1 +_2 -_3": 0.18128880821149607, "+_0 -_1 -_2 +_3": -0.18128880821149607, "-_0 +_1 +_2 -_3": -0.18128880821149607, "-_0 +_1 -_2 +_3": 0.18128880821149604, "+_3 -_3": -0.4759487152209648, "+_2 -_2": -1.2524635735648986, "+_2 -_2 +_3 -_3": 0.48217928821207245, "+_1 -_1": -0.4759487152209648, "+_1 -_1 +_3 -_3": 0.697393767423027, "+_1 -_1 +_2 -_2": 0.6634680964235684, "+_0 -_0": -1.2524635735648986, "+_0 -_0 +_3 -_3": 0.6634680964235684, "+_0 -_0 +_2 -_2": 0.6744887663568382, "+_0 -_0 +_1 -_1": 0.48217928821207245, }, num_spin_orbitals=4, copy=False, ) expected_pauli_op = SparsePauliOp.from_list( [ ("IIII", (-0.8126179630230767 + 0j)), ("IIZZ", (0.17119774903432952 + 0j)), ("IYYI", (0.04532220205287402 + 0j)), ("IZIZ", (0.17119774903432955 + 0j)), ("IZZI", (0.34297063344496626 + 0j)), ("XIIX", (0.04532220205287402 + 0j)), ("YIIY", (0.04532220205287402 + 0j)), ("YZZY", (0.04532220205287402 + 0j)), ("ZIIZ", (0.3317340482117842 + 0j)), ("ZIZI", (-0.22278593040418454 + 0j)), ("ZXXZ", (0.04532220205287402 + 0j)), ("ZYYZ", (0.04532220205287402 + 0j)), ("ZZII", (-0.22278593040418454 + 0j)), ("ZZZZ", (0.24108964410603623 + 0j)), ] ) pauli_sparse_op = BravyiKitaevSuperFastMapper().map(h2_fop) op1 = _sort_simplify(expected_pauli_op) op2 = _sort_simplify(pauli_sparse_op) with self.subTest("Map H2 frome sto3g basis, number of terms"): self.assertEqual(len(op1), len(op2)) with self.subTest("Map H2 frome sto3g basis result"): self.assertEqualSparsePauliOp(op1, op2) with self.subTest("Sparse FermionicOp input"): h2_fop_sparse = h2_fop.normal_order() pauli_sum_op_from_sparse = BravyiKitaevSuperFastMapper().map(h2_fop_sparse) op2_from_sparse = _sort_simplify(pauli_sum_op_from_sparse) self.assertEqualSparsePauliOp(op1, op2_from_sparse) with self.subTest("Test accepting identity with zero coefficient"): h2_fop_zero_term = h2_fop + FermionicOp({"": 0.0}, num_spin_orbitals=4) pauli_sum_op_extra = BravyiKitaevSuperFastMapper().map(h2_fop_zero_term) op3 = _sort_simplify(pauli_sum_op_extra) self.assertEqualSparsePauliOp(op1, op3) with self.subTest("Test zero FermiOp"): fermi_op = FermionicOp.zero() fermi_op.num_spin_orbitals = 4 pauli_op = BravyiKitaevSuperFastMapper().map(fermi_op) x = np.array([], dtype="bool") z = np.array([], dtype="bool") expected_pauli_op = SparsePauliOp(PauliList.from_symplectic(x, z), coeffs=[0.0]) self.assertEqualSparsePauliOp(pauli_op, expected_pauli_op) def test_LiH(self): """Test LiH molecule""" pauli_sparse_op = BravyiKitaevSuperFastMapper().map(FERMIONIC_HAMILTONIAN) self.assertEqualSparsePauliOp(pauli_sparse_op, QUBIT_HAMILTONIAN) def test_mapping_overwrite_reg_len(self): """Test overwriting the register length.""" op = FermionicOp({"+_0 -_0": 1}, num_spin_orbitals=1) expected = FermionicOp({"+_0 -_0": 1}, num_spin_orbitals=3) mapper = BravyiKitaevSuperFastMapper() self.assertEqual(mapper.map(op, register_length=3), mapper.map(expected)) if __name__ == "__main__": unittest.main()
qiskit-nature/test/second_q/mappers/test_bksf_mapper.py/0
{ "file_path": "qiskit-nature/test/second_q/mappers/test_bksf_mapper.py", "repo_id": "qiskit-nature", "token_count": 4519 }
149
# This code is part of a Qiskit project. # # (C) Copyright IBM 2021, 2023. # # 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. """Test for FermionicOp""" import unittest from test import QiskitNatureTestCase import numpy as np from ddt import data, ddt, unpack from qiskit.circuit import Parameter from qiskit_nature.exceptions import QiskitNatureError from qiskit_nature.second_q.operators import FermionicOp, PolynomialTensor import qiskit_nature.optionals as _optionals @ddt class TestFermionicOp(QiskitNatureTestCase): """FermionicOp tests.""" a = Parameter("a") b = Parameter("b") op1 = FermionicOp({"+_0 -_0": 1}) op2 = FermionicOp({"-_0 +_0": 2}) op3 = FermionicOp({"+_0 -_0": 1, "-_0 +_0": 2}) op4 = FermionicOp({"+_0 -_0": a}) def test_neg(self): """Test __neg__""" fer_op = -self.op1 targ = FermionicOp({"+_0 -_0": -1}, num_spin_orbitals=1) self.assertEqual(fer_op, targ) fer_op = -self.op4 targ = FermionicOp({"+_0 -_0": -self.a}) self.assertEqual(fer_op, targ) def test_mul(self): """Test __mul__, and __rmul__""" with self.subTest("rightmul"): fer_op = self.op1 * 2 targ = FermionicOp({"+_0 -_0": 2}, num_spin_orbitals=1) self.assertEqual(fer_op, targ) fer_op = self.op1 * self.a targ = FermionicOp({"+_0 -_0": self.a}) self.assertEqual(fer_op, targ) with self.subTest("left mul"): fer_op = (2 + 1j) * self.op3 targ = FermionicOp({"+_0 -_0": (2 + 1j), "-_0 +_0": (4 + 2j)}, num_spin_orbitals=1) self.assertEqual(fer_op, targ) def test_div(self): """Test __truediv__""" fer_op = self.op1 / 2 targ = FermionicOp({"+_0 -_0": 0.5}, num_spin_orbitals=1) self.assertEqual(fer_op, targ) fer_op = self.op1 / self.a targ = FermionicOp({"+_0 -_0": 1 / self.a}) self.assertEqual(fer_op, targ) def test_add(self): """Test __add__""" fer_op = self.op1 + self.op2 targ = self.op3 self.assertEqual(fer_op, targ) fer_op = self.op1 + self.op4 targ = FermionicOp({"+_0 -_0": 1 + self.a}) self.assertEqual(fer_op, targ) with self.subTest("sum"): fer_op = sum(FermionicOp({label: 1}) for label in ["+_0", "-_1", "+_2 -_2"]) targ = FermionicOp({"+_0": 1, "-_1": 1, "+_2 -_2": 1}) self.assertEqual(fer_op, targ) def test_sub(self): """Test __sub__""" fer_op = self.op3 - self.op2 targ = FermionicOp({"+_0 -_0": 1, "-_0 +_0": 0}, num_spin_orbitals=1) self.assertEqual(fer_op, targ) fer_op = self.op4 - self.op1 targ = FermionicOp({"+_0 -_0": self.a - 1}) self.assertEqual(fer_op, targ) def test_compose(self): """Test operator composition""" with self.subTest("single compose"): fer_op = FermionicOp({"+_0 -_1": 1}, num_spin_orbitals=2) @ FermionicOp( {"-_0": 1}, num_spin_orbitals=2 ) targ = FermionicOp({"+_0 -_1 -_0": 1}, num_spin_orbitals=2) self.assertEqual(fer_op, targ) with self.subTest("single compose with parameters"): fer_op = FermionicOp({"+_0 -_1": self.a}) @ FermionicOp({"-_0": 1}) targ = FermionicOp({"+_0 -_1 -_0": self.a}) self.assertEqual(fer_op, targ) with self.subTest("multi compose"): fer_op = FermionicOp( {"+_0 +_1 -_1": 1, "-_0 +_0 -_1": 1}, num_spin_orbitals=2 ) @ FermionicOp({"": 1, "-_0 +_1": 1}, num_spin_orbitals=2) fer_op = fer_op.simplify() targ = FermionicOp( {"+_0 +_1 -_1": 1, "-_0 +_0 -_1": 1, "+_0 +_1 -_0": -1, "-_0 -_1 +_1": -1}, num_spin_orbitals=2, ) self.assertEqual(fer_op, targ) with self.subTest("multi compose with parameters"): fer_op = FermionicOp({"+_0 +_1 -_1": self.a, "-_0 +_0 -_1": 1}) @ FermionicOp( {"": 1, "-_0 +_1": self.b} ) fer_op = fer_op.simplify() targ = FermionicOp( { "+_0 +_1 -_1": self.a, "-_0 +_0 -_1": 1, "+_0 +_1 -_0": -self.a * self.b, "-_0 -_1 +_1": -self.b, } ) self.assertEqual(fer_op, targ) def test_tensor(self): """Test tensor multiplication""" fer_op = self.op1.tensor(self.op2) targ = FermionicOp({"+_0 -_0 -_1 +_1": 2}, num_spin_orbitals=2) self.assertEqual(fer_op, targ) fer_op = self.op4.tensor(self.op2) targ = FermionicOp({"+_0 -_0 -_1 +_1": 2 * self.a}) self.assertEqual(fer_op, targ) def test_expand(self): """Test reversed tensor multiplication""" fer_op = self.op1.expand(self.op2) targ = FermionicOp({"-_0 +_0 +_1 -_1": 2}, num_spin_orbitals=2) self.assertEqual(fer_op, targ) fer_op = self.op4.expand(self.op2) targ = FermionicOp({"-_0 +_0 +_1 -_1": 2 * self.a}) self.assertEqual(fer_op, targ) def test_pow(self): """Test __pow__""" with self.subTest("square trivial"): fer_op = FermionicOp({"+_0 +_1 -_1": 3, "-_0 +_0 -_1": 1}, num_spin_orbitals=2) ** 2 fer_op = fer_op.simplify() targ = FermionicOp.zero() self.assertEqual(fer_op, targ) with self.subTest("square nontrivial"): fer_op = FermionicOp({"+_0 +_1 -_1": 3, "+_0 -_0 -_1": 1}, num_spin_orbitals=2) ** 2 fer_op = fer_op.simplify() targ = FermionicOp({"+_0 -_1": -3}, num_spin_orbitals=2) self.assertEqual(fer_op, targ) with self.subTest("3rd power"): fer_op = (3 * FermionicOp.one()) ** 3 targ = 27 * FermionicOp.one() self.assertEqual(fer_op, targ) with self.subTest("0th power"): fer_op = FermionicOp({"+_0 +_1 -_1": 3, "-_0 +_0 -_1": 1}, num_spin_orbitals=2) ** 0 fer_op = fer_op.simplify() targ = FermionicOp.one() self.assertEqual(fer_op, targ) with self.subTest("square nontrivial with parameters"): fer_op = FermionicOp({"+_0 +_1 -_1": self.a, "+_0 -_0 -_1": 1}) ** 2 fer_op = fer_op.simplify() targ = FermionicOp({"+_0 -_1": -self.a}) self.assertEqual(fer_op, targ) def test_adjoint(self): """Test adjoint method""" fer_op = FermionicOp( {"": 1j, "+_0 +_1 -_1": 3, "+_0 -_0 -_1": 1, "-_0 -_1": 2 + 4j}, num_spin_orbitals=3 ).adjoint() targ = FermionicOp( {"": -1j, "+_1 -_1 -_0": 3, "+_1 +_0 -_0": 1, "+_1 +_0": 2 - 4j}, num_spin_orbitals=3 ) self.assertEqual(fer_op, targ) fer_op = FermionicOp( {"": 1j, "+_0 +_1 -_1": 3, "+_0 -_0 -_1": self.a, "-_0 -_1": 2 + 4j} ).adjoint() targ = FermionicOp( {"": -1j, "+_1 -_1 -_0": 3, "+_1 +_0 -_0": self.a.conjugate(), "+_1 +_0": 2 - 4j} ) self.assertEqual(fer_op, targ) def test_simplify(self): """Test simplify""" with self.subTest("simplify integer"): fer_op = FermionicOp({"+_0 -_0": 1, "+_0 -_0 +_0 -_0": 1}, num_spin_orbitals=1) simplified_op = fer_op.simplify() targ = FermionicOp({"+_0 -_0": 2}, num_spin_orbitals=1) self.assertEqual(simplified_op, targ) with self.subTest("simplify complex"): fer_op = FermionicOp({"+_0 -_0": 1, "+_0 -_0 +_0 -_0": 1j}, num_spin_orbitals=1) simplified_op = fer_op.simplify() targ = FermionicOp({"+_0 -_0": 1 + 1j}, num_spin_orbitals=1) self.assertEqual(simplified_op, targ) with self.subTest("simplify doesn't reorder"): fer_op = FermionicOp({"-_0 +_1": 1 + 0j}, num_spin_orbitals=2) simplified_op = fer_op.simplify() self.assertEqual(simplified_op, fer_op) fer_op = FermionicOp({"-_1 +_0": 1 + 0j}, num_spin_orbitals=2) simplified_op = fer_op.simplify() self.assertEqual(simplified_op, fer_op) with self.subTest("simplify zero"): fer_op = self.op1 - self.op1 simplified_op = fer_op.simplify() targ = FermionicOp.zero() self.assertEqual(simplified_op, targ) with self.subTest("simplify parameters"): fer_op = FermionicOp({"+_0 -_0": self.a, "+_0 -_0 +_0 -_0": 1j}) simplified_op = fer_op.simplify() targ = FermionicOp({"+_0 -_0": self.a + 1j}) self.assertEqual(simplified_op, targ) with self.subTest("simplify commutes with normal_order"): fer_op = FermionicOp({"-_0 +_1": 1}, num_spin_orbitals=2) self.assertEqual(fer_op.simplify().normal_order(), fer_op.normal_order().simplify()) with self.subTest("simplify + index order"): orig = FermionicOp({"+_1 -_0 +_0 -_0": 1, "-_0 +_1": 2}) fer_op = orig.simplify().index_order() targ = FermionicOp({"-_0 +_1": 1}) self.assertEqual(fer_op, targ) def test_hermiticity(self): """test is_hermitian""" with self.subTest("operator hermitian"): # deliberately define test operator with duplicate terms in case .adjoint() simplifies terms fer_op = ( 1j * FermionicOp({"+_0 -_1 +_2 -_2 -_3 +_3": 1}, num_spin_orbitals=4) + 1j * FermionicOp({"+_0 -_1 +_2 -_2 -_3 +_3": 1}, num_spin_orbitals=4) + 1j * FermionicOp({"-_0 +_1 +_2 -_2 -_3 +_3": 1}, num_spin_orbitals=4) + 1j * FermionicOp({"-_0 +_1 +_2 -_2 -_3 +_3": 1}, num_spin_orbitals=4) + FermionicOp({"+_0 -_1 -_2 +_2 +_3 -_3": 1}, num_spin_orbitals=4) - FermionicOp({"-_0 +_1 -_2 +_2 +_3 -_3": 1}, num_spin_orbitals=4) ) self.assertTrue(fer_op.is_hermitian()) with self.subTest("operator not hermitian"): fer_op = ( 1j * FermionicOp({"+_0 -_1 +_2 -_2 -_3 +_3": 1}, num_spin_orbitals=4) + 1j * FermionicOp({"+_0 -_1 +_2 -_2 -_3 +_3": 1}, num_spin_orbitals=4) - 1j * FermionicOp({"-_0 +_1 +_2 -_2 -_3 +_3": 1}, num_spin_orbitals=4) - 1j * FermionicOp({"-_0 +_1 +_2 -_2 -_3 +_3": 1}, num_spin_orbitals=4) ) self.assertFalse(fer_op.is_hermitian()) with self.subTest("test require normal order"): fer_op = ( FermionicOp({"+_0 -_0 -_1": 1}, num_spin_orbitals=2) - FermionicOp({"+_1 -_0 +_0": 1}, num_spin_orbitals=2) + FermionicOp({"+_1": 1}, num_spin_orbitals=2) ) self.assertTrue(fer_op.is_hermitian()) with self.subTest("test passing atol"): fer_op = FermionicOp({"+_0 -_1": 1}, num_spin_orbitals=2) + (1 + 1e-7) * FermionicOp( {"+_1 -_0": 1}, num_spin_orbitals=2 ) self.assertFalse(fer_op.is_hermitian()) self.assertFalse(fer_op.is_hermitian(atol=1e-8)) self.assertTrue(fer_op.is_hermitian(atol=1e-6)) with self.subTest("parameters"): fer_op = FermionicOp({"+_0": self.a}) with self.assertRaisesRegex(ValueError, "parameter"): _ = fer_op.is_hermitian() def test_equiv(self): """test equiv""" prev_atol = FermionicOp.atol prev_rtol = FermionicOp.rtol op3 = self.op1 + (1 + 0.00005) * self.op2 self.assertFalse(op3.equiv(self.op3)) FermionicOp.atol = 1e-4 FermionicOp.rtol = 1e-4 self.assertTrue(op3.equiv(self.op3)) FermionicOp.atol = prev_atol FermionicOp.rtol = prev_rtol def test_normal_order(self): """test normal_order method""" with self.subTest("Test for creation operator"): orig = FermionicOp({"+_0": 1}, num_spin_orbitals=1) fer_op = orig.normal_order() self.assertEqual(fer_op, orig) with self.subTest("Test for annihilation operator"): orig = FermionicOp({"-_0": 1}, num_spin_orbitals=1) fer_op = orig.normal_order() self.assertEqual(fer_op, orig) with self.subTest("Test for number operator"): orig = FermionicOp({"+_0 -_0": 1}, num_spin_orbitals=1) fer_op = orig.normal_order() self.assertEqual(fer_op, orig) with self.subTest("Test for empty operator"): orig = FermionicOp({"-_0 +_0": 1}, num_spin_orbitals=1) fer_op = orig.normal_order() targ = FermionicOp({"": 1, "+_0 -_0": -1}, num_spin_orbitals=1) self.assertEqual(fer_op, targ) with self.subTest("Test for multiple operators 1"): orig = FermionicOp({"-_0 +_1": 1}, num_spin_orbitals=2) fer_op = orig.normal_order() targ = FermionicOp({"+_1 -_0": -1}, num_spin_orbitals=2) self.assertEqual(fer_op, targ) with self.subTest("Test for multiple operators 2"): orig = FermionicOp({"-_0 +_0 +_1 -_2": 1}, num_spin_orbitals=3) fer_op = orig.normal_order() targ = FermionicOp({"+_1 -_2": 1, "+_0 +_1 -_0 -_2": 1}, num_spin_orbitals=3) self.assertEqual(fer_op, targ) with self.subTest("Test normal ordering simplifies"): orig = FermionicOp({"-_0 +_1": 1, "+_1 -_0": -1, "+_0": 0.0}, num_spin_orbitals=2) fer_op = orig.normal_order() targ = FermionicOp({"+_1 -_0": -2}, num_spin_orbitals=2) self.assertEqual(fer_op, targ) with self.subTest("Test parameters"): orig = FermionicOp({"-_0 +_0 +_1 -_2": self.a}) fer_op = orig.normal_order() targ = FermionicOp({"+_1 -_2": self.a, "+_0 +_1 -_0 -_2": self.a}) self.assertEqual(fer_op, targ) def test_index_order(self): """test index_order method""" with self.subTest("Test for creation operator"): orig = FermionicOp({"+_0": 1}) fer_op = orig.index_order() self.assertEqual(fer_op, orig) with self.subTest("Test for annihilation operator"): orig = FermionicOp({"-_0": 1}) fer_op = orig.index_order() self.assertEqual(fer_op, orig) with self.subTest("Test for number operator"): orig = FermionicOp({"+_0 -_0": 1}) fer_op = orig.index_order() self.assertEqual(fer_op, orig) with self.subTest("Test for empty operator"): orig = FermionicOp({"-_0 +_0": 1}) fer_op = orig.index_order() self.assertEqual(fer_op, orig) with self.subTest("Test for multiple operators 1"): orig = FermionicOp({"+_1 -_0": 1}) fer_op = orig.index_order() targ = FermionicOp({"-_0 +_1": -1}) self.assertEqual(fer_op, targ) with self.subTest("Test for multiple operators 2"): orig = FermionicOp({"+_2 -_0 +_1 -_0": 1, "-_0 +_1": 2}) fer_op = orig.index_order() targ = FermionicOp({"-_0 -_0 +_1 +_2": 1, "-_0 +_1": 2}) self.assertEqual(fer_op, targ) with self.subTest("Test index ordering simplifies"): orig = FermionicOp({"-_0 +_1": 1, "+_1 -_0": -1, "+_0": 0.0}) fer_op = orig.index_order() targ = FermionicOp({"-_0 +_1": 2}) self.assertEqual(fer_op, targ) with self.subTest("index order + simplify"): orig = FermionicOp({"+_1 -_0 +_0 -_0": 1, "-_0 +_1": 2}) fer_op = orig.index_order().simplify() targ = FermionicOp({"-_0 +_1": 1}) self.assertEqual(fer_op, targ) def test_induced_norm(self): """Test induced norm.""" op = 3 * FermionicOp({"+_0": 1}, num_spin_orbitals=1) + 4j * FermionicOp( {"-_0": 1}, num_spin_orbitals=1 ) self.assertAlmostEqual(op.induced_norm(), 7.0) self.assertAlmostEqual(op.induced_norm(2), 5.0) @unpack @data( ("", 1, True), # empty string ("+_0", 1, True), # single term ("+_0 -_0", 1, True), # multiple terms ("+_10", 11, True), # multiple digits (" +_0", 1, False), # leading whitespace ("+_0 ", 1, False), # trailing whitespace ("+_0 -_0", 1, False), # multiple separating spaces ("+_0a", 1, False), # incorrect term pattern ("+_a0", 1, False), # incorrect term pattern ("0_+", 1, False), # incorrect term pattern ("something", 1, False), # incorrect term pattern ("+_1", 1, False), # register length is too short ) def test_validate(self, key: str, length: int, valid: bool): """Test key validation.""" if valid: _ = FermionicOp({key: 1.0}, num_spin_orbitals=length) else: with self.assertRaises(QiskitNatureError): _ = FermionicOp({key: 1.0}, num_spin_orbitals=length) def test_from_polynomial_tensor(self): """Test from PolynomialTensor construction""" with self.subTest("dense tensor"): r_l = 2 p_t = PolynomialTensor( { "+-": np.arange(1, 5).reshape((r_l, r_l)), "++--": np.arange(1, 17).reshape((r_l, r_l, r_l, r_l)), } ) op = FermionicOp.from_polynomial_tensor(p_t) expected = FermionicOp( { "+_0 -_0": 1, "+_0 -_1": 2, "+_1 -_0": 3, "+_1 -_1": 4, "+_0 +_0 -_0 -_0": 1, "+_0 +_0 -_0 -_1": 2, "+_0 +_0 -_1 -_0": 3, "+_0 +_0 -_1 -_1": 4, "+_0 +_1 -_0 -_0": 5, "+_0 +_1 -_0 -_1": 6, "+_0 +_1 -_1 -_0": 7, "+_0 +_1 -_1 -_1": 8, "+_1 +_0 -_0 -_0": 9, "+_1 +_0 -_0 -_1": 10, "+_1 +_0 -_1 -_0": 11, "+_1 +_0 -_1 -_1": 12, "+_1 +_1 -_0 -_0": 13, "+_1 +_1 -_0 -_1": 14, "+_1 +_1 -_1 -_0": 15, "+_1 +_1 -_1 -_1": 16, }, num_spin_orbitals=r_l, ) self.assertEqual(op, expected) if _optionals.HAS_SPARSE: import sparse as sp # pylint: disable=import-error with self.subTest("sparse tensor"): r_l = 2 p_t = PolynomialTensor( { "+-": sp.as_coo({(0, 0): 1, (1, 0): 2}, shape=(r_l, r_l)), "++--": sp.as_coo( {(0, 0, 0, 1): 1, (1, 0, 1, 1): 2}, shape=(r_l, r_l, r_l, r_l) ), } ) op = FermionicOp.from_polynomial_tensor(p_t) expected = FermionicOp( { "+_0 -_0": 1, "+_1 -_0": 2, "+_0 +_0 -_0 -_1": 1, "+_1 +_0 -_1 -_1": 2, }, num_spin_orbitals=r_l, ) self.assertEqual(op, expected) with self.subTest("compose operation order"): r_l = 2 p_t = PolynomialTensor( { "+-": np.arange(1, 5).reshape((r_l, r_l)), "++--": np.arange(1, 17).reshape((r_l, r_l, r_l, r_l)), } ) op = FermionicOp.from_polynomial_tensor(p_t) a = op @ op b = FermionicOp.from_polynomial_tensor(p_t @ p_t) self.assertEqual(a, b) with self.subTest("tensor operation order"): r_l = 2 p_t = PolynomialTensor( { "+-": np.arange(1, 5).reshape((r_l, r_l)), "++--": np.arange(1, 17).reshape((r_l, r_l, r_l, r_l)), } ) op = FermionicOp.from_polynomial_tensor(p_t) self.assertEqual(op ^ op, FermionicOp.from_polynomial_tensor(p_t ^ p_t)) def test_no_num_spin_orbitals(self): """Test operators with automatic register length""" op0 = FermionicOp({"": 1}) op1 = FermionicOp({"+_0 -_0": 1}) op2 = FermionicOp({"-_0 +_1": 2}) with self.subTest("Inferred register length"): self.assertEqual(op0.num_spin_orbitals, 0) self.assertEqual(op1.num_spin_orbitals, 1) self.assertEqual(op2.num_spin_orbitals, 2) with self.subTest("Mathematical operations"): self.assertEqual((op0 + op2).num_spin_orbitals, 2) self.assertEqual((op1 + op2).num_spin_orbitals, 2) self.assertEqual((op0 @ op2).num_spin_orbitals, 2) self.assertEqual((op1 @ op2).num_spin_orbitals, 2) self.assertEqual((op1 ^ op2).num_spin_orbitals, 3) with self.subTest("Equality"): op3 = FermionicOp({"+_0 -_0": 1}, num_spin_orbitals=3) self.assertEqual(op1, op3) self.assertTrue(op1.equiv(1.000001 * op3)) def test_terms(self): """Test terms generator.""" op = FermionicOp( { "+_0": 1, "-_0 +_1": 2, "+_1 -_1 +_2": 2, } ) terms = [([("+", 0)], 1), ([("-", 0), ("+", 1)], 2), ([("+", 1), ("-", 1), ("+", 2)], 2)] with self.subTest("terms"): self.assertEqual(list(op.terms()), terms) with self.subTest("from_terms"): self.assertEqual(FermionicOp.from_terms(terms), op) def test_permute_indices(self): """Test index permutation method.""" op = FermionicOp( { "+_0 -_1": 1, "+_1 -_2": 2, }, num_spin_orbitals=4, ) with self.subTest("wrong permutation length"): with self.assertRaises(ValueError): _ = op.permute_indices([1, 0]) with self.subTest("actual permutation"): permuted_op = op.permute_indices([2, 1, 3, 0]) self.assertEqual( permuted_op, FermionicOp({"+_2 -_1": 1, "+_1 -_3": 2}, num_spin_orbitals=4) ) def test_reg_len_with_skipped_key_validation(self): """Test the behavior of `register_length` after key validation was skipped.""" new_op = FermionicOp({"+_0 -_1": 1}, validate=False) self.assertIsNone(new_op.num_spin_orbitals) self.assertEqual(new_op.register_length, 2) if __name__ == "__main__": unittest.main()
qiskit-nature/test/second_q/operators/test_fermionic_op.py/0
{ "file_path": "qiskit-nature/test/second_q/operators/test_fermionic_op.py", "repo_id": "qiskit-nature", "token_count": 12957 }
150
# This code is part of a Qiskit project. # # (C) Copyright IBM 2021, 2023. # # 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. """Tests Electronic Structure Problem.""" import unittest from test import QiskitNatureTestCase import json import numpy as np from qiskit_algorithms import MinimumEigensolverResult import qiskit_nature.optionals as _optionals from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.hamiltonians import ElectronicEnergy from qiskit_nature.second_q.operators import SparseLabelOp from qiskit_nature.second_q.problems import ElectronicStructureProblem from qiskit_nature.second_q.properties import AngularMomentum, Magnetization, ParticleNumber from qiskit_nature.second_q.transformers import ActiveSpaceTransformer class TestElectronicStructureProblem(QiskitNatureTestCase): """Tests Electronic Structure Problem.""" def test_interpret(self): """Tests the result interpretation method.""" dummy_result = MinimumEigensolverResult() dummy_result.eigenvalue = 1.0 dummy_result.aux_operators_evaluated = { "ParticleNumber": (1.0, 0.0), "AngularMomentum": (2.0, 0.0), "Magnetization": (-1.0, 0.0), } dummy_problem = ElectronicStructureProblem( ElectronicEnergy.from_raw_integrals(np.zeros((2, 2)), np.zeros((2, 2, 2, 2))) ) dummy_problem.hamiltonian.nuclear_repulsion_energy = 1.23 dummy_problem.reference_energy = -4.56 dummy_problem.properties.angular_momentum = AngularMomentum(1) dummy_problem.properties.magnetization = Magnetization(1) dummy_problem.properties.particle_number = ParticleNumber(1) elec_struc_res = dummy_problem.interpret(dummy_result) with self.subTest("hartree fock energy"): self.assertAlmostEqual(elec_struc_res.hartree_fock_energy, -4.56) with self.subTest("nuclear repulsion energy"): self.assertAlmostEqual(elec_struc_res.nuclear_repulsion_energy, 1.23) with self.subTest("computed energy"): self.assertEqual(len(elec_struc_res.computed_energies), 1) self.assertAlmostEqual(elec_struc_res.computed_energies[0], 1.0) with self.subTest("number of particles"): self.assertAlmostEqual(elec_struc_res.num_particles[0], 1.0) with self.subTest("angular momentum"): self.assertAlmostEqual(elec_struc_res.total_angular_momentum[0], 2.0) with self.subTest("spin"): self.assertAlmostEqual(elec_struc_res.spin[0], 1.0) with self.subTest("magnetization"): self.assertAlmostEqual(elec_struc_res.magnetization[0], -1.0) @unittest.skipIf(not _optionals.HAS_PYSCF, "pyscf not available.") def test_second_q_ops_without_transformers(self): """Tests that the list of second quantized operators is created if no transformers provided.""" expected_num_of_sec_quant_ops = 6 with open( self.get_resource_path("H2_631g_ferm_op.json", "second_q/problems/resources"), "r", encoding="utf8", ) as file: expected = json.load(file) driver = PySCFDriver(basis="631g") electronic_structure_problem = driver.run() electr_sec_quant_op, second_quantized_ops = electronic_structure_problem.second_q_ops() with self.subTest("Check expected length of the list of second quantized operators."): assert len(second_quantized_ops) == expected_num_of_sec_quant_ops with self.subTest("Check types in the list of second quantized operators."): for second_quantized_op in second_quantized_ops.values(): assert isinstance(second_quantized_op, SparseLabelOp) with self.subTest("Check components of electronic second quantized operator."): assert all( s[0] == t[0] and np.isclose(np.abs(s[1]), np.abs(t[1])) for s, t in zip(sorted(expected.items()), sorted(electr_sec_quant_op.items())) ) @unittest.skipIf(not _optionals.HAS_PYSCF, "pyscf not available.") def test_second_q_ops_with_active_space(self): """Tests that the correct second quantized operator is created if an active space transformer is provided.""" expected_num_of_sec_quant_ops = 6 with open( self.get_resource_path( "H2_631g_ferm_op_active_space.json", "second_q/problems/resources" ), "r", encoding="utf8", ) as file: expected = json.load(file) driver = PySCFDriver(basis="631g") trafo = ActiveSpaceTransformer(2, 2) electronic_structure_problem = trafo.transform(driver.run()) electr_sec_quant_op, second_quantized_ops = electronic_structure_problem.second_q_ops() with self.subTest("Check expected length of the list of second quantized operators."): assert len(second_quantized_ops) == expected_num_of_sec_quant_ops with self.subTest("Check types in the list of second quantized operators."): for second_quantized_op in second_quantized_ops.values(): assert isinstance(second_quantized_op, SparseLabelOp) with self.subTest("Check components of electronic second quantized operator."): assert all( s[0] == t[0] and np.isclose(np.abs(s[1]), np.abs(t[1])) for s, t in zip(sorted(expected.items()), sorted(electr_sec_quant_op.items())) ) if __name__ == "__main__": unittest.main()
qiskit-nature/test/second_q/problems/test_electronic_structure_problem.py/0
{ "file_path": "qiskit-nature/test/second_q/problems/test_electronic_structure_problem.py", "repo_id": "qiskit-nature", "token_count": 2460 }
151
# This code is part of a Qiskit project. # # (C) Copyright IBM 2021, 2023. # # 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. """Test ParticleNumber Property""" from test.second_q.properties.property_test import PropertyTest from qiskit_nature.second_q.properties import ParticleNumber class TestParticleNumber(PropertyTest): """Test ParticleNumber Property""" def setUp(self): """Setup.""" super().setUp() num_spatial_orbitals = 4 self.prop = ParticleNumber(num_spatial_orbitals) def test_second_q_ops(self): """Test second_q_ops.""" ops = self.prop.second_q_ops()["ParticleNumber"] expected = { "+_0 -_0": 1.0, "+_1 -_1": 1.0, "+_2 -_2": 1.0, "+_3 -_3": 1.0, "+_4 -_4": 1.0, "+_5 -_5": 1.0, "+_6 -_6": 1.0, "+_7 -_7": 1.0, } self.assertEqual(dict(ops.items()), expected)
qiskit-nature/test/second_q/properties/test_particle_number.py/0
{ "file_path": "qiskit-nature/test/second_q/properties/test_particle_number.py", "repo_id": "qiskit-nature", "token_count": 559 }
152
# This code is part of a Qiskit project. # # (C) Copyright IBM 2020, 2023. # # 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. """ Fix copyright year in header """ from typing import Tuple, Union, List import builtins import sys import os import datetime import argparse import subprocess import traceback class CopyrightChecker: """Check copyright""" _UTF_STRING = "# -*- coding: utf-8 -*-" _COPYRIGHT_STRING = "# (C) Copyright IBM " def __init__(self, root_dir: str, check: bool) -> None: self._root_dir = root_dir self._check = check self._current_year = datetime.datetime.now().year self._changed_files = self._get_changed_files() @staticmethod def _exception_to_string(excp: Exception) -> str: stack = traceback.extract_stack()[:-3] + traceback.extract_tb(excp.__traceback__) pretty = traceback.format_list(stack) return "".join(pretty) + f"\n {excp.__class__} {excp}" @staticmethod def _get_year_from_date(date) -> int: if not date or len(date) < 4: return None return int(date[:4]) def _cmd_execute(self, args: List[str]) -> Tuple[str, Union[None, str]]: # execute command env = {} for k in ["SYSTEMROOT", "PATH"]: v = os.environ.get(k) if v is not None: env[k] = v # LANGUAGE is used on win32 env["LANGUAGE"] = "C" env["LANG"] = "C" env["LC_ALL"] = "C" with subprocess.Popen( args, cwd=self._root_dir, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) as popen: out, err = popen.communicate() popen.wait() out_str = out.decode("utf-8").strip() err_str = err.decode("utf-8").strip() err_str = err_str if err_str else None return out_str, err_str def _get_changed_files(self) -> List[str]: out_str, err_str = self._cmd_execute(["git", "diff", "--name-only", "HEAD"]) if err_str: raise builtins.Exception(err_str) return out_str.splitlines() def _get_file_last_year(self, relative_path: str) -> int: last_year = None errors = [] try: out_str, err_str = self._cmd_execute( ["git", "log", "-1", "--format=%cI", relative_path] ) last_year = CopyrightChecker._get_year_from_date(out_str) if err_str: errors.append(err_str) except Exception as ex: # pylint: disable=broad-except errors.append(f"'{relative_path}' Last year: {str(ex)}") if errors: raise ValueError(" - ".join(errors)) return last_year def check_copyright(self, file_path) -> Tuple[bool, bool, bool]: """check copyright for a file""" file_with_utf8 = False file_with_invalid_year = False file_has_header = False try: new_line = "# (C) Copyright IBM " idx_utf8 = -1 idx_new_line = -1 file_lines = None with open(file_path, "rt", encoding="utf8") as file: file_lines = file.readlines() for idx, line in enumerate(file_lines): relative_path = os.path.relpath(file_path, self._root_dir) if line.startswith(CopyrightChecker._UTF_STRING): if self._check: print(f"File contains utf-8 header: '{relative_path}'") file_with_utf8 = True idx_utf8 = idx if not line.startswith(CopyrightChecker._COPYRIGHT_STRING): continue file_has_header = True curr_years = [] for word in line.strip().split(): for year in word.strip().split(","): if year.startswith("20") and len(year) >= 4: try: curr_years.append(int(year[0:4])) except ValueError: pass header_start_year = None header_last_year = None if len(curr_years) > 1: header_start_year = curr_years[0] header_last_year = curr_years[1] elif len(curr_years) == 1: header_start_year = header_last_year = curr_years[0] if relative_path in self._changed_files: self._changed_files.remove(relative_path) last_year = self._current_year else: last_year = self._get_file_last_year(relative_path) if last_year and header_last_year != last_year: if header_start_year and header_start_year != last_year: new_line += f"{header_start_year}, " new_line += f"{self._current_year}.\n" if self._check: print( f"Wrong Copyright Year:'{relative_path}': ", f"Current:'{line[:-1]}' Correct:'{new_line[:-1]}'", ) file_with_invalid_year = True idx_new_line = idx break if not self._check and (idx_utf8 >= 0 or idx_new_line >= 0): if idx_new_line >= 0: file_lines[idx_new_line] = new_line if idx_utf8 >= 0: del file_lines[idx_utf8] with open(file_path, "w", encoding="utf8") as file: file.writelines(file_lines) if idx_new_line >= 0: file_with_invalid_year = False print(f"Fixed copyright year for {relative_path}.") if idx_utf8 >= 0: file_with_utf8 = False print(f"Removed utf-8 header for {relative_path}.") except UnicodeDecodeError: return file_with_utf8, file_with_invalid_year, file_has_header return file_with_utf8, file_with_invalid_year, file_has_header def check(self) -> Tuple[int, int, int]: """check copyright""" return self._check_copyright(self._root_dir) def _check_copyright(self, path: str) -> Tuple[int, int, int]: files_with_utf8 = 0 files_with_invalid_year = 0 files_with_header = 0 for item in os.listdir(path): fullpath = os.path.join(path, item) if os.path.isdir(fullpath): if not item.startswith("."): files = self._check_copyright(fullpath) files_with_utf8 += files[0] files_with_invalid_year += files[1] files_with_header += files[2] continue if os.path.isfile(fullpath): # check copyright year ( file_with_utf8, file_with_invalid_year, file_has_header, ) = self.check_copyright(fullpath) if file_with_utf8: files_with_utf8 += 1 if file_with_invalid_year: files_with_invalid_year += 1 if file_has_header: files_with_header += 1 return files_with_utf8, files_with_invalid_year, files_with_header def check_path(path): """valid path argument""" if not path or os.path.isdir(path): return path raise argparse.ArgumentTypeError(f"readable_dir:{path} is not a valid path") if __name__ == "__main__": PARSER = argparse.ArgumentParser(description="Check Copyright Tool") PARSER.add_argument("-path", type=check_path, metavar="path", help="Root path of project.") PARSER.add_argument( "-check", required=False, action="store_true", help="Just check copyright, without fixing it.", ) ARGS = PARSER.parse_args() if not ARGS.path: ARGS.path = os.getcwd() ARGS.path = os.path.abspath(os.path.realpath(os.path.expanduser(ARGS.path))) INVALID_UTF8, INVALID_YEAR, HAS_HEADER = CopyrightChecker(ARGS.path, ARGS.check).check() print(f"{INVALID_UTF8} files have utf8 headers.") print(f"{INVALID_YEAR} of {HAS_HEADER} files with copyright header have wrong years.") sys.exit(0 if INVALID_UTF8 == 0 and INVALID_YEAR == 0 else 1)
qiskit-nature/tools/check_copyright.py/0
{ "file_path": "qiskit-nature/tools/check_copyright.py", "repo_id": "qiskit-nature", "token_count": 4588 }
153
:orphan: ############### Getting started ############### Installation ============ Qiskit Optimization depends on Qiskit, which has its own `installation instructions <https://docs.quantum.ibm.com/start/install>`__ detailing the installation options for Qiskit and its supported environments/platforms. You should refer to that first. Then the information here can be followed which focuses on the additional installation specific to Qiskit Optimization. Qiskit Optimization has some functions that have been made optional where the dependent code and/or support program(s) are not (or cannot be) installed by default. Those are IBM CPLEX, CVXPY and Matplotlib. See :ref:`optional_installs` for more information. .. tab-set:: .. tab-item:: Start locally The simplest way to get started is to follow the `Qiskit installation instructions <https://docs.quantum.ibm.com/start/install>`__ In your virtual environment where you installed Qiskit, also install ``qiskit-optimization``: .. code:: sh pip install qiskit-optimization .. note:: As Qiskit Optimization depends on Qiskit, you can though simply install it into your environment, as above, and pip will automatically install a compatible version of Qiskit if one is not already installed. .. tab-item:: Install from source Installing Qiskit Optimization from source allows you to access the most recently updated version under development instead of using the version in the Python Package Index (PyPI) repository. This will give you the ability to inspect and extend the latest version of the Qiskit Optimization code more efficiently. Since Qiskit Optimization depends on Qiskit, and its latest changes may require new or changed features of Qiskit, you should first follow Qiskit's `"Install from source"` instructions `here <https://docs.quantum.ibm.com/start/install-qiskit-source>`__ .. raw:: html <h2>Installing Qiskit Optimization from Source</h2> Using the same development environment that you installed Qiskit in you are ready to install Qiskit Optimization. 1. Clone the Qiskit Optimization repository. .. code:: sh git clone https://github.com/qiskit-community/qiskit-optimization.git 2. Cloning the repository creates a local folder called ``qiskit-optimization``. .. code:: sh cd qiskit-optimization 3. If you want to run tests or linting checks, install the developer requirements. .. code:: sh pip install -r requirements-dev.txt 4. Install ``qiskit-optimization``. .. code:: sh pip install . If you want to install it in editable mode, meaning that code changes to the project don't require a reinstall to be applied, you can do this with: .. code:: sh pip install -e . .. _optional_installs: Optional installs ================= * **IBM CPLEX** may be installed using ``pip install 'qiskit-optimization[cplex]'`` to enable the reading of `LP` files and the usage of the `CplexOptimizer`, wrapper for ``cplex.Cplex``. CPLEX is a separate package and its support of Python versions is independent of Qiskit Optimization, where this CPLEX command will have no effect if there is no compatible version of CPLEX available (yet). * **CVXPY** may be installed using the command ``pip install 'qiskit-optimization[cvx]'``. CVXPY being installed will enable the usage of the Goemans-Williamson algorithm as an optimizer `GoemansWilliamsonOptimizer`. * **Matplotlib** may be installed using the command ``pip install 'qiskit-optimization[matplotlib]'``. Matplotlib being installed will enable the usage of the `draw` method in the graph optimization application classes. * **Gurobipy** may be installed using the command ``pip install 'qiskit-optimization[gurobi]'``. Gurobipy being installed will enable the usage of the `GurobiOptimizer`. ---- Ready to get going?... ====================== .. raw:: html <div class="tutorials-callout-container"> <div class="row"> .. qiskit-call-to-action-item:: :description: Find out about Qiskit Optimization. :header: Dive into the tutorials :button_link: ./tutorials/index.html :button_text: Qiskit Optimization tutorials .. raw:: html </div> </div> .. Hiding - Indices and tables :ref:`genindex` :ref:`modindex` :ref:`search`
qiskit-optimization/docs/getting_started.rst/0
{ "file_path": "qiskit-optimization/docs/getting_started.rst", "repo_id": "qiskit-optimization", "token_count": 1455 }
154
<jupyter_start><jupyter_text>Application Classes for Optimization Problems IntroductionWe introduce application classes for the following optimization problems so that users can easily try various optimization problems on quantum computers.1. Exact cover problem - Given a collection of subsets of items, find a subcollection such that each item is covered exactly once.2. Knapsack problem - Given a set of items, find a subset of items such that the total weight is within the capacity and the total value is maximized.3. Number partition problem - Given a multiset of positive integers, find a partition of the multiset into two subsets such that the sums of the subsets are equal.4. Set packing problem - Given a collection of subsets of items, find a subcollection such that all subsets of the subcollection are pairwise disjoint and the number of items in the subcollection is maximized.Graph problems5. Clique problem - Given an undirected graph, find a subset of nodes with a specified number or the maximum number such that the induced subgraph is complete.6. Graph partition problem - Given an undirected graph, find a partition into two components whose sizes are equal such that the total capacity of the edges between the two components is minimized.7. Max-cut problem - Given an undirected graph, find a partition of nodes into two subsets such that the total weight of the edges between the two subsets is maximized. 8. Stable set problem - Given an undirected graph, find a subset of nodes such that no edge connects the nodes in the subset and the number of nodes is maximized.9. Traveling salesman problem - Given a graph, find a route with the minimum distance such that the route visits each city exactly once.10. Vehicle routing problem - Given a graph, a depot node, and the number of vehicles (routes), find a set of routes such that each node is covered exactly once except the depot and the total distance of the routes is minimized.11. Vertex cover problem - Given an undirected graph, find a subset of nodes with the minimum size such that each edge has at least one endpoint in the subsets.The application classes for graph problems (`GraphOptimizationApplication`) provide a functionality to draw graphs of an instance and a result.Note that you need to install `matplotlib` beforehand to utilize the functionality. We introduce examples of the vertex cover problem and the knapsack problem in this page.Examples of the max-cut problem and the traveling salesman problem are available in [Max-Cut and Traveling Salesman Problem](06_examples_max_cut_and_tsp.ipynb). We first import packages necessary for application classes.<jupyter_code>from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit_algorithms.utils import algorithm_globals from qiskit_algorithms import QAOA, NumPyMinimumEigensolver from qiskit_algorithms.optimizers import COBYLA from qiskit.primitives import Sampler<jupyter_output><empty_output><jupyter_text>Vertex cover problemWe introduce the application class for the vertex cover problem as an example of graph problems.Given an undirected graph, the vertex cover problem asks us to find a subset of nodes with the minimum size such that all edges are covered by any node selected.We import the application class `VertexCover` for the vertex cover problem and `networkx` to generate a random graph.<jupyter_code>from qiskit_optimization.applications.vertex_cover import VertexCover import networkx as nx seed = 123 algorithm_globals.random_seed = seed graph = nx.random_regular_graph(d=3, n=6, seed=seed) pos = nx.spring_layout(graph, seed=seed) prob = VertexCover(graph) prob.draw(pos=pos)<jupyter_output><empty_output><jupyter_text>`VertexCover` takes a graph as an instance and `to_quadratic_program` generates a corresponding `QuadraticProgram` of the instance of the vertex cover problem.<jupyter_code>qp = prob.to_quadratic_program() print(qp.prettyprint())<jupyter_output>Problem name: Vertex cover Minimize x_0 + x_1 + x_2 + x_3 + x_4 + x_5 Subject to Linear constraints (9) x_1 + x_2 >= 1 'c0' x_1 + x_4 >= 1 'c1' x_1 + x_3 >= 1 'c2' x_2 + x_3 >= 1 'c3' x_0 + x_2 >= 1 'c4' x_0 + x_4 >= 1 'c5' x_0 + x_5 >= 1 'c6' x_4 + x_5 >= 1 'c7' x_3 + x_5 >= 1 'c8' Binary variables (6) x_0 x_1 x_2 x_3 x_4 x_5<jupyter_text>You can solve the problem as follows. `NumPyMinimumEigensolver` finds the minimum eigen vector. You can also apply QAOA. Note that the solution by QAOA is not always optimal.<jupyter_code># Numpy Eigensolver meo = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver()) result = meo.solve(qp) print(result.prettyprint()) print("\nsolution:", prob.interpret(result)) prob.draw(result, pos=pos) # QAOA meo = MinimumEigenOptimizer(min_eigen_solver=QAOA(reps=1, sampler=Sampler(), optimizer=COBYLA())) result = meo.solve(qp) print(result.prettyprint()) print("\nsolution:", prob.interpret(result)) print("\ntime:", result.min_eigen_solver_result.optimizer_time) prob.draw(result, pos=pos)<jupyter_output>objective function value: 4.0 variable values: x_0=1.0, x_1=1.0, x_2=0.0, x_3=1.0, x_4=1.0, x_5=0.0 status: SUCCESS solution: [0, 1, 3, 4] time: 2.721126079559326<jupyter_text>Knapsack problemThe knapsack problem asks us to find a combination of items such that the total weight is within the capacity of the knapsack and maximize the total value of the items.The following examples solve an instance of the knapsack problem with 5 items by Numpy eigensolver and QAOA.<jupyter_code>from qiskit_optimization.applications import Knapsack prob = Knapsack(values=[3, 4, 5, 6, 7], weights=[2, 3, 4, 5, 6], max_weight=10) qp = prob.to_quadratic_program() print(qp.prettyprint()) # Numpy Eigensolver meo = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver()) result = meo.solve(qp) print(result.prettyprint()) print("\nsolution:", prob.interpret(result)) # QAOA meo = MinimumEigenOptimizer(min_eigen_solver=QAOA(reps=1, sampler=Sampler(), optimizer=COBYLA())) result = meo.solve(qp) print(result.prettyprint()) print("\nsolution:", prob.interpret(result)) print("\ntime:", result.min_eigen_solver_result.optimizer_time)<jupyter_output>objective function value: 13.0 variable values: x_0=1.0, x_1=1.0, x_2=0.0, x_3=1.0, x_4=0.0 status: SUCCESS solution: [0, 1, 3] time: 2.0846190452575684<jupyter_text>How to check the HamiltonianIf you want to check the actual Hamiltonian generated from your problem instance, you need to apply a converter as follows.<jupyter_code>from qiskit_optimization.converters import QuadraticProgramToQubo # the same knapsack problem instance as in the previous section prob = Knapsack(values=[3, 4, 5, 6, 7], weights=[2, 3, 4, 5, 6], max_weight=10) qp = prob.to_quadratic_program() print(qp.prettyprint()) # intermediate QUBO form of the optimization problem conv = QuadraticProgramToQubo() qubo = conv.convert(qp) print(qubo.prettyprint()) # qubit Hamiltonian and offset op, offset = qubo.to_ising() print(f"num qubits: {op.num_qubits}, offset: {offset}\n") print(op) import tutorial_magics %qiskit_version_table %qiskit_copyright<jupyter_output><empty_output>
qiskit-optimization/docs/tutorials/09_application_classes.ipynb/0
{ "file_path": "qiskit-optimization/docs/tutorials/09_application_classes.ipynb", "repo_id": "qiskit-optimization", "token_count": 2273 }
155
# This code is part of a Qiskit project. # # (C) Copyright IBM 2020, 2023. # # 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. """An implementation of the ADMM algorithm.""" import copy import logging import time from typing import List, Optional, Tuple, cast import numpy as np from qiskit_algorithms import NumPyMinimumEigensolver from ..converters import MaximizeToMinimize from ..problems.constraint import Constraint from ..problems.linear_constraint import LinearConstraint from ..problems.linear_expression import LinearExpression from ..problems.quadratic_program import QuadraticProgram from ..problems.variable import Variable, VarType from .minimum_eigen_optimizer import MinimumEigenOptimizer from .optimization_algorithm import ( OptimizationAlgorithm, OptimizationResult, OptimizationResultStatus, ) from .slsqp_optimizer import SlsqpOptimizer UPDATE_RHO_BY_TEN_PERCENT = 0 UPDATE_RHO_BY_RESIDUALS = 1 logger = logging.getLogger(__name__) class ADMMParameters: """Defines a set of parameters for ADMM optimizer.""" def __init__( self, rho_initial: float = 10000, factor_c: float = 100000, beta: float = 1000, maxiter: int = 10, tol: float = 1.0e-4, max_time: float = np.inf, three_block: bool = True, vary_rho: int = UPDATE_RHO_BY_TEN_PERCENT, tau_incr: float = 2, tau_decr: float = 2, mu_res: float = 10, mu_merit: float = 1000, warm_start: bool = False, ) -> None: """Defines parameters for ADMM optimizer and their default values. Args: rho_initial: Initial value of rho parameter of ADMM. factor_c: Penalizing factor for equality constraints, when mapping to QUBO. beta: Penalization for y decision variables. maxiter: Maximum number of iterations for ADMM. tol: Tolerance for the residual convergence. max_time: Maximum running time (in seconds) for ADMM. three_block: Boolean flag to select the 3-block ADMM implementation. vary_rho: Flag to select the rule to update rho. If set to 0, then rho increases by 10% at each iteration. If set to 1, then rho is modified according to primal and dual residuals. tau_incr: Parameter used in the rho update (UPDATE_RHO_BY_RESIDUALS). The update rule can be found in: Boyd, S., Parikh, N., Chu, E., Peleato, B., & Eckstein, J. (2011). Distributed optimization and statistical learning via the alternating direction method of multipliers. Foundations and Trends® in Machine learning, 3(1), 1-122. tau_decr: Parameter used in the rho update (UPDATE_RHO_BY_RESIDUALS). mu_res: Parameter used in the rho update (UPDATE_RHO_BY_RESIDUALS). mu_merit: Penalization for constraint residual. Used to compute the merit values. warm_start: Start ADMM with pre-initialized values for binary and continuous variables by solving a relaxed (all variables are continuous) problem first. This option does not guarantee the solution will optimal or even feasible. The option should be used when tuning other options does not help and should be considered as a hint to the optimizer where to start its iterative process. """ super().__init__() self.mu_merit = mu_merit self.mu_res = mu_res self.tau_decr = tau_decr self.tau_incr = tau_incr self.vary_rho = vary_rho self.three_block = three_block self.max_time = max_time self.tol = tol self.maxiter = maxiter self.factor_c = factor_c self.beta = beta self.rho_initial = rho_initial self.warm_start = warm_start def __repr__(self) -> str: props = ", ".join([f"{key}={value}" for (key, value) in vars(self).items()]) return f"{type(self).__name__}({props})" class ADMMState: """Internal computation state of the ADMM implementation. The state keeps track of various variables are stored that are being updated during problem solving. The values are relevant to the problem being solved. The state is recreated for each optimization problem. State is returned as the third value. """ def __init__(self, op: QuadraticProgram, rho_initial: float) -> None: """ Args: op: The optimization problem being solved. rho_initial: Initial value of the rho parameter. """ super().__init__() # Optimization problem itself self.op = op # Indices of the variables self.binary_indices = None # type: Optional[List[int]] self.continuous_indices = None # type: Optional[List[int]] self.step1_absolute_indices = None # type: Optional[List[int]] self.step1_relative_indices = None # type: Optional[List[int]] # define heavily used matrix, they are used at each iteration, so let's cache them, # they are np.ndarrays # pylint:disable=invalid-name # objective self.q0 = None # type: Optional[np.ndarray] self.c0 = None # type: Optional[np.ndarray] self.q1 = None # type: Optional[np.ndarray] self.c1 = None # type: Optional[np.ndarray] # constraints self.a0 = None # type: Optional[np.ndarray] self.b0 = None # type: Optional[np.ndarray] # These are the parameters that are updated in the ADMM iterations. self.u = np.zeros(op.get_num_continuous_vars()) binary_size = op.get_num_binary_vars() self.x0 = np.zeros(binary_size) self.z = np.zeros(binary_size) self.z_init = self.z self.y = np.zeros(binary_size) self.lambda_mult = np.zeros(binary_size) # The following structures store quantities obtained in each ADMM iteration. self.cost_iterates = [] # type: List[float] self.residuals = [] # type: List[float] self.dual_residuals = [] # type: List[float] self.cons_r = [] # type: List[float] self.merits = [] # type: List[float] self.lambdas = [] # type: List[float] self.x0_saved = [] # type: List[np.ndarray] self.u_saved = [] # type: List[np.ndarray] self.z_saved = [] # type: List[np.ndarray] self.y_saved = [] # type: List[np.ndarray] self.rho = rho_initial # lin. eq. constraints with bin. vars. only self.binary_equality_constraints = [] # type: List[LinearConstraint] # all equality constraints self.equality_constraints = [] # type: List[Constraint] # all inequality constraints self.inequality_constraints = [] # type: List[Constraint] class ADMMOptimizationResult(OptimizationResult): """ADMMOptimization Result.""" def __init__( self, x: np.ndarray, fval: float, variables: List[Variable], state: ADMMState, status: OptimizationResultStatus, ) -> None: """ Args: x: the optimal value found by ADMM. fval: the optimal function value. variables: the list of variables of the optimization problem. state: the internal computation state of ADMM. status: Termination status of an optimization algorithm """ super().__init__(x=x, fval=fval, variables=variables, status=status, raw_results=state) @property def state(self) -> ADMMState: """returns state""" return self._raw_results class ADMMOptimizer(OptimizationAlgorithm): """An implementation of the ADMM-based heuristic. This algorithm is introduced in [1]. **References:** [1] Gambella, C., & Simonetto, A. (2020). Multi-block ADMM Heuristics for Mixed-Binary Optimization on Classical and Quantum Computers. arXiv preprint arXiv:2001.02069. """ def __init__( self, qubo_optimizer: Optional[OptimizationAlgorithm] = None, continuous_optimizer: Optional[OptimizationAlgorithm] = None, params: Optional[ADMMParameters] = None, ) -> None: """ Args: qubo_optimizer: An instance of OptimizationAlgorithm that can effectively solve QUBO problems. If not specified then :class:`MinimumEigenOptimizer` initialized with an instance of ``NumPyMinimumEigensolver`` will be used. continuous_optimizer: An instance of OptimizationAlgorithm that can solve continuous problems. If not specified then :class:`SlsqpOptimizer` will be used. params: An instance of ADMMParameters. """ super().__init__() self._log = logging.getLogger(__name__) # create default params if not present self._params = params or ADMMParameters() # create optimizers if not specified self._qubo_optimizer = qubo_optimizer or MinimumEigenOptimizer(NumPyMinimumEigensolver()) self._continuous_optimizer = continuous_optimizer or SlsqpOptimizer() # internal state where we'll keep intermediate solution # here, we just declare the class variable, the variable is initialized in kept in # the solve method. self._state = None # type: Optional[ADMMState] def get_compatibility_msg(self, problem: QuadraticProgram) -> str: """Checks whether a given problem can be solved with the optimizer implementing this method. Args: problem: The optimization problem to check compatibility. Returns: Returns the incompatibility message. If the message is empty no issues were found. """ msg = "" # 1. get bin/int and continuous variable indices bin_int_indices = self._get_variable_indices(problem, Variable.Type.BINARY) continuous_indices = self._get_variable_indices(problem, Variable.Type.CONTINUOUS) # 2. binary and continuous variables are separable in objective for bin_int_index in bin_int_indices: for continuous_index in continuous_indices: coeff = problem.objective.quadratic[bin_int_index, continuous_index] if coeff != 0: # binary and continuous vars are mixed. msg += "Binary and continuous variables are not separable in the objective. " # if an error occurred, return error message, otherwise, return the empty string return msg def solve(self, problem: QuadraticProgram) -> ADMMOptimizationResult: """Tries to solves the given problem using ADMM algorithm. Args: problem: The problem to be solved. Returns: The result of the optimizer applied to the problem. Raises: QiskitOptimizationError: If the problem is not compatible with the ADMM optimizer. """ self._verify_compatibility(problem) # debug self._log.debug("Initial problem: %s", problem.export_as_lp_string()) # map integer variables to binary variables from ..converters.integer_to_binary import IntegerToBinary # we deal with minimization in the optimizer, so turn the problem to minimization converters = [IntegerToBinary(), MaximizeToMinimize()] original_problem = problem problem = self._convert(problem, converters) # create our computation state. self._state = ADMMState(problem, self._params.rho_initial) # parse problem and convert to an ADMM specific representation. self._state.binary_indices = self._get_variable_indices(problem, Variable.Type.BINARY) self._state.continuous_indices = self._get_variable_indices( problem, Variable.Type.CONTINUOUS ) if self._params.warm_start: # warm start injection for the initial values of the variables self._warm_start(problem) # convert optimization problem to a set of matrices and vector that are used # at each iteration. self._convert_problem_representation() start_time = time.time() # we have not stated our computations yet, so elapsed time initialized as zero. elapsed_time = 0.0 iteration = 0 residual = 1.0e2 while (iteration < self._params.maxiter and residual > self._params.tol) and ( elapsed_time < self._params.max_time ): if self._state.step1_absolute_indices: op1 = self._create_step1_problem() self._state.x0 = self._update_x0(op1) # debug self._log.debug("Step 1 sub-problem: %s", op1.export_as_lp_string()) # else, no binary variables exist, and no update to be done in this case. # debug self._log.debug("x0=%s", self._state.x0) op2 = self._create_step2_problem() self._state.u, self._state.z = self._update_x1(op2) # debug self._log.debug("Step 2 sub-problem: %s", op2.export_as_lp_string()) self._log.debug("u=%s", self._state.u) self._log.debug("z=%s", self._state.z) if self._params.three_block: if self._state.binary_indices: op3 = self._create_step3_problem() self._state.y = self._update_y(op3) # debug self._log.debug("Step 3 sub-problem: %s", op3.export_as_lp_string()) # debug self._log.debug("y=%s", self._state.y) self._state.lambda_mult = self._update_lambda_mult() # debug self._log.debug("lambda: %s", self._state.lambda_mult) cost_iterate = self._get_objective_value() constraint_residual = self._get_constraint_residual() residual, dual_residual = self._get_solution_residuals(iteration) merit = self._get_merit(cost_iterate, constraint_residual) # debug self._log.debug( "cost_iterate=%s, cr=%s, merit=%s", cost_iterate, constraint_residual, merit, ) # costs are saved with their original sign. self._state.cost_iterates.append(cost_iterate) self._state.residuals.append(residual) self._state.dual_residuals.append(dual_residual) self._state.cons_r.append(constraint_residual) self._state.merits.append(merit) self._state.lambdas.append(cast(float, np.linalg.norm(self._state.lambda_mult))) self._state.x0_saved.append(self._state.x0) self._state.u_saved.append(self._state.u) self._state.z_saved.append(self._state.z) self._state.y_saved.append(self._state.y) self._update_rho(residual, dual_residual) iteration += 1 elapsed_time = time.time() - start_time binary_vars, continuous_vars, objective_value = self._get_best_merit_solution() solution = self._revert_solution_indexes(binary_vars, continuous_vars) self._log.debug( "solution=%s, objective=%s at iteration=%s", solution, objective_value, iteration ) # convert back integer to binary and eventually minimization to maximization # `state` is our internal state of computations. return cast( ADMMOptimizationResult, self._interpret( x=solution, converters=converters, problem=original_problem, result_class=ADMMOptimizationResult, state=self._state, ), ) @staticmethod def _get_variable_indices(op: QuadraticProgram, var_type: VarType) -> List[int]: """Returns a list of indices of the variables of the specified type. Args: op: Optimization problem. var_type: type of variables to look for. Returns: List of indices. """ indices = [] for i, variable in enumerate(op.variables): if variable.vartype == var_type: indices.append(i) return indices def _get_current_solution(self) -> np.ndarray: """ Returns current solution of the problem. Returns: An array of the current solution. """ return self._revert_solution_indexes(self._state.x0, self._state.u) def _revert_solution_indexes( self, binary_vars: np.ndarray, continuous_vars: np.ndarray ) -> np.ndarray: """Constructs a solution array where variables are stored in the correct order. Args: binary_vars: solution for binary variables continuous_vars: solution for continuous variables Returns: A solution array. """ solution = np.zeros(len(self._state.binary_indices) + len(self._state.continuous_indices)) # restore solution at the original index location solution.put(self._state.binary_indices, binary_vars) solution.put(self._state.continuous_indices, continuous_vars) return solution def _convert_problem_representation(self) -> None: """Converts problem representation into set of matrices and vectors.""" binary_var_indices = set(self._state.binary_indices) # separate constraints for l_constraint in self._state.op.linear_constraints: if l_constraint.sense == Constraint.Sense.EQ: self._state.equality_constraints.append(l_constraint) # verify that there are only binary variables in the constraint # this is to build A0, b0 in step 1 constraint_var_indices = set(l_constraint.linear.to_dict().keys()) if constraint_var_indices.issubset(binary_var_indices): self._state.binary_equality_constraints.append(l_constraint) elif l_constraint.sense in (Constraint.Sense.LE, Constraint.Sense.GE): self._state.inequality_constraints.append(l_constraint) # separate quadratic constraints into eq and non-eq for q_constraint in self._state.op.quadratic_constraints: if q_constraint.sense == Constraint.Sense.EQ: self._state.equality_constraints.append(q_constraint) elif q_constraint.sense in (Constraint.Sense.LE, Constraint.Sense.GE): self._state.inequality_constraints.append(q_constraint) # separately keep binary variables that are for step 1 only # temp variables are due to limit of 100 chars per line step1_absolute_indices, step1_relative_indices = self._get_step1_indices() self._state.step1_absolute_indices = step1_absolute_indices self._state.step1_relative_indices = step1_relative_indices # objective self._state.q0 = self._get_q(self._state.step1_absolute_indices) c0_vec = self._state.op.objective.linear.to_array()[self._state.step1_absolute_indices] self._state.c0 = c0_vec self._state.q1 = self._get_q(self._state.continuous_indices) self._state.c1 = self._state.op.objective.linear.to_array()[self._state.continuous_indices] # equality constraints with binary vars only self._state.a0, self._state.b0 = self._get_a0_b0() def _get_step1_indices(self) -> Tuple[List[int], List[int]]: """ Constructs two arrays of absolute (pointing to the original problem) and relative (pointing to the list of all binary variables) indices of the variables considered to be included in the step1(QUBO) problem. Returns: A tuple of lists with absolute and relative indices """ # here we keep binary indices from the original problem step1_absolute_indices = [] # iterate over binary variables and put all binary variables mentioned in the objective # to the array for the step1 for binary_index in self._state.binary_indices: # here we check if this binary variable present in the objective # either in the linear or quadratic terms if ( self._state.op.objective.linear[binary_index] != 0 or np.abs(self._state.op.objective.quadratic.coefficients[binary_index, :]).sum() != 0 ): # add the variable if it was not added before if binary_index not in step1_absolute_indices: step1_absolute_indices.append(binary_index) # compute all unverified binary variables (the variables that are present in constraints # but not in objective): # rest variables := all binary variables - already verified for step 1 rest_binary = set(self._state.binary_indices).difference(step1_absolute_indices) # verify if an equality contains binary variables for constraint in self._state.binary_equality_constraints: for binary_index in list(rest_binary): if ( constraint.linear[binary_index] > 0 and binary_index not in step1_absolute_indices ): # a binary variable with the binary_index is present in this constraint step1_absolute_indices.append(binary_index) # we want to preserve order of the variables but this order could be broken by adding # a variable in the previous for loop. step1_absolute_indices.sort() # compute relative indices, these indices are used when we generate step1 and # update variables on step1. # on step1 we solve for a subset of all binary variables, # so we want to operate only these indices step1_relative_indices = [] relative_index = 0 # for each binary variable that comes from lin.eq/obj and which is denoted by abs_index for abs_index in step1_absolute_indices: found = False # we want to find relative index of a variable the comes from linear constraints # or objective across all binary variables for j in range(relative_index, len(self._state.binary_indices)): if self._state.binary_indices[j] == abs_index: found = True relative_index = j break if found: step1_relative_indices.append(relative_index) else: raise ValueError("No relative index found!") return step1_absolute_indices, step1_relative_indices def _get_q(self, variable_indices: List[int]) -> np.ndarray: """Constructs a quadratic matrix for the variables with the specified indices from the quadratic terms in the objective. Args: variable_indices: variable indices to look for. Returns: A matrix as a numpy array of the shape(len(variable_indices), len(variable_indices)). """ size = len(variable_indices) q = np.zeros(shape=(size, size)) # fill in the matrix # in fact we use re-indexed variables # we build upper triangular matrix to avoid doubling of the coefficients for i in range(0, size): for j in range(i, size): q[i, j] = self._state.op.objective.quadratic[ variable_indices[i], variable_indices[j] ] return q def _get_a0_b0(self) -> Tuple[np.ndarray, np.ndarray]: """Constructs a matrix and a vector from the constraints in a form of Ax = b, where x is a vector of binary variables. Returns: Corresponding matrix and vector as numpy arrays. Raises: ValueError: if the problem is not suitable for this optimizer. """ matrix = [] vector = [] for constraint in self._state.binary_equality_constraints: row = constraint.linear.to_array().take(self._state.step1_absolute_indices).tolist() matrix.append(row) vector.append(constraint.rhs) if len(matrix) != 0: np_matrix = np.array(matrix) np_vector = np.array(vector) else: np_matrix = np.array([0] * len(self._state.step1_absolute_indices)).reshape((1, -1)) np_vector = np.zeros(shape=(1,)) return np_matrix, np_vector def _create_step1_problem(self) -> QuadraticProgram: """Creates a step 1 sub-problem. Returns: A newly created optimization problem. """ op1 = QuadraticProgram() binary_size = len(self._state.step1_absolute_indices) # create the same binary variables. for i in range(binary_size): name = self._state.op.variables[self._state.step1_absolute_indices[i]].name op1.binary_var(name=name) # prepare and set quadratic objective. quadratic_objective = ( self._state.q0 + self._params.factor_c / 2 * np.dot(self._state.a0.transpose(), self._state.a0) + self._state.rho / 2 * np.eye(binary_size) ) op1.objective.quadratic = quadratic_objective # prepare and set linear objective. linear_objective = ( self._state.c0 - self._params.factor_c * np.dot(self._state.b0, self._state.a0) + self._state.rho * ( -self._state.y[self._state.step1_relative_indices] - self._state.z[self._state.step1_relative_indices] ) + self._state.lambda_mult[self._state.step1_relative_indices] ) op1.objective.linear = linear_objective return op1 def _create_step2_problem(self) -> QuadraticProgram: """Creates a step 2 sub-problem. Returns: A newly created optimization problem. """ op2 = copy.deepcopy(self._state.op) # replace binary variables with the continuous ones bound in [0,1] # x0(bin) -> z(cts) # u (cts) are still there unchanged for i, var_index in enumerate(self._state.binary_indices): variable = op2.variables[var_index] variable.vartype = Variable.Type.CONTINUOUS variable.upperbound = 1.0 variable.lowerbound = 0.0 # replacing Q0 objective and take of min/max sense, initially we consider minimization op2.objective.quadratic[var_index, var_index] = self._state.rho / 2 # replacing linear objective op2.objective.linear[var_index] = -1 * self._state.lambda_mult[i] - self._state.rho * ( self._state.x0[i] - self._state.y[i] ) # remove A0 x0 = b0 constraints for constraint in self._state.binary_equality_constraints: op2.remove_linear_constraint(constraint.name) return op2 def _create_step3_problem(self) -> QuadraticProgram: """Creates a step 3 sub-problem. Returns: A newly created optimization problem. """ op3 = QuadraticProgram() # add y variables. binary_size = len(self._state.binary_indices) for i in range(binary_size): name = self._state.op.variables[self._state.binary_indices[i]].name op3.continuous_var(lowerbound=-np.inf, upperbound=np.inf, name=name) # set quadratic objective y quadratic_y = self._params.beta / 2 * np.eye(binary_size) + self._state.rho / 2 * np.eye( binary_size ) op3.objective.quadratic = quadratic_y # type: ignore[assignment] # set linear objective for y linear_y = -self._state.lambda_mult - self._state.rho * (self._state.x0 - self._state.z) op3.objective.linear = cast(LinearExpression, linear_y) return op3 def _update_x0(self, op1: QuadraticProgram) -> np.ndarray: """Solves the Step1 QuadraticProgram via the qubo optimizer. Args: op1: the Step1 QuadraticProgram. Returns: A solution of the Step1, as a numpy array. """ x0_all_binaries = np.zeros(len(self._state.binary_indices)) x0_qubo = np.asarray(self._qubo_optimizer.solve(op1).x) x0_all_binaries[self._state.step1_relative_indices] = x0_qubo return x0_all_binaries def _update_x1(self, op2: QuadraticProgram) -> Tuple[np.ndarray, np.ndarray]: """Solves the Step2 QuadraticProgram via the continuous optimizer. Args: op2: the Step2 QuadraticProgram Returns: A solution of the Step2, as a pair of numpy arrays. First array contains the values of decision variables u, and second array contains the values of decision variables z. """ vars_op2 = np.asarray(self._continuous_optimizer.solve(op2).x) vars_u = vars_op2.take(self._state.continuous_indices) vars_z = vars_op2.take(self._state.binary_indices) return vars_u, vars_z def _update_y(self, op3: QuadraticProgram) -> np.ndarray: """Solves the Step3 QuadraticProgram via the continuous optimizer. Args: op3: the Step3 QuadraticProgram Returns: A solution of the Step3, as a numpy array. """ return np.asarray(self._continuous_optimizer.solve(op3).x) def _get_best_merit_solution(self) -> Tuple[np.ndarray, np.ndarray, float]: """The ADMM solution is that for which the merit value is the min * sol: Iterate with the min merit value * sol_val: Value of sol, according to the original objective Returns: A tuple of (binary_vars, continuous_vars, sol_val), where * binary_vars: binary variable values with the min merit value * continuous_vars: continuous variable values with the min merit value * sol_val: Value of the objective function """ it_min_merits = self._state.merits.index(min(self._state.merits)) binary_vars = self._state.x0_saved[it_min_merits] continuous_vars = self._state.u_saved[it_min_merits] sol_val = self._state.cost_iterates[it_min_merits] return binary_vars, continuous_vars, sol_val def _update_lambda_mult(self) -> np.ndarray: """ Updates the values of lambda multiplier, given the updated iterates x0, z, and y. Returns: The updated array of values of lambda multiplier. """ return self._state.lambda_mult + self._state.rho * ( self._state.x0 - self._state.z - self._state.y ) def _update_rho(self, primal_residual: float, dual_residual: float) -> None: """Updating the rho parameter in ADMM. Args: primal_residual: primal residual dual_residual: dual residual """ if self._params.vary_rho == UPDATE_RHO_BY_TEN_PERCENT: # Increase rho, to aid convergence. if self._state.rho < 1.0e10: self._state.rho *= 1.1 elif self._params.vary_rho == UPDATE_RHO_BY_RESIDUALS: if primal_residual > self._params.mu_res * dual_residual: self._state.rho = self._params.tau_incr * self._state.rho elif dual_residual > self._params.mu_res * primal_residual: self._state.rho = self._state.rho / self._params.tau_decr def _get_constraint_residual(self) -> float: """Compute violation of the constraints of the original problem, as: * norm 1 of the body-rhs of eq. constraints * -1 * min(body - rhs, 0) for geq constraints * max(body - rhs, 0) for leq constraints Returns: Violation of the constraints as a float value """ solution = self._get_current_solution() # equality constraints cr_eq = 0 for constraint in self._state.equality_constraints: cr_eq += np.abs(constraint.evaluate(solution) - constraint.rhs) # inequality constraints cr_ineq = 0.0 for constraint in self._state.inequality_constraints: sense = -1.0 if constraint.sense == Constraint.Sense.GE else 1.0 cr_ineq += max(sense * (constraint.evaluate(solution) - constraint.rhs), 0.0) return cr_eq + cr_ineq def _get_merit(self, cost_iterate: float, constraint_residual: float) -> float: """Compute merit value associated with the current iterate Args: cost_iterate: Cost at the certain iteration. constraint_residual: Value of violation of the constraints. Returns: Merit value as a float """ return cost_iterate + self._params.mu_merit * constraint_residual def _get_objective_value(self) -> float: """Computes the value of the objective function. Returns: Value of the objective function as a float """ return self._state.op.objective.evaluate(self._get_current_solution()) def _get_solution_residuals(self, iteration: int) -> Tuple[float, float]: """Compute primal and dual residual. Args: iteration: Iteration number. Returns: r, s as primary and dual residuals. """ elements = self._state.x0 - self._state.z - self._state.y primal_residual: float = cast(float, np.linalg.norm(elements)) if iteration > 0: elements_dual = self._state.z - self._state.z_saved[iteration - 1] else: elements_dual = self._state.z - self._state.z_init dual_residual: float = cast(float, self._state.rho * np.linalg.norm(elements_dual)) return primal_residual, dual_residual def _warm_start(self, problem: QuadraticProgram) -> None: """Solves a relaxed (all variables are continuous) and initializes the optimizer state with the found solution. Args: problem: a problem to solve. Returns: None """ qp_copy = copy.deepcopy(problem) for variable in qp_copy.variables: variable.vartype = VarType.CONTINUOUS cts_result = self._continuous_optimizer.solve(qp_copy) logger.debug("Continuous relaxation: %s", cts_result.x) self._state.x0 = cts_result.x[self._state.binary_indices] self._state.u = cts_result.x[self._state.continuous_indices] self._state.z = cts_result.x[self._state.binary_indices] @property def parameters(self) -> ADMMParameters: """Returns current parameters of the optimizer. Returns: The parameters. """ return self._params @parameters.setter def parameters(self, params: ADMMParameters) -> None: """Sets the parameters of the optimizer. Args: params: New parameters to set. """ self._params = params
qiskit-optimization/qiskit_optimization/algorithms/admm_optimizer.py/0
{ "file_path": "qiskit-optimization/qiskit_optimization/algorithms/admm_optimizer.py", "repo_id": "qiskit-optimization", "token_count": 15367 }
156
# This code is part of a Qiskit project. # # (C) Copyright IBM 2020, 2023. # # 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 recursive minimal eigen optimizer in Qiskit optimization module.""" from copy import deepcopy from enum import Enum from typing import Dict, List, Optional, Tuple, Union, cast import numpy as np from qiskit_algorithms import NumPyMinimumEigensolver from qiskit_algorithms.utils.validation import validate_min from ..converters.quadratic_program_to_qubo import QuadraticProgramConverter, QuadraticProgramToQubo from ..exceptions import QiskitOptimizationError from ..problems import Variable from ..problems.quadratic_program import QuadraticProgram from .minimum_eigen_optimizer import MinimumEigenOptimizationResult, MinimumEigenOptimizer from .optimization_algorithm import ( OptimizationAlgorithm, OptimizationResult, OptimizationResultStatus, ) class IntermediateResult(Enum): """ Defines whether the intermediate results of :class:`~qiskit_optimization.algorithms.RecursiveMinimumEigenOptimizer` at each iteration should be stored and returned to the end user. """ NO_ITERATIONS = 0 """No intermediate results are stored.""" LAST_ITERATION = 1 """Only results from the last iteration are stored.""" ALL_ITERATIONS = 2 """All intermediate results are stored.""" class RecursiveMinimumEigenOptimizationResult(OptimizationResult): """Recursive Eigen Optimizer Result.""" def __init__( self, x: Union[List[float], np.ndarray], fval: float, variables: List[Variable], status: OptimizationResultStatus, replacements: Dict[str, Tuple[str, int]], history: Tuple[List[MinimumEigenOptimizationResult], OptimizationResult], ) -> None: """ Constructs an instance of the result class. Args: x: the optimal value found in the optimization. fval: the optimal function value. variables: the list of variables of the optimization problem. status: the termination status of the optimization algorithm. replacements: a dictionary of substituted variables. Key is a variable being substituted, value is a tuple of substituting variable and a weight, either 1 or -1. history: a tuple containing intermediate results. The first element is a list of :class:`~qiskit_optimization.algorithms.MinimumEigenOptimizerResult` obtained by invoking :class:`~qiskit_optimization.algorithms.MinimumEigenOptimizer` iteratively, the second element is an instance of :class:`~qiskit_optimization.algorithm.OptimizationResult` obtained at the last step via `min_num_vars_optimizer`. """ super().__init__(x, fval, variables, status, None) self._replacements = replacements self._history = history @property def replacements(self) -> Dict[str, Tuple[str, int]]: """ Returns a dictionary of substituted variables. Key is a variable being substituted, value is a tuple of substituting variable and a weight, either 1 or -1.""" return self._replacements @property def history( self, ) -> Tuple[List[MinimumEigenOptimizationResult], OptimizationResult]: """ Returns intermediate results. The first element is a list of :class:`~qiskit_optimization.algorithms.MinimumEigenOptimizerResult` obtained by invoking :class:`~qiskit_optimization.algorithms.MinimumEigenOptimizer` iteratively, the second element is an instance of :class:`~qiskit_optimization.algorithm.OptimizationResult` obtained at the last step via `min_num_vars_optimizer`. """ return self._history class RecursiveMinimumEigenOptimizer(OptimizationAlgorithm): """A meta-algorithm that applies a recursive optimization. The recursive minimum eigen optimizer applies a recursive optimization on top of :class:`~qiskit_optimization.algorithms.OptimizationAlgorithm`. This optimizer can use :class:`~qiskit_optimization.algorithms.MinimumEigenOptimizer` as an optimizer that is called at each iteration. The algorithm is introduced in [1]. Examples: Outline of how to use this class: .. code-block:: python from qiskit_algorithms import QAOA from qiskit_optimization.problems import QuadraticProgram from qiskit_optimization.algorithms import ( MinimumEigenOptimizer, RecursiveMinimumEigenOptimizer ) problem = QuadraticProgram() # specify problem here # specify minimum eigen solver to be used, e.g., QAOA qaoa = QAOA(...) internal_optimizer = MinimumEigenOptimizer(qaoa) optimizer = RecursiveMinimumEigenOptimizer(internal_optimizer) result = optimizer.solve(problem) References: [1] Bravyi et al. (2019), Obstacles to State Preparation and Variational Optimization from Symmetry Protection. `arXiv:1910.08980 <http://arxiv.org/abs/1910.08980>`_ """ def __init__( self, optimizer: OptimizationAlgorithm, min_num_vars: int = 1, min_num_vars_optimizer: Optional[OptimizationAlgorithm] = None, penalty: Optional[float] = None, history: Optional[IntermediateResult] = IntermediateResult.LAST_ITERATION, converters: Optional[ Union[QuadraticProgramConverter, List[QuadraticProgramConverter]] ] = None, ) -> None: """Initializes the recursive minimum eigen optimizer. This initializer takes an ``OptimizationAlgorithm``, the parameters to specify until when to to apply the iterative scheme, and the optimizer to be applied once the threshold number of variables is reached. Args: optimizer: The optimizer to use in every iteration. min_num_vars: The minimum number of variables to apply the recursive scheme. If this threshold is reached, the min_num_vars_optimizer is used. min_num_vars_optimizer: This optimizer is used after the recursive scheme for the problem with the remaining variables. Default value is :class:`~qiskit_optimization.algorithms.MinimumEigenOptimizer` created on top of :class:`~qiskit_algorithms.NumPyMinimumEigensolver`. penalty: The factor that is used to scale the penalty terms corresponding to linear equality constraints. history: Whether the intermediate results are stored. Default value is :py:obj:`~IntermediateResult.LAST_ITERATION`. converters: The converters to use for converting a problem into a different form. By default, when None is specified, an internally created instance of :class:`~qiskit_optimization.converters.QuadraticProgramToQubo` will be used. Raises: QiskitOptimizationError: In case of invalid parameters (num_min_vars < 1). TypeError: When there one of converters is an invalid type. """ validate_min("min_num_vars", min_num_vars, 1) self._optimizer = optimizer self._min_num_vars = min_num_vars if min_num_vars_optimizer: self._min_num_vars_optimizer = min_num_vars_optimizer else: self._min_num_vars_optimizer = MinimumEigenOptimizer(NumPyMinimumEigensolver()) self._penalty = penalty self._history = history self._converters = self._prepare_converters(converters, penalty) def get_compatibility_msg(self, problem: QuadraticProgram) -> str: """Checks whether a given problem can be solved with this optimizer. Checks whether the given problem is compatible, i.e., whether the problem can be converted to a QUBO, and otherwise, returns a message explaining the incompatibility. Args: problem: The optimization problem to check compatibility. Returns: A message describing the incompatibility. """ return QuadraticProgramToQubo.get_compatibility_msg(problem) def solve(self, problem: QuadraticProgram) -> OptimizationResult: """Tries to solve the given problem using the recursive optimizer. Runs the optimizer to try to solve the optimization problem. Args: problem: The problem to be solved. Returns: The result of the optimizer applied to the problem. Raises: QiskitOptimizationError: Incompatible problem. QiskitOptimizationError: Infeasible due to variable substitution """ self._verify_compatibility(problem) # convert problem to QUBO, this implicitly checks if the problem is compatible problem_ = self._convert(problem, self._converters) problem_ref = deepcopy(problem_) # run recursive optimization until the resulting problem is small enough replacements = {} # type: Dict[str, Tuple[str, int]] optimization_results = [] # type: List[OptimizationResult] while problem_.get_num_vars() > self._min_num_vars: # solve current problem with optimizer res = self._optimizer.solve(problem_) # type: OptimizationResult if self._history == IntermediateResult.ALL_ITERATIONS: optimization_results.append(res) # analyze results to get strongest correlation correlations = res.get_correlations() i, j = self._find_strongest_correlation(correlations) x_i = problem_.variables[i].name x_j = problem_.variables[j].name if correlations[i, j] > 0: # set x_i = x_j problem_ = problem_.substitute_variables(variables={i: (j, 1)}) if problem_.status == QuadraticProgram.Status.INFEASIBLE: raise QiskitOptimizationError("Infeasible due to variable substitution") replacements[x_i] = (x_j, 1) else: # set x_i = 1 - x_j, this is done in two steps: # 1. set x_i = 1 + x_i # 2. set x_i = -x_j # 1a. get additional offset constant = problem_.objective.constant constant += problem_.objective.linear[i] constant += problem_.objective.quadratic[i, i] problem_.objective.constant = constant # 1b. get additional linear part for k in range(problem_.get_num_vars()): coeff = problem_.objective.linear[k] if k == i: coeff += 2 * problem_.objective.quadratic[i, k] else: coeff += problem_.objective.quadratic[i, k] # set new coefficient if not too small if np.abs(coeff) > 1e-10: problem_.objective.linear[k] = coeff else: problem_.objective.linear[k] = 0 # 2. replace x_i by -x_j problem_ = problem_.substitute_variables(variables={i: (j, -1)}) if problem_.status == QuadraticProgram.Status.INFEASIBLE: raise QiskitOptimizationError("Infeasible due to variable substitution") replacements[x_i] = (x_j, -1) # solve remaining problem result = self._min_num_vars_optimizer.solve(problem_) # unroll replacements var_values = {} for i, x in enumerate(problem_.variables): var_values[x.name] = result.x[i] def find_value(x, replacements, var_values): if x in var_values: # if value for variable is known, return it return var_values[x] elif x in replacements: # get replacement for variable (y, sgn) = replacements[x] # find details for replacing variable value = find_value(y, replacements, var_values) # construct, set, and return new value var_values[x] = value if sgn == 1 else 1 - value return var_values[x] else: raise QiskitOptimizationError("Invalid values!") # loop over all variables to set their values for x_i in problem_ref.variables: if x_i.name not in var_values: find_value(x_i.name, replacements, var_values) # build history before any translations are applied # min_eigen_results is an empty list if history is set to NO or LAST. history = ( optimization_results, None if self._history == IntermediateResult.NO_ITERATIONS else result, ) # construct result x_v = np.array([var_values[x_aux.name] for x_aux in problem_ref.variables]) return cast( RecursiveMinimumEigenOptimizationResult, self._interpret( x=x_v, converters=self._converters, problem=problem, result_class=RecursiveMinimumEigenOptimizationResult, replacements=replacements, history=history, ), ) @staticmethod def _find_strongest_correlation(correlations): # get absolute values and set diagonal to -1 to make sure maximum is always on off-diagonal abs_correlations = np.abs(correlations) for i in range(len(correlations)): abs_correlations[i, i] = -1 # get index of maximum (by construction on off-diagonal) m_max = np.argmax(abs_correlations.flatten()) # translate back to indices i = int(m_max // len(correlations)) j = int(m_max - i * len(correlations)) return (i, j)
qiskit-optimization/qiskit_optimization/algorithms/recursive_minimum_eigen_optimizer.py/0
{ "file_path": "qiskit-optimization/qiskit_optimization/algorithms/recursive_minimum_eigen_optimizer.py", "repo_id": "qiskit-optimization", "token_count": 5864 }
157
# This code is part of a Qiskit project. # # (C) Copyright IBM 2018, 2023. # # 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. """An application class for the stable set.""" from typing import Dict, List, Optional, Union import networkx as nx import numpy as np from docplex.mp.model import Model from qiskit_optimization.algorithms import OptimizationResult from qiskit_optimization.problems.quadratic_program import QuadraticProgram from qiskit_optimization.translators import from_docplex_mp from .graph_optimization_application import GraphOptimizationApplication class StableSet(GraphOptimizationApplication): """Optimization application for the "stable set" [1] problem based on a NetworkX graph. References: [1]: "Independent set (graph theory)", `https://en.wikipedia.org/wiki/Independent_set_(graph_theory) <https://en.wikipedia.org/wiki/Independent_set_(graph_theory)>`_ """ def to_quadratic_program(self) -> QuadraticProgram: """Convert a stable set instance into a :class:`~qiskit_optimization.problems.QuadraticProgram` Returns: The :class:`~qiskit_optimization.problems.QuadraticProgram` created from the stable set instance. """ mdl = Model(name="Stable set") n = self._graph.number_of_nodes() x = {i: mdl.binary_var(name=f"x_{i}") for i in range(n)} for w, v in self._graph.edges: self._graph.edges[w, v].setdefault("weight", 1) objective = mdl.sum(x[i] for i in x) for w, v in self._graph.edges: mdl.add_constraint(x[w] + x[v] <= 1) mdl.maximize(objective) op = from_docplex_mp(mdl) return op def interpret(self, result: Union[OptimizationResult, np.ndarray]) -> List[int]: """Interpret a result as a list of node indices Args: result : The calculated result of the problem Returns: A list of node indices whose corresponding variable is 1 """ x = self._result_to_x(result) stable_set = [] for i, value in enumerate(x): if value: stable_set.append(i) return stable_set def _draw_result( self, result: Union[OptimizationResult, np.ndarray], pos: Optional[Dict[int, np.ndarray]] = None, ) -> None: """Draw the result with colors Args: result : The calculated result for the problem pos: The positions of nodes """ x = self._result_to_x(result) nx.draw(self._graph, node_color=self._node_colors(x), pos=pos, with_labels=True) def _node_colors(self, x: np.ndarray): # Return a list of strings for draw. # Color a node with red when the corresponding variable is 1. # Otherwise color it with dark gray. return ["r" if x[node] == 1 else "darkgrey" for node in self._graph.nodes]
qiskit-optimization/qiskit_optimization/applications/stable_set.py/0
{ "file_path": "qiskit-optimization/qiskit_optimization/applications/stable_set.py", "repo_id": "qiskit-optimization", "token_count": 1306 }
158
# This code is part of a Qiskit project. # # (C) Copyright IBM 2019, 2023. # # 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. """Abstract Constraint.""" from abc import abstractmethod from enum import Enum from typing import Union, List, Dict, Any from numpy import ndarray from .quadratic_program_element import QuadraticProgramElement from ..exceptions import QiskitOptimizationError class ConstraintSense(Enum): """Constraint Sense Type.""" # pylint: disable=invalid-name LE = 0 GE = 1 EQ = 2 @staticmethod def convert(sense: Union[str, "ConstraintSense"]) -> "ConstraintSense": """Convert a string into a corresponding sense of constraints Args: sense: A string or sense of constraints Returns: The sense of constraints Raises: QiskitOptimizationError: if the input string is invalid. """ if isinstance(sense, ConstraintSense): return sense sense = sense.upper() if sense not in [ "E", "L", "G", "EQ", "LE", "GE", "=", "==", "<=", "<", ">=", ">", ]: raise QiskitOptimizationError(f"Invalid sense: {sense}") if sense in ["E", "EQ", "=", "=="]: return ConstraintSense.EQ elif sense in ["L", "LE", "<=", "<"]: return ConstraintSense.LE else: return ConstraintSense.GE @property def label(self) -> str: """Label of the constraint sense Returns: The label of the constraint sense ('<=', '>=', or '==') """ if self is ConstraintSense.LE: return "<=" elif self is ConstraintSense.GE: return ">=" else: return "==" class Constraint(QuadraticProgramElement): """Abstract Constraint Class.""" Sense = ConstraintSense def __init__( self, quadratic_program: Any, name: str, sense: ConstraintSense, rhs: float ) -> None: """Initializes the constraint. Args: quadratic_program: The parent QuadraticProgram. name: The name of the constraint. sense: The sense of the constraint. rhs: The right-hand-side of the constraint. """ super().__init__(quadratic_program) self._name = name self._sense = sense self._rhs = rhs @property def name(self) -> str: """Returns the name of the constraint. Returns: The name of the constraint. """ return self._name @property def sense(self) -> ConstraintSense: """Returns the sense of the constraint. Returns: The sense of the constraint. """ return self._sense @sense.setter def sense(self, sense: ConstraintSense) -> None: """Sets the sense of the constraint. Args: sense: The sense of the constraint. """ self._sense = sense @property def rhs(self) -> float: """Returns the right-hand-side of the constraint. Returns: The right-hand-side of the constraint. """ return self._rhs @rhs.setter def rhs(self, rhs: float) -> None: """Sets the right-hand-side of the constraint. Args: rhs: The right-hand-side of the constraint. """ self._rhs = rhs @abstractmethod def evaluate(self, x: Union[ndarray, List, Dict[Union[int, str], float]]) -> float: """Evaluate left-hand-side of constraint for given values of variables. Args: x: The values to be used for the variables. Returns: The left-hand-side of the constraint. """ raise NotImplementedError()
qiskit-optimization/qiskit_optimization/problems/constraint.py/0
{ "file_path": "qiskit-optimization/qiskit_optimization/problems/constraint.py", "repo_id": "qiskit-optimization", "token_count": 1891 }
159
--- features: - | Adding the bin-packing application :class:`qiskit_optimization.applications.BinPacking`. https://en.wikipedia.org/wiki/Bin_packing_problem
qiskit-optimization/releasenotes/notes/0.3/add-bin-packing-app-c4ecf62fe047d496.yaml/0
{ "file_path": "qiskit-optimization/releasenotes/notes/0.3/add-bin-packing-app-c4ecf62fe047d496.yaml", "repo_id": "qiskit-optimization", "token_count": 59 }
160
--- prelude: > Qiskit Optimization 0.5 supports the new algorithms introduced in Qiskit Terra 0.22 which in turn rely on the `Qiskit Primitives <https://docs.quantum.ibm.com/api/qiskit/primitives>`_. Qiskit Optimization 0.5 still supports the former algorithms based on :class:`qiskit.utils.QuantumInstance`, but they will be deprecated and then removed, along with the support here, in future releases. features: - | The :class:`~.MinimumEigenOptimizer` class takes the primitives-based algorithms (:class:`qiskit.algorithms.minimum_eigensolvers.SamplingMinimumEigensolver` and :class:`qiskit.algorithms.minimum_eigensolvers.NumPyMinimumEigensolver`) as ``min_eigen_solver`` argument. The former algorithm :class:`qiskit.algorithms.MinimumEigensolver` is pending deprecation and will be deprecated and subsequently removed in future releases. Note that :class:`qiskit.algorithms.minimum_eigensolvers.SamplingVQE` supersedes :class:`qiskit.algorithms.VQE` for :class:`~.MinimumEigenOptimizer`. :class:`qiskit.algorithms.minimum_eigensolvers.NumPyMinimumEigensolver` also supersedes :class:`qiskit.algorithms.NumPyMinimumEigensolver`. - | The :class:`~.WarmStartQAOAOptimizer` class takes the primitives-based QAOA (:class:`qiskit.algorithms.minimum_eigensolvers.QAOA`) as ``qaoa`` argument. The former algorithm :class:`qiskit.algorithms.QAOA` is pending deprecation and will be deprecated and subsequently removed in future releases.
qiskit-optimization/releasenotes/notes/0.5/add-primitives-support-31af39549b5e66e3.yaml/0
{ "file_path": "qiskit-optimization/releasenotes/notes/0.5/add-primitives-support-31af39549b5e66e3.yaml", "repo_id": "qiskit-optimization", "token_count": 536 }
161
# This code is part of a Qiskit project. # # (C) Copyright IBM 2018, 2023. # # 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. """ Test Cplex Optimizer """ import unittest from test.optimization_test_case import QiskitOptimizationTestCase import numpy as np from ddt import data, ddt import qiskit_optimization.optionals as _optionals from qiskit_optimization.algorithms import CplexOptimizer, OptimizationResultStatus from qiskit_optimization.problems import QuadraticProgram @ddt class TestCplexOptimizer(QiskitOptimizationTestCase): """CPLEX Optimizer Tests.""" @data( ("op_ip1.lp", [0, 2], 6), ("op_mip1.lp", [0, 1, 1], 5.5), ("op_lp1.lp", [0.25, 1.75], 5.8750), ) @unittest.skipIf(not _optionals.HAS_CPLEX, "CPLEX not available.") def test_cplex_optimizer(self, config): """CPLEX Optimizer Test""" cplex_optimizer = CplexOptimizer( disp=False, cplex_parameters={"threads": 1, "randomseed": 1} ) # unpack configuration filename, x, fval = config # load optimization problem problem = QuadraticProgram() lp_file = self.get_resource_path(filename, "algorithms/resources") problem.read_from_lp_file(lp_file) # solve problem with cplex result = cplex_optimizer.solve(problem) # analyze results self.assertAlmostEqual(result.fval, fval) for i in range(problem.get_num_vars()): self.assertAlmostEqual(result.x[i], x[i]) @data( ("op_ip1.lp", [0, 2], 6), ("op_mip1.lp", [0, 1, 1], 5.5), ("op_lp1.lp", [0.25, 1.75], 5.8750), ) @unittest.skipIf(not _optionals.HAS_CPLEX, "CPLEX not available.") def test_cplex_optimizer_no_solution(self, config): """CPLEX Optimizer Test if no solution is found""" cplex_optimizer = CplexOptimizer(disp=False, cplex_parameters={"dettimelimit": 0}) # unpack configuration filename, _, _ = config # load optimization problem problem = QuadraticProgram() lp_file = self.get_resource_path(filename, "algorithms/resources") problem.read_from_lp_file(lp_file) # solve problem with cplex result = cplex_optimizer.solve(problem) np.testing.assert_array_almost_equal(result.x, np.zeros(problem.get_num_vars())) self.assertEqual(result.status, OptimizationResultStatus.FAILURE) self.assertEqual(result.raw_results, None) if __name__ == "__main__": unittest.main()
qiskit-optimization/test/algorithms/test_cplex_optimizer.py/0
{ "file_path": "qiskit-optimization/test/algorithms/test_cplex_optimizer.py", "repo_id": "qiskit-optimization", "token_count": 1181 }
162
\ This file has been generated by DOcplex \ ENCODING=ISO-8859-1 \Problem name: my problem Minimize obj: x - y + 10 z + [ x^2 - 2 y*z ]/2 + 1 Subject To lin_eq: x + 2 y = 1 lin_leq: x + 2 y <= 1 lin_geq: x + 2 y >= 1 quad_eq: [ x^2 - y*z + 2 z^2 ] + x + y = 1 quad_leq: [ x^2 - y*z + 2 z^2 ] + x + y <= 1 quad_geq: [ x^2 - y*z + 2 z^2 ] + x + y >= 1 Bounds 0 <= x <= 1 -1 <= y <= 5 -1 <= z <= 5 Binaries x Generals y End
qiskit-optimization/test/problems/resources/test_quadratic_program.lp/0
{ "file_path": "qiskit-optimization/test/problems/resources/test_quadratic_program.lp", "repo_id": "qiskit-optimization", "token_count": 213 }
163
# Code of Conduct All members of this project agree to adhere to the Qiskit Code of Conduct listed at [docs.quantum.ibm.com/open-source/code-of-conduct](https://docs.quantum.ibm.com/open-source/code-of-conduct)
qiskit/CODE_OF_CONDUCT.md/0
{ "file_path": "qiskit/CODE_OF_CONDUCT.md", "repo_id": "qiskit", "token_count": 68 }
164
# `qiskit-accelerate` This crate provides a bits-and-pieces Rust libary for small, self-contained functions that are used by the main Python-space components to accelerate certain tasks. If you're trying to speed up one particular Python function by replacing its innards with a Rust one, this is the best place to put the code. This is _usually_ the right place to put new Rust/Python code. The `qiskit-pyext` crate is what actually builds the C extension modules. Modules in here should define themselves has being submodules of `qiskit._accelerate`, and then the `qiskit-pyext` crate should bind them into its `fn _accelerate` when it's making the C extension.
qiskit/crates/accelerate/README.md/0
{ "file_path": "qiskit/crates/accelerate/README.md", "repo_id": "qiskit", "token_count": 177 }
165
// This code is part of Qiskit. // // (C) Copyright IBM 2022 // // 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. pub mod converters; pub mod marginalization; use pyo3::prelude::*; use pyo3::wrap_pyfunction; pub fn results(m: &Bound<PyModule>) -> PyResult<()> { m.add_wrapped(wrap_pyfunction!(marginalization::marginal_counts))?; m.add_wrapped(wrap_pyfunction!(marginalization::marginal_distribution))?; m.add_wrapped(wrap_pyfunction!(marginalization::marginal_memory))?; m.add_wrapped(wrap_pyfunction!(marginalization::marginal_measure_level_0))?; m.add_wrapped(wrap_pyfunction!( marginalization::marginal_measure_level_0_avg ))?; m.add_wrapped(wrap_pyfunction!(marginalization::marginal_measure_level_1))?; m.add_wrapped(wrap_pyfunction!( marginalization::marginal_measure_level_1_avg ))?; Ok(()) }
qiskit/crates/accelerate/src/results/mod.rs/0
{ "file_path": "qiskit/crates/accelerate/src/results/mod.rs", "repo_id": "qiskit", "token_count": 440 }
166
// This code is part of Qiskit. // // (C) Copyright IBM 2024 // // 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. use crate::synthesis::linear::utils::calc_inverse_matrix_inner; use ndarray::{azip, s, Array1, Array2, ArrayView2}; use qiskit_circuit::operations::{Param, StandardGate}; use qiskit_circuit::Qubit; use smallvec::{smallvec, SmallVec}; /// Symplectic matrix. /// Currently this class is internal to the synthesis library. pub struct SymplecticMatrix { /// Number of qubits. pub num_qubits: usize, /// Matrix with dimensions (2 * num_qubits) x (2 * num_qubits). pub smat: Array2<bool>, } /// Clifford. /// Currently this class is internal to the synthesis library and /// has a very different functionality from Qiskit's python-based /// Clifford class. #[derive(Clone)] pub struct Clifford { /// Number of qubits. pub num_qubits: usize, /// Matrix with dimensions (2 * num_qubits) x (2 * num_qubits + 1). pub tableau: Array2<bool>, } impl SymplecticMatrix { /// Modifies the matrix in-place by appending S-gate #[allow(dead_code)] pub fn append_s(&mut self, qubit: usize) { let (x, mut z) = self .smat .multi_slice_mut((s![.., qubit], s![.., self.num_qubits + qubit])); azip!((z in &mut z, &x in &x) *z ^= x); } /// Modifies the matrix in-place by prepending S-gate pub fn prepend_s(&mut self, qubit: usize) { let (x, mut z) = self .smat .multi_slice_mut((s![self.num_qubits + qubit, ..], s![qubit, ..])); azip!((z in &mut z, &x in &x) *z ^= x); } /// Modifies the matrix in-place by appending H-gate #[allow(dead_code)] pub fn append_h(&mut self, qubit: usize) { let (mut x, mut z) = self .smat .multi_slice_mut((s![.., qubit], s![.., self.num_qubits + qubit])); azip!((x in &mut x, z in &mut z) (*x, *z) = (*z, *x)); } /// Modifies the matrix in-place by prepending H-gate pub fn prepend_h(&mut self, qubit: usize) { let (mut x, mut z) = self .smat .multi_slice_mut((s![qubit, ..], s![self.num_qubits + qubit, ..])); azip!((x in &mut x, z in &mut z) (*x, *z) = (*z, *x)); } /// Modifies the matrix in-place by appending SWAP-gate #[allow(dead_code)] pub fn append_swap(&mut self, qubit0: usize, qubit1: usize) { let (mut x0, mut z0, mut x1, mut z1) = self.smat.multi_slice_mut(( s![.., qubit0], s![.., self.num_qubits + qubit0], s![.., qubit1], s![.., self.num_qubits + qubit1], )); azip!((x0 in &mut x0, x1 in &mut x1) (*x0, *x1) = (*x1, *x0)); azip!((z0 in &mut z0, z1 in &mut z1) (*z0, *z1) = (*z1, *z0)); } /// Modifies the matrix in-place by prepending SWAP-gate pub fn prepend_swap(&mut self, qubit0: usize, qubit1: usize) { let (mut x0, mut z0, mut x1, mut z1) = self.smat.multi_slice_mut(( s![qubit0, ..], s![self.num_qubits + qubit0, ..], s![qubit1, ..], s![self.num_qubits + qubit1, ..], )); azip!((x0 in &mut x0, x1 in &mut x1) (*x0, *x1) = (*x1, *x0)); azip!((z0 in &mut z0, z1 in &mut z1) (*z0, *z1) = (*z1, *z0)); } /// Modifies the matrix in-place by appending CX-gate #[allow(dead_code)] pub fn append_cx(&mut self, qubit0: usize, qubit1: usize) { let (x0, mut z0, mut x1, z1) = self.smat.multi_slice_mut(( s![.., qubit0], s![.., self.num_qubits + qubit0], s![.., qubit1], s![.., self.num_qubits + qubit1], )); azip!((x1 in &mut x1, &x0 in &x0) *x1 ^= x0); azip!((z0 in &mut z0, &z1 in &z1) *z0 ^= z1); } /// Modifies the matrix in-place by prepending CX-gate pub fn prepend_cx(&mut self, qubit0: usize, qubit1: usize) { let (x0, mut z0, mut x1, z1) = self.smat.multi_slice_mut(( s![qubit1, ..], s![self.num_qubits + qubit1, ..], s![qubit0, ..], s![self.num_qubits + qubit0, ..], )); azip!((x1 in &mut x1, &x0 in &x0) *x1 ^= x0); azip!((z0 in &mut z0, &z1 in &z1) *z0 ^= z1); } } impl Clifford { /// Modifies the tableau in-place by appending S-gate pub fn append_s(&mut self, qubit: usize) { let (x, mut z, mut p) = self.tableau.multi_slice_mut(( s![.., qubit], s![.., self.num_qubits + qubit], s![.., 2 * self.num_qubits], )); azip!((p in &mut p, &x in &x, &z in &z) *p ^= x & z); azip!((z in &mut z, &x in &x) *z ^= x); } /// Modifies the tableau in-place by appending Sdg-gate #[allow(dead_code)] pub fn append_sdg(&mut self, qubit: usize) { let (x, mut z, mut p) = self.tableau.multi_slice_mut(( s![.., qubit], s![.., self.num_qubits + qubit], s![.., 2 * self.num_qubits], )); azip!((p in &mut p, &x in &x, &z in &z) *p ^= x & !z); azip!((z in &mut z, &x in &x) *z ^= x); } /// Modifies the tableau in-place by appending H-gate pub fn append_h(&mut self, qubit: usize) { let (mut x, mut z, mut p) = self.tableau.multi_slice_mut(( s![.., qubit], s![.., self.num_qubits + qubit], s![.., 2 * self.num_qubits], )); azip!((p in &mut p, &x in &x, &z in &z) *p ^= x & z); azip!((x in &mut x, z in &mut z) (*x, *z) = (*z, *x)); } /// Modifies the tableau in-place by appending SWAP-gate pub fn append_swap(&mut self, qubit0: usize, qubit1: usize) { let (mut x0, mut z0, mut x1, mut z1) = self.tableau.multi_slice_mut(( s![.., qubit0], s![.., self.num_qubits + qubit0], s![.., qubit1], s![.., self.num_qubits + qubit1], )); azip!((x0 in &mut x0, x1 in &mut x1) (*x0, *x1) = (*x1, *x0)); azip!((z0 in &mut z0, z1 in &mut z1) (*z0, *z1) = (*z1, *z0)); } /// Modifies the tableau in-place by appending CX-gate pub fn append_cx(&mut self, qubit0: usize, qubit1: usize) { let (x0, mut z0, mut x1, z1, mut p) = self.tableau.multi_slice_mut(( s![.., qubit0], s![.., self.num_qubits + qubit0], s![.., qubit1], s![.., self.num_qubits + qubit1], s![.., 2 * self.num_qubits], )); azip!((p in &mut p, &x0 in &x0, &z0 in &z0, &x1 in &x1, &z1 in &z1) *p ^= (x1 ^ z0 ^ true) & z1 & x0); azip!((x1 in &mut x1, &x0 in &x0) *x1 ^= x0); azip!((z0 in &mut z0, &z1 in &z1) *z0 ^= z1); } /// Modifies the tableau in-place by appending W-gate. /// This is equivalent to an Sdg gate followed by an H gate. pub fn append_v(&mut self, qubit: usize) { let (mut x, mut z) = self .tableau .multi_slice_mut((s![.., qubit], s![.., self.num_qubits + qubit])); azip!((x in &mut x, z in &mut z) (*x, *z) = (*x ^ *z, *x)); } /// Modifies the tableau in-place by appending V-gate. /// This is equivalent to two V gates. pub fn append_w(&mut self, qubit: usize) { let (mut x, mut z) = self .tableau .multi_slice_mut((s![.., qubit], s![.., self.num_qubits + qubit])); azip!((x in &mut x, z in &mut z) (*x, *z) = (*z, *x ^ *z)); } /// Creates a Clifford from a given sequence of Clifford gates. /// In essence, starts from the identity tableau and modifies it /// based on the gates in the sequence. pub fn from_gate_sequence( gate_seq: &CliffordGatesVec, num_qubits: usize, ) -> Result<Clifford, String> { // create the identity let mut clifford = Clifford { num_qubits, tableau: Array2::from_shape_fn((2 * num_qubits, 2 * num_qubits + 1), |(i, j)| i == j), }; gate_seq .iter() .try_for_each(|(gate, _params, qubits)| match *gate { StandardGate::SGate => { clifford.append_s(qubits[0].0 as usize); Ok(()) } StandardGate::HGate => { clifford.append_h(qubits[0].0 as usize); Ok(()) } StandardGate::CXGate => { clifford.append_cx(qubits[0].0 as usize, qubits[1].0 as usize); Ok(()) } StandardGate::SwapGate => { clifford.append_swap(qubits[0].0 as usize, qubits[1].0 as usize); Ok(()) } _ => Err(format!("Unsupported gate {:?}", gate)), })?; Ok(clifford) } } /// A sequence of Clifford gates. /// Represents the return type of Clifford synthesis algorithms. pub type CliffordGatesVec = Vec<(StandardGate, SmallVec<[Param; 3]>, SmallVec<[Qubit; 2]>)>; /// Given a sequence of Clifford gates that correctly implements the symplectic matrix /// of the target clifford tableau, adds the Pauli gates to also match the phase of /// the tableau. pub fn adjust_final_pauli_gates( gate_seq: &mut CliffordGatesVec, target_tableau: ArrayView2<bool>, num_qubits: usize, ) -> Result<(), String> { // simulate the clifford circuit that we have constructed let simulated_clifford = Clifford::from_gate_sequence(gate_seq, num_qubits)?; // compute the phase difference let target_phase = target_tableau.column(2 * num_qubits); let sim_phase = simulated_clifford.tableau.column(2 * num_qubits); let delta_phase: Vec<bool> = target_phase .iter() .zip(sim_phase.iter()) .map(|(&a, &b)| a ^ b) .collect(); // compute inverse of the symplectic matrix let smat = target_tableau.slice(s![.., ..2 * num_qubits]); let smat_inv = calc_inverse_matrix_inner(smat, false)?; // compute smat_inv * delta_phase let arr1 = smat_inv.map(|v| *v as usize); let vec2: Vec<usize> = delta_phase.into_iter().map(|v| v as usize).collect(); let arr2 = Array1::from(vec2); let delta_phase_pre = arr1.dot(&arr2).map(|v| v % 2 == 1); // add pauli gates for qubit in 0..num_qubits { if delta_phase_pre[qubit] && delta_phase_pre[qubit + num_qubits] { // println!("=> Adding Y-gate on {}", qubit); gate_seq.push(( StandardGate::YGate, smallvec![], smallvec![Qubit(qubit as u32)], )); } else if delta_phase_pre[qubit] { // println!("=> Adding Z-gate on {}", qubit); gate_seq.push(( StandardGate::ZGate, smallvec![], smallvec![Qubit(qubit as u32)], )); } else if delta_phase_pre[qubit + num_qubits] { // println!("=> Adding X-gate on {}", qubit); gate_seq.push(( StandardGate::XGate, smallvec![], smallvec![Qubit(qubit as u32)], )); } } Ok(()) }
qiskit/crates/accelerate/src/synthesis/clifford/utils.rs/0
{ "file_path": "qiskit/crates/accelerate/src/synthesis/clifford/utils.rs", "repo_id": "qiskit", "token_count": 5756 }
167
// This code is part of Qiskit. // // (C) Copyright IBM 2024 // // 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. use pyo3::prelude::*; use faer_ext::IntoFaerComplex; use num_complex::Complex; use numpy::{IntoPyArray, PyReadonlyArray2}; /// Return indices that sort partially ordered data. /// If `data` contains two elements that are incomparable, /// an error will be thrown. pub fn arg_sort<T: PartialOrd>(data: &[T]) -> Vec<usize> { let mut indices = (0..data.len()).collect::<Vec<_>>(); indices.sort_by(|&a, &b| data[a].partial_cmp(&data[b]).unwrap()); indices } /// Return the eigenvalues of `unitary` as a one-dimensional `numpy.ndarray` /// with `dtype(complex128)`. #[pyfunction] #[pyo3(text_signature = "(unitary, /")] pub fn eigenvalues(py: Python, unitary: PyReadonlyArray2<Complex<f64>>) -> PyObject { unitary .as_array() .into_faer_complex() .complex_eigenvalues() .into_iter() .map(|x| Complex::<f64>::new(x.re, x.im)) .collect::<Vec<_>>() .into_pyarray_bound(py) .into() } pub fn utils(m: &Bound<PyModule>) -> PyResult<()> { m.add_wrapped(wrap_pyfunction!(eigenvalues))?; Ok(()) }
qiskit/crates/accelerate/src/utils.rs/0
{ "file_path": "qiskit/crates/accelerate/src/utils.rs", "repo_id": "qiskit", "token_count": 592 }
168
// This code is part of Qiskit. // // (C) Copyright IBM 2024 // // 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. #[cfg(feature = "cache_pygates")] use std::cell::OnceCell; use std::ptr::NonNull; use pyo3::intern; use pyo3::prelude::*; use pyo3::types::{PyDict, PyType}; use ndarray::Array2; use num_complex::Complex64; use smallvec::SmallVec; use crate::circuit_data::CircuitData; use crate::circuit_instruction::ExtraInstructionAttributes; use crate::imports::{get_std_gate_class, DEEPCOPY}; use crate::interner::Interned; use crate::operations::{ Operation, OperationRef, Param, PyGate, PyInstruction, PyOperation, StandardGate, }; use crate::{Clbit, Qubit}; /// The logical discriminant of `PackedOperation`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u8)] enum PackedOperationType { // It's important that the `StandardGate` item is 0, so that zeroing out a `PackedOperation` // will make it appear as a standard gate, which will never allow accidental dangling-pointer // dereferencing. StandardGate = 0, Gate = 1, Instruction = 2, Operation = 3, } unsafe impl ::bytemuck::CheckedBitPattern for PackedOperationType { type Bits = u8; fn is_valid_bit_pattern(bits: &Self::Bits) -> bool { *bits < 4 } } unsafe impl ::bytemuck::NoUninit for PackedOperationType {} /// A bit-packed `OperationType` enumeration. /// /// This is logically equivalent to: /// /// ```rust /// enum Operation { /// Standard(StandardGate), /// Gate(Box<PyGate>), /// Instruction(Box<PyInstruction>), /// Operation(Box<PyOperation>), /// } /// ``` /// /// including all ownership semantics, except it bit-packs the enumeration into a single pointer. /// This works because `PyGate` (and friends) have an alignment of 8, so pointers to them always /// have the low three bits set to 0, and `StandardGate` has a width much smaller than a pointer. /// This lets us store the enum discriminant in the low data bits, and then type-pun a suitable /// bitmask on the contained value back into proper data. /// /// Explicitly, this is logical memory layout of `PackedOperation` on a 64-bit system, written out /// as a binary integer. `x` marks padding bits with undefined values, `S` is the bits that make up /// a `StandardGate`, and `P` is bits that make up part of a pointer. /// /// ```text /// Standard gate: /// 0b_xxxxxxxx_xxxxxxxx_xxxxxxxx_xxxxxxxx_xxxxxxxx_xxxxxxxx_xxxxxxSS_SSSSSS00 /// |-------||| /// | | /// Standard gate, stored inline as a u8. --+ +-- Discriminant. /// /// Python object: /// 0b_PPPPPPPP_PPPPPPPP_PPPPPPPP_PPPPPPPP_PPPPPPPP_PPPPPPPP_PPPPPPPP_PPPPP10 /// |------------------------------------------------------------------||| /// | | /// The high 62 bits of the pointer. Because of alignment, the low 3 | Discriminant of the /// bits of the full 64 bits are guaranteed to be zero (so one marked +-- enumeration. This /// `P` is always zero here), so we can retrieve the "full" pointer by is 0b10, which means /// taking the whole `usize` and zeroing the low 3 bits, letting us that this points to /// store the discriminant in there at other times. a `PyInstruction`. /// ``` /// /// There is currently one spare bit that could be used for additional metadata, if required. /// /// # Construction /// /// From Rust space, build this type using one of the `from_*` methods, depending on which /// implementer of `Operation` you have. `StandardGate` has an implementation of `Into` for this. /// /// From Python space, use the supplied `FromPyObject`. /// /// # Safety /// /// `PackedOperation` asserts ownership over its contained pointer (if not a `StandardGate`). This /// has the following requirements: /// /// * The pointer must be managed by a `Box` using the global allocator. /// * The pointed-to data must match the type of the discriminant used to store it. /// * `PackedOperation` must take care to forward implementations of `Clone` and `Drop` to the /// contained pointer. #[derive(Debug)] #[repr(transparent)] pub struct PackedOperation(usize); impl PackedOperation { /// The bits representing the `PackedOperationType` discriminant. This can be used to mask out /// the discriminant, and defines the rest of the bit shifting. const DISCRIMINANT_MASK: usize = 0b11; /// The number of bits used to store the discriminant metadata. const DISCRIMINANT_BITS: u32 = Self::DISCRIMINANT_MASK.count_ones(); /// A bitmask that masks out only the standard gate information. This should always have the /// same effect as `POINTER_MASK` because the high bits should be 0 for a `StandardGate`, but /// this is defensive against us adding further metadata on `StandardGate` later. After /// masking, the resulting integer still needs shifting downwards to retrieve the standard gate. const STANDARD_GATE_MASK: usize = (u8::MAX as usize) << Self::DISCRIMINANT_BITS; /// A bitmask that retrieves the stored pointer directly. The discriminant is stored in the /// low pointer bits that are guaranteed to be 0 by alignment, so no shifting is required. const POINTER_MASK: usize = usize::MAX ^ Self::DISCRIMINANT_MASK; /// Extract the discriminant of the operation. #[inline] fn discriminant(&self) -> PackedOperationType { ::bytemuck::checked::cast((self.0 & Self::DISCRIMINANT_MASK) as u8) } /// Get the contained pointer to the `PyGate`/`PyInstruction`/`PyOperation` that this object /// contains. /// /// **Panics** if the object represents a standard gate; see `try_pointer`. #[inline] fn pointer(&self) -> NonNull<()> { self.try_pointer() .expect("the caller is responsible for knowing the correct type") } /// Get the contained pointer to the `PyGate`/`PyInstruction`/`PyOperation` that this object /// contains. /// /// Returns `None` if the object represents a standard gate. #[inline] pub fn try_pointer(&self) -> Option<NonNull<()>> { match self.discriminant() { PackedOperationType::StandardGate => None, PackedOperationType::Gate | PackedOperationType::Instruction | PackedOperationType::Operation => { let ptr = (self.0 & Self::POINTER_MASK) as *mut (); // SAFETY: `PackedOperation` can only be constructed from a pointer via `Box`, which // is always non-null (except in the case that we're partway through a `Drop`). Some(unsafe { NonNull::new_unchecked(ptr) }) } } } /// Get the contained `StandardGate`. /// /// **Panics** if this `PackedOperation` doesn't contain a `StandardGate`; see /// `try_standard_gate`. #[inline] pub fn standard_gate(&self) -> StandardGate { self.try_standard_gate() .expect("the caller is responsible for knowing the correct type") } /// Get the contained `StandardGate`, if any. #[inline] pub fn try_standard_gate(&self) -> Option<StandardGate> { match self.discriminant() { PackedOperationType::StandardGate => ::bytemuck::checked::try_cast( ((self.0 & Self::STANDARD_GATE_MASK) >> Self::DISCRIMINANT_BITS) as u8, ) .ok(), _ => None, } } /// Get a safe view onto the packed data within, without assuming ownership. #[inline] pub fn view(&self) -> OperationRef { match self.discriminant() { PackedOperationType::StandardGate => OperationRef::Standard(self.standard_gate()), PackedOperationType::Gate => { let ptr = self.pointer().cast::<PyGate>(); OperationRef::Gate(unsafe { ptr.as_ref() }) } PackedOperationType::Instruction => { let ptr = self.pointer().cast::<PyInstruction>(); OperationRef::Instruction(unsafe { ptr.as_ref() }) } PackedOperationType::Operation => { let ptr = self.pointer().cast::<PyOperation>(); OperationRef::Operation(unsafe { ptr.as_ref() }) } } } /// Create a `PackedOperation` from a `StandardGate`. #[inline] pub fn from_standard(standard: StandardGate) -> Self { Self((standard as usize) << Self::DISCRIMINANT_BITS) } /// Create a `PackedOperation` given a raw pointer to the inner type. /// /// **Panics** if the given `discriminant` does not correspond to a pointer type. /// /// SAFETY: the inner pointer must have come from an owning `Box` in the global allocator, whose /// type matches that indicated by the discriminant. The returned `PackedOperation` takes /// ownership of the pointed-to data. #[inline] unsafe fn from_py_wrapper(discriminant: PackedOperationType, value: NonNull<()>) -> Self { if discriminant == PackedOperationType::StandardGate { panic!("given standard-gate discriminant during pointer-type construction") } let addr = value.as_ptr() as usize; assert_eq!(addr & Self::DISCRIMINANT_MASK, 0); Self(addr | (discriminant as usize)) } /// Construct a new `PackedOperation` from an owned heap-allocated `PyGate`. pub fn from_gate(gate: Box<PyGate>) -> Self { let ptr = NonNull::from(Box::leak(gate)).cast::<()>(); // SAFETY: the `ptr` comes directly from a owning `Box` of the correct type. unsafe { Self::from_py_wrapper(PackedOperationType::Gate, ptr) } } /// Construct a new `PackedOperation` from an owned heap-allocated `PyInstruction`. pub fn from_instruction(instruction: Box<PyInstruction>) -> Self { let ptr = NonNull::from(Box::leak(instruction)).cast::<()>(); // SAFETY: the `ptr` comes directly from a owning `Box` of the correct type. unsafe { Self::from_py_wrapper(PackedOperationType::Instruction, ptr) } } /// Construct a new `PackedOperation` from an owned heap-allocated `PyOperation`. pub fn from_operation(operation: Box<PyOperation>) -> Self { let ptr = NonNull::from(Box::leak(operation)).cast::<()>(); // SAFETY: the `ptr` comes directly from a owning `Box` of the correct type. unsafe { Self::from_py_wrapper(PackedOperationType::Operation, ptr) } } /// Check equality of the operation, including Python-space checks, if appropriate. pub fn py_eq(&self, py: Python, other: &PackedOperation) -> PyResult<bool> { match (self.view(), other.view()) { (OperationRef::Standard(left), OperationRef::Standard(right)) => Ok(left == right), (OperationRef::Gate(left), OperationRef::Gate(right)) => { left.gate.bind(py).eq(&right.gate) } (OperationRef::Instruction(left), OperationRef::Instruction(right)) => { left.instruction.bind(py).eq(&right.instruction) } (OperationRef::Operation(left), OperationRef::Operation(right)) => { left.operation.bind(py).eq(&right.operation) } _ => Ok(false), } } /// Copy this operation, including a Python-space deep copy, if required. pub fn py_deepcopy<'py>( &self, py: Python<'py>, memo: Option<&Bound<'py, PyDict>>, ) -> PyResult<Self> { let deepcopy = DEEPCOPY.get_bound(py); match self.view() { OperationRef::Standard(standard) => Ok(standard.into()), OperationRef::Gate(gate) => Ok(PyGate { gate: deepcopy.call1((&gate.gate, memo))?.unbind(), qubits: gate.qubits, clbits: gate.clbits, params: gate.params, op_name: gate.op_name.clone(), } .into()), OperationRef::Instruction(instruction) => Ok(PyInstruction { instruction: deepcopy.call1((&instruction.instruction, memo))?.unbind(), qubits: instruction.qubits, clbits: instruction.clbits, params: instruction.params, control_flow: instruction.control_flow, op_name: instruction.op_name.clone(), } .into()), OperationRef::Operation(operation) => Ok(PyOperation { operation: deepcopy.call1((&operation.operation, memo))?.unbind(), qubits: operation.qubits, clbits: operation.clbits, params: operation.params, op_name: operation.op_name.clone(), } .into()), } } /// Copy this operation, including a Python-space call to `copy` on the `Operation` subclass, if /// any. pub fn py_copy(&self, py: Python) -> PyResult<Self> { let copy_attr = intern!(py, "copy"); match self.view() { OperationRef::Standard(standard) => Ok(standard.into()), OperationRef::Gate(gate) => Ok(Box::new(PyGate { gate: gate.gate.call_method0(py, copy_attr)?, qubits: gate.qubits, clbits: gate.clbits, params: gate.params, op_name: gate.op_name.clone(), }) .into()), OperationRef::Instruction(instruction) => Ok(Box::new(PyInstruction { instruction: instruction.instruction.call_method0(py, copy_attr)?, qubits: instruction.qubits, clbits: instruction.clbits, params: instruction.params, control_flow: instruction.control_flow, op_name: instruction.op_name.clone(), }) .into()), OperationRef::Operation(operation) => Ok(Box::new(PyOperation { operation: operation.operation.call_method0(py, copy_attr)?, qubits: operation.qubits, clbits: operation.clbits, params: operation.params, op_name: operation.op_name.clone(), }) .into()), } } /// Whether the Python class that we would use to represent the inner `Operation` object in /// Python space would be an instance of the given Python type. This does not construct the /// Python-space `Operator` instance if it can be avoided (i.e. for standard gates). pub fn py_op_is_instance(&self, py_type: &Bound<PyType>) -> PyResult<bool> { let py = py_type.py(); let py_op = match self.view() { OperationRef::Standard(standard) => { return get_std_gate_class(py, standard)? .bind(py) .downcast::<PyType>()? .is_subclass(py_type) } OperationRef::Gate(gate) => gate.gate.bind(py), OperationRef::Instruction(instruction) => instruction.instruction.bind(py), OperationRef::Operation(operation) => operation.operation.bind(py), }; py_op.is_instance(py_type) } } impl Operation for PackedOperation { fn name(&self) -> &str { let view = self.view(); let name = match view { OperationRef::Standard(ref standard) => standard.name(), OperationRef::Gate(gate) => gate.name(), OperationRef::Instruction(instruction) => instruction.name(), OperationRef::Operation(operation) => operation.name(), }; // SAFETY: all of the inner parts of the view are owned by `self`, so it's valid for us to // forcibly reborrowing up to our own lifetime. We avoid using `<OperationRef as Operation>` // just to avoid a further _potential_ unsafeness, were its implementation to start doing // something weird with the lifetimes. `str::from_utf8_unchecked` and // `slice::from_raw_parts` are both trivially safe because they're being called on immediate // values from a validated `str`. unsafe { ::std::str::from_utf8_unchecked(::std::slice::from_raw_parts(name.as_ptr(), name.len())) } } #[inline] fn num_qubits(&self) -> u32 { self.view().num_qubits() } #[inline] fn num_clbits(&self) -> u32 { self.view().num_clbits() } #[inline] fn num_params(&self) -> u32 { self.view().num_params() } #[inline] fn control_flow(&self) -> bool { self.view().control_flow() } #[inline] fn matrix(&self, params: &[Param]) -> Option<Array2<Complex64>> { self.view().matrix(params) } #[inline] fn definition(&self, params: &[Param]) -> Option<CircuitData> { self.view().definition(params) } #[inline] fn standard_gate(&self) -> Option<StandardGate> { self.view().standard_gate() } #[inline] fn directive(&self) -> bool { self.view().directive() } } impl From<StandardGate> for PackedOperation { #[inline] fn from(value: StandardGate) -> Self { Self::from_standard(value) } } macro_rules! impl_packed_operation_from_py { ($type:ty, $constructor:path) => { impl From<$type> for PackedOperation { #[inline] fn from(value: $type) -> Self { $constructor(Box::new(value)) } } impl From<Box<$type>> for PackedOperation { #[inline] fn from(value: Box<$type>) -> Self { $constructor(value) } } }; } impl_packed_operation_from_py!(PyGate, PackedOperation::from_gate); impl_packed_operation_from_py!(PyInstruction, PackedOperation::from_instruction); impl_packed_operation_from_py!(PyOperation, PackedOperation::from_operation); impl Clone for PackedOperation { fn clone(&self) -> Self { match self.view() { OperationRef::Standard(standard) => Self::from_standard(standard), OperationRef::Gate(gate) => Self::from_gate(Box::new(gate.to_owned())), OperationRef::Instruction(instruction) => { Self::from_instruction(Box::new(instruction.to_owned())) } OperationRef::Operation(operation) => { Self::from_operation(Box::new(operation.to_owned())) } } } } impl Drop for PackedOperation { fn drop(&mut self) { fn drop_pointer_as<T>(slf: &mut PackedOperation) { // This should only ever be called when the pointer is valid, but this is defensive just // to 100% ensure that our `Drop` implementation doesn't panic. let Some(pointer) = slf.try_pointer() else { return; }; // SAFETY: `PackedOperation` asserts ownership over its contents, and the contained // pointer can only be null if we were already dropped. We set our discriminant to mark // ourselves as plain old data immediately just as a defensive measure. let boxed = unsafe { Box::from_raw(pointer.cast::<T>().as_ptr()) }; slf.0 = PackedOperationType::StandardGate as usize; ::std::mem::drop(boxed); } match self.discriminant() { PackedOperationType::StandardGate => (), PackedOperationType::Gate => drop_pointer_as::<PyGate>(self), PackedOperationType::Instruction => drop_pointer_as::<PyInstruction>(self), PackedOperationType::Operation => drop_pointer_as::<PyOperation>(self), } } } /// The data-at-rest compressed storage format for a circuit instruction. /// /// Much of the actual data of a `PackedInstruction` is stored in the `CircuitData` (or /// DAG-equivalent) context objects, and the `PackedInstruction` itself just contains handles to /// that data. Components of the `PackedInstruction` can be unpacked individually by passing the /// `CircuitData` object to the relevant getter method. Many `PackedInstruction`s may contain /// handles to the same data within a `CircuitData` objects; we are re-using what we can. /// /// A `PackedInstruction` in general cannot be safely mutated outside the context of its /// `CircuitData`, because the majority of the data is not actually stored here. #[derive(Clone, Debug)] pub struct PackedInstruction { pub op: PackedOperation, /// The index under which the interner has stored `qubits`. pub qubits: Interned<[Qubit]>, /// The index under which the interner has stored `clbits`. pub clbits: Interned<[Clbit]>, pub params: Option<Box<SmallVec<[Param; 3]>>>, pub extra_attrs: Option<Box<ExtraInstructionAttributes>>, #[cfg(feature = "cache_pygates")] /// This is hidden in a `OnceCell` because it's just an on-demand cache; we don't create this /// unless asked for it. A `OnceCell` of a non-null pointer type (like `Py<T>`) is the same /// size as a pointer and there are no runtime checks on access beyond the initialisation check, /// which is a simple null-pointer check. /// /// WARNING: remember that `OnceCell`'s `get_or_init` method is no-reentrant, so the initialiser /// must not yield the GIL to Python space. We avoid using `GILOnceCell` here because it /// requires the GIL to even `get` (of course!), which makes implementing `Clone` hard for us. /// We can revisit once we're on PyO3 0.22+ and have been able to disable its `py-clone` /// feature. pub py_op: OnceCell<Py<PyAny>>, } impl PackedInstruction { /// Access the standard gate in this `PackedInstruction`, if it is one. If the instruction /// refers to a Python-space object, `None` is returned. #[inline] pub fn standard_gate(&self) -> Option<StandardGate> { self.op.try_standard_gate() } /// Get a slice view onto the contained parameters. #[inline] pub fn params_view(&self) -> &[Param] { self.params .as_deref() .map(SmallVec::as_slice) .unwrap_or(&[]) } /// Get a mutable slice view onto the contained parameters. #[inline] pub fn params_mut(&mut self) -> &mut [Param] { self.params .as_deref_mut() .map(SmallVec::as_mut_slice) .unwrap_or(&mut []) } /// Does this instruction contain any compile-time symbolic `ParameterExpression`s? pub fn is_parameterized(&self) -> bool { self.params_view() .iter() .any(|x| matches!(x, Param::ParameterExpression(_))) } #[inline] pub fn condition(&self) -> Option<&Py<PyAny>> { self.extra_attrs .as_ref() .and_then(|extra| extra.condition.as_ref()) } /// Build a reference to the Python-space operation object (the `Gate`, etc) packed into this /// instruction. This may construct the reference if the `PackedInstruction` is a standard /// gate with no already stored operation. /// /// A standard-gate operation object returned by this function is disconnected from the /// containing circuit; updates to its parameters, label, duration, unit and condition will not /// be propagated back. pub fn unpack_py_op(&self, py: Python) -> PyResult<Py<PyAny>> { let unpack = || -> PyResult<Py<PyAny>> { match self.op.view() { OperationRef::Standard(standard) => standard.create_py_op( py, self.params.as_deref().map(SmallVec::as_slice), self.extra_attrs.as_deref(), ), OperationRef::Gate(gate) => Ok(gate.gate.clone_ref(py)), OperationRef::Instruction(instruction) => Ok(instruction.instruction.clone_ref(py)), OperationRef::Operation(operation) => Ok(operation.operation.clone_ref(py)), } }; // `OnceCell::get_or_init` and the non-stabilised `get_or_try_init`, which would otherwise // be nice here are both non-reentrant. This is a problem if the init yields control to the // Python interpreter as this one does, since that can allow CPython to freeze the thread // and for another to attempt the initialisation. #[cfg(feature = "cache_pygates")] { if let Some(ob) = self.py_op.get() { return Ok(ob.clone_ref(py)); } } let out = unpack()?; #[cfg(feature = "cache_pygates")] { // The unpacking operation can cause a thread pause and concurrency, since it can call // interpreted Python code for a standard gate, so we need to take care that some other // Python thread might have populated the cache before we do. let _ = self.py_op.set(out.clone_ref(py)); } Ok(out) } /// Check equality of the operation, including Python-space checks, if appropriate. pub fn py_op_eq(&self, py: Python, other: &Self) -> PyResult<bool> { match (self.op.view(), other.op.view()) { (OperationRef::Standard(left), OperationRef::Standard(right)) => Ok(left == right), (OperationRef::Gate(left), OperationRef::Gate(right)) => { left.gate.bind(py).eq(&right.gate) } (OperationRef::Instruction(left), OperationRef::Instruction(right)) => { left.instruction.bind(py).eq(&right.instruction) } (OperationRef::Operation(left), OperationRef::Operation(right)) => { left.operation.bind(py).eq(&right.operation) } // Handle the case we end up with a pygate for a standard gate // this typically only happens if it's a ControlledGate in python // and we have mutable state set. (OperationRef::Standard(_left), OperationRef::Gate(right)) => { self.unpack_py_op(py)?.bind(py).eq(&right.gate) } (OperationRef::Gate(left), OperationRef::Standard(_right)) => { other.unpack_py_op(py)?.bind(py).eq(&left.gate) } _ => Ok(false), } } }
qiskit/crates/circuit/src/packed_instruction.rs/0
{ "file_path": "qiskit/crates/circuit/src/packed_instruction.rs", "repo_id": "qiskit", "token_count": 10795 }
169
[package] name = "qiskit-qasm3" version.workspace = true edition.workspace = true rust-version.workspace = true license.workspace = true [lib] name = "qiskit_qasm3" doctest = false [dependencies] pyo3.workspace = true indexmap.workspace = true hashbrown.workspace = true oq3_semantics = "0.6.0" ahash.workspace = true
qiskit/crates/qasm3/Cargo.toml/0
{ "file_path": "qiskit/crates/qasm3/Cargo.toml", "repo_id": "qiskit", "token_count": 123 }
170
.. _qiskit-compiler: .. automodule:: qiskit.compiler :no-members: :no-inherited-members: :no-special-members:
qiskit/docs/apidoc/compiler.rst/0
{ "file_path": "qiskit/docs/apidoc/compiler.rst", "repo_id": "qiskit", "token_count": 53 }
171
.. _qiskit-qobj: .. automodule:: qiskit.qobj :no-members: :no-inherited-members: :no-special-members:
qiskit/docs/apidoc/qobj.rst/0
{ "file_path": "qiskit/docs/apidoc/qobj.rst", "repo_id": "qiskit", "token_count": 53 }
172
[build-system] requires = ["setuptools", "wheel", "setuptools-rust"] build-backend = "setuptools.build_meta" [project] name = "qiskit" description = "An open-source SDK for working with quantum computers at the level of extended quantum circuits, operators, and primitives." requires-python = ">=3.8" license = {text = "Apache 2.0"} authors = [ { name = "Qiskit Development Team", email = "[email protected]" }, ] keywords = [ "qiskit", "quantum circuit", "quantum computing", "quantum programming language", "quantum", "sdk", ] classifiers = [ "Environment :: Console", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "License :: OSI Approved :: Apache Software License", "Operating System :: MacOS", "Operating System :: Microsoft :: Windows", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Topic :: Scientific/Engineering", ] # These are configured in the `tool.setuptools.dynamic` table. dynamic = ["version", "readme", "dependencies"] # If modifying this table, be sure to sync with `requirements-optional.txt` and # `qiskit.utils.optionals`. [project.optional-dependencies] qasm3-import = [ "qiskit-qasm3-import >= 0.1.0", ] visualization = [ "matplotlib >= 3.3", "pydot", "Pillow >= 4.2.1", "pylatexenc >= 1.4", "seaborn >= 0.9.0", ] crosstalk-pass = [ "z3-solver >= 4.7", ] csp-layout-pass = [ "python-constraint >= 1.4", ] # This will make the resolution work for installers from PyPI, but `pip install .[all]` will be # unreliable because `qiskit` will resolve to the PyPI version, so local changes in the # optionals won't be reflected. all = ["qiskit[qasm3-import,visualization,crosstalk-pass,csp-layout-pass]"] [project.urls] Homepage = "https://www.ibm.com/quantum/qiskit" Documentation = "https://docs.quantum.ibm.com" "API Reference" = "https://docs.quantum.ibm.com/api/qiskit" Repository = "https://github.com/Qiskit/qiskit" Issues = "https://github.com/Qiskit/qiskit/issues" Changelog = "https://docs.quantum.ibm.com/api/qiskit/release-notes" [project.entry-points."qiskit.unitary_synthesis"] default = "qiskit.transpiler.passes.synthesis.unitary_synthesis:DefaultUnitarySynthesis" aqc = "qiskit.transpiler.passes.synthesis.aqc_plugin:AQCSynthesisPlugin" sk = "qiskit.transpiler.passes.synthesis.solovay_kitaev_synthesis:SolovayKitaevSynthesis" [project.entry-points."qiskit.synthesis"] "clifford.default" = "qiskit.transpiler.passes.synthesis.hls_plugins:DefaultSynthesisClifford" "clifford.ag" = "qiskit.transpiler.passes.synthesis.hls_plugins:AGSynthesisClifford" "clifford.bm" = "qiskit.transpiler.passes.synthesis.hls_plugins:BMSynthesisClifford" "clifford.greedy" = "qiskit.transpiler.passes.synthesis.hls_plugins:GreedySynthesisClifford" "clifford.layers" = "qiskit.transpiler.passes.synthesis.hls_plugins:LayerSynthesisClifford" "clifford.lnn" = "qiskit.transpiler.passes.synthesis.hls_plugins:LayerLnnSynthesisClifford" "linear_function.default" = "qiskit.transpiler.passes.synthesis.hls_plugins:DefaultSynthesisLinearFunction" "linear_function.kms" = "qiskit.transpiler.passes.synthesis.hls_plugins:KMSSynthesisLinearFunction" "linear_function.pmh" = "qiskit.transpiler.passes.synthesis.hls_plugins:PMHSynthesisLinearFunction" "mcx.n_dirty_i15" = "qiskit.transpiler.passes.synthesis.hls_plugins:MCXSynthesisNDirtyI15" "mcx.n_clean_m15" = "qiskit.transpiler.passes.synthesis.hls_plugins:MCXSynthesisNCleanM15" "mcx.1_clean_b95" = "qiskit.transpiler.passes.synthesis.hls_plugins:MCXSynthesis1CleanB95" "mcx.gray_code" = "qiskit.transpiler.passes.synthesis.hls_plugins:MCXSynthesisGrayCode" "mcx.noaux_v24" = "qiskit.transpiler.passes.synthesis.hls_plugins:MCXSynthesisNoAuxV24" "mcx.default" = "qiskit.transpiler.passes.synthesis.hls_plugins:MCXSynthesisDefault" "permutation.default" = "qiskit.transpiler.passes.synthesis.hls_plugins:BasicSynthesisPermutation" "permutation.kms" = "qiskit.transpiler.passes.synthesis.hls_plugins:KMSSynthesisPermutation" "permutation.basic" = "qiskit.transpiler.passes.synthesis.hls_plugins:BasicSynthesisPermutation" "permutation.acg" = "qiskit.transpiler.passes.synthesis.hls_plugins:ACGSynthesisPermutation" "qft.full" = "qiskit.transpiler.passes.synthesis.hls_plugins:QFTSynthesisFull" "qft.line" = "qiskit.transpiler.passes.synthesis.hls_plugins:QFTSynthesisLine" "qft.default" = "qiskit.transpiler.passes.synthesis.hls_plugins:QFTSynthesisFull" "permutation.token_swapper" = "qiskit.transpiler.passes.synthesis.hls_plugins:TokenSwapperSynthesisPermutation" [project.entry-points."qiskit.transpiler.init"] default = "qiskit.transpiler.preset_passmanagers.builtin_plugins:DefaultInitPassManager" [project.entry-points."qiskit.transpiler.translation"] synthesis = "qiskit.transpiler.preset_passmanagers.builtin_plugins:UnitarySynthesisPassManager" translator = "qiskit.transpiler.preset_passmanagers.builtin_plugins:BasisTranslatorPassManager" [project.entry-points."qiskit.transpiler.routing"] basic = "qiskit.transpiler.preset_passmanagers.builtin_plugins:BasicSwapPassManager" lookahead = "qiskit.transpiler.preset_passmanagers.builtin_plugins:LookaheadSwapPassManager" none = "qiskit.transpiler.preset_passmanagers.builtin_plugins:NoneRoutingPassManager" sabre = "qiskit.transpiler.preset_passmanagers.builtin_plugins:SabreSwapPassManager" stochastic = "qiskit.transpiler.preset_passmanagers.builtin_plugins:StochasticSwapPassManager" [project.entry-points."qiskit.transpiler.optimization"] default = "qiskit.transpiler.preset_passmanagers.builtin_plugins:OptimizationPassManager" [project.entry-points."qiskit.transpiler.layout"] default = "qiskit.transpiler.preset_passmanagers.builtin_plugins:DefaultLayoutPassManager" dense = "qiskit.transpiler.preset_passmanagers.builtin_plugins:DenseLayoutPassManager" sabre = "qiskit.transpiler.preset_passmanagers.builtin_plugins:SabreLayoutPassManager" trivial = "qiskit.transpiler.preset_passmanagers.builtin_plugins:TrivialLayoutPassManager" [project.entry-points."qiskit.transpiler.scheduling"] alap = "qiskit.transpiler.preset_passmanagers.builtin_plugins:AlapSchedulingPassManager" asap = "qiskit.transpiler.preset_passmanagers.builtin_plugins:AsapSchedulingPassManager" default = "qiskit.transpiler.preset_passmanagers.builtin_plugins:DefaultSchedulingPassManager" [tool.setuptools] include-package-data = true [tool.setuptools.dynamic] version = { file = "qiskit/VERSION.txt" } readme = { file = "README.md", content-type = "text/markdown" } dependencies = {file = "requirements.txt" } [tool.setuptools.packages.find] include = ["qiskit", "qiskit.*"] [tool.black] line-length = 100 target-version = ['py38', 'py39', 'py310', 'py311'] [tool.cibuildwheel] manylinux-x86_64-image = "manylinux2014" manylinux-i686-image = "manylinux2014" skip = "pp* cp36-* cp37-* *musllinux* *win32 *i686 cp38-macosx_arm64" test-skip = "*win32 *linux_i686" test-command = "python {project}/examples/python/stochastic_swap.py" # We need to use pre-built versions of Numpy and Scipy in the tests; they have a # tendency to crash if they're installed from source by `pip install`, and since # Numpy 1.22 there are no i686 wheels, so we force pip to use older ones without # restricting any dependencies that Numpy and Scipy might have. before-test = "pip install --only-binary=numpy,scipy numpy scipy" # Some jobs locally override the before-build and environment configuration if a # specific job override is needed. For example tier 1 platforms locally override # the before-build and environment configuration to enable PGO, # see: .github/workflows/wheels.yml for the jobs where this is done environment = 'RUSTUP_TOOLCHAIN="stable"' [tool.cibuildwheel.linux] before-all = "yum install -y wget && {package}/tools/install_rust.sh" environment = 'PATH="$PATH:$HOME/.cargo/bin" CARGO_NET_GIT_FETCH_WITH_CLI="true" RUSTUP_TOOLCHAIN="stable"' repair-wheel-command = "auditwheel repair -w {dest_dir} {wheel} && pipx run abi3audit --strict --report {wheel}" [tool.cibuildwheel.macos] environment = "MACOSX_DEPLOYMENT_TARGET=10.12" repair-wheel-command = "delocate-wheel --require-archs {delocate_archs} -w {dest_dir} -v {wheel} && pipx run abi3audit --strict --report {wheel}" [tool.cibuildwheel.windows] repair-wheel-command = "cp {wheel} {dest_dir}/. && pipx run abi3audit --strict --report {wheel}" [tool.ruff] select = [ # Rules in alphabetic order "C4", # category: flake8-comprehensions "EXE", # Category: flake8-executable "F631", # assert-tuple "F632", # is-literal "F634", # if-tuple "F823", # undefined-local "G", # flake8-logging-format "T10", # category: flake8-debugger ] [tool.pylint.main] extension-pkg-allow-list = [ "numpy", "qiskit._accelerate", "qiskit._qasm2", "qiskit._qasm3", # We can't allow pylint to load qiskit._qasm2 because it's not able to # statically resolve the cyclical load of the exception and it bugs out. "retworkx", "rustworkx", "tweedledum", ] load-plugins = ["pylint.extensions.docparams", "pylint.extensions.docstyle"] py-version = "3.8" # update it when bumping minimum supported python version [tool.pylint.basic] good-names = ["a", "b", "i", "j", "k", "d", "n", "m", "ex", "v", "w", "x", "y", "z", "Run", "_", "logger", "q", "c", "r", "qr", "cr", "qc", "nd", "pi", "op", "b", "ar", "br", "p", "cp", "ax", "dt", "__unittest", "iSwapGate", "mu"] method-rgx = "(([a-z_][a-z0-9_]{2,49})|(assert[A-Z][a-zA-Z0-9]{2,43})|(test_[_a-zA-Z0-9]{2,}))$" variable-rgx = "[a-z_][a-z0-9_]{1,30}$" [tool.pylint.format] max-line-length = 105 # default 100 [tool.pylint."messages control"] disable = [ # intentionally disabled: "spelling", # too noisy "fixme", # disabled as TODOs would show up as warnings "protected-access", # disabled as we don't follow the public vs private convention strictly "duplicate-code", # disabled as it is too verbose "redundant-returns-doc", # for @abstractmethod, it cannot interpret "pass" "too-many-lines", "too-many-branches", "too-many-locals", "too-many-nested-blocks", "too-many-statements", "too-many-instance-attributes", "too-many-arguments", "too-many-public-methods", "too-few-public-methods", "too-many-ancestors", "unnecessary-pass", # allow for methods with just "pass", for clarity "unnecessary-dunder-call", # do not want to implement "no-else-return", # relax "elif" after a clause with a return "docstring-first-line-empty", # relax docstring style "import-outside-toplevel", "import-error", # overzealous with our optionals/dynamic packages "nested-min-max", # this gives false equivalencies if implemented for the current lint version "consider-using-max-builtin", "consider-using-min-builtin", # unnecessary stylistic opinion # TODO(#9614): these were added in modern Pylint. Decide if we want to enable them. If so, # remove from here and fix the issues. Else, move it above this section and add a comment # with the rationale "no-member", # for dynamically created members "not-context-manager", "unnecessary-lambda-assignment", # do not want to implement "unspecified-encoding", # do not want to implement ] enable = [ "use-symbolic-message-instead" ] [tool.pylint.spelling] spelling-private-dict-file = ".local-spellings" [tool.coverage.report] exclude_also = [ "def __repr__", # Printable epresentational string does not typically execute during testing "raise NotImplementedError", # Abstract methods are not testable "raise RuntimeError", # Exceptions for defensive programming that cannot be tested a head "if TYPE_CHECKING:", # Code that only runs during type checks "@abstractmethod", # Abstract methods are not testable ]
qiskit/pyproject.toml/0
{ "file_path": "qiskit/pyproject.toml", "repo_id": "qiskit", "token_count": 4551 }
173
# This code is part of Qiskit. # # (C) Copyright IBM 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. """ Quantum bit and Classical bit objects. """ import copy from qiskit.circuit.exceptions import CircuitError class Bit: """Implement a generic bit. .. note:: This class should not be instantiated directly. This is just a superclass for :class:`~.Clbit` and :class:`~.circuit.Qubit`. """ __slots__ = {"_register", "_index", "_hash", "_repr"} def __init__(self, register=None, index=None): """Create a new generic bit.""" if (register, index) == (None, None): self._register = None self._index = None # To sidestep the overridden Bit.__hash__ and use the default hash # algorithm (only new-style Bits), call default object hash method. self._hash = object.__hash__(self) else: try: index = int(index) except Exception as ex: raise CircuitError( f"index needs to be castable to an int: type {type(index)} was provided" ) from ex if index < 0: index += register.size if index >= register.size: raise CircuitError( f"index must be under the size of the register: {index} was provided" ) self._register = register self._index = index self._hash = hash((self._register, self._index)) self._repr = f"{self.__class__.__name__}({self._register}, {self._index})" def __repr__(self): """Return the official string representing the bit.""" if (self._register, self._index) == (None, None): # Similar to __hash__, use default repr method for new-style Bits. return object.__repr__(self) return self._repr def __hash__(self): return self._hash def __eq__(self, other): if (self._register, self._index) == (None, None): return other is self try: return self._repr == other._repr except AttributeError: return False def __copy__(self): # Bits are immutable. return self def __deepcopy__(self, memo=None): if (self._register, self._index) == (None, None): return self # Old-style bits need special handling for now, since some code seems # to rely on their registers getting deep-copied. bit = type(self).__new__(type(self)) bit._register = copy.deepcopy(self._register, memo) bit._index = self._index bit._hash = self._hash bit._repr = self._repr return bit
qiskit/qiskit/circuit/bit.py/0
{ "file_path": "qiskit/qiskit/circuit/bit.py", "repo_id": "qiskit", "token_count": 1298 }
174
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # 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. """Internal utils for Classical Function Compiler""" from qiskit.utils.optionals import HAS_TWEEDLEDUM from qiskit.circuit import QuantumCircuit from qiskit.circuit.library.standard_gates import ( HGate, SGate, SdgGate, SwapGate, TGate, TdgGate, XGate, YGate, ZGate, ) _QISKIT_OPS = { "std.h": HGate, "std.s": SGate, "std.sdg": SdgGate, "std.swap": SwapGate, "std.t": TGate, "std.tdg": TdgGate, "std.x": XGate, "std.y": YGate, "std.z": ZGate, } @HAS_TWEEDLEDUM.require_in_call def _convert_tweedledum_operator(op): base_gate = _QISKIT_OPS.get(op.kind()) if base_gate is None: if op.kind() == "py_operator": return op.py_op() else: raise RuntimeError(f"Unrecognized operator: {op.kind()}") # TODO: need to deal with cbits too! if op.num_controls() > 0: from tweedledum.ir import Qubit # pylint: disable=import-error qubits = op.qubits() ctrl_state = "" for qubit in qubits[: op.num_controls()]: ctrl_state += f"{int(qubit.polarity() == Qubit.Polarity.positive)}" return base_gate().control(len(ctrl_state), ctrl_state=ctrl_state[::-1]) return base_gate() @HAS_TWEEDLEDUM.require_in_call def tweedledum2qiskit(tweedledum_circuit, name=None, qregs=None): """Converts a `Tweedledum <https://github.com/boschmitt/tweedledum>`_ circuit into a Qiskit circuit. Args: tweedledum_circuit (tweedledum.ir.Circuit): Tweedledum circuit. name (str): Name for the resulting Qiskit circuit. qregs (list(QuantumRegister)): Optional. List of QuantumRegisters on which the circuit would operate. If not provided, it will create a flat register. Returns: QuantumCircuit: The Tweedledum circuit converted to a Qiskit circuit. Raises: ClassicalFunctionCompilerError: If a gate in the Tweedledum circuit has no Qiskit equivalent. """ if qregs: qiskit_qc = QuantumCircuit(*qregs, name=name) else: qiskit_qc = QuantumCircuit(tweedledum_circuit.num_qubits(), name=name) from tweedledum.passes import parity_decomp # pylint: disable=import-error for instruction in parity_decomp(tweedledum_circuit): gate = _convert_tweedledum_operator(instruction) qubits = [qubit.uid() for qubit in instruction.qubits()] qiskit_qc.append(gate, qubits) return qiskit_qc
qiskit/qiskit/circuit/classicalfunction/utils.py/0
{ "file_path": "qiskit/qiskit/circuit/classicalfunction/utils.py", "repo_id": "qiskit", "token_count": 1217 }
175
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # 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. """ Utilities for handling duration of a circuit instruction. """ import warnings from qiskit.circuit import QuantumCircuit from qiskit.circuit.exceptions import CircuitError from qiskit.utils.units import apply_prefix def duration_in_dt(duration_in_sec: float, dt_in_sec: float) -> int: """ Return duration in dt. Args: duration_in_sec: duration [s] to be converted. dt_in_sec: duration of dt in seconds used for conversion. Returns: Duration in dt. """ res = round(duration_in_sec / dt_in_sec) rounding_error = abs(duration_in_sec - res * dt_in_sec) if rounding_error > 1e-15: warnings.warn( f"Duration is rounded to {res:d} [dt] = {res * dt_in_sec:e} [s] " f"from {duration_in_sec:e} [s]", UserWarning, ) return res def convert_durations_to_dt(qc: QuantumCircuit, dt_in_sec: float, inplace=True): """Convert all the durations in SI (seconds) into those in dt. Returns a new circuit if `inplace=False`. Parameters: qc (QuantumCircuit): Duration of dt in seconds used for conversion. dt_in_sec (float): Duration of dt in seconds used for conversion. inplace (bool): All durations are converted inplace or return new circuit. Returns: QuantumCircuit: Converted circuit if `inplace = False`, otherwise None. Raises: CircuitError: if fail to convert durations. """ if inplace: circ = qc else: circ = qc.copy() for instruction in circ.data: operation = instruction.operation if operation.unit == "dt" or operation.duration is None: continue if not operation.unit.endswith("s"): raise CircuitError(f"Invalid time unit: '{operation.unit}'") duration = operation.duration if operation.unit != "s": duration = apply_prefix(duration, operation.unit) operation.duration = duration_in_dt(duration, dt_in_sec) operation.unit = "dt" if circ.duration is not None and circ.unit != "dt": if not circ.unit.endswith("s"): raise CircuitError(f"Invalid time unit: '{circ.unit}'") duration = circ.duration if circ.unit != "s": duration = apply_prefix(duration, circ.unit) circ.duration = duration_in_dt(duration, dt_in_sec) circ.unit = "dt" if not inplace: return circ else: return None
qiskit/qiskit/circuit/duration.py/0
{ "file_path": "qiskit/qiskit/circuit/duration.py", "repo_id": "qiskit", "token_count": 1143 }
176
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # 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. """Integer Comparator.""" from __future__ import annotations import math from qiskit.circuit import QuantumCircuit, QuantumRegister, AncillaRegister from qiskit.circuit.exceptions import CircuitError from ..boolean_logic import OR from ..blueprintcircuit import BlueprintCircuit class IntegerComparator(BlueprintCircuit): r"""Integer Comparator. Operator compares basis states :math:`|i\rangle_n` against a classically given integer :math:`L` of fixed value and flips a target qubit if :math:`i \geq L` (or :math:`<` depending on the parameter ``geq``): .. math:: |i\rangle_n |0\rangle \mapsto |i\rangle_n |i \geq L\rangle This operation is based on two's complement implementation of binary subtraction but only uses carry bits and no actual result bits. If the most significant carry bit (the results bit) is 1, the :math:`\geq` condition is ``True`` otherwise it is ``False``. """ def __init__( self, num_state_qubits: int | None = None, value: int | None = None, geq: bool = True, name: str = "cmp", ) -> None: """Create a new fixed value comparator circuit. Args: num_state_qubits: Number of state qubits. If this is set it will determine the number of qubits required for the circuit. value: The fixed value to compare with. geq: If True, evaluate a ``>=`` condition, else ``<``. name: Name of the circuit. """ super().__init__(name=name) self._value = None self._geq = None self._num_state_qubits = None self.value = value self.geq = geq self.num_state_qubits = num_state_qubits @property def value(self) -> int: """The value to compare the qubit register to. Returns: The value against which the value of the qubit register is compared. """ return self._value @value.setter def value(self, value: int) -> None: if value != self._value: self._invalidate() self._value = value @property def geq(self) -> bool: """Return whether the comparator compares greater or less equal. Returns: True, if the comparator compares ``>=``, False if ``<``. """ return self._geq @geq.setter def geq(self, geq: bool) -> None: """Set whether the comparator compares greater or less equal. Args: geq: If True, the comparator compares ``>=``, if False ``<``. """ if geq != self._geq: self._invalidate() self._geq = geq @property def num_state_qubits(self) -> int: """The number of qubits encoding the state for the comparison. Returns: The number of state qubits. """ return self._num_state_qubits @num_state_qubits.setter def num_state_qubits(self, num_state_qubits: int | None) -> None: """Set the number of state qubits. Note that this will change the quantum registers. Args: num_state_qubits: The new number of state qubits. """ if self._num_state_qubits is None or num_state_qubits != self._num_state_qubits: self._invalidate() # reset data self._num_state_qubits = num_state_qubits if num_state_qubits is not None: # set the new qubit registers qr_state = QuantumRegister(num_state_qubits, name="state") q_compare = QuantumRegister(1, name="compare") self.qregs = [qr_state, q_compare] # add ancillas is required num_ancillas = num_state_qubits - 1 if num_ancillas > 0: qr_ancilla = AncillaRegister(num_ancillas) self.add_register(qr_ancilla) def _get_twos_complement(self) -> list[int]: """Returns the 2's complement of ``self.value`` as array. Returns: The 2's complement of ``self.value``. """ twos_complement = pow(2, self.num_state_qubits) - math.ceil(self.value) twos_complement = f"{twos_complement:b}".rjust(self.num_state_qubits, "0") twos_complement = [ 1 if twos_complement[i] == "1" else 0 for i in reversed(range(len(twos_complement))) ] return twos_complement def _check_configuration(self, raise_on_failure: bool = True) -> bool: """Check if the current configuration is valid.""" valid = True if self._num_state_qubits is None: valid = False if raise_on_failure: raise AttributeError("Number of state qubits is not set.") if self._value is None: valid = False if raise_on_failure: raise AttributeError("No comparison value set.") required_num_qubits = 2 * self.num_state_qubits if self.num_qubits != required_num_qubits: valid = False if raise_on_failure: raise CircuitError("Number of qubits does not match required number of qubits.") return valid def _build(self) -> None: """If not already built, build the circuit.""" if self._is_built: return super()._build() qr_state = self.qubits[: self.num_state_qubits] q_compare = self.qubits[self.num_state_qubits] qr_ancilla = self.qubits[self.num_state_qubits + 1 :] circuit = QuantumCircuit(*self.qregs, name=self.name) if self.value <= 0: # condition always satisfied for non-positive values if self._geq: # otherwise the condition is never satisfied circuit.x(q_compare) # condition never satisfied for values larger than or equal to 2^n elif self.value < pow(2, self.num_state_qubits): if self.num_state_qubits > 1: twos = self._get_twos_complement() for i in range(self.num_state_qubits): if i == 0: if twos[i] == 1: circuit.cx(qr_state[i], qr_ancilla[i]) elif i < self.num_state_qubits - 1: if twos[i] == 1: circuit.compose( OR(2), [qr_state[i], qr_ancilla[i - 1], qr_ancilla[i]], inplace=True ) else: circuit.ccx(qr_state[i], qr_ancilla[i - 1], qr_ancilla[i]) else: if twos[i] == 1: # OR needs the result argument as qubit not register, thus # access the index [0] circuit.compose( OR(2), [qr_state[i], qr_ancilla[i - 1], q_compare], inplace=True ) else: circuit.ccx(qr_state[i], qr_ancilla[i - 1], q_compare) # flip result bit if geq flag is false if not self._geq: circuit.x(q_compare) # uncompute ancillas state for i in reversed(range(self.num_state_qubits - 1)): if i == 0: if twos[i] == 1: circuit.cx(qr_state[i], qr_ancilla[i]) else: if twos[i] == 1: circuit.compose( OR(2), [qr_state[i], qr_ancilla[i - 1], qr_ancilla[i]], inplace=True ) else: circuit.ccx(qr_state[i], qr_ancilla[i - 1], qr_ancilla[i]) else: # num_state_qubits == 1 and value == 1: circuit.cx(qr_state[0], q_compare) # flip result bit if geq flag is false if not self._geq: circuit.x(q_compare) else: if not self._geq: # otherwise the condition is never satisfied circuit.x(q_compare) self.append(circuit.to_gate(), self.qubits)
qiskit/qiskit/circuit/library/arithmetic/integer_comparator.py/0
{ "file_path": "qiskit/qiskit/circuit/library/arithmetic/integer_comparator.py", "repo_id": "qiskit", "token_count": 4280 }
177
# This code is part of Qiskit. # # (C) Copyright IBM 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. # pylint: disable=invalid-name # pylint: disable=unused-variable # pylint: disable=missing-param-doc # pylint: disable=missing-type-doc """ Generic isometries from m to n qubits. """ from __future__ import annotations import math import numpy as np from qiskit.circuit.exceptions import CircuitError from qiskit.circuit.instruction import Instruction from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.quantumregister import QuantumRegister from qiskit.exceptions import QiskitError from qiskit.quantum_info.operators.predicates import is_isometry from qiskit._accelerate import isometry as isometry_rs from .diagonal import Diagonal from .uc import UCGate from .mcg_up_to_diagonal import MCGupDiag _EPS = 1e-10 # global variable used to chop very small numbers to zero class Isometry(Instruction): r"""Decomposition of arbitrary isometries from :math:`m` to :math:`n` qubits. In particular, this allows to decompose unitaries (m=n) and to do state preparation (:math:`m=0`). The decomposition is based on [1]. References: 1. Iten et al., Quantum circuits for isometries (2016). `Phys. Rev. A 93, 032318 <https://journals.aps.org/pra/abstract/10.1103/PhysRevA.93.032318>`__. """ # Notation: In the following decomposition we label the qubit by # 0 -> most significant one # ... # n -> least significant one # finally, we convert the labels back to the qubit numbering used in Qiskit # (using: _get_qubits_by_label) def __init__( self, isometry: np.ndarray, num_ancillas_zero: int, num_ancillas_dirty: int, epsilon: float = _EPS, ) -> None: r""" Args: isometry: An isometry from :math:`m` to :math`n` qubits, i.e., a complex ``np.ndarray`` of dimension :math:`2^n \times 2^m` with orthonormal columns (given in the computational basis specified by the order of the ancillas and the input qubits, where the ancillas are considered to be more significant than the input qubits). num_ancillas_zero: Number of additional ancillas that start in the state :math:`|0\rangle` (the :math:`n-m` ancillas required for providing the output of the isometry are not accounted for here). num_ancillas_dirty: Number of additional ancillas that start in an arbitrary state. epsilon: Error tolerance of calculations. """ # Convert to numpy array in case not already an array isometry = np.array(isometry, dtype=complex) # change a row vector to a column vector (in the case of state preparation) if len(isometry.shape) == 1: isometry = isometry.reshape(isometry.shape[0], 1) self.iso_data = isometry self.num_ancillas_zero = num_ancillas_zero self.num_ancillas_dirty = num_ancillas_dirty self._inverse = None self._epsilon = epsilon # Check if the isometry has the right dimension and if the columns are orthonormal n = math.log2(isometry.shape[0]) m = math.log2(isometry.shape[1]) if not n.is_integer() or n < 0: raise QiskitError( "The number of rows of the isometry is not a non negative power of 2." ) if not m.is_integer() or m < 0: raise QiskitError( "The number of columns of the isometry is not a non negative power of 2." ) if m > n: raise QiskitError( "The input matrix has more columns than rows and hence it can't be an isometry." ) if not is_isometry(isometry, self._epsilon): raise QiskitError( "The input matrix has non orthonormal columns and hence it is not an isometry." ) num_qubits = int(n) + num_ancillas_zero + num_ancillas_dirty super().__init__("isometry", num_qubits, 0, [isometry]) def _define(self): # TODO The inverse().inverse() is because there is code to uncompute (_gates_to_uncompute) # an isometry, but not for generating its decomposition. It would be cheaper to do the # later here instead. gate = self.inv_gate() gate = gate.inverse() q = QuantumRegister(self.num_qubits, "q") iso_circuit = QuantumCircuit(q, name="isometry") iso_circuit.append(gate, q[:]) self.definition = iso_circuit def inverse(self, annotated: bool = False): self.params = [] inv = super().inverse(annotated=annotated) self.params = [self.iso_data] return inv def _gates_to_uncompute(self): """ Call to create a circuit with gates that take the desired isometry to the first 2^m columns of the 2^n*2^n identity matrix (see https://arxiv.org/abs/1501.06911) """ q = QuantumRegister(self.num_qubits, "q") circuit = QuantumCircuit(q, name="isometry_to_uncompute") ( q_input, q_ancillas_for_output, q_ancillas_zero, q_ancillas_dirty, ) = self._define_qubit_role(q) # Copy the isometry (this is computationally expensive for large isometries but guarantees # to keep a copyof the input isometry) remaining_isometry = self.iso_data.astype(complex) # note: "astype" does copy the isometry diag = [] m = int(math.log2(self.iso_data.shape[1])) # Decompose the column with index column_index and attache the gate to the circuit object. # Return the isometry that is left to decompose, where the columns up to index column_index # correspond to the firstfew columns of the identity matrix up to diag, and hence we only # have to save a list containing them. for column_index in range(2**m): remaining_isometry, diag = self._decompose_column( circuit, q, diag, remaining_isometry, column_index ) # extract phase of the state that was sent to the basis state ket(column_index) diag.append(remaining_isometry[column_index, 0]) # remove first column (which is now stored in diag) remaining_isometry = remaining_isometry[:, 1:] if len(diag) > 1 and not isometry_rs.diag_is_identity_up_to_global_phase( diag, self._epsilon ): diagonal = Diagonal(np.conj(diag)) circuit.append(diagonal, q_input) return circuit def _decompose_column(self, circuit, q, diag, remaining_isometry, column_index): """ Decomposes the column with index column_index. """ n = int(math.log2(self.iso_data.shape[0])) for s in range(n): remaining_isometry, diag = self._disentangle( circuit, q, diag, remaining_isometry, column_index, s ) return remaining_isometry, diag def _disentangle(self, circuit, q, diag, remaining_isometry, column_index, s): """ Disentangle the s-th significant qubit (starting with s = 0) into the zero or the one state (dependent on column_index) """ # To shorten the notation, we introduce: k = column_index # k_prime is the index of the column with index column_index in the remaining isometry # (note that we remove columns of the isometry during the procedure for efficiency) k_prime = 0 v = remaining_isometry n = int(math.log2(self.iso_data.shape[0])) # MCG to set one entry to zero (preparation for disentangling with UCGate): index1 = 2 * isometry_rs.a(k, s + 1) * 2**s + isometry_rs.b(k, s + 1) index2 = (2 * isometry_rs.a(k, s + 1) + 1) * 2**s + isometry_rs.b(k, s + 1) target_label = n - s - 1 # Check if a MCG is required if ( isometry_rs.k_s(k, s) == 0 and isometry_rs.b(k, s + 1) != 0 and np.abs(v[index2, k_prime]) > self._epsilon ): # Find the MCG, decompose it and apply it to the remaining isometry gate = isometry_rs.reverse_qubit_state( [v[index1, k_prime], v[index2, k_prime]], 0, self._epsilon ) control_labels = [ i for i, x in enumerate(_get_binary_rep_as_list(k, n)) if x == 1 and i != target_label ] diagonal_mcg = self._append_mcg_up_to_diagonal( circuit, q, gate, control_labels, target_label ) # apply the MCG to the remaining isometry v = isometry_rs.apply_multi_controlled_gate(v, control_labels, target_label, gate) # correct for the implementation "up to diagonal" diag_mcg_inverse = np.conj(diagonal_mcg).astype(complex, copy=False) v = isometry_rs.apply_diagonal_gate( v, control_labels + [target_label], diag_mcg_inverse ) # update the diag according to the applied diagonal gate diag = isometry_rs.apply_diagonal_gate_to_diag( diag, control_labels + [target_label], diag_mcg_inverse, n ) # UCGate to disentangle a qubit: # Find the UCGate, decompose it and apply it to the remaining isometry single_qubit_gates = self._find_squs_for_disentangling(v, k, s) if not isometry_rs.ucg_is_identity_up_to_global_phase(single_qubit_gates, self._epsilon): control_labels = list(range(target_label)) diagonal_ucg = self._append_ucg_up_to_diagonal( circuit, q, single_qubit_gates, control_labels, target_label ) # merge the diagonal into the UCGate for efficient application of both together diagonal_ucg_inverse = np.conj(diagonal_ucg).astype(complex, copy=False) single_qubit_gates = isometry_rs.merge_ucgate_and_diag( single_qubit_gates, diagonal_ucg_inverse ) # apply the UCGate (with the merged diagonal gate) to the remaining isometry v = isometry_rs.apply_ucg(v, len(control_labels), single_qubit_gates) # update the diag according to the applied diagonal gate diag = isometry_rs.apply_diagonal_gate_to_diag( diag, control_labels + [target_label], diagonal_ucg_inverse, n ) # # correct for the implementation "up to diagonal" # diag_inv = np.conj(diag).tolist() # _apply_diagonal_gate(v, control_labels + [target_label], diag_inv) return v, diag # This method finds the single-qubit gates for a UCGate to disentangle a qubit: # we consider the n-qubit state v[:,0] starting with k zeros (in the computational basis). # The qubit with label n-s-1 is disentangled into the basis state k_s(k,s). def _find_squs_for_disentangling(self, v, k, s): res = isometry_rs.find_squs_for_disentangling( v, k, s, self._epsilon, n=int(math.log2(self.iso_data.shape[0])) ) return res # Append a UCGate up to diagonal to the circuit circ. def _append_ucg_up_to_diagonal(self, circ, q, single_qubit_gates, control_labels, target_label): ( q_input, q_ancillas_for_output, q_ancillas_zero, q_ancillas_dirty, ) = self._define_qubit_role(q) n = int(math.log2(self.iso_data.shape[0])) qubits = q_input + q_ancillas_for_output # Note that we have to reverse the control labels, since controls are provided by # increasing qubit number toa UCGate by convention control_qubits = _reverse_qubit_oder(_get_qubits_by_label(control_labels, qubits, n)) target_qubit = _get_qubits_by_label([target_label], qubits, n)[0] ucg = UCGate(single_qubit_gates, up_to_diagonal=True) circ.append(ucg, [target_qubit] + control_qubits) return ucg._get_diagonal() # Append a MCG up to diagonal to the circuit circ. The diagonal should only act on the control # and target qubits and not on the ancillas. In principle, it would be allowed to act on the # dirty ancillas on which we perform the isometry (i.e., on the qubits listed in "qubits" # below). But for simplicity, the current code version ignores this future optimization # possibility. def _append_mcg_up_to_diagonal(self, circ, q, gate, control_labels, target_label): ( q_input, q_ancillas_for_output, q_ancillas_zero, q_ancillas_dirty, ) = self._define_qubit_role(q) n = int(math.log2(self.iso_data.shape[0])) qubits = q_input + q_ancillas_for_output control_qubits = _reverse_qubit_oder(_get_qubits_by_label(control_labels, qubits, n)) target_qubit = _get_qubits_by_label([target_label], qubits, n)[0] # The qubits on which we neither act nor control on with the MCG, can be used # as dirty ancillas ancilla_dirty_labels = [i for i in range(n) if i not in control_labels + [target_label]] ancillas_dirty = ( _reverse_qubit_oder(_get_qubits_by_label(ancilla_dirty_labels, qubits, n)) + q_ancillas_dirty ) mcg_up_to_diag = MCGupDiag( gate, len(control_qubits), len(q_ancillas_zero), len(ancillas_dirty) ) circ.append( mcg_up_to_diag, [target_qubit] + control_qubits + q_ancillas_zero + ancillas_dirty ) return mcg_up_to_diag._get_diagonal() def _define_qubit_role(self, q): n = int(math.log2(self.iso_data.shape[0])) m = int(math.log2(self.iso_data.shape[1])) # Define the role of the qubits q_input = q[:m] q_ancillas_for_output = q[m:n] q_ancillas_zero = q[n : n + self.num_ancillas_zero] q_ancillas_dirty = q[n + self.num_ancillas_zero :] return q_input, q_ancillas_for_output, q_ancillas_zero, q_ancillas_dirty def validate_parameter(self, parameter): """Isometry parameter has to be an ndarray.""" if isinstance(parameter, np.ndarray): return parameter if isinstance(parameter, (list, int)): return parameter else: raise CircuitError(f"invalid param type {type(parameter)} for gate {self.name}") def inv_gate(self): """Return the adjoint of the unitary.""" if self._inverse is None: # call to generate the circuit that takes the isometry to the first 2^m columns # of the 2^n identity matrix iso_circuit = self._gates_to_uncompute() # invert the circuit to create the circuit implementing the isometry self._inverse = iso_circuit.to_instruction() return self._inverse # Get the qubits in the list qubits corresponding to the labels listed in labels. The total number # of qubits is given by num_qubits (and determines the convention for the qubit labeling) # Remark: We labeled the qubits with decreasing significance. So we have to transform the labels to # be compatible with the standard convention of Qiskit. def _get_qubits_by_label(labels, qubits, num_qubits): return [qubits[num_qubits - label - 1] for label in labels] def _reverse_qubit_oder(qubits): return list(reversed(qubits)) # Convert list of binary digits to integer def _get_binary_rep_as_list(n, num_digits): binary_string = np.binary_repr(n).zfill(num_digits) binary = [] for line in binary_string: for c in line: binary.append(int(c)) return binary[-num_digits:]
qiskit/qiskit/circuit/library/generalized_gates/isometry.py/0
{ "file_path": "qiskit/qiskit/circuit/library/generalized_gates/isometry.py", "repo_id": "qiskit", "token_count": 6973 }
178
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # 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. """Hidden Linear Function circuit.""" from typing import Union, List import numpy as np from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.exceptions import CircuitError class HiddenLinearFunction(QuantumCircuit): r"""Circuit to solve the hidden linear function problem. The 2D Hidden Linear Function problem is determined by a 2D adjacency matrix A, where only elements that are nearest-neighbor on a grid have non-zero entries. Each row/column corresponds to one binary variable :math:`x_i`. The hidden linear function problem is as follows: Consider the quadratic form .. math:: q(x) = \sum_{i,j=1}^{n}{x_i x_j} ~(\mathrm{mod}~ 4) and restrict :math:`q(x)` onto the nullspace of A. This results in a linear function. .. math:: 2 \sum_{i=1}^{n}{z_i x_i} ~(\mathrm{mod}~ 4) \forall x \in \mathrm{Ker}(A) and the goal is to recover this linear function (equivalently a vector :math:`[z_0, ..., z_{n-1}]`). There can be multiple solutions. In [1] it is shown that the present circuit solves this problem on a quantum computer in constant depth, whereas any corresponding solution on a classical computer would require circuits that grow logarithmically with :math:`n`. Thus this circuit is an example of quantum advantage with shallow circuits. **Reference Circuit:** .. plot:: from qiskit.circuit.library import HiddenLinearFunction from qiskit.visualization.library import _generate_circuit_library_visualization A = [[1, 1, 0], [1, 0, 1], [0, 1, 1]] circuit = HiddenLinearFunction(A) _generate_circuit_library_visualization(circuit) **Reference:** [1] S. Bravyi, D. Gosset, R. Koenig, Quantum Advantage with Shallow Circuits, 2017. `arXiv:1704.00690 <https://arxiv.org/abs/1704.00690>`_ """ def __init__(self, adjacency_matrix: Union[List[List[int]], np.ndarray]) -> None: """Create new HLF circuit. Args: adjacency_matrix: a symmetric n-by-n list of 0-1 lists. n will be the number of qubits. Raises: CircuitError: If A is not symmetric. """ adjacency_matrix = np.asarray(adjacency_matrix) if not np.allclose(adjacency_matrix, adjacency_matrix.transpose()): raise CircuitError("The adjacency matrix must be symmetric.") num_qubits = len(adjacency_matrix) circuit = QuantumCircuit(num_qubits, name=f"hlf: {adjacency_matrix}") circuit.h(range(num_qubits)) for i in range(num_qubits): for j in range(i + 1, num_qubits): if adjacency_matrix[i][j]: circuit.cz(i, j) for i in range(num_qubits): if adjacency_matrix[i][i]: circuit.s(i) circuit.h(range(num_qubits)) super().__init__(*circuit.qregs, name=circuit.name) self.compose(circuit.to_gate(), qubits=self.qubits, inplace=True)
qiskit/qiskit/circuit/library/hidden_linear_function.py/0
{ "file_path": "qiskit/qiskit/circuit/library/hidden_linear_function.py", "repo_id": "qiskit", "token_count": 1384 }
179
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # 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. """ Standard gates """ from .h import HGate, CHGate from .i import IGate from .p import PhaseGate, CPhaseGate, MCPhaseGate from .r import RGate from .rx import RXGate, CRXGate from .rxx import RXXGate from .ry import RYGate, CRYGate from .ryy import RYYGate from .rz import RZGate, CRZGate from .rzz import RZZGate from .rzx import RZXGate from .xx_minus_yy import XXMinusYYGate from .xx_plus_yy import XXPlusYYGate from .ecr import ECRGate from .s import SGate, SdgGate, CSGate, CSdgGate from .swap import SwapGate, CSwapGate from .iswap import iSwapGate from .sx import SXGate, SXdgGate, CSXGate from .dcx import DCXGate from .t import TGate, TdgGate from .u import UGate, CUGate from .u1 import U1Gate, CU1Gate, MCU1Gate from .u2 import U2Gate from .u3 import U3Gate, CU3Gate from .x import XGate, CXGate, CCXGate, C3XGate, C3SXGate, C4XGate, RCCXGate, RC3XGate from .x import MCXGate, MCXGrayCode, MCXRecursive, MCXVChain from .y import YGate, CYGate from .z import ZGate, CZGate, CCZGate from .global_phase import GlobalPhaseGate from .multi_control_rotation_gates import mcrx, mcry, mcrz def get_standard_gate_name_mapping(): """Return a dictionary mapping the name of standard gates and instructions to an object for that name.""" from qiskit.circuit.parameter import Parameter from qiskit.circuit.measure import Measure from qiskit.circuit.delay import Delay from qiskit.circuit.reset import Reset # Standard gates library mapping, multicontrolled gates not included since they're # variable width gates = [ IGate(), SXGate(), XGate(), CXGate(), RZGate(Parameter("λ")), RGate(Parameter("ϴ"), Parameter("φ")), Reset(), C3SXGate(), CCXGate(), DCXGate(), CHGate(), CPhaseGate(Parameter("ϴ")), CRXGate(Parameter("ϴ")), CRYGate(Parameter("ϴ")), CRZGate(Parameter("ϴ")), CSwapGate(), CSXGate(), CUGate(Parameter("ϴ"), Parameter("φ"), Parameter("λ"), Parameter("γ")), CU1Gate(Parameter("λ")), CU3Gate(Parameter("ϴ"), Parameter("φ"), Parameter("λ")), CYGate(), CZGate(), CCZGate(), GlobalPhaseGate(Parameter("ϴ")), HGate(), PhaseGate(Parameter("ϴ")), RCCXGate(), RC3XGate(), RXGate(Parameter("ϴ")), RXXGate(Parameter("ϴ")), RYGate(Parameter("ϴ")), RYYGate(Parameter("ϴ")), RZZGate(Parameter("ϴ")), RZXGate(Parameter("ϴ")), XXMinusYYGate(Parameter("ϴ"), Parameter("β")), XXPlusYYGate(Parameter("ϴ"), Parameter("β")), ECRGate(), SGate(), SdgGate(), CSGate(), CSdgGate(), SwapGate(), iSwapGate(), SXdgGate(), TGate(), TdgGate(), UGate(Parameter("ϴ"), Parameter("φ"), Parameter("λ")), U1Gate(Parameter("λ")), U2Gate(Parameter("φ"), Parameter("λ")), U3Gate(Parameter("ϴ"), Parameter("φ"), Parameter("λ")), YGate(), ZGate(), Delay(Parameter("t")), Measure(), ] name_mapping = {gate.name: gate for gate in gates} return name_mapping
qiskit/qiskit/circuit/library/standard_gates/__init__.py/0
{ "file_path": "qiskit/qiskit/circuit/library/standard_gates/__init__.py", "repo_id": "qiskit", "token_count": 1562 }
180
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # 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. """Two-qubit ZX-rotation gate.""" from __future__ import annotations import math from typing import Optional from qiskit.circuit.gate import Gate from qiskit.circuit.quantumregister import QuantumRegister from qiskit.circuit.parameterexpression import ParameterValueType, ParameterExpression from qiskit._accelerate.circuit import StandardGate class RZXGate(Gate): r"""A parametric 2-qubit :math:`Z \otimes X` interaction (rotation about ZX). This gate is maximally entangling at :math:`\theta = \pi/2`. The cross-resonance gate (CR) for superconducting qubits implements a ZX interaction (however other terms are also present in an experiment). Can be applied to a :class:`~qiskit.circuit.QuantumCircuit` with the :meth:`~qiskit.circuit.QuantumCircuit.rzx` method. **Circuit Symbol:** .. parsed-literal:: ┌─────────┐ q_0: ┤0 ├ │ Rzx(θ) │ q_1: ┤1 ├ └─────────┘ **Matrix Representation:** .. math:: \newcommand{\rotationangle}{\frac{\theta}{2}} R_{ZX}(\theta)\ q_0, q_1 = \exp\left(-i \frac{\theta}{2} X{\otimes}Z\right) = \begin{pmatrix} \cos\left(\rotationangle\right) & 0 & -i\sin\left(\rotationangle\right) & 0 \\ 0 & \cos\left(\rotationangle\right) & 0 & i\sin\left(\rotationangle\right) \\ -i\sin\left(\rotationangle\right) & 0 & \cos\left(\rotationangle\right) & 0 \\ 0 & i\sin\left(\rotationangle\right) & 0 & \cos\left(\rotationangle\right) \end{pmatrix} .. note:: In Qiskit's convention, higher qubit indices are more significant (little endian convention). In the above example we apply the gate on (q_0, q_1) which results in the :math:`X \otimes Z` tensor order. Instead, if we apply it on (q_1, q_0), the matrix will be :math:`Z \otimes X`: .. parsed-literal:: ┌─────────┐ q_0: ┤1 ├ │ Rzx(θ) │ q_1: ┤0 ├ └─────────┘ .. math:: \newcommand{\rotationangle}{\frac{\theta}{2}} R_{ZX}(\theta)\ q_1, q_0 = exp(-i \frac{\theta}{2} Z{\otimes}X) = \begin{pmatrix} \cos(\rotationangle) & -i\sin(\rotationangle) & 0 & 0 \\ -i\sin(\rotationangle) & \cos(\rotationangle) & 0 & 0 \\ 0 & 0 & \cos(\rotationangle) & i\sin(\rotationangle) \\ 0 & 0 & i\sin(\rotationangle) & \cos(\rotationangle) \end{pmatrix} This is a direct sum of RX rotations, so this gate is equivalent to a uniformly controlled (multiplexed) RX gate: .. math:: R_{ZX}(\theta)\ q_1, q_0 = \begin{pmatrix} RX(\theta) & 0 \\ 0 & RX(-\theta) \end{pmatrix} **Examples:** .. math:: R_{ZX}(\theta = 0) = I .. math:: R_{ZX}(\theta = 2\pi) = -I .. math:: R_{ZX}(\theta = \pi) = -i Z \otimes X .. math:: RZX(\theta = \frac{\pi}{2}) = \frac{1}{\sqrt{2}} \begin{pmatrix} 1 & 0 & -i & 0 \\ 0 & 1 & 0 & i \\ -i & 0 & 1 & 0 \\ 0 & i & 0 & 1 \end{pmatrix} """ _standard_gate = StandardGate.RZXGate def __init__( self, theta: ParameterValueType, label: Optional[str] = None, *, duration=None, unit="dt" ): """Create new RZX gate.""" super().__init__("rzx", 2, [theta], label=label, duration=duration, unit=unit) def _define(self): """ gate rzx(theta) a, b { h b; cx a, b; u1(theta) b; cx a, b; h b;} """ # pylint: disable=cyclic-import from qiskit.circuit.quantumcircuit import QuantumCircuit from .h import HGate from .x import CXGate from .rz import RZGate # q_0: ───────■─────────────■─────── # ┌───┐┌─┴─┐┌───────┐┌─┴─┐┌───┐ # q_1: ┤ H ├┤ X ├┤ Rz(0) ├┤ X ├┤ H ├ # └───┘└───┘└───────┘└───┘└───┘ theta = self.params[0] q = QuantumRegister(2, "q") qc = QuantumCircuit(q, name=self.name) rules = [ (HGate(), [q[1]], []), (CXGate(), [q[0], q[1]], []), (RZGate(theta), [q[1]], []), (CXGate(), [q[0], q[1]], []), (HGate(), [q[1]], []), ] for instr, qargs, cargs in rules: qc._append(instr, qargs, cargs) self.definition = qc def control( self, num_ctrl_qubits: int = 1, label: str | None = None, ctrl_state: str | int | None = None, annotated: bool | None = None, ): """Return a (multi-)controlled-RZX gate. Args: num_ctrl_qubits: number of control qubits. label: An optional label for the gate [Default: ``None``] ctrl_state: control state expressed as integer, string (e.g.``'110'``), or ``None``. If ``None``, use all 1s. annotated: indicates whether the controlled gate should be implemented as an annotated gate. If ``None``, this is set to ``True`` if the gate contains free parameters, in which case it cannot yet be synthesized. Returns: ControlledGate: controlled version of this gate. """ if annotated is None: annotated = any(isinstance(p, ParameterExpression) for p in self.params) gate = super().control( num_ctrl_qubits=num_ctrl_qubits, label=label, ctrl_state=ctrl_state, annotated=annotated, ) return gate def inverse(self, annotated: bool = False): """Return inverse RZX gate (i.e. with the negative rotation angle). Args: annotated: when set to ``True``, this is typically used to return an :class:`.AnnotatedOperation` with an inverse modifier set instead of a concrete :class:`.Gate`. However, for this class this argument is ignored as the inverse of this gate is always a :class:`.RZXGate` with an inverted parameter value. Returns: RZXGate: inverse gate. """ return RZXGate(-self.params[0]) def __array__(self, dtype=None, copy=None): """Return a numpy.array for the RZX gate.""" import numpy if copy is False: raise ValueError("unable to avoid copy while creating an array as requested") half_theta = float(self.params[0]) / 2 cos = math.cos(half_theta) isin = 1j * math.sin(half_theta) return numpy.array( [[cos, 0, -isin, 0], [0, cos, 0, isin], [-isin, 0, cos, 0], [0, isin, 0, cos]], dtype=dtype, ) def power(self, exponent: float, annotated: bool = False): (theta,) = self.params return RZXGate(exponent * theta) def __eq__(self, other): if isinstance(other, RZXGate): return self._compare_parameters(other) return False
qiskit/qiskit/circuit/library/standard_gates/rzx.py/0
{ "file_path": "qiskit/qiskit/circuit/library/standard_gates/rzx.py", "repo_id": "qiskit", "token_count": 3993 }
181
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # 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. # pylint: disable=bad-docstring-quotes,invalid-name """Quantum circuit object.""" from __future__ import annotations import collections.abc import copy as _copy import itertools import multiprocessing as mp import typing from collections import OrderedDict, defaultdict, namedtuple from typing import ( Union, Optional, Tuple, Type, TypeVar, Sequence, Callable, Mapping, Iterable, Any, DefaultDict, Literal, overload, ) import numpy as np from qiskit._accelerate.circuit import CircuitData from qiskit._accelerate.circuit import StandardGate from qiskit.exceptions import QiskitError from qiskit.utils.multiprocessing import is_main_process from qiskit.circuit.instruction import Instruction from qiskit.circuit.gate import Gate from qiskit.circuit.parameter import Parameter from qiskit.circuit.exceptions import CircuitError from qiskit.utils import deprecate_func from . import _classical_resource_map from .controlflow import ControlFlowOp, _builder_utils from .controlflow.builder import CircuitScopeInterface, ControlFlowBuilderBlock from .controlflow.break_loop import BreakLoopOp, BreakLoopPlaceholder from .controlflow.continue_loop import ContinueLoopOp, ContinueLoopPlaceholder from .controlflow.for_loop import ForLoopOp, ForLoopContext from .controlflow.if_else import IfElseOp, IfContext from .controlflow.switch_case import SwitchCaseOp, SwitchContext from .controlflow.while_loop import WhileLoopOp, WhileLoopContext from .classical import expr, types from .parameterexpression import ParameterExpression, ParameterValueType from .quantumregister import QuantumRegister, Qubit, AncillaRegister, AncillaQubit from .classicalregister import ClassicalRegister, Clbit from .parametertable import ParameterView from .parametervector import ParameterVector from .instructionset import InstructionSet from .operation import Operation from .register import Register from .bit import Bit from .quantumcircuitdata import QuantumCircuitData, CircuitInstruction from .delay import Delay from .store import Store if typing.TYPE_CHECKING: import qiskit # pylint: disable=cyclic-import from qiskit.transpiler.layout import TranspileLayout # pylint: disable=cyclic-import from qiskit.quantum_info.operators.base_operator import BaseOperator from qiskit.quantum_info.states.statevector import Statevector # pylint: disable=cyclic-import BitLocations = namedtuple("BitLocations", ("index", "registers")) # The following types are not marked private to avoid leaking this "private/public" abstraction out # into the documentation. They are not imported by circuit.__init__, nor are they meant to be. # Arbitrary type variables for marking up generics. S = TypeVar("S") T = TypeVar("T") # Types that can be coerced to a valid Qubit specifier in a circuit. QubitSpecifier = Union[ Qubit, QuantumRegister, int, slice, Sequence[Union[Qubit, int]], ] # Types that can be coerced to a valid Clbit specifier in a circuit. ClbitSpecifier = Union[ Clbit, ClassicalRegister, int, slice, Sequence[Union[Clbit, int]], ] # Generic type which is either :obj:`~Qubit` or :obj:`~Clbit`, used to specify types of functions # which operate on either type of bit, but not both at the same time. BitType = TypeVar("BitType", Qubit, Clbit) # NOTE: # # If you're adding methods or attributes to `QuantumCircuit`, be sure to update the class docstring # to document them in a suitable place. The class is huge, so we do its documentation manually so # it has at least some amount of organizational structure. class QuantumCircuit: """Core Qiskit representation of a quantum circuit. .. note:: For more details setting the :class:`QuantumCircuit` in context of all of the data structures that go with it, how it fits into the rest of the :mod:`qiskit` package, and the different regimes of quantum-circuit descriptions in Qiskit, see the module-level documentation of :mod:`qiskit.circuit`. Circuit attributes ================== :class:`QuantumCircuit` has a small number of public attributes, which are mostly older functionality. Most of its functionality is accessed through methods. A small handful of the attributes are intentionally mutable, the rest are data attributes that should be considered immutable. ========================= ====================================================================== Mutable attribute Summary ========================= ====================================================================== :attr:`global_phase` The global phase of the circuit, measured in radians. :attr:`metadata` Arbitrary user mapping, which Qiskit will preserve through the transpiler, but otherwise completely ignore. :attr:`name` An optional string name for the circuit. ========================= ====================================================================== ========================= ====================================================================== Immutable data attribute Summary ========================= ====================================================================== :attr:`ancillas` List of :class:`AncillaQubit`\\ s tracked by the circuit. :attr:`calibrations` Custom user-supplied pulse calibrations for individual instructions. :attr:`cregs` List of :class:`ClassicalRegister`\\ s tracked by the circuit. :attr:`clbits` List of :class:`Clbit`\\ s tracked by the circuit. :attr:`data` List of individual :class:`CircuitInstruction`\\ s that make up the circuit. :attr:`duration` Total duration of the circuit, added by scheduling transpiler passes. :attr:`layout` Hardware layout and routing information added by the transpiler. :attr:`num_ancillas` The number of ancilla qubits in the circuit. :attr:`num_clbits` The number of clbits in the circuit. :attr:`num_captured_vars` Number of captured real-time classical variables. :attr:`num_declared_vars` Number of locally declared real-time classical variables in the outer circuit scope. :attr:`num_input_vars` Number of input real-time classical variables. :attr:`num_parameters` Number of compile-time :class:`Parameter`\\ s in the circuit. :attr:`num_qubits` Number of qubits in the circuit. :attr:`num_vars` Total number of real-time classical variables in the outer circuit scope. :attr:`op_start_times` Start times of scheduled operations, added by scheduling transpiler passes. :attr:`parameters` Ordered set-like view of the compile-time :class:`Parameter`\\ s tracked by the circuit. :attr:`qregs` List of :class:`QuantumRegister`\\ s tracked by the circuit. :attr:`qubits` List of :class:`Qubit`\\ s tracked by the circuit. :attr:`unit` The unit of the :attr:`duration` field. ========================= ====================================================================== The core attribute is :attr:`data`. This is a sequence-like object that exposes the :class:`CircuitInstruction`\\ s contained in an ordered form. You generally should not mutate this object directly; :class:`QuantumCircuit` is only designed for append-only operations (which should use :meth:`append`). Most operations that mutate circuits in place should be written as transpiler passes (:mod:`qiskit.transpiler`). .. autoattribute:: data Alongside the :attr:`data`, the :attr:`global_phase` of a circuit can have some impact on its output, if the circuit is used to describe a :class:`.Gate` that may be controlled. This is measured in radians and is directly settable. .. autoattribute:: global_phase The :attr:`name` of a circuit becomes the name of the :class:`~.circuit.Instruction` or :class:`.Gate` resulting from :meth:`to_instruction` and :meth:`to_gate` calls, which can be handy for visualizations. .. autoattribute:: name You can attach arbitrary :attr:`metadata` to a circuit. No part of core Qiskit will inspect this or change its behavior based on metadata, but it will be faithfully passed through the transpiler, so you can tag your circuits yourself. When serializing a circuit with QPY (see :mod:`qiskit.qpy`), the metadata will be JSON-serialized and you may need to pass a custom serializer to handle non-JSON-compatible objects within it (see :func:`.qpy.dump` for more detail). This field is ignored during export to OpenQASM 2 or 3. .. autoattribute:: metadata :class:`QuantumCircuit` exposes data attributes tracking its internal quantum and classical bits and registers. These appear as Python :class:`list`\\ s, but you should treat them as immutable; changing them will *at best* have no effect, and more likely will simply corrupt the internal data of the :class:`QuantumCircuit`. .. autoattribute:: qregs .. autoattribute:: cregs .. autoattribute:: qubits .. autoattribute:: ancillas .. autoattribute:: clbits The :ref:`compile-time parameters <circuit-compile-time-parameters>` present in instructions on the circuit are available in :attr:`parameters`. This has a canonical order (mostly lexical, except in the case of :class:`.ParameterVector`), which matches the order that parameters will be assigned when using the list forms of :meth:`assign_parameters`, but also supports :class:`set`-like constant-time membership testing. .. autoattribute:: parameters The storage of any :ref:`manual pulse-level calibrations <circuit-calibrations>` for individual instructions on the circuit is in :attr:`calibrations`. This presents as a :class:`dict`, but should not be mutated directly; use the methods discussed in :ref:`circuit-calibrations`. .. autoattribute:: calibrations If you have transpiled your circuit, so you have a physical circuit, you can inspect the :attr:`layout` attribute for information stored by the transpiler about how the virtual qubits of the source circuit map to the hardware qubits of your physical circuit, both at the start and end of the circuit. .. autoattribute:: layout If your circuit was also *scheduled* as part of a transpilation, it will expose the individual timings of each instruction, along with the total :attr:`duration` of the circuit. .. autoattribute:: duration .. autoattribute:: unit .. autoattribute:: op_start_times Finally, :class:`QuantumCircuit` exposes several simple properties as dynamic read-only numeric attributes. .. autoattribute:: num_ancillas .. autoattribute:: num_clbits .. autoattribute:: num_captured_vars .. autoattribute:: num_declared_vars .. autoattribute:: num_input_vars .. autoattribute:: num_parameters .. autoattribute:: num_qubits .. autoattribute:: num_vars Creating new circuits ===================== ========================= ===================================================================== Method Summary ========================= ===================================================================== :meth:`__init__` Default constructor of no-instruction circuits. :meth:`copy` Make a complete copy of an existing circuit. :meth:`copy_empty_like` Copy data objects from one circuit into a new one without any instructions. :meth:`from_instructions` Infer data objects needed from a list of instructions. :meth:`from_qasm_file` Legacy interface to :func:`.qasm2.load`. :meth:`from_qasm_str` Legacy interface to :func:`.qasm2.loads`. ========================= ===================================================================== The default constructor (``QuantumCircuit(...)``) produces a circuit with no initial instructions. The arguments to the default constructor can be used to seed the circuit with quantum and classical data storage, and to provide a name, global phase and arbitrary metadata. All of these fields can be expanded later. .. automethod:: __init__ If you have an existing circuit, you can produce a copy of it using :meth:`copy`, including all its instructions. This is useful if you want to keep partial circuits while extending another, or to have a version you can mutate in-place while leaving the prior one intact. .. automethod:: copy Similarly, if you want a circuit that contains all the same data objects (bits, registers, variables, etc) but with none of the instructions, you can use :meth:`copy_empty_like`. This is quite common when you want to build up a new layer of a circuit to then use apply onto the back with :meth:`compose`, or to do a full rewrite of a circuit's instructions. .. automethod:: copy_empty_like In some cases, it is most convenient to generate a list of :class:`.CircuitInstruction`\\ s separately to an entire circuit context, and then to build a circuit from this. The :meth:`from_instructions` constructor will automatically capture all :class:`.Qubit` and :class:`.Clbit` instances used in the instructions, and create a new :class:`QuantumCircuit` object that has the correct resources and all the instructions. .. automethod:: from_instructions :class:`QuantumCircuit` also still has two constructor methods that are legacy wrappers around the importers in :mod:`qiskit.qasm2`. These automatically apply :ref:`the legacy compatibility settings <qasm2-legacy-compatibility>` of :func:`~.qasm2.load` and :func:`~.qasm2.loads`. .. automethod:: from_qasm_file .. automethod:: from_qasm_str Data objects on circuits ======================== .. _circuit-adding-data-objects: Adding data objects ------------------- ============================= ================================================================= Method Adds this kind of data ============================= ================================================================= :meth:`add_bits` :class:`.Qubit`\\ s and :class:`.Clbit`\\ s. :meth:`add_register` :class:`.QuantumRegister` and :class:`.ClassicalRegister`. :meth:`add_var` :class:`~.expr.Var` nodes with local scope and initializers. :meth:`add_input` :class:`~.expr.Var` nodes that are treated as circuit inputs. :meth:`add_capture` :class:`~.expr.Var` nodes captured from containing scopes. :meth:`add_uninitialized_var` :class:`~.expr.Var` nodes with local scope and undefined state. ============================= ================================================================= Typically you add most of the data objects (:class:`.Qubit`, :class:`.Clbit`, :class:`.ClassicalRegister`, etc) to the circuit as part of using the :meth:`__init__` default constructor, or :meth:`copy_empty_like`. However, it is also possible to add these afterwards. Typed classical data, such as standalone :class:`~.expr.Var` nodes (see :ref:`circuit-repr-real-time-classical`), can be both constructed and added with separate methods. New registerless :class:`.Qubit` and :class:`.Clbit` objects are added using :meth:`add_bits`. These objects must not already be present in the circuit. You can check if a bit exists in the circuit already using :meth:`find_bit`. .. automethod:: add_bits Registers are added to the circuit with :meth:`add_register`. In this method, it is not an error if some of the bits are already present in the circuit. In this case, the register will be an "alias" over the bits. This is not generally well-supported by hardware backends; it is probably best to stay away from relying on it. The registers a given bit is in are part of the return of :meth:`find_bit`. .. automethod:: add_register :ref:`Real-time, typed classical data <circuit-repr-real-time-classical>` is represented on the circuit by :class:`~.expr.Var` nodes with a well-defined :class:`~.types.Type`. It is possible to instantiate these separately to a circuit (see :meth:`.Var.new`), but it is often more convenient to use circuit methods that will automatically manage the types and expression initialization for you. The two most common methods are :meth:`add_var` (locally scoped variables) and :meth:`add_input` (inputs to the circuit). .. automethod:: add_var .. automethod:: add_input In addition, there are two lower-level methods that can be useful for programmatic generation of circuits. When working interactively, you will most likely not need these; most uses of :meth:`add_uninitialized_var` are part of :meth:`copy_empty_like`, and most uses of :meth:`add_capture` would be better off using :ref:`the control-flow builder interface <circuit-control-flow-methods>`. .. automethod:: add_uninitialized_var .. automethod:: add_capture Working with bits and registers ------------------------------- A :class:`.Bit` instance is, on its own, just a unique handle for circuits to use in their own contexts. If you have got a :class:`.Bit` instance and a circuit, just can find the contexts that the bit exists in using :meth:`find_bit`, such as its integer index in the circuit and any registers it is contained in. .. automethod:: find_bit Similarly, you can query a circuit to see if a register has already been added to it by using :meth:`has_register`. .. automethod:: has_register Working with compile-time parameters ------------------------------------ .. seealso:: :ref:`circuit-compile-time-parameters` A more complete discussion of what compile-time parametrization is, and how it fits into Qiskit's data model. Unlike bits, registers, and real-time typed classical data, compile-time symbolic parameters are not manually added to a circuit. Their presence is inferred by being contained in operations added to circuits and the global phase. An ordered list of all parameters currently in a circuit is at :attr:`QuantumCircuit.parameters`. The most common operation on :class:`.Parameter` instances is to replace them in symbolic operations with some numeric value, or another symbolic expression. This is done with :meth:`assign_parameters`. .. automethod:: assign_parameters The circuit tracks parameters by :class:`.Parameter` instances themselves, and forbids having multiple parameters of the same name to avoid some problems when interoperating with OpenQASM or other external formats. You can use :meth:`has_parameter` and :meth:`get_parameter` to query the circuit for a parameter with the given string name. .. automethod:: has_parameter .. automethod:: get_parameter .. _circuit-real-time-methods: Working with real-time typed classical data ------------------------------------------- .. seealso:: :mod:`qiskit.circuit.classical` Module-level documentation for how the variable-, expression- and type-systems work, the objects used to represent them, and the classical operations available. :ref:`circuit-repr-real-time-classical` A discussion of how real-time data fits into the entire :mod:`qiskit.circuit` data model as a whole. :ref:`circuit-adding-data-objects` The methods for adding new :class:`~.expr.Var` variables to a circuit after initialization. You can retrive a :class:`~.expr.Var` instance attached to a circuit by using its variable name using :meth:`get_var`, or check if a circuit contains a given variable with :meth:`has_var`. .. automethod:: get_var .. automethod:: has_var There are also several iterator methods that you can use to get the full set of variables tracked by a circuit. At least one of :meth:`iter_input_vars` and :meth:`iter_captured_vars` will be empty, as inputs and captures are mutually exclusive. All of the iterators have corresponding dynamic properties on :class:`QuantumCircuit` that contain their length: :attr:`num_vars`, :attr:`num_input_vars`, :attr:`num_captured_vars` and :attr:`num_declared_vars`. .. automethod:: iter_vars .. automethod:: iter_input_vars .. automethod:: iter_captured_vars .. automethod:: iter_declared_vars .. _circuit-adding-operations: Adding operations to circuits ============================= You can add anything that implements the :class:`.Operation` interface to a circuit as a single instruction, though most things you will want to add will be :class:`~.circuit.Instruction` or :class:`~.circuit.Gate` instances. .. seealso:: :ref:`circuit-operations-instructions` The :mod:`qiskit.circuit`-level documentation on the different interfaces that Qiskit uses to define circuit-level instructions. .. _circuit-append-compose: Methods to add general operations --------------------------------- These are the base methods that handle adding any object, including user-defined ones, onto circuits. =============== =============================================================================== Method When to use it =============== =============================================================================== :meth:`append` Add an instruction as a single object onto a circuit. :meth:`_append` Same as :meth:`append`, but a low-level interface that elides almost all error checking. :meth:`compose` Inline the instructions from one circuit onto another. :meth:`tensor` Like :meth:`compose`, but strictly for joining circuits that act on disjoint qubits. =============== =============================================================================== :class:`QuantumCircuit` has two main ways that you will add more operations onto a circuit. Which to use depends on whether you want to add your object as a single "instruction" (:meth:`append`), or whether you want to join the instructions from two circuits together (:meth:`compose`). A single instruction or operation appears as a single entry in the :attr:`data` of the circuit, and as a single box when drawn in the circuit visualizers (see :meth:`draw`). A single instruction is the "unit" that a hardware backend might be defined in terms of (see :class:`.Target`). An :class:`~.circuit.Instruction` can come with a :attr:`~.circuit.Instruction.definition`, which is one rule the transpiler (see :mod:`qiskit.transpiler`) will be able to fall back on to decompose it for hardware, if needed. An :class:`.Operation` that is not also an :class:`~.circuit.Instruction` can only be decomposed if it has some associated high-level synthesis method registered for it (see :mod:`qiskit.transpiler.passes.synthesis.plugin`). A :class:`QuantumCircuit` alone is not a single :class:`~.circuit.Instruction`; it is rather more complicated, since it can, in general, represent a complete program with typed classical memory inputs and outputs, and control flow. Qiskit's (and most hardware's) data model does not yet have the concept of re-usable callable subroutines with virtual quantum operands. You can convert simple circuits that act only on qubits with unitary operations into a :class:`.Gate` using :meth:`to_gate`, and simple circuits acting only on qubits and clbits into a :class:`~.circuit.Instruction` with :meth:`to_instruction`. When you have an :class:`.Operation`, :class:`~.circuit.Instruction`, or :class:`.Gate`, add it to the circuit, specifying the qubit and clbit arguments with :meth:`append`. .. automethod:: append :meth:`append` does quite substantial error checking to ensure that you cannot accidentally break the data model of :class:`QuantumCircuit`. If you are programmatically generating a circuit from known-good data, you can elide much of this error checking by using the fast-path appender :meth:`_append`, but at the risk that the caller is responsible for ensuring they are passing only valid data. .. automethod:: _append In other cases, you may want to join two circuits together, applying the instructions from one circuit onto specified qubits and clbits on another circuit. This "inlining" operation is called :meth:`compose` in Qiskit. :meth:`compose` is, in general, more powerful than a :meth:`to_instruction`-plus-:meth:`append` combination for joining two circuits, because it can also link typed classical data together, and allows for circuit control-flow operations to be joined onto another circuit. The downsides to :meth:`compose` are that it is a more complex operation that can involve more rewriting of the operand, and that it necessarily must move data from one circuit object to another. If you are building up a circuit for yourself and raw performance is a core goal, consider passing around your base circuit and having different parts of your algorithm write directly to the base circuit, rather than building a temporary layer circuit. .. automethod:: compose If you are trying to join two circuits that will apply to completely disjoint qubits and clbits, :meth:`tensor` is a convenient wrapper around manually adding bit objects and calling :meth:`compose`. .. automethod:: tensor As some rules of thumb: * If you have a single :class:`.Operation`, :class:`~.circuit.Instruction` or :class:`.Gate`, you should definitely use :meth:`append` or :meth:`_append`. * If you have a :class:`QuantumCircuit` that represents a single atomic instruction for a larger circuit that you want to re-use, you probably want to call :meth:`to_instruction` or :meth:`to_gate`, and then apply the result of that to the circuit using :meth:`append`. * If you have a :class:`QuantumCircuit` that represents a larger "layer" of another circuit, or contains typed classical variables or control flow, you should use :meth:`compose` to merge it onto another circuit. * :meth:`tensor` is wanted far more rarely than either :meth:`append` or :meth:`compose`. Internally, it is mostly a wrapper around :meth:`add_bits` and :meth:`compose`. Some potential pitfalls to beware of: * Even if you re-use a custom :class:`~.circuit.Instruction` during circuit construction, the transpiler will generally have to "unroll" each invocation of it to its inner decomposition before beginning work on it. This should not prevent you from using the :meth:`to_instruction`-plus-:meth:`append` pattern, as the transpiler will improve in this regard over time. * :meth:`compose` will, by default, produce a new circuit for backwards compatibility. This is more expensive, and not usually what you want, so you should set ``inplace=True``. * Both :meth:`append` and :meth:`compose` (but not :meth:`_append`) have a ``copy`` keyword argument that defaults to ``True``. In these cases, the incoming :class:`.Operation` instances will be copied if Qiskit detects that the objects have mutability about them (such as taking gate parameters). If you are sure that you will not re-use the objects again in other places, you should set ``copy=False`` to prevent this copying, which can be a substantial speed-up for large objects. Methods to add standard instructions ------------------------------------ The :class:`QuantumCircuit` class has helper methods to add many of the Qiskit standard-library instructions and gates onto a circuit. These are generally equivalent to manually constructing an instance of the relevent :mod:`qiskit.circuit.library` object, then passing that to :meth:`append` with the remaining arguments placed into the ``qargs`` and ``cargs`` fields as appropriate. The following methods apply special non-unitary :class:`~.circuit.Instruction` operations to the circuit: =============================== ==================================================== :class:`QuantumCircuit` method :mod:`qiskit.circuit` :class:`~.circuit.Instruction` =============================== ==================================================== :meth:`barrier` :class:`Barrier` :meth:`delay` :class:`Delay` :meth:`initialize` :class:`~library.Initialize` :meth:`measure` :class:`Measure` :meth:`reset` :class:`Reset` :meth:`store` :class:`Store` =============================== ==================================================== These methods apply uncontrolled unitary :class:`.Gate` instances to the circuit: =============================== ============================================ :class:`QuantumCircuit` method :mod:`qiskit.circuit.library` :class:`.Gate` =============================== ============================================ :meth:`dcx` :class:`~library.DCXGate` :meth:`ecr` :class:`~library.ECRGate` :meth:`h` :class:`~library.HGate` :meth:`id` :class:`~library.IGate` :meth:`iswap` :class:`~library.iSwapGate` :meth:`ms` :class:`~library.MSGate` :meth:`p` :class:`~library.PhaseGate` :meth:`pauli` :class:`~library.PauliGate` :meth:`prepare_state` :class:`~library.StatePreparation` :meth:`r` :class:`~library.RGate` :meth:`rcccx` :class:`~library.RC3XGate` :meth:`rccx` :class:`~library.RCCXGate` :meth:`rv` :class:`~library.RVGate` :meth:`rx` :class:`~library.RXGate` :meth:`rxx` :class:`~library.RXXGate` :meth:`ry` :class:`~library.RYGate` :meth:`ryy` :class:`~library.RYYGate` :meth:`rz` :class:`~library.RZGate` :meth:`rzx` :class:`~library.RZXGate` :meth:`rzz` :class:`~library.RZZGate` :meth:`s` :class:`~library.SGate` :meth:`sdg` :class:`~library.SdgGate` :meth:`swap` :class:`~library.SwapGate` :meth:`sx` :class:`~library.SXGate` :meth:`sxdg` :class:`~library.SXdgGate` :meth:`t` :class:`~library.TGate` :meth:`tdg` :class:`~library.TdgGate` :meth:`u` :class:`~library.UGate` :meth:`unitary` :class:`~library.UnitaryGate` :meth:`x` :class:`~library.XGate` :meth:`y` :class:`~library.YGate` :meth:`z` :class:`~library.ZGate` =============================== ============================================ The following methods apply :class:`Gate` instances that are also controlled gates, so are direct subclasses of :class:`ControlledGate`: =============================== ====================================================== :class:`QuantumCircuit` method :mod:`qiskit.circuit.library` :class:`.ControlledGate` =============================== ====================================================== :meth:`ccx` :class:`~library.CCXGate` :meth:`ccz` :class:`~library.CCZGate` :meth:`ch` :class:`~library.CHGate` :meth:`cp` :class:`~library.CPhaseGate` :meth:`crx` :class:`~library.CRXGate` :meth:`cry` :class:`~library.CRYGate` :meth:`crz` :class:`~library.CRZGate` :meth:`cs` :class:`~library.CSGate` :meth:`csdg` :class:`~library.CSdgGate` :meth:`cswap` :class:`~library.CSwapGate` :meth:`csx` :class:`~library.CSXGate` :meth:`cu` :class:`~library.CUGate` :meth:`cx` :class:`~library.CXGate` :meth:`cy` :class:`~library.CYGate` :meth:`cz` :class:`~library.CZGate` =============================== ====================================================== Finally, these methods apply particular generalized multiply controlled gates to the circuit, often with eager syntheses. They are listed in terms of the *base* gate they are controlling, since their exact output is often a synthesized version of a gate. =============================== ================================================= :class:`QuantumCircuit` method Base :mod:`qiskit.circuit.library` :class:`.Gate` =============================== ================================================= :meth:`mcp` :class:`~library.PhaseGate` :meth:`mcrx` :class:`~library.RXGate` :meth:`mcry` :class:`~library.RYGate` :meth:`mcrz` :class:`~library.RZGate` :meth:`mcx` :class:`~library.XGate` =============================== ================================================= The rest of this section is the API listing of all the individual methods; the tables above are summaries whose links will jump you to the correct place. .. automethod:: barrier .. automethod:: ccx .. automethod:: ccz .. automethod:: ch .. automethod:: cp .. automethod:: crx .. automethod:: cry .. automethod:: crz .. automethod:: cs .. automethod:: csdg .. automethod:: cswap .. automethod:: csx .. automethod:: cu .. automethod:: cx .. automethod:: cy .. automethod:: cz .. automethod:: dcx .. automethod:: delay .. automethod:: ecr .. automethod:: h .. automethod:: id .. automethod:: initialize .. automethod:: iswap .. automethod:: mcp .. automethod:: mcrx .. automethod:: mcry .. automethod:: mcrz .. automethod:: mcx .. automethod:: measure .. automethod:: ms .. automethod:: p .. automethod:: pauli .. automethod:: prepare_state .. automethod:: r .. automethod:: rcccx .. automethod:: rccx .. automethod:: reset .. automethod:: rv .. automethod:: rx .. automethod:: rxx .. automethod:: ry .. automethod:: ryy .. automethod:: rz .. automethod:: rzx .. automethod:: rzz .. automethod:: s .. automethod:: sdg .. automethod:: store .. automethod:: swap .. automethod:: sx .. automethod:: sxdg .. automethod:: t .. automethod:: tdg .. automethod:: u .. automethod:: unitary .. automethod:: x .. automethod:: y .. automethod:: z .. _circuit-control-flow-methods: Adding control flow to circuits ------------------------------- .. seealso:: :ref:`circuit-control-flow-repr` Discussion of how control-flow operations are represented in the whole :mod:`qiskit.circuit` context. ============================== ================================================================ :class:`QuantumCircuit` method Control-flow instruction ============================== ================================================================ :meth:`if_test` :class:`.IfElseOp` with only a ``True`` body. :meth:`if_else` :class:`.IfElseOp` with both ``True`` and ``False`` bodies. :meth:`while_loop` :class:`.WhileLoopOp`. :meth:`switch` :class:`.SwitchCaseOp`. :meth:`for_loop` :class:`.ForLoopOp`. :meth:`break_loop` :class:`.BreakLoopOp`. :meth:`continue_loop` :class:`.ContinueLoopOp`. ============================== ================================================================ :class:`QuantumCircuit` has corresponding methods for all of the control-flow operations that are supported by Qiskit. These have two forms for calling them. The first is a very straightfowards convenience wrapper that takes in the block bodies of the instructions as :class:`QuantumCircuit` arguments, and simply constructs and appends the corresponding :class:`.ControlFlowOp`. The second form, which we strongly recommend you use for constructing control flow, is called *the builder interface*. Here, the methods take only the real-time discriminant of the operation, and return `context managers <https://docs.python.org/3/library/stdtypes.html#typecontextmanager>`__ that you enter using ``with``. You can then use regular :class:`QuantumCircuit` methods within those blocks to build up the control-flow bodies, and Qiskit will automatically track which of the data resources are needed for the inner blocks, building the complete :class:`.ControlFlowOp` as you leave the ``with`` statement. It is far simpler and less error-prone to build control flow programmatically this way. .. TODO: expand the examples of the builder interface. .. automethod:: break_loop .. automethod:: continue_loop .. automethod:: for_loop .. automethod:: if_else .. automethod:: if_test .. automethod:: switch .. automethod:: while_loop Converting circuits to single objects ------------------------------------- As discussed in :ref:`circuit-append-compose`, you can convert a circuit to either an :class:`~.circuit.Instruction` or a :class:`.Gate` using two helper methods. .. automethod:: to_instruction .. automethod:: to_gate Helper mutation methods ----------------------- There are two higher-level methods on :class:`QuantumCircuit` for appending measurements to the end of a circuit. Note that by default, these also add an extra register. .. automethod:: measure_active .. automethod:: measure_all There are two "subtractive" methods on :class:`QuantumCircuit` as well. This is not a use-case that :class:`QuantumCircuit` is designed for; typically you should just look to use :meth:`copy_empty_like` in place of :meth:`clear`, and run :meth:`remove_final_measurements` as its transpiler-pass form :class:`.RemoveFinalMeasurements`. .. automethod:: clear .. automethod:: remove_final_measurements .. _circuit-calibrations: Manual calibration of instructions ---------------------------------- :class:`QuantumCircuit` can store :attr:`calibrations` of instructions that define the pulses used to run them on one particular hardware backend. You can .. automethod:: add_calibration .. automethod:: has_calibration_for Circuit properties ================== Simple circuit metrics ---------------------- When constructing quantum circuits, there are several properties that help quantify the "size" of the circuits, and their ability to be run on a noisy quantum device. Some of these, like number of qubits, are straightforward to understand, while others like depth and number of tensor components require a bit more explanation. Here we will explain all of these properties, and, in preparation for understanding how circuits change when run on actual devices, highlight the conditions under which they change. Consider the following circuit: .. plot:: :include-source: from qiskit import QuantumCircuit qc = QuantumCircuit(12) for idx in range(5): qc.h(idx) qc.cx(idx, idx+5) qc.cx(1, 7) qc.x(8) qc.cx(1, 9) qc.x(7) qc.cx(1, 11) qc.swap(6, 11) qc.swap(6, 9) qc.swap(6, 10) qc.x(6) qc.draw('mpl') From the plot, it is easy to see that this circuit has 12 qubits, and a collection of Hadamard, CNOT, X, and SWAP gates. But how to quantify this programmatically? Because we can do single-qubit gates on all the qubits simultaneously, the number of qubits in this circuit is equal to the :meth:`width` of the circuit:: assert qc.width() == 12 We can also just get the number of qubits directly using :attr:`num_qubits`:: assert qc.num_qubits == 12 .. important:: For a quantum circuit composed from just qubits, the circuit width is equal to the number of qubits. This is the definition used in quantum computing. However, for more complicated circuits with classical registers, and classically controlled gates, this equivalence breaks down. As such, from now on we will not refer to the number of qubits in a quantum circuit as the width. It is also straightforward to get the number and type of the gates in a circuit using :meth:`count_ops`:: qc.count_ops() .. parsed-literal:: OrderedDict([('cx', 8), ('h', 5), ('x', 3), ('swap', 3)]) We can also get just the raw count of operations by computing the circuits :meth:`size`:: assert qc.size() == 19 A particularly important circuit property is known as the circuit :meth:`depth`. The depth of a quantum circuit is a measure of how many "layers" of quantum gates, executed in parallel, it takes to complete the computation defined by the circuit. Because quantum gates take time to implement, the depth of a circuit roughly corresponds to the amount of time it takes the quantum computer to execute the circuit. Thus, the depth of a circuit is one important quantity used to measure if a quantum circuit can be run on a device. The depth of a quantum circuit has a mathematical definition as the longest path in a directed acyclic graph (DAG). However, such a definition is a bit hard to grasp, even for experts. Fortunately, the depth of a circuit can be easily understood by anyone familiar with playing `Tetris <https://en.wikipedia.org/wiki/Tetris>`_. Lets see how to compute this graphically: .. image:: /source_images/depth.gif We can verify our graphical result using :meth:`QuantumCircuit.depth`:: assert qc.depth() == 9 .. automethod:: count_ops .. automethod:: depth .. automethod:: get_instructions .. automethod:: num_connected_components .. automethod:: num_nonlocal_gates .. automethod:: num_tensor_factors .. automethod:: num_unitary_factors .. automethod:: size .. automethod:: width Accessing scheduling information -------------------------------- If a :class:`QuantumCircuit` has been scheduled as part of a transpilation pipeline, the timing information for individual qubits can be accessed. The whole-circuit timing information is available through the :attr:`duration`, :attr:`unit` and :attr:`op_start_times` attributes. .. automethod:: qubit_duration .. automethod:: qubit_start_time .. automethod:: qubit_stop_time Instruction-like methods ======================== .. These methods really shouldn't be on `QuantumCircuit` at all. They're generally more appropriate as `Instruction` or `Gate` methods. `reverse_ops` shouldn't be a method _full stop_---it was copying a `DAGCircuit` method from an implementation detail of the original `SabreLayout` pass in Qiskit. :class:`QuantumCircuit` also contains a small number of methods that are very :class:`~.circuit.Instruction`-like in detail. You may well find better integration and more API support if you first convert your circuit to an :class:`~.circuit.Instruction` (:meth:`to_instruction`) or :class:`.Gate` (:meth:`to_gate`) as appropriate, then call the corresponding method. .. automethod:: control .. automethod:: inverse .. automethod:: power .. automethod:: repeat .. automethod:: reverse_ops Visualization ============= Qiskit includes some drawing tools to give you a quick feel for what your circuit looks like. This tooling is primarily targeted at producing either a `Matplotlib <https://matplotlib.org/>`__- or text-based drawing. There is also a lesser-featured LaTeX backend for drawing, but this is only for simple circuits, and is not as actively maintained. .. seealso:: :mod:`qiskit.visualization` The primary documentation for all of Qiskit's visualization tooling. .. automethod:: draw In addition to the core :meth:`draw` driver, there are two visualization-related helper methods, which are mostly useful for quickly unwrapping some inner instructions or reversing the :ref:`qubit-labelling conventions <circuit-conventions>` in the drawing. For more general mutation, including basis-gate rewriting, you should use the transpiler (:mod:`qiskit.transpiler`). .. automethod:: decompose .. automethod:: reverse_bits Internal utilities ================== These functions are not intended for public use, but were accidentally left documented in the public API during the 1.0 release. They will be removed in Qiskit 2.0, but will be supported until then. .. automethod:: cast .. automethod:: cbit_argument_conversion .. automethod:: cls_instances .. automethod:: cls_prefix .. automethod:: qbit_argument_conversion """ instances = 0 prefix = "circuit" def __init__( self, *regs: Register | int | Sequence[Bit], name: str | None = None, global_phase: ParameterValueType = 0, metadata: dict | None = None, inputs: Iterable[expr.Var] = (), captures: Iterable[expr.Var] = (), declarations: Mapping[expr.Var, expr.Expr] | Iterable[Tuple[expr.Var, expr.Expr]] = (), ): """ Default constructor of :class:`QuantumCircuit`. .. `QuantumCirucit` documents its `__init__` method explicitly, unlike most classes where it's implicitly appended to the class-level documentation, just because the class is so huge and has a lot of introductory material to its class docstring. Args: regs: The registers to be included in the circuit. * If a list of :class:`~.Register` objects, represents the :class:`.QuantumRegister` and/or :class:`.ClassicalRegister` objects to include in the circuit. For example: * ``QuantumCircuit(QuantumRegister(4))`` * ``QuantumCircuit(QuantumRegister(4), ClassicalRegister(3))`` * ``QuantumCircuit(QuantumRegister(4, 'qr0'), QuantumRegister(2, 'qr1'))`` * If a list of ``int``, the amount of qubits and/or classical bits to include in the circuit. It can either be a single int for just the number of quantum bits, or 2 ints for the number of quantum bits and classical bits, respectively. For example: * ``QuantumCircuit(4) # A QuantumCircuit with 4 qubits`` * ``QuantumCircuit(4, 3) # A QuantumCircuit with 4 qubits and 3 classical bits`` * If a list of python lists containing :class:`.Bit` objects, a collection of :class:`.Bit` s to be added to the circuit. name: the name of the quantum circuit. If not set, an automatically generated string will be assigned. global_phase: The global phase of the circuit in radians. metadata: Arbitrary key value metadata to associate with the circuit. This gets stored as free-form data in a dict in the :attr:`~qiskit.circuit.QuantumCircuit.metadata` attribute. It will not be directly used in the circuit. inputs: any variables to declare as ``input`` runtime variables for this circuit. These should already be existing :class:`.expr.Var` nodes that you build from somewhere else; if you need to create the inputs as well, use :meth:`QuantumCircuit.add_input`. The variables given in this argument will be passed directly to :meth:`add_input`. A circuit cannot have both ``inputs`` and ``captures``. captures: any variables that that this circuit scope should capture from a containing scope. The variables given here will be passed directly to :meth:`add_capture`. A circuit cannot have both ``inputs`` and ``captures``. declarations: any variables that this circuit should declare and initialize immediately. You can order this input so that later declarations depend on earlier ones (including inputs or captures). If you need to depend on values that will be computed later at runtime, use :meth:`add_var` at an appropriate point in the circuit execution. This argument is intended for convenient circuit initialization when you already have a set of created variables. The variables used here will be directly passed to :meth:`add_var`, which you can use directly if this is the first time you are creating the variable. Raises: CircuitError: if the circuit name, if given, is not valid. CircuitError: if both ``inputs`` and ``captures`` are given. """ if any(not isinstance(reg, (list, QuantumRegister, ClassicalRegister)) for reg in regs): # check if inputs are integers, but also allow e.g. 2.0 try: valid_reg_size = all(reg == int(reg) for reg in regs) except (ValueError, TypeError): valid_reg_size = False if not valid_reg_size: raise CircuitError( "Circuit args must be Registers or integers. (" f"{[type(reg).__name__ for reg in regs]} '{regs}' was " "provided)" ) regs = tuple(int(reg) for reg in regs) # cast to int self._base_name = None self.name: str """A human-readable name for the circuit.""" if name is None: self._base_name = self._cls_prefix() self._name_update() elif not isinstance(name, str): raise CircuitError( "The circuit name should be a string (or None to auto-generate a name)." ) else: self._base_name = name self.name = name self._increment_instances() # An explicit implementation of the circuit scope builder interface used to dispatch appends # and the like to the relevant control-flow scope. self._builder_api = _OuterCircuitScopeInterface(self) self._op_start_times = None # A stack to hold the instruction sets that are being built up during for-, if- and # while-block construction. These are stored as a stripped down sequence of instructions, # and sets of qubits and clbits, rather than a full QuantumCircuit instance because the # builder interfaces need to wait until they are completed before they can fill in things # like `break` and `continue`. This is because these instructions need to "operate" on the # full width of bits, but the builder interface won't know what bits are used until the end. self._control_flow_scopes: list[ "qiskit.circuit.controlflow.builder.ControlFlowBuilderBlock" ] = [] self.qregs: list[QuantumRegister] = [] """A list of the :class:`QuantumRegister`\\ s in this circuit. You should not mutate this.""" self.cregs: list[ClassicalRegister] = [] """A list of the :class:`ClassicalRegister`\\ s in this circuit. You should not mutate this.""" # Dict mapping Qubit or Clbit instances to tuple comprised of 0) the # corresponding index in circuit.{qubits,clbits} and 1) a list of # Register-int pairs for each Register containing the Bit and its index # within that register. self._qubit_indices: dict[Qubit, BitLocations] = {} self._clbit_indices: dict[Clbit, BitLocations] = {} # Data contains a list of instructions and their contexts, # in the order they were applied. self._data: CircuitData = CircuitData() self._ancillas: list[AncillaQubit] = [] self._calibrations: DefaultDict[str, dict[tuple, Any]] = defaultdict(dict) self.add_register(*regs) self._layout = None self.global_phase = global_phase # Add classical variables. Resolve inputs and captures first because they can't depend on # anything, but declarations might depend on them. self._vars_input: dict[str, expr.Var] = {} self._vars_capture: dict[str, expr.Var] = {} self._vars_local: dict[str, expr.Var] = {} for input_ in inputs: self.add_input(input_) for capture in captures: self.add_capture(capture) if isinstance(declarations, Mapping): declarations = declarations.items() for var, initial in declarations: self.add_var(var, initial) self.duration: int | float | None = None """The total duration of the circuit, set by a scheduling transpiler pass. Its unit is specified by :attr:`unit`.""" self.unit = "dt" """The unit that :attr:`duration` is specified in.""" self.metadata = {} if metadata is None else metadata """Arbitrary user-defined metadata for the circuit. Qiskit will not examine the content of this mapping, but it will pass it through the transpiler and reattach it to the output, so you can track your own metadata.""" @classmethod def _from_circuit_data(cls, data: CircuitData) -> typing.Self: """A private constructor from rust space circuit data.""" out = QuantumCircuit() out._data = data out._qubit_indices = {bit: BitLocations(index, []) for index, bit in enumerate(data.qubits)} out._clbit_indices = {bit: BitLocations(index, []) for index, bit in enumerate(data.clbits)} return out @staticmethod def from_instructions( instructions: Iterable[ CircuitInstruction | tuple[qiskit.circuit.Instruction] | tuple[qiskit.circuit.Instruction, Iterable[Qubit]] | tuple[qiskit.circuit.Instruction, Iterable[Qubit], Iterable[Clbit]] ], *, qubits: Iterable[Qubit] = (), clbits: Iterable[Clbit] = (), name: str | None = None, global_phase: ParameterValueType = 0, metadata: dict | None = None, ) -> "QuantumCircuit": """Construct a circuit from an iterable of :class:`.CircuitInstruction`\\ s. Args: instructions: The instructions to add to the circuit. qubits: Any qubits to add to the circuit. This argument can be used, for example, to enforce a particular ordering of qubits. clbits: Any classical bits to add to the circuit. This argument can be used, for example, to enforce a particular ordering of classical bits. name: The name of the circuit. global_phase: The global phase of the circuit in radians. metadata: Arbitrary key value metadata to associate with the circuit. Returns: The quantum circuit. """ circuit = QuantumCircuit(name=name, global_phase=global_phase, metadata=metadata) added_qubits = set() added_clbits = set() if qubits: qubits = list(qubits) circuit.add_bits(qubits) added_qubits.update(qubits) if clbits: clbits = list(clbits) circuit.add_bits(clbits) added_clbits.update(clbits) for instruction in instructions: if not isinstance(instruction, CircuitInstruction): instruction = CircuitInstruction(*instruction) qubits = [qubit for qubit in instruction.qubits if qubit not in added_qubits] clbits = [clbit for clbit in instruction.clbits if clbit not in added_clbits] circuit.add_bits(qubits) circuit.add_bits(clbits) added_qubits.update(qubits) added_clbits.update(clbits) circuit._append(instruction) return circuit @property def layout(self) -> Optional[TranspileLayout]: r"""Return any associated layout information about the circuit This attribute contains an optional :class:`~.TranspileLayout` object. This is typically set on the output from :func:`~.transpile` or :meth:`.PassManager.run` to retain information about the permutations caused on the input circuit by transpilation. There are two types of permutations caused by the :func:`~.transpile` function, an initial layout which permutes the qubits based on the selected physical qubits on the :class:`~.Target`, and a final layout which is an output permutation caused by :class:`~.SwapGate`\s inserted during routing. """ return self._layout @property def data(self) -> QuantumCircuitData: """The circuit data (instructions and context). Returns: QuantumCircuitData: a list-like object containing the :class:`.CircuitInstruction`\\ s for each instruction. """ return QuantumCircuitData(self) @data.setter def data(self, data_input: Iterable): """Sets the circuit data from a list of instructions and context. Args: data_input (Iterable): A sequence of instructions with their execution contexts. The elements must either be instances of :class:`.CircuitInstruction` (preferred), or a 3-tuple of ``(instruction, qargs, cargs)`` (legacy). In the legacy format, ``instruction`` must be an :class:`~.circuit.Instruction`, while ``qargs`` and ``cargs`` must be iterables of :class:`~.circuit.Qubit` or :class:`.Clbit` specifiers (similar to the allowed forms in calls to :meth:`append`). """ # If data_input is QuantumCircuitData(self), clearing self._data # below will also empty data_input, so make a shallow copy first. if isinstance(data_input, CircuitData): data_input = data_input.copy() else: data_input = list(data_input) self._data.clear() # Repopulate the parameter table with any global-phase entries. self.global_phase = self.global_phase if not data_input: return if isinstance(data_input[0], CircuitInstruction): for instruction in data_input: self.append(instruction, copy=False) else: for instruction, qargs, cargs in data_input: self.append(instruction, qargs, cargs, copy=False) @property def op_start_times(self) -> list[int]: """Return a list of operation start times. This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit. Returns: List of integers representing instruction start times. The index corresponds to the index of instruction in :attr:`QuantumCircuit.data`. Raises: AttributeError: When circuit is not scheduled. """ if self._op_start_times is None: raise AttributeError( "This circuit is not scheduled. " "To schedule it run the circuit through one of the transpiler scheduling passes." ) return self._op_start_times @property def calibrations(self) -> dict: """Return calibration dictionary. The custom pulse definition of a given gate is of the form ``{'gate_name': {(qubits, params): schedule}}`` """ return dict(self._calibrations) @calibrations.setter def calibrations(self, calibrations: dict): """Set the circuit calibration data from a dictionary of calibration definition. Args: calibrations (dict): A dictionary of input in the format ``{'gate_name': {(qubits, gate_params): schedule}}`` """ self._calibrations = defaultdict(dict, calibrations) def has_calibration_for(self, instruction: CircuitInstruction | tuple): """Return True if the circuit has a calibration defined for the instruction context. In this case, the operation does not need to be translated to the device basis. """ if isinstance(instruction, CircuitInstruction): operation = instruction.operation qubits = instruction.qubits else: operation, qubits, _ = instruction if not self.calibrations or operation.name not in self.calibrations: return False qubits = tuple(self.qubits.index(qubit) for qubit in qubits) params = [] for p in operation.params: if isinstance(p, ParameterExpression) and not p.parameters: params.append(float(p)) else: params.append(p) params = tuple(params) return (qubits, params) in self.calibrations[operation.name] @property def metadata(self) -> dict: """The user provided metadata associated with the circuit. The metadata for the circuit is a user provided ``dict`` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit. """ return self._metadata @metadata.setter def metadata(self, metadata: dict): """Update the circuit metadata""" if not isinstance(metadata, dict): raise TypeError("Only a dictionary is accepted for circuit metadata") self._metadata = metadata def __str__(self) -> str: return str(self.draw(output="text")) def __eq__(self, other) -> bool: if not isinstance(other, QuantumCircuit): return False # TODO: remove the DAG from this function from qiskit.converters import circuit_to_dag return circuit_to_dag(self, copy_operations=False) == circuit_to_dag( other, copy_operations=False ) def __deepcopy__(self, memo=None): # This is overridden to minimize memory pressure when we don't # actually need to pickle (i.e. the typical deepcopy case). # Note: # This is done here instead of in CircuitData since PyO3 # doesn't include a native way to recursively call # copy.deepcopy(memo). cls = self.__class__ result = cls.__new__(cls) for k in self.__dict__.keys() - {"_data", "_builder_api"}: setattr(result, k, _copy.deepcopy(self.__dict__[k], memo)) result._builder_api = _OuterCircuitScopeInterface(result) # Avoids pulling self._data into a Python list # like we would when pickling. result._data = self._data.copy(deepcopy=True) result._data.replace_bits( qubits=_copy.deepcopy(self._data.qubits, memo), clbits=_copy.deepcopy(self._data.clbits, memo), ) return result @classmethod def _increment_instances(cls): cls.instances += 1 @classmethod @deprecate_func( since=1.2, removal_timeline="in the 2.0 release", additional_msg="This method is only used as an internal helper " "and will be removed with no replacement.", ) def cls_instances(cls) -> int: """Return the current number of instances of this class, useful for auto naming.""" return cls.instances @classmethod def _cls_instances(cls) -> int: """Return the current number of instances of this class, useful for auto naming.""" return cls.instances @classmethod @deprecate_func( since=1.2, removal_timeline="in the 2.0 release", additional_msg="This method is only used as an internal helper " "and will be removed with no replacement.", ) def cls_prefix(cls) -> str: """Return the prefix to use for auto naming.""" return cls.prefix @classmethod def _cls_prefix(cls) -> str: """Return the prefix to use for auto naming.""" return cls.prefix def _name_update(self) -> None: """update name of instance using instance number""" if not is_main_process(): pid_name = f"-{mp.current_process().pid}" else: pid_name = "" self.name = f"{self._base_name}-{self._cls_instances()}{pid_name}" def has_register(self, register: Register) -> bool: """ Test if this circuit has the register r. Args: register (Register): a quantum or classical register. Returns: bool: True if the register is contained in this circuit. """ has_reg = False if isinstance(register, QuantumRegister) and register in self.qregs: has_reg = True elif isinstance(register, ClassicalRegister) and register in self.cregs: has_reg = True return has_reg def reverse_ops(self) -> "QuantumCircuit": """Reverse the circuit by reversing the order of instructions. This is done by recursively reversing all instructions. It does not invert (adjoint) any gate. Returns: QuantumCircuit: the reversed circuit. Examples: input: .. parsed-literal:: ┌───┐ q_0: ┤ H ├─────■────── └───┘┌────┴─────┐ q_1: ─────┤ RX(1.57) ├ └──────────┘ output: .. parsed-literal:: ┌───┐ q_0: ─────■──────┤ H ├ ┌────┴─────┐└───┘ q_1: ┤ RX(1.57) ├───── └──────────┘ """ reverse_circ = self.copy_empty_like(self.name + "_reverse") for instruction in reversed(self.data): reverse_circ._append(instruction.replace(operation=instruction.operation.reverse_ops())) reverse_circ.duration = self.duration reverse_circ.unit = self.unit return reverse_circ def reverse_bits(self) -> "QuantumCircuit": """Return a circuit with the opposite order of wires. The circuit is "vertically" flipped. If a circuit is defined over multiple registers, the resulting circuit will have the same registers but with their order flipped. This method is useful for converting a circuit written in little-endian convention to the big-endian equivalent, and vice versa. Returns: QuantumCircuit: the circuit with reversed bit order. Examples: input: .. parsed-literal:: ┌───┐ a_0: ┤ H ├──■───────────────── └───┘┌─┴─┐ a_1: ─────┤ X ├──■──────────── └───┘┌─┴─┐ a_2: ──────────┤ X ├──■─────── └───┘┌─┴─┐ b_0: ───────────────┤ X ├──■── └───┘┌─┴─┐ b_1: ────────────────────┤ X ├ └───┘ output: .. parsed-literal:: ┌───┐ b_0: ────────────────────┤ X ├ ┌───┐└─┬─┘ b_1: ───────────────┤ X ├──■── ┌───┐└─┬─┘ a_0: ──────────┤ X ├──■─────── ┌───┐└─┬─┘ a_1: ─────┤ X ├──■──────────── ┌───┐└─┬─┘ a_2: ┤ H ├──■───────────────── └───┘ """ circ = QuantumCircuit( list(reversed(self.qubits)), list(reversed(self.clbits)), name=self.name, global_phase=self.global_phase, ) new_qubit_map = circ.qubits[::-1] new_clbit_map = circ.clbits[::-1] for reg in reversed(self.qregs): bits = [new_qubit_map[self.find_bit(qubit).index] for qubit in reversed(reg)] circ.add_register(QuantumRegister(bits=bits, name=reg.name)) for reg in reversed(self.cregs): bits = [new_clbit_map[self.find_bit(clbit).index] for clbit in reversed(reg)] circ.add_register(ClassicalRegister(bits=bits, name=reg.name)) for instruction in self.data: qubits = [new_qubit_map[self.find_bit(qubit).index] for qubit in instruction.qubits] clbits = [new_clbit_map[self.find_bit(clbit).index] for clbit in instruction.clbits] circ._append(instruction.replace(qubits=qubits, clbits=clbits)) return circ def inverse(self, annotated: bool = False) -> "QuantumCircuit": """Invert (take adjoint of) this circuit. This is done by recursively inverting all gates. Args: annotated: indicates whether the inverse gate can be implemented as an annotated gate. Returns: QuantumCircuit: the inverted circuit Raises: CircuitError: if the circuit cannot be inverted. Examples: input: .. parsed-literal:: ┌───┐ q_0: ┤ H ├─────■────── └───┘┌────┴─────┐ q_1: ─────┤ RX(1.57) ├ └──────────┘ output: .. parsed-literal:: ┌───┐ q_0: ──────■──────┤ H ├ ┌─────┴─────┐└───┘ q_1: ┤ RX(-1.57) ├───── └───────────┘ """ inverse_circ = QuantumCircuit( self.qubits, self.clbits, *self.qregs, *self.cregs, name=self.name + "_dg", global_phase=-self.global_phase, ) for instruction in reversed(self._data): inverse_circ._append( instruction.replace(operation=instruction.operation.inverse(annotated=annotated)) ) return inverse_circ def repeat(self, reps: int, *, insert_barriers: bool = False) -> "QuantumCircuit": """Repeat this circuit ``reps`` times. Args: reps (int): How often this circuit should be repeated. insert_barriers (bool): Whether to include barriers between circuit repetitions. Returns: QuantumCircuit: A circuit containing ``reps`` repetitions of this circuit. """ repeated_circ = QuantumCircuit( self.qubits, self.clbits, *self.qregs, *self.cregs, name=self.name + f"**{reps}" ) # benefit of appending instructions: decomposing shows the subparts, i.e. the power # is actually `reps` times this circuit, and it is currently much faster than `compose`. if reps > 0: try: # try to append as gate if possible to not disallow to_gate inst: Instruction = self.to_gate() except QiskitError: inst = self.to_instruction() for i in range(reps): repeated_circ._append(inst, self.qubits, self.clbits) if insert_barriers and i != reps - 1: repeated_circ.barrier() return repeated_circ def power( self, power: float, matrix_power: bool = False, annotated: bool = False ) -> "QuantumCircuit": """Raise this circuit to the power of ``power``. If ``power`` is a positive integer and both ``matrix_power`` and ``annotated`` are ``False``, this implementation defaults to calling ``repeat``. Otherwise, the circuit is converted into a gate, and a new circuit, containing this gate raised to the given power, is returned. The gate raised to the given power is implemented either as a unitary gate if ``annotated`` is ``False`` or as an annotated operation if ``annotated`` is ``True``. Args: power (float): The power to raise this circuit to. matrix_power (bool): indicates whether the inner power gate can be implemented as a unitary gate. annotated (bool): indicates whether the inner power gate can be implemented as an annotated operation. Raises: CircuitError: If the circuit needs to be converted to a unitary gate, but is not unitary. Returns: QuantumCircuit: A circuit implementing this circuit raised to the power of ``power``. """ if ( power >= 0 and isinstance(power, (int, np.integer)) and not matrix_power and not annotated ): return self.repeat(power) # attempt conversion to gate if self.num_parameters > 0: raise CircuitError( "Cannot raise a parameterized circuit to a non-positive power " "or matrix-power, please bind the free parameters: " f"{self.parameters}" ) try: gate = self.to_gate() except QiskitError as ex: raise CircuitError( "The circuit contains non-unitary operations and cannot be " "raised to a power. Note that no qiskit.circuit.Instruction " "objects may be in the circuit for this operation." ) from ex power_circuit = QuantumCircuit(self.qubits, self.clbits, *self.qregs, *self.cregs) power_circuit.append(gate.power(power, annotated=annotated), list(range(gate.num_qubits))) return power_circuit def control( self, num_ctrl_qubits: int = 1, label: str | None = None, ctrl_state: str | int | None = None, annotated: bool = False, ) -> "QuantumCircuit": """Control this circuit on ``num_ctrl_qubits`` qubits. Args: num_ctrl_qubits (int): The number of control qubits. label (str): An optional label to give the controlled operation for visualization. ctrl_state (str or int): The control state in decimal or as a bitstring (e.g. '111'). If None, use ``2**num_ctrl_qubits - 1``. annotated: indicates whether the controlled gate should be implemented as an annotated gate. Returns: QuantumCircuit: The controlled version of this circuit. Raises: CircuitError: If the circuit contains a non-unitary operation and cannot be controlled. """ try: gate = self.to_gate() except QiskitError as ex: raise CircuitError( "The circuit contains non-unitary operations and cannot be " "controlled. Note that no qiskit.circuit.Instruction objects may " "be in the circuit for this operation." ) from ex controlled_gate = gate.control(num_ctrl_qubits, label, ctrl_state, annotated) control_qreg = QuantumRegister(num_ctrl_qubits) controlled_circ = QuantumCircuit( control_qreg, self.qubits, *self.qregs, name=f"c_{self.name}" ) controlled_circ.append(controlled_gate, controlled_circ.qubits) return controlled_circ def compose( self, other: Union["QuantumCircuit", Instruction], qubits: QubitSpecifier | Sequence[QubitSpecifier] | None = None, clbits: ClbitSpecifier | Sequence[ClbitSpecifier] | None = None, front: bool = False, inplace: bool = False, wrap: bool = False, *, copy: bool = True, var_remap: Mapping[str | expr.Var, str | expr.Var] | None = None, inline_captures: bool = False, ) -> Optional["QuantumCircuit"]: """Apply the instructions from one circuit onto specified qubits and/or clbits on another. .. note:: By default, this creates a new circuit object, leaving ``self`` untouched. For most uses of this function, it is far more efficient to set ``inplace=True`` and modify the base circuit in-place. When dealing with realtime variables (:class:`.expr.Var` instances), there are two principal strategies for using :meth:`compose`: 1. The ``other`` circuit is treated as entirely additive, including its variables. The variables in ``other`` must be entirely distinct from those in ``self`` (use ``var_remap`` to help with this), and all variables in ``other`` will be declared anew in the output with matching input/capture/local scoping to how they are in ``other``. This is generally what you want if you're joining two unrelated circuits. 2. The ``other`` circuit was created as an exact extension to ``self`` to be inlined onto it, including acting on the existing variables in their states at the end of ``self``. In this case, ``other`` should be created with all these variables to be inlined declared as "captures", and then you can use ``inline_captures=True`` in this method to link them. This is generally what you want if you're building up a circuit by defining layers on-the-fly, or rebuilding a circuit using layers taken from itself. You might find the ``vars_mode="captures"`` argument to :meth:`copy_empty_like` useful to create each layer's base, in this case. Args: other (qiskit.circuit.Instruction or QuantumCircuit): (sub)circuit or instruction to compose onto self. If not a :obj:`.QuantumCircuit`, this can be anything that :obj:`.append` will accept. qubits (list[Qubit|int]): qubits of self to compose onto. clbits (list[Clbit|int]): clbits of self to compose onto. front (bool): If ``True``, front composition will be performed. This is not possible within control-flow builder context managers. inplace (bool): If ``True``, modify the object. Otherwise, return composed circuit. copy (bool): If ``True`` (the default), then the input is treated as shared, and any contained instructions will be copied, if they might need to be mutated in the future. You can set this to ``False`` if the input should be considered owned by the base circuit, in order to avoid unnecessary copies; in this case, it is not valid to use ``other`` afterward, and some instructions may have been mutated in place. var_remap (Mapping): mapping to use to rewrite :class:`.expr.Var` nodes in ``other`` as they are inlined into ``self``. This can be used to avoid naming conflicts. Both keys and values can be given as strings or direct :class:`.expr.Var` instances. If a key is a string, it matches any :class:`~.expr.Var` with the same name. If a value is a string, whenever a new key matches a it, a new :class:`~.expr.Var` is created with the correct type. If a value is a :class:`~.expr.Var`, its :class:`~.expr.Expr.type` must exactly match that of the variable it is replacing. inline_captures (bool): if ``True``, then all "captured" :class:`~.expr.Var` nodes in the ``other`` :class:`.QuantumCircuit` are assumed to refer to variables already declared in ``self`` (as any input/capture/local type), and the uses in ``other`` will apply to the existing variables. If you want to build up a layer for an existing circuit to use with :meth:`compose`, you might find the ``vars_mode="captures"`` argument to :meth:`copy_empty_like` useful. Any remapping in ``vars_remap`` occurs before evaluating this variable inlining. If this is ``False`` (the default), then all variables in ``other`` will be required to be distinct from those in ``self``, and new declarations will be made for them. wrap (bool): If True, wraps the other circuit into a gate (or instruction, depending on whether it contains only unitary instructions) before composing it onto self. Rather than using this option, it is almost always better to manually control this yourself by using :meth:`to_instruction` or :meth:`to_gate`, and then call :meth:`append`. Returns: QuantumCircuit: the composed circuit (returns None if inplace==True). Raises: CircuitError: if no correct wire mapping can be made between the two circuits, such as if ``other`` is wider than ``self``. CircuitError: if trying to emit a new circuit while ``self`` has a partially built control-flow context active, such as the context-manager forms of :meth:`if_test`, :meth:`for_loop` and :meth:`while_loop`. CircuitError: if trying to compose to the front of a circuit when a control-flow builder block is active; there is no clear meaning to this action. Examples: .. code-block:: python >>> lhs.compose(rhs, qubits=[3, 2], inplace=True) .. parsed-literal:: ┌───┐ ┌─────┐ ┌───┐ lqr_1_0: ───┤ H ├─── rqr_0: ──■──┤ Tdg ├ lqr_1_0: ───┤ H ├─────────────── ├───┤ ┌─┴─┐└─────┘ ├───┤ lqr_1_1: ───┤ X ├─── rqr_1: ┤ X ├─────── lqr_1_1: ───┤ X ├─────────────── ┌──┴───┴──┐ └───┘ ┌──┴───┴──┐┌───┐ lqr_1_2: ┤ U1(0.1) ├ + = lqr_1_2: ┤ U1(0.1) ├┤ X ├─────── └─────────┘ └─────────┘└─┬─┘┌─────┐ lqr_2_0: ─────■───── lqr_2_0: ─────■───────■──┤ Tdg ├ ┌─┴─┐ ┌─┴─┐ └─────┘ lqr_2_1: ───┤ X ├─── lqr_2_1: ───┤ X ├─────────────── └───┘ └───┘ lcr_0: 0 ═══════════ lcr_0: 0 ═══════════════════════ lcr_1: 0 ═══════════ lcr_1: 0 ═══════════════════════ """ if inplace and front and self._control_flow_scopes: # If we're composing onto ourselves while in a stateful control-flow builder context, # there's no clear meaning to composition to the "front" of the circuit. raise CircuitError( "Cannot compose to the front of a circuit while a control-flow context is active." ) if not inplace and self._control_flow_scopes: # If we're inside a stateful control-flow builder scope, even if we successfully cloned # the partial builder scope (not simple), the scope wouldn't be controlled by an active # `with` statement, so the output circuit would be permanently broken. raise CircuitError( "Cannot emit a new composed circuit while a control-flow context is active." ) # Avoid mutating `dest` until as much of the error checking as possible is complete, to # avoid an in-place composition getting `self` in a partially mutated state for a simple # error that the user might want to correct in an interactive session. dest = self if inplace else self.copy() var_remap = {} if var_remap is None else var_remap # This doesn't use `functools.cache` so we can access it during the variable remapping of # instructions. We cache all replacement lookups for a) speed and b) to ensure that # the same variable _always_ maps to the same replacement even if it's used in different # places in the recursion tree (such as being a captured variable). def replace_var(var: expr.Var, cache: Mapping[expr.Var, expr.Var]) -> expr.Var: # This is closing over an argument to `compose`. nonlocal var_remap if out := cache.get(var): return out if (replacement := var_remap.get(var)) or (replacement := var_remap.get(var.name)): if isinstance(replacement, str): replacement = expr.Var.new(replacement, var.type) if replacement.type != var.type: raise CircuitError( f"mismatched types in replacement for '{var.name}':" f" '{var.type}' cannot become '{replacement.type}'" ) else: replacement = var cache[var] = replacement return replacement # As a special case, allow composing some clbits onto no clbits - normally the destination # has to be strictly larger. This allows composing final measurements onto unitary circuits. if isinstance(other, QuantumCircuit): if not self.clbits and other.clbits: if dest._control_flow_scopes: raise CircuitError( "cannot implicitly add clbits while within a control-flow scope" ) dest.add_bits(other.clbits) for reg in other.cregs: dest.add_register(reg) if wrap and isinstance(other, QuantumCircuit): other = ( other.to_gate() if all(isinstance(ins.operation, Gate) for ins in other.data) else other.to_instruction() ) if not isinstance(other, QuantumCircuit): if qubits is None: qubits = self.qubits[: other.num_qubits] if clbits is None: clbits = self.clbits[: other.num_clbits] if front: # Need to keep a reference to the data for use after we've emptied it. old_data = dest._data.copy(copy_instructions=copy) dest.clear() dest.append(other, qubits, clbits, copy=copy) for instruction in old_data: dest._append(instruction) else: dest.append(other, qargs=qubits, cargs=clbits, copy=copy) return None if inplace else dest if other.num_qubits > dest.num_qubits or other.num_clbits > dest.num_clbits: raise CircuitError( "Trying to compose with another QuantumCircuit which has more 'in' edges." ) # Maps bits in 'other' to bits in 'dest'. mapped_qubits: list[Qubit] mapped_clbits: list[Clbit] edge_map: dict[Qubit | Clbit, Qubit | Clbit] = {} if qubits is None: mapped_qubits = dest.qubits edge_map.update(zip(other.qubits, dest.qubits)) else: mapped_qubits = dest._qbit_argument_conversion(qubits) if len(mapped_qubits) != other.num_qubits: raise CircuitError( f"Number of items in qubits parameter ({len(mapped_qubits)}) does not" f" match number of qubits in the circuit ({other.num_qubits})." ) if len(set(mapped_qubits)) != len(mapped_qubits): raise CircuitError( f"Duplicate qubits referenced in 'qubits' parameter: '{mapped_qubits}'" ) edge_map.update(zip(other.qubits, mapped_qubits)) if clbits is None: mapped_clbits = dest.clbits edge_map.update(zip(other.clbits, dest.clbits)) else: mapped_clbits = dest._cbit_argument_conversion(clbits) if len(mapped_clbits) != other.num_clbits: raise CircuitError( f"Number of items in clbits parameter ({len(mapped_clbits)}) does not" f" match number of clbits in the circuit ({other.num_clbits})." ) if len(set(mapped_clbits)) != len(mapped_clbits): raise CircuitError( f"Duplicate clbits referenced in 'clbits' parameter: '{mapped_clbits}'" ) edge_map.update(zip(other.clbits, dest._cbit_argument_conversion(clbits))) for gate, cals in other.calibrations.items(): dest._calibrations[gate].update(cals) dest.duration = None dest.unit = "dt" dest.global_phase += other.global_phase # This is required to trigger data builds if the `other` is an unbuilt `BlueprintCircuit`, # so we can the access the complete `CircuitData` object at `_data`. _ = other.data def copy_with_remapping( source, dest, bit_map, var_map, inline_captures, new_qubits=None, new_clbits=None ): # Copy the instructions from `source` into `dest`, remapping variables in instructions # according to `var_map`. If `new_qubits` or `new_clbits` are given, the qubits and # clbits of the source instruction are remapped to those as well. for var in source.iter_input_vars(): dest.add_input(replace_var(var, var_map)) if inline_captures: for var in source.iter_captured_vars(): replacement = replace_var(var, var_map) if not dest.has_var(replace_var(var, var_map)): if var is replacement: raise CircuitError( f"Variable '{var}' to be inlined is not in the base circuit." " If you wanted it to be automatically added, use" " `inline_captures=False`." ) raise CircuitError( f"Replacement '{replacement}' for variable '{var}' is not in the" " base circuit. Is the replacement correct?" ) else: for var in source.iter_captured_vars(): dest.add_capture(replace_var(var, var_map)) for var in source.iter_declared_vars(): dest.add_uninitialized_var(replace_var(var, var_map)) def recurse_block(block): # Recurse the remapping into a control-flow block. Note that this doesn't remap the # clbits within; the story around nested classical-register-based control-flow # doesn't really work in the current data model, and we hope to replace it with # `Expr`-based control-flow everywhere. new_block = block.copy_empty_like() new_block._vars_input = {} new_block._vars_capture = {} new_block._vars_local = {} # For the recursion, we never want to inline captured variables because we're not # copying onto a base that has variables. copy_with_remapping(block, new_block, bit_map, var_map, inline_captures=False) return new_block variable_mapper = _classical_resource_map.VariableMapper( dest.cregs, bit_map, var_map, add_register=dest.add_register ) def map_vars(op): n_op = op is_control_flow = isinstance(n_op, ControlFlowOp) if ( not is_control_flow and (condition := getattr(n_op, "condition", None)) is not None ): n_op = n_op.copy() if n_op is op and copy else n_op n_op.condition = variable_mapper.map_condition(condition) elif is_control_flow: n_op = n_op.replace_blocks(recurse_block(block) for block in n_op.blocks) if isinstance(n_op, (IfElseOp, WhileLoopOp)): n_op.condition = variable_mapper.map_condition(n_op.condition) elif isinstance(n_op, SwitchCaseOp): n_op.target = variable_mapper.map_target(n_op.target) elif isinstance(n_op, Store): n_op = Store( variable_mapper.map_expr(n_op.lvalue), variable_mapper.map_expr(n_op.rvalue) ) return n_op.copy() if n_op is op and copy else n_op instructions = source._data.copy(copy_instructions=copy) instructions.replace_bits(qubits=new_qubits, clbits=new_clbits) instructions.map_nonstandard_ops(map_vars) dest._current_scope().extend(instructions) append_existing = None if front: append_existing = dest._data.copy(copy_instructions=copy) dest.clear() copy_with_remapping( other, dest, bit_map=edge_map, # The actual `Var: Var` map gets built up from the more freeform user input as we # encounter the variables, since the user might be using string keys to refer to more # than one variable in separated scopes of control-flow operations. var_map={}, inline_captures=inline_captures, new_qubits=mapped_qubits, new_clbits=mapped_clbits, ) if append_existing: dest._current_scope().extend(append_existing) return None if inplace else dest def tensor(self, other: "QuantumCircuit", inplace: bool = False) -> Optional["QuantumCircuit"]: """Tensor ``self`` with ``other``. Remember that in the little-endian convention the leftmost operation will be at the bottom of the circuit. See also `the docs <https://docs.quantum.ibm.com/build/circuit-construction>`__ for more information. .. parsed-literal:: ┌────────┐ ┌─────┐ ┌─────┐ q_0: ┤ bottom ├ ⊗ q_0: ┤ top ├ = q_0: ─┤ top ├── └────────┘ └─────┘ ┌┴─────┴─┐ q_1: ┤ bottom ├ └────────┘ Args: other (QuantumCircuit): The other circuit to tensor this circuit with. inplace (bool): If ``True``, modify the object. Otherwise return composed circuit. Examples: .. plot:: :include-source: from qiskit import QuantumCircuit top = QuantumCircuit(1) top.x(0); bottom = QuantumCircuit(2) bottom.cry(0.2, 0, 1); tensored = bottom.tensor(top) tensored.draw('mpl') Returns: QuantumCircuit: The tensored circuit (returns ``None`` if ``inplace=True``). """ num_qubits = self.num_qubits + other.num_qubits num_clbits = self.num_clbits + other.num_clbits # If a user defined both circuits with via register sizes and not with named registers # (e.g. QuantumCircuit(2, 2)) then we have a naming collision, as the registers are by # default called "q" resp. "c". To still allow tensoring we define new registers of the # correct sizes. if ( len(self.qregs) == len(other.qregs) == 1 and self.qregs[0].name == other.qregs[0].name == "q" ): # check if classical registers are in the circuit if num_clbits > 0: dest = QuantumCircuit(num_qubits, num_clbits) else: dest = QuantumCircuit(num_qubits) # handle case if ``measure_all`` was called on both circuits, in which case the # registers are both named "meas" elif ( len(self.cregs) == len(other.cregs) == 1 and self.cregs[0].name == other.cregs[0].name == "meas" ): cr = ClassicalRegister(self.num_clbits + other.num_clbits, "meas") dest = QuantumCircuit(*other.qregs, *self.qregs, cr) # Now we don't have to handle any more cases arising from special implicit naming else: dest = QuantumCircuit( other.qubits, self.qubits, other.clbits, self.clbits, *other.qregs, *self.qregs, *other.cregs, *self.cregs, ) # compose self onto the output, and then other dest.compose(other, range(other.num_qubits), range(other.num_clbits), inplace=True) dest.compose( self, range(other.num_qubits, num_qubits), range(other.num_clbits, num_clbits), inplace=True, ) # Replace information from tensored circuit into self when inplace = True if inplace: self.__dict__.update(dest.__dict__) return None return dest @property def qubits(self) -> list[Qubit]: """A list of :class:`Qubit`\\ s in the order that they were added. You should not mutate this.""" return self._data.qubits @property def clbits(self) -> list[Clbit]: """A list of :class:`Clbit`\\ s in the order that they were added. You should not mutate this.""" return self._data.clbits @property def ancillas(self) -> list[AncillaQubit]: """A list of :class:`AncillaQubit`\\ s in the order that they were added. You should not mutate this.""" return self._ancillas @property def num_vars(self) -> int: """The number of real-time classical variables in the circuit. This is the length of the :meth:`iter_vars` iterable.""" return self.num_input_vars + self.num_captured_vars + self.num_declared_vars @property def num_input_vars(self) -> int: """The number of real-time classical variables in the circuit marked as circuit inputs. This is the length of the :meth:`iter_input_vars` iterable. If this is non-zero, :attr:`num_captured_vars` must be zero.""" return len(self._vars_input) @property def num_captured_vars(self) -> int: """The number of real-time classical variables in the circuit marked as captured from an enclosing scope. This is the length of the :meth:`iter_captured_vars` iterable. If this is non-zero, :attr:`num_input_vars` must be zero.""" return len(self._vars_capture) @property def num_declared_vars(self) -> int: """The number of real-time classical variables in the circuit that are declared by this circuit scope, excluding inputs or captures. This is the length of the :meth:`iter_declared_vars` iterable.""" return len(self._vars_local) def iter_vars(self) -> typing.Iterable[expr.Var]: """Get an iterable over all real-time classical variables in scope within this circuit. This method will iterate over all variables in scope. For more fine-grained iterators, see :meth:`iter_declared_vars`, :meth:`iter_input_vars` and :meth:`iter_captured_vars`.""" if self._control_flow_scopes: builder = self._control_flow_scopes[-1] return itertools.chain(builder.iter_captured_vars(), builder.iter_local_vars()) return itertools.chain( self._vars_input.values(), self._vars_capture.values(), self._vars_local.values() ) def iter_declared_vars(self) -> typing.Iterable[expr.Var]: """Get an iterable over all real-time classical variables that are declared with automatic storage duration in this scope. This excludes input variables (see :meth:`iter_input_vars`) and captured variables (see :meth:`iter_captured_vars`).""" if self._control_flow_scopes: return self._control_flow_scopes[-1].iter_local_vars() return self._vars_local.values() def iter_input_vars(self) -> typing.Iterable[expr.Var]: """Get an iterable over all real-time classical variables that are declared as inputs to this circuit scope. This excludes locally declared variables (see :meth:`iter_declared_vars`) and captured variables (see :meth:`iter_captured_vars`).""" if self._control_flow_scopes: return () return self._vars_input.values() def iter_captured_vars(self) -> typing.Iterable[expr.Var]: """Get an iterable over all real-time classical variables that are captured by this circuit scope from a containing scope. This excludes input variables (see :meth:`iter_input_vars`) and locally declared variables (see :meth:`iter_declared_vars`).""" if self._control_flow_scopes: return self._control_flow_scopes[-1].iter_captured_vars() return self._vars_capture.values() def __and__(self, rhs: "QuantumCircuit") -> "QuantumCircuit": """Overload & to implement self.compose.""" return self.compose(rhs) def __iand__(self, rhs: "QuantumCircuit") -> "QuantumCircuit": """Overload &= to implement self.compose in place.""" self.compose(rhs, inplace=True) return self def __xor__(self, top: "QuantumCircuit") -> "QuantumCircuit": """Overload ^ to implement self.tensor.""" return self.tensor(top) def __ixor__(self, top: "QuantumCircuit") -> "QuantumCircuit": """Overload ^= to implement self.tensor in place.""" self.tensor(top, inplace=True) return self def __len__(self) -> int: """Return number of operations in circuit.""" return len(self._data) @typing.overload def __getitem__(self, item: int) -> CircuitInstruction: ... @typing.overload def __getitem__(self, item: slice) -> list[CircuitInstruction]: ... def __getitem__(self, item): """Return indexed operation.""" return self._data[item] @staticmethod @deprecate_func( since=1.2, removal_timeline="in the 2.0 release", additional_msg="This method is only used as an internal helper " "and will be removed with no replacement.", ) def cast(value: S, type_: Callable[..., T]) -> Union[S, T]: """Best effort to cast value to type. Otherwise, returns the value.""" try: return type_(value) except (ValueError, TypeError): return value @staticmethod def _cast(value: S, type_: Callable[..., T]) -> Union[S, T]: """Best effort to cast value to type. Otherwise, returns the value.""" try: return type_(value) except (ValueError, TypeError): return value @deprecate_func( since=1.2, removal_timeline="in the 2.0 release", additional_msg="This method is only used as an internal helper " "and will be removed with no replacement.", ) def qbit_argument_conversion(self, qubit_representation: QubitSpecifier) -> list[Qubit]: """ Converts several qubit representations (such as indexes, range, etc.) into a list of qubits. Args: qubit_representation: Representation to expand. Returns: The resolved instances of the qubits. """ return self._qbit_argument_conversion(qubit_representation) def _qbit_argument_conversion(self, qubit_representation: QubitSpecifier) -> list[Qubit]: """ Converts several qubit representations (such as indexes, range, etc.) into a list of qubits. Args: qubit_representation: Representation to expand. Returns: The resolved instances of the qubits. """ return _bit_argument_conversion( qubit_representation, self.qubits, self._qubit_indices, Qubit ) @deprecate_func( since=1.2, removal_timeline="in the 2.0 release", additional_msg="This method is only used as an internal helper " "and will be removed with no replacement.", ) def cbit_argument_conversion(self, clbit_representation: ClbitSpecifier) -> list[Clbit]: """ Converts several classical bit representations (such as indexes, range, etc.) into a list of classical bits. Args: clbit_representation : Representation to expand. Returns: A list of tuples where each tuple is a classical bit. """ return self._cbit_argument_conversion(clbit_representation) def _cbit_argument_conversion(self, clbit_representation: ClbitSpecifier) -> list[Clbit]: """ Converts several classical bit representations (such as indexes, range, etc.) into a list of classical bits. Args: clbit_representation: Representation to expand. Returns: A list of tuples where each tuple is a classical bit. """ return _bit_argument_conversion( clbit_representation, self.clbits, self._clbit_indices, Clbit ) def _append_standard_gate( self, op: StandardGate, qargs: Sequence[QubitSpecifier] = (), params: Sequence[ParameterValueType] = (), label: str | None = None, ) -> InstructionSet: """An internal method to bypass some checking when directly appending a standard gate.""" circuit_scope = self._current_scope() if params is None: params = [] expanded_qargs = [self._qbit_argument_conversion(qarg) for qarg in qargs or []] for param in params: Gate.validate_parameter(op, param) instructions = InstructionSet(resource_requester=circuit_scope.resolve_classical_resource) for qarg, _ in Gate.broadcast_arguments(op, expanded_qargs, []): self._check_dups(qarg) instruction = CircuitInstruction.from_standard(op, qarg, params, label=label) circuit_scope.append(instruction, _standard_gate=True) instructions._add_ref(circuit_scope.instructions, len(circuit_scope.instructions) - 1) return instructions def append( self, instruction: Operation | CircuitInstruction, qargs: Sequence[QubitSpecifier] | None = None, cargs: Sequence[ClbitSpecifier] | None = None, *, copy: bool = True, ) -> InstructionSet: """Append one or more instructions to the end of the circuit, modifying the circuit in place. The ``qargs`` and ``cargs`` will be expanded and broadcast according to the rules of the given :class:`~.circuit.Instruction`, and any non-:class:`.Bit` specifiers (such as integer indices) will be resolved into the relevant instances. If a :class:`.CircuitInstruction` is given, it will be unwrapped, verified in the context of this circuit, and a new object will be appended to the circuit. In this case, you may not pass ``qargs`` or ``cargs`` separately. Args: instruction: :class:`~.circuit.Instruction` instance to append, or a :class:`.CircuitInstruction` with all its context. qargs: specifiers of the :class:`~.circuit.Qubit`\\ s to attach instruction to. cargs: specifiers of the :class:`.Clbit`\\ s to attach instruction to. copy: if ``True`` (the default), then the incoming ``instruction`` is copied before adding it to the circuit if it contains symbolic parameters, so it can be safely mutated without affecting other circuits the same instruction might be in. If you are sure this instruction will not be in other circuits, you can set this ``False`` for a small speedup. Returns: qiskit.circuit.InstructionSet: a handle to the :class:`.CircuitInstruction`\\ s that were actually added to the circuit. Raises: CircuitError: if the operation passed is not an instance of :class:`~.circuit.Instruction` . """ if isinstance(instruction, CircuitInstruction): operation = instruction.operation qargs = instruction.qubits cargs = instruction.clbits else: operation = instruction # Convert input to instruction if not isinstance(operation, Operation): if hasattr(operation, "to_instruction"): operation = operation.to_instruction() if not isinstance(operation, Operation): raise CircuitError("operation.to_instruction() is not an Operation.") else: if issubclass(operation, Operation): raise CircuitError( "Object is a subclass of Operation, please add () to " "pass an instance of this object." ) raise CircuitError( "Object to append must be an Operation or have a to_instruction() method." ) circuit_scope = self._current_scope() # Make copy of parameterized gate instances if params := getattr(operation, "params", ()): is_parameter = False for param in params: is_parameter = is_parameter or isinstance(param, ParameterExpression) if isinstance(param, expr.Expr): param = _validate_expr(circuit_scope, param) if copy and is_parameter: operation = _copy.deepcopy(operation) if isinstance(operation, ControlFlowOp): # Verify that any variable bindings are valid. Control-flow ops are already enforced # by the class not to contain 'input' variables. if bad_captures := { var for var in itertools.chain.from_iterable( block.iter_captured_vars() for block in operation.blocks ) if not self.has_var(var) }: raise CircuitError( f"Control-flow op attempts to capture '{bad_captures}'" " which are not in this circuit" ) expanded_qargs = [self._qbit_argument_conversion(qarg) for qarg in qargs or []] expanded_cargs = [self._cbit_argument_conversion(carg) for carg in cargs or []] instructions = InstructionSet(resource_requester=circuit_scope.resolve_classical_resource) # For Operations that are non-Instructions, we use the Instruction's default method broadcast_iter = ( operation.broadcast_arguments(expanded_qargs, expanded_cargs) if isinstance(operation, Instruction) else Instruction.broadcast_arguments(operation, expanded_qargs, expanded_cargs) ) base_instruction = CircuitInstruction(operation, (), ()) for qarg, carg in broadcast_iter: self._check_dups(qarg) instruction = base_instruction.replace(qubits=qarg, clbits=carg) circuit_scope.append(instruction) instructions._add_ref(circuit_scope.instructions, len(circuit_scope.instructions) - 1) return instructions # Preferred new style. @typing.overload def _append( self, instruction: CircuitInstruction, *, _standard_gate: bool ) -> CircuitInstruction: ... # To-be-deprecated old style. @typing.overload def _append( self, instruction: Operation, qargs: Sequence[Qubit], cargs: Sequence[Clbit], ) -> Operation: ... def _append(self, instruction, qargs=(), cargs=(), *, _standard_gate: bool = False): """Append an instruction to the end of the circuit, modifying the circuit in place. .. warning:: This is an internal fast-path function, and it is the responsibility of the caller to ensure that all the arguments are valid; there is no error checking here. In particular: * all the qubits and clbits must already exist in the circuit and there can be no duplicates in the list. * any control-flow operations or classically conditioned instructions must act only on variables present in the circuit. * the circuit must not be within a control-flow builder context. .. note:: This function may be used by callers other than :obj:`.QuantumCircuit` when the caller is sure that all error-checking, broadcasting and scoping has already been performed, and the only reference to the circuit the instructions are being appended to is within that same function. In particular, it is not safe to call :meth:`QuantumCircuit._append` on a circuit that is received by a function argument. This is because :meth:`.QuantumCircuit._append` will not recognize the scoping constructs of the control-flow builder interface. Args: instruction: A complete well-formed :class:`.CircuitInstruction` of the operation and its context to be added. In the legacy compatibility form, this can be a bare :class:`.Operation`, in which case ``qargs`` and ``cargs`` must be explicitly given. qargs: Legacy argument for qubits to attach the bare :class:`.Operation` to. Ignored if the first argument is in the preferential :class:`.CircuitInstruction` form. cargs: Legacy argument for clbits to attach the bare :class:`.Operation` to. Ignored if the first argument is in the preferential :class:`.CircuitInstruction` form. Returns: CircuitInstruction: a handle to the instruction that was just added. :meta public: """ if _standard_gate: self._data.append(instruction) self.duration = None self.unit = "dt" return instruction old_style = not isinstance(instruction, CircuitInstruction) if old_style: instruction = CircuitInstruction(instruction, qargs, cargs) # If there is a reference to the outer circuit in an # instruction param the inner rust append method will raise a runtime error. # When this happens we need to handle the parameters separately. # This shouldn't happen in practice but 2 tests were doing this and it's not # explicitly prohibted by the API. try: self._data.append(instruction) except RuntimeError: params = [ (idx, param.parameters) for idx, param in enumerate(instruction.operation.params) if isinstance(param, (ParameterExpression, QuantumCircuit)) ] self._data.append_manual_params(instruction, params) # Invalidate whole circuit duration if an instruction is added self.duration = None self.unit = "dt" return instruction.operation if old_style else instruction @typing.overload def get_parameter(self, name: str, default: T) -> Union[Parameter, T]: ... # The builtin `types` module has `EllipsisType`, but only from 3.10+! @typing.overload def get_parameter(self, name: str, default: type(...) = ...) -> Parameter: ... # We use a _literal_ `Ellipsis` as the marker value to leave `None` available as a default. def get_parameter(self, name: str, default: typing.Any = ...) -> Parameter: """Retrieve a compile-time parameter that is accessible in this circuit scope by name. Args: name: the name of the parameter to retrieve. default: if given, this value will be returned if the parameter is not present. If it is not given, a :exc:`KeyError` is raised instead. Returns: The corresponding parameter. Raises: KeyError: if no default is given, but the parameter does not exist in the circuit. Examples: Retrieve a parameter by name from a circuit:: from qiskit.circuit import QuantumCircuit, Parameter my_param = Parameter("my_param") # Create a parametrized circuit. qc = QuantumCircuit(1) qc.rx(my_param, 0) # We can use 'my_param' as a parameter, but let's say we've lost the Python object # and need to retrieve it. my_param_again = qc.get_parameter("my_param") assert my_param is my_param_again Get a variable from a circuit by name, returning some default if it is not present:: assert qc.get_parameter("my_param", None) is my_param assert qc.get_parameter("unknown_param", None) is None See also: :meth:`get_var` A similar method, but for :class:`.expr.Var` run-time variables instead of :class:`.Parameter` compile-time parameters. """ if (parameter := self._data.get_parameter_by_name(name)) is None: if default is Ellipsis: raise KeyError(f"no parameter named '{name}' is present") return default return parameter def has_parameter(self, name_or_param: str | Parameter, /) -> bool: """Check whether a parameter object exists in this circuit. Args: name_or_param: the parameter, or name of a parameter to check. If this is a :class:`.Parameter` node, the parameter must be exactly the given one for this function to return ``True``. Returns: whether a matching parameter is assignable in this circuit. See also: :meth:`QuantumCircuit.get_parameter` Retrieve the :class:`.Parameter` instance from this circuit by name. :meth:`QuantumCircuit.has_var` A similar method to this, but for run-time :class:`.expr.Var` variables instead of compile-time :class:`.Parameter`\\ s. """ if isinstance(name_or_param, str): return self.get_parameter(name_or_param, None) is not None return self.get_parameter(name_or_param.name) == name_or_param @typing.overload def get_var(self, name: str, default: T) -> Union[expr.Var, T]: ... # The builtin `types` module has `EllipsisType`, but only from 3.10+! @typing.overload def get_var(self, name: str, default: type(...) = ...) -> expr.Var: ... # We use a _literal_ `Ellipsis` as the marker value to leave `None` available as a default. def get_var(self, name: str, default: typing.Any = ...): """Retrieve a variable that is accessible in this circuit scope by name. Args: name: the name of the variable to retrieve. default: if given, this value will be returned if the variable is not present. If it is not given, a :exc:`KeyError` is raised instead. Returns: The corresponding variable. Raises: KeyError: if no default is given, but the variable does not exist. Examples: Retrieve a variable by name from a circuit:: from qiskit.circuit import QuantumCircuit # Create a circuit and create a variable in it. qc = QuantumCircuit() my_var = qc.add_var("my_var", False) # We can use 'my_var' as a variable, but let's say we've lost the Python object and # need to retrieve it. my_var_again = qc.get_var("my_var") assert my_var is my_var_again Get a variable from a circuit by name, returning some default if it is not present:: assert qc.get_var("my_var", None) is my_var assert qc.get_var("unknown_variable", None) is None See also: :meth:`get_parameter` A similar method, but for :class:`.Parameter` compile-time parameters instead of :class:`.expr.Var` run-time variables. """ if (out := self._current_scope().get_var(name)) is not None: return out if default is Ellipsis: raise KeyError(f"no variable named '{name}' is present") return default def has_var(self, name_or_var: str | expr.Var, /) -> bool: """Check whether a variable is accessible in this scope. Args: name_or_var: the variable, or name of a variable to check. If this is a :class:`.expr.Var` node, the variable must be exactly the given one for this function to return ``True``. Returns: whether a matching variable is accessible. See also: :meth:`QuantumCircuit.get_var` Retrieve the :class:`.expr.Var` instance from this circuit by name. :meth:`QuantumCircuit.has_parameter` A similar method to this, but for compile-time :class:`.Parameter`\\ s instead of run-time :class:`.expr.Var` variables. """ if isinstance(name_or_var, str): return self.get_var(name_or_var, None) is not None return self.get_var(name_or_var.name, None) == name_or_var def _prepare_new_var( self, name_or_var: str | expr.Var, type_: types.Type | None, / ) -> expr.Var: """The common logic for preparing and validating a new :class:`~.expr.Var` for the circuit. The given ``type_`` can be ``None`` if the variable specifier is already a :class:`.Var`, and must be a :class:`~.types.Type` if it is a string. The argument is ignored if the given first argument is a :class:`.Var` already. Returns the validated variable, which is guaranteed to be safe to add to the circuit.""" if isinstance(name_or_var, str): if type_ is None: raise CircuitError("the type must be known when creating a 'Var' from a string") var = expr.Var.new(name_or_var, type_) else: var = name_or_var if not var.standalone: raise CircuitError( "cannot add variables that wrap `Clbit` or `ClassicalRegister` instances." " Use `add_bits` or `add_register` as appropriate." ) # The `var` is guaranteed to have a name because we already excluded the cases where it's # wrapping a bit/register. if (previous := self.get_var(var.name, default=None)) is not None: if previous == var: raise CircuitError(f"'{var}' is already present in the circuit") raise CircuitError(f"cannot add '{var}' as its name shadows the existing '{previous}'") return var def add_var(self, name_or_var: str | expr.Var, /, initial: typing.Any) -> expr.Var: """Add a classical variable with automatic storage and scope to this circuit. The variable is considered to have been "declared" at the beginning of the circuit, but it only becomes initialized at the point of the circuit that you call this method, so it can depend on variables defined before it. Args: name_or_var: either a string of the variable name, or an existing instance of :class:`~.expr.Var` to re-use. Variables cannot shadow names that are already in use within the circuit. initial: the value to initialize this variable with. If the first argument was given as a string name, the type of the resulting variable is inferred from the initial expression; to control this more manually, either use :meth:`.Var.new` to manually construct a new variable with the desired type, or use :func:`.expr.cast` to cast the initializer to the desired type. This must be either a :class:`~.expr.Expr` node, or a value that can be lifted to one using :class:`.expr.lift`. Returns: The created variable. If a :class:`~.expr.Var` instance was given, the exact same object will be returned. Raises: CircuitError: if the variable cannot be created due to shadowing an existing variable. Examples: Define a new variable given just a name and an initializer expression:: from qiskit.circuit import QuantumCircuit qc = QuantumCircuit(2) my_var = qc.add_var("my_var", False) Reuse a variable that may have been taken from a related circuit, or otherwise constructed manually, and initialize it to some more complicated expression:: from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit.classical import expr, types my_var = expr.Var.new("my_var", types.Uint(8)) cr1 = ClassicalRegister(8, "cr1") cr2 = ClassicalRegister(8, "cr2") qc = QuantumCircuit(QuantumRegister(8), cr1, cr2) # Get some measurement results into each register. qc.h(0) for i in range(1, 8): qc.cx(0, i) qc.measure(range(8), cr1) qc.reset(range(8)) qc.h(0) for i in range(1, 8): qc.cx(0, i) qc.measure(range(8), cr2) # Now when we add the variable, it is initialized using the real-time state of the # two classical registers we measured into above. qc.add_var(my_var, expr.bit_and(cr1, cr2)) """ # Validate the initializer first to catch cases where the variable to be declared is being # used in the initializer. circuit_scope = self._current_scope() # Convenience method to widen Python integer literals to the right width during the initial # lift, if the type is already known via the variable. if ( isinstance(name_or_var, expr.Var) and name_or_var.type.kind is types.Uint and isinstance(initial, int) and not isinstance(initial, bool) ): coerce_type = name_or_var.type else: coerce_type = None initial = _validate_expr(circuit_scope, expr.lift(initial, coerce_type)) if isinstance(name_or_var, str): var = expr.Var.new(name_or_var, initial.type) elif not name_or_var.standalone: raise CircuitError( "cannot add variables that wrap `Clbit` or `ClassicalRegister` instances." ) else: var = name_or_var circuit_scope.add_uninitialized_var(var) try: # Store is responsible for ensuring the type safety of the initialization. store = Store(var, initial) except CircuitError: circuit_scope.remove_var(var) raise circuit_scope.append(CircuitInstruction(store, (), ())) return var def add_uninitialized_var(self, var: expr.Var, /): """Add a variable with no initializer. In most cases, you should use :meth:`add_var` to initialize the variable. To use this function, you must already hold a :class:`~.expr.Var` instance, as the use of the function typically only makes sense in copying contexts. .. warning:: Qiskit makes no assertions about what an uninitialized variable will evaluate to at runtime, and some hardware may reject this as an error. You should treat this function with caution, and as a low-level primitive that is useful only in special cases of programmatically rebuilding two like circuits. Args: var: the variable to add. """ # This function is deliberately meant to be a bit harder to find, to have a long descriptive # name, and to be a bit less ergonomic than `add_var` (i.e. not allowing the (name, type) # overload) to discourage people from using it when they should use `add_var`. # # This function exists so that there is a method to emulate `copy_empty_like`'s behavior of # adding uninitialised variables, which there's no obvious way around. We need to be sure # that _some_ sort of handling of uninitialised variables is taken into account in our # structures, so that doesn't become a huge edge case, even though we make no assertions # about the _meaning_ if such an expression was run on hardware. if self._control_flow_scopes: raise CircuitError("cannot add an uninitialized variable in a control-flow scope") if not var.standalone: raise CircuitError("cannot add a variable wrapping a bit or register to a circuit") self._builder_api.add_uninitialized_var(var) def add_capture(self, var: expr.Var): """Add a variable to the circuit that it should capture from a scope it will be contained within. This method requires a :class:`~.expr.Var` node to enforce that you've got a handle to one, because you will need to declare the same variable using the same object into the outer circuit. This is a low-level method, which is only really useful if you are manually constructing control-flow operations. You typically will not need to call this method, assuming you are using the builder interface for control-flow scopes (``with`` context-manager statements for :meth:`if_test` and the other scoping constructs). The builder interface will automatically make the inner scopes closures on your behalf by capturing any variables that are used within them. Args: var: the variable to capture from an enclosing scope. Raises: CircuitError: if the variable cannot be created due to shadowing an existing variable. """ if self._control_flow_scopes: # Allow manual capturing. Not sure why it'd be useful, but there's a clear expected # behavior here. self._control_flow_scopes[-1].use_var(var) return if self._vars_input: raise CircuitError( "circuits with input variables cannot be enclosed, so cannot be closures" ) self._vars_capture[var.name] = self._prepare_new_var(var, None) @typing.overload def add_input(self, name_or_var: str, type_: types.Type, /) -> expr.Var: ... @typing.overload def add_input(self, name_or_var: expr.Var, type_: None = None, /) -> expr.Var: ... def add_input( # pylint: disable=missing-raises-doc self, name_or_var: str | expr.Var, type_: types.Type | None = None, / ) -> expr.Var: """Register a variable as an input to the circuit. Args: name_or_var: either a string name, or an existing :class:`~.expr.Var` node to use as the input variable. type_: if the name is given as a string, then this must be a :class:`~.types.Type` to use for the variable. If the variable is given as an existing :class:`~.expr.Var`, then this must not be given, and will instead be read from the object itself. Returns: the variable created, or the same variable as was passed in. Raises: CircuitError: if the variable cannot be created due to shadowing an existing variable. """ if self._control_flow_scopes: raise CircuitError("cannot add an input variable in a control-flow scope") if self._vars_capture: raise CircuitError("circuits to be enclosed with captures cannot have input variables") if isinstance(name_or_var, expr.Var) and type_ is not None: raise ValueError("cannot give an explicit type with an existing Var") var = self._prepare_new_var(name_or_var, type_) self._vars_input[var.name] = var return var def add_register(self, *regs: Register | int | Sequence[Bit]) -> None: """Add registers.""" if not regs: return if any(isinstance(reg, int) for reg in regs): # QuantumCircuit defined without registers if len(regs) == 1 and isinstance(regs[0], int): # QuantumCircuit with anonymous quantum wires e.g. QuantumCircuit(2) if regs[0] == 0: regs = () else: regs = (QuantumRegister(regs[0], "q"),) elif len(regs) == 2 and all(isinstance(reg, int) for reg in regs): # QuantumCircuit with anonymous wires e.g. QuantumCircuit(2, 3) if regs[0] == 0: qregs: tuple[QuantumRegister, ...] = () else: qregs = (QuantumRegister(regs[0], "q"),) if regs[1] == 0: cregs: tuple[ClassicalRegister, ...] = () else: cregs = (ClassicalRegister(regs[1], "c"),) regs = qregs + cregs else: raise CircuitError( "QuantumCircuit parameters can be Registers or Integers." " If Integers, up to 2 arguments. QuantumCircuit was called" f" with {(regs,)}." ) for register in regs: if isinstance(register, Register) and any( register.name == reg.name for reg in self.qregs + self.cregs ): raise CircuitError(f'register name "{register.name}" already exists') if isinstance(register, AncillaRegister): for bit in register: if bit not in self._qubit_indices: self._ancillas.append(bit) if isinstance(register, QuantumRegister): self.qregs.append(register) for idx, bit in enumerate(register): if bit in self._qubit_indices: self._qubit_indices[bit].registers.append((register, idx)) else: self._data.add_qubit(bit) self._qubit_indices[bit] = BitLocations( self._data.num_qubits - 1, [(register, idx)] ) elif isinstance(register, ClassicalRegister): self.cregs.append(register) for idx, bit in enumerate(register): if bit in self._clbit_indices: self._clbit_indices[bit].registers.append((register, idx)) else: self._data.add_clbit(bit) self._clbit_indices[bit] = BitLocations( self._data.num_clbits - 1, [(register, idx)] ) elif isinstance(register, list): self.add_bits(register) else: raise CircuitError("expected a register") def add_bits(self, bits: Iterable[Bit]) -> None: """Add Bits to the circuit.""" duplicate_bits = { bit for bit in bits if bit in self._qubit_indices or bit in self._clbit_indices } if duplicate_bits: raise CircuitError(f"Attempted to add bits found already in circuit: {duplicate_bits}") for bit in bits: if isinstance(bit, AncillaQubit): self._ancillas.append(bit) if isinstance(bit, Qubit): self._data.add_qubit(bit) self._qubit_indices[bit] = BitLocations(self._data.num_qubits - 1, []) elif isinstance(bit, Clbit): self._data.add_clbit(bit) self._clbit_indices[bit] = BitLocations(self._data.num_clbits - 1, []) else: raise CircuitError( "Expected an instance of Qubit, Clbit, or " f"AncillaQubit, but was passed {bit}" ) def find_bit(self, bit: Bit) -> BitLocations: """Find locations in the circuit which can be used to reference a given :obj:`~Bit`. In particular, this function can find the integer index of a qubit, which corresponds to its hardware index for a transpiled circuit. .. note:: The circuit index of a :class:`.AncillaQubit` will be its index in :attr:`qubits`, not :attr:`ancillas`. Args: bit (Bit): The bit to locate. Returns: namedtuple(int, List[Tuple(Register, int)]): A 2-tuple. The first element (``index``) contains the index at which the ``Bit`` can be found (in either :obj:`~QuantumCircuit.qubits`, :obj:`~QuantumCircuit.clbits`, depending on its type). The second element (``registers``) is a list of ``(register, index)`` pairs with an entry for each :obj:`~Register` in the circuit which contains the :obj:`~Bit` (and the index in the :obj:`~Register` at which it can be found). Raises: CircuitError: If the supplied :obj:`~Bit` was of an unknown type. CircuitError: If the supplied :obj:`~Bit` could not be found on the circuit. Examples: Loop through a circuit, getting the qubit and clbit indices of each operation:: from qiskit.circuit import QuantumCircuit, Qubit qc = QuantumCircuit(3, 3) qc.h(0) qc.cx(0, 1) qc.cx(1, 2) qc.measure([0, 1, 2], [0, 1, 2]) # The `.qubits` and `.clbits` fields are not integers. assert isinstance(qc.data[0].qubits[0], Qubit) # ... but we can use `find_bit` to retrieve them. assert qc.find_bit(qc.data[0].qubits[0]).index == 0 simple = [ ( instruction.operation.name, [qc.find_bit(bit).index for bit in instruction.qubits], [qc.find_bit(bit).index for bit in instruction.clbits], ) for instruction in qc.data ] """ try: if isinstance(bit, Qubit): return self._qubit_indices[bit] elif isinstance(bit, Clbit): return self._clbit_indices[bit] else: raise CircuitError(f"Could not locate bit of unknown type: {type(bit)}") except KeyError as err: raise CircuitError( f"Could not locate provided bit: {bit}. Has it been added to the QuantumCircuit?" ) from err def _check_dups(self, qubits: Sequence[Qubit]) -> None: """Raise exception if list of qubits contains duplicates.""" squbits = set(qubits) if len(squbits) != len(qubits): raise CircuitError("duplicate qubit arguments") def to_instruction( self, parameter_map: dict[Parameter, ParameterValueType] | None = None, label: str | None = None, ) -> Instruction: """Create an :class:`~.circuit.Instruction` out of this circuit. .. seealso:: :func:`circuit_to_instruction` The underlying driver of this method. Args: parameter_map: For parameterized circuits, a mapping from parameters in the circuit to parameters to be used in the instruction. If None, existing circuit parameters will also parameterize the instruction. label: Optional gate label. Returns: qiskit.circuit.Instruction: a composite instruction encapsulating this circuit (can be decomposed back). """ from qiskit.converters.circuit_to_instruction import circuit_to_instruction return circuit_to_instruction(self, parameter_map, label=label) def to_gate( self, parameter_map: dict[Parameter, ParameterValueType] | None = None, label: str | None = None, ) -> Gate: """Create a :class:`.Gate` out of this circuit. The circuit must act only qubits and contain only unitary operations. .. seealso:: :func:`circuit_to_gate` The underlying driver of this method. Args: parameter_map: For parameterized circuits, a mapping from parameters in the circuit to parameters to be used in the gate. If ``None``, existing circuit parameters will also parameterize the gate. label : Optional gate label. Returns: Gate: a composite gate encapsulating this circuit (can be decomposed back). """ from qiskit.converters.circuit_to_gate import circuit_to_gate return circuit_to_gate(self, parameter_map, label=label) def decompose( self, gates_to_decompose: Type[Gate] | Sequence[Type[Gate]] | Sequence[str] | str | None = None, reps: int = 1, ) -> "QuantumCircuit": """Call a decomposition pass on this circuit, to decompose one level (shallow decompose). Args: gates_to_decompose (type or str or list(type, str)): Optional subset of gates to decompose. Can be a gate type, such as ``HGate``, or a gate name, such as 'h', or a gate label, such as 'My H Gate', or a list of any combination of these. If a gate name is entered, it will decompose all gates with that name, whether the gates have labels or not. Defaults to all gates in circuit. reps (int): Optional number of times the circuit should be decomposed. For instance, ``reps=2`` equals calling ``circuit.decompose().decompose()``. can decompose specific gates specific time Returns: QuantumCircuit: a circuit one level decomposed """ # pylint: disable=cyclic-import from qiskit.transpiler.passes.basis.decompose import Decompose from qiskit.transpiler.passes.synthesis import HighLevelSynthesis from qiskit.converters.circuit_to_dag import circuit_to_dag from qiskit.converters.dag_to_circuit import dag_to_circuit dag = circuit_to_dag(self, copy_operations=True) if gates_to_decompose is None: # We should not rewrite the circuit using HLS when we have gates_to_decompose, # or else HLS will rewrite all objects with available plugins (e.g., Cliffords, # PermutationGates, and now also MCXGates) dag = HighLevelSynthesis().run(dag) pass_ = Decompose(gates_to_decompose) for _ in range(reps): dag = pass_.run(dag) # do not copy operations, this is done in the conversion with circuit_to_dag return dag_to_circuit(dag, copy_operations=False) def draw( self, output: str | None = None, scale: float | None = None, filename: str | None = None, style: dict | str | None = None, interactive: bool = False, plot_barriers: bool = True, reverse_bits: bool | None = None, justify: str | None = None, vertical_compression: str | None = "medium", idle_wires: bool | None = None, with_layout: bool = True, fold: int | None = None, # The type of ax is matplotlib.axes.Axes, but this is not a fixed dependency, so cannot be # safely forward-referenced. ax: Any | None = None, initial_state: bool = False, cregbundle: bool | None = None, wire_order: list[int] | None = None, expr_len: int = 30, ): r"""Draw the quantum circuit. Use the output parameter to choose the drawing format: **text**: ASCII art TextDrawing that can be printed in the console. **mpl**: images with color rendered purely in Python using matplotlib. **latex**: high-quality images compiled via latex. **latex_source**: raw uncompiled latex output. .. warning:: Support for :class:`~.expr.Expr` nodes in conditions and :attr:`.SwitchCaseOp.target` fields is preliminary and incomplete. The ``text`` and ``mpl`` drawers will make a best-effort attempt to show data dependencies, but the LaTeX-based drawers will skip these completely. Args: output: Select the output method to use for drawing the circuit. Valid choices are ``text``, ``mpl``, ``latex``, ``latex_source``. By default, the ``text`` drawer is used unless the user config file (usually ``~/.qiskit/settings.conf``) has an alternative backend set as the default. For example, ``circuit_drawer = latex``. If the output kwarg is set, that backend will always be used over the default in the user config file. scale: Scale of image to draw (shrink if ``< 1.0``). Only used by the ``mpl``, ``latex`` and ``latex_source`` outputs. Defaults to ``1.0``. filename: File path to save image to. Defaults to ``None`` (result not saved in a file). style: Style name, file name of style JSON file, or a dictionary specifying the style. * The supported style names are ``"iqp"`` (default), ``"iqp-dark"``, ``"clifford"``, ``"textbook"`` and ``"bw"``. * If given a JSON file, e.g. ``my_style.json`` or ``my_style`` (the ``.json`` extension may be omitted), this function attempts to load the style dictionary from that location. Note, that the JSON file must completely specify the visualization specifications. The file is searched for in ``qiskit/visualization/circuit/styles``, the current working directory, and the location specified in ``~/.qiskit/settings.conf``. * If a dictionary, every entry overrides the default configuration. If the ``"name"`` key is given, the default configuration is given by that style. For example, ``{"name": "textbook", "subfontsize": 5}`` loads the ``"texbook"`` style and sets the subfontsize (e.g. the gate angles) to ``5``. * If ``None`` the default style ``"iqp"`` is used or, if given, the default style specified in ``~/.qiskit/settings.conf``. interactive: When set to ``True``, show the circuit in a new window (for ``mpl`` this depends on the matplotlib backend being used supporting this). Note when used with either the `text` or the ``latex_source`` output type this has no effect and will be silently ignored. Defaults to ``False``. reverse_bits: When set to ``True``, reverse the bit order inside registers for the output visualization. Defaults to ``False`` unless the user config file (usually ``~/.qiskit/settings.conf``) has an alternative value set. For example, ``circuit_reverse_bits = True``. plot_barriers: Enable/disable drawing barriers in the output circuit. Defaults to ``True``. justify: Options are ``"left"``, ``"right"`` or ``"none"`` (str). If anything else is supplied, left justified will be used instead. It refers to where gates should be placed in the output circuit if there is an option. ``none`` results in each gate being placed in its own column. Defaults to ``left``. vertical_compression: ``high``, ``medium`` or ``low``. It merges the lines generated by the `text` output so the drawing will take less vertical room. Default is ``medium``. Only used by the ``text`` output, will be silently ignored otherwise. idle_wires: Include idle wires (wires with no circuit elements) in output visualization. Default is ``True`` unless the user config file (usually ``~/.qiskit/settings.conf``) has an alternative value set. For example, ``circuit_idle_wires = False``. with_layout: Include layout information, with labels on the physical layout. Default is ``True``. fold: Sets pagination. It can be disabled using -1. In ``text``, sets the length of the lines. This is useful when the drawing does not fit in the console. If None (default), it will try to guess the console width using ``shutil.get_terminal_size()``. However, if running in jupyter, the default line length is set to 80 characters. In ``mpl``, it is the number of (visual) layers before folding. Default is 25. ax: Only used by the `mpl` backend. An optional ``matplotlib.axes.Axes`` object to be used for the visualization output. If none is specified, a new matplotlib Figure will be created and used. Additionally, if specified there will be no returned Figure since it is redundant. initial_state: Adds :math:`|0\rangle` in the beginning of the qubit wires and :math:`0` to classical wires. Default is ``False``. cregbundle: If set to ``True``, bundle classical registers. Default is ``True``, except for when ``output`` is set to ``"text"``. wire_order: A list of integers used to reorder the display of the bits. The list must have an entry for every bit with the bits in the range 0 to (``num_qubits`` + ``num_clbits``). expr_len: The number of characters to display if an :class:`~.expr.Expr` is used for the condition in a :class:`.ControlFlowOp`. If this number is exceeded, the string will be truncated at that number and '...' added to the end. Returns: :class:`.TextDrawing` or :class:`matplotlib.figure` or :class:`PIL.Image` or :class:`str`: * ``TextDrawing`` (if ``output='text'``) A drawing that can be printed as ascii art. * ``matplotlib.figure.Figure`` (if ``output='mpl'``) A matplotlib figure object for the circuit diagram. * ``PIL.Image`` (if ``output='latex``') An in-memory representation of the image of the circuit diagram. * ``str`` (if ``output='latex_source'``) The LaTeX source code for visualizing the circuit diagram. Raises: VisualizationError: when an invalid output method is selected ImportError: when the output methods requires non-installed libraries. Example: .. plot:: :include-source: from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit qc = QuantumCircuit(1, 1) qc.h(0) qc.measure(0, 0) qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'}) """ # pylint: disable=cyclic-import from qiskit.visualization import circuit_drawer return circuit_drawer( self, scale=scale, filename=filename, style=style, output=output, interactive=interactive, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify, vertical_compression=vertical_compression, idle_wires=idle_wires, with_layout=with_layout, fold=fold, ax=ax, initial_state=initial_state, cregbundle=cregbundle, wire_order=wire_order, expr_len=expr_len, ) def size( self, filter_function: Callable[..., int] = lambda x: not getattr( x.operation, "_directive", False ), ) -> int: """Returns total number of instructions in circuit. Args: filter_function (callable): a function to filter out some instructions. Should take as input a tuple of (Instruction, list(Qubit), list(Clbit)). By default, filters out "directives", such as barrier or snapshot. Returns: int: Total number of gate operations. """ return sum(map(filter_function, self._data)) def depth( self, filter_function: Callable[[CircuitInstruction], bool] = lambda x: not getattr( x.operation, "_directive", False ), ) -> int: """Return circuit depth (i.e., length of critical path). .. warning:: This operation is not well defined if the circuit contains control-flow operations. Args: filter_function: A function to decide which instructions count to increase depth. Should take as a single positional input a :class:`CircuitInstruction`. Instructions for which the function returns ``False`` are ignored in the computation of the circuit depth. By default, filters out "directives", such as :class:`.Barrier`. Returns: int: Depth of circuit. Examples: Simple calculation of total circuit depth:: from qiskit.circuit import QuantumCircuit qc = QuantumCircuit(4) qc.h(0) qc.cx(0, 1) qc.h(2) qc.cx(2, 3) assert qc.depth() == 2 Modifying the previous example to only calculate the depth of multi-qubit gates:: assert qc.depth(lambda instr: len(instr.qubits) > 1) == 1 """ obj_depths = { obj: 0 for objects in (self.qubits, self.clbits, self.iter_vars()) for obj in objects } def update_from_expr(objects, node): for var in expr.iter_vars(node): if var.standalone: objects.add(var) else: objects.update(_builder_utils.node_resources(var).clbits) for instruction in self._data: objects = set(itertools.chain(instruction.qubits, instruction.clbits)) if (condition := getattr(instruction.operation, "condition", None)) is not None: objects.update(_builder_utils.condition_resources(condition).clbits) if isinstance(condition, expr.Expr): update_from_expr(objects, condition) else: objects.update(_builder_utils.condition_resources(condition).clbits) elif isinstance(instruction.operation, SwitchCaseOp): update_from_expr(objects, expr.lift(instruction.operation.target)) elif isinstance(instruction.operation, Store): update_from_expr(objects, instruction.operation.lvalue) update_from_expr(objects, instruction.operation.rvalue) # If we're counting this as adding to depth, do so. If not, it still functions as a # data synchronisation point between the objects (think "barrier"), so the depths still # get updated to match the current max over the affected objects. new_depth = max((obj_depths[obj] for obj in objects), default=0) if filter_function(instruction): new_depth += 1 for obj in objects: obj_depths[obj] = new_depth return max(obj_depths.values(), default=0) def width(self) -> int: """Return number of qubits plus clbits in circuit. Returns: int: Width of circuit. """ return self._data.width() @property def num_qubits(self) -> int: """Return number of qubits.""" return self._data.num_qubits @property def num_ancillas(self) -> int: """Return the number of ancilla qubits.""" return len(self.ancillas) @property def num_clbits(self) -> int: """Return number of classical bits.""" return self._data.num_clbits # The stringified return type is because OrderedDict can't be subscripted before Python 3.9, and # typing.OrderedDict wasn't added until 3.7.2. It can be turned into a proper type once 3.6 # support is dropped. def count_ops(self) -> "OrderedDict[Instruction, int]": """Count each operation kind in the circuit. Returns: OrderedDict: a breakdown of how many operations of each kind, sorted by amount. """ ops_dict = self._data.count_ops() return OrderedDict(ops_dict) def num_nonlocal_gates(self) -> int: """Return number of non-local gates (i.e. involving 2+ qubits). Conditional nonlocal gates are also included. """ return self._data.num_nonlocal_gates() def get_instructions(self, name: str) -> list[CircuitInstruction]: """Get instructions matching name. Args: name (str): The name of instruction to. Returns: list(tuple): list of (instruction, qargs, cargs). """ return [match for match in self._data if match.operation.name == name] def num_connected_components(self, unitary_only: bool = False) -> int: """How many non-entangled subcircuits can the circuit be factored to. Args: unitary_only (bool): Compute only unitary part of graph. Returns: int: Number of connected components in circuit. """ # Convert registers to ints (as done in depth). bits = self.qubits if unitary_only else (self.qubits + self.clbits) bit_indices: dict[Qubit | Clbit, int] = {bit: idx for idx, bit in enumerate(bits)} # Start with each qubit or clbit being its own subgraph. sub_graphs = [[bit] for bit in range(len(bit_indices))] num_sub_graphs = len(sub_graphs) # Here we are traversing the gates and looking to see # which of the sub_graphs the gate joins together. for instruction in self._data: if unitary_only: args = instruction.qubits num_qargs = len(args) else: args = instruction.qubits + instruction.clbits num_qargs = len(args) + ( 1 if getattr(instruction.operation, "condition", None) else 0 ) if num_qargs >= 2 and not getattr(instruction.operation, "_directive", False): graphs_touched = [] num_touched = 0 # Controls necessarily join all the cbits in the # register that they use. if not unitary_only: for bit in instruction.operation.condition_bits: idx = bit_indices[bit] for k in range(num_sub_graphs): if idx in sub_graphs[k]: graphs_touched.append(k) break for item in args: reg_int = bit_indices[item] for k in range(num_sub_graphs): if reg_int in sub_graphs[k]: if k not in graphs_touched: graphs_touched.append(k) break graphs_touched = list(set(graphs_touched)) num_touched = len(graphs_touched) # If the gate touches more than one subgraph # join those graphs together and return # reduced number of subgraphs if num_touched > 1: connections = [] for idx in graphs_touched: connections.extend(sub_graphs[idx]) _sub_graphs = [] for idx in range(num_sub_graphs): if idx not in graphs_touched: _sub_graphs.append(sub_graphs[idx]) _sub_graphs.append(connections) sub_graphs = _sub_graphs num_sub_graphs -= num_touched - 1 # Cannot go lower than one so break if num_sub_graphs == 1: break return num_sub_graphs def num_unitary_factors(self) -> int: """Computes the number of tensor factors in the unitary (quantum) part of the circuit only. """ return self.num_connected_components(unitary_only=True) def num_tensor_factors(self) -> int: """Computes the number of tensor factors in the unitary (quantum) part of the circuit only. Notes: This is here for backwards compatibility, and will be removed in a future release of Qiskit. You should call `num_unitary_factors` instead. """ return self.num_unitary_factors() def copy(self, name: str | None = None) -> typing.Self: """Copy the circuit. Args: name (str): name to be given to the copied circuit. If None, then the name stays the same. Returns: QuantumCircuit: a deepcopy of the current circuit, with the specified name """ cpy = self.copy_empty_like(name) cpy._data = self._data.copy() return cpy def copy_empty_like( self, name: str | None = None, *, vars_mode: Literal["alike", "captures", "drop"] = "alike", ) -> typing.Self: """Return a copy of self with the same structure but empty. That structure includes: * name, calibrations and other metadata * global phase * all the qubits and clbits, including the registers * the realtime variables defined in the circuit, handled according to the ``vars`` keyword argument. .. warning:: If the circuit contains any local variable declarations (those added by the ``declarations`` argument to the circuit constructor, or using :meth:`add_var`), they may be **uninitialized** in the output circuit. You will need to manually add store instructions for them (see :class:`.Store` and :meth:`.QuantumCircuit.store`) to initialize them. Args: name: Name for the copied circuit. If None, then the name stays the same. vars_mode: The mode to handle realtime variables in. alike The variables in the output circuit will have the same declaration semantics as in the original circuit. For example, ``input`` variables in the source will be ``input`` variables in the output circuit. captures All variables will be converted to captured variables. This is useful when you are building a new layer for an existing circuit that you will want to :meth:`compose` onto the base, since :meth:`compose` can inline captures onto the base circuit (but not other variables). drop The output circuit will have no variables defined. Returns: QuantumCircuit: An empty copy of self. """ if not (name is None or isinstance(name, str)): raise TypeError( f"invalid name for a circuit: '{name}'. The name must be a string or 'None'." ) cpy = _copy.copy(self) # copy registers correctly, in copy.copy they are only copied via reference cpy.qregs = self.qregs.copy() cpy.cregs = self.cregs.copy() cpy._builder_api = _OuterCircuitScopeInterface(cpy) cpy._ancillas = self._ancillas.copy() cpy._qubit_indices = self._qubit_indices.copy() cpy._clbit_indices = self._clbit_indices.copy() if vars_mode == "alike": # Note that this causes the local variables to be uninitialised, because the stores are # not copied. This can leave the circuit in a potentially dangerous state for users if # they don't re-add initializer stores. cpy._vars_local = self._vars_local.copy() cpy._vars_input = self._vars_input.copy() cpy._vars_capture = self._vars_capture.copy() elif vars_mode == "captures": cpy._vars_local = {} cpy._vars_input = {} cpy._vars_capture = {var.name: var for var in self.iter_vars()} elif vars_mode == "drop": cpy._vars_local = {} cpy._vars_input = {} cpy._vars_capture = {} else: # pragma: no cover raise ValueError(f"unknown vars_mode: '{vars_mode}'") cpy._data = CircuitData( self._data.qubits, self._data.clbits, global_phase=self._data.global_phase ) cpy._calibrations = _copy.deepcopy(self._calibrations) cpy._metadata = _copy.deepcopy(self._metadata) if name: cpy.name = name return cpy def clear(self) -> None: """Clear all instructions in self. Clearing the circuits will keep the metadata and calibrations. .. seealso:: :meth:`copy_empty_like` A method to produce a new circuit with no instructions and all the same tracking of quantum and classical typed data, but without mutating the original circuit. """ self._data.clear() # Repopulate the parameter table with any phase symbols. self.global_phase = self.global_phase def _create_creg(self, length: int, name: str) -> ClassicalRegister: """Creates a creg, checking if ClassicalRegister with same name exists""" if name in [creg.name for creg in self.cregs]: save_prefix = ClassicalRegister.prefix ClassicalRegister.prefix = name new_creg = ClassicalRegister(length) ClassicalRegister.prefix = save_prefix else: new_creg = ClassicalRegister(length, name) return new_creg def _create_qreg(self, length: int, name: str) -> QuantumRegister: """Creates a qreg, checking if QuantumRegister with same name exists""" if name in [qreg.name for qreg in self.qregs]: save_prefix = QuantumRegister.prefix QuantumRegister.prefix = name new_qreg = QuantumRegister(length) QuantumRegister.prefix = save_prefix else: new_qreg = QuantumRegister(length, name) return new_qreg def reset(self, qubit: QubitSpecifier) -> InstructionSet: """Reset the quantum bit(s) to their default state. Args: qubit: qubit(s) to reset. Returns: qiskit.circuit.InstructionSet: handle to the added instruction. """ from .reset import Reset return self.append(Reset(), [qubit], [], copy=False) def store(self, lvalue: typing.Any, rvalue: typing.Any, /) -> InstructionSet: """Store the result of the given real-time classical expression ``rvalue`` in the memory location defined by ``lvalue``. Typically ``lvalue`` will be a :class:`~.expr.Var` node and ``rvalue`` will be some :class:`~.expr.Expr` to write into it, but anything that :func:`.expr.lift` can raise to an :class:`~.expr.Expr` is permissible in both places, and it will be called on them. Args: lvalue: a valid specifier for a memory location in the circuit. This will typically be a :class:`~.expr.Var` node, but you can also write to :class:`.Clbit` or :class:`.ClassicalRegister` memory locations if your hardware supports it. The memory location must already be present in the circuit. rvalue: a real-time classical expression whose result should be written into the given memory location. .. seealso:: :class:`~.circuit.Store` The backing :class:`~.circuit.Instruction` class that represents this operation. :meth:`add_var` Create a new variable in the circuit that can be written to with this method. """ # As a convenience, lift integer-literal rvalues to the matching width. lvalue = expr.lift(lvalue) rvalue_type = ( lvalue.type if isinstance(rvalue, int) and not isinstance(rvalue, bool) else None ) rvalue = expr.lift(rvalue, rvalue_type) return self.append(Store(lvalue, rvalue), (), (), copy=False) def measure(self, qubit: QubitSpecifier, cbit: ClbitSpecifier) -> InstructionSet: r"""Measure a quantum bit (``qubit``) in the Z basis into a classical bit (``cbit``). When a quantum state is measured, a qubit is projected in the computational (Pauli Z) basis to either :math:`\lvert 0 \rangle` or :math:`\lvert 1 \rangle`. The classical bit ``cbit`` indicates the result of that projection as a ``0`` or a ``1`` respectively. This operation is non-reversible. Args: qubit: qubit(s) to measure. cbit: classical bit(s) to place the measurement result(s) in. Returns: qiskit.circuit.InstructionSet: handle to the added instructions. Raises: CircuitError: if arguments have bad format. Examples: In this example, a qubit is measured and the result of that measurement is stored in the classical bit (usually expressed in diagrams as a double line): .. code-block:: from qiskit import QuantumCircuit circuit = QuantumCircuit(1, 1) circuit.h(0) circuit.measure(0, 0) circuit.draw() .. parsed-literal:: ┌───┐┌─┐ q: ┤ H ├┤M├ └───┘└╥┘ c: 1/══════╩═ 0 It is possible to call ``measure`` with lists of ``qubits`` and ``cbits`` as a shortcut for one-to-one measurement. These two forms produce identical results: .. code-block:: circuit = QuantumCircuit(2, 2) circuit.measure([0,1], [0,1]) .. code-block:: circuit = QuantumCircuit(2, 2) circuit.measure(0, 0) circuit.measure(1, 1) Instead of lists, you can use :class:`~qiskit.circuit.QuantumRegister` and :class:`~qiskit.circuit.ClassicalRegister` under the same logic. .. code-block:: from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister qreg = QuantumRegister(2, "qreg") creg = ClassicalRegister(2, "creg") circuit = QuantumCircuit(qreg, creg) circuit.measure(qreg, creg) This is equivalent to: .. code-block:: circuit = QuantumCircuit(qreg, creg) circuit.measure(qreg[0], creg[0]) circuit.measure(qreg[1], creg[1]) """ from .measure import Measure return self.append(Measure(), [qubit], [cbit], copy=False) def measure_active(self, inplace: bool = True) -> Optional["QuantumCircuit"]: """Adds measurement to all non-idle qubits. Creates a new ClassicalRegister with a size equal to the number of non-idle qubits being measured. Returns a new circuit with measurements if `inplace=False`. Args: inplace (bool): All measurements inplace or return new circuit. Returns: QuantumCircuit: Returns circuit with measurements when ``inplace = False``. """ from qiskit.converters.circuit_to_dag import circuit_to_dag if inplace: circ = self else: circ = self.copy() dag = circuit_to_dag(circ) qubits_to_measure = [qubit for qubit in circ.qubits if qubit not in dag.idle_wires()] new_creg = circ._create_creg(len(qubits_to_measure), "measure") circ.add_register(new_creg) circ.barrier() circ.measure(qubits_to_measure, new_creg) if not inplace: return circ else: return None def measure_all( self, inplace: bool = True, add_bits: bool = True ) -> Optional["QuantumCircuit"]: """Adds measurement to all qubits. By default, adds new classical bits in a :obj:`.ClassicalRegister` to store these measurements. If ``add_bits=False``, the results of the measurements will instead be stored in the already existing classical bits, with qubit ``n`` being measured into classical bit ``n``. Returns a new circuit with measurements if ``inplace=False``. Args: inplace (bool): All measurements inplace or return new circuit. add_bits (bool): Whether to add new bits to store the results. Returns: QuantumCircuit: Returns circuit with measurements when ``inplace=False``. Raises: CircuitError: if ``add_bits=False`` but there are not enough classical bits. """ if inplace: circ = self else: circ = self.copy() if add_bits: new_creg = circ._create_creg(circ.num_qubits, "meas") circ.add_register(new_creg) circ.barrier() circ.measure(circ.qubits, new_creg) else: if circ.num_clbits < circ.num_qubits: raise CircuitError( "The number of classical bits must be equal or greater than " "the number of qubits." ) circ.barrier() circ.measure(circ.qubits, circ.clbits[0 : circ.num_qubits]) if not inplace: return circ else: return None def remove_final_measurements(self, inplace: bool = True) -> Optional["QuantumCircuit"]: """Removes final measurements and barriers on all qubits if they are present. Deletes the classical registers that were used to store the values from these measurements that become idle as a result of this operation, and deletes classical bits that are referenced only by removed registers, or that aren't referenced at all but have become idle as a result of this operation. Measurements and barriers are considered final if they are followed by no other operations (aside from other measurements or barriers.) .. note:: This method has rather complex behavior, particularly around the removal of newly idle classical bits and registers. It is much more efficient to avoid adding unnecessary classical data in the first place, rather than trying to remove it later. .. seealso:: :class:`.RemoveFinalMeasurements` A transpiler pass that removes final measurements and barriers. This does not remove the classical data. If this is your goal, you can call that with:: from qiskit.circuit import QuantumCircuit from qiskit.transpiler.passes import RemoveFinalMeasurements qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.barrier() qc.measure([0, 1], [0, 1]) pass_ = RemoveFinalMeasurements() just_bell = pass_(qc) Args: inplace (bool): All measurements removed inplace or return new circuit. Returns: QuantumCircuit: Returns the resulting circuit when ``inplace=False``, else None. """ # pylint: disable=cyclic-import from qiskit.transpiler.passes import RemoveFinalMeasurements from qiskit.converters import circuit_to_dag if inplace: circ = self else: circ = self.copy() dag = circuit_to_dag(circ) remove_final_meas = RemoveFinalMeasurements() new_dag = remove_final_meas.run(dag) kept_cregs = set(new_dag.cregs.values()) kept_clbits = set(new_dag.clbits) # Filter only cregs/clbits still in new DAG, preserving original circuit order cregs_to_add = [creg for creg in circ.cregs if creg in kept_cregs] clbits_to_add = [clbit for clbit in circ._data.clbits if clbit in kept_clbits] # Clear cregs and clbits circ.cregs = [] circ._clbit_indices = {} # Clear instruction info circ._data = CircuitData( qubits=circ._data.qubits, reserve=len(circ._data), global_phase=circ.global_phase ) # We must add the clbits first to preserve the original circuit # order. This way, add_register never adds clbits and just # creates registers that point to them. circ.add_bits(clbits_to_add) for creg in cregs_to_add: circ.add_register(creg) # Set circ instructions to match the new DAG for node in new_dag.topological_op_nodes(): # Get arguments for classical condition (if any) inst = node.op.copy() circ.append(inst, node.qargs, node.cargs) if not inplace: return circ else: return None @staticmethod def from_qasm_file(path: str) -> "QuantumCircuit": """Read an OpenQASM 2.0 program from a file and convert to an instance of :class:`.QuantumCircuit`. Args: path (str): Path to the file for an OpenQASM 2 program Return: QuantumCircuit: The QuantumCircuit object for the input OpenQASM 2. See also: :func:`.qasm2.load`: the complete interface to the OpenQASM 2 importer. """ # pylint: disable=cyclic-import from qiskit import qasm2 return qasm2.load( path, include_path=qasm2.LEGACY_INCLUDE_PATH, custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS, custom_classical=qasm2.LEGACY_CUSTOM_CLASSICAL, strict=False, ) @staticmethod def from_qasm_str(qasm_str: str) -> "QuantumCircuit": """Convert a string containing an OpenQASM 2.0 program to a :class:`.QuantumCircuit`. Args: qasm_str (str): A string containing an OpenQASM 2.0 program. Return: QuantumCircuit: The QuantumCircuit object for the input OpenQASM 2 See also: :func:`.qasm2.loads`: the complete interface to the OpenQASM 2 importer. """ # pylint: disable=cyclic-import from qiskit import qasm2 return qasm2.loads( qasm_str, include_path=qasm2.LEGACY_INCLUDE_PATH, custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS, custom_classical=qasm2.LEGACY_CUSTOM_CLASSICAL, strict=False, ) @property def global_phase(self) -> ParameterValueType: """The global phase of the current circuit scope in radians.""" if self._control_flow_scopes: return self._control_flow_scopes[-1].global_phase return self._data.global_phase @global_phase.setter def global_phase(self, angle: ParameterValueType): """Set the phase of the current circuit scope. Args: angle (float, ParameterExpression): radians """ if self._control_flow_scopes: self._control_flow_scopes[-1].global_phase = angle else: self._data.global_phase = angle @property def parameters(self) -> ParameterView: """The parameters defined in the circuit. This attribute returns the :class:`.Parameter` objects in the circuit sorted alphabetically. Note that parameters instantiated with a :class:`.ParameterVector` are still sorted numerically. Examples: The snippet below shows that insertion order of parameters does not matter. .. code-block:: python >>> from qiskit.circuit import QuantumCircuit, Parameter >>> a, b, elephant = Parameter("a"), Parameter("b"), Parameter("elephant") >>> circuit = QuantumCircuit(1) >>> circuit.rx(b, 0) >>> circuit.rz(elephant, 0) >>> circuit.ry(a, 0) >>> circuit.parameters # sorted alphabetically! ParameterView([Parameter(a), Parameter(b), Parameter(elephant)]) Bear in mind that alphabetical sorting might be unintuitive when it comes to numbers. The literal "10" comes before "2" in strict alphabetical sorting. .. code-block:: python >>> from qiskit.circuit import QuantumCircuit, Parameter >>> angles = [Parameter("angle_1"), Parameter("angle_2"), Parameter("angle_10")] >>> circuit = QuantumCircuit(1) >>> circuit.u(*angles, 0) >>> circuit.draw() ┌─────────────────────────────┐ q: ┤ U(angle_1,angle_2,angle_10) ├ └─────────────────────────────┘ >>> circuit.parameters ParameterView([Parameter(angle_1), Parameter(angle_10), Parameter(angle_2)]) To respect numerical sorting, a :class:`.ParameterVector` can be used. .. code-block:: python >>> from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector >>> x = ParameterVector("x", 12) >>> circuit = QuantumCircuit(1) >>> for x_i in x: ... circuit.rx(x_i, 0) >>> circuit.parameters ParameterView([ ParameterVectorElement(x[0]), ParameterVectorElement(x[1]), ParameterVectorElement(x[2]), ParameterVectorElement(x[3]), ..., ParameterVectorElement(x[11]) ]) Returns: The sorted :class:`.Parameter` objects in the circuit. """ # return as parameter view, which implements the set and list interface return ParameterView(self._data.parameters) @property def num_parameters(self) -> int: """The number of parameter objects in the circuit.""" return self._data.num_parameters() def _unsorted_parameters(self) -> set[Parameter]: """Efficiently get all parameters in the circuit, without any sorting overhead. .. warning:: The returned object may directly view onto the ``ParameterTable`` internals, and so should not be mutated. This is an internal performance detail. Code outside of this package should not use this method. """ # This should be free, by accessing the actual backing data structure of the table, but that # means that we need to copy it if adding keys from the global phase. return self._data.unsorted_parameters() @overload def assign_parameters( self, parameters: Union[Mapping[Parameter, ParameterValueType], Iterable[ParameterValueType]], inplace: Literal[False] = ..., *, flat_input: bool = ..., strict: bool = ..., ) -> "QuantumCircuit": ... @overload def assign_parameters( self, parameters: Union[Mapping[Parameter, ParameterValueType], Iterable[ParameterValueType]], inplace: Literal[True] = ..., *, flat_input: bool = ..., strict: bool = ..., ) -> None: ... def assign_parameters( # pylint: disable=missing-raises-doc self, parameters: Union[Mapping[Parameter, ParameterValueType], Iterable[ParameterValueType]], inplace: bool = False, *, flat_input: bool = False, strict: bool = True, ) -> Optional["QuantumCircuit"]: """Assign parameters to new parameters or values. If ``parameters`` is passed as a dictionary, the keys should be :class:`.Parameter` instances in the current circuit. The values of the dictionary can either be numeric values or new parameter objects. If ``parameters`` is passed as a list or array, the elements are assigned to the current parameters in the order of :attr:`parameters` which is sorted alphabetically (while respecting the ordering in :class:`.ParameterVector` objects). The values can be assigned to the current circuit object or to a copy of it. .. note:: When ``parameters`` is given as a mapping, it is permissible to have keys that are strings of the parameter names; these will be looked up using :meth:`get_parameter`. You can also have keys that are :class:`.ParameterVector` instances, and in this case, the dictionary value should be a sequence of values of the same length as the vector. If you use either of these cases, you must leave the setting ``flat_input=False``; changing this to ``True`` enables the fast path, where all keys must be :class:`.Parameter` instances. Args: parameters: Either a dictionary or iterable specifying the new parameter values. inplace: If False, a copy of the circuit with the bound parameters is returned. If True the circuit instance itself is modified. flat_input: If ``True`` and ``parameters`` is a mapping type, it is assumed to be exactly a mapping of ``{parameter: value}``. By default (``False``), the mapping may also contain :class:`.ParameterVector` keys that point to a corresponding sequence of values, and these will be unrolled during the mapping, or string keys, which will be converted to :class:`.Parameter` instances using :meth:`get_parameter`. strict: If ``False``, any parameters given in the mapping that are not used in the circuit will be ignored. If ``True`` (the default), an error will be raised indicating a logic error. Raises: CircuitError: If parameters is a dict and contains parameters not present in the circuit. ValueError: If parameters is a list/array and the length mismatches the number of free parameters in the circuit. Returns: A copy of the circuit with bound parameters if ``inplace`` is False, otherwise None. Examples: Create a parameterized circuit and assign the parameters in-place. .. plot:: :include-source: from qiskit.circuit import QuantumCircuit, Parameter circuit = QuantumCircuit(2) params = [Parameter('A'), Parameter('B'), Parameter('C')] circuit.ry(params[0], 0) circuit.crx(params[1], 0, 1) circuit.draw('mpl') circuit.assign_parameters({params[0]: params[2]}, inplace=True) circuit.draw('mpl') Bind the values out-of-place by list and get a copy of the original circuit. .. plot:: :include-source: from qiskit.circuit import QuantumCircuit, ParameterVector circuit = QuantumCircuit(2) params = ParameterVector('P', 2) circuit.ry(params[0], 0) circuit.crx(params[1], 0, 1) bound_circuit = circuit.assign_parameters([1, 2]) bound_circuit.draw('mpl') circuit.draw('mpl') """ if inplace: target = self else: if not isinstance(parameters, dict): # We're going to need to access the sorted order wihin the inner Rust method on # `target`, so warm up our own cache first so that subsequent calls to # `assign_parameters` on `self` benefit as well. _ = self._data.parameters target = self.copy() target._increment_instances() target._name_update() if isinstance(parameters, collections.abc.Mapping): raw_mapping = parameters if flat_input else self._unroll_param_dict(parameters) our_parameters = self._data.unsorted_parameters() if strict and (extras := raw_mapping.keys() - our_parameters): raise CircuitError( f"Cannot bind parameters ({', '.join(str(x) for x in extras)}) not present in" " the circuit." ) parameter_binds = _ParameterBindsDict(raw_mapping, our_parameters) target._data.assign_parameters_mapping(parameter_binds) else: parameter_binds = _ParameterBindsSequence(target._data.parameters, parameters) target._data.assign_parameters_iterable(parameters) # Finally, assign the parameters inside any of the calibrations. We don't track these in # the `ParameterTable`, so we manually reconstruct things. def map_calibration(qubits, parameters, schedule): modified = False new_parameters = list(parameters) for i, parameter in enumerate(new_parameters): if not isinstance(parameter, ParameterExpression): continue if not (contained := parameter.parameters & parameter_binds.mapping.keys()): continue for to_bind in contained: parameter = parameter.assign(to_bind, parameter_binds.mapping[to_bind]) if not parameter.parameters: parameter = parameter.numeric() if isinstance(parameter, complex): raise TypeError(f"Calibration cannot use complex number: '{parameter}'") new_parameters[i] = parameter modified = True if modified: schedule.assign_parameters(parameter_binds.mapping) return (qubits, tuple(new_parameters)), schedule target._calibrations = defaultdict( dict, ( ( gate, dict( map_calibration(qubits, parameters, schedule) for (qubits, parameters), schedule in calibrations.items() ), ) for gate, calibrations in target._calibrations.items() ), ) return None if inplace else target def _unroll_param_dict( self, parameter_binds: Mapping[Parameter, ParameterValueType] ) -> Mapping[Parameter, ParameterValueType]: out = {} for parameter, value in parameter_binds.items(): if isinstance(parameter, ParameterVector): if len(parameter) != len(value): raise CircuitError( f"Parameter vector '{parameter.name}' has length {len(parameter)}," f" but was assigned to {len(value)} values." ) out.update(zip(parameter, value)) elif isinstance(parameter, str): out[self.get_parameter(parameter)] = value else: out[parameter] = value return out def barrier(self, *qargs: QubitSpecifier, label=None) -> InstructionSet: """Apply :class:`~.library.Barrier`. If ``qargs`` is empty, applies to all qubits in the circuit. Args: qargs (QubitSpecifier): Specification for one or more qubit arguments. label (str): The string label of the barrier. Returns: qiskit.circuit.InstructionSet: handle to the added instructions. """ from .barrier import Barrier if qargs: # This uses a `dict` not a `set` to guarantee a deterministic order to the arguments. qubits = tuple( {q: None for qarg in qargs for q in self._qbit_argument_conversion(qarg)} ) return self.append( CircuitInstruction(Barrier(len(qubits), label=label), qubits, ()), copy=False ) else: qubits = self.qubits.copy() return self._current_scope().append( CircuitInstruction(Barrier(len(qubits), label=label), qubits, ()) ) def delay( self, duration: ParameterValueType, qarg: QubitSpecifier | None = None, unit: str = "dt", ) -> InstructionSet: """Apply :class:`~.circuit.Delay`. If qarg is ``None``, applies to all qubits. When applying to multiple qubits, delays with the same duration will be created. Args: duration (int or float or ParameterExpression): duration of the delay. qarg (Object): qubit argument to apply this delay. unit (str): unit of the duration. Supported units: ``'s'``, ``'ms'``, ``'us'``, ``'ns'``, ``'ps'``, and ``'dt'``. Default is ``'dt'``, i.e. integer time unit depending on the target backend. Returns: qiskit.circuit.InstructionSet: handle to the added instructions. Raises: CircuitError: if arguments have bad format. """ if qarg is None: qarg = self.qubits return self.append(Delay(duration, unit=unit), [qarg], [], copy=False) def h(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.HGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ return self._append_standard_gate(StandardGate.HGate, [qubit], ()) def ch( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CHGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ # if the control state is |1> use the fast Rust version of the gate if ctrl_state is None or ctrl_state in ["1", 1]: return self._append_standard_gate( StandardGate.CHGate, [control_qubit, target_qubit], (), label=label ) from .library.standard_gates.h import CHGate return self.append( CHGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], copy=False, ) def id(self, qubit: QubitSpecifier) -> InstructionSet: # pylint: disable=invalid-name """Apply :class:`~qiskit.circuit.library.IGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ return self._append_standard_gate(StandardGate.IGate, [qubit], ()) def ms(self, theta: ParameterValueType, qubits: Sequence[QubitSpecifier]) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.MSGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. qubits: The qubits to apply the gate to. Returns: A handle to the instructions created. """ # pylint: disable=cyclic-import from .library.generalized_gates.gms import MSGate return self.append(MSGate(len(qubits), theta), qubits, copy=False) def p(self, theta: ParameterValueType, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.PhaseGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: THe angle of the rotation. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ return self._append_standard_gate(StandardGate.PhaseGate, [qubit], (theta,)) def cp( self, theta: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CPhaseGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ # if the control state is |1> use the fast Rust version of the gate if ctrl_state is None or ctrl_state in ["1", 1]: return self._append_standard_gate( StandardGate.CPhaseGate, [control_qubit, target_qubit], (theta,), label=label ) from .library.standard_gates.p import CPhaseGate return self.append( CPhaseGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], copy=False, ) def mcp( self, lam: ParameterValueType, control_qubits: Sequence[QubitSpecifier], target_qubit: QubitSpecifier, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.MCPhaseGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: lam: The angle of the rotation. control_qubits: The qubits used as the controls. target_qubit: The qubit(s) targeted by the gate. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.p import MCPhaseGate num_ctrl_qubits = len(control_qubits) return self.append( MCPhaseGate(lam, num_ctrl_qubits, ctrl_state=ctrl_state), control_qubits[:] + [target_qubit], [], copy=False, ) def r( self, theta: ParameterValueType, phi: ParameterValueType, qubit: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. phi: The angle of the axis of rotation in the x-y plane. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ return self._append_standard_gate(StandardGate.RGate, [qubit], [theta, phi]) def rv( self, vx: ParameterValueType, vy: ParameterValueType, vz: ParameterValueType, qubit: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RVGate`. For the full matrix form of this gate, see the underlying gate documentation. Rotation around an arbitrary rotation axis :math:`v`, where :math:`|v|` is the angle of rotation in radians. Args: vx: x-component of the rotation axis. vy: y-component of the rotation axis. vz: z-component of the rotation axis. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.generalized_gates.rv import RVGate return self.append(RVGate(vx, vy, vz), [qubit], [], copy=False) def rccx( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, target_qubit: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RCCXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. target_qubit: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. """ return self._append_standard_gate( StandardGate.RCCXGate, [control_qubit1, control_qubit2, target_qubit], () ) def rcccx( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, control_qubit3: QubitSpecifier, target_qubit: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RC3XGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. control_qubit3: The qubit(s) used as the third control. target_qubit: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. """ return self._append_standard_gate( StandardGate.RC3XGate, [control_qubit1, control_qubit2, control_qubit3, target_qubit], (), ) def rx( self, theta: ParameterValueType, qubit: QubitSpecifier, label: str | None = None ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit: The qubit(s) to apply the gate to. label: The string label of the gate in the circuit. Returns: A handle to the instructions created. """ return self._append_standard_gate(StandardGate.RXGate, [qubit], [theta], label=label) def crx( self, theta: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CRXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ # if the control state is |1> use the fast Rust version of the gate if ctrl_state is None or ctrl_state in ["1", 1]: return self._append_standard_gate( StandardGate.CRXGate, [control_qubit, target_qubit], [theta], label=label ) from .library.standard_gates.rx import CRXGate return self.append( CRXGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], copy=False, ) def rxx( self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RXXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ return self._append_standard_gate(StandardGate.RXXGate, [qubit1, qubit2], [theta]) def ry( self, theta: ParameterValueType, qubit: QubitSpecifier, label: str | None = None ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RYGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit: The qubit(s) to apply the gate to. label: The string label of the gate in the circuit. Returns: A handle to the instructions created. """ return self._append_standard_gate(StandardGate.RYGate, [qubit], [theta], label=label) def cry( self, theta: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CRYGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ # if the control state is |1> use the fast Rust version of the gate if ctrl_state is None or ctrl_state in ["1", 1]: return self._append_standard_gate( StandardGate.CRYGate, [control_qubit, target_qubit], [theta], label=label ) from .library.standard_gates.ry import CRYGate return self.append( CRYGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], copy=False, ) def ryy( self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RYYGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ return self._append_standard_gate(StandardGate.RYYGate, [qubit1, qubit2], [theta]) def rz(self, phi: ParameterValueType, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: phi: The rotation angle of the gate. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ return self._append_standard_gate(StandardGate.RZGate, [qubit], [phi]) def crz( self, theta: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CRZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ # if the control state is |1> use the fast Rust version of the gate if ctrl_state is None or ctrl_state in ["1", 1]: return self._append_standard_gate( StandardGate.CRZGate, [control_qubit, target_qubit], [theta], label=label ) from .library.standard_gates.rz import CRZGate return self.append( CRZGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], copy=False, ) def rzx( self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RZXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ return self._append_standard_gate(StandardGate.RZXGate, [qubit1, qubit2], [theta]) def rzz( self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RZZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ return self._append_standard_gate(StandardGate.RZZGate, [qubit1, qubit2], [theta]) def ecr(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.ECRGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit1, qubit2: The qubits to apply the gate to. Returns: A handle to the instructions created. """ return self._append_standard_gate(StandardGate.ECRGate, [qubit1, qubit2], ()) def s(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ return self._append_standard_gate(StandardGate.SGate, [qubit], ()) def sdg(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SdgGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ return self._append_standard_gate(StandardGate.SdgGate, [qubit], ()) def cs( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ # if the control state is |1> use the fast Rust version of the gate if ctrl_state is None or ctrl_state in ["1", 1]: return self._append_standard_gate( StandardGate.CSGate, [control_qubit, target_qubit], (), label=label ) from .library.standard_gates.s import CSGate return self.append( CSGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], copy=False, ) def csdg( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSdgGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ # if the control state is |1> use the fast Rust version of the gate if ctrl_state is None or ctrl_state in ["1", 1]: return self._append_standard_gate( StandardGate.CSdgGate, [control_qubit, target_qubit], (), label=label ) from .library.standard_gates.s import CSdgGate return self.append( CSdgGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], copy=False, ) def swap(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SwapGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit1, qubit2: The qubits to apply the gate to. Returns: A handle to the instructions created. """ return self._append_standard_gate( StandardGate.SwapGate, [qubit1, qubit2], (), ) def iswap(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.iSwapGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit1, qubit2: The qubits to apply the gate to. Returns: A handle to the instructions created. """ return self._append_standard_gate(StandardGate.ISwapGate, [qubit1, qubit2], ()) def cswap( self, control_qubit: QubitSpecifier, target_qubit1: QubitSpecifier, target_qubit2: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSwapGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit1: The qubit(s) targeted by the gate. target_qubit2: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. ``'1'``). Defaults to controlling on the ``'1'`` state. Returns: A handle to the instructions created. """ # if the control state is |1> use the fast Rust version of the gate if ctrl_state is None or ctrl_state in ["1", 1]: return self._append_standard_gate( StandardGate.CSwapGate, [control_qubit, target_qubit1, target_qubit2], (), label=label, ) from .library.standard_gates.swap import CSwapGate return self.append( CSwapGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit1, target_qubit2], [], copy=False, ) def sx(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ return self._append_standard_gate(StandardGate.SXGate, [qubit], ()) def sxdg(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SXdgGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ return self._append_standard_gate(StandardGate.SXdgGate, [qubit], ()) def csx( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ # if the control state is |1> use the fast Rust version of the gate if ctrl_state is None or ctrl_state in ["1", 1]: return self._append_standard_gate( StandardGate.CSXGate, [control_qubit, target_qubit], (), label=label ) from .library.standard_gates.sx import CSXGate return self.append( CSXGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], copy=False, ) def t(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.TGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ return self._append_standard_gate(StandardGate.TGate, [qubit], ()) def tdg(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.TdgGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ return self._append_standard_gate(StandardGate.TdgGate, [qubit], ()) def u( self, theta: ParameterValueType, phi: ParameterValueType, lam: ParameterValueType, qubit: QubitSpecifier, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.UGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The :math:`\theta` rotation angle of the gate. phi: The :math:`\phi` rotation angle of the gate. lam: The :math:`\lambda` rotation angle of the gate. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ return self._append_standard_gate(StandardGate.UGate, [qubit], [theta, phi, lam]) def cu( self, theta: ParameterValueType, phi: ParameterValueType, lam: ParameterValueType, gamma: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CUGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The :math:`\theta` rotation angle of the gate. phi: The :math:`\phi` rotation angle of the gate. lam: The :math:`\lambda` rotation angle of the gate. gamma: The global phase applied of the U gate, if applied. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ # if the control state is |1> use the fast Rust version of the gate if ctrl_state is None or ctrl_state in ["1", 1]: return self._append_standard_gate( StandardGate.CUGate, [control_qubit, target_qubit], [theta, phi, lam, gamma], label=label, ) from .library.standard_gates.u import CUGate return self.append( CUGate(theta, phi, lam, gamma, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], copy=False, ) def x(self, qubit: QubitSpecifier, label: str | None = None) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.XGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. label: The string label of the gate in the circuit. Returns: A handle to the instructions created. """ return self._append_standard_gate(StandardGate.XGate, [qubit], (), label=label) def cx( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ # if the control state is |1> use the fast Rust version of the gate if ctrl_state is None or ctrl_state in ["1", 1]: return self._append_standard_gate( StandardGate.CXGate, [control_qubit, target_qubit], (), label=label, ) from .library.standard_gates.x import CXGate return self.append( CXGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], copy=False, ) def dcx(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.DCXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ return self._append_standard_gate(StandardGate.DCXGate, [qubit1, qubit2], ()) def ccx( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, target_qubit: QubitSpecifier, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CCXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. target_qubit: The qubit(s) targeted by the gate. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ # if the control state is |11> use the fast Rust version of the gate if ctrl_state is None or ctrl_state in ["11", 3]: return self._append_standard_gate( StandardGate.CCXGate, [control_qubit1, control_qubit2, target_qubit], (), ) from .library.standard_gates.x import CCXGate return self.append( CCXGate(ctrl_state=ctrl_state), [control_qubit1, control_qubit2, target_qubit], [], copy=False, ) def mcx( self, control_qubits: Sequence[QubitSpecifier], target_qubit: QubitSpecifier, ancilla_qubits: QubitSpecifier | Sequence[QubitSpecifier] | None = None, mode: str = "noancilla", ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.MCXGate`. The multi-cX gate can be implemented using different techniques, which use different numbers of ancilla qubits and have varying circuit depth. These modes are: - ``'noancilla'``: Requires 0 ancilla qubits. - ``'recursion'``: Requires 1 ancilla qubit if more than 4 controls are used, otherwise 0. - ``'v-chain'``: Requires 2 less ancillas than the number of control qubits. - ``'v-chain-dirty'``: Same as for the clean ancillas (but the circuit will be longer). For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubits: The qubits used as the controls. target_qubit: The qubit(s) targeted by the gate. ancilla_qubits: The qubits used as the ancillae, if the mode requires them. mode: The choice of mode, explained further above. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. Raises: ValueError: if the given mode is not known, or if too few ancilla qubits are passed. AttributeError: if no ancilla qubits are passed, but some are needed. """ from .library.standard_gates.x import MCXGate, MCXRecursive, MCXVChain num_ctrl_qubits = len(control_qubits) available_implementations = { "noancilla": MCXGate(num_ctrl_qubits, ctrl_state=ctrl_state), "recursion": MCXRecursive(num_ctrl_qubits, ctrl_state=ctrl_state), "v-chain": MCXVChain(num_ctrl_qubits, False, ctrl_state=ctrl_state), "v-chain-dirty": MCXVChain(num_ctrl_qubits, dirty_ancillas=True, ctrl_state=ctrl_state), # outdated, previous names "advanced": MCXRecursive(num_ctrl_qubits, ctrl_state=ctrl_state), "basic": MCXVChain(num_ctrl_qubits, dirty_ancillas=False, ctrl_state=ctrl_state), "basic-dirty-ancilla": MCXVChain( num_ctrl_qubits, dirty_ancillas=True, ctrl_state=ctrl_state ), } # check ancilla input if ancilla_qubits: _ = self._qbit_argument_conversion(ancilla_qubits) try: gate = available_implementations[mode] except KeyError as ex: all_modes = list(available_implementations.keys()) raise ValueError( f"Unsupported mode ({mode}) selected, choose one of {all_modes}" ) from ex if hasattr(gate, "num_ancilla_qubits") and gate.num_ancilla_qubits > 0: required = gate.num_ancilla_qubits if ancilla_qubits is None: raise AttributeError(f"No ancillas provided, but {required} are needed!") # convert ancilla qubits to a list if they were passed as int or qubit if not hasattr(ancilla_qubits, "__len__"): ancilla_qubits = [ancilla_qubits] if len(ancilla_qubits) < required: actually = len(ancilla_qubits) raise ValueError(f"At least {required} ancillas required, but {actually} given.") # size down if too many ancillas were provided ancilla_qubits = ancilla_qubits[:required] else: ancilla_qubits = [] return self.append(gate, control_qubits[:] + [target_qubit] + ancilla_qubits[:], []) def y(self, qubit: QubitSpecifier) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.YGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ return self._append_standard_gate(StandardGate.YGate, [qubit], ()) def cy( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CYGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the controls. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ # if the control state is |1> use the fast Rust version of the gate if ctrl_state is None or ctrl_state in ["1", 1]: return self._append_standard_gate( StandardGate.CYGate, [control_qubit, target_qubit], (), label=label, ) from .library.standard_gates.y import CYGate return self.append( CYGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], copy=False, ) def z(self, qubit: QubitSpecifier) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.ZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ return self._append_standard_gate(StandardGate.ZGate, [qubit], ()) def cz( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the controls. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ # if the control state is |1> use the fast Rust version of the gate if ctrl_state is None or ctrl_state in ["1", 1]: return self._append_standard_gate( StandardGate.CZGate, [control_qubit, target_qubit], (), label=label ) from .library.standard_gates.z import CZGate return self.append( CZGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], copy=False, ) def ccz( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CCZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '10'). Defaults to controlling on the '11' state. Returns: A handle to the instructions created. """ # if the control state is |11> use the fast Rust version of the gate if ctrl_state is None or ctrl_state in ["11", 3]: return self._append_standard_gate( StandardGate.CCZGate, [control_qubit1, control_qubit2, target_qubit], (), label=label, ) from .library.standard_gates.z import CCZGate return self.append( CCZGate(label=label, ctrl_state=ctrl_state), [control_qubit1, control_qubit2, target_qubit], [], copy=False, ) def pauli( self, pauli_string: str, qubits: Sequence[QubitSpecifier], ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.PauliGate`. Args: pauli_string: A string representing the Pauli operator to apply, e.g. 'XX'. qubits: The qubits to apply this gate to. Returns: A handle to the instructions created. """ from qiskit.circuit.library.generalized_gates.pauli import PauliGate return self.append(PauliGate(pauli_string), qubits, [], copy=False) def prepare_state( self, state: Statevector | Sequence[complex] | str | int, qubits: Sequence[QubitSpecifier] | None = None, label: str | None = None, normalize: bool = False, ) -> InstructionSet: r"""Prepare qubits in a specific state. This class implements a state preparing unitary. Unlike :meth:`.initialize` it does not reset the qubits first. Args: state: The state to initialize to, can be either of the following. * Statevector or vector of complex amplitudes to initialize to. * Labels of basis states of the Pauli eigenstates Z, X, Y. See :meth:`.Statevector.from_label`. Notice the order of the labels is reversed with respect to the qubit index to be applied to. Example label '01' initializes the qubit zero to :math:`|1\rangle` and the qubit one to :math:`|0\rangle`. * An integer that is used as a bitmap indicating which qubits to initialize to :math:`|1\rangle`. Example: setting params to 5 would initialize qubit 0 and qubit 2 to :math:`|1\rangle` and qubit 1 to :math:`|0\rangle`. qubits: Qubits to initialize. If ``None`` the initialization is applied to all qubits in the circuit. label: An optional label for the gate normalize: Whether to normalize an input array to a unit vector. Returns: A handle to the instruction that was just initialized Examples: Prepare a qubit in the state :math:`(|0\rangle - |1\rangle) / \sqrt{2}`. .. code-block:: import numpy as np from qiskit import QuantumCircuit circuit = QuantumCircuit(1) circuit.prepare_state([1/np.sqrt(2), -1/np.sqrt(2)], 0) circuit.draw() output: .. parsed-literal:: ┌─────────────────────────────────────┐ q_0: ┤ State Preparation(0.70711,-0.70711) ├ └─────────────────────────────────────┘ Prepare from a string two qubits in the state :math:`|10\rangle`. The order of the labels is reversed with respect to qubit index. More information about labels for basis states are in :meth:`.Statevector.from_label`. .. code-block:: import numpy as np from qiskit import QuantumCircuit circuit = QuantumCircuit(2) circuit.prepare_state('01', circuit.qubits) circuit.draw() output: .. parsed-literal:: ┌─────────────────────────┐ q_0: ┤0 ├ │ State Preparation(0,1) │ q_1: ┤1 ├ └─────────────────────────┘ Initialize two qubits from an array of complex amplitudes .. code-block:: import numpy as np from qiskit import QuantumCircuit circuit = QuantumCircuit(2) circuit.prepare_state([0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0], circuit.qubits) circuit.draw() output: .. parsed-literal:: ┌───────────────────────────────────────────┐ q_0: ┤0 ├ │ State Preparation(0,0.70711,-0.70711j,0) │ q_1: ┤1 ├ └───────────────────────────────────────────┘ """ # pylint: disable=cyclic-import from qiskit.circuit.library.data_preparation import StatePreparation if qubits is None: qubits = self.qubits elif isinstance(qubits, (int, np.integer, slice, Qubit)): qubits = [qubits] num_qubits = len(qubits) if isinstance(state, int) else None return self.append( StatePreparation(state, num_qubits, label=label, normalize=normalize), qubits, copy=False, ) def initialize( self, params: Statevector | Sequence[complex] | str | int, qubits: Sequence[QubitSpecifier] | None = None, normalize: bool = False, ): r"""Initialize qubits in a specific state. Qubit initialization is done by first resetting the qubits to :math:`|0\rangle` followed by calling :class:`~qiskit.circuit.library.StatePreparation` class to prepare the qubits in a specified state. Both these steps are included in the :class:`~qiskit.circuit.library.Initialize` instruction. Args: params: The state to initialize to, can be either of the following. * Statevector or vector of complex amplitudes to initialize to. * Labels of basis states of the Pauli eigenstates Z, X, Y. See :meth:`.Statevector.from_label`. Notice the order of the labels is reversed with respect to the qubit index to be applied to. Example label ``'01'`` initializes the qubit zero to :math:`|1\rangle` and the qubit one to :math:`|0\rangle`. * An integer that is used as a bitmap indicating which qubits to initialize to :math:`|1\rangle`. Example: setting params to 5 would initialize qubit 0 and qubit 2 to :math:`|1\rangle` and qubit 1 to :math:`|0\rangle`. qubits: Qubits to initialize. If ``None`` the initialization is applied to all qubits in the circuit. normalize: Whether to normalize an input array to a unit vector. Returns: A handle to the instructions created. Examples: Prepare a qubit in the state :math:`(|0\rangle - |1\rangle) / \sqrt{2}`. .. code-block:: import numpy as np from qiskit import QuantumCircuit circuit = QuantumCircuit(1) circuit.initialize([1/np.sqrt(2), -1/np.sqrt(2)], 0) circuit.draw() output: .. parsed-literal:: ┌──────────────────────────────┐ q_0: ┤ Initialize(0.70711,-0.70711) ├ └──────────────────────────────┘ Initialize from a string two qubits in the state :math:`|10\rangle`. The order of the labels is reversed with respect to qubit index. More information about labels for basis states are in :meth:`.Statevector.from_label`. .. code-block:: import numpy as np from qiskit import QuantumCircuit circuit = QuantumCircuit(2) circuit.initialize('01', circuit.qubits) circuit.draw() output: .. parsed-literal:: ┌──────────────────┐ q_0: ┤0 ├ │ Initialize(0,1) │ q_1: ┤1 ├ └──────────────────┘ Initialize two qubits from an array of complex amplitudes. .. code-block:: import numpy as np from qiskit import QuantumCircuit circuit = QuantumCircuit(2) circuit.initialize([0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0], circuit.qubits) circuit.draw() output: .. parsed-literal:: ┌────────────────────────────────────┐ q_0: ┤0 ├ │ Initialize(0,0.70711,-0.70711j,0) │ q_1: ┤1 ├ └────────────────────────────────────┘ """ # pylint: disable=cyclic-import from .library.data_preparation.initializer import Initialize if qubits is None: qubits = self.qubits elif isinstance(qubits, (int, np.integer, slice, Qubit)): qubits = [qubits] num_qubits = len(qubits) if isinstance(params, int) else None return self.append(Initialize(params, num_qubits, normalize), qubits, copy=False) def unitary( self, obj: np.ndarray | Gate | BaseOperator, qubits: Sequence[QubitSpecifier], label: str | None = None, ): """Apply unitary gate specified by ``obj`` to ``qubits``. Args: obj: Unitary operator. qubits: The circuit qubits to apply the transformation to. label: Unitary name for backend [Default: None]. Returns: QuantumCircuit: The quantum circuit. Example: Apply a gate specified by a unitary matrix to a quantum circuit .. code-block:: python from qiskit import QuantumCircuit matrix = [[0, 0, 0, 1], [0, 0, 1, 0], [1, 0, 0, 0], [0, 1, 0, 0]] circuit = QuantumCircuit(2) circuit.unitary(matrix, [0, 1]) """ # pylint: disable=cyclic-import from .library.generalized_gates.unitary import UnitaryGate gate = UnitaryGate(obj, label=label) # correctly treat as single-qubit gate if it only acts as 1 qubit, i.e. # allow a single qubit specifier and enable broadcasting if gate.num_qubits == 1: if isinstance(qubits, (int, Qubit)) or len(qubits) > 1: qubits = [qubits] return self.append(gate, qubits, [], copy=False) def _current_scope(self) -> CircuitScopeInterface: if self._control_flow_scopes: return self._control_flow_scopes[-1] return self._builder_api def _push_scope( self, qubits: Iterable[Qubit] = (), clbits: Iterable[Clbit] = (), registers: Iterable[Register] = (), allow_jumps: bool = True, forbidden_message: Optional[str] = None, ): """Add a scope for collecting instructions into this circuit. This should only be done by the control-flow context managers, which will handle cleaning up after themselves at the end as well. Args: qubits: Any qubits that this scope should automatically use. clbits: Any clbits that this scope should automatically use. allow_jumps: Whether this scope allows jumps to be used within it. forbidden_message: If given, all attempts to add instructions to this scope will raise a :exc:`.CircuitError` with this message. """ self._control_flow_scopes.append( ControlFlowBuilderBlock( qubits, clbits, parent=self._current_scope(), registers=registers, allow_jumps=allow_jumps, forbidden_message=forbidden_message, ) ) def _pop_scope(self) -> ControlFlowBuilderBlock: """Finish a scope used in the control-flow builder interface, and return it to the caller. This should only be done by the control-flow context managers, since they naturally synchronize the creation and deletion of stack elements.""" return self._control_flow_scopes.pop() def _peek_previous_instruction_in_scope(self) -> CircuitInstruction: """Return the instruction 3-tuple of the most recent instruction in the current scope, even if that scope is currently under construction. This function is only intended for use by the control-flow ``if``-statement builders, which may need to modify a previous instruction.""" if self._control_flow_scopes: return self._control_flow_scopes[-1].peek() if not self._data: raise CircuitError("This circuit contains no instructions.") return self._data[-1] def _pop_previous_instruction_in_scope(self) -> CircuitInstruction: """Return the instruction 3-tuple of the most recent instruction in the current scope, even if that scope is currently under construction, and remove it from that scope. This function is only intended for use by the control-flow ``if``-statement builders, which may need to replace a previous instruction with another. """ if self._control_flow_scopes: return self._control_flow_scopes[-1].pop() if not self._data: raise CircuitError("This circuit contains no instructions.") instruction = self._data.pop() return instruction @typing.overload def while_loop( self, condition: tuple[ClassicalRegister | Clbit, int] | expr.Expr, body: None, qubits: None, clbits: None, *, label: str | None, ) -> WhileLoopContext: ... @typing.overload def while_loop( self, condition: tuple[ClassicalRegister | Clbit, int] | expr.Expr, body: "QuantumCircuit", qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], *, label: str | None, ) -> InstructionSet: ... def while_loop(self, condition, body=None, qubits=None, clbits=None, *, label=None): """Create a ``while`` loop on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of ``label``), it will create a :obj:`~qiskit.circuit.controlflow.WhileLoopOp` with the given ``body``. If ``body`` (and ``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which will automatically build a :obj:`~qiskit.circuit.controlflow.WhileLoopOp` when the scope finishes. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. Example usage:: from qiskit.circuit import QuantumCircuit, Clbit, Qubit bits = [Qubit(), Qubit(), Clbit()] qc = QuantumCircuit(bits) with qc.while_loop((bits[2], 0)): qc.h(0) qc.cx(0, 1) qc.measure(0, 0) Args: condition (Tuple[Union[ClassicalRegister, Clbit], int]): An equality condition to be checked prior to executing ``body``. The left-hand side of the condition must be a :obj:`~ClassicalRegister` or a :obj:`~Clbit`, and the right-hand side must be an integer or boolean. body (Optional[QuantumCircuit]): The loop body to be repeatedly executed. Omit this to use the context-manager mode. qubits (Optional[Sequence[Qubit]]): The circuit qubits over which the loop body should be run. Omit this to use the context-manager mode. clbits (Optional[Sequence[Clbit]]): The circuit clbits over which the loop body should be run. Omit this to use the context-manager mode. label (Optional[str]): The string label of the instruction in the circuit. Returns: InstructionSet or WhileLoopContext: If used in context-manager mode, then this should be used as a ``with`` resource, which will infer the block content and operands on exit. If the full form is used, then this returns a handle to the instructions created. Raises: CircuitError: if an incorrect calling convention is used. """ circuit_scope = self._current_scope() if isinstance(condition, expr.Expr): condition = _validate_expr(circuit_scope, condition) else: condition = (circuit_scope.resolve_classical_resource(condition[0]), condition[1]) if body is None: if qubits is not None or clbits is not None: raise CircuitError( "When using 'while_loop' as a context manager," " you cannot pass qubits or clbits." ) return WhileLoopContext(self, condition, label=label) elif qubits is None or clbits is None: raise CircuitError( "When using 'while_loop' with a body, you must pass qubits and clbits." ) return self.append(WhileLoopOp(condition, body, label), qubits, clbits, copy=False) @typing.overload def for_loop( self, indexset: Iterable[int], loop_parameter: Parameter | None, body: None, qubits: None, clbits: None, *, label: str | None, ) -> ForLoopContext: ... @typing.overload def for_loop( self, indexset: Iterable[int], loop_parameter: Union[Parameter, None], body: "QuantumCircuit", qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], *, label: str | None, ) -> InstructionSet: ... def for_loop( self, indexset, loop_parameter=None, body=None, qubits=None, clbits=None, *, label=None ): """Create a ``for`` loop on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of ``label``), it will create a :class:`~qiskit.circuit.ForLoopOp` with the given ``body``. If ``body`` (and ``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which, when entered, provides a loop variable (unless one is given, in which case it will be reused) and will automatically build a :class:`~qiskit.circuit.ForLoopOp` when the scope finishes. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. For example:: from qiskit import QuantumCircuit qc = QuantumCircuit(2, 1) with qc.for_loop(range(5)) as i: qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc.break_loop().c_if(0, True) Args: indexset (Iterable[int]): A collection of integers to loop over. Always necessary. loop_parameter (Optional[Parameter]): The parameter used within ``body`` to which the values from ``indexset`` will be assigned. In the context-manager form, if this argument is not supplied, then a loop parameter will be allocated for you and returned as the value of the ``with`` statement. This will only be bound into the circuit if it is used within the body. If this argument is ``None`` in the manual form of this method, ``body`` will be repeated once for each of the items in ``indexset`` but their values will be ignored. body (Optional[QuantumCircuit]): The loop body to be repeatedly executed. Omit this to use the context-manager mode. qubits (Optional[Sequence[QubitSpecifier]]): The circuit qubits over which the loop body should be run. Omit this to use the context-manager mode. clbits (Optional[Sequence[ClbitSpecifier]]): The circuit clbits over which the loop body should be run. Omit this to use the context-manager mode. label (Optional[str]): The string label of the instruction in the circuit. Returns: InstructionSet or ForLoopContext: depending on the call signature, either a context manager for creating the for loop (it will automatically be added to the circuit at the end of the block), or an :obj:`~InstructionSet` handle to the appended loop operation. Raises: CircuitError: if an incorrect calling convention is used. """ if body is None: if qubits is not None or clbits is not None: raise CircuitError( "When using 'for_loop' as a context manager, you cannot pass qubits or clbits." ) return ForLoopContext(self, indexset, loop_parameter, label=label) elif qubits is None or clbits is None: raise CircuitError( "When using 'for_loop' with a body, you must pass qubits and clbits." ) return self.append( ForLoopOp(indexset, loop_parameter, body, label), qubits, clbits, copy=False ) @typing.overload def if_test(self, condition: tuple[ClassicalRegister | Clbit, int]) -> IfContext: ... @typing.overload def if_test( self, condition: tuple[ClassicalRegister | Clbit, int], true_body: "QuantumCircuit", qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], *, label: str | None = None, ) -> InstructionSet: ... def if_test( self, condition, true_body=None, qubits=None, clbits=None, *, label=None, ): """Create an ``if`` statement on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of ``label``), it will create a :obj:`~qiskit.circuit.IfElseOp` with the given ``true_body``, and there will be no branch for the ``false`` condition (see also the :meth:`.if_else` method). However, if ``true_body`` (and ``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which can be used to build ``if`` statements. The return value of the ``with`` statement is a chainable context manager, which can be used to create subsequent ``else`` blocks. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. For example:: from qiskit.circuit import QuantumCircuit, Qubit, Clbit bits = [Qubit(), Qubit(), Qubit(), Clbit(), Clbit()] qc = QuantumCircuit(bits) qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc.h(0) qc.cx(0, 1) qc.measure(0, 1) with qc.if_test((bits[3], 0)) as else_: qc.x(2) with else_: qc.h(2) qc.z(2) Args: condition (Tuple[Union[ClassicalRegister, Clbit], int]): A condition to be evaluated in real time during circuit execution, which, if true, will trigger the evaluation of ``true_body``. Can be specified as either a tuple of a ``ClassicalRegister`` to be tested for equality with a given ``int``, or as a tuple of a ``Clbit`` to be compared to either a ``bool`` or an ``int``. true_body (Optional[QuantumCircuit]): The circuit body to be run if ``condition`` is true. qubits (Optional[Sequence[QubitSpecifier]]): The circuit qubits over which the if/else should be run. clbits (Optional[Sequence[ClbitSpecifier]]): The circuit clbits over which the if/else should be run. label (Optional[str]): The string label of the instruction in the circuit. Returns: InstructionSet or IfContext: depending on the call signature, either a context manager for creating the ``if`` block (it will automatically be added to the circuit at the end of the block), or an :obj:`~InstructionSet` handle to the appended conditional operation. Raises: CircuitError: If the provided condition references Clbits outside the enclosing circuit. CircuitError: if an incorrect calling convention is used. Returns: A handle to the instruction created. """ circuit_scope = self._current_scope() if isinstance(condition, expr.Expr): condition = _validate_expr(circuit_scope, condition) else: condition = (circuit_scope.resolve_classical_resource(condition[0]), condition[1]) if true_body is None: if qubits is not None or clbits is not None: raise CircuitError( "When using 'if_test' as a context manager, you cannot pass qubits or clbits." ) # We can only allow jumps if we're in a loop block, but the default path (no scopes) # also allows adding jumps to support the more verbose internal mode. in_loop = bool(self._control_flow_scopes and self._control_flow_scopes[-1].allow_jumps) return IfContext(self, condition, in_loop=in_loop, label=label) elif qubits is None or clbits is None: raise CircuitError("When using 'if_test' with a body, you must pass qubits and clbits.") return self.append(IfElseOp(condition, true_body, None, label), qubits, clbits, copy=False) def if_else( self, condition: tuple[ClassicalRegister, int] | tuple[Clbit, int] | tuple[Clbit, bool], true_body: "QuantumCircuit", false_body: "QuantumCircuit", qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], label: str | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.IfElseOp`. .. note:: This method does not have an associated context-manager form, because it is already handled by the :meth:`.if_test` method. You can use the ``else`` part of that with something such as:: from qiskit.circuit import QuantumCircuit, Qubit, Clbit bits = [Qubit(), Qubit(), Clbit()] qc = QuantumCircuit(bits) qc.h(0) qc.cx(0, 1) qc.measure(0, 0) with qc.if_test((bits[2], 0)) as else_: qc.h(0) with else_: qc.x(0) Args: condition: A condition to be evaluated in real time at circuit execution, which, if true, will trigger the evaluation of ``true_body``. Can be specified as either a tuple of a ``ClassicalRegister`` to be tested for equality with a given ``int``, or as a tuple of a ``Clbit`` to be compared to either a ``bool`` or an ``int``. true_body: The circuit body to be run if ``condition`` is true. false_body: The circuit to be run if ``condition`` is false. qubits: The circuit qubits over which the if/else should be run. clbits: The circuit clbits over which the if/else should be run. label: The string label of the instruction in the circuit. Raises: CircuitError: If the provided condition references Clbits outside the enclosing circuit. Returns: A handle to the instruction created. """ circuit_scope = self._current_scope() if isinstance(condition, expr.Expr): condition = _validate_expr(circuit_scope, condition) else: condition = (circuit_scope.resolve_classical_resource(condition[0]), condition[1]) return self.append( IfElseOp(condition, true_body, false_body, label), qubits, clbits, copy=False ) @typing.overload def switch( self, target: Union[ClbitSpecifier, ClassicalRegister], cases: None, qubits: None, clbits: None, *, label: Optional[str], ) -> SwitchContext: ... @typing.overload def switch( self, target: Union[ClbitSpecifier, ClassicalRegister], cases: Iterable[Tuple[typing.Any, QuantumCircuit]], qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], *, label: Optional[str], ) -> InstructionSet: ... def switch(self, target, cases=None, qubits=None, clbits=None, *, label=None): """Create a ``switch``/``case`` structure on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of ``label``), it will create a :class:`.SwitchCaseOp` with the given case structure. If ``cases`` (and ``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which will automatically build a :class:`.SwitchCaseOp` when the scope finishes. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. Example usage:: from qiskit.circuit import QuantumCircuit, ClassicalRegister, QuantumRegister qreg = QuantumRegister(3) creg = ClassicalRegister(3) qc = QuantumCircuit(qreg, creg) qc.h([0, 1, 2]) qc.measure([0, 1, 2], [0, 1, 2]) with qc.switch(creg) as case: with case(0): qc.x(0) with case(1, 2): qc.z(1) with case(case.DEFAULT): qc.cx(0, 1) Args: target (Union[ClassicalRegister, Clbit]): The classical value to switch one. This must be integer-like. cases (Iterable[Tuple[typing.Any, QuantumCircuit]]): A sequence of case specifiers. Each tuple defines one case body (the second item). The first item of the tuple can be either a single integer value, the special value :data:`.CASE_DEFAULT`, or a tuple of several integer values. Each of the integer values will be tried in turn; control will then pass to the body corresponding to the first match. :data:`.CASE_DEFAULT` matches all possible values. Omit in context-manager form. qubits (Sequence[Qubit]): The circuit qubits over which all case bodies execute. Omit in context-manager form. clbits (Sequence[Clbit]): The circuit clbits over which all case bodies execute. Omit in context-manager form. label (Optional[str]): The string label of the instruction in the circuit. Returns: InstructionSet or SwitchCaseContext: If used in context-manager mode, then this should be used as a ``with`` resource, which will return an object that can be repeatedly entered to produce cases for the switch statement. If the full form is used, then this returns a handle to the instructions created. Raises: CircuitError: if an incorrect calling convention is used. """ circuit_scope = self._current_scope() if isinstance(target, expr.Expr): target = _validate_expr(circuit_scope, target) else: target = circuit_scope.resolve_classical_resource(target) if cases is None: if qubits is not None or clbits is not None: raise CircuitError( "When using 'switch' as a context manager, you cannot pass qubits or clbits." ) in_loop = bool(self._control_flow_scopes and self._control_flow_scopes[-1].allow_jumps) return SwitchContext(self, target, in_loop=in_loop, label=label) if qubits is None or clbits is None: raise CircuitError("When using 'switch' with cases, you must pass qubits and clbits.") return self.append(SwitchCaseOp(target, cases, label=label), qubits, clbits, copy=False) def break_loop(self) -> InstructionSet: """Apply :class:`~qiskit.circuit.BreakLoopOp`. .. warning:: If you are using the context-manager "builder" forms of :meth:`.if_test`, :meth:`.for_loop` or :meth:`.while_loop`, you can only call this method if you are within a loop context, because otherwise the "resource width" of the operation cannot be determined. This would quickly lead to invalid circuits, and so if you are trying to construct a reusable loop body (without the context managers), you must also use the non-context-manager form of :meth:`.if_test` and :meth:`.if_else`. Take care that the :obj:`.BreakLoopOp` instruction must span all the resources of its containing loop, not just the immediate scope. Returns: A handle to the instruction created. Raises: CircuitError: if this method was called within a builder context, but not contained within a loop. """ if self._control_flow_scopes: operation = BreakLoopPlaceholder() resources = operation.placeholder_resources() return self.append(operation, resources.qubits, resources.clbits, copy=False) return self.append( BreakLoopOp(self.num_qubits, self.num_clbits), self.qubits, self.clbits, copy=False ) def continue_loop(self) -> InstructionSet: """Apply :class:`~qiskit.circuit.ContinueLoopOp`. .. warning:: If you are using the context-manager "builder" forms of :meth:`.if_test`, :meth:`.for_loop` or :meth:`.while_loop`, you can only call this method if you are within a loop context, because otherwise the "resource width" of the operation cannot be determined. This would quickly lead to invalid circuits, and so if you are trying to construct a reusable loop body (without the context managers), you must also use the non-context-manager form of :meth:`.if_test` and :meth:`.if_else`. Take care that the :class:`~qiskit.circuit.ContinueLoopOp` instruction must span all the resources of its containing loop, not just the immediate scope. Returns: A handle to the instruction created. Raises: CircuitError: if this method was called within a builder context, but not contained within a loop. """ if self._control_flow_scopes: operation = ContinueLoopPlaceholder() resources = operation.placeholder_resources() return self.append(operation, resources.qubits, resources.clbits, copy=False) return self.append( ContinueLoopOp(self.num_qubits, self.num_clbits), self.qubits, self.clbits, copy=False ) def add_calibration( self, gate: Union[Gate, str], qubits: Sequence[int], # Schedule has the type `qiskit.pulse.Schedule`, but `qiskit.pulse` cannot be imported # while this module is, and so Sphinx will not accept a forward reference to it. Sphinx # needs the types available at runtime, whereas mypy will accept it, because it handles the # type checking by static analysis. schedule, params: Sequence[ParameterValueType] | None = None, ) -> None: """Register a low-level, custom pulse definition for the given gate. Args: gate (Union[Gate, str]): Gate information. qubits (Union[int, Tuple[int]]): List of qubits to be measured. schedule (Schedule): Schedule information. params (Optional[List[Union[float, Parameter]]]): A list of parameters. Raises: Exception: if the gate is of type string and params is None. """ def _format(operand): try: # Using float/complex value as a dict key is not good idea. # This makes the mapping quite sensitive to the rounding error. # However, the mechanism is already tied to the execution model (i.e. pulse gate) # and we cannot easily update this rule. # The same logic exists in DAGCircuit.add_calibration. evaluated = complex(operand) if np.isreal(evaluated): evaluated = float(evaluated.real) if evaluated.is_integer(): evaluated = int(evaluated) return evaluated except TypeError: # Unassigned parameter return operand if isinstance(gate, Gate): params = gate.params gate = gate.name if params is not None: params = tuple(map(_format, params)) else: params = () self._calibrations[gate][(tuple(qubits), params)] = schedule # Functions only for scheduled circuits def qubit_duration(self, *qubits: Union[Qubit, int]) -> float: """Return the duration between the start and stop time of the first and last instructions, excluding delays, over the supplied qubits. Its time unit is ``self.unit``. Args: *qubits: Qubits within ``self`` to include. Returns: Return the duration between the first start and last stop time of non-delay instructions """ return self.qubit_stop_time(*qubits) - self.qubit_start_time(*qubits) def qubit_start_time(self, *qubits: Union[Qubit, int]) -> float: """Return the start time of the first instruction, excluding delays, over the supplied qubits. Its time unit is ``self.unit``. Return 0 if there are no instructions over qubits Args: *qubits: Qubits within ``self`` to include. Integers are allowed for qubits, indicating indices of ``self.qubits``. Returns: Return the start time of the first instruction, excluding delays, over the qubits Raises: CircuitError: if ``self`` is a not-yet scheduled circuit. """ if self.duration is None: # circuit has only delays, this is kind of scheduled for instruction in self._data: if not isinstance(instruction.operation, Delay): raise CircuitError( "qubit_start_time undefined. Circuit must be scheduled first." ) return 0 qubits = [self.qubits[q] if isinstance(q, int) else q for q in qubits] starts = {q: 0 for q in qubits} dones = {q: False for q in qubits} for instruction in self._data: for q in qubits: if q in instruction.qubits: if isinstance(instruction.operation, Delay): if not dones[q]: starts[q] += instruction.operation.duration else: dones[q] = True if len(qubits) == len([done for done in dones.values() if done]): # all done return min(start for start in starts.values()) return 0 # If there are no instructions over bits def qubit_stop_time(self, *qubits: Union[Qubit, int]) -> float: """Return the stop time of the last instruction, excluding delays, over the supplied qubits. Its time unit is ``self.unit``. Return 0 if there are no instructions over qubits Args: *qubits: Qubits within ``self`` to include. Integers are allowed for qubits, indicating indices of ``self.qubits``. Returns: Return the stop time of the last instruction, excluding delays, over the qubits Raises: CircuitError: if ``self`` is a not-yet scheduled circuit. """ if self.duration is None: # circuit has only delays, this is kind of scheduled for instruction in self._data: if not isinstance(instruction.operation, Delay): raise CircuitError( "qubit_stop_time undefined. Circuit must be scheduled first." ) return 0 qubits = [self.qubits[q] if isinstance(q, int) else q for q in qubits] stops = {q: self.duration for q in qubits} dones = {q: False for q in qubits} for instruction in reversed(self._data): for q in qubits: if q in instruction.qubits: if isinstance(instruction.operation, Delay): if not dones[q]: stops[q] -= instruction.operation.duration else: dones[q] = True if len(qubits) == len([done for done in dones.values() if done]): # all done return max(stop for stop in stops.values()) return 0 # If there are no instructions over bits class _OuterCircuitScopeInterface(CircuitScopeInterface): # This is an explicit interface-fulfilling object friend of QuantumCircuit that acts as its # implementation of the control-flow builder scope methods. __slots__ = ("circuit",) def __init__(self, circuit: QuantumCircuit): self.circuit = circuit @property def instructions(self): return self.circuit._data def append(self, instruction, *, _standard_gate: bool = False): # QuantumCircuit._append is semi-public, so we just call back to it. return self.circuit._append(instruction, _standard_gate=_standard_gate) def extend(self, data: CircuitData): self.circuit._data.extend(data) self.circuit.duration = None self.circuit.unit = "dt" def resolve_classical_resource(self, specifier): # This is slightly different to cbit_argument_conversion, because it should not # unwrap :obj:`.ClassicalRegister` instances into lists, and in general it should not allow # iterables or broadcasting. It is expected to be used as a callback for things like # :meth:`.InstructionSet.c_if` to check the validity of their arguments. if isinstance(specifier, Clbit): if specifier not in self.circuit._clbit_indices: raise CircuitError(f"Clbit {specifier} is not present in this circuit.") return specifier if isinstance(specifier, ClassicalRegister): # This is linear complexity for something that should be constant, but QuantumCircuit # does not currently keep a hashmap of registers, and requires non-trivial changes to # how it exposes its registers publically before such a map can be safely stored so it # doesn't miss updates. (Jake, 2021-11-10). if specifier not in self.circuit.cregs: raise CircuitError(f"Register {specifier} is not present in this circuit.") return specifier if isinstance(specifier, int): try: return self.circuit._data.clbits[specifier] except IndexError: raise CircuitError(f"Classical bit index {specifier} is out-of-range.") from None raise CircuitError(f"Unknown classical resource specifier: '{specifier}'.") def add_uninitialized_var(self, var): var = self.circuit._prepare_new_var(var, None) self.circuit._vars_local[var.name] = var def remove_var(self, var): self.circuit._vars_local.pop(var.name) def get_var(self, name): if (out := self.circuit._vars_local.get(name)) is not None: return out if (out := self.circuit._vars_capture.get(name)) is not None: return out return self.circuit._vars_input.get(name) def use_var(self, var): if self.get_var(var.name) != var: raise CircuitError(f"'{var}' is not present in this circuit") def _validate_expr(circuit_scope: CircuitScopeInterface, node: expr.Expr) -> expr.Expr: # This takes the `circuit_scope` object as an argument rather than being a circuit method and # inferring it because we may want to call this several times, and we almost invariably already # need the interface implementation for something else anyway. for var in set(expr.iter_vars(node)): if var.standalone: circuit_scope.use_var(var) else: circuit_scope.resolve_classical_resource(var.var) return node class _ParameterBindsDict: __slots__ = ("mapping", "allowed_keys") def __init__(self, mapping, allowed_keys): self.mapping = mapping self.allowed_keys = allowed_keys def items(self): """Iterator through all the keys in the mapping that we care about. Wrapping the main mapping allows us to avoid reconstructing a new 'dict', but just use the given 'mapping' without any copy / reconstruction.""" for parameter, value in self.mapping.items(): if parameter in self.allowed_keys: yield parameter, value class _ParameterBindsSequence: __slots__ = ("parameters", "values", "mapping_cache") def __init__(self, parameters, values): self.parameters = parameters self.values = values self.mapping_cache = None def items(self): """Iterator through all the keys in the mapping that we care about.""" return zip(self.parameters, self.values) @property def mapping(self): """Cached version of a mapping. This is only generated on demand.""" if self.mapping_cache is None: self.mapping_cache = dict(zip(self.parameters, self.values)) return self.mapping_cache def _bit_argument_conversion(specifier, bit_sequence, bit_set, type_) -> list[Bit]: """Get the list of bits referred to by the specifier ``specifier``. Valid types for ``specifier`` are integers, bits of the correct type (as given in ``type_``), or iterables of one of those two scalar types. Integers are interpreted as indices into the sequence ``bit_sequence``. All allowed bits must be in ``bit_set`` (which should implement fast lookup), which is assumed to contain the same bits as ``bit_sequence``. Returns: List[Bit]: a list of the specified bits from ``bits``. Raises: CircuitError: if an incorrect type or index is encountered, if the same bit is specified more than once, or if the specifier is to a bit not in the ``bit_set``. """ # The duplication between this function and `_bit_argument_conversion_scalar` is so that fast # paths return as quickly as possible, and all valid specifiers will resolve without needing to # try/catch exceptions (which is too slow for inner-loop code). if isinstance(specifier, type_): if specifier in bit_set: return [specifier] raise CircuitError(f"Bit '{specifier}' is not in the circuit.") if isinstance(specifier, (int, np.integer)): try: return [bit_sequence[specifier]] except IndexError as ex: raise CircuitError( f"Index {specifier} out of range for size {len(bit_sequence)}." ) from ex # Slices can't raise IndexError - they just return an empty list. if isinstance(specifier, slice): return bit_sequence[specifier] try: return [ _bit_argument_conversion_scalar(index, bit_sequence, bit_set, type_) for index in specifier ] except TypeError as ex: message = ( f"Incorrect bit type: expected '{type_.__name__}' but got '{type(specifier).__name__}'" if isinstance(specifier, Bit) else f"Invalid bit index: '{specifier}' of type '{type(specifier)}'" ) raise CircuitError(message) from ex def _bit_argument_conversion_scalar(specifier, bit_sequence, bit_set, type_): if isinstance(specifier, type_): if specifier in bit_set: return specifier raise CircuitError(f"Bit '{specifier}' is not in the circuit.") if isinstance(specifier, (int, np.integer)): try: return bit_sequence[specifier] except IndexError as ex: raise CircuitError( f"Index {specifier} out of range for size {len(bit_sequence)}." ) from ex message = ( f"Incorrect bit type: expected '{type_.__name__}' but got '{type(specifier).__name__}'" if isinstance(specifier, Bit) else f"Invalid bit index: '{specifier}' of type '{type(specifier)}'" ) raise CircuitError(message)
qiskit/qiskit/circuit/quantumcircuit.py/0
{ "file_path": "qiskit/qiskit/circuit/quantumcircuit.py", "repo_id": "qiskit", "token_count": 122980 }
182
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # 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. """ ============================================= Circuit Converters (:mod:`qiskit.converters`) ============================================= .. currentmodule:: qiskit.converters QuantumCircuit -> circuit components ==================================== .. autofunction:: circuit_to_instruction .. autofunction:: circuit_to_gate QuantumCircuit <-> DagCircuit ============================= .. autofunction:: circuit_to_dag .. autofunction:: dag_to_circuit QuantumCircuit <-> DagDependency ================================ .. autofunction:: dagdependency_to_circuit .. autofunction:: circuit_to_dagdependency DagCircuit <-> DagDependency ============================ .. autofunction:: dag_to_dagdependency .. autofunction:: dagdependency_to_dag """ from .circuit_to_dag import circuit_to_dag from .dag_to_circuit import dag_to_circuit from .circuit_to_instruction import circuit_to_instruction from .circuit_to_gate import circuit_to_gate from .circuit_to_dagdependency import circuit_to_dagdependency from .dagdependency_to_circuit import dagdependency_to_circuit from .dag_to_dagdependency import dag_to_dagdependency from .dagdependency_to_dag import dagdependency_to_dag def isinstanceint(obj): """Like isinstance(obj,int), but with casting. Except for strings.""" if isinstance(obj, str): return False try: int(obj) return True except TypeError: return False def isinstancelist(obj): """Like isinstance(obj, list), but with casting. Except for strings and dicts.""" if isinstance(obj, (str, dict)): return False try: list(obj) return True except TypeError: return False
qiskit/qiskit/converters/__init__.py/0
{ "file_path": "qiskit/qiskit/converters/__init__.py", "repo_id": "qiskit", "token_count": 697 }
183
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # 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. # pylint: disable=redefined-builtin """Object to represent the information at a node in the DAGCircuit.""" from __future__ import annotations from qiskit.exceptions import QiskitError class DAGDepNode: """Object to represent the information at a node in the DAGDependency(). It is used as the return value from `*_nodes()` functions and can be supplied to functions that take a node. """ __slots__ = [ "type", "_op", "name", "_qargs", "cargs", "sort_key", "node_id", "successors", "predecessors", "reachable", "matchedwith", "isblocked", "successorstovisit", "qindices", "cindices", ] def __init__( self, type=None, op=None, name=None, qargs=(), cargs=(), successors: list[int] | None = None, predecessors: list[int] | None = None, reachable=None, matchedwith: list[int] | None = None, successorstovisit: list[int] | None = None, isblocked: bool | None = None, qindices: list[int] | None = None, cindices: list[int] | None = None, nid: int = -1, ): self.type = type self._op = op self.name = name self._qargs = tuple(qargs) if qargs is not None else () self.cargs = tuple(cargs) if cargs is not None else () self.node_id = nid self.sort_key: str = str(self._qargs) self.successors: list[int] = successors if successors is not None else [] self.predecessors: list[int] = predecessors if predecessors is not None else [] self.reachable = reachable self.matchedwith: list[int] = matchedwith if matchedwith is not None else [] self.isblocked: bool = isblocked self.successorstovisit: list[int] = ( successorstovisit if successorstovisit is not None else [] ) self.qindices: list[int] = qindices if qindices is not None else [] self.cindices: list[int] = cindices if cindices is not None else [] @property def op(self): """Returns the Instruction object corresponding to the op for the node, else None""" if not self.type or self.type != "op": raise QiskitError(f"The node {str(self)} is not an op node") return self._op @op.setter def op(self, data): self._op = data @property def qargs(self): """ Returns list of Qubit, else an empty list. """ return self._qargs @qargs.setter def qargs(self, new_qargs): """Sets the qargs to be the given list of qargs.""" self._qargs = tuple(new_qargs) self.sort_key = str(new_qargs) @staticmethod def semantic_eq(node1, node2): """ Check if DAG nodes are considered equivalent, e.g., as a node_match for nx.is_isomorphic. Args: node1 (DAGDepNode): A node to compare. node2 (DAGDepNode): The other node to compare. Return: Bool: If node1 == node2 """ # For barriers, qarg order is not significant so compare as sets if "barrier" == node1.name == node2.name: return set(node1._qargs) == set(node2._qargs) if node1.type == node2.type: if node1._op == node2._op: if node1.name == node2.name: if node1._qargs == node2._qargs: if node1.cargs == node2.cargs: if node1.type == "op": if getattr(node1._op, "condition", None) != getattr( node2._op, "condition", None ): return False return True return False def copy(self): """ Function to copy a DAGDepNode object. Returns: DAGDepNode: a copy of a DAGDepNode object. """ dagdepnode = DAGDepNode() dagdepnode.type = self.type dagdepnode._op = self.op dagdepnode.name = self.name dagdepnode._qargs = self._qargs dagdepnode.cargs = self.cargs dagdepnode.node_id = self.node_id dagdepnode.sort_key = self.sort_key dagdepnode.successors = self.successors dagdepnode.predecessors = self.predecessors dagdepnode.reachable = self.reachable dagdepnode.isblocked = self.isblocked dagdepnode.successorstovisit = self.successorstovisit dagdepnode.qindices = self.qindices dagdepnode.cindices = self.cindices dagdepnode.matchedwith = self.matchedwith.copy() return dagdepnode
qiskit/qiskit/dagcircuit/dagdepnode.py/0
{ "file_path": "qiskit/qiskit/dagcircuit/dagdepnode.py", "repo_id": "qiskit", "token_count": 2404 }
184
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023, 2024. # # 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. """Base Estimator V1 and V2 classes""" from __future__ import annotations from abc import abstractmethod, ABC from collections.abc import Iterable, Sequence from copy import copy from typing import Generic, TypeVar from qiskit.circuit import QuantumCircuit from qiskit.providers import JobV1 as Job from qiskit.quantum_info.operators import SparsePauliOp from qiskit.quantum_info.operators.base_operator import BaseOperator from qiskit.utils.deprecation import deprecate_func from ..containers import ( DataBin, EstimatorPubLike, PrimitiveResult, PubResult, ) from ..containers.estimator_pub import EstimatorPub from . import validation from .base_primitive import BasePrimitive from .base_primitive_job import BasePrimitiveJob T = TypeVar("T", bound=Job) class BaseEstimatorV1(BasePrimitive, Generic[T]): r"""Estimator V1 base class. Base class for Estimator that estimates expectation values of quantum circuits and observables. An estimator is initialized with an empty parameter set. The estimator is used to create a :class:`~qiskit.providers.JobV1`, via the :meth:`qiskit.primitives.Estimator.run()` method. This method is called with the following parameters * quantum circuits (:math:`\psi_i(\theta)`): list of (parameterized) quantum circuits (a list of :class:`~qiskit.circuit.QuantumCircuit` objects). * observables (:math:`H_j`): a list of :class:`~qiskit.quantum_info.SparsePauliOp` objects. * parameter values (:math:`\theta_k`): list of sets of values to be bound to the parameters of the quantum circuits (list of list of float). The method returns a :class:`~qiskit.providers.JobV1` object, calling :meth:`qiskit.providers.JobV1.result()` yields the a list of expectation values plus optional metadata like confidence intervals for the estimation. .. math:: \langle\psi_i(\theta_k)|H_j|\psi_i(\theta_k)\rangle Here is an example of how the estimator is used. .. code-block:: python from qiskit.primitives import Estimator from qiskit.circuit.library import RealAmplitudes from qiskit.quantum_info import SparsePauliOp psi1 = RealAmplitudes(num_qubits=2, reps=2) psi2 = RealAmplitudes(num_qubits=2, reps=3) H1 = SparsePauliOp.from_list([("II", 1), ("IZ", 2), ("XI", 3)]) H2 = SparsePauliOp.from_list([("IZ", 1)]) H3 = SparsePauliOp.from_list([("ZI", 1), ("ZZ", 1)]) theta1 = [0, 1, 1, 2, 3, 5] theta2 = [0, 1, 1, 2, 3, 5, 8, 13] theta3 = [1, 2, 3, 4, 5, 6] estimator = Estimator() # calculate [ <psi1(theta1)|H1|psi1(theta1)> ] job = estimator.run([psi1], [H1], [theta1]) job_result = job.result() # It will block until the job finishes. print(f"The primitive-job finished with result {job_result}")) # calculate [ <psi1(theta1)|H1|psi1(theta1)>, # <psi2(theta2)|H2|psi2(theta2)>, # <psi1(theta3)|H3|psi1(theta3)> ] job2 = estimator.run([psi1, psi2, psi1], [H1, H2, H3], [theta1, theta2, theta3]) job_result = job2.result() print(f"The primitive-job finished with result {job_result}") """ __hash__ = None def __init__( self, *, options: dict | None = None, ): """ Creating an instance of an Estimator V1, or using one in a ``with`` context opens a session that holds resources until the instance is ``close()`` ed or the context is exited. Args: options: Default options. """ super().__init__(options) def run( self, circuits: Sequence[QuantumCircuit] | QuantumCircuit, observables: Sequence[BaseOperator | str] | BaseOperator | str, parameter_values: Sequence[Sequence[float]] | Sequence[float] | float | None = None, **run_options, ) -> T: """Run the job of the estimation of expectation value(s). ``circuits``, ``observables``, and ``parameter_values`` should have the same length. The i-th element of the result is the expectation of observable .. code-block:: python obs = observables[i] for the state prepared by .. code-block:: python circ = circuits[i] with bound parameters .. code-block:: python values = parameter_values[i]. Args: circuits: one or more circuit objects. observables: one or more observable objects. Several formats are allowed; importantly, ``str`` should follow the string representation format for :class:`~qiskit.quantum_info.Pauli` objects. parameter_values: concrete parameters to be bound. run_options: runtime options used for circuit execution. Returns: The job object of EstimatorResult. Raises: TypeError: Invalid argument type given. ValueError: Invalid argument values given. """ # Validation circuits, observables, parameter_values = validation._validate_estimator_args( circuits, observables, parameter_values ) # Options run_opts = copy(self.options) run_opts.update_options(**run_options) return self._run( circuits, observables, parameter_values, **run_opts.__dict__, ) @abstractmethod def _run( self, circuits: tuple[QuantumCircuit, ...], observables: tuple[SparsePauliOp, ...], parameter_values: tuple[tuple[float, ...], ...], **run_options, ) -> T: raise NotImplementedError("The subclass of BaseEstimator must implement `_run` method.") class BaseEstimator(BaseEstimatorV1[T]): """DEPRECATED. Type alias for Estimator V1 base class. See :class:`.BaseEstimatorV1` for details. """ @deprecate_func( since="1.2", additional_msg="The `BaseEstimator` class is a type alias for the `BaseEstimatorV1` " "interface that has been deprecated in favor of explicitly versioned interface classes. " "It is recommended to migrate all implementations to use `BaseEstimatorV2`. " "However, for implementations incompatible with `BaseEstimatorV2`, `BaseEstimator` can " "be replaced with the explicitly versioned `BaseEstimatorV1` class.", ) def __init__( self, *, options: dict | None = None, ): """ Creating an instance of an Estimator, or using one in a ``with`` context opens a session that holds resources until the instance is ``close()`` ed or the context is exited. Args: options: Default options. """ super().__init__(options=options) class BaseEstimatorV2(ABC): r"""Estimator V2 base class. An estimator estimates expectation values for provided quantum circuit and observable combinations. An Estimator implementation must treat the :meth:`.run` method ``precision=None`` kwarg as using a default ``precision`` value. The default value and methods to set it can be determined by the Estimator implementor. """ @staticmethod def _make_data_bin(_: EstimatorPub) -> type[DataBin]: # this method is present for backwards compat. new primitive implementations # should avoid it. return DataBin @abstractmethod def run( self, pubs: Iterable[EstimatorPubLike], *, precision: float | None = None ) -> BasePrimitiveJob[PrimitiveResult[PubResult]]: """Estimate expectation values for each provided pub (Primitive Unified Bloc). Args: pubs: An iterable of pub-like objects, such as tuples ``(circuit, observables)`` or ``(circuit, observables, parameter_values)``. precision: The target precision for expectation value estimates of each run Estimator Pub that does not specify its own precision. If None the estimator's default precision value will be used. Returns: A job object that contains results. """
qiskit/qiskit/primitives/base/base_estimator.py/0
{ "file_path": "qiskit/qiskit/primitives/base/base_estimator.py", "repo_id": "qiskit", "token_count": 3448 }
185
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # 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. """ Base Pub result class """ from __future__ import annotations from typing import Any from .data_bin import DataBin class PubResult: """Result of Primitive Unified Bloc.""" __slots__ = ("_data", "_metadata") def __init__(self, data: DataBin, metadata: dict[str, Any] | None = None): """Initialize a pub result. Args: data: Result data. metadata: Metadata specific to this pub. Keys are expected to be strings. """ self._data = data self._metadata = metadata or {} def __repr__(self): metadata = f", metadata={self.metadata}" if self.metadata else "" return f"{type(self).__name__}(data={self._data}{metadata})" @property def data(self) -> DataBin: """Result data for the pub.""" return self._data @property def metadata(self) -> dict: """Metadata for the pub.""" return self._metadata
qiskit/qiskit/primitives/containers/pub_result.py/0
{ "file_path": "qiskit/qiskit/primitives/containers/pub_result.py", "repo_id": "qiskit", "token_count": 498 }
186
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2023. # # 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. """Contains functions used by the basic provider simulators. """ from __future__ import annotations from string import ascii_uppercase, ascii_lowercase import numpy as np import qiskit.circuit.library.standard_gates as gates from qiskit.exceptions import QiskitError # Single qubit gates supported by ``single_gate_params``. SINGLE_QUBIT_GATES = { "U": gates.UGate, "u": gates.UGate, "u1": gates.U1Gate, "u2": gates.U2Gate, "u3": gates.U3Gate, "h": gates.HGate, "p": gates.PhaseGate, "s": gates.SGate, "sdg": gates.SdgGate, "sx": gates.SXGate, "sxdg": gates.SXdgGate, "t": gates.TGate, "tdg": gates.TdgGate, "x": gates.XGate, "y": gates.YGate, "z": gates.ZGate, "id": gates.IGate, "i": gates.IGate, "r": gates.RGate, "rx": gates.RXGate, "ry": gates.RYGate, "rz": gates.RZGate, } def single_gate_matrix(gate: str, params: list[float] | None = None) -> np.ndarray: """Get the matrix for a single qubit. Args: gate: the single qubit gate name params: the operation parameters op['params'] Returns: array: A numpy array representing the matrix Raises: QiskitError: If a gate outside the supported set is passed in for the ``Gate`` argument. """ if params is None: params = [] if gate in SINGLE_QUBIT_GATES: gc = SINGLE_QUBIT_GATES[gate] else: raise QiskitError(f"Gate is not a valid basis gate for this simulator: {gate}") return gc(*params).to_matrix() # Two qubit gates WITHOUT parameters: name -> matrix TWO_QUBIT_GATES = { "CX": gates.CXGate().to_matrix(), "cx": gates.CXGate().to_matrix(), "ecr": gates.ECRGate().to_matrix(), "cy": gates.CYGate().to_matrix(), "cz": gates.CZGate().to_matrix(), "swap": gates.SwapGate().to_matrix(), "iswap": gates.iSwapGate().to_matrix(), "ch": gates.CHGate().to_matrix(), "cs": gates.CSGate().to_matrix(), "csdg": gates.CSdgGate().to_matrix(), "csx": gates.CSXGate().to_matrix(), "dcx": gates.DCXGate().to_matrix(), } # Two qubit gates WITH parameters: name -> class TWO_QUBIT_GATES_WITH_PARAMETERS = { "cp": gates.CPhaseGate, "crx": gates.CRXGate, "cry": gates.CRYGate, "crz": gates.CRZGate, "cu": gates.CUGate, "cu1": gates.CU1Gate, "cu3": gates.CU3Gate, "rxx": gates.RXXGate, "ryy": gates.RYYGate, "rzz": gates.RZZGate, "rzx": gates.RZXGate, "xx_minus_yy": gates.XXMinusYYGate, "xx_plus_yy": gates.XXPlusYYGate, } # Three qubit gates: name -> matrix THREE_QUBIT_GATES = { "ccx": gates.CCXGate().to_matrix(), "ccz": gates.CCZGate().to_matrix(), "rccx": gates.RCCXGate().to_matrix(), "cswap": gates.CSwapGate().to_matrix(), } def einsum_matmul_index(gate_indices: list[int], number_of_qubits: int) -> str: """Return the index string for Numpy.einsum matrix-matrix multiplication. The returned indices are to perform a matrix multiplication A.B where the matrix A is an M-qubit matrix, matrix B is an N-qubit matrix, and M <= N, and identity matrices are implied on the subsystems where A has no support on B. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: str: An indices string for the Numpy.einsum function. """ mat_l, mat_r, tens_lin, tens_lout = _einsum_matmul_index_helper(gate_indices, number_of_qubits) # Right indices for the N-qubit input and output tensor tens_r = ascii_uppercase[:number_of_qubits] # Combine indices into matrix multiplication string format # for numpy.einsum function return f"{mat_l}{mat_r}, {tens_lin}{tens_r}->{tens_lout}{tens_r}" def einsum_vecmul_index(gate_indices: list[int], number_of_qubits: int) -> str: """Return the index string for Numpy.einsum matrix-vector multiplication. The returned indices are to perform a matrix multiplication A.v where the matrix A is an M-qubit matrix, vector v is an N-qubit vector, and M <= N, and identity matrices are implied on the subsystems where A has no support on v. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: str: An indices string for the Numpy.einsum function. """ mat_l, mat_r, tens_lin, tens_lout = _einsum_matmul_index_helper(gate_indices, number_of_qubits) # Combine indices into matrix multiplication string format # for numpy.einsum function return f"{mat_l}{mat_r}, {tens_lin}->{tens_lout}" def _einsum_matmul_index_helper( gate_indices: list[int], number_of_qubits: int ) -> tuple[str, str, str, str]: """Return the index string for Numpy.einsum matrix multiplication. The returned indices are to perform a matrix multiplication A.v where the matrix A is an M-qubit matrix, matrix v is an N-qubit vector, and M <= N, and identity matrices are implied on the subsystems where A has no support on v. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: tuple: (mat_left, mat_right, tens_in, tens_out) of index strings for that may be combined into a Numpy.einsum function string. Raises: QiskitError: if the total number of qubits plus the number of contracted indices is greater than 26. """ # Since we use ASCII alphabet for einsum index labels we are limited # to 26 total free left (lowercase) and 26 right (uppercase) indexes. # The rank of the contracted tensor reduces this as we need to use that # many characters for the contracted indices if len(gate_indices) + number_of_qubits > 26: raise QiskitError("Total number of free indexes limited to 26") # Indices for N-qubit input tensor tens_in = ascii_lowercase[:number_of_qubits] # Indices for the N-qubit output tensor tens_out = list(tens_in) # Left and right indices for the M-qubit multiplying tensor mat_left = "" mat_right = "" # Update left indices for mat and output for pos, idx in enumerate(reversed(gate_indices)): mat_left += ascii_lowercase[-1 - pos] mat_right += tens_in[-1 - idx] tens_out[-1 - idx] = ascii_lowercase[-1 - pos] tens_out = "".join(tens_out) # Combine indices into matrix multiplication string format # for numpy.einsum function return mat_left, mat_right, tens_in, tens_out
qiskit/qiskit/providers/basic_provider/basic_provider_tools.py/0
{ "file_path": "qiskit/qiskit/providers/basic_provider/basic_provider_tools.py", "repo_id": "qiskit", "token_count": 2928 }
187
# This code is part of Qiskit. # # (C) Copyright IBM 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. """ Fake backend supporting OpenPulse. """ import warnings from qiskit.providers.models.backendconfiguration import ( GateConfig, PulseBackendConfiguration, UchannelLO, ) from qiskit.providers.models.pulsedefaults import PulseDefaults, Command from qiskit.qobj import PulseQobjInstruction from .fake_backend import FakeBackend class FakeOpenPulse3Q(FakeBackend): """Trivial extension of the FakeOpenPulse2Q.""" def __init__(self): configuration = PulseBackendConfiguration( backend_name="fake_openpulse_3q", backend_version="0.0.0", n_qubits=3, meas_levels=[0, 1, 2], basis_gates=["u1", "u2", "u3", "cx", "id"], simulator=False, local=True, conditional=True, open_pulse=True, memory=False, max_shots=65536, gates=[GateConfig(name="TODO", parameters=[], qasm_def="TODO")], coupling_map=[[0, 1], [1, 2]], n_registers=3, n_uchannels=3, u_channel_lo=[ [UchannelLO(q=0, scale=1.0 + 0.0j)], [UchannelLO(q=0, scale=-1.0 + 0.0j), UchannelLO(q=1, scale=1.0 + 0.0j)], [UchannelLO(q=0, scale=1.0 + 0.0j)], ], qubit_lo_range=[[4.5, 5.5], [4.5, 5.5], [4.5, 5.5]], meas_lo_range=[[6.0, 7.0], [6.0, 7.0], [6.0, 7.0]], dt=1.3333, dtm=10.5, rep_times=[100, 250, 500, 1000], meas_map=[[0, 1, 2]], channel_bandwidth=[ [-0.2, 0.4], [-0.3, 0.3], [-0.3, 0.3], [-0.02, 0.02], [-0.02, 0.02], [-0.02, 0.02], [-0.2, 0.4], [-0.3, 0.3], [-0.3, 0.3], ], meas_kernels=["kernel1"], discriminators=["max_1Q_fidelity"], acquisition_latency=[[100, 100], [100, 100], [100, 100]], conditional_latency=[ [100, 1000], [1000, 100], [100, 1000], [100, 1000], [1000, 100], [100, 1000], [1000, 100], [100, 1000], [1000, 100], ], channels={ "acquire0": {"type": "acquire", "purpose": "acquire", "operates": {"qubits": [0]}}, "acquire1": {"type": "acquire", "purpose": "acquire", "operates": {"qubits": [1]}}, "acquire2": {"type": "acquire", "purpose": "acquire", "operates": {"qubits": [2]}}, "d0": {"type": "drive", "purpose": "drive", "operates": {"qubits": [0]}}, "d1": {"type": "drive", "purpose": "drive", "operates": {"qubits": [1]}}, "d2": {"type": "drive", "purpose": "drive", "operates": {"qubits": [2]}}, "m0": {"type": "measure", "purpose": "measure", "operates": {"qubits": [0]}}, "m1": {"type": "measure", "purpose": "measure", "operates": {"qubits": [1]}}, "m2": {"type": "measure", "purpose": "measure", "operates": {"qubits": [2]}}, "u0": { "type": "control", "purpose": "cross-resonance", "operates": {"qubits": [0, 1]}, }, "u1": { "type": "control", "purpose": "cross-resonance", "operates": {"qubits": [1, 0]}, }, "u2": { "type": "control", "purpose": "cross-resonance", "operates": {"qubits": [2, 1]}, }, }, ) with warnings.catch_warnings(): # The class PulseQobjInstruction is deprecated warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") self._defaults = PulseDefaults.from_dict( { "qubit_freq_est": [4.9, 5.0, 4.8], "meas_freq_est": [6.5, 6.6, 6.4], "buffer": 10, "pulse_library": [ {"name": "x90p_d0", "samples": 2 * [0.1 + 0j]}, {"name": "x90p_d1", "samples": 2 * [0.1 + 0j]}, {"name": "x90p_d2", "samples": 2 * [0.1 + 0j]}, {"name": "x90m_d0", "samples": 2 * [-0.1 + 0j]}, {"name": "x90m_d1", "samples": 2 * [-0.1 + 0j]}, {"name": "x90m_d2", "samples": 2 * [-0.1 + 0j]}, {"name": "y90p_d0", "samples": 2 * [0.1j]}, {"name": "y90p_d1", "samples": 2 * [0.1j]}, {"name": "y90p_d2", "samples": 2 * [0.1j]}, {"name": "xp_d0", "samples": 2 * [0.2 + 0j]}, {"name": "ym_d0", "samples": 2 * [-0.2j]}, {"name": "xp_d1", "samples": 2 * [0.2 + 0j]}, {"name": "ym_d1", "samples": 2 * [-0.2j]}, {"name": "cr90p_u0", "samples": 9 * [0.1 + 0j]}, {"name": "cr90m_u0", "samples": 9 * [-0.1 + 0j]}, {"name": "cr90p_u1", "samples": 9 * [0.1 + 0j]}, {"name": "cr90m_u1", "samples": 9 * [-0.1 + 0j]}, {"name": "measure_m0", "samples": 10 * [0.1 + 0j]}, {"name": "measure_m1", "samples": 10 * [0.1 + 0j]}, {"name": "measure_m2", "samples": 10 * [0.1 + 0j]}, ], "cmd_def": [ Command.from_dict( { "name": "u1", "qubits": [0], "sequence": [ PulseQobjInstruction( name="fc", ch="d0", t0=0, phase="-P0" ).to_dict() ], } ).to_dict(), Command.from_dict( { "name": "u1", "qubits": [1], "sequence": [ PulseQobjInstruction( name="fc", ch="d1", t0=0, phase="-P0" ).to_dict() ], } ).to_dict(), Command.from_dict( { "name": "u1", "qubits": [2], "sequence": [ PulseQobjInstruction( name="fc", ch="d2", t0=0, phase="-P0" ).to_dict() ], } ).to_dict(), Command.from_dict( { "name": "u2", "qubits": [0], "sequence": [ PulseQobjInstruction( name="fc", ch="d0", t0=0, phase="-P1" ).to_dict(), PulseQobjInstruction(name="y90p_d0", ch="d0", t0=0).to_dict(), PulseQobjInstruction( name="fc", ch="d0", t0=2, phase="-P0" ).to_dict(), ], } ).to_dict(), Command.from_dict( { "name": "u2", "qubits": [1], "sequence": [ PulseQobjInstruction( name="fc", ch="d1", t0=0, phase="-P1" ).to_dict(), PulseQobjInstruction(name="y90p_d1", ch="d1", t0=0).to_dict(), PulseQobjInstruction( name="fc", ch="d1", t0=2, phase="-P0" ).to_dict(), ], } ).to_dict(), Command.from_dict( { "name": "u2", "qubits": [2], "sequence": [ PulseQobjInstruction( name="fc", ch="d2", t0=0, phase="-P1" ).to_dict(), PulseQobjInstruction(name="y90p_d2", ch="d2", t0=0).to_dict(), PulseQobjInstruction( name="fc", ch="d2", t0=2, phase="-P0" ).to_dict(), ], } ).to_dict(), Command.from_dict( { "name": "u3", "qubits": [0], "sequence": [ PulseQobjInstruction( name="fc", ch="d0", t0=0, phase="-P2" ).to_dict(), PulseQobjInstruction(name="x90p_d0", ch="d0", t0=0).to_dict(), PulseQobjInstruction( name="fc", ch="d0", t0=2, phase="-P0" ).to_dict(), PulseQobjInstruction(name="x90m_d0", ch="d0", t0=2).to_dict(), PulseQobjInstruction( name="fc", ch="d0", t0=4, phase="-P1" ).to_dict(), ], } ).to_dict(), Command.from_dict( { "name": "u3", "qubits": [1], "sequence": [ PulseQobjInstruction( name="fc", ch="d1", t0=0, phase="-P2" ).to_dict(), PulseQobjInstruction(name="x90p_d1", ch="d1", t0=0).to_dict(), PulseQobjInstruction( name="fc", ch="d1", t0=2, phase="-P0" ).to_dict(), PulseQobjInstruction(name="x90m_d1", ch="d1", t0=2).to_dict(), PulseQobjInstruction( name="fc", ch="d1", t0=4, phase="-P1" ).to_dict(), ], } ).to_dict(), Command.from_dict( { "name": "u3", "qubits": [2], "sequence": [ PulseQobjInstruction( name="fc", ch="d2", t0=0, phase="-P2" ).to_dict(), PulseQobjInstruction(name="x90p_d2", ch="d2", t0=0).to_dict(), PulseQobjInstruction( name="fc", ch="d2", t0=2, phase="-P0" ).to_dict(), PulseQobjInstruction(name="x90m_d2", ch="d2", t0=2).to_dict(), PulseQobjInstruction( name="fc", ch="d2", t0=4, phase="-P1" ).to_dict(), ], } ).to_dict(), Command.from_dict( { "name": "cx", "qubits": [0, 1], "sequence": [ PulseQobjInstruction( name="fc", ch="d0", t0=0, phase=1.57 ).to_dict(), PulseQobjInstruction(name="ym_d0", ch="d0", t0=0).to_dict(), PulseQobjInstruction(name="xp_d0", ch="d0", t0=11).to_dict(), PulseQobjInstruction(name="x90p_d1", ch="d1", t0=0).to_dict(), PulseQobjInstruction(name="cr90p_u0", ch="u0", t0=2).to_dict(), PulseQobjInstruction(name="cr90m_u0", ch="u0", t0=13).to_dict(), ], } ).to_dict(), Command.from_dict( { "name": "cx", "qubits": [1, 2], "sequence": [ PulseQobjInstruction( name="fc", ch="d1", t0=0, phase=1.57 ).to_dict(), PulseQobjInstruction(name="ym_d1", ch="d1", t0=0).to_dict(), PulseQobjInstruction(name="xp_d1", ch="d1", t0=11).to_dict(), PulseQobjInstruction(name="x90p_d2", ch="d2", t0=0).to_dict(), PulseQobjInstruction(name="cr90p_u1", ch="u1", t0=2).to_dict(), PulseQobjInstruction(name="cr90m_u1", ch="u1", t0=13).to_dict(), ], } ).to_dict(), Command.from_dict( { "name": "measure", "qubits": [0, 1, 2], "sequence": [ PulseQobjInstruction( name="measure_m0", ch="m0", t0=0 ).to_dict(), PulseQobjInstruction( name="measure_m1", ch="m1", t0=0 ).to_dict(), PulseQobjInstruction( name="measure_m2", ch="m2", t0=0 ).to_dict(), PulseQobjInstruction( name="acquire", duration=10, t0=0, qubits=[0, 1, 2], memory_slot=[0, 1, 2], ).to_dict(), ], } ).to_dict(), ], } ) super().__init__(configuration) def defaults(self): # pylint: disable=missing-function-docstring return self._defaults
qiskit/qiskit/providers/fake_provider/fake_openpulse_3q.py/0
{ "file_path": "qiskit/qiskit/providers/fake_provider/fake_openpulse_3q.py", "repo_id": "qiskit", "token_count": 11721 }
188
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2023. # # 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. """Base class for a provider.""" from abc import ABC, abstractmethod from qiskit.providers.exceptions import QiskitBackendNotFoundError from qiskit.utils import deprecate_func class Provider: """Base common type for all versioned Provider abstract classes. Note this class should not be inherited from directly, it is intended to be used for type checking. When implementing a provider you should use the versioned abstract classes as the parent class and not this class directly. """ version = 0 @deprecate_func( since=1.1, additional_msg="The abstract Provider and ProviderV1 classes are deprecated and will be " "removed in 2.0. You can just remove it as the parent class and a `get_backend` " "method that returns the backends from `self.backend`.", ) def __init__(self): pass class ProviderV1(Provider, ABC): """Base class for a Backend Provider.""" version = 1 @deprecate_func( since=1.1, additional_msg="The abstract Provider and ProviderV1 classes are deprecated and will be " "removed in 2.0. You can just remove it as the parent class and a `get_backend` " "method that returns the backends from `self.backend`.", ) def get_backend(self, name=None, **kwargs): """Return a single backend matching the specified filtering. Args: name (str): name of the backend. **kwargs: dict used for filtering. Returns: Backend: a backend matching the filtering. Raises: QiskitBackendNotFoundError: if no backend could be found or more than one backend matches the filtering criteria. """ backends = self.backends(name, **kwargs) if len(backends) > 1: raise QiskitBackendNotFoundError("More than one backend matches the criteria") if not backends: raise QiskitBackendNotFoundError("No backend matches the criteria") return backends[0] @abstractmethod def backends(self, name=None, **kwargs): """Return a list of backends matching the specified filtering. Args: name (str): name of the backend. **kwargs: dict used for filtering. Returns: list[Backend]: a list of Backends that match the filtering criteria. """ pass def __eq__(self, other): """Equality comparison. By default, it is assumed that two `Providers` from the same class are equal. Subclassed providers can override this behavior. """ return type(self).__name__ == type(other).__name__
qiskit/qiskit/providers/provider.py/0
{ "file_path": "qiskit/qiskit/providers/provider.py", "repo_id": "qiskit", "token_count": 1148 }
189
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # 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. """The phase instructions update the modulation phase of pulses played on a channel. This includes ``SetPhase`` instructions which lock the modulation to a particular phase at that moment, and ``ShiftPhase`` instructions which increase the existing phase by a relative amount. """ from typing import Optional, Union, Tuple from qiskit.circuit import ParameterExpression from qiskit.pulse.channels import PulseChannel from qiskit.pulse.instructions.instruction import Instruction from qiskit.pulse.exceptions import PulseError class ShiftPhase(Instruction): r"""The shift phase instruction updates the modulation phase of proceeding pulses played on the same :py:class:`~qiskit.pulse.channels.Channel`. It is a relative increase in phase determined by the ``phase`` operand. In particular, a PulseChannel creates pulses of the form .. math:: Re[\exp(i 2\pi f jdt + \phi) d_j]. The ``ShiftPhase`` instruction causes :math:`\phi` to be increased by the instruction's ``phase`` operand. This will affect all pulses following on the same channel. The qubit phase is tracked in software, enabling instantaneous, nearly error-free Z-rotations by using a ShiftPhase to update the frame tracking the qubit state. """ def __init__( self, phase: Union[complex, ParameterExpression], channel: PulseChannel, name: Optional[str] = None, ): """Instantiate a shift phase instruction, increasing the output signal phase on ``channel`` by ``phase`` [radians]. Args: phase: The rotation angle in radians. channel: The channel this instruction operates on. name: Display name for this instruction. """ super().__init__(operands=(phase, channel), name=name) def _validate(self): """Called after initialization to validate instruction data. Raises: PulseError: If the input ``channel`` is not type :class:`PulseChannel`. """ if not isinstance(self.channel, PulseChannel): raise PulseError(f"Expected a pulse channel, got {self.channel} instead.") @property def phase(self) -> Union[complex, ParameterExpression]: """Return the rotation angle enacted by this instruction in radians.""" return self.operands[0] @property def channel(self) -> PulseChannel: """Return the :py:class:`~qiskit.pulse.channels.Channel` that this instruction is scheduled on. """ return self.operands[1] @property def channels(self) -> Tuple[PulseChannel]: """Returns the channels that this schedule uses.""" return (self.channel,) @property def duration(self) -> int: """Duration of this instruction.""" return 0 class SetPhase(Instruction): r"""The set phase instruction sets the phase of the proceeding pulses on that channel to ``phase`` radians. In particular, a PulseChannel creates pulses of the form .. math:: Re[\exp(i 2\pi f jdt + \phi) d_j] The ``SetPhase`` instruction sets :math:`\phi` to the instruction's ``phase`` operand. """ def __init__( self, phase: Union[complex, ParameterExpression], channel: PulseChannel, name: Optional[str] = None, ): """Instantiate a set phase instruction, setting the output signal phase on ``channel`` to ``phase`` [radians]. Args: phase: The rotation angle in radians. channel: The channel this instruction operates on. name: Display name for this instruction. """ super().__init__(operands=(phase, channel), name=name) def _validate(self): """Called after initialization to validate instruction data. Raises: PulseError: If the input ``channel`` is not type :class:`PulseChannel`. """ if not isinstance(self.channel, PulseChannel): raise PulseError(f"Expected a pulse channel, got {self.channel} instead.") @property def phase(self) -> Union[complex, ParameterExpression]: """Return the rotation angle enacted by this instruction in radians.""" return self.operands[0] @property def channel(self) -> PulseChannel: """Return the :py:class:`~qiskit.pulse.channels.Channel` that this instruction is scheduled on. """ return self.operands[1] @property def channels(self) -> Tuple[PulseChannel]: """Returns the channels that this schedule uses.""" return (self.channel,) @property def duration(self) -> int: """Duration of this instruction.""" return 0
qiskit/qiskit/pulse/instructions/phase.py/0
{ "file_path": "qiskit/qiskit/pulse/instructions/phase.py", "repo_id": "qiskit", "token_count": 1802 }
190
# This code is part of Qiskit. # # (C) Copyright IBM 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. # pylint: disable=cyclic-import """ ========= Schedules ========= .. currentmodule:: qiskit.pulse Schedules are Pulse programs. They describe instruction sequences for the control hardware. The Schedule is one of the most fundamental objects to this pulse-level programming module. A ``Schedule`` is a representation of a *program* in Pulse. Each schedule tracks the time of each instruction occuring in parallel over multiple signal *channels*. .. autosummary:: :toctree: ../stubs/ Schedule ScheduleBlock """ from __future__ import annotations import abc import copy import functools import itertools import multiprocessing as mp import sys import warnings from collections.abc import Callable, Iterable from typing import List, Tuple, Union, Dict, Any, Sequence import numpy as np import rustworkx as rx from qiskit.circuit import ParameterVector from qiskit.circuit.parameter import Parameter from qiskit.circuit.parameterexpression import ParameterExpression, ParameterValueType from qiskit.pulse.channels import Channel from qiskit.pulse.exceptions import PulseError, UnassignedReferenceError from qiskit.pulse.instructions import Instruction, Reference from qiskit.pulse.utils import instruction_duration_validation from qiskit.pulse.reference_manager import ReferenceManager from qiskit.utils.multiprocessing import is_main_process from qiskit.utils import deprecate_arg Interval = Tuple[int, int] """An interval type is a tuple of a start time (inclusive) and an end time (exclusive).""" TimeSlots = Dict[Channel, List[Interval]] """List of timeslots occupied by instructions for each channel.""" class Schedule: """A quantum program *schedule* with exact time constraints for its instructions, operating over all input signal *channels* and supporting special syntaxes for building. Pulse program representation for the original Qiskit Pulse model [1]. Instructions are not allowed to overlap in time on the same channel. This overlap constraint is immediately evaluated when a new instruction is added to the ``Schedule`` object. It is necessary to specify the absolute start time and duration for each instruction so as to deterministically fix its execution time. The ``Schedule`` program supports some syntax sugar for easier programming. - Appending an instruction to the end of a channel .. code-block:: python sched = Schedule() sched += Play(Gaussian(160, 0.1, 40), DriveChannel(0)) - Appending an instruction shifted in time by a given amount .. code-block:: python sched = Schedule() sched += Play(Gaussian(160, 0.1, 40), DriveChannel(0)) << 30 - Merge two schedules .. code-block:: python sched1 = Schedule() sched1 += Play(Gaussian(160, 0.1, 40), DriveChannel(0)) sched2 = Schedule() sched2 += Play(Gaussian(160, 0.1, 40), DriveChannel(1)) sched2 = sched1 | sched2 A :obj:`.PulseError` is immediately raised when the overlap constraint is violated. In the schedule representation, we cannot parametrize the duration of instructions. Thus, we need to create a new schedule object for each duration. To parametrize an instruction's duration, the :class:`~qiskit.pulse.ScheduleBlock` representation may be used instead. References: [1]: https://arxiv.org/abs/2004.06755 """ # Prefix to use for auto naming. prefix = "sched" # Counter to count instance number. instances_counter = itertools.count() def __init__( self, *schedules: "ScheduleComponent" | tuple[int, "ScheduleComponent"], name: str | None = None, metadata: dict | None = None, ): """Create an empty schedule. Args: *schedules: Child Schedules of this parent Schedule. May either be passed as the list of schedules, or a list of ``(start_time, schedule)`` pairs. name: Name of this schedule. Defaults to an autogenerated string if not provided. metadata: Arbitrary key value metadata to associate with the schedule. This gets stored as free-form data in a dict in the :attr:`~qiskit.pulse.Schedule.metadata` attribute. It will not be directly used in the schedule. Raises: TypeError: if metadata is not a dict. """ from qiskit.pulse.parameter_manager import ParameterManager if name is None: name = self.prefix + str(next(self.instances_counter)) if sys.platform != "win32" and not is_main_process(): name += f"-{mp.current_process().pid}" self._name = name self._parameter_manager = ParameterManager() if not isinstance(metadata, dict) and metadata is not None: raise TypeError("Only a dictionary or None is accepted for schedule metadata") self._metadata = metadata or {} self._duration = 0 # These attributes are populated by ``_mutable_insert`` self._timeslots: TimeSlots = {} self._children: list[tuple[int, "ScheduleComponent"]] = [] for sched_pair in schedules: try: time, sched = sched_pair except TypeError: # recreate as sequence starting at 0. time, sched = 0, sched_pair self._mutable_insert(time, sched) @classmethod def initialize_from(cls, other_program: Any, name: str | None = None) -> "Schedule": """Create new schedule object with metadata of another schedule object. Args: other_program: Qiskit program that provides metadata to new object. name: Name of new schedule. Name of ``schedule`` is used by default. Returns: New schedule object with name and metadata. Raises: PulseError: When `other_program` does not provide necessary information. """ try: name = name or other_program.name if other_program.metadata: metadata = other_program.metadata.copy() else: metadata = None return cls(name=name, metadata=metadata) except AttributeError as ex: raise PulseError( f"{cls.__name__} cannot be initialized from the program data " f"{other_program.__class__.__name__}." ) from ex @property def name(self) -> str: """Name of this Schedule""" return self._name @property def metadata(self) -> dict[str, Any]: """The user provided metadata associated with the schedule. User provided ``dict`` of metadata for the schedule. The metadata contents do not affect the semantics of the program but are used to influence the execution of the schedule. It is expected to be passed between all transforms of the schedule and that providers will associate any schedule metadata with the results it returns from the execution of that schedule. """ return self._metadata @metadata.setter def metadata(self, metadata): """Update the schedule metadata""" if not isinstance(metadata, dict) and metadata is not None: raise TypeError("Only a dictionary or None is accepted for schedule metadata") self._metadata = metadata or {} @property def timeslots(self) -> TimeSlots: """Time keeping attribute.""" return self._timeslots @property def duration(self) -> int: """Duration of this schedule.""" return self._duration @property def start_time(self) -> int: """Starting time of this schedule.""" return self.ch_start_time(*self.channels) @property def stop_time(self) -> int: """Stopping time of this schedule.""" return self.duration @property def channels(self) -> tuple[Channel, ...]: """Returns channels that this schedule uses.""" return tuple(self._timeslots.keys()) @property def children(self) -> tuple[tuple[int, "ScheduleComponent"], ...]: """Return the child schedule components of this ``Schedule`` in the order they were added to the schedule. Notes: Nested schedules are returned as-is. If you want to collect only instructions, use :py:meth:`~Schedule.instructions` instead. Returns: A tuple, where each element is a two-tuple containing the initial scheduled time of each ``NamedValue`` and the component itself. """ return tuple(self._children) @property def instructions(self) -> tuple[tuple[int, Instruction], ...]: """Get the time-ordered instructions from self.""" def key(time_inst_pair): inst = time_inst_pair[1] return time_inst_pair[0], inst.duration, sorted(chan.name for chan in inst.channels) return tuple(sorted(self._instructions(), key=key)) @property def parameters(self) -> set[Parameter]: """Parameters which determine the schedule behavior.""" return self._parameter_manager.parameters def ch_duration(self, *channels: Channel) -> int: """Return the time of the end of the last instruction over the supplied channels. Args: *channels: Channels within ``self`` to include. """ return self.ch_stop_time(*channels) def ch_start_time(self, *channels: Channel) -> int: """Return the time of the start of the first instruction over the supplied channels. Args: *channels: Channels within ``self`` to include. """ try: chan_intervals = (self._timeslots[chan] for chan in channels if chan in self._timeslots) return min(intervals[0][0] for intervals in chan_intervals) except ValueError: # If there are no instructions over channels return 0 def ch_stop_time(self, *channels: Channel) -> int: """Return maximum start time over supplied channels. Args: *channels: Channels within ``self`` to include. """ try: chan_intervals = (self._timeslots[chan] for chan in channels if chan in self._timeslots) return max(intervals[-1][1] for intervals in chan_intervals) except ValueError: # If there are no instructions over channels return 0 def _instructions(self, time: int = 0): """Iterable for flattening Schedule tree. Args: time: Shifted time due to parent. Yields: Iterable[Tuple[int, Instruction]]: Tuple containing the time each :class:`~qiskit.pulse.Instruction` starts at and the flattened :class:`~qiskit.pulse.Instruction` s. """ for insert_time, child_sched in self.children: yield from child_sched._instructions(time + insert_time) def shift(self, time: int, name: str | None = None, inplace: bool = False) -> "Schedule": """Return a schedule shifted forward by ``time``. Args: time: Time to shift by. name: Name of the new schedule. Defaults to the name of self. inplace: Perform operation inplace on this schedule. Otherwise return a new ``Schedule``. """ if inplace: return self._mutable_shift(time) return self._immutable_shift(time, name=name) def _immutable_shift(self, time: int, name: str | None = None) -> "Schedule": """Return a new schedule shifted forward by `time`. Args: time: Time to shift by name: Name of the new schedule if call was mutable. Defaults to name of self """ shift_sched = Schedule.initialize_from(self, name) shift_sched.insert(time, self, inplace=True) return shift_sched def _mutable_shift(self, time: int) -> "Schedule": """Return this schedule shifted forward by `time`. Args: time: Time to shift by Raises: PulseError: if ``time`` is not an integer. """ if not isinstance(time, int): raise PulseError("Schedule start time must be an integer.") timeslots = {} for chan, ch_timeslots in self._timeslots.items(): timeslots[chan] = [(ts[0] + time, ts[1] + time) for ts in ch_timeslots] _check_nonnegative_timeslot(timeslots) self._duration = self._duration + time self._timeslots = timeslots self._children = [(orig_time + time, child) for orig_time, child in self.children] return self def insert( self, start_time: int, schedule: "ScheduleComponent", name: str | None = None, inplace: bool = False, ) -> "Schedule": """Return a new schedule with ``schedule`` inserted into ``self`` at ``start_time``. Args: start_time: Time to insert the schedule. schedule: Schedule to insert. name: Name of the new schedule. Defaults to the name of self. inplace: Perform operation inplace on this schedule. Otherwise return a new ``Schedule``. """ if inplace: return self._mutable_insert(start_time, schedule) return self._immutable_insert(start_time, schedule, name=name) def _mutable_insert(self, start_time: int, schedule: "ScheduleComponent") -> "Schedule": """Mutably insert `schedule` into `self` at `start_time`. Args: start_time: Time to insert the second schedule. schedule: Schedule to mutably insert. """ self._add_timeslots(start_time, schedule) self._children.append((start_time, schedule)) self._parameter_manager.update_parameter_table(schedule) return self def _immutable_insert( self, start_time: int, schedule: "ScheduleComponent", name: str | None = None, ) -> "Schedule": """Return a new schedule with ``schedule`` inserted into ``self`` at ``start_time``. Args: start_time: Time to insert the schedule. schedule: Schedule to insert. name: Name of the new ``Schedule``. Defaults to name of ``self``. """ new_sched = Schedule.initialize_from(self, name) new_sched._mutable_insert(0, self) new_sched._mutable_insert(start_time, schedule) return new_sched def append( self, schedule: "ScheduleComponent", name: str | None = None, inplace: bool = False ) -> "Schedule": r"""Return a new schedule with ``schedule`` inserted at the maximum time over all channels shared between ``self`` and ``schedule``. .. math:: t = \textrm{max}(\texttt{x.stop_time} |\texttt{x} \in \texttt{self.channels} \cap \texttt{schedule.channels}) Args: schedule: Schedule to be appended. name: Name of the new ``Schedule``. Defaults to name of ``self``. inplace: Perform operation inplace on this schedule. Otherwise return a new ``Schedule``. """ common_channels = set(self.channels) & set(schedule.channels) time = self.ch_stop_time(*common_channels) return self.insert(time, schedule, name=name, inplace=inplace) def filter( self, *filter_funcs: Callable, channels: Iterable[Channel] | None = None, instruction_types: Iterable[abc.ABCMeta] | abc.ABCMeta = None, time_ranges: Iterable[tuple[int, int]] | None = None, intervals: Iterable[Interval] | None = None, check_subroutine: bool = True, ) -> "Schedule": """Return a new ``Schedule`` with only the instructions from this ``Schedule`` which pass though the provided filters; i.e. an instruction will be retained iff every function in ``filter_funcs`` returns ``True``, the instruction occurs on a channel type contained in ``channels``, the instruction type is contained in ``instruction_types``, and the period over which the instruction operates is *fully* contained in one specified in ``time_ranges`` or ``intervals``. If no arguments are provided, ``self`` is returned. Args: filter_funcs: A list of Callables which take a (int, Union['Schedule', Instruction]) tuple and return a bool. channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``. instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``. time_ranges: For example, ``[(0, 5), (6, 10)]``. intervals: For example, ``[(0, 5), (6, 10)]``. check_subroutine: Set `True` to individually filter instructions inside of a subroutine defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction. """ from qiskit.pulse.filters import composite_filter, filter_instructions filters = composite_filter(channels, instruction_types, time_ranges, intervals) filters.extend(filter_funcs) return filter_instructions( self, filters=filters, negate=False, recurse_subroutines=check_subroutine ) def exclude( self, *filter_funcs: Callable, channels: Iterable[Channel] | None = None, instruction_types: Iterable[abc.ABCMeta] | abc.ABCMeta = None, time_ranges: Iterable[tuple[int, int]] | None = None, intervals: Iterable[Interval] | None = None, check_subroutine: bool = True, ) -> "Schedule": """Return a ``Schedule`` with only the instructions from this Schedule *failing* at least one of the provided filters. This method is the complement of :py:meth:`~Schedule.filter`, so that:: self.filter(args) | self.exclude(args) == self Args: filter_funcs: A list of Callables which take a (int, Union['Schedule', Instruction]) tuple and return a bool. channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``. instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``. time_ranges: For example, ``[(0, 5), (6, 10)]``. intervals: For example, ``[(0, 5), (6, 10)]``. check_subroutine: Set `True` to individually filter instructions inside of a subroutine defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction. """ from qiskit.pulse.filters import composite_filter, filter_instructions filters = composite_filter(channels, instruction_types, time_ranges, intervals) filters.extend(filter_funcs) return filter_instructions( self, filters=filters, negate=True, recurse_subroutines=check_subroutine ) def _add_timeslots(self, time: int, schedule: "ScheduleComponent") -> None: """Update all time tracking within this schedule based on the given schedule. Args: time: The time to insert the schedule into self. schedule: The schedule to insert into self. Raises: PulseError: If timeslots overlap or an invalid start time is provided. """ if not np.issubdtype(type(time), np.integer): raise PulseError("Schedule start time must be an integer.") other_timeslots = _get_timeslots(schedule) self._duration = max(self._duration, time + schedule.duration) for channel in schedule.channels: if channel not in self._timeslots: if time == 0: self._timeslots[channel] = copy.copy(other_timeslots[channel]) else: self._timeslots[channel] = [ (i[0] + time, i[1] + time) for i in other_timeslots[channel] ] continue for idx, interval in enumerate(other_timeslots[channel]): if interval[0] + time >= self._timeslots[channel][-1][1]: # Can append the remaining intervals self._timeslots[channel].extend( [(i[0] + time, i[1] + time) for i in other_timeslots[channel][idx:]] ) break try: interval = (interval[0] + time, interval[1] + time) index = _find_insertion_index(self._timeslots[channel], interval) self._timeslots[channel].insert(index, interval) except PulseError as ex: raise PulseError( f"Schedule(name='{schedule.name or ''}') cannot be inserted into " f"Schedule(name='{self.name or ''}') at " f"time {time} because its instruction on channel {channel} scheduled from time " f"{interval[0]} to {interval[1]} overlaps with an existing instruction." ) from ex _check_nonnegative_timeslot(self._timeslots) def _remove_timeslots(self, time: int, schedule: "ScheduleComponent"): """Delete the timeslots if present for the respective schedule component. Args: time: The time to remove the timeslots for the ``schedule`` component. schedule: The schedule to insert into self. Raises: PulseError: If timeslots overlap or an invalid start time is provided. """ if not isinstance(time, int): raise PulseError("Schedule start time must be an integer.") for channel in schedule.channels: if channel not in self._timeslots: raise PulseError(f"The channel {channel} is not present in the schedule") channel_timeslots = self._timeslots[channel] other_timeslots = _get_timeslots(schedule) for interval in other_timeslots[channel]: if channel_timeslots: interval = (interval[0] + time, interval[1] + time) index = _interval_index(channel_timeslots, interval) if channel_timeslots[index] == interval: channel_timeslots.pop(index) continue raise PulseError( f"Cannot find interval ({interval[0]}, {interval[1]}) to remove from " f"channel {channel} in Schedule(name='{schedule.name}')." ) if not channel_timeslots: self._timeslots.pop(channel) def _replace_timeslots(self, time: int, old: "ScheduleComponent", new: "ScheduleComponent"): """Replace the timeslots of ``old`` if present with the timeslots of ``new``. Args: time: The time to remove the timeslots for the ``schedule`` component. old: Instruction to replace. new: Instruction to replace with. """ self._remove_timeslots(time, old) self._add_timeslots(time, new) def _renew_timeslots(self): """Regenerate timeslots based on current instructions.""" self._timeslots.clear() for t0, inst in self.instructions: self._add_timeslots(t0, inst) def replace( self, old: "ScheduleComponent", new: "ScheduleComponent", inplace: bool = False, ) -> "Schedule": """Return a ``Schedule`` with the ``old`` instruction replaced with a ``new`` instruction. The replacement matching is based on an instruction equality check. .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) sched = pulse.Schedule() old = pulse.Play(pulse.Constant(100, 1.0), d0) new = pulse.Play(pulse.Constant(100, 0.1), d0) sched += old sched = sched.replace(old, new) assert sched == pulse.Schedule(new) Only matches at the top-level of the schedule tree. If you wish to perform this replacement over all instructions in the schedule tree. Flatten the schedule prior to running:: .. code-block:: sched = pulse.Schedule() sched += pulse.Schedule(old) sched = sched.flatten() sched = sched.replace(old, new) assert sched == pulse.Schedule(new) Args: old: Instruction to replace. new: Instruction to replace with. inplace: Replace instruction by mutably modifying this ``Schedule``. Returns: The modified schedule with ``old`` replaced by ``new``. Raises: PulseError: If the ``Schedule`` after replacements will has a timing overlap. """ from qiskit.pulse.parameter_manager import ParameterManager new_children = [] new_parameters = ParameterManager() for time, child in self.children: if child == old: new_children.append((time, new)) new_parameters.update_parameter_table(new) else: new_children.append((time, child)) new_parameters.update_parameter_table(child) if inplace: self._children = new_children self._parameter_manager = new_parameters self._renew_timeslots() return self else: try: new_sched = Schedule.initialize_from(self) for time, inst in new_children: new_sched.insert(time, inst, inplace=True) return new_sched except PulseError as err: raise PulseError( f"Replacement of {old} with {new} results in overlapping instructions." ) from err def is_parameterized(self) -> bool: """Return True iff the instruction is parameterized.""" return self._parameter_manager.is_parameterized() def assign_parameters( self, value_dict: dict[ ParameterExpression | ParameterVector | str, ParameterValueType | Sequence[ParameterValueType], ], inplace: bool = True, ) -> "Schedule": """Assign the parameters in this schedule according to the input. Args: value_dict: A mapping from parameters or parameter names (parameter vector or parameter vector name) to either numeric values (list of numeric values) or another parameter expression (list of parameter expressions). inplace: Set ``True`` to override this instance with new parameter. Returns: Schedule with updated parameters. """ if not inplace: new_schedule = copy.deepcopy(self) return new_schedule.assign_parameters(value_dict, inplace=True) return self._parameter_manager.assign_parameters(pulse_program=self, value_dict=value_dict) def get_parameters(self, parameter_name: str) -> list[Parameter]: """Get parameter object bound to this schedule by string name. Because different ``Parameter`` objects can have the same name, this method returns a list of ``Parameter`` s for the provided name. Args: parameter_name: Name of parameter. Returns: Parameter objects that have corresponding name. """ return self._parameter_manager.get_parameters(parameter_name) def __len__(self) -> int: """Return number of instructions in the schedule.""" return len(self.instructions) def __add__(self, other: "ScheduleComponent") -> "Schedule": """Return a new schedule with ``other`` inserted within ``self`` at ``start_time``.""" return self.append(other) def __or__(self, other: "ScheduleComponent") -> "Schedule": """Return a new schedule which is the union of `self` and `other`.""" return self.insert(0, other) def __lshift__(self, time: int) -> "Schedule": """Return a new schedule which is shifted forward by ``time``.""" return self.shift(time) def __eq__(self, other: object) -> bool: """Test if two Schedule are equal. Equality is checked by verifying there is an equal instruction at every time in ``other`` for every instruction in this ``Schedule``. .. warning:: This does not check for logical equivalency. Ie., ```python >>> Delay(10, DriveChannel(0)) + Delay(10, DriveChannel(0)) == Delay(20, DriveChannel(0)) False ``` """ # 0. type check, we consider Instruction is a subtype of schedule if not isinstance(other, (type(self), Instruction)): return False # 1. channel check if set(self.channels) != set(other.channels): return False # 2. size check if len(self.instructions) != len(other.instructions): return False # 3. instruction check return all( self_inst == other_inst for self_inst, other_inst in zip(self.instructions, other.instructions) ) def __repr__(self) -> str: name = format(self._name) if self._name else "" instructions = ", ".join([repr(instr) for instr in self.instructions[:50]]) if len(self.instructions) > 25: instructions += ", ..." return f'{self.__class__.__name__}({instructions}, name="{name}")' def _require_schedule_conversion(function: Callable) -> Callable: """A method decorator to convert schedule block to pulse schedule. This conversation is performed for backward compatibility only if all durations are assigned. """ @functools.wraps(function) def wrapper(self, *args, **kwargs): from qiskit.pulse.transforms import block_to_schedule return function(block_to_schedule(self), *args, **kwargs) return wrapper class ScheduleBlock: """Time-ordered sequence of instructions with alignment context. :class:`.ScheduleBlock` supports lazy scheduling of context instructions, i.e. their timeslots is always generated at runtime. This indicates we can parametrize instruction durations as well as other parameters. In contrast to :class:`.Schedule` being somewhat static, :class:`.ScheduleBlock` is a dynamic representation of a pulse program. .. rubric:: Pulse Builder The Qiskit pulse builder is a domain specific language that is developed on top of the schedule block. Use of the builder syntax will improve the workflow of pulse programming. See :ref:`pulse_builder` for a user guide. .. rubric:: Alignment contexts A schedule block is always relatively scheduled. Instead of taking individual instructions with absolute execution time ``t0``, the schedule block defines a context of scheduling and instructions under the same context are scheduled in the same manner (alignment). Several contexts are available in :ref:`pulse_alignments`. A schedule block is instantiated with one of these alignment contexts. The default context is :class:`AlignLeft`, for which all instructions are left-justified, in other words, meaning they use as-soon-as-possible scheduling. If you need an absolute-time interval in between instructions, you can explicitly insert :class:`~qiskit.pulse.instructions.Delay` instructions. .. rubric:: Nested blocks A schedule block can contain other nested blocks with different alignment contexts. This enables advanced scheduling, where a subset of instructions is locally scheduled in a different manner. Note that a :class:`.Schedule` instance cannot be directly added to a schedule block. To add a :class:`.Schedule` instance, wrap it in a :class:`.Call` instruction. This is implicitly performed when a schedule is added through the :ref:`pulse_builder`. .. rubric:: Unsupported operations Because the schedule block representation lacks timeslots, it cannot perform particular :class:`.Schedule` operations such as :meth:`insert` or :meth:`shift` that require instruction start time ``t0``. In addition, :meth:`exclude` and :meth:`filter` methods are not supported because these operations may identify the target instruction with ``t0``. Except for these operations, :class:`.ScheduleBlock` provides full compatibility with :class:`.Schedule`. .. rubric:: Subroutine The timeslots-free representation offers much greater flexibility for writing pulse programs. Because :class:`.ScheduleBlock` only cares about the ordering of the child blocks we can add an undefined pulse sequence as a subroutine of the main program. If your program contains the same sequence multiple times, this representation may reduce the memory footprint required by the program construction. Such a subroutine is realized by the special compiler directive :class:`~qiskit.pulse.instructions.Reference` that is defined by a unique set of reference key strings to the subroutine. The (executable) subroutine is separately stored in the main program. Appended reference directives are resolved when the main program is executed. Subroutines must be assigned through :meth:`assign_references` before execution. One way to reference a subroutine in a schedule is to use the pulse builder's :func:`~qiskit.pulse.builder.reference` function to declare an unassigned reference. In this example, the program is called with the reference key "grand_child". You can call a subroutine without specifying a substantial program. .. code-block:: from qiskit import pulse from qiskit.circuit.parameter import Parameter amp1 = Parameter("amp1") amp2 = Parameter("amp2") with pulse.build() as sched_inner: pulse.play(pulse.Constant(100, amp1), pulse.DriveChannel(0)) with pulse.build() as sched_outer: with pulse.align_right(): pulse.reference("grand_child") pulse.play(pulse.Constant(200, amp2), pulse.DriveChannel(0)) Now you assign the inner pulse program to this reference. .. code-block:: sched_outer.assign_references({("grand_child", ): sched_inner}) print(sched_outer.parameters) .. parsed-literal:: {Parameter(amp1), Parameter(amp2)} The outer program now has the parameter ``amp2`` from the inner program, indicating that the inner program's data has been made available to the outer program. The program calling the "grand_child" has a reference program description which is accessed through :attr:`ScheduleBlock.references`. .. code-block:: print(sched_outer.references) .. parsed-literal:: ReferenceManager: - ('grand_child',): ScheduleBlock(Play(Constant(duration=100, amp=amp1,... Finally, you may want to call this program from another program. Here we try a different approach to define subroutine. Namely, we call a subroutine from the root program with the actual program ``sched2``. .. code-block:: amp3 = Parameter("amp3") with pulse.build() as main: pulse.play(pulse.Constant(300, amp3), pulse.DriveChannel(0)) pulse.call(sched_outer, name="child") print(main.parameters) .. parsed-literal:: {Parameter(amp1), Parameter(amp2), Parameter(amp3} This implicitly creates a reference named "child" within the root program and assigns ``sched_outer`` to it. Note that the root program is only aware of its direct references. .. code-block:: print(main.references) .. parsed-literal:: ReferenceManager: - ('child',): ScheduleBlock(ScheduleBlock(ScheduleBlock(Play(Con... As you can see the main program cannot directly assign a subroutine to the "grand_child" because this subroutine is not called within the root program, i.e. it is indirectly called by "child". However, the returned :class:`.ReferenceManager` is a dict-like object, and you can still reach to "grand_child" via the "child" program with the following chained dict access. .. code-block:: main.references[("child", )].references[("grand_child", )] Note that :attr:`ScheduleBlock.parameters` still collects all parameters also from the subroutine once it's assigned. """ __slots__ = ( "_parent", "_name", "_reference_manager", "_parameter_manager", "_alignment_context", "_blocks", "_metadata", ) # Prefix to use for auto naming. prefix = "block" # Counter to count instance number. instances_counter = itertools.count() def __init__( self, name: str | None = None, metadata: dict | None = None, alignment_context=None ): """Create an empty schedule block. Args: name: Name of this schedule. Defaults to an autogenerated string if not provided. metadata: Arbitrary key value metadata to associate with the schedule. This gets stored as free-form data in a dict in the :attr:`~qiskit.pulse.ScheduleBlock.metadata` attribute. It will not be directly used in the schedule. alignment_context (AlignmentKind): ``AlignmentKind`` instance that manages scheduling of instructions in this block. Raises: TypeError: if metadata is not a dict. """ from qiskit.pulse.parameter_manager import ParameterManager from qiskit.pulse.transforms import AlignLeft if name is None: name = self.prefix + str(next(self.instances_counter)) if sys.platform != "win32" and not is_main_process(): name += f"-{mp.current_process().pid}" # This points to the parent schedule object in the current scope. # Note that schedule block can be nested without referencing, e.g. .append(child_block), # and parent=None indicates the root program of the current scope. # The nested schedule block objects should not have _reference_manager and # should refer to the one of the root program. # This also means referenced program should be assigned to the root program, not to child. self._parent: ScheduleBlock | None = None self._name = name self._parameter_manager = ParameterManager() self._reference_manager = ReferenceManager() self._alignment_context = alignment_context or AlignLeft() self._blocks: list["BlockComponent"] = [] # get parameters from context self._parameter_manager.update_parameter_table(self._alignment_context) if not isinstance(metadata, dict) and metadata is not None: raise TypeError("Only a dictionary or None is accepted for schedule metadata") self._metadata = metadata or {} @classmethod def initialize_from(cls, other_program: Any, name: str | None = None) -> "ScheduleBlock": """Create new schedule object with metadata of another schedule object. Args: other_program: Qiskit program that provides metadata to new object. name: Name of new schedule. Name of ``block`` is used by default. Returns: New block object with name and metadata. Raises: PulseError: When ``other_program`` does not provide necessary information. """ try: name = name or other_program.name if other_program.metadata: metadata = other_program.metadata.copy() else: metadata = None try: alignment_context = other_program.alignment_context except AttributeError: alignment_context = None return cls(name=name, metadata=metadata, alignment_context=alignment_context) except AttributeError as ex: raise PulseError( f"{cls.__name__} cannot be initialized from the program data " f"{other_program.__class__.__name__}." ) from ex @property def name(self) -> str: """Return name of this schedule""" return self._name @property def metadata(self) -> dict[str, Any]: """The user provided metadata associated with the schedule. User provided ``dict`` of metadata for the schedule. The metadata contents do not affect the semantics of the program but are used to influence the execution of the schedule. It is expected to be passed between all transforms of the schedule and that providers will associate any schedule metadata with the results it returns from the execution of that schedule. """ return self._metadata @metadata.setter def metadata(self, metadata): """Update the schedule metadata""" if not isinstance(metadata, dict) and metadata is not None: raise TypeError("Only a dictionary or None is accepted for schedule metadata") self._metadata = metadata or {} @property def alignment_context(self): """Return alignment instance that allocates block component to generate schedule.""" return self._alignment_context def is_schedulable(self) -> bool: """Return ``True`` if all durations are assigned.""" # check context assignment for context_param in self._alignment_context._context_params: if isinstance(context_param, ParameterExpression): return False # check duration assignment for elm in self.blocks: if isinstance(elm, ScheduleBlock): if not elm.is_schedulable(): return False else: try: if not isinstance(elm.duration, int): return False except UnassignedReferenceError: return False return True @property @_require_schedule_conversion def duration(self) -> int: """Duration of this schedule block.""" return self.duration @property def channels(self) -> tuple[Channel, ...]: """Returns channels that this schedule block uses.""" chans: set[Channel] = set() for elm in self.blocks: if isinstance(elm, Reference): raise UnassignedReferenceError( f"This schedule contains unassigned reference {elm.ref_keys} " "and channels are ambiguous. Please assign the subroutine first." ) chans = chans | set(elm.channels) return tuple(chans) @property @_require_schedule_conversion def instructions(self) -> tuple[tuple[int, Instruction]]: """Get the time-ordered instructions from self.""" return self.instructions @property def blocks(self) -> tuple["BlockComponent", ...]: """Get the block elements added to self. .. note:: The sequence of elements is returned in order of addition. Because the first element is schedule first, e.g. FIFO, the returned sequence is roughly time-ordered. However, in the parallel alignment context, especially in the as-late-as-possible scheduling, or :class:`.AlignRight` context, the actual timing of when the instructions are issued is unknown until the :class:`.ScheduleBlock` is scheduled and converted into a :class:`.Schedule`. """ blocks = [] for elm in self._blocks: if isinstance(elm, Reference): elm = self.references.get(elm.ref_keys, None) or elm blocks.append(elm) return tuple(blocks) @property def parameters(self) -> set[Parameter]: """Return unassigned parameters with raw names.""" # Need new object not to mutate parameter_manager.parameters out_params = set() out_params |= self._parameter_manager.parameters for subroutine in self.references.values(): if subroutine is None: continue out_params |= subroutine.parameters return out_params @property def references(self) -> ReferenceManager: """Return a reference manager of the current scope.""" if self._parent is not None: return self._parent.references return self._reference_manager @_require_schedule_conversion def ch_duration(self, *channels: Channel) -> int: """Return the time of the end of the last instruction over the supplied channels. Args: *channels: Channels within ``self`` to include. """ return self.ch_duration(*channels) def append( self, block: "BlockComponent", name: str | None = None, inplace: bool = True ) -> "ScheduleBlock": """Return a new schedule block with ``block`` appended to the context block. The execution time is automatically assigned when the block is converted into schedule. Args: block: ScheduleBlock to be appended. name: Name of the new ``Schedule``. Defaults to name of ``self``. inplace: Perform operation inplace on this schedule. Otherwise, return a new ``Schedule``. Returns: Schedule block with appended schedule. Raises: PulseError: When invalid schedule type is specified. """ if not isinstance(block, (ScheduleBlock, Instruction)): raise PulseError( f"Appended `schedule` {block.__class__.__name__} is invalid type. " "Only `Instruction` and `ScheduleBlock` can be accepted." ) if not inplace: schedule = copy.deepcopy(self) schedule._name = name or self.name schedule.append(block, inplace=True) return schedule if isinstance(block, Reference) and block.ref_keys not in self.references: self.references[block.ref_keys] = None elif isinstance(block, ScheduleBlock): block = copy.deepcopy(block) # Expose subroutines to the current main scope. # Note that this 'block' is not called. # The block is just directly appended to the current scope. if block.is_referenced(): if block._parent is not None: # This is an edge case: # If this is not a parent, block.references points to the parent's reference # where subroutine not referred within the 'block' may exist. # Move only references existing in the 'block'. # See 'test.python.pulse.test_reference.TestReference.test_appending_child_block' for ref in _get_references(block._blocks): self.references[ref.ref_keys] = block.references[ref.ref_keys] else: # Avoid using dict.update and explicitly call __set_item__ for validation. # Reference manager of appended block is cleared because of data reduction. for ref_keys, ref in block._reference_manager.items(): self.references[ref_keys] = ref block._reference_manager.clear() # Now switch the parent because block is appended to self. block._parent = self self._blocks.append(block) self._parameter_manager.update_parameter_table(block) return self def filter( self, *filter_funcs: Callable[..., bool], channels: Iterable[Channel] | None = None, instruction_types: Iterable[abc.ABCMeta] | abc.ABCMeta = None, check_subroutine: bool = True, ): """Return a new ``ScheduleBlock`` with only the instructions from this ``ScheduleBlock`` which pass though the provided filters; i.e. an instruction will be retained if every function in ``filter_funcs`` returns ``True``, the instruction occurs on a channel type contained in ``channels``, and the instruction type is contained in ``instruction_types``. .. warning:: Because ``ScheduleBlock`` is not aware of the execution time of the context instructions, filtering out some instructions may change the execution time of the remaining instructions. If no arguments are provided, ``self`` is returned. Args: filter_funcs: A list of Callables which take a ``Instruction`` and return a bool. channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``. instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``. check_subroutine: Set `True` to individually filter instructions inside a subroutine defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction. Returns: ``ScheduleBlock`` consisting of instructions that matches with filtering condition. """ from qiskit.pulse.filters import composite_filter, filter_instructions filters = composite_filter(channels, instruction_types) filters.extend(filter_funcs) return filter_instructions( self, filters=filters, negate=False, recurse_subroutines=check_subroutine ) def exclude( self, *filter_funcs: Callable[..., bool], channels: Iterable[Channel] | None = None, instruction_types: Iterable[abc.ABCMeta] | abc.ABCMeta = None, check_subroutine: bool = True, ): """Return a new ``ScheduleBlock`` with only the instructions from this ``ScheduleBlock`` *failing* at least one of the provided filters. This method is the complement of :py:meth:`~ScheduleBlock.filter`, so that:: self.filter(args) + self.exclude(args) == self in terms of instructions included. .. warning:: Because ``ScheduleBlock`` is not aware of the execution time of the context instructions, excluding some instructions may change the execution time of the remaining instructions. Args: filter_funcs: A list of Callables which take a ``Instruction`` and return a bool. channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``. instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``. check_subroutine: Set `True` to individually filter instructions inside of a subroutine defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction. Returns: ``ScheduleBlock`` consisting of instructions that do not match with at least one of filtering conditions. """ from qiskit.pulse.filters import composite_filter, filter_instructions filters = composite_filter(channels, instruction_types) filters.extend(filter_funcs) return filter_instructions( self, filters=filters, negate=True, recurse_subroutines=check_subroutine ) def replace( self, old: "BlockComponent", new: "BlockComponent", inplace: bool = True, ) -> "ScheduleBlock": """Return a ``ScheduleBlock`` with the ``old`` component replaced with a ``new`` component. Args: old: Schedule block component to replace. new: Schedule block component to replace with. inplace: Replace instruction by mutably modifying this ``ScheduleBlock``. Returns: The modified schedule block with ``old`` replaced by ``new``. """ if not inplace: schedule = copy.deepcopy(self) return schedule.replace(old, new, inplace=True) if old not in self._blocks: # Avoid unnecessary update of reference and parameter manager return self # Temporarily copies references all_references = ReferenceManager() if isinstance(new, ScheduleBlock): new = copy.deepcopy(new) all_references.update(new.references) new._reference_manager.clear() new._parent = self for ref_key, subroutine in self.references.items(): if ref_key in all_references: warnings.warn( f"Reference {ref_key} conflicts with substituted program {new.name}. " "Existing reference has been replaced with new reference.", UserWarning, ) continue all_references[ref_key] = subroutine # Regenerate parameter table by regenerating elements. # Note that removal of parameters in old is not sufficient, # because corresponding parameters might be also used in another block element. self._parameter_manager.clear() self._parameter_manager.update_parameter_table(self._alignment_context) new_elms = [] for elm in self._blocks: if elm == old: elm = new self._parameter_manager.update_parameter_table(elm) new_elms.append(elm) self._blocks = new_elms # Regenerate reference table # Note that reference is attached to the outer schedule if nested. # Thus, this investigates all references within the scope. self.references.clear() root = self while root._parent is not None: root = root._parent for ref in _get_references(root._blocks): self.references[ref.ref_keys] = all_references[ref.ref_keys] return self def is_parameterized(self) -> bool: """Return True iff the instruction is parameterized.""" return any(self.parameters) def is_referenced(self) -> bool: """Return True iff the current schedule block contains reference to subroutine.""" return len(self.references) > 0 def assign_parameters( self, value_dict: dict[ ParameterExpression | ParameterVector | str, ParameterValueType | Sequence[ParameterValueType], ], inplace: bool = True, ) -> "ScheduleBlock": """Assign the parameters in this schedule according to the input. Args: value_dict: A mapping from parameters or parameter names (parameter vector or parameter vector name) to either numeric values (list of numeric values) or another parameter expression (list of parameter expressions). inplace: Set ``True`` to override this instance with new parameter. Returns: Schedule with updated parameters. Raises: PulseError: When the block is nested into another block. """ if not inplace: new_schedule = copy.deepcopy(self) return new_schedule.assign_parameters(value_dict, inplace=True) # Update parameters in the current scope self._parameter_manager.assign_parameters(pulse_program=self, value_dict=value_dict) for subroutine in self._reference_manager.values(): # Also assigning parameters to the references associated with self. # Note that references are always stored in the root program. # So calling assign_parameters from nested block doesn't update references. if subroutine is None: continue subroutine.assign_parameters(value_dict=value_dict, inplace=True) return self def assign_references( self, subroutine_dict: dict[str | tuple[str, ...], "ScheduleBlock"], inplace: bool = True, ) -> "ScheduleBlock": """Assign schedules to references. It is only capable of assigning a schedule block to immediate references which are directly referred within the current scope. Let's see following example: .. code-block:: python from qiskit import pulse with pulse.build() as subroutine: pulse.delay(10, pulse.DriveChannel(0)) with pulse.build() as sub_prog: pulse.reference("A") with pulse.build() as main_prog: pulse.reference("B") In above example, the ``main_prog`` can refer to the subroutine "root::B" and the reference of "B" to program "A", i.e., "B::A", is not defined in the root namespace. This prevents breaking the reference "root::B::A" by the assignment of "root::B". For example, if a user could indirectly assign "root::B::A" from the root program, one can later assign another program to "root::B" that doesn't contain "A" within it. In this situation, a reference "root::B::A" would still live in the reference manager of the root. However, the subroutine "root::B::A" would no longer be used in the actual pulse program. To assign subroutine "A" to ``nested_prog`` as a nested subprogram of ``main_prog``, you must first assign "A" of the ``sub_prog``, and then assign the ``sub_prog`` to the ``main_prog``. .. code-block:: python sub_prog.assign_references({("A", ): nested_prog}, inplace=True) main_prog.assign_references({("B", ): sub_prog}, inplace=True) Alternatively, you can also write .. code-block:: python main_prog.assign_references({("B", ): sub_prog}, inplace=True) main_prog.references[("B", )].assign_references({"A": nested_prog}, inplace=True) Here :attr:`.references` returns a dict-like object, and you can mutably update the nested reference of the particular subroutine. .. note:: Assigned programs are deep-copied to prevent an unexpected update. Args: subroutine_dict: A mapping from reference key to schedule block of the subroutine. inplace: Set ``True`` to override this instance with new subroutine. Returns: Schedule block with assigned subroutine. Raises: PulseError: When reference key is not defined in the current scope. """ if not inplace: new_schedule = copy.deepcopy(self) return new_schedule.assign_references(subroutine_dict, inplace=True) for key, subroutine in subroutine_dict.items(): if key not in self.references: unassigned_keys = ", ".join(map(repr, self.references.unassigned())) raise PulseError( f"Reference instruction with {key} doesn't exist " f"in the current scope: {unassigned_keys}" ) self.references[key] = copy.deepcopy(subroutine) return self def get_parameters(self, parameter_name: str) -> list[Parameter]: """Get parameter object bound to this schedule by string name. Note that we can define different parameter objects with the same name, because these different objects are identified by their unique uuid. For example, .. code-block:: python from qiskit import pulse, circuit amp1 = circuit.Parameter("amp") amp2 = circuit.Parameter("amp") with pulse.build() as sub_prog: pulse.play(pulse.Constant(100, amp1), pulse.DriveChannel(0)) with pulse.build() as main_prog: pulse.call(sub_prog, name="sub") pulse.play(pulse.Constant(100, amp2), pulse.DriveChannel(0)) main_prog.get_parameters("amp") This returns a list of two parameters ``amp1`` and ``amp2``. Args: parameter_name: Name of parameter. Returns: Parameter objects that have corresponding name. """ matched = [p for p in self.parameters if p.name == parameter_name] return matched def __len__(self) -> int: """Return number of instructions in the schedule.""" return len(self.blocks) def __eq__(self, other: object) -> bool: """Test if two ScheduleBlocks are equal. Equality is checked by verifying there is an equal instruction at every time in ``other`` for every instruction in this ``ScheduleBlock``. This check is performed by converting the instruction representation into directed acyclic graph, in which execution order of every instruction is evaluated correctly across all channels. Also ``self`` and ``other`` should have the same alignment context. .. warning:: This does not check for logical equivalency. Ie., ```python >>> Delay(10, DriveChannel(0)) + Delay(10, DriveChannel(0)) == Delay(20, DriveChannel(0)) False ``` """ # 0. type check if not isinstance(other, type(self)): return False # 1. transformation check if self.alignment_context != other.alignment_context: return False # 2. size check if len(self) != len(other): return False # 3. instruction check with alignment from qiskit.pulse.transforms.dag import block_to_dag as dag if not rx.is_isomorphic_node_match(dag(self), dag(other), lambda x, y: x == y): return False return True def __repr__(self) -> str: name = format(self._name) if self._name else "" blocks = ", ".join([repr(instr) for instr in self.blocks[:50]]) if len(self.blocks) > 25: blocks += ", ..." return ( f'{self.__class__.__name__}({blocks}, name="{name}",' f" transform={repr(self.alignment_context)})" ) def __add__(self, other: "BlockComponent") -> "ScheduleBlock": """Return a new schedule with ``other`` inserted within ``self`` at ``start_time``.""" return self.append(other) def _common_method(*classes): """A function decorator to attach the function to specified classes as a method. .. note:: For developer: A method attached through this decorator may hurt readability of the codebase, because the method may not be detected by a code editor. Thus, this decorator should be used to a limited extent, i.e. huge helper method. By using this decorator wisely, we can reduce code maintenance overhead without losing readability of the codebase. """ def decorator(method): @functools.wraps(method) def wrapper(*args, **kwargs): return method(*args, **kwargs) for cls in classes: setattr(cls, method.__name__, wrapper) return method return decorator @deprecate_arg("show_barriers", new_alias="plot_barriers", since="1.1.0", pending=True) @_common_method(Schedule, ScheduleBlock) def draw( self, style: dict[str, Any] | None = None, backend=None, # importing backend causes cyclic import time_range: tuple[int, int] | None = None, time_unit: str = "dt", disable_channels: list[Channel] | None = None, show_snapshot: bool = True, show_framechange: bool = True, show_waveform_info: bool = True, plot_barrier: bool = True, plotter: str = "mpl2d", axis: Any | None = None, show_barrier: bool = True, ): """Plot the schedule. Args: style: Stylesheet options. This can be dictionary or preset stylesheet classes. See :py:class:`~qiskit.visualization.pulse_v2.stylesheets.IQXStandard`, :py:class:`~qiskit.visualization.pulse_v2.stylesheets.IQXSimple`, and :py:class:`~qiskit.visualization.pulse_v2.stylesheets.IQXDebugging` for details of preset stylesheets. backend (Optional[BaseBackend]): Backend object to play the input pulse program. If provided, the plotter may use to make the visualization hardware aware. time_range: Set horizontal axis limit. Tuple ``(tmin, tmax)``. time_unit: The unit of specified time range either ``dt`` or ``ns``. The unit of `ns` is available only when ``backend`` object is provided. disable_channels: A control property to show specific pulse channel. Pulse channel instances provided as a list are not shown in the output image. show_snapshot: Show snapshot instructions. show_framechange: Show frame change instructions. The frame change represents instructions that modulate phase or frequency of pulse channels. show_waveform_info: Show additional information about waveforms such as their name. plot_barrier: Show barrier lines. plotter: Name of plotter API to generate an output image. One of following APIs should be specified:: mpl2d: Matplotlib API for 2D image generation. Matplotlib API to generate 2D image. Charts are placed along y axis with vertical offset. This API takes matplotlib.axes.Axes as ``axis`` input. ``axis`` and ``style`` kwargs may depend on the plotter. axis: Arbitrary object passed to the plotter. If this object is provided, the plotters use a given ``axis`` instead of internally initializing a figure object. This object format depends on the plotter. See plotter argument for details. show_barrier: DEPRECATED. Show barrier lines. Returns: Visualization output data. The returned data type depends on the ``plotter``. If matplotlib family is specified, this will be a ``matplotlib.pyplot.Figure`` data. """ # pylint: disable=cyclic-import from qiskit.visualization import pulse_drawer del show_barrier return pulse_drawer( program=self, style=style, backend=backend, time_range=time_range, time_unit=time_unit, disable_channels=disable_channels, show_snapshot=show_snapshot, show_framechange=show_framechange, show_waveform_info=show_waveform_info, plot_barrier=plot_barrier, plotter=plotter, axis=axis, ) def _interval_index(intervals: list[Interval], interval: Interval) -> int: """Find the index of an interval. Args: intervals: A sorted list of non-overlapping Intervals. interval: The interval for which the index into intervals will be found. Returns: The index of the interval. Raises: PulseError: If the interval does not exist. """ index = _locate_interval_index(intervals, interval) found_interval = intervals[index] if found_interval != interval: raise PulseError(f"The interval: {interval} does not exist in intervals: {intervals}") return index def _locate_interval_index(intervals: list[Interval], interval: Interval, index: int = 0) -> int: """Using binary search on start times, find an interval. Args: intervals: A sorted list of non-overlapping Intervals. interval: The interval for which the index into intervals will be found. index: A running tally of the index, for recursion. The user should not pass a value. Returns: The index into intervals that new_interval would be inserted to maintain a sorted list of intervals. """ if not intervals or len(intervals) == 1: return index mid_idx = len(intervals) // 2 mid = intervals[mid_idx] if interval[1] <= mid[0] and (interval != mid): return _locate_interval_index(intervals[:mid_idx], interval, index=index) else: return _locate_interval_index(intervals[mid_idx:], interval, index=index + mid_idx) def _find_insertion_index(intervals: list[Interval], new_interval: Interval) -> int: """Using binary search on start times, return the index into `intervals` where the new interval belongs, or raise an error if the new interval overlaps with any existing ones. Args: intervals: A sorted list of non-overlapping Intervals. new_interval: The interval for which the index into intervals will be found. Returns: The index into intervals that new_interval should be inserted to maintain a sorted list of intervals. Raises: PulseError: If new_interval overlaps with the given intervals. """ index = _locate_interval_index(intervals, new_interval) if index < len(intervals): if _overlaps(intervals[index], new_interval): raise PulseError("New interval overlaps with existing.") return index if new_interval[1] <= intervals[index][0] else index + 1 return index def _overlaps(first: Interval, second: Interval) -> bool: """Return True iff first and second overlap. Note: first.stop may equal second.start, since Interval stop times are exclusive. """ if first[0] == second[0] == second[1]: # They fail to overlap if one of the intervals has duration 0 return False if first[0] > second[0]: first, second = second, first return second[0] < first[1] def _check_nonnegative_timeslot(timeslots: TimeSlots): """Test that a channel has no negative timeslots. Raises: PulseError: If a channel timeslot is negative. """ for chan, chan_timeslots in timeslots.items(): if chan_timeslots: if chan_timeslots[0][0] < 0: raise PulseError(f"An instruction on {chan} has a negative starting time.") def _get_timeslots(schedule: "ScheduleComponent") -> TimeSlots: """Generate timeslots from given schedule component. Args: schedule: Input schedule component. Raises: PulseError: When invalid schedule type is specified. """ if isinstance(schedule, Instruction): duration = schedule.duration instruction_duration_validation(duration) timeslots = {channel: [(0, duration)] for channel in schedule.channels} elif isinstance(schedule, Schedule): timeslots = schedule.timeslots else: raise PulseError(f"Invalid schedule type {type(schedule)} is specified.") return timeslots def _get_references(block_elms: list["BlockComponent"]) -> set[Reference]: """Recursively get reference instructions in the current scope. Args: block_elms: List of schedule block elements to investigate. Returns: A set of unique reference instructions. """ references = set() for elm in block_elms: if isinstance(elm, ScheduleBlock): references |= _get_references(elm._blocks) elif isinstance(elm, Reference): references.add(elm) return references # These type aliases are defined at the bottom of the file, because as of 2022-01-18 they are # imported into other parts of Terra. Previously, the aliases were at the top of the file and used # forwards references within themselves. This was fine within the same file, but causes scoping # issues when the aliases are imported into different scopes, in which the `ForwardRef` instances # would no longer resolve. Instead, we only use forward references in the annotations of _this_ # file to reference the aliases, which are guaranteed to resolve in scope, so the aliases can all be # concrete. ScheduleComponent = Union[Schedule, Instruction] """An element that composes a pulse schedule.""" BlockComponent = Union[ScheduleBlock, Instruction] """An element that composes a pulse schedule block."""
qiskit/qiskit/pulse/schedule.py/0
{ "file_path": "qiskit/qiskit/pulse/schedule.py", "repo_id": "qiskit", "token_count": 28401 }
191
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2022. # # 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. """Binary IO for any value objects, such as numbers, string, parameters.""" from __future__ import annotations import collections.abc import struct import uuid import numpy as np import symengine from symengine.lib.symengine_wrapper import ( # pylint: disable = no-name-in-module load_basic, ) from qiskit.circuit import CASE_DEFAULT, Clbit, ClassicalRegister from qiskit.circuit.classical import expr, types from qiskit.circuit.parameter import Parameter from qiskit.circuit.parameterexpression import ParameterExpression from qiskit.circuit.parametervector import ParameterVector, ParameterVectorElement from qiskit.qpy import common, formats, exceptions, type_keys def _write_parameter(file_obj, obj): name_bytes = obj.name.encode(common.ENCODE) file_obj.write(struct.pack(formats.PARAMETER_PACK, len(name_bytes), obj.uuid.bytes)) file_obj.write(name_bytes) def _write_parameter_vec(file_obj, obj): name_bytes = obj._vector._name.encode(common.ENCODE) file_obj.write( struct.pack( formats.PARAMETER_VECTOR_ELEMENT_PACK, len(name_bytes), len(obj._vector), obj.uuid.bytes, obj._index, ) ) file_obj.write(name_bytes) def _write_parameter_expression(file_obj, obj, use_symengine, *, version): if use_symengine: expr_bytes = obj._symbol_expr.__reduce__()[1][0] else: from sympy import srepr, sympify expr_bytes = srepr(sympify(obj._symbol_expr)).encode(common.ENCODE) param_expr_header_raw = struct.pack( formats.PARAMETER_EXPR_PACK, len(obj._parameter_symbols), len(expr_bytes) ) file_obj.write(param_expr_header_raw) file_obj.write(expr_bytes) for symbol, value in obj._parameter_symbols.items(): symbol_key = type_keys.Value.assign(symbol) # serialize key if symbol_key == type_keys.Value.PARAMETER_VECTOR: symbol_data = common.data_to_binary(symbol, _write_parameter_vec) else: symbol_data = common.data_to_binary(symbol, _write_parameter) # serialize value if value == symbol._symbol_expr: value_key = symbol_key value_data = bytes() else: value_key, value_data = dumps_value(value, version=version, use_symengine=use_symengine) elem_header = struct.pack( formats.PARAM_EXPR_MAP_ELEM_V3_PACK, symbol_key, value_key, len(value_data), ) file_obj.write(elem_header) file_obj.write(symbol_data) file_obj.write(value_data) class _ExprWriter(expr.ExprVisitor[None]): __slots__ = ("file_obj", "clbit_indices", "standalone_var_indices", "version") def __init__(self, file_obj, clbit_indices, standalone_var_indices, version): self.file_obj = file_obj self.clbit_indices = clbit_indices self.standalone_var_indices = standalone_var_indices self.version = version def visit_generic(self, node, /): raise exceptions.QpyError(f"unhandled Expr object '{node}'") def visit_var(self, node, /): self.file_obj.write(type_keys.Expression.VAR) _write_expr_type(self.file_obj, node.type) if node.standalone: self.file_obj.write(type_keys.ExprVar.UUID) self.file_obj.write( struct.pack( formats.EXPR_VAR_UUID_PACK, *formats.EXPR_VAR_UUID(self.standalone_var_indices[node]), ) ) elif isinstance(node.var, Clbit): self.file_obj.write(type_keys.ExprVar.CLBIT) self.file_obj.write( struct.pack( formats.EXPR_VAR_CLBIT_PACK, *formats.EXPR_VAR_CLBIT(self.clbit_indices[node.var]), ) ) elif isinstance(node.var, ClassicalRegister): self.file_obj.write(type_keys.ExprVar.REGISTER) self.file_obj.write( struct.pack( formats.EXPR_VAR_REGISTER_PACK, *formats.EXPR_VAR_REGISTER(len(node.var.name)) ) ) self.file_obj.write(node.var.name.encode(common.ENCODE)) else: raise exceptions.QpyError(f"unhandled Var object '{node.var}'") def visit_value(self, node, /): self.file_obj.write(type_keys.Expression.VALUE) _write_expr_type(self.file_obj, node.type) if node.value is True or node.value is False: self.file_obj.write(type_keys.ExprValue.BOOL) self.file_obj.write( struct.pack(formats.EXPR_VALUE_BOOL_PACK, *formats.EXPR_VALUE_BOOL(node.value)) ) elif isinstance(node.value, int): self.file_obj.write(type_keys.ExprValue.INT) if node.value == 0: num_bytes = 0 buffer = b"" else: # This wastes a byte for `-(2 ** (8*n - 1))` for natural `n`, but they'll still # decode fine so it's not worth another special case. They'll encode to # b"\xff\x80\x00\x00...", but we could encode them to b"\x80\x00\x00...". num_bytes = (node.value.bit_length() // 8) + 1 buffer = node.value.to_bytes(num_bytes, "big", signed=True) self.file_obj.write( struct.pack(formats.EXPR_VALUE_INT_PACK, *formats.EXPR_VALUE_INT(num_bytes)) ) self.file_obj.write(buffer) else: raise exceptions.QpyError(f"unhandled Value object '{node.value}'") def visit_cast(self, node, /): self.file_obj.write(type_keys.Expression.CAST) _write_expr_type(self.file_obj, node.type) self.file_obj.write( struct.pack(formats.EXPRESSION_CAST_PACK, *formats.EXPRESSION_CAST(node.implicit)) ) node.operand.accept(self) def visit_unary(self, node, /): self.file_obj.write(type_keys.Expression.UNARY) _write_expr_type(self.file_obj, node.type) self.file_obj.write( struct.pack(formats.EXPRESSION_UNARY_PACK, *formats.EXPRESSION_UNARY(node.op.value)) ) node.operand.accept(self) def visit_binary(self, node, /): self.file_obj.write(type_keys.Expression.BINARY) _write_expr_type(self.file_obj, node.type) self.file_obj.write( struct.pack(formats.EXPRESSION_BINARY_PACK, *formats.EXPRESSION_BINARY(node.op.value)) ) node.left.accept(self) node.right.accept(self) def visit_index(self, node, /): if self.version < 12: raise exceptions.UnsupportedFeatureForVersion( "the 'Index' expression", required=12, target=self.version ) self.file_obj.write(type_keys.Expression.INDEX) _write_expr_type(self.file_obj, node.type) node.target.accept(self) node.index.accept(self) def _write_expr( file_obj, node: expr.Expr, clbit_indices: collections.abc.Mapping[Clbit, int], standalone_var_indices: collections.abc.Mapping[expr.Var, int], version: int, ): node.accept(_ExprWriter(file_obj, clbit_indices, standalone_var_indices, version)) def _write_expr_type(file_obj, type_: types.Type): if type_.kind is types.Bool: file_obj.write(type_keys.ExprType.BOOL) elif type_.kind is types.Uint: file_obj.write(type_keys.ExprType.UINT) file_obj.write( struct.pack(formats.EXPR_TYPE_UINT_PACK, *formats.EXPR_TYPE_UINT(type_.width)) ) else: raise exceptions.QpyError(f"unhandled Type object '{type_};") def _read_parameter(file_obj): data = formats.PARAMETER( *struct.unpack(formats.PARAMETER_PACK, file_obj.read(formats.PARAMETER_SIZE)) ) param_uuid = uuid.UUID(bytes=data.uuid) name = file_obj.read(data.name_size).decode(common.ENCODE) return Parameter(name, uuid=param_uuid) def _read_parameter_vec(file_obj, vectors): data = formats.PARAMETER_VECTOR_ELEMENT( *struct.unpack( formats.PARAMETER_VECTOR_ELEMENT_PACK, file_obj.read(formats.PARAMETER_VECTOR_ELEMENT_SIZE), ), ) param_uuid = uuid.UUID(bytes=data.uuid) name = file_obj.read(data.vector_name_size).decode(common.ENCODE) if name not in vectors: vectors[name] = (ParameterVector(name, data.vector_size), set()) vector = vectors[name][0] if vector[data.index].uuid != param_uuid: vectors[name][1].add(data.index) vector._params[data.index] = ParameterVectorElement(vector, data.index, uuid=param_uuid) return vector[data.index] def _read_parameter_expression(file_obj): data = formats.PARAMETER_EXPR( *struct.unpack(formats.PARAMETER_EXPR_PACK, file_obj.read(formats.PARAMETER_EXPR_SIZE)) ) from sympy.parsing.sympy_parser import parse_expr expr_ = symengine.sympify(parse_expr(file_obj.read(data.expr_size).decode(common.ENCODE))) symbol_map = {} for _ in range(data.map_elements): elem_data = formats.PARAM_EXPR_MAP_ELEM( *struct.unpack( formats.PARAM_EXPR_MAP_ELEM_PACK, file_obj.read(formats.PARAM_EXPR_MAP_ELEM_SIZE), ) ) symbol = _read_parameter(file_obj) elem_key = type_keys.Value(elem_data.type) binary_data = file_obj.read(elem_data.size) if elem_key == type_keys.Value.INTEGER: value = struct.unpack("!q", binary_data) elif elem_key == type_keys.Value.FLOAT: value = struct.unpack("!d", binary_data) elif elem_key == type_keys.Value.COMPLEX: value = complex(*struct.unpack(formats.COMPLEX_PACK, binary_data)) elif elem_key == type_keys.Value.PARAMETER: value = symbol._symbol_expr elif elem_key == type_keys.Value.PARAMETER_EXPRESSION: value = common.data_from_binary(binary_data, _read_parameter_expression) else: raise exceptions.QpyError(f"Invalid parameter expression map type: {elem_key}") symbol_map[symbol] = value return ParameterExpression(symbol_map, expr_) def _read_parameter_expression_v3(file_obj, vectors, use_symengine): data = formats.PARAMETER_EXPR( *struct.unpack(formats.PARAMETER_EXPR_PACK, file_obj.read(formats.PARAMETER_EXPR_SIZE)) ) payload = file_obj.read(data.expr_size) if use_symengine: expr_ = load_basic(payload) else: from sympy.parsing.sympy_parser import parse_expr expr_ = symengine.sympify(parse_expr(payload.decode(common.ENCODE))) symbol_map = {} for _ in range(data.map_elements): elem_data = formats.PARAM_EXPR_MAP_ELEM_V3( *struct.unpack( formats.PARAM_EXPR_MAP_ELEM_V3_PACK, file_obj.read(formats.PARAM_EXPR_MAP_ELEM_V3_SIZE), ) ) symbol_key = type_keys.Value(elem_data.symbol_type) if symbol_key == type_keys.Value.PARAMETER: symbol = _read_parameter(file_obj) elif symbol_key == type_keys.Value.PARAMETER_VECTOR: symbol = _read_parameter_vec(file_obj, vectors) else: raise exceptions.QpyError(f"Invalid parameter expression map type: {symbol_key}") elem_key = type_keys.Value(elem_data.type) binary_data = file_obj.read(elem_data.size) if elem_key == type_keys.Value.INTEGER: value = struct.unpack("!q", binary_data) elif elem_key == type_keys.Value.FLOAT: value = struct.unpack("!d", binary_data) elif elem_key == type_keys.Value.COMPLEX: value = complex(*struct.unpack(formats.COMPLEX_PACK, binary_data)) elif elem_key in (type_keys.Value.PARAMETER, type_keys.Value.PARAMETER_VECTOR): value = symbol._symbol_expr elif elem_key == type_keys.Value.PARAMETER_EXPRESSION: value = common.data_from_binary( binary_data, _read_parameter_expression_v3, vectors=vectors, use_symengine=use_symengine, ) else: raise exceptions.QpyError(f"Invalid parameter expression map type: {elem_key}") symbol_map[symbol] = value return ParameterExpression(symbol_map, expr_) def _read_expr( file_obj, clbits: collections.abc.Sequence[Clbit], cregs: collections.abc.Mapping[str, ClassicalRegister], standalone_vars: collections.abc.Sequence[expr.Var], ) -> expr.Expr: # pylint: disable=too-many-return-statements type_key = file_obj.read(formats.EXPRESSION_DISCRIMINATOR_SIZE) type_ = _read_expr_type(file_obj) if type_key == type_keys.Expression.VAR: var_type_key = file_obj.read(formats.EXPR_VAR_DISCRIMINATOR_SIZE) if var_type_key == type_keys.ExprVar.UUID: payload = formats.EXPR_VAR_UUID._make( struct.unpack(formats.EXPR_VAR_UUID_PACK, file_obj.read(formats.EXPR_VAR_UUID_SIZE)) ) return standalone_vars[payload.var_index] if var_type_key == type_keys.ExprVar.CLBIT: payload = formats.EXPR_VAR_CLBIT._make( struct.unpack( formats.EXPR_VAR_CLBIT_PACK, file_obj.read(formats.EXPR_VAR_CLBIT_SIZE) ) ) return expr.Var(clbits[payload.index], type_) if var_type_key == type_keys.ExprVar.REGISTER: payload = formats.EXPR_VAR_REGISTER._make( struct.unpack( formats.EXPR_VAR_REGISTER_PACK, file_obj.read(formats.EXPR_VAR_REGISTER_SIZE) ) ) name = file_obj.read(payload.reg_name_size).decode(common.ENCODE) return expr.Var(cregs[name], type_) raise exceptions.QpyError("Invalid classical-expression Var key '{var_type_key}'") if type_key == type_keys.Expression.VALUE: value_type_key = file_obj.read(formats.EXPR_VALUE_DISCRIMINATOR_SIZE) if value_type_key == type_keys.ExprValue.BOOL: payload = formats.EXPR_VALUE_BOOL._make( struct.unpack( formats.EXPR_VALUE_BOOL_PACK, file_obj.read(formats.EXPR_VALUE_BOOL_SIZE) ) ) return expr.Value(payload.value, type_) if value_type_key == type_keys.ExprValue.INT: payload = formats.EXPR_VALUE_INT._make( struct.unpack( formats.EXPR_VALUE_INT_PACK, file_obj.read(formats.EXPR_VALUE_INT_SIZE) ) ) return expr.Value( int.from_bytes(file_obj.read(payload.num_bytes), "big", signed=True), type_ ) raise exceptions.QpyError("Invalid classical-expression Value key '{value_type_key}'") if type_key == type_keys.Expression.CAST: payload = formats.EXPRESSION_CAST._make( struct.unpack(formats.EXPRESSION_CAST_PACK, file_obj.read(formats.EXPRESSION_CAST_SIZE)) ) return expr.Cast( _read_expr(file_obj, clbits, cregs, standalone_vars), type_, implicit=payload.implicit ) if type_key == type_keys.Expression.UNARY: payload = formats.EXPRESSION_UNARY._make( struct.unpack( formats.EXPRESSION_UNARY_PACK, file_obj.read(formats.EXPRESSION_UNARY_SIZE) ) ) return expr.Unary( expr.Unary.Op(payload.opcode), _read_expr(file_obj, clbits, cregs, standalone_vars), type_, ) if type_key == type_keys.Expression.BINARY: payload = formats.EXPRESSION_BINARY._make( struct.unpack( formats.EXPRESSION_BINARY_PACK, file_obj.read(formats.EXPRESSION_BINARY_SIZE) ) ) return expr.Binary( expr.Binary.Op(payload.opcode), _read_expr(file_obj, clbits, cregs, standalone_vars), _read_expr(file_obj, clbits, cregs, standalone_vars), type_, ) if type_key == type_keys.Expression.INDEX: return expr.Index( _read_expr(file_obj, clbits, cregs, standalone_vars), _read_expr(file_obj, clbits, cregs, standalone_vars), type_, ) raise exceptions.QpyError(f"Invalid classical-expression Expr key '{type_key}'") def _read_expr_type(file_obj) -> types.Type: type_key = file_obj.read(formats.EXPR_TYPE_DISCRIMINATOR_SIZE) if type_key == type_keys.ExprType.BOOL: return types.Bool() if type_key == type_keys.ExprType.UINT: elem = formats.EXPR_TYPE_UINT._make( struct.unpack(formats.EXPR_TYPE_UINT_PACK, file_obj.read(formats.EXPR_TYPE_UINT_SIZE)) ) return types.Uint(elem.width) raise exceptions.QpyError(f"Invalid classical-expression Type key '{type_key}'") def read_standalone_vars(file_obj, num_vars): """Read the ``num_vars`` standalone variable declarations from the file. Args: file_obj (File): a file-like object to read from. num_vars (int): the number of variables to read. Returns: tuple[dict, list]: the first item is a mapping of the ``ExprVarDeclaration`` type keys to the variables defined by that type key, and the second is the total order of variable declarations. """ read_vars = { type_keys.ExprVarDeclaration.INPUT: [], type_keys.ExprVarDeclaration.CAPTURE: [], type_keys.ExprVarDeclaration.LOCAL: [], } var_order = [] for _ in range(num_vars): data = formats.EXPR_VAR_DECLARATION._make( struct.unpack( formats.EXPR_VAR_DECLARATION_PACK, file_obj.read(formats.EXPR_VAR_DECLARATION_SIZE), ) ) type_ = _read_expr_type(file_obj) name = file_obj.read(data.name_size).decode(common.ENCODE) var = expr.Var(uuid.UUID(bytes=data.uuid_bytes), type_, name=name) read_vars[data.usage].append(var) var_order.append(var) return read_vars, var_order def _write_standalone_var(file_obj, var, type_key): name = var.name.encode(common.ENCODE) file_obj.write( struct.pack( formats.EXPR_VAR_DECLARATION_PACK, *formats.EXPR_VAR_DECLARATION(var.var.bytes, type_key, len(name)), ) ) _write_expr_type(file_obj, var.type) file_obj.write(name) def write_standalone_vars(file_obj, circuit): """Write the standalone variables out from a circuit. Args: file_obj (File): the file-like object to write to. circuit (QuantumCircuit): the circuit to take the variables from. Returns: dict[expr.Var, int]: a mapping of the variables written to the index that they were written at. """ index = 0 out = {} for var in circuit.iter_input_vars(): _write_standalone_var(file_obj, var, type_keys.ExprVarDeclaration.INPUT) out[var] = index index += 1 for var in circuit.iter_captured_vars(): _write_standalone_var(file_obj, var, type_keys.ExprVarDeclaration.CAPTURE) out[var] = index index += 1 for var in circuit.iter_declared_vars(): _write_standalone_var(file_obj, var, type_keys.ExprVarDeclaration.LOCAL) out[var] = index index += 1 return out def dumps_value( obj, *, version, index_map=None, use_symengine=False, standalone_var_indices=None, ): """Serialize input value object. Args: obj (any): Arbitrary value object to serialize. version (int): the target QPY version for the dump. index_map (dict): Dictionary with two keys, "q" and "c". Each key has a value that is a dictionary mapping :class:`.Qubit` or :class:`.Clbit` instances (respectively) to their integer indices. use_symengine (bool): If True, symbolic objects will be serialized using symengine's native mechanism. This is a faster serialization alternative, but not supported in all platforms. Please check that your target platform is supported by the symengine library before setting this option, as it will be required by qpy to deserialize the payload. standalone_var_indices (dict): Dictionary that maps standalone :class:`.expr.Var` entries to the index that should be used to refer to them. Returns: tuple: TypeKey and binary data. Raises: QpyError: Serializer for given format is not ready. """ type_key = type_keys.Value.assign(obj) if type_key == type_keys.Value.INTEGER: binary_data = struct.pack("!q", obj) elif type_key == type_keys.Value.FLOAT: binary_data = struct.pack("!d", obj) elif type_key == type_keys.Value.COMPLEX: binary_data = struct.pack(formats.COMPLEX_PACK, obj.real, obj.imag) elif type_key == type_keys.Value.NUMPY_OBJ: binary_data = common.data_to_binary(obj, np.save) elif type_key == type_keys.Value.STRING: binary_data = obj.encode(common.ENCODE) elif type_key in (type_keys.Value.NULL, type_keys.Value.CASE_DEFAULT): binary_data = b"" elif type_key == type_keys.Value.PARAMETER_VECTOR: binary_data = common.data_to_binary(obj, _write_parameter_vec) elif type_key == type_keys.Value.PARAMETER: binary_data = common.data_to_binary(obj, _write_parameter) elif type_key == type_keys.Value.PARAMETER_EXPRESSION: binary_data = common.data_to_binary( obj, _write_parameter_expression, use_symengine=use_symengine, version=version ) elif type_key == type_keys.Value.EXPRESSION: clbit_indices = {} if index_map is None else index_map["c"] standalone_var_indices = {} if standalone_var_indices is None else standalone_var_indices binary_data = common.data_to_binary( obj, _write_expr, clbit_indices=clbit_indices, standalone_var_indices=standalone_var_indices, version=version, ) else: raise exceptions.QpyError(f"Serialization for {type_key} is not implemented in value I/O.") return type_key, binary_data def write_value( file_obj, obj, *, version, index_map=None, use_symengine=False, standalone_var_indices=None ): """Write a value to the file like object. Args: file_obj (File): A file like object to write data. obj (any): Value to write. version (int): the target QPY version for the dump. index_map (dict): Dictionary with two keys, "q" and "c". Each key has a value that is a dictionary mapping :class:`.Qubit` or :class:`.Clbit` instances (respectively) to their integer indices. use_symengine (bool): If True, symbolic objects will be serialized using symengine's native mechanism. This is a faster serialization alternative, but not supported in all platforms. Please check that your target platform is supported by the symengine library before setting this option, as it will be required by qpy to deserialize the payload. standalone_var_indices (dict): Dictionary that maps standalone :class:`.expr.Var` entries to the index that should be used to refer to them. """ type_key, data = dumps_value( obj, version=version, index_map=index_map, use_symengine=use_symengine, standalone_var_indices=standalone_var_indices, ) common.write_generic_typed_data(file_obj, type_key, data) def loads_value( type_key, binary_data, version, vectors, *, clbits=(), cregs=None, use_symengine=False, standalone_vars=(), ): """Deserialize input binary data to value object. Args: type_key (ValueTypeKey): Type enum information. binary_data (bytes): Data to deserialize. version (int): QPY version. vectors (dict): ParameterVector in current scope. clbits (Sequence[Clbit]): Clbits in the current scope. cregs (Mapping[str, ClassicalRegister]): Classical registers in the current scope. use_symengine (bool): If True, symbolic objects will be de-serialized using symengine's native mechanism. This is a faster serialization alternative, but not supported in all platforms. Please check that your target platform is supported by the symengine library before setting this option, as it will be required by qpy to deserialize the payload. standalone_vars (Sequence[Var]): standalone :class:`.expr.Var` nodes in the order that they were declared by the circuit header. Returns: any: Deserialized value object. Raises: QpyError: Serializer for given format is not ready. """ # pylint: disable=too-many-return-statements if isinstance(type_key, bytes): type_key = type_keys.Value(type_key) if type_key == type_keys.Value.INTEGER: return struct.unpack("!q", binary_data)[0] if type_key == type_keys.Value.FLOAT: return struct.unpack("!d", binary_data)[0] if type_key == type_keys.Value.COMPLEX: return complex(*struct.unpack(formats.COMPLEX_PACK, binary_data)) if type_key == type_keys.Value.NUMPY_OBJ: return common.data_from_binary(binary_data, np.load) if type_key == type_keys.Value.STRING: return binary_data.decode(common.ENCODE) if type_key == type_keys.Value.NULL: return None if type_key == type_keys.Value.CASE_DEFAULT: return CASE_DEFAULT if type_key == type_keys.Value.PARAMETER_VECTOR: return common.data_from_binary(binary_data, _read_parameter_vec, vectors=vectors) if type_key == type_keys.Value.PARAMETER: return common.data_from_binary(binary_data, _read_parameter) if type_key == type_keys.Value.PARAMETER_EXPRESSION: if version < 3: return common.data_from_binary(binary_data, _read_parameter_expression) else: return common.data_from_binary( binary_data, _read_parameter_expression_v3, vectors=vectors, use_symengine=use_symengine, ) if type_key == type_keys.Value.EXPRESSION: return common.data_from_binary( binary_data, _read_expr, clbits=clbits, cregs=cregs or {}, standalone_vars=standalone_vars, ) raise exceptions.QpyError(f"Serialization for {type_key} is not implemented in value I/O.") def read_value( file_obj, version, vectors, *, clbits=(), cregs=None, use_symengine=False, standalone_vars=(), ): """Read a value from the file like object. Args: file_obj (File): A file like object to write data. version (int): QPY version. vectors (dict): ParameterVector in current scope. clbits (Sequence[Clbit]): Clbits in the current scope. cregs (Mapping[str, ClassicalRegister]): Classical registers in the current scope. use_symengine (bool): If True, symbolic objects will be de-serialized using symengine's native mechanism. This is a faster serialization alternative, but not supported in all platforms. Please check that your target platform is supported by the symengine library before setting this option, as it will be required by qpy to deserialize the payload. standalone_vars (Sequence[expr.Var]): standalone variables in the order they were defined in the QPY payload. Returns: any: Deserialized value object. """ type_key, data = common.read_generic_typed_data(file_obj) return loads_value( type_key, data, version, vectors, clbits=clbits, cregs=cregs, use_symengine=use_symengine, standalone_vars=standalone_vars, )
qiskit/qiskit/qpy/binary_io/value.py/0
{ "file_path": "qiskit/qiskit/qpy/binary_io/value.py", "repo_id": "qiskit", "token_count": 12950 }
192
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 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. """ Choi-matrix representation of a Quantum Channel. """ from __future__ import annotations import copy as _copy import math import numpy as np from qiskit import _numpy_compat from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.instruction import Instruction from qiskit.exceptions import QiskitError from qiskit.quantum_info.operators.channel.quantum_channel import QuantumChannel from qiskit.quantum_info.operators.op_shape import OpShape from qiskit.quantum_info.operators.channel.superop import SuperOp from qiskit.quantum_info.operators.channel.transformations import _to_choi from qiskit.quantum_info.operators.channel.transformations import _bipartite_tensor from qiskit.quantum_info.operators.mixins import generate_apidocs from qiskit.quantum_info.operators.base_operator import BaseOperator class Choi(QuantumChannel): r"""Choi-matrix representation of a Quantum Channel. The Choi-matrix representation of a quantum channel :math:`\mathcal{E}` is a matrix .. math:: \Lambda = \sum_{i,j} |i\rangle\!\langle j|\otimes \mathcal{E}\left(|i\rangle\!\langle j|\right) Evolution of a :class:`~qiskit.quantum_info.DensityMatrix` :math:`\rho` with respect to the Choi-matrix is given by .. math:: \mathcal{E}(\rho) = \mbox{Tr}_{1}\left[\Lambda (\rho^T \otimes \mathbb{I})\right] where :math:`\mbox{Tr}_1` is the :func:`partial_trace` over subsystem 1. See reference [1] for further details. References: 1. C.J. Wood, J.D. Biamonte, D.G. Cory, *Tensor networks and graphical calculus for open quantum systems*, Quant. Inf. Comp. 15, 0579-0811 (2015). `arXiv:1111.6950 [quant-ph] <https://arxiv.org/abs/1111.6950>`_ """ def __init__( self, data: QuantumCircuit | Instruction | BaseOperator | np.ndarray, input_dims: int | tuple | None = None, output_dims: int | tuple | None = None, ): """Initialize a quantum channel Choi matrix operator. Args: data (QuantumCircuit or Instruction or BaseOperator or matrix): data to initialize superoperator. input_dims (tuple): the input subsystem dimensions. [Default: None] output_dims (tuple): the output subsystem dimensions. [Default: None] Raises: QiskitError: if input data cannot be initialized as a Choi matrix. Additional Information: If the input or output dimensions are None, they will be automatically determined from the input data. If the input data is a Numpy array of shape (4**N, 4**N) qubit systems will be used. If the input operator is not an N-qubit operator, it will assign a single subsystem with dimension specified by the shape of the input. """ # If the input is a raw list or matrix we assume that it is # already a Choi matrix. if isinstance(data, (list, np.ndarray)): # Initialize from raw numpy or list matrix. choi_mat = np.asarray(data, dtype=complex) # Determine input and output dimensions dim_l, dim_r = choi_mat.shape if dim_l != dim_r: raise QiskitError("Invalid Choi-matrix input.") if input_dims: input_dim = np.prod(input_dims) if output_dims: output_dim = np.prod(output_dims) if output_dims is None and input_dims is None: output_dim = int(math.sqrt(dim_l)) input_dim = dim_l // output_dim elif input_dims is None: input_dim = dim_l // output_dim elif output_dims is None: output_dim = dim_l // input_dim # Check dimensions if input_dim * output_dim != dim_l: raise QiskitError("Invalid shape for input Choi-matrix.") op_shape = OpShape.auto( dims_l=output_dims, dims_r=input_dims, shape=(output_dim, input_dim) ) else: # Otherwise we initialize by conversion from another Qiskit # object into the QuantumChannel. if isinstance(data, (QuantumCircuit, Instruction)): # If the input is a Terra QuantumCircuit or Instruction we # convert it to a SuperOp data = SuperOp._init_instruction(data) else: # We use the QuantumChannel init transform to initialize # other objects into a QuantumChannel or Operator object. data = self._init_transformer(data) op_shape = data._op_shape output_dim, input_dim = op_shape.shape # Now that the input is an operator we convert it to a Choi object rep = getattr(data, "_channel_rep", "Operator") choi_mat = _to_choi(rep, data._data, input_dim, output_dim) super().__init__(choi_mat, op_shape=op_shape) def __array__(self, dtype=None, copy=_numpy_compat.COPY_ONLY_IF_NEEDED): dtype = self.data.dtype if dtype is None else dtype return np.array(self.data, dtype=dtype, copy=copy) @property def _bipartite_shape(self): """Return the shape for bipartite matrix""" return (self._input_dim, self._output_dim, self._input_dim, self._output_dim) def _evolve(self, state, qargs=None): return SuperOp(self)._evolve(state, qargs) # --------------------------------------------------------------------- # BaseOperator methods # --------------------------------------------------------------------- def conjugate(self): ret = _copy.copy(self) ret._data = np.conj(self._data) return ret def transpose(self): ret = _copy.copy(self) ret._op_shape = self._op_shape.transpose() # Make bipartite matrix d_in, d_out = self.dim data = np.reshape(self._data, (d_in, d_out, d_in, d_out)) # Swap input and output indices on bipartite matrix data = np.transpose(data, (1, 0, 3, 2)) ret._data = np.reshape(data, (d_in * d_out, d_in * d_out)) return ret def compose(self, other: Choi, qargs: list | None = None, front: bool = False) -> Choi: if qargs is None: qargs = getattr(other, "qargs", None) if qargs is not None: return Choi(SuperOp(self).compose(other, qargs=qargs, front=front)) if not isinstance(other, Choi): other = Choi(other) new_shape = self._op_shape.compose(other._op_shape, qargs, front) output_dim, input_dim = new_shape.shape if front: first = np.reshape(other._data, other._bipartite_shape) second = np.reshape(self._data, self._bipartite_shape) else: first = np.reshape(self._data, self._bipartite_shape) second = np.reshape(other._data, other._bipartite_shape) # Contract Choi matrices for composition data = np.reshape( np.einsum("iAjB,AkBl->ikjl", first, second), (input_dim * output_dim, input_dim * output_dim), ) ret = Choi(data) ret._op_shape = new_shape return ret def tensor(self, other: Choi) -> Choi: if not isinstance(other, Choi): other = Choi(other) return self._tensor(self, other) def expand(self, other: Choi) -> Choi: if not isinstance(other, Choi): other = Choi(other) return self._tensor(other, self) @classmethod def _tensor(cls, a, b): ret = _copy.copy(a) ret._op_shape = a._op_shape.tensor(b._op_shape) ret._data = _bipartite_tensor( a._data, b.data, shape1=a._bipartite_shape, shape2=b._bipartite_shape ) return ret # Update docstrings for API docs generate_apidocs(Choi)
qiskit/qiskit/quantum_info/operators/channel/choi.py/0
{ "file_path": "qiskit/qiskit/quantum_info/operators/channel/choi.py", "repo_id": "qiskit", "token_count": 3743 }
193
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 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. """ Mixin for gate operator interface. """ import sys from abc import ABC, abstractmethod if sys.version_info >= (3, 11): from typing import Self else: from typing_extensions import Self class AdjointMixin(ABC): """Abstract Mixin for operator adjoint and transpose operations. This class defines the following methods - :meth:`transpose` - :meth:`conjugate` - :meth:`adjoint` The following abstract methods must be implemented by subclasses using this mixin - ``conjugate(self)`` - ``transpose(self)`` """ def adjoint(self) -> Self: """Return the adjoint of the CLASS.""" return self.conjugate().transpose() @abstractmethod def conjugate(self) -> Self: """Return the conjugate of the CLASS.""" @abstractmethod def transpose(self) -> Self: """Return the transpose of the CLASS."""
qiskit/qiskit/quantum_info/operators/mixins/adjoint.py/0
{ "file_path": "qiskit/qiskit/quantum_info/operators/mixins/adjoint.py", "repo_id": "qiskit", "token_count": 471 }
194
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2022 # # 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. """ Optimized list of Pauli operators """ from __future__ import annotations from collections import defaultdict from typing import Literal import numpy as np import rustworkx as rx from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.exceptions import QiskitError from qiskit.quantum_info.operators.custom_iterator import CustomIterator from qiskit.quantum_info.operators.mixins import GroupMixin, LinearMixin from qiskit.quantum_info.operators.symplectic.base_pauli import BasePauli from qiskit.quantum_info.operators.symplectic.clifford import Clifford from qiskit.quantum_info.operators.symplectic.pauli import Pauli class PauliList(BasePauli, LinearMixin, GroupMixin): r"""List of N-qubit Pauli operators. This class is an efficient representation of a list of :class:`Pauli` operators. It supports 1D numpy array indexing returning a :class:`Pauli` for integer indexes or a :class:`PauliList` for slice or list indices. **Initialization** A PauliList object can be initialized in several ways. ``PauliList(list[str])`` where strings are same representation with :class:`~qiskit.quantum_info.Pauli`. ``PauliList(Pauli) and PauliList(list[Pauli])`` where Pauli is :class:`~qiskit.quantum_info.Pauli`. ``PauliList.from_symplectic(z, x, phase)`` where ``z`` and ``x`` are 2 dimensional boolean ``numpy.ndarrays`` and ``phase`` is an integer in ``[0, 1, 2, 3]``. For example, .. code-block:: import numpy as np from qiskit.quantum_info import Pauli, PauliList # 1. init from list[str] pauli_list = PauliList(["II", "+ZI", "-iYY"]) print("1. ", pauli_list) pauli1 = Pauli("iXI") pauli2 = Pauli("iZZ") # 2. init from Pauli print("2. ", PauliList(pauli1)) # 3. init from list[Pauli] print("3. ", PauliList([pauli1, pauli2])) # 4. init from np.ndarray z = np.array([[True, True], [False, False]]) x = np.array([[False, True], [True, False]]) phase = np.array([0, 1]) pauli_list = PauliList.from_symplectic(z, x, phase) print("4. ", pauli_list) .. parsed-literal:: 1. ['II', 'ZI', '-iYY'] 2. ['iXI'] 3. ['iXI', 'iZZ'] 4. ['YZ', '-iIX'] **Data Access** The individual Paulis can be accessed and updated using the ``[]`` operator which accepts integer, lists, or slices for selecting subsets of PauliList. If integer is given, it returns Pauli not PauliList. .. code-block:: pauli_list = PauliList(["XX", "ZZ", "IZ"]) print("Integer: ", repr(pauli_list[1])) print("List: ", repr(pauli_list[[0, 2]])) print("Slice: ", repr(pauli_list[0:2])) .. parsed-literal:: Integer: Pauli('ZZ') List: PauliList(['XX', 'IZ']) Slice: PauliList(['XX', 'ZZ']) **Iteration** Rows in the Pauli table can be iterated over like a list. Iteration can also be done using the label or matrix representation of each row using the :meth:`label_iter` and :meth:`matrix_iter` methods. """ # Set the max number of qubits * paulis before string truncation __truncate__ = 2000 def __init__(self, data: Pauli | list): """Initialize the PauliList. Args: data (Pauli or list): input data for Paulis. If input is a list each item in the list must be a Pauli object or Pauli str. Raises: QiskitError: if input array is invalid shape. Additional Information: The input array is not copied so multiple Pauli tables can share the same underlying array. """ if isinstance(data, BasePauli): base_z, base_x, base_phase = data._z, data._x, data._phase else: # Conversion as iterable of Paulis base_z, base_x, base_phase = self._from_paulis(data) # Initialize BasePauli super().__init__(base_z, base_x, base_phase) # --------------------------------------------------------------------- # Representation conversions # --------------------------------------------------------------------- @property def settings(self): """Return settings.""" return {"data": self.to_labels()} def __array__(self, dtype=None, copy=None): """Convert to numpy array""" if copy is False: raise ValueError("cannot provide a matrix without calculation") shape = (len(self),) + 2 * (2**self.num_qubits,) ret = np.zeros(shape, dtype=complex) for i, mat in enumerate(self.matrix_iter()): ret[i] = mat return ret if dtype is None else ret.astype(dtype, copy=False) @staticmethod def _from_paulis(data): """Construct a PauliList from a list of Pauli data. Args: data (iterable): list of Pauli data. Returns: PauliList: the constructed PauliList. Raises: QiskitError: If the input list is empty or contains invalid Pauli strings. """ if not isinstance(data, (list, tuple, set, np.ndarray)): data = [data] num_paulis = len(data) if num_paulis == 0: raise QiskitError("Input Pauli list is empty.") paulis = [] for i in data: if not isinstance(i, Pauli): paulis.append(Pauli(i)) else: paulis.append(i) num_qubits = paulis[0].num_qubits base_z = np.zeros((num_paulis, num_qubits), dtype=bool) base_x = np.zeros((num_paulis, num_qubits), dtype=bool) base_phase = np.zeros(num_paulis, dtype=int) for i, pauli in enumerate(paulis): if pauli.num_qubits != num_qubits: raise ValueError( f"The {i}th Pauli is defined over {pauli.num_qubits} qubits, " f"but num_qubits == {num_qubits} was expected." ) base_z[i] = pauli._z base_x[i] = pauli._x base_phase[i] = pauli._phase.item() return base_z, base_x, base_phase def __repr__(self): """Display representation.""" return self._truncated_str(True) def __str__(self): """Print representation.""" return self._truncated_str(False) def _truncated_str(self, show_class): stop = self._num_paulis if self.__truncate__ and self.num_qubits > 0: max_paulis = self.__truncate__ // self.num_qubits if self._num_paulis > max_paulis: stop = max_paulis labels = [str(self[i]) for i in range(stop)] prefix = "PauliList(" if show_class else "" tail = ")" if show_class else "" if stop != self._num_paulis: suffix = ", ...]" + tail else: suffix = "]" + tail list_str = np.array2string( np.array(labels), threshold=stop + 1, separator=", ", prefix=prefix, suffix=suffix ) return prefix + list_str[:-1] + suffix def __eq__(self, other): """Entrywise comparison of Pauli equality.""" if not isinstance(other, PauliList): other = PauliList(other) if not isinstance(other, BasePauli): return False return self._eq(other) def equiv(self, other: PauliList | Pauli) -> np.ndarray: """Entrywise comparison of Pauli equivalence up to global phase. Args: other (PauliList or Pauli): a comparison object. Returns: np.ndarray: An array of ``True`` or ``False`` for entrywise equivalence of the current table. """ if not isinstance(other, PauliList): other = PauliList(other) return np.all(self.z == other.z, axis=1) & np.all(self.x == other.x, axis=1) # --------------------------------------------------------------------- # Direct array access # --------------------------------------------------------------------- @property def phase(self): """Return the phase exponent of the PauliList.""" # Convert internal ZX-phase convention to group phase convention return np.mod(self._phase - self._count_y(dtype=self._phase.dtype), 4) @phase.setter def phase(self, value): # Convert group phase convetion to internal ZX-phase convention self._phase[:] = np.mod(value + self._count_y(dtype=self._phase.dtype), 4) @property def x(self): """The x array for the symplectic representation.""" return self._x @x.setter def x(self, val): self._x[:] = val @property def z(self): """The z array for the symplectic representation.""" return self._z @z.setter def z(self, val): self._z[:] = val # --------------------------------------------------------------------- # Size Properties # --------------------------------------------------------------------- @property def shape(self): """The full shape of the :meth:`array`""" return self._num_paulis, self.num_qubits @property def size(self): """The number of Pauli rows in the table.""" return self._num_paulis def __len__(self): """Return the number of Pauli rows in the table.""" return self._num_paulis # --------------------------------------------------------------------- # Pauli Array methods # --------------------------------------------------------------------- def __getitem__(self, index): """Return a view of the PauliList.""" # Returns a view of specified rows of the PauliList # This supports all slicing operations the underlying array supports. if isinstance(index, tuple): if len(index) == 1: index = index[0] elif len(index) > 2: raise IndexError(f"Invalid PauliList index {index}") # Row-only indexing if isinstance(index, (int, np.integer)): # Single Pauli return Pauli( BasePauli( self._z[np.newaxis, index], self._x[np.newaxis, index], self._phase[np.newaxis, index], ) ) elif isinstance(index, (slice, list, np.ndarray)): # Sub-Table view return PauliList(BasePauli(self._z[index], self._x[index], self._phase[index])) # Row and Qubit indexing return PauliList((self._z[index], self._x[index], 0)) def __setitem__(self, index, value): """Update PauliList.""" if isinstance(index, tuple): if len(index) == 1: row, qubit = index[0], None elif len(index) > 2: raise IndexError(f"Invalid PauliList index {index}") else: row, qubit = index else: row, qubit = index, None # Modify specified rows of the PauliList if not isinstance(value, PauliList): value = PauliList(value) # It's not valid to set a single item with a sequence, even if the sequence is length 1. phase = value._phase.item() if isinstance(row, (int, np.integer)) else value._phase if qubit is None: self._z[row] = value._z self._x[row] = value._x self._phase[row] = phase else: self._z[row, qubit] = value._z self._x[row, qubit] = value._x self._phase[row] += phase self._phase %= 4 def delete(self, ind: int | list, qubit: bool = False) -> PauliList: """Return a copy with Pauli rows deleted from table. When deleting qubits the qubit index is the same as the column index of the underlying :attr:`X` and :attr:`Z` arrays. Args: ind (int or list): index(es) to delete. qubit (bool): if ``True`` delete qubit columns, otherwise delete Pauli rows (Default: ``False``). Returns: PauliList: the resulting table with the entries removed. Raises: QiskitError: if ``ind`` is out of bounds for the array size or number of qubits. """ if isinstance(ind, int): ind = [ind] if len(ind) == 0: return PauliList.from_symplectic(self._z, self._x, self.phase) # Row deletion if not qubit: if max(ind) >= len(self): raise QiskitError( f"Indices {ind} are not all less than the size" f" of the PauliList ({len(self)})" ) z = np.delete(self._z, ind, axis=0) x = np.delete(self._x, ind, axis=0) phase = np.delete(self._phase, ind) return PauliList(BasePauli(z, x, phase)) # Column (qubit) deletion if max(ind) >= self.num_qubits: raise QiskitError( f"Indices {ind} are not all less than the number of" f" qubits in the PauliList ({self.num_qubits})" ) z = np.delete(self._z, ind, axis=1) x = np.delete(self._x, ind, axis=1) # Use self.phase, not self._phase as deleting qubits can change the # ZX phase convention return PauliList.from_symplectic(z, x, self.phase) def insert(self, ind: int, value: PauliList, qubit: bool = False) -> PauliList: """Insert Paulis into the table. When inserting qubits the qubit index is the same as the column index of the underlying :attr:`X` and :attr:`Z` arrays. Args: ind (int): index to insert at. value (PauliList): values to insert. qubit (bool): if ``True`` insert qubit columns, otherwise insert Pauli rows (Default: ``False``). Returns: PauliList: the resulting table with the entries inserted. Raises: QiskitError: if the insertion index is invalid. """ if not isinstance(ind, int): raise QiskitError("Insert index must be an integer.") if not isinstance(value, PauliList): value = PauliList(value) # Row insertion size = self._num_paulis if not qubit: if ind > size: raise QiskitError( f"Index {ind} is larger than the number of rows in the" f" PauliList ({size})." ) base_z = np.insert(self._z, ind, value._z, axis=0) base_x = np.insert(self._x, ind, value._x, axis=0) base_phase = np.insert(self._phase, ind, value._phase) return PauliList(BasePauli(base_z, base_x, base_phase)) # Column insertion if ind > self.num_qubits: raise QiskitError( f"Index {ind} is greater than number of qubits" f" in the PauliList ({self.num_qubits})" ) if len(value) == 1: # Pad blocks to correct size value_x = np.vstack(size * [value.x]) value_z = np.vstack(size * [value.z]) value_phase = np.vstack(size * [value.phase]) elif len(value) == size: # Blocks are already correct size value_x = value.x value_z = value.z value_phase = value.phase else: # Blocks are incorrect size raise QiskitError( "Input PauliList must have a single row, or" " the same number of rows as the Pauli Table" f" ({size})." ) # Build new array by blocks z = np.hstack([self.z[:, :ind], value_z, self.z[:, ind:]]) x = np.hstack([self.x[:, :ind], value_x, self.x[:, ind:]]) phase = self.phase + value_phase return PauliList.from_symplectic(z, x, phase) def argsort(self, weight: bool = False, phase: bool = False) -> np.ndarray: """Return indices for sorting the rows of the table. The default sort method is lexicographic sorting by qubit number. By using the `weight` kwarg the output can additionally be sorted by the number of non-identity terms in the Pauli, where the set of all Paulis of a given weight are still ordered lexicographically. Args: weight (bool): Optionally sort by weight if ``True`` (Default: ``False``). phase (bool): Optionally sort by phase before weight or order (Default: ``False``). Returns: array: the indices for sorting the table. """ # Get order of each Pauli using # I => 0, X => 1, Y => 2, Z => 3 x = self.x z = self.z order = 1 * (x & ~z) + 2 * (x & z) + 3 * (~x & z) phases = self.phase # Optionally get the weight of Pauli # This is the number of non identity terms if weight: weights = np.sum(x | z, axis=1) # To preserve ordering between successive sorts we # are use the 'stable' sort method indices = np.arange(self._num_paulis) # Initial sort by phases sort_inds = phases.argsort(kind="stable") indices = indices[sort_inds] order = order[sort_inds] if phase: phases = phases[sort_inds] if weight: weights = weights[sort_inds] # Sort by order for i in range(self.num_qubits): sort_inds = order[:, i].argsort(kind="stable") order = order[sort_inds] indices = indices[sort_inds] if weight: weights = weights[sort_inds] if phase: phases = phases[sort_inds] # If using weights we implement a sort by total number # of non-identity Paulis if weight: sort_inds = weights.argsort(kind="stable") indices = indices[sort_inds] phases = phases[sort_inds] # If sorting by phase we perform a final sort by the phase value # of each pauli if phase: indices = indices[phases.argsort(kind="stable")] return indices def sort(self, weight: bool = False, phase: bool = False) -> PauliList: """Sort the rows of the table. The default sort method is lexicographic sorting by qubit number. By using the `weight` kwarg the output can additionally be sorted by the number of non-identity terms in the Pauli, where the set of all Paulis of a given weight are still ordered lexicographically. **Example** Consider sorting all a random ordering of all 2-qubit Paulis .. code-block:: from numpy.random import shuffle from qiskit.quantum_info.operators import PauliList # 2-qubit labels labels = ['II', 'IX', 'IY', 'IZ', 'XI', 'XX', 'XY', 'XZ', 'YI', 'YX', 'YY', 'YZ', 'ZI', 'ZX', 'ZY', 'ZZ'] # Shuffle Labels shuffle(labels) pt = PauliList(labels) print('Initial Ordering') print(pt) # Lexicographic Ordering srt = pt.sort() print('Lexicographically sorted') print(srt) # Weight Ordering srt = pt.sort(weight=True) print('Weight sorted') print(srt) .. parsed-literal:: Initial Ordering ['YX', 'ZZ', 'XZ', 'YI', 'YZ', 'II', 'XX', 'XI', 'XY', 'YY', 'IX', 'IZ', 'ZY', 'ZI', 'ZX', 'IY'] Lexicographically sorted ['II', 'IX', 'IY', 'IZ', 'XI', 'XX', 'XY', 'XZ', 'YI', 'YX', 'YY', 'YZ', 'ZI', 'ZX', 'ZY', 'ZZ'] Weight sorted ['II', 'IX', 'IY', 'IZ', 'XI', 'YI', 'ZI', 'XX', 'XY', 'XZ', 'YX', 'YY', 'YZ', 'ZX', 'ZY', 'ZZ'] Args: weight (bool): optionally sort by weight if ``True`` (Default: ``False``). phase (bool): Optionally sort by phase before weight or order (Default: ``False``). Returns: PauliList: a sorted copy of the original table. """ return self[self.argsort(weight=weight, phase=phase)] def unique(self, return_index: bool = False, return_counts: bool = False) -> PauliList: """Return unique Paulis from the table. **Example** .. code-block:: from qiskit.quantum_info.operators import PauliList pt = PauliList(['X', 'Y', '-X', 'I', 'I', 'Z', 'X', 'iZ']) unique = pt.unique() print(unique) .. parsed-literal:: ['X', 'Y', '-X', 'I', 'Z', 'iZ'] Args: return_index (bool): If ``True``, also return the indices that result in the unique array. (Default: ``False``) return_counts (bool): If ``True``, also return the number of times each unique item appears in the table. Returns: PauliList: unique the table of the unique rows. unique_indices: np.ndarray, optional The indices of the first occurrences of the unique values in the original array. Only provided if ``return_index`` is ``True``. unique_counts: np.array, optional The number of times each of the unique values comes up in the original array. Only provided if ``return_counts`` is ``True``. """ # Check if we need to stack the phase array if np.any(self._phase != self._phase[0]): # Create a single array of Pauli's and phases for calling np.unique on # so that we treat different phased Pauli's as unique array = np.hstack([self._z, self._x, self.phase.reshape((self.phase.shape[0], 1))]) else: # All Pauli's have the same phase so we only need to sort the array array = np.hstack([self._z, self._x]) # Get indexes of unique entries if return_counts: _, index, counts = np.unique(array, return_index=True, return_counts=True, axis=0) else: _, index = np.unique(array, return_index=True, axis=0) # Sort the index so we return unique rows in the original array order sort_inds = index.argsort() index = index[sort_inds] unique = PauliList(BasePauli(self._z[index], self._x[index], self._phase[index])) # Concatenate return tuples ret = (unique,) if return_index: ret += (index,) if return_counts: ret += (counts[sort_inds],) if len(ret) == 1: return ret[0] return ret # --------------------------------------------------------------------- # BaseOperator methods # --------------------------------------------------------------------- def tensor(self, other: PauliList) -> PauliList: """Return the tensor product with each Pauli in the list. Args: other (PauliList): another PauliList. Returns: PauliList: the list of tensor product Paulis. Raises: QiskitError: if other cannot be converted to a PauliList, does not have either 1 or the same number of Paulis as the current list. """ if not isinstance(other, PauliList): other = PauliList(other) return PauliList(super().tensor(other)) def expand(self, other: PauliList) -> PauliList: """Return the expand product of each Pauli in the list. Args: other (PauliList): another PauliList. Returns: PauliList: the list of tensor product Paulis. Raises: QiskitError: if other cannot be converted to a PauliList, does not have either 1 or the same number of Paulis as the current list. """ if not isinstance(other, PauliList): other = PauliList(other) if len(other) not in [1, len(self)]: raise QiskitError( "Incompatible PauliLists. Other list must " "have either 1 or the same number of Paulis." ) return PauliList(super().expand(other)) def compose( self, other: PauliList, qargs: None | list = None, front: bool = False, inplace: bool = False, ) -> PauliList: """Return the composition self∘other for each Pauli in the list. Args: other (PauliList): another PauliList. qargs (None or list): qubits to apply dot product on (Default: ``None``). front (bool): If True use `dot` composition method [default: ``False``]. inplace (bool): If ``True`` update in-place (default: ``False``). Returns: PauliList: the list of composed Paulis. Raises: QiskitError: if other cannot be converted to a PauliList, does not have either 1 or the same number of Paulis as the current list, or has the wrong number of qubits for the specified ``qargs``. """ if qargs is None: qargs = getattr(other, "qargs", None) if not isinstance(other, PauliList): other = PauliList(other) if len(other) not in [1, len(self)]: raise QiskitError( "Incompatible PauliLists. Other list must " "have either 1 or the same number of Paulis." ) return PauliList(super().compose(other, qargs=qargs, front=front, inplace=inplace)) def dot(self, other: PauliList, qargs: None | list = None, inplace: bool = False) -> PauliList: """Return the composition other∘self for each Pauli in the list. Args: other (PauliList): another PauliList. qargs (None or list): qubits to apply dot product on (Default: ``None``). inplace (bool): If True update in-place (default: ``False``). Returns: PauliList: the list of composed Paulis. Raises: QiskitError: if other cannot be converted to a PauliList, does not have either 1 or the same number of Paulis as the current list, or has the wrong number of qubits for the specified ``qargs``. """ return self.compose(other, qargs=qargs, front=True, inplace=inplace) def _add(self, other, qargs=None): """Append two PauliLists. If ``qargs`` are specified the other operator will be added assuming it is identity on all other subsystems. Args: other (PauliList): another table. qargs (None or list): optional subsystems to add on (Default: ``None``) Returns: PauliList: the concatenated list ``self`` + ``other``. """ if qargs is None: qargs = getattr(other, "qargs", None) if not isinstance(other, PauliList): other = PauliList(other) self._op_shape._validate_add(other._op_shape, qargs) base_phase = np.hstack((self._phase, other._phase)) if qargs is None or (sorted(qargs) == qargs and len(qargs) == self.num_qubits): base_z = np.vstack([self._z, other._z]) base_x = np.vstack([self._x, other._x]) else: # Pad other with identity and then add padded = BasePauli( np.zeros((other.size, self.num_qubits), dtype=bool), np.zeros((other.size, self.num_qubits), dtype=bool), np.zeros(other.size, dtype=int), ) padded = padded.compose(other, qargs=qargs, inplace=True) base_z = np.vstack([self._z, padded._z]) base_x = np.vstack([self._x, padded._x]) return PauliList(BasePauli(base_z, base_x, base_phase)) def _multiply(self, other): """Multiply each Pauli in the list by a phase. Args: other (complex or array): a complex number in [1, -1j, -1, 1j] Returns: PauliList: the list of Paulis other * self. Raises: QiskitError: if the phase is not in the set [1, -1j, -1, 1j]. """ return PauliList(super()._multiply(other)) def conjugate(self): """Return the conjugate of each Pauli in the list.""" return PauliList(super().conjugate()) def transpose(self): """Return the transpose of each Pauli in the list.""" return PauliList(super().transpose()) def adjoint(self): """Return the adjoint of each Pauli in the list.""" return PauliList(super().adjoint()) def inverse(self): """Return the inverse of each Pauli in the list.""" return PauliList(super().adjoint()) # --------------------------------------------------------------------- # Utility methods # --------------------------------------------------------------------- def commutes(self, other: BasePauli, qargs: list | None = None) -> bool: """Return True for each Pauli that commutes with other. Args: other (PauliList): another PauliList operator. qargs (list): qubits to apply dot product on (default: ``None``). Returns: bool: ``True`` if Paulis commute, ``False`` if they anti-commute. """ if qargs is None: qargs = getattr(other, "qargs", None) if not isinstance(other, BasePauli): other = PauliList(other) return super().commutes(other, qargs=qargs) def anticommutes(self, other: BasePauli, qargs: list | None = None) -> bool: """Return ``True`` if other Pauli that anticommutes with other. Args: other (PauliList): another PauliList operator. qargs (list): qubits to apply dot product on (default: ``None``). Returns: bool: ``True`` if Paulis anticommute, ``False`` if they commute. """ return np.logical_not(self.commutes(other, qargs=qargs)) def commutes_with_all(self, other: PauliList) -> np.ndarray: """Return indexes of rows that commute ``other``. If ``other`` is a multi-row Pauli list the returned vector indexes rows of the current PauliList that commute with *all* Paulis in other. If no rows satisfy the condition the returned array will be empty. Args: other (PauliList): a single Pauli or multi-row PauliList. Returns: array: index array of the commuting rows. """ return self._commutes_with_all(other) def anticommutes_with_all(self, other: PauliList) -> np.ndarray: """Return indexes of rows that commute other. If ``other`` is a multi-row Pauli list the returned vector indexes rows of the current PauliList that anti-commute with *all* Paulis in other. If no rows satisfy the condition the returned array will be empty. Args: other (PauliList): a single Pauli or multi-row PauliList. Returns: array: index array of the anti-commuting rows. """ return self._commutes_with_all(other, anti=True) def _commutes_with_all(self, other, anti=False): """Return row indexes that commute with all rows in another PauliList. Args: other (PauliList): a PauliList. anti (bool): if ``True`` return rows that anti-commute, otherwise return rows that commute (Default: ``False``). Returns: array: index array of commuting or anti-commuting row. """ if not isinstance(other, PauliList): other = PauliList(other) comms = self.commutes(other[0]) (inds,) = np.where(comms == int(not anti)) for pauli in other[1:]: comms = self[inds].commutes(pauli) (new_inds,) = np.where(comms == int(not anti)) if new_inds.size == 0: # No commuting rows return new_inds inds = inds[new_inds] return inds def evolve( self, other: Pauli | Clifford | QuantumCircuit, qargs: list | None = None, frame: Literal["h", "s"] = "h", ) -> Pauli: r"""Performs either Heisenberg (default) or Schrödinger picture evolution of the Pauli by a Clifford and returns the evolved Pauli. Schrödinger picture evolution can be chosen by passing parameter ``frame='s'``. This option yields a faster calculation. Heisenberg picture evolves the Pauli as :math:`P^\prime = C^\dagger.P.C`. Schrödinger picture evolves the Pauli as :math:`P^\prime = C.P.C^\dagger`. Args: other (Pauli or Clifford or QuantumCircuit): The Clifford operator to evolve by. qargs (list): a list of qubits to apply the Clifford to. frame (string): ``'h'`` for Heisenberg (default) or ``'s'`` for Schrödinger framework. Returns: PauliList: the Pauli :math:`C^\dagger.P.C` (Heisenberg picture) or the Pauli :math:`C.P.C^\dagger` (Schrödinger picture). Raises: QiskitError: if the Clifford number of qubits and qargs don't match. """ from qiskit.circuit import Instruction if qargs is None: qargs = getattr(other, "qargs", None) if not isinstance(other, (BasePauli, Instruction, QuantumCircuit, Clifford)): # Convert to a PauliList other = PauliList(other) return PauliList(super().evolve(other, qargs=qargs, frame=frame)) def to_labels(self, array: bool = False): r"""Convert a PauliList to a list Pauli string labels. For large PauliLists converting using the ``array=True`` kwarg will be more efficient since it allocates memory for the full Numpy array of labels in advance. .. list-table:: Pauli Representations :header-rows: 1 * - Label - Symplectic - Matrix * - ``"I"`` - :math:`[0, 0]` - :math:`\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}` * - ``"X"`` - :math:`[1, 0]` - :math:`\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}` * - ``"Y"`` - :math:`[1, 1]` - :math:`\begin{bmatrix} 0 & -i \\ i & 0 \end{bmatrix}` * - ``"Z"`` - :math:`[0, 1]` - :math:`\begin{bmatrix} 1 & 0 \\ 0 & -1 \end{bmatrix}` Args: array (bool): return a Numpy array if ``True``, otherwise return a list (Default: ``False``). Returns: list or array: The rows of the PauliList in label form. """ if (self.phase == 1).any(): prefix_len = 2 elif (self.phase > 0).any(): prefix_len = 1 else: prefix_len = 0 str_len = self.num_qubits + prefix_len ret = np.zeros(self.size, dtype=f"<U{str_len}") iterator = self.label_iter() for i in range(self.size): ret[i] = next(iterator) if array: return ret return ret.tolist() def to_matrix(self, sparse: bool = False, array: bool = False) -> list: r"""Convert to a list or array of Pauli matrices. For large PauliLists converting using the ``array=True`` kwarg will be more efficient since it allocates memory a full rank-3 Numpy array of matrices in advance. .. list-table:: Pauli Representations :header-rows: 1 * - Label - Symplectic - Matrix * - ``"I"`` - :math:`[0, 0]` - :math:`\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}` * - ``"X"`` - :math:`[1, 0]` - :math:`\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}` * - ``"Y"`` - :math:`[1, 1]` - :math:`\begin{bmatrix} 0 & -i \\ i & 0 \end{bmatrix}` * - ``"Z"`` - :math:`[0, 1]` - :math:`\begin{bmatrix} 1 & 0 \\ 0 & -1 \end{bmatrix}` Args: sparse (bool): if ``True`` return sparse CSR matrices, otherwise return dense Numpy arrays (Default: ``False``). array (bool): return as rank-3 numpy array if ``True``, otherwise return a list of Numpy arrays (Default: ``False``). Returns: list: A list of dense Pauli matrices if ``array=False` and ``sparse=False`. list: A list of sparse Pauli matrices if ``array=False`` and ``sparse=True``. array: A dense rank-3 array of Pauli matrices if ``array=True``. """ if not array: # We return a list of Numpy array matrices return list(self.matrix_iter(sparse=sparse)) # For efficiency we also allow returning a single rank-3 # array where first index is the Pauli row, and second two # indices are the matrix indices dim = 2**self.num_qubits ret = np.zeros((self.size, dim, dim), dtype=complex) iterator = self.matrix_iter(sparse=sparse) for i in range(self.size): ret[i] = next(iterator) return ret # --------------------------------------------------------------------- # Custom Iterators # --------------------------------------------------------------------- def label_iter(self): """Return a label representation iterator. This is a lazy iterator that converts each row into the string label only as it is used. To convert the entire table to labels use the :meth:`to_labels` method. Returns: LabelIterator: label iterator object for the PauliList. """ class LabelIterator(CustomIterator): """Label representation iteration and item access.""" def __repr__(self): return f"<PauliList_label_iterator at {hex(id(self))}>" def __getitem__(self, key): return self.obj._to_label(self.obj._z[key], self.obj._x[key], self.obj._phase[key]) return LabelIterator(self) def matrix_iter(self, sparse: bool = False): """Return a matrix representation iterator. This is a lazy iterator that converts each row into the Pauli matrix representation only as it is used. To convert the entire table to matrices use the :meth:`to_matrix` method. Args: sparse (bool): optionally return sparse CSR matrices if ``True``, otherwise return Numpy array matrices (Default: ``False``) Returns: MatrixIterator: matrix iterator object for the PauliList. """ class MatrixIterator(CustomIterator): """Matrix representation iteration and item access.""" def __repr__(self): return f"<PauliList_matrix_iterator at {hex(id(self))}>" def __getitem__(self, key): return self.obj._to_matrix( self.obj._z[key], self.obj._x[key], self.obj._phase[key], sparse=sparse ) return MatrixIterator(self) # --------------------------------------------------------------------- # Class methods # --------------------------------------------------------------------- @classmethod def from_symplectic( cls, z: np.ndarray, x: np.ndarray, phase: np.ndarray | None = 0 ) -> PauliList: """Construct a PauliList from a symplectic data. Args: z (np.ndarray): 2D boolean Numpy array. x (np.ndarray): 2D boolean Numpy array. phase (np.ndarray or None): Optional, 1D integer array from Z_4. Returns: PauliList: the constructed PauliList. """ base_z, base_x, base_phase = cls._from_array(z, x, phase) return cls(BasePauli(base_z, base_x, base_phase)) def _noncommutation_graph(self, qubit_wise): """Create an edge list representing the non-commutation graph (Pauli Graph). An edge (i, j) is present if i and j are not commutable. Args: qubit_wise (bool): whether the commutation rule is applied to the whole operator, or on a per-qubit basis. Returns: list[tuple[int,int]]: A list of pairs of indices of the PauliList that are not commutable. """ # convert a Pauli operator into int vector where {I: 0, X: 2, Y: 3, Z: 1} mat1 = np.array( [op.z + 2 * op.x for op in self], dtype=np.int8, ) mat2 = mat1[:, None] # This is 0 (false-y) iff one of the operators is the identity and/or both operators are the # same. In other cases, it is non-zero (truth-y). qubit_anticommutation_mat = (mat1 * mat2) * (mat1 - mat2) # 'adjacency_mat[i, j]' is True iff Paulis 'i' and 'j' do not commute in the given strategy. if qubit_wise: adjacency_mat = np.logical_or.reduce(qubit_anticommutation_mat, axis=2) else: # Don't commute if there's an odd number of element-wise anti-commutations. adjacency_mat = np.logical_xor.reduce(qubit_anticommutation_mat, axis=2) # Convert into list where tuple elements are non-commuting operators. We only want to # results from one triangle to avoid symmetric duplications. return list(zip(*np.where(np.triu(adjacency_mat, k=1)))) def noncommutation_graph(self, qubit_wise: bool) -> rx.PyGraph: """Create the non-commutation graph of this PauliList. This transforms the measurement operator grouping problem into graph coloring problem. The constructed graph contains one node for each Pauli. The nodes will be connecting for any two Pauli terms that do _not_ commute. Args: qubit_wise (bool): whether the commutation rule is applied to the whole operator, or on a per-qubit basis. Returns: rustworkx.PyGraph: the non-commutation graph with nodes for each Pauli and edges indicating a non-commutation relation. Each node will hold the index of the Pauli term it corresponds to in its data. The edges of the graph hold no data. """ edges = self._noncommutation_graph(qubit_wise) graph = rx.PyGraph() graph.add_nodes_from(range(self.size)) graph.add_edges_from_no_data(edges) return graph def _commuting_groups(self, qubit_wise: bool) -> dict[int, list[int]]: """Partition a PauliList into sets of commuting Pauli strings. This is the internal logic of the public ``PauliList.group_commuting`` method which returns a mapping of colors to Pauli indices. The same logic is re-used by ``SparsePauliOp.group_commuting``. Args: qubit_wise (bool): whether the commutation rule is applied to the whole operator, or on a per-qubit basis. Returns: dict[int, list[int]]: Dictionary of color indices mapping to a list of Pauli indices. """ graph = self.noncommutation_graph(qubit_wise) # Keys in coloring_dict are nodes, values are colors coloring_dict = rx.graph_greedy_color(graph) groups = defaultdict(list) for idx, color in coloring_dict.items(): groups[color].append(idx) return groups def group_qubit_wise_commuting(self) -> list[PauliList]: """Partition a PauliList into sets of mutually qubit-wise commuting Pauli strings. Returns: list[PauliList]: List of PauliLists where each PauliList contains commutable Pauli operators. """ return self.group_commuting(qubit_wise=True) def group_commuting(self, qubit_wise: bool = False) -> list[PauliList]: """Partition a PauliList into sets of commuting Pauli strings. Args: qubit_wise (bool): whether the commutation rule is applied to the whole operator, or on a per-qubit basis. For example: .. code-block:: python >>> from qiskit.quantum_info import PauliList >>> op = PauliList(["XX", "YY", "IZ", "ZZ"]) >>> op.group_commuting() [PauliList(['XX', 'YY']), PauliList(['IZ', 'ZZ'])] >>> op.group_commuting(qubit_wise=True) [PauliList(['XX']), PauliList(['YY']), PauliList(['IZ', 'ZZ'])] Returns: list[PauliList]: List of PauliLists where each PauliList contains commuting Pauli operators. """ groups = self._commuting_groups(qubit_wise) return [self[group] for group in groups.values()]
qiskit/qiskit/quantum_info/operators/symplectic/pauli_list.py/0
{ "file_path": "qiskit/qiskit/quantum_info/operators/symplectic/pauli_list.py", "repo_id": "qiskit", "token_count": 20680 }
195
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 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. """ Statevector quantum state class. """ from __future__ import annotations import copy as _copy import math import re from numbers import Number import numpy as np from qiskit import _numpy_compat from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.instruction import Instruction from qiskit.exceptions import QiskitError from qiskit.quantum_info.states.quantum_state import QuantumState from qiskit.quantum_info.operators.mixins.tolerances import TolerancesMixin from qiskit.quantum_info.operators.operator import Operator, BaseOperator from qiskit.quantum_info.operators.symplectic import Pauli, SparsePauliOp from qiskit.quantum_info.operators.op_shape import OpShape from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit._accelerate.pauli_expval import ( expval_pauli_no_x, expval_pauli_with_x, ) class Statevector(QuantumState, TolerancesMixin): """Statevector class""" def __init__( self, data: np.ndarray | list | Statevector | Operator | QuantumCircuit | Instruction, dims: int | tuple | list | None = None, ): """Initialize a statevector object. Args: data (np.array or list or Statevector or Operator or QuantumCircuit or qiskit.circuit.Instruction): Data from which the statevector can be constructed. This can be either a complex vector, another statevector, a ``Operator`` with only one column or a ``QuantumCircuit`` or ``Instruction``. If the data is a circuit or instruction, the statevector is constructed by assuming that all qubits are initialized to the zero state. dims (int or tuple or list): Optional. The subsystem dimension of the state (See additional information). Raises: QiskitError: if input data is not valid. Additional Information: The ``dims`` kwarg can be None, an integer, or an iterable of integers. * ``Iterable`` -- the subsystem dimensions are the values in the list with the total number of subsystems given by the length of the list. * ``Int`` or ``None`` -- the length of the input vector specifies the total dimension of the density matrix. If it is a power of two the state will be initialized as an N-qubit state. If it is not a power of two the state will have a single d-dimensional subsystem. """ if isinstance(data, (list, np.ndarray)): # Finally we check if the input is a raw vector in either a # python list or numpy array format. self._data = np.asarray(data, dtype=complex) elif isinstance(data, Statevector): self._data = data._data if dims is None: dims = data._op_shape._dims_l elif isinstance(data, Operator): # We allow conversion of column-vector operators to Statevectors input_dim, _ = data.dim if input_dim != 1: raise QiskitError("Input Operator is not a column-vector.") self._data = np.ravel(data.data) elif isinstance(data, (QuantumCircuit, Instruction)): self._data = Statevector.from_instruction(data).data else: raise QiskitError("Invalid input data format for Statevector") # Check that the input is a numpy vector or column-vector numpy # matrix. If it is a column-vector matrix reshape to a vector. ndim = self._data.ndim shape = self._data.shape if ndim != 1: if ndim == 2 and shape[1] == 1: self._data = np.reshape(self._data, shape[0]) shape = self._data.shape elif ndim != 2 or shape[1] != 1: raise QiskitError("Invalid input: not a vector or column-vector.") super().__init__(op_shape=OpShape.auto(shape=shape, dims_l=dims, num_qubits_r=0)) def __array__(self, dtype=None, copy=_numpy_compat.COPY_ONLY_IF_NEEDED): dtype = self.data.dtype if dtype is None else dtype return np.array(self.data, dtype=dtype, copy=copy) def __eq__(self, other): return super().__eq__(other) and np.allclose( self._data, other._data, rtol=self.rtol, atol=self.atol ) def __repr__(self): prefix = "Statevector(" pad = len(prefix) * " " return ( f"{prefix}{np.array2string(self._data, separator=', ', prefix=prefix)},\n{pad}" f"dims={self._op_shape.dims_l()})" ) @property def settings(self) -> dict: """Return settings.""" return {"data": self._data, "dims": self._op_shape.dims_l()} def draw(self, output: str | None = None, **drawer_args): """Return a visualization of the Statevector. **repr**: ASCII TextMatrix of the state's ``__repr__``. **text**: ASCII TextMatrix that can be printed in the console. **latex**: An IPython Latex object for displaying in Jupyter Notebooks. **latex_source**: Raw, uncompiled ASCII source to generate array using LaTeX. **qsphere**: Matplotlib figure, rendering of statevector using `plot_state_qsphere()`. **hinton**: Matplotlib figure, rendering of statevector using `plot_state_hinton()`. **bloch**: Matplotlib figure, rendering of statevector using `plot_bloch_multivector()`. **city**: Matplotlib figure, rendering of statevector using `plot_state_city()`. **paulivec**: Matplotlib figure, rendering of statevector using `plot_state_paulivec()`. Args: output (str): Select the output method to use for drawing the state. Valid choices are `repr`, `text`, `latex`, `latex_source`, `qsphere`, `hinton`, `bloch`, `city`, or `paulivec`. Default is `repr`. Default can be changed by adding the line ``state_drawer = <default>`` to ``~/.qiskit/settings.conf`` under ``[default]``. drawer_args: Arguments to be passed directly to the relevant drawing function or constructor (`TextMatrix()`, `array_to_latex()`, `plot_state_qsphere()`, `plot_state_hinton()` or `plot_bloch_multivector()`). See the relevant function under `qiskit.visualization` for that function's documentation. Returns: :class:`matplotlib.Figure` or :class:`str` or :class:`TextMatrix` or :class:`IPython.display.Latex`: Drawing of the Statevector. Raises: ValueError: when an invalid output method is selected. Examples: Plot one of the Bell states .. plot:: :include-source: from numpy import sqrt from qiskit.quantum_info import Statevector sv=Statevector([1/sqrt(2), 0, 0, -1/sqrt(2)]) sv.draw(output='hinton') """ # pylint: disable=cyclic-import from qiskit.visualization.state_visualization import state_drawer return state_drawer(self, output=output, **drawer_args) def _ipython_display_(self): out = self.draw() if isinstance(out, str): print(out) else: from IPython.display import display display(out) def __getitem__(self, key: int | str) -> np.complex128: """Return Statevector item either by index or binary label Args: key (int or str): index or corresponding binary label, e.g. '01' = 1. Returns: numpy.complex128: Statevector item. Raises: QiskitError: if key is not valid. """ if isinstance(key, str): try: key = int(key, 2) except ValueError: raise QiskitError(f"Key '{key}' is not a valid binary string.") from None if isinstance(key, int): if key >= self.dim: raise QiskitError(f"Key {key} is greater than Statevector dimension {self.dim}.") if key < 0: raise QiskitError(f"Key {key} is not a valid positive value.") return self._data[key] else: raise QiskitError("Key must be int or a valid binary string.") def __iter__(self): yield from self._data def __len__(self): return len(self._data) @property def data(self) -> np.ndarray: """Return data.""" return self._data def is_valid(self, atol: float | None = None, rtol: float | None = None) -> bool: """Return True if a Statevector has norm 1.""" if atol is None: atol = self.atol if rtol is None: rtol = self.rtol norm = np.linalg.norm(self.data) return np.allclose(norm, 1, rtol=rtol, atol=atol) def to_operator(self) -> Operator: """Convert state to a rank-1 projector operator""" mat = np.outer(self.data, np.conj(self.data)) return Operator(mat, input_dims=self.dims(), output_dims=self.dims()) def conjugate(self) -> Statevector: """Return the conjugate of the operator.""" return Statevector(np.conj(self.data), dims=self.dims()) def trace(self) -> np.float64: """Return the trace of the quantum state as a density matrix.""" return np.sum(np.abs(self.data) ** 2) def purity(self) -> np.float64: """Return the purity of the quantum state.""" # For a valid statevector the purity is always 1, however if we simply # have an arbitrary vector (not correctly normalized) then the # purity is equivalent to the trace squared: # P(|psi>) = Tr[|psi><psi|psi><psi|] = |<psi|psi>|^2 return self.trace() ** 2 def tensor(self, other: Statevector) -> Statevector: """Return the tensor product state self ⊗ other. Args: other (Statevector): a quantum state object. Returns: Statevector: the tensor product operator self ⊗ other. Raises: QiskitError: if other is not a quantum state. """ if not isinstance(other, Statevector): other = Statevector(other) ret = _copy.copy(self) ret._op_shape = self._op_shape.tensor(other._op_shape) ret._data = np.kron(self._data, other._data) return ret def inner(self, other: Statevector) -> np.complex128: r"""Return the inner product of self and other as :math:`\langle self| other \rangle`. Args: other (Statevector): a quantum state object. Returns: np.complex128: the inner product of self and other, :math:`\langle self| other \rangle`. Raises: QiskitError: if other is not a quantum state or has different dimension. """ if not isinstance(other, Statevector): other = Statevector(other) if self.dims() != other.dims(): raise QiskitError( f"Statevector dimensions do not match: {self.dims()} and {other.dims()}." ) inner = np.vdot(self.data, other.data) return inner def expand(self, other: Statevector) -> Statevector: """Return the tensor product state other ⊗ self. Args: other (Statevector): a quantum state object. Returns: Statevector: the tensor product state other ⊗ self. Raises: QiskitError: if other is not a quantum state. """ if not isinstance(other, Statevector): other = Statevector(other) ret = _copy.copy(self) ret._op_shape = self._op_shape.expand(other._op_shape) ret._data = np.kron(other._data, self._data) return ret def _add(self, other): """Return the linear combination self + other. Args: other (Statevector): a quantum state object. Returns: Statevector: the linear combination self + other. Raises: QiskitError: if other is not a quantum state, or has incompatible dimensions. """ if not isinstance(other, Statevector): other = Statevector(other) self._op_shape._validate_add(other._op_shape) ret = _copy.copy(self) ret._data = self.data + other.data return ret def _multiply(self, other): """Return the scalar multiplied state self * other. Args: other (complex): a complex number. Returns: Statevector: the scalar multiplied state other * self. Raises: QiskitError: if other is not a valid complex number. """ if not isinstance(other, Number): raise QiskitError("other is not a number") ret = _copy.copy(self) ret._data = other * self.data return ret def evolve( self, other: Operator | QuantumCircuit | Instruction, qargs: list[int] | None = None ) -> Statevector: """Evolve a quantum state by the operator. Args: other (Operator | QuantumCircuit | circuit.Instruction): The operator to evolve by. qargs (list): a list of Statevector subsystem positions to apply the operator on. Returns: Statevector: the output quantum state. Raises: QiskitError: if the operator dimension does not match the specified Statevector subsystem dimensions. """ if qargs is None: qargs = getattr(other, "qargs", None) # Get return vector ret = _copy.copy(self) # Evolution by a circuit or instruction if isinstance(other, QuantumCircuit): other = other.to_instruction() if isinstance(other, Instruction): if self.num_qubits is None: raise QiskitError("Cannot apply QuantumCircuit to non-qubit Statevector.") return self._evolve_instruction(ret, other, qargs=qargs) # Evolution by an Operator if not isinstance(other, Operator): dims = self.dims(qargs=qargs) other = Operator(other, input_dims=dims, output_dims=dims) # check dimension if self.dims(qargs) != other.input_dims(): raise QiskitError( "Operator input dimensions are not equal to statevector subsystem dimensions." ) return Statevector._evolve_operator(ret, other, qargs=qargs) def equiv( self, other: Statevector, rtol: float | None = None, atol: float | None = None ) -> bool: """Return True if other is equivalent as a statevector up to global phase. .. note:: If other is not a Statevector, but can be used to initialize a statevector object, this will check that Statevector(other) is equivalent to the current statevector up to global phase. Args: other (Statevector): an object from which a ``Statevector`` can be constructed. rtol (float): relative tolerance value for comparison. atol (float): absolute tolerance value for comparison. Returns: bool: True if statevectors are equivalent up to global phase. """ if not isinstance(other, Statevector): try: other = Statevector(other) except QiskitError: return False if self.dim != other.dim: return False if atol is None: atol = self.atol if rtol is None: rtol = self.rtol return matrix_equal(self.data, other.data, ignore_phase=True, rtol=rtol, atol=atol) def reverse_qargs(self) -> Statevector: r"""Return a Statevector with reversed subsystem ordering. For a tensor product state this is equivalent to reversing the order of tensor product subsystems. For a statevector :math:`|\psi \rangle = |\psi_{n-1} \rangle \otimes ... \otimes |\psi_0 \rangle` the returned statevector will be :math:`|\psi_{0} \rangle \otimes ... \otimes |\psi_{n-1} \rangle`. Returns: Statevector: the Statevector with reversed subsystem order. """ ret = _copy.copy(self) axes = tuple(range(self._op_shape._num_qargs_l - 1, -1, -1)) ret._data = np.reshape( np.transpose(np.reshape(self.data, self._op_shape.tensor_shape), axes), self._op_shape.shape, ) ret._op_shape = self._op_shape.reverse() return ret def _expectation_value_pauli(self, pauli, qargs=None): """Compute the expectation value of a Pauli. Args: pauli (Pauli): a Pauli operator to evaluate expval of. qargs (None or list): subsystems to apply operator on. Returns: complex: the expectation value. """ n_pauli = len(pauli) if qargs is None: qubits = np.arange(n_pauli) else: qubits = np.array(qargs) x_mask = np.dot(1 << qubits, pauli.x) z_mask = np.dot(1 << qubits, pauli.z) pauli_phase = (-1j) ** pauli.phase if pauli.phase else 1 if x_mask + z_mask == 0: return pauli_phase * np.linalg.norm(self.data) if x_mask == 0: return pauli_phase * expval_pauli_no_x(self.data, self.num_qubits, z_mask) x_max = qubits[pauli.x][-1] y_phase = (-1j) ** pauli._count_y() y_phase = y_phase[0] return pauli_phase * expval_pauli_with_x( self.data, self.num_qubits, z_mask, x_mask, y_phase, x_max ) def expectation_value( self, oper: BaseOperator | QuantumCircuit | Instruction, qargs: None | list[int] = None ) -> complex: """Compute the expectation value of an operator. Args: oper (Operator): an operator to evaluate expval of. qargs (None or list): subsystems to apply operator on. Returns: complex: the expectation value. """ if isinstance(oper, Pauli): return self._expectation_value_pauli(oper, qargs) if isinstance(oper, SparsePauliOp): return sum( coeff * self._expectation_value_pauli(Pauli((z, x)), qargs) for z, x, coeff in zip(oper.paulis.z, oper.paulis.x, oper.coeffs) ) val = self.evolve(oper, qargs=qargs) conj = self.conjugate() return np.dot(conj.data, val.data) def probabilities( self, qargs: None | list[int] = None, decimals: None | int = None ) -> np.ndarray: """Return the subsystem measurement probability vector. Measurement probabilities are with respect to measurement in the computation (diagonal) basis. Args: qargs (None or list): subsystems to return probabilities for, if None return for all subsystems (Default: None). decimals (None or int): the number of decimal places to round values. If None no rounding is done (Default: None). Returns: np.array: The Numpy vector array of probabilities. Examples: Consider a 2-qubit product state :math:`|\\psi\\rangle=|+\\rangle\\otimes|0\\rangle`. .. code-block:: from qiskit.quantum_info import Statevector psi = Statevector.from_label('+0') # Probabilities for measuring both qubits probs = psi.probabilities() print('probs: {}'.format(probs)) # Probabilities for measuring only qubit-0 probs_qubit_0 = psi.probabilities([0]) print('Qubit-0 probs: {}'.format(probs_qubit_0)) # Probabilities for measuring only qubit-1 probs_qubit_1 = psi.probabilities([1]) print('Qubit-1 probs: {}'.format(probs_qubit_1)) .. parsed-literal:: probs: [0.5 0. 0.5 0. ] Qubit-0 probs: [1. 0.] Qubit-1 probs: [0.5 0.5] We can also permute the order of qubits in the ``qargs`` list to change the qubit position in the probabilities output .. code-block:: from qiskit.quantum_info import Statevector psi = Statevector.from_label('+0') # Probabilities for measuring both qubits probs = psi.probabilities([0, 1]) print('probs: {}'.format(probs)) # Probabilities for measuring both qubits # but swapping qubits 0 and 1 in output probs_swapped = psi.probabilities([1, 0]) print('Swapped probs: {}'.format(probs_swapped)) .. parsed-literal:: probs: [0.5 0. 0.5 0. ] Swapped probs: [0.5 0.5 0. 0. ] """ probs = self._subsystem_probabilities( np.abs(self.data) ** 2, self._op_shape.dims_l(), qargs=qargs ) # to account for roundoff errors, we clip probs = np.clip(probs, a_min=0, a_max=1) if decimals is not None: probs = probs.round(decimals=decimals) return probs def reset(self, qargs: list[int] | None = None) -> Statevector: """Reset state or subsystems to the 0-state. Args: qargs (list or None): subsystems to reset, if None all subsystems will be reset to their 0-state (Default: None). Returns: Statevector: the reset state. Additional Information: If all subsystems are reset this will return the ground state on all subsystems. If only a some subsystems are reset this function will perform a measurement on those subsystems and evolve the subsystems so that the collapsed post-measurement states are rotated to the 0-state. The RNG seed for this sampling can be set using the :meth:`seed` method. """ if qargs is None: # Resetting all qubits does not require sampling or RNG ret = _copy.copy(self) state = np.zeros(self._op_shape.shape, dtype=complex) state[0] = 1 ret._data = state return ret # Sample a single measurement outcome dims = self.dims(qargs) probs = self.probabilities(qargs) sample = self._rng.choice(len(probs), p=probs, size=1) # Convert to projector for state update proj = np.zeros(len(probs), dtype=complex) proj[sample] = 1 / np.sqrt(probs[sample]) # Rotate outcome to 0 reset = np.eye(len(probs)) reset[0, 0] = 0 reset[sample, sample] = 0 reset[0, sample] = 1 # compose with reset projection reset = np.dot(reset, np.diag(proj)) return self.evolve(Operator(reset, input_dims=dims, output_dims=dims), qargs=qargs) @classmethod def from_label(cls, label: str) -> Statevector: """Return a tensor product of Pauli X,Y,Z eigenstates. .. list-table:: Single-qubit state labels :header-rows: 1 * - Label - Statevector * - ``"0"`` - :math:`[1, 0]` * - ``"1"`` - :math:`[0, 1]` * - ``"+"`` - :math:`[1 / \\sqrt{2}, 1 / \\sqrt{2}]` * - ``"-"`` - :math:`[1 / \\sqrt{2}, -1 / \\sqrt{2}]` * - ``"r"`` - :math:`[1 / \\sqrt{2}, i / \\sqrt{2}]` * - ``"l"`` - :math:`[1 / \\sqrt{2}, -i / \\sqrt{2}]` Args: label (string): a eigenstate string ket label (see table for allowed values). Returns: Statevector: The N-qubit basis state density matrix. Raises: QiskitError: if the label contains invalid characters, or the length of the label is larger than an explicitly specified num_qubits. """ # Check label is valid if re.match(r"^[01rl\-+]+$", label) is None: raise QiskitError("Label contains invalid characters.") # We can prepare Z-eigenstates by converting the computational # basis bit-string to an integer and preparing that unit vector # However, for X-basis states, we will prepare a Z-eigenstate first # then apply Hadamard gates to rotate 0 and 1s to + and -. z_label = label xy_states = False if re.match("^[01]+$", label) is None: # We have X or Y eigenstates so replace +,r with 0 and # -,l with 1 and prepare the corresponding Z state xy_states = True z_label = z_label.replace("+", "0") z_label = z_label.replace("r", "0") z_label = z_label.replace("-", "1") z_label = z_label.replace("l", "1") # Initialize Z eigenstate vector num_qubits = len(label) data = np.zeros(1 << num_qubits, dtype=complex) pos = int(z_label, 2) data[pos] = 1 state = Statevector(data) if xy_states: # Apply hadamards to all qubits in X eigenstates x_mat = np.array([[1, 1], [1, -1]], dtype=complex) / math.sqrt(2) # Apply S.H to qubits in Y eigenstates y_mat = np.dot(np.diag([1, 1j]), x_mat) for qubit, char in enumerate(reversed(label)): if char in ["+", "-"]: state = state.evolve(x_mat, qargs=[qubit]) elif char in ["r", "l"]: state = state.evolve(y_mat, qargs=[qubit]) return state @staticmethod def from_int(i: int, dims: int | tuple | list) -> Statevector: """Return a computational basis statevector. Args: i (int): the basis state element. dims (int or tuple or list): The subsystem dimensions of the statevector (See additional information). Returns: Statevector: The computational basis state :math:`|i\\rangle`. Additional Information: The ``dims`` kwarg can be an integer or an iterable of integers. * ``Iterable`` -- the subsystem dimensions are the values in the list with the total number of subsystems given by the length of the list. * ``Int`` -- the integer specifies the total dimension of the state. If it is a power of two the state will be initialized as an N-qubit state. If it is not a power of two the state will have a single d-dimensional subsystem. """ size = np.prod(dims) state = np.zeros(size, dtype=complex) state[i] = 1.0 return Statevector(state, dims=dims) @classmethod def from_instruction(cls, instruction: Instruction | QuantumCircuit) -> Statevector: """Return the output statevector of an instruction. The statevector is initialized in the state :math:`|{0,\\ldots,0}\\rangle` of the same number of qubits as the input instruction or circuit, evolved by the input instruction, and the output statevector returned. Args: instruction (qiskit.circuit.Instruction or QuantumCircuit): instruction or circuit Returns: Statevector: The final statevector. Raises: QiskitError: if the instruction contains invalid instructions for the statevector simulation. """ # Convert circuit to an instruction if isinstance(instruction, QuantumCircuit): instruction = instruction.to_instruction() # Initialize an the statevector in the all |0> state init = np.zeros(2**instruction.num_qubits, dtype=complex) init[0] = 1.0 vec = Statevector(init, dims=instruction.num_qubits * (2,)) return Statevector._evolve_instruction(vec, instruction) def to_dict(self, decimals: None | int = None) -> dict: r"""Convert the statevector to dictionary form. This dictionary representation uses a Ket-like notation where the dictionary keys are qudit strings for the subsystem basis vectors. If any subsystem has a dimension greater than 10 comma delimiters are inserted between integers so that subsystems can be distinguished. Args: decimals (None or int): the number of decimal places to round values. If None no rounding is done (Default: None). Returns: dict: the dictionary form of the Statevector. Example: The ket-form of a 2-qubit statevector :math:`|\psi\rangle = |-\rangle\otimes |0\rangle` .. code-block:: from qiskit.quantum_info import Statevector psi = Statevector.from_label('-0') print(psi.to_dict()) .. parsed-literal:: {'00': (0.7071067811865475+0j), '10': (-0.7071067811865475+0j)} For non-qubit subsystems the integer range can go from 0 to 9. For example in a qutrit system .. code-block:: import numpy as np from qiskit.quantum_info import Statevector vec = np.zeros(9) vec[0] = 1 / np.sqrt(2) vec[-1] = 1 / np.sqrt(2) psi = Statevector(vec, dims=(3, 3)) print(psi.to_dict()) .. parsed-literal:: {'00': (0.7071067811865475+0j), '22': (0.7071067811865475+0j)} For large subsystem dimensions delimiters are required. The following example is for a 20-dimensional system consisting of a qubit and 10-dimensional qudit. .. code-block:: import numpy as np from qiskit.quantum_info import Statevector vec = np.zeros(2 * 10) vec[0] = 1 / np.sqrt(2) vec[-1] = 1 / np.sqrt(2) psi = Statevector(vec, dims=(2, 10)) print(psi.to_dict()) .. parsed-literal:: {'00': (0.7071067811865475+0j), '91': (0.7071067811865475+0j)} """ return self._vector_to_dict( self.data, self._op_shape.dims_l(), decimals=decimals, string_labels=True ) @staticmethod def _evolve_operator(statevec, oper, qargs=None): """Evolve a qudit statevector""" new_shape = statevec._op_shape.compose(oper._op_shape, qargs=qargs) if qargs is None: # Full system evolution statevec._data = np.dot(oper._data, statevec._data) statevec._op_shape = new_shape return statevec # Get transpose axes num_qargs = statevec._op_shape.num_qargs[0] indices = [num_qargs - 1 - i for i in reversed(qargs)] axes = indices + [i for i in range(num_qargs) if i not in indices] axes_inv = np.argsort(axes).tolist() # Calculate contraction dimensions contract_dim = oper._op_shape.shape[1] contract_shape = (contract_dim, statevec._op_shape.shape[0] // contract_dim) # Reshape and transpose input array for contraction tensor = np.transpose( np.reshape(statevec.data, statevec._op_shape.tensor_shape), axes, ) tensor_shape = tensor.shape # Perform contraction tensor = np.reshape( np.dot(oper.data, np.reshape(tensor, contract_shape)), tensor_shape, ) # Transpose back to original subsystem spec and flatten statevec._data = np.reshape(np.transpose(tensor, axes_inv), new_shape.shape[0]) # Update dimension statevec._op_shape = new_shape return statevec @staticmethod def _evolve_instruction(statevec, obj, qargs=None): """Update the current Statevector by applying an instruction.""" from qiskit.circuit.reset import Reset from qiskit.circuit.barrier import Barrier # pylint complains about a cyclic import since the following Initialize file # imports the StatePreparation, which again requires the Statevector (this file), # but as this is a local import, it's not actually an issue and can be ignored # pylint: disable=cyclic-import from qiskit.circuit.library.data_preparation.initializer import Initialize mat = Operator._instruction_to_matrix(obj) if mat is not None: # Perform the composition and inplace update the current state # of the operator return Statevector._evolve_operator(statevec, Operator(mat), qargs=qargs) # Special instruction types if isinstance(obj, Reset): statevec._data = statevec.reset(qargs)._data return statevec if isinstance(obj, Barrier): return statevec if isinstance(obj, Initialize): # state is initialized to labels in the initialize object if all(isinstance(param, str) for param in obj.params): initialization = Statevector.from_label("".join(obj.params))._data # state is initialized to an integer # here we're only checking the length as (1) a length-1 object necessarily means the # state is described by an integer (as labels were already covered) and (2) the int # was cast to a complex and we cannot do an int typecheck anyways elif len(obj.params) == 1: state = int(np.real(obj.params[0])) initialization = Statevector.from_int(state, (2,) * obj.num_qubits)._data # state is initialized to the statevector else: initialization = np.asarray(obj.params, dtype=complex) if qargs is None: statevec._data = initialization else: # if we act on a subsystem we first need to reset and then apply the # state preparation statevec._data = statevec.reset(qargs)._data mat = np.zeros((2 ** len(qargs), 2 ** len(qargs)), dtype=complex) mat[:, 0] = initialization statevec = Statevector._evolve_operator(statevec, Operator(mat), qargs=qargs) return statevec # If the instruction doesn't have a matrix defined we use its # circuit decomposition definition if it exists, otherwise we # cannot compose this gate and raise an error. if obj.definition is None: raise QiskitError(f"Cannot apply Instruction: {obj.name}") if not isinstance(obj.definition, QuantumCircuit): raise QiskitError( f"{obj.name} instruction definition is {type(obj.definition)}; expected QuantumCircuit" ) if obj.definition.global_phase: statevec._data *= np.exp(1j * float(obj.definition.global_phase)) qubits = {qubit: i for i, qubit in enumerate(obj.definition.qubits)} for instruction in obj.definition: if instruction.clbits: raise QiskitError( f"Cannot apply instruction with classical bits: {instruction.operation.name}" ) # Get the integer position of the flat register if qargs is None: new_qargs = [qubits[tup] for tup in instruction.qubits] else: new_qargs = [qargs[qubits[tup]] for tup in instruction.qubits] Statevector._evolve_instruction(statevec, instruction.operation, qargs=new_qargs) return statevec
qiskit/qiskit/quantum_info/states/statevector.py/0
{ "file_path": "qiskit/qiskit/quantum_info/states/statevector.py", "repo_id": "qiskit", "token_count": 16511 }
196
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # 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. # pylint: disable=cyclic-import """Routines for computing expectation values from sampled distributions""" import numpy as np from qiskit._accelerate.sampled_exp_val import sampled_expval_float, sampled_expval_complex from qiskit.exceptions import QiskitError from .distributions import QuasiDistribution, ProbDistribution # A list of valid diagonal operators OPERS = {"Z", "I", "0", "1"} def sampled_expectation_value(dist, oper): """Computes expectation value from a sampled distribution Note that passing a raw dict requires bit-string keys. Parameters: dist (Counts or QuasiDistribution or ProbDistribution or dict): Input sampled distribution oper (str or Pauli or PauliOp or PauliSumOp or SparsePauliOp): The operator for the observable Returns: float: The expectation value Raises: QiskitError: if the input distribution or operator is an invalid type """ from .counts import Counts from qiskit.quantum_info import Pauli, SparsePauliOp # This should be removed when these return bit-string keys if isinstance(dist, (QuasiDistribution, ProbDistribution)): dist = dist.binary_probabilities() if not isinstance(dist, (Counts, dict)): raise QiskitError("Invalid input distribution type") if isinstance(oper, str): oper_strs = [oper.upper()] coeffs = np.asarray([1.0]) elif isinstance(oper, Pauli): oper_strs = [oper.to_label()] coeffs = np.asarray([1.0]) elif isinstance(oper, SparsePauliOp): oper_strs = oper.paulis.to_labels() coeffs = np.asarray(oper.coeffs) else: raise QiskitError("Invalid operator type") # Do some validation here bitstring_len = len(next(iter(dist))) if any(len(op) != bitstring_len for op in oper_strs): raise QiskitError( f"One or more operators not same length ({bitstring_len}) as input bitstrings" ) for op in oper_strs: if set(op).difference(OPERS): raise QiskitError(f"Input operator {op} is not diagonal") # Dispatch to Rust routines if coeffs.dtype == np.dtype(complex).type: return sampled_expval_complex(oper_strs, coeffs, dist) else: return sampled_expval_float(oper_strs, coeffs, dist)
qiskit/qiskit/result/sampled_expval.py/0
{ "file_path": "qiskit/qiskit/result/sampled_expval.py", "repo_id": "qiskit", "token_count": 1057 }
197
# This code is part of Qiskit. # # (C) Copyright IBM 2017 - 2023. # # 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. """Module containing cnot circuits""" from .cnot_synth import synth_cnot_count_full_pmh from .linear_depth_lnn import synth_cnot_depth_line_kms from .linear_matrix_utils import ( random_invertible_binary_matrix, calc_inverse_matrix, check_invertible_binary_matrix, binary_matmul, ) # This is re-import is kept for compatibility with Terra 0.23. Eligible for deprecation in 0.25+. # pylint: disable=cyclic-import,wrong-import-order from qiskit.synthesis.linear_phase import synth_cnot_phase_aam as graysynth
qiskit/qiskit/synthesis/linear/__init__.py/0
{ "file_path": "qiskit/qiskit/synthesis/linear/__init__.py", "repo_id": "qiskit", "token_count": 322 }
198
# This code is part of Qiskit. # # (C) Copyright IBM 2024 # # 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. """ Synthesis of a reverse permutation for LNN connectivity. """ from qiskit.circuit import QuantumCircuit from qiskit._accelerate.synthesis.permutation import ( synth_permutation_reverse_lnn_kms as synth_permutation_reverse_lnn_kms_inner, ) def _append_cx_stage1(qc, n): """A single layer of CX gates.""" for i in range(n // 2): qc.cx(2 * i, 2 * i + 1) for i in range((n + 1) // 2 - 1): qc.cx(2 * i + 2, 2 * i + 1) return qc def _append_cx_stage2(qc, n): """A single layer of CX gates.""" for i in range(n // 2): qc.cx(2 * i + 1, 2 * i) for i in range((n + 1) // 2 - 1): qc.cx(2 * i + 1, 2 * i + 2) return qc def _append_reverse_permutation_lnn_kms(qc: QuantumCircuit, num_qubits: int) -> None: """ Append reverse permutation to a QuantumCircuit for linear nearest-neighbor architectures using Kutin, Moulton, Smithline method. Synthesis algorithm for reverse permutation from [1], section 5. This algorithm synthesizes the reverse permutation on :math:`n` qubits over a linear nearest-neighbor architecture using CX gates with depth :math:`2 * n + 2`. Args: qc: The original quantum circuit. num_qubits: The number of qubits. Returns: The quantum circuit with appended reverse permutation. References: 1. Kutin, S., Moulton, D. P., Smithline, L., *Computation at a distance*, Chicago J. Theor. Comput. Sci., vol. 2007, (2007), `arXiv:quant-ph/0701194 <https://arxiv.org/abs/quant-ph/0701194>`_ """ for _ in range((num_qubits + 1) // 2): _append_cx_stage1(qc, num_qubits) _append_cx_stage2(qc, num_qubits) if (num_qubits % 2) == 0: _append_cx_stage1(qc, num_qubits) def synth_permutation_reverse_lnn_kms(num_qubits: int) -> QuantumCircuit: """ Synthesize reverse permutation for linear nearest-neighbor architectures using Kutin, Moulton, Smithline method. Synthesis algorithm for reverse permutation from [1], section 5. This algorithm synthesizes the reverse permutation on :math:`n` qubits over a linear nearest-neighbor architecture using CX gates with depth :math:`2 * n + 2`. Args: num_qubits: The number of qubits. Returns: The synthesized quantum circuit. References: 1. Kutin, S., Moulton, D. P., Smithline, L., *Computation at a distance*, Chicago J. Theor. Comput. Sci., vol. 2007, (2007), `arXiv:quant-ph/0701194 <https://arxiv.org/abs/quant-ph/0701194>`_ """ # Call Rust implementation return QuantumCircuit._from_circuit_data(synth_permutation_reverse_lnn_kms_inner(num_qubits))
qiskit/qiskit/synthesis/permutation/permutation_reverse_lnn.py/0
{ "file_path": "qiskit/qiskit/synthesis/permutation/permutation_reverse_lnn.py", "repo_id": "qiskit", "token_count": 1233 }
199