From 6226994b7b66c558a915c09b3e0af2a5e44fca8b Mon Sep 17 00:00:00 2001 From: drdren <104710745+drdren@users.noreply.github.com> Date: Mon, 20 Apr 2026 15:04:50 -0400 Subject: [PATCH 01/10] Change qml to qp for Batch 3 (#1754) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### Before submitting Please complete the following checklist when submitting a PR: - [ ] Ensure that your tutorial executes correctly, and conforms to the guidelines specified in the [README](https://github.com/PennyLaneAI/demos/blob/master/README.md). - [ ] Remember to do a grammar check of the content you include. - [ ] All tutorials conform to [PEP8 standards](https://www.python.org/dev/peps/pep-0008/). To auto format files, simply `pip install black`, and then run `black -l 100 path/to/file.py`. When all the above are checked, delete everything above the dashed line and fill in the pull request template. ------------------------------------------------------------------------------------------------------------ **Title:** **Summary:** **Relevant references:** **Possible Drawbacks:** **Related GitHub Issues:** ---- If you are writing a demonstration, please answer these questions to facilitate the marketing process. * GOALS — Why are we working on this now? *Eg. Promote a new PL feature or show a PL implementation of a recent paper.* * AUDIENCE — Who is this for? *Eg. Chemistry researchers, PL educators, beginners in quantum computing.* * KEYWORDS — What words should be included in the marketing post? * Which of the following types of documentation is most similar to your file? (more details [here](https://www.notion.so/xanaduai/Different-kinds-of-documentation-69200645fe59442991c71f9e7d8a77f8)) - [ ] Tutorial - [ ] Demo - [ ] How-to --------- Co-authored-by: David --- .../demo.py | 84 +++++----- .../metadata.json | 2 +- .../tutorial_coherent_vqls/demo.py | 46 +++--- .../tutorial_coherent_vqls/metadata.json | 2 +- .../tutorial_constant_depth_mps_prep/demo.py | 54 +++---- .../metadata.json | 2 +- .../tutorial_contextuality/demo.py | 52 +++---- .../tutorial_contextuality/metadata.json | 2 +- .../demo.py | 12 +- .../metadata.json | 2 +- .../tutorial_diffable-mitigation/demo.py | 40 ++--- .../metadata.json | 2 +- .../tutorial_diffable_shadows/demo.py | 144 +++++++++--------- .../tutorial_diffable_shadows/metadata.json | 2 +- .../tutorial_differentiable_HF/demo.py | 38 ++--- .../tutorial_differentiable_HF/metadata.json | 2 +- .../tutorial_dmet_embedding/demo.py | 1 - .../tutorial_dmet_embedding/metadata.json | 2 +- .../tutorial_doubly_stochastic/demo.py | 42 ++--- .../tutorial_doubly_stochastic/metadata.json | 2 +- demonstrations_v2/tutorial_dqi/demo.py | 76 ++++----- demonstrations_v2/tutorial_dqi/metadata.json | 2 +- .../tutorial_eqnn_force_field/demo.py | 34 ++--- .../tutorial_eqnn_force_field/metadata.json | 2 +- .../demo.py | 22 +-- .../metadata.json | 2 +- .../tutorial_error_mitigation/demo.py | 78 +++++----- .../tutorial_error_mitigation/metadata.json | 2 +- demonstrations_v2/tutorial_error_prop/demo.py | 44 +++--- .../tutorial_error_prop/metadata.json | 2 +- .../demo.py | 56 +++---- .../metadata.json | 2 +- demonstrations_v2/tutorial_falqon/demo.py | 46 +++--- .../tutorial_falqon/metadata.json | 2 +- .../tutorial_fermionic_operators/demo.py | 8 +- .../metadata.json | 2 +- .../demo.py | 42 ++--- .../metadata.json | 2 +- .../tutorial_gaussian_transformation/demo.py | 12 +- .../metadata.json | 2 +- .../tutorial_general_parshift/demo.py | 16 +- .../tutorial_general_parshift/metadata.json | 2 +- 42 files changed, 494 insertions(+), 495 deletions(-) diff --git a/demonstrations_v2/tutorial_clifford_circuit_simulations/demo.py b/demonstrations_v2/tutorial_clifford_circuit_simulations/demo.py index c4e85296e2..bd3b7ad332 100644 --- a/demonstrations_v2/tutorial_clifford_circuit_simulations/demo.py +++ b/demonstrations_v2/tutorial_clifford_circuit_simulations/demo.py @@ -131,21 +131,21 @@ """ -import pennylane as qml +import pennylane as qp -dev = qml.device("default.clifford", wires=2, tableau=True) +dev = qp.device("default.clifford", wires=2, tableau=True) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(return_state=True): - qml.X(wires=[0]) - qml.CNOT(wires=[0, 1]) - qml.Hadamard(wires=[0]) - qml.Hadamard(wires=[1]) + qp.X(wires=[0]) + qp.CNOT(wires=[0, 1]) + qp.Hadamard(wires=[0]) + qp.Hadamard(wires=[1]) return [ - qml.expval(op=qml.X(0) @ qml.X(1)), - qml.var(op=qml.Z(0) @ qml.Z(1)), - qml.probs(), - ] + ([qml.state()] if return_state else []) + qp.expval(op=qp.X(0) @ qp.X(1)), + qp.var(op=qp.Z(0) @ qp.Z(1)), + qp.probs(), + ] + ([qp.state()] if return_state else []) expval, var, probs, state = circuit(return_state=True) @@ -163,9 +163,9 @@ def circuit(return_state=True): import matplotlib.pyplot as plt # Get the results with 10000 shots and assert them -shot_result = qml.set_shots(circuit, shots=10000)(return_state=False) +shot_result = qp.set_shots(circuit, shots=10000)(return_state=False) shot_exp, shot_var, shot_probs = shot_result -assert qml.math.allclose([shot_exp, shot_var], [expval, var], atol=1e-3) +assert qp.math.allclose([shot_exp, shot_var], [expval, var], atol=1e-3) # Define computational basis states basis_states = ["|00⟩", "|01⟩", "|10⟩", "|11⟩"] @@ -203,15 +203,15 @@ def circuit(return_state=True): # preparation circuit: # -dev = qml.device("default.clifford") +dev = qp.device("default.clifford") -@qml.qnode(dev) +@qp.qnode(dev) def GHZStatePrep(num_wires): """Prepares the GHZ State""" - qml.Hadamard(wires=[0]) + qp.Hadamard(wires=[0]) for wire in range(num_wires): - qml.CNOT(wires=[wire, wire + 1]) - return qml.expval(qml.Z(0) @ qml.Z(num_wires - 1)) + qp.CNOT(wires=[wire, wire + 1]) + return qp.expval(qp.Z(0) @ qp.Z(num_wires - 1)) ###################################################################### @@ -221,7 +221,7 @@ def GHZStatePrep(num_wires): from timeit import timeit -dev = qml.device("default.clifford") +dev = qp.device("default.clifford") num_shots = [None, 100000] num_wires = [10, 100, 1000, 10000] @@ -232,7 +232,7 @@ def GHZStatePrep(num_wires): for ind, num_shot in enumerate(num_shots): for idx, num_wire in enumerate(num_wires): shots_times[ind][idx] = timeit( - "qml.set_shots(GHZStatePrep, shots=num_shot)(num_wire)", number=5, globals=globals() + "qp.set_shots(GHZStatePrep, shots=num_shot)(num_wire)", number=5, globals=globals() ) / 5 # average over 5 trials # Figure set up @@ -320,23 +320,23 @@ def tableau_to_pauli_rep(tableau): # As previously suggested, the evolution of the stabilizer tableau after the application of # each Clifford gate operation can be understood by learning how the generator set is # transformed based on their Clifford tableaus. For example, the first circuit operation -# ``qml.X(0)`` has the following tableau: +# ``qp.X(0)`` has the following tableau: # def clifford_tableau(op): """Prints a Clifford Tableau representation for a given operation.""" # Print the op and set up Pauli operators to be conjugated print(f"Tableau: {op.name}({', '.join(map(str, op.wires))})") - pauli_ops = [pauli(wire) for wire in op.wires for pauli in [qml.X, qml.Z]] + pauli_ops = [pauli(wire) for wire in op.wires for pauli in [qp.X, qp.Z]] # obtain conjugation of Pauli op and decompose it in Pauli basis for pauli in pauli_ops: - conjugate = qml.prod(qml.adjoint(op), pauli, op).simplify() - decompose = qml.pauli_decompose(conjugate.matrix(), wire_order=op.wires) + conjugate = qp.prod(qp.adjoint(op), pauli, op).simplify() + decompose = qp.pauli_decompose(conjugate.matrix(), wire_order=op.wires) decompose_coeffs, decompose_ops = decompose.terms() phase = "+" if list(decompose_coeffs)[0] >= 0 else "-" print(pauli, "-—>", phase, list(decompose_ops)[0]) -clifford_tableau(qml.X(0)) +clifford_tableau(qp.X(0)) ###################################################################### # We now have the two key components for studying the evolution of the stabilizer tableau of the @@ -347,26 +347,26 @@ def clifford_tableau(op): # :func:`~pennylane.snapshots` in the circuit using the following transform. # -@qml.transform +@qp.transform def state_at_each_step(tape): """Transforms a circuit to access state after every operation""" - # This builds list with a qml.Snapshot operation before every tape operation + # This builds list with a qp.Snapshot operation before every tape operation operations = [] for op in tape.operations: - operations.append(qml.Snapshot()) + operations.append(qp.Snapshot()) operations.append(op) - operations.append(qml.Snapshot()) # add a final qml.Snapshot operation at end + operations.append(qp.Snapshot()) # add a final qp.Snapshot operation at end new_tape = type(tape)(operations, tape.measurements, shots=tape.shots) postprocessing = lambda results: results[0] # func for processing results return [new_tape], postprocessing -snapshots = qml.snapshots(state_at_each_step(circuit))() +snapshots = qp.snapshots(state_at_each_step(circuit))() ###################################################################### # We can now access the tableau state via the ``snapshots`` dictionary, where the integer keys # represent each step. The step ``0`` corresponds to the initial all zero :math:`|00\rangle` # state, which is stabilized by the Pauli operators :math:`Z_0` and :math:`Z_1.` Evolving -# it by a ``qml.X(0)`` would correspond to transforming its stabilizer generators +# it by a ``qp.X(0)`` would correspond to transforming its stabilizer generators # from :math:`+Z_0` to :math:`-Z_0,` while keeping the destabilizer generators the same. # @@ -381,7 +381,7 @@ def state_at_each_step(tape): # Let's examine the remaining operations to confirm this. # -tape = qml.workflow.construct_tape(circuit)() +tape = qp.workflow.construct_tape(circuit)() circuit_ops = tape.operations print("Circ. Ops: ", circuit_ops) @@ -410,18 +410,18 @@ def state_at_each_step(tape): # Let's see this in action for the following two-qubit parameterized circuit: # -dev = qml.device("default.qubit") -@qml.qnode(dev) +dev = qp.device("default.qubit") +@qp.qnode(dev) def original_circuit(x, y): - qml.RX(x, 0) - qml.CNOT([0, 1]) - qml.RY(y, 0) - return qml.probs() + qp.RX(x, 0) + qp.CNOT([0, 1]) + qp.RY(y, 0) + return qp.probs() x, y = np.pi / 2, np.pi / 4 -unrolled_circuit = qml.transforms.clifford_t_decomposition(original_circuit) +unrolled_circuit = qp.transforms.clifford_t_decomposition(original_circuit) -qml.draw_mpl(unrolled_circuit, decimals=2, style="pennylane")(x, y) +qp.draw_mpl(unrolled_circuit, decimals=2, style="pennylane")(x, y) plt.show() ###################################################################### @@ -434,7 +434,7 @@ def original_circuit(x, y): # original_probs, unrolled_probs = original_circuit(x, y), unrolled_circuit(x, y) -assert qml.math.allclose(original_probs, unrolled_probs, atol=1e-3) +assert qp.math.allclose(original_probs, unrolled_probs, atol=1e-3) ###################################################################### # Ultimately, one can use this decomposition to perform some basic resource analysis for @@ -446,7 +446,7 @@ def original_circuit(x, y): # `Eastin-Knill `__ theorem. # -with qml.Tracker(dev) as tracker: +with qp.Tracker(dev) as tracker: unrolled_circuit(x, y) resources_lst = tracker.history["resources"] diff --git a/demonstrations_v2/tutorial_clifford_circuit_simulations/metadata.json b/demonstrations_v2/tutorial_clifford_circuit_simulations/metadata.json index a4e1a96c4d..b5e859b7ca 100644 --- a/demonstrations_v2/tutorial_clifford_circuit_simulations/metadata.json +++ b/demonstrations_v2/tutorial_clifford_circuit_simulations/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-04-12T00:00:00+00:00", - "dateOfLastModification": "2026-01-14T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Devices and Performance" ], diff --git a/demonstrations_v2/tutorial_coherent_vqls/demo.py b/demonstrations_v2/tutorial_coherent_vqls/demo.py index 5852af3bdc..6766ae2177 100644 --- a/demonstrations_v2/tutorial_coherent_vqls/demo.py +++ b/demonstrations_v2/tutorial_coherent_vqls/demo.py @@ -200,7 +200,7 @@ """ -import pennylane as qml +import pennylane as qp from pennylane import numpy as np import matplotlib.pyplot as plt @@ -247,16 +247,16 @@ def U_c(): """Unitary matrix rotating the ground state of the ancillary qubits to |sqrt(c)> = U_c |0>.""" # Circuit mapping |00> to sqrt_c[0] |00> + sqrt_c[1] |01> + sqrt_c[2] |10> - qml.RY(-2 * np.arccos(sqrt_c[0]), wires=ancilla_idx) - qml.CRY(-2 * np.arctan(sqrt_c[2] / sqrt_c[1]), wires=[ancilla_idx, ancilla_idx + 1]) - qml.CNOT(wires=[ancilla_idx + 1, ancilla_idx]) + qp.RY(-2 * np.arccos(sqrt_c[0]), wires=ancilla_idx) + qp.CRY(-2 * np.arctan(sqrt_c[2] / sqrt_c[1]), wires=[ancilla_idx, ancilla_idx + 1]) + qp.CNOT(wires=[ancilla_idx + 1, ancilla_idx]) def U_c_dagger(): """Adjoint of U_c.""" - qml.CNOT(wires=[ancilla_idx + 1, ancilla_idx]) - qml.CRY(2 * np.arctan(sqrt_c[2] / sqrt_c[1]), wires=[ancilla_idx, ancilla_idx + 1]) - qml.RY(2 * np.arccos(sqrt_c[0]), wires=ancilla_idx) + qp.CNOT(wires=[ancilla_idx + 1, ancilla_idx]) + qp.CRY(2 * np.arctan(sqrt_c[2] / sqrt_c[1]), wires=[ancilla_idx, ancilla_idx + 1]) + qp.RY(2 * np.arccos(sqrt_c[0]), wires=ancilla_idx) ############################################################################## @@ -269,11 +269,11 @@ def U_c_dagger(): def CA_all(): """Controlled application of all the unitary components A_l of the problem matrix A.""" # Controlled-A_1 - qml.CNOT(wires=[ancilla_idx, 0]) - qml.CZ(wires=[ancilla_idx, 1]) + qp.CNOT(wires=[ancilla_idx, 0]) + qp.CZ(wires=[ancilla_idx, 1]) # Controlled-A2 - qml.CNOT(wires=[ancilla_idx + 1, 0]) + qp.CNOT(wires=[ancilla_idx + 1, 0]) ############################################################################## @@ -284,7 +284,7 @@ def U_b(): """Unitary matrix rotating the system ground state to the problem vector |b> = U_b |0>.""" for idx in range(n_qubits): - qml.Hadamard(wires=idx) + qp.Hadamard(wires=idx) ############################################################################## @@ -308,11 +308,11 @@ def variational_block(weights): """Variational circuit mapping the ground state |0> to the ansatz state |x>.""" # We first prepare an equal superposition of all the states of the computational basis for idx in range(n_qubits): - qml.Hadamard(wires=idx) + qp.Hadamard(wires=idx) # A very minimal variational circuit for idx, element in enumerate(weights): - qml.RY(element, wires=idx) + qp.RY(element, wires=idx) ############################################################################## @@ -357,25 +357,25 @@ def full_circuit(weights): # To evaluate the two probabilities appearing on the right hand side of the previous equation # we initialize a ``default.qubit`` device and we define two different ``qnode`` circuits. -dev = qml.device("default.qubit", wires=tot_qubits) +dev = qp.device("default.qubit", wires=tot_qubits) -@qml.qnode(dev, interface="autograd") +@qp.qnode(dev, interface="autograd") def global_ground(weights): # Circuit gates full_circuit(weights) # Projector on the global ground state P = np.zeros((2 ** tot_qubits, 2 ** tot_qubits)) P[0, 0] = 1.0 - return qml.expval(qml.Hermitian(P, wires=range(tot_qubits))) + return qp.expval(qp.Hermitian(P, wires=range(tot_qubits))) -@qml.qnode(dev, interface="autograd") +@qp.qnode(dev, interface="autograd") def ancilla_ground(weights): # Circuit gates full_circuit(weights) # Projector on the ground state of the ancillary system P_anc = np.zeros((2 ** m, 2 ** m)) P_anc[0, 0] = 1.0 - return qml.expval(qml.Hermitian(P_anc, wires=range(n_qubits, tot_qubits))) + return qp.expval(qp.Hermitian(P_anc, wires=range(n_qubits, tot_qubits))) ############################################################################## @@ -399,7 +399,7 @@ def cost(weights): ############################################################################## # To minimize the cost function we use the gradient-descent optimizer. -opt = qml.GradientDescentOptimizer(eta) +opt = qp.GradientDescentOptimizer(eta) ############################################################################## # We initialize the variational weights with random parameters (with a fixed seed). @@ -485,10 +485,10 @@ def cost(weights): # For this task, we initialize a new PennyLane device and define the associated # QNode. -dev_x = qml.device("default.qubit", wires=n_qubits) +dev_x = qp.device("default.qubit", wires=n_qubits) -@qml.set_shots(n_shots) -@qml.qnode(dev_x, interface="autograd") +@qp.set_shots(n_shots) +@qp.qnode(dev_x, interface="autograd") def prepare_and_sample(weights): # Variational circuit generating a guess for the solution vector |x> @@ -497,7 +497,7 @@ def prepare_and_sample(weights): # We assume that the system is measured in the computational basis. # Therefore, sampling from the device will give us a value of 0 or 1 for each qubit (n_qubits) # this will be repeated for the total number of shots provided (n_shots). - return qml.sample() + return qp.sample() ############################################################################## diff --git a/demonstrations_v2/tutorial_coherent_vqls/metadata.json b/demonstrations_v2/tutorial_coherent_vqls/metadata.json index f9b2f2c63a..38cb71b50d 100644 --- a/demonstrations_v2/tutorial_coherent_vqls/metadata.json +++ b/demonstrations_v2/tutorial_coherent_vqls/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2019-11-06T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_constant_depth_mps_prep/demo.py b/demonstrations_v2/tutorial_constant_depth_mps_prep/demo.py index 7fb9eb8944..5a078f43ba 100644 --- a/demonstrations_v2/tutorial_constant_depth_mps_prep/demo.py +++ b/demonstrations_v2/tutorial_constant_depth_mps_prep/demo.py @@ -153,7 +153,7 @@ import matplotlib.pyplot as plt from matplotlib.patches import FancyBboxPatch -import pennylane as qml +import pennylane as qp def A(g): @@ -310,7 +310,7 @@ def label_fn(self, *_, **__): return f"$U^{{({self.wires[1]})}}$" -qml.QubitUnitary.label = label_fn +qp.QubitUnitary.label = label_fn def sequential_preparation(g, wires): @@ -322,34 +322,34 @@ def sequential_preparation(g, wires): phys_wires = wires[1:-1] # Prepare bond qubits in the Bell state (|00>+|11>)/sqrt(2) - qml.Hadamard(bond0) - qml.CNOT([bond0, bond1]) + qp.Hadamard(bond0) + qp.CNOT([bond0, bond1]) # Apply unitary U to second bond qubit and each physical qubit for phys_wire in phys_wires: - u = qml.QubitUnitary(U, wires=[bond1, phys_wire]) + u = qp.QubitUnitary(U, wires=[bond1, phys_wire]) def project_measure(wire_0, wire_1): """Measure two qubits in the Bell basis and postselect on (|00>+|11>)/sqrt(2).""" # Move bond qubits from Bell basis to computational basis - qml.CNOT([wire_0, wire_1]) - qml.Hadamard(wire_0) + qp.CNOT([wire_0, wire_1]) + qp.Hadamard(wire_0) # Measure in computational basis and postselect |00> - qml.measure(wire_0, postselect=0) - qml.measure(wire_1, postselect=0) + qp.measure(wire_0, postselect=0) + qp.measure(wire_1, postselect=0) -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") -@qml.qnode(dev) +@qp.qnode(dev) def sequential_circuit(N, g): """Run the preparation circuit and projectively measure the bond qubits.""" wires = list(range(N + 2)) sequential_preparation(g, wires) project_measure(0, N + 1) - return qml.probs(wires=wires[1 : N + 1]) + return qp.probs(wires=wires[1 : N + 1]) ###################################################################### @@ -357,7 +357,7 @@ def sequential_circuit(N, g): # against it. For now, let's draw it. N = 7 -_ = qml.draw_mpl(sequential_circuit)(N, g) +_ = qp.draw_mpl(sequential_circuit)(N, g) ###################################################################### # The sequential preparation circuit already uses mid-circuit measurements, as is visible @@ -466,9 +466,9 @@ def sequential_circuit(N, g): def fuse(wire_0, wire_1): """Measure two qubits in the Bell basis and return the outcome encoded in two bits.""" - qml.CNOT([wire_0, wire_1]) - qml.Hadamard(wire_0) - return np.array([qml.measure(w) for w in [wire_0, wire_1]]) + qp.CNOT([wire_0, wire_1]) + qp.Hadamard(wire_0) + return np.array([qp.measure(w) for w in [wire_0, wire_1]]) ###################################################################### @@ -491,13 +491,13 @@ def two_qubit_mps_by_fusion(g): # MPS already, the test measurement would just be :math:`\langle 00 | Z_0| 00\rangle=1.` -@qml.qnode(qml.device("default.qubit", wires=6)) +@qp.qnode(qp.device("default.qubit", wires=6)) def prepare_and_unprepare(g): two_qubit_mps_by_fusion(g) # The bond qubits for a sequential preparation are just 0 and 5 # The bond qubits 2 and 3 have been measured out in the fusion protocol - qml.adjoint(sequential_preparation)(g, [0, 1, 4, 5]) - return qml.expval(qml.PauliZ(1)) + qp.adjoint(sequential_preparation)(g, [0, 1, 4, 5]) + return qp.expval(qp.PauliZ(1)) test = prepare_and_unprepare(g) @@ -582,12 +582,12 @@ def push_and_correct(op_id, phys_wires): w = phys_wires[0] # Apply Z if input is Z or Y - qml.cond(op_id[0], qml.Z)(w) + qp.cond(op_id[0], qp.Z)(w) # Apply Y if input is X or Y - qml.cond(op_id[1], qml.Y)(w) + qp.cond(op_id[1], qp.Y)(w) # Apply X on other physical sites if input is X or Y for i in phys_wires[1:]: - qml.cond(op_id[1], qml.X)(i) + qp.cond(op_id[1], qp.X)(i) # Push through Y if input is X or Y return np.array([op_id[1], op_id[1]]) @@ -662,9 +662,9 @@ def xor(op_id_0, op_id_1): def correct_end_bond(bond_idx, op_id): """Perform a correction on the end bond site.""" # Apply Z if correction op is Z or Y - qml.cond(op_id[0], qml.Z)(bond_idx) + qp.cond(op_id[0], qp.Z)(bond_idx) # Apply X if correction op is X or Y - qml.cond(op_id[1], qml.X)(bond_idx) + qp.cond(op_id[1], qp.X)(bond_idx) def constant_depth(N, g, q): @@ -710,10 +710,10 @@ def constant_depth_ansatz(N, g, q): return sum(map(list, phys_wires), start=[]) -@qml.qnode(dev) +@qp.qnode(dev) def constant_depth_circuit(N, g, q): phys_wires = constant_depth_ansatz(N, g, q) - return qml.probs(wires=phys_wires) + return qp.probs(wires=phys_wires) ###################################################################### @@ -728,7 +728,7 @@ def constant_depth_circuit(N, g, q): N = 9 q = 3 g = -0.8 -fig, ax = qml.draw_mpl(constant_depth_circuit)(N, g, q) +fig, ax = qp.draw_mpl(constant_depth_circuit)(N, g, q) # Cosmetics options = { diff --git a/demonstrations_v2/tutorial_constant_depth_mps_prep/metadata.json b/demonstrations_v2/tutorial_constant_depth_mps_prep/metadata.json index 96cffe0ff4..a864cc1300 100644 --- a/demonstrations_v2/tutorial_constant_depth_mps_prep/metadata.json +++ b/demonstrations_v2/tutorial_constant_depth_mps_prep/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-10-09T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Computing", "Algorithms" diff --git a/demonstrations_v2/tutorial_contextuality/demo.py b/demonstrations_v2/tutorial_contextuality/demo.py index 4771bf6e24..33bf28dcd0 100644 --- a/demonstrations_v2/tutorial_contextuality/demo.py +++ b/demonstrations_v2/tutorial_contextuality/demo.py @@ -174,7 +174,7 @@ import jax import jax.numpy as jnp -import pennylane as qml +import pennylane as qp import numpy as np jax.config.update("jax_platform_name", "cpu") np.random.seed(666) # seed used for random functions @@ -415,11 +415,11 @@ def generate_data(N): def input_prep(alpha): # This ensures the prepared state has =0 - qml.Hadamard(wires=0) - qml.Hadamard(wires=1) - qml.Hadamard(wires=2) - qml.RY(alpha[0], wires=0) - qml.RY(alpha[0] + np.pi, wires=1) + qp.Hadamard(wires=0) + qp.Hadamard(wires=1) + qp.Hadamard(wires=2) + qp.RY(alpha[0], wires=0) + qp.RY(alpha[0] + np.pi, wires=1) ###################################################################### @@ -450,9 +450,9 @@ def swap_rot(weights, wires): """ bias-invariant unitary with swap matrix as generator """ - qml.PauliRot(weights, "XX", wires=wires) - qml.PauliRot(weights, "YY", wires=wires) - qml.PauliRot(weights, "ZZ", wires=wires) + qp.PauliRot(weights, "XX", wires=wires) + qp.PauliRot(weights, "YY", wires=wires) + qp.PauliRot(weights, "ZZ", wires=wires) def param_unitary(weights): @@ -461,10 +461,10 @@ def param_unitary(weights): """ for b in range(blocks): for q in range(3): - qml.RZ(weights[b, q], wires=q) - qml.PauliRot(weights[b, 3], "ZZ", wires=[0, 1]) - qml.PauliRot(weights[b, 4], "ZZ", wires=[0, 2]) - qml.PauliRot(weights[b, 5], "ZZ", wires=[1, 2]) + qp.RZ(weights[b, q], wires=q) + qp.PauliRot(weights[b, 3], "ZZ", wires=[0, 1]) + qp.PauliRot(weights[b, 4], "ZZ", wires=[0, 2]) + qp.PauliRot(weights[b, 5], "ZZ", wires=[1, 2]) swap_rot(weights[b, 6], wires=[0, 1]) swap_rot(weights[b, 7], wires=[1, 2]) swap_rot(weights[b, 8], wires=[0, 2]) @@ -475,16 +475,16 @@ def data_encoding(x): S_x^1 in paper """ for q in range(3): - qml.RZ(x[q], wires=q) + qp.RZ(x[q], wires=q) def data_encoding_pairs(x): """ S_x^2 in paper """ - qml.PauliRot(x[0] * x[1], "ZZ", wires=[0, 1]) - qml.PauliRot(x[1] * x[2], "ZZ", wires=[1, 2]) - qml.PauliRot(x[0] * x[2], "ZZ", wires=[0, 2]) + qp.PauliRot(x[0] * x[1], "ZZ", wires=[0, 1]) + qp.PauliRot(x[1] * x[2], "ZZ", wires=[1, 2]) + qp.PauliRot(x[0] * x[2], "ZZ", wires=[0, 2]) def bias_inv_layer(weights, x): @@ -507,14 +507,14 @@ def bias_inv_layer(weights, x): # define our quantum model. # -dev = qml.device("default.qubit", wires=3) +dev = qp.device("default.qubit", wires=3) -@qml.qnode(dev) +@qp.qnode(dev) def model(weights, x): input_prep(weights[2 * layers + 1, 0]) # alpha is stored in the weights array bias_inv_layer(weights, x) - return [qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)), qml.expval(qml.PauliZ(2))] + return [qp.expval(qp.PauliZ(0)), qp.expval(qp.PauliZ(1)), qp.expval(qp.PauliZ(2))] # jax vectorisation, we vectorise over the data input (the second argument) @@ -534,20 +534,20 @@ def generic_layer(weights, x): x1 = jnp.array([x[0, 0], x[1, 1], x[2, 2]]) x2 = jnp.array(([x[0, 1] - x[0, 2], x[1, 2] - x[1, 0], x[2, 0] - x[2, 1]])) for l in range(0, 2 * layers, 2): - qml.StronglyEntanglingLayers(weights[l], wires=range(3)) + qp.StronglyEntanglingLayers(weights[l], wires=range(3)) data_encoding(x1) - qml.StronglyEntanglingLayers(weights[l + 1], wires=range(3)) + qp.StronglyEntanglingLayers(weights[l + 1], wires=range(3)) data_encoding_pairs(x2) - qml.StronglyEntanglingLayers(weights[2 * layers], wires=range(3)) + qp.StronglyEntanglingLayers(weights[2 * layers], wires=range(3)) -dev = qml.device("default.qubit", wires=3) +dev = qp.device("default.qubit", wires=3) -@qml.qnode(dev) +@qp.qnode(dev) def generic_model(weights, x): generic_layer(weights, x) - return [qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)), qml.expval(qml.PauliZ(2))] + return [qp.expval(qp.PauliZ(0)), qp.expval(qp.PauliZ(1)), qp.expval(qp.PauliZ(2))] vmodel_generic = jax.vmap(generic_model, (None, 0)) diff --git a/demonstrations_v2/tutorial_contextuality/metadata.json b/demonstrations_v2/tutorial_contextuality/metadata.json index 87e3d9744b..9271f7302a 100644 --- a/demonstrations_v2/tutorial_contextuality/metadata.json +++ b/demonstrations_v2/tutorial_contextuality/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-09-06T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Machine Learning" ], diff --git a/demonstrations_v2/tutorial_data_reuploading_classifier/demo.py b/demonstrations_v2/tutorial_data_reuploading_classifier/demo.py index ef1c11b69c..b1ab82a0ec 100644 --- a/demonstrations_v2/tutorial_data_reuploading_classifier/demo.py +++ b/demonstrations_v2/tutorial_data_reuploading_classifier/demo.py @@ -174,7 +174,7 @@ --------------------------------------------------- """ -import pennylane as qml +import pennylane as qp from pennylane import numpy as np from pennylane.optimize import AdamOptimizer, GradientDescentOptimizer @@ -257,11 +257,11 @@ def density_matrix(state): # Simple classifier with data reloading and fidelity loss # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -dev = qml.device("lightning.qubit", wires=1) +dev = qp.device("lightning.qubit", wires=1) # Install any pennylane-plugin to run on some particular backend -@qml.qnode(dev) +@qp.qnode(dev) def qcircuit(params, x, y): """A variational quantum circuit representing the Universal classifier. @@ -274,9 +274,9 @@ def qcircuit(params, x, y): float: fidelity between output state and input """ for p in params: - qml.Rot(*x, wires=0) - qml.Rot(*p, wires=0) - return qml.expval(qml.Hermitian(y, wires=[0])) + qp.Rot(*x, wires=0) + qp.Rot(*p, wires=0) + return qp.expval(qp.Hermitian(y, wires=[0])) def cost(params, x, y, state_labels=None): diff --git a/demonstrations_v2/tutorial_data_reuploading_classifier/metadata.json b/demonstrations_v2/tutorial_data_reuploading_classifier/metadata.json index 2fca1ef7e1..7a8234862e 100644 --- a/demonstrations_v2/tutorial_data_reuploading_classifier/metadata.json +++ b/demonstrations_v2/tutorial_data_reuploading_classifier/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2019-10-11T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Machine Learning" ], diff --git a/demonstrations_v2/tutorial_diffable-mitigation/demo.py b/demonstrations_v2/tutorial_diffable-mitigation/demo.py index bc7b6d67e4..25f722103a 100644 --- a/demonstrations_v2/tutorial_diffable-mitigation/demo.py +++ b/demonstrations_v2/tutorial_diffable-mitigation/demo.py @@ -43,7 +43,7 @@ We start by initializing a noisy device using a noise model with :class:`~.pennylane.DepolarizingChannel` errors: """ -import pennylane as qml +import pennylane as qp import pennylane.numpy as np from pennylane.noise import mitigate_with_zne @@ -53,22 +53,22 @@ np.random.seed(1234) # Describe noise model -fcond = qml.noise.wires_in(range(n_wires)) -noise = qml.noise.partial_wires(qml.DepolarizingChannel, 0.05) -noise_model = qml.NoiseModel({fcond: noise}) +fcond = qp.noise.wires_in(range(n_wires)) +noise = qp.noise.partial_wires(qp.DepolarizingChannel, 0.05) +noise_model = qp.NoiseModel({fcond: noise}) # Load devices -dev_ideal = qml.device("default.mixed", wires=n_wires) -dev_noisy = qml.add_noise(dev_ideal, noise_model=noise_model) +dev_ideal = qp.device("default.mixed", wires=n_wires) +dev_noisy = qp.add_noise(dev_ideal, noise_model=noise_model) ############################################################################## # We are going to use the transverse field Ising model Hamiltonian :math:`H = - \sum_i X_i X_{i+1} + 0.5 \sum_i Z_i` as our observable: coeffs = [1.0] * (n_wires - 1) + [0.5] * n_wires -observables = [qml.PauliX(i) @ qml.PauliX(i + 1) for i in range(n_wires - 1)] -observables += [qml.PauliZ(i) for i in range(n_wires)] +observables = [qp.PauliX(i) @ qp.PauliX(i + 1) for i in range(n_wires - 1)] +observables += [qp.PauliZ(i) for i in range(n_wires)] -H = qml.Hamiltonian(coeffs, observables) +H = qp.Hamiltonian(coeffs, observables) ############################################################################## @@ -81,12 +81,12 @@ w2 = np.ones((n_layers, n_wires - 1, 2), requires_grad=True) def qfunc(w1, w2): - qml.SimplifiedTwoDesign(w1, w2, wires=range(n_wires)) - return qml.expval(H) + qp.SimplifiedTwoDesign(w1, w2, wires=range(n_wires)) + return qp.expval(H) -qnode_ideal = qml.QNode(qfunc, dev_ideal) -qnode_noisy = qml.QNode(qfunc, dev_noisy) -qnode_noisy = qml.transforms.decompose(qnode_noisy, gate_set = ["RY", "CZ"]) +qnode_ideal = qp.QNode(qfunc, dev_ideal) +qnode_noisy = qp.QNode(qfunc, dev_noisy) +qnode_noisy = qp.transforms.decompose(qnode_noisy, gate_set = ["RY", "CZ"]) ############################################################################## # We can then simply transform the noisy QNode :math:`f^{⚡}` with :func:`~.pennylane.noise.mitigate_with_zne` to generate :math:`\tilde{f}.` @@ -96,8 +96,8 @@ def qfunc(w1, w2): qnode_mitigated = mitigate_with_zne(qnode_noisy, scale_factors=scale_factors, - folding=qml.noise.fold_global, - extrapolate=qml.noise.richardson_extrapolate, + folding=qp.noise.fold_global, + extrapolate=qp.noise.richardson_extrapolate, ) print("Ideal QNode: ", qnode_ideal(w1, w2)) @@ -110,7 +110,7 @@ def qfunc(w1, w2): # # The cool thing about this new mitigated QNode is that it is still differentiable! That is, we can compute its gradient as usual: -grad = qml.grad(qnode_mitigated)(w1, w2) +grad = qp.grad(qnode_mitigated)(w1, w2) print(grad[0]) print(grad[1]) @@ -136,7 +136,7 @@ def qfunc(w1, w2): scale_factors = [1, 2, 3] folded_res = [ - qml.noise.fold_global(qnode_noisy, lambda_)(w1, w2) for lambda_ in scale_factors + qp.noise.fold_global(qnode_noisy, lambda_)(w1, w2) for lambda_ in scale_factors ] ideal_res = qnode_ideal(w1, w2) @@ -184,7 +184,7 @@ def qfunc(w1, w2): def VQE_run(cost_fn, max_iter, stepsize=0.1): """VQE Optimization loop""" - opt = qml.AdamOptimizer(stepsize=stepsize) + opt = qp.AdamOptimizer(stepsize=stepsize) # fixed initial guess w1 = np.ones((n_wires), requires_grad=True) @@ -209,7 +209,7 @@ def VQE_run(cost_fn, max_iter, stepsize=0.1): energy_noisy = VQE_run(qnode_noisy, max_iter) energy_mitigated = VQE_run(qnode_mitigated, max_iter) -energy_exact = np.min(np.linalg.eigvalsh(qml.matrix(H))) +energy_exact = np.min(np.linalg.eigvalsh(qp.matrix(H))) plt.figure(figsize=(8, 5)) plt.plot(energy_noisy, ".--", label="VQE E_noisy") diff --git a/demonstrations_v2/tutorial_diffable-mitigation/metadata.json b/demonstrations_v2/tutorial_diffable-mitigation/metadata.json index fa5ce11a7b..785352f272 100644 --- a/demonstrations_v2/tutorial_diffable-mitigation/metadata.json +++ b/demonstrations_v2/tutorial_diffable-mitigation/metadata.json @@ -8,7 +8,7 @@ "executable_stable": false, "executable_latest": false, "dateOfPublication": "2022-08-22T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_diffable_shadows/demo.py b/demonstrations_v2/tutorial_diffable_shadows/demo.py index 94a7aacef4..08d59950e6 100644 --- a/demonstrations_v2/tutorial_diffable_shadows/demo.py +++ b/demonstrations_v2/tutorial_diffable_shadows/demo.py @@ -89,26 +89,26 @@ PennyLane implementation ------------------------ -There are two ways of computing expectation values with classical shadows in PennyLane. The first is to return :func:`qml.shadow_expval ` directly from the qnode. +There are two ways of computing expectation values with classical shadows in PennyLane. The first is to return :func:`qp.shadow_expval ` directly from the qnode. This has the advantage that it preserves the typical PennyLane syntax *and* is differentiable. """ -import pennylane as qml +import pennylane as qp import pennylane.numpy as np from matplotlib import pyplot as plt from pennylane import classical_shadow, shadow_expval, ClassicalShadow np.random.seed(666) -H = qml.Hamiltonian([1., 1.], [qml.PauliZ(0) @ qml.PauliZ(1), qml.PauliX(0) @ qml.PauliX(1)]) +H = qp.Hamiltonian([1., 1.], [qp.PauliZ(0) @ qp.PauliZ(1), qp.PauliX(0) @ qp.PauliX(1)]) -dev = qml.device("default.qubit", wires=range(2)) -@qml.set_shots(10000) -@qml.qnode(dev, interface="autograd") +dev = qp.device("default.qubit", wires=range(2)) +@qp.set_shots(10000) +@qp.qnode(dev, interface="autograd") def qnode(x, H): - qml.Hadamard(0) - qml.CNOT((0,1)) - qml.RX(x, wires=0) + qp.Hadamard(0) + qp.CNOT((0,1)) + qp.RX(x, wires=0) return shadow_expval(H) x = np.array(0.5, requires_grad=True) @@ -116,27 +116,27 @@ def qnode(x, H): ############################################################################## # Compute expectation values and derivatives thereof in the common way in PennyLane. -print(qnode(x, H), qml.grad(qnode)(x, H)) +print(qnode(x, H), qp.grad(qnode)(x, H)) ############################################################################## -# Each call of :func:`qml.shadow_expval ` performs the number of shots dictated by the device. -# So to avoid unnecessary device executions you can provide a list of observables to :func:`qml.shadow_expval `. +# Each call of :func:`qp.shadow_expval ` performs the number of shots dictated by the device. +# So to avoid unnecessary device executions you can provide a list of observables to :func:`qp.shadow_expval `. -Hs = [H, qml.PauliX(0), qml.PauliY(0), qml.PauliZ(0)] +Hs = [H, qp.PauliX(0), qp.PauliY(0), qp.PauliZ(0)] print(qnode(x, Hs)) -print(qml.jacobian(qnode)(x, Hs)) +print(qp.jacobian(qnode)(x, Hs)) ############################################################################## # Alternatively, you can compute expectation values by first performing the shadow measurement and then perform classical post-processing using the :class:`~.pennylane.ClassicalShadow` # class methods. -dev = qml.device("default.qubit", wires=range(2)) -@qml.set_shots(1000) -@qml.qnode(dev, interface="autograd") +dev = qp.device("default.qubit", wires=range(2)) +@qp.set_shots(1000) +@qp.qnode(dev, interface="autograd") def qnode(x): - qml.Hadamard(0) - qml.CNOT((0,1)) - qml.RX(x, wires=0) + qp.Hadamard(0) + qp.CNOT((0,1)) + qp.RX(x, wires=0) return classical_shadow(wires=range(2)) bits, recipes = qnode(0.5) @@ -147,12 +147,12 @@ def qnode(x): # After recording these ``T=1000`` quantum measurements, we can post-process the results to arbitrary local expectation values of Pauli strings. # For example, we can compute the expectation value of a Pauli string -print(shadow.expval(qml.PauliX(0) @ qml.PauliX(1))) +print(shadow.expval(qp.PauliX(0) @ qp.PauliX(1))) ############################################################################## # or of a Hamiltonian: -H = qml.Hamiltonian([1., 1.], [qml.PauliZ(0) @ qml.PauliZ(1), qml.PauliX(0) @ qml.PauliX(1)]) +H = qp.Hamiltonian([1., 1.], [qp.PauliZ(0) @ qp.PauliZ(1), qp.PauliX(0) @ qp.PauliX(1)]) print(shadow.expval(H)) ############################################################################## @@ -187,19 +187,19 @@ def rmsd(x, y): x = np.arange(2*n_wires, dtype="float64") def circuit(): for i in range(n_wires): - qml.RY(x[i], i) + qp.RY(x[i], i) for i in range(n_wires-1): - qml.CNOT((i, i+1)) + qp.CNOT((i, i+1)) for i in range(n_wires): - qml.RY(x[i+n_wires], i) + qp.RY(x[i+n_wires], i) -obs = qml.PauliX(0) @ qml.PauliZ(3) @ qml.PauliX(6) @ qml.PauliZ(7) +obs = qp.PauliX(0) @ qp.PauliZ(3) @ qp.PauliX(6) @ qp.PauliZ(7) -dev_ideal = qml.device("default.qubit", wires=range(n_wires)) -@qml.qnode(dev_ideal, interface="autograd") +dev_ideal = qp.device("default.qubit", wires=range(n_wires)) +@qp.qnode(dev_ideal, interface="autograd") def qnode_ideal(): circuit() - return qml.expval(obs) + return qp.expval(obs) exact = qnode_ideal() @@ -212,19 +212,19 @@ def qnode_ideal(): for shots in shotss: for _ in range(10): # repeating experiment 10 times to obtain averages and standard deviations - dev = qml.device("default.qubit", wires=range(10)) + dev = qp.device("default.qubit", wires=range(10)) - @qml.set_shots(shots) - @qml.qnode(dev, interface="autograd") + @qp.set_shots(shots) + @qp.qnode(dev, interface="autograd") def qnode_finite(): circuit() - return qml.expval(obs) + return qp.expval(obs) - @qml.set_shots(shots) - @qml.qnode(dev, interface="autograd") + @qp.set_shots(shots) + @qp.qnode(dev, interface="autograd") def qnode_shadow(): circuit() - return qml.shadow_expval(obs) + return qp.shadow_expval(obs) finite.append(rmsd(qnode_finite(), exact)) shadow.append(rmsd(qnode_shadow(), exact)) @@ -267,7 +267,7 @@ def qnode_shadow(): # Create all combinations of possible Pauli products P_i P_j P_k.... for wires w for obs in product( - *[[qml.PauliX, qml.PauliY, qml.PauliZ] for _ in range(len(w))] + *[[qp.PauliX, qp.PauliY, qp.PauliZ] for _ in range(len(w))] ): # Perform tensor product (((P_i @ P_j) @ P_k ) @ ....) observables.append(reduce(lambda a, b: a @ b, [ob(wire) for ob, wire in zip(obs, w)])) @@ -281,28 +281,28 @@ def qnode_shadow(): # groups. We need this number to make a fair comparison with classical shadows as we allow for only ``T/n_groups`` shots per group, such that # the total number of shots is the same as for the classical shadow execution. We again compare both approaches. -n_groups = len(qml.pauli.group_observables(all_observables)) +n_groups = len(qp.pauli.group_observables(all_observables)) -dev_ideal = qml.device("default.qubit", wires=range(n)) +dev_ideal = qp.device("default.qubit", wires=range(n)) x = np.random.rand(n*2) def circuit(): for i in range(n): - qml.RX(x[i], i) + qp.RX(x[i], i) for i in range(n): - qml.CNOT((i, (i+1)%n)) + qp.CNOT((i, (i+1)%n)) for i in range(n): - qml.RY(x[i+n], i) + qp.RY(x[i+n], i) for i in range(n): - qml.CNOT((i, (i+1)%n)) + qp.CNOT((i, (i+1)%n)) -@qml.qnode(dev_ideal, interface="autograd") +@qp.qnode(dev_ideal, interface="autograd") def qnode_ideal(): circuit() - return qml.expval(H) + return qp.expval(H) exact = qnode_ideal() finite = [] @@ -311,30 +311,30 @@ def qnode_ideal(): for shots in shotss: # random Hamiltonian with all q-local observables coeffs = np.random.rand(len(all_observables)) - H = qml.Hamiltonian(coeffs, all_observables, grouping_type="qwc") + H = qp.Hamiltonian(coeffs, all_observables, grouping_type="qwc") - @qml.qnode(dev_ideal, interface="autograd") + @qp.qnode(dev_ideal, interface="autograd") def qnode_ideal(): circuit() - return qml.expval(H) + return qp.expval(H) exact = qnode_ideal() for _ in range(10): - dev = qml.device("default.qubit", wires=range(5)) + dev = qp.device("default.qubit", wires=range(5)) - @qml.set_shots(shots) - @qml.qnode(dev, interface="autograd") + @qp.set_shots(shots) + @qp.qnode(dev, interface="autograd") def qnode_finite(): circuit() - return qml.expval(H) + return qp.expval(H) - dev = qml.device("default.qubit", wires=range(5)) - @qml.set_shots(shots*n_groups) - @qml.qnode(dev, interface="autograd") + dev = qp.device("default.qubit", wires=range(5)) + @qp.set_shots(shots*n_groups) + @qp.qnode(dev, interface="autograd") def qnode_shadow(): circuit() - return qml.shadow_expval(H) + return qp.shadow_expval(H) finite.append(rmsd(qnode_finite(), exact)) shadow.append(rmsd(qnode_shadow(), exact)) @@ -368,9 +368,9 @@ def qnode_shadow(): coordinates = np.array([[-0.0399, -0.0038, 0.0], [1.5780, 0.8540, 0.0], [2.7909, -0.5159, 0.0]]) basis_set = "sto-3g" -molecule = qml.qchem.Molecule(symbols, coordinates, basis_name=basis_set) +molecule = qp.qchem.Molecule(symbols, coordinates, basis_name=basis_set) -H, n_wires = qml.qchem.molecular_hamiltonian( +H, n_wires = qp.qchem.molecular_hamiltonian( molecule, active_electrons=4, active_orbitals=4, @@ -379,9 +379,9 @@ def qnode_shadow(): ) coeffs, obs = H.terms() -H_qwc = qml.Hamiltonian(coeffs, obs, grouping_type="qwc") +H_qwc = qp.Hamiltonian(coeffs, obs, grouping_type="qwc") -groups = qml.pauli.group_observables(obs) +groups = qp.pauli.group_observables(obs) n_groups = len(groups) print(f"number of ops in H: {len(obs)}, number of qwc groups: {n_groups}") print(f"Each group has sizes {[len(_) for _ in groups]}") @@ -390,8 +390,8 @@ def qnode_shadow(): # We use a pre-prepared Ansatz that approximates the :math:`\text{H}_2\text{O}` ground state for the given geometry. You can construct this Ansatz by running VQE, see :doc:`demos/tutorial_vqe.` # We ran this once on an ideal simulator to get the exact result of the energy for the given Ansatz. -singles, doubles = qml.qchem.excitations(electrons=4, orbitals=n_wires) -hf = qml.qchem.hf_state(4, n_wires) +singles, doubles = qp.qchem.excitations(electrons=4, orbitals=n_wires) +hf = qp.qchem.hf_state(4, n_wires) theta = np.array([ 2.20700008e-02, 8.29716448e-02, 2.19227085e+00, 3.19128513e+00, -1.35370403e+00, 6.61615333e-03, 7.40317830e-01, -3.73367029e-01, 4.35206518e-02, @@ -404,7 +404,7 @@ def qnode_shadow(): res_exact = -74.57076341 def circuit(): - qml.AllSinglesDoubles(weights = theta, + qp.AllSinglesDoubles(weights = theta, wires = range(n_wires), hf_state = hf, singles = singles, @@ -422,26 +422,26 @@ def circuit(): for _ in range(10): # execute qwc measurements - dev_finite = qml.device("default.qubit", wires=range(n_wires)) + dev_finite = qp.device("default.qubit", wires=range(n_wires)) - @qml.set_shots(int(shots)) - @qml.qnode(dev_finite, interface="autograd") + @qp.set_shots(int(shots)) + @qp.qnode(dev_finite, interface="autograd") def qnode_finite(H): circuit() - return qml.expval(H) + return qp.expval(H) - with qml.Tracker(dev_finite) as tracker_finite: + with qp.Tracker(dev_finite) as tracker_finite: res_finite = qnode_finite(H_qwc) # execute shadows measurements - dev_shadow = qml.device("default.qubit", wires=range(n_wires)) - @qml.set_shots(int(shots)*n_groups) - @qml.qnode(dev_shadow, interface="autograd") + dev_shadow = qp.device("default.qubit", wires=range(n_wires)) + @qp.set_shots(int(shots)*n_groups) + @qp.qnode(dev_shadow, interface="autograd") def qnode(): circuit() return classical_shadow(wires=range(n_wires)) - with qml.Tracker(dev_shadow) as tracker_shadows: + with qp.Tracker(dev_shadow) as tracker_shadows: bits, recipes = qnode() shadow = ClassicalShadow(bits, recipes) diff --git a/demonstrations_v2/tutorial_diffable_shadows/metadata.json b/demonstrations_v2/tutorial_diffable_shadows/metadata.json index 8260976e50..ba1605a888 100644 --- a/demonstrations_v2/tutorial_diffable_shadows/metadata.json +++ b/demonstrations_v2/tutorial_diffable_shadows/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2022-10-07T00:00:00+00:00", - "dateOfLastModification": "2026-03-27T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Algorithms", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_differentiable_HF/demo.py b/demonstrations_v2/tutorial_differentiable_HF/demo.py index 0d89ef58b5..6e240fc392 100644 --- a/demonstrations_v2/tutorial_differentiable_HF/demo.py +++ b/demonstrations_v2/tutorial_differentiable_HF/demo.py @@ -15,7 +15,7 @@ In this tutorial, you will learn how to use PennyLane's differentiable Hartree-Fock solver -[#arrazola2021]_. The quantum chemistry module in PennyLane, :mod:`qml.qchem `, +[#arrazola2021]_. The quantum chemistry module in PennyLane, :mod:`qp.qchem `, provides built-in methods for constructing atomic and molecular orbitals, building Fock matrices and solving the self-consistent field equations to obtain optimized orbitals which can be used to construct fully-differentiable @@ -99,7 +99,7 @@ For the hydrogen molecule we have """ -import pennylane as qml +import pennylane as qp import numpy as np import jax import jax.numpy as jnp @@ -117,18 +117,18 @@ # nuclear coordinates. To do that, we create a molecule object that stores all the molecular # parameters needed to perform a Hartree-Fock calculation. -mol = qml.qchem.Molecule(symbols, geometry) +mol = qp.qchem.Molecule(symbols, geometry) ############################################################################## # The Hartree-Fock energy can now be computed with the # :func:`~.pennylane.qchem.hf_energy` function which is a function transform -qml.qchem.hf_energy(mol)() +qp.qchem.hf_energy(mol)() ############################################################################## # We now compute the gradient of the energy with respect to the nuclear coordinates -jax.grad(qml.qchem.hf_energy(mol), argnums=0)(geometry, mol.coeff, mol.alpha) +jax.grad(qp.qchem.hf_energy(mol), argnums=0)(geometry, mol.coeff, mol.alpha) ############################################################################## # The obtained gradients are equal or very close to zero because the geometry we used here has been @@ -180,13 +180,13 @@ # are those of the hydrogen atoms by default and are therefore treated as differentiable parameters # by PennyLane. -qml.qchem.overlap_integral(S1, S2)() +qp.qchem.overlap_integral(S1, S2)() ############################################################################## # You can verify that the overlap integral between two identical atomic orbitals is equal to one. # We can now compute the gradient of the overlap integral with respect to the orbital centres -jax.grad(qml.qchem.overlap_integral(S1, S2))(geometry, mol.coeff, mol.alpha) +jax.grad(qp.qchem.overlap_integral(S1, S2))(geometry, mol.coeff, mol.alpha) ############################################################################## # Can you explain why some of the computed gradients are zero? @@ -227,7 +227,7 @@ # plane. n = 30 # number of grid points along each axis -qml.qchem.hf_energy(mol)() +qp.qchem.hf_energy(mol)() mol.mo_coefficients = mol.mo_coefficients.T mo = mol.molecular_orbital(0) x, y = np.meshgrid(np.linspace(-2, 2, n), @@ -251,7 +251,7 @@ # over molecular orbitals that can be used to construct the molecular Hamiltonian with the # :func:`~.pennylane.qchem.molecular_hamiltonian` function. -hamiltonian, qubits = qml.qchem.molecular_hamiltonian(mol) +hamiltonian, qubits = qp.qchem.molecular_hamiltonian(mol) print(hamiltonian) ############################################################################## @@ -263,15 +263,15 @@ # to construct the exact ground state. The second set contains the nuclear coordinates of the # hydrogen atoms. -dev = qml.device("default.qubit", wires=4) +dev = qp.device("default.qubit", wires=4) def energy(): - @qml.qnode(dev, interface="jax") + @qp.qnode(dev, interface="jax") def circuit(*args): - qml.BasisState(np.array([1, 1, 0, 0]), wires=range(4)) - qml.DoubleExcitation(*args[0], wires=[0, 1, 2, 3]) - mol = qml.qchem.Molecule(symbols, geometry, alpha=args[3], coeff=args[2]) - H = qml.qchem.molecular_hamiltonian(mol, args=args[1:])[0] - return qml.expval(H) + qp.BasisState(np.array([1, 1, 0, 0]), wires=range(4)) + qp.DoubleExcitation(*args[0], wires=[0, 1, 2, 3]) + mol = qp.qchem.Molecule(symbols, geometry, alpha=args[3], coeff=args[2]) + H = qp.qchem.molecular_hamiltonian(mol, args=args[1:])[0] + return qp.expval(H) return circuit ############################################################################## @@ -288,7 +288,7 @@ def circuit(*args): [0.1, 0.0, 0.672943567415407]]) for n in range(36): - mol = qml.qchem.Molecule(symbols, geometry) + mol = qp.qchem.Molecule(symbols, geometry) args = [circuit_param, geometry, mol.coeff, mol.alpha] # gradient for circuit parameters g_param = jax.grad(energy(), argnums = 0)(*args) @@ -330,12 +330,12 @@ def circuit(*args): # initial value of the circuit parameter circuit_param = jnp.array([0.0]) -mol = qml.qchem.Molecule(symbols, geometry, coeff=coeff, alpha=alpha) +mol = qp.qchem.Molecule(symbols, geometry, coeff=coeff, alpha=alpha) args = [circuit_param, geometry, coeff, alpha] for n in range(36): args = [circuit_param, geometry, coeff, alpha] - mol = qml.qchem.Molecule(symbols, geometry, alpha=alpha, coeff=coeff) + mol = qp.qchem.Molecule(symbols, geometry, alpha=alpha, coeff=coeff) # gradient for circuit parameters g_param = jax.grad(energy(), argnums=[0, 1, 2, 3])(*args)[0] diff --git a/demonstrations_v2/tutorial_differentiable_HF/metadata.json b/demonstrations_v2/tutorial_differentiable_HF/metadata.json index 471c04820f..45f5ab1d7a 100644 --- a/demonstrations_v2/tutorial_differentiable_HF/metadata.json +++ b/demonstrations_v2/tutorial_differentiable_HF/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2022-05-09T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Chemistry" ], diff --git a/demonstrations_v2/tutorial_dmet_embedding/demo.py b/demonstrations_v2/tutorial_dmet_embedding/demo.py index 576bdee246..16a33ce7fb 100644 --- a/demonstrations_v2/tutorial_dmet_embedding/demo.py +++ b/demonstrations_v2/tutorial_dmet_embedding/demo.py @@ -431,7 +431,6 @@ # # .. code-block:: python # -# import pennylane as qml # from pennylane.qchem import one_particle, two_particle, observable # # one_elec = one_particle(h1[0]) diff --git a/demonstrations_v2/tutorial_dmet_embedding/metadata.json b/demonstrations_v2/tutorial_dmet_embedding/metadata.json index 4359895016..8265c1895f 100644 --- a/demonstrations_v2/tutorial_dmet_embedding/metadata.json +++ b/demonstrations_v2/tutorial_dmet_embedding/metadata.json @@ -8,7 +8,7 @@ "executable_stable": false, "executable_latest": false, "dateOfPublication": "2025-11-25T00:00:00+00:00", - "dateOfLastModification": "2025-11-25T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Quantum Chemistry", "How-to" diff --git a/demonstrations_v2/tutorial_doubly_stochastic/demo.py b/demonstrations_v2/tutorial_doubly_stochastic/demo.py index 10707aa772..83e2820577 100644 --- a/demonstrations_v2/tutorial_doubly_stochastic/demo.py +++ b/demonstrations_v2/tutorial_doubly_stochastic/demo.py @@ -117,7 +117,7 @@ # Let's use the ``lightning.qubit`` simulator for both the analytic gradient, # as well as the estimated gradient using number of shots :math:`N\in\{1, 100\}.` -import pennylane as qml +import pennylane as qp import numpy as np from pennylane import numpy as pnp @@ -131,11 +131,11 @@ eta = 0.01 steps = 200 -dev_analytic = qml.device("lightning.qubit", wires=num_wires) -dev_stochastic = qml.device("lightning.qubit", wires=num_wires) +dev_analytic = qp.device("lightning.qubit", wires=num_wires) +dev_stochastic = qp.device("lightning.qubit", wires=num_wires) ############################################################################## -# We can use ``qml.Hermitian`` to directly specify that we want to measure +# We can use ``qp.Hermitian`` to directly specify that we want to measure # the expectation value of the matrix :math:`H:` H = np.array([[8, 4, 0, -6], [4, 0, 4, 0], [0, 4, 8, 0], [-6, 0, 0, 0]]) @@ -143,16 +143,16 @@ def circuit(params): StronglyEntanglingLayers(weights=params, wires=[0, 1]) - return expval(qml.Hermitian(H, wires=[0, 1])) + return expval(qp.Hermitian(H, wires=[0, 1])) ############################################################################## # Now, we create three QNodes, each corresponding to a device above, # and optimize them using gradient descent via the parameter-shift rule. -qnode_analytic = qml.QNode(circuit, dev_analytic, interface="autograd", diff_method="parameter-shift") -qnode_stochastic = qml.QNode(circuit, dev_stochastic, interface="autograd", diff_method="parameter-shift") -qnode_stochastic = qml.set_shots(1000)(qnode_stochastic) +qnode_analytic = qp.QNode(circuit, dev_analytic, interface="autograd", diff_method="parameter-shift") +qnode_stochastic = qp.QNode(circuit, dev_stochastic, interface="autograd", diff_method="parameter-shift") +qnode_stochastic = qp.set_shots(1000)(qnode_stochastic) param_shape = StronglyEntanglingLayers.shape(n_layers=num_layers, n_wires=num_wires) init_params = pnp.random.uniform(low=0, high=2 * np.pi, size=param_shape, requires_grad=True) @@ -161,7 +161,7 @@ def circuit(params): cost_GD = [] params_GD = init_params -opt = qml.GradientDescentOptimizer(eta) +opt = qp.GradientDescentOptimizer(eta) for _ in range(steps): cost_GD.append(qnode_analytic(params_GD)) @@ -171,21 +171,21 @@ def circuit(params): cost_SGD1 = [] params_SGD1 = init_params -opt = qml.GradientDescentOptimizer(eta) +opt = qp.GradientDescentOptimizer(eta) for _ in range(steps): - cost_SGD1.append(qml.set_shots(qnode_stochastic, shots=1)(params_SGD1)) - params_SGD1 = opt.step(qml.set_shots(qnode_stochastic, shots=1), params_SGD1) + cost_SGD1.append(qp.set_shots(qnode_stochastic, shots=1)(params_SGD1)) + params_SGD1 = opt.step(qp.set_shots(qnode_stochastic, shots=1), params_SGD1) # Optimizing using stochastic gradient descent with shots=100 cost_SGD100 = [] params_SGD100 = init_params -opt = qml.GradientDescentOptimizer(eta) +opt = qp.GradientDescentOptimizer(eta) for _ in range(steps): - cost_SGD100.append(qml.set_shots(qnode_stochastic, shots=100)(params_SGD100)) - params_SGD100 = opt.step(qml.set_shots(qnode_stochastic, shots=100), params_SGD100) + cost_SGD100.append(qp.set_shots(qnode_stochastic, shots=100)(params_SGD100)) + params_SGD100 = opt.step(qp.set_shots(qnode_stochastic, shots=100), params_SGD100) ############################################################################## # Note that in the latter two cases we are sampling from an unbiased @@ -290,16 +290,16 @@ def circuit(params): ) -@qml.qnode(dev_stochastic, interface="autograd") +@qp.qnode(dev_stochastic, interface="autograd") def circuit(params, n=None): StronglyEntanglingLayers(weights=params, wires=[0, 1]) idx = np.random.choice(np.arange(5), size=n, replace=False) A = np.sum(terms[idx], axis=0) - return expval(qml.Hermitian(A, wires=[0, 1])) + return expval(qp.Hermitian(A, wires=[0, 1])) def loss(params, shots=None): - return 4 + (5 / 1) * qml.set_shots(circuit, shots=shots)(params, n=1) + return 4 + (5 / 1) * qp.set_shots(circuit, shots=shots)(params, n=1) ############################################################################## @@ -307,7 +307,7 @@ def loss(params, shots=None): cost = [] params = init_params -opt = qml.GradientDescentOptimizer(0.005) +opt = qp.GradientDescentOptimizer(0.005) for _ in range(250): cost.append(loss(params, shots=100)) @@ -365,13 +365,13 @@ def moving_average(data, n=3): cost = [] params = init_params -opt = qml.GradientDescentOptimizer(0.005) +opt = qp.GradientDescentOptimizer(0.005) for i in range(250): n = min(i // 25 + 1, 5) def loss(params, shots=None): - return 4 + (5 / n) * qml.set_shots(circuit, shots=shots)(params, n=n) + return 4 + (5 / n) * qp.set_shots(circuit, shots=shots)(params, n=n) cost.append(loss(params, shots=int(1 + (n - 1) ** 2))) params = opt.step(loss, params, shots=int(1 + (n - 1) ** 2)) diff --git a/demonstrations_v2/tutorial_doubly_stochastic/metadata.json b/demonstrations_v2/tutorial_doubly_stochastic/metadata.json index e0084b4976..5467305b99 100644 --- a/demonstrations_v2/tutorial_doubly_stochastic/metadata.json +++ b/demonstrations_v2/tutorial_doubly_stochastic/metadata.json @@ -6,7 +6,7 @@ } ], "dateOfPublication": "2019-10-16T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_dqi/demo.py b/demonstrations_v2/tutorial_dqi/demo.py index 78962cf72c..df69189e13 100644 --- a/demonstrations_v2/tutorial_dqi/demo.py +++ b/demonstrations_v2/tutorial_dqi/demo.py @@ -46,7 +46,7 @@ initial plot to see how well DQI performs. """ -import pennylane as qml +import pennylane as qp from pennylane import numpy as pnp import matplotlib.pyplot as plt @@ -214,12 +214,12 @@ def w_k_optimal(m, l): ###################################################################### # We will need two qubits to encode :math:`w_k` for :math:`k=0,1,2`. The state is given by a weighted superposition # of the basis states :math:`|00\rangle, |01\rangle, |10\rangle`. -# To prepare it, we will use ``qml.StatePrep`` in our ``embed_weights`` function shown below. +# To prepare it, we will use ``qp.StatePrep`` in our ``embed_weights`` function shown below. # def embed_weights(w_k, weight_register): """Prepares the weight register in superposition of given coefficients.""" - qml.StatePrep(w_k, wires=weight_register, pad_with=0) + qp.StatePrep(w_k, wires=weight_register, pad_with=0) ###################################################################### @@ -283,7 +283,7 @@ def embed_weights(w_k, weight_register): # ``SCS``, is not discussed here. However, it’s worth noting that it is composed of a two-qubit gate # followed by :math:`k-1` three-qubit gates (further details can be found in [#Bartschi2019]_). # Let’s now implement this algorithm in the ``prepare_dicke_state`` function and then use it twice in -# a controlled way via ``qml.ctrl()`` in the quantum function ``weight_error_prep``, after preparing +# a controlled way via ``qp.ctrl()`` in the quantum function ``weight_error_prep``, after preparing # the weight register. To verify that this step was implemented correctly, # we will output the resultant quantum state printed in a nice form using the auxiliary ``format_state_vector`` function. # We should expect :math:`\binom{5}{2}` and :math:`\binom{5}{1}` states in the error register @@ -315,15 +315,15 @@ def SCS(m, k): m = m + num_weight_qubits - 1 # Two-qubit gate - qml.CNOT(wires=[m - 1, m]) - qml.CRY(2 * pnp.arccos(pnp.sqrt(1 / m_angle)), wires=[m, m - 1]) - qml.CNOT(wires=[m - 1, m]) + qp.CNOT(wires=[m - 1, m]) + qp.CRY(2 * pnp.arccos(pnp.sqrt(1 / m_angle)), wires=[m, m - 1]) + qp.CNOT(wires=[m - 1, m]) # k-1 three-qubit gates for l in range(2, k + 1): - qml.CNOT(wires=[m - l, m]) - qml.ctrl(qml.RY, (m, m - l + 1))(2 * pnp.arccos(pnp.sqrt(l / m_angle)), wires=m - l) - qml.CNOT(wires=[m - l, m]) + qp.CNOT(wires=[m - l, m]) + qp.ctrl(qp.RY, (m, m - l + 1))(2 * pnp.arccos(pnp.sqrt(l / m_angle)), wires=m - l) + qp.CNOT(wires=[m - l, m]) @@ -332,7 +332,7 @@ def prepare_dicke_state(m, k): # Prepares input state for wire_idx in range(m - k + num_weight_qubits, m + num_weight_qubits): - qml.X(wires=wire_idx) + qp.X(wires=wire_idx) # Applies the SCS unitaries for i in reversed(range(k + 1, m + 1)): @@ -341,10 +341,10 @@ def prepare_dicke_state(m, k): SCS(i, i - 1) -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") -@qml.qnode(dev) +@qp.qnode(dev) def weight_error_prep(m, n, l): """Quantum circuit preparing weight and error registers.""" @@ -352,10 +352,10 @@ def weight_error_prep(m, n, l): embed_weights(w_k, weight_register) # Prepare Dicke states conditioned on k values - qml.ctrl(prepare_dicke_state, weight_register, control_values=(0,1))(m, k=1) - qml.ctrl(prepare_dicke_state, weight_register, control_values=(1,0))(m, k=2) + qp.ctrl(prepare_dicke_state, weight_register, control_values=(0,1))(m, k=1) + qp.ctrl(prepare_dicke_state, weight_register, control_values=(1,0))(m, k=2) - return qml.state() + return qp.state() raw_state_vector = weight_error_prep(m, n, l) @@ -403,8 +403,8 @@ def uncompute_weight(m, k): for j in range(len(binary_string_weight)): bit = int(binary_string_weight[j]) if bit == 1: - qml.ctrl( - qml.X, + qp.ctrl( + qp.X, m_register, control_values=bit_strings_dicke[i] )(weight_register[j]) @@ -423,15 +423,15 @@ def uncompute_weight(m, k): def phase_Z(v): """Imparts a phase (-1)^{vy}.""" for i in range(len(v)): - qml.cond(v[i],qml.Z)(wires=i + num_weight_qubits) + qp.cond(v[i],qp.Z)(wires=i + num_weight_qubits) -@qml.qnode(dev) +@qp.qnode(dev) def encode_v(m, n, l): """Quantum circuit uncomputing weight register and encoding vector of constraints.""" # Load the previous state - qml.StatePrep(raw_state_vector, wires=range(0, m + num_weight_qubits)) + qp.StatePrep(raw_state_vector, wires=range(0, m + num_weight_qubits)) # Uncompute weight register uncompute_weight(m, k=1) @@ -440,7 +440,7 @@ def encode_v(m, n, l): # Impart phase phase_Z(v) - return qml.state() + return qp.state() raw_state_vector = encode_v(m, n, l) @@ -469,20 +469,20 @@ def B_T_multiplication(B_T, n_register): for row_index, row in enumerate(B_T): for col_index, element in enumerate(row): if element == 1: - qml.CNOT(wires=[m_register[col_index], n_register[row_index]]) + qp.CNOT(wires=[m_register[col_index], n_register[row_index]]) -@qml.qnode(dev) +@qp.qnode(dev) def syndrome_prep(m, n, l): """Quantum circuit preparing syndrome register.""" # Load the previous state - qml.StatePrep(raw_state_vector, wires=range(0, m + num_weight_qubits)) + qp.StatePrep(raw_state_vector, wires=range(0, m + num_weight_qubits)) # Compute s = B^T y into the syndrome register B_T_multiplication(B_T, n_register) - return qml.state() + return qp.state() raw_state_vector = syndrome_prep(m, n, l) @@ -557,21 +557,21 @@ def syndrome_LUT(parity_check_matrix_T): # Generate the lookup table decoding_table = syndrome_LUT(B_T) -@partial(qml.set_shots, shots=n_samples) -@qml.qnode(dev) +@partial(qp.set_shots, shots=n_samples) +@qp.qnode(dev) def decoding(m, n, l): """Quantum circuit decoding and uncomputing error register""" # Load the previous state - qml.StatePrep(raw_state_vector, wires=range(0, m + n + num_weight_qubits)) + qp.StatePrep(raw_state_vector, wires=range(0, m + n + num_weight_qubits)) # Uncompute syndrome register using a Lookup table for syndrome, error in decoding_table: for i in range(len(error)): if error[i] == 1: - qml.ctrl(qml.X, n_register, control_values=syndrome)(m_register[i]) + qp.ctrl(qp.X, n_register, control_values=syndrome)(m_register[i]) - return qml.counts() + return qp.counts() pprint(decoding(m, n, l)) @@ -587,8 +587,8 @@ def decoding(m, n, l): # Let's write a ``DQI`` quantum function containing all the steps of the algorithm previously described. # -@partial(qml.set_shots, shots=n_samples) -@qml.qnode(dev) +@partial(qp.set_shots, shots=n_samples) +@qp.qnode(dev) def DQI(m, n, l): """Quantum circuit implementing the DQI algorithm to solve max-XORSAT.""" @@ -596,8 +596,8 @@ def DQI(m, n, l): embed_weights(w_k,weight_register) # Prepare Dicke states conditioned on k values - qml.ctrl(prepare_dicke_state, weight_register, control_values=(0,1))(m, k=1) - qml.ctrl(prepare_dicke_state, weight_register, control_values=(1,0))(m, k=2) + qp.ctrl(prepare_dicke_state, weight_register, control_values=(0,1))(m, k=1) + qp.ctrl(prepare_dicke_state, weight_register, control_values=(1,0))(m, k=2) # Uncompute weight register uncompute_weight(m, k=1) @@ -614,13 +614,13 @@ def DQI(m, n, l): syndrome, error = row for i in range(len(error)): if error[i] == 1: - qml.ctrl(qml.X, n_register, control_values=syndrome)(m_register[i]) + qp.ctrl(qp.X, n_register, control_values=syndrome)(m_register[i]) # Apply Hadamard transform for wire in n_register: - qml.Hadamard(wire) + qp.Hadamard(wire) - return qml.counts(wires=n_register) + return qp.counts(wires=n_register) ###################################################################### # We will collect samples, calculate their objective values, and build a histogram to compare with diff --git a/demonstrations_v2/tutorial_dqi/metadata.json b/demonstrations_v2/tutorial_dqi/metadata.json index 34f6495641..62e5111835 100644 --- a/demonstrations_v2/tutorial_dqi/metadata.json +++ b/demonstrations_v2/tutorial_dqi/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2025-09-19T10:00:00+00:00", - "dateOfLastModification": "2026-01-27T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Algorithms" ], diff --git a/demonstrations_v2/tutorial_eqnn_force_field/demo.py b/demonstrations_v2/tutorial_eqnn_force_field/demo.py index 2185f2f9be..fa11e9e5b5 100644 --- a/demonstrations_v2/tutorial_eqnn_force_field/demo.py +++ b/demonstrations_v2/tutorial_eqnn_force_field/demo.py @@ -129,7 +129,7 @@ # -------------------------- # We start by importing the libraries that we will need. -import pennylane as qml +import pennylane as qp import numpy as np import jax @@ -171,10 +171,10 @@ def singlet(wires): # Encode a 2-qubit rotation-invariant initial state, i.e., the singlet state. - qml.Hadamard(wires=wires[0]) - qml.PauliZ(wires=wires[0]) - qml.PauliX(wires=wires[1]) - qml.CNOT(wires=wires) + qp.Hadamard(wires=wires[0]) + qp.PauliZ(wires=wires[0]) + qp.PauliX(wires=wires[1]) + qp.CNOT(wires=wires) ###################################################################### @@ -190,7 +190,7 @@ def singlet(wires): # For this, we have noticed that any rotation on the data level can be parametrized by three angles # :math:`V_g = r(\psi,\theta,\phi),` which can also be used to parametrize the corresponding # single-qubit rotation :math:`\mathcal{R}_g = U(\psi,\theta,\phi),` implemented by the usual -# `qml.rot `__ +# `qp.rot `__ # operation. We choose to encode each atom # twice in parallel, resulting in higher expressivity. We can do so by simply using this encoding scheme twice for each # active atom (the two Hydrogens in our case): @@ -205,7 +205,7 @@ def equivariant_encoding(alpha, data, wires): hamiltonian = jnp.einsum("i,ijk", data, sigmas) # Heisenberg Hamiltonian U = jax.scipy.linalg.expm(-1.0j * alpha * hamiltonian / 2) - qml.QubitUnitary(U, wires=wires, id="E") + qp.QubitUnitary(U, wires=wires, id="E") ###################################################################### @@ -260,16 +260,16 @@ def equivariant_encoding(alpha, data, wires): def trainable_layer(weight, wires): hamiltonian = jnp.einsum("ijk->jk", sigmas_sigmas) U = jax.scipy.linalg.expm(-1.0j * weight * hamiltonian) - qml.QubitUnitary(U, wires=wires, id="U") + qp.QubitUnitary(U, wires=wires, id="U") # Invariant observable Heisenberg = [ - qml.PauliX(0) @ qml.PauliX(1), - qml.PauliY(0) @ qml.PauliY(1), - qml.PauliZ(0) @ qml.PauliZ(1), + qp.PauliX(0) @ qp.PauliX(1), + qp.PauliY(0) @ qp.PauliY(1), + qp.PauliZ(0) @ qp.PauliZ(1), ] -Observable = qml.Hamiltonian(np.ones((3)), Heisenberg) +Observable = qp.Hamiltonian(np.ones((3)), Heisenberg) ###################################################################### # It has been observed that a small amount of **symmetry-breaking** (SB) can improve the convergence @@ -279,7 +279,7 @@ def trainable_layer(weight, wires): def noise_layer(epsilon, wires): for _, w in enumerate(wires): - qml.RZ(epsilon[_], wires=[w]) + qp.RZ(epsilon[_], wires=[w]) ###################################################################### @@ -301,10 +301,10 @@ def noise_layer(epsilon, wires): ################################# -dev = qml.device("default.qubit", wires=num_qubits) +dev = qp.device("default.qubit", wires=num_qubits) -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def vqlm(data, params): weights = params["params"]["weights"] @@ -323,7 +323,7 @@ def vqlm(data, params): # Reuploading model for d in range(D): - qml.Barrier() + qp.Barrier() for b in range(B): # Even layer @@ -346,7 +346,7 @@ def vqlm(data, params): wires=[i], ) - return qml.expval(Observable) + return qp.expval(Observable) ###################################################################### diff --git a/demonstrations_v2/tutorial_eqnn_force_field/metadata.json b/demonstrations_v2/tutorial_eqnn_force_field/metadata.json index 0d932f545a..bd870d81e5 100644 --- a/demonstrations_v2/tutorial_eqnn_force_field/metadata.json +++ b/demonstrations_v2/tutorial_eqnn_force_field/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-03-12T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Machine Learning", "Quantum Chemistry" diff --git a/demonstrations_v2/tutorial_equivariant_graph_embedding/demo.py b/demonstrations_v2/tutorial_equivariant_graph_embedding/demo.py index b013b83540..7ae2183bcf 100644 --- a/demonstrations_v2/tutorial_equivariant_graph_embedding/demo.py +++ b/demonstrations_v2/tutorial_equivariant_graph_embedding/demo.py @@ -209,7 +209,7 @@ def permute(A, permutation): # -import pennylane as qml +import pennylane as qp def perm_equivariant_embedding(A, betas, gammas): """ @@ -225,17 +225,17 @@ def perm_equivariant_embedding(A, betas, gammas): # initialise in the plus state for i in range(n_nodes): - qml.Hadamard(i) + qp.Hadamard(i) for l in range(n_layers): for i in range(n_nodes): for j in range(i): # factor of 2 due to definition of gate - qml.IsingZZ(2*gammas[l]*A[i,j], wires=[i,j]) + qp.IsingZZ(2*gammas[l]*A[i,j], wires=[i,j]) for i in range(n_nodes): - qml.RX(A[i,i]*betas[l], wires=i) + qp.RX(A[i,i]*betas[l], wires=i) ###################################################################### # We can use this ansatz in a circuit. @@ -243,22 +243,22 @@ def perm_equivariant_embedding(A, betas, gammas): n_qubits = 5 n_layers = 2 -dev = qml.device("lightning.qubit", wires=n_qubits) +dev = qp.device("lightning.qubit", wires=n_qubits) -@qml.qnode(dev) +@qp.qnode(dev) def eqc(adjacency_matrix, observable, trainable_betas, trainable_gammas): """Circuit that uses the permutation equivariant embedding""" perm_equivariant_embedding(adjacency_matrix, trainable_betas, trainable_gammas) - return qml.expval(observable) + return qp.expval(observable) A = create_data_point(n_qubits) betas = rng.random(n_layers) gammas = rng.random(n_layers) -observable = qml.PauliX(0) @ qml.PauliX(1) @ qml.PauliX(3) +observable = qp.PauliX(0) @ qp.PauliX(1) @ qp.PauliX(3) -qml.draw_mpl(eqc, decimals=2)(A, observable, betas, gammas) +qp.draw_mpl(eqc, decimals=2)(A, observable, betas, gammas) plt.show() @@ -294,11 +294,11 @@ def eqc(adjacency_matrix, observable, trainable_betas, trainable_gammas): # # As a result, the final state before measurement is only the same if we # permute the qubits in the same manner that we permute the input adjacency matrix. We could insert a -# permutation operator ``qml.Permute(perm)`` to achieve this, or we simply permute the wires +# permutation operator ``qp.Permute(perm)`` to achieve this, or we simply permute the wires # of the observables! # -observable_perm = qml.PauliX(perm[0]) @ qml.PauliX(perm[1]) @ qml.PauliX(perm[3]) +observable_perm = qp.PauliX(perm[0]) @ qp.PauliX(perm[1]) @ qp.PauliX(perm[3]) ###################################################################### # Now everything should work out! diff --git a/demonstrations_v2/tutorial_equivariant_graph_embedding/metadata.json b/demonstrations_v2/tutorial_equivariant_graph_embedding/metadata.json index 71bdd65890..1f8aa49f90 100644 --- a/demonstrations_v2/tutorial_equivariant_graph_embedding/metadata.json +++ b/demonstrations_v2/tutorial_equivariant_graph_embedding/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-07-13T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Machine Learning" ], diff --git a/demonstrations_v2/tutorial_error_mitigation/demo.py b/demonstrations_v2/tutorial_error_mitigation/demo.py index 0c0b04cead..8aba4fb173 100644 --- a/demonstrations_v2/tutorial_error_mitigation/demo.py +++ b/demonstrations_v2/tutorial_error_mitigation/demo.py @@ -58,22 +58,22 @@ :class:`NoiseModel `. """ -import pennylane as qml +import pennylane as qp n_wires = 4 # Describe noise model -fcond = qml.noise.wires_in(range(n_wires)) -noise = qml.noise.partial_wires(qml.PhaseDamping, 0.1) -noise_model = qml.NoiseModel({fcond: noise}) +fcond = qp.noise.wires_in(range(n_wires)) +noise = qp.noise.partial_wires(qp.PhaseDamping, 0.1) +noise_model = qp.NoiseModel({fcond: noise}) # Load devices -dev_ideal = qml.device("default.mixed", wires=n_wires) -dev_noisy = qml.add_noise(dev_ideal, noise_model=noise_model) +dev_ideal = qp.device("default.mixed", wires=n_wires) +dev_noisy = qp.add_noise(dev_ideal, noise_model=noise_model) ############################################################################### # In the above, we load a noise-free device ``dev_ideal`` and a noisy device ``dev_noisy``, -# which is constructed from the :func:`qml.add_noise ` +# which is constructed from the :func:`qp.add_noise ` # transform. This transform works by intercepting each circuit executed on the device and # adding the noise to it based on the ``noise_model``. For example, in this case, it will # add :class:`PhaseDamping ` noise channel after every gate in the @@ -106,25 +106,25 @@ # Select template to use within circuit and generate parameters n_layers = 1 -template = qml.SimplifiedTwoDesign +template = qp.SimplifiedTwoDesign weights_shape = template.shape(n_layers, n_wires) w1, w2 = [2 * np.pi * np.random.random(s) for s in weights_shape] def circuit(w1, w2): template(w1, w2, wires=range(n_wires)) - qml.adjoint(template)(w1, w2, wires=range(n_wires)) - return qml.expval(qml.PauliZ(0)) + qp.adjoint(template)(w1, w2, wires=range(n_wires)) + return qp.expval(qp.PauliZ(0)) -ideal_qnode = qml.QNode(circuit, dev_ideal) -noisy_qnode = qml.QNode(circuit, dev_noisy) -noisy_qnode = qml.transforms.decompose(noisy_qnode, gate_set = ["RY", "CZ"]) +ideal_qnode = qp.QNode(circuit, dev_ideal) +noisy_qnode = qp.QNode(circuit, dev_noisy) +noisy_qnode = qp.transforms.decompose(noisy_qnode, gate_set = ["RY", "CZ"]) ############################################################################## # First, we'll visualize the circuit: -print(qml.draw(ideal_qnode, level="device")(w1, w2)) +print(qp.draw(ideal_qnode, level="device")(w1, w2)) ############################################################################## # As expected, executing the circuit on an ideal noise-free device gives a result of ``1``. @@ -205,10 +205,10 @@ def circuit(w1, w2): # :class:`QuantumTape `, which provides a low-level approach for circuit # construction in PennyLane. -circuit = qml.tape.QuantumTape( +circuit = qp.tape.QuantumTape( [ template(w1, w2, wires=range(n_wires)), - qml.adjoint(template(w1, w2, wires=range(n_wires))), + qp.adjoint(template(w1, w2, wires=range(n_wires))), ] ) @@ -223,7 +223,7 @@ def circuit(w1, w2): for s, c in zip(scale_factors, folded_circuits): print(f"Globally-folded circuit with a scale factor of {s}:") - print(qml.drawer.tape_text(c, decimals=2, max_length=80)) + print(qp.drawer.tape_text(c, decimals=2, max_length=80)) ############################################################################## # Although these circuits are a bit deep, if you look carefully, you might be able to convince @@ -265,18 +265,18 @@ def circuit(w1, w2): def executor(circuits, dev=dev_noisy): # Support both a single circuit and multiple circuit execution - circuits = [circuits] if isinstance(circuits, qml.tape.QuantumTape) else circuits + circuits = [circuits] if isinstance(circuits, qp.tape.QuantumTape) else circuits circuits_with_meas = [] # Loop through circuits and add on measurement for c in circuits: - circuit_with_meas = qml.tape.QuantumTape( - c.operations, [qml.expval(qml.PauliZ(0))] + circuit_with_meas = qp.tape.QuantumTape( + c.operations, [qp.expval(qp.PauliZ(0))] ) circuits_with_meas.append(circuit_with_meas) - return qml.execute(circuits_with_meas, dev, diff_method=None) + return qp.execute(circuits_with_meas, dev, diff_method=None) ############################################################################## @@ -383,7 +383,7 @@ def executor(circuits, dev=dev_noisy): for _ in range(3): print( - qml.drawer.tape_text( + qp.drawer.tape_text( folding(circuit, scale_factor=1.1), decimals=2, max_length=80 ) ) @@ -449,8 +449,8 @@ def executor(circuits, dev=dev_noisy): n_wires = 4 -dev_ideal = qml.device("default.qubit", wires=n_wires) -dev_noisy = qml.device( +dev_ideal = qp.device("default.qubit", wires=n_wires) +dev_noisy = qp.device( "qiskit.aer", wires=n_wires, noise_model=noise_model, @@ -491,14 +491,14 @@ def executor(circuits, dev=dev_noisy): # Define ansatz circuit def qchem_circuit(phi): - qml.PauliX(wires=0) - qml.PauliX(wires=1) - qml.DoubleExcitation(phi, wires=range(n_wires)) - return qml.expval(H) + qp.PauliX(wires=0) + qp.PauliX(wires=1) + qp.DoubleExcitation(phi, wires=range(n_wires)) + return qp.expval(H) - ideal_energy = qml.QNode(qchem_circuit, dev_ideal) - noisy_energy = qml.QNode(qchem_circuit, dev_noisy) - noisy_energy = qml.transforms.decompose(noisy_energy, gate_set=["RX", "RY", "RZ", "CNOT"]) + ideal_energy = qp.QNode(qchem_circuit, dev_ideal) + noisy_energy = qp.QNode(qchem_circuit, dev_noisy) + noisy_energy = qp.transforms.decompose(noisy_energy, gate_set=["RX", "RY", "RZ", "CNOT"]) ideal_energies.append(ideal_energy(phi)) noisy_energies.append(noisy_energy(phi)) @@ -521,12 +521,12 @@ def qchem_circuit(phi): # Define ansatz circuit ops = [ - qml.PauliX(0), - qml.PauliX(1), - qml.DoubleExcitation(phi, wires=range(n_wires)), + qp.PauliX(0), + qp.PauliX(1), + qp.DoubleExcitation(phi, wires=range(n_wires)), ] - circuit = qml.tape.QuantumTape(ops) - [circuit], _ = qml.transforms.decompose(circuit, gate_set=["RX", "RY", "RZ", "CNOT"]) + circuit = qp.tape.QuantumTape(ops) + [circuit], _ = qp.transforms.decompose(circuit, gate_set=["RX", "RY", "RZ", "CNOT"]) # Define custom executor that expands Hamiltonian measurement # into a linear combination of tensor products of Pauli @@ -534,16 +534,16 @@ def qchem_circuit(phi): def executor(circuit): # Add Hamiltonian measurement to circuit - circuit_with_meas = qml.tape.QuantumTape(circuit.operations, [qml.expval(H)], shots=10000) + circuit_with_meas = qp.tape.QuantumTape(circuit.operations, [qp.expval(H)], shots=10000) # Expand Hamiltonian measurement into tensor product of # of Pauli operators. We get a list of circuits to execute # and a postprocessing function to combine the results into # a single number. - circuits, postproc = qml.transforms.split_non_commuting( + circuits, postproc = qp.transforms.split_non_commuting( circuit_with_meas, grouping_strategy=None ) - circuits_executed = qml.execute(circuits, dev_noisy, diff_method=None) + circuits_executed = qp.execute(circuits, dev_noisy, diff_method=None) return postproc(circuits_executed) mitig_energy = execute_with_zne(circuit, executor, scale_noise=fold_global) diff --git a/demonstrations_v2/tutorial_error_mitigation/metadata.json b/demonstrations_v2/tutorial_error_mitigation/metadata.json index 0b73d001f7..fcc85ed848 100644 --- a/demonstrations_v2/tutorial_error_mitigation/metadata.json +++ b/demonstrations_v2/tutorial_error_mitigation/metadata.json @@ -11,7 +11,7 @@ "executable_stable": false, "executable_latest": false, "dateOfPublication": "2021-11-29T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Algorithms", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_error_prop/demo.py b/demonstrations_v2/tutorial_error_prop/demo.py index be29149f88..8dabb7355b 100644 --- a/demonstrations_v2/tutorial_error_prop/demo.py +++ b/demonstrations_v2/tutorial_error_prop/demo.py @@ -28,19 +28,19 @@ Before we can track the error in our quantum workflow, we need to quantify it. A common method for quantifying the error between operators is to compute the "distance" between them; specifically, the spectral norm of the difference between the operators. We can use the new :class:`~.pennylane.resource.error.SpectralNormError` class to compute and represent this error. -Consider for example, that instead of applying :code:`qml.RX(1.234)` we incur some *rounding* error in the rotation angle; +Consider for example, that instead of applying :code:`qp.RX(1.234)` we incur some *rounding* error in the rotation angle; how much error would the resulting operators have? We can compute this easily with PennyLane: """ -import pennylane as qml +import pennylane as qp from pennylane.resource import SpectralNormError -exact_op = qml.RX(1.234, wires=0) +exact_op = qp.RX(1.234, wires=0) thetas = [1.23, 1.2, 1.0] -ops = [qml.RX(theta, wires=0) for theta in thetas] +ops = [qp.RX(theta, wires=0) for theta in thetas] for approx_op, theta in zip(ops, thetas): error = SpectralNormError.get_error(exact_op, approx_op) @@ -63,10 +63,10 @@ # Let's explicitly compute the error from this algorithm for a simple Hamiltonian: time = 0.1 -Hamiltonian = qml.X(0) + qml.Y(0) +Hamiltonian = qp.X(0) + qp.Y(0) -exact_op = qml.exp(Hamiltonian, 1j * time) # U = e^iHt ~ TrotterProduct(..., order=2) -approx_op = qml.TrotterProduct( # eg: e^iHt ~ e^iXt/2 * e^iYt * e^iXt/2 +exact_op = qp.exp(Hamiltonian, 1j * time) # U = e^iHt ~ TrotterProduct(..., order=2) +approx_op = qp.TrotterProduct( # eg: e^iHt ~ e^iXt/2 * e^iYt * e^iXt/2 Hamiltonian, time, order=2, @@ -84,7 +84,7 @@ # We provide two common methods for bounding the error from literature [#TrotterError]_. # They can be accessed by using :code:`op.error()` and specifying the :code:`method` keyword argument: -op = qml.TrotterProduct(Hamiltonian, time, order=2) +op = qp.TrotterProduct(Hamiltonian, time, order=2) one_norm_error_bound = op.error(method="one-norm-bound") commutator_error_bound = op.error(method="commutator-bound") @@ -112,10 +112,10 @@ from pennylane import numpy as np -op1 = qml.RX(np.pi / 4, 0) -op2 = qml.GlobalPhase(np.pi / 8) @ qml.Hadamard(0) @ qml.T(0) @ qml.Hadamard(0) +op1 = qp.RX(np.pi / 4, 0) +op2 = qp.GlobalPhase(np.pi / 8) @ qp.Hadamard(0) @ qp.T(0) @ qp.Hadamard(0) -np.allclose(qml.matrix(op1), qml.matrix(op2)) +np.allclose(qp.matrix(op1), qp.matrix(op2)) ############################################################################### @@ -148,9 +148,9 @@ def compute_decomposition(phi, wires): num_iterations = int(phi // (np.pi / 4)) # how many rotations of pi/4 to apply global_phase = num_iterations * np.pi / 8 - decomposition = [qml.GlobalPhase(global_phase)] + decomposition = [qp.GlobalPhase(global_phase)] for _ in range(num_iterations): - decomposition += [qml.Hadamard(wires), qml.T(wires), qml.Hadamard(wires)] + decomposition += [qp.Hadamard(wires), qp.T(wires), qp.Hadamard(wires)] return decomposition @@ -170,7 +170,7 @@ def error(self): # we did for Hamiltonian simulation, using :code:`op.error()`. phi = 1.23 -true_op = qml.RX(phi, wires=0) +true_op = qp.RX(phi, wires=0) approx_op = Approximate_RX(phi, wires=0) error_from_theory = approx_op.error() @@ -186,25 +186,25 @@ def error(self): # pieces together in a quantum circuit. PennyLane now automatically tracks and propagates these errors through # the circuit. This means we can write our circuits as usual and get all the benefits of error tracking for free. -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") -@qml.qnode(dev) +@qp.qnode(dev) def circ(H, t, phi1, phi2): - qml.Hadamard(0) - qml.Hadamard(1) + qp.Hadamard(0) + qp.Hadamard(1) # Approx decomposition Approximate_RX(phi1, 0) Approximate_RX(phi2, 1) - qml.CNOT([0, 1]) + qp.CNOT([0, 1]) # Approx time evolution: - qml.TrotterProduct(H, t, order=2) + qp.TrotterProduct(H, t, order=2) # Measurement: - return qml.state() + return qp.state() ############################################################################### @@ -214,7 +214,7 @@ def circ(H, t, phi1, phi2): print("State:") print(circ(Hamiltonian, time, phi1, phi2), "\n") -errors_dict = qml.resource.algo_error(circ)(Hamiltonian, time, phi1, phi2) +errors_dict = qp.resource.algo_error(circ)(Hamiltonian, time, phi1, phi2) error = errors_dict["SpectralNormError"] print("Error:") print(error) diff --git a/demonstrations_v2/tutorial_error_prop/metadata.json b/demonstrations_v2/tutorial_error_prop/metadata.json index 049e58b120..a37ab383c5 100644 --- a/demonstrations_v2/tutorial_error_prop/metadata.json +++ b/demonstrations_v2/tutorial_error_prop/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-05-03T00:00:00+00:00", - "dateOfLastModification": "2026-01-14T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Algorithms", "Quantum Computing", diff --git a/demonstrations_v2/tutorial_expressivity_fourier_series/demo.py b/demonstrations_v2/tutorial_expressivity_fourier_series/demo.py index 3a6c16c711..79295ecfd2 100644 --- a/demonstrations_v2/tutorial_expressivity_fourier_series/demo.py +++ b/demonstrations_v2/tutorial_expressivity_fourier_series/demo.py @@ -138,7 +138,7 @@ # import matplotlib.pyplot as plt -import pennylane as qml +import pennylane as qp from pennylane import numpy as np np.random.seed(42) @@ -273,20 +273,20 @@ def target_function(x): scaling = 1 -dev = qml.device("default.qubit", wires=1) +dev = qp.device("default.qubit", wires=1) def S(x): """Data-encoding circuit block.""" - qml.RX(scaling * x, wires=0) + qp.RX(scaling * x, wires=0) def W(theta): """Trainable circuit block.""" - qml.Rot(theta[0], theta[1], theta[2], wires=0) + qp.Rot(theta[0], theta[1], theta[2], wires=0) -@qml.qnode(dev) +@qp.qnode(dev) def serial_quantum_model(weights, x): for theta in weights[:-1]: @@ -296,7 +296,7 @@ def serial_quantum_model(weights, x): # (L+1)'th unitary W(weights[-1]) - return qml.expval(qml.PauliZ(wires=0)) + return qp.expval(qp.PauliZ(wires=0)) ###################################################################### @@ -338,7 +338,7 @@ def serial_quantum_model(weights, x): # Finally, let's look at the circuit we just created: # -print(qml.draw(serial_quantum_model)(weights, x[-1])) +print(qp.draw(serial_quantum_model)(weights, x[-1])) ###################################################################### @@ -359,7 +359,7 @@ def cost(weights, x, y): max_steps = 50 -opt = qml.AdamOptimizer(0.3) +opt = qp.AdamOptimizer(0.3) batch_size = 25 cst = [cost(weights, x, target_y)] # initial cost @@ -493,17 +493,17 @@ def cost(weights, x, y): n_ansatz_layers = 2 n_qubits = 3 -dev = qml.device("default.qubit", wires=4) +dev = qp.device("default.qubit", wires=4) -@qml.qnode(dev) +@qp.qnode(dev) def ansatz(weights): StronglyEntanglingLayers(weights, wires=range(n_qubits)) - return qml.expval(qml.Identity(wires=0)) + return qp.expval(qp.Identity(wires=0)) weights_ansatz = 2 * np.pi * np.random.random(size=(n_ansatz_layers, n_qubits, 3)) -print(qml.draw(ansatz, level="device")(weights_ansatz)) +print(qp.draw(ansatz, level="device")(weights_ansatz)) ###################################################################### @@ -513,13 +513,13 @@ def ansatz(weights): scaling = 1 r = 3 -dev = qml.device("default.qubit", wires=r) +dev = qp.device("default.qubit", wires=r) def S(x): """Data-encoding circuit block.""" for w in range(r): - qml.RX(scaling * x, wires=w) + qp.RX(scaling * x, wires=w) def W(theta): @@ -527,14 +527,14 @@ def W(theta): StronglyEntanglingLayers(theta, wires=range(r)) -@qml.qnode(dev) +@qp.qnode(dev) def parallel_quantum_model(weights, x): W(weights[0]) S(x) W(weights[1]) - return qml.expval(qml.PauliZ(wires=0)) + return qp.expval(qp.PauliZ(wires=0)) ###################################################################### @@ -573,7 +573,7 @@ def cost(weights, x, y): max_steps = 70 -opt = qml.AdamOptimizer(0.3) +opt = qp.AdamOptimizer(0.3) batch_size = 25 cst = [cost(weights, x, target_y)] # initial cost @@ -675,13 +675,13 @@ def fourier_coefficients(f, K): scaling = 1 n_qubits = 4 -dev = qml.device("default.qubit", wires=n_qubits) +dev = qp.device("default.qubit", wires=n_qubits) def S(x): """Data encoding circuit block.""" for w in range(n_qubits): - qml.RX(scaling * x, wires=w) + qp.RX(scaling * x, wires=w) def W(theta): @@ -689,14 +689,14 @@ def W(theta): BasicEntanglerLayers(theta, wires=range(n_qubits)) -@qml.qnode(dev) +@qp.qnode(dev) def quantum_model(weights, x): W(weights[0]) S(x) W(weights[1]) - return qml.expval(qml.PauliZ(wires=0)) + return qp.expval(qp.PauliZ(wires=0)) ###################################################################### @@ -804,26 +804,26 @@ def f(x): var = 2 n_ansatz_layers = 1 -dev_cv = qml.device("default.gaussian", wires=1) +dev_cv = qp.device("default.gaussian", wires=1) def S(x): - qml.Rotation(x, wires=0) + qp.Rotation(x, wires=0) def W(theta): """Trainable circuit block.""" for r_ in range(n_ansatz_layers): - qml.Displacement(theta[0], theta[1], wires=0) - qml.Squeezing(theta[2], theta[3], wires=0) + qp.Displacement(theta[0], theta[1], wires=0) + qp.Squeezing(theta[2], theta[3], wires=0) -@qml.qnode(dev_cv) +@qp.qnode(dev_cv) def quantum_model(weights, x): W(weights[0]) S(x) W(weights[1]) - return qml.expval(qml.QuadX(wires=0)) + return qp.expval(qp.QuadX(wires=0)) def random_weights(): @@ -840,7 +840,7 @@ def random_weights(): # # .. code-block:: python # -# dev_cv = qml.device('strawberryfields.fock', wires=1, cutoff_dim=50) +# dev_cv = qp.device('strawberryfields.fock', wires=1, cutoff_dim=50) # diff --git a/demonstrations_v2/tutorial_expressivity_fourier_series/metadata.json b/demonstrations_v2/tutorial_expressivity_fourier_series/metadata.json index 00658e5cb1..9f32c76ad4 100644 --- a/demonstrations_v2/tutorial_expressivity_fourier_series/metadata.json +++ b/demonstrations_v2/tutorial_expressivity_fourier_series/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2020-08-24T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Machine Learning" ], diff --git a/demonstrations_v2/tutorial_falqon/demo.py b/demonstrations_v2/tutorial_falqon/demo.py index 4a62edfbcf..e9e3623ff0 100644 --- a/demonstrations_v2/tutorial_falqon/demo.py +++ b/demonstrations_v2/tutorial_falqon/demo.py @@ -108,7 +108,7 @@ # To begin, we import the necessary dependencies: # -import pennylane as qml +import pennylane as qp from pennylane import numpy as np from matplotlib import pyplot as plt from pennylane import qaoa as qaoa @@ -189,7 +189,7 @@ def build_hamiltonian(graph): - H = qml.Hamiltonian([], []) + H = qp.Hamiltonian([], []) # Computes the complement of the graph graph_c = nx.complement(graph) @@ -199,11 +199,11 @@ def build_hamiltonian(graph): for edge in graph_c.edges: i, j = edge if k == i: - H += 1.5 * (qml.PauliY(k) @ qml.PauliZ(j) - qml.PauliY(k)) + H += 1.5 * (qp.PauliY(k) @ qp.PauliZ(j) - qp.PauliY(k)) if k == j: - H += 1.5 * (qml.PauliZ(i) @ qml.PauliY(k) - qml.PauliY(k)) + H += 1.5 * (qp.PauliZ(i) @ qp.PauliY(k) - qp.PauliY(k)) # Adds the terms in the second sum - H += 2 * qml.PauliY(k) + H += 2 * qp.PauliY(k) return H @@ -221,7 +221,7 @@ def build_hamiltonian(graph): # .. code-block:: python # # cost_h, driver_h = qaoa.max_clique(graph, constrained=False) -# comm_h = qml.simplify(1j * qml.commutator(driver_h, cost_h)) +# comm_h = qp.simplify(1j * qp.commutator(driver_h, cost_h)) ###################################################################### # We can now build the FALQON algorithm. Our goal is to evolve some initial state under the Hamiltonian :math:`H,` @@ -230,8 +230,8 @@ def build_hamiltonian(graph): def falqon_layer(beta_k, cost_h, driver_h, delta_t): - qml.ApproxTimeEvolution(cost_h, delta_t, 1) - qml.ApproxTimeEvolution(driver_h, delta_t * beta_k, 1) + qp.ApproxTimeEvolution(cost_h, delta_t, 1) + qp.ApproxTimeEvolution(driver_h, delta_t * beta_k, 1) ###################################################################### @@ -244,8 +244,8 @@ def build_maxclique_ansatz(cost_h, driver_h, delta_t): def ansatz(beta, **kwargs): layers = len(beta) for w in dev.wires: - qml.Hadamard(wires=w) - qml.layer(falqon_layer, layers, beta, cost_h=cost_h, driver_h=driver_h, delta_t=delta_t) + qp.Hadamard(wires=w) + qp.layer(falqon_layer, layers, beta, cost_h=cost_h, driver_h=driver_h, delta_t=delta_t) return ansatz @@ -253,7 +253,7 @@ def ansatz(beta, **kwargs): def expval_circuit(beta, measurement_h): ansatz = build_maxclique_ansatz(cost_h, driver_h, delta_t) ansatz(beta) - return qml.expval(measurement_h) + return qp.expval(measurement_h) ###################################################################### @@ -265,7 +265,7 @@ def expval_circuit(beta, measurement_h): def max_clique_falqon(graph, n, beta_1, delta_t, dev): comm_h = build_hamiltonian(graph) # Builds the commutator cost_h, driver_h = qaoa.max_clique(graph, constrained=False) # Builds H_c and H_d - cost_fn = qml.QNode( + cost_fn = qp.QNode( expval_circuit, dev ) # The ansatz + measurement circuit is executable @@ -298,7 +298,7 @@ def max_clique_falqon(graph, n, beta_1, delta_t, dev): beta_1 = 0.0 delta_t = 0.03 -dev = qml.device("default.qubit", wires=graph.nodes) # Creates a device for the simulation +dev = qp.device("default.qubit", wires=graph.nodes) # Creates a device for the simulation res_beta, res_energies = max_clique_falqon(graph, n, beta_1, delta_t, dev) ###################################################################### @@ -319,11 +319,11 @@ def max_clique_falqon(graph, n, beta_1, delta_t, dev): # We define the following circuit, feeding in the optimal values of :math:`\beta_k:` -@qml.qnode(dev) +@qp.qnode(dev) def prob_circuit(): ansatz = build_maxclique_ansatz(cost_h, driver_h, delta_t) ansatz(res_beta) - return qml.probs(wires=dev.wires) + return qp.probs(wires=dev.wires) ###################################################################### @@ -429,7 +429,7 @@ def prob_circuit(): # demonstration, we set the depth to :math:`5:` depth = 5 -dev = qml.device("default.qubit", wires=new_graph.nodes) +dev = qp.device("default.qubit", wires=new_graph.nodes) # Creates the cost and mixer Hamiltonians cost_h, mixer_h = qaoa.max_clique(new_graph, constrained=False) @@ -444,14 +444,14 @@ def qaoa_layer(gamma, beta): # Creates the full QAOA circuit as an executable cost function def qaoa_circuit(params, **kwargs): for w in dev.wires: - qml.Hadamard(wires=w) - qml.layer(qaoa_layer, depth, params[0], params[1]) + qp.Hadamard(wires=w) + qp.layer(qaoa_layer, depth, params[0], params[1]) -@qml.qnode(dev) +@qp.qnode(dev) def qaoa_expval(params): qaoa_circuit(params) - return qml.expval(cost_h) + return qp.expval(cost_h) ###################################################################### @@ -470,7 +470,7 @@ def qaoa_expval(params): steps = 40 -optimizer = qml.GradientDescentOptimizer() +optimizer = qp.GradientDescentOptimizer() for s in range(steps): params, cost = optimizer.step_and_cost(qaoa_expval, params) @@ -482,10 +482,10 @@ def qaoa_expval(params): # create a bar graph: -@qml.qnode(dev) +@qp.qnode(dev) def prob_circuit(params): qaoa_circuit(params) - return qml.probs(wires=dev.wires) + return qp.probs(wires=dev.wires) probs = prob_circuit(params) diff --git a/demonstrations_v2/tutorial_falqon/metadata.json b/demonstrations_v2/tutorial_falqon/metadata.json index a4ea9f0a7e..542db4ad5f 100644 --- a/demonstrations_v2/tutorial_falqon/metadata.json +++ b/demonstrations_v2/tutorial_falqon/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2021-05-21T00:00:00+00:00", - "dateOfLastModification": "2026-03-27T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_fermionic_operators/demo.py b/demonstrations_v2/tutorial_fermionic_operators/demo.py index 17fbb5ae7f..dae2be7e59 100644 --- a/demonstrations_v2/tutorial_fermionic_operators/demo.py +++ b/demonstrations_v2/tutorial_fermionic_operators/demo.py @@ -133,7 +133,7 @@ # :func:`~.pennylane.qchem.electron_integrals` function. We can build the molecular Hamiltonian for # the hydrogen molecule as an example. We first define the atom types and the atomic coordinates. -import pennylane as qml +import pennylane as qp from jax import numpy as jnp symbols = ["H", "H"] @@ -144,8 +144,8 @@ # second quantized molecular Hamiltonian defined above. We also obtain the core constant, which is # later used to calculate the contribution of the nuclear energy to the Hamiltonian. -mol = qml.qchem.Molecule(symbols, geometry) -core, one, two = qml.qchem.electron_integrals(mol)() +mol = qp.qchem.Molecule(symbols, geometry) +core, one, two = qp.qchem.electron_integrals(mol)() ############################################################################## # These integrals are computed over molecular orbitals. Each molecular orbital contains a pair of @@ -198,7 +198,7 @@ ############################################################################## # We also need to include the contribution of the nuclear energy. -h += np.sum(core * qml.Identity(0)) +h += np.sum(core * qp.Identity(0)) ############################################################################## # This gives us the qubit Hamiltonian which can be used as an input for quantum algorithms. We can diff --git a/demonstrations_v2/tutorial_fermionic_operators/metadata.json b/demonstrations_v2/tutorial_fermionic_operators/metadata.json index f83719b73d..dbb5fef0d9 100644 --- a/demonstrations_v2/tutorial_fermionic_operators/metadata.json +++ b/demonstrations_v2/tutorial_fermionic_operators/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-06-27T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Chemistry" ], diff --git a/demonstrations_v2/tutorial_fixed_depth_hamiltonian_simulation_via_cartan_decomposition/demo.py b/demonstrations_v2/tutorial_fixed_depth_hamiltonian_simulation_via_cartan_decomposition/demo.py index 7031c06a95..02db7f78cf 100644 --- a/demonstrations_v2/tutorial_fixed_depth_hamiltonian_simulation_via_cartan_decomposition/demo.py +++ b/demonstrations_v2/tutorial_fixed_depth_hamiltonian_simulation_via_cartan_decomposition/demo.py @@ -72,7 +72,7 @@ import matplotlib.pyplot as plt import numpy as np -import pennylane as qml +import pennylane as qp from pennylane import X, Y, Z from pennylane.liealg import even_odd_involution, cartan_decomp, horizontal_cartan_subalgebra @@ -86,9 +86,9 @@ gens += [Y(i) @ Y(i+1) for i in range(n_wires-1)] gens += [Z(i) @ Z(i+1) for i in range(n_wires-1)] -H = qml.sum(*gens) +H = qp.sum(*gens) -g = qml.lie_closure(gens) +g = qp.lie_closure(gens) g = [op.pauli_rep for op in g] ############################################################################## @@ -196,8 +196,8 @@ gammas = [np.pi**i % 2 for i in range(1, len(h)+1)] -v = qml.dot(gammas, h) -v_m = qml.matrix(v, wire_order=range(n_wires)) +v = qp.dot(gammas, h) +v_m = qp.matrix(v, wire_order=range(n_wires)) v_m = jnp.array(v_m) @@ -261,16 +261,16 @@ def step(opt_state, theta): ############################################################################## # We can now implement the cost function and find a minimum via gradient descent. -H_m = qml.matrix(H, wire_order=range(n_wires)) +H_m = qp.matrix(H, wire_order=range(n_wires)) H_m = jnp.array(H_m) def K(theta, k): for th, k_j in zip(theta, k): - qml.exp(-1j * th * k_j.operation()) + qp.exp(-1j * th * k_j.operation()) @jax.jit def loss(theta): - K_m = qml.matrix(K, wire_order=range(n_wires))(theta, k) + K_m = qp.matrix(K, wire_order=range(n_wires))(theta, k) A = K_m @ v_m @ K_m.conj().T return jnp.trace(A.conj().T @ H_m).real @@ -288,7 +288,7 @@ def loss(theta): # This gives us the optimal values of the parameters :math:`\theta_\text{opt}` of :math:`K(\theta_\text{opt}) =: K_c.` theta_opt = thetas[-1] -Kc_m = qml.matrix(K, wire_order=range(n_wires))(theta_opt, k) +Kc_m = qp.matrix(K, wire_order=range(n_wires))(theta_opt, k) ############################################################################## # The special element :math:`h_0` from the Cartan subalgebra :math:`\mathfrak{h}` is given by @@ -299,15 +299,15 @@ def loss(theta): h_0_m = Kc_m.conj().T @ H_m @ Kc_m # decompose h_0_m in terms of the basis of h -basis = [qml.matrix(op, wire_order=range(n_wires)) for op in h] -coeffs = qml.pauli.trace_inner_product(h_0_m, basis) +basis = [qp.matrix(op, wire_order=range(n_wires)) for op in h] +coeffs = qp.pauli.trace_inner_product(h_0_m, basis) # ensure that decomposition is correct, i.e. h_0_m is truely an element of just h h_0_m_recomposed = np.sum([c * op for c, op in zip(coeffs, basis)], axis=0) print("Decomposition of h_0 is faithful: ", np.allclose(h_0_m_recomposed, h_0_m, atol=1e-10)) # sanity check that the horizontal CSA is Abelian, i.e. all its elements commute -print("All elements in h commute with each other: ", qml.liealg.check_abelian(h)) +print("All elements in h commute with each other: ", qp.liealg.check_abelian(h)) ############################################################################## @@ -334,16 +334,16 @@ def loss(theta): # t = 1. -U_exact = qml.exp(-1j * t * H) -U_exact_m = qml.matrix(U_exact, wire_order=range(n_wires)) -h_0 = qml.dot(coeffs, h) +U_exact = qp.exp(-1j * t * H) +U_exact_m = qp.matrix(U_exact, wire_order=range(n_wires)) +h_0 = qp.dot(coeffs, h) def U_kak(theta_opt, t): - qml.adjoint(K)(theta_opt, k) - qml.exp(-1j * t * h_0) + qp.adjoint(K)(theta_opt, k) + qp.exp(-1j * t * h_0) K(theta_opt, k) -U_kak_m = qml.matrix(U_kak, wire_order=range(n_wires))(theta_opt, t) +U_kak_m = qp.matrix(U_kak, wire_order=range(n_wires))(theta_opt, t) def trace_distance(A, B): return 1 - np.abs(np.trace(A.conj().T @ B))/len(A) @@ -378,14 +378,14 @@ def trace_distance(A, B): ts = jnp.linspace(1., 5., 10) -Us_exact = jax.vmap(lambda t: qml.matrix(qml.exp(-1j * t * H), wire_order=range(n_wires)))(ts) +Us_exact = jax.vmap(lambda t: qp.matrix(qp.exp(-1j * t * H), wire_order=range(n_wires)))(ts) def Us_kak(t): return Kc_m @ jax.scipy.linalg.expm(-1j * t * h_0_m) @ Kc_m.conj().T Us_kak = jax.vmap(Us_kak)(ts) -Us_trotter5 = jax.vmap(lambda t: qml.matrix(qml.TrotterProduct(H, time=-t, n=5, order=4), wire_order=range(n_wires)))(ts) -Us_trotter50 = jax.vmap(lambda t: qml.matrix(qml.TrotterProduct(H, time=-t, n=50, order=4), wire_order=range(n_wires)))(ts) +Us_trotter5 = jax.vmap(lambda t: qp.matrix(qp.TrotterProduct(H, time=-t, n=5, order=4), wire_order=range(n_wires)))(ts) +Us_trotter50 = jax.vmap(lambda t: qp.matrix(qp.TrotterProduct(H, time=-t, n=50, order=4), wire_order=range(n_wires)))(ts) def compute_res(Us): # vectorized trace inner product diff --git a/demonstrations_v2/tutorial_fixed_depth_hamiltonian_simulation_via_cartan_decomposition/metadata.json b/demonstrations_v2/tutorial_fixed_depth_hamiltonian_simulation_via_cartan_decomposition/metadata.json index d47a5584b4..68775430c4 100644 --- a/demonstrations_v2/tutorial_fixed_depth_hamiltonian_simulation_via_cartan_decomposition/metadata.json +++ b/demonstrations_v2/tutorial_fixed_depth_hamiltonian_simulation_via_cartan_decomposition/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-12-19T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Computing", "Algorithms" diff --git a/demonstrations_v2/tutorial_gaussian_transformation/demo.py b/demonstrations_v2/tutorial_gaussian_transformation/demo.py index 81ea2dff19..a9b8ba5645 100644 --- a/demonstrations_v2/tutorial_gaussian_transformation/demo.py +++ b/demonstrations_v2/tutorial_gaussian_transformation/demo.py @@ -65,7 +65,7 @@ # As before, we import PennyLane, as well as the wrapped version of NumPy provided # by JAX: -import pennylane as qml +import pennylane as qp from jax import numpy as np ############################################################################### @@ -73,7 +73,7 @@ # Because our circuit contains only Gaussian operations, we can make use of the # built-in ``default.gaussian`` device. -dev_gaussian = qml.device("default.gaussian", wires=1) +dev_gaussian = qp.device("default.gaussian", wires=1) ############################################################################### # After initializing the device, we can construct our quantum node. As before, we use the @@ -82,11 +82,11 @@ # device. -@qml.qnode(dev_gaussian) +@qp.qnode(dev_gaussian) def mean_photon_gaussian(mag_alpha, phase_alpha, phi): - qml.Displacement(mag_alpha, phase_alpha, wires=0) - qml.Rotation(phi, wires=0) - return qml.expval(qml.NumberOperator(0)) + qp.Displacement(mag_alpha, phase_alpha, wires=0) + qp.Rotation(phi, wires=0) + return qp.expval(qp.NumberOperator(0)) ############################################################################### diff --git a/demonstrations_v2/tutorial_gaussian_transformation/metadata.json b/demonstrations_v2/tutorial_gaussian_transformation/metadata.json index 9651ab4aba..68a26a2d46 100644 --- a/demonstrations_v2/tutorial_gaussian_transformation/metadata.json +++ b/demonstrations_v2/tutorial_gaussian_transformation/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2019-10-11T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Getting Started" ], diff --git a/demonstrations_v2/tutorial_general_parshift/demo.py b/demonstrations_v2/tutorial_general_parshift/demo.py index 533a6d085f..fe93c33c99 100644 --- a/demonstrations_v2/tutorial_general_parshift/demo.py +++ b/demonstrations_v2/tutorial_general_parshift/demo.py @@ -127,22 +127,22 @@ def random_observable(N, seed): import jax from jax import numpy as np -import pennylane as qml +import pennylane as qp jax.config.update("jax_enable_x64", True) def make_cost(N, seed): """Create a cost function on N qubits with N frequencies.""" - dev = qml.device("default.qubit", wires=N) + dev = qp.device("default.qubit", wires=N) @jax.jit - @qml.qnode(dev, interface="jax") + @qp.qnode(dev, interface="jax") def cost(x): """Cost function on N qubits with N frequencies.""" - qml.StatePrep(random_state(N, seed), wires=dev.wires) + qp.StatePrep(random_state(N, seed), wires=dev.wires) for w in dev.wires: - qml.RZ(x, wires=w, id="x") - return qml.expval(qml.Hermitian(random_observable(N, seed), wires=dev.wires)) + qp.RZ(x, wires=w, id="x") + return qp.expval(qp.Hermitian(random_observable(N, seed), wires=dev.wires)) return cost @@ -264,7 +264,7 @@ def cost(x): fig, axs = plt.subplots(2, len(Ns), figsize=(12, 4.5)) for i, (cost_function, spec) in enumerate(zip(cost_functions, spectra)): # Compute the Fourier coefficients - coeffs = qml.fourier.coefficients(cost_function, 1, len(spec)+2) + coeffs = qp.fourier.coefficients(cost_function, 1, len(spec)+2) # Show the Fourier coefficients bar(coeffs, 1, axs[:, i], show_freqs=True, colour_dict={"real": green, "imag": orange}) axs[0, i].set_title(f"{Ns[i]} qubits") @@ -880,6 +880,6 @@ def finite_diff_second(fun): # .. |shgo| replace:: ``shgo`` # .. _shgo: https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.shgo.html # -# .. |Rotosolve_code| replace:: ``qml.RotosolveOptimizer`` +# .. |Rotosolve_code| replace:: ``qp.RotosolveOptimizer`` # .. _Rotosolve_code: https://pennylane.readthedocs.io/en/stable/code/api/pennylane.RotosolveOptimizer.html # diff --git a/demonstrations_v2/tutorial_general_parshift/metadata.json b/demonstrations_v2/tutorial_general_parshift/metadata.json index d03bd443c7..ef4fa269a8 100644 --- a/demonstrations_v2/tutorial_general_parshift/metadata.json +++ b/demonstrations_v2/tutorial_general_parshift/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2021-08-23T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Optimization" ], From 287f10981cd6438693f1e70d9e8b82603716ba1d Mon Sep 17 00:00:00 2001 From: drdren <104710745+drdren@users.noreply.github.com> Date: Mon, 20 Apr 2026 16:11:48 -0400 Subject: [PATCH 02/10] qml to qp Batch 4 (#1755) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### Before submitting Please complete the following checklist when submitting a PR: - [ ] Ensure that your tutorial executes correctly, and conforms to the guidelines specified in the [README](https://github.com/PennyLaneAI/demos/blob/master/README.md). - [ ] Remember to do a grammar check of the content you include. - [ ] All tutorials conform to [PEP8 standards](https://www.python.org/dev/peps/pep-0008/). To auto format files, simply `pip install black`, and then run `black -l 100 path/to/file.py`. When all the above are checked, delete everything above the dashed line and fill in the pull request template. ------------------------------------------------------------------------------------------------------------ **Title:** **Summary:** **Relevant references:** **Possible Drawbacks:** **Related GitHub Issues:** ---- If you are writing a demonstration, please answer these questions to facilitate the marketing process. * GOALS — Why are we working on this now? *Eg. Promote a new PL feature or show a PL implementation of a recent paper.* * AUDIENCE — Who is this for? *Eg. Chemistry researchers, PL educators, beginners in quantum computing.* * KEYWORDS — What words should be included in the marketing post? * Which of the following types of documentation is most similar to your file? (more details [here](https://www.notion.so/xanaduai/Different-kinds-of-documentation-69200645fe59442991c71f9e7d8a77f8)) - [ ] Tutorial - [ ] Demo - [ ] How-to Co-authored-by: David --- .../tutorial_geometric_qml/demo.py | 194 +++++++++--------- .../tutorial_geometric_qml/metadata.json | 2 +- .../tutorial_givens_rotations/demo.py | 72 +++---- .../tutorial_givens_rotations/metadata.json | 2 +- .../tutorial_grovers_algorithm/demo.py | 76 +++---- .../tutorial_grovers_algorithm/metadata.json | 2 +- .../demo.py | 58 +++--- .../metadata.json | 2 +- .../tutorial_haar_measure/demo.py | 22 +- .../tutorial_haar_measure/metadata.json | 2 +- .../tutorial_here_comes_the_sun/demo.py | 94 ++++----- .../tutorial_here_comes_the_sun/metadata.json | 2 +- demonstrations_v2/tutorial_hidden_cut/demo.py | 20 +- .../tutorial_hidden_cut/metadata.json | 2 +- .../demo.py | 78 +++---- .../metadata.json | 2 +- .../demo.py | 32 +-- .../metadata.json | 2 +- .../tutorial_how_to_collect_mcm_stats/demo.py | 48 ++--- .../metadata.json | 2 +- .../demo.py | 70 +++---- .../metadata.json | 2 +- .../demo.py | 36 ++-- .../metadata.json | 2 +- .../demo.py | 36 ++-- .../metadata.json | 2 +- .../tutorial_how_to_use_noise_models/demo.py | 68 +++--- .../metadata.json | 2 +- .../demo.py | 46 ++--- .../metadata.json | 2 +- 30 files changed, 490 insertions(+), 490 deletions(-) diff --git a/demonstrations_v2/tutorial_geometric_qml/demo.py b/demonstrations_v2/tutorial_geometric_qml/demo.py index 845476eb21..ec35f6b2f1 100644 --- a/demonstrations_v2/tutorial_geometric_qml/demo.py +++ b/demonstrations_v2/tutorial_geometric_qml/demo.py @@ -493,84 +493,84 @@ def create_dataset(size_for_each_winner): # the symmetry classes we defined over the single-site and two-site measurements. -import pennylane as qml +import pennylane as qp import matplotlib.pyplot as plt # Set up a nine-qubit system -dev = qml.device("default.qubit", wires=9) +dev = qp.device("default.qubit", wires=9) -ob_center = qml.PauliZ(4) -ob_corner = (qml.PauliZ(0) + qml.PauliZ(2) + qml.PauliZ(6) + qml.PauliZ(8)) * (1 / 4) -ob_edge = (qml.PauliZ(1) + qml.PauliZ(3) + qml.PauliZ(5) + qml.PauliZ(7)) * (1 / 4) +ob_center = qp.PauliZ(4) +ob_corner = (qp.PauliZ(0) + qp.PauliZ(2) + qp.PauliZ(6) + qp.PauliZ(8)) * (1 / 4) +ob_edge = (qp.PauliZ(1) + qp.PauliZ(3) + qp.PauliZ(5) + qp.PauliZ(7)) * (1 / 4) # Now let's encode the data in the following qubit models, first with symmetry -@qml.qnode(dev) +@qp.qnode(dev) def circuit(x, p): - qml.RX(x[0], wires=0) - qml.RX(x[1], wires=1) - qml.RX(x[2], wires=2) - qml.RX(x[3], wires=3) - qml.RX(x[4], wires=4) - qml.RX(x[5], wires=5) - qml.RX(x[6], wires=6) - qml.RX(x[7], wires=7) - qml.RX(x[8], wires=8) + qp.RX(x[0], wires=0) + qp.RX(x[1], wires=1) + qp.RX(x[2], wires=2) + qp.RX(x[3], wires=3) + qp.RX(x[4], wires=4) + qp.RX(x[5], wires=5) + qp.RX(x[6], wires=6) + qp.RX(x[7], wires=7) + qp.RX(x[8], wires=8) # Centre single-qubit rotation - qml.RX(p[0], wires=4) - qml.RY(p[1], wires=4) + qp.RX(p[0], wires=4) + qp.RY(p[1], wires=4) # Corner single-qubit rotation - qml.RX(p[2], wires=0) - qml.RX(p[2], wires=2) - qml.RX(p[2], wires=6) - qml.RX(p[2], wires=8) + qp.RX(p[2], wires=0) + qp.RX(p[2], wires=2) + qp.RX(p[2], wires=6) + qp.RX(p[2], wires=8) - qml.RY(p[3], wires=0) - qml.RY(p[3], wires=2) - qml.RY(p[3], wires=6) - qml.RY(p[3], wires=8) + qp.RY(p[3], wires=0) + qp.RY(p[3], wires=2) + qp.RY(p[3], wires=6) + qp.RY(p[3], wires=8) # Edge single-qubit rotation - qml.RX(p[4], wires=1) - qml.RX(p[4], wires=3) - qml.RX(p[4], wires=5) - qml.RX(p[4], wires=7) + qp.RX(p[4], wires=1) + qp.RX(p[4], wires=3) + qp.RX(p[4], wires=5) + qp.RX(p[4], wires=7) - qml.RY(p[5], wires=1) - qml.RY(p[5], wires=3) - qml.RY(p[5], wires=5) - qml.RY(p[5], wires=7) + qp.RY(p[5], wires=1) + qp.RY(p[5], wires=3) + qp.RY(p[5], wires=5) + qp.RY(p[5], wires=7) # Entagling two-qubit gates # circling the edge of the board - qml.CRY(p[6], wires=[0, 1]) - qml.CRY(p[6], wires=[2, 1]) - qml.CRY(p[6], wires=[2, 5]) - qml.CRY(p[6], wires=[8, 5]) - qml.CRY(p[6], wires=[8, 7]) - qml.CRY(p[6], wires=[6, 7]) - qml.CRY(p[6], wires=[6, 3]) - qml.CRY(p[6], wires=[0, 3]) + qp.CRY(p[6], wires=[0, 1]) + qp.CRY(p[6], wires=[2, 1]) + qp.CRY(p[6], wires=[2, 5]) + qp.CRY(p[6], wires=[8, 5]) + qp.CRY(p[6], wires=[8, 7]) + qp.CRY(p[6], wires=[6, 7]) + qp.CRY(p[6], wires=[6, 3]) + qp.CRY(p[6], wires=[0, 3]) # To the corners from the centre - qml.CRY(p[7], wires=[4, 0]) - qml.CRY(p[7], wires=[4, 2]) - qml.CRY(p[7], wires=[4, 6]) - qml.CRY(p[7], wires=[4, 8]) + qp.CRY(p[7], wires=[4, 0]) + qp.CRY(p[7], wires=[4, 2]) + qp.CRY(p[7], wires=[4, 6]) + qp.CRY(p[7], wires=[4, 8]) # To the centre from the edges - qml.CRY(p[8], wires=[1, 4]) - qml.CRY(p[8], wires=[3, 4]) - qml.CRY(p[8], wires=[5, 4]) - qml.CRY(p[8], wires=[7, 4]) + qp.CRY(p[8], wires=[1, 4]) + qp.CRY(p[8], wires=[3, 4]) + qp.CRY(p[8], wires=[5, 4]) + qp.CRY(p[8], wires=[7, 4]) - return [qml.expval(ob_center), qml.expval(ob_corner), qml.expval(ob_edge)] + return [qp.expval(ob_center), qp.expval(ob_corner), qp.expval(ob_edge)] -fig, ax = qml.draw_mpl(circuit)([0] * 9, 18 * [0]) +fig, ax = qp.draw_mpl(circuit)([0] * 9, 18 * [0]) ###################################################################### # Let's also look at the same series of gates but this time they @@ -579,22 +579,22 @@ def circuit(x, p): # more parameters, as previously groups of gates were updated together. -@qml.qnode(dev) +@qp.qnode(dev) def circuit_no_sym(x, p): - qml.RX(x[0], wires=0) - qml.RX(x[1], wires=1) - qml.RX(x[2], wires=2) - qml.RX(x[3], wires=3) - qml.RX(x[4], wires=4) - qml.RX(x[5], wires=5) - qml.RX(x[6], wires=6) - qml.RX(x[7], wires=7) - qml.RX(x[8], wires=8) + qp.RX(x[0], wires=0) + qp.RX(x[1], wires=1) + qp.RX(x[2], wires=2) + qp.RX(x[3], wires=3) + qp.RX(x[4], wires=4) + qp.RX(x[5], wires=5) + qp.RX(x[6], wires=6) + qp.RX(x[7], wires=7) + qp.RX(x[8], wires=8) # Centre single-qubit rotation - qml.RX(p[0], wires=4) - qml.RY(p[1], wires=4) + qp.RX(p[0], wires=4) + qp.RY(p[1], wires=4) # Note in this circuit the parameters aren't all the same. # Previously they were identical to ensure they were applied @@ -602,54 +602,54 @@ def circuit_no_sym(x, p): # here means we aren't respecting the symmetry. # Corner single-qubit rotation - qml.RX(p[2], wires=0) - qml.RX(p[3], wires=2) - qml.RX(p[4], wires=6) - qml.RX(p[5], wires=8) + qp.RX(p[2], wires=0) + qp.RX(p[3], wires=2) + qp.RX(p[4], wires=6) + qp.RX(p[5], wires=8) - qml.RY(p[6], wires=0) - qml.RY(p[7], wires=2) - qml.RY(p[8], wires=6) - qml.RY(p[9], wires=8) + qp.RY(p[6], wires=0) + qp.RY(p[7], wires=2) + qp.RY(p[8], wires=6) + qp.RY(p[9], wires=8) # Edge single-qubit rotation - qml.RX(p[10], wires=1) - qml.RX(p[11], wires=3) - qml.RX(p[12], wires=5) - qml.RX(p[13], wires=7) + qp.RX(p[10], wires=1) + qp.RX(p[11], wires=3) + qp.RX(p[12], wires=5) + qp.RX(p[13], wires=7) - qml.RY(p[14], wires=1) - qml.RY(p[15], wires=3) - qml.RY(p[16], wires=5) - qml.RY(p[17], wires=7) + qp.RY(p[14], wires=1) + qp.RY(p[15], wires=3) + qp.RY(p[16], wires=5) + qp.RY(p[17], wires=7) # Entagling two-qubit gates # circling the edge of the board - qml.CRY(p[18], wires=[0, 1]) - qml.CRY(p[19], wires=[2, 1]) - qml.CRY(p[20], wires=[2, 5]) - qml.CRY(p[21], wires=[8, 5]) - qml.CRY(p[22], wires=[8, 7]) - qml.CRY(p[23], wires=[6, 7]) - qml.CRY(p[24], wires=[6, 3]) - qml.CRY(p[25], wires=[0, 3]) + qp.CRY(p[18], wires=[0, 1]) + qp.CRY(p[19], wires=[2, 1]) + qp.CRY(p[20], wires=[2, 5]) + qp.CRY(p[21], wires=[8, 5]) + qp.CRY(p[22], wires=[8, 7]) + qp.CRY(p[23], wires=[6, 7]) + qp.CRY(p[24], wires=[6, 3]) + qp.CRY(p[25], wires=[0, 3]) # To the corners from the centre - qml.CRY(p[26], wires=[4, 0]) - qml.CRY(p[27], wires=[4, 2]) - qml.CRY(p[28], wires=[4, 6]) - qml.CRY(p[29], wires=[4, 8]) + qp.CRY(p[26], wires=[4, 0]) + qp.CRY(p[27], wires=[4, 2]) + qp.CRY(p[28], wires=[4, 6]) + qp.CRY(p[29], wires=[4, 8]) # To the centre from the edges - qml.CRY(p[30], wires=[1, 4]) - qml.CRY(p[31], wires=[3, 4]) - qml.CRY(p[32], wires=[5, 4]) - qml.CRY(p[33], wires=[7, 4]) + qp.CRY(p[30], wires=[1, 4]) + qp.CRY(p[31], wires=[3, 4]) + qp.CRY(p[32], wires=[5, 4]) + qp.CRY(p[33], wires=[7, 4]) - return [qml.expval(ob_center), qml.expval(ob_corner), qml.expval(ob_edge)] + return [qp.expval(ob_center), qp.expval(ob_corner), qp.expval(ob_edge)] -fig, ax = qml.draw_mpl(circuit_no_sym)([0] * 9, [0] * 34) +fig, ax = qp.draw_mpl(circuit_no_sym)([0] * 9, [0] * 34) ###################################################################### diff --git a/demonstrations_v2/tutorial_geometric_qml/metadata.json b/demonstrations_v2/tutorial_geometric_qml/metadata.json index ad4c4a5619..1324b7739c 100644 --- a/demonstrations_v2/tutorial_geometric_qml/metadata.json +++ b/demonstrations_v2/tutorial_geometric_qml/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2022-10-18T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Machine Learning" ], diff --git a/demonstrations_v2/tutorial_givens_rotations/demo.py b/demonstrations_v2/tutorial_givens_rotations/demo.py index 0bd1ae478c..37ce83188c 100644 --- a/demonstrations_v2/tutorial_givens_rotations/demo.py +++ b/demonstrations_v2/tutorial_givens_rotations/demo.py @@ -182,21 +182,21 @@ This can be implemented in PennyLane as follows: """ -import pennylane as qml +import pennylane as qp from jax import numpy as jnp import jax jax.config.update("jax_enable_x64", True) -dev = qml.device('lightning.qubit', wires=3) +dev = qp.device('lightning.qubit', wires=3) -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def circuit(x, y): # prepares the reference state |100> - qml.BasisState(jnp.array([1, 0, 0]), wires=[0, 1, 2]) + qp.BasisState(jnp.array([1, 0, 0]), wires=[0, 1, 2]) # applies the single excitations - qml.SingleExcitation(x, wires=[0, 1]) - qml.SingleExcitation(y, wires=[0, 2]) - return qml.state() + qp.SingleExcitation(x, wires=[0, 1]) + qp.SingleExcitation(y, wires=[0, 2]) + return qp.state() x = -2 * jnp.arcsin(jnp.sqrt(1/3)) y = -2 * jnp.arcsin(jnp.sqrt(1/2)) @@ -251,7 +251,7 @@ def circuit(x, y): nr_particles = 3 nr_qubits = 6 -singles, doubles = qml.qchem.excitations(3, 6) +singles, doubles = qp.qchem.excitations(3, 6) print(f"Single excitations = {singles}") print(f"Double excitations = {doubles}") @@ -260,19 +260,19 @@ def circuit(x, y): from jax import random -dev2 = qml.device('lightning.qubit', wires=6) +dev2 = qp.device('lightning.qubit', wires=6) -@qml.qnode(dev2, interface="jax") +@qp.qnode(dev2, interface="jax") def circuit2(x, y): # prepares reference state - qml.BasisState(jnp.array([1, 1, 1, 0, 0, 0]), wires=[0, 1, 2, 3, 4, 5]) + qp.BasisState(jnp.array([1, 1, 1, 0, 0, 0]), wires=[0, 1, 2, 3, 4, 5]) # apply all single excitations for i, s in enumerate(singles): - qml.SingleExcitation(x[i], wires=s) + qp.SingleExcitation(x[i], wires=s) # apply all double excitations for j, d in enumerate(doubles): - qml.DoubleExcitation(y[j], wires=d) - return qml.state() + qp.DoubleExcitation(y[j], wires=d) + return qp.state() # random angles of rotation key = random.PRNGKey(0) @@ -360,15 +360,15 @@ def circuit2(x, y): # undesired contribution for the state :math:`|011000\rangle` through a coupling with # :math:`|001100\rangle.` Let's check that this is the case: -dev = qml.device('default.qubit', wires=6) +dev = qp.device('default.qubit', wires=6) -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def circuit3(x, y, z): - qml.BasisState(jnp.array([1, 1, 0, 0, 0, 0]), wires=[i for i in range(6)]) - qml.DoubleExcitation(x, wires=[0, 1, 2, 3]) - qml.DoubleExcitation(y, wires=[0, 1, 4, 5]) - qml.SingleExcitation(z, wires=[1, 3]) - return qml.state() + qp.BasisState(jnp.array([1, 1, 0, 0, 0, 0]), wires=[i for i in range(6)]) + qp.DoubleExcitation(x, wires=[0, 1, 2, 3]) + qp.DoubleExcitation(y, wires=[0, 1, 4, 5]) + qp.SingleExcitation(z, wires=[1, 3]) + return qp.state() x = -2 * jnp.arcsin(jnp.sqrt(1/4)) y = -2 * jnp.arcsin(jnp.sqrt(1/3)) @@ -386,14 +386,14 @@ def circuit3(x, y, z): # above, this time controlling on the state of the first qubit and verify that we can prepare the # desired state. To perform the control, we use the :func:`~.pennylane.ctrl` transform: -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def circuit4(x, y, z): - qml.BasisState(jnp.array([1, 1, 0, 0, 0, 0]), wires=[i for i in range(6)]) - qml.DoubleExcitation(x, wires=[0, 1, 2, 3]) - qml.DoubleExcitation(y, wires=[0, 1, 4, 5]) + qp.BasisState(jnp.array([1, 1, 0, 0, 0, 0]), wires=[i for i in range(6)]) + qp.DoubleExcitation(x, wires=[0, 1, 2, 3]) + qp.DoubleExcitation(y, wires=[0, 1, 4, 5]) # single excitation controlled on qubit 0 - qml.ctrl(qml.SingleExcitation, control=0)(z, wires=[1, 3]) - return qml.state() + qp.ctrl(qp.SingleExcitation, control=0)(z, wires=[1, 3]) + return qp.state() output = circuit4(x, y, z) states = [np.binary_repr(i, width=6) for i in range(len(output)) if output[i] != 0] @@ -442,18 +442,18 @@ def circuit4(x, y, z): # of the :math:`k`-th Givens rotation as :math:`-2 \arcsin(1/\sqrt{n-k}),` where :math:`n` is the # number of basis states in the superposition. -dev = qml.device('default.qubit', wires=4) +dev = qp.device('default.qubit', wires=4) -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def state_preparation(params): - qml.BasisState(jnp.array([1, 1, 0, 0]), wires=[0, 1, 2, 3]) - qml.SingleExcitation(params[0], wires=[1, 2]) - qml.SingleExcitation(params[1], wires=[1, 3]) + qp.BasisState(jnp.array([1, 1, 0, 0]), wires=[0, 1, 2, 3]) + qp.SingleExcitation(params[0], wires=[1, 2]) + qp.SingleExcitation(params[1], wires=[1, 3]) # single excitations controlled on qubit 1 - qml.ctrl(qml.SingleExcitation, control=1)(params[2], wires=[0, 2]) - qml.ctrl(qml.SingleExcitation, control=1)(params[3], wires=[0, 3]) - qml.DoubleExcitation(params[4], wires=[0, 1, 2, 3]) - return qml.state() + qp.ctrl(qp.SingleExcitation, control=1)(params[2], wires=[0, 2]) + qp.ctrl(qp.SingleExcitation, control=1)(params[3], wires=[0, 3]) + qp.DoubleExcitation(params[4], wires=[0, 1, 2, 3]) + return qp.state() n = 6 params = jnp.array([-2 * jnp.arcsin(1/jnp.sqrt(n-i)) for i in range(n-1)]) diff --git a/demonstrations_v2/tutorial_givens_rotations/metadata.json b/demonstrations_v2/tutorial_givens_rotations/metadata.json index ad01a86958..bce555f8d5 100644 --- a/demonstrations_v2/tutorial_givens_rotations/metadata.json +++ b/demonstrations_v2/tutorial_givens_rotations/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2021-06-30T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Chemistry" ], diff --git a/demonstrations_v2/tutorial_grovers_algorithm/demo.py b/demonstrations_v2/tutorial_grovers_algorithm/demo.py index c3a0fa0431..e44d8c1c0d 100644 --- a/demonstrations_v2/tutorial_grovers_algorithm/demo.py +++ b/demonstrations_v2/tutorial_grovers_algorithm/demo.py @@ -45,7 +45,7 @@ """ import matplotlib.pyplot as plt -import pennylane as qml +import pennylane as qp import numpy as np ###################################################################### @@ -68,24 +68,24 @@ NUM_QUBITS = 2 -dev = qml.device("default.qubit", wires=NUM_QUBITS) +dev = qp.device("default.qubit", wires=NUM_QUBITS) wires = list(range(NUM_QUBITS)) def equal_superposition(wires): for wire in wires: - qml.Hadamard(wires=wire) + qp.Hadamard(wires=wire) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(): - qml.Snapshot("Initial state") + qp.Snapshot("Initial state") equal_superposition(wires) - qml.Snapshot("After applying the Hadamard gates") - return qml.probs(wires=wires) # Probability of finding a computational basis state on the wires + qp.Snapshot("After applying the Hadamard gates") + return qp.probs(wires=wires) # Probability of finding a computational basis state on the wires -results = qml.snapshots(circuit)() +results = qp.snapshots(circuit)() for k, result in results.items(): print(f"{k}: {result}") @@ -131,17 +131,17 @@ def circuit(): # Let us take a look at an example. If we pass the array ``[0,0]``, the sign of the state # :math:`\vert 00 \rangle = \begin{bmatrix} 1 \\0 \\0 \\0 \end{bmatrix}` will flip: -dev = qml.device("default.qubit", wires=NUM_QUBITS) +dev = qp.device("default.qubit", wires=NUM_QUBITS) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(): - qml.Snapshot("Initial state |00>") + qp.Snapshot("Initial state |00>") # Flipping the marked state - qml.FlipSign([0, 0], wires=wires) - qml.Snapshot("After flipping it") - return qml.state() + qp.FlipSign([0, 0], wires=wires) + qp.Snapshot("After flipping it") + return qp.state() -results = qml.snapshots(circuit)() +results = qp.snapshots(circuit)() for k, result in results.items(): print(f"{k}: {result}") @@ -170,21 +170,21 @@ def circuit(): omega = np.zeros(NUM_QUBITS) def oracle(wires, omega): - qml.FlipSign(omega, wires=wires) + qp.FlipSign(omega, wires=wires) -dev = qml.device("default.qubit", wires=NUM_QUBITS) +dev = qp.device("default.qubit", wires=NUM_QUBITS) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(): equal_superposition(wires) - qml.Snapshot("Before querying the Oracle") + qp.Snapshot("Before querying the Oracle") oracle(wires, omega) - qml.Snapshot("After querying the Oracle") + qp.Snapshot("After querying the Oracle") - return qml.probs(wires=wires) + return qp.probs(wires=wires) -results = qml.snapshots(circuit)() +results = qp.snapshots(circuit)() for k, result in results.items(): print(f"{k}: {result}") @@ -259,32 +259,32 @@ def circuit(): # to solve the problem. -dev = qml.device("default.qubit", wires=NUM_QUBITS) +dev = qp.device("default.qubit", wires=NUM_QUBITS) def diffusion_operator(wires): for wire in wires: - qml.Hadamard(wires=wire) - qml.PauliZ(wires=wire) - qml.ctrl(qml.PauliZ, 0)(wires=1) + qp.Hadamard(wires=wire) + qp.PauliZ(wires=wire) + qp.ctrl(qp.PauliZ, 0)(wires=1) for wire in wires: - qml.Hadamard(wires=wire) + qp.Hadamard(wires=wire) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(): equal_superposition(wires) - qml.Snapshot("Uniform superposition |s>") + qp.Snapshot("Uniform superposition |s>") oracle(wires, omega) - qml.Snapshot("State marked by Oracle") + qp.Snapshot("State marked by Oracle") diffusion_operator(wires) - qml.Snapshot("Amplitude after diffusion") - return qml.probs(wires=wires) + qp.Snapshot("Amplitude after diffusion") + return qp.probs(wires=wires) -results = qml.snapshots(circuit)() +results = qp.snapshots(circuit)() for k, result in results.items(): print(f"{k}: {result}") @@ -318,9 +318,9 @@ def circuit(): N = 2**NUM_QUBITS wires = list(range(NUM_QUBITS)) -dev = qml.device("default.qubit", wires=NUM_QUBITS) +dev = qp.device("default.qubit", wires=NUM_QUBITS) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(): iterations = int(np.round(np.sqrt(N / M) * np.pi / 4)) @@ -331,12 +331,12 @@ def circuit(): for _ in range(iterations): for omg in omega: oracle(wires, omg) - qml.templates.GroverOperator(wires) + qp.templates.GroverOperator(wires) - return qml.probs(wires=wires) + return qp.probs(wires=wires) -results = qml.snapshots(circuit)() +results = qp.snapshots(circuit)() for k, result in results.items(): print(f"{k}: {result}") diff --git a/demonstrations_v2/tutorial_grovers_algorithm/metadata.json b/demonstrations_v2/tutorial_grovers_algorithm/metadata.json index c8a1496a1f..43f5b9b80a 100644 --- a/demonstrations_v2/tutorial_grovers_algorithm/metadata.json +++ b/demonstrations_v2/tutorial_grovers_algorithm/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-07-03T00:00:00+00:00", - "dateOfLastModification": "2025-12-19T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Getting Started", "Algorithms", diff --git a/demonstrations_v2/tutorial_guide_to_pennylane_knowing_qiskit/demo.py b/demonstrations_v2/tutorial_guide_to_pennylane_knowing_qiskit/demo.py index a73c64857c..6341e0e5f4 100644 --- a/demonstrations_v2/tutorial_guide_to_pennylane_knowing_qiskit/demo.py +++ b/demonstrations_v2/tutorial_guide_to_pennylane_knowing_qiskit/demo.py @@ -79,33 +79,33 @@ def qiskit_circuit(): qc = qiskit_circuit() ###################################################################### -# To convert this circuit to PennyLane, you just use ``qml.from_qiskit``: +# To convert this circuit to PennyLane, you just use ``qp.from_qiskit``: # -import pennylane as qml +import pennylane as qp import matplotlib.pyplot as plt -pl_func = qml.from_qiskit(qc) -qml.draw_mpl(pl_func, style="pennylane")() +pl_func = qp.from_qiskit(qc) +qp.draw_mpl(pl_func, style="pennylane")() plt.show() ###################################################################### -# Want to measure some expectation values of Pauli operators, as well? Use ``qml.from_qiskit_op`` to +# Want to measure some expectation values of Pauli operators, as well? Use ``qp.from_qiskit_op`` to # convert a ``SparsePauliOp`` into PennyLane’s equivalent operator. # from qiskit.quantum_info import SparsePauliOp qiskit_pauli_op = SparsePauliOp("XY") -pl_pauli_op = qml.from_qiskit_op(qiskit_pauli_op) +pl_pauli_op = qp.from_qiskit_op(qiskit_pauli_op) ###################################################################### -# Then, you can *append* the expectation value measurement — done with ``qml.expval`` — to the PennyLane -# circuit when you create it with ``qml.from_qiskit``: +# Then, you can *append* the expectation value measurement — done with ``qp.expval`` — to the PennyLane +# circuit when you create it with ``qp.from_qiskit``: # -pl_func = qml.from_qiskit(qc, measurements=[qml.expval(pl_pauli_op)]) -qml.draw_mpl(pl_func, style='pennylane')() +pl_func = qp.from_qiskit(qc, measurements=[qp.expval(pl_pauli_op)]) +qp.draw_mpl(pl_func, style='pennylane')() plt.show() ###################################################################### @@ -133,18 +133,18 @@ def qiskit_circuit(): print(result_sampler) ###################################################################### -# When we use ``qml.from_qiskit`` on our Qiskit circuit, this is equivalent to creating this function +# When we use ``qp.from_qiskit`` on our Qiskit circuit, this is equivalent to creating this function # in PennyLane. # def pl_func(): """ Equivalent to doing: - pl_func = qml.from_qiskit(qc, measurements=qml.counts(wires=[0, 1])) + pl_func = qp.from_qiskit(qc, measurements=qp.counts(wires=[0, 1])) """ - qml.Hadamard(0) - qml.CNOT([0, 1]) - return qml.counts(wires=[0, 1]) + qp.Hadamard(0) + qp.CNOT([0, 1]) + return qp.counts(wires=[0, 1]) ###################################################################### # .. note :: @@ -159,18 +159,18 @@ def pl_func(): # A function like ``pl_func`` is called a **quantum function**. A quantum function in PennyLane just # contains quantum gates and (optionally) returns a measurement. Measurements in PennyLane are quite # different than in Qiskit 1.0 — we'll touch on how measurements work in PennyLane shortly. But, in our -# case, :func:`qml.counts(wires=[0, 1]) ` is the measurement, which counts the number +# case, :func:`qp.counts(wires=[0, 1]) ` is the measurement, which counts the number # of times each basis state is sampled. # # If we actually want to execute the circuit and see the result of our measurement, we need to define # what the circuit runs on, just like how we defined a ``StatevectorSampler`` instance in Qiskit # (a new `V2 primitive `__). PennyLane’s -# way of doing this is simple: (1) define a device with :func:`qml.device ` and (2) pair +# way of doing this is simple: (1) define a device with :func:`qp.device ` and (2) pair # the device with the quantum function with :class:`~pennylane.QNode`. # -dev = qml.device("default.qubit") -pl_circuit = qml.set_shots(qml.QNode(pl_func, dev), shots = 1024) +dev = qp.device("default.qubit") +pl_circuit = qp.set_shots(qp.QNode(pl_func, dev), shots = 1024) print(pl_circuit()) @@ -183,11 +183,11 @@ def pl_func(): # called a *quantum node* (QNode), which is the union of two things: # # - **A quantum function that contains quantum instructions**. This is ``pl_func``, which just contains -# quantum operations (gates) and returns a measurement. In this case, ``qml.counts(wires=1)`` is +# quantum operations (gates) and returns a measurement. In this case, ``qp.counts(wires=1)`` is # the measurement, which counts the number of times each basis state is sampled and returns a dictionary # whose values are NumPy arrays. # -# - **A device** (e.g., ``qml.device("default.qubit")``). PennyLane has `many devices you can choose from `__, +# - **A device** (e.g., ``qp.device("default.qubit")``). PennyLane has `many devices you can choose from `__, # but ``"default.qubit"`` is our battle-tested Python state vector simulator. # # @@ -205,26 +205,26 @@ def pl_func(): # you specified and returning the measurement you asked for — as simple as that 🌈. # # Alternatively, wrapping a quantum -# function with :class:`qml.QNode ` is the same as *decorating* it with :func:`@qml.qnode(dev) `: +# function with :class:`qp.QNode ` is the same as *decorating* it with :func:`@qp.qnode(dev) `: # -@qml.set_shots(1024) -@qml.qnode(dev) +@qp.set_shots(1024) +@qp.qnode(dev) def pl_circuit(): """ Equivalent to doing: - pl_circuit = qml.QNode(qml.from_qiskit(qc, measurements=qml.counts(wires=[0, 1])), dev) + pl_circuit = qp.QNode(qp.from_qiskit(qc, measurements=qp.counts(wires=[0, 1])), dev) """ - qml.Hadamard(0) - qml.CNOT([0, 1]) - return qml.counts(wires=[0, 1]) + qp.Hadamard(0) + qp.CNOT([0, 1]) + return qp.counts(wires=[0, 1]) ###################################################################### # This is a minor point, but both approaches work. # # What's great about converting your work in Qiskit to PennyLane is that now you have access to all # of `PennyLane's plugins `__, meaning you can run your Qiskit circuit on more than just IBM hardware! All -# you need to do is install the plugin of interest and change the name of the device in ``qml.device``. +# you need to do is install the plugin of interest and change the name of the device in ``qp.device``. # ###################################################################### diff --git a/demonstrations_v2/tutorial_guide_to_pennylane_knowing_qiskit/metadata.json b/demonstrations_v2/tutorial_guide_to_pennylane_knowing_qiskit/metadata.json index eedcebb87b..e74175f97f 100644 --- a/demonstrations_v2/tutorial_guide_to_pennylane_knowing_qiskit/metadata.json +++ b/demonstrations_v2/tutorial_guide_to_pennylane_knowing_qiskit/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-07-22T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Quantum Computing" ], diff --git a/demonstrations_v2/tutorial_haar_measure/demo.py b/demonstrations_v2/tutorial_haar_measure/demo.py index 971ed0e610..84603b087f 100644 --- a/demonstrations_v2/tutorial_haar_measure/demo.py +++ b/demonstrations_v2/tutorial_haar_measure/demo.py @@ -172,7 +172,7 @@ """ -import pennylane as qml +import pennylane as qp import numpy as np import matplotlib.pyplot as plt @@ -180,14 +180,14 @@ np.random.seed(42) # Use the mixed state simulator to save some steps in plotting later -dev = qml.device('default.mixed', wires=1) +dev = qp.device('default.mixed', wires=1) -@qml.qnode(dev) +@qp.qnode(dev) def not_a_haar_random_unitary(): # Sample all parameters from their flat uniform distribution phi, theta, omega = 2 * np.pi * np.random.uniform(size=3) - qml.Rot(phi, theta, omega, wires=0) - return qml.state() + qp.Rot(phi, theta, omega, wires=0) + return qp.state() num_samples = 2021 @@ -275,12 +275,12 @@ def _pdf(self, theta): # Samples of theta should be drawn from between 0 and pi sin_sampler = sin_prob_dist(a=0, b=np.pi) -@qml.qnode(dev) +@qp.qnode(dev) def haar_random_unitary(): phi, omega = 2 * np.pi * np.random.uniform(size=2) # Sample phi and omega as normal theta = sin_sampler.rvs(size=1)[0] # Sample theta from our new distribution - qml.Rot(phi, theta, omega, wires=0) - return qml.state() + qp.Rot(phi, theta, omega, wires=0) + return qp.state() haar_samples = [haar_random_unitary() for _ in range(num_samples)] haar_bloch_vectors = np.array([convert_to_bloch_vector(s) for s in haar_samples]) @@ -524,10 +524,10 @@ def qr_haar(N): # by trying it out for :math:`N=2` and plotting on the Bloch sphere. # -@qml.qnode(dev) +@qp.qnode(dev) def qr_haar_random_unitary(): - qml.QubitUnitary(qr_haar(2), wires=0) - return qml.state() + qp.QubitUnitary(qr_haar(2), wires=0) + return qp.state() qr_haar_samples = [qr_haar_random_unitary() for _ in range(num_samples)] qr_haar_bloch_vectors = np.array([convert_to_bloch_vector(s) for s in qr_haar_samples]) diff --git a/demonstrations_v2/tutorial_haar_measure/metadata.json b/demonstrations_v2/tutorial_haar_measure/metadata.json index 9b4afc2132..4b4cb2afbc 100644 --- a/demonstrations_v2/tutorial_haar_measure/metadata.json +++ b/demonstrations_v2/tutorial_haar_measure/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2021-03-22T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Machine Learning", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_here_comes_the_sun/demo.py b/demonstrations_v2/tutorial_here_comes_the_sun/demo.py index 63cbe697c1..a0c48cc101 100644 --- a/demonstrations_v2/tutorial_here_comes_the_sun/demo.py +++ b/demonstrations_v2/tutorial_here_comes_the_sun/demo.py @@ -31,7 +31,7 @@ alternative differentiation strategies, namely finite differences and the `stochastic parameter-shift rule `_. Finally, we will compare the performance of -``qml.SpecialUnitary`` for a toy minimization problem to that of two other general +``qp.SpecialUnitary`` for a toy minimization problem to that of two other general local gates. That is, we compare the trainability of equally expressive ansätze. Ansätze, so many ansätze @@ -130,14 +130,14 @@ vanishing trace. Indeed, one can check that the dimension of :math:`\mathfrak{su}(N)` is :math:`4^n-1` and that there are :math:`4^n` Pauli words, so that one Pauli word — the identity — had to go in any case... We can use the canonical coordinates of the algebra to express a *group element* in -:math:`\mathrm{SU}(N)` as well, and the ``qml.SpecialUnitary`` gate we will use is defined as +:math:`\mathrm{SU}(N)` as well, and the ``qp.SpecialUnitary`` gate we will use is defined as .. math:: U(\boldsymbol{\theta}) = \exp\left\{\sum_{m=1}^d \theta_m G_m \right\}. The number of coordinates and Pauli words in :math:`\mathcal{P}^{(n)}` is :math:`d=4^n-1.` -Therefore, this will be the number of parameters that a single ``qml.SpecialUnitary`` gate acting on +Therefore, this will be the number of parameters that a single ``qp.SpecialUnitary`` gate acting on :math:`n` qubits will take. For example, it takes just three parameters for a single qubit, which is why :class:`~pennylane.Rot` and :class:`~pennylane.U3` take three parameters and may produce *any* single-qubit rotation. It takes a modest 15 parameters for two qubits, @@ -166,7 +166,7 @@ - The gradient with respect to all :math:`d` parameters of an :math:`\mathrm{SU}(N)` gate can be computed using :math:`2d` auxiliary circuits. Each of the circuits contains one additional - operation compared to the original circuit, namely a ``qml.PauliRot`` gate with rotation + operation compared to the original circuit, namely a ``qp.PauliRot`` gate with rotation angles of :math:`\pm\frac{\pi}{2}.` Note that these Pauli rotations act on up to :math:`n` qubits. - This differentiation method uses automatic differentiation during compilation and @@ -182,7 +182,7 @@ Comparing gradient methods -------------------------- -Before we dive into using ``qml.SpecialUnitary`` in an optimization task, let's compare +Before we dive into using ``qp.SpecialUnitary`` in an optimization task, let's compare a few methods to compute the gradient with respect to the parameters of such a gate. In particular, we will look at a finite difference (FD) approach, the stochastic parameter-shift rule, and the custom gradient method we described above. @@ -210,11 +210,11 @@ So, let's dive into a toy example and explore the three gradient methods! We start by defining a simple one-qubit circuit that contains a single :math:`\mathrm{SU}(2)` gate and measures the expectation value of :math:`H=\frac{3}{5} Z - \frac{4}{5} Y.` -As ``qml.SpecialUnitary`` requires automatic differentiation subroutines even for the +As ``qp.SpecialUnitary`` requires automatic differentiation subroutines even for the hardware-ready derivative recipe, we will make use of JAX. """ -import pennylane as qml +import pennylane as qp import numpy as np import jax @@ -222,16 +222,16 @@ jax.config.update("jax_platform_name", "cpu") jnp = jax.numpy -dev = qml.device("default.qubit", wires=1) -H = 0.6 * qml.PauliZ(0) - 0.8 * qml.PauliY(0) +dev = qp.device("default.qubit", wires=1) +H = 0.6 * qp.PauliZ(0) - 0.8 * qp.PauliY(0) def qfunc(theta): - qml.SpecialUnitary(theta, wires=0) - return qml.expval(H) + qp.SpecialUnitary(theta, wires=0) + return qp.expval(H) -circuit = qml.QNode(qfunc, dev, interface="jax", diff_method="parameter-shift") +circuit = qp.QNode(qfunc, dev, interface="jax", diff_method="parameter-shift") theta = jnp.array([0.4, 0.2, -0.5]) @@ -270,13 +270,13 @@ def central_diff_grad(theta, delta): @jax.jit -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def aux_circuit(theta, tau, sign): - qml.SpecialUnitary(tau * theta, wires=0) + qp.SpecialUnitary(tau * theta, wires=0) # This corresponds to the parameter-shift evaluations of RY at 0 - qml.RY(-sign * np.pi / 2, wires=0) - qml.SpecialUnitary((1 - tau) * theta, wires=0) - return qml.expval(H) + qp.RY(-sign * np.pi / 2, wires=0) + qp.SpecialUnitary((1 - tau) * theta, wires=0) + return qp.expval(H) def stochastic_parshift_grad(theta, num_samples): @@ -307,7 +307,7 @@ def stochastic_parshift_grad(theta, num_samples): # the exact value and see which method agrees with it (we again need to extract the # corresponding entry from the full gradient). -autodiff_circuit = qml.QNode(qfunc, dev, interface="jax", diff_method="parameter-shift") +autodiff_circuit = qp.QNode(qfunc, dev, interface="jax", diff_method="parameter-shift") exact_grad = jax.grad(autodiff_circuit)(theta)[1] print(f"Exact gradient: {exact_grad:.5f}") @@ -375,15 +375,15 @@ def stochastic_parshift_grad(theta, num_samples): # # We discussed above that there are many circuit architectures available and that choosing # a suitable ansatz is important but can be difficult. Here, we will compare a simple ansatz -# based on the ``qml.SpecialUnitary`` gate discussed above to other approaches that fully +# based on the ``qp.SpecialUnitary`` gate discussed above to other approaches that fully # parametrize the special unitary group for the respective number of qubits. -# In particular, we will compare ``qml.SpecialUnitary`` to standard decompositions from the +# In particular, we will compare ``qp.SpecialUnitary`` to standard decompositions from the # literature that parametrize :math:`\mathrm{SU}(N)` with elementary gates, as well as to a # sequence of Pauli rotation gates that also allows us to create any special unitary. # Let us start by defining the decomposition of a two-qubit unitary. # We choose the decomposition, which is optimal but not unique, from [#vatan]_. # The Pauli rotation sequence is available in PennyLane -# via ``qml.ArbitraryUnitary`` and we will not need to implement it ourselves. +# via ``qp.ArbitraryUnitary`` and we will not need to implement it ourselves. def two_qubit_decomp(params, wires): @@ -392,24 +392,24 @@ def two_qubit_decomp(params, wires): https://arxiv.org/pdf/quant-ph/0308006.pdf""" i, j = wires # Single U(2) parameterization on both qubits separately - qml.Rot(*params[:3], wires=i) - qml.Rot(*params[3:6], wires=j) - qml.CNOT(wires=[j, i]) # First CNOT - qml.RZ(params[6], wires=i) - qml.RY(params[7], wires=j) - qml.CNOT(wires=[i, j]) # Second CNOT - qml.RY(params[8], wires=j) - qml.CNOT(wires=[j, i]) # Third CNOT + qp.Rot(*params[:3], wires=i) + qp.Rot(*params[3:6], wires=j) + qp.CNOT(wires=[j, i]) # First CNOT + qp.RZ(params[6], wires=i) + qp.RY(params[7], wires=j) + qp.CNOT(wires=[i, j]) # Second CNOT + qp.RY(params[8], wires=j) + qp.CNOT(wires=[j, i]) # Third CNOT # Single U(2) parameterization on both qubits separately - qml.Rot(*params[9:12], wires=i) - qml.Rot(*params[12:15], wires=j) + qp.Rot(*params[9:12], wires=i) + qp.Rot(*params[12:15], wires=j) # The three building blocks on two qubits we will compare are: operations = { ("Decomposition", "decomposition"): two_qubit_decomp, - ("PauliRot sequence",) * 2: qml.ArbitraryUnitary, - ("$\mathrm{SU}(N)$ gate", "SU(N) gate"): qml.SpecialUnitary, + ("PauliRot sequence",) * 2: qp.ArbitraryUnitary, + ("$\mathrm{SU}(N)$ gate", "SU(N) gate"): qp.SpecialUnitary, } ############################################################################## @@ -430,12 +430,12 @@ def two_qubit_decomp(params, wires): coefficients = np.random.randn(4**num_wires - 1) # Create the matrices for the entire Pauli basis -basis = qml.ops.qubit.special_unitary.pauli_basis_matrices(num_wires) +basis = qp.ops.qubit.special_unitary.pauli_basis_matrices(num_wires) # Construct the Hamiltonian from the normal random coefficients and the basis -H_matrix = qml.math.tensordot(coefficients, basis, axes=[[0], [0]]) -H = qml.Hermitian(H_matrix, wires=wires) +H_matrix = qp.math.tensordot(coefficients, basis, axes=[[0], [0]]) +H = qp.Hermitian(H_matrix, wires=wires) # Compute the ground state energy -E_min = min(qml.eigvals(H)) +E_min = min(qp.eigvals(H)) print(f"Ground state energy: {E_min:.5f}") ############################################################################## @@ -446,7 +446,7 @@ def two_qubit_decomp(params, wires): loc = 2 d = loc**4 - 1 # d = 15 for two-qubit operations -dev = qml.device("default.qubit", wires=num_wires) +dev = qp.device("default.qubit", wires=num_wires) # two blocks with two layers. Each layer contains three operations with d parameters param_shape = (2, 2, 3, d) init_params = np.zeros(param_shape) @@ -463,11 +463,11 @@ def circuit(params, operation=None): for j, params_op in enumerate(params_layer): wires_op = [w % num_wires for w in range(loc * j + i, loc * (j + 1) + i)] operation(params_op, wires_op) - return qml.expval(H) + return qp.expval(H) -qnode = qml.QNode(circuit, dev, interface="jax") -print(qml.draw(qnode)(init_params, qml.SpecialUnitary)) +qnode = qp.QNode(circuit, dev, interface="jax") +print(qp.draw(qnode)(init_params, qp.SpecialUnitary)) ############################################################################## # We can now proceed to prepare the optimization task using this circuit @@ -517,7 +517,7 @@ def circuit(params, operation=None): plt.show() ############################################################################## -# We find that the optimization indeed performs significantly better for ``qml.SpecialUnitary`` +# We find that the optimization indeed performs significantly better for ``qp.SpecialUnitary`` # than for the other two general unitaries, while using the same number of parameters and # preserving the expressibility of the circuit ansatz. This # means that we found a particularly well-trainable parameterization of the local unitaries which @@ -528,21 +528,21 @@ def circuit(params, operation=None): # Conclusion # ---------- # -# To summarize, in this tutorial we introduced ``qml.SpecialUnitary``, a multi-parameter +# To summarize, in this tutorial we introduced ``qp.SpecialUnitary``, a multi-parameter # gate that can act like *any* gate on the qubits it is applied to and that is constructed # with Lie theory in mind. We discussed three methods of differentiating quantum circuits # that use this gate, showing that a new custom parameter-shift rule presented in # [#wiersema]_ is particularly suitable to produce unbiased gradient estimates with the # lowest variance. Afterwards, we used this differentiation technique when comparing -# the performance of ``qml.SpecialUnitary`` to that of other gates that can act +# the performance of ``qp.SpecialUnitary`` to that of other gates that can act # like *any* gate locally. For this, we ran a gradient-based optimization for a toy model -# Hamiltonian and found that ``qml.SpecialUnitary`` is particularly well-trainable, achieving +# Hamiltonian and found that ``qp.SpecialUnitary`` is particularly well-trainable, achieving # lower energies significantly quicker than the other tested gates. # -# There are still exciting questions to answer about ``qml.SpecialUnitary``: How can the +# There are still exciting questions to answer about ``qp.SpecialUnitary``: How can the # custom parameter-shift rule be used for other gates, and what does the so-called # *Dynamical Lie algebra* of these gates have to do with it? How can we implement -# the ``qml.SpecialUnitary`` gate on hardware? Is the unitary time evolution implemented +# the ``qp.SpecialUnitary`` gate on hardware? Is the unitary time evolution implemented # by this gate special in a physical sense? # # The answers to some, but not all, of these questions can be found in [#wiersema]_. diff --git a/demonstrations_v2/tutorial_here_comes_the_sun/metadata.json b/demonstrations_v2/tutorial_here_comes_the_sun/metadata.json index d470175afc..bfd58be705 100644 --- a/demonstrations_v2/tutorial_here_comes_the_sun/metadata.json +++ b/demonstrations_v2/tutorial_here_comes_the_sun/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-04-03T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_hidden_cut/demo.py b/demonstrations_v2/tutorial_hidden_cut/demo.py index e42629ac46..faa58563bd 100644 --- a/demonstrations_v2/tutorial_hidden_cut/demo.py +++ b/demonstrations_v2/tutorial_hidden_cut/demo.py @@ -72,7 +72,7 @@ import galois import matplotlib.pyplot as plt import numpy as np -import pennylane as qml +import pennylane as qp from scipy.stats import unitary_group # set random seed @@ -257,31 +257,31 @@ def separable_state(partitions): # array ``M``: # -dev = qml.device('default.qubit') +dev = qp.device('default.qubit') -@qml.set_shots(100) -@qml.qnode(dev) +@qp.set_shots(100) +@qp.qnode(dev) def circuit(): # Initialize psi x psi in registers 2 and 3 - qml.StatePrep(state, wires=range(n, 2*n)) - qml.StatePrep(state, wires=range(2*n, 3*n)) + qp.StatePrep(state, wires=range(n, 2*n)) + qp.StatePrep(state, wires=range(2*n, 3*n)) # Hadamards for a in range(n): - qml.Hadamard(a) + qp.Hadamard(a) # Controlled swaps for c in range(n): a = c + n b = c + 2*n - qml.ctrl(qml.SWAP, c, control_values=1)(wires=(a,b)) + qp.ctrl(qp.SWAP, c, control_values=1)(wires=(a,b)) # Hadamards for a in range(n): - qml.Hadamard(a) + qp.Hadamard(a) # Measure - return qml.sample(wires=range(n)) + return qp.sample(wires=range(n)) M = circuit() diff --git a/demonstrations_v2/tutorial_hidden_cut/metadata.json b/demonstrations_v2/tutorial_hidden_cut/metadata.json index 07aa690061..b7b496414d 100644 --- a/demonstrations_v2/tutorial_hidden_cut/metadata.json +++ b/demonstrations_v2/tutorial_hidden_cut/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2025-07-25T10:00:00+00:00", - "dateOfLastModification": "2026-01-23T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Algorithms" ], diff --git a/demonstrations_v2/tutorial_how_to_build_compressed_double_factorized_hamiltonians/demo.py b/demonstrations_v2/tutorial_how_to_build_compressed_double_factorized_hamiltonians/demo.py index 5adcc44881..94ffa369b2 100644 --- a/demonstrations_v2/tutorial_how_to_build_compressed_double_factorized_hamiltonians/demo.py +++ b/demonstrations_v2/tutorial_how_to_build_compressed_double_factorized_hamiltonians/demo.py @@ -30,13 +30,13 @@ :math:`h_{pq}` and :math:`g_{pqrs}` using the :func:`~pennylane.qchem.electron_integrals` function: """ -import pennylane as qml +import pennylane as qp symbols = ["H", "H", "H", "H"] -geometry = qml.math.array([[0., 0., -0.2], [0., 0., -0.1], [0., 0., 0.1], [0., 0., 0.2]]) +geometry = qp.math.array([[0., 0., -0.2], [0., 0., -0.1], [0., 0., 0.1], [0., 0., 0.2]]) -mol = qml.qchem.Molecule(symbols, geometry) -nuc_core, one_body, two_body = qml.qchem.electron_integrals(mol)() +mol = qp.qchem.Molecule(symbols, geometry) +nuc_core, one_body, two_body = qp.qchem.electron_integrals(mol)() print(f"One-body and two-body tensor shapes: {one_body.shape}, {two_body.shape}") @@ -53,8 +53,8 @@ # We can obtain the :math:`V_{pqrs}` and :math:`T_{pq}` tensors as: # -two_chem = 0.5 * qml.math.swapaxes(two_body, 1, 3) # V_pqrs -one_chem = one_body - 0.5 * qml.math.einsum("pqss", two_body) # T_pq +two_chem = 0.5 * qp.math.swapaxes(two_body, 1, 3) # V_pqrs +one_chem = one_body - 0.5 * qp.math.einsum("pqss", two_body) # T_pq ###################################################################### # A key feature of this representation is that the modified two-body terms can be factorized @@ -87,11 +87,11 @@ # optionally control the ranks of their second factorization (``tol_eigval``) as shown below: # -factors, _, _ = qml.qchem.factorize(two_chem, cholesky=True, tol_factor=1e-5) +factors, _, _ = qp.qchem.factorize(two_chem, cholesky=True, tol_factor=1e-5) print("Shape of the factors: ", factors.shape) -approx_two_chem = qml.math.tensordot(factors, factors, axes=([0], [0])) -assert qml.math.allclose(approx_two_chem, two_chem, atol=1e-5) +approx_two_chem = qp.math.tensordot(factors, factors, axes=([0], [0])) +assert qp.math.allclose(approx_two_chem, two_chem, atol=1e-5) ###################################################################### # Performing block-invariant symmetry shift @@ -105,7 +105,7 @@ # the symmetry-shifted integral tensors and core constant: # -core_shift, one_shift, two_shift = qml.qchem.symmetry_shift( +core_shift, one_shift, two_shift = qp.qchem.symmetry_shift( nuc_core, one_chem, two_chem, n_elec = mol.n_electrons ) # symmetry-shifted terms of the Hamiltonian @@ -146,16 +146,16 @@ # if the ``regularization`` keyword argument is set to either ``"L1"`` or ``"L2"``: # -_, two_body_cores, two_body_leaves = qml.qchem.factorize( +_, two_body_cores, two_body_leaves = qp.qchem.factorize( two_shift, tol_factor=1e-2, cholesky=True, compressed=True, regularization="L2" ) # compressed double-factorized shifted two-body terms with "L2" regularization print(f"Two-body tensors' shape: {two_body_cores.shape, two_body_leaves.shape}") -approx_two_shift = qml.math.einsum( +approx_two_shift = qp.math.einsum( "tpk,tqk,tkl,trl,tsl->pqrs", two_body_leaves, two_body_leaves, two_body_cores, two_body_leaves, two_body_leaves ) # computing V^\prime and comparing it with V below -assert qml.math.allclose(approx_two_shift, two_shift, atol=1e-2) +assert qp.math.allclose(approx_two_shift, two_shift, atol=1e-2) ###################################################################### # While the previous shape output for the factors ``(10, 4, 4)`` meant we had :math:`10` two-body @@ -190,15 +190,15 @@ # the orthonormal :math:`U^{\prime(0)}` and symmetric :math:`Z^{\prime(0)}` tensors instead: # -two_core_prime = (qml.math.eye(mol.n_orbitals) * two_body_cores.sum(axis=-1)[:, None, :]) -one_body_extra = qml.math.einsum( +two_core_prime = (qp.math.eye(mol.n_orbitals) * two_body_cores.sum(axis=-1)[:, None, :]) +one_body_extra = qp.math.einsum( 'tpk,tkk,tqk->pq', two_body_leaves, two_core_prime, two_body_leaves ) # one-body correction # factorize the corrected one-body tensor to obtain the core and leaf tensors -one_body_eigvals, one_body_eigvecs = qml.math.linalg.eigh(one_shift + one_body_extra) -one_body_cores = qml.math.expand_dims(qml.math.diag(one_body_eigvals), axis=0) -one_body_leaves = qml.math.expand_dims(one_body_eigvecs, axis=0) +one_body_eigvals, one_body_eigvecs = qp.math.linalg.eigh(one_shift + one_body_extra) +one_body_cores = qp.math.expand_dims(qp.math.diag(one_body_eigvals), axis=0) +one_body_leaves = qp.math.expand_dims(one_body_eigvecs, axis=0) print(f"One-body tensors' shape: {one_body_cores.shape, one_body_leaves.shape}") @@ -212,8 +212,8 @@ cdf_hamiltonian = { "nuc_constant": core_shift[0], - "core_tensors": qml.math.concatenate((one_body_cores, two_body_cores), axis=0), - "leaf_tensors": qml.math.concatenate((one_body_leaves, two_body_leaves), axis=0), + "core_tensors": qp.math.concatenate((one_body_cores, two_body_cores), axis=0), + "leaf_tensors": qp.math.concatenate((one_body_leaves, two_body_leaves), axis=0), } # CDF Hamiltonian ###################################################################### @@ -233,8 +233,8 @@ def leaf_unitary_rotation(leaf, wires): """Applies the basis rotation transformation corresponding to the leaf tensor.""" - basis_mat = qml.math.kron(leaf, qml.math.eye(2)) # account for spin - return qml.BasisRotation(unitary_matrix=basis_mat, wires=wires) + basis_mat = qp.math.kron(leaf, qp.math.eye(2)) # account for spin + return qp.BasisRotation(unitary_matrix=basis_mat, wires=wires) ###################################################################### # Similarly, the unitary transformation for the core tensors can be applied efficiently @@ -250,19 +250,19 @@ def core_unitary_rotation(core, body_type, wires): """Applies the unitary transformation corresponding to the core tensor.""" ops = [] if body_type == "one_body": # implements one-body term - for wire, cval in enumerate(qml.math.diag(core)): + for wire, cval in enumerate(qp.math.diag(core)): for sigma in [0, 1]: - ops.append(qml.RZ(-cval, wires=2 * wire + sigma)) - ops.append(qml.GlobalPhase(qml.math.sum(core), wires=wires)) + ops.append(qp.RZ(-cval, wires=2 * wire + sigma)) + ops.append(qp.GlobalPhase(qp.math.sum(core), wires=wires)) if body_type == "two_body": # implements two-body term for odx1, odx2 in it.product(range(len(wires) // 2), repeat=2): cval = core[odx1, odx2] / 4.0 for sigma, tau in it.product(range(2), repeat=2): if odx1 != odx2 or sigma != tau: - ops.append(qml.IsingZZ(cval, wires=[2*odx1+sigma, 2*odx2+tau])) - gphase = 0.5 * qml.math.sum(core) - 0.25 * qml.math.trace(core) - ops.append(qml.GlobalPhase(-gphase, wires=wires)) + ops.append(qp.IsingZZ(cval, wires=[2*odx1+sigma, 2*odx2+tau])) + gphase = 0.5 * qp.math.sum(core) - 0.25 * qp.math.trace(core) + ops.append(qp.GlobalPhase(-gphase, wires=wires)) return ops ###################################################################### @@ -296,7 +296,7 @@ def CDFTrotterStep(time, cdf_ham, wires): for bidx, (core, leaf) in enumerate(zip(cores, leaves)): # Note: only the first term is one-body, others are two-body body_type = "two_body" if bidx else "one_body" - qml.prod( + qp.prod( # revert the change-of-basis for leaf tensor leaf_unitary_rotation(leaf.conjugate().T, wires), # apply the rotation for core tensor scaled by the time-step @@ -313,14 +313,14 @@ def CDFTrotterStep(time, cdf_ham, wires): # time, circ_wires = 1.0, range(2 * mol.n_orbitals) -hf_state = qml.qchem.hf_state(electrons=mol.n_electrons, orbitals=len(circ_wires)) +hf_state = qp.qchem.hf_state(electrons=mol.n_electrons, orbitals=len(circ_wires)) -@qml.qnode(qml.device("lightning.qubit", wires=circ_wires)) +@qp.qnode(qp.device("lightning.qubit", wires=circ_wires)) def cdf_circuit(n_steps, order): - qml.BasisState(hf_state, wires=circ_wires) - qml.trotterize(CDFTrotterStep, n_steps, order)(time, cdf_hamiltonian, circ_wires) - qml.GlobalPhase(cdf_hamiltonian["nuc_constant"], wires=circ_wires) - return qml.state() + qp.BasisState(hf_state, wires=circ_wires) + qp.trotterize(CDFTrotterStep, n_steps, order)(time, cdf_hamiltonian, circ_wires) + qp.GlobalPhase(cdf_hamiltonian["nuc_constant"], wires=circ_wires) + return qp.state() circuit_state = cdf_circuit(n_steps=10, order=2) @@ -334,11 +334,11 @@ def cdf_circuit(n_steps, order): from scipy.linalg import expm # Evolve the state vector |0...0> to the |HF> state of the system -init_state = qml.math.array([1] + [0] * (2**len(circ_wires) - 1)) -hf_state_vec = qml.matrix(qml.BasisState(hf_state, wires=circ_wires)) @ init_state +init_state = qp.math.array([1] + [0] * (2**len(circ_wires) - 1)) +hf_state_vec = qp.matrix(qp.BasisState(hf_state, wires=circ_wires)) @ init_state -H = qml.qchem.molecular_hamiltonian(mol)[0] # original Hamiltonian -evolved_state = expm(-1j * qml.matrix(H) * time) @ hf_state_vec # e^{-iHt} @ |HF> +H = qp.qchem.molecular_hamiltonian(mol)[0] # original Hamiltonian +evolved_state = expm(-1j * qp.matrix(H) * time) @ hf_state_vec # e^{-iHt} @ |HF> print(f"Fidelity of two states: {fidelity_statevector(circuit_state, evolved_state)}") diff --git a/demonstrations_v2/tutorial_how_to_build_compressed_double_factorized_hamiltonians/metadata.json b/demonstrations_v2/tutorial_how_to_build_compressed_double_factorized_hamiltonians/metadata.json index 726724911e..bc0bf3763d 100644 --- a/demonstrations_v2/tutorial_how_to_build_compressed_double_factorized_hamiltonians/metadata.json +++ b/demonstrations_v2/tutorial_how_to_build_compressed_double_factorized_hamiltonians/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2025-03-05T09:00:00+00:00", - "dateOfLastModification": "2026-01-14T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Chemistry", "Algorithms", diff --git a/demonstrations_v2/tutorial_how_to_build_spin_hamiltonians/demo.py b/demonstrations_v2/tutorial_how_to_build_spin_hamiltonians/demo.py index 668029bc10..ffa93d9dab 100644 --- a/demonstrations_v2/tutorial_how_to_build_spin_hamiltonians/demo.py +++ b/demonstrations_v2/tutorial_how_to_build_spin_hamiltonians/demo.py @@ -22,7 +22,7 @@ # --------------------- # PennyLane provides a set of built-in # `functions `__ -# in the `qml.spin `__ module for +# in the `qp.spin `__ module for # constructing spin Hamiltonians with minimal input needed from the user: we only need to specify # the lattice that describes spin sites and the parameters that describe the interactions in our # system. Let’s look at some examples for the models that are currently supported in PennyLane. @@ -58,13 +58,13 @@ # :math:`2 \times 2 = 4` sites in total. We will provide more details on constructing lattices in # the following sections. -import pennylane as qml +import pennylane as qp n_cells = [2, 2] hopping = 0.2 onsite = 0.3 -hamiltonian = qml.spin.fermi_hubbard('square', n_cells, hopping, onsite) +hamiltonian = qp.spin.fermi_hubbard('square', n_cells, hopping, onsite) print('Hamiltonian:\n') hamiltonian @@ -103,7 +103,7 @@ def plot(lattice, figsize=None, showlabel=True): plt.axis("off") plt.show() -lattice = qml.spin.generate_lattice('square', n_cells) +lattice = qp.spin.generate_lattice('square', n_cells) plot(lattice) ###################################################################### @@ -125,9 +125,9 @@ def plot(lattice, figsize=None, showlabel=True): # can be constructed on a ``triangle`` lattice as follows. coupling = [0.5, 0.5, 0.5] -hamiltonian = qml.spin.heisenberg('triangle', n_cells, coupling) +hamiltonian = qp.spin.heisenberg('triangle', n_cells, coupling) -lattice = qml.spin.generate_lattice('triangle', n_cells) +lattice = qp.spin.generate_lattice('triangle', n_cells) plot(lattice) ###################################################################### @@ -146,9 +146,9 @@ def plot(lattice, figsize=None, showlabel=True): # ``honeycomb`` lattice as follows. coupling, h = 0.5, 1.0 -hamiltonian = qml.spin.transverse_ising('honeycomb', n_cells, coupling, h) +hamiltonian = qp.spin.transverse_ising('honeycomb', n_cells, coupling, h) -lattice = qml.spin.generate_lattice('honeycomb', n_cells) +lattice = qp.spin.generate_lattice('honeycomb', n_cells) plot(lattice) ###################################################################### @@ -167,7 +167,7 @@ def plot(lattice, figsize=None, showlabel=True): # are the coupling constants in each direction. The Hamiltonian can be constructed as follows. coupling = [0.5, 0.6, 0.7] -hamiltonian = qml.spin.kitaev(n_cells, coupling) +hamiltonian = qp.spin.kitaev(n_cells, coupling) ###################################################################### # Haldane model @@ -192,9 +192,9 @@ def plot(lattice, figsize=None, showlabel=True): hopping = 0.5 hopping_next = 1.0 phi = 0.1 -hamiltonian = qml.spin.haldane('kagome', n_cells, hopping, hopping_next, phi) +hamiltonian = qp.spin.haldane('kagome', n_cells, hopping, hopping_next, phi) -lattice = qml.spin.generate_lattice('kagome', n_cells) +lattice = qp.spin.generate_lattice('kagome', n_cells) plot(lattice) ###################################################################### @@ -220,9 +220,9 @@ def plot(lattice, figsize=None, showlabel=True): hopping = 0.5 coulomb = 1.0 intersite_coupling = 0.2 -hamiltonian = qml.spin.emery('lieb', n_cells, hopping, coulomb, intersite_coupling) +hamiltonian = qp.spin.emery('lieb', n_cells, hopping, coulomb, intersite_coupling) -lattice = qml.spin.generate_lattice('lieb', n_cells) +lattice = qp.spin.generate_lattice('lieb', n_cells) plot(lattice) ###################################################################### @@ -252,7 +252,7 @@ def plot(lattice, figsize=None, showlabel=True): # :math:`3 \times 3 = 9` cells. Because each cell of the ``square`` lattice contains only one # site, we get :math:`9` sites in total, which are all connected to their nearest neighbor. -lattice = qml.spin.generate_lattice('square', [3, 3]) +lattice = qp.spin.generate_lattice('square', [3, 3]) ###################################################################### # To visualize this lattice, we use the plotting function we created before. @@ -368,7 +368,7 @@ def plot(lattice, figsize=None, showlabel=True): # Now we pass the lattice object to the :func:`~.pennylane.spin.spin_hamiltonian` function, which is # a helper function that constructs a Hamiltonian from a lattice object. -hamiltonian = qml.spin.spin_hamiltonian(lattice=lattice) +hamiltonian = qp.spin.spin_hamiltonian(lattice=lattice) ###################################################################### # Alternatively, you can build the Hamiltonian manually by looping over the custom edges @@ -386,7 +386,7 @@ def plot(lattice, figsize=None, showlabel=True): ###################################################################### # You can see that it is easy and intuitive to construct this anisotropic Hamiltonian with the tools -# available in the `qml.spin `__ module. You can +# available in the `qp.spin `__ module. You can # use these tools to construct custom Hamiltonians for other interesting systems. # # Conclusion diff --git a/demonstrations_v2/tutorial_how_to_build_spin_hamiltonians/metadata.json b/demonstrations_v2/tutorial_how_to_build_spin_hamiltonians/metadata.json index 3e69b0f39a..978b3839f6 100644 --- a/demonstrations_v2/tutorial_how_to_build_spin_hamiltonians/metadata.json +++ b/demonstrations_v2/tutorial_how_to_build_spin_hamiltonians/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-12-05T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Getting Started", "How-to" diff --git a/demonstrations_v2/tutorial_how_to_collect_mcm_stats/demo.py b/demonstrations_v2/tutorial_how_to_collect_mcm_stats/demo.py index 31982228b0..955b4ca4ac 100644 --- a/demonstrations_v2/tutorial_how_to_collect_mcm_stats/demo.py +++ b/demonstrations_v2/tutorial_how_to_collect_mcm_stats/demo.py @@ -31,7 +31,7 @@ # Along the way, we perform some standard imports and set a randomness seed. # -import pennylane as qml +import pennylane as qp import numpy as np np.random.seed(511) @@ -45,18 +45,18 @@ def ansatz(x): # Rotate all qubits for w, x_ in enumerate(x): - qml.RX(x_, w) + qp.RX(x_, w) # Measure first qubit - mcms.append(qml.measure(first_wire)) + mcms.append(qp.measure(first_wire)) # Entangle all qubits with first qubit for w in other_wires: - qml.CNOT([first_wire, w]) + qp.CNOT([first_wire, w]) # Measure and reset all qubits but the first for w in other_wires: - mcms.append(qml.measure(w, reset=True)) + mcms.append(qp.measure(w, reset=True)) return mcms @@ -76,16 +76,16 @@ def ansatz(x): # To implement the ``QNode``, we also define a shot-based qubit device. # -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") -@qml.set_shots(100) -@qml.qnode(dev) +@qp.set_shots(100) +@qp.qnode(dev) def simple_node(x): # apply the ansatz, and collect mid-circuit measurements. mcm1 is the measurement # of wire 0, and mcms2 is a list of measurements of the other wires. mcm1, *mcms2 = ansatz(x) - return qml.probs(op=mcm1), qml.counts(mcms2) + return qp.probs(op=mcm1), qp.counts(mcms2) ###################################################################### @@ -94,13 +94,13 @@ def simple_node(x): # x = np.random.random(4) -fig, ax = qml.draw_mpl(simple_node)(x) +fig, ax = qp.draw_mpl(simple_node)(x) ###################################################################### # Neat, let's move on to executing the circuit. We apply the ``defer_measurements`` transform to # the ``QNode`` because it allows for fast evaluation even with many shots. -probs, counts = qml.defer_measurements(simple_node)(x) +probs, counts = qp.defer_measurements(simple_node)(x) print(f"Probability vector of first qubit MCM: {np.round(probs, 5)}") print(f"Bit string counts on other qubits: {counts}") @@ -119,13 +119,13 @@ def simple_node(x): # -@qml.set_shots(100) -@qml.qnode(dev) +@qp.set_shots(100) +@qp.qnode(dev) def interesting_qnode(x): first_mcms = ansatz(x) second_mcms = ansatz(-x) output = comparing_function(first_mcms, second_mcms) - return qml.counts(output) + return qp.counts(output) ###################################################################### @@ -158,7 +158,7 @@ def comparing_function(first_mcms, second_mcms): # We can again inspect this ``QNode`` by drawing it: # -fig, ax = qml.draw_mpl(interesting_qnode)(x) +fig, ax = qp.draw_mpl(interesting_qnode)(x) ###################################################################### # Note how all mid-circuit measurements feed into the classical output variable. @@ -166,7 +166,7 @@ def comparing_function(first_mcms, second_mcms): # Finally we may run the ``QNode`` and obtain the statistics for our comparison function: # -print(qml.defer_measurements(interesting_qnode)(x)) +print(qp.defer_measurements(interesting_qnode)(x)) ###################################################################### # We find that our question is answered with "yes" in about :math:`2/3` of all samples. @@ -174,7 +174,7 @@ def comparing_function(first_mcms, second_mcms): # num_shots = 10000 -counts = qml.set_shots(qml.defer_measurements(interesting_qnode), shots=num_shots)(x) +counts = qp.set_shots(qp.defer_measurements(interesting_qnode), shots=num_shots)(x) p_yes = counts[True] / num_shots p_no = counts[False] / num_shots print(f'The probability to answer with "yes" / "no" is {p_yes:.5f} / {p_no:.5f}') @@ -195,7 +195,7 @@ def comparing_function(first_mcms, second_mcms): # never see bit strings with differing second and third bits. # Sampling more shots eventually reveals this, even though they remain rare: -probs, counts = qml.set_shots(qml.defer_measurements(simple_node), shots=10000)(x) +probs, counts = qp.set_shots(qp.defer_measurements(simple_node), shots=10000)(x) print(f"Bit string counts on last three qubits: {counts}") ###################################################################### @@ -204,11 +204,11 @@ def comparing_function(first_mcms, second_mcms): # # Before finishing, we discuss the return types that are supported for (postprocessed) MCMs. # Depending on the processing applied to the MCM results, not all return types are supported. -# ``qml.probs(mcm0 * mcm1)``, for example, is not a valid return value, because it is not clear +# ``qp.probs(mcm0 * mcm1)``, for example, is not a valid return value, because it is not clear # which probabilities are being requested. # # Furthermore, available return types depend on whether or not the device is -# shot-based (``qml.sample`` can not be returned if the device is not sampling). +# shot-based (``qp.sample`` can not be returned if the device is not sampling). # Overall, **all combinations of post-processing and all of** # :func:`~.pennylane.expval`, # :func:`~.pennylane.var`, @@ -217,10 +217,10 @@ def comparing_function(first_mcms, second_mcms): # :func:`~.pennylane.counts`, # **are supported** for mid-circuit measurements with the following exceptions: # -# - ``qml.sample`` and ``qml.counts`` are not supported for ``shots=None``. -# - ``qml.probs`` is not supported for MCMs collected in arithmetic expressions. -# - ``qml.expval`` and ``qml.var`` are not supported for sequences of MCMs. -# ``qml.probs``, ``qml.sample``, and ``qml.counts`` are supported for sequences but +# - ``qp.sample`` and ``qp.counts`` are not supported for ``shots=None``. +# - ``qp.probs`` is not supported for MCMs collected in arithmetic expressions. +# - ``qp.expval`` and ``qp.var`` are not supported for sequences of MCMs. +# ``qp.probs``, ``qp.sample``, and ``qp.counts`` are supported for sequences but # only if they do not contain arithmetic expressions of these MCMs. # # For more details also consider the diff --git a/demonstrations_v2/tutorial_how_to_collect_mcm_stats/metadata.json b/demonstrations_v2/tutorial_how_to_collect_mcm_stats/metadata.json index 024dcbb1bb..8f1f7fe2b2 100644 --- a/demonstrations_v2/tutorial_how_to_collect_mcm_stats/metadata.json +++ b/demonstrations_v2/tutorial_how_to_collect_mcm_stats/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-04-26T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Getting Started", "Quantum Computing", diff --git a/demonstrations_v2/tutorial_how_to_create_dynamic_mcm_circuits/demo.py b/demonstrations_v2/tutorial_how_to_create_dynamic_mcm_circuits/demo.py index 2379f36c3e..c6bbb91081 100644 --- a/demonstrations_v2/tutorial_how_to_create_dynamic_mcm_circuits/demo.py +++ b/demonstrations_v2/tutorial_how_to_create_dynamic_mcm_circuits/demo.py @@ -41,21 +41,21 @@ # - Finally, the expectation value of the Pauli ``Y`` operator on the first qubit is returned. # -import pennylane as qml +import pennylane as qp import numpy as np -dev = qml.device("lightning.qubit", wires=2) +dev = qp.device("lightning.qubit", wires=2) -@qml.qnode(dev, interface="numpy") +@qp.qnode(dev, interface="numpy") def circuit(x): - qml.RX(x, 0) - qml.T(1) - qml.CNOT(wires=[0, 1]) - mcm = qml.measure(1) - qml.cond(mcm, qml.S)(wires=0) + qp.RX(x, 0) + qp.T(1) + qp.CNOT(wires=[0, 1]) + mcm = qp.measure(1) + qp.cond(mcm, qp.S)(wires=0) - return qml.expval(qml.Y(0)) + return qp.expval(qp.Y(0)) x = 1.361 @@ -89,11 +89,11 @@ def circuit(x): def init_state(x): # Rotate the first three qubits for w in range(3): - qml.RX(x[w], w) + qp.RX(x[w], w) # Entangle the first three qubits - qml.CNOT([0, 1]) - qml.CNOT([1, 2]) - qml.CNOT([2, 0]) + qp.CNOT([0, 1]) + qp.CNOT([1, 2]) + qp.CNOT([2, 0]) ###################################################################### @@ -102,19 +102,19 @@ def init_state(x): # shots = 100 -dev = qml.device("default.qubit", seed=0) +dev = qp.device("default.qubit", seed=0) -@qml.set_shots(shots) -@qml.qnode(dev) +@qp.set_shots(shots) +@qp.qnode(dev) def create_half_filled_state(x): init_state(x) for w in range(3): # Measure one qubit at a time and flip another, fresh qubit if measured 0 - mcm = qml.measure(w) - qml.cond(~mcm, qml.X)(w + 3) + mcm = qp.measure(w) + qp.cond(~mcm, qp.X)(w + 3) - return qml.counts(wires=range(6)) + return qp.counts(wires=range(6)) ###################################################################### @@ -124,7 +124,7 @@ def create_half_filled_state(x): np.random.seed(652) x = np.random.random(3) * np.pi -print(qml.draw(create_half_filled_state)(x)) +print(qp.draw(create_half_filled_state)(x)) ###################################################################### # We see an initial block of gates that prepares the starting state on the @@ -153,16 +153,16 @@ def create_half_filled_state(x): # -@qml.set_shots(shots) -@qml.qnode(dev) +@qp.set_shots(shots) +@qp.qnode(dev) def postselect_half_filled_state(x, selection): init_state(x) for w in range(3): # Postselect the measured qubit to match the selection criterion - mcm = qml.measure(w, postselect=selection[w]) - qml.cond(~mcm, qml.X)(w + 3) + mcm = qp.measure(w, postselect=selection[w]) + qp.cond(~mcm, qp.X)(w + 3) - return qml.counts(wires=range(6)) + return qp.counts(wires=range(6)) ###################################################################### @@ -173,7 +173,7 @@ def postselect_half_filled_state(x, selection): # selection = [0, None, 1] -print(qml.draw(postselect_half_filled_state)(x, selection)) +print(qp.draw(postselect_half_filled_state)(x, selection)) ###################################################################### # Note the indicated postselection values next to the drawn MCMs. @@ -203,28 +203,28 @@ def postselect_half_filled_state(x, selection): # -@qml.set_shots(shots) -@qml.qnode(dev) +@qp.set_shots(shots) +@qp.qnode(dev) def create_selected_half_filled_state(x, selection): init_state(x) all_mcms = [] for w in range(3): # Don't postselect on the selection criterion, but store the MCM for later - mcm = qml.measure(w) - qml.cond(~mcm, qml.X)(w + 3) + mcm = qp.measure(w) + qp.cond(~mcm, qp.X)(w + 3) all_mcms.append(mcm) for w, sel, mcm in zip(range(3), selection, all_mcms): # If the postselection criterion is not None, flip the corresponding pair # of qubits conditioned on the mcm not satisfying the selection criterion if sel is not None: - qml.cond(mcm != sel, qml.X)(w) - qml.cond(mcm != sel, qml.X)(w + 3) + qp.cond(mcm != sel, qp.X)(w) + qp.cond(mcm != sel, qp.X)(w + 3) - return qml.counts(wires=range(6)) + return qp.counts(wires=range(6)) -print(qml.draw(create_selected_half_filled_state)(x, selection)) +print(qp.draw(create_selected_half_filled_state)(x, selection)) ###################################################################### # We can see how the measured values are fed not only into the original conditioned operation, @@ -244,7 +244,7 @@ def create_selected_half_filled_state(x, selection): # Note that we kept all samples because we did not postselect, and that (in this particular case) # this evened out the probabilities of measuring either of the two possible bit strings. # Also, note that we conditionally -# applied the bit flip operators ``qml.X`` by comparing an MCM result to +# applied the bit flip operators ``qp.X`` by comparing an MCM result to # the corresponding selection criterion (``mcm!=sel``). More generally, MCM # results in PennyLane can be processed with standard arithmetic operations. For details, # see the `introduction to MCMs diff --git a/demonstrations_v2/tutorial_how_to_create_dynamic_mcm_circuits/metadata.json b/demonstrations_v2/tutorial_how_to_create_dynamic_mcm_circuits/metadata.json index a5e76d316e..0685a66ea7 100644 --- a/demonstrations_v2/tutorial_how_to_create_dynamic_mcm_circuits/metadata.json +++ b/demonstrations_v2/tutorial_how_to_create_dynamic_mcm_circuits/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-05-03T00:00:00+00:00", - "dateOfLastModification": "2026-01-14T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Getting Started", "Quantum Computing", diff --git a/demonstrations_v2/tutorial_how_to_import_qiskit_noise_models/demo.py b/demonstrations_v2/tutorial_how_to_import_qiskit_noise_models/demo.py index 6692442181..dd98f79a94 100644 --- a/demonstrations_v2/tutorial_how_to_import_qiskit_noise_models/demo.py +++ b/demonstrations_v2/tutorial_how_to_import_qiskit_noise_models/demo.py @@ -10,7 +10,7 @@ different approaches for storing and building Kraus operators to construct noise models. In this how-to guide, we will first compare the construction of noise models in `Qiskit `_ and -`PennyLane `_. Then, we will learn how to +`PennyLane `_. Then, we will learn how to convert a Qiskit noise model into an equivalent PennyLane one, allowing users to import any custom user-defined or fake backend-based noise models. """ @@ -75,25 +75,25 @@ # :doc:`how-to for noise models in PennyLane `. 🧑‍🏫 # -import pennylane as qml +import pennylane as qp # Depolarization error for single-qubit gates -gate1_fcond = qml.noise.op_in(["U1", "U2", "U3"]) & qml.noise.wires_in(range(n_qubits)) -gate1_noise = qml.noise.partial_wires(qml.DepolarizingChannel, prob_depol) +gate1_fcond = qp.noise.op_in(["U1", "U2", "U3"]) & qp.noise.wires_in(range(n_qubits)) +gate1_noise = qp.noise.partial_wires(qp.DepolarizingChannel, prob_depol) # Bit flip errors for two-qubit gate -gate2_fcond = qml.noise.op_eq("CNOT") +gate2_fcond = qp.noise.op_eq("CNOT") def gate2_noise(op, **metadata): - qml.BitFlip(prob_bit_flip, op.wires[1]) + qp.BitFlip(prob_bit_flip, op.wires[1]) # Readout errors for measurements -rmeas_fcond = qml.noise.meas_eq(qml.counts) +rmeas_fcond = qp.noise.meas_eq(qp.counts) def rmeas_noise(op, **metadata): for wire in op.wires: - qml.GeneralizedAmplitudeDamping(prob_ampl_damp[wire], exc_population, wire) + qp.GeneralizedAmplitudeDamping(prob_ampl_damp[wire], exc_population, wire) # Building the PennyLane noise model -model_pl = qml.NoiseModel( +model_pl = qp.NoiseModel( {gate1_fcond: gate1_noise, gate2_fcond: gate2_noise}, {rmeas_fcond: rmeas_noise}, ) @@ -112,19 +112,19 @@ def rmeas_noise(op, **metadata): # Preparing the devices n_shots = int(2e6) -dev_pl_ideal = qml.device("default.mixed", wires=n_qubits) -dev_qk_noisy = qml.device("qiskit.aer", wires=n_qubits, noise_model=model_qk) +dev_pl_ideal = qp.device("default.mixed", wires=n_qubits) +dev_qk_noisy = qp.device("qiskit.aer", wires=n_qubits, noise_model=model_qk) def GHZcircuit(): - qml.U2(0, np.pi, wires=[0]) + qp.U2(0, np.pi, wires=[0]) for wire in range(n_qubits-1): - qml.CNOT([wire, wire + 1]) - return qml.counts(wires=range(n_qubits), all_outcomes=True) + qp.CNOT([wire, wire + 1]) + return qp.counts(wires=range(n_qubits), all_outcomes=True) # Preparing the circuits -pl_ideal_circ = qml.set_shots(qml.QNode(GHZcircuit, dev_pl_ideal), shots = n_shots) -pl_noisy_circ = qml.add_noise(pl_ideal_circ, noise_model=model_pl) -qk_noisy_circ = qml.set_shots(qml.QNode(GHZcircuit, dev_qk_noisy), shots = n_shots) +pl_ideal_circ = qp.set_shots(qp.QNode(GHZcircuit, dev_pl_ideal), shots = n_shots) +pl_noisy_circ = qp.add_noise(pl_ideal_circ, noise_model=model_pl) +qk_noisy_circ = qp.set_shots(qp.QNode(GHZcircuit, dev_qk_noisy), shots = n_shots) # Preparing the results pl_noisy_res, qk_noisy_res = pl_noisy_circ(), qk_noisy_circ() @@ -169,7 +169,7 @@ def GHZcircuit(): # To import this noise model as a PennyLane one, we simply do: # -pl_noise_model = qml.from_qiskit_noise(qk_noise_model) +pl_noise_model = qp.from_qiskit_noise(qk_noise_model) print(pl_noise_model) ###################################################################### diff --git a/demonstrations_v2/tutorial_how_to_import_qiskit_noise_models/metadata.json b/demonstrations_v2/tutorial_how_to_import_qiskit_noise_models/metadata.json index 60dfb8156c..507cc2b21f 100644 --- a/demonstrations_v2/tutorial_how_to_import_qiskit_noise_models/metadata.json +++ b/demonstrations_v2/tutorial_how_to_import_qiskit_noise_models/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-11-25T00:00:00+00:00", - "dateOfLastModification": "2026-01-14T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Quantum Computing", "How-to" diff --git a/demonstrations_v2/tutorial_how_to_quantum_just_in_time_compile_vqe_catalyst/demo.py b/demonstrations_v2/tutorial_how_to_quantum_just_in_time_compile_vqe_catalyst/demo.py index 51cf6c6c54..1f9c9741d2 100644 --- a/demonstrations_v2/tutorial_how_to_quantum_just_in_time_compile_vqe_catalyst/demo.py +++ b/demonstrations_v2/tutorial_how_to_quantum_just_in_time_compile_vqe_catalyst/demo.py @@ -43,10 +43,10 @@ # service `__: # -import pennylane as qml +import pennylane as qp from pennylane import numpy as np -dataset = qml.data.load('qchem', molname="H3+")[0] +dataset = qp.data.load('qchem', molname="H3+")[0] H, qubits = dataset.hamiltonian, len(dataset.hamiltonian.wires) print(f"qubits: {qubits}") @@ -64,14 +64,14 @@ hf = dataset.hf_state # Define the device, using lightning.qubit device -dev = qml.device("lightning.qubit", wires=qubits) +dev = qp.device("lightning.qubit", wires=qubits) -@qml.qnode(dev, diff_method="adjoint") +@qp.qnode(dev, diff_method="adjoint") def cost(params): - qml.BasisState(hf, wires=range(qubits)) - qml.DoubleExcitation(params[0], wires=[0, 1, 2, 3]) - qml.DoubleExcitation(params[1], wires=[0, 1, 4, 5]) - return qml.expval(H) + qp.BasisState(hf, wires=range(qubits)) + qp.DoubleExcitation(params[0], wires=[0, 1, 2, 3]) + qp.DoubleExcitation(params[1], wires=[0, 1, 4, 5]) + return qp.expval(H) ###################################################################### # Step 3: Optimize the circuit @@ -82,7 +82,7 @@ def cost(params): # init_params = np.array([0.0, 0.0]) -opt = qml.GradientDescentOptimizer(stepsize=0.4) +opt = qp.GradientDescentOptimizer(stepsize=0.4) steps = 10 params = init_params @@ -120,13 +120,13 @@ def cost(params): hf = np.array(dataset.hf_state) -@qml.qjit -@qml.qnode(dev) +@qp.qjit +@qp.qnode(dev) def cost(params): - qml.BasisState(hf, wires=range(qubits)) - qml.DoubleExcitation(params[0], wires=[0, 1, 2, 3]) - qml.DoubleExcitation(params[1], wires=[0, 1, 4, 5]) - return qml.expval(H) + qp.BasisState(hf, wires=range(qubits)) + qp.DoubleExcitation(params[0], wires=[0, 1, 2, 3]) + qp.DoubleExcitation(params[1], wires=[0, 1, 4, 5]) + return qp.expval(H) init_params = jnp.array([0.0, 0.0]) @@ -153,7 +153,7 @@ def cost(params): opt = optax.sgd(learning_rate=0.4) -@qml.qjit +@qp.qjit def update_step(i, params, opt_state): """Perform a single gradient update step""" energy, grads = catalyst.value_and_grad(cost)(params) @@ -177,10 +177,10 @@ def update_step(i, params, opt_state): # leading to further performance improvements: # -@qml.qjit +@qp.qjit def optimization(params): opt_state = opt.init(params) - (params, opt_state) = qml.for_loop(0, 10, 1)(update_step)(params, opt_state) + (params, opt_state) = qp.for_loop(0, 10, 1)(update_step)(params, opt_state) return params final_params = optimization(init_params) diff --git a/demonstrations_v2/tutorial_how_to_quantum_just_in_time_compile_vqe_catalyst/metadata.json b/demonstrations_v2/tutorial_how_to_quantum_just_in_time_compile_vqe_catalyst/metadata.json index 8ca756bf26..0d47296f4a 100644 --- a/demonstrations_v2/tutorial_how_to_quantum_just_in_time_compile_vqe_catalyst/metadata.json +++ b/demonstrations_v2/tutorial_how_to_quantum_just_in_time_compile_vqe_catalyst/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-04-26T00:00:00+00:00", - "dateOfLastModification": "2025-12-10T04:00:00+00:00", + "dateOfLastModification": "2026-04-17T04:00:00+00:00", "categories": [ "Quantum Machine Learning", "Optimization", diff --git a/demonstrations_v2/tutorial_how_to_use_noise_models/demo.py b/demonstrations_v2/tutorial_how_to_use_noise_models/demo.py index b192f5076e..298d9c5f0d 100644 --- a/demonstrations_v2/tutorial_how_to_use_noise_models/demo.py +++ b/demonstrations_v2/tutorial_how_to_use_noise_models/demo.py @@ -58,16 +58,16 @@ # gate operations with :math:`|\phi| < 1.0` and wires :math:`\in \{0, 1\}`: # -import pennylane as qml +import pennylane as qp import numpy as np -@qml.BooleanFn +@qp.BooleanFn def rx_cond(op): - return isinstance(op, qml.RX) and np.abs(op.parameters[0]) < 1.0 + return isinstance(op, qp.RX) and np.abs(op.parameters[0]) < 1.0 # Combine this arbitrary conditional with a wire-based conditional -rx_and_wires_cond = rx_cond & qml.noise.wires_in([0, 1]) -for op in [qml.RX(0.05, wires=[0]), qml.RX(2.34, wires=[1])]: +rx_and_wires_cond = rx_cond & qp.noise.wires_in([0, 1]) +for op in [qp.RX(0.05, wires=[0]), qp.RX(2.34, wires=[1])]: print(f"Result for {op}: {rx_and_wires_cond(op)}") ###################################################################### @@ -89,9 +89,9 @@ def rx_cond(op): # the error that gets queued with an example gate operation: # -depol_error = qml.noise.partial_wires(qml.DepolarizingChannel, 0.01) +depol_error = qp.noise.partial_wires(qp.DepolarizingChannel, 0.01) -op = qml.X('w1') # Example gate operation +op = qp.X('w1') # Example gate operation print(f"Error for {op}: {depol_error(op)}") ###################################################################### @@ -112,11 +112,11 @@ def rx_cond(op): # Next, we construct a pair to mimic thermal relaxation errors that are encountered # during the state preparation via :class:`~.pennylane.ThermalRelaxationError`: -fcond2 = qml.noise.op_eq(qml.StatePrep) +fcond2 = qp.noise.op_eq(qp.StatePrep) def noise2(op, **kwargs): for wire in op.wires: - qml.ThermalRelaxationError(0.1, kwargs["t1"], kwargs["t2"], kwargs["tg"], wire) + qp.ThermalRelaxationError(0.1, kwargs["t1"], kwargs["t2"], kwargs["tg"], wire) ###################################################################### # By default, noise operations specified by a noise function will be inserted *after* the @@ -126,19 +126,19 @@ def noise2(op, **kwargs): # rotation error for :class:`~.pennylane.Hadamard` gates on the wires :math:`\in \{0, 1\}`: # -fcond3 = qml.noise.op_eq("Hadamard") & qml.noise.wires_in([0, 1]) +fcond3 = qp.noise.op_eq("Hadamard") & qp.noise.wires_in([0, 1]) def noise3(op, **kwargs): - qml.RX(np.pi / 16, op.wires) - qml.apply(op) - qml.RY(np.pi / 8, op.wires) + qp.RX(np.pi / 16, op.wires) + qp.apply(op) + qp.RY(np.pi / 8, op.wires) ###################################################################### # Finally, we can build the noise model with some required ``metadata`` for ``noise2``: # metadata = dict(t1=0.02, t2=0.03, tg=0.001) # times unit: sec -noise_model = qml.NoiseModel( +noise_model = qp.NoiseModel( {fcond1: noise1, fcond2: noise2, fcond3: noise3}, **metadata ) print(noise_model) @@ -156,33 +156,33 @@ def noise3(op, **kwargs): from matplotlib import pyplot as plt -qml.drawer.use_style("pennylane") -dev = qml.device("default.mixed", wires=3) +qp.drawer.use_style("pennylane") +dev = qp.device("default.mixed", wires=3) init_state = np.random.RandomState(42).rand(2 ** len(dev.wires)) init_state /= np.linalg.norm(init_state) def circuit(theta, phi): # State preparation - qml.StatePrep(init_state, wires=[0, 1, 2]) + qp.StatePrep(init_state, wires=[0, 1, 2]) # Evolve state - qml.Hadamard(0) - qml.RX(theta, 1) - qml.RX(phi, 2) - qml.CNOT([1, 2]) - qml.CNOT([0, 1]) + qp.Hadamard(0) + qp.RX(theta, 1) + qp.RX(phi, 2) + qp.CNOT([1, 2]) + qp.CNOT([0, 1]) # De-evolve state - qml.CNOT([0, 1]) - qml.CNOT([1, 2]) - qml.RX(-phi, 2) - qml.RX(-theta, 1) - qml.Hadamard(0) - return qml.state() + qp.CNOT([0, 1]) + qp.CNOT([1, 2]) + qp.RX(-phi, 2) + qp.RX(-theta, 1) + qp.Hadamard(0) + return qp.state() theta, phi = 0.21, 0.43 -ideal_circuit = qml.QNode(circuit, dev) -qml.draw_mpl(ideal_circuit)(theta, phi) +ideal_circuit = qp.QNode(circuit, dev) +qp.draw_mpl(ideal_circuit)(theta, phi) plt.show() ###################################################################### @@ -190,8 +190,8 @@ def circuit(theta, phi): # :func:`~.pennylane.add_noise` transform: # -noisy_circuit = qml.add_noise(ideal_circuit, noise_model) -qml.draw_mpl(noisy_circuit)(theta, phi) +noisy_circuit = qp.add_noise(ideal_circuit, noise_model) +qp.draw_mpl(noisy_circuit)(theta, phi) plt.show() ###################################################################### @@ -199,8 +199,8 @@ def circuit(theta, phi): # init_dm = np.outer(init_state, init_state) # density matrix for the init_state -ideal_res = np.round(qml.math.fidelity(ideal_circuit(theta, phi), init_dm), 8) -noisy_res = np.round(qml.math.fidelity(noisy_circuit(theta, phi), init_dm), 8) +ideal_res = np.round(qp.math.fidelity(ideal_circuit(theta, phi), init_dm), 8) +noisy_res = np.round(qp.math.fidelity(noisy_circuit(theta, phi), init_dm), 8) print(f"Ideal v/s Noisy: {ideal_res} and {noisy_res}") diff --git a/demonstrations_v2/tutorial_how_to_use_noise_models/metadata.json b/demonstrations_v2/tutorial_how_to_use_noise_models/metadata.json index f75808a784..b9c207742b 100644 --- a/demonstrations_v2/tutorial_how_to_use_noise_models/metadata.json +++ b/demonstrations_v2/tutorial_how_to_use_noise_models/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-10-01T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Computing", "How-to" diff --git a/demonstrations_v2/tutorial_how_to_use_qualtran_with_pennylane/demo.py b/demonstrations_v2/tutorial_how_to_use_qualtran_with_pennylane/demo.py index c88d8fe54f..ac0b3397ac 100644 --- a/demonstrations_v2/tutorial_how_to_use_qualtran_with_pennylane/demo.py +++ b/demonstrations_v2/tutorial_how_to_use_qualtran_with_pennylane/demo.py @@ -46,10 +46,10 @@ # may not have wires defined. But PennyLane operations do apply to specific wires, so we need to # provide qubit information to :class:`~pennylane.FromBloq` via the ``wires`` argument. -import pennylane as qml +import pennylane as qp from qualtran.bloqs.basic_gates import XGate -bloq_as_op = qml.FromBloq(XGate(), wires=0) +bloq_as_op = qp.FromBloq(XGate(), wires=0) print(bloq_as_op) ###################################################################### @@ -59,7 +59,7 @@ # When wire requirements are complicated, you can use the :func:`~.pennylane.bloq_registers` # helper function to generate the input values for ``wires``: -print(qml.bloq_registers(XGate())) +print(qp.bloq_registers(XGate())) ###################################################################### # This will create register names in accordance to the Bloq's signature. Here, the function created @@ -79,23 +79,23 @@ from qualtran.bloqs.gf_arithmetic import GF2Addition arithmetic_bloq = GF2Addition(4) -wires = qml.bloq_registers(arithmetic_bloq) # This gives us 2 registers, 'x' and 'y' +wires = qp.bloq_registers(arithmetic_bloq) # This gives us 2 registers, 'x' and 'y' print(wires) ###################################################################### five = [0, 1, 0, 1] # 5 in binary ten = [1, 0, 1, 0] # 10 in binary -@qml.set_shots(1) -@qml.qnode(qml.device('default.qubit')) +@qp.set_shots(1) +@qp.qnode(qp.device('default.qubit')) def circuit(): # Prepare the input registers for 5 and 10 - qml.BasisState(five + ten, wires=wires['x']+wires['y']) + qp.BasisState(five + ten, wires=wires['x']+wires['y']) # Sum the two registers - qml.FromBloq(arithmetic_bloq, wires=wires['x']+wires['y']) + qp.FromBloq(arithmetic_bloq, wires=wires['x']+wires['y']) # Measure the output binary string - a = [qml.measure(i) for i in range(len(wires['x']+wires['y']))] - return qml.sample(a) + a = [qp.measure(i) for i in range(len(wires['x']+wires['y']))] + return qp.sample(a) # Simulate the circuit and process binary output to integer binary_string = "".join([str(bit) for bit in circuit()[0]]) @@ -139,13 +139,13 @@ def circuit(): # Smart defaults # ~~~~~~~~~~~~~~ # -# By default, ``qml.to_bloq`` tries its best to translate PennyLane objects to Qualtran-native +# By default, ``qp.to_bloq`` tries its best to translate PennyLane objects to Qualtran-native # objects. This makes certain Qualtran functionalities, such as gate counting and # `generalizers `_, # work more seamlessly. In the following example, PennyLane's :class:`~pennylane.PauliX` operator is # mapped directly to Qualtran's ``XGate``. -op_as_bloq = qml.to_bloq(qml.X(0)) +op_as_bloq = qp.to_bloq(qp.X(0)) print(op_as_bloq) ###################################################################### @@ -157,10 +157,10 @@ def circuit(): # `QubitizationQPE `_. # In cases where the mapping is ambiguous, we get the smart default: -unitary = qml.RY(phi=0.3, wires=[0]) +unitary = qp.RY(phi=0.3, wires=[0]) estimation_wires = [1, 2, 3] -op = qml.QuantumPhaseEstimation(unitary=unitary, estimation_wires=estimation_wires) -qpe_bloq = qml.to_bloq(op) +op = qp.QuantumPhaseEstimation(unitary=unitary, estimation_wires=estimation_wires) +qpe_bloq = qp.to_bloq(op) print(qpe_bloq) ###################################################################### @@ -200,12 +200,12 @@ def circuit(): custom_map = { op: TextbookQPE( - unitary=qml.to_bloq(qml.RY(phi=0.3, wires=[0])), + unitary=qp.to_bloq(qp.RY(phi=0.3, wires=[0])), ctrl_state_prep=LPResourceState(3) ) } -qpe_bloq = qml.to_bloq(op, custom_mapping=custom_map) +qpe_bloq = qp.to_bloq(op, custom_mapping=custom_map) print(qpe_bloq) ###################################################################### @@ -228,10 +228,10 @@ def circuit(): # or smart default -- the circuit is wrapped as a :class:`~pennylane.io.ToBloq` object. def circ(): - qml.X(0) - qml.X(1) + qp.X(0) + qp.X(1) -qfunc_as_bloq = qml.to_bloq(circ) +qfunc_as_bloq = qp.to_bloq(circ) print(type(qfunc_as_bloq)) ###################################################################### @@ -244,10 +244,10 @@ def circ(): # ``map_ops`` to ``False``. This wraps the operators as a ``ToBloq`` object and keeps the original # PennyLane object information. -unitary = qml.RY(phi=0.3, wires=[0]) +unitary = qp.RY(phi=0.3, wires=[0]) estimation_wires = [1, 2, 3] -op = qml.QuantumPhaseEstimation(unitary=unitary, estimation_wires=estimation_wires) -wrapped_qpe_bloq = qml.to_bloq(op, map_ops=False) +op = qp.QuantumPhaseEstimation(unitary=unitary, estimation_wires=estimation_wires) +wrapped_qpe_bloq = qp.to_bloq(op, map_ops=False) print(wrapped_qpe_bloq) ###################################################################### diff --git a/demonstrations_v2/tutorial_how_to_use_qualtran_with_pennylane/metadata.json b/demonstrations_v2/tutorial_how_to_use_qualtran_with_pennylane/metadata.json index 4e6705ab40..67a022e067 100644 --- a/demonstrations_v2/tutorial_how_to_use_qualtran_with_pennylane/metadata.json +++ b/demonstrations_v2/tutorial_how_to_use_qualtran_with_pennylane/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2025-08-18T00:00:00+00:00", - "dateOfLastModification": "2026-01-23T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Quantum Computing", "How-to" From 8436f5dfb82589079217727a7ff8c4fac95f03cc Mon Sep 17 00:00:00 2001 From: drdren <104710745+drdren@users.noreply.github.com> Date: Mon, 20 Apr 2026 17:05:38 -0400 Subject: [PATCH 03/10] qml to qp Batch 5 (#1756) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### Before submitting Please complete the following checklist when submitting a PR: - [ ] Ensure that your tutorial executes correctly, and conforms to the guidelines specified in the [README](https://github.com/PennyLaneAI/demos/blob/master/README.md). - [ ] Remember to do a grammar check of the content you include. - [ ] All tutorials conform to [PEP8 standards](https://www.python.org/dev/peps/pep-0008/). To auto format files, simply `pip install black`, and then run `black -l 100 path/to/file.py`. When all the above are checked, delete everything above the dashed line and fill in the pull request template. ------------------------------------------------------------------------------------------------------------ **Title:** **Summary:** **Relevant references:** **Possible Drawbacks:** **Related GitHub Issues:** ---- If you are writing a demonstration, please answer these questions to facilitate the marketing process. * GOALS — Why are we working on this now? *Eg. Promote a new PL feature or show a PL implementation of a recent paper.* * AUDIENCE — Who is this for? *Eg. Chemistry researchers, PL educators, beginners in quantum computing.* * KEYWORDS — What words should be included in the marketing post? * Which of the following types of documentation is most similar to your file? (more details [here](https://www.notion.so/xanaduai/Different-kinds-of-documentation-69200645fe59442991c71f9e7d8a77f8)) - [ ] Tutorial - [ ] Demo - [ ] How-to Co-authored-by: David --- .../demo.py | 94 +++++----- .../metadata.json | 2 +- .../tutorial_how_to_use_registers/demo.py | 44 ++--- .../metadata.json | 2 +- .../demo.py | 28 +-- .../metadata.json | 2 +- .../demo.py | 36 ++-- .../metadata.json | 2 +- .../demo.py | 14 +- .../metadata.json | 2 +- .../demo.py | 46 ++--- .../metadata.json | 2 +- demonstrations_v2/tutorial_intro_qrom/demo.py | 76 ++++---- .../tutorial_intro_qrom/metadata.json | 2 +- demonstrations_v2/tutorial_intro_qsvt/demo.py | 20 +-- .../tutorial_intro_qsvt/metadata.json | 2 +- .../demo.py | 26 +-- .../metadata.json | 2 +- .../tutorial_isingmodel_PyTorch/demo.py | 12 +- .../tutorial_isingmodel_PyTorch/metadata.json | 2 +- .../tutorial_jax_transformations/demo.py | 32 ++-- .../metadata.json | 2 +- .../tutorial_kak_decomposition/demo.py | 58 +++--- .../tutorial_kak_decomposition/metadata.json | 2 +- .../tutorial_kernel_based_training/demo.py | 18 +- .../metadata.json | 2 +- .../tutorial_kernels_module/demo.py | 40 ++--- .../tutorial_kernels_module/metadata.json | 2 +- .../tutorial_lcu_blockencoding/demo.py | 50 +++--- .../tutorial_lcu_blockencoding/metadata.json | 2 +- .../demo.py | 74 ++++---- .../metadata.json | 2 +- .../tutorial_learning_few_data/demo.py | 36 ++-- .../tutorial_learning_few_data/metadata.json | 2 +- .../demo.py | 48 ++--- .../metadata.json | 2 +- .../tutorial_learningshallow/demo.py | 168 +++++++++--------- .../tutorial_learningshallow/metadata.json | 2 +- 38 files changed, 479 insertions(+), 479 deletions(-) diff --git a/demonstrations_v2/tutorial_how_to_use_quantum_arithmetic_operators/demo.py b/demonstrations_v2/tutorial_how_to_use_quantum_arithmetic_operators/demo.py index 306e203429..d6634e8af1 100644 --- a/demonstrations_v2/tutorial_how_to_use_quantum_arithmetic_operators/demo.py +++ b/demonstrations_v2/tutorial_how_to_use_quantum_arithmetic_operators/demo.py @@ -66,10 +66,10 @@ we will work with. We define wires for input registers, the output register, and also additional ``work_wires`` that will be important when we later discuss the :class:`~.pennylane.Multiplier` operator. """ -import pennylane as qml +import pennylane as qp # we indicate the name of the registers and their number of qubits. -wires = qml.registers({"x": 4, "y":4, "output":6,"work_wires": 4}) +wires = qp.registers({"x": 4, "y":4, "output":6,"work_wires": 4}) ###################################################################### # Now, we write a circuit to prepare the state :math:`|x \rangle|y \rangle|0 \rangle`, which will be needed for the out-place @@ -77,15 +77,15 @@ # you could introduce any quantum state as input. def product_basis_state(x=0,y=0): - qml.BasisState(x, wires=wires["x"]) - qml.BasisState(y, wires=wires["y"]) + qp.BasisState(x, wires=wires["x"]) + qp.BasisState(y, wires=wires["y"]) -dev = qml.device("default.qubit") -@qml.set_shots(1) -@qml.qnode(dev) +dev = qp.device("default.qubit") +@qp.set_shots(1) +@qp.qnode(dev) def circuit(x,y): product_basis_state(x, y) - return {name: qml.sample(wires=wires[name]) for name in ["x", "y", "output"]} + return {name: qp.sample(wires=wires[name]) for name in ["x", "y", "output"]} ###################################################################### # Since the arithmetic operations are deterministic, a single shot is enough to sample @@ -109,14 +109,14 @@ def state_to_decimal(binary_array): # Now we can implement an example for the :class:`~.pennylane.Adder` operator. We will add the integer :math:`5` to the ``wires["x"]`` register # that stores the state :math:`|x \rangle=|1 \rangle`. -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def circuit(x): product_basis_state(x) # |x> - qml.Adder(5, wires["x"]) # |x+5> + qp.Adder(5, wires["x"]) # |x+5> - return qml.sample(wires=wires["x"]) + return qp.sample(wires=wires["x"]) print(circuit(x=1), " (binary) ---> ", state_to_decimal(circuit(x=1)[0])," (decimal)") @@ -124,7 +124,7 @@ def circuit(x): # We obtained the result :math:`5+1=6`, as expected. At this point, it's worth taking a moment to look # at the decomposition of the circuit into quantum gates and operators. -fig, _ = qml.draw_mpl(circuit, decimals = 2, style = "pennylane", level='device')(x=1) +fig, _ = qp.draw_mpl(circuit, decimals = 2, style = "pennylane", level='device')(x=1) fig.show() ###################################################################### @@ -136,14 +136,14 @@ def circuit(x): # Now, let's see an example for the :class:`~.pennylane.OutAdder` operator to add the states # :math:`|x \rangle` and :math:`|y \rangle` to the output register. -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def circuit(x,y): product_basis_state(x, y) # |x> |y> |0> - qml.OutAdder(wires["x"], wires["y"], wires["output"]) # |x> |y> |x+y> + qp.OutAdder(wires["x"], wires["y"], wires["output"]) # |x> |y> |x+y> - return qml.sample(wires=wires["output"]) + return qp.sample(wires=wires["output"]) print(circuit(x=2,y=3), " (binary) ---> ", state_to_decimal(circuit(x=2,y=3)[0]), " (decimal)") @@ -172,14 +172,14 @@ def circuit(x,y): # :class:`~.pennylane.Multiplier` operator. We will multiply the state :math:`|x \rangle=|2 \rangle` by # the integer :math:`k=3`: -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def circuit(x): product_basis_state(x) # |x> - qml.Multiplier(3, wires["x"], work_wires=wires["work_wires"]) # |3x> + qp.Multiplier(3, wires["x"], work_wires=wires["work_wires"]) # |3x> - return qml.sample(wires=wires["x"]) + return qp.sample(wires=wires["x"]) print(circuit(x=2), " (binary) ---> ", state_to_decimal(circuit(x=2)[0])," (decimal)") @@ -189,14 +189,14 @@ def circuit(x): # Now, let's look at an example using the :class:`~.pennylane.OutMultiplier` operator to multiply the states :math:`|x \rangle` and # :math:`|y \rangle`, storing the result in the output register. -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def circuit(x,y): product_basis_state(x, y) # |x> |y> |0> - qml.OutMultiplier(wires["x"], wires["y"], wires["output"]) # |x> |y> |xy> + qp.OutMultiplier(wires["x"], wires["y"], wires["output"]) # |x> |y> |xy> - return qml.sample(wires=wires["output"]) + return qp.sample(wires=wires["output"]) print(circuit(x=4,y=2), " (binary) ---> ", state_to_decimal(circuit(x=4,y=2)[0])," (decimal)") @@ -205,14 +205,14 @@ def circuit(x,y): # multiplication, respectively. The inverse of a quantum circuit can be implemented with the # :func:`~.pennylane.adjoint` operator. Let's see an example of modular subtraction. -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def circuit(x): product_basis_state(x) # |x> - qml.adjoint(qml.Adder(3, wires["x"])) # |x-3> + qp.adjoint(qp.Adder(3, wires["x"])) # |x-3> - return qml.sample(wires=wires["x"]) + return qp.sample(wires=wires["x"]) print(circuit(x=6), " (binary) ---> ", state_to_decimal(circuit(x=6)[0]), " (decimal)") @@ -244,14 +244,14 @@ def circuit(x): def adding_3xy(): # |x> ---> |3x> - qml.Multiplier(3, wires["x"], work_wires=wires["work_wires"]) + qp.Multiplier(3, wires["x"], work_wires=wires["work_wires"]) # |3x>|y>|0> ---> |3x>|y>|3xy> - qml.OutMultiplier(wires["x"], wires["y"], wires["output"]) + qp.OutMultiplier(wires["x"], wires["y"], wires["output"]) # We return the x-register to its original value using the adjoint operation # |3x>|y>|3xy> ---> |x>|y>|3xy> - qml.adjoint(qml.Multiplier)(3, wires["x"], work_wires=wires["work_wires"]) + qp.adjoint(qp.Multiplier)(3, wires["x"], work_wires=wires["work_wires"]) ###################################################################### # Then we need to add the term :math:`5x + 3y` to the output register, which can be done by using the @@ -260,30 +260,30 @@ def adding_3xy(): def adding_5x_3y(): # |x>|y> ---> |5x>|3y> - qml.Multiplier(5, wires["x"], work_wires=wires["work_wires"]) - qml.Multiplier(3, wires["y"], work_wires=wires["work_wires"]) + qp.Multiplier(5, wires["x"], work_wires=wires["work_wires"]) + qp.Multiplier(3, wires["y"], work_wires=wires["work_wires"]) # |5x>|3y>|0> ---> |5x>|3y>|5x + 3y> - qml.OutAdder(wires["x"], wires["y"], wires["output"]) + qp.OutAdder(wires["x"], wires["y"], wires["output"]) # We return the x and y registers to their original value using the adjoint operation # |5x>|3y>|5x + 3y> ---> |x>|y>|5x + 3y> - qml.adjoint(qml.Multiplier)(5, wires["x"], work_wires=wires["work_wires"]) - qml.adjoint(qml.Multiplier)(3, wires["y"], work_wires=wires["work_wires"]) + qp.adjoint(qp.Multiplier)(5, wires["x"], work_wires=wires["work_wires"]) + qp.adjoint(qp.Multiplier)(3, wires["y"], work_wires=wires["work_wires"]) ###################################################################### # Now we can combine all these circuits to implement the transformation by the polynomial :math:`f(x,y)= 4 + 3xy + 5 x+ 3 y`. -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def circuit(x,y): product_basis_state(x, y) # |x> |y> |0> - qml.Adder(4, wires["output"]) # |x> |y> |4> + qp.Adder(4, wires["output"]) # |x> |y> |4> adding_3xy() # |x> |y> |4 + 3xy> adding_5x_3y() # |x> |y> |4 + 3xy + 5x + 3y> - return qml.sample(wires=wires["output"]) + return qp.sample(wires=wires["output"]) print(circuit(x=1,y=4), " (binary) ---> ", state_to_decimal(circuit(x=1,y=4)[0]), " (decimal)") @@ -293,7 +293,7 @@ def circuit(x,y): # At this point, it's interesting to consider what would happen if we had chosen a smaller number of wires for the output. # For instance, if we had selected one wire fewer, we would have obtained the result :math:`33 \mod 2^5 = 1`. -wires = qml.registers({"x": 4, "y": 4, "output": 5,"work_wires": 4}) +wires = qp.registers({"x": 4, "y": 4, "output": 5,"work_wires": 4}) print(circuit(x=1,y=4), " (binary) ---> ", state_to_decimal(circuit(x=1,y=4)[0]), " (decimal)") @@ -318,18 +318,18 @@ def f(x, y): ###################################################################### -wires = qml.registers({"x": 4, "y":4, "output":6}) -@qml.set_shots(1) -@qml.qnode(dev) +wires = qp.registers({"x": 4, "y":4, "output":6}) +@qp.set_shots(1) +@qp.qnode(dev) def circuit_with_Poly(x,y): product_basis_state(x, y) # |x> |y> |0> - qml.OutPoly( + qp.OutPoly( f, input_registers= [wires["x"], wires["y"]], output_wires = wires["output"]) # |x> |y> |4 + 3xy + 5x + 3y> - return qml.sample(wires = wires["output"]) + return qp.sample(wires = wires["output"]) print(circuit_with_Poly(x=1,y=4), " (binary) ---> ", state_to_decimal(circuit_with_Poly(x=1,y=4)[0]), " (decimal)") diff --git a/demonstrations_v2/tutorial_how_to_use_quantum_arithmetic_operators/metadata.json b/demonstrations_v2/tutorial_how_to_use_quantum_arithmetic_operators/metadata.json index c05209b78e..2e1e0a839e 100644 --- a/demonstrations_v2/tutorial_how_to_use_quantum_arithmetic_operators/metadata.json +++ b/demonstrations_v2/tutorial_how_to_use_quantum_arithmetic_operators/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-11-05T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Quantum Computing", "Algorithms", diff --git a/demonstrations_v2/tutorial_how_to_use_registers/demo.py b/demonstrations_v2/tutorial_how_to_use_registers/demo.py index b200ee934a..9501e97c57 100644 --- a/demonstrations_v2/tutorial_how_to_use_registers/demo.py +++ b/demonstrations_v2/tutorial_how_to_use_registers/demo.py @@ -14,9 +14,9 @@ # wires in each register: # -import pennylane as qml +import pennylane as qp -register = qml.registers({"alice": 1, "bob": 2, "charlie": 3}) +register = qp.registers({"alice": 1, "bob": 2, "charlie": 3}) print(register) ###################################################################### @@ -25,7 +25,7 @@ # # You can also pass in a dictionary that has nested dictionaries as its values. -nested_register = qml.registers( +nested_register = qp.registers( { "all_registers": { "alice": 1, @@ -75,25 +75,25 @@ import numpy as np -swap_register = qml.registers({"auxiliary": 1, "psi": 3, "phi": 3}) +swap_register = qp.registers({"auxiliary": 1, "psi": 3, "phi": 3}) -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") -@qml.qnode(dev) +@qp.qnode(dev) def swap_test(): # Make "psi" and "phi" state orthogonal to each other - qml.RX(np.pi/2, swap_register["phi"][0]) + qp.RX(np.pi/2, swap_register["phi"][0]) - qml.Hadamard(swap_register["auxiliary"]) + qp.Hadamard(swap_register["auxiliary"]) for i in range(len(swap_register["psi"])): # We can use the union operation to assemble our registers on the fly - qml.CSWAP( + qp.CSWAP( swap_register["auxiliary"] | swap_register["psi"][i] | swap_register["phi"][i] ) - qml.Hadamard(swap_register["auxiliary"]) - return qml.expval(qml.Z(wires=swap_register["auxiliary"])) + qp.Hadamard(swap_register["auxiliary"]) + return qp.expval(qp.Z(wires=swap_register["auxiliary"])) print(swap_test()) @@ -109,7 +109,7 @@ def swap_test(): # "estimation" or "measurement" register, and the other is the state register where we apply our # unitary operators :math:`U.` We can define these registers in PennyLane code: -register = qml.registers({"state": 4, "estimation": 6}) +register = qp.registers({"state": 4, "estimation": 6}) ###################################################################### # To build our unitary operator :math:`U,` there are a variety of options. We can opt to use a @@ -117,7 +117,7 @@ def swap_test(): # :class:`~.pennylane.Qubitization`, which means we have to define another preparation register. # Our registers now look like this: -register = qml.registers({"state": 4, "estimation": 6, "prep": 4}) +register = qp.registers({"state": 4, "estimation": 6, "prep": 4}) ###################################################################### # Finally, let's define our Hamiltonian. We'll use the `transverse-field Ising model `_ from @@ -125,7 +125,7 @@ def swap_test(): # but feel free to try this with any other Hamiltonian. -[dataset] = qml.data.load( +[dataset] = qp.data.load( "qspin", sysname="Ising", periodicity="open", lattice="chain", layout="1x4" ) H = dataset.hamiltonians[0] @@ -140,25 +140,25 @@ def swap_test(): ###################################################################### # With this, we can now define our QPE circuit: -dev = qml.device("lightning.qubit", wires=14) +dev = qp.device("lightning.qubit", wires=14) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(): # Initialize state register to initial state - qml.StatePrep(initial_state, wires=register["state"]) + qp.StatePrep(initial_state, wires=register["state"]) # Apply Hadamard gate to all wires in estimation register for wire in register["estimation"]: - qml.Hadamard(wires=wire) + qp.Hadamard(wires=wire) - qml.ControlledSequence( - qml.Qubitization(H, register["prep"]), + qp.ControlledSequence( + qp.Qubitization(H, register["prep"]), control=register["estimation"], ) - qml.adjoint(qml.QFT)(wires=register["estimation"]) + qp.adjoint(qp.QFT)(wires=register["estimation"]) - return qml.probs(wires=register["estimation"]) + return qp.probs(wires=register["estimation"]) ###################################################################### # We'll run our circuit and do some post-processing to get the energy eigenvalue: diff --git a/demonstrations_v2/tutorial_how_to_use_registers/metadata.json b/demonstrations_v2/tutorial_how_to_use_registers/metadata.json index 795e3c07d6..8ebacbcd2d 100644 --- a/demonstrations_v2/tutorial_how_to_use_registers/metadata.json +++ b/demonstrations_v2/tutorial_how_to_use_registers/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-09-05T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Getting Started", "How-to" diff --git a/demonstrations_v2/tutorial_huang_geometric_kernel_difference/demo.py b/demonstrations_v2/tutorial_huang_geometric_kernel_difference/demo.py index edb71382ac..32d78567ef 100644 --- a/demonstrations_v2/tutorial_huang_geometric_kernel_difference/demo.py +++ b/demonstrations_v2/tutorial_huang_geometric_kernel_difference/demo.py @@ -145,7 +145,7 @@ # :math:`\lvert \psi_{\text{E1}}(x) \rangle`. # # - **E2 – IQP embedding.** -# PennyLane’s ``qml.IQPEmbedding`` applies Hadamards, parameterized :math:`RZ(x_j)` rotations, and +# PennyLane’s ``qp.IQPEmbedding`` applies Hadamards, parameterized :math:`RZ(x_j)` rotations, and # entangling ZZ gates. # This creates an entangled quantum state :math:`\lvert \psi_{\text{E2}}(x) \rangle`, inspired by # Instantaneous Quantum Polynomial (IQP) circuits. @@ -186,7 +186,7 @@ # Let's define the embedding circuits E1 and E2, and visualize them using an auxiliary drawing function. import numpy as np -import pennylane as qml +import pennylane as qp import matplotlib.pyplot as plt n_features = X_train.shape[1] @@ -196,12 +196,12 @@ # -- E1: separable RX rotations --------------------------------------------- def embedding_E1(features): for j, xj in enumerate(features): - qml.RX(np.pi * xj, wires=j) + qp.RX(np.pi * xj, wires=j) # -- E2: IQP embedding via PennyLane template -------------------------------- def embedding_E2(features): - qml.IQPEmbedding(features, wires=range(n_features)) + qp.IQPEmbedding(features, wires=range(n_features)) from utils import draw_circuits_side_by_side @@ -247,23 +247,23 @@ def classical_rbf_kernel(X, gamma=1.0): # ---------------------------------------------------------------------------# # Quantum fidelity-based Gram matrices # # ---------------------------------------------------------------------------# -dev = qml.device("default.qubit", wires=n_qubits, shots=None) +dev = qp.device("default.qubit", wires=n_qubits, shots=None) def overlap_prob(x, y, embed): """Probability of measuring |0…0⟩ after U(x) U†(y).""" - @qml.qnode(dev) + @qp.qnode(dev) def circuit(): embed(x) - qml.adjoint(embed)(y) - return qml.probs(wires=range(n_qubits)) + qp.adjoint(embed)(y) + return qp.probs(wires=range(n_qubits)) return circuit()[0] def quantum_kernel_matrix(X, embed): - return qml.kernels.kernel_matrix(X, X, lambda v1, v2: overlap_prob(v1, v2, embed)) + return qp.kernels.kernel_matrix(X, X, lambda v1, v2: overlap_prob(v1, v2, embed)) print("Computing QK-E1 (fidelity)...") @@ -287,12 +287,12 @@ def get_pauli_vectors(embedding_func, X): """Returns Pauli expectation vectors for each input using the given embedding.""" observables = [] for i in range(n_qubits): - observables.extend([qml.PauliX(i), qml.PauliY(i), qml.PauliZ(i)]) + observables.extend([qp.PauliX(i), qp.PauliY(i), qp.PauliZ(i)]) - @qml.qnode(dev) + @qp.qnode(dev) def pauli_qnode(x): embedding_func(x) - return [qml.expval(obs) for obs in observables] + return [qp.expval(obs) for obs in observables] vectors = [pauli_qnode(x) for x in X] return np.array(vectors) @@ -437,13 +437,13 @@ def train_evaluate_svm(K_train, K_test, y_train, y_test, name): ) # Quantum Kernel E1 -K_qk_e1_test = qml.kernels.kernel_matrix( +K_qk_e1_test = qp.kernels.kernel_matrix( X_test, X_train, lambda x, y: overlap_prob(x, y, embedding_E1) ) results["QK-E1"] = train_evaluate_svm(K_quantum_E1, K_qk_e1_test, y_train, y_test, "Quantum E1") # Quantum Kernel E2 -K_qk_e2_test = qml.kernels.kernel_matrix( +K_qk_e2_test = qp.kernels.kernel_matrix( X_test, X_train, lambda x, y: overlap_prob(x, y, embedding_E2) ) results["QK-E2"] = train_evaluate_svm(K_quantum_E2, K_qk_e2_test, y_train, y_test, "Quantum E2") diff --git a/demonstrations_v2/tutorial_huang_geometric_kernel_difference/metadata.json b/demonstrations_v2/tutorial_huang_geometric_kernel_difference/metadata.json index 9a38998bc4..ed8b91b847 100644 --- a/demonstrations_v2/tutorial_huang_geometric_kernel_difference/metadata.json +++ b/demonstrations_v2/tutorial_huang_geometric_kernel_difference/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": false, "dateOfPublication": "2026-01-20T10:00:00+00:00", - "dateOfLastModification": "2026-01-22T10:00:00+00:01", + "dateOfLastModification": "2026-04-17T10:00:00+00:01", "categories": [ "Quantum Machine Learning" ], diff --git a/demonstrations_v2/tutorial_implicit_diff_susceptibility/demo.py b/demonstrations_v2/tutorial_implicit_diff_susceptibility/demo.py index 70d76b60e9..fecc3dd8aa 100644 --- a/demonstrations_v2/tutorial_implicit_diff_susceptibility/demo.py +++ b/demonstrations_v2/tutorial_implicit_diff_susceptibility/demo.py @@ -263,7 +263,7 @@ from jax import jit import jax.numpy as jnp -import pennylane as qml +import pennylane as qp import numpy as np import jaxopt @@ -301,30 +301,30 @@ def build_H0(N, J, gamma): gamma (float): Interaction strength. Returns: - qml.Hamiltonian: The Hamiltonian of the system. + qp.Hamiltonian: The Hamiltonian of the system. """ - H = qml.Hamiltonian([], []) + H = qp.Hamiltonian([], []) for i in range(N - 1): - H += -J * qml.PauliZ(i) @ qml.PauliZ(i + 1) + H += -J * qp.PauliZ(i) @ qp.PauliZ(i + 1) - H += -J * qml.PauliZ(N - 1) @ qml.PauliZ(0) + H += -J * qp.PauliZ(N - 1) @ qp.PauliZ(0) # Transverse for i in range(N): - H += -gamma * qml.PauliX(i) + H += -gamma * qp.PauliX(i) # Small magnetization for numerical stability for i in range(N): - H += -1e-1 * qml.PauliZ(i) + H += -1e-1 * qp.PauliZ(i) return H H0 = build_H0(N, J, gamma) -H0_matrix = qml.matrix(H0) -A = reduce(add, ((1 / N) * qml.PauliZ(i) for i in range(N))) -A_matrix = qml.matrix(A) +H0_matrix = qp.matrix(H0) +A = reduce(add, ((1 / N) * qp.PauliZ(i) for i in range(N))) +A_matrix = qp.matrix(A) ############################################################################### # Computing the exact ground state through eigendecomposition @@ -432,15 +432,15 @@ def expval_A_exact(a): # In a real device we would use a finite number of shots and the gradients would be computed # using the parameter-shift rule. However, this may be slower. -variational_ansatz = qml.SimplifiedTwoDesign +variational_ansatz = qp.SimplifiedTwoDesign n_layers = 5 weights_shape = variational_ansatz.shape(n_layers, N) -dev = qml.device("default.qubit", wires=N) +dev = qp.device("default.qubit", wires=N) @jax.jit -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def energy(z, a): """Computes the energy for a Hamiltonian H(a) using a measurement on the variational state U(z)|0> with U(z) being any circuit ansatz. @@ -454,7 +454,7 @@ def energy(z, a): """ variational_ansatz(*z, wires=range(N)) - return qml.expval(H0 + a * A) + return qp.expval(H0 + a * A) z_init = [jnp.array(2 * np.pi * np.random.random(s)) for s in weights_shape] @@ -542,7 +542,7 @@ def loss(z, a): @jax.jit -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def expval_A_variational(z: float) -> float: """Expectation value of $A$ as a function of $a$ where we use the a variational ground state solution map. @@ -554,7 +554,7 @@ def expval_A_variational(z: float) -> float: float: The expectation value of M on the ground state of H(a) """ variational_ansatz(*z, wires=range(N)) - return qml.expval(A) + return qp.expval(A) @jax.jit @@ -564,7 +564,7 @@ def groundstate_expval_variational(a, z_init) -> float: Args: a (float): The parameter in the Hamiltonian, H(a). z_init [jnp.array(jnp.float)]: The initial guess for the variational parameters. - H0 (qml.Hamiltonian): The static part of the Hamiltonian + H0 (qp.Hamiltonian): The static part of the Hamiltonian """ z_star = ground_state_solution_map_variational(a, z_init) return expval_A_variational(z_star) @@ -589,7 +589,7 @@ def groundstate_expval_variational(a, z_init) -> float: ############################################################################## # PennyLane version and details -print(qml.about()) +print(qp.about()) ############################################################################## # Conclusion diff --git a/demonstrations_v2/tutorial_implicit_diff_susceptibility/metadata.json b/demonstrations_v2/tutorial_implicit_diff_susceptibility/metadata.json index d8a945389e..4293aeb879 100644 --- a/demonstrations_v2/tutorial_implicit_diff_susceptibility/metadata.json +++ b/demonstrations_v2/tutorial_implicit_diff_susceptibility/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2022-11-28T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_initial_state_preparation/demo.py b/demonstrations_v2/tutorial_initial_state_preparation/demo.py index 0797a07a5b..17760a687b 100644 --- a/demonstrations_v2/tutorial_initial_state_preparation/demo.py +++ b/demonstrations_v2/tutorial_initial_state_preparation/demo.py @@ -218,7 +218,7 @@ # of VQE for obtaining the ground-state energy of a molecule. As a first step, create our # linear :math:`\text{H}_3^+` molecule, a device, and a simple VQE circuit with single and double excitations: -import pennylane as qml +import pennylane as qp from pennylane import qchem from jax import numpy as jnp @@ -229,7 +229,7 @@ H2mol, qubits = qchem.molecular_hamiltonian(molecule) wires = list(range(qubits)) -dev = qml.device("default.qubit", wires=qubits) +dev = qp.device("default.qubit", wires=qubits) # create all possible excitations in H3+ singles, doubles = qchem.excitations(2, qubits) @@ -239,15 +239,15 @@ # Now let's run VQE with the Hartree-Fock initial state. We first build the VQE circuit: -@qml.qnode(dev) +@qp.qnode(dev) def circuit_VQE(theta, initial_state): - qml.StatePrep(initial_state, wires=wires) + qp.StatePrep(initial_state, wires=wires) for i, excitation in enumerate(excitations): if len(excitation) == 4: - qml.DoubleExcitation(theta[i], wires=excitation) + qp.DoubleExcitation(theta[i], wires=excitation) else: - qml.SingleExcitation(theta[i], wires=excitation) - return qml.expval(H2mol) + qp.SingleExcitation(theta[i], wires=excitation) + return qp.expval(H2mol) def cost_fn(param): diff --git a/demonstrations_v2/tutorial_initial_state_preparation/metadata.json b/demonstrations_v2/tutorial_initial_state_preparation/metadata.json index 553515013a..4959239e1e 100644 --- a/demonstrations_v2/tutorial_initial_state_preparation/metadata.json +++ b/demonstrations_v2/tutorial_initial_state_preparation/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-10-20T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Chemistry" ], diff --git a/demonstrations_v2/tutorial_intro_amplitude_amplification/demo.py b/demonstrations_v2/tutorial_intro_amplitude_amplification/demo.py index 86d50f0ca1..10ddb64370 100644 --- a/demonstrations_v2/tutorial_intro_amplitude_amplification/demo.py +++ b/demonstrations_v2/tutorial_intro_amplitude_amplification/demo.py @@ -138,24 +138,24 @@ # This is a uniform superposition of all possible subsets so solutions are guaranteed to have non-zero amplitudes # in :math:`|\Psi\rangle.` Let's generate the state and visualize it. -import pennylane as qml +import pennylane as qp import matplotlib.pyplot as plt plt.style.use('pennylane.drawer.plot') -@qml.prod +@qp.prod # This decorator converts the quantum function U into an operator. # It is useful for later use in the AmplitudeAmplification template. def U(wires): # create the generator U, such that U|0⟩ = |Ψ⟩ for wire in wires: - qml.Hadamard(wires=wire) + qp.Hadamard(wires=wire) -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") -@qml.qnode(dev) +@qp.qnode(dev) def circuit(): U(wires = range(n)) - return qml.state() + return qp.state() output = circuit()[:64].real @@ -184,11 +184,11 @@ def circuit(): import numpy as np def Sum(wires_subset, wires_sum): - qml.QFT(wires = wires_sum) + qp.QFT(wires = wires_sum) for i, value in enumerate(values): for j in range(len(wires_sum)): - qml.CRZ(value * np.pi / (2 ** j), wires=[wires_subset[i], wires_sum[j]]) - qml.adjoint(qml.QFT)(wires=wires_sum) + qp.CRZ(value * np.pi / (2 ** j), wires=[wires_subset[i], wires_sum[j]]) + qp.adjoint(qp.QFT)(wires=wires_sum) ############################################################################## # To create the oracle that performs the reflection around :math:`|\phi^{\perp}\rangle,` we apply the :math:`\text{Sum}` operator to the @@ -196,19 +196,19 @@ def Sum(wires_subset, wires_sum): # This allows us to mark the searched elements. Then we apply the inverse of the sum to clean the auxiliary qubits. # -@qml.prod +@qp.prod def oracle(wires_subset, wires_sum): # Reflection on |ϕ⟂⟩ Sum(wires_subset, wires_sum) - qml.FlipSign(0, wires=wires_sum) - qml.adjoint(Sum)(wires_subset, wires_sum) + qp.FlipSign(0, wires=wires_sum) + qp.adjoint(Sum)(wires_subset, wires_sum) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(): U(wires=range(n)) # Generate initial state oracle(range(n), range(n, n+5)) # Apply the reflection on |ϕ⟂⟩ - return qml.state() + return qp.state() output = circuit()[0::2 ** 5].real @@ -232,12 +232,12 @@ def circuit(): # -@qml.qnode(dev) +@qp.qnode(dev) def circuit(): U(wires=range(n)) # Generate initial state oracle(range(n), range(n, n + 5)) # Apply the reflection on |ϕ⟂⟩ - qml.Reflection(U(wires=range(n))) # Reflect on |Ψ⟩ - return qml.state() + qp.Reflection(U(wires=range(n))) # Reflect on |Ψ⟩ + return qp.state() ############################################################################## # Let's now look at the state :math:`|\Psi\rangle` and see how it is changed. @@ -261,14 +261,14 @@ def circuit(): # to :math:`|\phi^{\perp}\rangle` (i.e. the oracle), and the number of iterations. # We increase the number of iterations in order to study the evolution of the initial state: -@qml.qnode(dev) +@qp.qnode(dev) def circuit(iters): U(wires=range(n)) - qml.AmplitudeAmplification(U = U(wires = range(n)), + qp.AmplitudeAmplification(U = U(wires = range(n)), O = oracle(range(n), range(n, n + 5)), iters = iters) - return qml.probs(wires = range(n)) + return qp.probs(wires = range(n)) fig, axs = plt.subplots(2, 2, figsize=(14, 10)) for i in range(1,9,2): @@ -308,16 +308,16 @@ def circuit(iters): # To use this variant we simply set ``fixed_point = True`` and indicate the auxiliary qubit. # Let's see what happens with the same example as before: -@qml.qnode(dev) +@qp.qnode(dev) def circuit(iters): U(wires=range(n)) - qml.AmplitudeAmplification(U = U(wires = range(n)), + qp.AmplitudeAmplification(U = U(wires = range(n)), O = oracle(range(n), range(n, n + 5)), iters = iters, fixed_point=True, work_wire = n + 5) - return qml.probs(wires = range(n)) + return qp.probs(wires = range(n)) fig, axs = plt.subplots(2, 2, figsize=(14, 10)) for i in range(1,9,2): diff --git a/demonstrations_v2/tutorial_intro_amplitude_amplification/metadata.json b/demonstrations_v2/tutorial_intro_amplitude_amplification/metadata.json index ef7ff29951..a11e58c7a6 100644 --- a/demonstrations_v2/tutorial_intro_amplitude_amplification/metadata.json +++ b/demonstrations_v2/tutorial_intro_amplitude_amplification/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-05-07T00:00:00+00:00", - "dateOfLastModification": "2025-12-19T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Quantum Computing", "Algorithms" diff --git a/demonstrations_v2/tutorial_intro_qrom/demo.py b/demonstrations_v2/tutorial_intro_qrom/demo.py index bbf3087ecf..54d45b9fc9 100644 --- a/demonstrations_v2/tutorial_intro_qrom/demo.py +++ b/demonstrations_v2/tutorial_intro_qrom/demo.py @@ -58,7 +58,7 @@ """ -import pennylane as qml +import pennylane as qp import numpy as np from functools import partial import matplotlib.pyplot as plt @@ -69,22 +69,22 @@ control_wires = [0, 1, 2] target_wires = [3, 4] -Ui = [qml.BasisState(int(bitstring, 2), target_wires) for bitstring in bitstrings] +Ui = [qp.BasisState(int(bitstring, 2), target_wires) for bitstring in bitstrings] -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") # This line is included for drawing purposes only. -@partial(qml.transforms.decompose, max_expansion=1) -@qml.set_shots(1) -@qml.qnode(dev) +@partial(qp.transforms.decompose, max_expansion=1) +@qp.set_shots(1) +@qp.qnode(dev) def circuit(index): - qml.BasisState(index, wires=control_wires) - qml.Select(Ui, control=control_wires) - return qml.sample(wires=target_wires) + qp.BasisState(index, wires=control_wires) + qp.Select(Ui, control=control_wires) + return qp.sample(wires=target_wires) -qml.draw_mpl(circuit, style="pennylane")(3) +qp.draw_mpl(circuit, style="pennylane")(3) plt.show() ############################################################################## @@ -106,13 +106,13 @@ def circuit(index): target_wires = [3, 4] -@partial(qml.compile, basis_set="CNOT") # Line added for resource estimation purposes only. -@qml.set_shots(1) -@qml.qnode(dev) +@partial(qp.compile, basis_set="CNOT") # Line added for resource estimation purposes only. +@qp.set_shots(1) +@qp.qnode(dev) def circuit(index): - qml.BasisState(index, wires=control_wires) - qml.QROM(bitstrings, control_wires, target_wires, work_wires=None) - return qml.sample(wires=target_wires) + qp.BasisState(index, wires=control_wires) + qp.QROM(bitstrings, control_wires, target_wires, work_wires=None) + return qp.sample(wires=target_wires) for i in range(8): @@ -123,8 +123,8 @@ def circuit(index): # Here we show the number of 1 and 2 qubit gates we use when decomposing the circuit: print("Number of qubits: ", len(control_wires + target_wires)) -print("One-qubit gates: ", qml.specs(circuit)(0)["resources"].gate_sizes[1]) -print("Two-qubit gates: ", qml.specs(circuit)(0)["resources"].gate_sizes[2]) +print("One-qubit gates: ", qp.specs(circuit)(0)["resources"].gate_sizes[1]) +print("Two-qubit gates: ", qp.specs(circuit)(0)["resources"].gate_sizes[2]) ############################################################################## # You can learn more about these resource estimation methods in @@ -148,18 +148,18 @@ def circuit(index): work_wires = [5, 6] -@partial(qml.compile, basis_set="CNOT") -@qml.set_shots(1) -@qml.qnode(dev) +@partial(qp.compile, basis_set="CNOT") +@qp.set_shots(1) +@qp.qnode(dev) def circuit(index): - qml.BasisState(index, wires=control_wires) + qp.BasisState(index, wires=control_wires) # added work wires below - qml.QROM(bitstrings, control_wires, target_wires, work_wires, clean=False) - return qml.sample(wires=control_wires + target_wires + work_wires) + qp.QROM(bitstrings, control_wires, target_wires, work_wires, clean=False) + return qp.sample(wires=control_wires + target_wires + work_wires) print("Number of qubits: ", len(control_wires + target_wires + work_wires)) -print("One-qubit gates: ", qml.specs(circuit)(0)["resources"].gate_sizes[1]) -print("Two-qubit gates: ", qml.specs(circuit)(0)["resources"].gate_sizes[2]) +print("One-qubit gates: ", qp.specs(circuit)(0)["resources"].gate_sizes[1]) +print("Two-qubit gates: ", qp.specs(circuit)(0)["resources"].gate_sizes[2]) ############################################################################## # The number of 1 and 2 qubit gates is significantly reduced! @@ -223,16 +223,16 @@ def circuit(index): # Line added for drawing purposes only -@partial(qml.transforms.decompose, max_expansion=2) -@qml.set_shots(1) -@qml.qnode(qml.device("default.qubit")) +@partial(qp.transforms.decompose, max_expansion=2) +@qp.set_shots(1) +@qp.qnode(qp.device("default.qubit")) def circuit(index): - qml.BasisState(index, wires=control_wires) - qml.QROM(bitstrings, control_wires, target_wires, work_wires, clean=False) - return qml.sample(wires=target_wires), qml.sample(wires=target_wires) + qp.BasisState(index, wires=control_wires) + qp.QROM(bitstrings, control_wires, target_wires, work_wires, clean=False) + return qp.sample(wires=target_wires), qp.sample(wires=target_wires) -qml.draw_mpl(circuit, style="pennylane")(0) +qp.draw_mpl(circuit, style="pennylane")(0) plt.show() @@ -254,12 +254,12 @@ def circuit(index): work_wires = [5, 6] -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def circuit(index): - qml.BasisState(index, wires=control_wires) - qml.QROM(bitstrings, control_wires, target_wires, work_wires, clean=True) - return qml.sample(wires=target_wires + work_wires) + qp.BasisState(index, wires=control_wires) + qp.QROM(bitstrings, control_wires, target_wires, work_wires, clean=True) + return qp.sample(wires=target_wires + work_wires) for i in range(8): diff --git a/demonstrations_v2/tutorial_intro_qrom/metadata.json b/demonstrations_v2/tutorial_intro_qrom/metadata.json index 2be42438f3..b73fa9dfd7 100644 --- a/demonstrations_v2/tutorial_intro_qrom/metadata.json +++ b/demonstrations_v2/tutorial_intro_qrom/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-09-18T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Algorithms", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_intro_qsvt/demo.py b/demonstrations_v2/tutorial_intro_qsvt/demo.py index dfc0c88b75..c2a7db12ee 100644 --- a/demonstrations_v2/tutorial_intro_qsvt/demo.py +++ b/demonstrations_v2/tutorial_intro_qsvt/demo.py @@ -100,7 +100,7 @@ \end{pmatrix}. """ -import pennylane as qml +import pennylane as qp import numpy as np import matplotlib.pyplot as plt @@ -110,7 +110,7 @@ def qsvt_output(a): # output matrix - out = qml.matrix(qml.qsvt(a, target_poly, encoding_wires=[0], block_encoding="embedding")) + out = qp.matrix(qp.qsvt(a, target_poly, encoding_wires=[0], block_encoding="embedding")) return out[0, 0] # top-left entry @@ -155,16 +155,16 @@ def qsvt_output(a): # square matrix A = [[0.1, 0.2], [0.3, 0.4]] -U1 = qml.BlockEncode(A, wires=range(2)) +U1 = qp.BlockEncode(A, wires=range(2)) print("U(A):") -print(np.round(qml.matrix(U1), 2)) +print(np.round(qp.matrix(U1), 2)) ############################################################################## # And also a rectangular matrix B = [[0.5, -0.5, 0.5]] -U2 = qml.BlockEncode(B, wires=range(2)) +U2 = qp.BlockEncode(B, wires=range(2)) print("U(B):") -print(np.round(qml.matrix(U2), 2)) +print(np.round(qp.matrix(U2), 2)) ############################################################################## @@ -206,9 +206,9 @@ def qsvt_output(a): dim = 2 phi = np.pi / 2 -pcp = qml.PCPhase(phi, dim, wires=range(2)) +pcp = qp.PCPhase(phi, dim, wires=range(2)) print("Pi:") -print(np.round(qml.matrix(pcp), 2)) +print(np.round(qp.matrix(pcp), 2)) ############################################################################## @@ -258,14 +258,14 @@ def qsvt_output(a): A = np.diag(eigvals) # 16-dim matrix wire_order = list(range(5)) -qml.draw_mpl(qml.transforms.decompose(qml.qsvt))(A, target_poly, encoding_wires=wire_order, block_encoding="embedding") +qp.draw_mpl(qp.transforms.decompose(qp.qsvt))(A, target_poly, encoding_wires=wire_order, block_encoding="embedding") plt.show() ############################################################################### # Now, let's see how each eigenvalue of :math:`A` is transformed by QSVT. We will plot the original eigenvalues # and the corresponding eigenvalues of the top-left block of the QSVT matrix. -U_A = qml.matrix(qml.qsvt, wire_order=wire_order)( +U_A = qp.matrix(qp.qsvt, wire_order=wire_order)( A, target_poly, encoding_wires=wire_order, block_encoding="embedding" ) # block-encoded in 5-qubit system diff --git a/demonstrations_v2/tutorial_intro_qsvt/metadata.json b/demonstrations_v2/tutorial_intro_qsvt/metadata.json index 7f91208fde..6e4c60f32d 100644 --- a/demonstrations_v2/tutorial_intro_qsvt/metadata.json +++ b/demonstrations_v2/tutorial_intro_qsvt/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-05-23T00:00:00+00:00", - "dateOfLastModification": "2026-02-23T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Algorithms", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_iqp_circuit_optimization_jax/demo.py b/demonstrations_v2/tutorial_iqp_circuit_optimization_jax/demo.py index 23908bf00d..fb19510f1e 100644 --- a/demonstrations_v2/tutorial_iqp_circuit_optimization_jax/demo.py +++ b/demonstrations_v2/tutorial_iqp_circuit_optimization_jax/demo.py @@ -113,7 +113,7 @@ # Additionally, we can evaluate expectation values of tensor products of Pauli Z operators # specified by lists of the form ``op`` above with the following # -import pennylane as qml +import pennylane as qp import numpy as np # Suppress the warning caused by iqpopt @@ -121,30 +121,30 @@ from pennylane.exceptions import PennyLaneDeprecationWarning warnings.filterwarnings("ignore", category=PennyLaneDeprecationWarning) -def penn_obs(op: np.ndarray) -> qml.operation.Operator: +def penn_obs(op: np.ndarray) -> qp.operation.Operator: """Returns a PennyLane observable from a bitstring representation. Args: op (np.ndarray): Bitstring representation of the Z operator. Returns: - qml.Observable: PennyLane observable. + qp.Observable: PennyLane observable. """ for i, z in enumerate(op): if i==0: if z: - obs = qml.Z(i) + obs = qp.Z(i) else: - obs = qml.I(i) + obs = qp.I(i) else: if z: - obs @= qml.Z(i) + obs @= qp.Z(i) return obs ###################################################################### # Now we have our circuit as # -def penn_iqp_circuit(params: np.ndarray, gates: list, op: np.ndarray, n_qubits: int) -> qml.measurements.ExpectationMP: +def penn_iqp_circuit(params: np.ndarray, gates: list, op: np.ndarray, n_qubits: int) -> qp.measurements.ExpectationMP: """Defines the circuit that calculates the expectation value of the operator with the IQP circuit with PennyLane tools. Args: @@ -154,11 +154,11 @@ def penn_iqp_circuit(params: np.ndarray, gates: list, op: np.ndarray, n_qubits: n_qubits (int): The total number of qubits in the circuit. Returns: - qml.measurements.ExpectationMP: PennyLane circuit with an expectation value. + qp.measurements.ExpectationMP: PennyLane circuit with an expectation value. """ - qml.IQP(weights=params, num_wires=n_qubits, pattern=gates) + qp.IQP(weights=params, num_wires=n_qubits, pattern=gates) obs = penn_obs(op) - return qml.expval(obs) + return qp.expval(obs) def penn_iqp_op_expval(params: np.ndarray, gates: list, op: np.ndarray, n_qubits: int) -> float: """Calculates the expectation value of the operator with the IQP circuit with PennyLane tools. @@ -172,8 +172,8 @@ def penn_iqp_op_expval(params: np.ndarray, gates: list, op: np.ndarray, n_qubits Returns: float: Expectation value. """ - dev = qml.device("lightning.qubit", wires=n_qubits) - penn_iqp_circuit_exe = qml.QNode(penn_iqp_circuit, dev) + dev = qp.device("lightning.qubit", wires=n_qubits) + penn_iqp_circuit_exe = qp.QNode(penn_iqp_circuit, dev) return penn_iqp_circuit_exe(params, gates, op, n_qubits) ###################################################################### @@ -261,7 +261,7 @@ def penn_iqp_op_expval(params: np.ndarray, gates: list, op: np.ndarray, n_qubits ###################################################################### # Since the calculation is stochastic, the result is not exactly the same as -# the one obtained with PennyLane's ``qml.expval`` method. However, as we can see, they are within the standard error `std`. You can try +# the one obtained with PennyLane's ``qp.expval`` method. However, as we can see, they are within the standard error `std`. You can try # increasing ``n_samples`` in order to obtain a more accurate approximation. # # Additionally, this function supports fast batch evaluation of expectation values. By specifying a batch of operators ``ops`` as an array, we can compute expectation values and errors in parallel using the same syntax. diff --git a/demonstrations_v2/tutorial_iqp_circuit_optimization_jax/metadata.json b/demonstrations_v2/tutorial_iqp_circuit_optimization_jax/metadata.json index 7609bfef9c..1bc5a94ce3 100644 --- a/demonstrations_v2/tutorial_iqp_circuit_optimization_jax/metadata.json +++ b/demonstrations_v2/tutorial_iqp_circuit_optimization_jax/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2025-02-14T09:00:00+00:00", - "dateOfLastModification": "2026-01-14T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Optimization", "Algorithms" diff --git a/demonstrations_v2/tutorial_isingmodel_PyTorch/demo.py b/demonstrations_v2/tutorial_isingmodel_PyTorch/demo.py index f113eed7aa..3df3020c9b 100644 --- a/demonstrations_v2/tutorial_isingmodel_PyTorch/demo.py +++ b/demonstrations_v2/tutorial_isingmodel_PyTorch/demo.py @@ -43,20 +43,20 @@ import torch from torch.autograd import Variable -import pennylane as qml +import pennylane as qp from pennylane import numpy as np ############################################################################### # A three-qubit quantum circuit is initialized to represent the three spins: -dev = qml.device("default.qubit", wires=3) +dev = qp.device("default.qubit", wires=3) -@qml.qnode(dev, interface="torch") +@qp.qnode(dev, interface="torch") def circuit(p1, p2): # We use the general Rot(phi,theta,omega,wires) single-qubit operation - qml.Rot(p1[0], p1[1], p1[2], wires=1) - qml.Rot(p2[0], p2[1], p2[2], wires=2) - return [qml.expval(qml.PauliZ(i)) for i in range(3)] + qp.Rot(p1[0], p1[1], p1[2], wires=1) + qp.Rot(p2[0], p2[1], p2[2], wires=2) + return [qp.expval(qp.PauliZ(i)) for i in range(3)] ############################################################################### # The cost function to be minimized is defined as the energy of the spin configuration: diff --git a/demonstrations_v2/tutorial_isingmodel_PyTorch/metadata.json b/demonstrations_v2/tutorial_isingmodel_PyTorch/metadata.json index c18c7ff855..53bc0bfda9 100644 --- a/demonstrations_v2/tutorial_isingmodel_PyTorch/metadata.json +++ b/demonstrations_v2/tutorial_isingmodel_PyTorch/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2019-10-16T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_jax_transformations/demo.py b/demonstrations_v2/tutorial_jax_transformations/demo.py index ec10ecbee2..f6b330b59a 100644 --- a/demonstrations_v2/tutorial_jax_transformations/demo.py +++ b/demonstrations_v2/tutorial_jax_transformations/demo.py @@ -43,28 +43,28 @@ import jax import jax.numpy as jnp -import pennylane as qml +import pennylane as qp # Added to silence some warnings. jax.config.update("jax_enable_x64", True) -dev = qml.device("default.qubit", wires=2) +dev = qp.device("default.qubit", wires=2) ############################################################################## # Let's start with a simple example circuit that generates a two-qubit entangled state, # then evaluates the expectation value of the Pauli-Z operator on the first wire. -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def circuit(param): # These two gates represent our QML model. - qml.RX(param, wires=0) - qml.CNOT(wires=[0, 1]) + qp.RX(param, wires=0) + qp.CNOT(wires=[0, 1]) # The expval here will be the "cost function" we try to minimize. # Usually, this would be defined by the problem we want to solve, # but for this example we'll just use a single PauliZ. - return qml.expval(qml.PauliZ(0)) + return qp.expval(qp.PauliZ(0)) ############################################################################## @@ -203,11 +203,11 @@ def circuit(param): print("-----------") -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def circuit(param): - qml.RX(param, wires=0) - qml.CNOT(wires=[0, 1]) - return qml.expval(qml.PauliZ(0)) + qp.RX(param, wires=0) + qp.CNOT(wires=[0, 1]) + return qp.expval(qp.PauliZ(0)) # Compiling your circuit with JAX is very easy, just add jax.jit! @@ -271,15 +271,15 @@ def circuit(param): @jax.jit def circuit(key, param): # Notice how the device construction now happens within the jitted method. - dev = qml.device("default.qubit", wires=2, seed=key) + dev = qp.device("default.qubit", wires=2, seed=key) # Now we can create our qnode within the circuit function. - @qml.set_shots(10) - @qml.qnode(dev, interface="jax", diff_method=None) + @qp.set_shots(10) + @qp.qnode(dev, interface="jax", diff_method=None) def my_circuit(): - qml.RX(param, wires=0) - qml.CNOT(wires=[0, 1]) - return qml.sample(qml.PauliZ(0)) + qp.RX(param, wires=0) + qp.CNOT(wires=[0, 1]) + return qp.sample(qp.PauliZ(0)) return my_circuit() diff --git a/demonstrations_v2/tutorial_jax_transformations/metadata.json b/demonstrations_v2/tutorial_jax_transformations/metadata.json index 874dc04eba..4dd4295467 100644 --- a/demonstrations_v2/tutorial_jax_transformations/metadata.json +++ b/demonstrations_v2/tutorial_jax_transformations/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2021-04-12T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Devices and Performance" ], diff --git a/demonstrations_v2/tutorial_kak_decomposition/demo.py b/demonstrations_v2/tutorial_kak_decomposition/demo.py index 666fb58bfc..08ac15bb0c 100644 --- a/demonstrations_v2/tutorial_kak_decomposition/demo.py +++ b/demonstrations_v2/tutorial_kak_decomposition/demo.py @@ -99,17 +99,17 @@ """ from itertools import product, combinations -import pennylane as qml +import pennylane as qp from pennylane import X, Y, Z import numpy as np su2 = [X(0), Y(0), Z(0)] print(f"su(2) is {len(su2)}-dimensional") -all_hermitian = all(qml.equal(qml.adjoint(op).simplify(), op) for op in su2) +all_hermitian = all(qp.equal(qp.adjoint(op).simplify(), op) for op in su2) print(f"The operators are all Hermitian: {all_hermitian}") -su2_lie_closed = qml.lie_closure(su2) +su2_lie_closed = qp.lie_closure(su2) print(f"The Lie closure of su(2) is {len(su2_lie_closed)}-dimensional.") traces = [op.pauli_rep.trace() for op in su2] @@ -259,7 +259,7 @@ def inner_product(op1, op2): """Compute the trace inner product between two operators.""" # Use two wires to reuse it in the second example on two qubits later on - return qml.math.trace(qml.matrix(qml.adjoint(op1) @ op2, wire_order=[0, 1])) + return qp.math.trace(qp.matrix(qp.adjoint(op1) @ op2, wire_order=[0, 1])) def is_orthogonal(op, basis): @@ -354,9 +354,9 @@ def is_orthogonal(op, basis): def check_cartan_decomp(g, k, space_name): """Given an algebra g and an operator subspace k, verify that k is a subalgebra - and gives rise to a Cartan decomposition. Similar to qml.liealg.check_cartan_decomp""" + and gives rise to a Cartan decomposition. Similar to qp.liealg.check_cartan_decomp""" # Check Lie closure of k - k_lie_closure = qml.lie_closure(k) + k_lie_closure = qp.lie_closure(k) k_is_closed = len(k_lie_closure) == len(k) print(f"The Lie closure of k is as big as k itself: {k_is_closed}.") @@ -368,7 +368,7 @@ def check_cartan_decomp(g, k, space_name): ) # Check reductive property - k_p_commutators = [qml.commutator(k_op, p_op) for k_op, p_op in product(k, p)] + k_p_commutators = [qp.commutator(k_op, p_op) for k_op, p_op in product(k, p)] k_p_coms_in_p = all([is_orthogonal(com, k) for com in k_p_commutators]) print(f"All commutators in [k, p] are in p (orthogonal to k): {k_p_coms_in_p}.") @@ -376,7 +376,7 @@ def check_cartan_decomp(g, k, space_name): print(f"{space_name} is a reductive homogeneous space.") # Check symmetric property - p_p_commutators = [qml.commutator(*ops) for ops in combinations(p, r=2)] + p_p_commutators = [qp.commutator(*ops) for ops in combinations(p, r=2)] p_p_coms_in_k = all([is_orthogonal(com, p) for com in p_p_commutators]) print(f"All commutators in [p, p] are in k (orthogonal to p): {p_p_coms_in_k}.") @@ -481,11 +481,11 @@ def check_cartan_decomp(g, k, space_name): # Rotate CSA by applying some vertical group element exp(i eta Z) eta = 0.6 # The factor -2 compensates the convention -1/2 in the RZ gate -a_prime = qml.RZ(-2 * eta, 0) @ a @ qml.RZ(2 * eta, 0) +a_prime = qp.RZ(-2 * eta, 0) @ a @ qp.RZ(2 * eta, 0) # Expectation from our theoretical calculation a_prime_expected = np.cos(2 * eta) * a + np.sin(2 * eta) * p[0] -a_primes_equal = np.allclose(qml.matrix(a_prime_expected), qml.matrix(a_prime)) +a_primes_equal = np.allclose(qp.matrix(a_prime_expected), qp.matrix(a_prime)) print(f"The rotated CSAs match between numerics and theory: {a_primes_equal}") ###################################################################### @@ -607,15 +607,15 @@ def check_cartan_decomp(g, k, space_name): def theta_Z(x): - return qml.simplify(Z(0) @ x @ Z(0)) + return qp.simplify(Z(0) @ x @ Z(0)) theta_of_u1 = [theta_Z(x) for x in u1] -u1_is_su2_plus = all(qml.equal(x, theta_of_x) for x, theta_of_x in zip(u1, theta_of_u1)) +u1_is_su2_plus = all(qp.equal(x, theta_of_x) for x, theta_of_x in zip(u1, theta_of_u1)) print(f"U(1) is the +1 eigenspace: {u1_is_su2_plus}") theta_of_p = [theta_Z(x) for x in p] -p_is_su2_minus = all(qml.equal(-x, theta_of_x) for x, theta_of_x in zip(p, theta_of_p)) +p_is_su2_minus = all(qp.equal(-x, theta_of_x) for x, theta_of_x in zip(p, theta_of_p)) print(f"p is the -1 eigenspace: {p_is_su2_minus}") ###################################################################### @@ -625,14 +625,14 @@ def theta_Z(x): def theta_Y(x): - return qml.simplify(Y(0) @ x @ Y(0)) + return qp.simplify(Y(0) @ x @ Y(0)) eigvals = [] for x in su2: - if qml.equal(theta_Y(x), x): + if qp.equal(theta_Y(x), x): eigvals.append(1) - elif qml.equal(theta_Y(x), -x): + elif qp.equal(theta_Y(x), -x): eigvals.append(-1) else: raise ValueError("Operator not purely in either eigenspace.") @@ -766,9 +766,9 @@ def theta_Y(x): # :math:`SU(2)` gate! PennyLane produces it with :func:`~.pennylane.ops.one_qubit_decomposition`: x = 0.2j * su2[0] - 0.1j * su2[1] - 0.2j * su2[2] -G = qml.math.linalg.expm(qml.matrix(x)) +G = qp.math.linalg.expm(qp.matrix(x)) print("Decomposition:") -print(*qml.ops.one_qubit_decomposition(G, 0, rotations="ZYZ"), sep="\n") +print(*qp.ops.one_qubit_decomposition(G, 0, rotations="ZYZ"), sep="\n") ###################################################################### # If we pick a *horizontal gate*, i.e., a gate :math:`G\in\mathcal{P}`, we obtain the same @@ -777,8 +777,8 @@ def theta_Y(x): horizontal_x = -0.1j * p[0] - 4.1j * p[1] print(horizontal_x) -P = qml.math.linalg.expm(qml.matrix(horizontal_x)) -decomp = qml.ops.one_qubit_decomposition(P, 0, rotations="ZYZ") +P = qp.math.linalg.expm(qp.matrix(horizontal_x)) +decomp = qp.ops.one_qubit_decomposition(P, 0, rotations="ZYZ") print("Decomposition:", *decomp, sep="\n") angle_match = np.isclose((decomp[0].data[0] + decomp[-1].data[0]) % (2 * np.pi), 0.0) print(f"First and last rotation angle match up to sign and shift by 2kπ: {angle_match}") @@ -807,7 +807,7 @@ def theta_Y(x): # tool from earlier: # Define su(4). Skip first entry of Pauli group, which is the identity -su4 = list(qml.pauli.pauli_group(2))[1:] +su4 = list(qp.pauli.pauli_group(2))[1:] print(f"su(4) is {len(su4)}-dimensional") # Define subalgebra su(2) ⊕ su(2) @@ -872,17 +872,17 @@ def theta_Y(x): def su4_gate(params): phi0, phi1, eta, theta0, theta1 = np.split(params, range(3, 15, 3)) - qml.Rot(*phi0, wires=0) - qml.Rot(*phi1, wires=1) - qml.IsingXX(eta[0], wires=[0, 1]) - qml.IsingYY(eta[1], wires=[0, 1]) - qml.IsingZZ(eta[2], wires=[0, 1]) - qml.Rot(*theta0, wires=0) - qml.Rot(*theta1, wires=1) + qp.Rot(*phi0, wires=0) + qp.Rot(*phi1, wires=1) + qp.IsingXX(eta[0], wires=[0, 1]) + qp.IsingYY(eta[1], wires=[0, 1]) + qp.IsingZZ(eta[2], wires=[0, 1]) + qp.Rot(*theta0, wires=0) + qp.Rot(*theta1, wires=1) params = np.random.random(15) -fig, ax = qml.draw_mpl(su4_gate, wire_order=[0, 1])(params) +fig, ax = qp.draw_mpl(su4_gate, wire_order=[0, 1])(params) ###################################################################### # And that's a wrap on our application of the KAK decomposition for two-qubit gates! diff --git a/demonstrations_v2/tutorial_kak_decomposition/metadata.json b/demonstrations_v2/tutorial_kak_decomposition/metadata.json index 1a8014293f..8a0ef524fb 100644 --- a/demonstrations_v2/tutorial_kak_decomposition/metadata.json +++ b/demonstrations_v2/tutorial_kak_decomposition/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-11-25T00:00:00+00:00", - "dateOfLastModification": "2026-01-15T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Computing", "Compilation" diff --git a/demonstrations_v2/tutorial_kernel_based_training/demo.py b/demonstrations_v2/tutorial_kernel_based_training/demo.py index 6a472f2a8b..e554e12e85 100644 --- a/demonstrations_v2/tutorial_kernel_based_training/demo.py +++ b/demonstrations_v2/tutorial_kernel_based_training/demo.py @@ -168,7 +168,7 @@ from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score -import pennylane as qml +import pennylane as qp from pennylane.templates import AngleEmbedding, StronglyEntanglingLayers import matplotlib.pyplot as plt @@ -240,23 +240,23 @@ # \end{align*} # # Note that a projector :math:`|0..0 \rangle \langle 0..0|` can be constructed -# using the ``qml.Hermitian`` observable in PennyLane. +# using the ``qp.Hermitian`` observable in PennyLane. # # Altogether, we use the following quantum node as a *quantum kernel # evaluator*: # -dev_kernel = qml.device("lightning.qubit", wires=n_qubits) +dev_kernel = qp.device("lightning.qubit", wires=n_qubits) projector = np.zeros((2 ** n_qubits, 2 ** n_qubits)) projector[0, 0] = 1 -@qml.qnode(dev_kernel) +@qp.qnode(dev_kernel) def kernel(x1, x2): """The quantum kernel.""" AngleEmbedding(x1, wires=range(n_qubits)) - qml.adjoint(AngleEmbedding)(x2, wires=range(n_qubits)) - return qml.expval(qml.Hermitian(projector, wires=range(n_qubits))) + qp.adjoint(AngleEmbedding)(x2, wires=range(n_qubits)) + return qp.expval(qp.Hermitian(projector, wires=range(n_qubits))) ###################################################################### @@ -376,9 +376,9 @@ def circuit_evals_kernel(n_data, split): # and can therefore not scale to more than a few dozen qubits. # -dev_var = qml.device("lightning.qubit", wires=n_qubits) +dev_var = qp.device("lightning.qubit", wires=n_qubits) -@qml.qnode(dev_var, diff_method="parameter-shift") +@qp.qnode(dev_var, diff_method="parameter-shift") def quantum_model(x, params): """A variational quantum model.""" @@ -387,7 +387,7 @@ def quantum_model(x, params): # trainable measurement StronglyEntanglingLayers(params, wires=range(n_qubits)) - return qml.expval(qml.PauliZ(0)) + return qp.expval(qp.PauliZ(0)) def quantum_model_plus_bias(x, params, bias): """Adding a bias.""" diff --git a/demonstrations_v2/tutorial_kernel_based_training/metadata.json b/demonstrations_v2/tutorial_kernel_based_training/metadata.json index e0ae767c80..45cb0d0e20 100644 --- a/demonstrations_v2/tutorial_kernel_based_training/metadata.json +++ b/demonstrations_v2/tutorial_kernel_based_training/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2021-02-03T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Machine Learning" ], diff --git a/demonstrations_v2/tutorial_kernels_module/demo.py b/demonstrations_v2/tutorial_kernels_module/demo.py index 7c0a19112a..5f4fad203b 100644 --- a/demonstrations_v2/tutorial_kernels_module/demo.py +++ b/demonstrations_v2/tutorial_kernels_module/demo.py @@ -236,21 +236,21 @@ def plot_double_cake_data(X, Y, ax, num_sectors=None): # need for this is an *ansatz*, which we will construct by repeating a # layer as building block. Let's start by defining this layer: -import pennylane as qml +import pennylane as qp def layer(x, params, wires, i0=0, inc=1): """Building block of the embedding ansatz""" i = i0 for j, wire in enumerate(wires): - qml.Hadamard(wires=[wire]) - qml.RZ(x[i % len(x)], wires=[wire]) + qp.Hadamard(wires=[wire]) + qp.RZ(x[i % len(x)], wires=[wire]) i += inc - qml.RY(params[0, j], wires=[wire]) + qp.RY(params[0, j], wires=[wire]) n_wires = len(wires) for p, w in zip(params[1], wires): - qml.CRZ(p, wires=[w % n_wires, (w + 1) % n_wires]) + qp.CRZ(p, wires=[w % n_wires, (w + 1) % n_wires]) ############################################################################## @@ -260,7 +260,7 @@ def layer(x, params, wires, i0=0, inc=1): # Together, the datapoint and the variational parameters fully determine # the embedding ansatz :math:`U(\boldsymbol{x}).` # In order to construct the full kernel circuit, we also require its adjoint -# :math:`U(\boldsymbol{x})^\dagger,` which we can obtain via ``qml.adjoint`.` +# :math:`U(\boldsymbol{x})^\dagger,` which we can obtain via ``qp.adjoint`.` def ansatz(x, params, wires): @@ -269,7 +269,7 @@ def ansatz(x, params, wires): layer(x, layer_params, wires, i0=j * len(wires)) -adjoint_ansatz = qml.adjoint(ansatz) +adjoint_ansatz = qp.adjoint(ansatz) def random_params(num_wires, num_layers): @@ -282,7 +282,7 @@ def random_params(num_wires, num_layers): # For the purpose of this tutorial we will use PennyLane's ``default.qubit`` # device with 5 wires in analytic mode. -dev = qml.device("default.qubit", wires=5) +dev = qp.device("default.qubit", wires=5) wires = dev.wires.tolist() ############################################################################## @@ -292,17 +292,17 @@ def random_params(num_wires, num_layers): # finally extract the probabilities of observing each basis state. -@qml.qnode(dev) +@qp.qnode(dev) def kernel_circuit(x1, x2, params): ansatz(x1, params, wires=wires) adjoint_ansatz(x2, params, wires=wires) - return qml.probs(wires=wires) + return qp.probs(wires=wires) ############################################################################## # The kernel function itself is now obtained by looking at the probability # of observing the all-zero state at the end of the kernel circuit – because -# of the ordering in ``qml.probs``, this is the first entry: +# of the ordering in ``qp.probs``, this is the first entry: def kernel(x1, x2, params): @@ -334,7 +334,7 @@ def kernel(x1, x2, params): ############################################################################## # The mutual kernel values between all elements of the dataset form the -# *kernel matrix*. We can inspect it via the ``qml.kernels.square_kernel_matrix`` +# *kernel matrix*. We can inspect it via the ``qp.kernels.square_kernel_matrix`` # method, which makes use of symmetry of the kernel, # :math:`k(\boldsymbol{x}_i,\boldsymbol{x}_j) = k(\boldsymbol{x}_j, \boldsymbol{x}_i).` # In addition, the option ``assume_normalized_kernel=True`` ensures that we do not @@ -345,7 +345,7 @@ def kernel(x1, x2, params): # fixes them to the values we sampled above. init_kernel = lambda x1, x2: kernel(x1, x2, init_params) -K_init = qml.kernels.square_kernel_matrix(X, init_kernel, assume_normalized_kernel=True) +K_init = qp.kernels.square_kernel_matrix(X, init_kernel, assume_normalized_kernel=True) with np.printoptions(precision=3, suppress=True): print(K_init) @@ -363,7 +363,7 @@ def kernel(x1, x2, params): ############################################################################## # To construct the SVM, we need to supply ``sklearn.svm.SVC`` with a function # that takes two sets of datapoints and returns the associated kernel matrix. -# We can make use of the function ``qml.kernels.kernel_matrix`` that provides +# We can make use of the function ``qp.kernels.kernel_matrix`` that provides # this functionality. It expects the kernel to not have additional parameters # besides the datapoints, which is why we again supply the variational # parameters via the ``lambda`` function from above. @@ -375,7 +375,7 @@ def kernel(x1, x2, params): # ansatz. What it does is solving a different optimization task for the # :math:`\alpha` and :math:`b` vectors we introduced in the beginning. -svm = SVC(kernel=lambda X1, X2: qml.kernels.kernel_matrix(X1, X2, init_kernel)).fit(X, Y) +svm = SVC(kernel=lambda X1, X2: qp.kernels.kernel_matrix(X1, X2, init_kernel)).fit(X, Y) ############################################################################## # To see how well our classifier performs we will measure which percentage @@ -494,7 +494,7 @@ def plot_decision_boundaries(classifier, ax, N_gridpoints=14): # ``kernels`` module allows you to easily evaluate the kernel # target alignment: -kta_init = qml.kernels.target_alignment(X, Y, init_kernel, assume_normalized_kernel=True) +kta_init = qp.kernels.target_alignment(X, Y, init_kernel, assume_normalized_kernel=True) print(f"The kernel-target alignment for our dataset and random parameters is {kta_init:.3f}") @@ -511,7 +511,7 @@ def plot_decision_boundaries(classifier, ax, N_gridpoints=14): # *maximize* it in the process. # # .. note:: -# Currently, the function ``qml.kernels.target_alignment`` is not +# Currently, the function ``qp.kernels.target_alignment`` is not # differentiable yet, making it unfit for gradient descent optimization. # We therefore first define a differentiable version of this function. @@ -525,7 +525,7 @@ def target_alignment( ): """Kernel-target alignment between kernel and labels.""" - K = qml.kernels.square_kernel_matrix( + K = qp.kernels.square_kernel_matrix( X, kernel, assume_normalized_kernel=assume_normalized_kernel, @@ -547,7 +547,7 @@ def target_alignment( params = init_params -opt = qml.GradientDescentOptimizer(0.2) +opt = qp.GradientDescentOptimizer(0.2) for i in range(500): # Choose subset of datapoints to compute the KTA on. @@ -581,7 +581,7 @@ def target_alignment( trained_kernel = lambda x1, x2: kernel(x1, x2, params) # Second create a kernel matrix function using the trained kernel. -trained_kernel_matrix = lambda X1, X2: qml.kernels.kernel_matrix(X1, X2, trained_kernel) +trained_kernel_matrix = lambda X1, X2: qp.kernels.kernel_matrix(X1, X2, trained_kernel) # Note that SVC expects the kernel argument to be a kernel matrix function. svm_trained = SVC(kernel=trained_kernel_matrix).fit(X, Y) diff --git a/demonstrations_v2/tutorial_kernels_module/metadata.json b/demonstrations_v2/tutorial_kernels_module/metadata.json index 9016a69670..64614f4997 100644 --- a/demonstrations_v2/tutorial_kernels_module/metadata.json +++ b/demonstrations_v2/tutorial_kernels_module/metadata.json @@ -23,7 +23,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2021-06-24T00:00:00+00:00", - "dateOfLastModification": "2026-01-14T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Quantum Machine Learning" ], diff --git a/demonstrations_v2/tutorial_lcu_blockencoding/demo.py b/demonstrations_v2/tutorial_lcu_blockencoding/demo.py index 49cee9c194..8bea9c8ec3 100644 --- a/demonstrations_v2/tutorial_lcu_blockencoding/demo.py +++ b/demonstrations_v2/tutorial_lcu_blockencoding/demo.py @@ -45,7 +45,7 @@ """ import numpy as np -import pennylane as qml +import pennylane as qp a = 0.25 b = 0.75 @@ -58,7 +58,7 @@ [b, 0, 0, -a]] ) -LCU = qml.pauli_decompose(A) +LCU = qp.pauli_decompose(A) LCU_coeffs, LCU_ops = LCU.terms() print(f"LCU decomposition:\n {LCU}") @@ -142,16 +142,16 @@ # Prepare circuits can be constructed using the :class:`~.pennylane.StatePrep` operation, which takes # the normalized target state as input: -dev1 = qml.device("default.qubit", wires=1) +dev1 = qp.device("default.qubit", wires=1) # normalized square roots of coefficients alphas = (np.sqrt(LCU_coeffs) / np.linalg.norm(np.sqrt(LCU_coeffs))) -@qml.qnode(dev1) +@qp.qnode(dev1) def prep_circuit(): - qml.StatePrep(alphas, wires=0) - return qml.state() + qp.StatePrep(alphas, wires=0) + return qp.state() print("Target state: ", alphas) @@ -165,21 +165,21 @@ def prep_circuit(): import matplotlib.pyplot as plt -dev2 = qml.device("default.qubit", wires=3) +dev2 = qp.device("default.qubit", wires=3) # unitaries ops = LCU_ops # relabeling wires: 0 → 1, and 1 → 2 -unitaries = [qml.map_wires(op, {0: 1, 1: 2}) for op in ops] +unitaries = [qp.map_wires(op, {0: 1, 1: 2}) for op in ops] -@qml.qnode(dev2) +@qp.qnode(dev2) def sel_circuit(qubit_value): - qml.BasisState(qubit_value, wires=0) - qml.Select(unitaries, control=0) - return qml.expval(qml.PauliZ(2)) + qp.BasisState(qubit_value, wires=0) + qp.Select(unitaries, control=0) + return qp.expval(qp.PauliZ(2)) -qml.draw_mpl(sel_circuit, style='pennylane')([0]) +qp.draw_mpl(sel_circuit, style='pennylane')([0]) plt.show() ############################################################################## # Based on the controlled operations, the circuit above will flip the measured qubit @@ -197,20 +197,20 @@ def sel_circuit(qubit_value): # encoding. -@qml.qnode(dev2) +@qp.qnode(dev2) def lcu_circuit(): # block_encode # PREP - qml.StatePrep(alphas, wires=0) + qp.StatePrep(alphas, wires=0) # SEL - qml.Select(unitaries, control=0) + qp.Select(unitaries, control=0) # PREP_dagger - qml.adjoint(qml.StatePrep(alphas, wires=0)) - return qml.state() + qp.adjoint(qp.StatePrep(alphas, wires=0)) + return qp.state() -output_matrix = qml.matrix(lcu_circuit)() +output_matrix = qp.matrix(lcu_circuit)() print("A:\n", A, "\n") print("Block-encoded A:\n") print(np.real(np.round(output_matrix,2))) @@ -240,7 +240,7 @@ def lcu_circuit(): # block_encode coeffs = np.array([1/2, 1/2]) alphas = np.sqrt(coeffs) / np.linalg.norm(np.sqrt(coeffs)) -proj_unitaries = [qml.Identity(0), qml.PauliZ(0)] +proj_unitaries = [qp.Identity(0), qp.PauliZ(0)] ############################################################################## # Note that the second term in our LCU simplifies to a Pauli :math:`Z` operation. We can now @@ -249,17 +249,17 @@ def lcu_circuit(): # block_encode def lcu_circuit(): # block_encode # PREP - qml.StatePrep(alphas, wires="ancilla") + qp.StatePrep(alphas, wires="ancilla") # SEL - qml.Select(proj_unitaries, control="ancilla") + qp.Select(proj_unitaries, control="ancilla") # PREP_dagger - qml.adjoint(qml.StatePrep(alphas, wires="ancilla")) - return qml.state() + qp.adjoint(qp.StatePrep(alphas, wires="ancilla")) + return qp.state() -output_matrix = qml.matrix(lcu_circuit, wire_order=["ancilla", 0])() +output_matrix = qp.matrix(lcu_circuit, wire_order=["ancilla", 0])() print("Block-encoded projector:\n") print(np.real(np.round(output_matrix,2))) diff --git a/demonstrations_v2/tutorial_lcu_blockencoding/metadata.json b/demonstrations_v2/tutorial_lcu_blockencoding/metadata.json index db06e00e1a..aaf861fe3a 100644 --- a/demonstrations_v2/tutorial_lcu_blockencoding/metadata.json +++ b/demonstrations_v2/tutorial_lcu_blockencoding/metadata.json @@ -14,7 +14,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-10-25T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Algorithms", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_learning_dynamics_incoherently/demo.py b/demonstrations_v2/tutorial_learning_dynamics_incoherently/demo.py index b21cea07ca..376a7cb5bc 100644 --- a/demonstrations_v2/tutorial_learning_dynamics_incoherently/demo.py +++ b/demonstrations_v2/tutorial_learning_dynamics_incoherently/demo.py @@ -52,7 +52,7 @@ # We first create the Hamiltonian and Trotterize later with :class:`~pennylane.TrotterProduct`. # -import pennylane as qml +import pennylane as qp from pennylane import numpy as pnp import numpy as np import matplotlib.pyplot as plt @@ -68,9 +68,9 @@ alphas = np.random.normal(0, 0.5, size=n_qubits) # create the Hamiltonian -hamiltonian = qml.sum( - *[qml.PauliZ(wires=i) @ qml.PauliZ(wires=i + 1) for i in range(n_qubits - 1)] -) + qml.dot(alphas, [qml.PauliX(wires=i) for i in range(n_qubits)]) +hamiltonian = qp.sum( + *[qp.PauliZ(wires=i) @ qp.PauliZ(wires=i + 1) for i in range(n_qubits - 1)] +) + qp.dot(alphas, [qp.PauliX(wires=i) for i in range(n_qubits)]) ###################################################################### # 2. Creating random initial states @@ -114,19 +114,19 @@ # will approximate the time evolution of the transverse-field Ising system. # -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") -@qml.qnode(dev) +@qp.qnode(dev) def target_circuit(input_state): # prepare training state - qml.StatePrep(input_state, wires=range(n_qubits)) + qp.StatePrep(input_state, wires=range(n_qubits)) # evolve the Hamiltonian for time=2 in n=1 steps with the order 1 formula - qml.TrotterProduct(hamiltonian, time=2, n=1, order=1) - return qml.classical_shadow(wires=range(n_qubits)) + qp.TrotterProduct(hamiltonian, time=2, n=1, order=1) + return qp.classical_shadow(wires=range(n_qubits)) -qml.draw_mpl(target_circuit)(random_states[0]) +qp.draw_mpl(target_circuit)(random_states[0]) plt.show() ###################################################################### @@ -140,8 +140,8 @@ def target_circuit(input_state): shadows = [] for random_state in random_states: - bits, recipes = qml.set_shots(target_circuit, shots=n_measurements)(random_state) - shadow = qml.ClassicalShadow(bits, recipes) + bits, recipes = qp.set_shots(target_circuit, shots=n_measurements)(random_state) + shadow = qp.ClassicalShadow(bits, recipes) shadows.append(shadow) @@ -165,21 +165,21 @@ def target_circuit(input_state): # hardware, the density matrix is obtained via state tomography using Pauli measurements or classical shadows. -@qml.qnode(dev) +@qp.qnode(dev) def model_circuit(params, random_state): - qml.StatePrep(random_state, wires=range(n_qubits)) + qp.StatePrep(random_state, wires=range(n_qubits)) # parameterized quantum circuit with the same gate structure as the target for i in range(n_qubits): - qml.RX(params[i], wires=i) + qp.RX(params[i], wires=i) for i in reversed(range(n_qubits - 1)): - qml.IsingZZ(params[n_qubits + i], wires=[i, i + 1]) - return [qml.density_matrix(i) for i in range(n_qubits)] + qp.IsingZZ(params[n_qubits + i], wires=[i, i + 1]) + return [qp.density_matrix(i) for i in range(n_qubits)] initial_params = pnp.random.random(size=n_qubits*2-1, requires_grad=True) -qml.draw_mpl(model_circuit)(initial_params, random_states[0]) +qp.draw_mpl(model_circuit)(initial_params, random_states[0]) plt.show() ###################################################################### @@ -213,18 +213,18 @@ def cost(params): observable_mats = model_circuit(params, random_state) # convert to a PauliSentence observable_pauli = [ - qml.pauli_decompose(observable_mat, wire_order=[qubit]) + qp.pauli_decompose(observable_mat, wire_order=[qubit]) for qubit, observable_mat in enumerate(observable_mats) ] # estimate the overlap for each qubit - cost = cost + qml.math.sum(shadows[idx].expval(observable_pauli)) + cost = cost + qp.math.sum(shadows[idx].expval(observable_pauli)) cost = 1 - cost / n_qubits / n_random_states return cost params = initial_params -optimizer = qml.GradientDescentOptimizer(stepsize=5) +optimizer = qp.GradientDescentOptimizer(stepsize=5) steps = 50 costs = [None]*(steps+1) @@ -248,7 +248,7 @@ def cost(params): # find the ideal parameters from the original Trotterized Hamiltonian ideal_parameters = [ op.decomposition()[0].parameters[0] - for op in qml.TrotterProduct(hamiltonian, 2, 1, 1).decomposition() + for op in qp.TrotterProduct(hamiltonian, 2, 1, 1).decomposition() ] ideal_parameters = ideal_parameters[:n_qubits][::-1] + ideal_parameters[n_qubits:] @@ -282,16 +282,16 @@ def cost(params): import scipy -target_matrix = qml.matrix( - qml.TrotterProduct(hamiltonian, 2, 1, 1), +target_matrix = qp.matrix( + qp.TrotterProduct(hamiltonian, 2, 1, 1), wire_order=range(n_qubits), ) zero_state = [1] + [0]*(2**n_qubits-1) # model matrix using the all-|0> state to negate state preparation effects -model_matrices = [qml.matrix(model_circuit, wire_order=range(n_qubits))(params, zero_state) for params in params_list] -trace_distances = [qml.math.trace_distance(target_matrix, model_matrix) for model_matrix in model_matrices] +model_matrices = [qp.matrix(model_circuit, wire_order=range(n_qubits))(params, zero_state) for params in params_list] +trace_distances = [qp.math.trace_distance(target_matrix, model_matrix) for model_matrix in model_matrices] plt.plot(trace_distances) plt.ylabel("Trace distance") @@ -309,9 +309,9 @@ def cost(params): # larger, 16-qubit transverse-field Ising # Hamiltonian, and use classical shadow samples from quantum hardware to estimate the cost function. # The corresponding `Learning Dynamics Incoherently PennyLane Dataset `__ -# can be downloaded via the :mod:`qml.data` module. +# can be downloaded via the :mod:`qp.data` module. -[ds] = qml.data.load("other", name="learning-dynamics-incoherently") +[ds] = qp.data.load("other", name="learning-dynamics-incoherently") # print the available data print(ds.list_attributes()) @@ -332,7 +332,7 @@ def cost(params): random_states = ds.training_states n_measurements = 10000 -shadows = [qml.ClassicalShadow(shadow_meas[:n_measurements], shadow_bases[:n_measurements]) for shadow_meas, shadow_bases in zip(ds.shadow_meas,ds.shadow_bases)] +shadows = [qp.ClassicalShadow(shadow_meas[:n_measurements], shadow_bases[:n_measurements]) for shadow_meas, shadow_bases in zip(ds.shadow_meas,ds.shadow_bases)] ###################################################################### # @@ -342,23 +342,23 @@ def cost(params): # the increased number of qubits. # -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") -@qml.qnode(dev) +@qp.qnode(dev) def model_circuit(params, random_state): # this is a parameterized quantum circuit with the same gate structure as the target unitary - qml.StatePrep(random_state, wires=range(16)) + qp.StatePrep(random_state, wires=range(16)) for i in range(16): - qml.RX(params[i], wires=i) + qp.RX(params[i], wires=i) for i in reversed(range(15)): - qml.IsingZZ(params[16 + i], wires=[i, i + 1]) - return [qml.density_matrix(i) for i in range(16)] + qp.IsingZZ(params[16 + i], wires=[i, i + 1]) + return [qp.density_matrix(i) for i in range(16)] initial_params = pnp.random.random(size=31) -qml.draw_mpl(model_circuit)(initial_params, random_states[0]) +qp.draw_mpl(model_circuit)(initial_params, random_states[0]) plt.show() ###################################################################### @@ -372,7 +372,7 @@ def model_circuit(params, random_state): n_qubits = 16 n_random_states = len(ds.training_states) -optimizer = qml.GradientDescentOptimizer(stepsize=5) +optimizer = qp.GradientDescentOptimizer(stepsize=5) steps = 50 costs = [None]*(steps+1) diff --git a/demonstrations_v2/tutorial_learning_dynamics_incoherently/metadata.json b/demonstrations_v2/tutorial_learning_dynamics_incoherently/metadata.json index 970bedd9a9..df4619210e 100644 --- a/demonstrations_v2/tutorial_learning_dynamics_incoherently/metadata.json +++ b/demonstrations_v2/tutorial_learning_dynamics_incoherently/metadata.json @@ -4,7 +4,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-08-15T00:00:00+00:00", - "dateOfLastModification": "2025-11-05T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Quantum Machine Learning", "How-to" diff --git a/demonstrations_v2/tutorial_learning_few_data/demo.py b/demonstrations_v2/tutorial_learning_few_data/demo.py index 4a4f9a51ce..6e7fb6411e 100644 --- a/demonstrations_v2/tutorial_learning_few_data/demo.py +++ b/demonstrations_v2/tutorial_learning_few_data/demo.py @@ -140,7 +140,7 @@ import optax # optimization using jax -import pennylane as qml +import pennylane as qp import pennylane.numpy as pnp sns.set() @@ -189,13 +189,13 @@ def convolutional_layer(weights, wires, skip_first_layer=True): for indx, w in enumerate(wires): if indx % 2 == p and indx < n_wires - 1: if indx % 2 == 0 and not skip_first_layer: - qml.U3(*weights[:3], wires=[w]) - qml.U3(*weights[3:6], wires=[wires[indx + 1]]) - qml.IsingXX(weights[6], wires=[w, wires[indx + 1]]) - qml.IsingYY(weights[7], wires=[w, wires[indx + 1]]) - qml.IsingZZ(weights[8], wires=[w, wires[indx + 1]]) - qml.U3(*weights[9:12], wires=[w]) - qml.U3(*weights[12:], wires=[wires[indx + 1]]) + qp.U3(*weights[:3], wires=[w]) + qp.U3(*weights[3:6], wires=[wires[indx + 1]]) + qp.IsingXX(weights[6], wires=[w, wires[indx + 1]]) + qp.IsingYY(weights[7], wires=[w, wires[indx + 1]]) + qp.IsingZZ(weights[8], wires=[w, wires[indx + 1]]) + qp.U3(*weights[9:12], wires=[w]) + qp.U3(*weights[12:], wires=[wires[indx + 1]]) ############################################################################## @@ -215,8 +215,8 @@ def pooling_layer(weights, wires): for indx, w in enumerate(wires): if indx % 2 == 1 and indx < n_wires: - m_outcome = qml.measure(w) - qml.cond(m_outcome, qml.U3)(*weights, wires=wires[indx - 1]) + m_outcome = qp.measure(w) + qp.cond(m_outcome, qp.U3)(*weights, wires=wires[indx - 1]) ############################################################################## @@ -234,14 +234,14 @@ def conv_and_pooling(kernel_weights, n_wires, skip_first_layer=True): def dense_layer(weights, wires): """Apply an arbitrary unitary gate to a specified set of wires.""" - qml.ArbitraryUnitary(weights, wires) + qp.ArbitraryUnitary(weights, wires) num_wires = 6 -device = qml.device("default.qubit", wires=num_wires) +device = qp.device("default.qubit", wires=num_wires) -@qml.qnode(device) +@qp.qnode(device) def conv_net(weights, last_layer_weights, features): """Define the QCNN circuit Args: @@ -253,24 +253,24 @@ def conv_net(weights, last_layer_weights, features): wires = list(range(num_wires)) # inputs the state input_state - qml.AmplitudeEmbedding(features=features, wires=wires, pad_with=0.5) - qml.Barrier(wires=wires, only_visual=True) + qp.AmplitudeEmbedding(features=features, wires=wires, pad_with=0.5) + qp.Barrier(wires=wires, only_visual=True) # adds convolutional and pooling layers for j in range(layers): conv_and_pooling(weights[:, j], wires, skip_first_layer=(not j == 0)) wires = wires[::2] - qml.Barrier(wires=wires, only_visual=True) + qp.Barrier(wires=wires, only_visual=True) assert last_layer_weights.size == 4 ** (len(wires)) - 1, ( "The size of the last layer weights vector is incorrect!" f" \n Expected {4 ** (len(wires)) - 1}, Given {last_layer_weights.size}" ) dense_layer(last_layer_weights, wires) - return qml.probs(wires=(0)) + return qp.probs(wires=(0)) -fig, ax = qml.draw_mpl(conv_net)( +fig, ax = qp.draw_mpl(conv_net)( np.random.rand(18, 2), np.random.rand(4 ** 2 - 1), np.random.rand(2 ** num_wires) ) plt.show() diff --git a/demonstrations_v2/tutorial_learning_few_data/metadata.json b/demonstrations_v2/tutorial_learning_few_data/metadata.json index 92a1a3a2bb..31869b383b 100644 --- a/demonstrations_v2/tutorial_learning_few_data/metadata.json +++ b/demonstrations_v2/tutorial_learning_few_data/metadata.json @@ -14,7 +14,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2022-08-29T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Machine Learning" ], diff --git a/demonstrations_v2/tutorial_learning_from_experiments/demo.py b/demonstrations_v2/tutorial_learning_from_experiments/demo.py index 7003534eff..e8c95f56f3 100644 --- a/demonstrations_v2/tutorial_learning_from_experiments/demo.py +++ b/demonstrations_v2/tutorial_learning_from_experiments/demo.py @@ -159,7 +159,7 @@ # will allow rotations about X,Y, and Z. # -import pennylane as qml +import pennylane as qp from pennylane.templates.layers import RandomLayers import numpy as np @@ -173,21 +173,21 @@ def generate_circuit(shots): generate a random circuit that returns a number of measuement samples given by shots """ - dev = qml.device("lightning.qubit", wires=qubits) + dev = qp.device("lightning.qubit", wires=qubits) - @qml.set_shots(shots) - @qml.qnode(dev) + @qp.set_shots(shots) + @qp.qnode(dev) def circuit(ts=False): if ts == True: - ops = [qml.RY] # time-symmetric unitaries + ops = [qp.RY] # time-symmetric unitaries else: - ops = [qml.RX, qml.RY, qml.RZ] # general unitaries + ops = [qp.RX, qp.RY, qp.RZ] # general unitaries weights = np.random.rand(layers, gates) * np.pi RandomLayers(weights, wires=range(qubits), rotations=ops, seed=np.random.randint(0, 10000)) - return [qml.sample(op=qml.PauliY(q)) for q in range(qubits)] + return [qp.sample(op=qp.PauliY(q)) for q in range(qubits)] return circuit @@ -342,30 +342,30 @@ def process_data(raw_data): n_shots = 50 qubits = 8 -dev = qml.device("lightning.qubit", wires=qubits * 2) +dev = qp.device("lightning.qubit", wires=qubits * 2) def CNOT_sequence(control_wires, target_wires): """Apply CNOTs in sequence using the provided control and target wires""" for c_wire, t_wire in zip(control_wires, target_wires): - qml.CNOT([c_wire, t_wire]) + qp.CNOT([c_wire, t_wire]) -@qml.set_shots(n_shots) -@qml.qnode(dev) +@qp.set_shots(n_shots) +@qp.qnode(dev) def enhanced_circuit(ts=False): "implement the enhanced circuit, using a random unitary" if ts == True: - ops = [qml.RY] + ops = [qp.RY] else: - ops = [qml.RX, qml.RY, qml.RZ] + ops = [qp.RX, qp.RY, qp.RZ] weights = np.random.rand(layers, n_shots) * np.pi seed = np.random.randint(0, 10000) for q in range(qubits): - qml.Hadamard(wires=q) + qp.Hadamard(wires=q) CNOT_sequence(control_wires=range(qubits), target_wires=range(qubits, 2 * qubits)) RandomLayers(weights, wires=range(0, qubits), rotations=ops, seed=seed) @@ -373,9 +373,9 @@ def enhanced_circuit(ts=False): CNOT_sequence(control_wires=range(qubits), target_wires=range(qubits, 2 * qubits)) for q in range(qubits): - qml.Hadamard(wires=q) + qp.Hadamard(wires=q) - return [qml.sample(op=qml.PauliZ(q)) for q in range(2 * qubits)] + return [qp.sample(op=qp.PauliZ(q)) for q in range(2 * qubits)] ###################################################################### @@ -457,7 +457,7 @@ def noise_layer(epsilon): "apply a random rotation to each qubit" for q in range(2 * qubits): angles = (2 * np.random.rand(3) - 1) * epsilon - qml.Rot(angles[0], angles[1], angles[2], wires=q) + qp.Rot(angles[0], angles[1], angles[2], wires=q) ###################################################################### @@ -466,21 +466,21 @@ def noise_layer(epsilon): # -@qml.set_shots(n_shots) -@qml.qnode(dev) +@qp.set_shots(n_shots) +@qp.qnode(dev) def enhanced_circuit(ts=False): "implement the enhanced circuit, using a random unitary with a noise layer" if ts == True: - ops = [qml.RY] + ops = [qp.RY] else: - ops = [qml.RX, qml.RY, qml.RZ] + ops = [qp.RX, qp.RY, qp.RZ] weights = np.random.rand(layers, n_shots) * np.pi seed = np.random.randint(0, 10000) for q in range(qubits): - qml.Hadamard(wires=q) + qp.Hadamard(wires=q) CNOT_sequence(control_wires=range(qubits), target_wires=range(qubits, 2 * qubits)) RandomLayers(weights, wires=range(0, qubits), rotations=ops, seed=seed) @@ -489,9 +489,9 @@ def enhanced_circuit(ts=False): CNOT_sequence(control_wires=range(qubits, 2 * qubits), target_wires=range(qubits)) for q in range(qubits): - qml.Hadamard(wires=qubits + q) + qp.Hadamard(wires=qubits + q) - return [qml.sample(op=qml.PauliZ(q)) for q in range(2 * qubits)] + return [qp.sample(op=qp.PauliZ(q)) for q in range(2 * qubits)] ###################################################################### diff --git a/demonstrations_v2/tutorial_learning_from_experiments/metadata.json b/demonstrations_v2/tutorial_learning_from_experiments/metadata.json index a024d9c065..17244422bb 100644 --- a/demonstrations_v2/tutorial_learning_from_experiments/metadata.json +++ b/demonstrations_v2/tutorial_learning_from_experiments/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2022-04-18T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Quantum Machine Learning" ], diff --git a/demonstrations_v2/tutorial_learningshallow/demo.py b/demonstrations_v2/tutorial_learningshallow/demo.py index 664c50f6e5..539be154d3 100644 --- a/demonstrations_v2/tutorial_learningshallow/demo.py +++ b/demonstrations_v2/tutorial_learningshallow/demo.py @@ -32,18 +32,18 @@ make an explicit example in PennyLane after some boilerplate imports. Let us look at a very shallow unitary circuit :math:`U^\text{test} = \text{CNOT}_{(0, 1)}\text{CNOT}_{(2, 3)}\text{CNOT}_{(1, 2)} H^{\otimes n}.` """ -import pennylane as qml +import pennylane as qp import numpy as np import matplotlib.pyplot as plt def U_test(): for i in range(4): - qml.Hadamard(i) - qml.CNOT((1, 2)) - qml.CNOT((2, 3)) - qml.CNOT((0, 1)) + qp.Hadamard(i) + qp.CNOT((1, 2)) + qp.CNOT((2, 3)) + qp.CNOT((0, 1)) -qml.draw_mpl(U_test)() +qp.draw_mpl(U_test)() plt.show() @@ -55,17 +55,17 @@ def U_test(): # and perform the inverse operations in reverse order in :math:`V_0.` def V_0(): - qml.CNOT((0, 1)) - qml.CNOT((1, 2)) - qml.Hadamard(0) + qp.CNOT((0, 1)) + qp.CNOT((1, 2)) + qp.Hadamard(0) -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") -@qml.qnode(dev) +@qp.qnode(dev) def local_inversion(): U_test() # some shallow unitary circuit V_0() # supposed to disentangle qubit 0 - return qml.density_matrix(wires=[0]) + return qp.density_matrix(wires=[0]) print(np.allclose(local_inversion(), np.array([[1., 0.], [0., 0.]]))) @@ -84,19 +84,19 @@ def local_inversion(): # reverse-engineer them from knowing :math:`U^\text{test}.` def V_1(): - qml.CNOT((0, 1)) - qml.CNOT((1, 2)) - qml.Hadamard(1) + qp.CNOT((0, 1)) + qp.CNOT((1, 2)) + qp.Hadamard(1) def V_2(): - qml.CNOT((2, 3)) - qml.CNOT((1, 2)) - qml.Hadamard(2) + qp.CNOT((2, 3)) + qp.CNOT((1, 2)) + qp.Hadamard(2) def V_3(): - qml.CNOT((2, 3)) - qml.CNOT((1, 2)) - qml.Hadamard(3) + qp.CNOT((2, 3)) + qp.CNOT((1, 2)) + qp.Hadamard(3) ############################################################################## @@ -116,21 +116,21 @@ def V_3(): n = 4 # number of qubits -@qml.qnode(dev) +@qp.qnode(dev) def sewing_1(): U_test() # some shallow unitary circuit - qml.Barrier() + qp.Barrier() V_0() # disentangle qubit 0 - qml.Barrier() - qml.SWAP((0, n)) # swap out disentangled qubit 0 and n+0 - qml.Barrier() - qml.adjoint(V_0)() # repair circuit from V_0 - qml.Barrier() + qp.Barrier() + qp.SWAP((0, n)) # swap out disentangled qubit 0 and n+0 + qp.Barrier() + qp.adjoint(V_0)() # repair circuit from V_0 + qp.Barrier() V_1() # disentangle qubit 1 - return qml.density_matrix(wires=[1]), qml.density_matrix(wires=[n]) + return qp.density_matrix(wires=[1]), qp.density_matrix(wires=[n]) # The Barriers are to see which part of the circuit corresponds to which gate -qml.draw_mpl(sewing_1)() +qp.draw_mpl(sewing_1)() plt.show() r1, rn = sewing_1() @@ -141,17 +141,17 @@ def sewing_1(): ############################################################################## # We can continue this process for all qubits. Let us be tedious and do all steps one by one. -@qml.qnode(dev) +@qp.qnode(dev) def sewing_2(): U_test() # some shallow unitary circuit V_0() # disentangle qubit 0 - qml.SWAP((0, n)) # swap out disentangled qubit 0 and n+0 - qml.adjoint(V_0)() # repair circuit from V_0 + qp.SWAP((0, n)) # swap out disentangled qubit 0 and n+0 + qp.adjoint(V_0)() # repair circuit from V_0 V_1() # disentangle qubit 1 - qml.SWAP((1, n + 1)) # swap out disentangled qubit 1 to n+1 - qml.adjoint(V_1)() # repair circuit from V_1 + qp.SWAP((1, n + 1)) # swap out disentangled qubit 1 to n+1 + qp.adjoint(V_1)() # repair circuit from V_1 V_2() # disentangle qubit 2 - return qml.density_matrix(wires=[2]), qml.density_matrix(wires=[n]), qml.density_matrix(wires=[n + 1]) + return qp.density_matrix(wires=[2]), qp.density_matrix(wires=[n]), qp.density_matrix(wires=[n + 1]) r2, rn, rn1 = sewing_2() print(f"Sewing qubit 2") @@ -162,20 +162,20 @@ def sewing_2(): ############################################################################## # We continue to show that the swapped out wires remain decoupled, as well as the qubit we are currently decoupling. -@qml.qnode(dev) +@qp.qnode(dev) def sewing_3(): U_test() # some shallow unitary circuit V_0() # disentangle qubit 0 - qml.SWAP((0, n)) # swap out disentangled qubit 0 and n+0 - qml.adjoint(V_0)() # repair circuit from V_0 + qp.SWAP((0, n)) # swap out disentangled qubit 0 and n+0 + qp.adjoint(V_0)() # repair circuit from V_0 V_1() # disentangle qubit 1 - qml.SWAP((1, n + 1)) # swap out disentangled qubit 1 to n+1 - qml.adjoint(V_1)() # repair circuit from V_1 + qp.SWAP((1, n + 1)) # swap out disentangled qubit 1 to n+1 + qp.adjoint(V_1)() # repair circuit from V_1 V_2() # disentangle qubit 2 - qml.SWAP((2, n + 2)) # swap out disentangled qubit 2 to n+2 - qml.adjoint(V_2)() # repair circuit from V_2 + qp.SWAP((2, n + 2)) # swap out disentangled qubit 2 to n+2 + qp.adjoint(V_2)() # repair circuit from V_2 V_3() # disentangle qubit 3 - return qml.density_matrix(wires=[3]), qml.density_matrix(wires=[n]), qml.density_matrix(wires=[n + 1]), qml.density_matrix(wires=[n + 2]) + return qp.density_matrix(wires=[3]), qp.density_matrix(wires=[n]), qp.density_matrix(wires=[n + 1]), qp.density_matrix(wires=[n + 2]) r3, rn, rn1, rn2 = sewing_3() print(f"Sewing qubit 3") @@ -189,24 +189,24 @@ def sewing_3(): # with a global SWAP. # But not just that, we also now know that, globally, the original :math:`U^\text{test}` is inverted. -@qml.qnode(dev) +@qp.qnode(dev) def V_dagger_test(): U_test() # some shallow unitary circuit V_0() # disentangle qubit 0 - qml.SWAP((0, n)) # swap out disentangled qubit 0 and n+0 - qml.adjoint(V_0)() # repair circuit from V_0 + qp.SWAP((0, n)) # swap out disentangled qubit 0 and n+0 + qp.adjoint(V_0)() # repair circuit from V_0 V_1() # disentangle qubit 1 - qml.SWAP((1, n + 1)) # swap out disentangled qubit 1 to n+1 - qml.adjoint(V_1)() # repair circuit from V_1 + qp.SWAP((1, n + 1)) # swap out disentangled qubit 1 to n+1 + qp.adjoint(V_1)() # repair circuit from V_1 V_2() # disentangle qubit 2 - qml.SWAP((2, n + 2)) # swap out disentangled qubit 2 to n+2 - qml.adjoint(V_2)() # repair circuit from V_2 + qp.SWAP((2, n + 2)) # swap out disentangled qubit 2 to n+2 + qp.adjoint(V_2)() # repair circuit from V_2 V_3() # disentangle qubit 3 - qml.SWAP((3, n + 3)) # swap out disentangled qubit 3 to n+3 - qml.adjoint(V_3)() # repair circuit from V_3 + qp.SWAP((3, n + 3)) # swap out disentangled qubit 3 to n+3 + qp.adjoint(V_3)() # repair circuit from V_3 for i in range(n): # swap back all decoupled wires to their original registers - qml.SWAP((i + n, i)) - return qml.density_matrix([0, 1, 2, 3]) + qp.SWAP((i + n, i)) + return qp.density_matrix([0, 1, 2, 3]) psi0 = np.eye(2**4)[0] # |0>^n np.allclose(V_dagger_test(), np.outer(psi0, psi0)) @@ -217,19 +217,19 @@ def V_dagger_test(): def V_dagger(): V_0() # disentangle qubit 0 - qml.SWAP((0, n)) # swap out disentangled qubit 0 and n+0 - qml.adjoint(V_0)() # repair circuit from V_0 + qp.SWAP((0, n)) # swap out disentangled qubit 0 and n+0 + qp.adjoint(V_0)() # repair circuit from V_0 V_1() # disentangle qubit 1 - qml.SWAP((1, n + 1)) # swap out disentangled qubit 1 to n+1 - qml.adjoint(V_1)() # repair circuit from V_1 + qp.SWAP((1, n + 1)) # swap out disentangled qubit 1 to n+1 + qp.adjoint(V_1)() # repair circuit from V_1 V_2() # disentangle qubit 2 - qml.SWAP((2, n + 2)) # swap out disentangled qubit 2 to n+2 - qml.adjoint(V_2)() # repair circuit from V_2 + qp.SWAP((2, n + 2)) # swap out disentangled qubit 2 to n+2 + qp.adjoint(V_2)() # repair circuit from V_2 V_3() # disentangle qubit 3 - qml.SWAP((3, n + 3)) # swap out disentangled qubit 3 to n+3 - qml.adjoint(V_3)() # repair circuit from V_3 + qp.SWAP((3, n + 3)) # swap out disentangled qubit 3 to n+3 + qp.adjoint(V_3)() # repair circuit from V_3 for i in range(n): # swap back all decoupled wires to their original registers - qml.SWAP((i + n, i)) + qp.SWAP((i + n, i)) ############################################################################## # It is such that the action of :math:`U^\text{test}` on :math:`|0 \rangle^{\otimes n}` is reverted when tracing out the ancilla qubits. @@ -266,14 +266,14 @@ def V_dagger(): def U_target(wires): for i in range(n): - qml.Hadamard(wires=wires[i]) + qp.Hadamard(wires=wires[i]) # brick-wall ansatz for i in range(0, n, 2): - qml.IsingXX(U_params[0, i], wires=(wires[i], wires[(i+1)%len(wires)])) + qp.IsingXX(U_params[0, i], wires=(wires[i], wires[(i+1)%len(wires)])) for i in range(1, n, 2): - qml.IsingXX(U_params[1, i], wires=(wires[i], wires[(i+1)%len(wires)])) + qp.IsingXX(U_params[1, i], wires=(wires[i], wires[(i+1)%len(wires)])) -qml.draw_mpl(U_target)(wires) +qp.draw_mpl(U_target)(wires) plt.show() ############################################################################## @@ -284,23 +284,23 @@ def U_target(wires): def V_i(params, wires): for i in range(n): - qml.RX(params[0, 0, i], i) + qp.RX(params[0, 0, i], i) for i in range(n): - qml.RY(params[0, 1, i], i) + qp.RY(params[0, 1, i], i) for ll in range(n_layers): for i in range(0, n, 2): - qml.CNOT((wires[i], wires[i+1])) + qp.CNOT((wires[i], wires[i+1])) for i in range(1, n, 2): - qml.CNOT((wires[i], wires[(i+1)%n])) + qp.CNOT((wires[i], wires[(i+1)%n])) for i in range(n): - qml.RX(params[ll+1, 0, i], i) + qp.RX(params[ll+1, 0, i], i) for i in range(n): - qml.RY(params[ll+1, 1, i], i) + qp.RY(params[ll+1, 1, i], i) params = jax.random.normal(jax.random.PRNGKey(10), shape=(n_layers+1, 2, n), dtype=float) -qml.draw_mpl(V_i)(params, wires) +qp.draw_mpl(V_i)(params, wires) plt.show() ############################################################################## @@ -312,7 +312,7 @@ def V_i(params, wires): from datetime import datetime from functools import partial -X, Y, Z = qml.PauliX, qml.PauliY, qml.PauliZ +X, Y, Z = qp.PauliX, qp.PauliY, qp.PauliZ def run_opt(value_and_grad, theta, n_epochs=100, lr=0.1, b1=0.9, b2=0.999): @@ -344,17 +344,17 @@ def step(opt_state, theta): return thetas, energy -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") ############################################################################## # As a cost function, we perform state tomography after applying :math:`U^\text{target}` and our Ansatz :math:`V_i.` # Our aim is to bring the state on qubit ``i`` back to the north pole of the Bloch sphere, and we specify our cost function accordingly. -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def qnode_i(params, i): U_target(wires) V_i(params, wires) - return [qml.expval(P(i)) for P in [X, Y, Z]] + return [qp.expval(P(i)) for P in [X, Y, Z]] @partial(jax.jit, static_argnums=1) @jax.value_and_grad @@ -386,18 +386,18 @@ def V_sew(): for i in range(n): # local sewing: inversion, exchange, heal V_i(params_i[i], range(n)) - qml.SWAP((i, i+n)) - qml.adjoint(V_i)(params_i[i], range(n)) + qp.SWAP((i, i+n)) + qp.adjoint(V_i)(params_i[i], range(n)) # global SWAP for i in range(n): - qml.SWAP((i, i+n)) + qp.SWAP((i, i+n)) -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def sewing_test(): U_target(range(n)) V_sew() - return qml.density_matrix(range(4)) + return qp.density_matrix(range(4)) print(np.allclose(sewing_test(), np.outer(psi0, psi0), atol=1e-1)) diff --git a/demonstrations_v2/tutorial_learningshallow/metadata.json b/demonstrations_v2/tutorial_learningshallow/metadata.json index f6da8b5eaa..0bd4549ef5 100644 --- a/demonstrations_v2/tutorial_learningshallow/metadata.json +++ b/demonstrations_v2/tutorial_learningshallow/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-01-24T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Optimization", "Quantum Computing", From 3ef96362aafa9a0249f7c2bbaa842d050cd01f05 Mon Sep 17 00:00:00 2001 From: drdren <104710745+drdren@users.noreply.github.com> Date: Tue, 21 Apr 2026 10:50:02 -0400 Subject: [PATCH 04/10] qml to qp Batch 6 (#1757) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### Before submitting Please complete the following checklist when submitting a PR: - [ ] Ensure that your tutorial executes correctly, and conforms to the guidelines specified in the [README](https://github.com/PennyLaneAI/demos/blob/master/README.md). - [ ] Remember to do a grammar check of the content you include. - [ ] All tutorials conform to [PEP8 standards](https://www.python.org/dev/peps/pep-0008/). To auto format files, simply `pip install black`, and then run `black -l 100 path/to/file.py`. When all the above are checked, delete everything above the dashed line and fill in the pull request template. ------------------------------------------------------------------------------------------------------------ **Title:** **Summary:** **Relevant references:** **Possible Drawbacks:** **Related GitHub Issues:** ---- If you are writing a demonstration, please answer these questions to facilitate the marketing process. * GOALS — Why are we working on this now? *Eg. Promote a new PL feature or show a PL implementation of a recent paper.* * AUDIENCE — Who is this for? *Eg. Chemistry researchers, PL educators, beginners in quantum computing.* * KEYWORDS — What words should be included in the marketing post? * Which of the following types of documentation is most similar to your file? (more details [here](https://www.notion.so/xanaduai/Different-kinds-of-documentation-69200645fe59442991c71f9e7d8a77f8)) - [ ] Tutorial - [ ] Demo - [ ] How-to Co-authored-by: David --- demonstrations_v2/tutorial_liealgebra/demo.py | 56 +++---- .../tutorial_liealgebra/metadata.json | 2 +- demonstrations_v2/tutorial_liesim/demo.py | 20 +-- .../tutorial_liesim/metadata.json | 2 +- .../tutorial_liesim_extension/demo.py | 32 ++-- .../tutorial_liesim_extension/metadata.json | 2 +- .../tutorial_local_cost_functions/demo.py | 86 +++++----- .../metadata.json | 2 +- .../tutorial_loom_catalyst/demo.py | 26 +-- .../tutorial_loom_catalyst/metadata.json | 2 +- .../tutorial_magic_state_distillation/demo.py | 70 ++++---- .../metadata.json | 2 +- .../tutorial_magic_states/demo.py | 20 +-- .../tutorial_magic_states/metadata.json | 2 +- demonstrations_v2/tutorial_mapping/demo.py | 36 ++--- .../tutorial_mapping/metadata.json | 2 +- demonstrations_v2/tutorial_mbqc/demo.py | 152 +++++++++--------- demonstrations_v2/tutorial_mbqc/metadata.json | 2 +- .../tutorial_mcm_introduction/demo.py | 62 +++---- .../tutorial_mcm_introduction/metadata.json | 2 +- .../tutorial_measurement_optimize/demo.py | 114 ++++++------- .../metadata.json | 2 +- .../tutorial_mitigation_advantage/demo.py | 30 ++-- .../metadata.json | 2 +- .../tutorial_mol_geo_opt/demo.py | 20 +-- .../tutorial_mol_geo_opt/metadata.json | 2 +- demonstrations_v2/tutorial_mps/demo.py | 18 +-- demonstrations_v2/tutorial_mps/metadata.json | 2 +- .../demo.py | 16 +- .../metadata.json | 2 +- .../tutorial_neutral_atoms/demo.py | 46 +++--- .../tutorial_neutral_atoms/metadata.json | 2 +- .../demo.py | 56 +++---- .../metadata.json | 2 +- .../tutorial_noisy_circuits/demo.py | 58 +++---- .../tutorial_noisy_circuits/metadata.json | 2 +- demonstrations_v2/tutorial_odegen/demo.py | 30 ++-- .../tutorial_odegen/metadata.json | 2 +- 38 files changed, 493 insertions(+), 493 deletions(-) diff --git a/demonstrations_v2/tutorial_liealgebra/demo.py b/demonstrations_v2/tutorial_liealgebra/demo.py index 49566c0140..af9a664483 100644 --- a/demonstrations_v2/tutorial_liealgebra/demo.py +++ b/demonstrations_v2/tutorial_liealgebra/demo.py @@ -98,22 +98,22 @@ First, let us do a linear combination of :math:`\{iX, iY, iZ\}` with some real values and check unitarity after putting them in the exponent. """ import numpy as np -import pennylane as qml +import pennylane as qp from pennylane import X, Y, Z su2 = [1j * X(0), 1j * Y(0), 1j * Z(0)] coeffs = [1., 2., 3.] # some real coefficients -exponent = qml.dot(coeffs, su2) # linear combination of operators -U = qml.math.expm(exponent.matrix()) # compute matrix exponent of lin. comb. +exponent = qp.dot(coeffs, su2) # linear combination of operators +U = qp.math.expm(exponent.matrix()) # compute matrix exponent of lin. comb. print(np.allclose(U.conj().T @ U, np.eye(2))) # check that result is unitary UU* = 1 ############################################################################## # If we throw complex values in the mix, the resulting matrix is not unitary anymore. coeffs = [1., 2.+ 1j, 3.] # some complex coefficients -exponent = qml.dot(coeffs, su2) -U = qml.math.expm(exponent.matrix()) +exponent = qp.dot(coeffs, su2) +U = qp.math.expm(exponent.matrix()) print(np.allclose(U.conj().T @ U, np.eye(2))) # result is not unitary anymore ############################################################################## @@ -158,7 +158,7 @@ # # Let us do a quick example and compute the Lie closure of :math:`\{iX, iY\}` (more examples later). -print(qml.commutator(1j * X(0), 1j * Y(0))) +print(qp.commutator(1j * X(0), 1j * Y(0))) ############################################################################## # We know that the commutator between :math:`iX` and :math:`iY` yields a new operator :math:`\propto iZ.` @@ -168,15 +168,15 @@ list_ops = [1j * X(0), 1j * Y(0), 1j * Z(0)] for op1 in list_ops: for op2 in list_ops: - print(qml.commutator(op1, op2)) + print(qp.commutator(op1, op2)) ############################################################################## # Since no new operators have been created we know the lie closure is complete and our dynamical Lie algebra # is :math:`\langle\{iX, iY\}\rangle_\text{Lie} = \{iX, iY, iZ\}( = \mathfrak{su}(2)).` # -# PennyLane provides some dedicated functionality for Lie algebras. We can compute the Lie closure of the generators using ``qml.lie_closure``. +# PennyLane provides some dedicated functionality for Lie algebras. We can compute the Lie closure of the generators using ``qp.lie_closure``. -dla = qml.lie_closure([X(0), Y(0)]) +dla = qp.lie_closure([X(0), Y(0)]) dla ############################################################################## @@ -187,14 +187,14 @@ # these :math:`X` and :math:`Y` rotations :math:`e^{-i \phi X}` and :math:`e^{-i \phi Y}.` # For example, let us write a Pauli-Z rotation at non-trivial angle :math:`0.5` as a product of them. -U_target = qml.matrix(qml.RZ(-0.5, 0)) -decomp = qml.ops.one_qubit_decomposition(U_target, 0, rotations="XYX") +U_target = qp.matrix(qp.RZ(-0.5, 0)) +decomp = qp.ops.one_qubit_decomposition(U_target, 0, rotations="XYX") print(decomp) ############################################################################## # We can check that this is indeed a valid decomposition by computing the trace distance to the target. -U = qml.prod(*decomp).matrix() +U = qp.prod(*decomp).matrix() print(1 - np.real(np.trace(U_target @ U))/2) ############################################################################## @@ -215,10 +215,10 @@ generators = [1j * (X(0) @ X(1)), 1j * Z(0), 1j * Z(1)] # collection of linearly independent basis vectors, automatically discards linearly dependent ones -dla = qml.pauli.PauliVSpace(generators, dtype=complex) +dla = qp.pauli.PauliVSpace(generators, dtype=complex) for i, op1 in enumerate(generators): for op2 in generators[i+1:]: - res = qml.commutator(op1, op2)/2 + res = qp.commutator(op1, op2)/2 res = res.simplify() # ensures all products of scalars are executed print(f"[{op1}, {op2}] = {res}") @@ -234,7 +234,7 @@ for i, op1 in enumerate(dla.basis.copy()): for op2 in dla.basis.copy()[i+1:]: - res = qml.commutator(op1, op2)/2 + res = qp.commutator(op1, op2)/2 res = res.simplify() print(f"[{op1}, {op2}] = {res}") @@ -257,7 +257,7 @@ # We have constructed the DLA by hand to showcase the process. We can use the PennyLane function :func:`~lie_closure` for convenience. # In that case, we omit the explicit use of the imgaginary factor. -dla2 = qml.lie_closure([X(0) @ X(1), Z(0), Z(1)]) +dla2 = qp.lie_closure([X(0) @ X(1), Z(0), Z(1)]) for op in dla2: print(op) @@ -277,8 +277,8 @@ def IsingGenerators(n, bc="open"): return gens for n in range(2, 5): - open_ = qml.lie_closure(IsingGenerators(n, "open")) - periodic_ = qml.lie_closure(IsingGenerators(n, "periodic")) + open_ = qp.lie_closure(IsingGenerators(n, "open")) + periodic_ = qp.lie_closure(IsingGenerators(n, "periodic")) print(f"Ising for n = {n}") print(f"open: {len(open_)} = {n*(2*n-1)} = 2n * (2n - 1)/2") print(f"open: {len(periodic_)} = {2*n*(2*n-1)} = 2 * 2n * (2n - 1)/2") @@ -328,15 +328,15 @@ def IsingGenerators(n, bc="open"): # Let us briefly verify this for a small example for ``n = 3`` qubits that readily generalizes to arbitrary sizes. n = 3 -H = qml.sum(*(P(i) @ P(i+1) for i in range(n-1) for P in [X, Y, Z])) +H = qp.sum(*(P(i) @ P(i+1) for i in range(n-1) for P in [X, Y, Z])) -SX = qml.sum(*(X(i) for i in range(n))) -SY = qml.sum(*(Y(i) for i in range(n))) -SZ = qml.sum(*(Z(i) for i in range(n))) +SX = qp.sum(*(X(i) for i in range(n))) +SY = qp.sum(*(Y(i) for i in range(n))) +SZ = qp.sum(*(Z(i) for i in range(n))) -print(qml.commutator(H, SX)) -print(qml.commutator(H, SY)) -print(qml.commutator(H, SZ)) +print(qp.commutator(H, SX)) +print(qp.commutator(H, SY)) +print(qp.commutator(H, SZ)) ############################################################################## # @@ -363,9 +363,9 @@ def IsingGenerators(n, bc="open"): # This is easily verified by looking at the commutation relation between these operators that match :math:`[\hat{O}_i, \hat{O}_j] = 2i \varepsilon_{ij\ell} \hat{O}_\ell,` the defining # property of :math:`\mathfrak{su}(2).` -print(qml.commutator(SX, SY) == (2j*SZ).simplify()) -print(qml.commutator(SZ, SX) == (2j*SY).simplify()) -print(qml.commutator(SY, SZ) == (2j*SX).simplify()) +print(qp.commutator(SX, SY) == (2j*SZ).simplify()) +print(qp.commutator(SZ, SX) == (2j*SY).simplify()) +print(qp.commutator(SY, SZ) == (2j*SX).simplify()) ############################################################################## # diff --git a/demonstrations_v2/tutorial_liealgebra/metadata.json b/demonstrations_v2/tutorial_liealgebra/metadata.json index 34d266c35b..8f1a5ee484 100644 --- a/demonstrations_v2/tutorial_liealgebra/metadata.json +++ b/demonstrations_v2/tutorial_liealgebra/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-02-27T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Computing", "Getting Started" diff --git a/demonstrations_v2/tutorial_liesim/demo.py b/demonstrations_v2/tutorial_liesim/demo.py index 1a04dbac6c..91ad534511 100644 --- a/demonstrations_v2/tutorial_liesim/demo.py +++ b/demonstrations_v2/tutorial_liesim/demo.py @@ -156,7 +156,7 @@ """ -import pennylane as qml +import pennylane as qp from pennylane import X, Z, I import numpy as np @@ -186,7 +186,7 @@ # work with PauliSentence instances for efficiency generators = [op.pauli_rep for op in generators] -dla = qml.lie_closure(generators, pauli=True) +dla = qp.lie_closure(generators, pauli=True) dim_g = len(dla) ############################################################################## @@ -207,7 +207,7 @@ # initial state |0x0| = (I + Z)/2, note that trace function # below already normalizes by the dimension, # so we can ommit the explicit factor /2 - rho_in = qml.prod(*(I(i) + Z(i) for i in h_i.wires)) + rho_in = qp.prod(*(I(i) + Z(i) for i in h_i.wires)) rho_in = rho_in.pauli_rep e_in[i] = (h_i @ rho_in).trace() @@ -239,7 +239,7 @@ # the forward pass of the expectation value computation. For demonstration purposes, # we choose a random subset of ``depth=10`` generators for gates from the DLA. -adjoint_repr = qml.structure_constants(dla) +adjoint_repr = qp.structure_constants(dla) depth = 10 gate_choice = np.random.choice(dim_g, size=depth) @@ -264,13 +264,13 @@ def forward(theta): ############################################################################## # As a sanity check, we compare the computation with the full state vector equivalent circuit. -H = 0.5 * qml.sum(*[op.operation() for op in generators]) +H = 0.5 * qp.sum(*[op.operation() for op in generators]) -@qml.qnode(qml.device("default.qubit"), interface="jax") +@qp.qnode(qp.device("default.qubit"), interface="jax") def qnode(theta): for i, mu in enumerate(gate_choice): - qml.exp(-1j * theta[i] * dla[mu].operation()) - return qml.expval(H) + qp.exp(-1j * theta[i] * dla[mu].operation()) + return qp.expval(H) statevec_forward, statevec_backward = qnode(theta), jax.grad(qnode)(theta) statevec_forward, statevec_backward @@ -282,8 +282,8 @@ def qnode(theta): # expectation value vector. print( - qml.math.allclose(statevec_forward, gsim_forward), - qml.math.allclose(statevec_backward, gsim_backward), + qp.math.allclose(statevec_forward, gsim_forward), + qp.math.allclose(statevec_backward, gsim_backward), ) ############################################################################## diff --git a/demonstrations_v2/tutorial_liesim/metadata.json b/demonstrations_v2/tutorial_liesim/metadata.json index 7b2680231c..dc43b78ca2 100644 --- a/demonstrations_v2/tutorial_liesim/metadata.json +++ b/demonstrations_v2/tutorial_liesim/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-06-07T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Computing", "Getting Started" diff --git a/demonstrations_v2/tutorial_liesim_extension/demo.py b/demonstrations_v2/tutorial_liesim_extension/demo.py index 177f0cd807..56c1a40446 100644 --- a/demonstrations_v2/tutorial_liesim_extension/demo.py +++ b/demonstrations_v2/tutorial_liesim_extension/demo.py @@ -84,7 +84,7 @@ """ -import pennylane as qml +import pennylane as qp import numpy as np from pennylane import X, Y, Z, I @@ -99,7 +99,7 @@ def TFIM(n): generators += [Z(i) for i in range(n)] generators = [op.pauli_rep for op in generators] - dla = qml.lie_closure(generators, pauli=True) + dla = qp.lie_closure(generators, pauli=True) dim_g = len(dla) return generators, dla, dim_g @@ -109,7 +109,7 @@ def TFIM(n): # In regular :math:`\mathfrak{g}`-sim, the unitary evolution :math:`\mathcal{U}` of the expectation vector # is simply generated by the adjoint representation :math:`U.` -adjoint_repr = qml.structure_constants(dla) +adjoint_repr = qp.structure_constants(dla) gate = adjoint_repr[-1] theta = 0.5 @@ -135,7 +135,7 @@ def TFIM(n): p = dla[-5] @ dla[-1] p = next(iter(p)) # strip any scalar coefficients -dla_vspace = qml.pauli.PauliVSpace(dla, dtype=complex) +dla_vspace = qp.pauli.PauliVSpace(dla, dtype=complex) dla_vspace.is_independent(p.pauli_rep) @@ -248,7 +248,7 @@ def exppw(theta, ps): E_in = [E0_in, E1_in] for i, hi in enumerate(dla): - rho_in = qml.prod(*(I(i) + Z(i) for i in hi.wires)) + rho_in = qp.prod(*(I(i) + Z(i) for i in hi.wires)) rho_in = rho_in.pauli_rep E_in[0][i] = (hi @ rho_in).trace() @@ -256,8 +256,8 @@ def exppw(theta, ps): for i, hi in enumerate(dla): for j, hj in enumerate(dla): prod = hi @ hj - if prod.wires != qml.wires.Wires([]): - rho_in = qml.prod(*(I(i) + Z(i) for i in prod.wires)) + if prod.wires != qp.wires.Wires([]): + rho_in = qp.prod(*(I(i) + Z(i) for i in prod.wires)) else: rho_in = PauliWord({}) # identity rho_in = rho_in.pauli_rep @@ -301,12 +301,12 @@ def exppw(theta, ps): ############################################################################## # As a sanity check, let us compare this to the same circuit but using our default state vector simulator in PennyLane. -@qml.qnode(qml.device("default.qubit")) +@qp.qnode(qp.device("default.qubit")) def true(): - qml.exp(-1j * theta * dla[-1].operation()) - qml.exp(-1j * 0.5 * p.operation()) - qml.exp(-1j * 0.5 * dla[-2].operation()) - return [qml.expval(op.operation()) for op in dla] + qp.exp(-1j * theta * dla[-1].operation()) + qp.exp(-1j * 0.5 * p.operation()) + qp.exp(-1j * 0.5 * dla[-2].operation()) + return [qp.expval(op.operation()) for op in dla] true_res = np.array(true()) @@ -362,7 +362,7 @@ def true(): # We now set up the moment vector spaces starting from the DLA and keep adding linearly independent product operators. def Moment_step(ops, dla): - MomentX = qml.pauli.PauliVSpace(ops.copy()) + MomentX = qp.pauli.PauliVSpace(ops.copy()) for i, op1 in enumerate(dla): for op2 in ops[i+1:]: prod = op1 @ op2 @@ -399,7 +399,7 @@ def Moment_step(ops, dla): e_in = np.zeros((dim[comp_moment]), dtype=float) for i, hi in enumerate(Moment[comp_moment]): - rho_in = qml.prod(*(I(i) + Z(i) for i in hi.wires)) + rho_in = qp.prod(*(I(i) + Z(i) for i in hi.wires)) rho_in = rho_in.pauli_rep e_in[i] = (hi @ rho_in).trace() @@ -408,7 +408,7 @@ def Moment_step(ops, dla): # # Next, we compute the (pseudo-)adjoint representation of :math:`\mathcal{M}^1.` -adjoint_repr = qml.structure_constants(Moment[comp_moment]) +adjoint_repr = qp.structure_constants(Moment[comp_moment]) ############################################################################## # @@ -454,7 +454,7 @@ def Moment_step(ops, dla): Moment.append(Moment_step(Moment[-1], dla)) dim.append(len(Moment[-1])) - tempdla = qml.lie_closure(dla + [Moment[1][-1]], pauli=True) + tempdla = qp.lie_closure(dla + [Moment[1][-1]], pauli=True) dims_dla.append(dim_g) dims_moment.append(dim) diff --git a/demonstrations_v2/tutorial_liesim_extension/metadata.json b/demonstrations_v2/tutorial_liesim_extension/metadata.json index f20d933038..ce84d69bc5 100644 --- a/demonstrations_v2/tutorial_liesim_extension/metadata.json +++ b/demonstrations_v2/tutorial_liesim_extension/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-06-18T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Computing", "Quantum Machine Learning" diff --git a/demonstrations_v2/tutorial_local_cost_functions/demo.py b/demonstrations_v2/tutorial_local_cost_functions/demo.py index 96f1400645..ea6a56eef1 100644 --- a/demonstrations_v2/tutorial_local_cost_functions/demo.py +++ b/demonstrations_v2/tutorial_local_cost_functions/demo.py @@ -56,7 +56,7 @@ We first need to import the following modules. """ -import pennylane as qml +import pennylane as qp from pennylane import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import LinearLocator, FormatStrFormatter @@ -76,7 +76,7 @@ # how many qubits we train on will effect our results. wires = 6 -dev = qml.device("lightning.qubit", wires=wires) +dev = qp.device("lightning.qubit", wires=wires) ###################################################################### @@ -111,19 +111,19 @@ def global_cost_simple(rotations): for i in range(wires): - qml.RX(rotations[0][i], wires=i) - qml.RY(rotations[1][i], wires=i) - return qml.probs(wires=range(wires)) + qp.RX(rotations[0][i], wires=i) + qp.RY(rotations[1][i], wires=i) + return qp.probs(wires=range(wires)) def local_cost_simple(rotations): for i in range(wires): - qml.RX(rotations[0][i], wires=i) - qml.RY(rotations[1][i], wires=i) - return [qml.probs(wires=i) for i in range(wires)] + qp.RX(rotations[0][i], wires=i) + qp.RY(rotations[1][i], wires=i) + return [qp.probs(wires=i) for i in range(wires)] -global_circuit = qml.set_shots(qml.QNode(global_cost_simple, dev, interface="autograd"), shots = 10000) +global_circuit = qp.set_shots(qp.QNode(global_cost_simple, dev, interface="autograd"), shots = 10000) -local_circuit = qml.set_shots(qml.QNode(local_cost_simple, dev, interface="autograd"), shots = 10000) +local_circuit = qp.set_shots(qp.QNode(local_cost_simple, dev, interface="autograd"), shots = 10000) def cost_local(rotations): return 1 - np.sum([i for (i, _) in local_circuit(rotations)]) / wires @@ -150,12 +150,12 @@ def cost_global(rotations): print("Global Cost: {: .7f}".format(cost_global(rotations))) print("Local Cost: {: .7f}".format(cost_local(rotations))) -qml.drawer.use_style('black_white') -fig1, ax1 = qml.draw_mpl(global_circuit, decimals=2)(rotations) +qp.drawer.use_style('black_white') +fig1, ax1 = qp.draw_mpl(global_circuit, decimals=2)(rotations) fig1.suptitle("Global Cost", fontsize='xx-large') plt.show() -fig2, ax2 = qml.draw_mpl(local_circuit, decimals=2)(rotations) +fig2, ax2 = qp.draw_mpl(local_circuit, decimals=2)(rotations) fig2.suptitle("Local Cost", fontsize='xx-large') plt.show() @@ -237,23 +237,23 @@ def plot_surface(surface): def global_cost_simple(rotations): for i in range(wires): - qml.RX(rotations[0][i], wires=i) - qml.RY(rotations[1][i], wires=i) + qp.RX(rotations[0][i], wires=i) + qp.RY(rotations[1][i], wires=i) for i in range(wires - 1): - qml.CNOT([i, i + 1]) - return qml.probs(wires=range(wires)) + qp.CNOT([i, i + 1]) + return qp.probs(wires=range(wires)) def local_cost_simple(rotations): for i in range(wires): - qml.RX(rotations[0][i], wires=i) - qml.RY(rotations[1][i], wires=i) + qp.RX(rotations[0][i], wires=i) + qp.RY(rotations[1][i], wires=i) for i in range(wires - 1): - qml.CNOT([i, i + 1]) - return qml.probs(wires=[0]) + qp.CNOT([i, i + 1]) + return qp.probs(wires=[0]) -global_circuit = qml.set_shots(qml.QNode(global_cost_simple, dev, interface="autograd"), shots = 10000) +global_circuit = qp.set_shots(qp.QNode(global_cost_simple, dev, interface="autograd"), shots = 10000) -local_circuit = qml.set_shots(qml.QNode(local_cost_simple, dev, interface="autograd"), shots = 10000) +local_circuit = qp.set_shots(qp.QNode(local_cost_simple, dev, interface="autograd"), shots = 10000) def cost_local(rotations): return 1 - local_circuit(rotations)[0] @@ -285,7 +285,7 @@ def cost_global(rotations): rotations = np.array([[3.] * len(range(wires)), [0.] * len(range(wires))], requires_grad=True) -opt = qml.GradientDescentOptimizer(stepsize=0.2) +opt = qp.GradientDescentOptimizer(stepsize=0.2) steps = 100 params_global = rotations for i in range(steps): @@ -296,7 +296,7 @@ def cost_global(rotations): print("Cost after step {:5d}: {: .7f}".format(i + 1, cost_global(params_global))) if cost_global(params_global) < 0.1: break -fig, ax = qml.draw_mpl(global_circuit, decimals=2)(params_global) +fig, ax = qp.draw_mpl(global_circuit, decimals=2)(params_global) plt.show() @@ -307,7 +307,7 @@ def cost_global(rotations): # rotations = np.array([[3. for i in range(wires)], [0. for i in range(wires)]], requires_grad=True) -opt = qml.GradientDescentOptimizer(stepsize=0.2) +opt = qp.GradientDescentOptimizer(stepsize=0.2) steps = 100 params_local = rotations for i in range(steps): @@ -319,7 +319,7 @@ def cost_global(rotations): if cost_local(params_local) < 0.05: break -fig, ax = qml.draw_mpl(local_circuit, decimals=2)(params_local) +fig, ax = qp.draw_mpl(local_circuit, decimals=2)(params_local) plt.show() @@ -343,8 +343,8 @@ def cost_global(rotations): # us the exact representation. # -_dev = qml.device("lightning.qubit", wires=wires) -global_circuit = qml.QNode(global_cost_simple, _dev, interface="autograd") +_dev = qp.device("lightning.qubit", wires=wires) +global_circuit = qp.QNode(global_cost_simple, _dev, interface="autograd") print( "Current cost: " + str(cost_global(params_local)) @@ -369,24 +369,24 @@ def cost_global(rotations): def tunable_cost_simple(rotations): for i in range(wires): - qml.RX(rotations[0][i], wires=i) - qml.RY(rotations[1][i], wires=i) + qp.RX(rotations[0][i], wires=i) + qp.RY(rotations[1][i], wires=i) for i in range(wires - 1): - qml.CNOT([i, i + 1]) - return qml.probs(range(locality)) + qp.CNOT([i, i + 1]) + return qp.probs(range(locality)) def cost_tunable(rotations): return 1 - tunable_circuit(rotations)[0] -tunable_circuit = qml.set_shots(qml.QNode(tunable_cost_simple, dev, interface="autograd"), shots = 10000) +tunable_circuit = qp.set_shots(qp.QNode(tunable_cost_simple, dev, interface="autograd"), shots = 10000) locality = 2 params_tunable = params_local -fig, ax = qml.draw_mpl(tunable_circuit, decimals=2)(params_tunable) +fig, ax = qp.draw_mpl(tunable_circuit, decimals=2)(params_tunable) plt.show() print(cost_tunable(params_tunable)) locality = 2 -opt = qml.GradientDescentOptimizer(stepsize=0.1) +opt = qp.GradientDescentOptimizer(stepsize=0.1) steps = 600 for i in range(steps): # update the circuit parameters @@ -406,7 +406,7 @@ def cost_tunable(rotations): continue elif runCost < 0.1 and locality >= wires: break -fig, ax = qml.draw_mpl(tunable_circuit, decimals=2)(params_tunable) +fig, ax = qp.draw_mpl(tunable_circuit, decimals=2)(params_tunable) plt.show() @@ -436,12 +436,12 @@ def cost_tunable(rotations): samples = 10 plateau = 0 trained = 0 -opt = qml.GradientDescentOptimizer(stepsize=0.2) +opt = qp.GradientDescentOptimizer(stepsize=0.2) steps = 400 wires = 8 -dev = qml.device("lightning.qubit", wires=wires) -global_circuit = qml.set_shots(qml.QNode(global_cost_simple, dev, interface="autograd"), shots = 10000) +dev = qp.device("lightning.qubit", wires=wires) +global_circuit = qp.set_shots(qp.QNode(global_cost_simple, dev, interface="autograd"), shots = 10000) for runs in range(samples): print("--- New run! ---") @@ -469,12 +469,12 @@ def cost_tunable(rotations): samples = 10 plateau = 0 trained = 0 -opt = qml.GradientDescentOptimizer(stepsize=0.2) +opt = qp.GradientDescentOptimizer(stepsize=0.2) steps = 400 wires = 8 -dev = qml.device("lightning.qubit", wires=wires) -tunable_circuit = qml.set_shots(qml.QNode(tunable_cost_simple, dev, interface="autograd"), shots = 10000) +dev = qp.device("lightning.qubit", wires=wires) +tunable_circuit = qp.set_shots(qp.QNode(tunable_cost_simple, dev, interface="autograd"), shots = 10000) for runs in range(samples): locality = 1 diff --git a/demonstrations_v2/tutorial_local_cost_functions/metadata.json b/demonstrations_v2/tutorial_local_cost_functions/metadata.json index ad7db05171..858306c14b 100644 --- a/demonstrations_v2/tutorial_local_cost_functions/metadata.json +++ b/demonstrations_v2/tutorial_local_cost_functions/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2020-09-09T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_loom_catalyst/demo.py b/demonstrations_v2/tutorial_loom_catalyst/demo.py index af1a96fbc2..cd5e8bbce3 100644 --- a/demonstrations_v2/tutorial_loom_catalyst/demo.py +++ b/demonstrations_v2/tutorial_loom_catalyst/demo.py @@ -187,7 +187,7 @@ from catalyst import qjit, cond, measure, debug from jax import random, numpy as jnp -import pennylane as qml +import pennylane as qp distance = 3 @@ -201,7 +201,7 @@ # the Pennylane backend. # -dev = qml.device("qrack.simulator", wires=n_qubits) +dev = qp.device("qrack.simulator", wires=n_qubits) ###################################################################### # Then, we proceed to generate the circuit. Note that we start by introducing an error by hand, and @@ -209,7 +209,7 @@ # @qjit() -@qml.qnode(dev) +@qp.qnode(dev) def circuit(seed : int): # Based on the seed, apply an X gate to a random data qubit @@ -220,14 +220,14 @@ def circuit(seed : int): @cond(random_qubit != -1) def apply_noise(): debug.print("Applying noise to qubit: {}", random_qubit) - qml.X(random_qubit) + qp.X(random_qubit) apply_noise() # Syndrome extraction routine: entangle data and auxiliary, and measure auxiliary for i in range(distance-1): - qml.CNOT(wires=[data_qubits[i], aux_qubits[i]]) - qml.CNOT(wires=[data_qubits[i+1], aux_qubits[i]]) + qp.CNOT(wires=[data_qubits[i], aux_qubits[i]]) + qp.CNOT(wires=[data_qubits[i+1], aux_qubits[i]]) syndrome = [measure(aux_qubit) for aux_qubit in aux_qubits] @@ -235,15 +235,15 @@ def apply_noise(): @cond(jnp.logical_and(syndrome[0] == 0, syndrome[1] == 1)) def fix_data_qubits(): debug.print("Applying correction on data qubit 2") - qml.X(data_qubits[2]) + qp.X(data_qubits[2]) @fix_data_qubits.else_if( jnp.logical_and(syndrome[0] == 1, syndrome[1] == 0)) def fix_data_qubits(): debug.print("Applying correction on data qubit 0") - qml.X(data_qubits[0]) + qp.X(data_qubits[0]) @fix_data_qubits.else_if(jnp.logical_and(syndrome[0] == 1, syndrome[1] == 1)) def fix_data_qubits(): debug.print("Applying correction on data qubit 1") - qml.X(data_qubits[1]) + qp.X(data_qubits[1]) # Apply the the fix fix_data_qubits() @@ -348,7 +348,7 @@ def fix_data_qubits(): # # Define device -dev = qml.device( +dev = qp.device( "qrack.simulator", wires=len(reg_rc), shots=1, @@ -376,7 +376,7 @@ def fix_data_qubits(): # @qjit() -@qml.qnode(dev) +@qp.qnode(dev) def repetition_code_circuit(): ## Run the circuit @@ -462,11 +462,11 @@ def repetition_code_circuit(): # Indeed, the probability of getting a logical error without decoding is much higher. Interestingly # enough, though, even with the QEC scheme, the probability of error did not go to zero! Wonder why? # -# When we defined the ``qml.device``, we set the noise level at at 0.05: +# When we defined the ``qp.device``, we set the noise level at at 0.05: # # Define device -dev = qml.device( +dev = qp.device( "qrack.simulator", wires=len(reg_rc), shots=1, diff --git a/demonstrations_v2/tutorial_loom_catalyst/metadata.json b/demonstrations_v2/tutorial_loom_catalyst/metadata.json index 2a41af3d3c..f567cfc4cc 100644 --- a/demonstrations_v2/tutorial_loom_catalyst/metadata.json +++ b/demonstrations_v2/tutorial_loom_catalyst/metadata.json @@ -11,7 +11,7 @@ "executable_stable": false, "executable_latest": false, "dateOfPublication": "2025-08-29T14:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Computing", "Quantum Hardware" diff --git a/demonstrations_v2/tutorial_magic_state_distillation/demo.py b/demonstrations_v2/tutorial_magic_state_distillation/demo.py index 0138e99d8c..bb48736361 100644 --- a/demonstrations_v2/tutorial_magic_state_distillation/demo.py +++ b/demonstrations_v2/tutorial_magic_state_distillation/demo.py @@ -61,7 +61,7 @@ and a phase shift: """ -import pennylane as qml +import pennylane as qp import jax; jax.config.update('jax_platform_name', 'cpu') from jax import numpy as jnp @@ -70,8 +70,8 @@ b = 0.5 * jnp.arccos(1 / jnp.sqrt(3)) def generate_T0(wire): - qml.RY(2 * b, wires=wire) - qml.PhaseShift(jnp.pi / 4, wires=wire) + qp.RY(2 * b, wires=wire) + qp.PhaseShift(jnp.pi / 4, wires=wire) ###################################################################### # Now, let’s create up a *faulty* :math:`| T_0\rangle` state-generating function. We can do this by @@ -84,11 +84,11 @@ def generate_T0(wire): def faulty_generate_T0(wire, key, r): key, subkey = random.split(key) disturbance = random.uniform(subkey, minval=-r, maxval=r) - qml.RY(2 * (b + disturbance), wires=wire) + qp.RY(2 * (b + disturbance), wires=wire) key, subkey = random.split(key) disturbance = random.uniform(subkey, minval=-r, maxval=r) - qml.PhaseShift(jnp.pi / 4 + disturbance, wires=wire) + qp.PhaseShift(jnp.pi / 4 + disturbance, wires=wire) return key ###################################################################### @@ -128,30 +128,30 @@ def error_correction_decoder(wires): """ w0, w1, w2, w3, w4 = wires - qml.CNOT(wires=[w1, w0]) - qml.CZ(wires=[w1, w0]) - qml.CZ(wires=[w1, w2]) - qml.CZ(wires=[w1, w4]) + qp.CNOT(wires=[w1, w0]) + qp.CZ(wires=[w1, w0]) + qp.CZ(wires=[w1, w2]) + qp.CZ(wires=[w1, w4]) - qml.CNOT(wires=[w2, w0]) - qml.CZ(wires=[w2, w3]) - qml.CZ(wires=[w2, w4]) + qp.CNOT(wires=[w2, w0]) + qp.CZ(wires=[w2, w3]) + qp.CZ(wires=[w2, w4]) - qml.CNOT(wires=[w3, w0]) + qp.CNOT(wires=[w3, w0]) - qml.CNOT(wires=[w4, w0]) - qml.CZ(wires=[w4, w0]) + qp.CNOT(wires=[w4, w0]) + qp.CZ(wires=[w4, w0]) - qml.PauliZ(wires=w0) - qml.PauliZ(wires=w1) - qml.PauliZ(wires=w4) + qp.PauliZ(wires=w0) + qp.PauliZ(wires=w1) + qp.PauliZ(wires=w4) - qml.Hadamard(wires=w1) - qml.Hadamard(wires=w2) - qml.Hadamard(wires=w3) - qml.Hadamard(wires=w4) + qp.Hadamard(wires=w1) + qp.Hadamard(wires=w2) + qp.Hadamard(wires=w3) + qp.Hadamard(wires=w4) -print(qml.draw(error_correction_decoder)(range(5))) +print(qp.draw(error_correction_decoder)(range(5))) ###################################################################### # We’ll also define some helper functions to perform a conditional reset of a qubit into the @@ -168,7 +168,7 @@ def measure_and_reset(wire): m = measure(wire) if m: - qml.PauliX(wires=wire) + qp.PauliX(wires=wire) return m @@ -191,10 +191,10 @@ def measure_and_reset(wire): # operations. # -dev = qml.device("lightning.qubit", wires=5) +dev = qp.device("lightning.qubit", wires=5) -@qml.qjit(autograph=True) -@qml.qnode(dev) +@qp.qjit(autograph=True) +@qp.qnode(dev) def state_distillation(random_key, r): key = random_key syndrome = True @@ -228,10 +228,10 @@ def state_distillation(random_key, r): # We can convert the T1 state back to T0 # by applying a Hadamard and Pauli-Y rotation - qml.Hadamard(wires=0) - qml.PauliY(wires=0) + qp.Hadamard(wires=0) + qp.PauliY(wires=0) - return qml.state() + return qp.state() ###################################################################### # Benchmark @@ -246,19 +246,19 @@ def state_distillation(random_key, r): import matplotlib.pyplot as plt import os -dev_5_qubits = qml.device("default.qubit", wires=5) +dev_5_qubits = qp.device("default.qubit", wires=5) @jax.jit -@qml.qnode(dev_5_qubits, interface="jax") +@qp.qnode(dev_5_qubits, interface="jax") def T0_state(): generate_T0(0) - return qml.state() + return qp.state() @jax.jit -@qml.qnode(dev_5_qubits, interface="jax") +@qp.qnode(dev_5_qubits, interface="jax") def faulty_T0_state(random_key, r): faulty_generate_T0(0, random_key, r) - return qml.state() + return qp.state() exact_T0_state = T0_state() perturbations = jnp.linspace(0, 1, 20) diff --git a/demonstrations_v2/tutorial_magic_state_distillation/metadata.json b/demonstrations_v2/tutorial_magic_state_distillation/metadata.json index 28ec7547df..d85ead16fd 100644 --- a/demonstrations_v2/tutorial_magic_state_distillation/metadata.json +++ b/demonstrations_v2/tutorial_magic_state_distillation/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-04-26T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Algorithms", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_magic_states/demo.py b/demonstrations_v2/tutorial_magic_states/demo.py index 53af85b59e..a11a89f9d3 100644 --- a/demonstrations_v2/tutorial_magic_states/demo.py +++ b/demonstrations_v2/tutorial_magic_states/demo.py @@ -47,36 +47,36 @@ """ -import pennylane as qml +import pennylane as qp from pennylane import numpy as np def prepare_magic_state(): """Prepares the |H> magic state on wire 1.""" - qml.Hadamard(wires=1) - qml.T(wires=1) + qp.Hadamard(wires=1) + qp.T(wires=1) -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") -@qml.qnode(dev) +@qp.qnode(dev) def magic_state_injection_circuit(target_state_params): # Prepare the initial target state (e.g., Ry rotation) - qml.RY(target_state_params, wires=0) + qp.RY(target_state_params, wires=0) # Prepare the Magic State on Qubit 1 prepare_magic_state() # Apply the Clifford operations for injection - qml.CNOT(wires=[0, 1]) + qp.CNOT(wires=[0, 1]) # The outcome of m_1 dictates the final correction - m_1 = qml.measure(1) - qml.cond(m_1 == 1, qml.S)(wires=0) + m_1 = qp.measure(1) + qp.cond(m_1 == 1, qp.S)(wires=0) - return qml.density_matrix(wires=[0]) + return qp.density_matrix(wires=[0]) print(magic_state_injection_circuit(np.pi / 3)) diff --git a/demonstrations_v2/tutorial_magic_states/metadata.json b/demonstrations_v2/tutorial_magic_states/metadata.json index 5009bb2fd9..d1dcddc80b 100644 --- a/demonstrations_v2/tutorial_magic_states/metadata.json +++ b/demonstrations_v2/tutorial_magic_states/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2026-01-23T10:00:00+00:00", - "dateOfLastModification": "2026-01-23T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Computing" ], diff --git a/demonstrations_v2/tutorial_mapping/demo.py b/demonstrations_v2/tutorial_mapping/demo.py index 7e7795f331..cf642d3bae 100644 --- a/demonstrations_v2/tutorial_mapping/demo.py +++ b/demonstrations_v2/tutorial_mapping/demo.py @@ -84,7 +84,7 @@ then map the operator using :func:`~.pennylane.fermi.jordan_wigner`. """ -import pennylane as qml +import pennylane as qp from pennylane.fermi import from_string, jordan_wigner qubits = 10 @@ -109,8 +109,8 @@ orbitals = 10 electrons = 5 -state_number = qml.qchem.hf_state(electrons, orbitals) -state_parity = qml.qchem.hf_state(electrons, orbitals, basis="parity") +state_number = qp.qchem.hf_state(electrons, orbitals) +state_parity = qp.qchem.hf_state(electrons, orbitals, basis="parity") print("State in occupation number basis:\n", state_number) print("State in parity basis:\n", state_parity) @@ -143,7 +143,7 @@ # Parity mapping using :func:`~.pennylane.fermi.parity_transform` in PennyLane. qubits = 10 -pauli_pr = qml.parity_transform(fermi_op, qubits, ps=True) +pauli_pr = qp.parity_transform(fermi_op, qubits, ps=True) pauli_pr ############################################################################## @@ -155,11 +155,11 @@ # `qubit tapering `__ demo. # Let's look at an example. -generators = [qml.prod(*[qml.Z(i) for i in range(qubits-1)]), qml.Z(qubits-1)] -paulixops = qml.paulix_ops(generators, qubits) +generators = [qp.prod(*[qp.Z(i) for i in range(qubits-1)]), qp.Z(qubits-1)] +paulixops = qp.paulix_ops(generators, qubits) paulix_sector = [1, 1] -taper_op = qml.taper(pauli_pr, generators, paulixops, paulix_sector) -qml.simplify(taper_op) +taper_op = qp.taper(pauli_pr, generators, paulixops, paulix_sector) +qp.simplify(taper_op) ############################################################################### # Note that the tapered operator doesn't include qubit :math:`8` and :math:`9.` @@ -175,7 +175,7 @@ # Let's use the :func:`~.pennylane.fermi.bravyi_kitaev` function to map our :math:`a_{5}^{\dagger}` # operator. -pauli_bk = qml.bravyi_kitaev(fermi_op, qubits, ps=True) +pauli_bk = qp.bravyi_kitaev(fermi_op, qubits, ps=True) pauli_bk ############################################################################## @@ -225,7 +225,7 @@ electrons = 2 qubits = len(h_fermi.wires) -h_pauli = qml.bravyi_kitaev(h_fermi, qubits, tol=1e-16) +h_pauli = qp.bravyi_kitaev(h_fermi, qubits, tol=1e-16) ############################################################################## # Initial state @@ -282,11 +282,11 @@ singles_pauli = [] for op in singles_fermi: - singles_pauli.append(qml.bravyi_kitaev(op, qubits, ps=True)) + singles_pauli.append(qp.bravyi_kitaev(op, qubits, ps=True)) doubles_pauli = [] for op in doubles_fermi: - doubles_pauli.append(qml.bravyi_kitaev(op, qubits, ps=True)) + doubles_pauli.append(qp.bravyi_kitaev(op, qubits, ps=True)) ############################################################################## # Note that we need to exponentiate these operators to be able to use them in the circuit @@ -294,19 +294,19 @@ params = jnp.array([0.22347661, 0.0, 0.0]) -dev = qml.device("default.qubit", wires=qubits) +dev = qp.device("default.qubit", wires=qubits) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(params): - qml.BasisState(hf_state, wires=range(qubits)) + qp.BasisState(hf_state, wires=range(qubits)) for i, excitation in enumerate(doubles_pauli): - qml.exp((excitation * params[i] / 2).operation()), range(qubits) + qp.exp((excitation * params[i] / 2).operation()), range(qubits) for j, excitation in enumerate(singles_pauli): - qml.exp((excitation * params[i + j + 1] / 2).operation()), range(qubits) + qp.exp((excitation * params[i + j + 1] / 2).operation()), range(qubits) - return qml.expval(h_pauli) + return qp.expval(h_pauli) print('Energy =', circuit(params)) diff --git a/demonstrations_v2/tutorial_mapping/metadata.json b/demonstrations_v2/tutorial_mapping/metadata.json index fbb0c1de4d..d6a1428ef3 100644 --- a/demonstrations_v2/tutorial_mapping/metadata.json +++ b/demonstrations_v2/tutorial_mapping/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-05-06T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Algorithms", "Quantum Computing", diff --git a/demonstrations_v2/tutorial_mbqc/demo.py b/demonstrations_v2/tutorial_mbqc/demo.py index 06c3e71d2c..0a5aaba3e1 100644 --- a/demonstrations_v2/tutorial_mbqc/demo.py +++ b/demonstrations_v2/tutorial_mbqc/demo.py @@ -89,25 +89,25 @@ # and define a circuit to prepare the cluster state. # -import pennylane as qml +import pennylane as qp qubits = [str(node) for node in G.nodes] -dev = qml.device("lightning.qubit", wires=qubits) +dev = qp.device("lightning.qubit", wires=qubits) -@qml.qnode(dev, interface="autograd") +@qp.qnode(dev, interface="autograd") def cluster_state(): for node in qubits: - qml.Hadamard(wires=[node]) + qp.Hadamard(wires=[node]) for edge in G.edges: i, j = edge - qml.CZ(wires=[str(i), str(j)]) + qp.CZ(wires=[str(i), str(j)]) - return qml.state() + return qp.state() -print(qml.draw(cluster_state)()) +print(qp.draw(cluster_state)()) ############################################################################## # @@ -151,30 +151,30 @@ def cluster_state(): # # Let's implement one-qubit teleportation in PennyLane. -import pennylane as qml +import pennylane as qp import pennylane.numpy as np -dev = qml.device("lightning.qubit", wires=2) +dev = qp.device("lightning.qubit", wires=2) -@qml.qnode(dev, interface="autograd") +@qp.qnode(dev, interface="autograd") def one_bit_teleportation(input_state): # Prepare the input state - qml.StatePrep(input_state, wires=0) + qp.StatePrep(input_state, wires=0) # Prepare the cluster state - qml.Hadamard(wires=1) - qml.CZ(wires=[0, 1]) + qp.Hadamard(wires=1) + qp.CZ(wires=[0, 1]) # Measure the first qubit in the Pauli-X basis # and apply an X-gate conditioned on the outcome - qml.Hadamard(wires=0) - m = qml.measure(wires=[0]) - qml.cond(m == 1, qml.PauliX)(wires=1) - qml.Hadamard(wires=1) + qp.Hadamard(wires=0) + m = qp.measure(wires=[0]) + qp.cond(m == 1, qp.PauliX)(wires=1) + qp.Hadamard(wires=1) # Return the density matrix of the output state - return qml.density_matrix(wires=[1]) + return qp.density_matrix(wires=[1]) ############################################################################## @@ -297,19 +297,19 @@ def generate_random_state(n=1): # To start off, we define the :math:`R_z(\theta)` gate using two qubits with the gate-based approach # so we can later compare our MBQC approach to it. -dev = qml.device("lightning.qubit", wires=1) +dev = qp.device("lightning.qubit", wires=1) -@qml.qnode(dev, interface="autograd") +@qp.qnode(dev, interface="autograd") def RZ(theta, input_state): # Prepare the input state - qml.StatePrep(input_state, wires=0) + qp.StatePrep(input_state, wires=0) # Perform the Rz rotation - qml.RZ(theta, wires=0) + qp.RZ(theta, wires=0) # Return the density matrix of the output state - return qml.density_matrix(wires=[0]) + return qp.density_matrix(wires=[0]) ############################################################################## @@ -318,28 +318,28 @@ def RZ(theta, input_state): # in the MBQC formalism. # -mbqc_dev = qml.device("lightning.qubit", wires=2) +mbqc_dev = qp.device("lightning.qubit", wires=2) -@qml.qnode(mbqc_dev, interface="autograd") +@qp.qnode(mbqc_dev, interface="autograd") def RZ_MBQC(theta, input_state): # Prepare the input state - qml.StatePrep(input_state, wires=0) + qp.StatePrep(input_state, wires=0) # Prepare the cluster state - qml.Hadamard(wires=1) - qml.CZ(wires=[0, 1]) + qp.Hadamard(wires=1) + qp.CZ(wires=[0, 1]) # Measure the first qubit and correct the state - qml.RZ(theta, wires=0) - qml.Hadamard(wires=0) - m = qml.measure(wires=[0]) + qp.RZ(theta, wires=0) + qp.Hadamard(wires=0) + m = qp.measure(wires=[0]) - qml.cond(m == 1, qml.PauliX)(wires=1) - qml.Hadamard(wires=1) + qp.cond(m == 1, qp.PauliX)(wires=1) + qp.Hadamard(wires=1) # Return the density matrix of the output state - return qml.density_matrix(wires=[1]) + return qp.density_matrix(wires=[1]) ############################################################################## @@ -359,49 +359,49 @@ def RZ_MBQC(theta, input_state): # For the :math:`R_x(\theta)` gate we take a similar approach. # -dev = qml.device("lightning.qubit", wires=1) +dev = qp.device("lightning.qubit", wires=1) -@qml.qnode(dev, interface="autograd") +@qp.qnode(dev, interface="autograd") def RX(theta, input_state): # Prepare the input state - qml.StatePrep(input_state, wires=0) + qp.StatePrep(input_state, wires=0) # Perform the Rz rotation - qml.RX(theta, wires=0) + qp.RX(theta, wires=0) # Return the density matrix of the output state - return qml.density_matrix(wires=[0]) + return qp.density_matrix(wires=[0]) -mbqc_dev = qml.device("lightning.qubit", wires=3) +mbqc_dev = qp.device("lightning.qubit", wires=3) -@qml.qnode(mbqc_dev, interface="autograd") +@qp.qnode(mbqc_dev, interface="autograd") def RX_MBQC(theta, input_state): # Prepare the input state - qml.StatePrep(input_state, wires=0) + qp.StatePrep(input_state, wires=0) # Prepare the cluster state - qml.Hadamard(wires=1) - qml.Hadamard(wires=2) - qml.CZ(wires=[0, 1]) - qml.CZ(wires=[1, 2]) + qp.Hadamard(wires=1) + qp.Hadamard(wires=2) + qp.CZ(wires=[0, 1]) + qp.CZ(wires=[1, 2]) # Measure the qubits and perform corrections - qml.Hadamard(wires=0) - m1 = qml.measure(wires=[0]) + qp.Hadamard(wires=0) + m1 = qp.measure(wires=[0]) - qml.RZ(theta, wires=1) - qml.cond(m1 == 1, qml.RX)(-2 * theta, wires=2) - qml.Hadamard(wires=1) - m2 = qml.measure(wires=[1]) + qp.RZ(theta, wires=1) + qp.cond(m1 == 1, qp.RX)(-2 * theta, wires=2) + qp.Hadamard(wires=1) + m2 = qp.measure(wires=[1]) - qml.cond(m2 == 1, qml.PauliX)(wires=2) - qml.cond(m1 == 1, qml.PauliZ)(wires=2) + qp.cond(m2 == 1, qp.PauliX)(wires=2) + qp.cond(m1 == 1, qp.PauliZ)(wires=2) # Return the density matrix of the output state - return qml.density_matrix(wires=[2]) + return qp.density_matrix(wires=[2]) ############################################################################## @@ -439,46 +439,46 @@ def RX_MBQC(theta, input_state): # # Let's see how one can do this in PennyLane. -dev = qml.device("lightning.qubit", wires=2) +dev = qp.device("lightning.qubit", wires=2) -@qml.qnode(dev, interface="autograd") +@qp.qnode(dev, interface="autograd") def CNOT(input_state): # Prepare the input state - qml.StatePrep(input_state, wires=[0, 1]) - qml.CNOT(wires=[0, 1]) + qp.StatePrep(input_state, wires=[0, 1]) + qp.CNOT(wires=[0, 1]) - return qml.density_matrix(wires=[0, 1]) + return qp.density_matrix(wires=[0, 1]) -mbqc_dev = qml.device("lightning.qubit", wires=4) +mbqc_dev = qp.device("lightning.qubit", wires=4) -@qml.qnode(mbqc_dev, interface="autograd") +@qp.qnode(mbqc_dev, interface="autograd") def CNOT_MBQC(input_state): # Prepare the input state - qml.StatePrep(input_state, wires=[0, 1]) + qp.StatePrep(input_state, wires=[0, 1]) # Prepare the cluster state - qml.Hadamard(wires=2) - qml.Hadamard(wires=3) - qml.CZ(wires=[2, 0]) - qml.CZ(wires=[2, 1]) - qml.CZ(wires=[2, 3]) + qp.Hadamard(wires=2) + qp.Hadamard(wires=3) + qp.CZ(wires=[2, 0]) + qp.CZ(wires=[2, 1]) + qp.CZ(wires=[2, 3]) # Measure the qubits in the appropriate bases - qml.Hadamard(wires=1) - m1 = qml.measure(wires=[1]) - qml.Hadamard(wires=2) - m2 = qml.measure(wires=[2]) + qp.Hadamard(wires=1) + m1 = qp.measure(wires=[1]) + qp.Hadamard(wires=2) + m2 = qp.measure(wires=[2]) # Correct the state - qml.cond(m1 == 1, qml.PauliZ)(wires=0) - qml.cond(m2 == 1, qml.PauliX)(wires=3) - qml.cond(m1 == 1, qml.PauliZ)(wires=3) + qp.cond(m1 == 1, qp.PauliZ)(wires=0) + qp.cond(m2 == 1, qp.PauliX)(wires=3) + qp.cond(m1 == 1, qp.PauliZ)(wires=3) # Return the density matrix of the output state - return qml.density_matrix(wires=[0, 3]) + return qp.density_matrix(wires=[0, 3]) ############################################################################## diff --git a/demonstrations_v2/tutorial_mbqc/metadata.json b/demonstrations_v2/tutorial_mbqc/metadata.json index ff3cfdb5b3..f0d2fdc653 100644 --- a/demonstrations_v2/tutorial_mbqc/metadata.json +++ b/demonstrations_v2/tutorial_mbqc/metadata.json @@ -11,7 +11,7 @@ "executable_stable": false, "executable_latest": false, "dateOfPublication": "2022-12-05T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Hardware", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_mcm_introduction/demo.py b/demonstrations_v2/tutorial_mcm_introduction/demo.py index 2728396fd7..39cd544803 100644 --- a/demonstrations_v2/tutorial_mcm_introduction/demo.py +++ b/demonstrations_v2/tutorial_mcm_introduction/demo.py @@ -122,14 +122,14 @@ # them in detail. # -import pennylane as qml +import pennylane as qp -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") -@qml.qnode(dev) +@qp.qnode(dev) def before(): - qml.Hadamard(0) # Create |+> state - return qml.expval(qml.X(0)), qml.expval(qml.Z(0)) + qp.Hadamard(0) # Create |+> state + return qp.expval(qp.X(0)), qp.expval(qp.Z(0)) b = before() print(f"Expectation values before any measurement: {b[0]:.1f}, {b[1]:.1f}") @@ -164,11 +164,11 @@ def before(): # variable to its outcome. # -@qml.qnode(dev) +@qp.qnode(dev) def after(): - qml.Hadamard(0) # Create |+> state - qml.measure(0) # Measure without recording the outcome - return qml.expval(qml.X(0)), qml.expval(qml.Z(0)) + qp.Hadamard(0) # Create |+> state + qp.measure(0) # Measure without recording the outcome + return qp.expval(qp.X(0)), qp.expval(qp.Z(0)) a = after() print(f"Expectation value after the measurement: {a[0]:.1f}, {a[1]:.1f}") @@ -188,14 +188,14 @@ def after(): # # that is, the qubit is in a new, pure state. In PennyLane, we can postselect on the case # where we measured a :math:`0` using the ``postselect`` keyword argument of -# ``qml.measure``: +# ``qp.measure``: # -@qml.qnode(dev) +@qp.qnode(dev) def after(): - qml.Hadamard(0) # Create |+> state - qml.measure(0, postselect=0) # Measure and only accept 0 as outcome - return qml.expval(qml.X(0)), qml.expval(qml.Z(0)) + qp.Hadamard(0) # Create |+> state + qp.measure(0, postselect=0) # Measure and only accept 0 as outcome + return qp.expval(qp.X(0)), qp.expval(qp.Z(0)) a = after() print(f"Expectation value after the postselected measurement: {a[0]:.1f}, {a[1]:.1f}") @@ -224,14 +224,14 @@ def after(): # We code this circuit up similar to the one above, using an additional ``CNOT`` gate # to create the Bell state. We also include optional hyperparameters such as # ``postselect`` as keyword arguments to our quantum function and pass them on to -# ``qml.measure``. Note that we can't complete the quantum function yet, because we still +# ``qp.measure``. Note that we can't complete the quantum function yet, because we still # need to discuss what to return from it! # def bell_pair_preparation(**kwargs): - qml.Hadamard(0) - qml.CNOT([0, 1]) # Create a Bell pair - qml.measure(0, **kwargs) # Measure first qubit, using keyword arguments + qp.Hadamard(0) + qp.CNOT([0, 1]) # Create a Bell pair + qp.measure(0, **kwargs) # Measure first qubit, using keyword arguments ###################################################################### # Without recording the outcome, i.e., ``postselect=None``, we obtain the state @@ -251,10 +251,10 @@ def bell_pair_preparation(**kwargs): # And those will be the return types to complete our quantum function: # -@qml.qnode(dev) +@qp.qnode(dev) def bell_pair(postselect): bell_pair_preparation(postselect=postselect) - return qml.purity([0, 1]), qml.vn_entropy(0) + return qp.purity([0, 1]), qp.vn_entropy(0) ###################################################################### # So let's compare the purities and von Neumann entropies of the Bell state @@ -297,10 +297,10 @@ def bell_pair(postselect): # can simply pass the keyword argument ``reset`` to activate the qubit reset: # -@qml.qnode(dev) +@qp.qnode(dev) def bell_pair_with_reset(reset): bell_pair_preparation(reset=reset) - return qml.expval(qml.Z(0)), qml.expval(qml.Z(1)), qml.expval(qml.Z(0) @ qml.Z(1)) + return qp.expval(qp.Z(0)), qp.expval(qp.Z(1)), qp.expval(qp.Z(0) @ qp.Z(1)) no_reset = bell_pair_with_reset(reset=False) reset = bell_pair_with_reset(reset=True) @@ -360,10 +360,10 @@ def bell_pair_with_reset(reset): magic_state = np.array([1, np.exp(1j * np.pi / 4)]) / np.sqrt(2) def t_gadget(wire, aux_wire): - qml.StatePrep(magic_state, aux_wire) - qml.CNOT([wire, aux_wire]) - mcm = qml.measure(aux_wire, reset=True) # Resetting disentangles aux qubit - qml.cond(mcm, qml.S)(wire) # Apply qml.S(wire) if mcm was 1 + qp.StatePrep(magic_state, aux_wire) + qp.CNOT([wire, aux_wire]) + mcm = qp.measure(aux_wire, reset=True) # Resetting disentangles aux qubit + qp.cond(mcm, qp.S)(wire) # Apply qp.S(wire) if mcm was 1 ###################################################################### # We will not derive why this works (see, e.g., [#zhou]_ instead), but @@ -380,16 +380,16 @@ def t_gadget(wire, aux_wire): # - return the expectation value :math:`\langle X_0\rangle.` # -@qml.qnode(dev) +@qp.qnode(dev) def test_t_gadget(init_state): - qml.Hadamard(0) # Create |+> state + qp.Hadamard(0) # Create |+> state if init_state == "-": - qml.Z(0) # Flip to |-> state + qp.Z(0) # Flip to |-> state t_gadget(0, 1) # Apply T-gadget - qml.adjoint(qml.T)(0) # Apply T^† to undo the gadget + qp.adjoint(qp.T)(0) # Apply T^† to undo the gadget - return qml.expval(qml.X(0)) + return qp.expval(qp.X(0)) print(f" with initial state |+>: {test_t_gadget('+'):4.1f}") print(f" with initial state |->: {test_t_gadget('-'):4.1f}") diff --git a/demonstrations_v2/tutorial_mcm_introduction/metadata.json b/demonstrations_v2/tutorial_mcm_introduction/metadata.json index 3baae949fe..8717812448 100644 --- a/demonstrations_v2/tutorial_mcm_introduction/metadata.json +++ b/demonstrations_v2/tutorial_mcm_introduction/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-05-10T00:00:00+00:00", - "dateOfLastModification": "2026-01-15T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Getting Started", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_measurement_optimize/demo.py b/demonstrations_v2/tutorial_measurement_optimize/demo.py index 83d218cc4f..a1ccf3bf71 100644 --- a/demonstrations_v2/tutorial_measurement_optimize/demo.py +++ b/demonstrations_v2/tutorial_measurement_optimize/demo.py @@ -110,11 +110,11 @@ import warnings import jax from jax import numpy as jnp -import pennylane as qml +import pennylane as qp jax.config.update("jax_enable_x64", True) -dataset = qml.data.load("qchem", molname="H2", bondlength=0.7)[0] +dataset = qp.data.load("qchem", molname="H2", bondlength=0.7)[0] H, num_qubits = dataset.hamiltonian, len(dataset.hamiltonian.wires) print("Required number of qubits:", num_qubits) @@ -125,27 +125,27 @@ # on hardware. Let's generate the cost function to check this. # Create a 4 qubit simulator -dev = qml.device("default.qubit", seed=904932) +dev = qp.device("default.qubit", seed=904932) # number of electrons electrons = 2 # Define the Hartree-Fock initial state for our variational circuit -initial_state = qml.qchem.hf_state(electrons, num_qubits) +initial_state = qp.qchem.hf_state(electrons, num_qubits) # Construct the UCCSD ansatz -singles, doubles = qml.qchem.excitations(electrons, num_qubits) -s_wires, d_wires = qml.qchem.excitations_to_wires(singles, doubles) +singles, doubles = qp.qchem.excitations(electrons, num_qubits) +s_wires, d_wires = qp.qchem.excitations_to_wires(singles, doubles) ansatz = functools.partial( - qml.UCCSD, init_state=initial_state, s_wires=s_wires, d_wires=d_wires + qp.UCCSD, init_state=initial_state, s_wires=s_wires, d_wires=d_wires ) # generate the cost function -@qml.set_shots(1000) -@qml.qnode(dev, interface="jax") +@qp.set_shots(1000) +@qp.qnode(dev, interface="jax") def cost_circuit(params): ansatz(params, wires=range(num_qubits)) - return qml.expval(H) + return qp.expval(H) ############################################################################## # If we evaluate this cost function, we can see that it corresponds to 15 different @@ -154,7 +154,7 @@ def cost_circuit(params): from jax import random as random key, scale = random.PRNGKey(0), jnp.pi params = random.normal(key, shape=(len(singles) + len(doubles),)) * scale -with qml.Tracker(dev) as tracker: # track the number of executions +with qp.Tracker(dev) as tracker: # track the number of executions print("Cost function value:", cost_circuit(params)) print("Number of quantum evaluations:", tracker.totals['executions']) @@ -163,7 +163,7 @@ def cost_circuit(params): # How about a larger molecule? Let's try the # `water molecule `__: -dataset = qml.data.load('qchem', molname="H2O")[0] +dataset = qp.data.load('qchem', molname="H2O")[0] H, num_qubits = dataset.hamiltonian, len(dataset.hamiltonian.wires) print("Required number of qubits:", num_qubits) @@ -359,8 +359,8 @@ def cost_circuit(params): obs = [ - qml.PauliX(0) @ qml.PauliY(1), - qml.PauliX(0) @ qml.PauliZ(2) + qp.PauliX(0) @ qp.PauliY(1), + qp.PauliX(0) @ qp.PauliZ(2) ] @@ -369,20 +369,20 @@ def cost_circuit(params): # the two QWC terms. -dev = qml.device("default.qubit", wires=3) +dev = qp.device("default.qubit", wires=3) -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def circuit1(weights): - qml.StronglyEntanglingLayers(weights, wires=range(3)) - return qml.expval(obs[0]) + qp.StronglyEntanglingLayers(weights, wires=range(3)) + return qp.expval(obs[0]) -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def circuit2(weights): - qml.StronglyEntanglingLayers(weights, wires=range(3)) - return qml.expval(obs[1]) + qp.StronglyEntanglingLayers(weights, wires=range(3)) + return qp.expval(obs[1]) -param_shape = qml.templates.StronglyEntanglingLayers.shape(n_layers=3, n_wires=3) +param_shape = qp.templates.StronglyEntanglingLayers.shape(n_layers=3, n_wires=3) key, scale = random.PRNGKey(192933), 0.1 weights = scale * random.normal(key, shape=param_shape) @@ -393,20 +393,20 @@ def circuit2(weights): # Now, let's use our QWC approach to reduce this down to a *single* measurement # of the probabilities in the shared eigenbasis of both QWC observables: -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def circuit_qwc(weights): - qml.StronglyEntanglingLayers(weights, wires=range(3)) + qp.StronglyEntanglingLayers(weights, wires=range(3)) # rotate wire 0 into the shared eigenbasis - qml.RY(-jnp.pi / 2, wires=0) + qp.RY(-jnp.pi / 2, wires=0) # rotate wire 1 into the shared eigenbasis - qml.RX(jnp.pi / 2, wires=1) + qp.RX(jnp.pi / 2, wires=1) # wire 2 does not require a rotation # measure probabilities in the computational basis - return qml.probs(wires=range(3)) + return qp.probs(wires=range(3)) rotated_probs = circuit_qwc(weights) @@ -438,12 +438,12 @@ def circuit_qwc(weights): # Luckily, PennyLane automatically performs this QWC grouping under the hood. We simply # return the two QWC Pauli terms from the QNode: -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def circuit(weights): - qml.StronglyEntanglingLayers(weights, wires=range(3)) + qp.StronglyEntanglingLayers(weights, wires=range(3)) return [ - qml.expval(qml.PauliX(0) @ qml.PauliY(1)), - qml.expval(qml.PauliX(0) @ qml.PauliZ(2)) + qp.expval(qp.PauliX(0) @ qp.PauliY(1)), + qp.expval(qp.PauliX(0) @ qp.PauliZ(2)) ] @@ -452,10 +452,10 @@ def circuit(weights): ############################################################################## # Behind the scenes, PennyLane is making use of our built-in -# :mod:`qml.pauli ` module, which contains functions for diagonalizing QWC +# :mod:`qp.pauli ` module, which contains functions for diagonalizing QWC # terms: -rotations, new_obs = qml.pauli.diagonalize_qwc_pauli_words(obs) +rotations, new_obs = qp.pauli.diagonalize_qwc_pauli_words(obs) print(rotations) print(new_obs) @@ -463,7 +463,7 @@ def circuit(weights): ############################################################################## # Here, the first line corresponds to the basis rotations that were discussed above, written in -# terms of ``RX`` and ``RY`` rotations. Check out the :mod:`qml.pauli ` +# terms of ``RX`` and ``RY`` rotations. Check out the :mod:`qp.pauli ` # documentation for more details on its provided functionality and how it works. # # Given a Hamiltonian containing a large number of Pauli terms, @@ -543,19 +543,19 @@ def circuit(weights): from matplotlib import pyplot as plt terms = [ - qml.PauliZ(0), - qml.PauliZ(0) @ qml.PauliZ(1), - qml.PauliZ(0) @ qml.PauliZ(1) @ qml.PauliZ(2), - qml.PauliZ(0) @ qml.PauliZ(1) @ qml.PauliZ(2) @ qml.PauliZ(3), - qml.PauliX(2) @ qml.PauliX(3), - qml.PauliY(0) @ qml.PauliX(2) @ qml.PauliX(3), - qml.PauliY(0) @ qml.PauliY(1) @ qml.PauliX(2) @ qml.PauliX(3) + qp.PauliZ(0), + qp.PauliZ(0) @ qp.PauliZ(1), + qp.PauliZ(0) @ qp.PauliZ(1) @ qp.PauliZ(2), + qp.PauliZ(0) @ qp.PauliZ(1) @ qp.PauliZ(2) @ qp.PauliZ(3), + qp.PauliX(2) @ qp.PauliX(3), + qp.PauliY(0) @ qp.PauliX(2) @ qp.PauliX(3), + qp.PauliY(0) @ qp.PauliY(1) @ qp.PauliX(2) @ qp.PauliX(3) ] def format_pauli_word(term): """Convenience function that nicely formats a PennyLane tensor observable as a Pauli word""" - if isinstance(term, qml.ops.Prod): + if isinstance(term, qp.ops.Prod): return " ".join([format_pauli_word(t) for t in term]) return f"{term.name[-1]}{term.wires.tolist()[0]}" @@ -675,9 +675,9 @@ def format_pauli_word(term): # the entire process using the provided grouping functions. # # Steps 1-3 (finding and grouping QWC terms in the Hamiltonian) can be done via the -# :func:`qml.pauli.group_observables ` function: +# :func:`qp.pauli.group_observables ` function: -obs_groupings = qml.pauli.group_observables(terms, grouping_type='qwc', method='rlf') +obs_groupings = qp.pauli.group_observables(terms, grouping_type='qwc', method='rlf') ############################################################################## @@ -686,23 +686,23 @@ def format_pauli_word(term): # heuristic (in this case, ``"rlf"`` refers to Recursive Largest First, a variant of largest first colouring heuristic). # # If we want to see what the required rotations and measurements are, we can use the -# :func:`qml.pauli.diagonalize_qwc_groupings ` +# :func:`qp.pauli.diagonalize_qwc_groupings ` # function: -rotations, measurements = qml.pauli.diagonalize_qwc_groupings(obs_groupings) +rotations, measurements = qp.pauli.diagonalize_qwc_groupings(obs_groupings) ############################################################################## # However, this isn't strictly necessary—recall previously that the QNode # has the capability to *automatically* measure qubit-wise commuting observables! -dev = qml.device("lightning.qubit", wires=4) +dev = qp.device("lightning.qubit", wires=4) -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def circuit(weights, group=None, **kwargs): - qml.StronglyEntanglingLayers(weights, wires=range(4)) - return [qml.expval(o) for o in group] + qp.StronglyEntanglingLayers(weights, wires=range(4)) + return [qp.expval(o) for o in group] -param_shape = qml.templates.StronglyEntanglingLayers.shape(n_layers=3, n_wires=4) +param_shape = qp.templates.StronglyEntanglingLayers.shape(n_layers=3, n_wires=4) key = random.PRNGKey(1) weights = random.normal(key, shape=param_shape) * 0.1 result = [jnp.array(circuit(weights, group=g)) for g in obs_groupings] @@ -722,12 +722,12 @@ def circuit(weights, group=None, **kwargs): # problems), we can use the option ``grouping_type="qwc"`` in :class:`~.pennylane.Hamiltonian` to # automatically optimize the measurements. -H = qml.Hamiltonian(coeffs=jnp.ones(len(terms)), observables=terms, grouping_type="qwc") +H = qp.Hamiltonian(coeffs=jnp.ones(len(terms)), observables=terms, grouping_type="qwc") _, H_ops = H.terms() -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def cost_fn(weights): - qml.StronglyEntanglingLayers(weights, wires=range(4)) - return qml.expval(H) + qp.StronglyEntanglingLayers(weights, wires=range(4)) + return qp.expval(H) print(cost_fn(weights)) ############################################################################## @@ -738,12 +738,12 @@ def cost_fn(weights): # how this affects the number of measurements required to perform the VQE on :math:`\text{H}_2 \text{O}!` # Let's use our new-found knowledge to see what happens. -dataset = qml.data.load('qchem', molname="H2O")[0] +dataset = qp.data.load('qchem', molname="H2O")[0] H, num_qubits = dataset.hamiltonian, len(dataset.hamiltonian.wires) print("Number of Hamiltonian terms/required measurements:", len(H_ops)) # grouping -groups = qml.pauli.group_observables(H_ops, grouping_type='qwc', method='rlf') +groups = qp.pauli.group_observables(H_ops, grouping_type='qwc', method='rlf') print("Number of required measurements after optimization:", len(groups)) ############################################################################## diff --git a/demonstrations_v2/tutorial_measurement_optimize/metadata.json b/demonstrations_v2/tutorial_measurement_optimize/metadata.json index 3c1d70ff0b..c03f02dea2 100644 --- a/demonstrations_v2/tutorial_measurement_optimize/metadata.json +++ b/demonstrations_v2/tutorial_measurement_optimize/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2021-01-18T00:00:00+00:00", - "dateOfLastModification": "2025-11-10T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Quantum Chemistry" ], diff --git a/demonstrations_v2/tutorial_mitigation_advantage/demo.py b/demonstrations_v2/tutorial_mitigation_advantage/demo.py index 037d4fa863..a2291e225b 100644 --- a/demonstrations_v2/tutorial_mitigation_advantage/demo.py +++ b/demonstrations_v2/tutorial_mitigation_advantage/demo.py @@ -79,7 +79,7 @@ at the classical mixtures introduced by the Kraus operators of the noise channel. That is why we need to use the mixed state simulator. For more information see e.g. our :doc:`demo on simulating noisy circuits `. """ -import pennylane as qml +import pennylane as qp import jax import jax.numpy as jnp import matplotlib.pyplot as plt @@ -88,12 +88,12 @@ n_wires = 9 # Describe noise -noise_gate = qml.DepolarizingChannel +noise_gate = qp.DepolarizingChannel p = 0.005 # Load devices -dev_ideal = qml.device("default.mixed", wires=n_wires) -dev_noisy = qml.noise.insert(dev_ideal, noise_gate, p, position="all") +dev_ideal = qp.device("default.mixed", wires=n_wires) +dev_noisy = qp.noise.insert(dev_ideal, noise_gate, p, position="all") # 3x3 grid with nearest neighbors connections = [(0, 1), (1, 2), @@ -103,16 +103,16 @@ (1, 4), (4, 7), (2, 5), (5, 8)] -def time_evolution(theta_h, n_layers = 10, obs = qml.PauliZ(4)): +def time_evolution(theta_h, n_layers = 10, obs = qp.PauliZ(4)): for _ in range(n_layers): for i, j in connections: - qml.IsingZZ(-jnp.pi/2, wires=(i, j)) + qp.IsingZZ(-jnp.pi/2, wires=(i, j)) for i in range(n_wires): - qml.RX(theta_h, wires=i) - return qml.expval(obs) + qp.RX(theta_h, wires=i) + return qp.expval(obs) -qnode_ideal = qml.QNode(time_evolution, dev_ideal, interface="jax") -qnode_noisy = qml.QNode(time_evolution, dev_noisy, interface="jax") +qnode_ideal = qp.QNode(time_evolution, dev_ideal, interface="jax") +qnode_noisy = qp.QNode(time_evolution, dev_noisy, interface="jax") ############################################################################## # We can now simulate the final expectation value with and without noise. Note that the ``IsingZZ`` gate is not natively @@ -167,11 +167,11 @@ def time_evolution(theta_h, n_layers = 10, obs = qml.PauliZ(4)): # our model by an appropriate gain factor. Here, :math:`G=(1, 1.2, 1.6)` in accordance with [#ibm]_. In order to do this in PennyLane, we simply # set up two new noisy devices with the appropriately attenuated noise parameters. -dev_noisy1 = qml.noise.insert(dev_ideal, noise_gate, p*1.2, position="all") -dev_noisy2 = qml.noise.insert(dev_ideal, noise_gate, p*1.6, position="all") +dev_noisy1 = qp.noise.insert(dev_ideal, noise_gate, p*1.2, position="all") +dev_noisy2 = qp.noise.insert(dev_ideal, noise_gate, p*1.6, position="all") -qnode_noisy1 = qml.QNode(time_evolution, dev_noisy1, interface="jax") -qnode_noisy2 = qml.QNode(time_evolution, dev_noisy2, interface="jax") +qnode_noisy1 = qp.QNode(time_evolution, dev_noisy1, interface="jax") +qnode_noisy2 = qp.QNode(time_evolution, dev_noisy2, interface="jax") res_noisy1 = jax.vmap(qnode_noisy1)(thetas) res_noisy2 = jax.vmap(qnode_noisy2)(thetas) @@ -197,7 +197,7 @@ def time_evolution(theta_h, n_layers = 10, obs = qml.PauliZ(4)): # We now repeat this procedure for all values of :math:`\theta_h` and see how the results are much improved. # We can use :func:`~pennylane.noise.richardson_extrapolate` that performs a polynomial fit of a degree matching the input data size. -res_mitigated = [qml.noise.richardson_extrapolate(Gs, [res_noisy[i], res_noisy1[i], res_noisy2[i]]) for i in range(len(res_ideal))] +res_mitigated = [qp.noise.richardson_extrapolate(Gs, [res_noisy[i], res_noisy1[i], res_noisy2[i]]) for i in range(len(res_ideal))] plt.plot(thetas, res_ideal, label="exact") plt.plot(thetas, res_mitigated, label="mitigated") diff --git a/demonstrations_v2/tutorial_mitigation_advantage/metadata.json b/demonstrations_v2/tutorial_mitigation_advantage/metadata.json index 69626781c8..328335b6e3 100644 --- a/demonstrations_v2/tutorial_mitigation_advantage/metadata.json +++ b/demonstrations_v2/tutorial_mitigation_advantage/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-06-16T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Quantum Hardware", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_mol_geo_opt/demo.py b/demonstrations_v2/tutorial_mol_geo_opt/demo.py index 91d6315eef..a8fc8c6092 100644 --- a/demonstrations_v2/tutorial_mol_geo_opt/demo.py +++ b/demonstrations_v2/tutorial_mol_geo_opt/demo.py @@ -123,12 +123,12 @@ # of the trihydrogen cation using the # :func:`~.pennylane.qchem.molecular_hamiltonian` function. -import pennylane as qml +import pennylane as qp def H(x): - molecule = qml.qchem.Molecule(symbols, x, charge=1) - return qml.qchem.molecular_hamiltonian(molecule)[0] + molecule = qp.qchem.Molecule(symbols, x, charge=1) + return qp.qchem.molecular_hamiltonian(molecule)[0] ############################################################################## @@ -185,7 +185,7 @@ def H(x): # :func:`~.pennylane.qchem.hf_state` function to generate the # occupation-number vector representing the Hartree-Fock state -hf = qml.qchem.hf_state(electrons=2, orbitals=6) +hf = qp.qchem.hf_state(electrons=2, orbitals=6) print(hf) ############################################################################## @@ -194,16 +194,16 @@ def H(x): # First, we define the quantum device used to compute the expectation value. # In this example, we use the ``default.qubit`` simulator: num_wires = 6 -dev = qml.device("default.qubit", wires=num_wires) +dev = qp.device("default.qubit", wires=num_wires) -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def circuit(params, obs, wires): - qml.BasisState(hf, wires=wires) - qml.DoubleExcitation(params[0], wires=[0, 1, 2, 3]) - qml.DoubleExcitation(params[1], wires=[0, 1, 4, 5]) + qp.BasisState(hf, wires=wires) + qp.DoubleExcitation(params[0], wires=[0, 1, 2, 3]) + qp.DoubleExcitation(params[1], wires=[0, 1, 4, 5]) - return qml.expval(obs) + return qp.expval(obs) ############################################################################## diff --git a/demonstrations_v2/tutorial_mol_geo_opt/metadata.json b/demonstrations_v2/tutorial_mol_geo_opt/metadata.json index 5d9c500c9b..bd1ab0a1bc 100644 --- a/demonstrations_v2/tutorial_mol_geo_opt/metadata.json +++ b/demonstrations_v2/tutorial_mol_geo_opt/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2021-06-30T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Chemistry" ], diff --git a/demonstrations_v2/tutorial_mps/demo.py b/demonstrations_v2/tutorial_mps/demo.py index 444eb70734..f1eb037c36 100644 --- a/demonstrations_v2/tutorial_mps/demo.py +++ b/demonstrations_v2/tutorial_mps/demo.py @@ -571,24 +571,24 @@ def dense_to_mps(psi, bond_dim): # Let us run a VQE example from using the `PennyLane Datasets `__ data for the :math:`H_6` molecule. What you will see here is mostly boilerplate code in PennyLane for using ``default.tensor`,` and you can # see our :doc:`demo on how to use default.tensor ` for more details. -import pennylane as qml +import pennylane as qp -[dataset] = qml.data.load("qchem", molname="H6", bondlength=1.3, basis="STO-3G") +[dataset] = qp.data.load("qchem", molname="H6", bondlength=1.3, basis="STO-3G") H = dataset.hamiltonian # molecular Hamiltonian in qubit basis n_wires = len(H.wires) # number of qubits def circuit(): - qml.BasisState(dataset.hf_state, wires=H.wires) # Hartree–Fock initial state + qp.BasisState(dataset.hf_state, wires=H.wires) # Hartree–Fock initial state for op in dataset.vqe_gates: # Applying all pre-optimized VQE gates - qml.apply(op) - return qml.expval(H) # expectation value of molecular Hamiltonian + qp.apply(op) + return qp.expval(H) # expectation value of molecular Hamiltonian # set up device with hyper-parameters and kwargs -mps = qml.device("default.tensor", wires=n_wires, method="mps", max_bond_dim=30, contract="auto-mps") +mps = qp.device("default.tensor", wires=n_wires, method="mps", max_bond_dim=30, contract="auto-mps") # Create the QNode to execute the circuit on the device, and call it (w/o arguments) -res = qml.QNode(circuit, mps)() +res = qp.QNode(circuit, mps)() # Compare MPS simulation result with pre-optimized state-vector result res, dataset.vqe_energy @@ -611,8 +611,8 @@ def circuit(): ress = [] for bond_dim in bond_dims: - mps = qml.device("default.tensor", wires=n_wires, method="mps", max_bond_dim=bond_dim, contract="auto-mps") - res = qml.QNode(circuit, mps)() + mps = qp.device("default.tensor", wires=n_wires, method="mps", max_bond_dim=bond_dim, contract="auto-mps") + res = qp.QNode(circuit, mps)() ress.append(res) diff --git a/demonstrations_v2/tutorial_mps/metadata.json b/demonstrations_v2/tutorial_mps/metadata.json index 5302ecb0dd..1a82840021 100644 --- a/demonstrations_v2/tutorial_mps/metadata.json +++ b/demonstrations_v2/tutorial_mps/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-09-29T00:00:00+00:00", - "dateOfLastModification": "2026-01-14T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Computing", "Algorithms", diff --git a/demonstrations_v2/tutorial_multiclass_classification/demo.py b/demonstrations_v2/tutorial_multiclass_classification/demo.py index 46789a958b..a6669bf3f2 100644 --- a/demonstrations_v2/tutorial_multiclass_classification/demo.py +++ b/demonstrations_v2/tutorial_multiclass_classification/demo.py @@ -47,7 +47,7 @@ of size 4. """ -import pennylane as qml +import pennylane as qp import torch import numpy as np from torch.autograd import Variable @@ -67,7 +67,7 @@ num_layers = 6 total_iterations = 100 -dev = qml.device("default.qubit", wires=num_qubits) +dev = qp.device("default.qubit", wires=num_qubits) ################################################################################# @@ -81,12 +81,12 @@ def layer(W): for i in range(num_qubits): - qml.Rot(W[i, 0], W[i, 1], W[i, 2], wires=i) + qp.Rot(W[i, 0], W[i, 1], W[i, 2], wires=i) for j in range(num_qubits - 1): - qml.CNOT(wires=[j, j + 1]) + qp.CNOT(wires=[j, j + 1]) if num_qubits >= 2: # Apply additional CNOT to entangle the last with the first qubit - qml.CNOT(wires=[num_qubits - 1, 0]) + qp.CNOT(wires=[num_qubits - 1, 0]) ################################################################################# @@ -104,17 +104,17 @@ def layer(W): def circuit(weights, feat=None): - qml.AmplitudeEmbedding(feat, range(num_qubits), pad_with=0.0, normalize=True) + qp.AmplitudeEmbedding(feat, range(num_qubits), pad_with=0.0, normalize=True) for W in weights: layer(W) - return qml.expval(qml.PauliZ(0)) + return qp.expval(qp.PauliZ(0)) qnodes = [] for iq in range(num_classes): - qnode = qml.QNode(circuit, dev, interface="torch") + qnode = qp.QNode(circuit, dev, interface="torch") qnodes.append(qnode) diff --git a/demonstrations_v2/tutorial_multiclass_classification/metadata.json b/demonstrations_v2/tutorial_multiclass_classification/metadata.json index aadd811853..4fae5a0130 100644 --- a/demonstrations_v2/tutorial_multiclass_classification/metadata.json +++ b/demonstrations_v2/tutorial_multiclass_classification/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2020-04-09T00:00:00+00:00", - "dateOfLastModification": "2025-12-19T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Algorithms" ], diff --git a/demonstrations_v2/tutorial_neutral_atoms/demo.py b/demonstrations_v2/tutorial_neutral_atoms/demo.py index 478dfaaf78..cac9ead1d6 100644 --- a/demonstrations_v2/tutorial_neutral_atoms/demo.py +++ b/demonstrations_v2/tutorial_neutral_atoms/demo.py @@ -304,7 +304,7 @@ # this can be easily changed in programmable devices. # Let's plot this function to get an idea of what the pulse looks like. First, let's import all the relevant libraries. -import pennylane as qml +import pennylane as qp from pennylane import numpy as np import matplotlib.pyplot as plt import jax @@ -359,16 +359,16 @@ def blackman_window(peak, time): detuning = 0 # For now, let's act on only one neutral atom -single_qubit_dev = qml.device("default.qubit", wires=1) +single_qubit_dev = qp.device("default.qubit", wires=1) -@qml.qnode(single_qubit_dev) +@qp.qnode(single_qubit_dev) def state_evolution(): - # Use qml.evolve to find the final state of the atom after interacting with the pulse - qml.evolve(H_d(blackman_window, phase, detuning, wires=[0]))([peak], t=[0, duration]) + # Use qp.evolve to find the final state of the atom after interacting with the pulse + qp.evolve(H_d(blackman_window, phase, detuning, wires=[0]))([peak], t=[0, duration]) - return qml.state() + return qp.state() print("The final state is {}".format(state_evolution().round(2))) @@ -384,13 +384,13 @@ def state_evolution(): detuning = 100 # Some large detuning to prove the point -@qml.qnode(single_qubit_dev) +@qp.qnode(single_qubit_dev) def state_evolution_detuned(): - # Use qml.evolve to find the final state of the atom after interacting with the pulse - qml.evolve(H_d(blackman_window, phase, detuning, wires=[0]))([peak], t=[0, duration]) + # Use qp.evolve to find the final state of the atom after interacting with the pulse + qp.evolve(H_d(blackman_window, phase, detuning, wires=[0]))([peak], t=[0, duration]) - return qml.state() + return qp.state() print( @@ -438,17 +438,17 @@ def neutral_atom_RX(theta): peak = theta / duration / 0.42 / (2 * jnp.pi) # Recall that duration is 0.2 # Set phase and detuning equal to zero for RX gate - qml.evolve(H_d(blackman_window, 0, 0, wires=[0]))([peak], t=[0, duration]) + qp.evolve(H_d(blackman_window, 0, 0, wires=[0]))([peak], t=[0, duration]) print( "For theta = pi/2, the matrix for the pulse-based RX gate is \n {} \n".format( - qml.matrix(neutral_atom_RX, wire_order=[0])(jnp.pi / 2).round(2) + qp.matrix(neutral_atom_RX, wire_order=[0])(jnp.pi / 2).round(2) ) ) print( "The matrix for the exact RX(pi/2) gate is \n {}".format( - qml.matrix(qml.RX(jnp.pi / 2, wires=0)).round(2) + qp.matrix(qp.RX(jnp.pi / 2, wires=0)).round(2) ) ) ############################################################################## @@ -461,17 +461,17 @@ def neutral_atom_RY(theta): peak = theta / duration / 0.42 / (2 * jnp.pi) # Recall that duration is 0.2 # Set phase equal to pi/2 and detuning equal to zero for RY gate - qml.evolve(H_d(blackman_window, -jnp.pi / 2, 0, wires=[0]))([peak], t=[0, duration]) + qp.evolve(H_d(blackman_window, -jnp.pi / 2, 0, wires=[0]))([peak], t=[0, duration]) print( "For theta = pi/2, the matrix for the pulse-based RY gate is \n {} \n".format( - qml.matrix(neutral_atom_RY, wire_order=[0])(jnp.pi / 2).round(2) + qp.matrix(neutral_atom_RY, wire_order=[0])(jnp.pi / 2).round(2) ) ) print( "The matrix for the exact RY(pi/2) gate is \n {}".format( - qml.matrix(qml.RY(jnp.pi / 2, wires=0)).round(2) + qp.matrix(qp.RY(jnp.pi / 2, wires=0)).round(2) ) ) ############################################################################## @@ -521,7 +521,7 @@ def H_i(distance, coupling): atomic_coordinates = [[0, 0], [0, distance]] # Return the interaction term for two atoms in terms of the distance - return qml.pulse.rydberg_interaction( + return qp.pulse.rydberg_interaction( atomic_coordinates, interaction_coeff=coupling, wires=[0, 1] ) @@ -551,7 +551,7 @@ def energy_gap(distance): H = (interaction_term + drive_term)([peak], time) # Calculate the eigenvalues for the full Hamiltonian - eigenvalues = jnp.linalg.eigvals(qml.matrix(H)) + eigenvalues = jnp.linalg.eigvals(qp.matrix(H)) return jnp.sort(eigenvalues - eigenvalues[0]) @@ -608,7 +608,7 @@ def two_pi_pulse(distance, coupling, wires=[0]): full_hamiltonian = H_d(blackman_window, 0, 0, wires) + H_i(distance, coupling) # Return the 2 pi pulse - qml.evolve(full_hamiltonian)([2 * jnp.pi / 0.42 / 0.2 / (2 * jnp.pi)], t=[0, 0.2]) + qp.evolve(full_hamiltonian)([2 * jnp.pi / 0.42 / 0.2 / (2 * jnp.pi)], t=[0, 0.2]) def pi_pulse(distance, coupling, wires=[0]): @@ -616,7 +616,7 @@ def pi_pulse(distance, coupling, wires=[0]): full_hamiltonian = H_d(blackman_window, 0, 0, wires) + H_i(distance, coupling) # Return the pi pulse - qml.evolve(full_hamiltonian)([jnp.pi / 0.42 / 0.2 / (2 * jnp.pi)], t=[0, 0.2]) + qp.evolve(full_hamiltonian)([jnp.pi / 0.42 / 0.2 / (2 * jnp.pi)], t=[0, 0.2]) ############################################################################## @@ -626,10 +626,10 @@ def pi_pulse(distance, coupling, wires=[0]): # Then, let's see the effect the sequence of pulses has on the :math:`\vert 00 \rangle` state when the atoms are close enough. # -dev_two_qubits = qml.device("default.qubit", wires=2) +dev_two_qubits = qp.device("default.qubit", wires=2) -@qml.qnode(dev_two_qubits) +@qp.qnode(dev_two_qubits) def neutral_atom_CZ(distance, coupling): pi_pulse(distance, coupling, wires=[0]) @@ -638,7 +638,7 @@ def neutral_atom_CZ(distance, coupling): pi_pulse(distance, coupling, wires=[0]) - return qml.state() + return qp.state() print( diff --git a/demonstrations_v2/tutorial_neutral_atoms/metadata.json b/demonstrations_v2/tutorial_neutral_atoms/metadata.json index ffefd50101..09d7877354 100644 --- a/demonstrations_v2/tutorial_neutral_atoms/metadata.json +++ b/demonstrations_v2/tutorial_neutral_atoms/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-05-30T00:00:00+00:00", - "dateOfLastModification": "2025-12-19T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Quantum Hardware", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_noisy_circuit_optimization/demo.py b/demonstrations_v2/tutorial_noisy_circuit_optimization/demo.py index 434e3537ad..ccebd61814 100644 --- a/demonstrations_v2/tutorial_noisy_circuit_optimization/demo.py +++ b/demonstrations_v2/tutorial_noisy_circuit_optimization/demo.py @@ -79,53 +79,53 @@ to carry out our noisy simulations. """ -import pennylane as qml +import pennylane as qp from pennylane import numpy as np import matplotlib.pyplot as plt -dev = qml.device("cirq.mixedsimulator", wires=2) +dev = qp.device("cirq.mixedsimulator", wires=2) # CHSH observables -A1 = qml.PauliZ(0) -A2 = qml.PauliX(0) -B1 = qml.Hermitian(np.array([[1, 1], [1, -1]]) / np.sqrt(2), wires=1) -B2 = qml.Hermitian(np.array([[1, -1], [-1, -1]]) / np.sqrt(2), wires=1) +A1 = qp.PauliZ(0) +A2 = qp.PauliX(0) +B1 = qp.Hermitian(np.array([[1, 1], [1, -1]]) / np.sqrt(2), wires=1) +B2 = qp.Hermitian(np.array([[1, -1], [-1, -1]]) / np.sqrt(2), wires=1) CHSH_observables = [A1 @ B1, A1 @ B2, A2 @ B1, A2 @ B2] # subcircuit for creating an entangled pair of qubits def bell_pair(): - qml.Hadamard(wires=0) - qml.CNOT(wires=[0, 1]) + qp.Hadamard(wires=0) + qp.CNOT(wires=[0, 1]) # circuits for measuring each distinct observable -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def measure_A1B1(): bell_pair() - return qml.expval(A1 @ B1) + return qp.expval(A1 @ B1) -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def measure_A1B2(): bell_pair() - return qml.expval(A1 @ B2) + return qp.expval(A1 @ B2) -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def measure_A2B1(): bell_pair() - return qml.expval(A2 @ B1) + return qp.expval(A2 @ B1) -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def measure_A2B2(): bell_pair() - return qml.expval(A2 @ B2) + return qp.expval(A2 @ B2) # now we measure each circuit and construct the CHSH inequality @@ -181,8 +181,8 @@ def measure_A2B2(): # we overwrite the bell_pair() subcircuit to add # extra noisy channels after the entangled state is created def bell_pair(): - qml.Hadamard(wires=0) - qml.CNOT(wires=[0, 1]) + qp.Hadamard(wires=0) + qp.CNOT(wires=[0, 1]) cirq_ops.BitFlip(p, wires=0) cirq_ops.BitFlip(p, wires=1) @@ -261,13 +261,13 @@ def bell_pair(): # situations. -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def circuit(gate_params, noise_param=0.0): - qml.RX(gate_params[0], wires=0) - qml.RY(gate_params[1], wires=0) + qp.RX(gate_params[0], wires=0) + qp.RY(gate_params[1], wires=0) cirq_ops.Depolarize(noise_param, wires=0) - return qml.expval(qml.PauliZ(0)) + return qp.expval(qp.PauliZ(0)) gate_pars = [0.54, 0.12] @@ -316,7 +316,7 @@ def noisy_cost(x): # initialize the optimizer -opt = qml.GradientDescentOptimizer(stepsize=0.4) +opt = qp.GradientDescentOptimizer(stepsize=0.4) # set the number of steps steps = 100 diff --git a/demonstrations_v2/tutorial_noisy_circuit_optimization/metadata.json b/demonstrations_v2/tutorial_noisy_circuit_optimization/metadata.json index 23bd8bc4af..733d12d692 100644 --- a/demonstrations_v2/tutorial_noisy_circuit_optimization/metadata.json +++ b/demonstrations_v2/tutorial_noisy_circuit_optimization/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2020-06-01T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Devices and Performance" ], diff --git a/demonstrations_v2/tutorial_noisy_circuits/demo.py b/demonstrations_v2/tutorial_noisy_circuits/demo.py index 2009b347a6..d80b979d2b 100644 --- a/demonstrations_v2/tutorial_noisy_circuits/demo.py +++ b/demonstrations_v2/tutorial_noisy_circuits/demo.py @@ -57,7 +57,7 @@ # Bell state :math:`|\psi\rangle=\frac{1}{\sqrt{2}}(|00\rangle+|11\rangle).` We ask the QNode to # return the expectation value of :math:`Z_0\otimes Z_1:` # -import pennylane as qml +import pennylane as qp from jax import numpy as np import jax import jaxopt @@ -65,13 +65,13 @@ jax.config.update("jax_platform_name", "cpu") jax.config.update('jax_enable_x64', True) -dev = qml.device('default.mixed', wires=2) +dev = qp.device('default.mixed', wires=2) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(): - qml.Hadamard(wires=0) - qml.CNOT(wires=[0, 1]) - return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) + qp.Hadamard(wires=0) + qp.CNOT(wires=[0, 1]) + return qp.expval(qp.PauliZ(0) @ qp.PauliZ(1)) print(f"QNode output = {circuit():.4f}") @@ -81,11 +81,11 @@ def circuit(): # equal to :math:`|\psi\rangle\langle\psi|,` # where :math:`|\psi\rangle=\frac{1}{\sqrt{2}}(|00\rangle + |11\rangle).` -@qml.qnode(dev) +@qp.qnode(dev) def density_matrix_circuit(): - qml.Hadamard(wires=0) - qml.CNOT(wires=[0, 1]) - return qml.state() + qp.Hadamard(wires=0) + qp.CNOT(wires=[0, 1]) + return qp.state() matrix = density_matrix_circuit() print(f"Output density matrix is = \n{np.real(matrix)}") @@ -128,7 +128,7 @@ def density_matrix_circuit(): # K_0 &= \sqrt{1-p}\begin{pmatrix}1 & 0\\ 0 & 1\end{pmatrix}, \\ # K_1 &= \sqrt{p}\begin{pmatrix}0 & 1\\ 1 & 0\end{pmatrix}. # -# This channel can be implemented in PennyLane using the :class:`qml.BitFlip ` +# This channel can be implemented in PennyLane using the :class:`qp.BitFlip ` # operation. # # Let's see what happens when we simulate this type of noise acting on @@ -136,13 +136,13 @@ def density_matrix_circuit(): # -@qml.qnode(dev) +@qp.qnode(dev) def bitflip_circuit(p): - qml.Hadamard(wires=0) - qml.CNOT(wires=[0, 1]) - qml.BitFlip(p, wires=0) - qml.BitFlip(p, wires=1) - return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)), qml.state() + qp.Hadamard(wires=0) + qp.CNOT(wires=[0, 1]) + qp.BitFlip(p, wires=0) + qp.BitFlip(p, wires=1) + return qp.expval(qp.PauliZ(0) @ qp.PauliZ(1)), qp.state() ps = [0.001, 0.01, 0.1, 0.2] @@ -185,13 +185,13 @@ def bitflip_circuit(p): # below. -@qml.qnode(dev) +@qp.qnode(dev) def depolarizing_circuit(p): - qml.Hadamard(wires=0) - qml.CNOT(wires=[0, 1]) - qml.DepolarizingChannel(p, wires=0) - qml.DepolarizingChannel(p, wires=1) - return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) + qp.Hadamard(wires=0) + qp.CNOT(wires=[0, 1]) + qp.DepolarizingChannel(p, wires=0) + qp.DepolarizingChannel(p, wires=1) + return qp.expval(qp.PauliZ(0) @ qp.PauliZ(1)) ps = [0.001, 0.01, 0.1, 0.2] @@ -245,13 +245,13 @@ def depolarizing_circuit(p): def sigmoid(x): return 1/(1+np.exp(-x)) -@qml.qnode(dev) +@qp.qnode(dev) def damping_circuit(x): - qml.Hadamard(wires=0) - qml.CNOT(wires=[0, 1]) - qml.AmplitudeDamping(sigmoid(x), wires=0) # p = sigmoid(x) - qml.AmplitudeDamping(sigmoid(x), wires=1) - return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) + qp.Hadamard(wires=0) + qp.CNOT(wires=[0, 1]) + qp.AmplitudeDamping(sigmoid(x), wires=0) # p = sigmoid(x) + qp.AmplitudeDamping(sigmoid(x), wires=1) + return qp.expval(qp.PauliZ(0) @ qp.PauliZ(1)) ###################################################################### # We optimize the circuit with respect to a simple cost function that attains its minimum when diff --git a/demonstrations_v2/tutorial_noisy_circuits/metadata.json b/demonstrations_v2/tutorial_noisy_circuits/metadata.json index f3881691b8..1db86074e2 100644 --- a/demonstrations_v2/tutorial_noisy_circuits/metadata.json +++ b/demonstrations_v2/tutorial_noisy_circuits/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2021-02-22T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Getting Started" ], diff --git a/demonstrations_v2/tutorial_odegen/demo.py b/demonstrations_v2/tutorial_odegen/demo.py index c7b4cc1e21..3c7232729a 100644 --- a/demonstrations_v2/tutorial_odegen/demo.py +++ b/demonstrations_v2/tutorial_odegen/demo.py @@ -164,7 +164,7 @@ """ -import pennylane as qml +import pennylane as qp import numpy as np import jax.numpy as jnp import jax @@ -176,7 +176,7 @@ import matplotlib.pyplot as plt -H_obj = qml.sum(qml.PauliX(0) @ qml.PauliX(1), qml.PauliY(0) @ qml.PauliY(1), qml.PauliZ(0) @ qml.PauliZ(1)) +H_obj = qp.sum(qp.PauliX(0) @ qp.PauliX(1), qp.PauliY(0) @ qp.PauliY(1), qp.PauliZ(0) @ qp.PauliZ(1)) E_exact = -3. wires = H_obj.wires @@ -209,17 +209,17 @@ def drive_field(T, wdrive): """Set the evolution time ``T`` and drive frequency ``wdrive``""" def wrapped(p, t): # The first len(p) values of the trainable params p characterize the pwc function - amp = qml.pulse.pwc(T)(p[:len(p)//2], t) - phi = qml.pulse.pwc(T)(p[len(p)//2:], t) + amp = qp.pulse.pwc(T)(p[:len(p)//2], t) + phi = qp.pulse.pwc(T)(p[len(p)//2:], t) return amp * jnp.sin(wdrive * t + phi) return wrapped -H_pulse = qml.dot(-0.5*qubit_freq, [qml.PauliZ(i) for i in wires]) -H_pulse += g * (qml.PauliX(wires[0]) @ qml.PauliX(wires[1]) + qml.PauliY(wires[0]) @ qml.PauliY(wires[1])) +H_pulse = qp.dot(-0.5*qubit_freq, [qp.PauliZ(i) for i in wires]) +H_pulse += g * (qp.PauliX(wires[0]) @ qp.PauliX(wires[1]) + qp.PauliY(wires[0]) @ qp.PauliY(wires[1])) -H_pulse += drive_field(T_CR, qubit_freq[0]) * qml.PauliY(wires[0]) # on-resonance driving of qubit 0 -H_pulse += drive_field(T_CR, qubit_freq[0]) * qml.PauliY(wires[1]) # off-resonance driving of qubit 1 +H_pulse += drive_field(T_CR, qubit_freq[0]) * qp.PauliY(wires[0]) # on-resonance driving of qubit 0 +H_pulse += drive_field(T_CR, qubit_freq[0]) * qp.PauliY(wires[1]) # off-resonance driving of qubit 1 ############################################################################## # We can now define the cost function that computes the expectation value of @@ -227,26 +227,26 @@ def wrapped(p, t): # We then define the two separate qnodes with ODEgen and SPS as their differentiation methods, respectively. def qnode0(params): - qml.evolve(H_pulse)((params[0], params[1]), t=T_CR) - return qml.expval(H_obj) + qp.evolve(H_pulse)((params[0], params[1]), t=T_CR) + return qp.expval(H_obj) -dev = qml.device("default.qubit", wires=range(2)) +dev = qp.device("default.qubit", wires=range(2)) -qnode_jax = qml.QNode(qnode0, dev, interface="jax") +qnode_jax = qp.QNode(qnode0, dev, interface="jax") value_and_grad_jax = jax.jit(jax.value_and_grad(qnode_jax)) num_split_times = 8 gradient_kwargs = {"use_broadcasting": True, "num_split_times": num_split_times} -qnode_sps = qml.QNode( +qnode_sps = qp.QNode( qnode0, dev, interface="jax", - diff_method=qml.gradients.stoch_pulse_grad, + diff_method=qp.gradients.stoch_pulse_grad, gradient_kwargs=gradient_kwargs, ) value_and_grad_sps = jax.value_and_grad(qnode_sps) -qnode_odegen = qml.QNode(qnode0, dev, interface="jax", diff_method=qml.gradients.pulse_odegen) +qnode_odegen = qp.QNode(qnode0, dev, interface="jax", diff_method=qp.gradients.pulse_odegen) value_and_grad_odegen = jax.value_and_grad(qnode_odegen) ############################################################################## diff --git a/demonstrations_v2/tutorial_odegen/metadata.json b/demonstrations_v2/tutorial_odegen/metadata.json index 607e117847..047482eaca 100644 --- a/demonstrations_v2/tutorial_odegen/metadata.json +++ b/demonstrations_v2/tutorial_odegen/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-12-12T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Optimization", "Quantum Computing", From 5cdae9bde99521926f4911d18a57e996b2a1c8df Mon Sep 17 00:00:00 2001 From: drdren <104710745+drdren@users.noreply.github.com> Date: Tue, 21 Apr 2026 11:58:59 -0400 Subject: [PATCH 05/10] qml to qp Batch 7 (#1758) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### Before submitting Please complete the following checklist when submitting a PR: - [ ] Ensure that your tutorial executes correctly, and conforms to the guidelines specified in the [README](https://github.com/PennyLaneAI/demos/blob/master/README.md). - [ ] Remember to do a grammar check of the content you include. - [ ] All tutorials conform to [PEP8 standards](https://www.python.org/dev/peps/pep-0008/). To auto format files, simply `pip install black`, and then run `black -l 100 path/to/file.py`. When all the above are checked, delete everything above the dashed line and fill in the pull request template. ------------------------------------------------------------------------------------------------------------ **Title:** **Summary:** **Relevant references:** **Possible Drawbacks:** **Related GitHub Issues:** ---- If you are writing a demonstration, please answer these questions to facilitate the marketing process. * GOALS — Why are we working on this now? *Eg. Promote a new PL feature or show a PL implementation of a recent paper.* * AUDIENCE — Who is this for? *Eg. Chemistry researchers, PL educators, beginners in quantum computing.* * KEYWORDS — What words should be included in the marketing post? * Which of the following types of documentation is most similar to your file? (more details [here](https://www.notion.so/xanaduai/Different-kinds-of-documentation-69200645fe59442991c71f9e7d8a77f8)) - [ ] Tutorial - [ ] Demo - [ ] How-to Co-authored-by: David --- .../tutorial_optimal_control/demo.py | 28 ++-- .../tutorial_optimal_control/metadata.json | 2 +- demonstrations_v2/tutorial_pasqal/demo.py | 20 +-- .../tutorial_pasqal/metadata.json | 2 +- .../tutorial_period_finding/demo.py | 28 ++-- .../tutorial_period_finding/metadata.json | 2 +- .../tutorial_phase_kickback/demo.py | 20 +-- .../tutorial_phase_kickback/metadata.json | 2 +- demonstrations_v2/tutorial_photonics/demo.py | 148 +++++++++--------- .../tutorial_photonics/metadata.json | 2 +- .../demo.py | 42 ++--- .../metadata.json | 2 +- .../tutorial_pulse_programming101/demo.py | 56 +++---- .../metadata.json | 2 +- demonstrations_v2/tutorial_qaoa_intro/demo.py | 62 ++++---- .../tutorial_qaoa_intro/metadata.json | 2 +- .../tutorial_qaoa_maxcut/demo.py | 28 ++-- .../tutorial_qaoa_maxcut/metadata.json | 2 +- demonstrations_v2/tutorial_qcbm/demo.py | 34 ++-- demonstrations_v2/tutorial_qcbm/metadata.json | 2 +- .../tutorial_qchem_external/demo.py | 18 +-- .../tutorial_qchem_external/metadata.json | 2 +- demonstrations_v2/tutorial_qft/demo.py | 32 ++-- demonstrations_v2/tutorial_qft/metadata.json | 2 +- .../tutorial_qft_and_groups/demo.py | 24 +-- .../tutorial_qft_and_groups/metadata.json | 2 +- .../tutorial_qft_arithmetics/demo.py | 92 +++++------ .../tutorial_qft_arithmetics/metadata.json | 2 +- demonstrations_v2/tutorial_qgrnn/demo.py | 32 ++-- .../tutorial_qgrnn/metadata.json | 2 +- .../demo.py | 26 +-- .../metadata.json | 2 +- .../tutorial_qksd_qsp_qualtran/demo.py | 60 +++---- .../tutorial_qksd_qsp_qualtran/metadata.json | 2 +- .../tutorial_qnn_module_torch/demo.py | 18 +-- .../tutorial_qnn_module_torch/metadata.json | 2 +- .../demo.py | 14 +- .../metadata.json | 2 +- demonstrations_v2/tutorial_qpe/demo.py | 18 +-- demonstrations_v2/tutorial_qpe/metadata.json | 2 +- .../tutorial_qsvt_hardware/demo.py | 42 ++--- .../tutorial_qsvt_hardware/metadata.json | 2 +- .../tutorial_quantum_analytic_descent/demo.py | 18 +-- .../metadata.json | 2 +- .../demo.py | 48 +++--- .../metadata.json | 2 +- 46 files changed, 477 insertions(+), 477 deletions(-) diff --git a/demonstrations_v2/tutorial_optimal_control/demo.py b/demonstrations_v2/tutorial_optimal_control/demo.py index 635b8dfa90..36d73a53a9 100644 --- a/demonstrations_v2/tutorial_optimal_control/demo.py +++ b/demonstrations_v2/tutorial_optimal_control/demo.py @@ -444,9 +444,9 @@ def smooth_rectangles(params, t, k=2.0, max_amp=1.0, eps=0.0, T=1.0): # up the subsequent executions a lot. For optimization workflows of small-scale # functions, this almost always pays off. -import pennylane as qml +import pennylane as qp -X, Y, Z = qml.PauliX, qml.PauliY, qml.PauliZ +X, Y, Z = qp.PauliX, qp.PauliY, qp.PauliZ num_wires = 2 # Hamiltonian terms of the drift and parametrized parts of H @@ -455,20 +455,20 @@ def smooth_rectangles(params, t, k=2.0, max_amp=1.0, eps=0.0, T=1.0): # Coefficients: 1 for drift Hamiltonian and smooth rectangles for parametrized part coeffs = [1.0, 1.0] + [S_k for op in ops_param] # Build H -H = qml.dot(coeffs, ops_H_d + ops_param) +H = qp.dot(coeffs, ops_H_d + ops_param) # Set tolerances for the ODE solver atol = rtol = 1e-10 # Target unitary is CNOT. We get its matrix and note that we do not need the dagger # because CNOT is Hermitian. -target = qml.CNOT([0, 1]).matrix() +target = qp.CNOT([0, 1]).matrix() target_name = "CNOT" print(f"Our target unitary is a {target_name} gate, with matrix\n{target.astype('int')}") def pulse_matrix(params): """Compute the unitary time evolution matrix of the pulse for given parameters.""" - return qml.evolve(H, atol=atol, rtol=rtol)(params, T).matrix() + return qp.evolve(H, atol=atol, rtol=rtol)(params, T).matrix() @jax.jit @@ -644,20 +644,20 @@ def plot_optimal_pulses(hist, pulse_fn, ops, T, target_name): # Coefficients: 1. for drift Hamiltonian and smooth rectangles for parametrized part coeffs = [1.0, 1.0, 1.0] + [S_k for op in ops_param] # Build H -H = qml.dot(coeffs, ops_H_d + ops_param) +H = qp.dot(coeffs, ops_H_d + ops_param) # Set tolerances for the ODE solver atol = rtol = 1e-10 # Target unitary is Toffoli. We get its matrix and note that we do not need the dagger # because Toffoli is Hermitian and unitary. -target = qml.Toffoli([0, 1, 2]).matrix() +target = qp.Toffoli([0, 1, 2]).matrix() target_name = "Toffoli" print(f"Our target unitary is a {target_name} gate, with matrix\n{target.astype('int')}") def pulse_matrix(params): """Compute the unitary time evolution matrix of the pulse for given parameters.""" - return qml.evolve(H, atol=atol, rtol=rtol)(params, T).matrix() + return qp.evolve(H, atol=atol, rtol=rtol)(params, T).matrix() @jax.jit @@ -697,18 +697,18 @@ def profit(params): # flip the third qubit, returning a probability of one in the last entry # and zeros elsewhere. -dev = qml.device("default.qubit", wires=3) +dev = qp.device("default.qubit", wires=3) -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def node(params): # Prepare |110> - qml.PauliX(0) - qml.PauliX(1) + qp.PauliX(0) + qp.PauliX(1) # Apply pulse sequence - qml.evolve(H, atol=atol, rtol=rtol)(params, T) + qp.evolve(H, atol=atol, rtol=rtol)(params, T) # Return quantum state - return qml.probs() + return qp.probs() probs = node(max_params) diff --git a/demonstrations_v2/tutorial_optimal_control/metadata.json b/demonstrations_v2/tutorial_optimal_control/metadata.json index 66c1448139..51663872b5 100644 --- a/demonstrations_v2/tutorial_optimal_control/metadata.json +++ b/demonstrations_v2/tutorial_optimal_control/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-08-08T00:00:00+00:00", - "dateOfLastModification": "2025-12-10T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Optimization", "Quantum Computing", diff --git a/demonstrations_v2/tutorial_pasqal/demo.py b/demonstrations_v2/tutorial_pasqal/demo.py index 2731d65864..0d646ee6ca 100644 --- a/demonstrations_v2/tutorial_pasqal/demo.py +++ b/demonstrations_v2/tutorial_pasqal/demo.py @@ -152,11 +152,11 @@ # We will need to provide this device with the ``ThreeDQubit`` object that we created # above. We also need to instantiate the device with a fixed control radius. -import pennylane as qml +import pennylane as qp num_wires = len(qubits) control_radius = 32.4 -dev = qml.device("cirq.pasqal", control_radius=control_radius, +dev = qp.device("cirq.pasqal", control_radius=control_radius, qubits=qubits, wires=num_wires) ############################################################################## @@ -263,28 +263,28 @@ peak_qubit = 8 def controlled_rotation(phi, wires): - qml.RY(phi, wires=wires[1]) - qml.CNOT(wires=wires) - qml.RY(-phi, wires=wires[1]) - qml.CNOT(wires=wires) + qp.RY(phi, wires=wires[1]) + qp.CNOT(wires=wires) + qp.RY(-phi, wires=wires[1]) + qp.CNOT(wires=wires) -@qml.qnode(dev, interface="tf") +@qp.qnode(dev, interface="tf") def circuit(weights, data): # Input classical data loaded into qubits at second level for idx in range(4): if data[idx]: - qml.PauliX(wires=idx) + qp.PauliX(wires=idx) # Interact qubits from second and third levels for idx in range(4): - qml.CNOT(wires=[idx, idx + 4]) + qp.CNOT(wires=[idx, idx + 4]) # Interact qubits from third level with peak using parameterized gates for idx, wire in enumerate(range(4, 8)): controlled_rotation(weights[idx], wires=[wire, peak_qubit]) - return qml.expval(qml.PauliZ(wires=peak_qubit)) + return qp.expval(qp.PauliZ(wires=peak_qubit)) ############################################################################## diff --git a/demonstrations_v2/tutorial_pasqal/metadata.json b/demonstrations_v2/tutorial_pasqal/metadata.json index a86cb969b4..3909d9b049 100644 --- a/demonstrations_v2/tutorial_pasqal/metadata.json +++ b/demonstrations_v2/tutorial_pasqal/metadata.json @@ -8,7 +8,7 @@ "executable_stable": false, "executable_latest": false, "dateOfPublication": "2020-10-13T00:00:00+00:00", - "dateOfLastModification": "2026-02-19T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Quantum Hardware", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_period_finding/demo.py b/demonstrations_v2/tutorial_period_finding/demo.py index a8cedd5348..74f632394b 100644 --- a/demonstrations_v2/tutorial_period_finding/demo.py +++ b/demonstrations_v2/tutorial_period_finding/demo.py @@ -98,7 +98,7 @@ # Implementation of period finding in PennyLane # ---------------- -import pennylane as qml +import pennylane as qp import numpy as np import matplotlib.pyplot as plt @@ -194,7 +194,7 @@ def Oracle(f): # check that this is a unitary assert np.allclose(U @ np.linalg.inv(U), np.eye(2**7)) - return qml.QubitUnitary(U, wires=range(7)) + return qp.QubitUnitary(U, wires=range(7)) ##################################################################### @@ -208,28 +208,28 @@ def Oracle(f): # reason we define a device with 2 shots. We also add some snapshots to the circuit that we will look at later. -dev = qml.device("default.qubit", wires=7) +dev = qp.device("default.qubit", wires=7) -@qml.set_shots(2) -@qml.qnode(dev) +@qp.set_shots(2) +@qp.qnode(dev) def circuit(): """Circuit to implement the period finding algorithm.""" for i in range(4): - qml.Hadamard(wires=i) + qp.Hadamard(wires=i) - qml.Snapshot("initial_state") + qp.Snapshot("initial_state") Oracle(f) - qml.Snapshot("loaded_function") + qp.Snapshot("loaded_function") - qml.QFT(wires=range(4)) + qp.QFT(wires=range(4)) - qml.Snapshot("fourier_spectrum") + qp.Snapshot("fourier_spectrum") - return qml.sample(wires=range(4)) + return qp.sample(wires=range(4)) # take two samples from the circuit @@ -271,9 +271,9 @@ def circuit(): # look at the states that were prepared by making use of the snapshots we recorded during the # circuit simulation. -dev = qml.device("default.qubit", wires=7) -qnode = qml.set_shots(qml.QNode(circuit, dev), shots = 1) -intermediate_states = qml.snapshots(circuit)() +dev = qp.device("default.qubit", wires=7) +qnode = qp.set_shots(qp.QNode(circuit, dev), shots = 1) +intermediate_states = qp.snapshots(circuit)() ##################################################################### # We can plot them as discrete functions, where the size of a point indicates the absolute value diff --git a/demonstrations_v2/tutorial_period_finding/metadata.json b/demonstrations_v2/tutorial_period_finding/metadata.json index a3a560e988..3384381242 100644 --- a/demonstrations_v2/tutorial_period_finding/metadata.json +++ b/demonstrations_v2/tutorial_period_finding/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2025-04-16T10:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Algorithms" ], diff --git a/demonstrations_v2/tutorial_phase_kickback/demo.py b/demonstrations_v2/tutorial_phase_kickback/demo.py index aa0ec72bab..8fffa6d831 100644 --- a/demonstrations_v2/tutorial_phase_kickback/demo.py +++ b/demonstrations_v2/tutorial_phase_kickback/demo.py @@ -45,11 +45,11 @@ # circuits. Here we will work with 5 qubits, we will use qubit [0] as the control ancilla qubit, and qubits [1,2,3,4] will be our target qubits where we will encode :math:`|\psi\rangle.` # -import pennylane as qml +import pennylane as qp import numpy as np num_wires = 5 -dev = qml.device("default.qubit", wires=num_wires) +dev = qp.device("default.qubit", wires=num_wires) ###################################################################### # Building the quantum lock @@ -83,7 +83,7 @@ def quantum_lock(secret_key): - return qml.FlipSign(secret_key, wires=list(range(1, num_wires))) + return qp.FlipSign(secret_key, wires=list(range(1, num_wires))) ###################################################################### @@ -93,7 +93,7 @@ def quantum_lock(secret_key): def build_key(key): - return qml.BasisState(key, wires=list(range(1, num_wires))) + return qp.BasisState(key, wires=list(range(1, num_wires))) ###################################################################### @@ -101,14 +101,14 @@ def build_key(key): # -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def quantum_locking_mechanism(lock, key): build_key(key) - qml.Hadamard(wires=0) # Hadamard on ancilla qubit - qml.ctrl(lock, control=0) # Controlled unitary operation - qml.Hadamard(wires=0) # Hadamard again on ancilla qubit - return qml.sample(wires=0) + qp.Hadamard(wires=0) # Hadamard on ancilla qubit + qp.ctrl(lock, control=0) # Controlled unitary operation + qp.Hadamard(wires=0) # Hadamard again on ancilla qubit + return qp.sample(wires=0) def check_key(lock, key): diff --git a/demonstrations_v2/tutorial_phase_kickback/metadata.json b/demonstrations_v2/tutorial_phase_kickback/metadata.json index 7bb354424b..3c3e228636 100644 --- a/demonstrations_v2/tutorial_phase_kickback/metadata.json +++ b/demonstrations_v2/tutorial_phase_kickback/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-08-01T00:00:00+00:00", - "dateOfLastModification": "2025-12-19T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Getting Started", "Algorithms", diff --git a/demonstrations_v2/tutorial_photonics/demo.py b/demonstrations_v2/tutorial_photonics/demo.py index 4ff7294302..d71d21a651 100644 --- a/demonstrations_v2/tutorial_photonics/demo.py +++ b/demonstrations_v2/tutorial_photonics/demo.py @@ -128,7 +128,7 @@ # states of light. Let's first call the usual imports, # -import pennylane as qml +import pennylane as qp from pennylane import numpy as np import matplotlib.pyplot as plt @@ -136,7 +136,7 @@ # # and define the device. -dev = qml.device("default.gaussian", wires=1) +dev = qp.device("default.gaussian", wires=1) ############################################################################## # @@ -154,16 +154,16 @@ # We plot 1000 measurement results for both :math:`x` and :math:`p.` -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def vacuum_measure_x(): - return qml.sample(qml.QuadX(0)) # Samples X quadratures + return qp.sample(qp.QuadX(0)) # Samples X quadratures -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def vacuum_measure_p(): - return qml.sample(qml.QuadP(0)) # Samples P quadrature + return qp.sample(qp.QuadP(0)) # Samples P quadrature # Sample measurements in phase space @@ -197,27 +197,27 @@ def vacuum_measure_p(): # origin with a spread of approximately 1. We can check these eyeballed values explicitly, # using a device without shots this time. -dev_exact = qml.device("default.gaussian", wires=1) # No explicit shots gives analytic calculations +dev_exact = qp.device("default.gaussian", wires=1) # No explicit shots gives analytic calculations -@qml.qnode(dev_exact) +@qp.qnode(dev_exact) def vacuum_mean_x(): - return qml.expval(qml.QuadX(0)) # Returns exact expecation value of x + return qp.expval(qp.QuadX(0)) # Returns exact expecation value of x -@qml.qnode(dev_exact) +@qp.qnode(dev_exact) def vacuum_mean_p(): - return qml.expval(qml.QuadP(0)) # Returns exact expectation value of p + return qp.expval(qp.QuadP(0)) # Returns exact expectation value of p -@qml.qnode(dev_exact) +@qp.qnode(dev_exact) def vacuum_var_x(): - return qml.var(qml.QuadX(0)) # Returns exact variance of x + return qp.var(qp.QuadX(0)) # Returns exact variance of x -@qml.qnode(dev_exact) +@qp.qnode(dev_exact) def vacuum_var_p(): - return qml.var(qml.QuadP(0)) # Returns exact variance of p + return qp.var(qp.QuadP(0)) # Returns exact variance of p # Print calculated statistical quantities @@ -273,18 +273,18 @@ def vacuum_var_p(): # Let us plot sample quadrature measurements for a coherent state. -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def measure_coherent_x(alpha, phi): - qml.CoherentState(alpha, phi, wires=0) # Prepares coherent state - return qml.sample(qml.QuadX(0)) # Measures X quadrature + qp.CoherentState(alpha, phi, wires=0) # Prepares coherent state + return qp.sample(qp.QuadX(0)) # Measures X quadrature -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def measure_coherent_p(alpha, phi): - qml.CoherentState(alpha, phi, wires=0) # Prepares coherent state - return qml.sample(qml.QuadP(0)) # Measures P quadrature + qp.CoherentState(alpha, phi, wires=0) # Prepares coherent state + return qp.sample(qp.QuadP(0)) # Measures P quadrature # Choose alpha and phi and sample 1000 measurements @@ -357,20 +357,20 @@ def measure_coherent_p(alpha, phi): # Let's see the effect of this operation on an intial coherent state. -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def displace_coherent_x(alpha, phi, x): - qml.CoherentState(alpha, phi, wires = 0) # Create coherent state - qml.Displacement(x, 0, wires = 0) # Second argument is the displacement direction in phase space - return qml.sample(qml.QuadX(0)) + qp.CoherentState(alpha, phi, wires = 0) # Create coherent state + qp.Displacement(x, 0, wires = 0) # Second argument is the displacement direction in phase space + return qp.sample(qp.QuadX(0)) -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def displace_coherent_p(alpha, phi, x): - qml.CoherentState(alpha, phi, wires = 0) - qml.Displacement(x, 0, wires = 0) - return qml.sample(qml.QuadP(0)) + qp.CoherentState(alpha, phi, wires = 0) + qp.Displacement(x, 0, wires = 0) + return qp.sample(qp.QuadP(0)) # We plot both the initial and displaced state @@ -424,25 +424,25 @@ def displace_coherent_p(alpha, phi, x): # Let us be mindful that this will only work when the amplitude of the input state is much smaller # than that of the auxiliary coherent state. -dev2 = qml.device("default.gaussian", wires=2) +dev2 = qp.device("default.gaussian", wires=2) -@qml.set_shots(1000) -@qml.qnode(dev2) +@qp.set_shots(1000) +@qp.qnode(dev2) def disp_optics(z, x): - qml.CoherentState(z, 0, wires = 0) # High-amplitude auxiliary coherent state - qml.CoherentState(3, np.pi / 3, wires = 1) # Input state (e.g. low amplitude coherent state) - qml.Beamsplitter(np.arccos(1 - x ** 2 / z ** 2), 0, wires=[0, 1]) # Beamsplitter - return qml.sample(qml.QuadX(1)) # Measure x quadrature + qp.CoherentState(z, 0, wires = 0) # High-amplitude auxiliary coherent state + qp.CoherentState(3, np.pi / 3, wires = 1) # Input state (e.g. low amplitude coherent state) + qp.Beamsplitter(np.arccos(1 - x ** 2 / z ** 2), 0, wires=[0, 1]) # Beamsplitter + return qp.sample(qp.QuadX(1)) # Measure x quadrature -@qml.set_shots(1000) -@qml.qnode(dev2) +@qp.set_shots(1000) +@qp.qnode(dev2) def mom_optics(z, x): - qml.CoherentState(z, 0, wires = 0) - qml.CoherentState(3, np.pi / 3, wires = 1) - qml.Beamsplitter(np.arccos(1 - x ** 2 / z ** 2), 0, wires = [0, 1]) - return qml.sample(qml.QuadP(1)) # Measure p quadrature + qp.CoherentState(z, 0, wires = 0) + qp.CoherentState(3, np.pi / 3, wires = 1) + qp.Beamsplitter(np.arccos(1 - x ** 2 / z ** 2), 0, wires = [0, 1]) + return qp.sample(qp.QuadP(1)) # Measure p quadrature # Plot quadrature measurement before and after implementation of displacement @@ -506,18 +506,18 @@ def mom_optics(z, x): # of quadrature measurements. -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def measure_squeezed_x(r): - qml.Squeezing(r, 0, wires = 0) - return qml.sample(qml.QuadX(0)) + qp.Squeezing(r, 0, wires = 0) + return qp.sample(qp.QuadX(0)) -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def measure_squeezed_p(r): - qml.Squeezing(r, 0, wires = 0) - return qml.sample(qml.QuadP(0)) + qp.Squeezing(r, 0, wires = 0) + return qp.sample(qp.QuadP(0)) # Choose alpha and phi and sample 1000 measurements @@ -583,13 +583,13 @@ def measure_squeezed_p(r): # are superpositions of Fock States, including Gaussian states! # For example, let's measure the expected photon number for some squeezed state: -dev3 = qml.device("default.gaussian", wires=1) +dev3 = qp.device("default.gaussian", wires=1) -@qml.qnode(dev3) +@qp.qnode(dev3) def measure_n_coherent(alpha, phi): - qml.Squeezing(alpha, phi, wires = 0) - return qml.expval(qml.NumberOperator(0)) + qp.Squeezing(alpha, phi, wires = 0) + return qp.expval(qp.NumberOperator(0)) coherent_expval = measure_n_coherent(1, np.pi / 3) @@ -614,28 +614,28 @@ def measure_n_coherent(alpha, phi): # # Let's code this setup using PennyLane and check that it amounts to the measurement of quadratures. -dev_exact2 = qml.device("default.gaussian", wires = 2) +dev_exact2 = qp.device("default.gaussian", wires = 2) -@qml.qnode(dev_exact2) +@qp.qnode(dev_exact2) def measurement(a, phi): - qml.Displacement(a, phi, wires = 0) # Implement displacement using PennyLane - return qml.expval(qml.QuadX(0)) + qp.Displacement(a, phi, wires = 0) # Implement displacement using PennyLane + return qp.expval(qp.QuadX(0)) -@qml.qnode(dev_exact2) +@qp.qnode(dev_exact2) def measurement2_0(a, theta, alpha, phi): - qml.Displacement(a, theta, wires = 0) # We choose the initial to be a displaced vacuum - qml.CoherentState(alpha, phi, wires = 1) # Prepare coherent as second qumode - qml.Beamsplitter(np.pi / 4, 0, wires=[0, 1]) # Interfere both states - return qml.expval(qml.NumberOperator(0)) # Read out N + qp.Displacement(a, theta, wires = 0) # We choose the initial to be a displaced vacuum + qp.CoherentState(alpha, phi, wires = 1) # Prepare coherent as second qumode + qp.Beamsplitter(np.pi / 4, 0, wires=[0, 1]) # Interfere both states + return qp.expval(qp.NumberOperator(0)) # Read out N -@qml.qnode(dev_exact2) +@qp.qnode(dev_exact2) def measurement2_1(a, theta, alpha, phi): - qml.Displacement(a, theta, wires = 0) # We choose the initial to be a displaced vacuum - qml.CoherentState(alpha, phi, wires = 1) # Prepare coherent as second qumode - qml.Beamsplitter(np.pi / 4, 0, wires=[0, 1]) # Interfere both states - return qml.expval(qml.NumberOperator(1)) # Read out N + qp.Displacement(a, theta, wires = 0) # We choose the initial to be a displaced vacuum + qp.CoherentState(alpha, phi, wires = 1) # Prepare coherent as second qumode + qp.Beamsplitter(np.pi / 4, 0, wires=[0, 1]) # Interfere both states + return qp.expval(qp.NumberOperator(1)) # Read out N print( diff --git a/demonstrations_v2/tutorial_photonics/metadata.json b/demonstrations_v2/tutorial_photonics/metadata.json index fe69c53263..850cabed1d 100644 --- a/demonstrations_v2/tutorial_photonics/metadata.json +++ b/demonstrations_v2/tutorial_photonics/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2022-05-31T00:00:00+00:00", - "dateOfLastModification": "2025-12-19T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Quantum Hardware", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_post-variational_quantum_neural_networks/demo.py b/demonstrations_v2/tutorial_post-variational_quantum_neural_networks/demo.py index 77e5e2500b..6485c2677e 100644 --- a/demonstrations_v2/tutorial_post-variational_quantum_neural_networks/demo.py +++ b/demonstrations_v2/tutorial_post-variational_quantum_neural_networks/demo.py @@ -83,7 +83,7 @@ # testing. # -import pennylane as qml +import pennylane as qp from pennylane import numpy as np import jax from jax import numpy as jnp @@ -182,35 +182,35 @@ def feature_map(features): # Apply Hadamard gates to all qubits to create an equal superposition state for i in range(len(features[0])): - qml.Hadamard(i) + qp.Hadamard(i) # Apply angle embeddings based on the feature values for i in range(len(features)): # For odd-indexed features, use Z-rotation in the angle embedding if i % 2: - qml.AngleEmbedding(features=features[i], wires=range(8), rotation="Z") + qp.AngleEmbedding(features=features[i], wires=range(8), rotation="Z") # For even-indexed features, use X-rotation in the angle embedding else: - qml.AngleEmbedding(features=features[i], wires=range(8), rotation="X") + qp.AngleEmbedding(features=features[i], wires=range(8), rotation="X") # Define the ansatz (quantum circuit ansatz) for parameterized quantum operations def ansatz(params): # Apply RY rotations with the first set of parameters for i in range(8): - qml.RY(params[i], wires=i) + qp.RY(params[i], wires=i) # Apply CNOT gates with adjacent qubits (cyclically connected) to create entanglement for i in range(8): - qml.CNOT(wires=[(i - 1) % 8, (i) % 8]) + qp.CNOT(wires=[(i - 1) % 8, (i) % 8]) # Apply RY rotations with the second set of parameters for i in range(8): - qml.RY(params[i + 8], wires=i) + qp.RY(params[i + 8], wires=i) # Apply CNOT gates with qubits in reverse order (cyclically connected) # to create additional entanglement for i in range(8): - qml.CNOT(wires=[(8 - 2 - i) % 8, (8 - i - 1) % 8]) + qp.CNOT(wires=[(8 - 2 - i) % 8, (8 - i - 1) % 8]) ###################################################################### # Variational approach # --------------------- @@ -222,14 +222,14 @@ def ansatz(params): # ansatz. # -dev = qml.device("default.qubit", wires=8) +dev = qp.device("default.qubit", wires=8) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(params, features): feature_map(features) ansatz(params) - return qml.expval(qml.PauliZ(0)) + return qp.expval(qp.PauliZ(0)) def variational_classifier(weights, bias, x): @@ -237,7 +237,7 @@ def variational_classifier(weights, bias, x): def square_loss(labels, predictions): - return np.mean((labels - qml.math.stack(predictions)) ** 2) + return np.mean((labels - qp.math.stack(predictions)) ** 2) def accuracy(labels, predictions): @@ -355,10 +355,10 @@ def generate_paulis(identities: int, paulis: int, output: str, qubits: int, loca print(str(locality) + "-local: ") # Define a quantum device with 8 qubits using the default simulator. - dev = qml.device("default.qubit", wires=8) + dev = qp.device("default.qubit", wires=8) # Define a quantum node (qnode) with the quantum circuit that will be executed on the device. - @qml.qnode(dev) + @qp.qnode(dev) def circuit(features): # Generate all possible Pauli strings for the given locality. measurements = local_pauli_group(8, locality) @@ -367,7 +367,7 @@ def circuit(features): feature_map(features) # Measure the expectation values of the generated Pauli operators. - return [qml.expval(qml.pauli.string_to_pauli_word(measurement)) for measurement in measurements] + return [qp.expval(qp.pauli.string_to_pauli_word(measurement)) for measurement in measurements] # Vectorize the quantum circuit function to apply it to multiple data points in parallel. vcircuit = jax.vmap(circuit) @@ -498,14 +498,14 @@ def generate_shifts(thetas: int, order: int): # n_wires = 8 -dev = qml.device("default.qubit", wires=n_wires) +dev = qp.device("default.qubit", wires=n_wires) @jax.jit -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def circuit(features, params, n_wires=8): feature_map(features) ansatz(params) - return qml.expval(qml.PauliZ(0)) + return qp.expval(qp.PauliZ(0)) ###################################################################### # For each image sample, we measure the outputs of each parameterised circuit for each feature, and @@ -612,20 +612,20 @@ def circuit(features, params, n_wires=8): print("Locality: " + str(locality) + " Order: " + str(order)) # Define a quantum device with 8 qubits using the default simulator. - dev = qml.device("default.qubit", wires=8) + dev = qp.device("default.qubit", wires=8) # Generate the parameter shifts required for the given derivative order and transpose them. params = deriv_params(16, order).T # Define a quantum node (qnode) with the quantum circuit that will be executed on the device. - @qml.qnode(dev) + @qp.qnode(dev) def circuit(features, params): # Generate the Pauli group for the given locality. measurements = local_pauli_group(8, locality) feature_map(features) ansatz(params) # Measure the expectation values of the generated Pauli operators. - return [qml.expval(qml.pauli.string_to_pauli_word(measurement)) for measurement in measurements] + return [qp.expval(qp.pauli.string_to_pauli_word(measurement)) for measurement in measurements] # Vectorize the quantum circuit function to apply it to multiple data points in parallel. vcircuit = jax.vmap(circuit) diff --git a/demonstrations_v2/tutorial_post-variational_quantum_neural_networks/metadata.json b/demonstrations_v2/tutorial_post-variational_quantum_neural_networks/metadata.json index 5b17127241..d0f17a8a10 100644 --- a/demonstrations_v2/tutorial_post-variational_quantum_neural_networks/metadata.json +++ b/demonstrations_v2/tutorial_post-variational_quantum_neural_networks/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-10-07T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Machine Learning", "Algorithms", diff --git a/demonstrations_v2/tutorial_pulse_programming101/demo.py b/demonstrations_v2/tutorial_pulse_programming101/demo.py index f6cf3c50a1..55ae9b705b 100644 --- a/demonstrations_v2/tutorial_pulse_programming101/demo.py +++ b/demonstrations_v2/tutorial_pulse_programming101/demo.py @@ -59,7 +59,7 @@ The Hamiltonian depends on the set of parameters :math:`p = \{p_i\}.` One way to do this in PennyLane is in the following way: """ -import pennylane as qml +import pennylane as qp import numpy as np import jax.numpy as jnp import jax @@ -80,7 +80,7 @@ def f2(p, t): return p[0] * jnp.sin(p[1] * t) -Ht = f1 * qml.PauliX(0) + f2 * qml.PauliY(1) +Ht = f1 * qp.PauliX(0) + f2 * qp.PauliY(1) ############################################################################## # This constructs a :class:`~pennylane.pulse.ParametrizedHamiltonian`. Note that the ``callable`` functions ``f1`` and ``f2`` @@ -95,16 +95,16 @@ def f2(p, t): ############################################################################## # We can construct general Hamiltonians of the form :math:`\sum_i H_i^d + \sum_i f_i(p_i, t) H_i` -# using :func:`qml.dot `. Such a time-dependent Hamiltonian consists of time-independent drift terms :math:`H_i^d` +# using :func:`qp.dot `. Such a time-dependent Hamiltonian consists of time-independent drift terms :math:`H_i^d` # and time-dependent control terms :math:`f_i(p_i, t) H_i` with scalar complex-valued functions :math:`f_i(p, t).` # In the following we are going to construct :math:`\sum_i X_i X_{i+1} + \sum_i f_i(p_i, t) Z_i` with :math:`f_i(p_i, t) = \sin(p_i^0 t) + \sin(p_i^1 t) \forall i` as an example: coeffs = [1.0] * 2 coeffs += [lambda p, t: jnp.sin(p[0] * t) + jnp.sin(p[1] * t) for _ in range(3)] -ops = [qml.PauliX(i) @ qml.PauliX(i + 1) for i in range(2)] -ops += [qml.PauliZ(i) for i in range(3)] +ops = [qp.PauliX(i) @ qp.PauliX(i + 1) for i in range(2)] +ops += [qp.PauliZ(i) for i in range(3)] -Ht = qml.dot(coeffs, ops) +Ht = qp.dot(coeffs, ops) # random coefficients key = jax.random.PRNGKey(777) @@ -136,17 +136,17 @@ def f2(p, t): # gate :math:`U(t_0, t_1),` which implicitly depends on the parameters ``p`.` The objective of the program # is then to compute the expectation value of some objective Hamiltonian ``H_obj`` (here :math:`\sum_i Z_i` as a simple example). -dev = qml.device("default.qubit", range(4)) +dev = qp.device("default.qubit", range(4)) ts = jnp.array([0.0, 3.0]) -H_obj = sum([qml.PauliZ(i) for i in range(4)]) +H_obj = sum([qp.PauliZ(i) for i in range(4)]) @jax.jit -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def qnode(params): - qml.evolve(Ht)(params, ts) - return qml.expval(H_obj) + qp.evolve(Ht)(params, ts) + return qp.expval(H_obj) print(qnode(params)) @@ -181,7 +181,7 @@ def qnode(params): # by providing a ``timespan`` argument which is expected to be either a total time (``float``) or a start and end time (``tuple``). timespan = 10.0 -coeffs = [qml.pulse.pwc(timespan) for _ in range(2)] +coeffs = [qp.pulse.pwc(timespan) for _ in range(2)] ############################################################################## # This creates a callable with signature ``(p, t)`` that returns ``p[int(len(p)*t/duration)]``, such that the passed parameters are the function values @@ -208,12 +208,12 @@ def qnode(params): ############################################################################## # We can use these callables as before to construct a :func:`~.pennylane.pulse.ParametrizedHamiltonian`. -ops = [qml.PauliX(i) for i in range(2)] -H = qml.pulse.ParametrizedHamiltonian(coeffs, ops) +ops = [qp.PauliX(i) for i in range(2)] +H = qp.pulse.ParametrizedHamiltonian(coeffs, ops) print(H(theta, 0.5)) ############################################################################## -# Note that this construction is equivalent to using :func:`qml.dot `. +# Note that this construction is equivalent to using :func:`qp.dot `. # # Variational quantum eigensolver with pulse programming # ------------------------------------------------------ @@ -223,12 +223,12 @@ def qnode(params): # We are using :math:`\text{HeH}^+` as a simple example and load it from the `PennyLane quantum datasets `_ website. # We are going to use the tapered Hamiltonian, which makes use of symmetries to reduce the number of qubits, see :doc:`demos/tutorial_qubit_tapering` for details. -data = qml.data.load("qchem", molname="HeH+", basis="STO-3G", bondlength=1.5)[0] +data = qp.data.load("qchem", molname="HeH+", basis="STO-3G", bondlength=1.5)[0] H_obj = data.tapered_hamiltonian H_obj_coeffs, H_obj_ops = H_obj.terms() # casting the Hamiltonian coefficients to a jax Array -H_obj = qml.Hamiltonian(jnp.array(H_obj_coeffs), H_obj_ops) +H_obj = qp.Hamiltonian(jnp.array(H_obj_coeffs), H_obj_ops) E_exact = data.fci_energy n_wires = len(H_obj.wires) @@ -244,18 +244,18 @@ def qnode(params): def a(wires): - return 0.5 * qml.PauliX(wires) + 0.5j * qml.PauliY(wires) + return 0.5 * qp.PauliX(wires) + 0.5j * qp.PauliY(wires) def ad(wires): - return 0.5 * qml.PauliX(wires) - 0.5j * qml.PauliY(wires) + return 0.5 * qp.PauliX(wires) - 0.5j * qp.PauliY(wires) omega = 2 * jnp.pi * jnp.array([4.8080, 4.8333]) g = 2 * jnp.pi * jnp.array([0.01831, 0.02131]) -H_D = qml.dot(omega, [ad(i) @ a(i) for i in range(n_wires)]) -H_D += qml.dot( +H_D = qp.dot(omega, [ad(i) @ a(i) for i in range(n_wires)]) +H_D += qp.dot( g, [ad(i) @ a((i + 1) % n_wires) + ad((i + 1) % n_wires) @ a(i) for i in range(n_wires)], ) @@ -288,7 +288,7 @@ def normalize(x): def drive_field(T, omega, sign=1.0): def wrapped(p, t): # The first len(p)-1 values of the trainable params p characterize the pwc function - amp = qml.pulse.pwc(T)(p[:-1], t) + amp = qp.pulse.pwc(T)(p[:-1], t) # The amplitude is normalized to maximally reach +/-20MHz (0.02GHz) amp = 0.02 * normalize(amp) @@ -308,7 +308,7 @@ def wrapped(p, t): ops = [a(i) for i in range(n_wires)] ops += [ad(i) for i in range(n_wires)] -H_C = qml.dot(fs, ops) +H_C = qp.dot(fs, ops) ############################################################################## # Overall, we end up with the time-dependent parametrized Hamiltonian :math:`H(p, t) = H_D + H_C(p, t)` @@ -323,15 +323,15 @@ def wrapped(p, t): # We need to wrap the ``qnode`` in a function so that we can convert the expectation value to a real number. # This will enable use to make use of gradient descent methods that require real-valued loss functions. -dev = qml.device("default.qubit", wires=range(n_wires)) +dev = qp.device("default.qubit", wires=range(n_wires)) def qnode(theta, t=duration): - @qml.qnode(dev) + @qp.qnode(dev) def _qnode_inner(theta, t=duration): - qml.BasisState(jnp.array(data.tapered_hf_state), wires=H_obj.wires) - qml.evolve(H_pulse)(params=(*theta, *theta), t=t) - return qml.expval(H_obj) + qp.BasisState(jnp.array(data.tapered_hf_state), wires=H_obj.wires) + qp.evolve(H_pulse)(params=(*theta, *theta), t=t) + return qp.expval(H_obj) expectation_value = _qnode_inner(theta, t) # Execute the qnode return jnp.real(expectation_value) # Typecast to real number diff --git a/demonstrations_v2/tutorial_pulse_programming101/metadata.json b/demonstrations_v2/tutorial_pulse_programming101/metadata.json index 065394b0d8..b421e10003 100644 --- a/demonstrations_v2/tutorial_pulse_programming101/metadata.json +++ b/demonstrations_v2/tutorial_pulse_programming101/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-03-08T00:00:00+00:00", - "dateOfLastModification": "2025-12-10T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Hardware", "Quantum Computing", diff --git a/demonstrations_v2/tutorial_qaoa_intro/demo.py b/demonstrations_v2/tutorial_qaoa_intro/demo.py index 8c86f00dae..508580e713 100644 --- a/demonstrations_v2/tutorial_qaoa_intro/demo.py +++ b/demonstrations_v2/tutorial_qaoa_intro/demo.py @@ -79,9 +79,9 @@ # In PennyLane, this is implemented using the :func:`~.pennylane.ApproxTimeEvolution` # template. For example, let's say we have the following Hamiltonian: -import pennylane as qml +import pennylane as qp -H = qml.Hamiltonian([1, 1, 0.5], [qml.PauliX(0), qml.PauliZ(1), qml.PauliX(0) @ qml.PauliX(1)]) +H = qp.Hamiltonian([1, 1, 0.5], [qp.PauliX(0), qp.PauliZ(1), qp.PauliX(0) @ qp.PauliX(1)]) print(H) @@ -90,19 +90,19 @@ # We can implement the approximate time-evolution operator corresponding to this # Hamiltonian: -dev = qml.device("default.qubit", wires=2) +dev = qp.device("default.qubit", wires=2) t = 1 n = 2 -@qml.qnode(dev) +@qp.qnode(dev) def circuit(): - qml.ApproxTimeEvolution(H, t, n) - return [qml.expval(qml.PauliZ(i)) for i in range(2)] + qp.ApproxTimeEvolution(H, t, n) + return [qp.expval(qp.PauliZ(i)) for i in range(2)] -print(qml.draw(circuit, level="device")()) +print(qp.draw(circuit, level="device")()) ###################################################################### # Layering circuits @@ -139,18 +139,18 @@ def circuit(): def circ(theta): - qml.RX(theta, wires=0) - qml.Hadamard(wires=1) - qml.CNOT(wires=[0, 1]) + qp.RX(theta, wires=0) + qp.Hadamard(wires=1) + qp.CNOT(wires=[0, 1]) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(param): circ(param) - return [qml.expval(qml.PauliZ(i)) for i in range(2)] + return [qp.expval(qp.PauliZ(i)) for i in range(2)] -print(qml.draw(circuit)(0.5)) +print(qp.draw(circuit)(0.5)) ###################################################################### # @@ -158,13 +158,13 @@ def circuit(param): # -@qml.qnode(dev) +@qp.qnode(dev) def circuit(params, **kwargs): - qml.layer(circ, 3, params) - return [qml.expval(qml.PauliZ(i)) for i in range(2)] + qp.layer(circ, 3, params) + return [qp.expval(qp.PauliZ(i)) for i in range(2)] -print(qml.draw(circuit)([0.3, 0.4, 0.5])) +print(qp.draw(circuit)([0.3, 0.4, 0.5])) ###################################################################### # @@ -308,8 +308,8 @@ def qaoa_layer(gamma, alpha): def circuit(params, **kwargs): for w in wires: - qml.Hadamard(wires=w) - qml.layer(qaoa_layer, depth, params[0], params[1]) + qp.Hadamard(wires=w) + qp.layer(qaoa_layer, depth, params[0], params[1]) ###################################################################### @@ -325,13 +325,13 @@ def circuit(params, **kwargs): # PennyLane-Qulacs plugin to run the circuit on the Qulacs simulator: # -dev = qml.device("qulacs.simulator", wires=wires) +dev = qp.device("qulacs.simulator", wires=wires) -@qml.qnode(dev) +@qp.qnode(dev) def cost_function(params): circuit(params) - return qml.expval(cost_h) + return qp.expval(cost_h) ###################################################################### @@ -341,7 +341,7 @@ def cost_function(params): # parameters: -optimizer = qml.GradientDescentOptimizer() +optimizer = qp.GradientDescentOptimizer() steps = 70 params = np.array([[0.5, 0.5], [0.5, 0.5]], requires_grad=True) @@ -375,10 +375,10 @@ def cost_function(params): # -@qml.qnode(dev) +@qp.qnode(dev) def probability_circuit(gamma, alpha): circuit([gamma, alpha]) - return qml.probs(wires=wires) + return qp.probs(wires=wires) probs = probability_circuit(params[0], params[1]) @@ -451,14 +451,14 @@ def qaoa_layer(gamma, alpha): def circuit(params, **kwargs): for w in wires: - qml.Hadamard(wires=w) - qml.layer(qaoa_layer, depth, params[0], params[1]) + qp.Hadamard(wires=w) + qp.layer(qaoa_layer, depth, params[0], params[1]) -@qml.qnode(dev) +@qp.qnode(dev) def cost_function(params): circuit(params) - return qml.expval(new_cost_h) + return qp.expval(new_cost_h) params = np.array([[0.5, 0.5], [0.5, 0.5]], requires_grad=True) @@ -476,10 +476,10 @@ def cost_function(params): # -@qml.qnode(dev) +@qp.qnode(dev) def probability_circuit(gamma, alpha): circuit([gamma, alpha]) - return qml.probs(wires=wires) + return qp.probs(wires=wires) probs = probability_circuit(params[0], params[1]) diff --git a/demonstrations_v2/tutorial_qaoa_intro/metadata.json b/demonstrations_v2/tutorial_qaoa_intro/metadata.json index dac985e37e..e1b5db2eb5 100644 --- a/demonstrations_v2/tutorial_qaoa_intro/metadata.json +++ b/demonstrations_v2/tutorial_qaoa_intro/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2020-11-18T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_qaoa_maxcut/demo.py b/demonstrations_v2/tutorial_qaoa_maxcut/demo.py index c9bcc2b671..ff757b58ae 100644 --- a/demonstrations_v2/tutorial_qaoa_maxcut/demo.py +++ b/demonstrations_v2/tutorial_qaoa_maxcut/demo.py @@ -130,7 +130,7 @@ version of NumPy. """ -import pennylane as qml +import pennylane as qp from pennylane import numpy as np np.random.seed(42) @@ -153,15 +153,15 @@ # unitary operator U_B with parameter beta def U_B(beta): for wire in range(n_wires): - qml.RX(2 * beta, wires=wire) + qp.RX(2 * beta, wires=wire) # unitary operator U_C with parameter gamma def U_C(gamma): for edge in graph: - qml.CNOT(wires=edge) - qml.RZ(gamma, wires=edge[1]) - qml.CNOT(wires=edge) + qp.CNOT(wires=edge) + qp.RZ(gamma, wires=edge[1]) + qp.CNOT(wires=edge) # Could also do # IsingZZ(gamma, wires=edge) @@ -180,7 +180,7 @@ def bitstring_to_int(bit_string_sample): # ~~~~~~~ # Next, we create a quantum device with 4 qubits. -dev = qml.device("lightning.qubit", wires=n_wires) +dev = qp.device("lightning.qubit", wires=n_wires) ############################################################################## # We also require a quantum node which will apply the operators according to the angle parameters, @@ -194,12 +194,12 @@ def bitstring_to_int(bit_string_sample): # by setting ``return_samples=True``. -@qml.set_shots(20) -@qml.qnode(dev) +@qp.set_shots(20) +@qp.qnode(dev) def circuit(gammas, betas, return_samples=False): # apply Hadamards to get the n qubit |+> state for wire in range(n_wires): - qml.Hadamard(wires=wire) + qp.Hadamard(wires=wire) # p instances of unitary operators for gamma, beta in zip(gammas, betas): U_C(gamma) @@ -207,10 +207,10 @@ def circuit(gammas, betas, return_samples=False): if return_samples: # sample bitstrings to obtain cuts - return qml.sample() + return qp.sample() # during the optimization phase we are evaluating the objective using expval - C = qml.sum(*(qml.Z(w1) @ qml.Z(w2) for w1, w2 in graph)) - return qml.expval(C) + C = qp.sum(*(qp.Z(w1) @ qp.Z(w2) for w1, w2 in graph)) + return qp.expval(C) def objective(params): @@ -237,7 +237,7 @@ def qaoa_maxcut(n_layers=1): init_params = 0.01 * np.random.rand(2, n_layers, requires_grad=True) # initialize optimizer: Adagrad works well empirically - opt = qml.AdagradOptimizer(stepsize=0.5) + opt = qp.AdagradOptimizer(stepsize=0.5) # optimize parameters in objective params = init_params.copy() @@ -248,7 +248,7 @@ def qaoa_maxcut(n_layers=1): print(f"Objective after step {i+1:3d}: {-objective(params): .7f}") # sample 100 bitstrings by setting return_samples=True and the QNode shot count to 100 - bitstrings = qml.set_shots(circuit, shots=100)(*params, return_samples=True) + bitstrings = qp.set_shots(circuit, shots=100)(*params, return_samples=True) # convert the samples bitstrings to integers sampled_ints = [bitstring_to_int(string) for string in bitstrings] diff --git a/demonstrations_v2/tutorial_qaoa_maxcut/metadata.json b/demonstrations_v2/tutorial_qaoa_maxcut/metadata.json index f749ff5587..6146fc0749 100644 --- a/demonstrations_v2/tutorial_qaoa_maxcut/metadata.json +++ b/demonstrations_v2/tutorial_qaoa_maxcut/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2019-10-11T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_qcbm/demo.py b/demonstrations_v2/tutorial_qcbm/demo.py index 375c2dc519..9a497502d3 100644 --- a/demonstrations_v2/tutorial_qcbm/demo.py +++ b/demonstrations_v2/tutorial_qcbm/demo.py @@ -233,23 +233,23 @@ def get_bars_and_stripes(n): # will act as a generative model, thus, realize a Born machine. # -import pennylane as qml +import pennylane as qp np.random.seed(42) n_qubits = size -dev = qml.device("default.qubit", wires=n_qubits) +dev = qp.device("default.qubit", wires=n_qubits) n_layers = 6 -wshape = qml.StronglyEntanglingLayers.shape(n_layers=n_layers, n_wires=n_qubits) +wshape = qp.StronglyEntanglingLayers.shape(n_layers=n_layers, n_wires=n_qubits) weights = np.random.random(size=wshape) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(weights): - qml.StronglyEntanglingLayers(weights=weights, ranges=[1] * n_layers, wires=range(n_qubits)) - return qml.probs() + qp.StronglyEntanglingLayers(weights=weights, ranges=[1] * n_layers, wires=range(n_qubits)) + return qp.probs() jit_circuit = jax.jit(circuit) @@ -384,13 +384,13 @@ def update_step(params, opt_state): def circuit(weights): - qml.StronglyEntanglingLayers(weights=weights, ranges=[1] * n_layers, wires=range(n_qubits)) - return qml.sample() + qp.StronglyEntanglingLayers(weights=weights, ranges=[1] * n_layers, wires=range(n_qubits)) + return qp.sample() for N in [2000, 20000]: - dev = qml.device("default.qubit", wires=n_qubits) - circ = qml.set_shots(qml.QNode(circuit, device=dev), shots = N) + dev = qp.device("default.qubit", wires=n_qubits) + circ = qp.set_shots(qp.QNode(circuit, device=dev), shots = N) preds = circ(weights) mask = np.any(np.all(preds[:, None] == data, axis=2), axis=1) # Check for row-wise equality chi = np.sum(mask) / N @@ -462,25 +462,25 @@ def mixture_gaussian_pdf(x, mus, sigmas): # we will create an ansatz and measure probabilities. # -dev = qml.device("default.qubit", wires=n_qubits) +dev = qp.device("default.qubit", wires=n_qubits) n_layers = 4 -wshape = qml.StronglyEntanglingLayers.shape(n_layers=n_layers, n_wires=n_qubits) +wshape = qp.StronglyEntanglingLayers.shape(n_layers=n_layers, n_wires=n_qubits) weights = np.random.random(size=wshape) -@qml.set_shots(N) -@qml.qnode(dev) +@qp.set_shots(N) +@qp.qnode(dev) def circuit(weights): - qml.StronglyEntanglingLayers( + qp.StronglyEntanglingLayers( weights=weights, ranges=[1] * n_layers, wires=range(n_qubits) ) - return qml.probs() + return qp.probs() jit_circuit = jax.jit(circuit) -qml.draw_mpl(circuit, level="device")(weights) +qp.draw_mpl(circuit, level="device")(weights) plt.show() ###################################################################### diff --git a/demonstrations_v2/tutorial_qcbm/metadata.json b/demonstrations_v2/tutorial_qcbm/metadata.json index bc9fd2a217..8dede33249 100644 --- a/demonstrations_v2/tutorial_qcbm/metadata.json +++ b/demonstrations_v2/tutorial_qcbm/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-05-22T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Quantum Machine Learning" ], diff --git a/demonstrations_v2/tutorial_qchem_external/demo.py b/demonstrations_v2/tutorial_qchem_external/demo.py index 0e37c0aef2..79bab90bbf 100644 --- a/demonstrations_v2/tutorial_qchem_external/demo.py +++ b/demonstrations_v2/tutorial_qchem_external/demo.py @@ -46,16 +46,16 @@ backend as: """ -import pennylane as qml +import pennylane as qp import numpy as np symbols = ["H", "O", "H"] geometry = np.array([[-0.0399, -0.0038, 0.0000], [ 1.5780, 0.8540, 0.0000], [ 2.7909, -0.5159, 0.0000]]) -molecule = qml.qchem.Molecule(symbols, geometry) +molecule = qp.qchem.Molecule(symbols, geometry) -H, qubits = qml.qchem.molecular_hamiltonian(molecule, method="pyscf") +H, qubits = qp.qchem.molecular_hamiltonian(molecule, method="pyscf") print(H) ############################################################################## @@ -72,7 +72,7 @@ from openfermion.ops import QubitOperator H = 0.1 * QubitOperator('X0 X1') + 0.2 * QubitOperator('Z0') -H = qml.qchem.import_operator(H) +H = qp.qchem.import_operator(H) print(f'Type: \n {type(H)} \n') print(f'Hamiltonian: \n {H}') @@ -135,13 +135,13 @@ # for creating and manipulating # :doc:`fermionic operators `: -H_fermionic = qml.qchem.fermionic_observable(core_constant, one_mo, two_mo) +H_fermionic = qp.qchem.fermionic_observable(core_constant, one_mo, two_mo) ############################################################################## # The Hamiltonian can be mapped to the qubit basis with the :func:`~.pennylane.jordan_wigner` # function: -H = qml.jordan_wigner(H_fermionic) +H = qp.jordan_wigner(H_fermionic) ############################################################################## # Importing initial states @@ -173,7 +173,7 @@ # Then, we use the :func:`~.pennylane.qchem.import_state` function to obtain the # state vector. -state = qml.qchem.import_state(mycc) +state = qp.qchem.import_state(mycc) print(state) ############################################################################## @@ -190,14 +190,14 @@ from openfermion import FermionOperator openfermion_op = 0.5 * FermionOperator('0^ 2') + FermionOperator('0 2^') -pennylane_op = qml.from_openfermion(openfermion_op) +pennylane_op = qp.from_openfermion(openfermion_op) print(pennylane_op) ############################################################################## # The resulting operator can be used in PennyLane like any other fermionic object. We now take this # PennyLane fermionic operator and convert it back to an OpenFermion operator. -openfermion_op = qml.to_openfermion(pennylane_op) +openfermion_op = qp.to_openfermion(pennylane_op) print(openfermion_op) ############################################################################## diff --git a/demonstrations_v2/tutorial_qchem_external/metadata.json b/demonstrations_v2/tutorial_qchem_external/metadata.json index fced5a817b..1d83ddf04f 100644 --- a/demonstrations_v2/tutorial_qchem_external/metadata.json +++ b/demonstrations_v2/tutorial_qchem_external/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-01-03T00:00:00+00:00", - "dateOfLastModification": "2026-01-14T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Chemistry", "Devices and Performance" diff --git a/demonstrations_v2/tutorial_qft/demo.py b/demonstrations_v2/tutorial_qft/demo.py index 550a5fd14c..a8c5bb5806 100644 --- a/demonstrations_v2/tutorial_qft/demo.py +++ b/demonstrations_v2/tutorial_qft/demo.py @@ -33,7 +33,7 @@ """ from scipy.linalg import dft -import pennylane as qml +import pennylane as qp import numpy as np n = 2 @@ -41,7 +41,7 @@ print("DFT matrix for n = 2:\n") print(np.round(1 / np.sqrt(2 ** n) * dft(2 ** n), 2)) -qft_inverse = qml.adjoint(qml.QFT([0,1])) +qft_inverse = qp.adjoint(qp.QFT([0,1])) print("\n inverse QFT matrix for n = 2:\n") print(np.round(qft_inverse.matrix(), 2)) @@ -90,19 +90,19 @@ # In PennyLane, we rearrange the qubits in the opposite ordering; that is why we # apply SWAP gates at the end. Let's see how the decomposition looks like using the drawer: -import pennylane as qml +import pennylane as qp from functools import partial import matplotlib.pyplot as plt plt.style.use('pennylane.drawer.plot') # This line is to expand the circuit to see the operators -@partial(qml.transforms.decompose, max_expansion=1) +@partial(qp.transforms.decompose, max_expansion=1) def circuit(): - qml.QFT(wires=range(4)) + qp.QFT(wires=range(4)) -qml.draw_mpl(circuit, decimals = 2, style = "pennylane")() +qp.draw_mpl(circuit, decimals = 2, style = "pennylane")() plt.show() ############################################# @@ -124,17 +124,17 @@ def circuit(): def prep(): """quntum function that prepares the state.""" - qml.PauliX(wires=0) + qp.PauliX(wires=0) for wire in range(1, 6): - qml.Hadamard(wires=wire) - qml.ControlledSequence(qml.PhaseShift(-2 * np.pi / 10, wires=0), control=range(1, 6)) - qml.PauliX(wires=0) + qp.Hadamard(wires=wire) + qp.ControlledSequence(qp.PhaseShift(-2 * np.pi / 10, wires=0), control=range(1, 6)) + qp.PauliX(wires=0) -dev = qml.device("default.qubit") -@qml.qnode(dev) +dev = qp.device("default.qubit") +@qp.qnode(dev) def circuit(): prep() - return qml.state() + return qp.state() state = circuit().real[:32] @@ -149,12 +149,12 @@ def circuit(): # which is able to transform the state into the frequency domain. This is shown in the code below: # -@qml.qnode(dev) +@qp.qnode(dev) def circuit(): prep() - qml.QFT(wires=range(1, 6)) + qp.QFT(wires=range(1, 6)) - return qml.probs(wires=range(1, 6)) + return qp.probs(wires=range(1, 6)) state = circuit()[:32] diff --git a/demonstrations_v2/tutorial_qft/metadata.json b/demonstrations_v2/tutorial_qft/metadata.json index e7d0474270..981be66533 100644 --- a/demonstrations_v2/tutorial_qft/metadata.json +++ b/demonstrations_v2/tutorial_qft/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-04-16T00:00:00+00:00", - "dateOfLastModification": "2025-12-19T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Algorithms", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_qft_and_groups/demo.py b/demonstrations_v2/tutorial_qft_and_groups/demo.py index 939a835451..8a47e89cac 100644 --- a/demonstrations_v2/tutorial_qft_and_groups/demo.py +++ b/demonstrations_v2/tutorial_qft_and_groups/demo.py @@ -227,7 +227,7 @@ def g_hat(k): # This works because the Fourier transform, if normalised appropriately, is a unitary transform! # # Let us verify this by comparing the DFT of a function, as coded up above, with the result of a quantum circuit -# that implements ``qml.QFT``. However, now we need a function that, written as a vector, can be interpreted +# that implements ``qp.QFT``. However, now we need a function that, written as a vector, can be interpreted # as a normalised quantum state. We therefore apply a slight modification to our function ``f`` from before. # @@ -249,16 +249,16 @@ def h_hat(k): # the output state vector from the simulator. # -import pennylane as qml +import pennylane as qp -dev = qml.device("default.qubit", wires=4, shots=None) +dev = qp.device("default.qubit", wires=4, shots=None) -@qml.qnode(dev) +@qp.qnode(dev) def qft(state): """Prepare a state \sum_x f(x) |x> and apply the discrete Fourier transform.""" - qml.StatePrep(state, wires=range(4)) - qml.QFT(wires=range(4)) - return qml.state() + qp.StatePrep(state, wires=range(4)) + qp.QFT(wires=range(4)) + return qp.state() ##################################################################### @@ -272,7 +272,7 @@ def qft(state): print("QFT and DFT coincide:", np.allclose(h_hat_state, h_hat_vec)) ##################################################################### -# But of course, ``qml.QFT`` only implements the Fourier transform with respect to the group :math:`Z_N`, which +# But of course, ``qp.QFT`` only implements the Fourier transform with respect to the group :math:`Z_N`, which # interprets computational basis states as integers. # As mentioned before, we can alternatively interpret bit strings as a collection of binary variables, which changes the group # to :math:`Z_2^n`. Both map into a Fourier basis, but with respect a different @@ -280,13 +280,13 @@ def qft(state): # -@qml.qnode(dev) +@qp.qnode(dev) def qft2(state): """Prepare a state \sum_x f(x) |x> and apply the Fourier transform over Z_2^4.""" - qml.StatePrep(state, wires=range(4)) + qp.StatePrep(state, wires=range(4)) for i in range(4): - qml.Hadamard(wires=i) - return qml.state() + qp.Hadamard(wires=i) + return qp.state() h_hat_state2 = qft2(h_vec) print("QFTs over different groups coincide:", np.allclose(h_hat_state, h_hat_state2)) diff --git a/demonstrations_v2/tutorial_qft_and_groups/metadata.json b/demonstrations_v2/tutorial_qft_and_groups/metadata.json index b018708fb9..1cf6d91b16 100644 --- a/demonstrations_v2/tutorial_qft_and_groups/metadata.json +++ b/demonstrations_v2/tutorial_qft_and_groups/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2025-09-18T10:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Algorithms" ], diff --git a/demonstrations_v2/tutorial_qft_arithmetics/demo.py b/demonstrations_v2/tutorial_qft_arithmetics/demo.py index 4bf57edc8e..2d9110a3de 100644 --- a/demonstrations_v2/tutorial_qft_arithmetics/demo.py +++ b/demonstrations_v2/tutorial_qft_arithmetics/demo.py @@ -94,25 +94,25 @@ representation that helps better visualize and interpret quantum gates such as rotations. We can use -the :class:`qml.BasisEmbedding ` +the :class:`qp.BasisEmbedding ` template to obtain the binary representation in a simple way. Let's see how we would code the number :math:`6.` """ -import pennylane as qml +import pennylane as qp import matplotlib.pyplot as plt -dev = qml.device("default.qubit", wires=3) +dev = qp.device("default.qubit", wires=3) -@qml.compile -@qml.qnode(dev) +@qp.compile +@qp.qnode(dev) def basis_embedding_circuit(m): - qml.BasisEmbedding(m, wires=range(3)) - return qml.state() + qp.BasisEmbedding(m, wires=range(3)) + return qp.state() m = 6 # number to be encoded -qml.draw_mpl(basis_embedding_circuit, show_all_wires=True)(m) +qp.draw_mpl(basis_embedding_circuit, show_all_wires=True)(m) plt.show() ###################################################################### @@ -168,28 +168,28 @@ def basis_embedding_circuit(m): # Let's see how this process would look in PennyLane. # -import pennylane as qml +import pennylane as qp import numpy as np n_wires = 4 -dev = qml.device("default.qubit", wires=n_wires) +dev = qp.device("default.qubit", wires=n_wires) def add_k_fourier(k, wires): for j in range(len(wires)): - qml.RZ(k * np.pi / (2**j), wires=wires[j]) + qp.RZ(k * np.pi / (2**j), wires=wires[j]) -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def sum(m, k): - qml.BasisEmbedding(m, wires=range(n_wires)) # m encoding + qp.BasisEmbedding(m, wires=range(n_wires)) # m encoding - qml.QFT(wires=range(n_wires)) # step 1 + qp.QFT(wires=range(n_wires)) # step 1 add_k_fourier(k, range(n_wires)) # step 2 - qml.adjoint(qml.QFT)(wires=range(n_wires)) # step 3 + qp.adjoint(qp.QFT)(wires=range(n_wires)) # step 3 - return qml.sample() + return qp.sample() print(f"The ket representation of the sum of 3 and 4 is {sum(3,4)}") @@ -233,41 +233,41 @@ def sum(m, k): wires_k = [3, 4, 5] # qubits needed to encode k wires_solution = [6, 7, 8, 9] # qubits needed to encode the solution -dev = qml.device("default.qubit", wires=wires_m + wires_k + wires_solution) +dev = qp.device("default.qubit", wires=wires_m + wires_k + wires_solution) n_wires = len(dev.wires) # total number of qubits used def addition(wires_m, wires_k, wires_solution): # prepare solution qubits to counting - qml.QFT(wires=wires_solution) + qp.QFT(wires=wires_solution) # add m to the counter for i in range(len(wires_m)): - qml.ctrl(add_k_fourier, control=wires_m[i])(2 **(len(wires_m) - i - 1), wires_solution) + qp.ctrl(add_k_fourier, control=wires_m[i])(2 **(len(wires_m) - i - 1), wires_solution) # add k to the counter for i in range(len(wires_k)): - qml.ctrl(add_k_fourier, control=wires_k[i])(2 **(len(wires_k) - i - 1), wires_solution) + qp.ctrl(add_k_fourier, control=wires_k[i])(2 **(len(wires_k) - i - 1), wires_solution) # return to computational basis - qml.adjoint(qml.QFT)(wires=wires_solution) + qp.adjoint(qp.QFT)(wires=wires_solution) -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def sum2(m, k, wires_m, wires_k, wires_solution): # m and k codification - qml.BasisEmbedding(m, wires=wires_m) - qml.BasisEmbedding(k, wires=wires_k) + qp.BasisEmbedding(m, wires=wires_m) + qp.BasisEmbedding(k, wires=wires_k) # apply the addition circuit addition(wires_m, wires_k, wires_solution) - return qml.sample(wires=wires_solution) + return qp.sample(wires=wires_solution) print(f"The ket representation of the sum of 7 and 3 is " f"{sum2(7, 3, wires_m, wires_k, wires_solution)}") -qml.draw_mpl(sum2, show_all_wires=True)(7, 3, wires_m, wires_k, wires_solution) +qp.draw_mpl(sum2, show_all_wires=True)(7, 3, wires_m, wires_k, wires_solution) plt.show() ###################################################################### @@ -300,39 +300,39 @@ def sum2(m, k, wires_m, wires_k, wires_solution): wires_k = [3, 4, 5] # qubits needed to encode k wires_solution = [6, 7, 8, 9, 10] # qubits needed to encode the solution -dev = qml.device("default.qubit", wires=wires_m + wires_k + wires_solution) +dev = qp.device("default.qubit", wires=wires_m + wires_k + wires_solution) n_wires = len(dev.wires) def multiplication(wires_m, wires_k, wires_solution): # prepare sol-qubits to counting - qml.QFT(wires=wires_solution) + qp.QFT(wires=wires_solution) # add m to the counter for i in range(len(wires_k)): for j in range(len(wires_m)): coeff = 2 ** (len(wires_m) + len(wires_k) - i - j - 2) - qml.ctrl(add_k_fourier, control=[wires_k[i], wires_m[j]])(coeff, wires_solution) + qp.ctrl(add_k_fourier, control=[wires_k[i], wires_m[j]])(coeff, wires_solution) # return to computational basis - qml.adjoint(qml.QFT)(wires=wires_solution) + qp.adjoint(qp.QFT)(wires=wires_solution) -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def mul(m, k): # m and k codification - qml.BasisEmbedding(m, wires=wires_m) - qml.BasisEmbedding(k, wires=wires_k) + qp.BasisEmbedding(m, wires=wires_m) + qp.BasisEmbedding(k, wires=wires_k) # Apply multiplication multiplication(wires_m, wires_k, wires_solution) - return qml.sample(wires=wires_solution) + return qp.sample(wires=wires_solution) print(f"The ket representation of the multiplication of 3 and 7 is {mul(3,7)}") -qml.draw_mpl(mul, show_all_wires=True)(3, 7) +qp.draw_mpl(mul, show_all_wires=True)(3, 7) plt.show() @@ -375,32 +375,32 @@ def mul(m, k): wires_k = [3, 4, 5] # qubits needed to encode k wires_solution = [6, 7, 8, 9, 10] # qubits needed to encode the solution -dev = qml.device("default.qubit", wires=wires_m + wires_k + wires_solution) +dev = qp.device("default.qubit", wires=wires_m + wires_k + wires_solution) n_wires = len(dev.wires) -@qml.qnode(dev) +@qp.qnode(dev) def factorization(n, wires_m, wires_k, wires_solution): # Superposition of the input for wire in wires_m: - qml.Hadamard(wires=wire) + qp.Hadamard(wires=wire) for wire in wires_k: - qml.Hadamard(wires=wire) + qp.Hadamard(wires=wire) # Apply the multiplication multiplication(wires_m, wires_k, wires_solution) # Change sign of n - qml.FlipSign(n, wires=wires_solution) + qp.FlipSign(n, wires=wires_solution) # Uncompute multiplication - qml.adjoint(multiplication)(wires_m, wires_k, wires_solution) + qp.adjoint(multiplication)(wires_m, wires_k, wires_solution) # Apply Grover operator - qml.GroverOperator(wires=wires_m + wires_k) + qp.GroverOperator(wires=wires_m + wires_k) - return qml.probs(wires=wires_m) + return qp.probs(wires=wires_m) plt.bar(range(2 ** len(wires_m)), factorization(n, wires_m, wires_k, wires_solution)) diff --git a/demonstrations_v2/tutorial_qft_arithmetics/metadata.json b/demonstrations_v2/tutorial_qft_arithmetics/metadata.json index 026ea5158c..85db5b038d 100644 --- a/demonstrations_v2/tutorial_qft_arithmetics/metadata.json +++ b/demonstrations_v2/tutorial_qft_arithmetics/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2022-11-07T00:00:00+00:00", - "dateOfLastModification": "2025-11-05T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Getting Started", "Algorithms", diff --git a/demonstrations_v2/tutorial_qgrnn/demo.py b/demonstrations_v2/tutorial_qgrnn/demo.py index db0de46c7e..2275af712c 100644 --- a/demonstrations_v2/tutorial_qgrnn/demo.py +++ b/demonstrations_v2/tutorial_qgrnn/demo.py @@ -192,7 +192,7 @@ # -import pennylane as qml +import pennylane as qp from matplotlib import pyplot as plt from pennylane import numpy as np import scipy @@ -275,7 +275,7 @@ def create_hamiltonian_matrix(n_qubits, graph, weights, bias): interaction_term = 1 for qubit in range(0, n_qubits): if qubit in edge: - interaction_term = np.kron(interaction_term, qml.matrix(qml.PauliZ(0))) + interaction_term = np.kron(interaction_term, qp.matrix(qp.PauliZ(0))) else: interaction_term = np.kron(interaction_term, np.identity(2)) full_matrix += weights[i] * interaction_term @@ -285,8 +285,8 @@ def create_hamiltonian_matrix(n_qubits, graph, weights, bias): z_term = x_term = 1 for j in range(0, n_qubits): if j == i: - z_term = np.kron(z_term, qml.matrix(qml.PauliZ(0))) - x_term = np.kron(x_term, qml.matrix(qml.PauliX(0))) + z_term = np.kron(z_term, qp.matrix(qp.PauliZ(0))) + x_term = np.kron(x_term, qp.matrix(qp.PauliX(0))) else: z_term = np.kron(z_term, np.identity(2)) x_term = np.kron(x_term, np.identity(2)) @@ -374,7 +374,7 @@ def create_hamiltonian_matrix(n_qubits, graph, weights, bias): def state_evolve(hamiltonian, qubits, time): U = scipy.linalg.expm(-1j * hamiltonian * time) - qml.QubitUnitary(U, wires=qubits) + qp.QubitUnitary(U, wires=qubits) ###################################################################### @@ -404,15 +404,15 @@ def qgrnn_layer(weights, bias, qubits, graph, trotter_step): # Applies a layer of RZZ gates (based on a graph) for i, edge in enumerate(graph.edges): - qml.MultiRZ(2 * weights[i] * trotter_step, wires=(edge[0], edge[1])) + qp.MultiRZ(2 * weights[i] * trotter_step, wires=(edge[0], edge[1])) # Applies a layer of RZ gates for i, qubit in enumerate(qubits): - qml.RZ(2 * bias[i] * trotter_step, wires=qubit) + qp.RZ(2 * bias[i] * trotter_step, wires=qubit) # Applies a layer of RX gates for qubit in qubits: - qml.RX(2 * trotter_step, wires=qubit) + qp.RX(2 * trotter_step, wires=qubit) ###################################################################### @@ -431,10 +431,10 @@ def qgrnn_layer(weights, bias, qubits, graph, trotter_step): def swap_test(control, register1, register2): - qml.Hadamard(wires=control) + qp.Hadamard(wires=control) for reg1_qubit, reg2_qubit in zip(register1, register2): - qml.CSWAP(wires=(control, reg1_qubit, reg2_qubit)) - qml.Hadamard(wires=control) + qp.CSWAP(wires=(control, reg1_qubit, reg2_qubit)) + qp.Hadamard(wires=control) ###################################################################### @@ -482,7 +482,7 @@ def swap_test(control, register1, register2): def qgrnn(weights, bias, time=None): # Prepares the low energy state in the two registers - qml.StatePrep(np.kron(low_energy_state, low_energy_state), wires=reg1 + reg2) + qp.StatePrep(np.kron(low_energy_state, low_energy_state), wires=reg1 + reg2) # Evolves the first qubit register with the time-evolution circuit to # prepare a piece of quantum data @@ -497,7 +497,7 @@ def qgrnn(weights, bias, time=None): swap_test(control, reg1, reg2) # Returns the results of the SWAP test - return qml.expval(qml.PauliZ(control)) + return qp.expval(qp.PauliZ(control)) ###################################################################### @@ -551,14 +551,14 @@ def cost_function(weight_params, bias_params): # # Defines the new device -qgrnn_dev = qml.device("default.qubit", wires=2 * qubit_number + 1) +qgrnn_dev = qp.device("default.qubit", wires=2 * qubit_number + 1) # Defines the new QNode -qgrnn_qnode = qml.QNode(qgrnn, qgrnn_dev) +qgrnn_qnode = qp.QNode(qgrnn, qgrnn_dev) steps = 300 -optimizer = qml.AdamOptimizer(stepsize=0.5) +optimizer = qp.AdamOptimizer(stepsize=0.5) weights = rng.random(size=len(new_ising_graph.edges), requires_grad=True) - 0.5 bias = rng.random(size=qubit_number, requires_grad=True) - 0.5 diff --git a/demonstrations_v2/tutorial_qgrnn/metadata.json b/demonstrations_v2/tutorial_qgrnn/metadata.json index 1d6f12a1f3..7677903d6a 100644 --- a/demonstrations_v2/tutorial_qgrnn/metadata.json +++ b/demonstrations_v2/tutorial_qgrnn/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2020-07-27T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Machine Learning" ], diff --git a/demonstrations_v2/tutorial_qjit_compile_grovers_algorithm_with_catalyst/demo.py b/demonstrations_v2/tutorial_qjit_compile_grovers_algorithm_with_catalyst/demo.py index fbb1de821e..3f090e5e11 100644 --- a/demonstrations_v2/tutorial_qjit_compile_grovers_algorithm_with_catalyst/demo.py +++ b/demonstrations_v2/tutorial_qjit_compile_grovers_algorithm_with_catalyst/demo.py @@ -65,16 +65,16 @@ import matplotlib.pyplot as plt import numpy as np -import pennylane as qml +import pennylane as qp def equal_superposition(wires): for wire in wires: - qml.Hadamard(wires=wire) + qp.Hadamard(wires=wire) def oracle(wires, omega): - qml.FlipSign(omega, wires=wires) + qp.FlipSign(omega, wires=wires) def num_grover_iterations(N, M): @@ -95,9 +95,9 @@ def grover_circuit(num_qubits): for _ in range(num_grover_iterations(N, M)): for omg in omega: oracle(wires, omg) - qml.templates.GroverOperator(wires) + qp.templates.GroverOperator(wires) - return qml.probs(wires=wires) + return qp.probs(wires=wires) ###################################################################### @@ -108,10 +108,10 @@ def grover_circuit(num_qubits): NUM_QUBITS = 12 -dev = qml.device("default.qubit", wires=NUM_QUBITS) +dev = qp.device("default.qubit", wires=NUM_QUBITS) -@qml.qnode(dev) +@qp.qnode(dev) def circuit_default_qubit(): return grover_circuit(NUM_QUBITS) @@ -157,10 +157,10 @@ def print_most_probable_states_descending(probs, N): # performant state simulators written in C++. See the :doc:`Catalyst documentation # ` for the full list of devices supported by Catalyst. -dev = qml.device("lightning.qubit", wires=NUM_QUBITS) +dev = qp.device("lightning.qubit", wires=NUM_QUBITS) -@qml.qnode(dev) +@qp.qnode(dev) def circuit_lightning(): return grover_circuit(NUM_QUBITS) @@ -168,7 +168,7 @@ def circuit_lightning(): ###################################################################### # Then, to QJIT compile our circuit with Catalyst, we simply wrap it with :func:`~pennylane.qjit`. -circuit_qjit = qml.qjit(circuit_lightning) +circuit_qjit = qp.qjit(circuit_lightning) ###################################################################### @@ -264,15 +264,15 @@ def circuit_lightning(): repeat=NUM_REPS, ) runtimes_compilation = timeit.repeat( - "qml.qjit(circuit_lightning)", - setup="import pennylane as qml", + "qp.qjit(circuit_lightning)", + setup="import pennylane as qp", globals={"circuit_lightning": circuit_lightning}, number=1, repeat=1, ) runtimes_qjit_call = timeit.repeat( "_circuit_qjit()", - setup="import pennylane as qml; _circuit_qjit = qml.qjit(circuit_lightning);", + setup="import pennylane as qp; _circuit_qjit = qp.qjit(circuit_lightning);", globals={"circuit_lightning": circuit_lightning}, number=1, repeat=NUM_REPS, diff --git a/demonstrations_v2/tutorial_qjit_compile_grovers_algorithm_with_catalyst/metadata.json b/demonstrations_v2/tutorial_qjit_compile_grovers_algorithm_with_catalyst/metadata.json index 860c5649db..aac80d7a0d 100644 --- a/demonstrations_v2/tutorial_qjit_compile_grovers_algorithm_with_catalyst/metadata.json +++ b/demonstrations_v2/tutorial_qjit_compile_grovers_algorithm_with_catalyst/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-11-07T00:00:00+00:00", - "dateOfLastModification": "2025-12-10T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Algorithms", "Devices and Performance", diff --git a/demonstrations_v2/tutorial_qksd_qsp_qualtran/demo.py b/demonstrations_v2/tutorial_qksd_qsp_qualtran/demo.py index 6826cbf66e..226d797cc9 100644 --- a/demonstrations_v2/tutorial_qksd_qsp_qualtran/demo.py +++ b/demonstrations_v2/tutorial_qksd_qsp_qualtran/demo.py @@ -63,12 +63,12 @@ # `PennyLane Datasets `_ or the :mod:`pennylane.qchem` # module. We use the pre-calculated results below to create a :class:`~pennylane.ops.Hamiltonian` object. -import pennylane as qml +import pennylane as qp import numpy as np coeffs = [-2.6055398817649027, 0.4725512342017669, 0.06908378485045799, 0.06908378485045799, 0.42465877221739423, 0.040785962774025165, 0.02016371425557293, 0.33650704944175736, 0.059002396986463035, 0.059002396986463035, 0.2401948108687125, 0.2696430914655511, 0.04971997220167805, 0.04971997220167805, 0.2751875205710399, 0.30033122257656397, 0.22551650339251875] -paulis = [qml.GlobalPhase(0, 0), qml.Z(0), qml.Y(0) @ qml.Z(1) @ qml.Y(2), qml.X(0) @ qml.Z(1) @ qml.X(2), qml.Z(1), qml.Z(2), qml.Z(3), qml.Z(0) @ qml.Z(1), qml.Y(0) @ qml.Y(2), qml.X(0) @ qml.X(2), qml.Z(0) @ qml.Z(2), qml.Z(0) @ qml.Z(3), qml.Y(0) @ qml.Z(1) @ qml.Y(2) @ qml.Z(3), qml.X(0) @ qml.Z(1) @ qml.X(2) @ qml.Z(3), qml.Z(1) @ qml.Z(2), qml.Z(1) @ qml.Z(3), qml.Z(2) @ qml.Z(3)] -hamiltonian = qml.Hamiltonian(coeffs, paulis) +paulis = [qp.GlobalPhase(0, 0), qp.Z(0), qp.Y(0) @ qp.Z(1) @ qp.Y(2), qp.X(0) @ qp.Z(1) @ qp.X(2), qp.Z(1), qp.Z(2), qp.Z(3), qp.Z(0) @ qp.Z(1), qp.Y(0) @ qp.Y(2), qp.X(0) @ qp.X(2), qp.Z(0) @ qp.Z(2), qp.Z(0) @ qp.Z(3), qp.Y(0) @ qp.Z(1) @ qp.Y(2) @ qp.Z(3), qp.X(0) @ qp.Z(1) @ qp.X(2) @ qp.Z(3), qp.Z(1) @ qp.Z(2), qp.Z(1) @ qp.Z(3), qp.Z(2) @ qp.Z(3)] +hamiltonian = qp.Hamiltonian(coeffs, paulis) ###################################################################### # Next, we will define the Krylov subspace, :math:`\mathcal{K}`. @@ -175,15 +175,15 @@ def rotation_about_reflection_axis(angle, wires): """Rotation operation, S(phi_k)""" - qml.ctrl(qml.PauliX(wires[0]), wires[1:], (0,) * len(wires[1:])) - qml.RZ(angle, wires[0]) - qml.ctrl(qml.PauliX(wires[0]), wires[1:], (0,) * len(wires[1:])) + qp.ctrl(qp.PauliX(wires[0]), wires[1:], (0,) * len(wires[1:])) + qp.RZ(angle, wires[0]) + qp.ctrl(qp.PauliX(wires[0]), wires[1:], (0,) * len(wires[1:])) def qsp(lcu, angles, rot_wires, prep_wires): """Applies QSP by alternating between S(phi_k) and U_{QSP}""" for angle in angles[::-1][:-1]: rotation_about_reflection_axis(angle, rot_wires) - qml.PrepSelPrep(lcu, control=prep_wires) + qp.PrepSelPrep(lcu, control=prep_wires) rotation_about_reflection_axis(angles[0], rot_wires) ###################################################################### @@ -192,19 +192,19 @@ def qsp(lcu, angles, rot_wires, prep_wires): # polynomial. def qsp_poly_complex(lcu, angles_real, angles_imag, ctrl_wire, rot_wires, prep_wires): - qml.H(ctrl_wire) - qml.ctrl(qsp, ctrl_wire, 0)(lcu, angles_real, rot_wires, prep_wires) - qml.ctrl(qsp, ctrl_wire, 1)(lcu, angles_imag, rot_wires, prep_wires) - qml.H(ctrl_wire) + qp.H(ctrl_wire) + qp.ctrl(qsp, ctrl_wire, 0)(lcu, angles_real, rot_wires, prep_wires) + qp.ctrl(qsp, ctrl_wire, 1)(lcu, angles_imag, rot_wires, prep_wires) + qp.H(ctrl_wire) ###################################################################### # Additionally, we require a template to perform the :math:`R_0` reflection for our measurements. def reflection(wire, ctrl_wires): """Reflection operator, R_0""" - qml.ctrl(qml.X(wire), ctrl_wires, [0] * len(ctrl_wires)) - qml.Z(wire) - qml.ctrl(qml.X(wire), ctrl_wires, [0] * len(ctrl_wires)) + qp.ctrl(qp.X(wire), ctrl_wires, [0] * len(ctrl_wires)) + qp.Z(wire) + qp.ctrl(qp.X(wire), ctrl_wires, [0] * len(ctrl_wires)) ###################################################################### # We will also need to split even- and odd-parity polynomial terms, which is captured in the @@ -221,10 +221,10 @@ def reflection(wire, ctrl_wires): # and return measurements of the elements of # the one-particle reduced density matrix: -dev = qml.device("lightning.qubit") -ref_state = qml.qchem.hf_state(electrons=4, orbitals=4) +dev = qp.device("lightning.qubit") +ref_state = qp.qchem.hf_state(electrons=4, orbitals=4) -@qml.qnode(dev) +@qp.qnode(dev) def krylov_qsp(lcu, even_real, even_imag, odd_real, odd_imag, obs, measure_reflection=False): """Prepares the Krylov ground-state by applying QSP with the input angles. Then measures the expectation value of the desired observable. @@ -239,22 +239,22 @@ def krylov_qsp(lcu, even_real, even_imag, odd_real, odd_imag, obs, measure_refle #prepare the reference state for i in hamiltonian.wires: - qml.X(i) + qp.X(i) if measure_reflection: # preprocessing for reflection measurement - qml.X(rdm_ctrl_wire) + qp.X(rdm_ctrl_wire) - qml.H(ctrl_wires[0]) - qml.ctrl(qsp_poly_complex, ctrl_wires[0], 0)(lcu, even_real, even_imag, ctrl_wires[1], + qp.H(ctrl_wires[0]) + qp.ctrl(qsp_poly_complex, ctrl_wires[0], 0)(lcu, even_real, even_imag, ctrl_wires[1], rot_wires, prep_wires) - qml.ctrl(qsp_poly_complex, ctrl_wires[0], 1)(lcu, odd_real, odd_imag, ctrl_wires[1], + qp.ctrl(qsp_poly_complex, ctrl_wires[0], 1)(lcu, odd_real, odd_imag, ctrl_wires[1], rot_wires, prep_wires) - qml.H(ctrl_wires[0]) + qp.H(ctrl_wires[0]) # measurements if measure_reflection: - return qml.expval(qml.prod(reflection)(rdm_ctrl_wire, set(ctrl_wires+prep_wires))@obs) - return qml.expval(obs) + return qp.expval(qp.prod(reflection)(rdm_ctrl_wire, set(ctrl_wires+prep_wires))@obs) + return qp.expval(obs) ###################################################################### @@ -262,8 +262,8 @@ def krylov_qsp(lcu, even_real, even_imag, odd_real, odd_imag, obs, measure_refle # We can obtain the Jordan-Wigner mapping of the fermionic operators via PennyLane using the # :func:`~pennylane.fermi.from_string` and :func:`~pennylane.jordan_wigner` functions as follows: -Epq = qml.fermi.from_string('0+ 0-') -obs = qml.jordan_wigner(Epq) +Epq = qp.fermi.from_string('0+ 0-') +obs = qp.jordan_wigner(Epq) ###################################################################### # For this demo, we used a Krylov subspace dimension of :math:`D=15` and pre-computed QSP angles @@ -301,7 +301,7 @@ def krylov_qsp(lcu, even_real, even_imag, odd_real, odd_imag, obs, measure_refle # We first convert the PennyLane circuit to a Qualtran bloq using :func:`~pennylane.to_bloq` and # then use the call graph to count the required gates: -bloq = qml.to_bloq(krylov_qsp, map_ops=False, +bloq = qp.to_bloq(krylov_qsp, map_ops=False, even_real=even_real, even_imag=even_imag, odd_real=odd_real, odd_imag=odd_imag, lcu=hamiltonian, obs=obs) @@ -333,7 +333,7 @@ def krylov_qsp(lcu, even_real, even_imag, odd_real, odd_imag, obs, measure_refle ###################################################################### # We then repeat the gate counts and see they have increased: -bloq = qml.to_bloq(krylov_qsp, map_ops=False, even_real=even_real, +bloq = qp.to_bloq(krylov_qsp, map_ops=False, even_real=even_real, even_imag=even_imag, odd_real=odd_real, odd_imag=odd_imag, lcu=hamiltonian, obs=obs) @@ -352,7 +352,7 @@ def krylov_qsp(lcu, even_real, even_imag, odd_real, odd_imag, obs, measure_refle def count_cnots(krylov_dimension): even_real = even_imag = odd_real = odd_imag = np.random.random(krylov_dimension) - bloq = qml.to_bloq(krylov_qsp, map_ops=False, even_real=even_real, + bloq = qp.to_bloq(krylov_qsp, map_ops=False, even_real=even_real, even_imag=even_imag, odd_real=odd_real, odd_imag=odd_imag, lcu=hamiltonian, obs=obs) _, sigma = bloq.call_graph(generalizer=generalize_rotation_angle) diff --git a/demonstrations_v2/tutorial_qksd_qsp_qualtran/metadata.json b/demonstrations_v2/tutorial_qksd_qsp_qualtran/metadata.json index 516d7f939a..3819718bb2 100644 --- a/demonstrations_v2/tutorial_qksd_qsp_qualtran/metadata.json +++ b/demonstrations_v2/tutorial_qksd_qsp_qualtran/metadata.json @@ -17,7 +17,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2025-08-29T00:00:00+00:00", - "dateOfLastModification": "2026-01-23T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Computing" ], diff --git a/demonstrations_v2/tutorial_qnn_module_torch/demo.py b/demonstrations_v2/tutorial_qnn_module_torch/demo.py index bd7e4fb028..a9aafbf9df 100644 --- a/demonstrations_v2/tutorial_qnn_module_torch/demo.py +++ b/demonstrations_v2/tutorial_qnn_module_torch/demo.py @@ -76,16 +76,16 @@ # :doc:`default.qubit ` simulator and # operations from the :doc:`templates ` module. -import pennylane as qml +import pennylane as qp n_qubits = 2 -dev = qml.device("default.qubit", wires=n_qubits) +dev = qp.device("default.qubit", wires=n_qubits) -@qml.qnode(dev) +@qp.qnode(dev) def qnode(inputs, weights): - qml.AngleEmbedding(inputs, wires=range(n_qubits)) - qml.BasicEntanglerLayers(weights, wires=range(n_qubits)) - return [qml.expval(qml.PauliZ(wires=i)) for i in range(n_qubits)] + qp.AngleEmbedding(inputs, wires=range(n_qubits)) + qp.BasicEntanglerLayers(weights, wires=range(n_qubits)) + return [qp.expval(qp.PauliZ(wires=i)) for i in range(n_qubits)] ############################################################################### # Interfacing with Torch @@ -113,7 +113,7 @@ def qnode(inputs, weights): # # Now that ``weight_shapes`` is defined, it is easy to then convert the QNode: -qlayer = qml.qnn.TorchLayer(qnode, weight_shapes) +qlayer = qp.qnn.TorchLayer(qnode, weight_shapes) ############################################################################### # With this done, the QNode can now be treated just like any other ``torch.nn`` layer and we can @@ -235,8 +235,8 @@ class HybridModel(torch.nn.Module): def __init__(self): super().__init__() self.clayer_1 = torch.nn.Linear(2, 4) - self.qlayer_1 = qml.qnn.TorchLayer(qnode, weight_shapes) - self.qlayer_2 = qml.qnn.TorchLayer(qnode, weight_shapes) + self.qlayer_1 = qp.qnn.TorchLayer(qnode, weight_shapes) + self.qlayer_2 = qp.qnn.TorchLayer(qnode, weight_shapes) self.clayer_2 = torch.nn.Linear(4, 2) self.softmax = torch.nn.Softmax(dim=1) diff --git a/demonstrations_v2/tutorial_qnn_module_torch/metadata.json b/demonstrations_v2/tutorial_qnn_module_torch/metadata.json index 7147ab3159..68c7945588 100644 --- a/demonstrations_v2/tutorial_qnn_module_torch/metadata.json +++ b/demonstrations_v2/tutorial_qnn_module_torch/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2020-11-02T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Devices and Performance", "Quantum Machine Learning" diff --git a/demonstrations_v2/tutorial_qnn_multivariate_regression/demo.py b/demonstrations_v2/tutorial_qnn_multivariate_regression/demo.py index 61b0ea9006..75cd2d7424 100644 --- a/demonstrations_v2/tutorial_qnn_multivariate_regression/demo.py +++ b/demonstrations_v2/tutorial_qnn_multivariate_regression/demo.py @@ -67,7 +67,7 @@ """ import matplotlib.pyplot as plt -import pennylane as qml +import pennylane as qp from pennylane import numpy as pnp import jax from jax import numpy as jnp @@ -75,7 +75,7 @@ pnp.random.seed(42) -dev = qml.device('default.qubit', wires=2) +dev = qp.device('default.qubit', wires=2) ###################################################################### # Now we will construct the data-encoding circuit block, :math:`S(\vec{x})`, as a product of :math:`R_z` rotations: @@ -86,18 +86,18 @@ # Specifically, we define the :math:`S(\vec{x})` operator using the :class:`~.pennylane.AngleEmbedding` function. def S(x): - qml.AngleEmbedding( x, wires=[0,1],rotation='Z') + qp.AngleEmbedding( x, wires=[0,1],rotation='Z') ###################################################################### # For the :math:`W(\vec{\theta})` operator, we will use an ansatz that is available in PennyLane, called :class:`~.pennylane.StronglyEntanglingLayers`. def W(params): - qml.StronglyEntanglingLayers(params, wires=[0,1]) + qp.StronglyEntanglingLayers(params, wires=[0,1]) ###################################################################### # Now we will build the circuit in PennyLane by alternating layers of :math:`W(\vec{\theta})` and :math:`S(\vec{x})` layers. On this prepared state, we estimate the expectation value of the :math:`Z\otimes Z` operator, using PennyLane's :func:`~.pennylane.expval` function. -@qml.qnode(dev,interface="jax") +@qp.qnode(dev,interface="jax") def quantum_neural_network(params, x): layers=len(params[:,0,0])-1 n_wires=len(params[0,:,0]) @@ -107,7 +107,7 @@ def quantum_neural_network(params, x): S(x) W(params[-1,:,:].reshape(1,n_wires,n_params_rot)) - return qml.expval(qml.PauliZ(wires=0)@qml.PauliZ(wires=1)) + return qp.expval(qp.PauliZ(wires=0)@qp.PauliZ(wires=1)) ###################################################################### # The function we will be fitting is :math:`f(x_1, x_2) = \frac{1}{2} \left( x_1^2 + x_2^2 \right)`, which we will define as ``target_function``: @@ -203,7 +203,7 @@ def optimization_jit(params, data, targets, print_training=False): wires=2 layers=4 -params_shape = qml.StronglyEntanglingLayers.shape(n_layers=layers+1,n_wires=wires) +params_shape = qp.StronglyEntanglingLayers.shape(n_layers=layers+1,n_wires=wires) params=pnp.random.default_rng().random(size=params_shape) best_params=optimization_jit(params, x_train, jnp.array(y_train), print_training=True) diff --git a/demonstrations_v2/tutorial_qnn_multivariate_regression/metadata.json b/demonstrations_v2/tutorial_qnn_multivariate_regression/metadata.json index f4e9f44d1c..733a5bd8ff 100644 --- a/demonstrations_v2/tutorial_qnn_multivariate_regression/metadata.json +++ b/demonstrations_v2/tutorial_qnn_multivariate_regression/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-10-01T00:00:00+00:00", - "dateOfLastModification": "2026-01-14T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Computing", "Quantum Machine Learning", diff --git a/demonstrations_v2/tutorial_qpe/demo.py b/demonstrations_v2/tutorial_qpe/demo.py index 33b1e51edd..ea81e50736 100644 --- a/demonstrations_v2/tutorial_qpe/demo.py +++ b/demonstrations_v2/tutorial_qpe/demo.py @@ -207,11 +207,11 @@ """ -import pennylane as qml +import pennylane as qp import numpy as np def U(wires): - return qml.PhaseShift(2 * np.pi / 5, wires=wires) + return qp.PhaseShift(2 * np.pi / 5, wires=wires) ############################################################################## # We construct a uniform superposition by applying Hadamard gates followed by a :class:`~.ControlledSequence` @@ -220,21 +220,21 @@ def U(wires): # return the probability of each computational basis state. -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") -@qml.qnode(dev) +@qp.qnode(dev) def circuit_qpe(estimation_wires): # initialize to state |1> - qml.PauliX(wires=0) + qp.PauliX(wires=0) for wire in estimation_wires: - qml.Hadamard(wires=wire) + qp.Hadamard(wires=wire) - qml.ControlledSequence(U(wires=0), control=estimation_wires) + qp.ControlledSequence(U(wires=0), control=estimation_wires) - qml.adjoint(qml.QFT)(wires=estimation_wires) + qp.adjoint(qp.QFT)(wires=estimation_wires) - return qml.probs(wires=estimation_wires) + return qp.probs(wires=estimation_wires) ############################################################################## # Let's run the circuit and plot the results. We use 4 estimation qubits. diff --git a/demonstrations_v2/tutorial_qpe/metadata.json b/demonstrations_v2/tutorial_qpe/metadata.json index 47d1d47529..cd0738b721 100644 --- a/demonstrations_v2/tutorial_qpe/metadata.json +++ b/demonstrations_v2/tutorial_qpe/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-01-30T00:00:00+00:00", - "dateOfLastModification": "2025-12-19T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Algorithms", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_qsvt_hardware/demo.py b/demonstrations_v2/tutorial_qsvt_hardware/demo.py index 2130f6538e..eb70b82cb8 100644 --- a/demonstrations_v2/tutorial_qsvt_hardware/demo.py +++ b/demonstrations_v2/tutorial_qsvt_hardware/demo.py @@ -24,7 +24,7 @@ fundamental components of the QSVT algorithm: - **Projection angles**: A list of angles that will determine the coefficients of the polynomial to be applied. -- **Block encoding**: The strategy used to encode the Hamiltonian. We will use the :doc:`linear combinations of unitaries ` approach via the PennyLane :class:`~.qml.PrepSelPrep` operation. +- **Block encoding**: The strategy used to encode the Hamiltonian. We will use the :doc:`linear combinations of unitaries ` approach via the PennyLane :class:`~.qp.PrepSelPrep` operation. Calculating angles is not a trivial task, but we can use the PennyLane function :func:`~.pennylane.poly_to_angles` to obtain them. There are also tools such as `pyqsp `_ that can do the job for us. @@ -35,9 +35,9 @@ polynomial, ordered from lowest to highest power, as input. We also need to define the routine for which the angles are computed, which is ``'QSVT'`` here. """ -import pennylane as qml +import pennylane as qp poly = [0, -1.0, 0, 1/2, 0, 1/2] -angles_pl = qml.poly_to_angles(poly, "QSVT") +angles_pl = qp.poly_to_angles(poly, "QSVT") print(angles_pl) ###################################################################### @@ -66,7 +66,7 @@ # context of QSP and are not the same as the ones we have to use in QSVT. # We can use the :func:`~.pennylane.transform_angles` function to transform the angles: -angles_pyqsp = qml.transform_angles(ang_seq, "QSP", "QSVT") +angles_pyqsp = qp.transform_angles(ang_seq, "QSP", "QSVT") print(angles_pyqsp) ###################################################################### @@ -78,23 +78,23 @@ # QSVT on hardware # ----------------- # -# The :class:`~.qml.QSVT` template expects two inputs. The first one is the block encoding operator, :class:`~.qml.PrepSelPrep`, -# and the second one is a set of projection operators, :class:`~.qml.PCPhase`, that encode the angles properly. +# The :class:`~.qp.QSVT` template expects two inputs. The first one is the block encoding operator, :class:`~.qp.PrepSelPrep`, +# and the second one is a set of projection operators, :class:`~.qp.PCPhase`, that encode the angles properly. # We will see how to apply them later, but first let's define # a Hamiltonian and manually apply the polynomial of interest: -import pennylane as qml +import pennylane as qp import numpy as np from numpy.linalg import matrix_power as mpow coeffs = np.array([0.2, -0.7, -0.6]) coeffs /= np.linalg.norm(coeffs, ord=1) # Normalize the coefficients -obs = [qml.X(3), qml.X(3) @ qml.Z(4), qml.Z(3) @ qml.Y(4)] +obs = [qp.X(3), qp.X(3) @ qp.Z(4), qp.Z(3) @ qp.Y(4)] -H = qml.dot(coeffs, obs) +H = qp.dot(coeffs, obs) -H_mat = qml.matrix(H, wire_order=[3, 4]) +H_mat = qp.matrix(H, wire_order=[3, 4]) # We calculate p(H) = -H + 0.5 * H^3 + 0.5 * H^5 H_poly = -H_mat + 0.5 * mpow(H_mat, 3) + 0.5 * mpow(H_mat, 5) @@ -103,32 +103,32 @@ ###################################################################### # Now that we know what the target result is, let's see how to apply the polynomial with a quantum circuit instead. -# We start by defining the proper input operators for the :class:`~.qml.QSVT` template. +# We start by defining the proper input operators for the :class:`~.qp.QSVT` template. # We need |log2(len(coeffs))| = 2 control wires to encode the Hamiltonian control_wires = [1, 2] -block_encode = qml.PrepSelPrep(H, control=control_wires) +block_encode = qp.PrepSelPrep(H, control=control_wires) projectors = [ - qml.PCPhase(angles_pl[i], dim=2 ** len(H.wires), wires=control_wires + H.wires) + qp.PCPhase(angles_pl[i], dim=2 ** len(H.wires), wires=control_wires + H.wires) for i in range(len(angles_pl)) ] -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") -@qml.qnode(dev) +@qp.qnode(dev) def circuit(): - qml.Hadamard(0) - qml.ctrl(qml.QSVT, control=0, control_values=[1])(block_encode, projectors) - qml.ctrl(qml.adjoint(qml.QSVT), control=0, control_values=[0])(block_encode, projectors) - qml.Hadamard(0) + qp.Hadamard(0) + qp.ctrl(qp.QSVT, control=0, control_values=[1])(block_encode, projectors) + qp.ctrl(qp.adjoint(qp.QSVT), control=0, control_values=[0])(block_encode, projectors) + qp.Hadamard(0) - return qml.state() + return qp.state() -matrix = qml.matrix(circuit, wire_order=[0] + control_wires + H.wires)() +matrix = qp.matrix(circuit, wire_order=[0] + control_wires + H.wires)() print(np.round(matrix[: 2 ** len(H.wires), : 2 ** len(H.wires)], 4)) ###################################################################### diff --git a/demonstrations_v2/tutorial_qsvt_hardware/metadata.json b/demonstrations_v2/tutorial_qsvt_hardware/metadata.json index 648534b0d9..5c830a9513 100644 --- a/demonstrations_v2/tutorial_qsvt_hardware/metadata.json +++ b/demonstrations_v2/tutorial_qsvt_hardware/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-09-18T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Algorithms", "Quantum Computing", diff --git a/demonstrations_v2/tutorial_quantum_analytic_descent/demo.py b/demonstrations_v2/tutorial_quantum_analytic_descent/demo.py index a950327342..35765aa1b3 100644 --- a/demonstrations_v2/tutorial_quantum_analytic_descent/demo.py +++ b/demonstrations_v2/tutorial_quantum_analytic_descent/demo.py @@ -88,7 +88,7 @@ Let's look at a toy example to illustrate this structure of the cost function. """ -import pennylane as qml +import pennylane as qp from pennylane import numpy as np import matplotlib.pyplot as plt import warnings @@ -98,14 +98,14 @@ np.random.seed(0) # Create a device with 2 qubits. -dev = qml.device("lightning.qubit", wires=2) +dev = qp.device("lightning.qubit", wires=2) # Define the variational form V and observable M and combine them into a QNode. -@qml.qnode(dev, diff_method="parameter-shift", max_diff=2) +@qp.qnode(dev, diff_method="parameter-shift", max_diff=2) def circuit(parameters): - qml.RX(parameters[0], wires=0) - qml.RX(parameters[1], wires=1) - return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) + qp.RX(parameters[0], wires=0) + qp.RX(parameters[1], wires=1) + return qp.expval(qp.PauliZ(0) @ qp.PauliZ(1)) ############################################################################### @@ -308,9 +308,9 @@ def get_model_data(fun, params): E_A = fun(params) # E_B contains the gradient. - E_B = qml.grad(fun)(params) + E_B = qp.grad(fun)(params) - hessian = qml.jacobian(qml.grad(fun))(params) + hessian = qp.jacobian(qp.grad(fun))(params) # E_C contains the slightly adapted diagonal of the Hessian. E_C = np.diag(hessian) + E_A / 2 @@ -577,7 +577,7 @@ def plot_cost_and_model(f, model, params, shift_radius=5 * np.pi / 8, num_points if iter_outer == 0: print(f"True energy at initial parameters: {np.round(coeffs[0], decimals=4)}\n") - opt = qml.AdamOptimizer(0.05) + opt = qp.AdamOptimizer(0.05) # Recall that the parameters of the model are relative coordinates. # Correspondingly, we initialize at 0, not at parameters. relative_parameters = np.zeros_like(parameters, requires_grad=True) diff --git a/demonstrations_v2/tutorial_quantum_analytic_descent/metadata.json b/demonstrations_v2/tutorial_quantum_analytic_descent/metadata.json index 91f0768ded..7353e73b2e 100644 --- a/demonstrations_v2/tutorial_quantum_analytic_descent/metadata.json +++ b/demonstrations_v2/tutorial_quantum_analytic_descent/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2021-06-30T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_quantum_chebyshev_transform/demo.py b/demonstrations_v2/tutorial_quantum_chebyshev_transform/demo.py index ba6131bd52..018ea3c1f0 100644 --- a/demonstrations_v2/tutorial_quantum_chebyshev_transform/demo.py +++ b/demonstrations_v2/tutorial_quantum_chebyshev_transform/demo.py @@ -159,7 +159,7 @@ To start, we will define a function for the CNOT ladder. """ -import pennylane as qml +import pennylane as qp # Number of qubits (non-auxiliary qubit). N = 4 @@ -167,11 +167,11 @@ def CNOT_ladder(): for wire in range(1, N + 1): - qml.CNOT([0, wire]) + qp.CNOT([0, wire]) ############################################# -# After the initial CNOT ladder comes an :math:`N+1` QFT circuit, which can be implemented using ``qml.QFT``. +# After the initial CNOT ladder comes an :math:`N+1` QFT circuit, which can be implemented using ``qp.QFT``. # # Next are phase rotations and shifts. # For the auxiliary qubit, there is a :math:`Z` rotation by and angle of :math:`-\pi(2^N - 1)/2^{N+1}` followed by a phase shift of :math:`-\pi/2^{(N+1)}` . @@ -185,10 +185,10 @@ def CNOT_ladder(): def rotate_phases(): """Rotates and shifts the phase of the auxiliary qubit and rotates the jth qubit by pi/2^(j+1) in Z.""" - qml.RZ(-pi * (2**N - 1) / 2 ** (N + 1), wires=0) - qml.PhaseShift(-pi / 2 ** (N + 1), wires=0) + qp.RZ(-pi * (2**N - 1) / 2 ** (N + 1), wires=0) + qp.PhaseShift(-pi / 2 ** (N + 1), wires=0) for wire in range(1, N + 1): - qml.RZ(pi / 2 ** (wire + 1), wires=wire) + qp.RZ(pi / 2 ** (wire + 1), wires=wire) ############################################# @@ -202,7 +202,7 @@ def permute_elements(): """Reorders amplitudes of the conditioned states.""" for wire in reversed(range(1, N + 1)): control_wires = [0] + list(range(wire + 1, N + 1)) - qml.MultiControlledX(wires=(*control_wires, wire)) + qp.MultiControlledX(wires=(*control_wires, wire)) ############################################# @@ -211,66 +211,66 @@ def permute_elements(): # # The last part is a phase adjustment of the auxiliary qubit: a rotation in :math:`Y` by :math:`\pi/2`, a phase shift of :math:`-\pi/2` and a multicontrolled :math:`X` rotation by :math:`\pi/2`. # All of the other qubits control the :math:`X` rotation, but the control is sandwiched by Pauli :math:`X` operators. -# We can implement the multicontrolled :math:`X` rotation by using the function ``qml.ctrl`` on ``qml.RX``, specifying the target wire in ``qml.RX`` and the control wires as the second argument of ``qml.ctrl``. +# We can implement the multicontrolled :math:`X` rotation by using the function ``qp.ctrl`` on ``qp.RX``, specifying the target wire in ``qp.RX`` and the control wires as the second argument of ``qp.ctrl``. def adjust_phases(): """Adjusts the phase of the auxiliary qubit.""" - qml.RY(-pi / 2, wires=0) - qml.PhaseShift(-pi / 2, wires=0) + qp.RY(-pi / 2, wires=0) + qp.PhaseShift(-pi / 2, wires=0) # First Pauli X gates. for wire in range(1, N + 1): - qml.PauliX(wires=wire) + qp.PauliX(wires=wire) # Controlled RX gate. - qml.ctrl(qml.RX(pi / 2, wires=0), range(1, N + 1)) + qp.ctrl(qp.RX(pi / 2, wires=0), range(1, N + 1)) # Second Pauli X gates. for wire in range(1, N + 1): - qml.PauliX(wires=wire) + qp.PauliX(wires=wire) ############################################# # All together, we can construct the circuit. -# We have added :class:`qml.BasisState` to initialize the input in any computational basis state with the optional argument ``state``. +# We have added :class:`qp.BasisState` to initialize the input in any computational basis state with the optional argument ``state``. def QChT(): """Performs the quantum Chebyshev transform.""" - qml.Hadamard(wires=0) + qp.Hadamard(wires=0) CNOT_ladder() - qml.QFT(wires=range(N + 1)) + qp.QFT(wires=range(N + 1)) rotate_phases() permute_elements() CNOT_ladder() adjust_phases() -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") -@qml.qnode(dev) +@qp.qnode(dev) def circuit(state=0): - qml.BasisState(state=state, wires=range(1, N + 1)) + qp.BasisState(state=state, wires=range(1, N + 1)) QChT() - return qml.state() + return qp.state() ############################################# -# Finally, we can reproduce the circuit diagram shown at the beginning of this section using ``qml.draw_mpl``. +# Finally, we can reproduce the circuit diagram shown at the beginning of this section using ``qp.draw_mpl``. def circuit_to_draw(): - qml.BasisState(state=0, wires=range(1, N + 1)) + qp.BasisState(state=0, wires=range(1, N + 1)) QChT() -fig, ax = qml.draw_mpl(circuit_to_draw, decimals=2, style="pennylane")() +fig, ax = qp.draw_mpl(circuit_to_draw, decimals=2, style="pennylane")() fig.show() ############################################# -# Note we defined a new function for the circuit to simplify the drawing, removing the returned ``qml.state``. +# Note we defined a new function for the circuit to simplify the drawing, removing the returned ``qp.state``. # # Testing the quantum Chebyshev transform # ---------------- diff --git a/demonstrations_v2/tutorial_quantum_chebyshev_transform/metadata.json b/demonstrations_v2/tutorial_quantum_chebyshev_transform/metadata.json index 9275e8cc09..1fafcf66b6 100644 --- a/demonstrations_v2/tutorial_quantum_chebyshev_transform/metadata.json +++ b/demonstrations_v2/tutorial_quantum_chebyshev_transform/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2025-07-22T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Algorithms", "Quantum Machine Learning" From 05506f8f3d82b7a0e65b55022dcf766a7524db91 Mon Sep 17 00:00:00 2001 From: drdren <104710745+drdren@users.noreply.github.com> Date: Tue, 21 Apr 2026 12:51:31 -0400 Subject: [PATCH 06/10] qml to qp Batch 8 (#1759) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### Before submitting Please complete the following checklist when submitting a PR: - [ ] Ensure that your tutorial executes correctly, and conforms to the guidelines specified in the [README](https://github.com/PennyLaneAI/demos/blob/master/README.md). - [ ] Remember to do a grammar check of the content you include. - [ ] All tutorials conform to [PEP8 standards](https://www.python.org/dev/peps/pep-0008/). To auto format files, simply `pip install black`, and then run `black -l 100 path/to/file.py`. When all the above are checked, delete everything above the dashed line and fill in the pull request template. ------------------------------------------------------------------------------------------------------------ **Title:** **Summary:** **Relevant references:** **Possible Drawbacks:** **Related GitHub Issues:** ---- If you are writing a demonstration, please answer these questions to facilitate the marketing process. * GOALS — Why are we working on this now? *Eg. Promote a new PL feature or show a PL implementation of a recent paper.* * AUDIENCE — Who is this for? *Eg. Chemistry researchers, PL educators, beginners in quantum computing.* * KEYWORDS — What words should be included in the marketing post? * Which of the following types of documentation is most similar to your file? (more details [here](https://www.notion.so/xanaduai/Different-kinds-of-documentation-69200645fe59442991c71f9e7d8a77f8)) - [ ] Tutorial - [ ] Demo - [ ] How-to Co-authored-by: David --- .../tutorial_quantum_circuit_cutting/demo.py | 152 +++++++++--------- .../metadata.json | 2 +- .../tutorial_quantum_dropout/demo.py | 18 +-- .../tutorial_quantum_dropout/metadata.json | 2 +- .../tutorial_quantum_gans/demo.py | 14 +- .../tutorial_quantum_gans/metadata.json | 2 +- .../tutorial_quantum_metrology/demo.py | 20 +-- .../tutorial_quantum_metrology/metadata.json | 2 +- .../tutorial_quantum_natural_gradient/demo.py | 82 +++++----- .../metadata.json | 2 +- .../demo.py | 92 +++++------ .../metadata.json | 2 +- .../demo.py | 16 +- .../metadata.json | 2 +- .../tutorial_quanvolution/demo.py | 10 +- .../tutorial_quanvolution/metadata.json | 2 +- .../tutorial_qubit_rotation/demo.py | 26 +-- .../tutorial_qubit_rotation/metadata.json | 2 +- .../tutorial_qubit_tapering/demo.py | 56 +++---- .../tutorial_qubit_tapering/metadata.json | 2 +- .../tutorial_qubitization/demo.py | 18 +-- .../tutorial_qubitization/metadata.json | 2 +- .../demo.py | 88 +++++----- .../metadata.json | 2 +- .../tutorial_resource_estimation/demo.py | 30 ++-- .../metadata.json | 2 +- .../tutorial_resource_estimation_QSVT/demo.py | 8 +- .../metadata.json | 2 +- .../tutorial_resourcefulness/demo.py | 24 +-- .../tutorial_resourcefulness/metadata.json | 2 +- demonstrations_v2/tutorial_rl_pulse/demo.py | 60 +++---- .../tutorial_rl_pulse/metadata.json | 2 +- demonstrations_v2/tutorial_rosalin/demo.py | 60 +++---- .../tutorial_rosalin/metadata.json | 2 +- demonstrations_v2/tutorial_rotoselect/demo.py | 44 ++--- .../tutorial_rotoselect/metadata.json | 2 +- demonstrations_v2/tutorial_sc_qubits/demo.py | 112 ++++++------- .../tutorial_sc_qubits/metadata.json | 2 +- .../demo.py | 22 +-- .../metadata.json | 2 +- 40 files changed, 496 insertions(+), 496 deletions(-) diff --git a/demonstrations_v2/tutorial_quantum_circuit_cutting/demo.py b/demonstrations_v2/tutorial_quantum_circuit_cutting/demo.py index bdcfb59cb2..e5118e08c9 100644 --- a/demonstrations_v2/tutorial_quantum_circuit_cutting/demo.py +++ b/demonstrations_v2/tutorial_quantum_circuit_cutting/demo.py @@ -116,41 +116,41 @@ PennyLane implementation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -PennyLane's built-in circuit cutting algorithm, ``qml.cut_circuit``, +PennyLane's built-in circuit cutting algorithm, ``qp.cut_circuit``, takes a large quantum circuit and decomposes it into smaller subcircuits that are executed on a small quantum device. The results from executing the smaller subcircuits are then recombined through some classical post-processing to obtain the original result of the large quantum circuit. -Let’s simulate a "real-world" scenario with ``qml.cut_circuit`` using the +Let’s simulate a "real-world" scenario with ``qp.cut_circuit`` using the circuit below. """ # Import the relevant libraries from functools import partial -import pennylane as qml +import pennylane as qp from pennylane import numpy as np -dev = qml.device("default.qubit", wires=3) +dev = qp.device("default.qubit", wires=3) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(x): - qml.RX(x, wires=0) - qml.RY(0.9, wires=1) - qml.RX(0.3, wires=2) + qp.RX(x, wires=0) + qp.RY(0.9, wires=1) + qp.RX(0.3, wires=2) - qml.CZ(wires=[0, 1]) - qml.RY(-0.4, wires=0) + qp.CZ(wires=[0, 1]) + qp.RY(-0.4, wires=0) - qml.CZ(wires=[1, 2]) + qp.CZ(wires=[1, 2]) - return qml.expval(qml.pauli.string_to_pauli_word("ZZZ")) + return qp.expval(qp.pauli.string_to_pauli_word("ZZZ")) x = np.array(0.531, requires_grad=True) -fig, ax = qml.draw_mpl(circuit)(x) +fig, ax = qp.draw_mpl(circuit)(x) ###################################################################### @@ -167,29 +167,29 @@ def circuit(x): # ``WireCut`` operation at that location as shown below: # -dev = qml.device("default.qubit", wires=3) +dev = qp.device("default.qubit", wires=3) # Quantum Circuit with QNode -@qml.qnode(dev) +@qp.qnode(dev) def circuit(x): - qml.RX(x, wires=0) - qml.RY(0.9, wires=1) - qml.RX(0.3, wires=2) + qp.RX(x, wires=0) + qp.RY(0.9, wires=1) + qp.RX(0.3, wires=2) - qml.CZ(wires=[0, 1]) - qml.RY(-0.4, wires=0) + qp.CZ(wires=[0, 1]) + qp.RY(-0.4, wires=0) - qml.WireCut(wires=1) # Cut location + qp.WireCut(wires=1) # Cut location - qml.CZ(wires=[1, 2]) + qp.CZ(wires=[1, 2]) - return qml.expval(qml.pauli.string_to_pauli_word("ZZZ")) + return qp.expval(qp.pauli.string_to_pauli_word("ZZZ")) x = np.array(0.531, requires_grad=True) # Defining the parameter x -fig, ax = qml.draw_mpl(circuit)(x) # Drawing circuit +fig, ax = qp.draw_mpl(circuit)(x) # Drawing circuit ###################################################################### @@ -198,29 +198,29 @@ def circuit(x): # operation is inserted. ``WireCut`` is used to manually mark locations for # wire cuts. # -# Next, we apply ``qml.cut_circuit`` operation as a decorator to the +# Next, we apply ``qp.cut_circuit`` operation as a decorator to the # ``circuit`` function to perform circuit cutting on the quantum circuit. -dev = qml.device("default.qubit", wires=3) +dev = qp.device("default.qubit", wires=3) # Quantum Circuit with QNode -@qml.cut_circuit # Applying qml.cut_circuit for circuit cut operation -@qml.qnode(dev) +@qp.cut_circuit # Applying qp.cut_circuit for circuit cut operation +@qp.qnode(dev) def circuit(x): - qml.RX(x, wires=0) - qml.RY(0.9, wires=1) - qml.RX(0.3, wires=2) + qp.RX(x, wires=0) + qp.RY(0.9, wires=1) + qp.RX(0.3, wires=2) - qml.CZ(wires=[0, 1]) - qml.RY(-0.4, wires=0) + qp.CZ(wires=[0, 1]) + qp.RY(-0.4, wires=0) - qml.WireCut(wires=1) # Cut location + qp.WireCut(wires=1) # Cut location - qml.CZ(wires=[1, 2]) + qp.CZ(wires=[1, 2]) - return qml.expval(qml.pauli.string_to_pauli_word("ZZZ")) + return qp.expval(qp.pauli.string_to_pauli_word("ZZZ")) x = np.array(0.531, requires_grad=True) @@ -228,7 +228,7 @@ def circuit(x): ###################################################################### -# Let's explore what happens behind the scenes in ``qml.cut_circuit``. When the +# Let's explore what happens behind the scenes in ``qp.cut_circuit``. When the # ``circuit`` qnode function is executed, the quantum circuit is converted to # a `quantum tape `__ # and then to a graph. Any ``WireCut`` in the quantum @@ -253,7 +253,7 @@ def circuit(x): # separate these fragments into different subcircuit graphs, the # ``fragment_graph()`` function is called to pull apart the quantum circuit # graph as shown in figure 3. The subcircuit graphs are reconverted back to -# quantum tapes and ``qml.cut_circuit`` runs multiple configurations of the +# quantum tapes and ``qp.cut_circuit`` runs multiple configurations of the # 2-qubit subcircuit tapes which are then post-processed to replicate the result # of the uncut circuit. # @@ -286,29 +286,29 @@ def circuit(x): # the classical post-processing overhead is minimized. The main algorithm # behind automatic cut placement is `graph partitioning `__ # -# If ``auto_cutter`` is enabled in ``qml.cut_circuit``, PennyLane makes attempts +# If ``auto_cutter`` is enabled in ``qp.cut_circuit``, PennyLane makes attempts # to find an optimal cut using graph partitioning. Whenever it is difficult to # manually determine the optimal cut location, this is the recommended # approach to circuit cutting. The following example shows this capability # on the same circuit as above but with the ``WireCut`` removed. # -dev = qml.device("default.qubit", wires=3) +dev = qp.device("default.qubit", wires=3) -@partial(qml.cut_circuit, auto_cutter=True) # auto_cutter enabled -@qml.qnode(dev) +@partial(qp.cut_circuit, auto_cutter=True) # auto_cutter enabled +@qp.qnode(dev) def circuit(x): - qml.RX(x, wires=0) - qml.RY(0.9, wires=1) - qml.RX(0.3, wires=2) + qp.RX(x, wires=0) + qp.RY(0.9, wires=1) + qp.RX(0.3, wires=2) - qml.CZ(wires=[0, 1]) - qml.RY(-0.4, wires=0) + qp.CZ(wires=[0, 1]) + qp.RY(-0.4, wires=0) - qml.CZ(wires=[1, 2]) + qp.CZ(wires=[1, 2]) - return qml.expval(qml.pauli.string_to_pauli_word("ZZZ")) + return qp.expval(qp.pauli.string_to_pauli_word("ZZZ")) x = np.array(0.531, requires_grad=True) @@ -499,7 +499,7 @@ def qaoa_template(params): gamma, beta = params for i in range(len(graph)): # Apply the Hadamard gates - qml.Hadamard(wires=i) + qp.Hadamard(wires=i) for i, j in top_edges: @@ -507,9 +507,9 @@ def qaoa_template(params): # corresponding to the # green edges in the figure - qml.MultiRZ(2 * gamma, wires=[i, j]) + qp.MultiRZ(2 * gamma, wires=[i, j]) - qml.WireCut(wires=middle_nodes) # Place the wire cut + qp.WireCut(wires=middle_nodes) # Place the wire cut for i, j in bottom_edges: @@ -517,10 +517,10 @@ def qaoa_template(params): # corresponding to the # purple edges in the figure - qml.MultiRZ(2 * gamma, wires=[i, j]) + qp.MultiRZ(2 * gamma, wires=[i, j]) for i in graph.nodes(): # Finally, apply the RX gates - qml.RX(2 * beta, wires=i) + qp.RX(2 * beta, wires=i) ###################################################################### @@ -532,13 +532,13 @@ def qaoa_template(params): all_wires = list(range(len(graph))) -with qml.queuing.AnnotatedQueue() as q: +with qp.queuing.AnnotatedQueue() as q: qaoa_template(optimal_params) - qml.sample(wires=all_wires) + qp.sample(wires=all_wires) tape = QuantumTape.from_queue(q) -fig, _ = qml.drawer.tape_mpl(tape) +fig, _ = qp.drawer.tape_mpl(tape) fig.set_size_inches(12, 6) @@ -548,24 +548,24 @@ def qaoa_template(params): # # To run fragment subcircuits and combine them into a finite-shot estimate # of the optimal cost function using the Pauli cut method, we can use -# built-in PennyLane functions. We simply use the ``qml.cut_circuit_mc`` +# built-in PennyLane functions. We simply use the ``qp.cut_circuit_mc`` # transform and everything is taken care of for us. # -# Note that we have already introduced the ``qml.cut_circuit`` transform +# Note that we have already introduced the ``qp.cut_circuit`` transform # in the previous section. The ``_mc`` appendix stands for Monte Carlo and # is used to calculate finite-shot estimates of observables. The -# observable itself is passed to the ``qml.cut_circuit_mc`` transform as a +# observable itself is passed to the ``qp.cut_circuit_mc`` transform as a # function mapping a bitstring (circuit sample) to a single number. # -dev = qml.device("default.qubit", wires=all_wires) +dev = qp.device("default.qubit", wires=all_wires) -@partial(qml.cut_circuit_mc, classical_processing_fn=qaoa_cost) -@qml.qnode(dev) +@partial(qp.cut_circuit_mc, classical_processing_fn=qaoa_cost) +@qp.qnode(dev) def qaoa(params): qaoa_template(params) - return qml.sample(wires=all_wires) + return qp.sample(wires=all_wires) ###################################################################### @@ -580,7 +580,7 @@ def qaoa(params): pauli_cost_values = np.zeros_like(shot_counts, dtype=float) for i, shots in enumerate(shot_counts): - pauli_cost_values[i] = qml.set_shots(qaoa, int(shots))(optimal_params) + pauli_cost_values[i] = qp.set_shots(qaoa, int(shots))(optimal_params) ###################################################################### @@ -593,7 +593,7 @@ def qaoa(params): # As noted earlier, the easiest way to mathematically represent the # randomized channel-based method is to write down Kraus operators for the # relevant channels, :math:`\Psi _0` and :math:`\Psi _1.` Once we have -# represented them in explicit matrix form, we can simply use ``qml.QubitChannel``. +# represented them in explicit matrix form, we can simply use ``qp.QubitChannel``. # # # To get our matrices, we represent the computational basis set along the @@ -640,17 +640,17 @@ def make_kraus_ops(num_wires: int): kraus1 = np.identity(d**2).reshape(d**2, d, d) kraus1 /= np.sqrt(d) - # Finally, return a list of NumPy arrays, as per `qml.QubitChannel` docs. + # Finally, return a list of NumPy arrays, as per `qp.QubitChannel` docs. return list(kraus0.astype(complex)), list(kraus1.astype(complex)) ###################################################################### # Our next task is to generate two new ``QuantumTape`` objects from our # existing ``tape``, one for :math:`\Psi _0` and one for :math:`\Psi _1.` -# Currently, a ``qml.WireCut`` dummy gate is used to represent the cut +# Currently, a ``qp.WireCut`` dummy gate is used to represent the cut # position and size. So, iterating through gates in ``tape``: # -# - If the gate is a ``qml.WireCut``, we apply the ``qml.QubitChannel`` +# - If the gate is a ``qp.WireCut``, we apply the ``qp.QubitChannel`` # corresponding to :math:`\Psi _0` or :math:`\Psi _1` to different new # tapes. # - Otherwise, just apply the same existing gate to both new tapes. @@ -662,7 +662,7 @@ def make_kraus_ops(num_wires: int): wire_cut = None for i, op in enumerate(tape.operations): - if isinstance(op, qml.WireCut): + if isinstance(op, qp.WireCut): cut_index = i wire_cut = op break @@ -673,8 +673,8 @@ def make_kraus_ops(num_wires: int): K0, K1 = make_kraus_ops(k) # Generate Kraus operators on the fly probs = (d + 1) / (2 * d + 1), d / (2 * d + 1) # Probabilities of the two channels -psi_0 = qml.QubitChannel(K0, wires=wire_cut.wires) -psi_1 = qml.QubitChannel(K1, wires=wire_cut.wires) +psi_0 = qp.QubitChannel(K0, wires=wire_cut.wires) +psi_1 = qp.QubitChannel(K1, wires=wire_cut.wires) ops_0 = tape.operations ops_0[cut_index] = psi_0 @@ -692,7 +692,7 @@ def make_kraus_ops(num_wires: int): print(f"Cut size: k={k}") print(f"Channel probabilities: p0={probs[0]:.2f}; p1={probs[1]:.2f}", "\n") -fig, _ = qml.drawer.tape_mpl(tape0) +fig, _ = qp.drawer.tape_mpl(tape0) fig.set_size_inches(12, 6) ###################################################################### @@ -709,7 +709,7 @@ def make_kraus_ops(num_wires: int): # simulator. Luckily, PennyLane has just what we need: # -device = qml.device("default.mixed", wires=tape.wires) +device = qp.device("default.mixed", wires=tape.wires) ###################################################################### # We only need a single run for each of the two generated tapes, ``tape0`` and @@ -737,10 +737,10 @@ def make_kraus_ops(num_wires: int): tape0 = QuantumTape(ops=ops_0, measurements=tape.measurements, shots=channel_shots[0].item()) tape1 = QuantumTape(ops=ops_1, measurements=tape.measurements, shots=channel_shots[1].item()) -(shots0,) = qml.execute([tape0], device=device, cache=False, diff_method=None) +(shots0,) = qp.execute([tape0], device=device, cache=False, diff_method=None) samples[choices == 0] = shots0 -(shots1,) = qml.execute([tape1], device=device, cache=False, diff_method=None) +(shots1,) = qp.execute([tape1], device=device, cache=False, diff_method=None) samples[choices == 1] = shots1 ###################################################################### diff --git a/demonstrations_v2/tutorial_quantum_circuit_cutting/metadata.json b/demonstrations_v2/tutorial_quantum_circuit_cutting/metadata.json index 5c07f1258f..7dea29fec9 100644 --- a/demonstrations_v2/tutorial_quantum_circuit_cutting/metadata.json +++ b/demonstrations_v2/tutorial_quantum_circuit_cutting/metadata.json @@ -14,7 +14,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2022-09-02T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Algorithms", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_quantum_dropout/demo.py b/demonstrations_v2/tutorial_quantum_dropout/demo.py index 4469c56943..bef5b9b756 100644 --- a/demonstrations_v2/tutorial_quantum_dropout/demo.py +++ b/demonstrations_v2/tutorial_quantum_dropout/demo.py @@ -55,7 +55,7 @@ # import numpy as np -import pennylane as qml +import pennylane as qp seed = 12345 np.random.seed(seed=seed) @@ -91,9 +91,9 @@ def embedding(x, wires): # employing also nonlinear functions assert len(x) == 1 # check feature is 1-D for i in wires: - qml.RY(jnp.arcsin(x), wires=i) + qp.RY(jnp.arcsin(x), wires=i) for i in wires: - qml.RZ(jnp.arccos(x ** 2), wires=i) + qp.RZ(jnp.arccos(x ** 2), wires=i) def true_cond(angle): @@ -111,7 +111,7 @@ def false_cond(angle): def var_ansatz( - theta, wires, rotations=[qml.RX, qml.RZ, qml.RX], entangler=qml.CNOT, keep_rotation=None + theta, wires, rotations=[qp.RX, qp.RZ, qp.RX], entangler=qp.CNOT, keep_rotation=None ): """Single layer of the variational ansatz for our QNN. @@ -170,9 +170,9 @@ def var_ansatz( def create_circuit(n_qubits, layers): - device = qml.device("default.qubit", wires=n_qubits) + device = qp.device("default.qubit", wires=n_qubits) - @qml.qnode(device) + @qp.qnode(device) def circuit(x, theta, keep_rot): # print(x) # print(theta) @@ -185,11 +185,11 @@ def circuit(x, theta, keep_rot): var_ansatz( theta[i * params_per_layer : (i + 1) * params_per_layer], wires=range(n_qubits), - entangler=qml.CNOT, + entangler=qp.CNOT, keep_rotation=keep_rotation, ) - return qml.expval(qml.PauliZ(wires=0)) # we measure only the first qubit + return qp.expval(qp.PauliZ(wires=0)) # we measure only the first qubit return circuit @@ -215,7 +215,7 @@ def circuit(x, theta, keep_rot): # we encode a single coordinate single_sample = np.array([0]) -qml.draw_mpl(circ, decimals=2,)(single_sample, numbered_params, keep_all_rot) +qp.draw_mpl(circ, decimals=2,)(single_sample, numbered_params, keep_all_rot) plt.show() diff --git a/demonstrations_v2/tutorial_quantum_dropout/metadata.json b/demonstrations_v2/tutorial_quantum_dropout/metadata.json index 3620227380..411c815c9b 100644 --- a/demonstrations_v2/tutorial_quantum_dropout/metadata.json +++ b/demonstrations_v2/tutorial_quantum_dropout/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-03-12T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Machine Learning" ], diff --git a/demonstrations_v2/tutorial_quantum_gans/demo.py b/demonstrations_v2/tutorial_quantum_gans/demo.py index 9883817a9c..a642a48cc4 100644 --- a/demonstrations_v2/tutorial_quantum_gans/demo.py +++ b/demonstrations_v2/tutorial_quantum_gans/demo.py @@ -132,7 +132,7 @@ import pandas as pd import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec -import pennylane as qml +import pennylane as qp # Pytorch imports import torch @@ -366,32 +366,32 @@ def forward(self, x): # # Quantum simulator -dev = qml.device("lightning.qubit", wires=n_qubits) +dev = qp.device("lightning.qubit", wires=n_qubits) # Enable CUDA device if available device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") ###################################################################### # Next, we define the quantum circuit and measurement process described above. -@qml.qnode(dev, diff_method="parameter-shift") +@qp.qnode(dev, diff_method="parameter-shift") def quantum_circuit(noise, weights): weights = weights.reshape(q_depth, n_qubits) # Initialise latent vectors for i in range(n_qubits): - qml.RY(noise[i], wires=i) + qp.RY(noise[i], wires=i) # Repeated layer for i in range(q_depth): # Parameterised layer for y in range(n_qubits): - qml.RY(weights[i][y], wires=y) + qp.RY(weights[i][y], wires=y) # Control Z gates for y in range(n_qubits - 1): - qml.CZ(wires=[y, y + 1]) + qp.CZ(wires=[y, y + 1]) - return qml.probs(wires=list(range(n_qubits))) + return qp.probs(wires=list(range(n_qubits))) # For further info on how the non-linear transform is implemented in Pennylane diff --git a/demonstrations_v2/tutorial_quantum_gans/metadata.json b/demonstrations_v2/tutorial_quantum_gans/metadata.json index c07e0c8b38..47a5365623 100644 --- a/demonstrations_v2/tutorial_quantum_gans/metadata.json +++ b/demonstrations_v2/tutorial_quantum_gans/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2022-02-01T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Machine Learning" ], diff --git a/demonstrations_v2/tutorial_quantum_metrology/demo.py b/demonstrations_v2/tutorial_quantum_metrology/demo.py index 6340f0c1b3..40d357da59 100644 --- a/demonstrations_v2/tutorial_quantum_metrology/demo.py +++ b/demonstrations_v2/tutorial_quantum_metrology/demo.py @@ -119,7 +119,7 @@ We now turn to the actual implementation of the scheme. """ -import pennylane as qml +import pennylane as qp from pennylane import numpy as np @@ -132,7 +132,7 @@ # We will choose the ``cirq.mixedsimulator`` device from the # `Pennylane-Cirq `_ # plugin for this tutorial. -dev = qml.device("cirq.mixedsimulator", wires=3) +dev = qp.device("cirq.mixedsimulator", wires=3) ############################################################################## # Next, we model the parameter encoding. The phase shifts are recreated using @@ -143,7 +143,7 @@ def encoding(phi, gamma): for i in range(3): - qml.RZ(phi[i], wires=[i]) + qp.RZ(phi[i], wires=[i]) cirq_ops.PhaseDamp(gamma, wires=[i]) @@ -156,7 +156,7 @@ def encoding(phi, gamma): def ansatz(weights): - qml.ArbitraryStatePreparation(weights, wires=[0, 1, 2]) + qp.ArbitraryStatePreparation(weights, wires=[0, 1, 2]) NUM_ANSATZ_PARAMETERS = 14 @@ -164,7 +164,7 @@ def ansatz(weights): def measurement(weights): for i in range(3): - qml.ArbitraryStatePreparation(weights[2 * i : 2 * (i + 1)], wires=[i]) + qp.ArbitraryStatePreparation(weights[2 * i : 2 * (i + 1)], wires=[i]) NUM_MEASUREMENT_PARAMETERS = 6 @@ -174,19 +174,19 @@ def measurement(weights): # We now have everything at hand to model the quantum part of our experiment # as a QNode. We will return the output probabilities necessary to compute the # Classical Fisher Information Matrix. -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def experiment(weights, phi, gamma=0.0): ansatz(weights[:NUM_ANSATZ_PARAMETERS]) encoding(phi, gamma) measurement(weights[NUM_ANSATZ_PARAMETERS:]) - return qml.probs(wires=[0, 1, 2]) + return qp.probs(wires=[0, 1, 2]) # Draw the circuit at the given parameter values print( - qml.draw(experiment, level="device", max_length=80)( + qp.draw(experiment, level="device", max_length=80)( np.arange(NUM_ANSATZ_PARAMETERS + NUM_MEASUREMENT_PARAMETERS), np.zeros(3), gamma=0.2, @@ -285,7 +285,7 @@ def opt_cost(weights, phi=phi, gamma=gamma, J=J, W=W): requires_grad=True, ) -opt = qml.AdagradOptimizer(stepsize=0.1) +opt = qp.AdagradOptimizer(stepsize=0.1) print("Initialization: Cost = {:6.4f}".format(opt_cost(weights))) for i in range(20): diff --git a/demonstrations_v2/tutorial_quantum_metrology/metadata.json b/demonstrations_v2/tutorial_quantum_metrology/metadata.json index f6e3173885..242aee7d9a 100644 --- a/demonstrations_v2/tutorial_quantum_metrology/metadata.json +++ b/demonstrations_v2/tutorial_quantum_metrology/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2020-06-18T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_quantum_natural_gradient/demo.py b/demonstrations_v2/tutorial_quantum_natural_gradient/demo.py index 44f59b57e6..405f77819b 100644 --- a/demonstrations_v2/tutorial_quantum_natural_gradient/demo.py +++ b/demonstrations_v2/tutorial_quantum_natural_gradient/demo.py @@ -185,36 +185,36 @@ # Let's consider a small variational quantum circuit example coded in PennyLane: import numpy as np -import pennylane as qml +import pennylane as qp from pennylane import numpy as pnp -dev = qml.device("lightning.qubit", wires=3) +dev = qp.device("lightning.qubit", wires=3) -@qml.qnode(dev, interface="autograd", diff_method="parameter-shift") +@qp.qnode(dev, interface="autograd", diff_method="parameter-shift") def circuit(params): # |psi_0>: state preparation - qml.RY(np.pi / 4, wires=0) - qml.RY(np.pi / 3, wires=1) - qml.RY(np.pi / 7, wires=2) + qp.RY(np.pi / 4, wires=0) + qp.RY(np.pi / 3, wires=1) + qp.RY(np.pi / 7, wires=2) # V0(theta0, theta1): Parametrized layer 0 - qml.RZ(params[0], wires=0) - qml.RZ(params[1], wires=1) + qp.RZ(params[0], wires=0) + qp.RZ(params[1], wires=1) # W1: non-parametrized gates - qml.CNOT(wires=[0, 1]) - qml.CNOT(wires=[1, 2]) + qp.CNOT(wires=[0, 1]) + qp.CNOT(wires=[1, 2]) # V_1(theta2, theta3): Parametrized layer 1 - qml.RY(params[2], wires=1) - qml.RX(params[3], wires=2) + qp.RY(params[2], wires=1) + qp.RX(params[3], wires=2) # W2: non-parametrized gates - qml.CNOT(wires=[0, 1]) - qml.CNOT(wires=[1, 2]) + qp.CNOT(wires=[0, 1]) + qp.CNOT(wires=[1, 2]) - return qml.expval(qml.PauliY(0)) + return qp.expval(qp.PauliY(0)) # Use pennylane.numpy for trainable parameters params = pnp.array([0.432, -0.123, 0.543, 0.233]) @@ -255,9 +255,9 @@ def circuit(params): def layer0_subcircuit(params): """This function contains all gates that precede parametrized layer 0""" - qml.RY(np.pi / 4, wires=0) - qml.RY(np.pi / 3, wires=1) - qml.RY(np.pi / 7, wires=2) + qp.RY(np.pi / 4, wires=0) + qp.RY(np.pi / 3, wires=1) + qp.RY(np.pi / 7, wires=2) ############################################################################## @@ -272,10 +272,10 @@ def layer0_subcircuit(params): # We can see that the diagonal terms are simply given by the variance: -@qml.qnode(dev, interface="autograd") +@qp.qnode(dev, interface="autograd") def layer0_diag(params): layer0_subcircuit(params) - return qml.var(qml.PauliZ(0)), qml.var(qml.PauliZ(1)) + return qp.var(qp.PauliZ(0)), qp.var(qp.PauliZ(1)) # calculate the diagonal terms @@ -288,17 +288,17 @@ def layer0_diag(params): # off-diagonal covariance terms of :math:`g^{(0)}:` -@qml.qnode(dev, interface="autograd") +@qp.qnode(dev, interface="autograd") def layer0_off_diag_single(params): layer0_subcircuit(params) - return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)) + return qp.expval(qp.PauliZ(0)), qp.expval(qp.PauliZ(1)) -@qml.qnode(dev, interface="autograd") +@qp.qnode(dev, interface="autograd") def layer0_off_diag_double(params): layer0_subcircuit(params) ZZ = np.kron(np.diag([1, -1]), np.diag([1, -1])) - return qml.expval(qml.Hermitian(ZZ, wires=[0, 1])) + return qp.expval(qp.Hermitian(ZZ, wires=[0, 1])) # calculate the off-diagonal terms @@ -327,17 +327,17 @@ def layer1_subcircuit(params): """This function contains all gates that precede parametrized layer 1""" # |psi_0>: state preparation - qml.RY(np.pi / 4, wires=0) - qml.RY(np.pi / 3, wires=1) - qml.RY(np.pi / 7, wires=2) + qp.RY(np.pi / 4, wires=0) + qp.RY(np.pi / 3, wires=1) + qp.RY(np.pi / 7, wires=2) # V0(theta0, theta1): Parametrized layer 0 - qml.RZ(params[0], wires=0) - qml.RZ(params[1], wires=1) + qp.RZ(params[0], wires=0) + qp.RZ(params[1], wires=1) # W1: non-parametrized gates - qml.CNOT(wires=[0, 1]) - qml.CNOT(wires=[1, 2]) + qp.CNOT(wires=[0, 1]) + qp.CNOT(wires=[1, 2]) ############################################################################## @@ -349,10 +349,10 @@ def layer1_subcircuit(params): # :target: javascript:void(0) -@qml.qnode(dev, interface="autograd") +@qp.qnode(dev, interface="autograd") def layer1_diag(params): layer1_subcircuit(params) - return qml.var(qml.PauliY(1)), qml.var(qml.PauliX(2)) + return qp.var(qp.PauliY(1)), qp.var(qp.PauliX(2)) ############################################################################## @@ -368,19 +368,19 @@ def layer1_diag(params): # observables to be computed. -@qml.qnode(dev, interface="autograd") +@qp.qnode(dev, interface="autograd") def layer1_off_diag_single(params): layer1_subcircuit(params) - return qml.expval(qml.PauliY(1)), qml.expval(qml.PauliX(2)) + return qp.expval(qp.PauliY(1)), qp.expval(qp.PauliX(2)) -@qml.qnode(dev, interface="autograd") +@qp.qnode(dev, interface="autograd") def layer1_off_diag_double(params): layer1_subcircuit(params) X = np.array([[0, 1], [1, 0]]) Y = np.array([[0, -1j], [1j, 0]]) YX = np.kron(Y, X) - return qml.expval(qml.Hermitian(YX, wires=[1, 2])) + return qp.expval(qp.Hermitian(YX, wires=[1, 2])) # calculate the off-diagonal terms @@ -404,7 +404,7 @@ def layer1_off_diag_double(params): # PennyLane contains a built-in function for computing the Fubini-Study metric # tensor, :func:`~.pennylane.metric_tensor`, which # we can use to verify this result: -print(np.round(qml.metric_tensor(circuit, approx="block-diag")(params), 8)) +print(np.round(qp.metric_tensor(circuit, approx="block-diag")(params), 8)) ############################################################################## # As opposed to our manual computation, which required 6 different quantum @@ -420,7 +420,7 @@ def layer1_off_diag_double(params): # # Note that the :func:`~.pennylane.metric_tensor` function also supports computing the diagonal # approximation to the metric tensor: -print(qml.metric_tensor(circuit, approx='diag')(params)) +print(qp.metric_tensor(circuit, approx='diag')(params)) ############################################################################## # Furthermore, the returned metric tensor is **full differentiable**; include it @@ -442,7 +442,7 @@ def layer1_off_diag_double(params): # Performing vanilla gradient descent: gd_cost = [] -opt = qml.GradientDescentOptimizer(0.01) +opt = qp.GradientDescentOptimizer(0.01) theta = init_params for _ in range(steps): @@ -453,7 +453,7 @@ def layer1_off_diag_double(params): # Performing quantum natural gradient descent: qng_cost = [] -opt = qml.QNGOptimizer(0.01) +opt = qp.QNGOptimizer(0.01) theta = init_params for _ in range(steps): diff --git a/demonstrations_v2/tutorial_quantum_natural_gradient/metadata.json b/demonstrations_v2/tutorial_quantum_natural_gradient/metadata.json index 3c62496128..62d7441fbb 100644 --- a/demonstrations_v2/tutorial_quantum_natural_gradient/metadata.json +++ b/demonstrations_v2/tutorial_quantum_natural_gradient/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2019-10-11T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_quantum_phase_transitions/demo.py b/demonstrations_v2/tutorial_quantum_phase_transitions/demo.py index 6510ef32ce..4ba0e5548d 100644 --- a/demonstrations_v2/tutorial_quantum_phase_transitions/demo.py +++ b/demonstrations_v2/tutorial_quantum_phase_transitions/demo.py @@ -78,7 +78,7 @@ # # The code below creates this Hamiltonian for three qubits: # -import pennylane as qml +import pennylane as qp from pennylane import numpy as np @@ -86,14 +86,14 @@ J = 2 wires = range(N) -dev = qml.device("lightning.qubit", wires=N) +dev = qp.device("lightning.qubit", wires=N) coeffs = [-J] * (N - 1) obs = [] for i in range(N - 1): - obs.append(qml.Z(i) @ qml.Z(i + 1)) -H = qml.Hamiltonian(coeffs, obs) + obs.append(qp.Z(i) @ qp.Z(i + 1)) +H = qp.Hamiltonian(coeffs, obs) print(f"H={H}") @@ -141,31 +141,31 @@ def create_ansatz(params, N): # STEP 1: perform single-qubit rotations on all the qubits for i in range(N): - qml.RZ(phi=params[i], wires=i) - qml.RX(phi=params[N + i], wires=i) - qml.RZ(phi=params[2 * N + i], wires=i) + qp.RZ(phi=params[i], wires=i) + qp.RX(phi=params[N + i], wires=i) + qp.RZ(phi=params[2 * N + i], wires=i) # STEP 2: perform a CNOT gate on each pair of neighbouring qubits for i in range(N - 1): - qml.CNOT(wires=[i, i + 1]) + qp.CNOT(wires=[i, i + 1]) # STEP 3: perform single-qubit rotations on all the qubits for i in range(N): - qml.RZ(phi=params[3 * N + i], wires=i) - qml.RX(phi=params[4 * N + i], wires=i) - qml.RZ(phi=params[5 * N + i], wires=i) + qp.RZ(phi=params[3 * N + i], wires=i) + qp.RX(phi=params[4 * N + i], wires=i) + qp.RZ(phi=params[5 * N + i], wires=i) -@qml.qnode(dev) +@qp.qnode(dev) def quantum_circuit(params): # Create a quantum state using params create_ansatz(params, N) - return qml.expval(H) + return qp.expval(H) max_iters = 200 tolerance = 1e-04 # create an optimizer -opt = qml.GradientDescentOptimizer(stepsize=0.1) +opt = qp.GradientDescentOptimizer(stepsize=0.1) # energy is a list that stores all the estimates for the ground-state energy energy = [] @@ -279,30 +279,30 @@ def quantum_circuit(params): # Store the expectation values of the magnetization operator M for different values of J/h_x magnetization_list = [] -dev_2 = qml.device("lightning.qubit", wires=N) +dev_2 = qp.device("lightning.qubit", wires=N) # This function prepares an estimate of the ground state & calculates its energy. -@qml.qnode(dev_2) +@qp.qnode(dev_2) def quantum_circuit_2(params): # Generate an estimate of the ground state create_ansatz(params, N) - return qml.expval(H) + return qp.expval(H) # A function that returns the magnetization operator of N qubits. def magnetization_op(N): - total_op = qml.PauliZ(0) + total_op = qp.PauliZ(0) if N > 1: for i in range(1, N): - total_op = total_op + qml.PauliZ(i) + total_op = total_op + qp.PauliZ(i) return total_op / N #Prepare a parameterized state & return the value of the magnetization operator. -@qml.qnode(dev_2) +@qp.qnode(dev_2) def calculate_magnetization(params): create_ansatz(params, N) - return qml.expval(magnetization_op(N)) + return qp.expval(magnetization_op(N)) # Loop through all the different values of J for i in range(len(J_list)): @@ -314,14 +314,14 @@ def calculate_magnetization(params): obs = [] for j in range(N - 1): - obs.append(qml.Z(j) @ qml.Z(j + 1)) + obs.append(qp.Z(j) @ qp.Z(j + 1)) # Add Pauli X terms to the Hamiltonian for j in range(N): - obs.append(qml.X(j)) + obs.append(qp.X(j)) coeffs.append(-h_x) - H = qml.Hamiltonian(coeffs, obs) + H = qp.Hamiltonian(coeffs, obs) params = np.array([2 * np.pi * random.uniform(0, 1)] * (6 * N), requires_grad=True) @@ -329,7 +329,7 @@ def calculate_magnetization(params): tolerance = 1e-04 # create an optimizer - opt = qml.MomentumOptimizer(stepsize=0.02, momentum=0.9) + opt = qp.MomentumOptimizer(stepsize=0.02, momentum=0.9) energy = [] @@ -432,7 +432,7 @@ def calculate_magnetization(params): N = 2 -H = qml.spin.transverse_ising(lattice="square", n_cells=[N, N], h=1.0, boundary_condition=True) +H = qp.spin.transverse_ising(lattice="square", n_cells=[N, N], h=1.0, boundary_condition=True) print(f"H={H}") @@ -441,23 +441,23 @@ def calculate_magnetization(params): # wires_2D = range(N**2) -dev_2D = qml.device("lightning.qubit", wires=wires_2D) +dev_2D = qp.device("lightning.qubit", wires=wires_2D) random.seed(a=10) # generate random parameter values for the initial statevector params = np.array([2 * np.pi * random.uniform(0, 1)] * (6 * N), requires_grad=True) -@qml.qnode(dev_2D) +@qp.qnode(dev_2D) def quantum_circuit_2D(params): create_ansatz(params, N) - return qml.expval(H) + return qp.expval(H) max_iters = 500 tolerance = 3e-04 # create an optimizer -opt = qml.GradientDescentOptimizer(stepsize=0.015) +opt = qp.GradientDescentOptimizer(stepsize=0.015) energy = [] @@ -484,7 +484,7 @@ def quantum_circuit_2D(params): # N = 3 -dev_2D_varying_J = qml.device("lightning.qubit", wires=N**2) +dev_2D_varying_J = qp.device("lightning.qubit", wires=N**2) # strength of transverse magnetic field h_x = 1 @@ -495,19 +495,19 @@ def quantum_circuit_2D(params): magnetization_list = [] # Prepare a parameterized state & calculate the value of the magnetization operator. -@qml.qnode(dev_2D_varying_J) +@qp.qnode(dev_2D_varying_J) def calculate_magnetization_2D(params): create_ansatz(params, N) - return qml.expval(magnetization_op(N)) + return qp.expval(magnetization_op(N)) -@qml.qnode(dev_2D_varying_J) +@qp.qnode(dev_2D_varying_J) def quantum_circuit_2D_varying_J(params): create_ansatz(params, N) - return qml.expval(H) + return qp.expval(H) # Loop through all values of J for i in range(len(J_list)): - H = qml.spin.transverse_ising( + H = qp.spin.transverse_ising( lattice="square", coupling=J_list[i], n_cells=[N, N], boundary_condition=True ) #Set the initial values of the rotation angle parameters. @@ -521,7 +521,7 @@ def quantum_circuit_2D_varying_J(params): max_iters = 500 # create an optimizer - opt = qml.MomentumOptimizer(stepsize=0.03, momentum=0.9) + opt = qp.MomentumOptimizer(stepsize=0.03, momentum=0.9) energy = [] @@ -584,18 +584,18 @@ def quantum_circuit_2D_varying_J(params): # We do this to copy what was done in Reference 13: https://arxiv.org/abs/2008.04894 obs = [] for j in range(N - 1): - obs.append(qml.Z(j) @ qml.Z(j + 1)) -obs.append(qml.Z(N-1) @ qml.Z(0)) + obs.append(qp.Z(j) @ qp.Z(j + 1)) +obs.append(qp.Z(N-1) @ qp.Z(0)) # add Pauli X terms to Hamiltonian (transverse field) for j in range(N): - obs.append(qml.X(j)) + obs.append(qp.X(j)) # add Pauli Z terms to Hamiltonian (longitudinal field) for j in range(N): - obs.append(qml.Z(j)) + obs.append(qp.Z(j)) -dev = qml.device("lightning.qubit", wires=N) +dev = qp.device("lightning.qubit", wires=N) J = -0.1 @@ -613,17 +613,17 @@ def quantum_circuit_2D_varying_J(params): coeffs = J_coeffs + X_coeffs + Z_coeffs -H = qml.Hamiltonian(coeffs, obs) +H = qp.Hamiltonian(coeffs, obs) # create the circuit that evolves the system in time -@qml.qnode(dev) +@qp.qnode(dev) def time_evolution_circuit(H, T): #Evolve the system via a sequence of short approximate Trotter time steps #https://docs.pennylane.ai/en/stable/code/api/pennylane.TrotterProduct.html - qml.TrotterProduct(H, time=T, n=math.ceil(T / 0.1)+1, order=2) + qp.TrotterProduct(H, time=T, n=math.ceil(T / 0.1)+1, order=2) # return the final probabilities - return qml.probs(wires=range(N)) + return qp.probs(wires=range(N)) ############################################################################## diff --git a/demonstrations_v2/tutorial_quantum_phase_transitions/metadata.json b/demonstrations_v2/tutorial_quantum_phase_transitions/metadata.json index ffeea8659c..75397ca2a8 100644 --- a/demonstrations_v2/tutorial_quantum_phase_transitions/metadata.json +++ b/demonstrations_v2/tutorial_quantum_phase_transitions/metadata.json @@ -9,7 +9,7 @@ } ], "dateOfPublication": "2025-10-28T00:00:00+00:00", - "dateOfLastModification": "2025-10-30T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": ["Optimization","Quantum Machine Learning"], "tags": ["quantum phase transition", "Ising model"], "previewImages": [ diff --git a/demonstrations_v2/tutorial_quantum_transfer_learning/demo.py b/demonstrations_v2/tutorial_quantum_transfer_learning/demo.py index 1cf90b6c24..3c5e316062 100644 --- a/demonstrations_v2/tutorial_quantum_transfer_learning/demo.py +++ b/demonstrations_v2/tutorial_quantum_transfer_learning/demo.py @@ -133,7 +133,7 @@ from torchvision import datasets, transforms # Pennylane -import pennylane as qml +import pennylane as qp from pennylane import numpy as np torch.manual_seed(42) @@ -167,7 +167,7 @@ ############################################################################## # We initialize a PennyLane device with a ``default.qubit`` backend. -dev = qml.device("default.qubit", wires=n_qubits) +dev = qp.device("default.qubit", wires=n_qubits) ############################################################################## # We configure PyTorch to use CUDA only if available. Otherwise the CPU is used. @@ -274,14 +274,14 @@ def H_layer(nqubits): """Layer of single-qubit Hadamard gates. """ for idx in range(nqubits): - qml.Hadamard(wires=idx) + qp.Hadamard(wires=idx) def RY_layer(w): """Layer of parametrized qubit rotations around the y axis. """ for idx, element in enumerate(w): - qml.RY(element, wires=idx) + qp.RY(element, wires=idx) def entangling_layer(nqubits): @@ -291,9 +291,9 @@ def entangling_layer(nqubits): # CNOT CNOT CNOT CNOT... CNOT # CNOT CNOT CNOT... CNOT for i in range(0, nqubits - 1, 2): # Loop over even indices: i=0,2,...N-2 - qml.CNOT(wires=[i, i + 1]) + qp.CNOT(wires=[i, i + 1]) for i in range(1, nqubits - 1, 2): # Loop over odd indices: i=1,3,...N-3 - qml.CNOT(wires=[i, i + 1]) + qp.CNOT(wires=[i, i + 1]) ############################################################################## @@ -313,7 +313,7 @@ def entangling_layer(nqubits): # additional post-processing. -@qml.qnode(dev) +@qp.qnode(dev) def quantum_net(q_input_features, q_weights_flat): """ The variational quantum circuit. @@ -334,7 +334,7 @@ def quantum_net(q_input_features, q_weights_flat): RY_layer(q_weights[k]) # Expectation values in the Z basis - exp_vals = [qml.expval(qml.PauliZ(position)) for position in range(n_qubits)] + exp_vals = [qp.expval(qp.PauliZ(position)) for position in range(n_qubits)] return tuple(exp_vals) diff --git a/demonstrations_v2/tutorial_quantum_transfer_learning/metadata.json b/demonstrations_v2/tutorial_quantum_transfer_learning/metadata.json index f586354c9a..f67e0590b4 100644 --- a/demonstrations_v2/tutorial_quantum_transfer_learning/metadata.json +++ b/demonstrations_v2/tutorial_quantum_transfer_learning/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2019-12-19T00:00:00+00:00", - "dateOfLastModification": "2025-11-10T11:00:00+00:00", + "dateOfLastModification": "2026-04-17T11:00:00+00:00", "categories": [ "Quantum Machine Learning" ], diff --git a/demonstrations_v2/tutorial_quanvolution/demo.py b/demonstrations_v2/tutorial_quanvolution/demo.py index 7ada3a800c..c7525d9a8d 100644 --- a/demonstrations_v2/tutorial_quanvolution/demo.py +++ b/demonstrations_v2/tutorial_quanvolution/demo.py @@ -83,7 +83,7 @@ This Python code requires *PennyLane* with the *TensorFlow* interface and the plotting library *matplotlib*. """ -import pennylane as qml +import pennylane as qp from pennylane import numpy as np from pennylane.templates import RandomLayers import tensorflow as tf @@ -146,21 +146,21 @@ # 3. a final measurement in the computational basis, estimating :math:`4` expectation values. -dev = qml.device("default.qubit", wires=4) +dev = qp.device("default.qubit", wires=4) # Random circuit parameters rand_params = np.random.uniform(high=2 * np.pi, size=(n_layers, 4)) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(phi): # Encoding of 4 classical input values for j in range(4): - qml.RY(np.pi * phi[j], wires=j) + qp.RY(np.pi * phi[j], wires=j) # Random quantum circuit RandomLayers(rand_params, wires=list(range(4))) # Measurement producing 4 classical output values - return [qml.expval(qml.PauliZ(j)) for j in range(4)] + return [qp.expval(qp.PauliZ(j)) for j in range(4)] ############################################################################## diff --git a/demonstrations_v2/tutorial_quanvolution/metadata.json b/demonstrations_v2/tutorial_quanvolution/metadata.json index d44930f757..ecb21ac8da 100644 --- a/demonstrations_v2/tutorial_quanvolution/metadata.json +++ b/demonstrations_v2/tutorial_quanvolution/metadata.json @@ -8,7 +8,7 @@ "executable_stable": false, "executable_latest": false, "dateOfPublication": "2020-03-24T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Quantum Machine Learning" ], diff --git a/demonstrations_v2/tutorial_qubit_rotation/demo.py b/demonstrations_v2/tutorial_qubit_rotation/demo.py index cf68662eaf..16163f009f 100644 --- a/demonstrations_v2/tutorial_qubit_rotation/demo.py +++ b/demonstrations_v2/tutorial_qubit_rotation/demo.py @@ -86,7 +86,7 @@ # The first thing we need to do is import PennyLane, as well as the wrapped version # of NumPy provided by Jax. -import pennylane as qml +import pennylane as qp from jax import numpy as np import jax @@ -118,7 +118,7 @@ # For this tutorial, we are using the qubit model, so let's initialize the ``'lightning.qubit'`` device # provided by PennyLane. -dev1 = qml.device("lightning.qubit", wires=1) +dev1 = qp.device("lightning.qubit", wires=1) ############################################################################## # For all devices, :func:`~.pennylane.device` accepts the following arguments: @@ -152,9 +152,9 @@ def circuit(params): - qml.RX(params[0], wires=0) - qml.RY(params[1], wires=0) - return qml.expval(qml.PauliZ(0)) + qp.RX(params[0], wires=0) + qp.RY(params[1], wires=0) + return qp.expval(qp.PauliZ(0)) ############################################################################## @@ -195,11 +195,11 @@ def circuit(params): # **directly above** the function definition: -@qml.qnode(dev1) +@qp.qnode(dev1) def circuit(params): - qml.RX(params[0], wires=0) - qml.RY(params[1], wires=0) - return qml.expval(qml.PauliZ(0)) + qp.RX(params[0], wires=0) + qp.RY(params[1], wires=0) + return qp.expval(qp.PauliZ(0)) ############################################################################## @@ -248,11 +248,11 @@ def circuit(params): # two positional arguments, instead of one array argument: -@qml.qnode(dev1) +@qp.qnode(dev1) def circuit2(phi1, phi2): - qml.RX(phi1, wires=0) - qml.RY(phi2, wires=0) - return qml.expval(qml.PauliZ(0)) + qp.RX(phi1, wires=0) + qp.RY(phi2, wires=0) + return qp.expval(qp.PauliZ(0)) ################################################################################ diff --git a/demonstrations_v2/tutorial_qubit_rotation/metadata.json b/demonstrations_v2/tutorial_qubit_rotation/metadata.json index 0d9725d3e2..f8e7e1b502 100644 --- a/demonstrations_v2/tutorial_qubit_rotation/metadata.json +++ b/demonstrations_v2/tutorial_qubit_rotation/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2019-10-11T00:00:00+00:00", - "dateOfLastModification": "2026-02-15T14:40:02+02:00", + "dateOfLastModification": "2026-04-17T14:40:02+02:00", "categories": [ "Getting Started" ], diff --git a/demonstrations_v2/tutorial_qubit_tapering/demo.py b/demonstrations_v2/tutorial_qubit_tapering/demo.py index 5f338e68f3..d7b4235b36 100644 --- a/demonstrations_v2/tutorial_qubit_tapering/demo.py +++ b/demonstrations_v2/tutorial_qubit_tapering/demo.py @@ -119,7 +119,7 @@ In PennyLane, a :doc:`molecular Hamiltonian ` can be created by specifying the atomic symbols and coordinates. """ -import pennylane as qml +import pennylane as qp from jax import numpy as jnp import jax @@ -128,8 +128,8 @@ geometry = jnp.array([[0.00000000, 0.00000000, -0.87818361], [0.00000000, 0.00000000, 0.87818362]]) -molecule = qml.qchem.Molecule(symbols, geometry, charge=1) -H, qubits = qml.qchem.molecular_hamiltonian(molecule) +molecule = qp.qchem.Molecule(symbols, geometry, charge=1) +H, qubits = qp.qchem.molecular_hamiltonian(molecule) H ############################################################################## @@ -140,8 +140,8 @@ # Hamiltonian. In PennyLane, these are constructed by using the # :func:`~.pennylane.symmetry_generators` and :func:`~.pennylane.paulix_ops` functions. -generators = qml.symmetry_generators(H) -paulixops = qml.paulix_ops(generators, qubits) +generators = qp.symmetry_generators(H) +paulixops = qp.paulix_ops(generators, qubits) for idx, generator in enumerate(generators): print(f"generator {idx+1}: {generator}, paulix_op: {paulixops[idx]}") @@ -157,7 +157,7 @@ n_electrons = 2 -paulix_sector = qml.qchem.optimal_sector(H, generators, n_electrons) +paulix_sector = qp.qchem.optimal_sector(H, generators, n_electrons) print(paulix_sector) ############################################################################## @@ -167,9 +167,9 @@ # qubits :math:`q_2, q_3` by replacing the Pauli-X operators acting on those qubits with the optimal # eigenvalues. -H_tapered = qml.taper(H, generators, paulixops, paulix_sector) +H_tapered = qp.taper(H, generators, paulixops, paulix_sector) H_tapered_coeffs, H_tapered_ops = H_tapered.terms() -H_tapered = qml.Hamiltonian(jnp.real(jnp.array(H_tapered_coeffs)), H_tapered_ops) +H_tapered = qp.Hamiltonian(jnp.real(jnp.array(H_tapered_coeffs)), H_tapered_ops) print(H_tapered) ############################################################################## @@ -180,11 +180,11 @@ # representation of Hamiltonians. This allows us to directly diagonalize them to obtain exact values # of the ground-state energies. -H_sparse = qml.SparseHamiltonian(H.sparse_matrix(), wires=H.wires) -H_tapered_sparse = qml.SparseHamiltonian(H_tapered.sparse_matrix(), wires=H_tapered.wires) +H_sparse = qp.SparseHamiltonian(H.sparse_matrix(), wires=H.wires) +H_tapered_sparse = qp.SparseHamiltonian(H_tapered.sparse_matrix(), wires=H_tapered.wires) -print("Eigenvalues of H:\n", qml.eigvals(H_sparse, k=16)) -print("\nEigenvalues of H_tapered:\n", qml.eigvals(H_tapered_sparse, k=4)) +print("Eigenvalues of H:\n", qp.eigvals(H_sparse, k=16)) +print("\nEigenvalues of H_tapered:\n", qp.eigvals(H_tapered_sparse, k=4)) ############################################################################## # Note that a second-quantized Hamiltonian is independent of the number of electrons and its @@ -205,7 +205,7 @@ # Hamiltonian. This reduces the number of qubits in the Hartree-Fock state to match that of the # tapered Hamiltonian. It can be done with the :func:`~.pennylane.qchem.taper_hf` function. -state_tapered = qml.qchem.taper_hf(generators, paulixops, paulix_sector, +state_tapered = qp.qchem.taper_hf(generators, paulixops, paulix_sector, num_electrons=n_electrons, num_wires=len(H.wires)) print(state_tapered) @@ -214,21 +214,21 @@ # :math:`[1 1 0 0].` We can now generate the qubit representation of these states and compute the # Hartree-Fock energies for each Hamiltonian. -dev = qml.device("default.qubit", wires=H.wires) -@qml.qnode(dev, interface="jax") +dev = qp.device("default.qubit", wires=H.wires) +@qp.qnode(dev, interface="jax") def circuit(): - qml.BasisState(jnp.array([1, 1, 0, 0]), wires=H.wires) - return qml.state() + qp.BasisState(jnp.array([1, 1, 0, 0]), wires=H.wires) + return qp.state() qubit_state = circuit() HF_energy = qubit_state.T @ H.sparse_matrix().toarray() @ qubit_state print(f"HF energy: {jnp.real(HF_energy):.8f} Ha") -dev = qml.device("lightning.qubit", wires=H_tapered.wires) -@qml.qnode(dev, interface="jax") +dev = qp.device("lightning.qubit", wires=H_tapered.wires) +@qp.qnode(dev, interface="jax") def circuit(): - qml.BasisState(jnp.array([1, 1]), wires=H_tapered.wires) - return qml.state() + qp.BasisState(jnp.array([1, 1]), wires=H_tapered.wires) + return qp.state() qubit_state = circuit() HF_energy = qubit_state.T @ H_tapered.sparse_matrix().toarray() @ qubit_state @@ -247,24 +247,24 @@ def circuit(): # :func:`~.pennylane.DoubleExcitation` operations tapered using # :func:`~.pennylane.qchem.taper_operation`. -singles, doubles = qml.qchem.excitations(n_electrons, len(H.wires)) +singles, doubles = qp.qchem.excitations(n_electrons, len(H.wires)) tapered_doubles = [ - qml.taper_operation(qml.DoubleExcitation, generators, paulixops, paulix_sector, + qp.taper_operation(qp.DoubleExcitation, generators, paulixops, paulix_sector, wire_order=H.wires, op_wires=double) for double in doubles ] tapered_singles = [ - qml.taper_operation(qml.SingleExcitation, generators, paulixops, paulix_sector, + qp.taper_operation(qp.SingleExcitation, generators, paulixops, paulix_sector, wire_order=H.wires, op_wires=single) for single in singles ] -dev = qml.device("lightning.qubit", wires=H_tapered.wires) +dev = qp.device("lightning.qubit", wires=H_tapered.wires) -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def tapered_circuit(params): - qml.BasisState(state_tapered, wires=H_tapered.wires) + qp.BasisState(state_tapered, wires=H_tapered.wires) for idx, tapered_op in enumerate(tapered_doubles + tapered_singles): tapered_op(params[idx]) - return qml.expval(H_tapered) + return qp.expval(H_tapered) ############################################################################## # We define an optimizer and the initial values of the circuit parameters and optimize the circuit diff --git a/demonstrations_v2/tutorial_qubit_tapering/metadata.json b/demonstrations_v2/tutorial_qubit_tapering/metadata.json index 42212516f7..da68134fe7 100644 --- a/demonstrations_v2/tutorial_qubit_tapering/metadata.json +++ b/demonstrations_v2/tutorial_qubit_tapering/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2022-05-16T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Chemistry" ], diff --git a/demonstrations_v2/tutorial_qubitization/demo.py b/demonstrations_v2/tutorial_qubitization/demo.py index f4382e3460..40e83f5f41 100644 --- a/demonstrations_v2/tutorial_qubitization/demo.py +++ b/demonstrations_v2/tutorial_qubitization/demo.py @@ -92,11 +92,11 @@ First, let's define a simple Hamiltonian to use as an example: """ -import pennylane as qml +import pennylane as qp -H = -0.4 * qml.Z(0) + 0.3 * qml.Z(1) + 0.4 * qml.Z(0) @ qml.Z(1) +H = -0.4 * qp.Z(0) + 0.3 * qp.Z(1) + 0.4 * qp.Z(0) @ qp.Z(1) -print(qml.matrix(H).real) +print(qp.matrix(H).real) ############################################################################## # We have chosen an operator that is diagonal in the computational basis because it is easy to identify @@ -110,21 +110,21 @@ control_wires = [2, 3] estimation_wires = [4, 5, 6, 7, 8, 9] -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") -@qml.qnode(dev) +@qp.qnode(dev) def circuit(): # Initialize the eigenstate |11⟩ for wire in [0, 1]: - qml.X(wire) + qp.X(wire) # Apply QPE with the qubitization operator - qml.QuantumPhaseEstimation( - qml.Qubitization(H, control_wires), estimation_wires=estimation_wires + qp.QuantumPhaseEstimation( + qp.Qubitization(H, control_wires), estimation_wires=estimation_wires ) - return qml.probs(wires=estimation_wires) + return qp.probs(wires=estimation_wires) ############################################################################## diff --git a/demonstrations_v2/tutorial_qubitization/metadata.json b/demonstrations_v2/tutorial_qubitization/metadata.json index 7df408a5e5..ceb21c75d0 100644 --- a/demonstrations_v2/tutorial_qubitization/metadata.json +++ b/demonstrations_v2/tutorial_qubitization/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-09-09T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Computing", "Algorithms" diff --git a/demonstrations_v2/tutorial_qutrits_bernstein_vazirani/demo.py b/demonstrations_v2/tutorial_qutrits_bernstein_vazirani/demo.py index be3dfde8c2..88e43ee5d2 100644 --- a/demonstrations_v2/tutorial_qutrits_bernstein_vazirani/demo.py +++ b/demonstrations_v2/tutorial_qutrits_bernstein_vazirani/demo.py @@ -126,58 +126,58 @@ """ -import pennylane as qml +import pennylane as qp -dev = qml.device("default.qubit", wires = 4) +dev = qp.device("default.qubit", wires = 4) def Uf(): # The oracle in charge of encoding a hidden "a" value. - qml.CNOT(wires=[1, 3]) - qml.CNOT(wires=[2 ,3]) + qp.CNOT(wires=[1, 3]) + qp.CNOT(wires=[2 ,3]) -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def circuit0(): """Circuit used to derive a0""" # Initialize x = [1,0,0] - qml.PauliX(wires = 0) + qp.PauliX(wires = 0) # Apply our oracle Uf() # We measure the last qubit - return qml.sample(wires = 3) + return qp.sample(wires = 3) -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def circuit1(): # Circuit used to derive a1 # Initialize x = [0,1,0] - qml.PauliX(wires = 1) + qp.PauliX(wires = 1) # We apply our oracle Uf() # We measure the last qubit - return qml.sample(wires = 3) + return qp.sample(wires = 3) -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def circuit2(): # Circuit used to derive a2 # Initialize x = [0,0,1] - qml.PauliX(wires = 2) + qp.PauliX(wires = 2) # We apply our oracle Uf() # We measure the last qubit - return qml.sample(wires = 3) + return qp.sample(wires = 3) # We run for x = [1,0,0] a0 = circuit0() @@ -195,26 +195,26 @@ def circuit2(): # In this case, with 3 queries (:math:`n=3`), we have discovered the value of :math:`\vec{a}.` Let's run the Bernstein–Vazirani subroutine (using qubits as qubits this time) to check that one call is enough: -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def circuit(): # We initialize to |0001> - qml.PauliX(wires = 3) + qp.PauliX(wires = 3) # We run the Hadamards for i in range(4): - qml.Hadamard(wires = i) + qp.Hadamard(wires = i) # We apply our function Uf() # We run the Hadamards for i in range(3): - qml.Hadamard(wires = i) + qp.Hadamard(wires = i) # We measure the first 3 qubits - return qml.sample(wires = range(3)) + return qp.sample(wires = range(3)) a = circuit() @@ -248,52 +248,52 @@ def circuit(): # These generalizations simply adjust the addition operation to be performed in modulo 3 instead of modulo 2. # So, with these ingredients, we are ready to go to the code. -dev = qml.device("default.qutrit", wires=4) +dev = qp.device("default.qutrit", wires=4) def Uf(): # The oracle in charge of encoding a hidden "a" value. - qml.TAdd(wires = [1,3]) - qml.TAdd(wires = [1,3]) - qml.TAdd(wires = [2,3]) + qp.TAdd(wires = [1,3]) + qp.TAdd(wires = [1,3]) + qp.TAdd(wires = [2,3]) -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def circuit0(): # Initialize x = [1,0,0] - qml.TShift(wires = 0) + qp.TShift(wires = 0) # We apply our oracle Uf() # We measure the last qutrit - return qml.sample(wires = 3) + return qp.sample(wires = 3) -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def circuit1(): # Initialize x = [0,1,0] - qml.TShift(wires = 1) + qp.TShift(wires = 1) # We apply our oracle Uf() # We measure the last qutrit - return qml.sample(wires = 3) + return qp.sample(wires = 3) -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def circuit2(): # Initialize x = [0,0,1] - qml.TShift(wires = 2) + qp.TShift(wires = 2) # We apply our oracle Uf() # We measure the last qutrit - return qml.sample(wires = 3) + return qp.sample(wires = 3) # Run to obtain the three trits of a a0 = circuit0() @@ -321,26 +321,26 @@ def circuit2(): # Let's go to the code and see how to run this in PennyLane. -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def circuit(): # We initialize to |0001> - qml.TShift(wires = 3) + qp.TShift(wires = 3) # We run the THadamard for i in range(4): - qml.THadamard(wires = i) + qp.THadamard(wires = i) # We run the oracle Uf() # We run the THadamard again for i in range(3): - qml.THadamard(wires = i) + qp.THadamard(wires = i) # We measure the first 3 qutrits - return qml.sample(wires = range(3)) + return qp.sample(wires = range(3)) a = circuit() diff --git a/demonstrations_v2/tutorial_qutrits_bernstein_vazirani/metadata.json b/demonstrations_v2/tutorial_qutrits_bernstein_vazirani/metadata.json index 6e7db66160..39a19c531d 100644 --- a/demonstrations_v2/tutorial_qutrits_bernstein_vazirani/metadata.json +++ b/demonstrations_v2/tutorial_qutrits_bernstein_vazirani/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-05-09T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Algorithms", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_resource_estimation/demo.py b/demonstrations_v2/tutorial_resource_estimation/demo.py index 81648ed18a..3bf3dc69e2 100644 --- a/demonstrations_v2/tutorial_resource_estimation/demo.py +++ b/demonstrations_v2/tutorial_resource_estimation/demo.py @@ -46,7 +46,7 @@ For most cases of interest, this algorithm requires more qubits and longer circuit depths than what can be implemented on existing hardware. The PennyLane functionality in the -:mod:`qml.estimator ` module allows us to estimate the number of logical qubits +:mod:`qp.estimator ` module allows us to estimate the number of logical qubits and the number of non-Clifford gates that are needed to implement the algorithm. We can estimate these resources by simply defining system specifications and a target error for estimation. Let's see how! @@ -62,7 +62,7 @@ the water molecule at its equilibrium geometry with the `6-31g basis set `_ as an example. """ -import pennylane as qml +import pennylane as qp import numpy as np import jax @@ -77,13 +77,13 @@ # Then we construct a molecule object and compute the one- and two-electron # integrals in the molecular orbital basis. -mol = qml.qchem.Molecule(symbols, geometry, basis_name='6-31g') -core, one, two = qml.qchem.electron_integrals(mol)() +mol = qp.qchem.Molecule(symbols, geometry, basis_name='6-31g') +core, one, two = qp.qchem.electron_integrals(mol)() ############################################################################## # We now create an instance of the :class:`~.pennylane.estimator.qpe_resources.DoubleFactorization` class -algo = qml.estimator.DoubleFactorization(one, two) +algo = qp.estimator.DoubleFactorization(one, two) ############################################################################## # and obtain the estimated number of non-Clifford gates and logical qubits. @@ -97,7 +97,7 @@ chemical_accuracy = 0.0016 error = chemical_accuracy * 10 -algo = qml.estimator.DoubleFactorization(one, two, error=error) +algo = qp.estimator.DoubleFactorization(one, two, error=error) print(f'Estimated gates : {algo.gates:.2e} \nEstimated qubits: {algo.qubits}') ############################################################################## @@ -110,7 +110,7 @@ n_qubits = [] for tol in threshold: - algo_ = qml.estimator.DoubleFactorization(one, two, tol_factor=tol, tol_eigval=tol) + algo_ = qp.estimator.DoubleFactorization(one, two, tol_factor=tol, tol_eigval=tol) n_gates.append(algo_.gates) n_qubits.append(algo_.qubits) @@ -143,7 +143,7 @@ ############################################################################## # We now create an instance of the :class:`~.pennylane.estimator.qpe_resources.FirstQuantization` class -algo = qml.estimator.FirstQuantization(planewaves, electrons, vectors=vectors) +algo = qp.estimator.FirstQuantization(planewaves, electrons, vectors=vectors) ############################################################################## # and obtain the estimated number of non-Clifford gates and logical qubits. @@ -163,7 +163,7 @@ n_qubits_ = [] for pw in planewaves: - algo_ = qml.estimator.FirstQuantization(pw, electrons, vectors=vectors, error=er) + algo_ = qp.estimator.FirstQuantization(pw, electrons, vectors=vectors, error=er) n_gates_.append(algo_.gates) n_qubits_.append(algo_.qubits) n_gates.append(n_gates_) @@ -219,8 +219,8 @@ # # First, we construct the molecular Hamiltonian. -molecule = qml.qchem.Molecule(symbols, geometry) -H = qml.qchem.molecular_hamiltonian(molecule)[0] +molecule = qp.qchem.Molecule(symbols, geometry) +H = qp.qchem.molecular_hamiltonian(molecule)[0] H_coeffs, H_ops = H.terms() ############################################################################## @@ -230,7 +230,7 @@ # :math:`\left \langle H \right \rangle` with a target error set to the chemical accuracy, 0.0016 # :math:`\text{Ha},` is obtained as follows. -m = qml.estimator.estimate_shots(H_coeffs) +m = qp.estimator.estimate_shots(H_coeffs) print(f'Shots : {m:.2e}') ############################################################################## @@ -239,17 +239,17 @@ # :func:`~.pennylane.pauli.group_observables()`, which partitions the Pauli words into # groups of commuting terms that can be measured simultaneously. -ops, coeffs = qml.pauli.group_observables(H_ops, H_coeffs) +ops, coeffs = qp.pauli.group_observables(H_ops, H_coeffs) coeffs = [np.array(c) for c in coeffs] # cast as numpy array -m = qml.estimator.estimate_shots(coeffs) +m = qp.estimator.estimate_shots(coeffs) print(f'Shots : {m:.2e}') ############################################################################## # It is also interesting to illustrate how the number of shots depends on the target error. error = np.array([0.02, 0.015, 0.01, 0.005, 0.001]) -m = [qml.estimator.estimate_shots(H_coeffs, error=er) for er in error] +m = [qp.estimator.estimate_shots(H_coeffs, error=er) for er in error] e_ = np.linspace(error[0], error[-1], num=50) m_ = 1.4e4 / np.linspace(error[0], error[-1], num=50)**2 diff --git a/demonstrations_v2/tutorial_resource_estimation/metadata.json b/demonstrations_v2/tutorial_resource_estimation/metadata.json index 988ff6fe92..ce8aa233a5 100644 --- a/demonstrations_v2/tutorial_resource_estimation/metadata.json +++ b/demonstrations_v2/tutorial_resource_estimation/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2022-11-21T00:00:00+00:00", - "dateOfLastModification": "2026-01-14T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Chemistry" ], diff --git a/demonstrations_v2/tutorial_resource_estimation_QSVT/demo.py b/demonstrations_v2/tutorial_resource_estimation_QSVT/demo.py index 6dd043b96a..0200e26706 100644 --- a/demonstrations_v2/tutorial_resource_estimation_QSVT/demo.py +++ b/demonstrations_v2/tutorial_resource_estimation_QSVT/demo.py @@ -48,11 +48,11 @@ For a recap on this technique, see our demo on `linear combination of unitaries and block encodings `_. """ -import pennylane as qml +import pennylane as qp -A = 0.1 * (qml.Z(0) @ qml.Z(1)) + 0.2 * (qml.X(0) @ qml.X(1)) + 0.3 * (qml.X(0) @ qml.Z(1)) +A = 0.1 * (qp.Z(0) @ qp.Z(1)) + 0.2 * (qp.X(0) @ qp.X(1)) + 0.3 * (qp.X(0) @ qp.Z(1)) -print(qml.matrix(A, wire_order=[0, 1])) +print(qp.matrix(A, wire_order=[0, 1])) ############################################################################## # Resources from an Executable Workflow @@ -73,7 +73,7 @@ poly = (0, 0, 0, 0, 0, 1) # f(x) = x^5 def circ(): - qml.qsvt(A, poly, encoding_wires=encoding_wires) + qp.qsvt(A, poly, encoding_wires=encoding_wires) return ## --- Resource Estimation: --- diff --git a/demonstrations_v2/tutorial_resource_estimation_QSVT/metadata.json b/demonstrations_v2/tutorial_resource_estimation_QSVT/metadata.json index fee8744bdc..f03fe5a910 100644 --- a/demonstrations_v2/tutorial_resource_estimation_QSVT/metadata.json +++ b/demonstrations_v2/tutorial_resource_estimation_QSVT/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2026-02-27T10:00:00+00:00", - "dateOfLastModification": "2026-02-27T10:00:00+00:00", + "dateOfLastModification": "2026-04-17T10:00:00+00:00", "categories": [ "Algorithms" ], diff --git a/demonstrations_v2/tutorial_resourcefulness/demo.py b/demonstrations_v2/tutorial_resourcefulness/demo.py index 4ed0121eb1..85cf63c7ab 100644 --- a/demonstrations_v2/tutorial_resourcefulness/demo.py +++ b/demonstrations_v2/tutorial_resourcefulness/demo.py @@ -359,31 +359,31 @@ def g(x): # -import pennylane as qml +import pennylane as qp from scipy.stats import unitary_group -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") -@qml.qnode(dev) +@qp.qnode(dev) def product_state(n_qubits): for i in range(n_qubits): U_haar = unitary_group.rvs(2) - qml.QubitUnitary(U_haar, wires=i) - return qml.state() + qp.QubitUnitary(U_haar, wires=i) + return qp.state() -@qml.qnode(dev) +@qp.qnode(dev) def haar_state(n_qubits): U_haar = unitary_group.rvs(2**n_qubits) - qml.QubitUnitary(U_haar, wires=range(n_qubits)) - return qml.state() + qp.QubitUnitary(U_haar, wires=range(n_qubits)) + return qp.state() -@qml.qnode(dev) +@qp.qnode(dev) def ghz_state(n_qubits): - qml.Hadamard(wires=0) + qp.Hadamard(wires=0) for i in range(1, n_qubits): - qml.CNOT(wires=[0, i]) - return qml.state() + qp.CNOT(wires=[0, i]) + return qp.state() n = 2 states = [product_state(n), haar_state(n), ghz_state(n)] diff --git a/demonstrations_v2/tutorial_resourcefulness/metadata.json b/demonstrations_v2/tutorial_resourcefulness/metadata.json index 2b2a6a0de0..7a1c57243b 100644 --- a/demonstrations_v2/tutorial_resourcefulness/metadata.json +++ b/demonstrations_v2/tutorial_resourcefulness/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2025-10-30T09:00:00+00:00", - "dateOfLastModification": "2026-02-19T09:00:00+00:00", + "dateOfLastModification": "2026-04-17T09:00:00+00:00", "categories": [ "Quantum Computing" ], diff --git a/demonstrations_v2/tutorial_rl_pulse/demo.py b/demonstrations_v2/tutorial_rl_pulse/demo.py index 0b40f614e2..574a45023e 100644 --- a/demonstrations_v2/tutorial_rl_pulse/demo.py +++ b/demonstrations_v2/tutorial_rl_pulse/demo.py @@ -177,7 +177,7 @@ multi-qubit devices and gates. """ -import pennylane as qml +import pennylane as qp # Quantum computer qubit_freqs = [4.81] # GHz @@ -185,7 +185,7 @@ couplings = [] # No couplings wires = [0] -H_int = qml.pulse.transmon_interaction(qubit_freqs, connections, couplings, wires) +H_int = qp.pulse.transmon_interaction(qubit_freqs, connections, couplings, wires) # Microwave pulse pulse_duration = 22.4 # ns @@ -193,10 +193,10 @@ segment_duration = pulse_duration / n_segments freq = qubit_freqs[0] # Resonant with the qubit -amplitude = qml.pulse.pwc(pulse_duration) -phase = qml.pulse.pwc(pulse_duration) +amplitude = qp.pulse.pwc(pulse_duration) +phase = qp.pulse.pwc(pulse_duration) -H_drive = qml.pulse.transmon_drive(amplitude, phase, freq, wires) +H_drive = qp.pulse.transmon_drive(amplitude, phase, freq, wires) # Full time-dependent parametrized Hamiltonian H = H_int + H_drive @@ -217,16 +217,16 @@ import jax from functools import partial -device = qml.device("default.qubit", wires=1) +device = qp.device("default.qubit", wires=1) @partial(jax.jit, static_argnames="H") @partial(jax.vmap, in_axes=(0, None, 0, None)) -@qml.qnode(device=device, interface="jax") +@qp.qnode(device=device, interface="jax") def evolve_states(state, H, params, t): - qml.StatePrep(state, wires=wires) - qml.evolve(H)(params, t, atol=1e-5) - return qml.state() + qp.StatePrep(state, wires=wires) + qp.evolve(H)(params, t, atol=1e-5) + return qp.state() state_size = 2 ** len(wires) @@ -283,7 +283,7 @@ def evolve_states(state, H, params, t): # named tuple) and the code below will assume this container is being passed. # -target = jnp.array(qml.RX(jnp.pi / 2, 0).matrix()) # RX(pi/2) gate +target = jnp.array(qp.RX(jnp.pi / 2, 0).matrix()) # RX(pi/2) gate @partial(jax.jit, static_argnames=["H", "config"]) @@ -327,7 +327,7 @@ def sample_random_states(subkey, n_states, dim): def get_pulse_matrix(H, params, time): """Compute the unitary matrix associated to the time evolution of H.""" - return qml.evolve(H)(params, time, atol=1e-5).matrix() + return qp.evolve(H)(params, time, atol=1e-5).matrix() @jax.jit @@ -757,9 +757,9 @@ def evaluate_program(pulse_program, H, target, config, subkey): """Compute the average gate fidelity over 1000 random initial states.""" states = sample_random_states(subkey, 1000, state_size) target_states = jnp.einsum("ab,cb->ca", target, states) - pulse_matrix = qml.matrix(qml.evolve(H)(pulse_program, config.pulse_duration)) + pulse_matrix = qp.matrix(qp.evolve(H)(pulse_program, config.pulse_duration)) final_states = jnp.einsum("ab,cb->ca", pulse_matrix, states) - fidelities = qml.math.fidelity_statevector(final_states, target_states) + fidelities = qp.math.fidelity_statevector(final_states, target_states) return fidelities @@ -774,7 +774,7 @@ def evaluate_program(pulse_program, H, target, config, subkey): def vector_to_bloch(vector): """Transform a vector into Bloch sphere coordinates.""" rho = jnp.outer(vector, vector.conj()) - X, Y, Z = qml.PauliX(0).matrix(), qml.PauliY(0).matrix(), qml.PauliZ(0).matrix() + X, Y, Z = qp.PauliX(0).matrix(), qp.PauliY(0).matrix(), qp.PauliZ(0).matrix() x, y, z = ( jnp.trace(rho @ X).real.item(), jnp.trace(rho @ Y).real.item(), @@ -812,12 +812,12 @@ def plot_rotation_axes(rotation_axes, color=["#70CEFF"], fig=None, ax=None): ts = jnp.linspace(0, pulse_duration - 1e-3, 100) fig, axs = plt.subplots(ncols=3, figsize=(14, 4), constrained_layout=True) -axs[0].plot(ts, qml.pulse.pwc(pulse_duration)(pulse_program[0], ts), color="#70CEFF", linewidth=3) +axs[0].plot(ts, qp.pulse.pwc(pulse_duration)(pulse_program[0], ts), color="#70CEFF", linewidth=3) axs[0].set_ylabel("Amplitude (GHz)", fontsize=14) axs[0].set_yticks(values_ampl) axs[0].set_ylim([values_ampl[0], values_ampl[-1]]) -axs[1].plot(ts, qml.pulse.pwc(pulse_duration)(pulse_program[1], ts), color="#FFE096", linewidth=3) +axs[1].plot(ts, qp.pulse.pwc(pulse_duration)(pulse_program[1], ts), color="#FFE096", linewidth=3) axs[1].set_ylabel("Phase (rad)", fontsize=14) axs[1].set_yticks( values_phase, @@ -857,7 +857,7 @@ def plot_rotation_axes(rotation_axes, color=["#70CEFF"], fig=None, ax=None): couplings = [0.02] wires = [0, 1] -H_int = qml.pulse.transmon_interaction(qubit_freqs, connections, couplings, wires) +H_int = qp.pulse.transmon_interaction(qubit_freqs, connections, couplings, wires) ###################################################################### # The CNOT gate is typically constituted by a series of single-qubit pulses and cross-resonant (CR) @@ -883,9 +883,9 @@ def plot_rotation_axes(rotation_axes, color=["#70CEFF"], fig=None, ax=None): def get_drive(timespan, freq, wire): """Parametrized Hamiltonian driving the qubit in wire with a fixed frequency.""" - amplitude = qml.pulse.pwc(timespan) - phase = qml.pulse.pwc(timespan) - return qml.pulse.transmon_drive(amplitude, phase, freq, wire) + amplitude = qp.pulse.pwc(timespan) + phase = qp.pulse.pwc(timespan) + return qp.pulse.transmon_drive(amplitude, phase, freq, wire) pulse_durations = jnp.array( @@ -926,23 +926,23 @@ def get_drive(timespan, freq, wire): @jax.jit @partial(jax.vmap, in_axes=(0, None, 0, None)) -@qml.qnode(device=device, interface="jax") +@qp.qnode(device=device, interface="jax") def evolve_states(state, params, t): params_sq, params_cr = params - qml.StatePrep(state, wires=wires) + qp.StatePrep(state, wires=wires) # Single qubit pulses - qml.evolve(H_int + H_sq_ini)(params_sq, t, atol=1e-5) + qp.evolve(H_int + H_sq_ini)(params_sq, t, atol=1e-5) # Echoed CR - qml.evolve(H_int + H_cr_pos)(params_cr, t, atol=1e-5) - qml.PauliX(0) # Flip control qubit - qml.evolve(H_int - H_cr_neg)(params_cr, t, atol=1e-5) # Negative CR - qml.PauliX(0) # Recover control qubit + qp.evolve(H_int + H_cr_pos)(params_cr, t, atol=1e-5) + qp.PauliX(0) # Flip control qubit + qp.evolve(H_int - H_cr_neg)(params_cr, t, atol=1e-5) # Negative CR + qp.PauliX(0) # Recover control qubit # Single qubit pulses - qml.evolve(H_int + H_sq_end)(params_sq, t, atol=1e-5) + qp.evolve(H_int + H_sq_end)(params_sq, t, atol=1e-5) - return qml.state() + return qp.state() ###################################################################### diff --git a/demonstrations_v2/tutorial_rl_pulse/metadata.json b/demonstrations_v2/tutorial_rl_pulse/metadata.json index a0dbaaf21f..dc6d8e17bf 100644 --- a/demonstrations_v2/tutorial_rl_pulse/metadata.json +++ b/demonstrations_v2/tutorial_rl_pulse/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-04-09T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Getting Started", "Optimization", diff --git a/demonstrations_v2/tutorial_rosalin/demo.py b/demonstrations_v2/tutorial_rosalin/demo.py index b179d3eebc..918fbe718e 100644 --- a/demonstrations_v2/tutorial_rosalin/demo.py +++ b/demonstrations_v2/tutorial_rosalin/demo.py @@ -111,7 +111,7 @@ First, let's import NumPy and PennyLane, and define our Hamiltonian. """ -import pennylane as qml +import pennylane as qp from pennylane import numpy as np # set the random seed @@ -120,11 +120,11 @@ coeffs = [2, 4, -1, 5, 2] obs = [ - qml.PauliX(1), - qml.PauliZ(1), - qml.PauliX(0) @ qml.PauliX(1), - qml.PauliY(0) @ qml.PauliY(1), - qml.PauliZ(0) @ qml.PauliZ(1) + qp.PauliX(1), + qp.PauliZ(1), + qp.PauliX(0) @ qp.PauliX(1), + qp.PauliY(0) @ qp.PauliY(1), + qp.PauliZ(0) @ qp.PauliZ(1) ] @@ -135,10 +135,10 @@ num_wires = 2 # create a device that estimates expectation values using a finite number of shots -non_analytic_dev = qml.device("default.qubit", wires=num_wires, seed=432423) +non_analytic_dev = qp.device("default.qubit", wires=num_wires, seed=432423) # create a device that calculates exact expectation values -analytic_dev = qml.device("default.qubit", wires=num_wires) +analytic_dev = qp.device("default.qubit", wires=num_wires) ############################################################################## # Now, let's set the total number of shots, and determine the probability @@ -185,11 +185,11 @@ from pennylane.templates.layers import StronglyEntanglingLayers -@qml.set_shots(100) -@qml.qnode(non_analytic_dev, diff_method="parameter-shift", interface="autograd") +@qp.set_shots(100) +@qp.qnode(non_analytic_dev, diff_method="parameter-shift", interface="autograd") def qnode(weights, observable): StronglyEntanglingLayers(weights, wires=non_analytic_dev.wires) - return qml.expval(observable) + return qp.expval(observable) def cost(params): # sample from the multinomial distribution @@ -200,7 +200,7 @@ def cost(params): for o, c, s in zip(obs, coeffs, shots_per_term): # evaluate the QNode corresponding to # the Hamiltonian term, and add it on to our running sum - result += c * qml.set_shots(qnode, shots=int(s))(params, o) + result += c * qp.set_shots(qnode, shots=int(s))(params, o) return result @@ -218,7 +218,7 @@ def cost(params): # Performing the optimization, with the number of shots randomly # determined at each optimization step: -opt = qml.AdamOptimizer(0.05) +opt = qp.AdamOptimizer(0.05) params = init_params cost_wrs = [] @@ -235,11 +235,11 @@ def cost(params): # Here, we will split the 8000 total shots evenly across all Hamiltonian terms, # also known as *uniform deterministic sampling*. -@qml.set_shots(100) -@qml.qnode(non_analytic_dev, diff_method="parameter-shift", interface="autograd") +@qp.set_shots(100) +@qp.qnode(non_analytic_dev, diff_method="parameter-shift", interface="autograd") def qnode(weights, obs): StronglyEntanglingLayers(weights, wires=non_analytic_dev.wires) - return qml.expval(obs) + return qp.expval(obs) def cost(params): shots_per_term = int(total_shots / len(coeffs)) @@ -250,11 +250,11 @@ def cost(params): # evaluate the QNode corresponding to # the Hamiltonian term, and add it on to our running sum - result += c * qml.set_shots(qnode, shots=shots_per_term)(params, o) + result += c * qp.set_shots(qnode, shots=shots_per_term)(params, o) return result -opt = qml.AdamOptimizer(0.05) +opt = qp.AdamOptimizer(0.05) params = init_params cost_adam = [] @@ -438,7 +438,7 @@ def estimate_hamiltonian(self, params, shots): set to 'sample' mode. """ # note that convergence depends on seed for random number generation - rosalin_device = qml.device("default.qubit", wires=num_wires, seed=93754352) + rosalin_device = qp.device("default.qubit", wires=num_wires, seed=93754352) # determine the shot probability per term prob_shots = np.abs(coeffs) / np.sum(np.abs(coeffs)) @@ -450,11 +450,11 @@ def estimate_hamiltonian(self, params, shots): results = [] - @qml.set_shots(100) - @qml.qnode(rosalin_device, diff_method="parameter-shift", interface="autograd") + @qp.set_shots(100) + @qp.qnode(rosalin_device, diff_method="parameter-shift", interface="autograd") def qnode(weights, observable): StronglyEntanglingLayers(weights, wires=rosalin_device.wires) - return qml.sample(observable) + return qp.sample(observable) for o, c, p, s in zip(self.obs, self.coeffs, prob_shots, shots_per_term): @@ -464,7 +464,7 @@ def qnode(weights, observable): # evaluate the QNode corresponding to # the Hamiltonian term - res = qml.set_shots(qnode, shots=int(s))(params, o) + res = qp.set_shots(qnode, shots=int(s))(params, o) # Note that, unlike above, we divide each term by the # probability per shot. This is because we are sampling one at a time. @@ -555,10 +555,10 @@ def step(self, params): # also create a separate cost function using an 'exact' quantum device, so that we can keep track of the # *exact* cost function value at each iteration. -@qml.qnode(analytic_dev, interface="autograd") +@qp.qnode(analytic_dev, interface="autograd") def cost_analytic(weights): StronglyEntanglingLayers(weights, wires=analytic_dev.wires) - return qml.expval(qml.Hamiltonian(coeffs, obs)) + return qp.expval(qp.Hamiltonian(coeffs, obs)) ############################################################################## # Creating the optimizer and beginning the optimization: @@ -589,15 +589,15 @@ def cost_analytic(weights): # Thus, Adam is using 2400 shots per update step. params = init_params -opt = qml.AdamOptimizer(0.07) +opt = qp.AdamOptimizer(0.07) -adam_dev = qml.device('default.qubit', seed=595905) +adam_dev = qp.device('default.qubit', seed=595905) -@qml.set_shots(adam_shots_per_eval) -@qml.qnode(adam_dev, diff_method="parameter-shift", interface="autograd") +@qp.set_shots(adam_shots_per_eval) +@qp.qnode(adam_dev, diff_method="parameter-shift", interface="autograd") def cost(weights): StronglyEntanglingLayers(weights, wires=non_analytic_dev.wires) - return qml.expval(qml.Hamiltonian(coeffs, obs)) + return qp.expval(qp.Hamiltonian(coeffs, obs)) cost_adam = [cost_analytic(params)] shots_adam = [0] diff --git a/demonstrations_v2/tutorial_rosalin/metadata.json b/demonstrations_v2/tutorial_rosalin/metadata.json index 9a97a4c86f..f48d9739b4 100644 --- a/demonstrations_v2/tutorial_rosalin/metadata.json +++ b/demonstrations_v2/tutorial_rosalin/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2020-05-19T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_rotoselect/demo.py b/demonstrations_v2/tutorial_rotoselect/demo.py index 981ea26c62..c067da0f7c 100644 --- a/demonstrations_v2/tutorial_rotoselect/demo.py +++ b/demonstrations_v2/tutorial_rotoselect/demo.py @@ -122,14 +122,14 @@ # in order to obtain exact values for any expectation values calculated. In contrast to real # devices, simulators have the capability of doing these calculations without sampling. -import pennylane as qml +import pennylane as qp from pennylane import numpy as np np.random.seed(9432092) n_wires = 2 -dev = qml.device("lightning.qubit", wires=2) +dev = qp.device("lightning.qubit", wires=2) ############################################################################## # Creating a fixed quantum circuit @@ -147,23 +147,23 @@ def ansatz(params): - qml.RX(params[0], wires=0) - qml.RY(params[1], wires=1) - qml.CNOT(wires=[0, 1]) + qp.RX(params[0], wires=0) + qp.RY(params[1], wires=1) + qp.CNOT(wires=[0, 1]) -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def circuit(params): ansatz(params) - return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliY(1)) + return qp.expval(qp.PauliZ(0)), qp.expval(qp.PauliY(1)) -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def circuit2(params): ansatz(params) - return qml.expval(qml.PauliX(0)) + return qp.expval(qp.PauliX(0)) def cost(params): @@ -231,7 +231,7 @@ def rotosolve_cycle(cost, params): # converges on the minimum after the first cycle for this simple circuit. params_gd = init_params.copy() -opt = qml.GradientDescentOptimizer(stepsize=0.5) +opt = qp.GradientDescentOptimizer(stepsize=0.5) costs_gd = [] for i in range(n_steps): costs_gd.append(cost(params_gd)) @@ -316,31 +316,31 @@ def rotosolve_cycle(cost, params): def RGen(param, generator, wires): if generator == "X": - qml.RX(param, wires=wires) + qp.RX(param, wires=wires) elif generator == "Y": - qml.RY(param, wires=wires) + qp.RY(param, wires=wires) elif generator == "Z": - qml.RZ(param, wires=wires) + qp.RZ(param, wires=wires) def ansatz_rsel(params, generators): RGen(params[0], generators[0], wires=0) RGen(params[1], generators[1], wires=1) - qml.CNOT(wires=[0, 1]) + qp.CNOT(wires=[0, 1]) -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def circuit_rsel(params, generators): ansatz_rsel(params, generators) - return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliY(1)) + return qp.expval(qp.PauliZ(0)), qp.expval(qp.PauliY(1)) -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def circuit_rsel2(params, generators): ansatz_rsel(params, generators) - return qml.expval(qml.PauliX(0)) + return qp.expval(qp.PauliX(0)) def cost_rsel(params, generators): diff --git a/demonstrations_v2/tutorial_rotoselect/metadata.json b/demonstrations_v2/tutorial_rotoselect/metadata.json index d3125fd7f1..4ac44e75c1 100644 --- a/demonstrations_v2/tutorial_rotoselect/metadata.json +++ b/demonstrations_v2/tutorial_rotoselect/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2019-10-16T00:00:00+00:00", - "dateOfLastModification": "2025-12-10T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Optimization", "Compilation" diff --git a/demonstrations_v2/tutorial_sc_qubits/demo.py b/demonstrations_v2/tutorial_sc_qubits/demo.py index 47b9a2cfc5..50afa15633 100644 --- a/demonstrations_v2/tutorial_sc_qubits/demo.py +++ b/demonstrations_v2/tutorial_sc_qubits/demo.py @@ -381,8 +381,8 @@ # # Let us see how this works in practice using PennyLane. The ``default.gaussian`` device allows us to simulate # coherent states of light. These states start implicitly in the vacuum (no photons) state. -# The PennyLane function ``qml.Displacement(x,0)`` applies a *displacement operator*, which creates -# a coherent state :math:`\left\lvert \bar{x}, 0\right\rangle.` The rotation operator ``qml.Rotation(phi)`` rotates the state +# The PennyLane function ``qp.Displacement(x,0)`` applies a *displacement operator*, which creates +# a coherent state :math:`\left\lvert \bar{x}, 0\right\rangle.` The rotation operator ``qp.Rotation(phi)`` rotates the state # :math:`\left\lvert \bar{x}, 0\right\rangle` in :math:`(x, p)` space. When applied after a large displacement, # it changes the value of :math:`\bar{x}` only slightly, but noticeably changes the value of :math:`\bar{p}` by shifting it # off from zero, as shown in the figure [#Blais2021]_: @@ -400,12 +400,12 @@ # taking :math:`\omega_r=0,` which simply corresponds to taking :math:`\omega_r` as a reference frequency, so a rotation by # angle :math:`\phi` actually means a rotation by :math:`\omega_r+\phi.` In PennyLane, the operations read: -import pennylane as qml +import pennylane as qp import numpy as np import matplotlib.pyplot as plt # Call the default.gaussian device with 50 shots -dev = qml.device("default.gaussian", wires=1) +dev = qp.device("default.gaussian", wires=1) # Fix parameters epsilon, chi = 1.0, 0.1 @@ -413,20 +413,20 @@ # Implement displacement and rotation and measure both X and P observables -@qml.set_shots(50) -@qml.qnode(dev) +@qp.set_shots(50) +@qp.qnode(dev) def measure_P_shots(time, state): - qml.Displacement(epsilon * time, 0, wires=0) - qml.Rotation((-1) ** state * chi * time, wires=0) - return qml.sample(qml.QuadP(0)) + qp.Displacement(epsilon * time, 0, wires=0) + qp.Rotation((-1) ** state * chi * time, wires=0) + return qp.sample(qp.QuadP(0)) -@qml.set_shots(50) -@qml.qnode(dev) +@qp.set_shots(50) +@qp.qnode(dev) def measure_X_shots(time, state): - qml.Displacement(epsilon * time, 0, wires=0) - qml.Rotation((-1) ** state * chi * time, wires=0) - return qml.sample(qml.QuadX(0)) + qp.Displacement(epsilon * time, 0, wires=0) + qp.Rotation((-1) ** state * chi * time, wires=0) + return qp.sample(qp.QuadX(0)) ############################################################################## @@ -491,46 +491,46 @@ def measure_X_shots(time, state): # applies a :math:`Y`-rotation. # # Let us check this using PennyLane. For qubits, we can define -# Hamiltonians using ``qml.Hamiltonian`` and evolve an initial state using ``ApproxTimeEvolution``: +# Hamiltonians using ``qp.Hamiltonian`` and evolve an initial state using ``ApproxTimeEvolution``: from pennylane.templates import ApproxTimeEvolution -dev2 = qml.device("lightning.qubit", wires=1) +dev2 = qp.device("lightning.qubit", wires=1) # Implement Hamiltonian evolution given phase phi and time t, from a given initial state -@qml.qnode(dev2) +@qp.qnode(dev2) def H_evolve(state, phi, time): if state == 1: - qml.PauliX(wires=0) + qp.PauliX(wires=0) coeffs = [np.cos(phi), np.sin(phi)] - ops = [qml.PauliX(0), qml.PauliY(0)] - Ham = qml.Hamiltonian(coeffs, ops) + ops = [qp.PauliX(0), qp.PauliY(0)] + Ham = qp.Hamiltonian(coeffs, ops) ApproxTimeEvolution(Ham, time, 1) - return qml.state() + return qp.state() # Implement X rotation exactly -@qml.qnode(dev2) +@qp.qnode(dev2) def Sc_X_rot(state, phi): if state == 1: - qml.PauliX(wires=0) + qp.PauliX(wires=0) - qml.RX(phi, wires=0) - return qml.state() + qp.RX(phi, wires=0) + return qp.state() # Implement Y rotation exactly -@qml.qnode(dev2) +@qp.qnode(dev2) def Sc_Y_rot(state, phi): if state == 1: - qml.PauliX(wires=0) + qp.PauliX(wires=0) - qml.RY(phi, wires=0) - return qml.state() + qp.RY(phi, wires=0) + return qp.state() # Print to compare results @@ -607,28 +607,28 @@ def Sc_Y_rot(state, phi): # # when applied for a time :math:`t=3\pi/2J,` as shown with the following PennyLane code: # -dev3 = qml.device("lightning.qubit", wires=2) +dev3 = qp.device("lightning.qubit", wires=2) # Define Hamiltonian coeffs = [0.5, 0.5] -ops = [qml.PauliX(0) @ qml.PauliX(1), qml.PauliY(0) @ qml.PauliY(1)] +ops = [qp.PauliX(0) @ qp.PauliX(1), qp.PauliY(0) @ qp.PauliY(1)] -Two_qubit_H = qml.Hamiltonian(coeffs, ops) +Two_qubit_H = qp.Hamiltonian(coeffs, ops) # Implement Hamiltonian evolution for time t and some initial computational basis state -@qml.qnode(dev3) +@qp.qnode(dev3) def Sc_ISWAP(basis_state, time): - qml.BasisState(basis_state, wires=range(2)) + qp.BasisState(basis_state, wires=range(2)) ApproxTimeEvolution(Two_qubit_H, time, 1) - return qml.state() + return qp.state() # Implement ISWAP exactly -@qml.qnode(dev3) +@qp.qnode(dev3) def iswap(basis_state): - qml.BasisState(basis_state, wires=range(2)) - qml.ISWAP(wires=[0, 1]) - return qml.state() + qp.BasisState(basis_state, wires=range(2)) + qp.ISWAP(wires=[0, 1]) + return qp.state() # Print to compare results @@ -679,17 +679,17 @@ def iswap(basis_state): # We can verify that the circuit above gives us the ``CNOT`` gate up to a global phase using PennyLane: # def cnot_with_iswap(): - qml.RZ(-np.pi / 2, wires=0) - qml.RX(np.pi / 2, wires=1) - qml.RZ(np.pi / 2, wires=1) - qml.ISWAP(wires=[0, 1]) - qml.RX(np.pi / 2, wires=0) - qml.ISWAP(wires=[0, 1]) - qml.RZ(np.pi / 2, wires=1) + qp.RZ(-np.pi / 2, wires=0) + qp.RX(np.pi / 2, wires=1) + qp.RZ(np.pi / 2, wires=1) + qp.ISWAP(wires=[0, 1]) + qp.RX(np.pi / 2, wires=0) + qp.ISWAP(wires=[0, 1]) + qp.RZ(np.pi / 2, wires=1) # Get matrix of circuit above -matrix = qml.matrix(cnot_with_iswap, wire_order=[0, 1])() +matrix = qp.matrix(cnot_with_iswap, wire_order=[0, 1])() # Multiply by a global phase to obtain CNOT (np.exp(1j * np.pi / 4) * matrix).round(2) @@ -729,22 +729,22 @@ def cnot_with_iswap(): # # where :math:`\phi` is the phase of the wave. As promised, we can obtain an entangled state by concatenating # the evolution under this Hamiltonian for a time :math:`t=\tfrac{\pi}{4\Omega}` with :math:`R_x` and :math:`R_y` rotations -# and a ``qml.Hadamard`` gate: +# and a ``qp.Hadamard`` gate: # -@qml.qnode(dev3) +@qp.qnode(dev3) def H_evolve(state, phi, time): # Prepare initial state - qml.BasisState(state, wires=range(2)) + qp.BasisState(state, wires=range(2)) # Define Hamiltonian coeffs = [np.cos(phi), np.sin(phi)] - ops = [qml.PauliZ(0) @ qml.PauliX(1), qml.PauliZ(0) @ qml.PauliY(1)] - Ham = qml.Hamiltonian(coeffs, ops) + ops = [qp.PauliZ(0) @ qp.PauliX(1), qp.PauliZ(0) @ qp.PauliY(1)] + Ham = qp.Hamiltonian(coeffs, ops) # Combine Hamiltonian evolution with single-qubit gates - qml.Hadamard(wires=0) - qml.RX(-np.pi / 2, wires=1) + qp.Hadamard(wires=0) + qp.RX(-np.pi / 2, wires=1) ApproxTimeEvolution(Ham, time, 1) - qml.RZ(-np.pi / 2, wires=0) - return qml.state() + qp.RZ(-np.pi / 2, wires=0) + return qp.state() # Verify that we return maximally entangled state up to a global phase diff --git a/demonstrations_v2/tutorial_sc_qubits/metadata.json b/demonstrations_v2/tutorial_sc_qubits/metadata.json index e109bc232c..436117e895 100644 --- a/demonstrations_v2/tutorial_sc_qubits/metadata.json +++ b/demonstrations_v2/tutorial_sc_qubits/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2022-03-22T00:00:00+00:00", - "dateOfLastModification": "2025-12-19T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Quantum Hardware", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_shadow_hamiltonian_simulation/demo.py b/demonstrations_v2/tutorial_shadow_hamiltonian_simulation/demo.py index e03d4ab9dc..89ab99a3be 100644 --- a/demonstrations_v2/tutorial_shadow_hamiltonian_simulation/demo.py +++ b/demonstrations_v2/tutorial_shadow_hamiltonian_simulation/demo.py @@ -134,19 +134,19 @@ """ -import pennylane as qml +import pennylane as qp import numpy as np from pennylane import X, Y, Z, I -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") S = [X(0), Y(0), Z(0), I(0)] H = X(0) + Y(0) -@qml.qnode(dev) +@qp.qnode(dev) def evolve(H, t): - qml.evolve(H, t) - return [qml.expval(Om) for Om in S] + qp.evolve(H, t) + return [qp.expval(Om) for Om in S] t = 1. O_t_standard = np.array(evolve(H, t)) @@ -236,7 +236,7 @@ def evolve(H, t): # be implemented on a quantum computer. # -H_S_qubit = qml.pauli_decompose(H_S) +H_S_qubit = qp.pauli_decompose(H_S) H_S_qubit ############################################################################## @@ -247,11 +247,11 @@ def evolve(H, t): A = np.linalg.norm(O_0) -@qml.qnode(dev) +@qp.qnode(dev) def shadow_evolve(H_S_qubit, O_0, t): - qml.StatePrep(O_0 / A, wires=range(2)) - qml.evolve(H_S_qubit, t) - return qml.state() + qp.StatePrep(O_0 / A, wires=range(2)) + qp.evolve(H_S_qubit, t) + return qp.state() O_t_shadow = shadow_evolve(H_S_qubit, O_0, t) * A @@ -263,7 +263,7 @@ def shadow_evolve(H_S_qubit, O_0, t): # # The first result is coming from three independent measurements on a quantum computer after evolution with system Hamiltonian :math:`H.` # This is conceptually very different from the second result where -# :math:`\boldsymbol{O}` is encoded in the state of the shadow system (note the ``qml.state()`` return), which we evolved according to :math:`H_S.` +# :math:`\boldsymbol{O}` is encoded in the state of the shadow system (note the ``qp.state()`` return), which we evolved according to :math:`H_S.` # # In the first case, the measurement is directly obtained, however, # in the shadow Hamiltonian simulation, we need to access the amplitudes of the underlying state. diff --git a/demonstrations_v2/tutorial_shadow_hamiltonian_simulation/metadata.json b/demonstrations_v2/tutorial_shadow_hamiltonian_simulation/metadata.json index 17ef1b5b3d..b1f0d93b9a 100644 --- a/demonstrations_v2/tutorial_shadow_hamiltonian_simulation/metadata.json +++ b/demonstrations_v2/tutorial_shadow_hamiltonian_simulation/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-08-06T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Computing", "Algorithms" From d0a8c749abd24efeeca7b597a6a8cdd6cf8c6ad9 Mon Sep 17 00:00:00 2001 From: drdren <104710745+drdren@users.noreply.github.com> Date: Tue, 21 Apr 2026 13:18:30 -0400 Subject: [PATCH 07/10] qml to qp Batch 9 (#1760) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### Before submitting Please complete the following checklist when submitting a PR: - [ ] Ensure that your tutorial executes correctly, and conforms to the guidelines specified in the [README](https://github.com/PennyLaneAI/demos/blob/master/README.md). - [ ] Remember to do a grammar check of the content you include. - [ ] All tutorials conform to [PEP8 standards](https://www.python.org/dev/peps/pep-0008/). To auto format files, simply `pip install black`, and then run `black -l 100 path/to/file.py`. When all the above are checked, delete everything above the dashed line and fill in the pull request template. ------------------------------------------------------------------------------------------------------------ **Title:** **Summary:** **Relevant references:** **Possible Drawbacks:** **Related GitHub Issues:** ---- If you are writing a demonstration, please answer these questions to facilitate the marketing process. * GOALS — Why are we working on this now? *Eg. Promote a new PL feature or show a PL implementation of a recent paper.* * AUDIENCE — Who is this for? *Eg. Chemistry researchers, PL educators, beginners in quantum computing.* * KEYWORDS — What words should be included in the marketing post? * Which of the following types of documentation is most similar to your file? (more details [here](https://www.notion.so/xanaduai/Different-kinds-of-documentation-69200645fe59442991c71f9e7d8a77f8)) - [ ] Tutorial - [ ] Demo - [ ] How-to Co-authored-by: David --- .../tutorial_shors_algorithm_catalyst/demo.py | 108 ++++++------- .../metadata.json | 2 +- demonstrations_v2/tutorial_spsa/demo.py | 42 ++--- demonstrations_v2/tutorial_spsa/metadata.json | 2 +- .../tutorial_stabilizer_codes/demo.py | 146 +++++++++--------- .../tutorial_stabilizer_codes/metadata.json | 2 +- .../tutorial_state_preparation/demo.py | 20 +-- .../tutorial_state_preparation/metadata.json | 2 +- .../demo.py | 32 ++-- .../metadata.json | 2 +- .../tutorial_teleportation/demo.py | 38 ++--- .../tutorial_teleportation/metadata.json | 2 +- .../tutorial_tensor_network_basics/demo.py | 4 +- .../metadata.json | 2 +- .../tutorial_testing_symmetry/demo.py | 50 +++--- .../tutorial_testing_symmetry/metadata.json | 2 +- .../tutorial_tn_circuits/demo.py | 86 +++++------ .../tutorial_tn_circuits/metadata.json | 2 +- demonstrations_v2/tutorial_toric_code/demo.py | 54 +++---- .../tutorial_toric_code/metadata.json | 2 +- .../tutorial_trapped_ions/demo.py | 80 +++++----- .../tutorial_trapped_ions/metadata.json | 2 +- .../tutorial_unitary_designs/demo.py | 40 ++--- .../tutorial_unitary_designs/metadata.json | 2 +- .../tutorial_unitary_synthesis_kak/demo.py | 20 +-- .../metadata.json | 2 +- .../tutorial_univariate_qvr/demo.py | 28 ++-- .../tutorial_univariate_qvr/metadata.json | 2 +- .../tutorial_variational_classifier/demo.py | 50 +++--- .../metadata.json | 2 +- demonstrations_v2/tutorial_vqe/demo.py | 20 +-- demonstrations_v2/tutorial_vqe/metadata.json | 2 +- demonstrations_v2/tutorial_vqe_qng/demo.py | 48 +++--- .../tutorial_vqe_qng/metadata.json | 2 +- .../tutorial_vqe_spin_sectors/demo.py | 42 ++--- .../tutorial_vqe_spin_sectors/metadata.json | 2 +- demonstrations_v2/tutorial_vqe_vqd/demo.py | 42 ++--- .../tutorial_vqe_vqd/metadata.json | 2 +- 38 files changed, 494 insertions(+), 494 deletions(-) diff --git a/demonstrations_v2/tutorial_shors_algorithm_catalyst/demo.py b/demonstrations_v2/tutorial_shors_algorithm_catalyst/demo.py index a29b8bd9df..3be6f4b9cf 100644 --- a/demonstrations_v2/tutorial_shors_algorithm_catalyst/demo.py +++ b/demonstrations_v2/tutorial_shors_algorithm_catalyst/demo.py @@ -173,10 +173,10 @@ def shors_algorithm(N): # compilation of the *entire* algorithm from beginning to end. On the surface, it # looks to be as simple as the following: -import pennylane as qml +import pennylane as qp -@qml.qjit +@qp.qjit def shors_algorithm(N): # Implementation goes here return p, q @@ -188,7 +188,7 @@ def shors_algorithm(N): # important parts such that the signature can be as minimal as this: -@qml.qjit(autograph=True, static_argnums=(1)) +@qp.qjit(autograph=True, static_argnums=(1)) def shors_algorithm(N, n_bits): # Implementation goes here return p, q @@ -667,7 +667,7 @@ def phase_to_order(phase, max_denominator): # Below, we have the implementations of the arithmetic circuits derived in the # previous section. -import pennylane as qml +import pennylane as qp import catalyst from catalyst import measure @@ -679,10 +679,10 @@ def QFT(wires): shifts = jnp.array([2 * jnp.pi * 2**-i for i in range(2, len(wires) + 1)]) for i in range(len(wires)): - qml.Hadamard(wires[i]) + qp.Hadamard(wires[i]) for j in range(len(shifts) - i): - qml.ControlledPhaseShift(shifts[j], wires=[wires[(i + 1) + j], wires[i]]) + qp.ControlledPhaseShift(shifts[j], wires=[wires[(i + 1) + j], wires[i]]) def fourier_adder_phase_shift(a, wires): @@ -694,30 +694,30 @@ def fourier_adder_phase_shift(a, wires): for i in range(len(wires)): if phases[i] != 0: - qml.PhaseShift(2 * jnp.pi * phases[i], wires=wires[i]) + qp.PhaseShift(2 * jnp.pi * phases[i], wires=wires[i]) def doubly_controlled_adder(N, a, control_wires, wires, aux_wire): """Sends |c>|x>QFT(|b>)|0> -> |c>|x>QFT(|b + c x a) mod N>)|0>.""" - qml.ctrl(fourier_adder_phase_shift, control=control_wires)(a, wires) + qp.ctrl(fourier_adder_phase_shift, control=control_wires)(a, wires) - qml.adjoint(fourier_adder_phase_shift)(N, wires) + qp.adjoint(fourier_adder_phase_shift)(N, wires) - qml.adjoint(QFT)(wires) - qml.CNOT(wires=[wires[0], aux_wire]) + qp.adjoint(QFT)(wires) + qp.CNOT(wires=[wires[0], aux_wire]) QFT(wires) - qml.ctrl(fourier_adder_phase_shift, control=aux_wire)(N, wires) + qp.ctrl(fourier_adder_phase_shift, control=aux_wire)(N, wires) - qml.adjoint(qml.ctrl(fourier_adder_phase_shift, control=control_wires))(a, wires) + qp.adjoint(qp.ctrl(fourier_adder_phase_shift, control=control_wires))(a, wires) - qml.adjoint(QFT)(wires) - qml.PauliX(wires=wires[0]) - qml.CNOT(wires=[wires[0], aux_wire]) - qml.PauliX(wires=wires[0]) + qp.adjoint(QFT)(wires) + qp.PauliX(wires=wires[0]) + qp.CNOT(wires=[wires[0], aux_wire]) + qp.PauliX(wires=wires[0]) QFT(wires) - qml.ctrl(fourier_adder_phase_shift, control=control_wires)(a, wires) + qp.ctrl(fourier_adder_phase_shift, control=control_wires)(a, wires) def controlled_ua(N, a, control_wire, target_wires, aux_wires, mult_a_mask, mult_a_inv_mask): @@ -735,14 +735,14 @@ def controlled_ua(N, a, control_wire, target_wires, aux_wires, mult_a_mask, mult N, pow_a, [control_wire, target_wires[n - i - 1]], aux_wires[:-1], aux_wires[-1] ) - qml.adjoint(QFT)(wires=aux_wires[:-1]) + qp.adjoint(QFT)(wires=aux_wires[:-1]) # Controlled SWAP the target and aux wires; note that the top-most aux wire # is only to catch overflow, so we ignore it here. for i in range(n): - qml.CNOT(wires=[aux_wires[i + 1], target_wires[i]]) - qml.Toffoli(wires=[control_wire, target_wires[i], aux_wires[i + 1]]) - qml.CNOT(wires=[aux_wires[i + 1], target_wires[i]]) + qp.CNOT(wires=[aux_wires[i + 1], target_wires[i]]) + qp.Toffoli(wires=[control_wire, target_wires[i], aux_wires[i + 1]]) + qp.CNOT(wires=[aux_wires[i + 1], target_wires[i]]) # Adjoint of controlled multiplication with the modular inverse of a a_mod_inv = modular_inverse(a, N) @@ -752,7 +752,7 @@ def controlled_ua(N, a, control_wire, target_wires, aux_wires, mult_a_mask, mult for i in range(n): if mult_a_inv_mask[i] > 0: pow_a_inv = (a_mod_inv * (2 ** (n - i - 1))) % N - qml.adjoint(doubly_controlled_adder)( + qp.adjoint(doubly_controlled_adder)( N, pow_a_inv, [control_wire, target_wires[i]], @@ -763,14 +763,14 @@ def controlled_ua(N, a, control_wire, target_wires, aux_wires, mult_a_mask, mult ###################################################################### # Finally, let's put it all together in the core portion of Shor's algorithm, -# under the ``@qml.qjit`` decorator. +# under the ``@qp.qjit`` decorator. from jax import random # ``n_bits`` is a static argument because ``jnp.arange`` does not currently # support dynamically-shaped arrays when jitted. -@qml.qjit(autograph=True, static_argnums=(3)) +@qp.qjit(autograph=True, static_argnums=(3)) def shors_algorithm(N, key, a, n_bits, n_trials): # If no explicit a is passed (denoted by a = 0), randomly choose a # non-trivial value of a that does not have a common factor with N. @@ -783,10 +783,10 @@ def shors_algorithm(N, key, a, n_bits, n_trials): target_wires = jnp.arange(n_bits) + 1 aux_wires = jnp.arange(n_bits + 2) + n_bits + 1 - dev = qml.device("lightning.qubit", wires=2 * n_bits + 3) + dev = qp.device("lightning.qubit", wires=2 * n_bits + 3) - @qml.set_shots(1) - @qml.qnode(dev) + @qp.set_shots(1) + @qp.qnode(dev) def run_qpe(): meas_results = jnp.zeros((n_bits,), dtype=jnp.int32) cumulative_phase = jnp.array(0.0) @@ -799,7 +799,7 @@ def run_qpe(): a_inv_mask = a_mask # Initialize the target register of QPE in |1> - qml.PauliX(wires=target_wires[-1]) + qp.PauliX(wires=target_wires[-1]) # The "first" QFT on the auxiliary register; required here because # QFT are largely omitted in the modular arithmetic routines due to @@ -807,14 +807,14 @@ def run_qpe(): QFT(wires=aux_wires[:-1]) # First iteration: add a - 1 using the Fourier adder. - qml.Hadamard(wires=est_wire) + qp.Hadamard(wires=est_wire) QFT(wires=target_wires) - qml.ctrl(fourier_adder_phase_shift, control=est_wire)(a - 1, target_wires) - qml.adjoint(QFT)(wires=target_wires) + qp.ctrl(fourier_adder_phase_shift, control=est_wire)(a - 1, target_wires) + qp.adjoint(QFT)(wires=target_wires) # Measure the estimation wire and store the phase - qml.Hadamard(wires=est_wire) + qp.Hadamard(wires=est_wire) meas_results[0] = measure(est_wire, reset=True) cumulative_phase = -2 * jnp.pi * jnp.sum(meas_results / jnp.roll(phase_divisors, 1)) @@ -838,7 +838,7 @@ def run_qpe(): jnp.unpackbits(next_pow_a.view("uint8"), bitorder="little")[:n_bits] ) - qml.Hadamard(wires=est_wire) + qp.Hadamard(wires=est_wire) controlled_ua(N, pow_cua, est_wire, target_wires, aux_wires, a_mask, a_inv_mask) @@ -846,15 +846,15 @@ def run_qpe(): a_inv_mask = jnp.zeros_like(a_inv_mask) # Rotate the estimation wire by the accumulated phase, then measure and reset it - qml.PhaseShift(cumulative_phase, wires=est_wire) - qml.Hadamard(wires=est_wire) + qp.PhaseShift(cumulative_phase, wires=est_wire) + qp.Hadamard(wires=est_wire) meas_results[pow_a_idx] = measure(est_wire, reset=True) cumulative_phase = ( -2 * jnp.pi * jnp.sum(meas_results / jnp.roll(phase_divisors, pow_a_idx + 1)) ) # The adjoint partner of the QFT from the beginning, to reset the auxiliary register - qml.adjoint(QFT)(wires=aux_wires[:-1]) + qp.adjoint(QFT)(wires=aux_wires[:-1]) return meas_results @@ -965,8 +965,8 @@ def run_qpe(): # circuits for many different :math:`N` using both the QJIT version, and the # plain PennyLane version below. Note the standard PennyLane version makes use # of many of the same subroutines and optimizations, but due to limitations on -# how PennyLane handles mid-circuit measurements, we must use ``qml.cond`` and -# explicit ``qml.PhaseShift`` gates. +# how PennyLane handles mid-circuit measurements, we must use ``qp.cond`` and +# explicit ``qp.PhaseShift`` gates. def shors_algorithm_no_qjit(N, key, a, n_bits, n_trials): @@ -974,10 +974,10 @@ def shors_algorithm_no_qjit(N, key, a, n_bits, n_trials): target_wires = list(range(1, n_bits + 1)) aux_wires = list(range(n_bits + 1, 2 * n_bits + 3)) - dev = qml.device("lightning.qubit", wires=2 * n_bits + 3) + dev = qp.device("lightning.qubit", wires=2 * n_bits + 3) - @qml.set_shots(1) - @qml.qnode(dev) + @qp.set_shots(1) + @qp.qnode(dev) def run_qpe(): a_mask = jnp.zeros(n_bits, dtype=jnp.int64) a_mask = a_mask.at[0].set(1) + jnp.array( @@ -987,18 +987,18 @@ def run_qpe(): measurements = [] - qml.PauliX(wires=target_wires[-1]) + qp.PauliX(wires=target_wires[-1]) QFT(wires=aux_wires[:-1]) - qml.Hadamard(wires=est_wire) + qp.Hadamard(wires=est_wire) QFT(wires=target_wires) - qml.ctrl(fourier_adder_phase_shift, control=est_wire)(a - 1, target_wires) - qml.adjoint(QFT)(wires=target_wires) + qp.ctrl(fourier_adder_phase_shift, control=est_wire)(a - 1, target_wires) + qp.adjoint(QFT)(wires=target_wires) - qml.Hadamard(wires=est_wire) - measurements.append(qml.measure(est_wire, reset=True)) + qp.Hadamard(wires=est_wire) + measurements.append(qp.measure(est_wire, reset=True)) powers_cua = jnp.array([repeated_squaring(a, 2**p, N) for p in range(n_bits)]) @@ -1016,7 +1016,7 @@ def run_qpe(): jnp.unpackbits(next_pow_a.view("uint8"), bitorder="little")[:n_bits] ) - qml.Hadamard(wires=est_wire) + qp.Hadamard(wires=est_wire) controlled_ua(N, pow_cua, est_wire, target_wires, aux_wires, a_mask, a_inv_mask) @@ -1025,16 +1025,16 @@ def run_qpe(): # The main difference with the QJIT version for meas_idx, meas in enumerate(measurements): - qml.cond(meas, qml.PhaseShift)( + qp.cond(meas, qp.PhaseShift)( -2 * jnp.pi / 2 ** (pow_a_idx + 2 - meas_idx), wires=est_wire ) - qml.Hadamard(wires=est_wire) - measurements.append(qml.measure(est_wire, reset=True)) + qp.Hadamard(wires=est_wire) + measurements.append(qp.measure(est_wire, reset=True)) - qml.adjoint(QFT)(wires=aux_wires[:-1]) + qp.adjoint(QFT)(wires=aux_wires[:-1]) - return qml.sample(measurements) + return qp.sample(measurements) p, q = jnp.array(0, dtype=jnp.int32), jnp.array(0, dtype=jnp.int32) successful_trials = jnp.array(0, dtype=jnp.int32) diff --git a/demonstrations_v2/tutorial_shors_algorithm_catalyst/metadata.json b/demonstrations_v2/tutorial_shors_algorithm_catalyst/metadata.json index 060fa92efe..acd9a76105 100644 --- a/demonstrations_v2/tutorial_shors_algorithm_catalyst/metadata.json +++ b/demonstrations_v2/tutorial_shors_algorithm_catalyst/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2025-04-04T09:00:00+00:00", - "dateOfLastModification": "2025-12-10T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Algorithms", "Quantum Computing", diff --git a/demonstrations_v2/tutorial_spsa/demo.py b/demonstrations_v2/tutorial_spsa/demo.py index 2d45d0a089..aca6176a11 100644 --- a/demonstrations_v2/tutorial_spsa/demo.py +++ b/demonstrations_v2/tutorial_spsa/demo.py @@ -163,25 +163,25 @@ """ -import pennylane as qml +import pennylane as qp from pennylane import numpy as np num_wires = 4 num_layers = 5 -device = qml.device("qiskit.aer", wires=num_wires) +device = qp.device("qiskit.aer", wires=num_wires) -ansatz = qml.StronglyEntanglingLayers +ansatz = qp.StronglyEntanglingLayers -all_pauliz_tensor_prod = qml.prod(*[qml.PauliZ(i) for i in range(num_wires)]) +all_pauliz_tensor_prod = qp.prod(*[qp.PauliZ(i) for i in range(num_wires)]) def circuit(param): ansatz(param, wires=list(range(num_wires))) - return qml.expval(all_pauliz_tensor_prod) + return qp.expval(all_pauliz_tensor_prod) -cost_function = qml.set_shots(qml.QNode(circuit, device), shots = 1000) +cost_function = qp.set_shots(qp.QNode(circuit, device), shots = 1000) np.random.seed(50) @@ -262,7 +262,7 @@ def run_optimizer(opt, cost_function, init_param, num_steps, interval, execs_per # `__ num_steps_spsa = 200 -opt = qml.SPSAOptimizer(maxiter=num_steps_spsa, c=0.15, a=0.2) +opt = qp.SPSAOptimizer(maxiter=num_steps_spsa, c=0.15, a=0.2) # We spend 2 circuit evaluations per step: execs_per_step = 2 cost_history_spsa, exec_history_spsa = run_optimizer( @@ -275,7 +275,7 @@ def run_optimizer(opt, cost_function, init_param, num_steps, interval, execs_per # convergence. num_steps_grad = 15 -opt = qml.GradientDescentOptimizer(stepsize=0.3) +opt = qp.GradientDescentOptimizer(stepsize=0.3) # We spend 2 circuit evaluations per parameter per step: execs_per_step = 2 * np.prod(param_shape) cost_history_grad, exec_history_grad = run_optimizer( @@ -344,21 +344,21 @@ def run_optimizer(opt, cost_function, init_param, num_steps, interval, execs_per molecule = qchem.Molecule(symbols, coordinates) h2_ham, num_qubits = qchem.molecular_hamiltonian(molecule) h2_ham_coeffs, h2_ham_ops = h2_ham.terms() -h2_ham = qml.Hamiltonian(qml.math.real(h2_ham_coeffs), h2_ham_ops) +h2_ham = qp.Hamiltonian(qp.math.real(h2_ham_coeffs), h2_ham_ops) true_energy = -1.136189454088 # Variational ansatz for H_2 - see Intro VQE demo for more details def ansatz(param, wires): - qml.BasisState(np.array([1, 1, 0, 0]), wires=wires) + qp.BasisState(np.array([1, 1, 0, 0]), wires=wires) for i in wires: - qml.Rot(*param[0, i], wires=i) - qml.CNOT(wires=[2, 3]) - qml.CNOT(wires=[2, 0]) - qml.CNOT(wires=[3, 1]) + qp.Rot(*param[0, i], wires=i) + qp.CNOT(wires=[2, 3]) + qp.CNOT(wires=[2, 0]) + qp.CNOT(wires=[3, 1]) for i in wires: - qml.Rot(*param[1, i], wires=i) + qp.Rot(*param[1, i], wires=i) ############################################################################## @@ -376,24 +376,24 @@ def ansatz(param, wires): # The above line only needs to be run once. # List the providers to pick an available backend: # IBMProvider().backends() # List all available backends -# dev = qml.device("qiskit.ibmq", wires=num_qubits, backend="ibmq_lima") +# dev = qp.device("qiskit.ibmq", wires=num_qubits, backend="ibmq_lima") from qiskit_ibm_runtime.fake_provider import FakeLimaV2 as FakeLima from qiskit_aer import noise # Load a fake backed to create a noise model, and create a device using that model noise_model = noise.NoiseModel.from_backend(FakeLima()) -noisy_device = qml.device( +noisy_device = qp.device( "qiskit.aer", wires=num_qubits, noise_model=noise_model ) def circuit(param): ansatz(param, range(num_qubits)) - return qml.expval(h2_ham) + return qp.expval(h2_ham) -cost_function = qml.set_shots(qml.QNode(circuit, noisy_device), shots = 1000) +cost_function = qp.set_shots(qp.QNode(circuit, noisy_device), shots = 1000) # This random seed was used in the original VQE demo and is known to allow the # gradient descent algorithm to converge to the global minimum. @@ -402,7 +402,7 @@ def circuit(param): init_param = np.random.normal(0, np.pi, param_shape, requires_grad=True) # Initialize the optimizer - optimal step size was found through a grid search -opt = qml.GradientDescentOptimizer(stepsize=2.2) +opt = qp.GradientDescentOptimizer(stepsize=2.2) # We spend 2 * 15 circuit evaluations per parameter per step, as there are # 15 Hamiltonian terms @@ -458,7 +458,7 @@ def circuit(param): # executions. num_steps_spsa = 160 -opt = qml.SPSAOptimizer(maxiter=num_steps_spsa, c=0.3, a=1.5) +opt = qp.SPSAOptimizer(maxiter=num_steps_spsa, c=0.3, a=1.5) # We spend 2 * 15 circuit evaluations per step, as there are 15 Hamiltonian terms execs_per_step = 2 * 15 diff --git a/demonstrations_v2/tutorial_spsa/metadata.json b/demonstrations_v2/tutorial_spsa/metadata.json index f30460d51c..728f8dba44 100644 --- a/demonstrations_v2/tutorial_spsa/metadata.json +++ b/demonstrations_v2/tutorial_spsa/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-03-19T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_stabilizer_codes/demo.py b/demonstrations_v2/tutorial_stabilizer_codes/demo.py index df4477acb1..0065626129 100644 --- a/demonstrations_v2/tutorial_stabilizer_codes/demo.py +++ b/demonstrations_v2/tutorial_stabilizer_codes/demo.py @@ -67,27 +67,27 @@ """ -import pennylane as qml +import pennylane as qp from pennylane import numpy as np def encode(alpha, beta): - qml.StatePrep([alpha, beta], wires=0) - qml.CNOT(wires=[0, 1]) - qml.CNOT(wires=[0, 2]) + qp.StatePrep([alpha, beta], wires=0) + qp.CNOT(wires=[0, 1]) + qp.CNOT(wires=[0, 2]) def encoded_state(alpha, beta): encode(alpha, beta) - return qml.state() + return qp.state() -encode_qnode = qml.QNode(encoded_state, qml.device("default.qubit")) +encode_qnode = qp.QNode(encoded_state, qp.device("default.qubit")) alpha = 1 / np.sqrt(2) beta = 1 / np.sqrt(2) -encode_qnode = qml.QNode(encoded_state, qml.device("default.qubit")) +encode_qnode = qp.QNode(encoded_state, qp.device("default.qubit")) print("|000> component: ", encode_qnode(alpha, beta)[0]) print("|111> component: ", encode_qnode(alpha, beta)[7]) @@ -138,22 +138,22 @@ def encoded_state(alpha, beta): def error_detection(): - qml.CNOT(wires=[0, 3]) - qml.CNOT(wires=[1, 3]) - qml.CNOT(wires=[1, 4]) - qml.CNOT(wires=[2, 4]) + qp.CNOT(wires=[0, 3]) + qp.CNOT(wires=[1, 3]) + qp.CNOT(wires=[1, 4]) + qp.CNOT(wires=[2, 4]) -@qml.set_shots(1) -@qml.qnode(qml.device("default.qubit", wires=5)) # A single sample flags error +@qp.set_shots(1) +@qp.qnode(qp.device("default.qubit", wires=5)) # A single sample flags error def syndrome_measurement(error_wire): encode(alpha, beta) - qml.PauliX(wires=error_wire) # Unwanted Pauli Operator + qp.PauliX(wires=error_wire) # Unwanted Pauli Operator error_detection() - return qml.sample(wires=[3, 4]) + return qp.sample(wires=[3, 4]) print("Syndrome if error on wire 0: ", syndrome_measurement(0)) @@ -190,28 +190,28 @@ def syndrome_measurement(error_wire): # We can use PennyLane's mid-circuit measurement features to implement the full three-qubit repetition code. -@qml.qnode(qml.device("default.qubit", wires=5)) +@qp.qnode(qp.device("default.qubit", wires=5)) def error_correction(error_wire): encode(alpha, beta) - qml.PauliX(wires=error_wire) + qp.PauliX(wires=error_wire) error_detection() # Mid circuit measurements - m3 = qml.measure(3) - m4 = qml.measure(4) + m3 = qp.measure(3) + m4 = qp.measure(4) # Operations conditional on measurements - qml.cond(m3 & ~m4, qml.PauliX)(wires=0) - qml.cond(m3 & m4, qml.PauliX)(wires=1) - qml.cond(~m3 & m4, qml.PauliX)(wires=2) + qp.cond(m3 & ~m4, qp.PauliX)(wires=0) + qp.cond(m3 & m4, qp.PauliX)(wires=1) + qp.cond(~m3 & m4, qp.PauliX)(wires=2) - return qml.density_matrix( + return qp.density_matrix( wires=[0, 1, 2] - ) # qml.state not supported, but density matrices are. + ) # qp.state not supported, but density matrices are. ############################################################################## @@ -220,23 +220,23 @@ def error_correction(error_wire): # With this result, we can verify that the fidelity of the encoded state is the same as the final state after correction # as follows. -dev = qml.device("default.qubit", wires=5) -error_correction_qnode = qml.QNode(error_correction, dev) -encoded_state = qml.math.dm_from_state_vector(encode_qnode(alpha, beta)) +dev = qp.device("default.qubit", wires=5) +error_correction_qnode = qp.QNode(error_correction, dev) +encoded_state = qp.math.dm_from_state_vector(encode_qnode(alpha, beta)) # Compute fidelity of final corrected state with initial encoded state print( "Fidelity when error on wire 0: ", - qml.math.fidelity(encoded_state, error_correction_qnode(0)).round(2), + qp.math.fidelity(encoded_state, error_correction_qnode(0)).round(2), ) print( "Fidelity when error on wire 1: ", - qml.math.fidelity(encoded_state, error_correction_qnode(1)).round(2), + qp.math.fidelity(encoded_state, error_correction_qnode(1)).round(2), ) print( "Fidelity when error on wire 2: ", - qml.math.fidelity(encoded_state, error_correction_qnode(2)).round(2), + qp.math.fidelity(encoded_state, error_correction_qnode(2)).round(2), ) ############################################################################## @@ -385,7 +385,7 @@ def generate_stabilizer_group(gens, num_wires): op = init_op for i, bit in enumerate(bits): if bit: - op = qml.prod(op, gens[i]).simplify() + op = qp.prod(op, gens[i]).simplify() group.append(op) return set(group) @@ -479,7 +479,7 @@ def classify_pauli(operator, logical_ops, generators, n_wires): if operator.simplify() in stabilizer_group: return f"{operator} is a Stabilizer." - if all(qml.is_commuting(operator, g) for g in generators): + if all(qp.is_commuting(operator, g) for g in generators): if operator in logical_ops: return f"{operator} is a Logical Operator." else: @@ -564,25 +564,25 @@ def classify_pauli(operator, logical_ops, generators, n_wires): def five_qubit_encode(alpha, beta): - qml.StatePrep([alpha, beta], wires=4) - qml.Hadamard(wires=0) - qml.S(wires=0) - qml.CZ(wires=[0, 1]) - qml.CZ(wires=[0, 3]) - qml.CY(wires=[0, 4]) - qml.Hadamard(wires=1) - qml.CZ(wires=[1, 2]) - qml.CZ(wires=[1, 3]) - qml.CNOT(wires=[1, 4]) - qml.Hadamard(wires=2) - qml.CZ(wires=[2, 0]) - qml.CZ(wires=[2, 1]) - qml.CNOT(wires=[2, 4]) - qml.Hadamard(wires=3) - qml.S(wires=3) - qml.CZ(wires=[3, 0]) - qml.CZ(wires=[3, 2]) - qml.CY(wires=[3, 4]) + qp.StatePrep([alpha, beta], wires=4) + qp.Hadamard(wires=0) + qp.S(wires=0) + qp.CZ(wires=[0, 1]) + qp.CZ(wires=[0, 3]) + qp.CY(wires=[0, 4]) + qp.Hadamard(wires=1) + qp.CZ(wires=[1, 2]) + qp.CZ(wires=[1, 3]) + qp.CNOT(wires=[1, 4]) + qp.Hadamard(wires=2) + qp.CZ(wires=[2, 0]) + qp.CZ(wires=[2, 1]) + qp.CNOT(wires=[2, 4]) + qp.Hadamard(wires=3) + qp.S(wires=3) + qp.CZ(wires=[3, 0]) + qp.CZ(wires=[3, 2]) + qp.CY(wires=[3, 4]) ############################################################################## @@ -612,13 +612,13 @@ def five_qubit_encode(alpha, beta): def five_qubit_error_detection(): for wire in range(5, 9): - qml.Hadamard(wires=wire) + qp.Hadamard(wires=wire) for i in range(len(stabilizers)): - qml.ctrl(stabilizers[i], control=[i + 5]) + qp.ctrl(stabilizers[i], control=[i + 5]) for wire in range(5, 9): - qml.Hadamard(wires=wire) + qp.Hadamard(wires=wire) ############################################################################# @@ -627,11 +627,11 @@ def five_qubit_error_detection(): # measures the syndrome, as we did in the three-qubit code. # -dev = qml.device("default.qubit", wires=9) +dev = qp.device("default.qubit", wires=9) -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def five_qubit_syndromes(alpha, beta, error_op, error_wire): five_qubit_encode(alpha, beta) @@ -639,7 +639,7 @@ def five_qubit_syndromes(alpha, beta, error_op, error_wire): five_qubit_error_detection() - return qml.sample(wires=range(5, 9)) + return qp.sample(wires=range(5, 9)) ############################################################################# @@ -650,7 +650,7 @@ def five_qubit_syndromes(alpha, beta, error_op, error_wire): ops_and_syndromes = [] for wire in (0, 1, 2, 3, 4): - for error_op in (qml.PauliX, qml.PauliY, qml.PauliZ): + for error_op in (qp.PauliX, qp.PauliY, qp.PauliZ): ops_and_syndromes.append( ( error_op, @@ -678,7 +678,7 @@ def five_qubit_syndromes(alpha, beta, error_op, error_wire): # PennyLane's mid-circuit measurement capabilities, which only allows for Boolean operators. # def syndrome_booleans(syndrome, measurements): - syndrome = qml.math.squeeze(syndrome) + syndrome = qp.math.squeeze(syndrome) if syndrome[0] == 0: m = ~measurements[0] else: @@ -697,10 +697,10 @@ def syndrome_booleans(syndrome, measurements): # # Combining all these pieces, we can write the full error correcting code. # -dev = qml.device("default.qubit", wires=9) +dev = qp.device("default.qubit", wires=9) -@qml.qnode(dev) +@qp.qnode(dev) def five_qubit_code(alpha, beta, error_op, error_wire): five_qubit_encode(alpha, beta) @@ -708,17 +708,17 @@ def five_qubit_code(alpha, beta, error_op, error_wire): five_qubit_error_detection() - m5 = qml.measure(5) - m6 = qml.measure(6) - m7 = qml.measure(7) - m8 = qml.measure(8) + m5 = qp.measure(5) + m6 = qp.measure(6) + m7 = qp.measure(7) + m8 = qp.measure(8) measurements = [m5, m6, m7, m8] for op, wire, synd in ops_and_syndromes: - qml.cond(syndrome_booleans(synd, measurements), op)(wires=wire) + qp.cond(syndrome_booleans(synd, measurements), op)(wires=wire) - return qml.density_matrix(wires=[0, 1, 2, 3, 4]) + return qp.density_matrix(wires=[0, 1, 2, 3, 4]) ############################################################################# @@ -728,18 +728,18 @@ def five_qubit_code(alpha, beta, error_op, error_wire): # -@qml.qnode(qml.device("default.qubit", wires=5)) +@qp.qnode(qp.device("default.qubit", wires=5)) def five_qubit_encoded_state(alpha, beta): five_qubit_encode(alpha, beta) - return qml.state() + return qp.state() -encoded_state = qml.math.dm_from_state_vector(five_qubit_encoded_state(alpha, beta)) +encoded_state = qp.math.dm_from_state_vector(five_qubit_encoded_state(alpha, beta)) for wire in range(5): - for error_op in (qml.PauliX, qml.PauliY, qml.PauliZ): + for error_op in (qp.PauliX, qp.PauliY, qp.PauliZ): print( f"Fidelity when error {error_op(wire).name[-1]}{wire}:", - qml.math.fidelity( + qp.math.fidelity( encoded_state, five_qubit_code(alpha, beta, error_op, wire) ).round(2), ) diff --git a/demonstrations_v2/tutorial_stabilizer_codes/metadata.json b/demonstrations_v2/tutorial_stabilizer_codes/metadata.json index 831026aa2a..39d7502672 100644 --- a/demonstrations_v2/tutorial_stabilizer_codes/metadata.json +++ b/demonstrations_v2/tutorial_stabilizer_codes/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2025-08-19T09:00:00+00:00", - "dateOfLastModification": "2025-12-19T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Algorithms", "Quantum Computing", diff --git a/demonstrations_v2/tutorial_state_preparation/demo.py b/demonstrations_v2/tutorial_state_preparation/demo.py index f91faefdb0..fe22833915 100644 --- a/demonstrations_v2/tutorial_state_preparation/demo.py +++ b/demonstrations_v2/tutorial_state_preparation/demo.py @@ -47,7 +47,7 @@ # # To start, we import PennyLane, NumPy, and PyTorch for the optimization: -import pennylane as qml +import pennylane as qp import numpy as np import torch from torch.autograd import Variable @@ -99,20 +99,20 @@ # a layer of the circuit ansatz def layer(params, j): for i in range(nr_qubits): - qml.RX(params[i, j, 0], wires=i) - qml.RY(params[i, j, 1], wires=i) - qml.RZ(params[i, j, 2], wires=i) + qp.RX(params[i, j, 0], wires=i) + qp.RY(params[i, j, 1], wires=i) + qp.RZ(params[i, j, 2], wires=i) - qml.CNOT(wires=[0, 1]) - qml.CNOT(wires=[0, 2]) - qml.CNOT(wires=[1, 2]) + qp.CNOT(wires=[0, 1]) + qp.CNOT(wires=[0, 2]) + qp.CNOT(wires=[1, 2]) ############################################################################## # Here, we use the ``default.qubit`` device to perform the optimization, but this can be changed to # any other supported device. -dev = qml.device("default.qubit", wires=3) +dev = qp.device("default.qubit", wires=3) ############################################################################## # When defining the QNode, we introduce as input a Hermitian operator @@ -124,7 +124,7 @@ def layer(params, j): # to use the PyTorch interface: -@qml.qnode(dev, interface="torch") +@qp.qnode(dev, interface="torch") def circuit(params, A): # repeatedly apply each layer in the circuit @@ -132,7 +132,7 @@ def circuit(params, A): layer(params, j) # returns the expectation of the input matrix A on the first qubit - return qml.expval(qml.Hermitian(A, wires=0)) + return qp.expval(qp.Hermitian(A, wires=0)) ############################################################################## diff --git a/demonstrations_v2/tutorial_state_preparation/metadata.json b/demonstrations_v2/tutorial_state_preparation/metadata.json index 61dfbdd860..37f7acaa4b 100644 --- a/demonstrations_v2/tutorial_state_preparation/metadata.json +++ b/demonstrations_v2/tutorial_state_preparation/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2019-10-11T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Devices and Performance" ], diff --git a/demonstrations_v2/tutorial_stochastic_parameter_shift/demo.py b/demonstrations_v2/tutorial_stochastic_parameter_shift/demo.py index 9447e2203b..a0cde0a5e5 100644 --- a/demonstrations_v2/tutorial_stochastic_parameter_shift/demo.py +++ b/demonstrations_v2/tutorial_stochastic_parameter_shift/demo.py @@ -114,24 +114,24 @@ Let's jump into some code and take a look at the parameter-shift rule in action. """ -import pennylane as qml +import pennylane as qp import matplotlib.pyplot as plt from pennylane import numpy as np from scipy.linalg import expm np.random.seed(143) angles = np.linspace(0, 2 * np.pi, 50) -dev = qml.device('default.qubit', wires=2) +dev = qp.device('default.qubit', wires=2) ############################################################################## # We will consider a very simple circuit, containing just a single-qubit # rotation about the x-axis, followed by a measurement along the z-axis. -@qml.qnode(dev) +@qp.qnode(dev) def rotation_circuit(theta): - qml.RX(theta, wires=0) - return qml.expval(qml.PauliZ(0)) + qp.RX(theta, wires=0) + return qp.expval(qp.PauliZ(0)) ############################################################################## @@ -143,7 +143,7 @@ def rotation_circuit(theta): # # .. note:: # -# Check out the :mod:`qml.gradients ` module +# Check out the :mod:`qp.gradients ` module # to explore all quantum gradient transforms provided by PennyLane. def param_shift(theta): @@ -152,13 +152,13 @@ def param_shift(theta): r_minus = rotation_circuit(theta - np.pi / 2) return 0.5 * (r_plus - r_minus) -gradient = qml.grad(rotation_circuit, argnums=0) +gradient = qp.grad(rotation_circuit, argnums=0) expvals = [rotation_circuit(theta) for theta in angles] grad_vals = [gradient(theta) for theta in angles] param_shift_vals = [param_shift(theta) for theta in angles] plt.plot(angles, expvals, 'b', label="Expecation value") -plt.plot(angles, grad_vals, 'r', label="qml.grad function") +plt.plot(angles, grad_vals, 'r', label="qp.grad function") plt.plot(angles, param_shift_vals, 'mx', label="Parameter-shift rule") plt.xlabel("theta") plt.legend() @@ -291,11 +291,11 @@ def Generator(theta1, theta2, theta3): return G # A simple example circuit that contains the cross-resonance gate -@qml.qnode(dev) +@qp.qnode(dev) def crossres_circuit(gate_pars): G = Generator(*gate_pars) - qml.QubitUnitary(expm(-1j * G), wires=[0, 1]) - return qml.expval(qml.PauliZ(0)) + qp.QubitUnitary(expm(-1j * G), wires=[0, 1]) + return qp.expval(qp.PauliZ(0)) # Subcircuit implementing the gates necessary for the # stochastic parameter-shift rule. @@ -304,18 +304,18 @@ def crossres_circuit(gate_pars): def SPSRgates(gate_pars, s, sign): G = Generator(*gate_pars) # step a) - qml.QubitUnitary(expm(1j * (1 - s) * G), wires=[0, 1]) + qp.QubitUnitary(expm(1j * (1 - s) * G), wires=[0, 1]) # step b) - qml.QubitUnitary(expm(1j * sign * np.pi / 4 * X), wires=0) + qp.QubitUnitary(expm(1j * sign * np.pi / 4 * X), wires=0) # step c) - qml.QubitUnitary(expm(1j * s * G), wires=[0,1]) + qp.QubitUnitary(expm(1j * s * G), wires=[0,1]) # Function which can obtain all expectation vals needed # for the stochastic parameter-shift rule -@qml.qnode(dev) +@qp.qnode(dev) def spsr_circuit(gate_pars, s=None, sign=+1): SPSRgates(gate_pars, s, sign) - return qml.expval(qml.PauliZ(0)) + return qp.expval(qp.PauliZ(0)) # Fix the other parameters of the gate theta2, theta3 = -0.15, 1.6 diff --git a/demonstrations_v2/tutorial_stochastic_parameter_shift/metadata.json b/demonstrations_v2/tutorial_stochastic_parameter_shift/metadata.json index e1058082ab..39f6f0c2c4 100644 --- a/demonstrations_v2/tutorial_stochastic_parameter_shift/metadata.json +++ b/demonstrations_v2/tutorial_stochastic_parameter_shift/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2020-05-25T00:00:00+00:00", - "dateOfLastModification": "2026-01-14T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_teleportation/demo.py b/demonstrations_v2/tutorial_teleportation/demo.py index 37ed6f2605..a834077b33 100644 --- a/demonstrations_v2/tutorial_teleportation/demo.py +++ b/demonstrations_v2/tutorial_teleportation/demo.py @@ -124,12 +124,12 @@ # We can use the following `quantum function `__ # to do the state preparation step: -import pennylane as qml +import pennylane as qp import numpy as np def state_preparation(state): - qml.StatePrep(state, wires=["S"]) + qp.StatePrep(state, wires=["S"]) ############################################################################## @@ -171,8 +171,8 @@ def state_preparation(state): def entangle_qubits(): - qml.Hadamard(wires="A") - qml.CNOT(wires=["A", "B"]) + qp.Hadamard(wires="A") + qp.CNOT(wires=["A", "B"]) ############################################################################## @@ -230,8 +230,8 @@ def entangle_qubits(): def basis_rotation(): - qml.CNOT(wires=["S", "A"]) - qml.Hadamard(wires="S") + qp.CNOT(wires=["S", "A"]) + qp.Hadamard(wires="S") ############################################################################## @@ -275,16 +275,16 @@ def basis_rotation(): # correction. In this situation, measurements are happening partway through the protocol, # and the results would be used to control the application of future quantum gates. This # is known as mid-circuit measurement, and such mid-circuit measurements are expressed -# in PennyLane using :func:`qml.measure `. Mid-circuit measurement +# in PennyLane using :func:`qp.measure `. Mid-circuit measurement # results can be used to control operations, and this is expressed in PennyLane using -# :func:`qml.cond `. +# :func:`qp.cond `. def measure_and_update(): - m0 = qml.measure("S") - m1 = qml.measure("A") - qml.cond(m1, qml.PauliX)("B") - qml.cond(m0, qml.PauliZ)("B") + m0 = qp.measure("S") + m1 = qp.measure("A") + qp.cond(m1, qp.PauliX)("B") + qp.cond(m0, qp.PauliZ)("B") ############################################################################## @@ -301,7 +301,7 @@ def teleport(state): state = np.array([1 / np.sqrt(2) + 0.3j, 0.4 - 0.5j]) -_ = qml.draw_mpl(teleport, style="pennylane")(state) +_ = qp.draw_mpl(teleport, style="pennylane")(state) ############################################################################## # @@ -316,19 +316,19 @@ def teleport(state): # specify ``level="device"`` when calling ``draw_mpl`` so it # runs the device pre-processing before drawing the circuit. -dev = qml.device("default.qubit", wires=["S", "A", "B"]) +dev = qp.device("default.qubit", wires=["S", "A", "B"]) -@qml.qnode(dev) +@qp.qnode(dev) def teleport(state): state_preparation(state) entangle_qubits() basis_rotation() measure_and_update() - return qml.density_matrix(wires=["B"]) + return qp.density_matrix(wires=["B"]) -_ = qml.draw_mpl(teleport, style="pennylane", level="device")(state) +_ = qp.draw_mpl(teleport, style="pennylane", level="device")(state) ############################################################################## # @@ -355,7 +355,7 @@ def teleport(state): # 1\rangle`. This means that our protocol has changed the state of Bob's qubit # into the one Alice wished to send him, which is truly incredible! # -# We can use :func:`qml.density_matrix ` to trace out +# We can use :func:`qp.density_matrix ` to trace out # and return Bob's subsystem as a density matrix, which is a more general # description of the state of his qubit. We will use this to verify that Alice's # state was successfully teleported to Bob's qubit. @@ -372,7 +372,7 @@ def teleport(state): def teleport_state(state): teleported_density_matrix = teleport(state) - original_density_matrix = qml.math.dm_from_state_vector(state) + original_density_matrix = qp.math.dm_from_state_vector(state) if not np.allclose(teleported_density_matrix, original_density_matrix): raise ValueError( diff --git a/demonstrations_v2/tutorial_teleportation/metadata.json b/demonstrations_v2/tutorial_teleportation/metadata.json index ba9fe90a44..f0f73aa2f6 100644 --- a/demonstrations_v2/tutorial_teleportation/metadata.json +++ b/demonstrations_v2/tutorial_teleportation/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-10-20T00:00:00+00:00", - "dateOfLastModification": "2025-12-19T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Getting Started", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_tensor_network_basics/demo.py b/demonstrations_v2/tutorial_tensor_network_basics/demo.py index f459bc2e96..78398596b7 100644 --- a/demonstrations_v2/tutorial_tensor_network_basics/demo.py +++ b/demonstrations_v2/tutorial_tensor_network_basics/demo.py @@ -379,9 +379,9 @@ # # As we will explore in the next section, we can use tensor networks to simulate quantum circuits. In particular, the calculation of an expectation value corresponds to the contraction of the tensor network into a single tensor (scalar). In ``Pennylane``, this simulation can be performed using the :class:`~pennylane.devices.default_tensor.DefaultTensor` device, and the method used to find the contraction path can be chosen via the ``contraction_optimizer`` keyword argument. -import pennylane as qml +import pennylane as qp -dev = qml.device("default.tensor", method="tn", contraction_optimizer="auto-hq") +dev = qp.device("default.tensor", method="tn", contraction_optimizer="auto-hq") ############################################################################## # The different types of values accepted for ``contraction_optimizer`` are determined by the ``optimize`` parameter in ``Quimb`` (see `docs `_) as this is the backend behind the :class:`~pennylane.devices.default_tensor.DefaultTensor` device. See our `simulate quantum circuits with tensor networks demo `_ to learn more about the use of this device in ``Pennylane``. diff --git a/demonstrations_v2/tutorial_tensor_network_basics/metadata.json b/demonstrations_v2/tutorial_tensor_network_basics/metadata.json index dafbcb9d77..4177c4fb87 100644 --- a/demonstrations_v2/tutorial_tensor_network_basics/metadata.json +++ b/demonstrations_v2/tutorial_tensor_network_basics/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2025-01-23T09:00:00+00:00", - "dateOfLastModification": "2026-01-14T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Getting Started", "Quantum Computing", diff --git a/demonstrations_v2/tutorial_testing_symmetry/demo.py b/demonstrations_v2/tutorial_testing_symmetry/demo.py index bc8963d699..b01ec214ae 100644 --- a/demonstrations_v2/tutorial_testing_symmetry/demo.py +++ b/demonstrations_v2/tutorial_testing_symmetry/demo.py @@ -107,37 +107,37 @@ for basis states :math:`\vert x_0 x_1 x_2 x_3\rangle` and extends by linearity. The simplest way to do this is by using -:class:`qml.Permute `. +:class:`qp.Permute `. We can convert this into a matrix by using -:class:`qml.matrix() `. +:class:`qp.matrix() `. We can obtain any other element :math:`g\in G` by simply iterating :math:`c` the appropriate number of times. """ -import pennylane as qml +import pennylane as qp from pennylane import numpy as np # Create wires for the system system = range(4) # The generator of the group -c = qml.Permute([3, 0, 1, 2], wires=system) -c_mat = qml.matrix(c) +c = qp.Permute([3, 0, 1, 2], wires=system) +c_mat = qp.matrix(c) ###################################################################### # To create the Hamiltonians, we use -# :class:`qml.Hamiltonian `: +# :class:`qp.Hamiltonian `: # # Create Hamiltonians -obs = [qml.PauliX(system[0]), qml.PauliX(system[1]), qml.PauliX(system[2]), qml.PauliX(system[3])] +obs = [qp.PauliX(system[0]), qp.PauliX(system[1]), qp.PauliX(system[2]), qp.PauliX(system[3])] coeffs1, coeffs2, coeffs3 = [1, 1, 1, 1], [1, 1.1, 0.9, 1], [1, 2, 3, 0] Hsymm, Hnsym, Hasym = ( - qml.Hamiltonian(coeffs1, obs), - qml.Hamiltonian(coeffs2, obs), - qml.Hamiltonian(coeffs3, obs), + qp.Hamiltonian(coeffs1, obs), + qp.Hamiltonian(coeffs2, obs), + qp.Hamiltonian(coeffs3, obs), ) @@ -203,8 +203,8 @@ # Prepare entangled state on system and copy def prep_entangle(): for wire in system: - qml.Hadamard(wire) - qml.CNOT(wires=[wire, wire + 4]) + qp.Hadamard(wire) + qp.CNOT(wires=[wire, wire + 4]) ###################################################################### @@ -212,17 +212,17 @@ def prep_entangle(): # the system’s evolution could be a “black box” we can query, or something # given to us analytically. In general, we can approximate time evolution # with -# :class:`qml.ApproxTimeEvolution `. +# :class:`qp.ApproxTimeEvolution `. # However, since our Hamiltonians consist of terms that *commute*, we will # be able to evolve exactly using -# :class:`qml.CommutingEvolution `. +# :class:`qp.CommutingEvolution `. # We will reiterate this below. # That's it for part (a)! # Use Choi-Jamiołkowski isomorphism def choi_state(hamiltonian, time): prep_entangle() - qml.CommutingEvolution(hamiltonian, time) + qp.CommutingEvolution(hamiltonian, time) ###################################################################### # Controlled symmetries @@ -286,7 +286,7 @@ def choi_state(hamiltonian, time): # :math:`\vert+\rangle_G` state at the end, we undo these Hadamards and # try to measure “:math:`00`”. Finally, it’s straightforward to implement # the controlled gate :math:`CU` using controlled -# operations (namely :class:`qml.ControlledQubitUnitary`) +# operations (namely :class:`qp.ControlledQubitUnitary`) # on each qubit: # # .. figure:: ../_static/demonstration_assets/testing_symmetry/cu.png @@ -297,30 +297,30 @@ def choi_state(hamiltonian, time): # Create group register and device aux = range(8, 10) -dev = qml.device("lightning.qubit", wires=10) +dev = qp.device("lightning.qubit", wires=10) # Create plus state def prep_plus(): - qml.Hadamard(wires=aux[0]) - qml.Hadamard(wires=aux[1]) + qp.Hadamard(wires=aux[0]) + qp.Hadamard(wires=aux[1]) # Implement controlled symmetry operations on system def CU_sys(): - qml.ControlledQubitUnitary(c_mat @ c_mat, wires=[aux[0]] + list(system)) - qml.ControlledQubitUnitary(c_mat, wires=[aux[1]] + list(system)) + qp.ControlledQubitUnitary(c_mat @ c_mat, wires=[aux[0]] + list(system)) + qp.ControlledQubitUnitary(c_mat, wires=[aux[1]] + list(system)) # Implement controlled symmetry operations on copy def CU_cpy(): - qml.ControlledQubitUnitary(c_mat @ c_mat, wires=[aux[0]] + list(copy)) - qml.ControlledQubitUnitary(c_mat, wires=[aux[1]] + list(copy)) + qp.ControlledQubitUnitary(c_mat @ c_mat, wires=[aux[0]] + list(copy)) + qp.ControlledQubitUnitary(c_mat, wires=[aux[1]] + list(copy)) ###################################################################### # Let’s combine everything and actually run our circuit! # # Circuit for average symmetry -@qml.qnode(dev, interface="autograd") +@qp.qnode(dev, interface="autograd") def avg_symm(hamiltonian, time): # Use Choi-Jamiołkowski isomorphism @@ -334,7 +334,7 @@ def avg_symm(hamiltonian, time): # Ready register for measurement prep_plus() - return qml.probs(wires=aux) + return qp.probs(wires=aux) print("For Hamiltonian Hsymm, the |+> state is observed with probability", avg_symm(Hsymm, 1)[0], ".") diff --git a/demonstrations_v2/tutorial_testing_symmetry/metadata.json b/demonstrations_v2/tutorial_testing_symmetry/metadata.json index 688ed12a2a..f0e3508bc4 100644 --- a/demonstrations_v2/tutorial_testing_symmetry/metadata.json +++ b/demonstrations_v2/tutorial_testing_symmetry/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-01-24T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Algorithms", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_tn_circuits/demo.py b/demonstrations_v2/tutorial_tn_circuits/demo.py index 77bad8c5f1..54329612b3 100644 --- a/demonstrations_v2/tutorial_tn_circuits/demo.py +++ b/demonstrations_v2/tutorial_tn_circuits/demo.py @@ -115,14 +115,14 @@ """ import numpy as onp -import pennylane as qml +import pennylane as qp from pennylane import numpy as np def block(weights, wires): - qml.RX(weights[0], wires=wires[0]) - qml.RY(weights[1], wires=wires[1]) - qml.CNOT(wires=wires) + qp.RX(weights[0], wires=wires[0]) + qp.RY(weights[1], wires=wires[1]) + qp.CNOT(wires=wires) ############################################################################## @@ -131,25 +131,25 @@ def block(weights, wires): # shape of an MPS tensor network and computes the expectation value of a Pauli Z # operator on the bottom qubit. -dev = qml.device("default.qubit", wires=4) +dev = qp.device("default.qubit", wires=4) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(template_weights): - qml.MPS( + qp.MPS( wires=range(4), n_block_wires=2, block=block, n_params_block=2, template_weights=template_weights, ) - return qml.expval(qml.PauliZ(wires=3)) + return qp.expval(qp.PauliZ(wires=3)) np.random.seed(1) weights = np.random.random(size=[3, 2]) -qml.drawer.use_style("black_white") -fig, ax = qml.draw_mpl(circuit, level="device")(weights) +qp.drawer.use_style("black_white") +fig, ax = qp.draw_mpl(circuit, level="device")(weights) fig.set_size_inches((6, 3)) ############################################################################## @@ -159,26 +159,26 @@ def circuit(template_weights): def deep_block(weights, wires): - qml.StronglyEntanglingLayers(weights, wires) + qp.StronglyEntanglingLayers(weights, wires) ############################################################################## # We can use the :class:`~pennylane.MPS` template again and simply set # ``n_params_block = 3`` to suit the new block. -dev = qml.device("default.qubit", wires=4) +dev = qp.device("default.qubit", wires=4) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(template_weights): - qml.MPS( + qp.MPS( wires=range(4), n_block_wires=2, block=deep_block, n_params_block=3, template_weights=template_weights, ) - return qml.expval(qml.PauliZ(wires=3)) + return qp.expval(qp.PauliZ(wires=3)) ############################################################################## @@ -193,9 +193,9 @@ def circuit(template_weights): # Both this circuit and the previous circuit # can be represented by an MPS with a bond dimension of two. -shape = qml.StronglyEntanglingLayers.shape(n_layers=2, n_wires=2) +shape = qp.StronglyEntanglingLayers.shape(n_layers=2, n_wires=2) template_weights = [np.random.random(size=shape)] * 3 -fig, ax = qml.draw_mpl(circuit, level="device")(template_weights) +fig, ax = qp.draw_mpl(circuit, level="device")(template_weights) ############################################################################## # In addition to deep blocks, we can easily expand to wider blocks with more @@ -204,7 +204,7 @@ def circuit(template_weights): def wide_block(weights, wires): - qml.SimplifiedTwoDesign(initial_layer_weights=weights[0], weights=weights[1], wires=wires) + qp.SimplifiedTwoDesign(initial_layer_weights=weights[0], weights=weights[1], wires=wires) ############################################################################### @@ -215,25 +215,25 @@ def wide_block(weights, wires): # appear near the beginning of the circuit. Furthermore, this circuit has a higher bond # dimension than the previous ones and would correspond to an MPS with a bond dimension of four. -dev = qml.device("default.qubit", wires=8) +dev = qp.device("default.qubit", wires=8) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(template_weights): - qml.MPS( + qp.MPS( wires=range(8), n_block_wires=4, block=wide_block, n_params_block=2, template_weights=template_weights, ) - return qml.expval(qml.PauliZ(wires=7)) + return qp.expval(qp.PauliZ(wires=7)) -shapes = qml.SimplifiedTwoDesign.shape(n_layers=1, n_wires=4) +shapes = qp.SimplifiedTwoDesign.shape(n_layers=1, n_wires=4) weights = [onp.random.random(size=shape) for shape in shapes] template_weights = onp.array([weights] * 3, dtype="object") -fig, ax = qml.draw_mpl(circuit, level="device")(template_weights) +fig, ax = qp.draw_mpl(circuit, level="device")(template_weights) ############################################################################## # We can also broadcast a block to the tree tensor network architecture by using the @@ -241,28 +241,28 @@ def circuit(template_weights): def block(weights, wires): - qml.RX(weights[0], wires=wires[0]) - qml.RX(weights[1], wires=wires[1]) - qml.CNOT(wires=wires) + qp.RX(weights[0], wires=wires[0]) + qp.RX(weights[1], wires=wires[1]) + qp.CNOT(wires=wires) -dev = qml.device("default.qubit", wires=8) +dev = qp.device("default.qubit", wires=8) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(template_weights): - qml.TTN( + qp.TTN( wires=range(8), n_block_wires=2, block=block, n_params_block=2, template_weights=template_weights, ) - return qml.expval(qml.PauliZ(wires=7)) + return qp.expval(qp.PauliZ(wires=7)) weights = np.random.random(size=[7, 2]) -fig, ax = qml.draw_mpl(circuit, level="device")(weights) +fig, ax = qp.draw_mpl(circuit, level="device")(weights) fig.set_size_inches((4, 4)) ############################################################################## # Classifying the bars and stripes data set @@ -309,9 +309,9 @@ def circuit(template_weights): def block(weights, wires): - qml.RY(weights[0], wires=wires[0]) - qml.RY(weights[1], wires=wires[1]) - qml.CNOT(wires=wires) + qp.RY(weights[0], wires=wires[0]) + qp.RY(weights[1], wires=wires[1]) + qp.CNOT(wires=wires) ############################################################################## @@ -323,24 +323,24 @@ def block(weights, wires): # The circuit diagram below shows the full circuit. The :class:`~pennylane.BasisState` # encoding appears in the initial :class:`~pennylane.PauliX` gates. -dev = qml.device("default.qubit", wires=4) +dev = qp.device("default.qubit", wires=4) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(image, template_weights): - qml.BasisState(image, wires=range(4)) - qml.TTN( + qp.BasisState(image, wires=range(4)) + qp.TTN( wires=range(4), n_block_wires=2, block=block, n_params_block=2, template_weights=template_weights, ) - return qml.expval(qml.PauliZ(wires=3)) + return qp.expval(qp.PauliZ(wires=3)) weights = np.random.random(size=[3, 2]) -fig, ax = qml.draw_mpl(circuit, level="device")(BAS[0], weights) +fig, ax = qp.draw_mpl(circuit, level="device")(BAS[0], weights) fig.set_size_inches((6, 3.5)) ############################################################################## @@ -368,7 +368,7 @@ def costfunc(params): # the cost function. params = np.random.random(size=[3, 2], requires_grad=True) -optimizer = qml.GradientDescentOptimizer(stepsize=0.1) +optimizer = qp.GradientDescentOptimizer(stepsize=0.1) for k in range(100): if k % 20 == 0: @@ -380,7 +380,7 @@ def costfunc(params): # we can now show the full circuits and the resulting output for each image. for image in BAS: - fig, ax = qml.draw_mpl(circuit, level="device")(image, params) + fig, ax = qp.draw_mpl(circuit, level="device")(image, params) plt.figure(figsize=[1.8, 1.8]) plt.imshow(np.reshape(image, [2, 2]), cmap="gray") plt.title( diff --git a/demonstrations_v2/tutorial_tn_circuits/metadata.json b/demonstrations_v2/tutorial_tn_circuits/metadata.json index bfb7e23fd6..9a51a681b8 100644 --- a/demonstrations_v2/tutorial_tn_circuits/metadata.json +++ b/demonstrations_v2/tutorial_tn_circuits/metadata.json @@ -17,7 +17,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2022-03-29T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Machine Learning" ], diff --git a/demonstrations_v2/tutorial_toric_code/demo.py b/demonstrations_v2/tutorial_toric_code/demo.py index d338c4d8d2..debb31352e 100644 --- a/demonstrations_v2/tutorial_toric_code/demo.py +++ b/demonstrations_v2/tutorial_toric_code/demo.py @@ -112,7 +112,7 @@ On to some practical coding! First, let's define the sites on a :math:`4\times 6` lattice. """ -import pennylane as qml +import pennylane as qp import matplotlib.pyplot as plt from matplotlib.patches import Polygon, Patch from itertools import product @@ -170,7 +170,7 @@ class Wire: sites = [(x0, y), (x0 + 1, y), (x0 + 1, y + 1), (x0, y + 1)] - op = qml.prod(*(qml.PauliZ(mod(s)) for s in sites)) + op = qp.prod(*(qp.PauliZ(mod(s)) for s in sites)) zgroup_sites.append(sites) zgroup_ops.append(op) @@ -196,7 +196,7 @@ class Wire: if x == 2 and y == 1: # change order for state prep later sites = sites[1:] + sites[0:1] - op = qml.prod(*(qml.PauliX(mod(s)) for s in sites)) + op = qp.prod(*(qp.PauliX(mod(s)) for s in sites)) xgroup_sites.append(sites) xgroup_ops.append(op) @@ -306,18 +306,18 @@ def misc_plot_formatting(fig, ax): # Now let’s actually put these together into a circuit! # -dev = qml.device("lightning.qubit", wires=[Wire(*s) for s in all_sites]) +dev = qp.device("lightning.qubit", wires=[Wire(*s) for s in all_sites]) def state_prep(): for op in xgroup_ops[0:-1]: - qml.Hadamard(op.wires[0]) + qp.Hadamard(op.wires[0]) for w in op.wires[1:]: - qml.CNOT(wires=[op.wires[0], w]) + qp.CNOT(wires=[op.wires[0], w]) -@qml.qnode(dev, diff_method=None) +@qp.qnode(dev, diff_method=None) def circuit(): state_prep() - return [qml.expval(op) for op in xgroup_ops + zgroup_ops] + return [qp.expval(op) for op in xgroup_ops + zgroup_ops] ###################################################################### @@ -413,17 +413,17 @@ def circuit(): # Let’s create a QNode where we can apply these perturbations: -@qml.qnode(dev, diff_method=None) +@qp.qnode(dev, diff_method=None) def excitations(x_sites, z_sites): state_prep() for s in x_sites: - qml.PauliX(Wire(*s)) + qp.PauliX(Wire(*s)) for s in z_sites: - qml.PauliZ(Wire(*s)) + qp.PauliZ(Wire(*s)) - return [qml.expval(op) for op in xgroup_ops + zgroup_ops] + return [qp.expval(op) for op in xgroup_ops + zgroup_ops] ###################################################################### @@ -686,17 +686,17 @@ def excitation_plot(x_excite, z_excite): # -@qml.qnode(dev, diff_method=None) +@qp.qnode(dev, diff_method=None) def probs(x_sites, z_sites): state_prep() for s in x_sites: - qml.PauliX(Wire(*s)) + qp.PauliX(Wire(*s)) for s in z_sites: - qml.PauliZ(Wire(*s)) + qp.PauliZ(Wire(*s)) - return qml.probs(wires=[Wire(*s) for s in all_sites]) + return qp.probs(wires=[Wire(*s) for s in all_sites]) null_probs = probs([], []) @@ -772,7 +772,7 @@ def probs(x_sites, z_sites): # if the probability distributions are different: # -print("Are the probabilities equal? ", qml.math.allclose(null_probs, horizontal_probs)) +print("Are the probabilities equal? ", qp.math.allclose(null_probs, horizontal_probs)) print("Is this significant?") print("Maximum difference in probabilities: ", max(abs(null_probs - horizontal_probs))) print("Maximum probability: ", max(null_probs)) @@ -918,28 +918,28 @@ def probs(x_sites, z_sites): # Below we implement this algorithm in PennyLane and measure the mutual exchange statistics # of an X Group excitation and a Z Group excitation. -dev_aux = qml.device("lightning.qubit", wires=[Wire(*s) for s in all_sites] + ["aux"]) +dev_aux = qp.device("lightning.qubit", wires=[Wire(*s) for s in all_sites] + ["aux"]) def loop(x_loop, z_loop): for s in x_loop: - qml.PauliX(Wire(*s)) + qp.PauliX(Wire(*s)) for s in z_loop: - qml.PauliZ(Wire(*s)) + qp.PauliZ(Wire(*s)) -@qml.qnode(dev_aux, diff_method=None) +@qp.qnode(dev_aux, diff_method=None) def hadamard_test(x_prep, z_prep, x_loop, z_loop): state_prep() for s in x_prep: - qml.PauliX(Wire(*s)) + qp.PauliX(Wire(*s)) for s in z_prep: - qml.PauliZ(Wire(*s)) + qp.PauliZ(Wire(*s)) - qml.Hadamard("aux") - qml.ctrl(loop, control="aux")(x_loop, z_loop) - qml.Hadamard("aux") - return qml.expval(qml.PauliZ("aux")) + qp.Hadamard("aux") + qp.ctrl(loop, control="aux")(x_loop, z_loop) + qp.Hadamard("aux") + return qp.expval(qp.PauliZ("aux")) x_around_z = hadamard_test(prep1, prep2, [], loop1) print("Move x excitation around z excitation: ", x_around_z) diff --git a/demonstrations_v2/tutorial_toric_code/metadata.json b/demonstrations_v2/tutorial_toric_code/metadata.json index 96780d5ac6..37c0ff4eb4 100644 --- a/demonstrations_v2/tutorial_toric_code/metadata.json +++ b/demonstrations_v2/tutorial_toric_code/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2022-08-08T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Algorithms", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_trapped_ions/demo.py b/demonstrations_v2/tutorial_trapped_ions/demo.py index 33b7cff188..0cc31b3739 100644 --- a/demonstrations_v2/tutorial_trapped_ions/demo.py +++ b/demonstrations_v2/tutorial_trapped_ions/demo.py @@ -397,7 +397,7 @@ # :math:`\exp(-i \hat{H} t/\hbar)` as a function of :math:`\varphi` and the # duration :math:`t` of the pulse, with :math:`\Omega` set to 100 kHz. -import pennylane as qml +import pennylane as qp import numpy as np from scipy.linalg import expm @@ -416,36 +416,36 @@ def evolution(phi, t): # produce common gates. For example, there is a combination of pulses # with different phases and durations that yield the Hadamard gate: -dev = qml.device("default.qubit", wires=1) +dev = qp.device("default.qubit", wires=1) -@qml.qnode(dev) +@qp.qnode(dev) def ion_hadamard(state): if state == 1: - qml.PauliX(wires=0) + qp.PauliX(wires=0) """We use a series of seemingly arbitrary pulses that will give the Hadamard gate. Why this is the case will become clear later""" - qml.QubitUnitary(evolution(0, -np.pi / 2 / Omega), wires=0) - qml.QubitUnitary(evolution(np.pi / 2, np.pi / 2 / Omega), wires=0) - qml.QubitUnitary(evolution(0, np.pi / 2 / Omega), wires=0) - qml.QubitUnitary(evolution(np.pi / 2, np.pi / 2 / Omega), wires=0) - qml.QubitUnitary(evolution(0, np.pi / 2 / Omega), wires=0) + qp.QubitUnitary(evolution(0, -np.pi / 2 / Omega), wires=0) + qp.QubitUnitary(evolution(np.pi / 2, np.pi / 2 / Omega), wires=0) + qp.QubitUnitary(evolution(0, np.pi / 2 / Omega), wires=0) + qp.QubitUnitary(evolution(np.pi / 2, np.pi / 2 / Omega), wires=0) + qp.QubitUnitary(evolution(0, np.pi / 2 / Omega), wires=0) - return qml.state() + return qp.state() #For comparison, we use the Hadamard built into PennyLane -@qml.qnode(dev) +@qp.qnode(dev) def hadamard(state): if state == 1: - qml.PauliX(wires=0) + qp.PauliX(wires=0) - qml.Hadamard(wires=0) + qp.Hadamard(wires=0) - return qml.state() + return qp.state() #We confirm that the values given by both functions are the same up to numerical error print(np.isclose(1j * ion_hadamard(0), hadamard(0))) @@ -456,28 +456,28 @@ def hadamard(state): # A similar exercise can be done for the :math:`T` gate: -@qml.qnode(dev) +@qp.qnode(dev) def ion_Tgate(state): if state == 1: - qml.PauliX(wires=0) + qp.PauliX(wires=0) - qml.QubitUnitary(evolution(0, -np.pi / 2 / Omega), wires=0) - qml.QubitUnitary(evolution(np.pi / 2, np.pi / 4 / Omega), wires=0) - qml.QubitUnitary(evolution(0, np.pi / 2 / Omega), wires=0) + qp.QubitUnitary(evolution(0, -np.pi / 2 / Omega), wires=0) + qp.QubitUnitary(evolution(np.pi / 2, np.pi / 4 / Omega), wires=0) + qp.QubitUnitary(evolution(0, np.pi / 2 / Omega), wires=0) - return qml.state() + return qp.state() -@qml.qnode(dev) +@qp.qnode(dev) def tgate(state): if state == 1: - qml.PauliX(wires=0) + qp.PauliX(wires=0) - qml.T(wires=0) + qp.T(wires=0) - return qml.state() + return qp.state() print(np.isclose(np.exp(1j * np.pi / 8) * ion_Tgate(0), tgate(0))) @@ -501,12 +501,12 @@ def tgate(state): import matplotlib.pyplot as plt -@qml.qnode(dev) +@qp.qnode(dev) def evolution_prob(t): - qml.QubitUnitary(evolution(0, t / Omega), wires=0) + qp.QubitUnitary(evolution(0, t / Omega), wires=0) - return qml.probs(wires=0) + return qp.probs(wires=0) t = np.linspace(0, 4 * np.pi, 101) @@ -806,32 +806,32 @@ def Molmer_Sorensen(t): # time :math:`t/\Omega_{MS}.` Let us verify that this is indeed the case # by building the circuit in PennyLane: -dev2 = qml.device("default.qubit",wires=2) +dev2 = qp.device("default.qubit",wires=2) -@qml.qnode(dev2) +@qp.qnode(dev2) def ion_cnot(basis_state): #Prepare the two-qubit basis states from the input - qml.BasisState(basis_state, wires=range(2)) + qp.BasisState(basis_state, wires=range(2)) #Implements the circuit shown above - qml.RY(np.pi/2, wires=0) - qml.QubitUnitary(Molmer_Sorensen(np.pi/2/Omega),wires=[0,1]) - qml.RX(-np.pi/2, wires=0) - qml.RX(-np.pi/2, wires=1) - qml.RY(-np.pi/2, wires=0) + qp.RY(np.pi/2, wires=0) + qp.QubitUnitary(Molmer_Sorensen(np.pi/2/Omega),wires=[0,1]) + qp.RX(-np.pi/2, wires=0) + qp.RX(-np.pi/2, wires=1) + qp.RY(-np.pi/2, wires=0) - return qml.state() + return qp.state() #Compare with built-in CNOT -@qml.qnode(dev2) +@qp.qnode(dev2) def cnot_gate(basis_state): - qml.BasisState(basis_state, wires=range(2)) + qp.BasisState(basis_state, wires=range(2)) - qml.CNOT(wires=[0,1]) + qp.CNOT(wires=[0,1]) - return qml.state() + return qp.state() #Check that they are the same up to numerical error and global phase print(np.isclose(np.exp(-1j*np.pi/4)*ion_cnot([0,0]),cnot_gate([0,0]))) diff --git a/demonstrations_v2/tutorial_trapped_ions/metadata.json b/demonstrations_v2/tutorial_trapped_ions/metadata.json index 14c4a77a2b..d9d5fe61f6 100644 --- a/demonstrations_v2/tutorial_trapped_ions/metadata.json +++ b/demonstrations_v2/tutorial_trapped_ions/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2021-11-10T00:00:00+00:00", - "dateOfLastModification": "2025-12-19T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Quantum Hardware", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_unitary_designs/demo.py b/demonstrations_v2/tutorial_unitary_designs/demo.py index 83180842e4..30ffe0c9da 100644 --- a/demonstrations_v2/tutorial_unitary_designs/demo.py +++ b/demonstrations_v2/tutorial_unitary_designs/demo.py @@ -431,7 +431,7 @@ def f(x, y, z): # operation first with experiments using a large but finite amount of Haar-random # unitaries, and then again with only the Clifford group. -import pennylane as qml +import pennylane as qp # Scipy allows us to sample Haar-random unitaries directly from scipy.stats import unitary_group @@ -440,7 +440,7 @@ def f(x, y, z): np.random.seed(42) # Use the mixed state simulator -dev = qml.device("default.mixed", wires=1) +dev = qp.device("default.mixed", wires=1) ###################################################################### # Let's set up a noisy quantum channel. To keep things simple, assume it @@ -449,8 +449,8 @@ def f(x, y, z): # quantum function for our ideal experiment: def ideal_experiment(): - qml.SX(wires=0) - return qml.state() + qp.SX(wires=0) + return qp.state() ###################################################################### # Next, we apply some noise. We do so by making use of a relatively new feature @@ -459,9 +459,9 @@ def ideal_experiment(): # operations. Suppose the noisy channel is composed of the following: def noisy_operations(damp_factor, depo_factor, flip_prob): - qml.AmplitudeDamping(damp_factor, wires=0) - qml.DepolarizingChannel(depo_factor, wires=0) - qml.BitFlip(flip_prob, wires=0) + qp.AmplitudeDamping(damp_factor, wires=0) + qp.DepolarizingChannel(depo_factor, wires=0) + qp.BitFlip(flip_prob, wires=0) ###################################################################### @@ -469,10 +469,10 @@ def noisy_operations(damp_factor, depo_factor, flip_prob): # *after* the original operations, but before the measurements. We use the # convenient :func:`~.pennylane.transform` decorator: -@qml.transform +@qp.transform def apply_noise(tape, damp_factor, depo_factor, flip_prob): # Capture the operations from the noisy sequence - noisy_tape = qml.tape.make_qscript(noisy_operations)(damp_factor, depo_factor, flip_prob) + noisy_tape = qp.tape.make_qscript(noisy_operations)(damp_factor, depo_factor, flip_prob) # Apply the original operations, then the noisy ones noisy_ops = tape.operations + noisy_tape.operations @@ -499,12 +499,12 @@ def null_postprocessing_fn(results): # before all the operations, and its inverse right before the measurements. We # can write another transform here to streamline this process: -@qml.transform +@qp.transform def conjugate_with_unitary(tape, matrix): new_ops = [ - qml.QubitUnitary(matrix, wires=0), + qp.QubitUnitary(matrix, wires=0), *tape.operations, - qml.QubitUnitary(matrix.conj().T, wires=0), + qp.QubitUnitary(matrix.conj().T, wires=0), ] def null_postprocessing_fn(results): @@ -541,8 +541,8 @@ def fidelity(rho, sigma): conjugated_noisy_experiment = conjugate_with_unitary(noisy_experiment, U) # Use the functions to create QNodes - ideal_qnode = qml.QNode(conjugated_ideal_experiment, dev) - noisy_qnode = qml.QNode(conjugated_noisy_experiment, dev) + ideal_qnode = qp.QNode(conjugated_ideal_experiment, dev) + noisy_qnode = qp.QNode(conjugated_noisy_experiment, dev) # Execute the QNodes ideal_state = ideal_qnode() @@ -562,19 +562,19 @@ def fidelity(rho, sigma): def apply_single_clifford(clifford_string, inverse=False): for gate in clifford_string: if gate == 'H': - qml.Hadamard(wires=0) + qp.Hadamard(wires=0) else: sign = -1 if inverse else 1 - qml.PhaseShift(sign * np.pi/2, wires=0) + qp.PhaseShift(sign * np.pi/2, wires=0) ###################################################################### # Next, we write a transform that applies a Clifford in the context of the full # experiment, i.e., apply the Clifford, then the operations, followed by the # inverse of the Clifford. -@qml.transform +@qp.transform def conjugate_with_clifford(tape, clifford_string): - make_single_clifford = qml.tape.make_qscript(apply_single_clifford) + make_single_clifford = qp.tape.make_qscript(apply_single_clifford) non_inv_tape = make_single_clifford(clifford_string, inverse=False) inv_tape = make_single_clifford(clifford_string, inverse=True) @@ -598,8 +598,8 @@ def null_postprocessing_fn(results): conjugated_ideal_experiment = conjugate_with_clifford(ideal_experiment, C) conjugated_noisy_experiment = conjugate_with_clifford(noisy_experiment, C) - ideal_qnode = qml.QNode(conjugated_ideal_experiment, dev) - noisy_qnode = qml.QNode(conjugated_noisy_experiment, dev) + ideal_qnode = qp.QNode(conjugated_ideal_experiment, dev) + noisy_qnode = qp.QNode(conjugated_noisy_experiment, dev) ideal_state = ideal_qnode() noisy_state = noisy_qnode() diff --git a/demonstrations_v2/tutorial_unitary_designs/metadata.json b/demonstrations_v2/tutorial_unitary_designs/metadata.json index f0e508788b..34c4e2b8ef 100644 --- a/demonstrations_v2/tutorial_unitary_designs/metadata.json +++ b/demonstrations_v2/tutorial_unitary_designs/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2021-09-07T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Machine Learning", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_unitary_synthesis_kak/demo.py b/demonstrations_v2/tutorial_unitary_synthesis_kak/demo.py index 2b7feefec6..5f24a52c0b 100644 --- a/demonstrations_v2/tutorial_unitary_synthesis_kak/demo.py +++ b/demonstrations_v2/tutorial_unitary_synthesis_kak/demo.py @@ -193,10 +193,10 @@ We may check that this works with the following code. We apply ``cossin`` to some input ``U``, from which we create the block matrices :math:`K_1` and :math:`K_2` with ``numpy`` and the Cartan subgroup matrix :math:`A` via a Select-applied, -or multiplexed, ``qml.RY`` rotation. Then we check that those matrices multiplied together +or multiplexed, ``qp.RY`` rotation. Then we check that those matrices multiplied together yield the input ``U`` again. """ -import pennylane as qml +import pennylane as qp import numpy as np import matplotlib.pyplot as plt from scipy.linalg import cossin, eig, qr @@ -220,8 +220,8 @@ def aiii_decomposition(U): # Check that the decomposition is valid zero = np.zeros_like(u_1) K_1 = np.block([[u_1, zero], [zero, u_2]]) -ry_ops = [qml.RY(2 * th, 0) for th in theta] -A = qml.matrix(qml.Select(ry_ops, control=range(1, n)), wire_order=range(n)) +ry_ops = [qp.RY(2 * th, 0) for th in theta] +A = qp.matrix(qp.Select(ry_ops, control=range(1, n)), wire_order=range(n)) K_2 = np.block([[v_1, zero], [zero, v_2]]) reconstructed_U = K_1 @ A @ K_2 @@ -249,8 +249,8 @@ def aiii_decomposition_rotated(U): zero = np.zeros_like(u_1) K_1 = np.block([[u_1, zero], [zero, u_2]]) K_2 = np.block([[v_1, zero], [zero, v_2]]) - rotation = (qml.X(0) + qml.Y(0)) / np.sqrt(2) - rotation_mat = qml.matrix(rotation, wire_order=range(n)) + rotation = (qp.X(0) + qp.Y(0)) / np.sqrt(2) + rotation_mat = qp.matrix(rotation, wire_order=range(n)) # Transform K_1 and K_2. No need to transform theta, just re-interpret as RX angles K_1 = K_1 @ rotation_mat K_2 = rotation_mat @ K_2 @@ -273,8 +273,8 @@ def aiii_decomposition_rotated(U): # The decomposition is still valid: -rx_ops = [qml.RX(2 * th, 0) for th in theta] -new_A = qml.matrix(qml.Select(rx_ops, control=range(1, n)), wire_order=range(n)) +rx_ops = [qp.RX(2 * th, 0) for th in theta] +new_A = qp.matrix(qp.Select(rx_ops, control=range(1, n)), wire_order=range(n)) reconstructed_U = new_K_1 @ new_A @ new_K_2 print(np.allclose(reconstructed_U, U)) @@ -379,8 +379,8 @@ def demultiplex(U, V): # The demultiplexed matrices make up :math:`K_1=u_1\oplus u_2` from above: # -rz_ops = [qml.RZ(-2 * p, 0) for p in phi] -demultiplex_A = qml.matrix(qml.Select(rz_ops, control=range(1, n)), wire_order=range(n)) +rz_ops = [qp.RZ(-2 * p, 0) for p in phi] +demultiplex_A = qp.matrix(qp.Select(rz_ops, control=range(1, n)), wire_order=range(n)) demultiplex_K_1 = np.block([[U_1, zero], [zero, U_1]]) demultiplex_K_2 = np.block([[U_2, zero], [zero, U_2]]) reconstructed_K_1 = demultiplex_K_1 @ demultiplex_A @ demultiplex_K_2 diff --git a/demonstrations_v2/tutorial_unitary_synthesis_kak/metadata.json b/demonstrations_v2/tutorial_unitary_synthesis_kak/metadata.json index 577c5dc4e5..eb95f5e2e0 100644 --- a/demonstrations_v2/tutorial_unitary_synthesis_kak/metadata.json +++ b/demonstrations_v2/tutorial_unitary_synthesis_kak/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2025-05-30T09:00:00+00:00", - "dateOfLastModification": "2025-12-10T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Compilation", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_univariate_qvr/demo.py b/demonstrations_v2/tutorial_univariate_qvr/demo.py index cb4a682061..a794d4e11c 100644 --- a/demonstrations_v2/tutorial_univariate_qvr/demo.py +++ b/demonstrations_v2/tutorial_univariate_qvr/demo.py @@ -434,7 +434,7 @@ def get_training_cycler(Xtr: torch.Tensor, batch_size: int, seed: int = GLOBAL_S # appendix of [#Cîrstoiu2020]_), we create the electron: # -import pennylane as qml +import pennylane as qp from itertools import combinations @@ -451,18 +451,18 @@ def D(gamma: torch.Tensor, n_qubits: int, k: int = None, get_probs: bool = False for i in range(1, k + 1): for comb in combinations(range(n_qubits), i): if len(comb) == 1: - qml.RZ(gamma[cnt], wires=[comb[0]]) + qp.RZ(gamma[cnt], wires=[comb[0]]) cnt += 1 elif len(comb) > 1: cnots = [comb[i : i + 2] for i in range(len(comb) - 1)] for j in cnots: - qml.CNOT(wires=j) - qml.RZ(gamma[cnt], wires=[comb[-1]]) + qp.CNOT(wires=j) + qp.RZ(gamma[cnt], wires=[comb[-1]]) cnt += 1 for j in cnots[::-1]: - qml.CNOT(wires=j) + qp.CNOT(wires=j) if get_probs: - return qml.probs(wires=range(n_qubits)) + return qp.probs(wires=range(n_qubits)) ###################################################################### @@ -470,9 +470,9 @@ def D(gamma: torch.Tensor, n_qubits: int, k: int = None, get_probs: bool = False # qubit in this tutorial, the resulting circuit is merely a single :math:`R_z(\theta)` gate. n_qubits = 1 -dev = qml.device("default.qubit", wires=n_qubits) -D_one_qubit = qml.qnode(dev)(D) -_ = qml.draw_mpl(D_one_qubit, decimals=2)(torch.tensor([1, 0]), 1, 1, True) +dev = qp.device("default.qubit", wires=n_qubits) +D_one_qubit = qp.qnode(dev)(D) +_ = qp.draw_mpl(D_one_qubit, decimals=2)(torch.tensor([1, 0]), 1, 1, True) ###################################################################### # You may find the general function for :math:`D`` useful in case you want to experiment @@ -486,7 +486,7 @@ def D(gamma: torch.Tensor, n_qubits: int, k: int = None, get_probs: bool = False @ct.electron -@qml.qnode(dev, interface="torch", diff_method="backprop") +@qp.qnode(dev, interface="torch", diff_method="backprop") def get_probs( xt: torch.Tensor, t: float, @@ -505,8 +505,8 @@ def get_probs( U(xt, wires=range(n_qubits)) W(alpha, wires=range(n_qubits)) D(gamma * t, n_qubits, k) - qml.adjoint(W)(alpha, wires=range(n_qubits)) - return qml.probs(range(n_qubits)) + qp.adjoint(W)(alpha, wires=range(n_qubits)) + return qp.probs(range(n_qubits)) ###################################################################### @@ -776,8 +776,8 @@ def training_workflow( # general_options = { - "U": qml.AngleEmbedding, - "W": qml.StronglyEntanglingLayers, + "U": qp.AngleEmbedding, + "W": qp.StronglyEntanglingLayers, "D": D, "n_qubits": 1, "probs_func": get_probs, diff --git a/demonstrations_v2/tutorial_univariate_qvr/metadata.json b/demonstrations_v2/tutorial_univariate_qvr/metadata.json index c35abd766a..0abe4181ee 100644 --- a/demonstrations_v2/tutorial_univariate_qvr/metadata.json +++ b/demonstrations_v2/tutorial_univariate_qvr/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-02-07T00:00:00+00:00", - "dateOfLastModification": "2025-11-28T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Quantum Machine Learning" ], diff --git a/demonstrations_v2/tutorial_variational_classifier/demo.py b/demonstrations_v2/tutorial_variational_classifier/demo.py index 4e1198574f..53aa324da5 100644 --- a/demonstrations_v2/tutorial_variational_classifier/demo.py +++ b/demonstrations_v2/tutorial_variational_classifier/demo.py @@ -53,7 +53,7 @@ # We start by importing PennyLane, the PennyLane-provided version of NumPy, # and an optimizer. -import pennylane as qml +import pennylane as qp from pennylane import numpy as np from pennylane.optimize import NesterovMomentumOptimizer @@ -63,7 +63,7 @@ # # We then create a quantum device that will run our circuits. -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") ############################################################################## # Variational classifiers usually define a “layer” or “block”, which is an @@ -78,10 +78,10 @@ def layer(layer_weights): for wire in range(4): - qml.Rot(*layer_weights[wire], wires=wire) + qp.Rot(*layer_weights[wire], wires=wire) for wires in ([0, 1], [1, 2], [2, 3], [3, 0]): - qml.CNOT(wires) + qp.CNOT(wires) ############################################################################## @@ -99,7 +99,7 @@ def layer(layer_weights): def state_preparation(x): - qml.BasisState(x, wires=[0, 1, 2, 3]) + qp.BasisState(x, wires=[0, 1, 2, 3]) ############################################################################## @@ -107,14 +107,14 @@ def state_preparation(x): # by a repetition of the layer structure. -@qml.qnode(dev) +@qp.qnode(dev) def circuit(weights, x): state_preparation(x) for layer_weights in weights: layer(layer_weights) - return qml.expval(qml.PauliZ(0)) + return qp.expval(qp.PauliZ(0)) ############################################################################## @@ -136,8 +136,8 @@ def variational_classifier(weights, bias, x): def square_loss(labels, predictions): - # We use a call to qml.math.stack to allow subtracting the arrays directly - return np.mean((labels - qml.math.stack(predictions)) ** 2) + # We use a call to qp.math.stack to allow subtracting the arrays directly + return np.mean((labels - qp.math.stack(predictions)) ** 2) ############################################################################## @@ -301,19 +301,19 @@ def get_angles(x): def state_preparation(a): - qml.RY(a[0], wires=0) + qp.RY(a[0], wires=0) - qml.CNOT(wires=[0, 1]) - qml.RY(a[1], wires=1) - qml.CNOT(wires=[0, 1]) - qml.RY(a[2], wires=1) + qp.CNOT(wires=[0, 1]) + qp.RY(a[1], wires=1) + qp.CNOT(wires=[0, 1]) + qp.RY(a[2], wires=1) - qml.PauliX(wires=0) - qml.CNOT(wires=[0, 1]) - qml.RY(a[3], wires=1) - qml.CNOT(wires=[0, 1]) - qml.RY(a[4], wires=1) - qml.PauliX(wires=0) + qp.PauliX(wires=0) + qp.CNOT(wires=[0, 1]) + qp.RY(a[3], wires=1) + qp.CNOT(wires=[0, 1]) + qp.RY(a[4], wires=1) + qp.PauliX(wires=0) ############################################################################## @@ -323,11 +323,11 @@ def state_preparation(a): ang = get_angles(x) -@qml.qnode(dev) +@qp.qnode(dev) def test(angles): state_preparation(angles) - return qml.state() + return qp.state() state = test(ang) @@ -344,7 +344,7 @@ def test(angles): # # The ``default.qubit`` simulator provides a shortcut to # ``state_preparation`` with the command -# ``qml.StatePrep(x, wires=[0, 1])``. On state simulators, this just +# ``qp.StatePrep(x, wires=[0, 1])``. On state simulators, this just # replaces the quantum state with our (normalized) input. On hardware, the operation implements # more sophisticated versions of the routine used above. @@ -358,8 +358,8 @@ def test(angles): def layer(layer_weights): for wire in range(2): - qml.Rot(*layer_weights[wire], wires=wire) - qml.CNOT(wires=[0, 1]) + qp.Rot(*layer_weights[wire], wires=wire) + qp.CNOT(wires=[0, 1]) def cost(weights, bias, X, Y): diff --git a/demonstrations_v2/tutorial_variational_classifier/metadata.json b/demonstrations_v2/tutorial_variational_classifier/metadata.json index 94296eb863..bb5d75ea99 100644 --- a/demonstrations_v2/tutorial_variational_classifier/metadata.json +++ b/demonstrations_v2/tutorial_variational_classifier/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2019-10-11T00:00:00+00:00", - "dateOfLastModification": "2025-10-03T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Machine Learning", "Getting Started" diff --git a/demonstrations_v2/tutorial_vqe/demo.py b/demonstrations_v2/tutorial_vqe/demo.py index 65785f0561..98ebe87707 100644 --- a/demonstrations_v2/tutorial_vqe/demo.py +++ b/demonstrations_v2/tutorial_vqe/demo.py @@ -52,9 +52,9 @@ jax.config.update("jax_platform_name", "cpu") jax.config.update('jax_enable_x64', True) -import pennylane as qml +import pennylane as qp -dataset = qml.data.load('qchem', molname="H2")[0] +dataset = qp.data.load('qchem', molname="H2")[0] H, qubits = dataset.hamiltonian, len(dataset.hamiltonian.wires) print("Number of qubits = ", qubits) print("The Hamiltonian is ", H) @@ -85,8 +85,8 @@ # # symbols = ["H", "H"] # coordinates = np.array([[-0.70108983, 0.0, 0.0], [0.70108983, 0.0, 0.0]]) -# molecule = qml.qchem.Molecule(symbols, coordinates) -# H, qubits = qml.qchem.molecular_hamiltonian(molecule) +# molecule = qp.qchem.Molecule(symbols, coordinates) +# H, qubits = qp.qchem.molecular_hamiltonian(molecule) # # Implementing the VQE algorithm # ------------------------------ @@ -94,7 +94,7 @@ # algorithms and optimizers. We begin by defining the device, in this case PennyLane’s # standard qubit simulator: -dev = qml.device("lightning.qubit", wires=qubits) +dev = qp.device("lightning.qubit", wires=qubits) ############################################################################## # Next, we need to define the quantum circuit that prepares the trial state of the @@ -134,7 +134,7 @@ # :func:`~.pennylane.qchem.hf_state` function to generate the vector representing the Hartree-Fock state. electrons = 2 -hf = qml.qchem.hf_state(electrons, qubits) +hf = qp.qchem.hf_state(electrons, qubits) print(hf) ############################################################################## @@ -145,11 +145,11 @@ # We do this using the :func:`~.pennylane.expval` function. The decorator syntax allows us to # run the cost function as an executable QNode with the gate parameter :math:`\theta:` -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def circuit(param, wires): - qml.BasisState(hf, wires=wires) - qml.DoubleExcitation(param, wires=[0, 1, 2, 3]) - return qml.expval(H) + qp.BasisState(hf, wires=wires) + qp.DoubleExcitation(param, wires=[0, 1, 2, 3]) + return qp.expval(H) ############################################################################## diff --git a/demonstrations_v2/tutorial_vqe/metadata.json b/demonstrations_v2/tutorial_vqe/metadata.json index 72bbf9d642..4f7c18dc79 100644 --- a/demonstrations_v2/tutorial_vqe/metadata.json +++ b/demonstrations_v2/tutorial_vqe/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2020-02-08T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Chemistry", "Getting Started" diff --git a/demonstrations_v2/tutorial_vqe_qng/demo.py b/demonstrations_v2/tutorial_vqe_qng/demo.py index d235c5fbc9..03301d663d 100644 --- a/demonstrations_v2/tutorial_vqe_qng/demo.py +++ b/demonstrations_v2/tutorial_vqe_qng/demo.py @@ -32,14 +32,14 @@ import matplotlib.pyplot as plt from pennylane import numpy as np -import pennylane as qml +import pennylane as qp ############################################################################## # For this simple example, we consider the following single-qubit Hamiltonian: :math:`\sigma_x + \sigma_z.` # # We define the device: -dev = qml.device("default.qubit", wires=1) +dev = qp.device("default.qubit", wires=1) ############################################################################## @@ -48,8 +48,8 @@ def circuit(params, wires=0): - qml.RX(params[0], wires=wires) - qml.RY(params[1], wires=wires) + qp.RX(params[0], wires=wires) + qp.RY(params[1], wires=wires) ############################################################################## @@ -58,14 +58,14 @@ def circuit(params, wires=0): # crucial component for optimizing with quantum natural gradients. coeffs = [1, 1] -obs = [qml.PauliX(0), qml.PauliZ(0)] +obs = [qp.PauliX(0), qp.PauliZ(0)] -H = qml.Hamiltonian(coeffs, obs) +H = qp.Hamiltonian(coeffs, obs) -@qml.qnode(dev, interface="autograd") +@qp.qnode(dev, interface="autograd") def cost_fn(params): circuit(params) - return qml.expval(H) + return qp.expval(H) ############################################################################## # To analyze the performance of quantum natural gradient on VQE calculations, @@ -90,7 +90,7 @@ def cost_fn(params): ############################################################################## # First, we carry out the VQE optimization using the standard gradient descent method. -opt = qml.GradientDescentOptimizer(stepsize=step_size) +opt = qp.GradientDescentOptimizer(stepsize=step_size) params = init_params @@ -125,7 +125,7 @@ def cost_fn(params): ############################################################################## # We then repeat the process for the optimizer employing quantum natural gradients: -opt = qml.QNGOptimizer(stepsize=step_size, approx="block-diag") +opt = qp.QNGOptimizer(stepsize=step_size, approx="block-diag") params = init_params @@ -259,7 +259,7 @@ def cost_fn(params): # # To construct our system Hamiltonian, we can use `PennyLane Datasets `__ to obtain the dataset for a :math:`\text{H}_2` molecule. -dataset = qml.data.load('qchem',molname="H2", bondlength=0.7)[0] +dataset = qp.data.load('qchem',molname="H2", bondlength=0.7)[0] hamiltonian, qubits = dataset.hamiltonian, len(dataset.hamiltonian.wires) hamiltonian_coeffs, hamiltonian_ops = hamiltonian.terms() @@ -272,18 +272,18 @@ def cost_fn(params): # but expand out the arbitrary single-qubit rotations to elementary # gates (RZ-RY-RZ). -dev = qml.device("default.qubit", wires=qubits) +dev = qp.device("default.qubit", wires=qubits) hf_state = np.array([1, 1, 0, 0], requires_grad=False) def ansatz(params, wires=[0, 1, 2, 3]): - qml.BasisState(hf_state, wires=wires) + qp.BasisState(hf_state, wires=wires) for i in wires: - qml.RZ(params[3 * i], wires=i) - qml.RY(params[3 * i + 1], wires=i) - qml.RZ(params[3 * i + 2], wires=i) - qml.CNOT(wires=[2, 3]) - qml.CNOT(wires=[2, 0]) - qml.CNOT(wires=[3, 1]) + qp.RZ(params[3 * i], wires=i) + qp.RY(params[3 * i + 1], wires=i) + qp.RZ(params[3 * i + 2], wires=i) + qp.CNOT(wires=[2, 3]) + qp.CNOT(wires=[2, 0]) + qp.CNOT(wires=[3, 1]) ############################################################################## @@ -291,10 +291,10 @@ def ansatz(params, wires=[0, 1, 2, 3]): # the Hartree-Fock state of the hydrogen molecule described in the minimal basis. # Again, we define the cost function to be the following QNode that measures ``expval(H)``: -@qml.qnode(dev, interface="autograd") +@qp.qnode(dev, interface="autograd") def cost(params): ansatz(params) - return qml.expval(hamiltonian) + return qp.expval(hamiltonian) ############################################################################## # For this problem, we can compute the exact value of the @@ -316,7 +316,7 @@ def cost(params): # As was done with our previous VQE example, we run the standard gradient descent # optimizer. -opt = qml.GradientDescentOptimizer(step_size) +opt = qp.GradientDescentOptimizer(step_size) params = init_params @@ -355,9 +355,9 @@ def cost(params): # Next, we run the optimizer employing quantum natural gradients. We also need to make the # Hamiltonian coefficients non-differentiable by setting ``requires_grad=False``. -hamiltonian = qml.Hamiltonian(np.array(hamiltonian_coeffs, requires_grad=False), hamiltonian_ops) +hamiltonian = qp.Hamiltonian(np.array(hamiltonian_coeffs, requires_grad=False), hamiltonian_ops) -opt = qml.QNGOptimizer(step_size, lam=0.001, approx="block-diag") +opt = qp.QNGOptimizer(step_size, lam=0.001, approx="block-diag") params = init_params prev_energy = cost(params) diff --git a/demonstrations_v2/tutorial_vqe_qng/metadata.json b/demonstrations_v2/tutorial_vqe_qng/metadata.json index 5a27a98566..a941085608 100644 --- a/demonstrations_v2/tutorial_vqe_qng/metadata.json +++ b/demonstrations_v2/tutorial_vqe_qng/metadata.json @@ -14,7 +14,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2020-11-06T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_vqe_spin_sectors/demo.py b/demonstrations_v2/tutorial_vqe_spin_sectors/demo.py index 0e24022bb4..2ace64f88f 100644 --- a/demonstrations_v2/tutorial_vqe_spin_sectors/demo.py +++ b/demonstrations_v2/tutorial_vqe_spin_sectors/demo.py @@ -62,9 +62,9 @@ # the qubit Hamiltonian of the molecule is built using the # :func:`~.pennylane.qchem.molecular_hamiltonian` function. -import pennylane as qml +import pennylane as qp -H, qubits = qml.qchem.molecular_hamiltonian(symbols, coordinates) +H, qubits = qp.qchem.molecular_hamiltonian(symbols, coordinates) print("Number of qubits = ", qubits) print("The Hamiltonian is ", H) @@ -99,7 +99,7 @@ # :math:`\hat{S}^2` observable. electrons = 2 -S2 = qml.qchem.spin2(electrons, qubits) +S2 = qp.qchem.spin2(electrons, qubits) print(S2) ############################################################################## @@ -118,7 +118,7 @@ # function to generate the vector representing the Hartree-Fock state # :math:`\vert 1100 \rangle` of the :math:`\mathrm{H}_2` molecule. -hf = qml.qchem.hf_state(electrons, qubits) +hf = qp.qchem.hf_state(electrons, qubits) print(hf) ############################################################################## @@ -139,7 +139,7 @@ # Therefore, for the ground state of the :math:`\mathrm{H}_2` molecule we choose # ``delta_sz = 0``. -singles, doubles = qml.qchem.excitations(electrons, qubits, delta_sz=0) +singles, doubles = qp.qchem.excitations(electrons, qubits, delta_sz=0) print(singles) print(doubles) @@ -154,7 +154,7 @@ def circuit(params, wires): - qml.AllSinglesDoubles(params, wires, hf, singles, doubles) + qp.AllSinglesDoubles(params, wires, hf, singles, doubles) ############################################################################## @@ -180,7 +180,7 @@ def circuit(params, wires): # Now we proceed to optimize the variational parameters. First, we define the device, # in this case a qubit simulator: -dev = qml.device("lightning.qubit", wires=qubits) +dev = qp.device("lightning.qubit", wires=qubits) ############################################################################## # Next, we define the cost function as the following QNode, where we make use of @@ -189,20 +189,20 @@ def circuit(params, wires): # a cost function that can be evaluated with the circuit parameters: -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def cost_fn(params): circuit(params, wires=range(qubits)) - return qml.expval(H) + return qp.expval(H) ############################################################################## # As a reminder, we also built the total spin operator :math:`\hat{S}^2` for which # we can now define a function to compute its expectation value: -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def S2_exp_value(params): circuit(params, wires=range(qubits)) - return qml.expval(S2) + return qp.expval(S2) ############################################################################## @@ -239,10 +239,10 @@ def total_spin(params): max_iterations = 100 prev_energy = 0.0 -@qml.qjit +@qp.qjit def update_step(i, params, opt_state): """Perform a single gradient update step""" - grads = qml.grad(cost_fn)(params) + grads = qp.grad(cost_fn)(params) updates, opt_state = opt.update(grads, opt_state) params = optax.apply_updates(params, updates) return (params, opt_state) @@ -271,7 +271,7 @@ def update_step(i, params, opt_state): # excitations whose total-spin projection differs by the quantity ``delta_sz=1`` # with respect to the Hartree-Fock state. -singles, doubles = qml.qchem.excitations(electrons, qubits, delta_sz=1) +singles, doubles = qp.qchem.excitations(electrons, qubits, delta_sz=1) print(singles) print(doubles) @@ -284,7 +284,7 @@ def update_step(i, params, opt_state): def circuit(params, wires): - qml.AllSinglesDoubles(params, wires, np.flip(hf), singles, doubles) + qp.AllSinglesDoubles(params, wires, np.flip(hf), singles, doubles) ############################################################################## @@ -306,16 +306,16 @@ def circuit(params, wires): # and the total spin operator for the new circuit. -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def cost_fn(params): circuit(params, wires=range(qubits)) - return qml.expval(H) + return qp.expval(H) -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def S2_exp_value(params): circuit(params, wires=range(qubits)) - return qml.expval(S2) + return qp.expval(S2) ############################################################################## @@ -328,10 +328,10 @@ def S2_exp_value(params): max_iterations = 100 -@qml.qjit +@qp.qjit def update_step(i, params, opt_state): """Perform a single gradient update step""" - grads = qml.grad(cost_fn)(params) + grads = qp.grad(cost_fn)(params) updates, opt_state = opt.update(grads, opt_state) params = optax.apply_updates(params, updates) return (params, opt_state) diff --git a/demonstrations_v2/tutorial_vqe_spin_sectors/metadata.json b/demonstrations_v2/tutorial_vqe_spin_sectors/metadata.json index c7c38851ea..de3f434cee 100644 --- a/demonstrations_v2/tutorial_vqe_spin_sectors/metadata.json +++ b/demonstrations_v2/tutorial_vqe_spin_sectors/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2020-10-13T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Chemistry" ], diff --git a/demonstrations_v2/tutorial_vqe_vqd/demo.py b/demonstrations_v2/tutorial_vqe_vqd/demo.py index a899af0c90..d26dcc9096 100644 --- a/demonstrations_v2/tutorial_vqe_vqd/demo.py +++ b/demonstrations_v2/tutorial_vqe_vqd/demo.py @@ -51,14 +51,14 @@ # The warnings do not impact the correctness of the results, but make it harder to view outputs. # -import pennylane as qml +import pennylane as qp import numpy as np import warnings warnings.filterwarnings(action="ignore", category=np.exceptions.ComplexWarning) # Load the dataset -h2 = qml.data.load("qchem", molname="H2", bondlength=0.742, basis="STO-3G")[0] +h2 = qp.data.load("qchem", molname="H2", bondlength=0.742, basis="STO-3G")[0] # Extract the Hamiltonian H, n_qubits = h2.hamiltonian, len(h2.hamiltonian.wires) @@ -66,23 +66,23 @@ # Obtain the ground state from the operations given by the dataset def generate_ground_state(wires): - qml.BasisState(np.array(h2.hf_state), wires=wires) + qp.BasisState(np.array(h2.hf_state), wires=wires) for op in h2.vqe_gates: # use the gates data from the dataset - op = qml.map_wires(op, {op.wires[i]: wires[i] for i in range(len(wires))}) - qml.apply(op) + op = qp.map_wires(op, {op.wires[i]: wires[i] for i in range(len(wires))}) + qp.apply(op) ###################################################################### # The ``generate_ground_state`` function prepares the ground state of the molecule using the data obtained from the dataset. # Let's use it to check the energy of that state: # -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") -@qml.qnode(dev) +@qp.qnode(dev) def circuit(): generate_ground_state(range(n_qubits)) - return qml.expval(H) + return qp.expval(H) print(f"Ground state energy: {circuit()}") @@ -100,16 +100,16 @@ def circuit(): from functools import partial # This line is added to better visualise the circuit -@partial(qml.transforms.decompose, max_expansion=1) +@partial(qp.transforms.decompose, max_expansion=1) def ansatz(theta, wires): - singles, doubles = qml.qchem.excitations(2, n_qubits) + singles, doubles = qp.qchem.excitations(2, n_qubits) singles = [[wires[i] for i in single] for single in singles] doubles = [[wires[i] for i in double] for double in doubles] - qml.AllSinglesDoubles(theta, wires, np.array([1,1,0,0]), singles, doubles) + qp.AllSinglesDoubles(theta, wires, np.array([1,1,0,0]), singles, doubles) theta = np.random.rand(3) # 3 parameters for the ansatz -print(qml.draw(ansatz, decimals = 2)(theta, range(4))) +print(qp.draw(ansatz, decimals = 2)(theta, range(4))) ###################################################################### # The ``ansatz`` function is the one that generates the state :math:`|\Psi(\theta)\rangle.` @@ -117,19 +117,19 @@ def ansatz(theta, wires): # known as `swap test `__. -@qml.qnode(dev) +@qp.qnode(dev) def swap_test(params): generate_ground_state(range(1, n_qubits + 1)) ansatz(params, range(n_qubits + 1, 2 * n_qubits + 1)) - qml.Barrier() # added to better visualise the circuit - qml.Hadamard(wires=0) + qp.Barrier() # added to better visualise the circuit + qp.Hadamard(wires=0) for i in range(n_qubits): - qml.CSWAP(wires=[0, 1 + i + n_qubits, 1 + i]) - qml.Hadamard(wires=0) - return qml.expval(qml.Z(0)) + qp.CSWAP(wires=[0, 1 + i + n_qubits, 1 + i]) + qp.Hadamard(wires=0) + return qp.expval(qp.Z(0)) -print(qml.draw(swap_test)(theta)) +print(qp.draw(swap_test)(theta)) print(f"\nOverlap between the ground state and the ansatz: {swap_test(theta)}") ###################################################################### @@ -138,10 +138,10 @@ def swap_test(params): # With this we have all the ingredients to define the loss function that we want to minimize: # -@qml.qnode(dev) +@qp.qnode(dev) def expected_value(theta): ansatz(theta, range(n_qubits)) - return qml.expval(H) + return qp.expval(H) def loss_f(theta, beta): return expected_value(theta) + beta * swap_test(theta) diff --git a/demonstrations_v2/tutorial_vqe_vqd/metadata.json b/demonstrations_v2/tutorial_vqe_vqd/metadata.json index 4b1bd2ad70..3ead91be51 100644 --- a/demonstrations_v2/tutorial_vqe_vqd/metadata.json +++ b/demonstrations_v2/tutorial_vqe_vqd/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-08-26T00:00:00+00:00", - "dateOfLastModification": "2026-01-14T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Chemistry", "How-to" From af43609f054ce7fdd22b5a5e9a1629e6edf19479 Mon Sep 17 00:00:00 2001 From: drdren <104710745+drdren@users.noreply.github.com> Date: Tue, 21 Apr 2026 14:28:39 -0400 Subject: [PATCH 08/10] qml to qp Batch 10 (#1761) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### Before submitting Please complete the following checklist when submitting a PR: - [ ] Ensure that your tutorial executes correctly, and conforms to the guidelines specified in the [README](https://github.com/PennyLaneAI/demos/blob/master/README.md). - [ ] Remember to do a grammar check of the content you include. - [ ] All tutorials conform to [PEP8 standards](https://www.python.org/dev/peps/pep-0008/). To auto format files, simply `pip install black`, and then run `black -l 100 path/to/file.py`. When all the above are checked, delete everything above the dashed line and fill in the pull request template. ------------------------------------------------------------------------------------------------------------ **Title:** **Summary:** **Relevant references:** **Possible Drawbacks:** **Related GitHub Issues:** ---- If you are writing a demonstration, please answer these questions to facilitate the marketing process. * GOALS — Why are we working on this now? *Eg. Promote a new PL feature or show a PL implementation of a recent paper.* * AUDIENCE — Who is this for? *Eg. Chemistry researchers, PL educators, beginners in quantum computing.* * KEYWORDS — What words should be included in the marketing post? * Which of the following types of documentation is most similar to your file? (more details [here](https://www.notion.so/xanaduai/Different-kinds-of-documentation-69200645fe59442991c71f9e7d8a77f8)) - [ ] Tutorial - [ ] Demo - [ ] How-to Co-authored-by: David --- demonstrations_v2/tutorial_vqls/demo.py | 38 ++-- demonstrations_v2/tutorial_vqls/metadata.json | 2 +- demonstrations_v2/tutorial_vqt/demo.py | 24 +-- demonstrations_v2/tutorial_vqt/metadata.json | 2 +- demonstrations_v2/tutorial_xas/demo.py | 78 ++++---- demonstrations_v2/tutorial_xas/metadata.json | 2 +- .../tutorial_zx_calculus/demo.py | 166 +++++++++--------- .../tutorial_zx_calculus/metadata.json | 2 +- demonstrations_v2/vqe_parallel/demo.py | 34 ++-- demonstrations_v2/vqe_parallel/metadata.json | 2 +- demonstrations_v2/zne_catalyst/demo.py | 30 ++-- demonstrations_v2/zne_catalyst/metadata.json | 2 +- 12 files changed, 191 insertions(+), 191 deletions(-) diff --git a/demonstrations_v2/tutorial_vqls/demo.py b/demonstrations_v2/tutorial_vqls/demo.py index 28cceff0e1..32e1e68fd5 100644 --- a/demonstrations_v2/tutorial_vqls/demo.py +++ b/demonstrations_v2/tutorial_vqls/demo.py @@ -183,7 +183,7 @@ """ # Pennylane -import pennylane as qml +import pennylane as qp from pennylane import numpy as np # Plotting @@ -219,7 +219,7 @@ def U_b(): """Unitary matrix rotating the ground state to the problem vector |b> = U_b |0>.""" for idx in range(n_qubits): - qml.Hadamard(wires=idx) + qp.Hadamard(wires=idx) def CA(idx): """Controlled versions of the unitary components A_l of the problem matrix A.""" @@ -228,11 +228,11 @@ def CA(idx): None elif idx == 1: - qml.CNOT(wires=[ancilla_idx, 0]) - qml.CZ(wires=[ancilla_idx, 1]) + qp.CNOT(wires=[ancilla_idx, 0]) + qp.CZ(wires=[ancilla_idx, 1]) elif idx == 2: - qml.CNOT(wires=[ancilla_idx, 0]) + qp.CNOT(wires=[ancilla_idx, 0]) ############################################################################## @@ -256,11 +256,11 @@ def variational_block(weights): """Variational circuit mapping the ground state |0> to the ansatz state |x>.""" # We first prepare an equal superposition of all the states of the computational basis. for idx in range(n_qubits): - qml.Hadamard(wires=idx) + qp.Hadamard(wires=idx) # A very minimal variational circuit. for idx, element in enumerate(weights): - qml.RY(element, wires=idx) + qp.RY(element, wires=idx) ############################################################################## @@ -276,18 +276,18 @@ def variational_block(weights): # and will be used to estimate the coefficients :math:`\mu_{l,l',j}` defined in the introduction. # A graphical representation of this circuit is shown at the top of this tutorial. -dev_mu = qml.device("lightning.qubit", wires=tot_qubits) +dev_mu = qp.device("lightning.qubit", wires=tot_qubits) -@qml.qnode(dev_mu, interface="autograd") +@qp.qnode(dev_mu, interface="autograd") def local_hadamard_test(weights, l=None, lp=None, j=None, part=None): # First Hadamard gate applied to the ancillary qubit. - qml.Hadamard(wires=ancilla_idx) + qp.Hadamard(wires=ancilla_idx) # For estimating the imaginary part of the coefficient "mu", we must add a "-i" # phase gate. if part == "Im" or part == "im": - qml.PhaseShift(-np.pi / 2, wires=ancilla_idx) + qp.PhaseShift(-np.pi / 2, wires=ancilla_idx) # Variational circuit generating a guess for the solution vector |x> variational_block(weights) @@ -301,7 +301,7 @@ def local_hadamard_test(weights, l=None, lp=None, j=None, part=None): # Controlled Z operator at position j. If j = -1, apply the identity. if j != -1: - qml.CZ(wires=[ancilla_idx, j]) + qp.CZ(wires=[ancilla_idx, j]) # Unitary U_b associated to the problem vector |b>. U_b() @@ -311,10 +311,10 @@ def local_hadamard_test(weights, l=None, lp=None, j=None, part=None): CA(lp) # Second Hadamard gate applied to the ancillary qubit. - qml.Hadamard(wires=ancilla_idx) + qp.Hadamard(wires=ancilla_idx) # Expectation value of Z for the ancillary qubit. - return qml.expval(qml.PauliZ(wires=ancilla_idx)) + return qp.expval(qp.PauliZ(wires=ancilla_idx)) ############################################################################################## @@ -382,7 +382,7 @@ def cost_loc(weights): ############################################################################## # To minimize the cost function we use the gradient-descent optimizer. -opt = qml.GradientDescentOptimizer(eta) +opt = qp.GradientDescentOptimizer(eta) ############################################################################## @@ -463,10 +463,10 @@ def cost_loc(weights): # For this task, we initialize a new PennyLane device and define the associated # *qnode* circuit. -dev_x = qml.device("lightning.qubit", wires=n_qubits) +dev_x = qp.device("lightning.qubit", wires=n_qubits) -@qml.set_shots(n_shots) -@qml.qnode(dev_x, interface="autograd") +@qp.set_shots(n_shots) +@qp.qnode(dev_x, interface="autograd") def prepare_and_sample(weights): # Variational circuit generating a guess for the solution vector |x> @@ -475,7 +475,7 @@ def prepare_and_sample(weights): # We assume that the system is measured in the computational basis. # then sampling the device will give us a value of 0 or 1 for each qubit (n_qubits) # this will be repeated for the total number of shots provided (n_shots) - return qml.sample() + return qp.sample() ############################################################################## diff --git a/demonstrations_v2/tutorial_vqls/metadata.json b/demonstrations_v2/tutorial_vqls/metadata.json index e51c4d7111..a7d97e876e 100644 --- a/demonstrations_v2/tutorial_vqls/metadata.json +++ b/demonstrations_v2/tutorial_vqls/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2019-11-04T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_vqt/demo.py b/demonstrations_v2/tutorial_vqt/demo.py index 69dd331ac6..fcc3618823 100644 --- a/demonstrations_v2/tutorial_vqt/demo.py +++ b/demonstrations_v2/tutorial_vqt/demo.py @@ -107,7 +107,7 @@ # -import pennylane as qml +import pennylane as qp from matplotlib import pyplot as plt import numpy as np import scipy @@ -148,9 +148,9 @@ def create_hamiltonian_matrix(n, graph): x = y = z = 1 for j in range(0, n): if j == i[0] or j == i[1]: - x = np.kron(x, qml.matrix(qml.PauliX(0))) - y = np.kron(y, qml.matrix(qml.PauliY(0))) - z = np.kron(z, qml.matrix(qml.PauliZ(0))) + x = np.kron(x, qp.matrix(qp.PauliX(0))) + y = np.kron(y, qp.matrix(qp.PauliY(0))) + z = np.kron(z, qp.matrix(qp.PauliZ(0))) else: x = np.kron(x, np.identity(2)) y = np.kron(y, np.identity(2)) @@ -237,7 +237,7 @@ def single_rotation(phi_params, qubits): rotations = ["Z", "Y", "X"] for i in range(0, len(rotations)): - qml.AngleEmbedding(phi_params[i], wires=qubits, rotation=rotations[i]) + qp.AngleEmbedding(phi_params[i], wires=qubits, rotation=rotations[i]) ###################################################################### @@ -254,17 +254,17 @@ def CRX_ring(parameters, wires): n_wires = len(wires) for param, w in zip(parameters, wires): - qml.CRX(param, wires=[w % n_wires, (w + 1) % n_wires]) + qp.CRX(param, wires=[w % n_wires, (w + 1) % n_wires]) depth = 4 -dev = qml.device("lightning.qubit", wires=nr_qubits) +dev = qp.device("lightning.qubit", wires=nr_qubits) def quantum_circuit(rotation_params, coupling_params, sample=None, return_state=False): # Prepares the initial basis state corresponding to the sample - qml.BasisState(sample, wires=range(nr_qubits)) + qp.BasisState(sample, wires=range(nr_qubits)) # Prepares the variational ansatz for the circuit for i in range(0, depth): @@ -272,14 +272,14 @@ def quantum_circuit(rotation_params, coupling_params, sample=None, return_state= CRX_ring(coupling_params[i], list(range(nr_qubits))) if return_state: - return qml.state() + return qp.state() # Calculates the expectation value of the Hamiltonian with respect to the prepared states - return qml.expval(qml.Hermitian(ham_matrix, wires=range(nr_qubits))) + return qp.expval(qp.Hermitian(ham_matrix, wires=range(nr_qubits))) # Constructs the QNode -qnode = qml.QNode(quantum_circuit, dev, interface="autograd") +qnode = qp.QNode(quantum_circuit, dev, interface="autograd") ###################################################################### @@ -291,7 +291,7 @@ def quantum_circuit(rotation_params, coupling_params, sample=None, return_state= rotation_params = [[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]] for i in range(0, depth)] coupling_params = [[1, 1, 1, 1] for i in range(0, depth)] print( - qml.draw(qnode, level="device", show_matrices=True)( + qp.draw(qnode, level="device", show_matrices=True)( rotation_params, coupling_params, sample=[1, 0, 1, 0] ) ) diff --git a/demonstrations_v2/tutorial_vqt/metadata.json b/demonstrations_v2/tutorial_vqt/metadata.json index f1aa07f6c3..8b03fcda50 100644 --- a/demonstrations_v2/tutorial_vqt/metadata.json +++ b/demonstrations_v2/tutorial_vqt/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2020-07-07T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_xas/demo.py b/demonstrations_v2/tutorial_xas/demo.py index abb6336cb8..c67d5a9a52 100644 --- a/demonstrations_v2/tutorial_xas/demo.py +++ b/demonstrations_v2/tutorial_xas/demo.py @@ -167,12 +167,12 @@ # Since we will be using PennyLane for other aspects of this calculation, we want to make sure the molecular orbital coefficients are consistent between our PennyLane and PySCF calculations. # To do this, we can obtain the molecular orbital coefficients from PennyLane using :func:`~.pennylane.qchem.scf`, and change the coefficients in the ``hf`` instance to match. -import pennylane as qml +import pennylane as qp -mole = qml.qchem.Molecule(symbols, geometry, basis_name="sto-3g", unit="angstrom") +mole = qp.qchem.Molecule(symbols, geometry, basis_name="sto-3g", unit="angstrom") # Run self-consistent fields method to get molecular orbital coefficients. -_, coeffs, _, _, _ = qml.qchem.scf(mole)() +_, coeffs, _, _, _ = qp.qchem.scf(mole)() # Change MO coefficients in hf object to PennyLane calculated values. hf.mo_coeff = coeffs @@ -258,13 +258,13 @@ # This is fine for our simple example, but for more complex instances you may want to modify the dipole operator to restrict the final states (see the Appendix for more details). # Get core and active orbital indices. -core, active = qml.qchem.active_space( +core, active = qp.qchem.active_space( mole.n_electrons, mole.n_orbitals, active_electrons=n_electron_cas, active_orbitals=n_cas ) -m_rho = qml.qchem.dipole_moment(mole, cutoff=1e-8, core=core, active=active)() +m_rho = qp.qchem.dipole_moment(mole, cutoff=1e-8, core=core, active=active)() rhos = range(len(m_rho)) # [0, 1, 2] are [x, y, z]. wf_dipole = [] @@ -272,7 +272,7 @@ # Loop over cartesian coordinates and calculate m_rho|I>. for rho in rhos: - dipole_matrix_rho = qml.matrix(m_rho[rho], wire_order=range(2 * n_cas)) + dipole_matrix_rho = qp.matrix(m_rho[rho], wire_order=range(2 * n_cas)) wf = dipole_matrix_rho.dot(wf_casci) # Multiply state into dipole matrix. if np.allclose(wf, np.zeros_like(wf)): # If wf is zero, then set norm as zero. @@ -294,15 +294,15 @@ # We will also add one auxiliary wire for the measurement circuit, which we will prepare as the 0 wire with an applied Hadamard gate. device_type = "lightning.qubit" -dev_prop = qml.device(device_type, wires=int(2*n_cas) + 1) +dev_prop = qp.device(device_type, wires=int(2*n_cas) + 1) -@qml.qnode(dev_prop) +@qp.qnode(dev_prop) def initial_circuit(wf): """Circuit to load initial state and prepare auxiliary qubit.""" - qml.StatePrep(wf, wires=dev_prop.wires.tolist()[1:]) - qml.Hadamard(wires=0) - return qml.state() + qp.StatePrep(wf, wires=dev_prop.wires.tolist()[1:]) + qp.Hadamard(wires=0) + return qp.state() ###################################################################### @@ -331,14 +331,14 @@ def initial_circuit(wf): # # The core constant and the one- and two-electron integrals can be computed in PennyLane using :func:`~pennylane.qchem.electron_integrals`. -core_constant, one, two = qml.qchem.electron_integrals(mole, core=core, active=active)() +core_constant, one, two = qp.qchem.electron_integrals(mole, core=core, active=active)() core_constant = core_constant[0] ###################################################################### # We will have to convert these to chemists' notation [#Sherrill2005]_. -two_chemist = qml.math.einsum("prsq->pqrs", two) -one_chemist = one - qml.math.einsum("pqrr->pq", two) / 2.0 +two_chemist = qp.math.einsum("prsq->pqrs", two) +one_chemist = one - qp.math.einsum("pqrr->pq", two) / 2.0 ###################################################################### # Next, we will perform compressed double factorization of the Hamiltonian's two-electron integrals to approximate them as a sum of :math:`L` fragments @@ -355,7 +355,7 @@ def initial_circuit(wf): config.update("jax_enable_x64", True) # Required for factorize consistency. # Factorize Hamiltonian, producing matrices Z and U for each fragment. -_, Z, U = qml.qchem.factorize(two_chemist, compressed=True) +_, Z, U = qp.qchem.factorize(two_chemist, compressed=True) print("Shape of the factors: ") print("two_chemist", two_chemist.shape) @@ -363,8 +363,8 @@ def initial_circuit(wf): print("Z", Z.shape) # Compare factorized two-electron fragment sum to the original. -approx_two_chemist = qml.math.einsum("tpk,tqk,tkl,trl,tsl->pqrs", U, U, Z, U, U) -assert qml.math.allclose(approx_two_chemist, two_chemist, atol=0.1) +approx_two_chemist = qp.math.einsum("tpk,tqk,tkl,trl,tsl->pqrs", U, U, Z, U, U) +assert qp.math.allclose(approx_two_chemist, two_chemist, atol=0.1) ###################################################################### # Note there are some terms in this decomposition of the two-electron integrals that are exactly diagonalizable, and can be combined with the one-electron integrals to simplify how the Hamiltonian time evolution is implemented. @@ -373,7 +373,7 @@ def initial_circuit(wf): # Calculate the one-electron extra terms. Z_prime = np.stack([np.diag(np.sum(Z[i], axis=-1)) for i in range(Z.shape[0])], axis=0) -one_electron_extra = qml.math.einsum("tpk,tkk,tqk->pq", U, Z_prime, U) +one_electron_extra = qp.math.einsum("tpk,tkk,tqk->pq", U, Z_prime, U) # Diagonalize the one-electron integral matrix while adding the one-electron extra. eigenvals, U0 = np.linalg.eigh(one_chemist + one_electron_extra) @@ -411,8 +411,8 @@ def initial_circuit(wf): def U_rotations(U, control_wires): """Circuit implementing the basis rotations of the Hamiltonian fragments.""" - U_spin = qml.math.kron(U, qml.math.eye(2)) # Apply to both spins. - qml.BasisRotation( + U_spin = qp.math.kron(U, qp.math.eye(2)) # Apply to both spins. + qp.BasisRotation( unitary_matrix=U_spin, wires=[int(i + control_wires) for i in range(2 * n_cas)] ) @@ -439,14 +439,14 @@ def Z_rotations(Z, step, is_one_electron_term, control_wires): if is_one_electron_term: for sigma in range(2): for i in range(n_cas): - qml.ctrl( - qml.X(wires=int(2*i + sigma + control_wires)), + qp.ctrl( + qp.X(wires=int(2*i + sigma + control_wires)), control=range(control_wires), control_values=0, ) - qml.RZ(-Z[i, i] * step / 2, wires=int(2*i + sigma + control_wires)) - qml.ctrl( - qml.X(wires=int(2*i + sigma + control_wires)), + qp.RZ(-Z[i, i] * step / 2, wires=int(2*i + sigma + control_wires)) + qp.ctrl( + qp.X(wires=int(2*i + sigma + control_wires)), control=range(control_wires), control_values=0, ) @@ -456,16 +456,16 @@ def Z_rotations(Z, step, is_one_electron_term, control_wires): for sigma, tau in product(range(2), repeat=2): for i, k in product(range(n_cas), repeat=2): if i != k or sigma != tau: # Skip the one-electron correction terms. - qml.ctrl(qml.X(wires=int(2*i + sigma + control_wires)), + qp.ctrl(qp.X(wires=int(2*i + sigma + control_wires)), control=range(control_wires), control_values=0) - qml.MultiRZ(Z[i, k] / 8.0 * step, + qp.MultiRZ(Z[i, k] / 8.0 * step, wires=[int(2*i + sigma + control_wires), int(2*k + tau + control_wires)]) - qml.ctrl(qml.X(wires=int(2 * i + sigma + control_wires)), + qp.ctrl(qp.X(wires=int(2 * i + sigma + control_wires)), control=range(control_wires), control_values=0) globalphase = np.trace(Z)/4.0*step - np.sum(Z)*step/2.0 - qml.PhaseShift(-globalphase, wires=0) + qp.PhaseShift(-globalphase, wires=0) ###################################################################### @@ -503,7 +503,7 @@ def first_order_trotter(step, prior_U, final_rotation, reverse=False): U_rotations(prior_U, 1) # Global phase adjustment from core constant. - qml.PhaseShift(-core_constant * step, wires=0) + qp.PhaseShift(-core_constant * step, wires=0) return prior_U @@ -519,7 +519,7 @@ def second_order_trotter(dev, state, step): def circuit(): # State preparation -- set as the final state from the previous iteration. - qml.StatePrep(state, wires=qubits) + qp.StatePrep(state, wires=qubits) prior_U = np.eye(n_cas) # No initial prior U, so set as identity matrix. prior_U = first_order_trotter(step / 2, prior_U=prior_U, @@ -527,9 +527,9 @@ def circuit(): prior_U = first_order_trotter(step / 2, prior_U=prior_U, final_rotation=True, reverse=True) - return qml.state() + return qp.state() - return qml.QNode(circuit, dev) + return qp.QNode(circuit, dev) ###################################################################### @@ -541,9 +541,9 @@ def circuit(): def meas_circuit(state): - qml.StatePrep(state, wires=range(int(2*n_cas) + 1)) + qp.StatePrep(state, wires=range(int(2*n_cas) + 1)) # Measure in PauliX/PauliY to get the real/imaginary parts. - return [qml.expval(op) for op in [qml.PauliX(wires=0), qml.PauliY(wires=0)]] + return [qp.expval(op) for op in [qp.PauliX(wires=0), qp.PauliY(wires=0)]] ###################################################################### @@ -630,11 +630,11 @@ def L_j(t_j): # Define measurement circuit device with shots. shots = shots_list[i] # Kernel-aware number of shots. - dev_est = qml.device(device_type, wires=int(2*n_cas) + 1) + dev_est = qp.device(device_type, wires=int(2*n_cas) + 1) # Update state and then measure expectation values. state = circuit() - measurement = qml.QNode(meas_circuit, dev_est, shots=shots)(state) + measurement = qp.QNode(meas_circuit, dev_est, shots=shots)(state) expvals[:, i] += dipole_norm[rho]**2 * np.array(measurement).real @@ -706,7 +706,7 @@ def L_j(t_j): mo_coeffs = coeffs[:, n_core : n_core + n_cas] # Convert to molecular orbital basis. -dip_ints_mo = qml.math.einsum("ik,xkl,lj->xij", mo_coeffs.T, dip_ints_ao, mo_coeffs) +dip_ints_mo = qp.math.einsum("ik,xkl,lj->xij", mo_coeffs.T, dip_ints_ao, mo_coeffs) def final_state_overlap(ci_id): @@ -715,7 +715,7 @@ def final_state_overlap(ci_id): mycasci.ci[0], mycasci.ci[ci_id], n_cas, n_electron_cas ) # Transition dipole moments. - return qml.math.einsum("xij,ji->x", dip_ints_mo, t_dm1) + return qp.math.einsum("xij,ji->x", dip_ints_mo, t_dm1) # Compute overlaps. diff --git a/demonstrations_v2/tutorial_xas/metadata.json b/demonstrations_v2/tutorial_xas/metadata.json index a078eb70cb..0ce7d069ab 100644 --- a/demonstrations_v2/tutorial_xas/metadata.json +++ b/demonstrations_v2/tutorial_xas/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2025-08-29T09:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Quantum Chemistry", "Algorithms" diff --git a/demonstrations_v2/tutorial_zx_calculus/demo.py b/demonstrations_v2/tutorial_zx_calculus/demo.py index d8a292adb3..6b6a5b28ce 100644 --- a/demonstrations_v2/tutorial_zx_calculus/demo.py +++ b/demonstrations_v2/tutorial_zx_calculus/demo.py @@ -513,19 +513,19 @@ import matplotlib.pyplot as plt -import pennylane as qml +import pennylane as qp import pyzx -dev = qml.device("default.qubit", wires=2) +dev = qp.device("default.qubit", wires=2) -@qml.transforms.to_zx -@qml.qnode(device=dev) +@qp.transforms.to_zx +@qp.qnode(device=dev) def circuit(): - qml.PauliX(wires=0), - qml.PauliY(wires=1), - qml.CNOT(wires=[0, 1]), - return qml.expval(qml.PauliZ(wires=0)) + qp.PauliX(wires=0), + qp.PauliY(wires=1), + qp.CNOT(wires=[0, 1]), + return qp.expval(qp.PauliZ(wires=0)) g = circuit() @@ -572,7 +572,7 @@ def circuit(): graph = random_circuit.to_graph() -tape = qml.transforms.from_zx(graph) +tape = qp.transforms.from_zx(graph) print(tape.operations) ############################################################################# @@ -629,76 +629,76 @@ def circuit(): # -dev = qml.device("default.qubit", wires=5) +dev = qp.device("default.qubit", wires=5) -@qml.transforms.to_zx -@qml.qnode(device=dev) +@qp.transforms.to_zx +@qp.qnode(device=dev) def mod_5_4(): - qml.PauliX(wires=4), - qml.Hadamard(wires=4), - qml.CNOT(wires=[3, 4]), - qml.adjoint(qml.T(wires=[4])), - qml.CNOT(wires=[0, 4]), - qml.T(wires=[4]), - qml.CNOT(wires=[3, 4]), - qml.adjoint(qml.T(wires=[4])), - qml.CNOT(wires=[0, 4]), - qml.T(wires=[3]), - qml.T(wires=[4]), - qml.CNOT(wires=[0, 3]), - qml.T(wires=[0]), - qml.adjoint(qml.T(wires=[3])) - qml.CNOT(wires=[0, 3]), - qml.CNOT(wires=[3, 4]), - qml.adjoint(qml.T(wires=[4])), - qml.CNOT(wires=[2, 4]), - qml.T(wires=[4]), - qml.CNOT(wires=[3, 4]), - qml.adjoint(qml.T(wires=[4])), - qml.CNOT(wires=[2, 4]), - qml.T(wires=[3]), - qml.T(wires=[4]), - qml.CNOT(wires=[2, 3]), - qml.T(wires=[2]), - qml.adjoint(qml.T(wires=[3])) - qml.CNOT(wires=[2, 3]), - qml.Hadamard(wires=[4]), - qml.CNOT(wires=[3, 4]), - qml.Hadamard(wires=4), - qml.CNOT(wires=[2, 4]), - qml.adjoint(qml.T(wires=[4])), - qml.CNOT(wires=[1, 4]), - qml.T(wires=[4]), - qml.CNOT(wires=[2, 4]), - qml.adjoint(qml.T(wires=[4])), - qml.CNOT(wires=[1, 4]), - qml.T(wires=[4]), - qml.T(wires=[2]), - qml.CNOT(wires=[1, 2]), - qml.T(wires=[1]), - qml.adjoint(qml.T(wires=[2])) - qml.CNOT(wires=[1, 2]), - qml.Hadamard(wires=[4]), - qml.CNOT(wires=[2, 4]), - qml.Hadamard(wires=4), - qml.CNOT(wires=[1, 4]), - qml.adjoint(qml.T(wires=[4])), - qml.CNOT(wires=[0, 4]), - qml.T(wires=[4]), - qml.CNOT(wires=[1, 4]), - qml.adjoint(qml.T(wires=[4])), - qml.CNOT(wires=[0, 4]), - qml.T(wires=[4]), - qml.T(wires=[1]), - qml.CNOT(wires=[0, 1]), - qml.T(wires=[0]), - qml.adjoint(qml.T(wires=[1])), - qml.CNOT(wires=[0, 1]), - qml.Hadamard(wires=[4]), - qml.CNOT(wires=[1, 4]), - qml.CNOT(wires=[0, 4]), - return qml.expval(qml.PauliZ(wires=0)) + qp.PauliX(wires=4), + qp.Hadamard(wires=4), + qp.CNOT(wires=[3, 4]), + qp.adjoint(qp.T(wires=[4])), + qp.CNOT(wires=[0, 4]), + qp.T(wires=[4]), + qp.CNOT(wires=[3, 4]), + qp.adjoint(qp.T(wires=[4])), + qp.CNOT(wires=[0, 4]), + qp.T(wires=[3]), + qp.T(wires=[4]), + qp.CNOT(wires=[0, 3]), + qp.T(wires=[0]), + qp.adjoint(qp.T(wires=[3])) + qp.CNOT(wires=[0, 3]), + qp.CNOT(wires=[3, 4]), + qp.adjoint(qp.T(wires=[4])), + qp.CNOT(wires=[2, 4]), + qp.T(wires=[4]), + qp.CNOT(wires=[3, 4]), + qp.adjoint(qp.T(wires=[4])), + qp.CNOT(wires=[2, 4]), + qp.T(wires=[3]), + qp.T(wires=[4]), + qp.CNOT(wires=[2, 3]), + qp.T(wires=[2]), + qp.adjoint(qp.T(wires=[3])) + qp.CNOT(wires=[2, 3]), + qp.Hadamard(wires=[4]), + qp.CNOT(wires=[3, 4]), + qp.Hadamard(wires=4), + qp.CNOT(wires=[2, 4]), + qp.adjoint(qp.T(wires=[4])), + qp.CNOT(wires=[1, 4]), + qp.T(wires=[4]), + qp.CNOT(wires=[2, 4]), + qp.adjoint(qp.T(wires=[4])), + qp.CNOT(wires=[1, 4]), + qp.T(wires=[4]), + qp.T(wires=[2]), + qp.CNOT(wires=[1, 2]), + qp.T(wires=[1]), + qp.adjoint(qp.T(wires=[2])) + qp.CNOT(wires=[1, 2]), + qp.Hadamard(wires=[4]), + qp.CNOT(wires=[2, 4]), + qp.Hadamard(wires=4), + qp.CNOT(wires=[1, 4]), + qp.adjoint(qp.T(wires=[4])), + qp.CNOT(wires=[0, 4]), + qp.T(wires=[4]), + qp.CNOT(wires=[1, 4]), + qp.adjoint(qp.T(wires=[4])), + qp.CNOT(wires=[0, 4]), + qp.T(wires=[4]), + qp.T(wires=[1]), + qp.CNOT(wires=[0, 1]), + qp.T(wires=[0]), + qp.adjoint(qp.T(wires=[1])), + qp.CNOT(wires=[0, 1]), + qp.Hadamard(wires=[4]), + qp.CNOT(wires=[1, 4]), + qp.CNOT(wires=[0, 4]), + return qp.expval(qp.PauliZ(wires=0)) g = mod_5_4() @@ -770,20 +770,20 @@ def mod_5_4(): # and which is made possible because we used `pyzx.teleport_reduce` and do not need to extract # the circuit. -qscript_opt = qml.transforms.from_zx(g) +qscript_opt = qp.transforms.from_zx(g) -wires = qml.wires.Wires([4, 3, 0, 2, 1]) +wires = qp.wires.Wires([4, 3, 0, 2, 1]) wires_map = dict(zip(qscript_opt.wires, wires)) -qscript_opt_reorder, processing = qml.map_wires(qscript_opt, wire_map=wires_map) +qscript_opt_reorder, processing = qp.map_wires(qscript_opt, wire_map=wires_map) -@qml.qnode(device=dev) +@qp.qnode(device=dev) def mod_5_4(): for o in processing(qscript_opt_reorder): - qml.apply(o) - return qml.expval(qml.PauliZ(wires=0)) + qp.apply(o) + return qp.expval(qp.PauliZ(wires=0)) -specs = qml.specs(mod_5_4)() +specs = qp.specs(mod_5_4)() print("Number of quantum gates:", specs["resources"].num_gates) print("Circuit gates:", specs["resources"].gate_types) diff --git a/demonstrations_v2/tutorial_zx_calculus/metadata.json b/demonstrations_v2/tutorial_zx_calculus/metadata.json index c244f4fbe8..d5c0df619c 100644 --- a/demonstrations_v2/tutorial_zx_calculus/metadata.json +++ b/demonstrations_v2/tutorial_zx_calculus/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-06-06T00:00:00+00:00", - "dateOfLastModification": "2026-01-14T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Computing", "Compilation" diff --git a/demonstrations_v2/vqe_parallel/demo.py b/demonstrations_v2/vqe_parallel/demo.py index 1223044da9..44f515e3e9 100644 --- a/demonstrations_v2/vqe_parallel/demo.py +++ b/demonstrations_v2/vqe_parallel/demo.py @@ -35,7 +35,7 @@ import matplotlib.pyplot as plt from pennylane import numpy as np -import pennylane as qml +import pennylane as qp from pennylane import qchem ############################################################################## @@ -66,7 +66,7 @@ # `PennyLane Datasets library `__: bonds = [0.5, 0.58, 0.7, 0.9, 1.1, 1.3, 1.5, 1.7, 1.9, 2.1] -datasets = qml.data.load("qchem", molname="H2", bondlength=bonds, basis="STO-3G") +datasets = qp.data.load("qchem", molname="H2", bondlength=bonds, basis="STO-3G") ############################################################################## # We can now extract the qubit Hamiltonians from these datasets for each bond length: @@ -136,8 +136,8 @@ # # To do this, start by instantiating a device for each term: -dev1 = [qml.device("rigetti.qvm", device="4q-qvm") for _ in range(8)] -dev2 = [qml.device("rigetti.qvm", device="9q-square-qvm") for _ in range(7)] +dev1 = [qp.device("rigetti.qvm", device="4q-qvm") for _ in range(8)] +dev2 = [qp.device("rigetti.qvm", device="9q-square-qvm") for _ in range(7)] devs = dev1 + dev2 ############################################################################## @@ -168,12 +168,12 @@ def circuit(param, H): - qml.BasisState(np.array([1, 1, 0, 0], requires_grad=False), wires=[0, 1, 2, 3]) - qml.RY(param, wires=2) - qml.CNOT(wires=[2, 3]) - qml.CNOT(wires=[2, 0]) - qml.CNOT(wires=[3, 1]) - return qml.expval(H) + qp.BasisState(np.array([1, 1, 0, 0], requires_grad=False), wires=[0, 1, 2, 3]) + qp.RY(param, wires=2) + qp.CNOT(wires=[2, 3]) + qp.CNOT(wires=[2, 0]) + qp.CNOT(wires=[3, 1]) + return qp.expval(H) ############################################################################## @@ -200,7 +200,7 @@ def circuit(param, H): print( f"{i+1} / {len(bonds)}: Sequential execution; Running for inter-atomic distance {bonds[i]} Å" ) - energies_seq.append(qml.QNode(circuit, devs[0])(param, h)) + energies_seq.append(qp.QNode(circuit, devs[0])(param, h)) dt_seq = time.time() - t0 @@ -218,7 +218,7 @@ def compute_energy_parallel(H, devs, param): results = [] for i in range(len(H_ops)): - qnode = qml.QNode(circuit, devs[i]) + qnode = qp.QNode(circuit, devs[i]) results.append(dask.delayed(qnode)(param, H_ops[i])) results = dask.compute(*results, scheduler="threads") @@ -229,7 +229,7 @@ def compute_energy_parallel(H, devs, param): ############################################################################## # We can now compute all 10 samples from the energy surface sequentially, where each execution is making use of # parallel device execution. Curiously, in this example the overhead from doing so outweighs the speed-up -# and the execution is slower than standard execution using ``qml.expval``. For different circuits and +# and the execution is slower than standard execution using ``qp.expval``. For different circuits and # different Hamiltonians, however, parallelization may provide significant speed-ups. print("Evaluating the potential energy surface in parallel") @@ -259,16 +259,16 @@ def compute_energy_parallel_optimized(H, devs, param): assert len(H_ops) == len(devs) results = [] - obs_groupings, coeffs_groupings = qml.pauli.group_observables( + obs_groupings, coeffs_groupings = qp.pauli.group_observables( H_ops, H_coeffs, "qwc" ) for i, (obs, coeffs) in enumerate(zip(obs_groupings, coeffs_groupings)): - H_part = qml.Hamiltonian(coeffs, obs) - qnode = qml.QNode(circuit, devs[i]) + H_part = qp.Hamiltonian(coeffs, obs) + qnode = qp.QNode(circuit, devs[i]) results.append(dask.delayed(qnode)(param, H_part)) - result = qml.math.sum(dask.compute(*results, scheduler="threads")) + result = qp.math.sum(dask.compute(*results, scheduler="threads")) return result print( diff --git a/demonstrations_v2/vqe_parallel/metadata.json b/demonstrations_v2/vqe_parallel/metadata.json index 99a308023e..00333508c3 100644 --- a/demonstrations_v2/vqe_parallel/metadata.json +++ b/demonstrations_v2/vqe_parallel/metadata.json @@ -8,7 +8,7 @@ "executable_stable": false, "executable_latest": false, "dateOfPublication": "2020-02-14T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Chemistry" ], diff --git a/demonstrations_v2/zne_catalyst/demo.py b/demonstrations_v2/zne_catalyst/demo.py index 1db090fed4..74d536d79e 100644 --- a/demonstrations_v2/zne_catalyst/demo.py +++ b/demonstrations_v2/zne_catalyst/demo.py @@ -96,7 +96,7 @@ # equal to 1. import numpy as np -import pennylane as qml +import pennylane as qp from catalyst import mitigate_with_zne import warnings @@ -108,21 +108,21 @@ np.random.seed(42) n_layers = 5 -template = qml.SimplifiedTwoDesign +template = qp.SimplifiedTwoDesign weights_shape = template.shape(n_layers, n_wires) w1, w2 = [2 * np.pi * np.random.random(s) for s in weights_shape] def circuit(w1, w2): template(w1, w2, wires=range(n_wires)) - qml.adjoint(template)(w1, w2, wires=range(n_wires)) - return qml.expval(qml.PauliZ(0)) + qp.adjoint(template)(w1, w2, wires=range(n_wires)) + return qp.expval(qp.PauliZ(0)) ############################################################################## # As a sanity check, we first execute the circuit on the Qrack simulator without any noise. -noiseless_device = qml.device("qrack.simulator", n_wires, noise=0) +noiseless_device = qp.device("qrack.simulator", n_wires, noise=0) -ideal_value = qml.QNode(circuit, device=noiseless_device)(w1, w2) +ideal_value = qp.QNode(circuit, device=noiseless_device)(w1, w2) print(f"Ideal value: {ideal_value}") ############################################################################## @@ -136,9 +136,9 @@ def circuit(w1, w2): # The probability of error is specified by the value of the ``noise`` constructor argument. NOISE_LEVEL = 0.01 -noisy_device = qml.device("qrack.simulator", n_wires, shots=1000, noise=NOISE_LEVEL) +noisy_device = qp.device("qrack.simulator", n_wires, shots=1000, noise=NOISE_LEVEL) -noisy_qnode = qml.QNode(circuit, device=noisy_device, mcm_method="one-shot") +noisy_qnode = qp.QNode(circuit, device=noisy_device, mcm_method="one-shot") noisy_value = noisy_qnode(w1, w2) print(f"Error without mitigation: {abs(ideal_value - noisy_value):.3f}") @@ -166,7 +166,7 @@ def circuit(w1, w2): ############################################################################## # Finally, we'll choose the extrapolation technique. Both exponential and polynomial extrapolation -# is available in the :mod:`qml.noise ` module, and both of these functions can be passed directly +# is available in the :mod:`qp.noise ` module, and both of these functions can be passed directly # into Catalyst's :func:`catalyst.mitigate_with_zne` function. In this tutorial we use polynomial extrapolation, # which we hypothesize best models the behavior of the noise scenario we are considering. @@ -180,7 +180,7 @@ def circuit(w1, w2): # to define a very simple :func:`~.QNode`, which represents the mitigated version of the original circuit. -@qml.qjit +@qp.qjit def mitigated_circuit_qjit(w1, w2): return mitigate_with_zne( noisy_qnode, @@ -209,11 +209,11 @@ def mitigated_circuit_qjit(w1, w2): def mitigated_circuit(w1, w2): - return qml.noise.mitigate_with_zne( + return qp.noise.mitigate_with_zne( noisy_qnode, scale_factors=scale_factors, extrapolate=extrapolation_method, - folding=qml.noise.fold_global, + folding=qp.noise.fold_global, )(w1, w2) @@ -230,10 +230,10 @@ def mitigated_circuit(w1, w2): # reduce the running time of this tutorial, while still showcasing the performance differences. import timeit -noisy_device = qml.device("qrack.simulator", n_wires, shots=100, noise=NOISE_LEVEL) -noisy_qnode = qml.QNode(circuit, device=noisy_device, mcm_method="one-shot") +noisy_device = qp.device("qrack.simulator", n_wires, shots=100, noise=NOISE_LEVEL) +noisy_qnode = qp.QNode(circuit, device=noisy_device, mcm_method="one-shot") -@qml.qjit +@qp.qjit def mitigated_circuit_qjit(w1, w2): return mitigate_with_zne( noisy_qnode, diff --git a/demonstrations_v2/zne_catalyst/metadata.json b/demonstrations_v2/zne_catalyst/metadata.json index 9376a3d40a..9211308089 100644 --- a/demonstrations_v2/zne_catalyst/metadata.json +++ b/demonstrations_v2/zne_catalyst/metadata.json @@ -11,7 +11,7 @@ "executable_stable": false, "executable_latest": true, "dateOfPublication": "2024-11-15T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Algorithms", "Quantum Computing" From f25438bb79c295c33613bf148b46e07e8b74a8ad Mon Sep 17 00:00:00 2001 From: drdren <104710745+drdren@users.noreply.github.com> Date: Tue, 21 Apr 2026 15:43:55 -0400 Subject: [PATCH 09/10] Update Getting Started and Resource Estimation tags (#1764) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### Before submitting Please complete the following checklist when submitting a PR: - [ ] Ensure that your tutorial executes correctly, and conforms to the guidelines specified in the [README](https://github.com/PennyLaneAI/demos/blob/master/README.md). - [ ] Remember to do a grammar check of the content you include. - [ ] All tutorials conform to [PEP8 standards](https://www.python.org/dev/peps/pep-0008/). To auto format files, simply `pip install black`, and then run `black -l 100 path/to/file.py`. When all the above are checked, delete everything above the dashed line and fill in the pull request template. ------------------------------------------------------------------------------------------------------------ **Title:** **Summary:** **Relevant references:** **Possible Drawbacks:** **Related GitHub Issues:** ---- If you are writing a demonstration, please answer these questions to facilitate the marketing process. * GOALS — Why are we working on this now? *Eg. Promote a new PL feature or show a PL implementation of a recent paper.* * AUDIENCE — Who is this for? *Eg. Chemistry researchers, PL educators, beginners in quantum computing.* * KEYWORDS — What words should be included in the marketing post? * Which of the following types of documentation is most similar to your file? (more details [here](https://www.notion.so/xanaduai/Different-kinds-of-documentation-69200645fe59442991c71f9e7d8a77f8)) - [ ] Tutorial - [ ] Demo - [ ] How-to --- .../metadata.json | 5 +++-- .../metadata.json | 5 +++-- .../tutorial_guide_to_pennylane_knowing_qiskit/metadata.json | 5 +++-- .../tutorial_how_to_use_noise_models/metadata.json | 5 +++-- demonstrations_v2/tutorial_jax_transformations/metadata.json | 5 +++-- demonstrations_v2/tutorial_liealgebra/metadata.json | 5 ++--- demonstrations_v2/tutorial_liesim/metadata.json | 5 ++--- demonstrations_v2/tutorial_mbqc/metadata.json | 5 +++-- demonstrations_v2/tutorial_qaoa_intro/metadata.json | 5 +++-- demonstrations_v2/tutorial_qksd_qsp_qualtran/metadata.json | 5 +++-- .../tutorial_qnn_multivariate_regression/metadata.json | 5 ++--- demonstrations_v2/tutorial_re_for_qubitizedQPE/metadata.json | 5 +++-- demonstrations_v2/tutorial_resource_estimation/metadata.json | 5 +++-- .../tutorial_resource_estimation_QSVT/metadata.json | 5 +++-- .../tutorial_resource_estimation_QSVT_CFD/metadata.json | 5 +++-- .../tutorial_resource_estimation_spectroscopy/metadata.json | 5 +++-- .../metadata.json | 5 +++-- demonstrations_v2/tutorial_rl_pulse/metadata.json | 3 +-- .../tutorial_tensor_network_basics/metadata.json | 3 +-- 19 files changed, 50 insertions(+), 41 deletions(-) diff --git a/demonstrations_v2/re_how_to_use_pennylane_for_resource_estimation/metadata.json b/demonstrations_v2/re_how_to_use_pennylane_for_resource_estimation/metadata.json index 2476e6e234..9a1cf90d38 100644 --- a/demonstrations_v2/re_how_to_use_pennylane_for_resource_estimation/metadata.json +++ b/demonstrations_v2/re_how_to_use_pennylane_for_resource_estimation/metadata.json @@ -11,11 +11,12 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2026-01-13T10:00:00+00:00", - "dateOfLastModification": "2026-04-14T10:00:00+00:01", + "dateOfLastModification": "2026-04-21T10:00:00+00:01", "categories": [ "Algorithms", "How-to", - "Getting Started" + "Getting Started", + "Resource Estimation" ], "tags": [], "previewImages": [ diff --git a/demonstrations_v2/tutorial_estimator_hamiltonian_simulation_gqsp/metadata.json b/demonstrations_v2/tutorial_estimator_hamiltonian_simulation_gqsp/metadata.json index 9a093ccbd0..2a365c1b2a 100644 --- a/demonstrations_v2/tutorial_estimator_hamiltonian_simulation_gqsp/metadata.json +++ b/demonstrations_v2/tutorial_estimator_hamiltonian_simulation_gqsp/metadata.json @@ -8,11 +8,12 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2026-02-03T00:00:00+00:00", - "dateOfLastModification": "2026-02-24T00:00:00+00:00", + "dateOfLastModification": "2026-04-21T00:00:00+00:00", "categories": [ "Algorithms", "Quantum Chemistry", - "Optimization" + "Optimization", + "Resource Estimation" ], "tags": [], "previewImages": [ diff --git a/demonstrations_v2/tutorial_guide_to_pennylane_knowing_qiskit/metadata.json b/demonstrations_v2/tutorial_guide_to_pennylane_knowing_qiskit/metadata.json index e74175f97f..5873d176b1 100644 --- a/demonstrations_v2/tutorial_guide_to_pennylane_knowing_qiskit/metadata.json +++ b/demonstrations_v2/tutorial_guide_to_pennylane_knowing_qiskit/metadata.json @@ -8,9 +8,10 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-07-22T00:00:00+00:00", - "dateOfLastModification": "2026-04-17T00:00:00+00:00", + "dateOfLastModification": "2026-04-21T00:00:00+00:00", "categories": [ - "Quantum Computing" + "Quantum Computing", + "Getting Started" ], "tags": [], "previewImages": [ diff --git a/demonstrations_v2/tutorial_how_to_use_noise_models/metadata.json b/demonstrations_v2/tutorial_how_to_use_noise_models/metadata.json index b9c207742b..6fc84ff15b 100644 --- a/demonstrations_v2/tutorial_how_to_use_noise_models/metadata.json +++ b/demonstrations_v2/tutorial_how_to_use_noise_models/metadata.json @@ -8,10 +8,11 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-10-01T00:00:00+00:00", - "dateOfLastModification": "2026-04-17T15:48:14+00:00", + "dateOfLastModification": "2026-04-21T15:48:14+00:00", "categories": [ "Quantum Computing", - "How-to" + "How-to", + "Getting Started" ], "tags": [], "previewImages": [ diff --git a/demonstrations_v2/tutorial_jax_transformations/metadata.json b/demonstrations_v2/tutorial_jax_transformations/metadata.json index 4dd4295467..66a0d1d61e 100644 --- a/demonstrations_v2/tutorial_jax_transformations/metadata.json +++ b/demonstrations_v2/tutorial_jax_transformations/metadata.json @@ -8,9 +8,10 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2021-04-12T00:00:00+00:00", - "dateOfLastModification": "2026-04-17T00:00:00+00:00", + "dateOfLastModification": "2026-04-21T00:00:00+00:00", "categories": [ - "Devices and Performance" + "Devices and Performance", + "Getting Started" ], "tags": [], "previewImages": [ diff --git a/demonstrations_v2/tutorial_liealgebra/metadata.json b/demonstrations_v2/tutorial_liealgebra/metadata.json index 8f1a5ee484..3eec4a5f88 100644 --- a/demonstrations_v2/tutorial_liealgebra/metadata.json +++ b/demonstrations_v2/tutorial_liealgebra/metadata.json @@ -8,10 +8,9 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-02-27T00:00:00+00:00", - "dateOfLastModification": "2026-04-17T15:48:14+00:00", + "dateOfLastModification": "2026-04-21T15:48:14+00:00", "categories": [ - "Quantum Computing", - "Getting Started" + "Quantum Computing" ], "tags": [], "previewImages": [ diff --git a/demonstrations_v2/tutorial_liesim/metadata.json b/demonstrations_v2/tutorial_liesim/metadata.json index dc43b78ca2..693989cb72 100644 --- a/demonstrations_v2/tutorial_liesim/metadata.json +++ b/demonstrations_v2/tutorial_liesim/metadata.json @@ -8,10 +8,9 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-06-07T00:00:00+00:00", - "dateOfLastModification": "2026-04-17T15:48:14+00:00", + "dateOfLastModification": "2026-04-21T15:48:14+00:00", "categories": [ - "Quantum Computing", - "Getting Started" + "Quantum Computing" ], "tags": [], "previewImages": [ diff --git a/demonstrations_v2/tutorial_mbqc/metadata.json b/demonstrations_v2/tutorial_mbqc/metadata.json index f0d2fdc653..3c44b7f8f5 100644 --- a/demonstrations_v2/tutorial_mbqc/metadata.json +++ b/demonstrations_v2/tutorial_mbqc/metadata.json @@ -11,10 +11,11 @@ "executable_stable": false, "executable_latest": false, "dateOfPublication": "2022-12-05T00:00:00+00:00", - "dateOfLastModification": "2026-04-17T15:48:14+00:00", + "dateOfLastModification": "2026-04-21T15:48:14+00:00", "categories": [ "Quantum Hardware", - "Quantum Computing" + "Quantum Computing", + "Getting Started" ], "tags": [], "previewImages": [ diff --git a/demonstrations_v2/tutorial_qaoa_intro/metadata.json b/demonstrations_v2/tutorial_qaoa_intro/metadata.json index e1b5db2eb5..70275ee104 100644 --- a/demonstrations_v2/tutorial_qaoa_intro/metadata.json +++ b/demonstrations_v2/tutorial_qaoa_intro/metadata.json @@ -8,9 +8,10 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2020-11-18T00:00:00+00:00", - "dateOfLastModification": "2026-04-17T15:48:14+00:00", + "dateOfLastModification": "2026-04-21T15:48:14+00:00", "categories": [ - "Optimization" + "Optimization", + "Getting Started" ], "tags": [], "previewImages": [ diff --git a/demonstrations_v2/tutorial_qksd_qsp_qualtran/metadata.json b/demonstrations_v2/tutorial_qksd_qsp_qualtran/metadata.json index 3819718bb2..0c80eaf1b2 100644 --- a/demonstrations_v2/tutorial_qksd_qsp_qualtran/metadata.json +++ b/demonstrations_v2/tutorial_qksd_qsp_qualtran/metadata.json @@ -17,9 +17,10 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2025-08-29T00:00:00+00:00", - "dateOfLastModification": "2026-04-17T15:48:14+00:00", + "dateOfLastModification": "2026-04-21T15:48:14+00:00", "categories": [ - "Quantum Computing" + "Quantum Computing", + "Resource Estimation" ], "tags": [], "previewImages": [ diff --git a/demonstrations_v2/tutorial_qnn_multivariate_regression/metadata.json b/demonstrations_v2/tutorial_qnn_multivariate_regression/metadata.json index 733a5bd8ff..1da2c7e5e8 100644 --- a/demonstrations_v2/tutorial_qnn_multivariate_regression/metadata.json +++ b/demonstrations_v2/tutorial_qnn_multivariate_regression/metadata.json @@ -11,11 +11,10 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-10-01T00:00:00+00:00", - "dateOfLastModification": "2026-04-17T15:48:14+00:00", + "dateOfLastModification": "2026-04-21T15:48:14+00:00", "categories": [ "Quantum Computing", - "Quantum Machine Learning", - "Getting Started" + "Quantum Machine Learning" ], "tags": [], "previewImages": [ diff --git a/demonstrations_v2/tutorial_re_for_qubitizedQPE/metadata.json b/demonstrations_v2/tutorial_re_for_qubitizedQPE/metadata.json index 78f2d2fedf..ab9c093089 100644 --- a/demonstrations_v2/tutorial_re_for_qubitizedQPE/metadata.json +++ b/demonstrations_v2/tutorial_re_for_qubitizedQPE/metadata.json @@ -8,11 +8,12 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2026-01-29T00:00:00+00:00", - "dateOfLastModification": "2026-02-24T15:48:14+00:00", + "dateOfLastModification": "2026-04-21T15:48:14+00:00", "categories": [ "Algorithms", "Optimization", - "Quantum Chemistry" + "Quantum Chemistry", + "Resource Estimation" ], "tags": [], "previewImages": [ diff --git a/demonstrations_v2/tutorial_resource_estimation/metadata.json b/demonstrations_v2/tutorial_resource_estimation/metadata.json index ce8aa233a5..b26d48fd1d 100644 --- a/demonstrations_v2/tutorial_resource_estimation/metadata.json +++ b/demonstrations_v2/tutorial_resource_estimation/metadata.json @@ -8,9 +8,10 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2022-11-21T00:00:00+00:00", - "dateOfLastModification": "2026-04-17T15:48:14+00:00", + "dateOfLastModification": "2026-04-21T15:48:14+00:00", "categories": [ - "Quantum Chemistry" + "Quantum Chemistry", + "Resource Estimation" ], "tags": [], "previewImages": [ diff --git a/demonstrations_v2/tutorial_resource_estimation_QSVT/metadata.json b/demonstrations_v2/tutorial_resource_estimation_QSVT/metadata.json index f03fe5a910..717ba74fb0 100644 --- a/demonstrations_v2/tutorial_resource_estimation_QSVT/metadata.json +++ b/demonstrations_v2/tutorial_resource_estimation_QSVT/metadata.json @@ -8,9 +8,10 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2026-02-27T10:00:00+00:00", - "dateOfLastModification": "2026-04-17T10:00:00+00:00", + "dateOfLastModification": "2026-04-21T10:00:00+00:00", "categories": [ - "Algorithms" + "Algorithms", + "Resource Estimation" ], "tags": [], "previewImages": [ diff --git a/demonstrations_v2/tutorial_resource_estimation_QSVT_CFD/metadata.json b/demonstrations_v2/tutorial_resource_estimation_QSVT_CFD/metadata.json index ea7494369c..8af46f587b 100644 --- a/demonstrations_v2/tutorial_resource_estimation_QSVT_CFD/metadata.json +++ b/demonstrations_v2/tutorial_resource_estimation_QSVT_CFD/metadata.json @@ -8,10 +8,11 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2026-03-13T10:00:00+00:00", - "dateOfLastModification": "2026-03-13T10:00:00+00:00", + "dateOfLastModification": "2026-04-21T10:00:00+00:00", "categories": [ "Algorithms", - "Optimization" + "Optimization", + "Resource Estimation" ], "tags": [], "previewImages": [ diff --git a/demonstrations_v2/tutorial_resource_estimation_spectroscopy/metadata.json b/demonstrations_v2/tutorial_resource_estimation_spectroscopy/metadata.json index e2994db180..d65458e3ac 100644 --- a/demonstrations_v2/tutorial_resource_estimation_spectroscopy/metadata.json +++ b/demonstrations_v2/tutorial_resource_estimation_spectroscopy/metadata.json @@ -11,11 +11,12 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2026-03-17T10:00:00+00:00", - "dateOfLastModification": "2026-03-17T10:00:00+00:00", + "dateOfLastModification": "2026-04-21T10:00:00+00:00", "categories": [ "Algorithms", "Quantum Chemistry", - "Optimization" + "Optimization", + "Resource Estimation" ], "tags": [], "previewImages": [ diff --git a/demonstrations_v2/tutorial_resource_estimation_vibronic_dynamics/metadata.json b/demonstrations_v2/tutorial_resource_estimation_vibronic_dynamics/metadata.json index ab7bc55e6a..c8fd287785 100644 --- a/demonstrations_v2/tutorial_resource_estimation_vibronic_dynamics/metadata.json +++ b/demonstrations_v2/tutorial_resource_estimation_vibronic_dynamics/metadata.json @@ -8,10 +8,11 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2026-03-16T10:00:00+00:00", - "dateOfLastModification": "2026-03-16T10:00:00+00:00", + "dateOfLastModification": "2026-04-21T10:00:00+00:00", "categories": [ "Algorithms", - "Quantum Chemistry" + "Quantum Chemistry", + "Resource Estimation" ], "tags": [], "previewImages": [ diff --git a/demonstrations_v2/tutorial_rl_pulse/metadata.json b/demonstrations_v2/tutorial_rl_pulse/metadata.json index dc6d8e17bf..9f51ec353f 100644 --- a/demonstrations_v2/tutorial_rl_pulse/metadata.json +++ b/demonstrations_v2/tutorial_rl_pulse/metadata.json @@ -8,9 +8,8 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-04-09T00:00:00+00:00", - "dateOfLastModification": "2026-04-17T15:48:14+00:00", + "dateOfLastModification": "2026-04-21T15:48:14+00:00", "categories": [ - "Getting Started", "Optimization", "Quantum Hardware" ], diff --git a/demonstrations_v2/tutorial_tensor_network_basics/metadata.json b/demonstrations_v2/tutorial_tensor_network_basics/metadata.json index 4177c4fb87..cd858e1d3a 100644 --- a/demonstrations_v2/tutorial_tensor_network_basics/metadata.json +++ b/demonstrations_v2/tutorial_tensor_network_basics/metadata.json @@ -8,9 +8,8 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2025-01-23T09:00:00+00:00", - "dateOfLastModification": "2026-04-17T15:48:14+00:00", + "dateOfLastModification": "2026-04-21T15:48:14+00:00", "categories": [ - "Getting Started", "Quantum Computing", "Algorithms" ], From a2c2f5c40713bd680413d147f9764ad595798390 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 22 Apr 2026 09:56:47 -0400 Subject: [PATCH 10/10] Bump lxml from 5.4.0 to 6.1.0 (#1767) Bumps [lxml](https://github.com/lxml/lxml) from 5.4.0 to 6.1.0.
Changelog

Sourced from lxml's changelog.

6.1.0 (2026-04-17)

This release fixes a possible external entity injection (XXE) vulnerability in iterparse() and the ETCompatXMLParser.

Features added

  • GH#486: The HTML ARIA accessibility attributes were added to the set of safe attributes in lxml.html.defs. This allows lxml_html_clean to pass them through. Patch by oomsveta.

  • The default chunk size for reading from file-likes in iterparse() is now configurable with a new chunk_size argument.

Bugs fixed

  • LP#2146291: The resolve_entities option was still set to True for iterparse and ETCompatXMLParser, allowing for external entity injection (XXE) when using these parsers without setting this option explicitly. The default was now changed to 'internal' only (as for the normal XML and HTML parsers since lxml 5.0). Issue found by Sihao Qiu as CVE-2026-41066.

6.0.4 (2026-04-12)

Bugs fixed

  • LP#2148019: Spurious MemoryError during namespace cleanup.

6.0.3 (2026-04-09)

Bugs fixed

  • Several out of memory error cases now raise MemoryError that were not handled before.

  • Slicing with large step values (outside of +/- sys.maxsize) could trigger undefined C behaviour.

  • LP#2125399: Some failing tests were fixed or disabled in PyPy.

  • LP#2138421: Memory leak in error cases when setting the public_id or system_url of a document.

... (truncated)

Commits
  • 43722f4 Update changelog.
  • 8747040 Name version of option change in docstring.
  • 6c36e6c Fix pypistats URL in download statistics script.
  • c7d76d6 Change security policy to point to Github security advisories.
  • 378ccf8 Update project income report.
  • 315270b Docs: Reduce TOC depth of package pages and move module contents first.
  • 6dbba7f Docs: Show current year in copyright line.
  • e4385bf Update project income report.
  • 5bed1e1 Validate file hashes in release download script.
  • c13ee10 Prepare release of 6.1.0.
  • Additional commits viewable in compare view

[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=lxml&package-manager=pip&previous-version=5.4.0&new-version=6.1.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) ---
Dependabot commands and options
You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) You can disable automated security fix PRs for this repo from the [Security Alerts page](https://github.com/PennyLaneAI/demos/network/alerts).
Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- poetry.lock | 275 +++++++++++++++++++++++++------------------------ pyproject.toml | 2 +- 2 files changed, 139 insertions(+), 138 deletions(-) diff --git a/poetry.lock b/poetry.lock index 32830a95b2..af19d16dd2 100644 --- a/poetry.lock +++ b/poetry.lock @@ -960,144 +960,146 @@ testing = ["pytest (>=6)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-ena [[package]] name = "lxml" -version = "5.4.0" +version = "6.1.0" description = "Powerful and Pythonic XML processing library combining libxml2/libxslt with the ElementTree API." optional = false -python-versions = ">=3.6" +python-versions = ">=3.8" groups = ["main"] files = [ - {file = "lxml-5.4.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:e7bc6df34d42322c5289e37e9971d6ed114e3776b45fa879f734bded9d1fea9c"}, - {file = "lxml-5.4.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:6854f8bd8a1536f8a1d9a3655e6354faa6406621cf857dc27b681b69860645c7"}, - {file = "lxml-5.4.0-cp310-cp310-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:696ea9e87442467819ac22394ca36cb3d01848dad1be6fac3fb612d3bd5a12cf"}, - {file = "lxml-5.4.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6ef80aeac414f33c24b3815ecd560cee272786c3adfa5f31316d8b349bfade28"}, - {file = "lxml-5.4.0-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3b9c2754cef6963f3408ab381ea55f47dabc6f78f4b8ebb0f0b25cf1ac1f7609"}, - {file = "lxml-5.4.0-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:7a62cc23d754bb449d63ff35334acc9f5c02e6dae830d78dab4dd12b78a524f4"}, - {file = "lxml-5.4.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8f82125bc7203c5ae8633a7d5d20bcfdff0ba33e436e4ab0abc026a53a8960b7"}, - {file = "lxml-5.4.0-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:b67319b4aef1a6c56576ff544b67a2a6fbd7eaee485b241cabf53115e8908b8f"}, - {file = "lxml-5.4.0-cp310-cp310-manylinux_2_28_ppc64le.whl", hash = "sha256:a8ef956fce64c8551221f395ba21d0724fed6b9b6242ca4f2f7beb4ce2f41997"}, - {file = "lxml-5.4.0-cp310-cp310-manylinux_2_28_s390x.whl", hash = "sha256:0a01ce7d8479dce84fc03324e3b0c9c90b1ece9a9bb6a1b6c9025e7e4520e78c"}, - {file = "lxml-5.4.0-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:91505d3ddebf268bb1588eb0f63821f738d20e1e7f05d3c647a5ca900288760b"}, - {file = "lxml-5.4.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:a3bcdde35d82ff385f4ede021df801b5c4a5bcdfb61ea87caabcebfc4945dc1b"}, - {file = "lxml-5.4.0-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:aea7c06667b987787c7d1f5e1dfcd70419b711cdb47d6b4bb4ad4b76777a0563"}, - {file = "lxml-5.4.0-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:a7fb111eef4d05909b82152721a59c1b14d0f365e2be4c742a473c5d7372f4f5"}, - {file = "lxml-5.4.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:43d549b876ce64aa18b2328faff70f5877f8c6dede415f80a2f799d31644d776"}, - {file = "lxml-5.4.0-cp310-cp310-win32.whl", hash = "sha256:75133890e40d229d6c5837b0312abbe5bac1c342452cf0e12523477cd3aa21e7"}, - {file = "lxml-5.4.0-cp310-cp310-win_amd64.whl", hash = "sha256:de5b4e1088523e2b6f730d0509a9a813355b7f5659d70eb4f319c76beea2e250"}, - {file = "lxml-5.4.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:98a3912194c079ef37e716ed228ae0dcb960992100461b704aea4e93af6b0bb9"}, - {file = "lxml-5.4.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:0ea0252b51d296a75f6118ed0d8696888e7403408ad42345d7dfd0d1e93309a7"}, - {file = "lxml-5.4.0-cp311-cp311-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b92b69441d1bd39f4940f9eadfa417a25862242ca2c396b406f9272ef09cdcaa"}, - {file = "lxml-5.4.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:20e16c08254b9b6466526bc1828d9370ee6c0d60a4b64836bc3ac2917d1e16df"}, - {file = "lxml-5.4.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7605c1c32c3d6e8c990dd28a0970a3cbbf1429d5b92279e37fda05fb0c92190e"}, - {file = "lxml-5.4.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ecf4c4b83f1ab3d5a7ace10bafcb6f11df6156857a3c418244cef41ca9fa3e44"}, - {file = "lxml-5.4.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0cef4feae82709eed352cd7e97ae062ef6ae9c7b5dbe3663f104cd2c0e8d94ba"}, - {file = "lxml-5.4.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:df53330a3bff250f10472ce96a9af28628ff1f4efc51ccba351a8820bca2a8ba"}, - {file = "lxml-5.4.0-cp311-cp311-manylinux_2_28_ppc64le.whl", hash = "sha256:aefe1a7cb852fa61150fcb21a8c8fcea7b58c4cb11fbe59c97a0a4b31cae3c8c"}, - {file = "lxml-5.4.0-cp311-cp311-manylinux_2_28_s390x.whl", hash = "sha256:ef5a7178fcc73b7d8c07229e89f8eb45b2908a9238eb90dcfc46571ccf0383b8"}, - {file = "lxml-5.4.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:d2ed1b3cb9ff1c10e6e8b00941bb2e5bb568b307bfc6b17dffbbe8be5eecba86"}, - {file = "lxml-5.4.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:72ac9762a9f8ce74c9eed4a4e74306f2f18613a6b71fa065495a67ac227b3056"}, - {file = "lxml-5.4.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:f5cb182f6396706dc6cc1896dd02b1c889d644c081b0cdec38747573db88a7d7"}, - {file = "lxml-5.4.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:3a3178b4873df8ef9457a4875703488eb1622632a9cee6d76464b60e90adbfcd"}, - {file = "lxml-5.4.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:e094ec83694b59d263802ed03a8384594fcce477ce484b0cbcd0008a211ca751"}, - {file = "lxml-5.4.0-cp311-cp311-win32.whl", hash = "sha256:4329422de653cdb2b72afa39b0aa04252fca9071550044904b2e7036d9d97fe4"}, - {file = "lxml-5.4.0-cp311-cp311-win_amd64.whl", hash = "sha256:fd3be6481ef54b8cfd0e1e953323b7aa9d9789b94842d0e5b142ef4bb7999539"}, - {file = "lxml-5.4.0-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:b5aff6f3e818e6bdbbb38e5967520f174b18f539c2b9de867b1e7fde6f8d95a4"}, - {file = "lxml-5.4.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:942a5d73f739ad7c452bf739a62a0f83e2578afd6b8e5406308731f4ce78b16d"}, - {file = "lxml-5.4.0-cp312-cp312-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:460508a4b07364d6abf53acaa0a90b6d370fafde5693ef37602566613a9b0779"}, - {file = "lxml-5.4.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:529024ab3a505fed78fe3cc5ddc079464e709f6c892733e3f5842007cec8ac6e"}, - {file = "lxml-5.4.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7ca56ebc2c474e8f3d5761debfd9283b8b18c76c4fc0967b74aeafba1f5647f9"}, - {file = "lxml-5.4.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a81e1196f0a5b4167a8dafe3a66aa67c4addac1b22dc47947abd5d5c7a3f24b5"}, - {file = "lxml-5.4.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:00b8686694423ddae324cf614e1b9659c2edb754de617703c3d29ff568448df5"}, - {file = "lxml-5.4.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:c5681160758d3f6ac5b4fea370495c48aac0989d6a0f01bb9a72ad8ef5ab75c4"}, - {file = "lxml-5.4.0-cp312-cp312-manylinux_2_28_ppc64le.whl", hash = "sha256:2dc191e60425ad70e75a68c9fd90ab284df64d9cd410ba8d2b641c0c45bc006e"}, - {file = "lxml-5.4.0-cp312-cp312-manylinux_2_28_s390x.whl", hash = "sha256:67f779374c6b9753ae0a0195a892a1c234ce8416e4448fe1e9f34746482070a7"}, - {file = "lxml-5.4.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:79d5bfa9c1b455336f52343130b2067164040604e41f6dc4d8313867ed540079"}, - {file = "lxml-5.4.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3d3c30ba1c9b48c68489dc1829a6eede9873f52edca1dda900066542528d6b20"}, - {file = "lxml-5.4.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:1af80c6316ae68aded77e91cd9d80648f7dd40406cef73df841aa3c36f6907c8"}, - {file = "lxml-5.4.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:4d885698f5019abe0de3d352caf9466d5de2baded00a06ef3f1216c1a58ae78f"}, - {file = "lxml-5.4.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:aea53d51859b6c64e7c51d522c03cc2c48b9b5d6172126854cc7f01aa11f52bc"}, - {file = "lxml-5.4.0-cp312-cp312-win32.whl", hash = "sha256:d90b729fd2732df28130c064aac9bb8aff14ba20baa4aee7bd0795ff1187545f"}, - {file = "lxml-5.4.0-cp312-cp312-win_amd64.whl", hash = "sha256:1dc4ca99e89c335a7ed47d38964abcb36c5910790f9bd106f2a8fa2ee0b909d2"}, - {file = "lxml-5.4.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:773e27b62920199c6197130632c18fb7ead3257fce1ffb7d286912e56ddb79e0"}, - {file = "lxml-5.4.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:ce9c671845de9699904b1e9df95acfe8dfc183f2310f163cdaa91a3535af95de"}, - {file = "lxml-5.4.0-cp313-cp313-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:9454b8d8200ec99a224df8854786262b1bd6461f4280064c807303c642c05e76"}, - {file = "lxml-5.4.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cccd007d5c95279e529c146d095f1d39ac05139de26c098166c4beb9374b0f4d"}, - {file = "lxml-5.4.0-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:0fce1294a0497edb034cb416ad3e77ecc89b313cff7adbee5334e4dc0d11f422"}, - {file = "lxml-5.4.0-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:24974f774f3a78ac12b95e3a20ef0931795ff04dbb16db81a90c37f589819551"}, - {file = "lxml-5.4.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:497cab4d8254c2a90bf988f162ace2ddbfdd806fce3bda3f581b9d24c852e03c"}, - {file = "lxml-5.4.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:e794f698ae4c5084414efea0f5cc9f4ac562ec02d66e1484ff822ef97c2cadff"}, - {file = "lxml-5.4.0-cp313-cp313-manylinux_2_28_ppc64le.whl", hash = "sha256:2c62891b1ea3094bb12097822b3d44b93fc6c325f2043c4d2736a8ff09e65f60"}, - {file = "lxml-5.4.0-cp313-cp313-manylinux_2_28_s390x.whl", hash = "sha256:142accb3e4d1edae4b392bd165a9abdee8a3c432a2cca193df995bc3886249c8"}, - {file = "lxml-5.4.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:1a42b3a19346e5601d1b8296ff6ef3d76038058f311902edd574461e9c036982"}, - {file = "lxml-5.4.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4291d3c409a17febf817259cb37bc62cb7eb398bcc95c1356947e2871911ae61"}, - {file = "lxml-5.4.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:4f5322cf38fe0e21c2d73901abf68e6329dc02a4994e483adbcf92b568a09a54"}, - {file = "lxml-5.4.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:0be91891bdb06ebe65122aa6bf3fc94489960cf7e03033c6f83a90863b23c58b"}, - {file = "lxml-5.4.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:15a665ad90054a3d4f397bc40f73948d48e36e4c09f9bcffc7d90c87410e478a"}, - {file = "lxml-5.4.0-cp313-cp313-win32.whl", hash = "sha256:d5663bc1b471c79f5c833cffbc9b87d7bf13f87e055a5c86c363ccd2348d7e82"}, - {file = "lxml-5.4.0-cp313-cp313-win_amd64.whl", hash = "sha256:bcb7a1096b4b6b24ce1ac24d4942ad98f983cd3810f9711bcd0293f43a9d8b9f"}, - {file = "lxml-5.4.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:7be701c24e7f843e6788353c055d806e8bd8466b52907bafe5d13ec6a6dbaecd"}, - {file = "lxml-5.4.0-cp36-cp36m-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:fb54f7c6bafaa808f27166569b1511fc42701a7713858dddc08afdde9746849e"}, - {file = "lxml-5.4.0-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:97dac543661e84a284502e0cf8a67b5c711b0ad5fb661d1bd505c02f8cf716d7"}, - {file = "lxml-5.4.0-cp36-cp36m-manylinux_2_28_x86_64.whl", hash = "sha256:c70e93fba207106cb16bf852e421c37bbded92acd5964390aad07cb50d60f5cf"}, - {file = "lxml-5.4.0-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:9c886b481aefdf818ad44846145f6eaf373a20d200b5ce1a5c8e1bc2d8745410"}, - {file = "lxml-5.4.0-cp36-cp36m-musllinux_1_2_x86_64.whl", hash = "sha256:fa0e294046de09acd6146be0ed6727d1f42ded4ce3ea1e9a19c11b6774eea27c"}, - {file = "lxml-5.4.0-cp36-cp36m-win32.whl", hash = "sha256:61c7bbf432f09ee44b1ccaa24896d21075e533cd01477966a5ff5a71d88b2f56"}, - {file = "lxml-5.4.0-cp36-cp36m-win_amd64.whl", hash = "sha256:7ce1a171ec325192c6a636b64c94418e71a1964f56d002cc28122fceff0b6121"}, - {file = "lxml-5.4.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:795f61bcaf8770e1b37eec24edf9771b307df3af74d1d6f27d812e15a9ff3872"}, - {file = "lxml-5.4.0-cp37-cp37m-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:29f451a4b614a7b5b6c2e043d7b64a15bd8304d7e767055e8ab68387a8cacf4e"}, - {file = "lxml-5.4.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:891f7f991a68d20c75cb13c5c9142b2a3f9eb161f1f12a9489c82172d1f133c0"}, - {file = "lxml-5.4.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4aa412a82e460571fad592d0f93ce9935a20090029ba08eca05c614f99b0cc92"}, - {file = "lxml-5.4.0-cp37-cp37m-manylinux_2_28_aarch64.whl", hash = "sha256:ac7ba71f9561cd7d7b55e1ea5511543c0282e2b6450f122672a2694621d63b7e"}, - {file = "lxml-5.4.0-cp37-cp37m-manylinux_2_28_x86_64.whl", hash = "sha256:c5d32f5284012deaccd37da1e2cd42f081feaa76981f0eaa474351b68df813c5"}, - {file = "lxml-5.4.0-cp37-cp37m-musllinux_1_2_aarch64.whl", hash = "sha256:ce31158630a6ac85bddd6b830cffd46085ff90498b397bd0a259f59d27a12188"}, - {file = "lxml-5.4.0-cp37-cp37m-musllinux_1_2_x86_64.whl", hash = "sha256:31e63621e073e04697c1b2d23fcb89991790eef370ec37ce4d5d469f40924ed6"}, - {file = "lxml-5.4.0-cp37-cp37m-win32.whl", hash = "sha256:be2ba4c3c5b7900246a8f866580700ef0d538f2ca32535e991027bdaba944063"}, - {file = "lxml-5.4.0-cp37-cp37m-win_amd64.whl", hash = "sha256:09846782b1ef650b321484ad429217f5154da4d6e786636c38e434fa32e94e49"}, - {file = "lxml-5.4.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:eaf24066ad0b30917186420d51e2e3edf4b0e2ea68d8cd885b14dc8afdcf6556"}, - {file = "lxml-5.4.0-cp38-cp38-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:2b31a3a77501d86d8ade128abb01082724c0dfd9524f542f2f07d693c9f1175f"}, - {file = "lxml-5.4.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0e108352e203c7afd0eb91d782582f00a0b16a948d204d4dec8565024fafeea5"}, - {file = "lxml-5.4.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a11a96c3b3f7551c8a8109aa65e8594e551d5a84c76bf950da33d0fb6dfafab7"}, - {file = "lxml-5.4.0-cp38-cp38-manylinux_2_28_aarch64.whl", hash = "sha256:ca755eebf0d9e62d6cb013f1261e510317a41bf4650f22963474a663fdfe02aa"}, - {file = "lxml-5.4.0-cp38-cp38-manylinux_2_28_x86_64.whl", hash = "sha256:4cd915c0fb1bed47b5e6d6edd424ac25856252f09120e3e8ba5154b6b921860e"}, - {file = "lxml-5.4.0-cp38-cp38-musllinux_1_2_aarch64.whl", hash = "sha256:226046e386556a45ebc787871d6d2467b32c37ce76c2680f5c608e25823ffc84"}, - {file = "lxml-5.4.0-cp38-cp38-musllinux_1_2_x86_64.whl", hash = "sha256:b108134b9667bcd71236c5a02aad5ddd073e372fb5d48ea74853e009fe38acb6"}, - {file = "lxml-5.4.0-cp38-cp38-win32.whl", hash = "sha256:1320091caa89805df7dcb9e908add28166113dcd062590668514dbd510798c88"}, - {file = "lxml-5.4.0-cp38-cp38-win_amd64.whl", hash = "sha256:073eb6dcdf1f587d9b88c8c93528b57eccda40209cf9be549d469b942b41d70b"}, - {file = "lxml-5.4.0-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:bda3ea44c39eb74e2488297bb39d47186ed01342f0022c8ff407c250ac3f498e"}, - {file = "lxml-5.4.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:9ceaf423b50ecfc23ca00b7f50b64baba85fb3fb91c53e2c9d00bc86150c7e40"}, - {file = "lxml-5.4.0-cp39-cp39-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:664cdc733bc87449fe781dbb1f309090966c11cc0c0cd7b84af956a02a8a4729"}, - {file = "lxml-5.4.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:67ed8a40665b84d161bae3181aa2763beea3747f748bca5874b4af4d75998f87"}, - {file = "lxml-5.4.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9b4a3bd174cc9cdaa1afbc4620c049038b441d6ba07629d89a83b408e54c35cd"}, - {file = "lxml-5.4.0-cp39-cp39-manylinux_2_28_aarch64.whl", hash = "sha256:b0989737a3ba6cf2a16efb857fb0dfa20bc5c542737fddb6d893fde48be45433"}, - {file = "lxml-5.4.0-cp39-cp39-manylinux_2_28_x86_64.whl", hash = "sha256:dc0af80267edc68adf85f2a5d9be1cdf062f973db6790c1d065e45025fa26140"}, - {file = "lxml-5.4.0-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:639978bccb04c42677db43c79bdaa23785dc7f9b83bfd87570da8207872f1ce5"}, - {file = "lxml-5.4.0-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:5a99d86351f9c15e4a901fc56404b485b1462039db59288b203f8c629260a142"}, - {file = "lxml-5.4.0-cp39-cp39-win32.whl", hash = "sha256:3e6d5557989cdc3ebb5302bbdc42b439733a841891762ded9514e74f60319ad6"}, - {file = "lxml-5.4.0-cp39-cp39-win_amd64.whl", hash = "sha256:a8c9b7f16b63e65bbba889acb436a1034a82d34fa09752d754f88d708eca80e1"}, - {file = "lxml-5.4.0-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:1b717b00a71b901b4667226bba282dd462c42ccf618ade12f9ba3674e1fabc55"}, - {file = "lxml-5.4.0-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:27a9ded0f0b52098ff89dd4c418325b987feed2ea5cc86e8860b0f844285d740"}, - {file = "lxml-5.4.0-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4b7ce10634113651d6f383aa712a194179dcd496bd8c41e191cec2099fa09de5"}, - {file = "lxml-5.4.0-pp310-pypy310_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:53370c26500d22b45182f98847243efb518d268374a9570409d2e2276232fd37"}, - {file = "lxml-5.4.0-pp310-pypy310_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:c6364038c519dffdbe07e3cf42e6a7f8b90c275d4d1617a69bb59734c1a2d571"}, - {file = "lxml-5.4.0-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:b12cb6527599808ada9eb2cd6e0e7d3d8f13fe7bbb01c6311255a15ded4c7ab4"}, - {file = "lxml-5.4.0-pp37-pypy37_pp73-macosx_10_9_x86_64.whl", hash = "sha256:5f11a1526ebd0dee85e7b1e39e39a0cc0d9d03fb527f56d8457f6df48a10dc0c"}, - {file = "lxml-5.4.0-pp37-pypy37_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:48b4afaf38bf79109bb060d9016fad014a9a48fb244e11b94f74ae366a64d252"}, - {file = "lxml-5.4.0-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:de6f6bb8a7840c7bf216fb83eec4e2f79f7325eca8858167b68708b929ab2172"}, - {file = "lxml-5.4.0-pp37-pypy37_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:5cca36a194a4eb4e2ed6be36923d3cffd03dcdf477515dea687185506583d4c9"}, - {file = "lxml-5.4.0-pp37-pypy37_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:b7c86884ad23d61b025989d99bfdd92a7351de956e01c61307cb87035960bcb1"}, - {file = "lxml-5.4.0-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:53d9469ab5460402c19553b56c3648746774ecd0681b1b27ea74d5d8a3ef5590"}, - {file = "lxml-5.4.0-pp38-pypy38_pp73-macosx_10_9_x86_64.whl", hash = "sha256:56dbdbab0551532bb26c19c914848d7251d73edb507c3079d6805fa8bba5b706"}, - {file = "lxml-5.4.0-pp38-pypy38_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:14479c2ad1cb08b62bb941ba8e0e05938524ee3c3114644df905d2331c76cd57"}, - {file = "lxml-5.4.0-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:32697d2ea994e0db19c1df9e40275ffe84973e4232b5c274f47e7c1ec9763cdd"}, - {file = "lxml-5.4.0-pp38-pypy38_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:24f6df5f24fc3385f622c0c9d63fe34604893bc1a5bdbb2dbf5870f85f9a404a"}, - {file = "lxml-5.4.0-pp38-pypy38_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:151d6c40bc9db11e960619d2bf2ec5829f0aaffb10b41dcf6ad2ce0f3c0b2325"}, - {file = "lxml-5.4.0-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:4025bf2884ac4370a3243c5aa8d66d3cb9e15d3ddd0af2d796eccc5f0244390e"}, - {file = "lxml-5.4.0-pp39-pypy39_pp73-macosx_10_15_x86_64.whl", hash = "sha256:9459e6892f59ecea2e2584ee1058f5d8f629446eab52ba2305ae13a32a059530"}, - {file = "lxml-5.4.0-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:47fb24cc0f052f0576ea382872b3fc7e1f7e3028e53299ea751839418ade92a6"}, - {file = "lxml-5.4.0-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:50441c9de951a153c698b9b99992e806b71c1f36d14b154592580ff4a9d0d877"}, - {file = "lxml-5.4.0-pp39-pypy39_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:ab339536aa798b1e17750733663d272038bf28069761d5be57cb4a9b0137b4f8"}, - {file = "lxml-5.4.0-pp39-pypy39_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:9776af1aad5a4b4a1317242ee2bea51da54b2a7b7b48674be736d463c999f37d"}, - {file = "lxml-5.4.0-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:63e7968ff83da2eb6fdda967483a7a023aa497d85ad8f05c3ad9b1f2e8c84987"}, - {file = "lxml-5.4.0.tar.gz", hash = "sha256:d12832e1dbea4be280b22fd0ea7c9b87f0d8fc51ba06e92dc62d52f804f78ebd"}, + {file = "lxml-6.1.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:41dcc4c7b10484257cbd6c37b83ddb26df2b0e5aff5ac00d095689015af868ec"}, + {file = "lxml-6.1.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:a31286dbb5e74c8e9a5344465b77ab4c5bd511a253b355b5ca2fae7e579fafec"}, + {file = "lxml-6.1.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:1bc4cc83fb7f66ffb16f74d6dd0162e144333fc36ebcce32246f80c8735b2551"}, + {file = "lxml-6.1.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:20cf4d0651987c906a2f5cba4e3a8d6ba4bfdf973cfe2a96c0d6053888ea2ecd"}, + {file = "lxml-6.1.0-cp310-cp310-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ffb34ea45a82dd637c2c97ae1bbb920850c1e59bcae79ce1c15af531d83e7215"}, + {file = "lxml-6.1.0-cp310-cp310-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a1d9b99e5b2597e4f5aed2484fef835256fa1b68a19e4265c97628ef4bf8bcf4"}, + {file = "lxml-6.1.0-cp310-cp310-manylinux_2_28_i686.whl", hash = "sha256:d43aa26dcda363f21e79afa0668f5029ed7394b3bb8c92a6927a3d34e8b610ea"}, + {file = "lxml-6.1.0-cp310-cp310-manylinux_2_31_armv7l.whl", hash = "sha256:6262b87f9e5c1e5fe501d6c153247289af42eb44ad7660b9b3de17baaf92d6f6"}, + {file = "lxml-6.1.0-cp310-cp310-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d1392c569c032f78a11a25d1de1c43fff13294c793b39e19d84fade3045cbbc3"}, + {file = "lxml-6.1.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:045e387d1f4f42a418380930fa3f45c73c9b392faf67e495e58902e68e8f44a7"}, + {file = "lxml-6.1.0-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:9f93d5b8b07f73e8c77e3c6556a3db269918390c804b5e5fcdd4858232cc8f16"}, + {file = "lxml-6.1.0-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:de550d129f18d8ab819651ffe4f38b1b713c7e116707de3c0c6400d0ef34fbc1"}, + {file = "lxml-6.1.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:c08da09dc003c9e8c70e06b53a11db6fb3b250c21c4236b03c7d7b443c318e7a"}, + {file = "lxml-6.1.0-cp310-cp310-win32.whl", hash = "sha256:37448bf9c7d7adfc5254763901e2bbd6bb876228dfc1fc7f66e58c06368a7544"}, + {file = "lxml-6.1.0-cp310-cp310-win_amd64.whl", hash = "sha256:2593a0a6621545b9095b71ad74ed4226eba438a7d9fc3712a99bdb15508cf93a"}, + {file = "lxml-6.1.0-cp310-cp310-win_arm64.whl", hash = "sha256:e80807d72f96b96ad5588cb85c75616e4f2795a7737d4630784c51497beb7776"}, + {file = "lxml-6.1.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:cec05be8c876f92a5aa07b01d60bbb4d11cfbdd654cad0561c0d7b5c043a61b9"}, + {file = "lxml-6.1.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:9c03e048b6ce8e77b09c734e931584894ecd58d08296804ca2d0b184c933ce50"}, + {file = "lxml-6.1.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:942454ff253da14218f972b23dc72fa4edf6c943f37edd19cd697618b626fac5"}, + {file = "lxml-6.1.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:d036ee7b99d5148072ac7c9b847193decdfeac633db350363f7bce4fff108f0e"}, + {file = "lxml-6.1.0-cp311-cp311-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3ae5d8d5427f3cc317e7950f2da7ad276df0cfa37b8de2f5658959e618ea8512"}, + {file = "lxml-6.1.0-cp311-cp311-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:363e47283bde87051b821826e71dde47f107e08614e1aa312ba0c5711e77738c"}, + {file = "lxml-6.1.0-cp311-cp311-manylinux_2_28_i686.whl", hash = "sha256:f504d861d9f2a8f94020130adac88d66de93841707a23a86244263d1e54682f5"}, + {file = "lxml-6.1.0-cp311-cp311-manylinux_2_31_armv7l.whl", hash = "sha256:23a5dc68e08ed13331d61815c08f260f46b4a60fdd1640bbeb82cf89a9d90289"}, + {file = "lxml-6.1.0-cp311-cp311-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f15401d8d3dbf239e23c818afc10c7207f7b95f9a307e092122b6f86dd43209a"}, + {file = "lxml-6.1.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:fcf3da95e93349e0647d48d4b36a12783105bcc74cb0c416952f9988410846a3"}, + {file = "lxml-6.1.0-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:0d082495c5fcf426e425a6e28daaba1fcb6d8f854a4ff01effb1f1f381203eb9"}, + {file = "lxml-6.1.0-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:e3c4f84b24a1fcba435157d111c4b755099c6ff00a3daee1ad281817de75ed11"}, + {file = "lxml-6.1.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:976a6b39b1b13e8c354ad8d3f261f3a4ac6609518af91bdb5094760a08f132c4"}, + {file = "lxml-6.1.0-cp311-cp311-win32.whl", hash = "sha256:857efde87d365706590847b916baff69c0bc9252dc5af030e378c9800c0b10e3"}, + {file = "lxml-6.1.0-cp311-cp311-win_amd64.whl", hash = "sha256:183bfb45a493081943be7ea2b5adfc2b611e1cf377cefa8b8a8be404f45ef9a7"}, + {file = "lxml-6.1.0-cp311-cp311-win_arm64.whl", hash = "sha256:19f4164243fc206d12ed3d866e80e74f5bc3627966520da1a5f97e42c32a3f39"}, + {file = "lxml-6.1.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:d2f17a16cd8751e8eb233a7e41aecdf8e511712e00088bf9be455f604cd0d28d"}, + {file = "lxml-6.1.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:f0cea5b1d3e6e77d71bd2b9972eb2446221a69dc52bb0b9c3c6f6e5700592d93"}, + {file = "lxml-6.1.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:fc46da94826188ed45cb53bd8e3fc076ae22675aea2087843d4735627f867c6d"}, + {file = "lxml-6.1.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:9147d8e386ec3b82c3b15d88927f734f565b0aaadef7def562b853adca45784a"}, + {file = "lxml-6.1.0-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5715e0e28736a070f3f34a7ccc09e2fdcba0e3060abbcf61a1a5718ff6d6b105"}, + {file = "lxml-6.1.0-cp312-cp312-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4937460dc5df0cdd2f06a86c285c28afda06aefa3af949f9477d3e8df430c485"}, + {file = "lxml-6.1.0-cp312-cp312-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bc783ee3147e60a25aa0445ea82b3e8aabb83b240f2b95d32cb75587ff781814"}, + {file = "lxml-6.1.0-cp312-cp312-manylinux_2_28_i686.whl", hash = "sha256:40d9189f80075f2e1f88db21ef815a2b17b28adf8e50aaf5c789bfe737027f32"}, + {file = "lxml-6.1.0-cp312-cp312-manylinux_2_31_armv7l.whl", hash = "sha256:05b9b8787e35bec69e68daf4952b2e6dfcfb0db7ecf1a06f8cdfbbac4eb71aad"}, + {file = "lxml-6.1.0-cp312-cp312-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0f0f08beb0182e3e9a86fae124b3c47a7b41b7b69b225e1377db983802404e54"}, + {file = "lxml-6.1.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:73becf6d8c81d4c76b1014dbd3584cb26d904492dcf73ca85dc8bff08dcd6d2d"}, + {file = "lxml-6.1.0-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:1ae225f66e5938f4fa29d37e009a3bb3b13032ac57eb4eb42afa44f6e4054e69"}, + {file = "lxml-6.1.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:690022c7fae793b0489aa68a658822cea83e0d5933781811cabbf5ea3bcfe73d"}, + {file = "lxml-6.1.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:63aeafc26aac0be8aff14af7871249e87ea1319be92090bfd632ec68e03b16a5"}, + {file = "lxml-6.1.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:264c605ab9c0e4aa1a679636f4582c4d3313700009fac3ec9c3412ed0d8f3e1d"}, + {file = "lxml-6.1.0-cp312-cp312-win32.whl", hash = "sha256:56971379bc5ee8037c5a0f09fa88f66cdb7d37c3e38af3e45cf539f41131ac1f"}, + {file = "lxml-6.1.0-cp312-cp312-win_amd64.whl", hash = "sha256:bba078de0031c219e5dd06cf3e6bf8fb8e6e64a77819b358f53bb132e3e03366"}, + {file = "lxml-6.1.0-cp312-cp312-win_arm64.whl", hash = "sha256:c3592631e652afa34999a088f98ba7dfc7d6aff0d535c410bea77a71743f3819"}, + {file = "lxml-6.1.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:a0092f2b107b69601adf562a57c956fbb596e05e3e6651cabd3054113b007e45"}, + {file = "lxml-6.1.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:fc7140d7a7386e6b545d41b7358f4d02b656d4053f5fa6859f92f4b9c2572c4d"}, + {file = "lxml-6.1.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:419c58fc92cc3a2c3fa5f78c63dbf5da70c1fa9c1b25f25727ecee89a96c7de2"}, + {file = "lxml-6.1.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:37fabd1452852636cf38ecdcc9dd5ca4bba7a35d6c53fa09725deeb894a87491"}, + {file = "lxml-6.1.0-cp313-cp313-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a2853c8b2170cc6cd54a6b4d50d2c1a8a7aeca201f23804b4898525c7a152cfc"}, + {file = "lxml-6.1.0-cp313-cp313-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8e369cbd690e788c8d15e56222d91a09c6a417f49cbc543040cba0fe2e25a79e"}, + {file = "lxml-6.1.0-cp313-cp313-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e69aa6805905807186eb00e66c6d97a935c928275182eb02ee40ba00da9623b2"}, + {file = "lxml-6.1.0-cp313-cp313-manylinux_2_28_i686.whl", hash = "sha256:4bd1bdb8a9e0e2dd229de19b5f8aebac80e916921b4b2c6ef8a52bc131d0c1f9"}, + {file = "lxml-6.1.0-cp313-cp313-manylinux_2_31_armv7l.whl", hash = "sha256:cbd7b79cdcb4986ad78a2662625882747f09db5e4cd7b2ae178a88c9c51b3dfe"}, + {file = "lxml-6.1.0-cp313-cp313-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:43e4d297f11080ec9d64a4b1ad7ac02b4484c9f0e2179d9c4ef78e886e747b88"}, + {file = "lxml-6.1.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:cc16682cc987a3da00aa56a3aa3075b08edb10d9b1e476938cfdbee8f3b67181"}, + {file = "lxml-6.1.0-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:d6d8efe71429635f0559579092bb5e60560d7b9115ee38c4adbea35632e7fa24"}, + {file = "lxml-6.1.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:7e39ab3a28af7784e206d8606ec0e4bcad0190f63a492bca95e94e5a4aef7f6e"}, + {file = "lxml-6.1.0-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:9eb667bf50856c4a58145f8ca2d5e5be160191e79eb9e30855a476191b3c3495"}, + {file = "lxml-6.1.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:7f4a77d6f7edf9230cee3e1f7f6764722a41604ee5681844f18db9a81ea0ec33"}, + {file = "lxml-6.1.0-cp313-cp313-win32.whl", hash = "sha256:28902146ffbe5222df411c5d19e5352490122e14447e98cd118907ee3fd6ee62"}, + {file = "lxml-6.1.0-cp313-cp313-win_amd64.whl", hash = "sha256:4a1503c56e4e2b38dc76f2f2da7bae69670c0f1933e27cfa34b2fa5876410b16"}, + {file = "lxml-6.1.0-cp313-cp313-win_arm64.whl", hash = "sha256:e0af85773850417d994d019741239b901b22c6680206f46a34766926e466141d"}, + {file = "lxml-6.1.0-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:ab863fd37458fed6456525f297d21239d987800c46e67da5ef04fc6b3dd93ac8"}, + {file = "lxml-6.1.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:6fd8b1df8254ff4fd93fd31da1fc15770bde23ac045be9bb1f87425702f61cc9"}, + {file = "lxml-6.1.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:47024feaae386a92a146af0d2aeed65229bf6fff738e6a11dda6b0015fb8fd03"}, + {file = "lxml-6.1.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3f00972f84450204cd5d93a5395965e348956aaceaadec693a22ec743f8ae3eb"}, + {file = "lxml-6.1.0-cp314-cp314-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:97faa0860e13b05b15a51fb4986421ef7a30f0b3334061c416e0981e9450ca4c"}, + {file = "lxml-6.1.0-cp314-cp314-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:972a6451204798675407beaad97b868d0c733d9a74dafefc63120b81b8c2de28"}, + {file = "lxml-6.1.0-cp314-cp314-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fe022f20bc4569ec66b63b3fb275a3d628d9d32da6326b2982584104db6d3086"}, + {file = "lxml-6.1.0-cp314-cp314-manylinux_2_28_i686.whl", hash = "sha256:75c4c7c619a744f972f4451bf5adf6d0fb00992a1ffc9fd78e13b0bc817cc99f"}, + {file = "lxml-6.1.0-cp314-cp314-manylinux_2_31_armv7l.whl", hash = "sha256:3648f20d25102a22b6061c688beb3a805099ea4beb0a01ce62975d926944d292"}, + {file = "lxml-6.1.0-cp314-cp314-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:77b9f99b17cbf14026d1e618035077060fc7195dd940d025149f3e2e830fbfcb"}, + {file = "lxml-6.1.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:32662519149fd7a9db354175aa5e417d83485a8039b8aaa62f873ceee7ea4cad"}, + {file = "lxml-6.1.0-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:73d658216fc173cf2c939e90e07b941c5e12736b0bf6a99e7af95459cfe8eabb"}, + {file = "lxml-6.1.0-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:ac4db068889f8772a4a698c5980ec302771bb545e10c4b095d4c8be26749616f"}, + {file = "lxml-6.1.0-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:45e9dfbd1b661eb64ba0d4dbe762bd210c42d86dd1e5bd2bdf89d634231beb43"}, + {file = "lxml-6.1.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:89e8d73d09ac696a5ba42ec69787913d53284f12092f651506779314f10ba585"}, + {file = "lxml-6.1.0-cp314-cp314-win32.whl", hash = "sha256:ebe33f4ec1b2de38ceb225a1749a2965855bffeef435ba93cd2d5d540783bf2f"}, + {file = "lxml-6.1.0-cp314-cp314-win_amd64.whl", hash = "sha256:398443df51c538bd578529aa7e5f7afc6c292644174b47961f3bf87fe5741120"}, + {file = "lxml-6.1.0-cp314-cp314-win_arm64.whl", hash = "sha256:8c8984e1d8c4b3949e419158fda14d921ff703a9ed8a47236c6eb7a2b6cb4946"}, + {file = "lxml-6.1.0-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:1081dd10bc6fa437db2500e13993abf7cc30716d0a2f40e65abb935f02ec559c"}, + {file = "lxml-6.1.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:dabecc48db5f42ba348d1f5d5afdc54c6c4cc758e676926c7cd327045749517d"}, + {file = "lxml-6.1.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:e3dd5fe19c9e0ac818a9c7f132a5e43c1339ec1cbbfecb1a938bd3a47875b7c9"}, + {file = "lxml-6.1.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:9e7b0a4ca6dcc007a4cef00a761bba2dea959de4bd2df98f926b33c92ca5dfb9"}, + {file = "lxml-6.1.0-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5d27bbe326c6b539c64b42638b18bc6003a8d88f76213a97ac9ed4f885efeab7"}, + {file = "lxml-6.1.0-cp314-cp314t-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c4e425db0c5445ef0ad56b0eec54f89b88b2d884656e536a90b2f52aecb4ca86"}, + {file = "lxml-6.1.0-cp314-cp314t-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4b89b098105b8599dc57adac95d1813409ac476d3c948a498775d3d0c6124bfb"}, + {file = "lxml-6.1.0-cp314-cp314t-manylinux_2_28_i686.whl", hash = "sha256:c4a699432846df86cc3de502ee85f445ebad748a1c6021d445f3e514d2cd4b1c"}, + {file = "lxml-6.1.0-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:30e7b2ed63b6c8e97cca8af048589a788ab5c9c905f36d9cf1c2bb549f450d2f"}, + {file = "lxml-6.1.0-cp314-cp314t-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:022981127642fe19866d2907d76241bb07ed21749601f727d5d5dd1ce5d1b773"}, + {file = "lxml-6.1.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:23cad0cc86046d4222f7f418910e46b89971c5a45d3c8abfad0f64b7b05e4a9b"}, + {file = "lxml-6.1.0-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:21c3302068f50d1e8728c67c87ba92aa87043abee517aa2576cca1855326b405"}, + {file = "lxml-6.1.0-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:be10838781cb3be19251e276910cd508fe127e27c3242e50521521a0f3781690"}, + {file = "lxml-6.1.0-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:2173a7bffe97667bbf0767f8a99e587740a8c56fdf3befac4b09cb29a80276fd"}, + {file = "lxml-6.1.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:c6854e9cf99c84beb004eecd7d3a3868ef1109bf2b1df92d7bc11e96a36c2180"}, + {file = "lxml-6.1.0-cp314-cp314t-win32.whl", hash = "sha256:00750d63ef0031a05331b9223463b1c7c02b9004cef2346a5b2877f0f9494dd2"}, + {file = "lxml-6.1.0-cp314-cp314t-win_amd64.whl", hash = "sha256:80410c3a7e3c617af04de17caa9f9f20adaa817093293d69eae7d7d0522836f5"}, + {file = "lxml-6.1.0-cp314-cp314t-win_arm64.whl", hash = "sha256:26dd9f57ee3bd41e7d35b4c98a2ffd89ed11591649f421f0ec19f67d50ec67ac"}, + {file = "lxml-6.1.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:b6c2f225662bc5ad416bdd06f72ca301b31b39ce4261f0e0097017fc2891b940"}, + {file = "lxml-6.1.0-cp38-cp38-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a86f06f059e22a0d574990ee2df24ede03f7f3c68c1336293eee9536c4c776cd"}, + {file = "lxml-6.1.0-cp38-cp38-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:468479e52ecf3ec23799c863336d02c05fc2f7ffd1a1424eeeb9a28d4eb69d13"}, + {file = "lxml-6.1.0-cp38-cp38-manylinux_2_28_i686.whl", hash = "sha256:a02ca8fe48815bddcfca3248efe54451abb9dbf2f7d1c5744c8aa4142d476919"}, + {file = "lxml-6.1.0-cp38-cp38-musllinux_1_2_x86_64.whl", hash = "sha256:bb40648d96157f9081886defe13eac99253e663be969ff938a9289eff6e47b72"}, + {file = "lxml-6.1.0-cp38-cp38-win32.whl", hash = "sha256:1dd6a1c3ad4cb674f44525d9957f3e9c209bb6dd9213245195167a281fcc2bdc"}, + {file = "lxml-6.1.0-cp38-cp38-win_amd64.whl", hash = "sha256:4e2c54d6b47361d0f1d3bc8d4e082ad87201e56ccdcca4d3b9ee3644ff595ec8"}, + {file = "lxml-6.1.0-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:920354904d1cb86577d4b3cfe2830c2dbe81d6f4449e57ada428f1609b5985f7"}, + {file = "lxml-6.1.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:c871299c595ee004d186f61840f0bfc4941aa3f17c8ba4a565ead7e4f4f820ee"}, + {file = "lxml-6.1.0-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d0d799ff958655781296ec870d5e2448e75150da2b3d07f13ff5b0c2c35beefd"}, + {file = "lxml-6.1.0-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7ba11752e346bd804ea312ec2eea2532dfa8b8d3261d81a32ef9e6ab16256280"}, + {file = "lxml-6.1.0-cp39-cp39-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:26c5272c6a4bf4cf32d3f5a7890c942b0e04438691157d341616d02cca74d4bd"}, + {file = "lxml-6.1.0-cp39-cp39-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c53fa3a5a52122d590e847a57ccf955557b9634a7f99ff5a35131321b0a85317"}, + {file = "lxml-6.1.0-cp39-cp39-manylinux_2_28_i686.whl", hash = "sha256:76b958b4ea3104483c20f74866d55aa056546e15ebe83dd7aecd63698f43b755"}, + {file = "lxml-6.1.0-cp39-cp39-manylinux_2_31_armv7l.whl", hash = "sha256:8c11b984b5ce6add4dccc7144c7be5d364d298f15b0c6a57da1991baedc750ce"}, + {file = "lxml-6.1.0-cp39-cp39-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d3829a6e6fd550a219564912d4002c537f65da4c6ae4e093cc34462f4fa027ad"}, + {file = "lxml-6.1.0-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:52b0ac6903cf74ebf997eb8c682d2fbac7d1ab7e4c552413eec55868a9b73f39"}, + {file = "lxml-6.1.0-cp39-cp39-musllinux_1_2_armv7l.whl", hash = "sha256:29f5c00cb7d752bce2c70ebd2d31b0a42f9499ffdd3ecb2f31a5b73ee43031ad"}, + {file = "lxml-6.1.0-cp39-cp39-musllinux_1_2_riscv64.whl", hash = "sha256:c748ebcb6877de89f48ab90ca96642ac458fff5dec291a2b9337cd4d0934e383"}, + {file = "lxml-6.1.0-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:08950a23f296b3f83521577274e3d3b0f3d739bf2e68d01a752e4288bc50d286"}, + {file = "lxml-6.1.0-cp39-cp39-win32.whl", hash = "sha256:11a873c77a181b4fef9c2e357d08ed399542c2af1390101da66720a19c7c9618"}, + {file = "lxml-6.1.0-cp39-cp39-win_amd64.whl", hash = "sha256:81ff55c70b67d19d52b6fd118a114c0a4c97d799cd3089ff9bd9e2ff4b414ee2"}, + {file = "lxml-6.1.0-cp39-cp39-win_arm64.whl", hash = "sha256:481d6e2104285d9add34f41b42b247b76b61c5b5c26c303c2e9707bbf8bd9a64"}, + {file = "lxml-6.1.0-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:546b66c0dd1bb8d9fa89d7123e5fa19a8aff3a1f2141eb22df96112afb17b842"}, + {file = "lxml-6.1.0-pp311-pypy311_pp73-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:5cfa1a34df366d9dc0d5eaf420f4cf2bb1e1bebe1066d1c2fc28c179f8a4004c"}, + {file = "lxml-6.1.0-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:db88156fcf544cdbf0d95588051515cfdfd4c876fc66444eb98bceb5d6db76de"}, + {file = "lxml-6.1.0-pp311-pypy311_pp73-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:07f98f5496f96bf724b1e3c933c107f0cbf2745db18c03d2e13a291c3afd2635"}, + {file = "lxml-6.1.0-pp311-pypy311_pp73-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4642e04449a1e164b5ff71ffd901ddb772dfabf5c9adf1b7be5dffe1212bc037"}, + {file = "lxml-6.1.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:7da13bb6fbadfafb474e0226a30570a3445cfd47c86296f2446dafbd77079ace"}, + {file = "lxml-6.1.0.tar.gz", hash = "sha256:bfd57d8008c4965709a919c3e9a98f76c2c7cb319086b3d26858250620023b13"}, ] [package.extras] @@ -1105,7 +1107,6 @@ cssselect = ["cssselect (>=0.7)"] html-clean = ["lxml_html_clean"] html5 = ["html5lib"] htmlsoup = ["BeautifulSoup4"] -source = ["Cython (>=3.0.11,<3.1.0)"] [[package]] name = "markdown-it-py" @@ -1515,7 +1516,7 @@ version = "12.2.0" description = "Python Imaging Library (fork)" optional = false python-versions = ">=3.10" -groups = ["base", "dev"] +groups = ["base"] files = [ {file = "pillow-12.2.0-cp310-cp310-macosx_10_10_x86_64.whl", hash = "sha256:a4e8f36e677d3336f35089648c8955c51c6d386a13cf6ee9c189c5f5bd713a9f"}, {file = "pillow-12.2.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:2e589959f10d9824d39b350472b92f0ce3b443c0a3442ebf41c40cb8361c5b97"}, @@ -2964,4 +2965,4 @@ type = ["pytest-mypy"] [metadata] lock-version = "2.1" python-versions = ">=3.11.0,<3.15.0" -content-hash = "cf179cde481e3ebda3e755e254df872595c28d250be6ddc78314367a2af01ca6" +content-hash = "bd69223a3dd72cd953af5df2af75c81d0fc3f691a8212f00dab3e3c750726698" diff --git a/pyproject.toml b/pyproject.toml index a8edcd177b..ef34b58359 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -20,7 +20,7 @@ dependencies = [ "poetry-plugin-export>=1.8.0,<2.0.0", "dulwich<0.22", "requirements-parser>=0.11.0,<0.12.0", - "lxml>=5.3.0,<6.0.0", + "lxml>=6.1.0,<7.0.0", "uv>=0.7.18,<0.8.0", "sphobjinv>=2.3.1.3,<3.0.0", "pandocfilters>=1.4.0",