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" ],